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
|
lgpl-2.1
|
1bc72c83a9a904f1b02fe86f90e883ec6d4a0959
| 0
|
Vitalij-Voronkoff/jcommune,illerax/jcommune,a-nigredo/jcommune,Noctrunal/jcommune,NCNecros/jcommune,SurfVaporizer/jcommune,vps2/jcommune,mihnayan/jcommune,oatkachenko/jcommune,SurfVaporizer/jcommune,Relvl/jcommune,vps2/jcommune,Vitalij-Voronkoff/jcommune,Relvl/jcommune,Z00M/jcommune,shevarnadze/jcommune,jtalks-org/jcommune,mihnayan/jcommune,a-nigredo/jcommune,0x0000-dot-ru/jcommune,NCNecros/jcommune,Vitalij-Voronkoff/jcommune,jtalks-org/jcommune,Z00M/jcommune,shevarnadze/jcommune,CocoJumbo/jcommune,Noctrunal/jcommune,vps2/jcommune,SurfVaporizer/jcommune,jtalks-org/jcommune,0x0000-dot-ru/jcommune,shevarnadze/jcommune,illerax/jcommune,Noctrunal/jcommune,duffdodger/jcomm,Relvl/jcommune,a-nigredo/jcommune,CocoJumbo/jcommune,despc/jcommune,NCNecros/jcommune,oatkachenko/jcommune,CocoJumbo/jcommune,despc/jcommune,Z00M/jcommune,illerax/jcommune,oatkachenko/jcommune,despc/jcommune,duffdodger/jcomm,mihnayan/jcommune
|
/**
* 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.jcommune.web.tags;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.FixedLocaleResolver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Evgeniy Naumenko
*/
public class FormattedDateTagTest {
private PageContext context;
private HttpServletRequest request;
private Cookie[] cookies;
private DateTime localDate = new DateTime(2011, 10, 30, 20, 15, 10, 5);
private DateTime utcDate = new DateTime(localDate.getZone().convertLocalToUTC(localDate.getMillis(), true));
private DateTimeFormatter formatter = DateTimeFormat.forPattern(FormattedDate.DATE_FORMAT_PATTERN);
private Locale locale = Locale.ENGLISH;
private FormattedDate tag;
@BeforeMethod
public void setUp() {
request = mock(HttpServletRequest.class);
context = new MockPageContext(new MockServletContext(), request);
LocaleResolver resolver = new FixedLocaleResolver(locale);
when(request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE)).thenReturn(resolver);
tag = new FormattedDate();
}
@Test
public void testRenderDateWithPositiveOffset() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{new Cookie("foo", "bar"), new Cookie(FormattedDate.GMT_COOKIE_NAME, "60")};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate.minusHours(1)));
}
@Test
public void testRenderDateWithNegativeOffset() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{new Cookie(FormattedDate.GMT_COOKIE_NAME, "-60")};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate.plusHours(1)));
}
@Test
public void testRenderDateWithZeroOffset() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{new Cookie(FormattedDate.GMT_COOKIE_NAME, "0")};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate));
}
@Test
public void testRenderDateWithoutCookies() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate));
}
@Test
public void testRenderDateWithNullCookies() throws JspException, UnsupportedEncodingException {
when(request.getCookies()).thenReturn(null);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate));
}
@Test
public void testRenderDateWithWrongCookiesSet() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{new Cookie(FormattedDate.GMT_COOKIE_NAME, "lol")};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate));
}
@Test
public void testTagWithNullData() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{new Cookie(FormattedDate.GMT_COOKIE_NAME, "0")};
tag.setPageContext(context);
tag.setValue(null);
tag.doStartTag();
tag.doEndTag();
String result = ((MockHttpServletResponse) context.getResponse()).getContentAsString();
assertEquals("", result);
}
private String render() throws JspException, UnsupportedEncodingException {
//cannot move it to @Before as cookies should be set first
tag.setPageContext(context);
tag.setValue(localDate);
tag.doStartTag();
tag.doEndTag();
return ((MockHttpServletResponse) context.getResponse()).getContentAsString();
}
}
|
jcommune-view/jcommune-web-view/src/test/java/org/jtalks/jcommune/web/tags/FormattedDateTagTest.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.jcommune.web.tags;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.FixedLocaleResolver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Evgeniy Naumenko
*/
public class FormattedDateTagTest {
private PageContext context;
private HttpServletRequest request;
private Cookie[] cookies;
private DateTime localDate = new DateTime(2011, 10, 30, 20, 15, 10, 5);
private DateTime utcDate = new DateTime(localDate.getZone().convertLocalToUTC(localDate.getMillis(), true));
private DateTimeFormatter formatter = DateTimeFormat.forPattern(FormattedDate.DATE_FORMAT_PATTERN);
private Locale locale = Locale.ENGLISH;
private FormattedDate tag;
@BeforeMethod
public void setUp() {
request = mock(HttpServletRequest.class);
context = new MockPageContext(new MockServletContext(), request);
LocaleResolver resolver = new FixedLocaleResolver(locale);
when(request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE)).thenReturn(resolver);
tag = new FormattedDate();
}
@Test
public void testRenderDateWithPositiveOffset() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{new Cookie("foo", "bar"), new Cookie(FormattedDate.GMT_COOKIE_NAME, "60")};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate.minusHours(1)));
}
@Test
public void testRenderDateWithNegativeOffset() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{new Cookie(FormattedDate.GMT_COOKIE_NAME, "-60")};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate.plusHours(1)));
}
@Test
public void testRenderDateWithZeroOffset() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{new Cookie(FormattedDate.GMT_COOKIE_NAME, "0")};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate));
}
@Test
public void testRenderDateWithoutCookies() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate));
}
@Test
public void testRenderDateWithNullCookies() throws JspException, UnsupportedEncodingException {
when(request.getCookies()).thenReturn(null);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate));
}
@Test
public void testRenderDateWithWrongCookiesSet() throws JspException, UnsupportedEncodingException {
cookies = new Cookie[]{new Cookie(FormattedDate.GMT_COOKIE_NAME, "lol")};
when(request.getCookies()).thenReturn(cookies);
String output = this.render();
assertEquals(output, formatter.withLocale(locale).print(utcDate));
}
private String render() throws JspException, UnsupportedEncodingException {
//cannot move it to @Before as cookies should be set first
tag.setPageContext(context);
tag.setValue(localDate);
tag.doStartTag();
tag.doEndTag();
return ((MockHttpServletResponse) context.getResponse()).getContentAsString();
}
}
|
Added some tests
|
jcommune-view/jcommune-web-view/src/test/java/org/jtalks/jcommune/web/tags/FormattedDateTagTest.java
|
Added some tests
|
|
Java
|
lgpl-2.1
|
16ca7b0228696790c9eb5c334f2e67f466be59d3
| 0
|
beast-dev/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,maxbiostat/beast-mcmc,adamallo/beast-mcmc,maxbiostat/beast-mcmc,codeaudit/beast-mcmc,maxbiostat/beast-mcmc,codeaudit/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,maxbiostat/beast-mcmc,maxbiostat/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc,codeaudit/beast-mcmc,codeaudit/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,maxbiostat/beast-mcmc,codeaudit/beast-mcmc,codeaudit/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc
|
package dr.evomodel.antigenic;
import java.util.logging.Logger;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.inference.operators.GibbsOperator;
import dr.inference.operators.MCMCOperator;
import dr.inference.operators.SimpleMCMCOperator;
import dr.math.GammaFunction;
import dr.math.MathUtils;
import dr.math.distributions.MultivariateNormalDistribution;
import dr.math.distributions.WishartDistribution;
import dr.math.matrixAlgebra.Matrix;
import dr.math.matrixAlgebra.SymmetricMatrix;
import dr.xml.*;
/**
* A Gibbs operator for allocation of items to clusters under a distance dependent Chinese restaurant process.
*
* @author Gabriela Cybis
* @author Marc Suchard
*/
public class DistanceDependentCRPGibbsOperator extends SimpleMCMCOperator implements GibbsOperator {
public final static String DDCRP_GIBBS_OPERATOR = "distanceDependentCRPGibbsOperator";
private final Parameter chiParameter;
private final double[][] depMatrix;
public NPAntigenicLikelihood modelLikelihood;
private Parameter links = null;
private Parameter assignments = null;
// double[][] x;
double k0;
double v0;
double[] m;
double[][] T0Inv;
double logDetT0;
public DistanceDependentCRPGibbsOperator(Parameter links, Parameter assignments,
Parameter chiParameter,
NPAntigenicLikelihood Likelihood,
double weight) {
this.links = links;
this.assignments = assignments;
this.modelLikelihood = Likelihood;
this.chiParameter = chiParameter;
this.depMatrix = Likelihood.getLogDepMatrix();
for (int i=0;i<links.getDimension();i++){
links.setParameterValue(i, i);
}
setWeight(weight);
// double[][] x=modelLikelihood.getData();
// modelLikelihood.printInformtion(x[0][0]);
this.m = new double[2];
m[0]= modelLikelihood.priorMean.getParameterValue(0);
m[1]= modelLikelihood.priorMean.getParameterValue(1);
this.v0 = 2;
this.k0= modelLikelihood.priorPrec.getParameterValue(0)/modelLikelihood.clusterPrec.getParameterValue(0);
this.T0Inv= new double[2][2];
T0Inv[0][0]= v0/modelLikelihood.clusterPrec.getParameterValue(0);
T0Inv[1][1]= v0/modelLikelihood.clusterPrec.getParameterValue(0);
T0Inv[1][0]= 0.0;
T0Inv[0][1]= 0.0;
this.logDetT0= -Math.log(T0Inv[0][0]*T0Inv[1][1]);
}
/**
* @return the parameter this operator acts on.
*/
public Parameter getParameter() {
return (Parameter) links;
}
/**
* @return the Variable this operator acts on.
public Variable getVariable() {
return clusteringParameter;
}
*/
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() {
int index = MathUtils.nextInt(links.getDimension());
int oldGroup = (int)assignments.getParameterValue(index);
/*
* Set index customer link to index and all connected to it to a new assignment (min value empty)
*/
int minEmp = minEmpty(modelLikelihood.getLogLikelihoodsVector());
links.setParameterValue(index, index);
int[] visited = connected(index, links);
int ii = 0;
while (visited[ii]!=0){
assignments.setParameterValue(visited[ii]-1, minEmp);
ii++;
}
/*
* Adjust likvector for group separated
*/
modelLikelihood.setLogLikelihoodsVector(oldGroup,modelLikelihood.getLogLikGroup(oldGroup) );
modelLikelihood.setLogLikelihoodsVector(minEmp,modelLikelihood.getLogLikGroup(minEmp) );
int maxFull = maxFull( modelLikelihood.getLogLikelihoodsVector());
double[] liks = modelLikelihood.getLogLikelihoodsVector();
/*
* computing likelihoods of joint groups
*/
double[] crossedLiks = new double[maxFull+1];
for (int ll=0;ll<maxFull+1;ll++ ){
if (ll!=minEmp){
crossedLiks[ll]=getLogLik2Group(ll,minEmp);
}
}
/*
* Add logPrior
*/
double[] logP = new double[links.getDimension()];
for (int jj=0; jj<links.getDimension(); jj++){
logP[jj] += depMatrix[index][jj];
int n = (int)assignments.getParameterValue(jj);
if (n!= minEmp){
logP[jj]+=crossedLiks[n] - liks[n] - liks[minEmp];
}
}
logP[index]= Math.log(chiParameter.getParameterValue(0));
/*
* possibilidade de mandar p zero as probs muito pequenas
*/
/*
* Gibbs sampling
*/
this.rescale(logP); // Improve numerical stability
this.exp(logP); // Transform back to probability-scale
int k = MathUtils.randomChoicePDF(logP);
links.setParameterValue(index, k);
int newGroup = (int)assignments.getParameterValue(k);
ii = 0;
while (visited[ii]!=0){
assignments.setParameterValue(visited[ii]-1, newGroup);
ii++;
}
/*
* updating conditional likelihood vector
*/
modelLikelihood.setLogLikelihoodsVector(newGroup, modelLikelihood.getLogLikGroup(newGroup));
if (newGroup!=minEmp){
modelLikelihood.setLogLikelihoodsVector(minEmp, 0);
}
sampleMeans(maxFull);
return 0.0;
}
/*
* find min Empty
*/
public int minEmpty(double[] logLikVector){
int isEmpty=0;
int i =0;
while (isEmpty==0){
if(logLikVector[i]==0){
isEmpty=1;}
else {
if(i==logLikVector.length-1){isEmpty=1;}
i++;}
}
return i;
}
/*
* find max Full
*/
public int maxFull(double[] logLikVector){
int isEmpty=1;
int i =logLikVector.length-1;
while (isEmpty==1){
if(logLikVector[i]!=0){
isEmpty=0;}
else {i--;}
}
return i;
}
/*
* find customers connected to i
*/
public int[] connected(int i, Parameter clusteringParameter){
int n = clusteringParameter.getDimension();
int[] visited = new int[n+1];
visited[0]=i+1;
int tv=1;
for(int j=0;j<n;j++){
if(visited[j]!=0){
int curr = visited[j]-1;
/*look forward
*/
int forward = (int) clusteringParameter.getParameterValue(curr);
visited[tv] = forward+1;
tv++;
// Check to see if is isn't already on the list
for(int ii=0; ii<tv-1; ii++){
if(visited[ii]==forward+1){
tv--;
visited[tv]=0;
}
}
/*look back
*/
for (int jj=0; jj<n;jj++){
if((int)clusteringParameter.getParameterValue(jj)==curr){
visited[tv]= jj+1;
tv++;
for(int ii=0; ii<tv-1; ii++){
if(visited[ii]==jj+1){
tv--;
visited[tv]=0;
}
}
}
}
}}
return visited;
}
private void printInformtion(Parameter par) {
StringBuffer sb = new StringBuffer("parameter \n");
for(int j=0; j<par.getDimension(); j++){
sb.append(par.getParameterValue(j));
}
Logger.getLogger("dr.evomodel").info(sb.toString()); };
/* OLD
public double getLogLikGroup(int groupNumber){
double L =0.0;
int ngroup=0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == groupNumber){
ngroup++;}}
if (ngroup != 0){
double[] group = new double[2*ngroup];
int count = 0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == groupNumber){
group[count] = modelLikelihood.getData()[i][0];
group[ngroup+count] = modelLikelihood.getData()[i][1];
count+=1;}}
double[][] var = new double[2*ngroup][2*ngroup];
double[] mean = new double[2*ngroup];
double m0 = modelLikelihood.getPriorMean().getParameterValue(0);
double m1 = modelLikelihood.getPriorMean().getParameterValue(1);
double vp = modelLikelihood.getPriorPrec().getParameterValue(0);
double vc = modelLikelihood.getClusterPrec().getParameterValue(0);
for (int i=0; i<ngroup; i++){
mean[i]=m0;
mean[ngroup+i]=m1;
for (int l=0;l<ngroup;l++){
var[i][ngroup+l]=0;
var[ngroup+i][l]=0;
if (l==i){var[i][l]= vp+ vc;
var[ngroup+i][ngroup+l]= vp+ vc;}
else { var[i][l] = vp;
var[ngroup+i][ngroup+l]= vp;}
}
}
double[][] precision = new SymmetricMatrix(var).inverse().toComponents();
L = new MultivariateNormalDistribution(mean, precision).logPdf(group);
}
return L;
}
*/
public double getLogLik2Group(int group1, int group2){
throw new UnsupportedOperationException("This method has been commented out because of build errors");
// double L =0.0;
//
//
// int ngroup1=0;
// for (int i=0;i<assignments.getDimension(); i++){
// if((int) assignments.getParameterValue(i) == group1 ){
// ngroup1++;}}
//
// int ngroup2=0;
// for (int i=0;i<assignments.getDimension(); i++){
// if((int) assignments.getParameterValue(i) == group2 ){
// ngroup2++;}}
//
// int ngroup = (ngroup1+ngroup2);
//
// if (ngroup != 0){
// double[][] group = new double[ngroup][2];
//
// double mean[]=new double[2];
//
//
// int count = 0;
// for (int i=0;i<assignments.getDimension(); i++){
// if((int) assignments.getParameterValue(i) == group1 ){
// group[count][0] = modelLikelihood.getData()[i][0];
// group[count][1] = modelLikelihood.getData()[i][1];
// mean[0]+=group[count][0];
// mean[1]+=group[count][1];
// count+=1;}}
//
// for (int i=0;i<assignments.getDimension(); i++){
// if((int) assignments.getParameterValue(i) == group2 ){
// group[count][0] = modelLikelihood.getData()[i][0];
// group[count][1] = modelLikelihood.getData()[i][1];
// mean[0]+=group[count][0];
// mean[1]+=group[count][1];
// count+=1;}}
//
//
//
// mean[0]/=ngroup;
// mean[1]/=ngroup;
//
//
//
// double kn= k0+ngroup;
// double vn= v0+ngroup;
//
//
// double[][] sumdif=new double[2][2];
//
// for(int i=0;i<ngroup;i++){
// sumdif[0][0]+= (group[i][0]-mean[0])*(group[i][0]-mean[0]);
// sumdif[0][1]+= (group[i][0]-mean[0])*(group[i][1]-mean[1]);
// sumdif[1][0]+= (group[i][0]-mean[0])*(group[i][1]-mean[1]);
// sumdif[1][1]+= (group[i][1]-mean[1])*(group[i][1]-mean[1]);
// }
//
//
//
// double[][] TnInv = new double[2][2];
// TnInv[0][0]=T0Inv[0][0]+ngroup*(k0/kn)*(mean[0]-m[0])*(mean[0]-m[0])+sumdif[0][0];
// TnInv[0][1]=T0Inv[0][1]+ngroup*(k0/kn)*(mean[1]-m[1])*(mean[0]-m[0])+sumdif[0][1];
// TnInv[1][0]=T0Inv[1][0]+ngroup*(k0/kn)* (mean[0]-m[0])*(mean[1]-m[1])+sumdif[1][0];
// TnInv[1][1]=T0Inv[1][1]+ngroup*(k0/kn)* (mean[1]-m[1])*(mean[1]-m[1])+sumdif[1][1];
//
//
// double logDetTn=-Math.log(TnInv[0][0]*TnInv[1][1]-TnInv[0][1]*TnInv[1][0]);
//
//
// L+= -(ngroup)*Math.log(Math.PI);
// L+= Math.log(k0) - Math.log(kn);
// L+= (vn/2)*logDetTn - (v0/2)*logDetT0;
// L+= GammaFunction.lnGamma(vn/2)+ GammaFunction.lnGamma((vn/2)-0.5);
// L+=-GammaFunction.lnGamma(v0/2)- GammaFunction.lnGamma((v0/2)-0.5);
//
//
//
//
//
//
//
//
// }
//
// return L;
}
/*public double getLogLik2Group(int group1, int group2){
double L =0.0;
int ngroup1=0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group1 ){
ngroup1++;}}
int ngroup2=0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group2 ){
ngroup2++;}}
int ngroup = (ngroup1+ngroup2);
if (ngroup != 0){
double[] group = new double[2*ngroup];
int count = 0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group1 ){
group[count] = modelLikelihood.getData()[i][0];
group[count+ngroup] = modelLikelihood.getData()[i][1];
count+=1;}}
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group2 ){
group[count] = modelLikelihood.getData()[i][0];
group[count+ngroup] = modelLikelihood.getData()[i][1];
count+=1;}}
double[][] var = new double[2*ngroup][2*ngroup];
double[] mean = new double[2*ngroup];
double m0 = modelLikelihood.getPriorMean().getParameterValue(0);
double m1 = modelLikelihood.getPriorMean().getParameterValue(1);
double vp = modelLikelihood.getPriorPrec().getParameterValue(0);
double vc = modelLikelihood.getClusterPrec().getParameterValue(0);
for (int i=0; i<ngroup; i++){
mean[i]=m0;
mean[i+ngroup]=m1;
for (int l=0;l<ngroup;l++){
var[i][ngroup+l]=0;
var[ngroup+i][l]=0;
if (l==i){var[i][l]= vp+ vc;
var[ngroup+i][ngroup+l]= vp+ vc;}
else { var[i][l] = vp;
var[ngroup+i][ngroup+l]= vp;}
}
}
double[][] precision = new SymmetricMatrix(var).inverse().toComponents();
L = new MultivariateNormalDistribution(mean, precision).logPdf(group);
}
return L;
}
*/
public void sampleMeans(int maxFull){
double[][] means=new double[maxFull+2][2];
throw new UnsupportedOperationException("This method has been commented out because of build errors");
//sample mean vector for each cluster
// for (int i=0; i<maxFull+1; i++){
//
// // Find all elements in cluster
//
// int ngroup=0;
// for (int ii=0;ii<assignments.getDimension(); ii++){
// if((int) assignments.getParameterValue(ii) == i ){
// ngroup++;}}
//
//
// if (ngroup != 0){
// double[][] group = new double[ngroup][2];
// double[] groupMean=new double[2];
//
// int count = 0;
// for (int ii=0;ii<assignments.getDimension(); ii++){
// if((int) assignments.getParameterValue(ii) == i ){
// group[count][0] = modelLikelihood.getData()[ii][0];
// group[count][1] = modelLikelihood.getData()[ii][1];
// groupMean[0]+=group[count][0];
// groupMean[1]+=group[count][1];
// count+=1;}}
//
// groupMean[0]/=ngroup;
// groupMean[1]/=ngroup;
//
//
//
// double kn= k0+ngroup;
// double vn= v0+ngroup;
//
//
// double[][] sumdif=new double[2][2];
//
// for(int jj=0;jj<ngroup;jj++){
// sumdif[0][0]+= (group[jj][0]-groupMean[0])*(group[jj][0]-groupMean[0]);
// sumdif[0][1]+= (group[jj][0]-groupMean[0])*(group[jj][1]-groupMean[1]);
// sumdif[1][0]+= (group[jj][0]-groupMean[0])*(group[jj][1]-groupMean[1]);
// sumdif[1][1]+= (group[jj][1]-groupMean[1])*(group[jj][1]-groupMean[1]);
// }
//
//
//
// double[][] TnInv = new double[2][2];
// TnInv[0][0]=T0Inv[0][0]+ngroup*(k0/kn)*(groupMean[0]-m[0])*(groupMean[0]-m[0])+sumdif[0][0];
// TnInv[0][1]=T0Inv[0][1]+ngroup*(k0/kn)*(groupMean[1]-m[1])*(groupMean[0]-m[0])+sumdif[0][1];
// TnInv[1][0]=T0Inv[1][0]+ngroup*(k0/kn)* (groupMean[0]-m[0])*(groupMean[1]-m[1])+sumdif[1][0];
// TnInv[1][1]=T0Inv[1][1]+ngroup*(k0/kn)* (groupMean[1]-m[1])*(groupMean[1]-m[1])+sumdif[1][1];
//
// Matrix Tn = new SymmetricMatrix(TnInv).inverse();
//
//
// double[] posteriorMean=new double[2];
// // compute posterior mean
//
// posteriorMean[0]= (k0*m[0] +ngroup*groupMean[0])/(k0+ngroup);
// posteriorMean[1]= (k0*m[1] +ngroup*groupMean[1])/(k0+ngroup);
//
//
//
// //compute posterior Precision
// double[][] posteriorPrecision=new WishartDistribution(vn,Tn.toComponents()).nextWishart();
// posteriorPrecision[0][0]*= kn;
// posteriorPrecision[1][0]*= kn;
// posteriorPrecision[0][1]*= kn;
// posteriorPrecision[1][1]*= kn;
//
//
//
//
// double[] sample= new MultivariateNormalDistribution(posteriorMean,posteriorPrecision).nextMultivariateNormal();
// means[i][0]=sample[0];
// means[i][1]=sample[1];
// }
// }
//
// //Fill in cluster means for each observation
//
// for (int j=0; j<assignments.getDimension();j++){
// double[] group=new double[2];
// group[0]=means[(int)assignments.getParameterValue(j)][0];
// group[1]=means[(int)assignments.getParameterValue(j)][1];
//
// modelLikelihood.setMeans(j, group);
// }
}
private void exp(double[] logX) {
for (int i = 0; i < logX.length; ++i) {
logX[i] = Math.exp(logX[i]);
// if(logX[i]<1E-8){logX[i]=0;}
}
}
private void rescale(double[] logX) {
throw new UnsupportedOperationException("This method has been commented out because of build errors");
// double max = this.max(logX);
// for (int i = 0; i < logX.length; ++i) {
// if(logX[i] == Double.NEGATIVE_INFINITY){
// modelLikelihood.printInformtion(logX[i]);
// logX[i]=-1E16;
// }
// if(logX[i]==Double.POSITIVE_INFINITY){
// modelLikelihood.printInformtion(logX[i]);
// logX[i]=1E16;
// }
// logX[i] -= max;
//
// }
}
private double max(double[] x) {
double max = x[0];
for (double xi : x) {
if (xi > max) {
max = xi;
}
}
return max;
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return DDCRP_GIBBS_OPERATOR;
}
public final void optimize(double targetProb) {
throw new RuntimeException("This operator cannot be optimized!");
}
public boolean isOptimizing() {
return false;
}
public void setOptimizing(boolean opt) {
throw new RuntimeException("This operator cannot be optimized!");
}
public double getMinimumAcceptanceLevel() {
return 0.1;
}
public double getMaximumAcceptanceLevel() {
return 0.4;
}
public double getMinimumGoodAcceptanceLevel() {
return 0.20;
}
public double getMaximumGoodAcceptanceLevel() {
return 0.30;
}
public String getPerformanceSuggestion() {
if (Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) {
return "";
} else if (Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) {
return "";
} else {
return "";
}
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String CHI = "chi";
public final static String LIKELIHOOD = "likelihood";
public final static String ASSIGNMENTS = "assignments";
public final static String LINKS = "links";
public final static String DEP_MATRIX = "depMatrix";
public String getParserName() {
return DDCRP_GIBBS_OPERATOR;
}
/* (non-Javadoc)
* @see dr.xml.AbstractXMLObjectParser#parseXMLObject(dr.xml.XMLObject)
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT);
XMLObject cxo = xo.getChild(ASSIGNMENTS);
Parameter assignments = (Parameter) cxo.getChild(Parameter.class);
cxo = xo.getChild(LINKS);
Parameter links = (Parameter) cxo.getChild(Parameter.class);
cxo = xo.getChild(CHI);
Parameter chiParameter = (Parameter) cxo.getChild(Parameter.class);
cxo = xo.getChild(LIKELIHOOD);
NPAntigenicLikelihood likelihood = (NPAntigenicLikelihood)cxo.getChild(NPAntigenicLikelihood.class);
return new DistanceDependentCRPGibbsOperator( links, assignments,
chiParameter,likelihood, weight);
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "An operator that picks a new allocation of an item to a cluster under the Dirichlet process.";
}
public Class getReturnType() {
return DistanceDependentCRPGibbsOperator.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MCMCOperator.WEIGHT),
new ElementRule(CHI, new XMLSyntaxRule[] {
new ElementRule(Parameter.class),
}),
new ElementRule(LIKELIHOOD, new XMLSyntaxRule[] {
new ElementRule(Likelihood.class),
}, true),
new ElementRule(ASSIGNMENTS,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
new ElementRule(LINKS,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
};
};
public int getStepCount() {
return 1;
}
}
|
src/dr/evomodel/antigenic/DistanceDependentCRPGibbsOperator.java
|
package dr.evomodel.antigenic;
import java.util.logging.Logger;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.inference.operators.GibbsOperator;
import dr.inference.operators.MCMCOperator;
import dr.inference.operators.SimpleMCMCOperator;
import dr.math.GammaFunction;
import dr.math.MathUtils;
import dr.math.distributions.MultivariateNormalDistribution;
import dr.math.distributions.WishartDistribution;
import dr.math.matrixAlgebra.Matrix;
import dr.math.matrixAlgebra.SymmetricMatrix;
import dr.xml.*;
/**
* A Gibbs operator for allocation of items to clusters under a distance dependent Chinese restaurant process.
*
* @author Gabriela Cybis
* @author Marc Suchard
*/
public class DistanceDependentCRPGibbsOperator extends SimpleMCMCOperator implements GibbsOperator {
public final static String DDCRP_GIBBS_OPERATOR = "distanceDependentCRPGibbsOperator";
private final Parameter chiParameter;
private final double[][] depMatrix;
public NPAntigenicLikelihood modelLikelihood;
private Parameter links = null;
private Parameter assignments = null;
// double[][] x;
double k0;
double v0;
double[] m;
double[][] T0Inv;
double logDetT0;
public DistanceDependentCRPGibbsOperator(Parameter links, Parameter assignments,
Parameter chiParameter,
NPAntigenicLikelihood Likelihood,
double weight) {
this.links = links;
this.assignments = assignments;
this.modelLikelihood = Likelihood;
this.chiParameter = chiParameter;
this.depMatrix = Likelihood.getLogDepMatrix();
for (int i=0;i<links.getDimension();i++){
links.setParameterValue(i, i);
}
setWeight(weight);
// double[][] x=modelLikelihood.getData();
// modelLikelihood.printInformtion(x[0][0]);
this.m = new double[2];
m[0]= modelLikelihood.priorMean.getParameterValue(0);
m[1]= modelLikelihood.priorMean.getParameterValue(1);
this.v0 = 2;
this.k0= modelLikelihood.priorPrec.getParameterValue(0)/modelLikelihood.clusterPrec.getParameterValue(0);
this.T0Inv= new double[2][2];
T0Inv[0][0]= v0/modelLikelihood.clusterPrec.getParameterValue(0);
T0Inv[1][1]= v0/modelLikelihood.clusterPrec.getParameterValue(0);
T0Inv[1][0]= 0.0;
T0Inv[0][1]= 0.0;
this.logDetT0= -Math.log(T0Inv[0][0]*T0Inv[1][1]);
}
/**
* @return the parameter this operator acts on.
*/
public Parameter getParameter() {
return (Parameter) links;
}
/**
* @return the Variable this operator acts on.
public Variable getVariable() {
return clusteringParameter;
}
*/
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() {
int index = MathUtils.nextInt(links.getDimension());
int oldGroup = (int)assignments.getParameterValue(index);
/*
* Set index customer link to index and all connected to it to a new assignment (min value empty)
*/
int minEmp = minEmpty(modelLikelihood.getLogLikelihoodsVector());
links.setParameterValue(index, index);
int[] visited = connected(index, links);
int ii = 0;
while (visited[ii]!=0){
assignments.setParameterValue(visited[ii]-1, minEmp);
ii++;
}
/*
* Adjust likvector for group separated
*/
modelLikelihood.setLogLikelihoodsVector(oldGroup,modelLikelihood.getLogLikGroup(oldGroup) );
modelLikelihood.setLogLikelihoodsVector(minEmp,modelLikelihood.getLogLikGroup(minEmp) );
int maxFull = maxFull( modelLikelihood.getLogLikelihoodsVector());
double[] liks = modelLikelihood.getLogLikelihoodsVector();
/*
* computing likelihoods of joint groups
*/
double[] crossedLiks = new double[maxFull+1];
for (int ll=0;ll<maxFull+1;ll++ ){
if (ll!=minEmp){
crossedLiks[ll]=getLogLik2Group(ll,minEmp);
}
}
/*
* Add logPrior
*/
double[] logP = new double[links.getDimension()];
for (int jj=0; jj<links.getDimension(); jj++){
logP[jj] += depMatrix[index][jj];
int n = (int)assignments.getParameterValue(jj);
if (n!= minEmp){
logP[jj]+=crossedLiks[n] - liks[n] - liks[minEmp];
}
}
logP[index]= Math.log(chiParameter.getParameterValue(0));
/*
* possibilidade de mandar p zero as probs muito pequenas
*/
/*
* Gibbs sampling
*/
this.rescale(logP); // Improve numerical stability
this.exp(logP); // Transform back to probability-scale
int k = MathUtils.randomChoicePDF(logP);
links.setParameterValue(index, k);
int newGroup = (int)assignments.getParameterValue(k);
ii = 0;
while (visited[ii]!=0){
assignments.setParameterValue(visited[ii]-1, newGroup);
ii++;
}
/*
* updating conditional likelihood vector
*/
modelLikelihood.setLogLikelihoodsVector(newGroup, modelLikelihood.getLogLikGroup(newGroup));
if (newGroup!=minEmp){
modelLikelihood.setLogLikelihoodsVector(minEmp, 0);
}
sampleMeans(maxFull);
return 0.0;
}
/*
* find min Empty
*/
public int minEmpty(double[] logLikVector){
int isEmpty=0;
int i =0;
while (isEmpty==0){
if(logLikVector[i]==0){
isEmpty=1;}
else {
if(i==logLikVector.length-1){isEmpty=1;}
i++;}
}
return i;
}
/*
* find max Full
*/
public int maxFull(double[] logLikVector){
int isEmpty=1;
int i =logLikVector.length-1;
while (isEmpty==1){
if(logLikVector[i]!=0){
isEmpty=0;}
else {i--;}
}
return i;
}
/*
* find customers connected to i
*/
public int[] connected(int i, Parameter clusteringParameter){
int n = clusteringParameter.getDimension();
int[] visited = new int[n+1];
visited[0]=i+1;
int tv=1;
for(int j=0;j<n;j++){
if(visited[j]!=0){
int curr = visited[j]-1;
/*look forward
*/
int forward = (int) clusteringParameter.getParameterValue(curr);
visited[tv] = forward+1;
tv++;
// Check to see if is isn't already on the list
for(int ii=0; ii<tv-1; ii++){
if(visited[ii]==forward+1){
tv--;
visited[tv]=0;
}
}
/*look back
*/
for (int jj=0; jj<n;jj++){
if((int)clusteringParameter.getParameterValue(jj)==curr){
visited[tv]= jj+1;
tv++;
for(int ii=0; ii<tv-1; ii++){
if(visited[ii]==jj+1){
tv--;
visited[tv]=0;
}
}
}
}
}}
return visited;
}
private void printInformtion(Parameter par) {
StringBuffer sb = new StringBuffer("parameter \n");
for(int j=0; j<par.getDimension(); j++){
sb.append(par.getParameterValue(j));
}
Logger.getLogger("dr.evomodel").info(sb.toString()); };
/* OLD
public double getLogLikGroup(int groupNumber){
double L =0.0;
int ngroup=0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == groupNumber){
ngroup++;}}
if (ngroup != 0){
double[] group = new double[2*ngroup];
int count = 0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == groupNumber){
group[count] = modelLikelihood.getData()[i][0];
group[ngroup+count] = modelLikelihood.getData()[i][1];
count+=1;}}
double[][] var = new double[2*ngroup][2*ngroup];
double[] mean = new double[2*ngroup];
double m0 = modelLikelihood.getPriorMean().getParameterValue(0);
double m1 = modelLikelihood.getPriorMean().getParameterValue(1);
double vp = modelLikelihood.getPriorPrec().getParameterValue(0);
double vc = modelLikelihood.getClusterPrec().getParameterValue(0);
for (int i=0; i<ngroup; i++){
mean[i]=m0;
mean[ngroup+i]=m1;
for (int l=0;l<ngroup;l++){
var[i][ngroup+l]=0;
var[ngroup+i][l]=0;
if (l==i){var[i][l]= vp+ vc;
var[ngroup+i][ngroup+l]= vp+ vc;}
else { var[i][l] = vp;
var[ngroup+i][ngroup+l]= vp;}
}
}
double[][] precision = new SymmetricMatrix(var).inverse().toComponents();
L = new MultivariateNormalDistribution(mean, precision).logPdf(group);
}
return L;
}
*/
public double getLogLik2Group(int group1, int group2){
double L =0.0;
int ngroup1=0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group1 ){
ngroup1++;}}
int ngroup2=0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group2 ){
ngroup2++;}}
int ngroup = (ngroup1+ngroup2);
if (ngroup != 0){
double[][] group = new double[ngroup][2];
double mean[]=new double[2];
int count = 0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group1 ){
group[count][0] = modelLikelihood.getData()[i][0];
group[count][1] = modelLikelihood.getData()[i][1];
mean[0]+=group[count][0];
mean[1]+=group[count][1];
count+=1;}}
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group2 ){
group[count][0] = modelLikelihood.getData()[i][0];
group[count][1] = modelLikelihood.getData()[i][1];
mean[0]+=group[count][0];
mean[1]+=group[count][1];
count+=1;}}
mean[0]/=ngroup;
mean[1]/=ngroup;
double kn= k0+ngroup;
double vn= v0+ngroup;
double[][] sumdif=new double[2][2];
for(int i=0;i<ngroup;i++){
sumdif[0][0]+= (group[i][0]-mean[0])*(group[i][0]-mean[0]);
sumdif[0][1]+= (group[i][0]-mean[0])*(group[i][1]-mean[1]);
sumdif[1][0]+= (group[i][0]-mean[0])*(group[i][1]-mean[1]);
sumdif[1][1]+= (group[i][1]-mean[1])*(group[i][1]-mean[1]);
}
double[][] TnInv = new double[2][2];
TnInv[0][0]=T0Inv[0][0]+ngroup*(k0/kn)*(mean[0]-m[0])*(mean[0]-m[0])+sumdif[0][0];
TnInv[0][1]=T0Inv[0][1]+ngroup*(k0/kn)*(mean[1]-m[1])*(mean[0]-m[0])+sumdif[0][1];
TnInv[1][0]=T0Inv[1][0]+ngroup*(k0/kn)* (mean[0]-m[0])*(mean[1]-m[1])+sumdif[1][0];
TnInv[1][1]=T0Inv[1][1]+ngroup*(k0/kn)* (mean[1]-m[1])*(mean[1]-m[1])+sumdif[1][1];
double logDetTn=-Math.log(TnInv[0][0]*TnInv[1][1]-TnInv[0][1]*TnInv[1][0]);
L+= -(ngroup)*Math.log(Math.PI);
L+= Math.log(k0) - Math.log(kn);
L+= (vn/2)*logDetTn - (v0/2)*logDetT0;
L+= GammaFunction.lnGamma(vn/2)+ GammaFunction.lnGamma((vn/2)-0.5);
L+=-GammaFunction.lnGamma(v0/2)- GammaFunction.lnGamma((v0/2)-0.5);
}
return L;
}
/*public double getLogLik2Group(int group1, int group2){
double L =0.0;
int ngroup1=0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group1 ){
ngroup1++;}}
int ngroup2=0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group2 ){
ngroup2++;}}
int ngroup = (ngroup1+ngroup2);
if (ngroup != 0){
double[] group = new double[2*ngroup];
int count = 0;
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group1 ){
group[count] = modelLikelihood.getData()[i][0];
group[count+ngroup] = modelLikelihood.getData()[i][1];
count+=1;}}
for (int i=0;i<assignments.getDimension(); i++){
if((int) assignments.getParameterValue(i) == group2 ){
group[count] = modelLikelihood.getData()[i][0];
group[count+ngroup] = modelLikelihood.getData()[i][1];
count+=1;}}
double[][] var = new double[2*ngroup][2*ngroup];
double[] mean = new double[2*ngroup];
double m0 = modelLikelihood.getPriorMean().getParameterValue(0);
double m1 = modelLikelihood.getPriorMean().getParameterValue(1);
double vp = modelLikelihood.getPriorPrec().getParameterValue(0);
double vc = modelLikelihood.getClusterPrec().getParameterValue(0);
for (int i=0; i<ngroup; i++){
mean[i]=m0;
mean[i+ngroup]=m1;
for (int l=0;l<ngroup;l++){
var[i][ngroup+l]=0;
var[ngroup+i][l]=0;
if (l==i){var[i][l]= vp+ vc;
var[ngroup+i][ngroup+l]= vp+ vc;}
else { var[i][l] = vp;
var[ngroup+i][ngroup+l]= vp;}
}
}
double[][] precision = new SymmetricMatrix(var).inverse().toComponents();
L = new MultivariateNormalDistribution(mean, precision).logPdf(group);
}
return L;
}
*/
public void sampleMeans(int maxFull){
double[][] means=new double[maxFull+2][2];
//sample mean vector for each cluster
for (int i=0; i<maxFull+1; i++){
// Find all elements in cluster
int ngroup=0;
for (int ii=0;ii<assignments.getDimension(); ii++){
if((int) assignments.getParameterValue(ii) == i ){
ngroup++;}}
if (ngroup != 0){
double[][] group = new double[ngroup][2];
double[] groupMean=new double[2];
int count = 0;
for (int ii=0;ii<assignments.getDimension(); ii++){
if((int) assignments.getParameterValue(ii) == i ){
group[count][0] = modelLikelihood.getData()[ii][0];
group[count][1] = modelLikelihood.getData()[ii][1];
groupMean[0]+=group[count][0];
groupMean[1]+=group[count][1];
count+=1;}}
groupMean[0]/=ngroup;
groupMean[1]/=ngroup;
double kn= k0+ngroup;
double vn= v0+ngroup;
double[][] sumdif=new double[2][2];
for(int jj=0;jj<ngroup;jj++){
sumdif[0][0]+= (group[jj][0]-groupMean[0])*(group[jj][0]-groupMean[0]);
sumdif[0][1]+= (group[jj][0]-groupMean[0])*(group[jj][1]-groupMean[1]);
sumdif[1][0]+= (group[jj][0]-groupMean[0])*(group[jj][1]-groupMean[1]);
sumdif[1][1]+= (group[jj][1]-groupMean[1])*(group[jj][1]-groupMean[1]);
}
double[][] TnInv = new double[2][2];
TnInv[0][0]=T0Inv[0][0]+ngroup*(k0/kn)*(groupMean[0]-m[0])*(groupMean[0]-m[0])+sumdif[0][0];
TnInv[0][1]=T0Inv[0][1]+ngroup*(k0/kn)*(groupMean[1]-m[1])*(groupMean[0]-m[0])+sumdif[0][1];
TnInv[1][0]=T0Inv[1][0]+ngroup*(k0/kn)* (groupMean[0]-m[0])*(groupMean[1]-m[1])+sumdif[1][0];
TnInv[1][1]=T0Inv[1][1]+ngroup*(k0/kn)* (groupMean[1]-m[1])*(groupMean[1]-m[1])+sumdif[1][1];
Matrix Tn = new SymmetricMatrix(TnInv).inverse();
double[] posteriorMean=new double[2];
// compute posterior mean
posteriorMean[0]= (k0*m[0] +ngroup*groupMean[0])/(k0+ngroup);
posteriorMean[1]= (k0*m[1] +ngroup*groupMean[1])/(k0+ngroup);
//compute posterior Precision
double[][] posteriorPrecision=new WishartDistribution(vn,Tn.toComponents()).nextWishart();
posteriorPrecision[0][0]*= kn;
posteriorPrecision[1][0]*= kn;
posteriorPrecision[0][1]*= kn;
posteriorPrecision[1][1]*= kn;
double[] sample= new MultivariateNormalDistribution(posteriorMean,posteriorPrecision).nextMultivariateNormal();
means[i][0]=sample[0];
means[i][1]=sample[1];
}
}
//Fill in cluster means for each observation
for (int j=0; j<assignments.getDimension();j++){
double[] group=new double[2];
group[0]=means[(int)assignments.getParameterValue(j)][0];
group[1]=means[(int)assignments.getParameterValue(j)][1];
modelLikelihood.setMeans(j, group);
}
}
private void exp(double[] logX) {
for (int i = 0; i < logX.length; ++i) {
logX[i] = Math.exp(logX[i]);
// if(logX[i]<1E-8){logX[i]=0;}
}
}
private void rescale(double[] logX) {
double max = this.max(logX);
for (int i = 0; i < logX.length; ++i) {
if(logX[i] == Double.NEGATIVE_INFINITY){
modelLikelihood.printInformtion(logX[i]);
logX[i]=-1E16;
}
if(logX[i]==Double.POSITIVE_INFINITY){
modelLikelihood.printInformtion(logX[i]);
logX[i]=1E16;
}
logX[i] -= max;
}
}
private double max(double[] x) {
double max = x[0];
for (double xi : x) {
if (xi > max) {
max = xi;
}
}
return max;
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return DDCRP_GIBBS_OPERATOR;
}
public final void optimize(double targetProb) {
throw new RuntimeException("This operator cannot be optimized!");
}
public boolean isOptimizing() {
return false;
}
public void setOptimizing(boolean opt) {
throw new RuntimeException("This operator cannot be optimized!");
}
public double getMinimumAcceptanceLevel() {
return 0.1;
}
public double getMaximumAcceptanceLevel() {
return 0.4;
}
public double getMinimumGoodAcceptanceLevel() {
return 0.20;
}
public double getMaximumGoodAcceptanceLevel() {
return 0.30;
}
public String getPerformanceSuggestion() {
if (Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) {
return "";
} else if (Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) {
return "";
} else {
return "";
}
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String CHI = "chi";
public final static String LIKELIHOOD = "likelihood";
public final static String ASSIGNMENTS = "assignments";
public final static String LINKS = "links";
public final static String DEP_MATRIX = "depMatrix";
public String getParserName() {
return DDCRP_GIBBS_OPERATOR;
}
/* (non-Javadoc)
* @see dr.xml.AbstractXMLObjectParser#parseXMLObject(dr.xml.XMLObject)
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT);
XMLObject cxo = xo.getChild(ASSIGNMENTS);
Parameter assignments = (Parameter) cxo.getChild(Parameter.class);
cxo = xo.getChild(LINKS);
Parameter links = (Parameter) cxo.getChild(Parameter.class);
cxo = xo.getChild(CHI);
Parameter chiParameter = (Parameter) cxo.getChild(Parameter.class);
cxo = xo.getChild(LIKELIHOOD);
NPAntigenicLikelihood likelihood = (NPAntigenicLikelihood)cxo.getChild(NPAntigenicLikelihood.class);
return new DistanceDependentCRPGibbsOperator( links, assignments,
chiParameter,likelihood, weight);
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "An operator that picks a new allocation of an item to a cluster under the Dirichlet process.";
}
public Class getReturnType() {
return DistanceDependentCRPGibbsOperator.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MCMCOperator.WEIGHT),
new ElementRule(CHI, new XMLSyntaxRule[] {
new ElementRule(Parameter.class),
}),
new ElementRule(LIKELIHOOD, new XMLSyntaxRule[] {
new ElementRule(Likelihood.class),
}, true),
new ElementRule(ASSIGNMENTS,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
new ElementRule(LINKS,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
};
};
public int getStepCount() {
return 1;
}
}
|
Commented out some functions that were giving link errors and breaking the build. Throws exceptions.
|
src/dr/evomodel/antigenic/DistanceDependentCRPGibbsOperator.java
|
Commented out some functions that were giving link errors and breaking the build. Throws exceptions.
|
|
Java
|
lgpl-2.1
|
3dc5e7942bfd3d55ff524b382c1bc874df6995cf
| 0
|
deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features,deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features,deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features,deadcyclo/nuxeo-features,deadcyclo/nuxeo-features,deadcyclo/nuxeo-features,nuxeo-archives/nuxeo-features,nuxeo-archives/nuxeo-features,bjalon/nuxeo-features,bjalon/nuxeo-features,bjalon/nuxeo-features
|
package org.nuxeo.ecm.automation.jaxrs.io.documents;
import static org.nuxeo.ecm.core.api.security.SecurityConstants.BROWSE;
import static org.nuxeo.ecm.core.api.security.SecurityConstants.EVERYONE;
import static org.nuxeo.ecm.core.api.security.SecurityConstants.UNSUPPORTED_ACL;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Produces;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.security.ACE;
import org.nuxeo.ecm.core.api.security.ACL;
import org.nuxeo.ecm.core.api.security.ACP;
import org.nuxeo.ecm.core.security.SecurityService;
import org.nuxeo.ecm.platform.tag.Tag;
import org.nuxeo.ecm.platform.tag.TagService;
import org.nuxeo.runtime.api.Framework;
/**
* JSon writer that outputs a format ready to eat by elasticsearch.
*
*
* @since 5.9.3
*/
@Provider
@Produces({ JsonESDocumentWriter.MIME_TYPE })
public class JsonESDocumentWriter extends JsonDocumentWriter {
public static final String MIME_TYPE = "application/json+esentity";
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return super.isWriteable(type, genericType, annotations, mediaType)
&& MIME_TYPE.equals(mediaType.toString());
}
public static void writeDoc(JsonGenerator jg, DocumentModel doc,
String[] schemas, Map<String, String> contextParameters,
HttpHeaders headers) throws Exception {
jg.writeStartObject();
jg.writeStringField("ecm:repository", doc.getRepositoryName());
jg.writeStringField("ecm:uuid", doc.getId());
jg.writeStringField("ecm:name", doc.getName());
jg.writeStringField("ecm:title", doc.getTitle());
jg.writeStringField("ecm:path", doc.getPathAsString());
jg.writeStringField("ecm:primaryType", doc.getType());
DocumentRef parentRef = doc.getParentRef();
if (parentRef != null) {
jg.writeStringField("ecm:parentId", parentRef.toString());
}
jg.writeStringField("ecm:currentLifeCycleState",
doc.getCurrentLifeCycleState());
jg.writeStringField("ecm:versionLabel", doc.getVersionLabel());
jg.writeBooleanField("ecm:isCheckedIn", !doc.isCheckedOut());
jg.writeBooleanField("ecm:isProxy", doc.isProxy());
jg.writeBooleanField("ecm:isVersion", doc.isVersion());
jg.writeArrayFieldStart("ecm:mixinType");
for (String facet : doc.getFacets()) {
jg.writeString(facet);
}
jg.writeEndArray();
TagService tagService = Framework.getService(TagService.class);
if (tagService != null) {
jg.writeArrayFieldStart("ecm:tag");
for (Tag tag : tagService.getDocumentTags(doc.getCoreSession(),
doc.getId(), null, true)) {
jg.writeString(tag.getLabel());
}
jg.writeEndArray();
}
jg.writeStringField("ecm:changeToken", doc.getChangeToken());
// Add a positive ACL only
SecurityService securityService = Framework
.getService(SecurityService.class);
List<String> browsePermissions = new ArrayList<String>(
Arrays.asList(securityService.getPermissionsToCheck(BROWSE)));
ACP acp = doc.getACP();
jg.writeArrayFieldStart("ecm:acl");
outerloop: for (ACL acl : acp.getACLs()) {
for (ACE ace : acl.getACEs()) {
if (ace.isGranted()
&& browsePermissions.contains(ace.getPermission())) {
jg.writeString(ace.getUsername());
}
if (ace.isDenied()) {
if (!EVERYONE.equals(ace.getUsername())) {
jg.writeString(UNSUPPORTED_ACL);
}
break outerloop;
}
}
}
jg.writeEndArray();
Map<String, String> bmap = doc.getBinaryFulltext();
if (bmap != null && !bmap.isEmpty()) {
for (Map.Entry<String, String> item : bmap.entrySet()) {
String value = item.getValue();
if (value != null) {
jg.writeStringField("ecm:" + item.getKey(), value);
}
}
}
if (schemas == null || (schemas.length == 1 && "*".equals(schemas[0]))) {
schemas = doc.getSchemas();
}
for (String schema : schemas) {
writeProperties(jg, doc, schema, null);
}
if (contextParameters != null && !contextParameters.isEmpty()) {
for (Map.Entry<String, String> parameter : contextParameters
.entrySet()) {
jg.writeStringField(parameter.getKey(), parameter.getValue());
}
}
jg.writeEndObject();
jg.flush();
}
@Override
public void writeDocument(OutputStream out, DocumentModel doc,
String[] schemas, Map<String, String> contextParameters)
throws Exception {
writeDoc(factory.createJsonGenerator(out, JsonEncoding.UTF8), doc,
schemas, contextParameters, headers);
}
public static void writeESDocument(JsonGenerator jg, DocumentModel doc,
String[] schemas, Map<String, String> contextParameters)
throws Exception {
writeDoc(jg, doc, schemas, contextParameters, null);
}
}
|
nuxeo-automation/nuxeo-automation-io/src/main/java/org/nuxeo/ecm/automation/jaxrs/io/documents/JsonESDocumentWriter.java
|
package org.nuxeo.ecm.automation.jaxrs.io.documents;
import static org.nuxeo.ecm.core.api.security.SecurityConstants.BROWSE;
import static org.nuxeo.ecm.core.api.security.SecurityConstants.EVERYONE;
import static org.nuxeo.ecm.core.api.security.SecurityConstants.UNSUPPORTED_ACL;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Produces;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.security.ACE;
import org.nuxeo.ecm.core.api.security.ACL;
import org.nuxeo.ecm.core.api.security.ACP;
import org.nuxeo.ecm.core.security.SecurityService;
import org.nuxeo.ecm.platform.tag.Tag;
import org.nuxeo.ecm.platform.tag.TagService;
import org.nuxeo.runtime.api.Framework;
/**
* JSon writer that outputs a format ready to eat by elasticsearch.
*
*
* @since 5.9.3
*/
@Provider
@Produces({ JsonESDocumentWriter.MIME_TYPE })
public class JsonESDocumentWriter extends JsonDocumentWriter {
public static final String MIME_TYPE = "application/json+esentity";
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return super.isWriteable(type, genericType, annotations, mediaType)
&& MIME_TYPE.equals(mediaType.toString());
}
public static void writeDoc(JsonGenerator jg, DocumentModel doc,
String[] schemas, Map<String, String> contextParameters,
HttpHeaders headers) throws Exception {
jg.writeStartObject();
jg.writeStringField("ecm:repository", doc.getRepositoryName());
jg.writeStringField("ecm:uuid", doc.getId());
jg.writeStringField("ecm:name", doc.getName());
jg.writeStringField("ecm:title", doc.getTitle());
jg.writeStringField("ecm:path", doc.getPathAsString());
jg.writeStringField("ecm:primaryType", doc.getType());
DocumentRef parentRef = doc.getParentRef();
if (parentRef != null) {
jg.writeStringField("ecm:parentId", parentRef.toString());
}
jg.writeStringField("ecm:currentLifeCycleState",
doc.getCurrentLifeCycleState());
jg.writeStringField("ecm:versionLabel", doc.getVersionLabel());
jg.writeBooleanField("ecm:isCheckedIn", !doc.isCheckedOut());
jg.writeBooleanField("ecm:isProxy", doc.isProxy());
jg.writeBooleanField("ecm:isVersion", doc.isVersion());
jg.writeArrayFieldStart("ecm:mixinType");
for (String facet : doc.getFacets()) {
jg.writeString(facet);
}
jg.writeEndArray();
TagService tagService = Framework.getService(TagService.class);
if (tagService != null) {
jg.writeArrayFieldStart("ecm:tag");
for (Tag tag : tagService.getDocumentTags(doc.getCoreSession(),
doc.getId(), null)) {
jg.writeString(tag.getLabel());
}
jg.writeEndArray();
}
jg.writeStringField("ecm:changeToken", doc.getChangeToken());
// Add a positive ACL only
SecurityService securityService = Framework
.getService(SecurityService.class);
List<String> browsePermissions = new ArrayList<String>(
Arrays.asList(securityService.getPermissionsToCheck(BROWSE)));
ACP acp = doc.getACP();
jg.writeArrayFieldStart("ecm:acl");
outerloop: for (ACL acl : acp.getACLs()) {
for (ACE ace : acl.getACEs()) {
if (ace.isGranted()
&& browsePermissions.contains(ace.getPermission())) {
jg.writeString(ace.getUsername());
}
if (ace.isDenied()) {
if (!EVERYONE.equals(ace.getUsername())) {
jg.writeString(UNSUPPORTED_ACL);
}
break outerloop;
}
}
}
jg.writeEndArray();
Map<String, String> bmap = doc.getBinaryFulltext();
if (bmap != null && !bmap.isEmpty()) {
for (Map.Entry<String, String> item : bmap.entrySet()) {
String value = item.getValue();
if (value != null) {
jg.writeStringField("ecm:" + item.getKey(), value);
}
}
}
if (schemas == null || (schemas.length == 1 && "*".equals(schemas[0]))) {
schemas = doc.getSchemas();
}
for (String schema : schemas) {
writeProperties(jg, doc, schema, null);
}
if (contextParameters != null && !contextParameters.isEmpty()) {
for (Map.Entry<String, String> parameter : contextParameters
.entrySet()) {
jg.writeStringField(parameter.getKey(), parameter.getValue());
}
}
jg.writeEndObject();
jg.flush();
}
@Override
public void writeDocument(OutputStream out, DocumentModel doc,
String[] schemas, Map<String, String> contextParameters)
throws Exception {
writeDoc(factory.createJsonGenerator(out, JsonEncoding.UTF8), doc,
schemas, contextParameters, headers);
}
public static void writeESDocument(JsonGenerator jg, DocumentModel doc,
String[] schemas, Map<String, String> contextParameters)
throws Exception {
writeDoc(jg, doc, schemas, contextParameters, null);
}
}
|
NXP-14893: make sure JsonESDocumentWriter uses the core to retrieve tags
|
nuxeo-automation/nuxeo-automation-io/src/main/java/org/nuxeo/ecm/automation/jaxrs/io/documents/JsonESDocumentWriter.java
|
NXP-14893: make sure JsonESDocumentWriter uses the core to retrieve tags
|
|
Java
|
apache-2.0
|
d19d6f615a5324677210aa89ca006847a3596dc0
| 0
|
JetBrains/teamcity-vmware-plugin,JetBrains/teamcity-vmware-plugin
|
/*
*
* * Copyright 2000-2014 JetBrains s.r.o.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package jetbrains.buildServer.clouds.vmware;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import java.util.Collections;
import java.util.HashMap;
import jetbrains.buildServer.CommandLineExecutor;
import jetbrains.buildServer.serverSide.TeamCityProperties;
import jetbrains.buildServer.util.StringUtil;
import java.io.File;
import java.util.Map;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.clouds.CloudInstanceUserData;
import jetbrains.buildServer.util.EventDispatcher;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static jetbrains.buildServer.clouds.vmware.VMWarePropertiesNames.*;
/**
* @author Sergey.Pak
* Date: 4/23/2014
* Time: 6:40 PM
*/
public class VMWarePropertiesReader {
private static final Logger LOG = Logger.getInstance(VMWarePropertiesReader.class.getName());
private static final String RPC_TOOL_PARAMETER = "teamcity.vmware.rpctool.path";
private static final String[] WINDOWS_COMMANDS = {"C:\\Program Files\\VMware\\VMware Tools\\rpctool.exe"};
private static final String[] LINUX_COMMANDS = {"/usr/sbin/vmware-rpctool", "/usr/bin/vmware-rpctool"};
private static final String[] MAC_COMMANDS = {"/usr/sbin/vmware-rpctool", "/sbin/rpctool", "/Library/Application Support/VMware Tools/vmware-tools-daemon"};
private static final String VMWARE_RPCTOOL_NAME = "vmware-rpctool";
private final String myVMWareRPCToolPath;
private final BuildAgentConfigurationEx myAgentConfiguration;
private static final Map<String, String> SPECIAL_COMMAND_FORMATS = Collections.unmodifiableMap(new HashMap<String, String>(){{
put("/Library/Application Support/VMware Tools/vmware-tools-daemon", "--cmd='info-get %s'");
}});
public VMWarePropertiesReader(final BuildAgentConfigurationEx agentConfiguration,
@NotNull EventDispatcher<AgentLifeCycleListener> events) {
LOG.info("VSphere plugin initializing...");
myAgentConfiguration = agentConfiguration;
myVMWareRPCToolPath = getToolPath(myAgentConfiguration);
if (myVMWareRPCToolPath == null) {
LOG.info("Unable to locate " + VMWARE_RPCTOOL_NAME + ". Looks like not a VMWare VM or VWWare tools are not installed");
return;
} else {
LOG.info("Detected vmware-tools or open-vm-tools. Found required vmware-rpctool at " + myVMWareRPCToolPath + ". " +
"Will attempt to authorize agent as VMWare cloud agent. ");
}
events.addListener(new AgentLifeCycleAdapter(){
@Override
public void afterAgentConfigurationLoaded(@NotNull final BuildAgent agent) {
final String serverUrl = getPropertyValue(SERVER_URL);
if (StringUtil.isEmpty(serverUrl)){
LOG.info("Unable to read property " + SERVER_URL + ". VMWare integration is disabled");
return;
} else {
LOG.info("Server URL: " + serverUrl);
}
final String instanceName = getPropertyValue(INSTANCE_NAME);
if (StringUtil.isEmpty(instanceName)){
LOG.info("Unable to read property " + INSTANCE_NAME + ". VMWare integration is disabled");
return;
} else {
LOG.info("Instance name: " + instanceName);
}
myAgentConfiguration.setName(instanceName);
myAgentConfiguration.setServerUrl(serverUrl);
myAgentConfiguration.addConfigurationParameter(INSTANCE_NAME, instanceName);
String imageName = getPropertyValue(IMAGE_NAME);
if (!StringUtil.isEmpty(imageName)){
LOG.info("Image name: " + imageName);
myAgentConfiguration.addConfigurationParameter(IMAGE_NAME, imageName);
}
String userData = getPropertyValue(USER_DATA);
if (!StringUtil.isEmpty(userData)){
LOG.debug("UserData: " + userData);
final CloudInstanceUserData cloudUserData = CloudInstanceUserData.deserialize(userData);
if (cloudUserData != null) {
final Map<String, String> customParameters = cloudUserData.getCustomAgentConfigurationParameters();
for (Map.Entry<String, String> entry : customParameters.entrySet()) {
myAgentConfiguration.addConfigurationParameter(entry.getKey(), entry.getValue());
}
}
}
}
});
}
private String getPropertyValue(String propName){
final StringBuilder commandOutput = new StringBuilder();
final GeneralCommandLine commandLine = new GeneralCommandLine();
if (myVMWareRPCToolPath.contains(" ")){
commandLine.setExePath("/bin/sh");
commandLine.addParameter("-c");
final String specialCommand = SPECIAL_COMMAND_FORMATS.get(myVMWareRPCToolPath);
final String param = String.format(specialCommand != null ? specialCommand : "info-get %s", propName);
commandLine.addParameter(String.format("\"%s\" %s", myVMWareRPCToolPath, param));
} else {
commandLine.setExePath(myVMWareRPCToolPath);
final String specialCommand = SPECIAL_COMMAND_FORMATS.get(myVMWareRPCToolPath);
final String param = String.format(specialCommand != null ? specialCommand : "info-get %s", propName);
commandLine.addParameter(param);
}
commandOutput.append("Will execute: ").append(commandLine.toString()).append("\n");
final CommandLineExecutor executor = new CommandLineExecutor(commandLine);
try {
final int executionTimeoutSeconds = TeamCityProperties.getInteger("teamcity.guest.props.read.timeout.sec", 5);
final ExecResult result = executor.runProcess(executionTimeoutSeconds);
if (result != null) {
final String executionResult = result.getStdout();
commandOutput.append("Execution result: ").append(StringUtil.trim(executionResult)).append('\n');
commandOutput.append("Execution errors: ").append(StringUtil.trim(result.getStderr())).append('\n');
commandOutput.append("Exit code:").append(result.getExitCode()).append('\n');
if (result.getExitCode() != 0){
LOG.warn("Got non-zero exit code for '" + commandLine.toString() + "'. Output:\n" + commandOutput.toString());
}
return executionResult;
} else {
LOG.error("Didn't get response for " + commandLine.toString() + " in " + executionTimeoutSeconds + " seconds.\n" +
"Consider setting agent property 'teamcity.guest.props.read.timeout.sec' to a higher value (default=5)");
}
} catch (ExecutionException e) {
LOG.info("Error getting property " + propName + ": " + e.toString());
}
return null;
}
@Nullable
private static String getToolPath(@NotNull final BuildAgentConfiguration configuration) {
final String rpctoolPath = TeamCityProperties.getProperty(RPC_TOOL_PARAMETER);
if (StringUtil.isNotEmpty(rpctoolPath)){
return rpctoolPath;
}
if (SystemInfo.isUnix) { // Linux, MacOSX, FreeBSD
final Map<String, String> envs = configuration.getBuildParameters().getEnvironmentVariables();
final String path = envs.get("PATH");
if (path != null) for (String p : StringUtil.splitHonorQuotes(path, File.pathSeparatorChar)) {
final File file = new File(p, VMWARE_RPCTOOL_NAME);
if (file.exists()) {
return file.getAbsolutePath();
}
}
}
if (SystemInfo.isLinux) {
return getExistingCommandPath(LINUX_COMMANDS);
} else if (SystemInfo.isWindows) {
return getExistingCommandPath(WINDOWS_COMMANDS);
} else if (SystemInfo.isMac) {
return getExistingCommandPath(MAC_COMMANDS);
} else {
return getExistingCommandPath(LINUX_COMMANDS); //todo: update for other OS'es
}
}
@Nullable
private static String getExistingCommandPath(String[] fileNames){
for (String fileName : fileNames) {
if (new File(fileName).exists())
return fileName;
}
return null;
}
}
|
cloud-vmware-agent/src/main/java/jetbrains/buildServer/clouds/vmware/VMWarePropertiesReader.java
|
/*
*
* * Copyright 2000-2014 JetBrains s.r.o.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package jetbrains.buildServer.clouds.vmware;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import java.util.Collections;
import java.util.HashMap;
import jetbrains.buildServer.CommandLineExecutor;
import jetbrains.buildServer.serverSide.TeamCityProperties;
import jetbrains.buildServer.util.StringUtil;
import java.io.File;
import java.util.Map;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.clouds.CloudInstanceUserData;
import jetbrains.buildServer.util.EventDispatcher;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static jetbrains.buildServer.clouds.vmware.VMWarePropertiesNames.*;
/**
* @author Sergey.Pak
* Date: 4/23/2014
* Time: 6:40 PM
*/
public class VMWarePropertiesReader {
private static final Logger LOG = Logger.getInstance(VMWarePropertiesReader.class.getName());
private static final String RPC_TOOL_PARAMETER = "teamcity.vmware.rpctool.path";
private static final String[] WINDOWS_COMMANDS = {"C:\\Program Files\\VMware\\VMware Tools\\rpctool.exe"};
private static final String[] LINUX_COMMANDS = {"/usr/sbin/vmware-rpctool", "/usr/bin/vmware-rpctool"};
private static final String[] MAC_COMMANDS = {"/usr/sbin/vmware-rpctool", "/sbin/rpctool", "/Library/Application Support/VMware Tools/vmware-tools-daemon"};
private static final String VMWARE_RPCTOOL_NAME = "vmware-rpctool";
private final String myVMWareRPCToolPath;
private final BuildAgentConfigurationEx myAgentConfiguration;
private static final Map<String, String> SPECIAL_COMMAND_FORMATS = Collections.unmodifiableMap(new HashMap<String, String>(){{
put("/Library/Application Support/VMware Tools/vmware-tools-daemon", "--cmd='info-get %s'");
}});
public VMWarePropertiesReader(final BuildAgentConfigurationEx agentConfiguration,
@NotNull EventDispatcher<AgentLifeCycleListener> events) {
LOG.info("VSphere plugin initializing...");
myAgentConfiguration = agentConfiguration;
myVMWareRPCToolPath = getToolPath(myAgentConfiguration);
if (myVMWareRPCToolPath == null) {
LOG.info("Unable to locate " + VMWARE_RPCTOOL_NAME + ". Looks like not a VMWare VM or VWWare tools are not installed");
return;
} else {
LOG.info("Detected vmware-tools or open-vm-tools. Found required vmware-rpctool at " + myVMWareRPCToolPath + ". " +
"Will attempt to authorize agent as VMWare cloud agent. ");
}
events.addListener(new AgentLifeCycleAdapter(){
@Override
public void afterAgentConfigurationLoaded(@NotNull final BuildAgent agent) {
final String serverUrl = getPropertyValue(SERVER_URL);
if (StringUtil.isEmpty(serverUrl)){
LOG.info("Unable to read property " + SERVER_URL + ". VMWare integration is disabled");
return;
} else {
LOG.info("Server URL: " + serverUrl);
}
final String instanceName = getPropertyValue(INSTANCE_NAME);
if (StringUtil.isEmpty(instanceName)){
LOG.info("Unable to read property " + INSTANCE_NAME + ". VMWare integration is disabled");
return;
} else {
LOG.info("Instance name: " + instanceName);
}
myAgentConfiguration.setName(instanceName);
myAgentConfiguration.setServerUrl(serverUrl);
myAgentConfiguration.addConfigurationParameter(INSTANCE_NAME, instanceName);
String imageName = getPropertyValue(IMAGE_NAME);
if (!StringUtil.isEmpty(imageName)){
LOG.info("Image name: " + imageName);
myAgentConfiguration.addConfigurationParameter(IMAGE_NAME, imageName);
}
String userData = getPropertyValue(USER_DATA);
if (!StringUtil.isEmpty(userData)){
LOG.debug("UserData: " + userData);
final CloudInstanceUserData cloudUserData = CloudInstanceUserData.deserialize(userData);
if (cloudUserData != null) {
final Map<String, String> customParameters = cloudUserData.getCustomAgentConfigurationParameters();
for (Map.Entry<String, String> entry : customParameters.entrySet()) {
myAgentConfiguration.addConfigurationParameter(entry.getKey(), entry.getValue());
}
}
}
}
});
}
private String getPropertyValue(String propName){
final GeneralCommandLine commandLine = new GeneralCommandLine();
commandLine.setExePath(myVMWareRPCToolPath);
final String specialCommand = SPECIAL_COMMAND_FORMATS.get(myVMWareRPCToolPath);
final String param = String.format(specialCommand != null ? specialCommand : "info-get %s", propName);
commandLine.addParameter(param);
final CommandLineExecutor executor = new CommandLineExecutor(commandLine);
try {
final ExecResult result = executor.runProcess(5);
return result != null ? StringUtil.trim(result.getStdout()) : null;
} catch (ExecutionException e) {
LOG.info("Error getting property " + propName + ": " + e.toString());
}
return null;
}
@Nullable
private static String getToolPath(@NotNull final BuildAgentConfiguration configuration) {
final String rpctoolPath = TeamCityProperties.getProperty(RPC_TOOL_PARAMETER);
if (StringUtil.isNotEmpty(rpctoolPath)){
return rpctoolPath;
}
if (SystemInfo.isUnix) { // Linux, MacOSX, FreeBSD
final Map<String, String> envs = configuration.getBuildParameters().getEnvironmentVariables();
final String path = envs.get("PATH");
if (path != null) for (String p : StringUtil.splitHonorQuotes(path, File.pathSeparatorChar)) {
final File file = new File(p, VMWARE_RPCTOOL_NAME);
if (file.exists()) {
return file.getAbsolutePath();
}
}
}
if (SystemInfo.isLinux) {
return getExistingCommandPath(LINUX_COMMANDS);
} else if (SystemInfo.isWindows) {
return getExistingCommandPath(WINDOWS_COMMANDS);
} else if (SystemInfo.isMac) {
return getExistingCommandPath(MAC_COMMANDS);
} else {
return getExistingCommandPath(LINUX_COMMANDS); //todo: update for other OS'es
}
}
@Nullable
private static String getExistingCommandPath(String[] fileNames){
for (String fileName : fileNames) {
if (new File(fileName).exists())
return fileName;
}
return null;
}
}
|
prefix command vwmare-rpctool command with "/bin/sh -c". This fixes TW-51506 (Vmware plugin unable to read guestInfo properties on macOS)
|
cloud-vmware-agent/src/main/java/jetbrains/buildServer/clouds/vmware/VMWarePropertiesReader.java
|
prefix command vwmare-rpctool command with "/bin/sh -c". This fixes TW-51506 (Vmware plugin unable to read guestInfo properties on macOS)
|
|
Java
|
apache-2.0
|
9c71b5923b7a2f8a69e1eedcce698e846b14c777
| 0
|
11xor6/otj-pg-embedded,opentable/otj-pg-embedded,11xor6/otj-pg-embedded
|
/**
* Copyright (C) 2012 Ness Computing, 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.nesscomputing.db.postgres.embedded;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sql.DataSource;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.postgresql.jdbc2.optional.SimpleDataSource;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import com.nesscomputing.logging.Log;
public class EmbeddedPostgreSQL implements Closeable
{
private static final Log LOG = Log.findLog();
private static final String PG_STOP_MODE = "fast";
private static final String PG_STOP_WAIT_S = "5";
private static final String PG_SUPERUSER = "postgres";
private static final int PG_STARTUP_WAIT_MS = 10 * 1000;
private static final String PG_DIGEST;
private static final String TMP_DIR_LOC = System.getProperty("java.io.tmpdir");
private static final File TMP_DIR = new File(TMP_DIR_LOC, "embedded-pg");
private static final String LOCK_FILE_NAME = "epg-lock";
private static final String UNAME_S, UNAME_M;
private static final File PG_DIR;
private final File dataDirectory, lockFile;
private final UUID instanceId = UUID.randomUUID();
private final int port;
private final AtomicBoolean started = new AtomicBoolean();
private final AtomicBoolean closed = new AtomicBoolean();
private final Map<String, String> postgresConfig;
private volatile Process postmaster;
private volatile FileOutputStream lockStream;
private volatile FileLock lock;
EmbeddedPostgreSQL(File parentDirectory, Map<String, String> postgresConfig) throws IOException
{
this.postgresConfig = ImmutableMap.copyOf(postgresConfig);
Preconditions.checkNotNull(parentDirectory, "null parent directory");
mkdirs(parentDirectory);
cleanOldDataDirectories(parentDirectory);
port = detectPort();
dataDirectory = new File(parentDirectory, instanceId.toString());
LOG.trace("%s postgres data directory is %s", instanceId, dataDirectory);
Preconditions.checkState(dataDirectory.mkdir(), "Failed to mkdir %s", dataDirectory);
lockFile = new File(dataDirectory, LOCK_FILE_NAME);
initdb();
lock();
startPostmaster();
}
public DataSource getTemplateDatabase()
{
return getDatabase("postgres", "template1");
}
public DataSource getPostgresDatabase()
{
return getDatabase("postgres", "postgres");
}
public DataSource getDatabase(String userName, String dbName)
{
final SimpleDataSource ds = new SimpleDataSource();
ds.setServerName("localhost");
ds.setPortNumber(port);
ds.setDatabaseName(dbName);
ds.setUser(userName);
return ds;
}
public int getPort()
{
return port;
}
private int detectPort() throws IOException
{
final ServerSocket socket = new ServerSocket(0);
try {
return socket.getLocalPort();
} finally {
socket.close();
}
}
private void lock() throws IOException
{
lockStream = new FileOutputStream(lockFile);
Preconditions.checkState((lock = lockStream.getChannel().tryLock()) != null, "could not lock %s", lockFile);
}
private void initdb()
{
final StopWatch watch = new StopWatch();
watch.start();
system(pgBin("initdb"), "-A", "trust", "-U", PG_SUPERUSER, "-D", dataDirectory.getPath(), "-E", "UTF-8");
LOG.info("%s initdb completed in %s", instanceId, watch);
}
private void startPostmaster() throws IOException
{
final StopWatch watch = new StopWatch();
watch.start();
Preconditions.checkState(started.getAndSet(true) == false, "Postmaster already started");
final List<String> args = Lists.newArrayList(
pgBin("postgres"),
"-D", dataDirectory.getPath(),
"-p", Integer.toString(port),
"-i",
"-F");
for (final Entry<String, String> config : postgresConfig.entrySet())
{
args.add("-c");
args.add(config.getKey() + "=" + config.getValue());
}
final ProcessBuilder builder = new ProcessBuilder(args);
builder.redirectErrorStream(true);
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
postmaster = builder.start();
LOG.info("%s postmaster started as %s on port %s. Waiting up to %sms for server startup to finish.", instanceId, postmaster.toString(), port, PG_STARTUP_WAIT_MS);
Runtime.getRuntime().addShutdownHook(newCloserThread());
waitForServerStartup(watch);
}
private void waitForServerStartup(StopWatch watch) throws UnknownHostException, IOException
{
Throwable lastCause = null;
final long start = System.nanoTime();
final long maxWaitNs = TimeUnit.NANOSECONDS.convert(PG_STARTUP_WAIT_MS, TimeUnit.MILLISECONDS);
while (System.nanoTime() - start < maxWaitNs) {
try {
checkReady();
LOG.info("%s postmaster startup finished in %s", instanceId, watch);
return;
} catch (final SQLException e) {
lastCause = e;
LOG.trace(e);
}
try {
throw new IOException(String.format("%s postmaster exited with value %d, check standard out for more detail!", instanceId, postmaster.exitValue()));
} catch (final IllegalThreadStateException e) {
// Process is not yet dead, loop and try again
LOG.trace(e);
}
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
throw new IOException("Gave up waiting for server to start after " + PG_STARTUP_WAIT_MS + "ms", lastCause);
}
private void checkReady() throws SQLException
{
final Connection c = getPostgresDatabase().getConnection();
try {
final Statement s = c.createStatement();
try {
final ResultSet rs = s.executeQuery("SELECT 1"); // NOPMD
Preconditions.checkState(rs.next() == true, "expecting single row");
Preconditions.checkState(1 == rs.getInt(1), "expecting 1");
Preconditions.checkState(rs.next() == false, "expecting single row");
} finally {
s.close();
}
} finally {
c.close();
}
}
private Thread newCloserThread()
{
final Thread closeThread = new Thread(new Runnable() {
@Override
public void run()
{
Closeables.closeQuietly(EmbeddedPostgreSQL.this);
}
});
closeThread.setName("postgres-" + instanceId + "-closer");
return closeThread;
}
@Override
public void close() throws IOException
{
if (closed.getAndSet(true)) {
return;
}
final StopWatch watch = new StopWatch();
watch.start();
try {
pgCtl(dataDirectory, "stop");
LOG.info("%s shut down postmaster in %s", instanceId, watch);
} catch (final Exception e) {
LOG.error(e, "Could not stop postmaster %s", instanceId);
}
if (lock != null) {
lock.release();
}
Closeables.closeQuietly(lockStream);
if (System.getProperty("ness.epg.no-cleanup") == null) {
FileUtils.deleteDirectory(dataDirectory);
} else {
LOG.info("Did not clean up directory %s", dataDirectory.getAbsolutePath());
}
}
private void pgCtl(File dir, String action)
{
system(pgBin("pg_ctl"), "-D", dir.getPath(), action, "-m", PG_STOP_MODE, "-t", PG_STOP_WAIT_S, "-w");
}
private void cleanOldDataDirectories(File parentDirectory)
{
for (final File dir : parentDirectory.listFiles())
{
if (!dir.isDirectory()) {
continue;
}
final File lockFile = new File(dir, LOCK_FILE_NAME);
if (!lockFile.exists()) {
continue;
}
try {
final FileOutputStream fos = new FileOutputStream(lockFile);
try {
final FileLock lock = fos.getChannel().tryLock();
if (lock != null) {
LOG.info("Found stale data directory %s", dir);
if (new File(dir, "postmaster.pid").exists()) {
pgCtl(dir, "stop");
LOG.info("Shut down orphaned postmaster!");
}
FileUtils.deleteDirectory(dir);
}
} finally {
fos.close();
}
} catch (final IOException e) {
LOG.error(e);
} catch (final OverlappingFileLockException e) {
// The directory belongs to another instance in this VM.
LOG.trace(e);
}
}
}
private static String pgBin(String binaryName)
{
return new File(PG_DIR, "bin/" + binaryName).getPath();
}
public static EmbeddedPostgreSQL start() throws IOException
{
return builder().start();
}
public static EmbeddedPostgreSQL.Builder builder()
{
return new Builder();
}
public static class Builder
{
private final File parentDirectory = new File(System.getProperty("ness.embedded-pg.dir", TMP_DIR.getPath()));
private final Map<String, String> config = Maps.newHashMap();
Builder() {
config.put("timezone", "UTC");
config.put("max_connections", "300");
}
public void setServerConfig(String key, String value)
{
config.put(key, value);
}
public EmbeddedPostgreSQL start() throws IOException
{
return new EmbeddedPostgreSQL(parentDirectory, config);
}
}
private static List<String> system(String... command)
{
try {
final Process process = new ProcessBuilder(command).start();
Preconditions.checkState(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command), IOUtils.toString(process.getErrorStream()));
final InputStream stream = process.getInputStream();
return IOUtils.readLines(stream);
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
private static void mkdirs(File dir)
{
Preconditions.checkState(dir.mkdirs() || (dir.isDirectory() && dir.exists()),
"could not create %s", dir);
}
static {
UNAME_S = system("uname", "-s").get(0);
UNAME_M = system("uname", "-m").get(0);
LOG.info("Detected a %s %s system", UNAME_S, UNAME_M);
File pgTbz;
try {
pgTbz = File.createTempFile("pgpg", "pgpg");
} catch (final IOException e) {
throw new ExceptionInInitializerError(e);
}
try {
final DigestInputStream pgArchiveData = new DigestInputStream(
EmbeddedPostgreSQL.class.getResourceAsStream(String.format("/postgresql-%s-%s.tbz", UNAME_S, UNAME_M)),
MessageDigest.getInstance("MD5"));
final FileOutputStream os = new FileOutputStream(pgTbz);
IOUtils.copy(pgArchiveData, os);
pgArchiveData.close();
os.close();
PG_DIGEST = Hex.encodeHexString(pgArchiveData.getMessageDigest().digest());
PG_DIR = new File(TMP_DIR, String.format("PG-%s", PG_DIGEST));
final File pgDirExists = new File(PG_DIR, ".exists");
if (!pgDirExists.exists())
{
LOG.info("Extracting Postgres...");
mkdirs(PG_DIR);
system("tar", "-x", "-f", pgTbz.getPath(), "-C", PG_DIR.getPath());
Files.touch(pgDirExists);
}
} catch (final Exception e) {
throw new ExceptionInInitializerError(e);
} finally {
Preconditions.checkState(pgTbz.delete(), "could not delete %s", pgTbz);
}
LOG.info("Postgres binaries at %s", PG_DIR);
}
@Override
public String toString()
{
return "EmbeddedPG-" + instanceId;
}
}
|
pg-embedded/src/main/java/com/nesscomputing/db/postgres/embedded/EmbeddedPostgreSQL.java
|
/**
* Copyright (C) 2012 Ness Computing, 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.nesscomputing.db.postgres.embedded;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sql.DataSource;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.postgresql.jdbc2.optional.SimpleDataSource;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import com.nesscomputing.logging.Log;
public class EmbeddedPostgreSQL implements Closeable
{
private static final Log LOG = Log.findLog();
private static final String PG_STOP_MODE = "fast";
private static final String PG_STOP_WAIT_S = "5";
private static final String PG_SUPERUSER = "postgres";
private static final int PG_STARTUP_WAIT_MS = 10 * 1000;
private static final String PG_DIGEST;
private static final String TMP_DIR_LOC = System.getProperty("java.io.tmpdir");
private static final File TMP_DIR = new File(TMP_DIR_LOC, "embedded-pg");
private static final String LOCK_FILE_NAME = "epg-lock";
private static final String UNAME_S, UNAME_M;
private static final File PG_DIR;
private final File dataDirectory, lockFile;
private final UUID instanceId = UUID.randomUUID();
private final int port;
private final AtomicBoolean started = new AtomicBoolean();
private final AtomicBoolean closed = new AtomicBoolean();
private final Map<String, String> postgresConfig;
private volatile Process postmaster;
private volatile FileOutputStream lockStream;
private volatile FileLock lock;
EmbeddedPostgreSQL(File parentDirectory, Map<String, String> postgresConfig) throws IOException
{
this.postgresConfig = ImmutableMap.copyOf(postgresConfig);
Preconditions.checkNotNull(parentDirectory, "null parent directory");
mkdirs(parentDirectory);
cleanOldDataDirectories(parentDirectory);
port = detectPort();
dataDirectory = new File(parentDirectory, instanceId.toString());
LOG.trace("%s postgres data directory is %s", instanceId, dataDirectory);
Preconditions.checkState(dataDirectory.mkdir(), "Failed to mkdir %s", dataDirectory);
lockFile = new File(dataDirectory, LOCK_FILE_NAME);
initdb();
lock();
startPostmaster();
}
public DataSource getTemplateDatabase()
{
return getDatabase("postgres", "template1");
}
public DataSource getPostgresDatabase()
{
return getDatabase("postgres", "postgres");
}
public DataSource getDatabase(String userName, String dbName)
{
final SimpleDataSource ds = new SimpleDataSource();
ds.setServerName("localhost");
ds.setPortNumber(port);
ds.setDatabaseName(dbName);
ds.setUser(userName);
return ds;
}
public int getPort()
{
return port;
}
private int detectPort() throws IOException
{
final ServerSocket socket = new ServerSocket(0);
try {
return socket.getLocalPort();
} finally {
socket.close();
}
}
private void lock() throws IOException
{
lockStream = new FileOutputStream(lockFile);
Preconditions.checkState((lock = lockStream.getChannel().tryLock()) != null, "could not lock %s", lockFile);
}
private void initdb()
{
final StopWatch watch = new StopWatch();
watch.start();
system(pgBin("initdb"), "-A", "trust", "-U", PG_SUPERUSER, "-D", dataDirectory.getPath(), "-E", "UTF-8");
LOG.info("%s initdb completed in %s", instanceId, watch);
}
private void startPostmaster() throws IOException
{
final StopWatch watch = new StopWatch();
watch.start();
Preconditions.checkState(started.getAndSet(true) == false, "Postmaster already started");
final List<String> args = Lists.newArrayList(
pgBin("postgres"),
"-D", dataDirectory.getPath(),
"-p", Integer.toString(port),
"-i",
"-F");
for (final Entry<String, String> config : postgresConfig.entrySet())
{
args.add("-c");
args.add(config.getKey() + "=" + config.getValue());
}
ProcessBuilder builder = new ProcessBuilder(args);
enableRedirects(builder);
postmaster = builder.start();
LOG.info("%s postmaster started as %s on port %s. Waiting up to %sms for server startup to finish.", instanceId, postmaster.toString(), port, PG_STARTUP_WAIT_MS);
Runtime.getRuntime().addShutdownHook(newCloserThread());
waitForServerStartup(watch);
}
private void waitForServerStartup(StopWatch watch) throws UnknownHostException, IOException
{
Throwable lastCause = null;
final long start = System.nanoTime();
final long maxWaitNs = TimeUnit.NANOSECONDS.convert(PG_STARTUP_WAIT_MS, TimeUnit.MILLISECONDS);
while (System.nanoTime() - start < maxWaitNs) {
try {
checkReady();
LOG.info("%s postmaster startup finished in %s", instanceId, watch);
return;
} catch (final SQLException e) {
lastCause = e;
LOG.trace(e);
}
try {
throw new IOException(String.format("%s postmaster exited with value %d, check standard out for more detail!", instanceId, postmaster.exitValue()));
} catch (final IllegalThreadStateException e) {
// Process is not yet dead, loop and try again
LOG.trace(e);
}
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
throw new IOException("Gave up waiting for server to start after " + PG_STARTUP_WAIT_MS + "ms", lastCause);
}
private void checkReady() throws SQLException
{
final Connection c = getPostgresDatabase().getConnection();
try {
final Statement s = c.createStatement();
try {
final ResultSet rs = s.executeQuery("SELECT 1"); // NOPMD
Preconditions.checkState(rs.next() == true, "expecting single row");
Preconditions.checkState(1 == rs.getInt(1), "expecting 1");
Preconditions.checkState(rs.next() == false, "expecting single row");
} finally {
s.close();
}
} finally {
c.close();
}
}
private Thread newCloserThread()
{
final Thread closeThread = new Thread(new Runnable() {
@Override
public void run()
{
Closeables.closeQuietly(EmbeddedPostgreSQL.this);
}
});
closeThread.setName("postgres-" + instanceId + "-closer");
return closeThread;
}
@Override
public void close() throws IOException
{
if (closed.getAndSet(true)) {
return;
}
final StopWatch watch = new StopWatch();
watch.start();
try {
pgCtl(dataDirectory, "stop");
LOG.info("%s shut down postmaster in %s", instanceId, watch);
} catch (final Exception e) {
LOG.error(e, "Could not stop postmaster %s", instanceId);
}
if (lock != null) {
lock.release();
}
Closeables.closeQuietly(lockStream);
if (System.getProperty("ness.epg.no-cleanup") == null) {
FileUtils.deleteDirectory(dataDirectory);
} else {
LOG.info("Did not clean up directory %s", dataDirectory.getAbsolutePath());
}
}
private void pgCtl(File dir, String action)
{
system(pgBin("pg_ctl"), "-D", dir.getPath(), action, "-m", PG_STOP_MODE, "-t", PG_STOP_WAIT_S, "-w");
}
private void cleanOldDataDirectories(File parentDirectory)
{
for (final File dir : parentDirectory.listFiles())
{
if (!dir.isDirectory()) {
continue;
}
final File lockFile = new File(dir, LOCK_FILE_NAME);
if (!lockFile.exists()) {
continue;
}
try {
final FileOutputStream fos = new FileOutputStream(lockFile);
try {
final FileLock lock = fos.getChannel().tryLock();
if (lock != null) {
LOG.info("Found stale data directory %s", dir);
if (new File(dir, "postmaster.pid").exists()) {
pgCtl(dir, "stop");
LOG.info("Shut down orphaned postmaster!");
}
FileUtils.deleteDirectory(dir);
}
} finally {
fos.close();
}
} catch (final IOException e) {
LOG.error(e);
} catch (final OverlappingFileLockException e) {
// The directory belongs to another instance in this VM.
LOG.trace(e);
}
}
}
private static String pgBin(String binaryName)
{
return new File(PG_DIR, "bin/" + binaryName).getPath();
}
public static EmbeddedPostgreSQL start() throws IOException
{
return builder().start();
}
public static EmbeddedPostgreSQL.Builder builder()
{
return new Builder();
}
public static class Builder
{
private final File parentDirectory = new File(System.getProperty("ness.embedded-pg.dir", TMP_DIR.getPath()));
private final Map<String, String> config = Maps.newHashMap();
Builder() {
config.put("timezone", "UTC");
config.put("max_connections", "300");
}
public void setServerConfig(String key, String value)
{
config.put(key, value);
}
public EmbeddedPostgreSQL start() throws IOException
{
return new EmbeddedPostgreSQL(parentDirectory, config);
}
}
private static List<String> system(String... command)
{
try {
final Process process = new ProcessBuilder(command).start();
Preconditions.checkState(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command), IOUtils.toString(process.getErrorStream()));
final InputStream stream = process.getInputStream();
return IOUtils.readLines(stream);
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
private static void mkdirs(File dir)
{
Preconditions.checkState(dir.mkdirs() || (dir.isDirectory() && dir.exists()),
"could not create %s", dir);
}
static {
UNAME_S = system("uname", "-s").get(0);
UNAME_M = system("uname", "-m").get(0);
LOG.info("Detected a %s %s system", UNAME_S, UNAME_M);
File pgTbz;
try {
pgTbz = File.createTempFile("pgpg", "pgpg");
} catch (final IOException e) {
throw new ExceptionInInitializerError(e);
}
try {
final DigestInputStream pgArchiveData = new DigestInputStream(
EmbeddedPostgreSQL.class.getResourceAsStream(String.format("/postgresql-%s-%s.tbz", UNAME_S, UNAME_M)),
MessageDigest.getInstance("MD5"));
final FileOutputStream os = new FileOutputStream(pgTbz);
IOUtils.copy(pgArchiveData, os);
pgArchiveData.close();
os.close();
PG_DIGEST = Hex.encodeHexString(pgArchiveData.getMessageDigest().digest());
PG_DIR = new File(TMP_DIR, String.format("PG-%s", PG_DIGEST));
if (!PG_DIR.exists())
{
LOG.info("Extracting Postgres...");
mkdirs(PG_DIR);
system("tar", "-x", "-f", pgTbz.getPath(), "-C", PG_DIR.getPath());
}
} catch (final Exception e) {
throw new ExceptionInInitializerError(e);
} finally {
Preconditions.checkState(pgTbz.delete(), "could not delete %s", pgTbz);
}
LOG.info("Postgres binaries at %s", PG_DIR);
}
@Override
public String toString()
{
return "EmbeddedPG-" + instanceId;
}
}
|
Now that we use Java 7, eliminate reflection hackery. Also ensure that we actually finish extracting and otherwise retry next time.
|
pg-embedded/src/main/java/com/nesscomputing/db/postgres/embedded/EmbeddedPostgreSQL.java
|
Now that we use Java 7, eliminate reflection hackery. Also ensure that we actually finish extracting and otherwise retry next time.
|
|
Java
|
apache-2.0
|
78e043447c6103bbde92febbf8ef4b3c0db24303
| 0
|
yingyun001/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,halober/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine
|
package org.ovirt.engine.core.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.lang.NotImplementedException;
import org.ovirt.engine.core.common.businessentities.vds_spm_id_map;
import org.ovirt.engine.core.compat.Guid;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
/**
* <code>VdsSpmIdMapDAODbFacadeImpl</code> provides an implementation of {@link VdsSpmIdMapDAO} that uses previously written code from
* {@link org.ovirt.engine.core.dal.dbbroker.DbFacade}.
*/
public class VdsSpmIdMapDAODbFacadeImpl extends BaseDAODbFacade implements VdsSpmIdMapDAO{
@Override
public vds_spm_id_map get(Guid vdsId) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vds_id", vdsId);
return getCallsHandler().executeRead("Getvds_spm_id_mapByvds_id",
VdsSpmIdMapRowMapper.instance,
parameterSource);
}
@Override
public void save(vds_spm_id_map vds_spm_id_map) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("storage_pool_id",
vds_spm_id_map.getstorage_pool_id()).addValue("vds_id", vds_spm_id_map.getId()).addValue(
"vds_spm_id", vds_spm_id_map.getvds_spm_id());
getCallsHandler().executeModification("Insertvds_spm_id_map", parameterSource);
}
@Override
public void remove(Guid vdsId) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vds_id", vdsId);
getCallsHandler().executeModification("Deletevds_spm_id_map", parameterSource);
}
@Override
public List<vds_spm_id_map> getAll(Guid storagePoolId) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("storage_pool_id",
storagePoolId);
return getCallsHandler().executeReadList("Getvds_spm_id_mapBystorage_pool_id",
VdsSpmIdMapRowMapper.instance,
parameterSource);
}
@Override
public void removeByVdsAndStoragePool(Guid vdsId, Guid storagePoolId) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vds_id", vdsId).addValue("storage_pool_id",
storagePoolId);
getCallsHandler().executeModification("DeleteByPoolvds_spm_id_map", parameterSource);
}
@Override
public vds_spm_id_map get(Guid storagePoolId, int spmId ) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("storage_pool_id",
storagePoolId).addValue("vds_spm_id", spmId);
return getCallsHandler().executeRead("Getvds_spm_id_mapBystorage_pool_idAndByvds_spm_id",
VdsSpmIdMapRowMapper.instance,
parameterSource);
}
@Override
public List<vds_spm_id_map> getAll() {
throw new NotImplementedException();
}
@Override
public void update(vds_spm_id_map entity) {
throw new NotImplementedException();
}
private static final class VdsSpmIdMapRowMapper implements ParameterizedRowMapper<vds_spm_id_map> {
public static final VdsSpmIdMapRowMapper instance = new VdsSpmIdMapRowMapper();
@Override
public vds_spm_id_map mapRow(ResultSet rs, int rowNum) throws SQLException {
vds_spm_id_map entity = new vds_spm_id_map();
entity.setstorage_pool_id(Guid.createGuidFromString(rs.getString("storage_pool_id")));
entity.setId(Guid.createGuidFromString(rs.getString("vds_id")));
entity.setvds_spm_id(rs.getInt("vds_spm_id"));
return entity;
}
}
}
|
backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/VdsSpmIdMapDAODbFacadeImpl.java
|
package org.ovirt.engine.core.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.lang.NotImplementedException;
import org.ovirt.engine.core.common.businessentities.vds_spm_id_map;
import org.ovirt.engine.core.compat.Guid;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
/**
* <code>VdsSpmIdMapDAODbFacadeImpl</code> provides an implementation of {@link VdsSpmIdMapDAO} that uses previously written code from
* {@link org.ovirt.engine.core.dal.dbbroker.DbFacade}.
*/
public class VdsSpmIdMapDAODbFacadeImpl extends BaseDAODbFacade implements VdsSpmIdMapDAO{
@Override
public vds_spm_id_map get(Guid vdsId) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vds_id", vdsId);
ParameterizedRowMapper<vds_spm_id_map> mapper = new ParameterizedRowMapper<vds_spm_id_map>() {
@Override
public vds_spm_id_map mapRow(ResultSet rs, int rowNum) throws SQLException {
vds_spm_id_map entity = new vds_spm_id_map();
entity.setstorage_pool_id(Guid.createGuidFromString(rs.getString("storage_pool_id")));
entity.setId(Guid.createGuidFromString(rs.getString("vds_id")));
entity.setvds_spm_id(rs.getInt("vds_spm_id"));
return entity;
}
};
return getCallsHandler().executeRead("Getvds_spm_id_mapByvds_id", mapper, parameterSource);
}
@Override
public void save(vds_spm_id_map vds_spm_id_map) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("storage_pool_id",
vds_spm_id_map.getstorage_pool_id()).addValue("vds_id", vds_spm_id_map.getId()).addValue(
"vds_spm_id", vds_spm_id_map.getvds_spm_id());
getCallsHandler().executeModification("Insertvds_spm_id_map", parameterSource);
}
@Override
public void remove(Guid vdsId) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vds_id", vdsId);
getCallsHandler().executeModification("Deletevds_spm_id_map", parameterSource);
}
@Override
public List<vds_spm_id_map> getAll(Guid storagePoolId) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("storage_pool_id",
storagePoolId);
ParameterizedRowMapper<vds_spm_id_map> mapper = new ParameterizedRowMapper<vds_spm_id_map>() {
@Override
public vds_spm_id_map mapRow(ResultSet rs, int rowNum) throws SQLException {
vds_spm_id_map entity = new vds_spm_id_map();
entity.setstorage_pool_id(Guid.createGuidFromString(rs.getString("storage_pool_id")));
entity.setId(Guid.createGuidFromString(rs.getString("vds_id")));
entity.setvds_spm_id(rs.getInt("vds_spm_id"));
return entity;
}
};
return getCallsHandler().executeReadList("Getvds_spm_id_mapBystorage_pool_id", mapper, parameterSource);
}
@Override
public void removeByVdsAndStoragePool(Guid vdsId, Guid storagePoolId) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("vds_id", vdsId).addValue("storage_pool_id",
storagePoolId);
getCallsHandler().executeModification("DeleteByPoolvds_spm_id_map", parameterSource);
}
@Override
public vds_spm_id_map get(Guid storagePoolId, int spmId ) {
MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("storage_pool_id",
storagePoolId).addValue("vds_spm_id", spmId);
ParameterizedRowMapper<vds_spm_id_map> mapper = new ParameterizedRowMapper<vds_spm_id_map>() {
@Override
public vds_spm_id_map mapRow(ResultSet rs, int rowNum) throws SQLException {
vds_spm_id_map entity = new vds_spm_id_map();
entity.setstorage_pool_id(Guid.createGuidFromString(rs.getString("storage_pool_id")));
entity.setId(Guid.createGuidFromString(rs.getString("vds_id")));
entity.setvds_spm_id(rs.getInt("vds_spm_id"));
return entity;
}
};
return getCallsHandler().executeRead("Getvds_spm_id_mapBystorage_pool_idAndByvds_spm_id",
mapper,
parameterSource);
}
@Override
public List<vds_spm_id_map> getAll() {
throw new NotImplementedException();
}
@Override
public void update(vds_spm_id_map entity) {
throw new NotImplementedException();
}
}
|
core: Singleton row mapper for vds_spm_id_map
Added a singleton row mapper for VdsSpmIdMapDAO, as specified by
http://www.ovirt.org/Backend_Coding_Standards .
Change-Id: I04b439e9e2868d66f612144dd91e4f65becd9936
Signed-off-by: Allon Mureinik <abc9ddaceaf0c059a5d9bc2aed71f25cb5370dba@redhat.com>
|
backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/VdsSpmIdMapDAODbFacadeImpl.java
|
core: Singleton row mapper for vds_spm_id_map
|
|
Java
|
apache-2.0
|
ec057ed764f85a8f2195111e415e557aeed7d5a0
| 0
|
avano/fabric8,jludvice/fabric8,jludvice/fabric8,avano/fabric8,avano/fabric8,avano/fabric8,chirino/fabric8,jludvice/fabric8,chirino/fabric8,chirino/fabric8,chirino/fabric8,jludvice/fabric8
|
/**
* Copyright 2005-2015 Red Hat, Inc.
*
* Red Hat 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.fabric8.patch.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import io.fabric8.patch.Service;
import io.fabric8.patch.management.Artifact;
import io.fabric8.patch.management.BundleUpdate;
import io.fabric8.patch.management.FeatureUpdate;
import io.fabric8.patch.management.Patch;
import io.fabric8.patch.management.PatchData;
import io.fabric8.patch.management.PatchDetailsRequest;
import io.fabric8.patch.management.PatchException;
import io.fabric8.patch.management.PatchKind;
import io.fabric8.patch.management.PatchManagement;
import io.fabric8.patch.management.PatchResult;
import io.fabric8.patch.management.Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.utils.manifest.Clause;
import org.apache.felix.utils.manifest.Parser;
import org.apache.felix.utils.version.VersionRange;
import org.apache.felix.utils.version.VersionTable;
import org.apache.karaf.features.Feature;
import org.apache.karaf.features.FeaturesService;
import org.apache.karaf.features.Repository;
import org.apache.karaf.util.bundles.BundleUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.service.component.ComponentContext;
import org.osgi.util.tracker.ServiceTracker;
import static io.fabric8.patch.management.Utils.mvnurlToArtifact;
import static io.fabric8.patch.management.Utils.stripSymbolicName;
@Component(immediate = true, metatype = false)
@org.apache.felix.scr.annotations.Service(Service.class)
public class ServiceImpl implements Service {
private static final String ID = "id";
private static final String DESCRIPTION = "description";
private static final String DATE = "date";
private static final String BUNDLES = "bundle";
private static final String UPDATES = "update";
private static final String COUNT = "count";
private static final String RANGE = "range";
private static final String SYMBOLIC_NAME = "symbolic-name";
private static final String NEW_VERSION = "new-version";
private static final String NEW_LOCATION = "new-location";
private static final String OLD_VERSION = "old-version";
private static final String OLD_LOCATION = "old-location";
private static final String STARTUP = "startup";
private static final String OVERRIDES = "overrides";
private BundleContext bundleContext;
private File patchDir;
@Reference(referenceInterface = PatchManagement.class, cardinality = ReferenceCardinality.MANDATORY_UNARY, policy = ReferencePolicy.STATIC)
private PatchManagement patchManagement;
@Reference(referenceInterface = FeaturesService.class, cardinality = ReferenceCardinality.MANDATORY_UNARY, policy = ReferencePolicy.STATIC)
private FeaturesService featuresService;
private File karafHome;
// by default it's ${karaf.home}/system
private File repository;
@Activate
void activate(ComponentContext componentContext) {
// Use system bundle' bundle context to avoid running into
// "Invalid BundleContext" exceptions when updating bundles
this.bundleContext = componentContext.getBundleContext().getBundle(0).getBundleContext();
String dir = this.bundleContext.getProperty(NEW_PATCH_LOCATION);
if (dir != null) {
patchDir = new File(dir);
} else {
dir = this.bundleContext.getProperty(PATCH_LOCATION);
if (dir != null) {
patchDir = new File(dir);
} else {
// only now fallback to datafile of system bundle
patchDir = this.bundleContext.getDataFile("patches");
}
}
if (!patchDir.isDirectory()) {
patchDir.mkdirs();
if (!patchDir.isDirectory()) {
throw new PatchException("Unable to create patch folder");
}
}
this.karafHome = new File(bundleContext.getProperty("karaf.home"));
this.repository = new File(bundleContext.getProperty("karaf.default.repository"));
load(true);
}
@Override
public Iterable<Patch> getPatches() {
return Collections.unmodifiableCollection(load(true).values());
}
@Override
public Patch getPatch(String id) {
return patchManagement.loadPatch(new PatchDetailsRequest(id));
}
@Override
public Iterable<Patch> download(URL url) {
try {
List<PatchData> patchesData = patchManagement.fetchPatches(url);
List<Patch> patches = new ArrayList<>(patchesData.size());
for (PatchData patchData : patchesData) {
Patch patch = patchManagement.trackPatch(patchData);
patches.add(patch);
}
return patches;
} catch (Exception e) {
throw new PatchException("Unable to download patch from url " + url, e);
}
}
/**
* Loads available patches without caching
* @param details whether to load {@link io.fabric8.patch.management.ManagedPatch} details too
* @return
*/
private Map<String, Patch> load(boolean details) {
List<Patch> patchesList = patchManagement.listPatches(details);
Map<String, Patch> patches = new HashMap<String, Patch>();
for (Patch patch : patchesList) {
patches.put(patch.getPatchData().getId(), patch);
}
return patches;
}
/**
* Used by the patch client when executing the script in the console
* @param ids
*/
public void cliInstall(String[] ids) {
final List<Patch> patches = new ArrayList<Patch>();
for (String id : ids) {
Patch patch = getPatch(id);
if (patch == null) {
throw new IllegalArgumentException("Unknown patch: " + id);
}
patches.add(patch);
}
install(patches, false, false);
}
@Override
public PatchResult install(Patch patch, boolean simulate) {
return install(patch, simulate, true);
}
@Override
public PatchResult install(Patch patch, boolean simulate, boolean synchronous) {
Map<String, PatchResult> results = install(Collections.singleton(patch), simulate, synchronous);
return results.get(patch.getPatchData().getId());
}
/**
* <p>Main installation method. Installing a patch in non-fabric mode is a matter of correct merge (cherry-pick, merge,
* rebase) of patch branch into <code>master</code> branch.</p>
* <p>Instaling a patch has three goals:<ul>
* <li>update static files/libs in KARAF_HOME</li>
* <li>update (uninstall+install) features</li>
* <li>update remaining bundles (not yet updated during feature update)</li>
* </ul></p>
* @param patches
* @param simulate
* @param synchronous
* @return
*/
private Map<String, PatchResult> install(final Collection<Patch> patches, final boolean simulate, boolean synchronous) {
PatchKind kind = checkConsistency(patches);
checkPrerequisites(patches);
String transaction = null;
// poor-man's lifecycle management in case when SCR nullifies our reference
final PatchManagement pm = patchManagement;
try {
// Compute individual patch results (patchId -> Result)
final Map<String, PatchResult> results = new LinkedHashMap<String, PatchResult>();
// current state of the framework
Bundle[] allBundles = bundleContext.getBundles();
Map<String, Repository> allFeatureRepositories = getAvailableFeatureRepositories();
// bundle -> url to update the bundle from
final Map<Bundle, String> bundleUpdateLocations = new HashMap<>();
// [feature name|updateable-version] -> url of repository to get it from
final Map<String, String> featureUpdateRepositories = new HashMap<>();
// feature name -> url of repository to get it from - in case we have only one feature with that name
// like "transaction" in karaf-enterprise features
final Map<String, String> singleFeatureUpdateRepositories = new HashMap<>();
/* A "key" is name + "update'able version". Such version is current version with micro version == 0 */
// [symbolic name|updateable-version] -> newest update for the bundle out of all installed patches
Map<String, BundleUpdate> updatesForBundleKeys = new HashMap<>();
// [feature name|updateable-version] -> newest update for the feature out of all installed patches
final Map<String, FeatureUpdate> updatesForFeatureKeys = new HashMap<>();
// symbolic name -> version -> location
final BundleVersionHistory history = createBundleVersionHistory();
// beginning installation transaction = creating of temporary branch in git
transaction = this.patchManagement.beginInstallation(kind);
// bundles from etc/startup.properties + felix.framework = all bundles not managed by features
// these bundles will be treated in special way
// symbolic name -> Bundle
final Map<String, Bundle> coreBundles = getCoreBundles(allBundles);
// collect runtime information from patches (features, bundles) and static information (files)
// runtime info is prepared to apply runtime changes and static info is prepared to update KARAF_HOME files
for (Patch patch : patches) {
// list of bundle updates for the current patch - only for the purpose of storing result
List<BundleUpdate> bundleUpdatesInThisPatch = bundleUpdatesInPatch(patch, allBundles,
bundleUpdateLocations, history, updatesForBundleKeys, kind, coreBundles);
// list of feature updates for the current patch - only for the purpose of storing result
List<FeatureUpdate> featureUpdatesInThisPatch = featureUpdatesInPatch(patch, allFeatureRepositories,
featureUpdateRepositories, singleFeatureUpdateRepositories, updatesForFeatureKeys, kind);
// each patch may change files, we're not updating the main files yet - it'll be done when
// install transaction is committed
patchManagement.install(transaction, patch);
// each patch may ship a migrator
installMigratorBundle(patch);
// prepare patch result before doing runtime changes
PatchResult result = new PatchResult(patch.getPatchData(), simulate, System.currentTimeMillis(),
bundleUpdatesInThisPatch, featureUpdatesInThisPatch);
results.put(patch.getPatchData().getId(), result);
}
// We don't have to update bundles that are uninstalled anyway when uninstalling features we
// are updating. Updating a feature = uninstall + install
// When feature is uninstalled, its bundles may get uninstalled too, if they are not referenced
// from any other feature, including special (we're implementation aware!) "startup" feature
// that is created during initailization of FeaturesService. As expected, this feature contains
// all bundles started by other means which is:
// - felix.framework (system bundle)
// - all bundles referenced in etc/startup.properties
// Some special cases
for (Map.Entry<Bundle, String> entry : bundleUpdateLocations.entrySet()) {
Bundle bundle = entry.getKey();
if ("org.ops4j.pax.url.mvn".equals(stripSymbolicName(bundle.getSymbolicName()))) {
// handle this bundle specially - update it here
URL location = new URL(entry.getValue());
System.out.printf("Special update of bundle \"%s\" from \"%s\"%n",
bundle.getSymbolicName(), location);
if (!simulate) {
BundleUtils.update(bundle, location);
bundle.start();
}
// replace location - to be stored in result
bundleUpdateLocations.put(bundle, location.toString());
}
}
displayFeatureUpdates(updatesForFeatureKeys, simulate);
// effectively, we will update all the bundles from this list - even if some bundles will be "updated"
// as part of feature installation
displayBundleUpdates(bundleUpdateLocations, simulate);
if (!simulate) {
// update KARAF_HOME
pm.commitInstallation(transaction);
for (Patch patch : patches) {
PatchResult result = results.get(patch.getPatchData().getId());
patch.setResult(result);
result.store();
}
storeWorkForPendingRestart(results);
System.out.println("Restarting Karaf..");
File karafData = new File(bundleContext.getProperty("karaf.data"));
File cleanCache = new File(karafData, "clean_cache");
cleanCache.createNewFile();
System.setProperty("karaf.restart", "true");
bundleContext.getBundle(0l).stop();
} else {
patchManagement.rollbackInstallation(transaction);
}
///
// Leaving all of this in place for nw
///
if( true ) {
return results;
}
Runnable task = null;
if (!simulate) {
final String finalTransaction = transaction;
task = new Runnable() {
@Override
public void run() {
try {
// collect features to uninstall
List<String[]> featuresToUninstallAfterUpdatingBundles = new LinkedList<>();
// uninstall old features and repositories repositories
if (!simulate && updatesForFeatureKeys.size() > 0) {
Set<String> oldRepositories = new HashSet<>();
Set<String> newRepositories = new HashSet<>();
for (FeatureUpdate fu : updatesForFeatureKeys.values()) {
oldRepositories.add(fu.getPreviousRepository());
newRepositories.add(fu.getNewRepository());
}
Map<String, Repository> repos = new HashMap<>();
for (Repository r : featuresService.listRepositories()) {
repos.put(r.getURI().toString(), r);
}
for (String uri : oldRepositories) {
if (repos.containsKey(uri)) {
Repository r = repos.get(uri);
for (Feature f : r.getFeatures()) {
if (featuresService.isInstalled(f)) {
featuresToUninstallAfterUpdatingBundles.add(new String[] {
f.getName(),
f.getVersion()
});
// fs.uninstallFeature(f.getName(), f.getVersion(), EnumSet.of(FeaturesService.Option.NoAutoRefreshBundles));
}
}
}
}
// we can already remove repositories
for (String uri : oldRepositories) {
featuresService.removeRepository(URI.create(uri));
}
// TODO: we should add not only repositories related to updated features, but also all from
// "featureRepositories" property from new etc/org.apache.karaf.features.cfg
for (Patch p : patches) {
for (String uri : p.getPatchData().getFeatureFiles()) {
featuresService.addRepository(URI.create(uri));
}
}
}
// update bundles
applyChanges(bundleUpdateLocations);
if (updatesForFeatureKeys.size() > 0) {
Object featuresService = null;
try {
ServiceTracker<?, ?> tracker = new ServiceTracker<>(bundleContext, "org.apache.karaf.features.FeaturesService", null);
tracker.open();
Object service = tracker.waitForService(30000);
if (service != null) {
featuresService = service;
}
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace(System.err);
System.err.flush();
}
}
// update KARAF_HOME
if (!simulate) {
pm.commitInstallation(finalTransaction);
} else {
patchManagement.rollbackInstallation(finalTransaction);
}
// TODO: uninstall features?
// install new features - in order
if (updatesForFeatureKeys.size() > 0) {
Properties properties = new Properties();
FileInputStream inStream = new FileInputStream(new File(karafHome, "etc/org.apache.karaf.features.cfg"));
properties.load(inStream);
IOUtils.closeQuietly(inStream);
String featuresBoot = properties.getProperty("featuresBoot");
Set<String> coreFeatures = new LinkedHashSet<>(Arrays.asList(featuresBoot.split(", *")));
// Now that we don't have any of the old feature repos installed
// Lets re-install the features that were previously installed.
try {
ServiceTracker<FeaturesService, FeaturesService> tracker = new ServiceTracker<>(bundleContext, FeaturesService.class, null);
tracker.open();
Object service = tracker.waitForService(30000);
if (service != null) {
Method m = service.getClass().getDeclaredMethod("installFeature", String.class );
if (m != null) {
for (String cf : coreFeatures) {
if (simulate) {
System.out.println("Simulation: Enable core feature: " + cf);
} else {
System.out.println("Enable core feature: " + cf);
m.invoke(service, cf);
}
}
}
m = service.getClass().getDeclaredMethod("installFeature", String.class, String.class );
if (m != null) {
for (FeatureUpdate update : updatesForFeatureKeys.values()) {
if (coreFeatures.contains(update.getName())) {
continue;
}
if (simulate) {
System.out.println("Simulation: Enable feature: " + update.getName() + "/" + update.getNewVersion());
} else {
System.out.println("Enable feature: " + update.getName() + "/" + update.getNewVersion());
m.invoke(service, update.getName(), update.getNewVersion());
}
}
}
} else {
System.err.println("Can't get OSGi reference to FeaturesService");
}
} catch (Exception e) {
e.printStackTrace();
System.err.flush();
}
}
// persist results of all installed patches
for (Patch patch : patches) {
PatchResult result = results.get(patch.getPatchData().getId());
patch.setResult(result);
result.store();
}
} catch (Exception e) {
e.printStackTrace(System.err);
System.err.flush();
}
}
};
}
// Bundle fileinstal = null;
// Bundle configadmin = null;
// if (!simulate) {
// // let's stop fileinstall and configadmin
// for (Bundle b : allBundles) {
// if ("org.apache.felix.fileinstall".equals(b.getSymbolicName())) {
// fileinstal = b;
// } else if ("org.apache.felix.configadmin".equals(b.getSymbolicName())) {
// configadmin = b;
// }
// }
// if (fileinstal != null) {
// fileinstal.stop(Bundle.STOP_TRANSIENT);
// }
// if (configadmin != null) {
// configadmin.stop(Bundle.STOP_TRANSIENT);
// }
// }
// update bundles (special case: pax-url-aether) and install features
if (!simulate) {
if (synchronous) {
task.run();
} else {
new Thread(task).start();
}
}
// if (!simulate) {
// if (configadmin != null) {
// configadmin.start(Bundle.START_TRANSIENT);
// }
// if (fileinstal != null) {
// fileinstal.start(Bundle.START_TRANSIENT);
// }
// }
return results;
} catch (Exception e) {
if (transaction != null) {
pm.rollbackInstallation(transaction);
}
throw new PatchException(e.getMessage(), e);
}
}
private void storeWorkForPendingRestart(Map<String, PatchResult> results) throws Exception {
for (PatchResult patchResult : results.values()) {
HashMap<String, BundleUpdate> bundleUpdates = new HashMap<>();
for (BundleUpdate update : patchResult.getBundleUpdates()) {
bundleUpdates.put(update.getSymbolicName() + ";" + update.getPreviousVersion(), update);
}
HashSet<String> bundlesToInstall = new HashSet<>();
for (Bundle bundle : bundleContext.getBundles()) {
if( bundle.getState() == Bundle.UNINSTALLED ) {
continue;
}
BundleUpdate update = bundleUpdates.get(bundle.getSymbolicName() + ":" + bundle.getVersion());
if( update!=null ) {
bundlesToInstall.add(bundle.getLocation());
} else {
bundlesToInstall.add(update.getNewLocation());
}
}
HashMap<String, FeatureUpdate> featureUpdates = new HashMap<>();
for (FeatureUpdate update : patchResult.getFeatureUpdates()) {
String key = update.getPreviousRepository()+";"+update.getName()+";"+update.getPreviousVersion();
featureUpdates.put(key, update);
}
HashSet<String> featuresReposToInstall = new HashSet<>();
HashSet<String> featuresToInstall = new HashSet<>();
for (Repository repo : featuresService.listRepositories()) {
for (Feature feature : repo.getFeatures()) {
if( featuresService.isInstalled(feature) ) {
String key = repo.getURI()+";"+feature.getName()+";"+feature.getVersion();
FeatureUpdate update = featureUpdates.get(key);
if( update!=null ) {
featuresReposToInstall.add(update.getNewRepository());
featuresToInstall.add(update.getName()+":"+update.getNewVersion());
} else {
featuresReposToInstall.add(repo.getURI().toString());
featuresToInstall.add(feature.getName()+":"+feature.getVersion());
}
}
}
}
// Ok lets store bundlesToInstall, featuresReposToInstall, featuresToInstall
}
}
// Lets create a pending restart work file that
// re-instates the container state.
private void storeWorkForPendingRestart() {
}
private void displayFeatureUpdates(Map<String, FeatureUpdate> featureUpdates, boolean simulate) {
Set<String> toRemove = new TreeSet<>();
Set<String> toAdd = new TreeSet<>();
for (FeatureUpdate fu : featureUpdates.values()) {
toRemove.add(fu.getPreviousRepository());
toAdd.add(fu.getNewRepository());
}
System.out.println("Repositories to remove:");
for (String repo : toRemove) {
System.out.println(" - " + repo);
}
System.out.println("Repositories to add:");
for (String repo : toAdd) {
System.out.println(" - " + repo);
}
System.out.println("Features to update:");
int l1 = "[name]".length();
int l2 = "[version]".length();
int l3 = "[new version]".length();
for (FeatureUpdate fu : featureUpdates.values()) {
if (fu.getName().length() > l1) {
l1 = fu.getName().length();
}
if (fu.getPreviousVersion().length() > l2) {
l2 = fu.getPreviousVersion().length();
}
if (fu.getNewVersion().length() > l3) {
l3 = fu.getNewVersion().length();
}
}
System.out.printf("%-" + l1 + "s %-" + l2 + "s %-" + l3 + "s%n",
"[name]", "[version]", "[new version]");
for (FeatureUpdate fu : featureUpdates.values()) {
System.out.printf("%-" + l1 + "s %-" + l2 + "s %-" + l3 + "s%n",
fu.getName(), fu.getPreviousVersion(), fu.getNewVersion());
}
if (simulate) {
System.out.println("Running simulation only - no features are being updated at this time");
} else {
System.out.println("Installation of features will begin.");
}
System.out.flush();
}
private void displayBundleUpdates(Map<Bundle, String> bundleUpdateLocations, boolean simulate) {
System.out.println("Bundles to update:");
int l1 = "[symbolic name]".length();
int l2 = "[version]".length();
int l3 = "[new location]".length();
for (Map.Entry<Bundle, String> e : bundleUpdateLocations.entrySet()) {
String sn = stripSymbolicName(e.getKey().getSymbolicName());
if (sn.length() > l1) {
l1 = sn.length();
}
String version = e.getKey().getVersion().toString();
if (version.length() > l2) {
l2 = version.length();
}
String newLocation = e.getValue();
if (newLocation.length() > l3) {
l3 = newLocation.length();
}
}
System.out.printf("%-" + l1 + "s %-" + l2 + "s %-" + l3 + "s%n",
"[symbolic name]", "[version]", "[new location]");
for (Map.Entry<Bundle, String> e : bundleUpdateLocations.entrySet()) {
System.out.printf("%-" + l1 + "s %-" + l2 + "s %-" + l3 + "s%n",
stripSymbolicName(e.getKey().getSymbolicName()),
e.getKey().getVersion().toString(), e.getValue());
}
if (simulate) {
System.out.println("Running simulation only - no bundles are being updated at this time");
} else {
System.out.println("Installation will begin. The connection may be lost or the console restarted.");
}
System.out.flush();
}
/**
* Returns a list of {@link BundleUpdate} for single patch, taking into account already discovered updates
* @param patch
* @param allBundles
* @param bundleUpdateLocations out parameter that gathers update locations for bundles across patches
* @param history
* @param updatesForBundleKeys
* @param kind
* @param coreBundles
* @return
* @throws IOException
*/
private List<BundleUpdate> bundleUpdatesInPatch(Patch patch,
Bundle[] allBundles,
Map<Bundle, String> bundleUpdateLocations,
BundleVersionHistory history,
Map<String, BundleUpdate> updatesForBundleKeys,
PatchKind kind,
Map<String, Bundle> coreBundles) throws IOException {
List<BundleUpdate> updatesInThisPatch = new LinkedList<>();
for (String newLocation : patch.getPatchData().getBundles()) {
// [symbolicName, version] of the new bundle
String[] symbolicNameVersion = getBundleIdentity(newLocation);
if (symbolicNameVersion == null) {
continue;
}
String sn = symbolicNameVersion[0];
String vr = symbolicNameVersion[1];
Version newVersion = VersionTable.getVersion(vr);
// if existing bundle is withing this range, update is possible
VersionRange range = getUpdateableRange(patch, newLocation, newVersion);
if (coreBundles.containsKey(sn)) {
if (range == null) {
range = new VersionRange(false, Version.emptyVersion, newVersion, true);
} else {
range = new VersionRange(false, Version.emptyVersion, range.getCeiling(), true);
}
}
if (range != null) {
for (Bundle bundle : allBundles) {
if (bundle.getBundleId() == 0L) {
continue;
}
if (!stripSymbolicName(sn).equals(stripSymbolicName(bundle.getSymbolicName()))) {
continue;
}
Version oldVersion = bundle.getVersion();
if (range.contains(oldVersion)) {
String oldLocation = history.getLocation(bundle);
if ("org.ops4j.pax.url.mvn".equals(stripSymbolicName(sn))) {
Artifact artifact = Utils.mvnurlToArtifact(newLocation, true);
URL location = new File(repository,
String.format("org/ops4j/pax/url/pax-url-aether/%s/pax-url-aether-%s.jar",
artifact.getVersion(), artifact.getVersion())).toURI().toURL();
newLocation = location.toString();
}
BundleUpdate update = new BundleUpdate(sn, newVersion.toString(), newLocation,
oldVersion.toString(), oldLocation);
updatesInThisPatch.add(update);
// Merge result
String key = String.format("%s|%s", sn, range.getFloor());
BundleUpdate oldUpdate = updatesForBundleKeys.get(key);
if (oldUpdate != null) {
Version upv = VersionTable.getVersion(oldUpdate.getNewVersion());
if (upv.compareTo(newVersion) < 0) {
// other patch contains newer update for a bundle
updatesForBundleKeys.put(key, update);
bundleUpdateLocations.put(bundle, newLocation);
}
} else {
// this is the first update of the bundle
updatesForBundleKeys.put(key, update);
bundleUpdateLocations.put(bundle, newLocation);
}
}
}
} else {
if (kind == PatchKind.ROLLUP) {
// we simply do not touch the bundle from patch - it is installed in KARAF_HOME/system
// and available to be installed when new features are detected
} else {
// for non-rollup patches however, we signal an error - all bundles from P patch
// should be used to update already installed bundles
System.err.printf("Skipping bundle %s - unable to process bundle without a version range configuration%n", newLocation);
}
}
}
return updatesInThisPatch;
}
/**
* Returns a list of {@link FeatureUpdate} for single patch, taking into account already discovered updates
* @param patch
* @param allFeatureRepositories
* @param featureUpdateRepositories
* @param singleFeatureUpdateRepositories
* @param updatesForFeatureKeys
* @param kind @return
*/
private List<FeatureUpdate> featureUpdatesInPatch(Patch patch,
Map<String, Repository> allFeatureRepositories,
Map<String, String> featureUpdateRepositories,
Map<String, String> singleFeatureUpdateRepositories,
Map<String, FeatureUpdate> updatesForFeatureKeys,
PatchKind kind) throws Exception {
Set<String> addedRepositoryNames = new HashSet<>();
HashMap<String, Repository> after = null;
try {
List<FeatureUpdate> updatesInThisPatch = new LinkedList<>();
/*
* Two pairs of features makes feature names not enough to be a key:
* <feature name="openjpa" description="Apache OpenJPA 2.2.x persistent engine support" version="2.2.2" resolver="(obr)">
* <feature name="openjpa" description="Apache OpenJPA 2.3.x persistence engine support" version="2.3.0" resolver="(obr)">
* and
* <feature name="activemq-camel" version="5.11.0.redhat-621039" resolver="(obr)" start-level="50">
* <feature name="activemq-camel" version="1.2.0.redhat-621039" resolver="(obr)">
*/
// install the new feature repos, tracking the set the were
// installed before and after
// (e.g, "karaf-enterprise-2.4.0.redhat-620133" -> Repository)
Map<String, Repository> before = new HashMap<>(allFeatureRepositories);
for (String url : patch.getPatchData().getFeatureFiles()) {
featuresService.addRepository(new URI(url));
}
after = getAvailableFeatureRepositories();
// track which old repos provide which features to find out if we have new repositories for those features
// key is name|version (don't expect '|' to be part of name...)
// assume that [feature-name, feature-version{major,minor,0,0}] is defined only in single repository
Map<String, String> featuresInOldRepositories = new HashMap<>();
// key is only name, without version - used when there's single feature in old and in new repositories
MultiMap<String, String> singleFeaturesInOldRepositories = new MultiMap<>();
Map<String, Version> actualOldFeatureVersions = new HashMap<>();
for (Repository repository : before.values()) {
for (Feature feature : repository.getFeatures()) {
Version v = Utils.getFeatureVersion(feature.getVersion());
Version lowestUpdateableVersion = new Version(v.getMajor(), v.getMinor(), 0);
// assume that we can update feature XXX-2.2.3 to XXX-2.2.142, but not to XXX-2.3.0.alpha-1
String key = String.format("%s|%s", feature.getName(), lowestUpdateableVersion.toString());
featuresInOldRepositories.put(key, repository.getName());
singleFeaturesInOldRepositories.put(feature.getName(), repository.getName());
actualOldFeatureVersions.put(key, v);
}
}
// Use the before and after set to figure out which repos were added.
addedRepositoryNames = new HashSet<>(after.keySet());
addedRepositoryNames.removeAll(before.keySet());
// track the new repositories where we can find old features
Map<String, String> featuresInNewRepositories = new HashMap<>();
MultiMap<String, String> singleFeaturesInNewRepositories = new MultiMap<>();
Map<String, String> actualNewFeatureVersions = new HashMap<>();
MultiMap<String, String> singleActualNewFeatureVersions = new MultiMap<>();
// Figure out which old repos were updated: Do they have feature
// with the same name as one contained in a repo being added?
// and do they have update'able version? (just like with bundles)
HashSet<String> oldRepositoryNames = new HashSet<String>();
for (String addedRepositoryName : addedRepositoryNames) {
Repository added = after.get(addedRepositoryName);
for (Feature feature : added.getFeatures()) {
Version v = Utils.getFeatureVersion(feature.getVersion());
Version lowestUpdateableVersion = new Version(v.getMajor(), v.getMinor(), 0);
String key = String.format("%s|%s", feature.getName(), lowestUpdateableVersion.toString());
featuresInNewRepositories.put(key, addedRepositoryName);
singleFeaturesInNewRepositories.put(feature.getName(), addedRepositoryName);
actualNewFeatureVersions.put(key, v.toString());
singleActualNewFeatureVersions.put(feature.getName(), v.toString());
String oldRepositoryWithUpdateableFeature = featuresInOldRepositories.get(key);
if (oldRepositoryWithUpdateableFeature == null
&& singleFeaturesInOldRepositories.get(feature.getName()) != null) {
oldRepositoryWithUpdateableFeature = singleFeaturesInOldRepositories.get(feature.getName()).get(0);
}
if (oldRepositoryWithUpdateableFeature != null) {
oldRepositoryNames.add(oldRepositoryWithUpdateableFeature);
}
}
}
// Now we know which are the old repos that have been udpated.
// again assume that we can find ALL of the features from this old repository in a new repository
// We need to uninstall them. Before we uninstall, track which features were installed.
for (String oldRepositoryName : oldRepositoryNames) {
Repository repository = before.get(oldRepositoryName);
for (Feature feature : repository.getFeatures()) {
if (featuresService.isInstalled(feature)) {
Version v = Utils.getFeatureVersion(feature.getVersion());
Version lowestUpdateableVersion = new Version(v.getMajor(), v.getMinor(), 0);
String key = String.format("%s|%s", feature.getName(), lowestUpdateableVersion.toString());
String newRepository = featuresInNewRepositories.get(key);
String newVersion = actualNewFeatureVersions.get(key);
if (newRepository == null) {
// try looking up the feature without version - e.g., like in updating "transaction"
// feature from 1.1.1 to 1.3.0
if (singleFeaturesInOldRepositories.get(feature.getName()) != null
&& singleFeaturesInOldRepositories.get(feature.getName()).size() == 1
&& singleFeaturesInNewRepositories.get(feature.getName()) != null
&& singleFeaturesInNewRepositories.get(feature.getName()).size() == 1) {
newRepository = singleFeaturesInNewRepositories.get(feature.getName()).get(0);
}
}
if (newVersion == null) {
if (singleActualNewFeatureVersions.get(feature.getName()) != null
&& singleActualNewFeatureVersions.get(feature.getName()).size() == 1) {
newVersion = singleActualNewFeatureVersions.get(feature.getName()).get(0);
}
}
FeatureUpdate featureUpdate = new FeatureUpdate(feature.getName(),
after.get(oldRepositoryName).getURI().toString(),
feature.getVersion(),
after.get(newRepository).getURI().toString(),
newVersion);
updatesInThisPatch.add(featureUpdate);
// Merge result
FeatureUpdate oldUpdate = updatesForFeatureKeys.get(key);
if (oldUpdate != null) {
Version upv = VersionTable.getVersion(oldUpdate.getNewVersion());
Version newV = VersionTable.getVersion(actualNewFeatureVersions.get(key));
if (upv.compareTo(newV) < 0) {
// other patch contains newer update for the feature
updatesForFeatureKeys.put(key, featureUpdate);
featureUpdateRepositories.put(key, featuresInNewRepositories.get(key));
}
} else {
// this is the first update of the bundle
updatesForFeatureKeys.put(key, featureUpdate);
featureUpdateRepositories.put(key, featuresInNewRepositories.get(key));
}
}
}
}
return updatesInThisPatch;
} catch (Exception e) {
throw new PatchException(e.getMessage(), e);
} finally {
// we'll add new feature repositories again. here we've added them only to track the updates
if (addedRepositoryNames != null && after != null) {
for (String repo : addedRepositoryNames) {
if (after.get(repo) != null) {
featuresService.removeRepository(after.get(repo).getURI(), false);
}
}
}
}
}
/**
* If patch contains migrator bundle, install it by dropping to <code>deploy</code> directory.
* @param patch
* @throws IOException
*/
private void installMigratorBundle(Patch patch) throws IOException {
if (patch.getPatchData().getMigratorBundle() != null) {
Artifact artifact = mvnurlToArtifact(patch.getPatchData().getMigratorBundle(), true);
if (artifact != null) {
// Copy it to the deploy dir
File src = new File(repository, artifact.getPath());
File target = new File(Utils.getDeployDir(karafHome), artifact.getArtifactId() + ".jar");
FileUtils.copyFile(src, target);
}
}
}
/**
* Returns a map of bundles (symbolic name -> Bundle) that were installed in <em>classic way</em> - i.e.,
* not using {@link FeaturesService}.
* User may have installed other bundles, drop some to <code>deploy/</code>, etc, but these probably
* are not handled by patch mechanism.
* @param allBundles
* @return
*/
private Map<String, Bundle> getCoreBundles(Bundle[] allBundles) throws IOException {
Map<String, Bundle> coreBundles = new HashMap<>();
Properties props = new Properties();
FileInputStream stream = new FileInputStream(new File(karafHome, "etc/startup.properties"));
props.load(stream);
Set<String> locations = new HashSet<>();
for (String startupBundle : props.stringPropertyNames()) {
locations.add(Utils.pathToMvnurl(startupBundle));
}
for (Bundle b : allBundles) {
String symbolicName = Utils.stripSymbolicName(b.getSymbolicName());
if ("org.apache.felix.framework".equals(symbolicName)) {
coreBundles.put(symbolicName, b);
} else if ("org.ops4j.pax.url.mvn".equals(symbolicName)) {
// we could check if it's in etc/startup.properties, but we're 100% sure :)
coreBundles.put(symbolicName, b);
} else {
// only if it's in etc/startup.properties
if (locations.contains(b.getLocation())) {
coreBundles.put(symbolicName, b);
}
}
}
IOUtils.closeQuietly(stream);
return coreBundles;
}
static class MultiMap<K,V> {
HashMap<K,ArrayList<V>> delegate = new HashMap<>();
public List<V> get(Object key) {
return delegate.get(key);
}
public void put(K key, V value) {
ArrayList<V> list = delegate.get(key);
if( list == null ) {
list = new ArrayList<>();
delegate.put(key, list);
}
list.add(value);
}
}
/**
* Returns currently installed feature repositories. If patch is not installed, we should have the same state
* before&after.
* @return
*/
private HashMap<String, Repository> getAvailableFeatureRepositories() {
HashMap<String, Repository> before = new HashMap<String, Repository>();
if (featuresService != null) {
for (Repository repository : featuresService.listRepositories()) {
before.put(repository.getName(), repository);
}
}
return before;
}
@Override
public void rollback(final Patch patch, boolean force) throws PatchException {
final PatchResult result = patch.getResult();
if (result == null) {
throw new PatchException("Patch " + patch.getPatchData().getId() + " is not installed");
}
// current state of the framework
Bundle[] allBundles = bundleContext.getBundles();
// check if all the bundles that were updated in patch are available (installed)
List<BundleUpdate> badUpdates = new ArrayList<BundleUpdate>();
for (BundleUpdate update : result.getBundleUpdates()) {
boolean found = false;
Version v = Version.parseVersion(update.getNewVersion());
for (Bundle bundle : allBundles) {
if (stripSymbolicName(bundle.getSymbolicName()).equals(stripSymbolicName(update.getSymbolicName()))
&& bundle.getVersion().equals(v)) {
found = true;
break;
}
}
if (!found) {
badUpdates.add(update);
}
}
if (!badUpdates.isEmpty() && !force) {
StringBuilder sb = new StringBuilder();
sb.append("Unable to rollback patch ").append(patch.getPatchData().getId()).append(" because of the following missing bundles:\n");
for (BundleUpdate up : badUpdates) {
sb.append("\t").append(up.getSymbolicName()).append("/").append(up.getNewVersion()).append("\n");
}
throw new PatchException(sb.toString());
}
// bundle -> old location of the bundle to downgrade from
final Map<Bundle, String> toUpdate = new HashMap<Bundle, String>();
for (BundleUpdate update : result.getBundleUpdates()) {
Version v = Version.parseVersion(update.getNewVersion());
for (Bundle bundle : allBundles) {
if (stripSymbolicName(bundle.getSymbolicName()).equals(stripSymbolicName(update.getSymbolicName()))
&& bundle.getVersion().equals(v)) {
toUpdate.put(bundle, update.getPreviousLocation());
}
}
}
// restore startup.properties and overrides.properties
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
PatchManagement pm = patchManagement;
applyChanges(toUpdate);
pm.rollback(result);
} catch (Exception e) {
throw new PatchException("Unable to rollback patch " + patch.getPatchData().getId() + ": " + e.getMessage(), e);
}
((Patch) patch).setResult(null);
File file = new File(patchDir, result.getPatchData().getId() + ".patch.result");
file.delete();
}
});
}
/**
* Returns two element table: symbolic name and version
* @param url
* @return
* @throws IOException
*/
private String[] getBundleIdentity(String url) throws IOException {
JarInputStream jis = new JarInputStream(new URL(url).openStream());
jis.close();
Manifest manifest = jis.getManifest();
Attributes att = manifest != null ? manifest.getMainAttributes() : null;
String sn = att != null ? att.getValue(Constants.BUNDLE_SYMBOLICNAME) : null;
String vr = att != null ? att.getValue(Constants.BUNDLE_VERSION) : null;
if (sn == null || vr == null) {
return null;
}
return new String[] { sn, vr };
}
/**
* <p>Returns a {@link VersionRange} that existing bundle has to satisfy in order to be updated to
* <code>newVersion</code></p>
* <p>If we're upgrading to <code>1.2.3</code>, existing bundle has to be in range
* <code>[1.2.0,1.2.3)</code></p>
* @param patch
* @param url
* @param newVersion
* @return
*/
private VersionRange getUpdateableRange(Patch patch, String url, Version newVersion) {
VersionRange range = null;
if (patch.getPatchData().getVersionRange(url) == null) {
// default version range starts with x.y.0 as the lower bound
Version lower = new Version(newVersion.getMajor(), newVersion.getMinor(), 0);
// We can't really upgrade with versions such as 2.1.0
if (newVersion.compareTo(lower) > 0) {
range = new VersionRange(false, lower, newVersion, true);
}
} else {
range = new VersionRange(patch.getPatchData().getVersionRange(url));
}
return range;
}
private File getPatchStorage(Patch patch) {
return new File(patchDir, patch.getPatchData().getId());
}
private void applyChanges(Map<Bundle, String> toUpdate) throws BundleException, IOException {
List<Bundle> toStop = new ArrayList<Bundle>();
Map<Bundle, String> lessToUpdate = new HashMap<>();
for (Bundle b : toUpdate.keySet()) {
if (b.getState() != Bundle.UNINSTALLED) {
toStop.add(b);
lessToUpdate.put(b, toUpdate.get(b));
}
}
while (!toStop.isEmpty()) {
List<Bundle> bs = getBundlesToDestroy(toStop);
for (Bundle bundle : bs) {
String hostHeader = (String) bundle.getHeaders().get(Constants.FRAGMENT_HOST);
if (hostHeader == null && (bundle.getState() == Bundle.ACTIVE || bundle.getState() == Bundle.STARTING)) {
if (!"org.ops4j.pax.url.mvn".equals(bundle.getSymbolicName())) {
bundle.stop();
}
}
toStop.remove(bundle);
}
}
Set<Bundle> toRefresh = new HashSet<Bundle>();
Set<Bundle> toStart = new HashSet<Bundle>();
for (Map.Entry<Bundle, String> e : lessToUpdate.entrySet()) {
Bundle bundle = e.getKey();
if (!"org.ops4j.pax.url.mvn".equals(bundle.getSymbolicName())) {
System.out.println("updating: " + bundle.getSymbolicName());
try {
BundleUtils.update(bundle, new URL(e.getValue()));
} catch (BundleException ex) {
System.err.println("Failed to update: " + bundle.getSymbolicName()+", due to: "+e);
}
toStart.add(bundle);
}
toRefresh.add(bundle);
}
findBundlesWithOptionalPackagesToRefresh(toRefresh);
findBundlesWithFragmentsToRefresh(toRefresh);
if (!toRefresh.isEmpty()) {
final CountDownLatch l = new CountDownLatch(1);
FrameworkListener listener = new FrameworkListener() {
@Override
public void frameworkEvent(FrameworkEvent event) {
l.countDown();
}
};
FrameworkWiring wiring = (FrameworkWiring) bundleContext.getBundle(0).adapt(FrameworkWiring.class);
wiring.refreshBundles((Collection<Bundle>) toRefresh, listener);
try {
l.await();
} catch (InterruptedException e) {
throw new PatchException("Bundle refresh interrupted", e);
}
}
for (Bundle bundle : toStart) {
String hostHeader = (String) bundle.getHeaders().get(Constants.FRAGMENT_HOST);
if (hostHeader == null) {
try {
bundle.start();
} catch (BundleException e) {
System.err.println("Failed to start: " + bundle.getSymbolicName()+", due to: "+e);
}
}
}
}
private List<Bundle> getBundlesToDestroy(List<Bundle> bundles) {
List<Bundle> bundlesToDestroy = new ArrayList<Bundle>();
for (Bundle bundle : bundles) {
ServiceReference[] references = bundle.getRegisteredServices();
int usage = 0;
if (references != null) {
for (ServiceReference reference : references) {
usage += getServiceUsage(reference, bundles);
}
}
if (usage == 0) {
bundlesToDestroy.add(bundle);
}
}
if (!bundlesToDestroy.isEmpty()) {
Collections.sort(bundlesToDestroy, new Comparator<Bundle>() {
public int compare(Bundle b1, Bundle b2) {
return (int) (b2.getLastModified() - b1.getLastModified());
}
});
} else {
ServiceReference ref = null;
for (Bundle bundle : bundles) {
ServiceReference[] references = bundle.getRegisteredServices();
for (ServiceReference reference : references) {
if (getServiceUsage(reference, bundles) == 0) {
continue;
}
if (ref == null || reference.compareTo(ref) < 0) {
ref = reference;
}
}
}
if (ref != null) {
bundlesToDestroy.add(ref.getBundle());
}
}
return bundlesToDestroy;
}
private static int getServiceUsage(ServiceReference ref, List<Bundle> bundles) {
Bundle[] usingBundles = ref.getUsingBundles();
int nb = 0;
if (usingBundles != null) {
for (Bundle bundle : usingBundles) {
if (bundles.contains(bundle)) {
nb++;
}
}
}
return nb;
}
protected void findBundlesWithFragmentsToRefresh(Set<Bundle> toRefresh) {
for (Bundle b : toRefresh) {
if (b.getState() != Bundle.UNINSTALLED) {
String hostHeader = (String) b.getHeaders().get(Constants.FRAGMENT_HOST);
if (hostHeader != null) {
Clause[] clauses = Parser.parseHeader(hostHeader);
if (clauses != null && clauses.length > 0) {
Clause path = clauses[0];
for (Bundle hostBundle : bundleContext.getBundles()) {
if (hostBundle.getSymbolicName().equals(path.getName())) {
String ver = path.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE);
if (ver != null) {
VersionRange v = VersionRange.parseVersionRange(ver);
if (v.contains(hostBundle.getVersion())) {
toRefresh.add(hostBundle);
}
} else {
toRefresh.add(hostBundle);
}
}
}
}
}
}
}
}
protected void findBundlesWithOptionalPackagesToRefresh(Set<Bundle> toRefresh) {
// First pass: include all bundles contained in these features
Set<Bundle> bundles = new HashSet<Bundle>(Arrays.asList(bundleContext.getBundles()));
bundles.removeAll(toRefresh);
if (bundles.isEmpty()) {
return;
}
// Second pass: for each bundle, check if there is any unresolved optional package that could be resolved
Map<Bundle, List<Clause>> imports = new HashMap<Bundle, List<Clause>>();
for (Iterator<Bundle> it = bundles.iterator(); it.hasNext();) {
Bundle b = it.next();
String importsStr = (String) b.getHeaders().get(Constants.IMPORT_PACKAGE);
List<Clause> importsList = getOptionalImports(importsStr);
if (importsList.isEmpty()) {
it.remove();
} else {
imports.put(b, importsList);
}
}
if (bundles.isEmpty()) {
return;
}
// Third pass: compute a list of packages that are exported by our bundles and see if
// some exported packages can be wired to the optional imports
List<Clause> exports = new ArrayList<Clause>();
for (Bundle b : toRefresh) {
if (b.getState() != Bundle.UNINSTALLED) {
String exportsStr = (String) b.getHeaders().get(Constants.EXPORT_PACKAGE);
if (exportsStr != null) {
Clause[] exportsList = Parser.parseHeader(exportsStr);
exports.addAll(Arrays.asList(exportsList));
}
}
}
for (Iterator<Bundle> it = bundles.iterator(); it.hasNext();) {
Bundle b = it.next();
List<Clause> importsList = imports.get(b);
for (Iterator<Clause> itpi = importsList.iterator(); itpi.hasNext();) {
Clause pi = itpi.next();
boolean matching = false;
for (Clause pe : exports) {
if (pi.getName().equals(pe.getName())) {
String evStr = pe.getAttribute(Constants.VERSION_ATTRIBUTE);
String ivStr = pi.getAttribute(Constants.VERSION_ATTRIBUTE);
Version exported = evStr != null ? Version.parseVersion(evStr) : Version.emptyVersion;
VersionRange imported = ivStr != null ? VersionRange.parseVersionRange(ivStr) : VersionRange.ANY_VERSION;
if (imported.contains(exported)) {
matching = true;
break;
}
}
}
if (!matching) {
itpi.remove();
}
}
if (importsList.isEmpty()) {
it.remove();
}
}
toRefresh.addAll(bundles);
}
protected List<Clause> getOptionalImports(String importsStr) {
Clause[] imports = Parser.parseHeader(importsStr);
List<Clause> result = new LinkedList<Clause>();
for (Clause anImport : imports) {
String resolution = anImport.getDirective(Constants.RESOLUTION_DIRECTIVE);
if (Constants.RESOLUTION_OPTIONAL.equals(resolution)) {
result.add(anImport);
}
}
return result;
}
/*
* Create a bundle version history based on the information in the .patch and .patch.result files
*/
protected BundleVersionHistory createBundleVersionHistory() {
return new BundleVersionHistory(load(true));
}
/**
* Check if the set of patches mixes P and R patches. We can install several {@link PatchKind#NON_ROLLUP}
* patches at once, but only one {@link PatchKind#ROLLUP} patch.
* @param patches
* @return kind of patches in the set
*/
private PatchKind checkConsistency(Collection<Patch> patches) throws PatchException {
boolean hasP = false, hasR = false;
for (Patch patch : patches) {
if (patch.getPatchData().isRollupPatch()) {
if (hasR) {
throw new PatchException("Can't install more than one rollup patch at once");
}
hasR = true;
} else {
hasP = true;
}
}
if (hasR && hasP) {
throw new PatchException("Can't install both rollup and non-rollup patches in single run");
}
return hasR ? PatchKind.ROLLUP : PatchKind.NON_ROLLUP;
}
/**
* Check if the requirements for all specified patches have been installed
* @param patches the set of patches to check
* @throws PatchException if at least one of the patches has missing requirements
*/
protected void checkPrerequisites(Collection<Patch> patches) throws PatchException {
for (Patch patch : patches) {
checkPrerequisites(patch);
}
}
/**
* Check if the requirements for the specified patch have been installed
* @param patch the patch to check
* @throws PatchException if the requirements for the patch are missing or not yet installed
*/
protected void checkPrerequisites(Patch patch) throws PatchException {
for (String requirement : patch.getPatchData().getRequirements()) {
Patch required = getPatch(requirement);
if (required == null) {
throw new PatchException(String.format("Required patch '%s' is missing", requirement));
}
if (!required.isInstalled()) {
throw new PatchException(String.format("Required patch '%s' is not installed", requirement));
}
}
}
/**
* Contains the history of bundle versions that have been applied through the patching mechanism
*/
protected static final class BundleVersionHistory {
// symbolic name -> version -> location
private Map<String, Map<String, String>> bundleVersions = new HashMap<String, Map<String, String>>();
public BundleVersionHistory(Map<String, Patch> patches) {
for (Map.Entry<String, Patch> patch : patches.entrySet()) {
PatchResult result = patch.getValue().getResult();
if (result != null) {
for (BundleUpdate update : result.getBundleUpdates()) {
String symbolicName = stripSymbolicName(update.getSymbolicName());
Map<String, String> versions = bundleVersions.get(symbolicName);
if (versions == null) {
versions = new HashMap<String, String>();
bundleVersions.put(symbolicName, versions);
}
versions.put(update.getNewVersion(), update.getNewLocation());
}
}
}
}
/**
* Get the bundle location for a given bundle version. If this bundle version was not installed through a patch,
* this methods will return the original bundle location.
*
* @param bundle the bundle
* @return the location for this bundle version
*/
protected String getLocation(Bundle bundle) {
String symbolicName = stripSymbolicName(bundle.getSymbolicName());
Map<String, String> versions = bundleVersions.get(symbolicName);
String location = null;
if (versions != null) {
location = versions.get(bundle.getVersion().toString());
}
if (location == null) {
location = bundle.getLocation();
}
return location;
}
}
}
|
patch/patch-core/src/main/java/io/fabric8/patch/impl/ServiceImpl.java
|
/**
* Copyright 2005-2015 Red Hat, Inc.
*
* Red Hat 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.fabric8.patch.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import io.fabric8.patch.Service;
import io.fabric8.patch.management.Artifact;
import io.fabric8.patch.management.BundleUpdate;
import io.fabric8.patch.management.FeatureUpdate;
import io.fabric8.patch.management.Patch;
import io.fabric8.patch.management.PatchData;
import io.fabric8.patch.management.PatchDetailsRequest;
import io.fabric8.patch.management.PatchException;
import io.fabric8.patch.management.PatchKind;
import io.fabric8.patch.management.PatchManagement;
import io.fabric8.patch.management.PatchResult;
import io.fabric8.patch.management.Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.utils.manifest.Clause;
import org.apache.felix.utils.manifest.Parser;
import org.apache.felix.utils.version.VersionRange;
import org.apache.felix.utils.version.VersionTable;
import org.apache.karaf.features.Feature;
import org.apache.karaf.features.FeaturesService;
import org.apache.karaf.features.Repository;
import org.apache.karaf.util.bundles.BundleUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.osgi.framework.wiring.FrameworkWiring;
import org.osgi.service.component.ComponentContext;
import org.osgi.util.tracker.ServiceTracker;
import static io.fabric8.patch.management.Utils.mvnurlToArtifact;
import static io.fabric8.patch.management.Utils.stripSymbolicName;
@Component(immediate = true, metatype = false)
@org.apache.felix.scr.annotations.Service(Service.class)
public class ServiceImpl implements Service {
private static final String ID = "id";
private static final String DESCRIPTION = "description";
private static final String DATE = "date";
private static final String BUNDLES = "bundle";
private static final String UPDATES = "update";
private static final String COUNT = "count";
private static final String RANGE = "range";
private static final String SYMBOLIC_NAME = "symbolic-name";
private static final String NEW_VERSION = "new-version";
private static final String NEW_LOCATION = "new-location";
private static final String OLD_VERSION = "old-version";
private static final String OLD_LOCATION = "old-location";
private static final String STARTUP = "startup";
private static final String OVERRIDES = "overrides";
private BundleContext bundleContext;
private File patchDir;
@Reference(referenceInterface = PatchManagement.class, cardinality = ReferenceCardinality.MANDATORY_UNARY, policy = ReferencePolicy.STATIC)
private PatchManagement patchManagement;
@Reference(referenceInterface = FeaturesService.class, cardinality = ReferenceCardinality.MANDATORY_UNARY, policy = ReferencePolicy.STATIC)
private FeaturesService featuresService;
private File karafHome;
// by default it's ${karaf.home}/system
private File repository;
@Activate
void activate(ComponentContext componentContext) {
// Use system bundle' bundle context to avoid running into
// "Invalid BundleContext" exceptions when updating bundles
this.bundleContext = componentContext.getBundleContext().getBundle(0).getBundleContext();
String dir = this.bundleContext.getProperty(NEW_PATCH_LOCATION);
if (dir != null) {
patchDir = new File(dir);
} else {
dir = this.bundleContext.getProperty(PATCH_LOCATION);
if (dir != null) {
patchDir = new File(dir);
} else {
// only now fallback to datafile of system bundle
patchDir = this.bundleContext.getDataFile("patches");
}
}
if (!patchDir.isDirectory()) {
patchDir.mkdirs();
if (!patchDir.isDirectory()) {
throw new PatchException("Unable to create patch folder");
}
}
this.karafHome = new File(bundleContext.getProperty("karaf.home"));
this.repository = new File(bundleContext.getProperty("karaf.default.repository"));
load(true);
}
@Override
public Iterable<Patch> getPatches() {
return Collections.unmodifiableCollection(load(true).values());
}
@Override
public Patch getPatch(String id) {
return patchManagement.loadPatch(new PatchDetailsRequest(id));
}
@Override
public Iterable<Patch> download(URL url) {
try {
List<PatchData> patchesData = patchManagement.fetchPatches(url);
List<Patch> patches = new ArrayList<>(patchesData.size());
for (PatchData patchData : patchesData) {
Patch patch = patchManagement.trackPatch(patchData);
patches.add(patch);
}
return patches;
} catch (Exception e) {
throw new PatchException("Unable to download patch from url " + url, e);
}
}
/**
* Loads available patches without caching
* @param details whether to load {@link io.fabric8.patch.management.ManagedPatch} details too
* @return
*/
private Map<String, Patch> load(boolean details) {
List<Patch> patchesList = patchManagement.listPatches(details);
Map<String, Patch> patches = new HashMap<String, Patch>();
for (Patch patch : patchesList) {
patches.put(patch.getPatchData().getId(), patch);
}
return patches;
}
/**
* Used by the patch client when executing the script in the console
* @param ids
*/
public void cliInstall(String[] ids) {
final List<Patch> patches = new ArrayList<Patch>();
for (String id : ids) {
Patch patch = getPatch(id);
if (patch == null) {
throw new IllegalArgumentException("Unknown patch: " + id);
}
patches.add(patch);
}
install(patches, false, false);
}
@Override
public PatchResult install(Patch patch, boolean simulate) {
return install(patch, simulate, true);
}
@Override
public PatchResult install(Patch patch, boolean simulate, boolean synchronous) {
Map<String, PatchResult> results = install(Collections.singleton(patch), simulate, synchronous);
return results.get(patch.getPatchData().getId());
}
/**
* <p>Main installation method. Installing a patch in non-fabric mode is a matter of correct merge (cherry-pick, merge,
* rebase) of patch branch into <code>master</code> branch.</p>
* <p>Instaling a patch has three goals:<ul>
* <li>update static files/libs in KARAF_HOME</li>
* <li>update (uninstall+install) features</li>
* <li>update remaining bundles (not yet updated during feature update)</li>
* </ul></p>
* @param patches
* @param simulate
* @param synchronous
* @return
*/
private Map<String, PatchResult> install(final Collection<Patch> patches, final boolean simulate, boolean synchronous) {
PatchKind kind = checkConsistency(patches);
checkPrerequisites(patches);
String transaction = null;
// poor-man's lifecycle management in case when SCR nullifies our reference
final PatchManagement pm = patchManagement;
try {
// Compute individual patch results (patchId -> Result)
final Map<String, PatchResult> results = new LinkedHashMap<String, PatchResult>();
// current state of the framework
Bundle[] allBundles = bundleContext.getBundles();
Map<String, Repository> allFeatureRepositories = getAvailableFeatureRepositories();
// bundle -> url to update the bundle from
final Map<Bundle, String> bundleUpdateLocations = new HashMap<>();
// [feature name|updateable-version] -> url of repository to get it from
final Map<String, String> featureUpdateRepositories = new HashMap<>();
// feature name -> url of repository to get it from - in case we have only one feature with that name
// like "transaction" in karaf-enterprise features
final Map<String, String> singleFeatureUpdateRepositories = new HashMap<>();
/* A "key" is name + "update'able version". Such version is current version with micro version == 0 */
// [symbolic name|updateable-version] -> newest update for the bundle out of all installed patches
Map<String, BundleUpdate> updatesForBundleKeys = new HashMap<>();
// [feature name|updateable-version] -> newest update for the feature out of all installed patches
final Map<String, FeatureUpdate> updatesForFeatureKeys = new HashMap<>();
// symbolic name -> version -> location
final BundleVersionHistory history = createBundleVersionHistory();
// beginning installation transaction = creating of temporary branch in git
transaction = this.patchManagement.beginInstallation(kind);
// bundles from etc/startup.properties + felix.framework = all bundles not managed by features
// these bundles will be treated in special way
// symbolic name -> Bundle
final Map<String, Bundle> coreBundles = getCoreBundles(allBundles);
// collect runtime information from patches (features, bundles) and static information (files)
// runtime info is prepared to apply runtime changes and static info is prepared to update KARAF_HOME files
for (Patch patch : patches) {
// list of bundle updates for the current patch - only for the purpose of storing result
List<BundleUpdate> bundleUpdatesInThisPatch = bundleUpdatesInPatch(patch, allBundles,
bundleUpdateLocations, history, updatesForBundleKeys, kind, coreBundles);
// list of feature updates for the current patch - only for the purpose of storing result
List<FeatureUpdate> featureUpdatesInThisPatch = featureUpdatesInPatch(patch, allFeatureRepositories,
featureUpdateRepositories, singleFeatureUpdateRepositories, updatesForFeatureKeys, kind);
// each patch may change files, we're not updating the main files yet - it'll be done when
// install transaction is committed
patchManagement.install(transaction, patch);
// each patch may ship a migrator
installMigratorBundle(patch);
// prepare patch result before doing runtime changes
PatchResult result = new PatchResult(patch.getPatchData(), simulate, System.currentTimeMillis(),
bundleUpdatesInThisPatch, featureUpdatesInThisPatch);
results.put(patch.getPatchData().getId(), result);
}
// We don't have to update bundles that are uninstalled anyway when uninstalling features we
// are updating. Updating a feature = uninstall + install
// When feature is uninstalled, its bundles may get uninstalled too, if they are not referenced
// from any other feature, including special (we're implementation aware!) "startup" feature
// that is created during initailization of FeaturesService. As expected, this feature contains
// all bundles started by other means which is:
// - felix.framework (system bundle)
// - all bundles referenced in etc/startup.properties
// Some special cases
for (Map.Entry<Bundle, String> entry : bundleUpdateLocations.entrySet()) {
Bundle bundle = entry.getKey();
if ("org.ops4j.pax.url.mvn".equals(stripSymbolicName(bundle.getSymbolicName()))) {
// handle this bundle specially - update it here
URL location = new URL(entry.getValue());
System.out.printf("Special update of bundle \"%s\" from \"%s\"%n",
bundle.getSymbolicName(), location);
if (!simulate) {
BundleUtils.update(bundle, location);
bundle.start();
}
// replace location - to be stored in result
bundleUpdateLocations.put(bundle, location.toString());
}
}
displayFeatureUpdates(updatesForFeatureKeys, simulate);
// effectively, we will update all the bundles from this list - even if some bundles will be "updated"
// as part of feature installation
displayBundleUpdates(bundleUpdateLocations, simulate);
Runnable task = null;
if (!simulate) {
final String finalTransaction = transaction;
task = new Runnable() {
@Override
public void run() {
try {
// collect features to uninstall
List<String[]> featuresToUninstallAfterUpdatingBundles = new LinkedList<>();
// uninstall old features and repositories repositories
if (!simulate && updatesForFeatureKeys.size() > 0) {
Set<String> oldRepositories = new HashSet<>();
Set<String> newRepositories = new HashSet<>();
for (FeatureUpdate fu : updatesForFeatureKeys.values()) {
oldRepositories.add(fu.getPreviousRepository());
newRepositories.add(fu.getNewRepository());
}
Map<String, Repository> repos = new HashMap<>();
for (Repository r : featuresService.listRepositories()) {
repos.put(r.getURI().toString(), r);
}
for (String uri : oldRepositories) {
if (repos.containsKey(uri)) {
Repository r = repos.get(uri);
for (Feature f : r.getFeatures()) {
if (featuresService.isInstalled(f)) {
featuresToUninstallAfterUpdatingBundles.add(new String[] {
f.getName(),
f.getVersion()
});
// fs.uninstallFeature(f.getName(), f.getVersion(), EnumSet.of(FeaturesService.Option.NoAutoRefreshBundles));
}
}
}
}
// we can already remove repositories
for (String uri : oldRepositories) {
featuresService.removeRepository(URI.create(uri));
}
// TODO: we should add not only repositories related to updated features, but also all from
// "featureRepositories" property from new etc/org.apache.karaf.features.cfg
for (Patch p : patches) {
for (String uri : p.getPatchData().getFeatureFiles()) {
featuresService.addRepository(URI.create(uri));
}
}
}
// update bundles
applyChanges(bundleUpdateLocations);
if (updatesForFeatureKeys.size() > 0) {
Object featuresService = null;
try {
ServiceTracker<?, ?> tracker = new ServiceTracker<>(bundleContext, "org.apache.karaf.features.FeaturesService", null);
tracker.open();
Object service = tracker.waitForService(30000);
if (service != null) {
featuresService = service;
}
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace(System.err);
System.err.flush();
}
}
// update KARAF_HOME
if (!simulate) {
pm.commitInstallation(finalTransaction);
} else {
patchManagement.rollbackInstallation(finalTransaction);
}
// TODO: uninstall features?
// install new features - in order
if (updatesForFeatureKeys.size() > 0) {
Properties properties = new Properties();
FileInputStream inStream = new FileInputStream(new File(karafHome, "etc/org.apache.karaf.features.cfg"));
properties.load(inStream);
IOUtils.closeQuietly(inStream);
String featuresBoot = properties.getProperty("featuresBoot");
Set<String> coreFeatures = new LinkedHashSet<>(Arrays.asList(featuresBoot.split(", *")));
// Now that we don't have any of the old feature repos installed
// Lets re-install the features that were previously installed.
try {
ServiceTracker<FeaturesService, FeaturesService> tracker = new ServiceTracker<>(bundleContext, FeaturesService.class, null);
tracker.open();
Object service = tracker.waitForService(30000);
if (service != null) {
Method m = service.getClass().getDeclaredMethod("installFeature", String.class );
if (m != null) {
for (String cf : coreFeatures) {
if (simulate) {
System.out.println("Simulation: Enable core feature: " + cf);
} else {
System.out.println("Enable core feature: " + cf);
m.invoke(service, cf);
}
}
}
m = service.getClass().getDeclaredMethod("installFeature", String.class, String.class );
if (m != null) {
for (FeatureUpdate update : updatesForFeatureKeys.values()) {
if (coreFeatures.contains(update.getName())) {
continue;
}
if (simulate) {
System.out.println("Simulation: Enable feature: " + update.getName() + "/" + update.getNewVersion());
} else {
System.out.println("Enable feature: " + update.getName() + "/" + update.getNewVersion());
m.invoke(service, update.getName(), update.getNewVersion());
}
}
}
} else {
System.err.println("Can't get OSGi reference to FeaturesService");
}
} catch (Exception e) {
e.printStackTrace();
System.err.flush();
}
}
// persist results of all installed patches
for (Patch patch : patches) {
PatchResult result = results.get(patch.getPatchData().getId());
patch.setResult(result);
result.store();
}
} catch (Exception e) {
e.printStackTrace(System.err);
System.err.flush();
}
}
};
}
// Bundle fileinstal = null;
// Bundle configadmin = null;
// if (!simulate) {
// // let's stop fileinstall and configadmin
// for (Bundle b : allBundles) {
// if ("org.apache.felix.fileinstall".equals(b.getSymbolicName())) {
// fileinstal = b;
// } else if ("org.apache.felix.configadmin".equals(b.getSymbolicName())) {
// configadmin = b;
// }
// }
// if (fileinstal != null) {
// fileinstal.stop(Bundle.STOP_TRANSIENT);
// }
// if (configadmin != null) {
// configadmin.stop(Bundle.STOP_TRANSIENT);
// }
// }
// update bundles (special case: pax-url-aether) and install features
if (!simulate) {
if (synchronous) {
task.run();
} else {
new Thread(task).start();
}
}
// if (!simulate) {
// if (configadmin != null) {
// configadmin.start(Bundle.START_TRANSIENT);
// }
// if (fileinstal != null) {
// fileinstal.start(Bundle.START_TRANSIENT);
// }
// }
return results;
} catch (Exception e) {
if (transaction != null) {
pm.rollbackInstallation(transaction);
}
throw new PatchException(e.getMessage(), e);
}
}
private void displayFeatureUpdates(Map<String, FeatureUpdate> featureUpdates, boolean simulate) {
Set<String> toRemove = new TreeSet<>();
Set<String> toAdd = new TreeSet<>();
for (FeatureUpdate fu : featureUpdates.values()) {
toRemove.add(fu.getPreviousRepository());
toAdd.add(fu.getNewRepository());
}
System.out.println("Repositories to remove:");
for (String repo : toRemove) {
System.out.println(" - " + repo);
}
System.out.println("Repositories to add:");
for (String repo : toAdd) {
System.out.println(" - " + repo);
}
System.out.println("Features to update:");
int l1 = "[name]".length();
int l2 = "[version]".length();
int l3 = "[new version]".length();
for (FeatureUpdate fu : featureUpdates.values()) {
if (fu.getName().length() > l1) {
l1 = fu.getName().length();
}
if (fu.getPreviousVersion().length() > l2) {
l2 = fu.getPreviousVersion().length();
}
if (fu.getNewVersion().length() > l3) {
l3 = fu.getNewVersion().length();
}
}
System.out.printf("%-" + l1 + "s %-" + l2 + "s %-" + l3 + "s%n",
"[name]", "[version]", "[new version]");
for (FeatureUpdate fu : featureUpdates.values()) {
System.out.printf("%-" + l1 + "s %-" + l2 + "s %-" + l3 + "s%n",
fu.getName(), fu.getPreviousVersion(), fu.getNewVersion());
}
if (simulate) {
System.out.println("Running simulation only - no features are being updated at this time");
} else {
System.out.println("Installation of features will begin.");
}
System.out.flush();
}
private void displayBundleUpdates(Map<Bundle, String> bundleUpdateLocations, boolean simulate) {
System.out.println("Bundles to update:");
int l1 = "[symbolic name]".length();
int l2 = "[version]".length();
int l3 = "[new location]".length();
for (Map.Entry<Bundle, String> e : bundleUpdateLocations.entrySet()) {
String sn = stripSymbolicName(e.getKey().getSymbolicName());
if (sn.length() > l1) {
l1 = sn.length();
}
String version = e.getKey().getVersion().toString();
if (version.length() > l2) {
l2 = version.length();
}
String newLocation = e.getValue();
if (newLocation.length() > l3) {
l3 = newLocation.length();
}
}
System.out.printf("%-" + l1 + "s %-" + l2 + "s %-" + l3 + "s%n",
"[symbolic name]", "[version]", "[new location]");
for (Map.Entry<Bundle, String> e : bundleUpdateLocations.entrySet()) {
System.out.printf("%-" + l1 + "s %-" + l2 + "s %-" + l3 + "s%n",
stripSymbolicName(e.getKey().getSymbolicName()),
e.getKey().getVersion().toString(), e.getValue());
}
if (simulate) {
System.out.println("Running simulation only - no bundles are being updated at this time");
} else {
System.out.println("Installation will begin. The connection may be lost or the console restarted.");
}
System.out.flush();
}
/**
* Returns a list of {@link BundleUpdate} for single patch, taking into account already discovered updates
* @param patch
* @param allBundles
* @param bundleUpdateLocations out parameter that gathers update locations for bundles across patches
* @param history
* @param updatesForBundleKeys
* @param kind
* @param coreBundles
* @return
* @throws IOException
*/
private List<BundleUpdate> bundleUpdatesInPatch(Patch patch,
Bundle[] allBundles,
Map<Bundle, String> bundleUpdateLocations,
BundleVersionHistory history,
Map<String, BundleUpdate> updatesForBundleKeys,
PatchKind kind,
Map<String, Bundle> coreBundles) throws IOException {
List<BundleUpdate> updatesInThisPatch = new LinkedList<>();
for (String newLocation : patch.getPatchData().getBundles()) {
// [symbolicName, version] of the new bundle
String[] symbolicNameVersion = getBundleIdentity(newLocation);
if (symbolicNameVersion == null) {
continue;
}
String sn = symbolicNameVersion[0];
String vr = symbolicNameVersion[1];
Version newVersion = VersionTable.getVersion(vr);
// if existing bundle is withing this range, update is possible
VersionRange range = getUpdateableRange(patch, newLocation, newVersion);
if (coreBundles.containsKey(sn)) {
if (range == null) {
range = new VersionRange(false, Version.emptyVersion, newVersion, true);
} else {
range = new VersionRange(false, Version.emptyVersion, range.getCeiling(), true);
}
}
if (range != null) {
for (Bundle bundle : allBundles) {
if (bundle.getBundleId() == 0L) {
continue;
}
if (!stripSymbolicName(sn).equals(stripSymbolicName(bundle.getSymbolicName()))) {
continue;
}
Version oldVersion = bundle.getVersion();
if (range.contains(oldVersion)) {
String oldLocation = history.getLocation(bundle);
if ("org.ops4j.pax.url.mvn".equals(stripSymbolicName(sn))) {
Artifact artifact = Utils.mvnurlToArtifact(newLocation, true);
URL location = new File(repository,
String.format("org/ops4j/pax/url/pax-url-aether/%s/pax-url-aether-%s.jar",
artifact.getVersion(), artifact.getVersion())).toURI().toURL();
newLocation = location.toString();
}
BundleUpdate update = new BundleUpdate(sn, newVersion.toString(), newLocation,
oldVersion.toString(), oldLocation);
updatesInThisPatch.add(update);
// Merge result
String key = String.format("%s|%s", sn, range.getFloor());
BundleUpdate oldUpdate = updatesForBundleKeys.get(key);
if (oldUpdate != null) {
Version upv = VersionTable.getVersion(oldUpdate.getNewVersion());
if (upv.compareTo(newVersion) < 0) {
// other patch contains newer update for a bundle
updatesForBundleKeys.put(key, update);
bundleUpdateLocations.put(bundle, newLocation);
}
} else {
// this is the first update of the bundle
updatesForBundleKeys.put(key, update);
bundleUpdateLocations.put(bundle, newLocation);
}
}
}
} else {
if (kind == PatchKind.ROLLUP) {
// we simply do not touch the bundle from patch - it is installed in KARAF_HOME/system
// and available to be installed when new features are detected
} else {
// for non-rollup patches however, we signal an error - all bundles from P patch
// should be used to update already installed bundles
System.err.printf("Skipping bundle %s - unable to process bundle without a version range configuration%n", newLocation);
}
}
}
return updatesInThisPatch;
}
/**
* Returns a list of {@link FeatureUpdate} for single patch, taking into account already discovered updates
* @param patch
* @param allFeatureRepositories
* @param featureUpdateRepositories
* @param singleFeatureUpdateRepositories
* @param updatesForFeatureKeys
* @param kind @return
*/
private List<FeatureUpdate> featureUpdatesInPatch(Patch patch,
Map<String, Repository> allFeatureRepositories,
Map<String, String> featureUpdateRepositories,
Map<String, String> singleFeatureUpdateRepositories,
Map<String, FeatureUpdate> updatesForFeatureKeys,
PatchKind kind) throws Exception {
Set<String> addedRepositoryNames = new HashSet<>();
HashMap<String, Repository> after = null;
try {
List<FeatureUpdate> updatesInThisPatch = new LinkedList<>();
/*
* Two pairs of features makes feature names not enough to be a key:
* <feature name="openjpa" description="Apache OpenJPA 2.2.x persistent engine support" version="2.2.2" resolver="(obr)">
* <feature name="openjpa" description="Apache OpenJPA 2.3.x persistence engine support" version="2.3.0" resolver="(obr)">
* and
* <feature name="activemq-camel" version="5.11.0.redhat-621039" resolver="(obr)" start-level="50">
* <feature name="activemq-camel" version="1.2.0.redhat-621039" resolver="(obr)">
*/
// install the new feature repos, tracking the set the were
// installed before and after
// (e.g, "karaf-enterprise-2.4.0.redhat-620133" -> Repository)
Map<String, Repository> before = new HashMap<>(allFeatureRepositories);
for (String url : patch.getPatchData().getFeatureFiles()) {
featuresService.addRepository(new URI(url));
}
after = getAvailableFeatureRepositories();
// track which old repos provide which features to find out if we have new repositories for those features
// key is name|version (don't expect '|' to be part of name...)
// assume that [feature-name, feature-version{major,minor,0,0}] is defined only in single repository
Map<String, String> featuresInOldRepositories = new HashMap<>();
// key is only name, without version - used when there's single feature in old and in new repositories
MultiMap<String, String> singleFeaturesInOldRepositories = new MultiMap<>();
Map<String, Version> actualOldFeatureVersions = new HashMap<>();
for (Repository repository : before.values()) {
for (Feature feature : repository.getFeatures()) {
Version v = Utils.getFeatureVersion(feature.getVersion());
Version lowestUpdateableVersion = new Version(v.getMajor(), v.getMinor(), 0);
// assume that we can update feature XXX-2.2.3 to XXX-2.2.142, but not to XXX-2.3.0.alpha-1
String key = String.format("%s|%s", feature.getName(), lowestUpdateableVersion.toString());
featuresInOldRepositories.put(key, repository.getName());
singleFeaturesInOldRepositories.put(feature.getName(), repository.getName());
actualOldFeatureVersions.put(key, v);
}
}
// Use the before and after set to figure out which repos were added.
addedRepositoryNames = new HashSet<>(after.keySet());
addedRepositoryNames.removeAll(before.keySet());
// track the new repositories where we can find old features
Map<String, String> featuresInNewRepositories = new HashMap<>();
MultiMap<String, String> singleFeaturesInNewRepositories = new MultiMap<>();
Map<String, String> actualNewFeatureVersions = new HashMap<>();
MultiMap<String, String> singleActualNewFeatureVersions = new MultiMap<>();
// Figure out which old repos were updated: Do they have feature
// with the same name as one contained in a repo being added?
// and do they have update'able version? (just like with bundles)
HashSet<String> oldRepositoryNames = new HashSet<String>();
for (String addedRepositoryName : addedRepositoryNames) {
Repository added = after.get(addedRepositoryName);
for (Feature feature : added.getFeatures()) {
Version v = Utils.getFeatureVersion(feature.getVersion());
Version lowestUpdateableVersion = new Version(v.getMajor(), v.getMinor(), 0);
String key = String.format("%s|%s", feature.getName(), lowestUpdateableVersion.toString());
featuresInNewRepositories.put(key, addedRepositoryName);
singleFeaturesInNewRepositories.put(feature.getName(), addedRepositoryName);
actualNewFeatureVersions.put(key, v.toString());
singleActualNewFeatureVersions.put(feature.getName(), v.toString());
String oldRepositoryWithUpdateableFeature = featuresInOldRepositories.get(key);
if (oldRepositoryWithUpdateableFeature == null
&& singleFeaturesInOldRepositories.get(feature.getName()) != null) {
oldRepositoryWithUpdateableFeature = singleFeaturesInOldRepositories.get(feature.getName()).get(0);
}
if (oldRepositoryWithUpdateableFeature != null) {
oldRepositoryNames.add(oldRepositoryWithUpdateableFeature);
}
}
}
// Now we know which are the old repos that have been udpated.
// again assume that we can find ALL of the features from this old repository in a new repository
// We need to uninstall them. Before we uninstall, track which features were installed.
for (String oldRepositoryName : oldRepositoryNames) {
Repository repository = before.get(oldRepositoryName);
for (Feature feature : repository.getFeatures()) {
if (featuresService.isInstalled(feature)) {
Version v = Utils.getFeatureVersion(feature.getVersion());
Version lowestUpdateableVersion = new Version(v.getMajor(), v.getMinor(), 0);
String key = String.format("%s|%s", feature.getName(), lowestUpdateableVersion.toString());
String newRepository = featuresInNewRepositories.get(key);
String newVersion = actualNewFeatureVersions.get(key);
if (newRepository == null) {
// try looking up the feature without version - e.g., like in updating "transaction"
// feature from 1.1.1 to 1.3.0
if (singleFeaturesInOldRepositories.get(feature.getName()) != null
&& singleFeaturesInOldRepositories.get(feature.getName()).size() == 1
&& singleFeaturesInNewRepositories.get(feature.getName()) != null
&& singleFeaturesInNewRepositories.get(feature.getName()).size() == 1) {
newRepository = singleFeaturesInNewRepositories.get(feature.getName()).get(0);
}
}
if (newVersion == null) {
if (singleActualNewFeatureVersions.get(feature.getName()) != null
&& singleActualNewFeatureVersions.get(feature.getName()).size() == 1) {
newVersion = singleActualNewFeatureVersions.get(feature.getName()).get(0);
}
}
FeatureUpdate featureUpdate = new FeatureUpdate(feature.getName(),
after.get(oldRepositoryName).getURI().toString(),
feature.getVersion(),
after.get(newRepository).getURI().toString(),
newVersion);
updatesInThisPatch.add(featureUpdate);
// Merge result
FeatureUpdate oldUpdate = updatesForFeatureKeys.get(key);
if (oldUpdate != null) {
Version upv = VersionTable.getVersion(oldUpdate.getNewVersion());
Version newV = VersionTable.getVersion(actualNewFeatureVersions.get(key));
if (upv.compareTo(newV) < 0) {
// other patch contains newer update for the feature
updatesForFeatureKeys.put(key, featureUpdate);
featureUpdateRepositories.put(key, featuresInNewRepositories.get(key));
}
} else {
// this is the first update of the bundle
updatesForFeatureKeys.put(key, featureUpdate);
featureUpdateRepositories.put(key, featuresInNewRepositories.get(key));
}
}
}
}
return updatesInThisPatch;
} catch (Exception e) {
throw new PatchException(e.getMessage(), e);
} finally {
// we'll add new feature repositories again. here we've added them only to track the updates
if (addedRepositoryNames != null && after != null) {
for (String repo : addedRepositoryNames) {
if (after.get(repo) != null) {
featuresService.removeRepository(after.get(repo).getURI(), false);
}
}
}
}
}
/**
* If patch contains migrator bundle, install it by dropping to <code>deploy</code> directory.
* @param patch
* @throws IOException
*/
private void installMigratorBundle(Patch patch) throws IOException {
if (patch.getPatchData().getMigratorBundle() != null) {
Artifact artifact = mvnurlToArtifact(patch.getPatchData().getMigratorBundle(), true);
if (artifact != null) {
// Copy it to the deploy dir
File src = new File(repository, artifact.getPath());
File target = new File(Utils.getDeployDir(karafHome), artifact.getArtifactId() + ".jar");
FileUtils.copyFile(src, target);
}
}
}
/**
* Returns a map of bundles (symbolic name -> Bundle) that were installed in <em>classic way</em> - i.e.,
* not using {@link FeaturesService}.
* User may have installed other bundles, drop some to <code>deploy/</code>, etc, but these probably
* are not handled by patch mechanism.
* @param allBundles
* @return
*/
private Map<String, Bundle> getCoreBundles(Bundle[] allBundles) throws IOException {
Map<String, Bundle> coreBundles = new HashMap<>();
Properties props = new Properties();
FileInputStream stream = new FileInputStream(new File(karafHome, "etc/startup.properties"));
props.load(stream);
Set<String> locations = new HashSet<>();
for (String startupBundle : props.stringPropertyNames()) {
locations.add(Utils.pathToMvnurl(startupBundle));
}
for (Bundle b : allBundles) {
String symbolicName = Utils.stripSymbolicName(b.getSymbolicName());
if ("org.apache.felix.framework".equals(symbolicName)) {
coreBundles.put(symbolicName, b);
} else if ("org.ops4j.pax.url.mvn".equals(symbolicName)) {
// we could check if it's in etc/startup.properties, but we're 100% sure :)
coreBundles.put(symbolicName, b);
} else {
// only if it's in etc/startup.properties
if (locations.contains(b.getLocation())) {
coreBundles.put(symbolicName, b);
}
}
}
IOUtils.closeQuietly(stream);
return coreBundles;
}
static class MultiMap<K,V> {
HashMap<K,ArrayList<V>> delegate = new HashMap<>();
public List<V> get(Object key) {
return delegate.get(key);
}
public void put(K key, V value) {
ArrayList<V> list = delegate.get(key);
if( list == null ) {
list = new ArrayList<>();
delegate.put(key, list);
}
list.add(value);
}
}
/**
* Returns currently installed feature repositories. If patch is not installed, we should have the same state
* before&after.
* @return
*/
private HashMap<String, Repository> getAvailableFeatureRepositories() {
HashMap<String, Repository> before = new HashMap<String, Repository>();
if (featuresService != null) {
for (Repository repository : featuresService.listRepositories()) {
before.put(repository.getName(), repository);
}
}
return before;
}
@Override
public void rollback(final Patch patch, boolean force) throws PatchException {
final PatchResult result = patch.getResult();
if (result == null) {
throw new PatchException("Patch " + patch.getPatchData().getId() + " is not installed");
}
// current state of the framework
Bundle[] allBundles = bundleContext.getBundles();
// check if all the bundles that were updated in patch are available (installed)
List<BundleUpdate> badUpdates = new ArrayList<BundleUpdate>();
for (BundleUpdate update : result.getBundleUpdates()) {
boolean found = false;
Version v = Version.parseVersion(update.getNewVersion());
for (Bundle bundle : allBundles) {
if (stripSymbolicName(bundle.getSymbolicName()).equals(stripSymbolicName(update.getSymbolicName()))
&& bundle.getVersion().equals(v)) {
found = true;
break;
}
}
if (!found) {
badUpdates.add(update);
}
}
if (!badUpdates.isEmpty() && !force) {
StringBuilder sb = new StringBuilder();
sb.append("Unable to rollback patch ").append(patch.getPatchData().getId()).append(" because of the following missing bundles:\n");
for (BundleUpdate up : badUpdates) {
sb.append("\t").append(up.getSymbolicName()).append("/").append(up.getNewVersion()).append("\n");
}
throw new PatchException(sb.toString());
}
// bundle -> old location of the bundle to downgrade from
final Map<Bundle, String> toUpdate = new HashMap<Bundle, String>();
for (BundleUpdate update : result.getBundleUpdates()) {
Version v = Version.parseVersion(update.getNewVersion());
for (Bundle bundle : allBundles) {
if (stripSymbolicName(bundle.getSymbolicName()).equals(stripSymbolicName(update.getSymbolicName()))
&& bundle.getVersion().equals(v)) {
toUpdate.put(bundle, update.getPreviousLocation());
}
}
}
// restore startup.properties and overrides.properties
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
try {
PatchManagement pm = patchManagement;
applyChanges(toUpdate);
pm.rollback(result);
} catch (Exception e) {
throw new PatchException("Unable to rollback patch " + patch.getPatchData().getId() + ": " + e.getMessage(), e);
}
((Patch) patch).setResult(null);
File file = new File(patchDir, result.getPatchData().getId() + ".patch.result");
file.delete();
}
});
}
/**
* Returns two element table: symbolic name and version
* @param url
* @return
* @throws IOException
*/
private String[] getBundleIdentity(String url) throws IOException {
JarInputStream jis = new JarInputStream(new URL(url).openStream());
jis.close();
Manifest manifest = jis.getManifest();
Attributes att = manifest != null ? manifest.getMainAttributes() : null;
String sn = att != null ? att.getValue(Constants.BUNDLE_SYMBOLICNAME) : null;
String vr = att != null ? att.getValue(Constants.BUNDLE_VERSION) : null;
if (sn == null || vr == null) {
return null;
}
return new String[] { sn, vr };
}
/**
* <p>Returns a {@link VersionRange} that existing bundle has to satisfy in order to be updated to
* <code>newVersion</code></p>
* <p>If we're upgrading to <code>1.2.3</code>, existing bundle has to be in range
* <code>[1.2.0,1.2.3)</code></p>
* @param patch
* @param url
* @param newVersion
* @return
*/
private VersionRange getUpdateableRange(Patch patch, String url, Version newVersion) {
VersionRange range = null;
if (patch.getPatchData().getVersionRange(url) == null) {
// default version range starts with x.y.0 as the lower bound
Version lower = new Version(newVersion.getMajor(), newVersion.getMinor(), 0);
// We can't really upgrade with versions such as 2.1.0
if (newVersion.compareTo(lower) > 0) {
range = new VersionRange(false, lower, newVersion, true);
}
} else {
range = new VersionRange(patch.getPatchData().getVersionRange(url));
}
return range;
}
private File getPatchStorage(Patch patch) {
return new File(patchDir, patch.getPatchData().getId());
}
private void applyChanges(Map<Bundle, String> toUpdate) throws BundleException, IOException {
List<Bundle> toStop = new ArrayList<Bundle>();
Map<Bundle, String> lessToUpdate = new HashMap<>();
for (Bundle b : toUpdate.keySet()) {
if (b.getState() != Bundle.UNINSTALLED) {
toStop.add(b);
lessToUpdate.put(b, toUpdate.get(b));
}
}
while (!toStop.isEmpty()) {
List<Bundle> bs = getBundlesToDestroy(toStop);
for (Bundle bundle : bs) {
String hostHeader = (String) bundle.getHeaders().get(Constants.FRAGMENT_HOST);
if (hostHeader == null && (bundle.getState() == Bundle.ACTIVE || bundle.getState() == Bundle.STARTING)) {
if (!"org.ops4j.pax.url.mvn".equals(bundle.getSymbolicName())) {
bundle.stop();
}
}
toStop.remove(bundle);
}
}
Set<Bundle> toRefresh = new HashSet<Bundle>();
Set<Bundle> toStart = new HashSet<Bundle>();
for (Map.Entry<Bundle, String> e : lessToUpdate.entrySet()) {
Bundle bundle = e.getKey();
if (!"org.ops4j.pax.url.mvn".equals(bundle.getSymbolicName())) {
System.out.println("updating: " + bundle.getSymbolicName());
try {
BundleUtils.update(bundle, new URL(e.getValue()));
} catch (BundleException ex) {
System.err.println("Failed to update: " + bundle.getSymbolicName()+", due to: "+e);
}
toStart.add(bundle);
}
toRefresh.add(bundle);
}
findBundlesWithOptionalPackagesToRefresh(toRefresh);
findBundlesWithFragmentsToRefresh(toRefresh);
if (!toRefresh.isEmpty()) {
final CountDownLatch l = new CountDownLatch(1);
FrameworkListener listener = new FrameworkListener() {
@Override
public void frameworkEvent(FrameworkEvent event) {
l.countDown();
}
};
FrameworkWiring wiring = (FrameworkWiring) bundleContext.getBundle(0).adapt(FrameworkWiring.class);
wiring.refreshBundles((Collection<Bundle>) toRefresh, listener);
try {
l.await();
} catch (InterruptedException e) {
throw new PatchException("Bundle refresh interrupted", e);
}
}
for (Bundle bundle : toStart) {
String hostHeader = (String) bundle.getHeaders().get(Constants.FRAGMENT_HOST);
if (hostHeader == null) {
try {
bundle.start();
} catch (BundleException e) {
System.err.println("Failed to start: " + bundle.getSymbolicName()+", due to: "+e);
}
}
}
}
private List<Bundle> getBundlesToDestroy(List<Bundle> bundles) {
List<Bundle> bundlesToDestroy = new ArrayList<Bundle>();
for (Bundle bundle : bundles) {
ServiceReference[] references = bundle.getRegisteredServices();
int usage = 0;
if (references != null) {
for (ServiceReference reference : references) {
usage += getServiceUsage(reference, bundles);
}
}
if (usage == 0) {
bundlesToDestroy.add(bundle);
}
}
if (!bundlesToDestroy.isEmpty()) {
Collections.sort(bundlesToDestroy, new Comparator<Bundle>() {
public int compare(Bundle b1, Bundle b2) {
return (int) (b2.getLastModified() - b1.getLastModified());
}
});
} else {
ServiceReference ref = null;
for (Bundle bundle : bundles) {
ServiceReference[] references = bundle.getRegisteredServices();
for (ServiceReference reference : references) {
if (getServiceUsage(reference, bundles) == 0) {
continue;
}
if (ref == null || reference.compareTo(ref) < 0) {
ref = reference;
}
}
}
if (ref != null) {
bundlesToDestroy.add(ref.getBundle());
}
}
return bundlesToDestroy;
}
private static int getServiceUsage(ServiceReference ref, List<Bundle> bundles) {
Bundle[] usingBundles = ref.getUsingBundles();
int nb = 0;
if (usingBundles != null) {
for (Bundle bundle : usingBundles) {
if (bundles.contains(bundle)) {
nb++;
}
}
}
return nb;
}
protected void findBundlesWithFragmentsToRefresh(Set<Bundle> toRefresh) {
for (Bundle b : toRefresh) {
if (b.getState() != Bundle.UNINSTALLED) {
String hostHeader = (String) b.getHeaders().get(Constants.FRAGMENT_HOST);
if (hostHeader != null) {
Clause[] clauses = Parser.parseHeader(hostHeader);
if (clauses != null && clauses.length > 0) {
Clause path = clauses[0];
for (Bundle hostBundle : bundleContext.getBundles()) {
if (hostBundle.getSymbolicName().equals(path.getName())) {
String ver = path.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE);
if (ver != null) {
VersionRange v = VersionRange.parseVersionRange(ver);
if (v.contains(hostBundle.getVersion())) {
toRefresh.add(hostBundle);
}
} else {
toRefresh.add(hostBundle);
}
}
}
}
}
}
}
}
protected void findBundlesWithOptionalPackagesToRefresh(Set<Bundle> toRefresh) {
// First pass: include all bundles contained in these features
Set<Bundle> bundles = new HashSet<Bundle>(Arrays.asList(bundleContext.getBundles()));
bundles.removeAll(toRefresh);
if (bundles.isEmpty()) {
return;
}
// Second pass: for each bundle, check if there is any unresolved optional package that could be resolved
Map<Bundle, List<Clause>> imports = new HashMap<Bundle, List<Clause>>();
for (Iterator<Bundle> it = bundles.iterator(); it.hasNext();) {
Bundle b = it.next();
String importsStr = (String) b.getHeaders().get(Constants.IMPORT_PACKAGE);
List<Clause> importsList = getOptionalImports(importsStr);
if (importsList.isEmpty()) {
it.remove();
} else {
imports.put(b, importsList);
}
}
if (bundles.isEmpty()) {
return;
}
// Third pass: compute a list of packages that are exported by our bundles and see if
// some exported packages can be wired to the optional imports
List<Clause> exports = new ArrayList<Clause>();
for (Bundle b : toRefresh) {
if (b.getState() != Bundle.UNINSTALLED) {
String exportsStr = (String) b.getHeaders().get(Constants.EXPORT_PACKAGE);
if (exportsStr != null) {
Clause[] exportsList = Parser.parseHeader(exportsStr);
exports.addAll(Arrays.asList(exportsList));
}
}
}
for (Iterator<Bundle> it = bundles.iterator(); it.hasNext();) {
Bundle b = it.next();
List<Clause> importsList = imports.get(b);
for (Iterator<Clause> itpi = importsList.iterator(); itpi.hasNext();) {
Clause pi = itpi.next();
boolean matching = false;
for (Clause pe : exports) {
if (pi.getName().equals(pe.getName())) {
String evStr = pe.getAttribute(Constants.VERSION_ATTRIBUTE);
String ivStr = pi.getAttribute(Constants.VERSION_ATTRIBUTE);
Version exported = evStr != null ? Version.parseVersion(evStr) : Version.emptyVersion;
VersionRange imported = ivStr != null ? VersionRange.parseVersionRange(ivStr) : VersionRange.ANY_VERSION;
if (imported.contains(exported)) {
matching = true;
break;
}
}
}
if (!matching) {
itpi.remove();
}
}
if (importsList.isEmpty()) {
it.remove();
}
}
toRefresh.addAll(bundles);
}
protected List<Clause> getOptionalImports(String importsStr) {
Clause[] imports = Parser.parseHeader(importsStr);
List<Clause> result = new LinkedList<Clause>();
for (Clause anImport : imports) {
String resolution = anImport.getDirective(Constants.RESOLUTION_DIRECTIVE);
if (Constants.RESOLUTION_OPTIONAL.equals(resolution)) {
result.add(anImport);
}
}
return result;
}
/*
* Create a bundle version history based on the information in the .patch and .patch.result files
*/
protected BundleVersionHistory createBundleVersionHistory() {
return new BundleVersionHistory(load(true));
}
/**
* Check if the set of patches mixes P and R patches. We can install several {@link PatchKind#NON_ROLLUP}
* patches at once, but only one {@link PatchKind#ROLLUP} patch.
* @param patches
* @return kind of patches in the set
*/
private PatchKind checkConsistency(Collection<Patch> patches) throws PatchException {
boolean hasP = false, hasR = false;
for (Patch patch : patches) {
if (patch.getPatchData().isRollupPatch()) {
if (hasR) {
throw new PatchException("Can't install more than one rollup patch at once");
}
hasR = true;
} else {
hasP = true;
}
}
if (hasR && hasP) {
throw new PatchException("Can't install both rollup and non-rollup patches in single run");
}
return hasR ? PatchKind.ROLLUP : PatchKind.NON_ROLLUP;
}
/**
* Check if the requirements for all specified patches have been installed
* @param patches the set of patches to check
* @throws PatchException if at least one of the patches has missing requirements
*/
protected void checkPrerequisites(Collection<Patch> patches) throws PatchException {
for (Patch patch : patches) {
checkPrerequisites(patch);
}
}
/**
* Check if the requirements for the specified patch have been installed
* @param patch the patch to check
* @throws PatchException if the requirements for the patch are missing or not yet installed
*/
protected void checkPrerequisites(Patch patch) throws PatchException {
for (String requirement : patch.getPatchData().getRequirements()) {
Patch required = getPatch(requirement);
if (required == null) {
throw new PatchException(String.format("Required patch '%s' is missing", requirement));
}
if (!required.isInstalled()) {
throw new PatchException(String.format("Required patch '%s' is not installed", requirement));
}
}
}
/**
* Contains the history of bundle versions that have been applied through the patching mechanism
*/
protected static final class BundleVersionHistory {
// symbolic name -> version -> location
private Map<String, Map<String, String>> bundleVersions = new HashMap<String, Map<String, String>>();
public BundleVersionHistory(Map<String, Patch> patches) {
for (Map.Entry<String, Patch> patch : patches.entrySet()) {
PatchResult result = patch.getValue().getResult();
if (result != null) {
for (BundleUpdate update : result.getBundleUpdates()) {
String symbolicName = stripSymbolicName(update.getSymbolicName());
Map<String, String> versions = bundleVersions.get(symbolicName);
if (versions == null) {
versions = new HashMap<String, String>();
bundleVersions.put(symbolicName, versions);
}
versions.put(update.getNewVersion(), update.getNewLocation());
}
}
}
}
/**
* Get the bundle location for a given bundle version. If this bundle version was not installed through a patch,
* this methods will return the original bundle location.
*
* @param bundle the bundle
* @return the location for this bundle version
*/
protected String getLocation(Bundle bundle) {
String symbolicName = stripSymbolicName(bundle.getSymbolicName());
Map<String, String> versions = bundleVersions.get(symbolicName);
String location = null;
if (versions != null) {
location = versions.get(bundle.getVersion().toString());
}
if (location == null) {
location = bundle.getLocation();
}
return location;
}
}
}
|
[git-patching] start of storeWorkForPendingRestart
|
patch/patch-core/src/main/java/io/fabric8/patch/impl/ServiceImpl.java
|
[git-patching] start of storeWorkForPendingRestart
|
|
Java
|
apache-2.0
|
638ae20fb33241adcdd553a8e0cd977a45fe3910
| 0
|
arangodb/arangodb-java-driver,arangodb/arangodb-java-driver
|
package com.arangodb;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import com.arangodb.entity.AqlExecutionExplainResult;
import com.arangodb.entity.AqlExecutionExplainResult.ExecutionNode;
import com.arangodb.entity.AqlExecutionExplainResult.ExecutionPlan;
import com.arangodb.entity.AqlFunctionResult;
import com.arangodb.entity.AqlParseResult;
import com.arangodb.entity.AqlParseResult.AstNode;
import com.arangodb.entity.BaseDocument;
import com.arangodb.entity.CollectionResult;
import com.arangodb.entity.DatabaseResult;
import com.arangodb.entity.GraphResult;
import com.arangodb.entity.IndexResult;
import com.arangodb.model.AqlFunctionDeleteOptions;
import com.arangodb.model.AqlQueryOptions;
import com.arangodb.model.CollectionsReadOptions;
import com.arangodb.model.TransactionOptions;
import com.arangodb.velocypack.VPackBuilder;
import com.arangodb.velocypack.VPackSlice;
import com.arangodb.velocypack.Value;
import com.arangodb.velocypack.exception.VPackException;
/**
* @author Mark - mark at arangodb.com
*
*/
public class ArangoDatabaseTest extends BaseTest {
private static final String COLLECTION_NAME = "db_test";
private static final String GRAPH_NAME = "graph_test";
@Test
public void createCollection() {
try {
final CollectionResult result = db.createCollection(COLLECTION_NAME, null);
assertThat(result, is(notNullValue()));
assertThat(result.getId(), is(notNullValue()));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void deleteCollection() {
db.createCollection(COLLECTION_NAME, null);
db.collection(COLLECTION_NAME).drop();
try {
db.collection(COLLECTION_NAME).getInfo();
fail();
} catch (final ArangoDBException e) {
}
}
@Test
public void getIndex() {
try {
db.createCollection(COLLECTION_NAME, null);
final Collection<String> fields = new ArrayList<>();
fields.add("a");
final IndexResult createResult = db.collection(COLLECTION_NAME).createHashIndex(fields, null);
final IndexResult readResult = db.getIndex(createResult.getId());
assertThat(readResult.getId(), is(createResult.getId()));
assertThat(readResult.getType(), is(createResult.getType()));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void deleteIndex() {
try {
db.createCollection(COLLECTION_NAME, null);
final Collection<String> fields = new ArrayList<>();
fields.add("a");
final IndexResult createResult = db.collection(COLLECTION_NAME).createHashIndex(fields, null);
final String id = db.deleteIndex(createResult.getId());
assertThat(id, is(createResult.getId()));
try {
db.getIndex(id);
fail();
} catch (final ArangoDBException e) {
}
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void getCollections() {
try {
final Collection<CollectionResult> systemCollections = db.getCollections(null);
db.createCollection(COLLECTION_NAME + "1", null);
db.createCollection(COLLECTION_NAME + "2", null);
final Collection<CollectionResult> collections = db.getCollections(null);
assertThat(collections.size(), is(2 + systemCollections.size()));
assertThat(collections, is(notNullValue()));
} finally {
db.collection(COLLECTION_NAME + "1").drop();
db.collection(COLLECTION_NAME + "2").drop();
}
}
@Test
public void getCollectionsExcludeSystem() {
try {
final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true);
final Collection<CollectionResult> systemCollections = db.getCollections(options);
assertThat(systemCollections.size(), is(0));
db.createCollection(COLLECTION_NAME + "1", null);
db.createCollection(COLLECTION_NAME + "2", null);
final Collection<CollectionResult> collections = db.getCollections(options);
assertThat(collections.size(), is(2));
assertThat(collections, is(notNullValue()));
} finally {
db.collection(COLLECTION_NAME + "1").drop();
db.collection(COLLECTION_NAME + "2").drop();
}
}
@Test
public void grantAccess() {
try {
arangoDB.createUser("user1", "1234", null);
db.grandAccess("user1");
} finally {
arangoDB.deleteUser("user1");
}
}
@Test(expected = ArangoDBException.class)
public void grantAccessUserNotFound() {
db.grandAccess("user1");
}
@Test
public void revokeAccess() {
try {
arangoDB.createUser("user1", "1234", null);
db.revokeAccess("user1");
} finally {
arangoDB.deleteUser("user1");
}
}
@Test(expected = ArangoDBException.class)
public void revokeAccessUserNotFound() {
db.revokeAccess("user1");
}
@Test
public void query() {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test return i._id", null, null, String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 10; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 10));
}
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithCount() {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test Limit 6 return i._id", null,
new AqlQueryOptions().count(true), String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 6; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 6));
}
assertThat(cursor.getCount().isPresent(), is(true));
assertThat(cursor.getCount().get(), is(6));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithLimitAndFullCount() {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test Limit 5 return i._id", null,
new AqlQueryOptions().fullCount(true), String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 5; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 5));
}
assertThat(cursor.getStats().isPresent(), is(true));
assertThat(cursor.getStats().get().getFullCount(), is(10L));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithBatchSize() {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test return i._id", null,
new AqlQueryOptions().batchSize(5).count(true), String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 10; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 10));
}
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
/**
* ignored. takes to long
*/
@Test
@Ignore
public void queryWithTTL() throws InterruptedException {
// set TTL to 1 seconds and get the second batch after 2 seconds!
final int ttl = 1;
final int wait = 2;
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test return i._id", null,
new AqlQueryOptions().batchSize(5).ttl(ttl), String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 10; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 10));
if (i == 1) {
Thread.sleep(wait * 1000);
}
}
fail("this should fail");
} catch (final ArangoDBException ex) {
assertThat(ex.getMessage(), is("Response: 404, Error: 1600 - cursor not found"));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
@Ignore
public void queryWithCache() throws InterruptedException {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
// TODO: set query cache property to "on"!
final ArangoCursor<String> cursor = db.query("FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id",
null, new AqlQueryOptions().cache(true), String.class);
assertThat(cursor, is(notNullValue()));
assertThat(cursor.isCached(), is(false));
final ArangoCursor<String> cachedCursor = db.query(
"FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id", null, new AqlQueryOptions().cache(true),
String.class);
assertThat(cachedCursor, is(notNullValue()));
assertThat(cachedCursor.isCached(), is(true));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithBindVars() throws InterruptedException {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
final BaseDocument baseDocument = new BaseDocument();
baseDocument.addAttribute("age", 20 + i);
db.collection(COLLECTION_NAME).insertDocument(baseDocument, null);
}
final Map<String, Object> bindVars = new HashMap<>();
bindVars.put("@coll", COLLECTION_NAME);
bindVars.put("age", 25);
final ArangoCursor<String> cursor = db.query("FOR t IN @@coll FILTER t.age >= @age SORT t.age RETURN t._id",
bindVars, null, String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 5; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 5));
}
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithWarning() {
final ArangoCursor<String> cursor = arangoDB.db().query("return _users + 1", null, null, String.class);
assertThat(cursor, is(notNullValue()));
assertThat(cursor.getWarnings().isPresent(), is(true));
assertThat(cursor.getWarnings().get().isEmpty(), is(false));
}
@Test
public void queryClose() throws IOException {
final ArangoCursor<String> cursor = arangoDB.db().query("for i in _apps return i._id", null,
new AqlQueryOptions().batchSize(1), String.class);
cursor.close();
int count = 0;
try {
for (final Iterator<String> iterator = cursor.iterator(); iterator.hasNext(); iterator.next(), count++) {
}
fail();
} catch (final ArangoDBException e) {
assertThat(count, is(1));
}
}
@Test
public void explainQuery() {
final AqlExecutionExplainResult explain = arangoDB.db().explainQuery("for i in _apps return i", null, null);
assertThat(explain, is(notNullValue()));
assertThat(explain.getPlan().isPresent(), is(true));
assertThat(explain.getPlans().isPresent(), is(false));
final ExecutionPlan plan = explain.getPlan().get();
assertThat(plan.getCollections().size(), is(1));
assertThat(plan.getCollections().stream().findFirst().get().getName(), is("_apps"));
assertThat(plan.getCollections().stream().findFirst().get().getType(), is("read"));
assertThat(plan.getEstimatedCost(), is(5));
assertThat(plan.getEstimatedNrItems(), is(2));
assertThat(plan.getVariables().size(), is(1));
assertThat(plan.getVariables().stream().findFirst().get().getName(), is("i"));
assertThat(plan.getNodes().size(), is(3));
final Iterator<ExecutionNode> iterator = plan.getNodes().iterator();
final ExecutionNode singletonNode = iterator.next();
assertThat(singletonNode.getType(), is("SingletonNode"));
final ExecutionNode collectionNode = iterator.next();
assertThat(collectionNode.getType(), is("EnumerateCollectionNode"));
assertThat(collectionNode.getDatabase().isPresent(), is(true));
assertThat(collectionNode.getDatabase().get(), is("_system"));
assertThat(collectionNode.getCollection().isPresent(), is(true));
assertThat(collectionNode.getCollection().get(), is("_apps"));
assertThat(collectionNode.getOutVariable().isPresent(), is(true));
assertThat(collectionNode.getOutVariable().get().getName(), is("i"));
final ExecutionNode returnNode = iterator.next();
assertThat(returnNode.getType(), is("ReturnNode"));
assertThat(returnNode.getInVariable().isPresent(), is(true));
assertThat(returnNode.getInVariable().get().getName(), is("i"));
}
@Test
public void parseQuery() {
final AqlParseResult parse = arangoDB.db().parseQuery("for i in _apps return i");
assertThat(parse, is(notNullValue()));
assertThat(parse.getBindVars(), is(empty()));
assertThat(parse.getCollections().size(), is(1));
assertThat(parse.getCollections().stream().findFirst().get(), is("_apps"));
assertThat(parse.getAst().size(), is(1));
final AstNode root = parse.getAst().stream().findFirst().get();
assertThat(root.getType(), is("root"));
assertThat(root.getName().isPresent(), is(false));
assertThat(root.getSubNodes().isPresent(), is(true));
assertThat(root.getSubNodes().get().size(), is(2));
final Iterator<AstNode> iterator = root.getSubNodes().get().iterator();
final AstNode for_ = iterator.next();
assertThat(for_.getType(), is("for"));
assertThat(for_.getSubNodes().isPresent(), is(true));
assertThat(for_.getSubNodes().get().size(), is(2));
final Iterator<AstNode> iterator2 = for_.getSubNodes().get().iterator();
final AstNode first = iterator2.next();
assertThat(first.getType(), is("variable"));
assertThat(first.getName().isPresent(), is(true));
assertThat(first.getName().get(), is("i"));
final AstNode second = iterator2.next();
assertThat(second.getType(), is("collection"));
assertThat(second.getName().isPresent(), is(true));
assertThat(second.getName().get(), is("_apps"));
final AstNode return_ = iterator.next();
assertThat(return_.getType(), is("return"));
assertThat(return_.getSubNodes().isPresent(), is(true));
assertThat(return_.getSubNodes().get().size(), is(1));
assertThat(return_.getSubNodes().get().stream().findFirst().get().getType(), is("reference"));
assertThat(return_.getSubNodes().get().stream().findFirst().get().getName().isPresent(), is(true));
assertThat(return_.getSubNodes().get().stream().findFirst().get().getName().get(), is("i"));
}
@Test
public void createGetDeleteAqlFunction() {
final Collection<AqlFunctionResult> aqlFunctionsInitial = db.getAqlFunctions(null);
assertThat(aqlFunctionsInitial, is(empty()));
try {
db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit",
"function (celsius) { return celsius * 1.8 + 32; }", null);
final Collection<AqlFunctionResult> aqlFunctions = db.getAqlFunctions(null);
assertThat(aqlFunctions.size(), is(greaterThan(aqlFunctionsInitial.size())));
} finally {
db.deleteAqlFunction("myfunctions::temperature::celsiustofahrenheit", null);
final Collection<AqlFunctionResult> aqlFunctions = db.getAqlFunctions(null);
assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size()));
}
}
@Test
public void createGetDeleteAqlFunctionWithNamespace() {
final Collection<AqlFunctionResult> aqlFunctionsInitial = db.getAqlFunctions(null);
assertThat(aqlFunctionsInitial, is(empty()));
try {
db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit1",
"function (celsius) { return celsius * 1.8 + 32; }", null);
db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit2",
"function (celsius) { return celsius * 1.8 + 32; }", null);
} finally {
db.deleteAqlFunction("myfunctions::temperature", new AqlFunctionDeleteOptions().group(true));
final Collection<AqlFunctionResult> aqlFunctions = db.getAqlFunctions(null);
assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size()));
}
}
@Test
public void createGraph() {
try {
final GraphResult result = db.createGraph(GRAPH_NAME, null, null);
assertThat(result, is(notNullValue()));
assertThat(result.getName(), is(GRAPH_NAME));
} finally {
db.graph(GRAPH_NAME).drop();
}
}
@Test
public void getGraphs() {
try {
db.createGraph(GRAPH_NAME, null, null);
final Collection<GraphResult> graphs = db.getGraphs();
assertThat(graphs, is(notNullValue()));
assertThat(graphs.size(), is(1));
} finally {
db.graph(GRAPH_NAME).drop();
}
}
@Test
public void transactionString() {
final TransactionOptions options = new TransactionOptions().params("test");
final String result = db.transaction("function (params) {return params;}", String.class, options);
assertThat(result, is("test"));
}
@Test
public void transactionNumber() {
final TransactionOptions options = new TransactionOptions().params(5);
final Integer result = db.transaction("function (params) {return params;}", Integer.class, options);
assertThat(result, is(5));
}
@Test
public void transactionVPack() throws VPackException {
final TransactionOptions options = new TransactionOptions()
.params(new VPackBuilder().add(new Value("test")).slice());
final VPackSlice result = db.transaction("function (params) {return params;}", VPackSlice.class, options);
assertThat(result.isString(), is(true));
assertThat(result.getAsString(), is("test"));
}
@Test
public void transactionEmpty() {
db.transaction("function () {}", null, null);
}
@Test
public void transactionallowImplicit() {
try {
db.createCollection("someCollection", null);
db.createCollection("someOtherCollection", null);
final String action = "function (params) {" + "var db = require('internal').db;"
+ "return {'a':db.someCollection.all().toArray()[0], 'b':db.someOtherCollection.all().toArray()[0]};"
+ "}";
final TransactionOptions options = new TransactionOptions().readCollections("someCollection");
db.transaction(action, VPackSlice.class, options);
try {
options.allowImplicit(false);
db.transaction(action, VPackSlice.class, options);
fail();
} catch (final ArangoDBException e) {
}
} finally {
db.collection("someCollection").drop();
db.collection("someOtherCollection").drop();
}
}
@Test
public void getInfo() {
final DatabaseResult info = db.getInfo();
assertThat(info, is(notNullValue()));
assertThat(info.getId(), is(notNullValue()));
assertThat(info.getName(), is(TEST_DB));
assertThat(info.getPath(), is(notNullValue()));
assertThat(info.getIsSystem(), is(false));
}
}
|
src/test/java/com/arangodb/ArangoDatabaseTest.java
|
package com.arangodb;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import com.arangodb.entity.AqlExecutionExplainResult;
import com.arangodb.entity.AqlExecutionExplainResult.ExecutionNode;
import com.arangodb.entity.AqlExecutionExplainResult.ExecutionPlan;
import com.arangodb.entity.AqlFunctionResult;
import com.arangodb.entity.AqlParseResult;
import com.arangodb.entity.AqlParseResult.AstNode;
import com.arangodb.entity.BaseDocument;
import com.arangodb.entity.CollectionResult;
import com.arangodb.entity.DatabaseResult;
import com.arangodb.entity.GraphResult;
import com.arangodb.entity.IndexResult;
import com.arangodb.model.AqlFunctionDeleteOptions;
import com.arangodb.model.AqlQueryOptions;
import com.arangodb.model.CollectionsReadOptions;
import com.arangodb.model.TransactionOptions;
import com.arangodb.velocypack.VPackBuilder;
import com.arangodb.velocypack.VPackSlice;
import com.arangodb.velocypack.Value;
import com.arangodb.velocypack.exception.VPackException;
/**
* @author Mark - mark at arangodb.com
*
*/
public class ArangoDatabaseTest extends BaseTest {
private static final String COLLECTION_NAME = "db_test";
private static final String GRAPH_NAME = "graph_test";
@Test
public void createCollection() {
try {
final CollectionResult result = db.createCollection(COLLECTION_NAME, null);
assertThat(result, is(notNullValue()));
assertThat(result.getId(), is(notNullValue()));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void deleteCollection() {
db.createCollection(COLLECTION_NAME, null);
db.collection(COLLECTION_NAME).drop();
try {
db.collection(COLLECTION_NAME).getInfo();
fail();
} catch (final ArangoDBException e) {
}
}
@Test
public void getIndex() {
try {
db.createCollection(COLLECTION_NAME, null);
final Collection<String> fields = new ArrayList<>();
fields.add("a");
final IndexResult createResult = db.collection(COLLECTION_NAME).createHashIndex(fields, null);
final IndexResult readResult = db.getIndex(createResult.getId());
assertThat(readResult.getId(), is(createResult.getId()));
assertThat(readResult.getType(), is(createResult.getType()));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void deleteIndex() {
try {
db.createCollection(COLLECTION_NAME, null);
final Collection<String> fields = new ArrayList<>();
fields.add("a");
final IndexResult createResult = db.collection(COLLECTION_NAME).createHashIndex(fields, null);
final String id = db.deleteIndex(createResult.getId());
assertThat(id, is(createResult.getId()));
try {
db.getIndex(id);
fail();
} catch (final ArangoDBException e) {
}
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void getCollections() {
try {
final Collection<CollectionResult> systemCollections = db.getCollections(null);
db.createCollection(COLLECTION_NAME + "1", null);
db.createCollection(COLLECTION_NAME + "2", null);
final Collection<CollectionResult> collections = db.getCollections(null);
assertThat(collections.size(), is(2 + systemCollections.size()));
assertThat(collections, is(notNullValue()));
} finally {
db.collection(COLLECTION_NAME + "1").drop();
db.collection(COLLECTION_NAME + "2").drop();
}
}
@Test
public void getCollectionsExcludeSystem() {
try {
final CollectionsReadOptions options = new CollectionsReadOptions().excludeSystem(true);
final Collection<CollectionResult> systemCollections = db.getCollections(options);
assertThat(systemCollections.size(), is(0));
db.createCollection(COLLECTION_NAME + "1", null);
db.createCollection(COLLECTION_NAME + "2", null);
final Collection<CollectionResult> collections = db.getCollections(options);
assertThat(collections.size(), is(2));
assertThat(collections, is(notNullValue()));
} finally {
db.collection(COLLECTION_NAME + "1").drop();
db.collection(COLLECTION_NAME + "2").drop();
}
}
@Test
public void grantAccess() {
try {
arangoDB.createUser("user1", "1234", null);
db.grandAccess("user1");
} finally {
arangoDB.deleteUser("user1");
}
}
@Test(expected = ArangoDBException.class)
public void grantAccessUserNotFound() {
db.grandAccess("user1");
}
@Test
public void revokeAccess() {
try {
arangoDB.createUser("user1", "1234", null);
db.revokeAccess("user1");
} finally {
arangoDB.deleteUser("user1");
}
}
@Test(expected = ArangoDBException.class)
public void revokeAccessUserNotFound() {
db.revokeAccess("user1");
}
@Test
public void query() {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test return i._id", null, null, String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 10; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 10));
}
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithCount() {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test Limit 6 return i._id", null,
new AqlQueryOptions().count(true), String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 6; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 6));
}
assertThat(cursor.getCount().isPresent(), is(true));
assertThat(cursor.getCount().get(), is(6));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithLimitAndFullCount() {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test Limit 5 return i._id", null,
new AqlQueryOptions().fullCount(true), String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 5; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 5));
}
assertThat(cursor.getStats().isPresent(), is(true));
assertThat(cursor.getStats().get().getFullCount(), is(10L));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithBatchSize() {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test return i._id", null,
new AqlQueryOptions().batchSize(5).count(true), String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 10; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 10));
}
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
/**
* ignored. takes to long
*/
@Test
@Ignore
public void queryWithTTL() throws InterruptedException {
// set TTL to 1 seconds and get the second batch after 2 seconds!
final int ttl = 1;
final int wait = 2;
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
final ArangoCursor<String> cursor = db.query("for i in db_test return i._id", null,
new AqlQueryOptions().batchSize(5).ttl(ttl), String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 10; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 10));
if (i == 1) {
Thread.sleep(wait * 1000);
}
}
fail("this should fail");
} catch (final ArangoDBException ex) {
assertThat(ex.getMessage(), is("Response: 404, Error: 1600 - cursor not found"));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
@Ignore
public void queryWithCache() throws InterruptedException {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
db.collection(COLLECTION_NAME).insertDocument(new BaseDocument(), null);
}
// TODO: set query cache property to "on"!
final ArangoCursor<String> cursor = db.query("FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id",
null, new AqlQueryOptions().cache(true), String.class);
assertThat(cursor, is(notNullValue()));
assertThat(cursor.isCached(), is(false));
final ArangoCursor<String> cachedCursor = db.query(
"FOR t IN db_test FILTER t.age >= 10 SORT t.age RETURN t._id", null, new AqlQueryOptions().cache(true),
String.class);
assertThat(cachedCursor, is(notNullValue()));
assertThat(cachedCursor.isCached(), is(true));
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithBindVars() throws InterruptedException {
try {
db.createCollection(COLLECTION_NAME, null);
for (int i = 0; i < 10; i++) {
final BaseDocument baseDocument = new BaseDocument();
baseDocument.addAttribute("age", 20 + i);
db.collection(COLLECTION_NAME).insertDocument(baseDocument, null);
}
final Map<String, Object> bindVars = new HashMap<>();
bindVars.put("@coll", COLLECTION_NAME);
bindVars.put("age", 25);
final ArangoCursor<String> cursor = db.query("FOR t IN @@coll FILTER t.age >= @age SORT t.age RETURN t._id",
bindVars, null, String.class);
assertThat(cursor, is(notNullValue()));
final Iterator<String> iterator = cursor.iterator();
assertThat(iterator, is(notNullValue()));
for (int i = 0; i < 5; i++, iterator.next()) {
assertThat(iterator.hasNext(), is(i != 5));
}
} finally {
db.collection(COLLECTION_NAME).drop();
}
}
@Test
public void queryWithWarning() {
final ArangoCursor<String> cursor = arangoDB.db().query("return _users + 1", null, null, String.class);
assertThat(cursor, is(notNullValue()));
assertThat(cursor.getWarnings().isPresent(), is(true));
assertThat(cursor.getWarnings().get().isEmpty(), is(false));
}
@Test
public void queryClose() throws IOException {
final ArangoCursor<String> cursor = arangoDB.db().query("for i in _apps return i._id", null,
new AqlQueryOptions().batchSize(1), String.class);
cursor.close();
int count = 0;
try {
for (final Iterator<String> iterator = cursor.iterator(); iterator.hasNext(); iterator.next(), count++) {
}
fail();
} catch (final ArangoDBException e) {
assertThat(count, is(1));
}
}
@Test
public void explainQuery() {
final AqlExecutionExplainResult explain = arangoDB.db().explainQuery("for i in _apps return i", null, null);
assertThat(explain, is(notNullValue()));
assertThat(explain.getPlan().isPresent(), is(true));
assertThat(explain.getPlans().isPresent(), is(false));
final ExecutionPlan plan = explain.getPlan().get();
assertThat(plan.getCollections().size(), is(1));
assertThat(plan.getCollections().stream().findFirst().get().getName(), is("_apps"));
assertThat(plan.getCollections().stream().findFirst().get().getType(), is("read"));
assertThat(plan.getEstimatedCost(), is(5));
assertThat(plan.getEstimatedNrItems(), is(2));
assertThat(plan.getVariables().size(), is(1));
assertThat(plan.getVariables().stream().findFirst().get().getName(), is("i"));
assertThat(plan.getNodes().size(), is(3));
final Iterator<ExecutionNode> iterator = plan.getNodes().iterator();
final ExecutionNode singletonNode = iterator.next();
assertThat(singletonNode.getType(), is("SingletonNode"));
final ExecutionNode collectionNode = iterator.next();
assertThat(collectionNode.getType(), is("EnumerateCollectionNode"));
assertThat(collectionNode.getDatabase().isPresent(), is(true));
assertThat(collectionNode.getDatabase().get(), is("_system"));
assertThat(collectionNode.getCollection().isPresent(), is(true));
assertThat(collectionNode.getCollection().get(), is("_apps"));
assertThat(collectionNode.getOutVariable().isPresent(), is(true));
assertThat(collectionNode.getOutVariable().get().getName(), is("i"));
final ExecutionNode returnNode = iterator.next();
assertThat(returnNode.getType(), is("ReturnNode"));
assertThat(returnNode.getInVariable().isPresent(), is(true));
assertThat(returnNode.getInVariable().get().getName(), is("i"));
}
@Test
public void parseQuery() {
final AqlParseResult parse = arangoDB.db().parseQuery("for i in _apps return i");
assertThat(parse, is(notNullValue()));
assertThat(parse.getBindVars(), is(empty()));
assertThat(parse.getCollections().size(), is(1));
assertThat(parse.getCollections().stream().findFirst().get(), is("_apps"));
assertThat(parse.getAst().size(), is(1));
final AstNode root = parse.getAst().stream().findFirst().get();
assertThat(root.getType(), is("root"));
assertThat(root.getName().isPresent(), is(false));
assertThat(root.getSubNodes().isPresent(), is(true));
assertThat(root.getSubNodes().get().size(), is(2));
final Iterator<AstNode> iterator = root.getSubNodes().get().iterator();
final AstNode for_ = iterator.next();
assertThat(for_.getType(), is("for"));
assertThat(for_.getSubNodes().isPresent(), is(true));
assertThat(for_.getSubNodes().get().size(), is(2));
final Iterator<AstNode> iterator2 = for_.getSubNodes().get().iterator();
final AstNode first = iterator2.next();
assertThat(first.getType(), is("variable"));
assertThat(first.getName().isPresent(), is(true));
assertThat(first.getName().get(), is("i"));
final AstNode second = iterator2.next();
assertThat(second.getType(), is("collection"));
assertThat(second.getName().isPresent(), is(true));
assertThat(second.getName().get(), is("_apps"));
final AstNode return_ = iterator.next();
assertThat(return_.getType(), is("return"));
assertThat(return_.getSubNodes().isPresent(), is(true));
assertThat(return_.getSubNodes().get().size(), is(1));
assertThat(return_.getSubNodes().get().stream().findFirst().get().getType(), is("reference"));
assertThat(return_.getSubNodes().get().stream().findFirst().get().getName().isPresent(), is(true));
assertThat(return_.getSubNodes().get().stream().findFirst().get().getName().get(), is("i"));
}
@Test
public void createGetDeleteAqlFunction() {
final Collection<AqlFunctionResult> aqlFunctionsInitial = db.getAqlFunctions(null);
assertThat(aqlFunctionsInitial, is(empty()));
try {
db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit",
"function (celsius) { return celsius * 1.8 + 32; }", null);
final Collection<AqlFunctionResult> aqlFunctions = db.getAqlFunctions(null);
assertThat(aqlFunctions.size(), is(greaterThan(aqlFunctionsInitial.size())));
} finally {
db.deleteAqlFunction("myfunctions::temperature::celsiustofahrenheit", null);
final Collection<AqlFunctionResult> aqlFunctions = db.getAqlFunctions(null);
assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size()));
}
}
@Test
public void createGetDeleteAqlFunctionWithNamespace() {
final Collection<AqlFunctionResult> aqlFunctionsInitial = db.getAqlFunctions(null);
assertThat(aqlFunctionsInitial, is(empty()));
try {
db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit1",
"function (celsius) { return celsius * 1.8 + 32; }", null);
db.createAqlFunction("myfunctions::temperature::celsiustofahrenheit2",
"function (celsius) { return celsius * 1.8 + 32; }", null);
} finally {
db.deleteAqlFunction("myfunctions::temperature", new AqlFunctionDeleteOptions().group(true));
final Collection<AqlFunctionResult> aqlFunctions = db.getAqlFunctions(null);
assertThat(aqlFunctions.size(), is(aqlFunctionsInitial.size()));
}
}
@Test
public void createGraph() {
final GraphResult result = db.createGraph(GRAPH_NAME, null, null);
assertThat(result, is(notNullValue()));
assertThat(result.getName(), is(GRAPH_NAME));
}
@Test
public void getGraphs() {
db.createGraph(GRAPH_NAME, null, null);
final Collection<GraphResult> graphs = db.getGraphs();
assertThat(graphs, is(notNullValue()));
assertThat(graphs.size(), is(1));
}
@Test
public void transactionString() {
final TransactionOptions options = new TransactionOptions().params("test");
final String result = db.transaction("function (params) {return params;}", String.class, options);
assertThat(result, is("test"));
}
@Test
public void transactionNumber() {
final TransactionOptions options = new TransactionOptions().params(5);
final Integer result = db.transaction("function (params) {return params;}", Integer.class, options);
assertThat(result, is(5));
}
@Test
public void transactionVPack() throws VPackException {
final TransactionOptions options = new TransactionOptions()
.params(new VPackBuilder().add(new Value("test")).slice());
final VPackSlice result = db.transaction("function (params) {return params;}", VPackSlice.class, options);
assertThat(result.isString(), is(true));
assertThat(result.getAsString(), is("test"));
}
@Test
public void transactionEmpty() {
db.transaction("function () {}", null, null);
}
@Test
public void transactionallowImplicit() {
try {
db.createCollection("someCollection", null);
db.createCollection("someOtherCollection", null);
final String action = "function (params) {" + "var db = require('internal').db;"
+ "return {'a':db.someCollection.all().toArray()[0], 'b':db.someOtherCollection.all().toArray()[0]};"
+ "}";
final TransactionOptions options = new TransactionOptions().readCollections("someCollection");
db.transaction(action, VPackSlice.class, options);
try {
options.allowImplicit(false);
db.transaction(action, VPackSlice.class, options);
fail();
} catch (final ArangoDBException e) {
}
} finally {
db.collection("someCollection").drop();
db.collection("someOtherCollection").drop();
}
}
@Test
public void getInfo() {
final DatabaseResult info = db.getInfo();
assertThat(info, is(notNullValue()));
assertThat(info.getId(), is(notNullValue()));
assertThat(info.getName(), is(TEST_DB));
assertThat(info.getPath(), is(notNullValue()));
assertThat(info.getIsSystem(), is(false));
}
}
|
fixed tests
|
src/test/java/com/arangodb/ArangoDatabaseTest.java
|
fixed tests
|
|
Java
|
apache-2.0
|
16d2a565e4c0c17223a2471d98d0bc189d3809dd
| 0
|
LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb
|
/*
// $Id$
// Package org.eigenbase is a class library of data management components.
// Copyright (C) 2005-2007 The Eigenbase Project
// Copyright (C) 2002-2007 Disruptive Tech
// Copyright (C) 2005-2007 LucidEra, Inc.
// Portions Copyright (C) 2003-2007 John V. Sichi
//
// 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 approved by The Eigenbase Project.
//
// 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 org.eigenbase.sql.test;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import junit.framework.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.fun.*;
import org.eigenbase.sql.parser.*;
import org.eigenbase.sql.type.*;
import org.eigenbase.test.*;
import org.eigenbase.util.*;
/**
* Contains unit tests for all operators. Each of the methods is named after an
* operator.
*
* <p>The class is abstract. It contains a test for every operator, but does not
* provide a mechanism to execute the tests: parse, validate, and execute
* expressions on the operators. This is left to a {@link SqlTester} object
* which the derived class must provide.
*
* <p>Different implementations of {@link SqlTester} are possible, such as:
*
* <ul>
* <li>Execute against a real farrago database
* <li>Execute in pure java (parsing and validation can be done, but expression
* evaluation is not possible)
* <li>Generate a SQL script.
* <li>Analyze which operators are adequately tested.
* </ul>
*
* <p>A typical method will be named after the operator it is testing (say
* <code>testSubstringFunc</code>). It first calls {@link
* SqlTester#setFor(SqlOperator)} to declare which operator it is testing.
* <blockqoute>
*
* <pre><code>
* public void testSubstringFunc() {
* getTester().setFor(SqlStdOperatorTable.substringFunc);
* getTester().checkScalar("sin(0)", "0");
* getTester().checkScalar("sin(1.5707)", "1");
* }</code></pre>
*
* </blockqoute> The rest of the method contains calls to the various <code>
* checkXxx</code> methods in the {@link SqlTester} interface. For an operator
* to be adequately tested, there need to be tests for:
*
* <ul>
* <li>Parsing all of its the syntactic variants.
* <li>Deriving the type of in all combinations of arguments.
*
* <ul>
* <li>Pay particular attention to nullability. For example, the result of the
* "+" operator is NOT NULL if and only if both of its arguments are NOT
* NULL.</li>
* <li>Also pay attention to precsion/scale/length. For example, the maximum
* length of the "||" operator is the sum of the maximum lengths of its
* arguments.</li>
* </ul>
* </li>
* <li>Executing the function. Pay particular attention to corner cases such as
* null arguments or null results.</li>
* </ul>
*
* @author Julian Hyde
* @version $Id$
* @since October 1, 2004
*/
public abstract class SqlOperatorTests
extends TestCase
{
//~ Static fields/initializers ---------------------------------------------
public static final String NL = TestUtil.NL;
// TODO: Change message when Fnl3Fixed to something like
// "Invalid character for cast: PC=0 Code=22018"
public static final String invalidCharMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
// TODO: Change message when Fnl3Fixed to something like
// "Overflow during calculation or cast: PC=0 Code=22003"
public static final String outOfRangeMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
// TODO: Change message when Fnl3Fixed to something like
// "Division by zero: PC=0 Code=22012"
public static final String divisionByZeroMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
// TODO: Change message when Fnl3Fixed to something like
// "String right truncation: PC=0 Code=22001"
public static final String stringTruncMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
// TODO: Change message when Fnl3Fixed to something like
// "Invalid datetime format: PC=0 Code=22007"
public static final String badDatetimeMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
public static final String literalOutOfRangeMessage =
"(?s).*Numeric literal.*out of range.*";
public static final boolean todo = false;
/**
* Regular expression for a SQL TIME(0) value.
*/
public static final Pattern timePattern =
Pattern.compile(
"[0-9][0-9]:[0-9][0-9]:[0-9][0-9]");
/**
* Regular expression for a SQL TIMESTAMP(3) value.
*/
public static final Pattern timestampPattern =
Pattern.compile(
"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] "
+ "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\\.[0-9]+");
/**
* Regular expression for a SQL DATE value.
*/
public static final Pattern datePattern =
Pattern.compile(
"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]");
public static final String [] numericTypeNames =
new String[] {
"TINYINT", "SMALLINT", "INTEGER", "BIGINT",
"DECIMAL(5, 2)", "REAL", "FLOAT", "DOUBLE"
};
// REVIEW jvs 27-Apr-2006: for Float and Double, MIN_VALUE
// is the smallest positive value, not the smallest negative value
public static final String [] minNumericStrings =
new String[] {
Long.toString(Byte.MIN_VALUE), Long.toString(
Short.MIN_VALUE), Long.toString(Integer.MIN_VALUE),
Long.toString(Long.MIN_VALUE), "-999.99",
// NOTE jvs 26-Apr-2006: Win32 takes smaller values from
// win32_values.h
"1E-37", /*Float.toString(Float.MIN_VALUE)*/
"2E-307", /*Double.toString(Double.MIN_VALUE)*/
"2E-307" /*Double.toString(Double.MIN_VALUE)*/,
};
public static final String [] minOverflowNumericStrings =
new String[] {
Long.toString(Byte.MIN_VALUE - 1),
Long.toString(Short.MIN_VALUE - 1),
Long.toString((long) Integer.MIN_VALUE - 1),
(new BigDecimal(Long.MIN_VALUE)).subtract(BigDecimal.ONE).toString(),
"-1000.00",
"1e-46",
"1e-324",
"1e-324"
};
public static final String [] maxNumericStrings =
new String[] {
Long.toString(Byte.MAX_VALUE), Long.toString(
Short.MAX_VALUE), Long.toString(Integer.MAX_VALUE),
Long.toString(Long.MAX_VALUE), "999.99",
// NOTE jvs 26-Apr-2006: use something slightly less than MAX_VALUE
// because roundtripping string to approx to string doesn't preserve
// MAX_VALUE on win32
"3.4028234E38", /*Float.toString(Float.MAX_VALUE)*/
"1.79769313486231E308", /*Double.toString(Double.MAX_VALUE)*/
"1.79769313486231E308" /*Double.toString(Double.MAX_VALUE)*/
};
public static final String [] maxOverflowNumericStrings =
new String[] {
Long.toString(Byte.MAX_VALUE + 1),
Long.toString(Short.MAX_VALUE + 1),
Long.toString((long) Integer.MAX_VALUE + 1),
(new BigDecimal(Long.MAX_VALUE)).add(BigDecimal.ONE).toString(),
"1000.00",
"1e39",
"-1e309",
"1e309"
};
private static final boolean [] FalseTrue = new boolean[] { false, true };
//~ Constructors -----------------------------------------------------------
public SqlOperatorTests(String testName)
{
super(testName);
}
//~ Methods ----------------------------------------------------------------
/**
* Derived class must implement this method to provide a means to validate,
* execute various statements.
*/
protected abstract SqlTester getTester();
protected void setUp()
throws Exception
{
getTester().setFor(null);
}
protected void check(String query, SqlTester.TypeChecker typeChecker,
Object result, double delta)
{
getTester().check(query, typeChecker, result, delta);
}
protected void checkAgg(String expr, String[] inputValues, Object result, int delta)
{
getTester().checkAgg(expr, inputValues, result, delta);
}
protected void checkBoolean(String expression, Boolean result)
{
getTester().checkBoolean(expression, result);
}
protected void checkFails(String expression, String expectedError, Boolean runtime)
{
getTester().checkFails(expression, expectedError, runtime);
}
protected void checkNull(String expression)
{
getTester().checkNull(expression);
}
protected void checkScalar(String expression, Object result, String resultType)
{
getTester().checkScalar(expression, result, resultType);
}
protected void checkScalarApprox(String expression, String expectedType,
double expectedResult, double delta)
{
getTester().checkScalarApprox(expression, expectedType,
expectedResult, delta);
}
protected void checkScalarExact(String expression, String expectedType,
String result)
{
getTester().checkScalarExact(expression, expectedType, result);
}
protected void checkScalarExact(String expression, String result)
{
getTester().checkScalarExact(expression, result);
}
protected void checkString(String expression, String result, String resultType)
{
getTester().checkString(expression, result, resultType);
}
protected void checkType(String expression, String type)
{
getTester().checkType(expression, type);
}
protected void setFor(SqlOperator operator)
{
getTester().setFor(operator);
}
//--- Tests -----------------------------------------------------------
public void testBetween()
{
setFor(SqlStdOperatorTable.betweenOperator);
checkBoolean("2 between 1 and 3", Boolean.TRUE);
checkBoolean("2 between 3 and 2", Boolean.FALSE);
checkBoolean("2 between symmetric 3 and 2", Boolean.TRUE);
checkBoolean("3 between 1 and 3", Boolean.TRUE);
checkBoolean("4 between 1 and 3", Boolean.FALSE);
checkBoolean("1 between 4 and -3", Boolean.FALSE);
checkBoolean("1 between -1 and -3", Boolean.FALSE);
checkBoolean("1 between -1 and 3", Boolean.TRUE);
checkBoolean("1 between 1 and 1", Boolean.TRUE);
checkBoolean("1.5 between 1 and 3", Boolean.TRUE);
checkBoolean("1.2 between 1.1 and 1.3", Boolean.TRUE);
checkBoolean("1.5 between 2 and 3", Boolean.FALSE);
checkBoolean("1.5 between 1.6 and 1.7", Boolean.FALSE);
checkBoolean("1.2e1 between 1.1 and 1.3", Boolean.FALSE);
checkBoolean("1.2e0 between 1.1 and 1.3", Boolean.TRUE);
checkBoolean("1.5e0 between 2 and 3", Boolean.FALSE);
checkBoolean("1.5e0 between 2e0 and 3e0", Boolean.FALSE);
checkBoolean(
"1.5e1 between 1.6e1 and 1.7e1",
Boolean.FALSE);
checkBoolean("x'' between x'' and x''", Boolean.TRUE);
checkNull("cast(null as integer) between -1 and 2");
checkNull("1 between -1 and cast(null as integer)");
checkNull(
"1 between cast(null as integer) and cast(null as integer)");
checkNull("1 between cast(null as integer) and 1");
}
public void testBetweenTemporal()
{
setFor(SqlStdOperatorTable.betweenOperator);
//TRUE
checkBoolean(
"interval '2' second between " +
"interval '1' second and " +
"interval '3' second",
Boolean.TRUE);
checkBoolean(
"interval -'1.000001' second(6) between " +
"interval -'1.000000' second(6) and " +
"interval -'1.000002' second(6)",
Boolean.TRUE);
checkBoolean(
"interval '2' minute between " +
"interval '1' minute and " +
"interval '3' minute",
Boolean.TRUE);
checkBoolean(
"interval '-1:2' minute to second between " +
"interval '-1:1' minute to second and " +
"interval '-1:3' minute to second",
Boolean.TRUE);
checkBoolean(
"interval '1:1.000001' minute to second(6) between " +
"interval '1:1.000000' minute to second(6) and " +
"interval '1:1.000002' minute to second(6)",
Boolean.TRUE);
checkBoolean(
"interval -'2' hour between " +
"interval -'1' hour and " +
"interval -'3' hour",
Boolean.TRUE);
checkBoolean(
"interval '1:2' hour to minute between " +
"interval '1:1' hour to minute and " +
"interval '1:3' hour to minute",
Boolean.TRUE);
checkBoolean(
"interval '-1:2:3' hour to second between " +
"interval '-1:2:2' hour to second and " +
"interval '-1:2:4' hour to second",
Boolean.TRUE);
checkBoolean(
"interval '1:2:1.000003' hour to second(6) between " +
"interval '1:2:1.000002' hour to second(6) and " +
"interval '1:2:1.000004' hour to second(6)",
Boolean.TRUE);
checkBoolean(
"interval -'2' day between " +
"interval -'1' day and " +
"interval -'3' day",
Boolean.TRUE);
checkBoolean(
"interval '1 2' day to hour between " +
"interval '1 1' day to hour and " +
"interval '1 3' day to hour",
Boolean.TRUE);
checkBoolean(
"interval '-1 1:2' day to minute between " +
"interval '-1 1:1' day to minute and " +
"interval '-1 1:3' day to minute",
Boolean.TRUE);
checkBoolean(
"interval '1 1:1:2' day to second between " +
"interval '1 1:1:1' day to second and " +
"interval '1 1:1:3' day to second",
Boolean.TRUE);
checkBoolean(
"interval -'1 1:1:1.000002' day to second(6) between " +
"interval -'1 1:1:1.000001' day to second(6) and " +
"interval -'1 1:1:1.000003' day to second(6)",
Boolean.TRUE);
checkBoolean(
"interval '2' month between " +
"interval '1' month and " +
"interval '3' month",
Boolean.TRUE);
checkBoolean(
"interval '-2' year between " +
"interval '-1' year and " +
"interval '-3' year",
Boolean.TRUE);
checkBoolean(
"interval '1-2' year to month between " +
"interval '1-1' year to month and " +
"interval '1-3' year to month",
Boolean.TRUE);
//FALSE
checkBoolean(
"interval '1' second between " +
"interval '1' second and " +
"interval '3' second",
Boolean.FALSE);
checkBoolean(
"interval -'1.000001' second(6) between " +
"interval -'1.000001' second(6) and " +
"interval -'1.000002' second(6)",
Boolean.FALSE);
checkBoolean(
"interval '2' minute between " +
"interval '1' minute and " +
"interval '2' minute",
Boolean.FALSE);
checkBoolean(
"interval '-1:1' minute to second between " +
"interval '-1:1' minute to second and " +
"interval '-1:3' minute to second",
Boolean.FALSE);
checkBoolean(
"interval '1:1.000001' minute to second(6) between " +
"interval '1:1.000001' minute to second(6) and " +
"interval '1:1.000002' minute to second(6)",
Boolean.FALSE);
checkBoolean(
"interval -'2' hour between " +
"interval -'1' hour and " +
"interval -'2' hour",
Boolean.FALSE);
checkBoolean(
"interval '1:1' hour to minute between " +
"interval '1:1' hour to minute and " +
"interval '1:3' hour to minute",
Boolean.FALSE);
checkBoolean(
"interval '-1:2:3' hour to second between " +
"interval '-1:2:3' hour to second and " +
"interval '-1:2:4' hour to second",
Boolean.FALSE);
checkBoolean(
"interval '1:2:1.000003' hour to second(6) between " +
"interval '1:2:1.000002' hour to second(6) and " +
"interval '1:2:1.000003' hour to second(6)",
Boolean.FALSE);
checkBoolean(
"interval -'1' day between " +
"interval -'1' day and " +
"interval -'3' day",
Boolean.FALSE);
checkBoolean(
"interval '1 2' day to hour between " +
"interval '1 2' day to hour and " +
"interval '1 3' day to hour",
Boolean.FALSE);
checkBoolean(
"interval '-1 1:2' day to minute between " +
"interval '-1 1:1' day to minute and " +
"interval '-1 1:2' day to minute",
Boolean.FALSE);
checkBoolean(
"interval '1 1:1:1' day to second between " +
"interval '1 1:1:1' day to second and " +
"interval '1 1:1:3' day to second",
Boolean.FALSE);
checkBoolean(
"interval -'1 1:1:1.000002' day to second(6) between " +
"interval -'1 1:1:1.000002' day to second(6) and " +
"interval -'1 1:1:1.000003' day to second(6)",
Boolean.FALSE);
checkBoolean(
"interval '2' month between " +
"interval '1' month and " +
"interval '2' month",
Boolean.FALSE);
checkBoolean(
"interval '-1' year between " +
"interval '-1' year and " +
"interval '-3' year",
Boolean.FALSE);
checkBoolean(
"interval '1-2' year to month between " +
"interval '1-2' year to month and " +
"interval '1-3' year to month",
Boolean.FALSE);
//time & date
checkBoolean(
"time '01:23:45' between " +
"time '01:23:44' and " +
"time '01:23:46'",
Boolean.TRUE);
checkBoolean(
"time '01:23:45.000001' between " +
"time '01:23:45.000000' and " +
"time '01:23:45.000002'",
Boolean.TRUE);
checkBoolean(
"date '2007-01-01' between " +
"date '2006-12-31' and " +
"date '2007-01-02'",
Boolean.TRUE);
checkBoolean(
"timestamp '2007-01-01 01:23:45' between " +
"timestamp '2007-01-01 01:23:44' and " +
"timestamp '2007-01-01 01:23:46'",
Boolean.TRUE);
checkBoolean(
"timestamp '2007-01-01 01:23:45.000001' between " +
"timestamp '2007-01-01 01:23:45.000000' and " +
"timestamp '2007-01-01 01:23:45.000002'",
Boolean.TRUE);
}
public void testNotBetween()
{
setFor(SqlStdOperatorTable.notBetweenOperator);
checkBoolean("2 not between 1 and 3", Boolean.FALSE);
checkBoolean("3 not between 1 and 3", Boolean.FALSE);
checkBoolean("4 not between 1 and 3", Boolean.TRUE);
checkBoolean(
"1.2e0 not between 1.1 and 1.3",
Boolean.FALSE);
checkBoolean("1.2e1 not between 1.1 and 1.3", Boolean.TRUE);
checkBoolean("1.5e0 not between 2 and 3", Boolean.TRUE);
checkBoolean("1.5e0 not between 2e0 and 3e0", Boolean.TRUE);
}
private String getCastString(
String value,
String targetType,
boolean errorLoc)
{
if (errorLoc) {
value = "^" + value + "^";
}
return "cast(" + value + " as " + targetType + ")";
}
private void checkCastToApproxOkay(
String value,
String targetType,
double expected,
double delta)
{
checkScalarApprox(
getCastString(value, targetType, false),
targetType + " NOT NULL",
expected,
delta);
}
private void checkCastToStringOkay(
String value,
String targetType,
String expected)
{
checkString(
getCastString(value, targetType, false),
expected,
targetType + " NOT NULL");
}
private void checkCastToScalarOkay(
String value,
String targetType,
String expected)
{
checkScalarExact(
getCastString(value, targetType, false),
targetType + " NOT NULL",
expected);
}
private void checkCastToScalarOkay(String value, String targetType)
{
checkCastToScalarOkay(value, targetType, value);
}
private void checkCastFails(
String value,
String targetType,
String expectedError,
boolean runtime)
{
checkFails(
getCastString(value, targetType, !runtime),
expectedError,
runtime);
}
private void checkCastToString(String value, String type, String expected)
{
String spaces = " ";
if (expected == null) {
expected = value.trim();
}
int len = expected.length();
if (type != null) {
value = getCastString(value, type, false);
}
checkCastFails(
value,
"VARCHAR(" + (len - 1) + ")",
stringTruncMessage,
true);
checkCastToStringOkay(value, "VARCHAR(" + len + ")", expected);
checkCastToStringOkay(value, "VARCHAR(" + (len + 5) + ")", expected);
checkCastFails(
value,
"CHAR(" + (len - 1) + ")",
stringTruncMessage,
true);
checkCastToStringOkay(value, "CHAR(" + len + ")", expected);
checkCastToStringOkay(
value,
"CHAR(" + (len + 5) + ")",
expected + spaces);
}
public void testCastChar()
{
setFor(SqlStdOperatorTable.castFunc);
// "CHAR" is shorthand for "CHAR(1)"
checkString("CAST('abc' AS CHAR)", "a", "CHAR(1) NOT NULL");
checkString(
"CAST('abc' AS VARCHAR)",
"a",
"VARCHAR(1) NOT NULL");
}
public void testCastExactNumerics()
{
setFor(SqlStdOperatorTable.castFunc);
// Test casting for min,max, out of range for exact numeric types
for (int i = 0; i < numericTypeNames.length; i++) {
String type = numericTypeNames[i];
if (type.equalsIgnoreCase("DOUBLE")
|| type.equalsIgnoreCase("FLOAT")
|| type.equalsIgnoreCase("REAL"))
{
// Skip approx types
continue;
}
// Convert from literal to type
checkCastToScalarOkay(maxNumericStrings[i], type);
checkCastToScalarOkay(minNumericStrings[i], type);
// Overflow test
if (type.equalsIgnoreCase("BIGINT")) {
// Literal of range
checkCastFails(
maxOverflowNumericStrings[i],
type,
literalOutOfRangeMessage,
false);
checkCastFails(
minOverflowNumericStrings[i],
type,
literalOutOfRangeMessage,
false);
} else {
checkCastFails(
maxOverflowNumericStrings[i],
type,
outOfRangeMessage,
true);
checkCastFails(
minOverflowNumericStrings[i],
type,
outOfRangeMessage,
true);
}
// Convert from string to type
checkCastToScalarOkay(
"'" + maxNumericStrings[i] + "'",
type,
maxNumericStrings[i]);
checkCastToScalarOkay(
"'" + minNumericStrings[i] + "'",
type,
minNumericStrings[i]);
checkCastFails(
"'" + maxOverflowNumericStrings[i] + "'",
type,
outOfRangeMessage,
true);
checkCastFails(
"'" + minOverflowNumericStrings[i] + "'",
type,
outOfRangeMessage,
true);
// Convert from type to string
checkCastToString(maxNumericStrings[i], null, null);
checkCastToString(maxNumericStrings[i], type, null);
checkCastToString(minNumericStrings[i], null, null);
checkCastToString(minNumericStrings[i], type, null);
checkCastFails("'notnumeric'", type, invalidCharMessage, true);
}
checkScalarExact(
"cast(1.0 as bigint)",
"BIGINT NOT NULL",
"1");
checkScalarExact("cast(1.0 as int)", "1");
}
public void testCastApproxNumerics()
{
setFor(SqlStdOperatorTable.castFunc);
// Test casting for min,max, out of range for approx numeric types
for (int i = 0; i < numericTypeNames.length; i++) {
String type = numericTypeNames[i];
boolean isFloat;
if (type.equalsIgnoreCase("DOUBLE")
|| type.equalsIgnoreCase("FLOAT"))
{
isFloat = false;
} else if (type.equalsIgnoreCase("REAL")) {
isFloat = true;
} else {
// Skip non-approx types
continue;
}
// Convert from literal to type
checkCastToApproxOkay(
maxNumericStrings[i],
type,
Double.parseDouble(maxNumericStrings[i]),
isFloat ? 1E32 : 0);
checkCastToApproxOkay(
minNumericStrings[i],
type,
Double.parseDouble(minNumericStrings[i]),
0);
if (isFloat) {
checkCastFails(
maxOverflowNumericStrings[i],
type,
outOfRangeMessage,
true);
} else {
// Double: Literal out of range
checkCastFails(
maxOverflowNumericStrings[i],
type,
literalOutOfRangeMessage,
false);
}
// Underflow: goes to 0
checkCastToApproxOkay(minOverflowNumericStrings[i], type, 0, 0);
// Convert from string to type
checkCastToApproxOkay(
"'" + maxNumericStrings[i] + "'",
type,
Double.parseDouble(maxNumericStrings[i]),
isFloat ? 1E32 : 0);
checkCastToApproxOkay(
"'" + minNumericStrings[i] + "'",
type,
Double.parseDouble(minNumericStrings[i]),
0);
checkCastFails(
"'" + maxOverflowNumericStrings[i] + "'",
type,
outOfRangeMessage,
true);
// Underflow: goes to 0
checkCastToApproxOkay(
"'" + minOverflowNumericStrings[i] + "'",
type,
0,
0);
// Convert from type to string
// Treated as DOUBLE
checkCastToString(
maxNumericStrings[i],
null,
isFloat ? null : "1.79769313486231E308");
/*
// TODO: The following tests are slightly different depending on //
whether the java or fennel calc are used. // Try to make them
the same if (FennelCalc) { // Treated as FLOAT or DOUBLE
checkCastToString(maxNumericStrings[i], type, isFloat?
"3.402824E38": "1.797693134862316E308"); // Treated as DOUBLE
checkCastToString(minNumericStrings[i], null, isFloat? null:
"4.940656458412465E-324"); // Treated as FLOAT or DOUBLE
checkCastToString(minNumericStrings[i], type, isFloat?
"1.401299E-45": "4.940656458412465E-324"); } else if (JavaCalc) {
// Treated as FLOAT or DOUBLE
checkCastToString(maxNumericStrings[i], type, isFloat?
"3.402823E38": "1.797693134862316E308"); // Treated as DOUBLE
checkCastToString(minNumericStrings[i], null, isFloat? null:
null); // Treated as FLOAT or DOUBLE
checkCastToString(minNumericStrings[i], type, isFloat?
"1.401298E-45": null); }
*/
checkCastFails("'notnumeric'", type, invalidCharMessage, true);
}
checkScalarExact(
"cast(1.0e0 as bigint)",
"BIGINT NOT NULL",
"1");
checkScalarExact("cast(1.0e0 as int)", "1");
}
public void testCastDecimalToInteger()
{
setFor(SqlStdOperatorTable.castFunc);
// decimal to integer
checkScalarExact("cast(1.25 as integer)", "1");
checkScalarExact("cast(-1.25 as integer)", "-1");
checkScalarExact("cast(1.75 as integer)", "2");
checkScalarExact("cast(-1.75 as integer)", "-2");
checkScalarExact("cast(1.5 as integer)", "2");
checkScalarExact("cast(-1.5 as integer)", "-2");
}
public void testCastDecimalToDecimal()
{
setFor(SqlStdOperatorTable.castFunc);
// decimal to decimal
checkScalarExact(
"cast(1.29 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.3");
checkScalarExact(
"cast(1.25 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.3");
checkScalarExact(
"cast(1.21 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.2");
checkScalarExact(
"cast(-1.29 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.3");
checkScalarExact(
"cast(-1.25 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.3");
checkScalarExact(
"cast(-1.21 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.2");
// decimal to decimal
checkScalarExact(
"cast(1.29 as decimal(7,5))",
"DECIMAL(7, 5) NOT NULL",
"1.29000");
checkScalarExact(
"cast(-1.21 as decimal(7,5))",
"DECIMAL(7, 5) NOT NULL",
"-1.21000");
checkScalarExact(
"cast(-1.21 as decimal)",
"DECIMAL(19, 0) NOT NULL",
"-1");
// 9.99 round to 10.0, should give out of range error
checkFails(
"cast(9.99 as decimal(2,1))",
outOfRangeMessage,
true);
}
public void testCastDecimalToDoubleToInteger()
{
setFor(SqlStdOperatorTable.castFunc);
checkScalarExact(
"cast( cast(1.25 as double) as integer)",
"1");
checkScalarExact(
"cast( cast(-1.25 as double) as integer)",
"-1");
checkScalarExact(
"cast( cast(1.75 as double) as integer)",
"2");
checkScalarExact(
"cast( cast(-1.75 as double) as integer)",
"-2");
checkScalarExact(
"cast( cast(1.5 as double) as integer)",
"2");
checkScalarExact(
"cast( cast(-1.5 as double) as integer)",
"-2");
}
public void testCastToDouble()
{
setFor(SqlStdOperatorTable.castFunc);
checkScalarApprox(
"cast(1 as double)",
"DOUBLE NOT NULL",
1,
0);
checkScalarApprox(
"cast(1.0 as double)",
"DOUBLE NOT NULL",
1,
0);
checkScalarApprox(
"cast(-5.9 as double)",
"DOUBLE NOT NULL",
-5.9,
0);
}
public void testCastNull()
{
setFor(SqlStdOperatorTable.castFunc);
// null
checkNull("cast(null as decimal(4,3))");
checkNull("cast(null as double)");
checkNull("cast(null as varchar(10))");
checkNull("cast(null as char(10))");
}
public void testCastDateTime()
{
// Test cast for date/time/timestamp
setFor(SqlStdOperatorTable.castFunc);
checkScalar(
"cast(TIMESTAMP '1945-02-24 12:42:25.34' as TIMESTAMP)",
"1945-02-24 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
checkScalar(
"cast(TIME '12:42:25.34' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
// test rounding
checkScalar(
"cast(TIME '12:42:25.9' as TIME)",
"12:42:26",
"TIME(0) NOT NULL");
if (Bug.Frg282Fixed) {
// test precision
checkScalar(
"cast(TIME '12:42:25.34' as TIME(2))",
"12:42:25.34",
"TIME(2) NOT NULL");
}
checkScalar(
"cast(DATE '1945-02-24' as DATE)",
"1945-02-24",
"DATE NOT NULL");
// timestamp <-> time
checkScalar(
"cast(TIMESTAMP '1945-02-24 12:42:25.34' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
// Generate the current date as a string, e.g. "2007-04-18". The value
// is guaranteed to be good for at least 2 minutes, which should give
// us time to run the rest of the tests.
final String today;
while (true) {
final Calendar cal = Calendar.getInstance();
if ((cal.get(Calendar.HOUR_OF_DAY) == 23)
&& (cal.get(Calendar.MINUTE) >= 58))
{
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
// ignore
}
} else {
today =
new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
break;
}
}
// Note: Casting to time(0) should lose date info and fractional
// seconds, then casting back to timestamp should initialize to
// current_date.
if (Bug.Fnl66Fixed) {
checkScalar(
"cast(cast(TIMESTAMP '1945-02-24 12:42:25.34' as TIME) as TIMESTAMP)",
today + " 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
checkScalar(
"cast(TIME '12:42:25.34' as TIMESTAMP)",
today + " 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
}
// timestamp <-> date
checkScalar(
"cast(TIMESTAMP '1945-02-24 12:42:25.34' as DATE)",
"1945-02-24",
"DATE NOT NULL");
// Note: casting to Date discards Time fields
checkScalar(
"cast(cast(TIMESTAMP '1945-02-24 12:42:25.34' as DATE) as TIMESTAMP)",
"1945-02-24 00:00:00.0",
"TIMESTAMP(0) NOT NULL");
// TODO: precision should not be included
checkScalar(
"cast(DATE '1945-02-24' as TIMESTAMP)",
"1945-02-24 00:00:00.0",
"TIMESTAMP(0) NOT NULL");
// time <-> string
checkCastToString("TIME '12:42:25'", null, "12:42:25");
checkCastToString("TIME '12:42:25.34'", null, "12:42:25.34");
checkScalar(
"cast('12:42:25' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
checkScalar(
"cast('1:42:25' as TIME)",
"01:42:25",
"TIME(0) NOT NULL");
checkScalar(
"cast('1:2:25' as TIME)",
"01:02:25",
"TIME(0) NOT NULL");
checkScalar(
"cast(' 12:42:25 ' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
checkScalar(
"cast('12:42:25.34' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
if (Bug.Frg282Fixed) {
checkScalar(
"cast('12:42:25.34' as TIME(2))",
"12:42:25.34",
"TIME(2) NOT NULL");
}
checkFails(
"cast('nottime' as TIME)",
badDatetimeMessage,
true);
checkFails(
"cast('1241241' as TIME)",
badDatetimeMessage,
true);
checkFails(
"cast('12:54:78' as TIME)",
badDatetimeMessage,
true);
// timestamp <-> string
// TODO: Java calc displays ".0" while Fennel does not
checkCastToString(
"TIMESTAMP '1945-02-24 12:42:25'",
null,
"1945-02-24 12:42:25.0");
// TODO: casting allows one to discard precision without error
checkCastToString(
"TIMESTAMP '1945-02-24 12:42:25.34'",
null,
"1945-02-24 12:42:25.34");
checkScalar(
"cast('1945-02-24 12:42:25' as TIMESTAMP)",
"1945-02-24 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
checkScalar(
"cast('1945-2-2 12:2:5' as TIMESTAMP)",
"1945-02-02 12:02:05.0",
"TIMESTAMP(0) NOT NULL");
checkScalar(
"cast(' 1945-02-24 12:42:25 ' as TIMESTAMP)",
"1945-02-24 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
checkScalar(
"cast('1945-02-24 12:42:25.34' as TIMESTAMP)",
"1945-02-24 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
if (Bug.Frg282Fixed) {
checkScalar(
"cast('1945-02-24 12:42:25.34' as TIMESTAMP(2))",
"1945-02-24 12:42:25.34",
"TIMESTAMP(2) NOT NULL");
}
checkFails(
"cast('nottime' as TIMESTAMP)",
badDatetimeMessage,
true);
checkFails(
"cast('1241241' as TIMESTAMP)",
badDatetimeMessage,
true);
checkFails(
"cast('1945-20-24 12:42:25.34' as TIMESTAMP)",
badDatetimeMessage,
true);
checkFails(
"cast('1945-01-24 25:42:25.34' as TIMESTAMP)",
badDatetimeMessage,
true);
// date <-> string
checkCastToString("DATE '1945-02-24'", null, "1945-02-24");
checkCastToString("DATE '1945-2-24'", null, "1945-02-24");
checkScalar(
"cast('1945-02-24' as DATE)",
"1945-02-24",
"DATE NOT NULL");
checkScalar(
"cast(' 1945-02-24 ' as DATE)",
"1945-02-24",
"DATE NOT NULL");
checkFails(
"cast('notdate' as DATE)",
badDatetimeMessage,
true);
checkFails(
"cast('52534253' as DATE)",
badDatetimeMessage,
true);
checkFails(
"cast('1945-30-24' as DATE)",
badDatetimeMessage,
true);
// cast null
checkNull("cast(null as date)");
checkNull("cast(null as timestamp)");
checkNull("cast(null as time)");
checkNull("cast(cast(null as varchar(10)) as time)");
checkNull("cast(cast(null as varchar(10)) as date)");
checkNull("cast(cast(null as varchar(10)) as timestamp)");
checkNull("cast(cast(null as date) as timestamp)");
checkNull("cast(cast(null as time) as timestamp)");
checkNull("cast(cast(null as timestamp) as date)");
checkNull("cast(cast(null as timestamp) as time)");
}
public void testCastInterval()
{
setFor(SqlStdOperatorTable.castFunc);
checkScalar(
"cast(interval '1' second as interval second)",
"+1",
"INTERVAL SECOND NOT NULL");
checkScalar(
"cast(interval '1' second as interval minute to second)",
"+0:01",
"INTERVAL MINUTE TO SECOND NOT NULL");
checkScalar(
"cast(interval '1' second as interval hour to second)",
"+0:00:01",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"cast(interval '1' second as interval day to second)",
"+0 0:00:01",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1' minute as interval minute)",
"+1",
"INTERVAL MINUTE NOT NULL");
checkScalar(
"cast(interval '1' minute as interval minute to second)",
"+1:00",
"INTERVAL MINUTE TO SECOND NOT NULL");
checkScalar(
"cast(interval '1' minute as interval hour to second)",
"+0:01:00",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"cast(interval '1' minute as interval hour to minute)",
"+0:01",
"INTERVAL HOUR TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' minute as interval day to second)",
"+0 0:01:00",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1' minute as interval day to minute)",
"+0 0:01",
"INTERVAL DAY TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' hour as interval hour)",
"+1",
"INTERVAL HOUR NOT NULL");
checkScalar(
"cast(interval '1' hour as interval hour to second)",
"+1:00:00",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"cast(interval '1' hour as interval hour to minute)",
"+1:00",
"INTERVAL HOUR TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' hour as interval day to second)",
"+0 1:00:00",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1' hour as interval day to minute)",
"+0 1:00",
"INTERVAL DAY TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' hour as interval day to hour)",
"+0 1",
"INTERVAL DAY TO HOUR NOT NULL");
checkScalar(
"cast(interval '1' day as interval day)",
"+1",
"INTERVAL DAY NOT NULL");
checkScalar(
"cast(interval '1' day as interval day to second)",
"+1 0:00:00",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1' day as interval day to minute)",
"+1 0:00",
"INTERVAL DAY TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' day as interval day to hour)",
"+1 0",
"INTERVAL DAY TO HOUR NOT NULL");
checkScalar(
"cast(interval '1:02' minute to second as interval minute to second)",
"+1:02",
"INTERVAL MINUTE TO SECOND NOT NULL");
checkScalar(
"cast(interval '1:02' minute to second as interval hour to second)",
"+0:01:02",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"cast(interval '1:02' minute to second as interval day to second)",
"+0 0:01:02",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1:02:03' hour to second as interval hour to second)",
"+1:02:03",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"cast(interval '1:02:03' hour to second as interval day to second)",
"+0 1:02:03",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1:02' hour to minute as interval hour to second)",
"+1:02:00",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"cast(interval '1:02' hour to minute as interval hour to minute)",
"+1:02",
"INTERVAL HOUR TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1:02' hour to minute as interval day to second)",
"+0 1:02:00",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1:02' hour to minute as interval day to minute)",
"+0 1:02",
"INTERVAL DAY TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1 2:3:4' day to second as interval day to second)",
"+1 2:03:04",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1 2:3' day to minute as interval day to minute)",
"+1 2:03",
"INTERVAL DAY TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1 2:3' day to minute as interval day to second)",
"+1 2:03:00",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1 2' day to hour as interval day to hour)",
"+1 2",
"INTERVAL DAY TO HOUR NOT NULL");
checkScalar(
"cast(interval '1 2' day to hour as interval day to second)",
"+1 2:00:00",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"cast(interval '1 2' day to hour as interval day to minute)",
"+1 2:00",
"INTERVAL DAY TO MINUTE NOT NULL");
//month and year
checkScalar(
"cast(interval '1' month as interval month)",
"+1",
"INTERVAL MONTH NOT NULL");
checkScalar(
"cast(interval '1' month as interval year to month)",
"+0-1",
"INTERVAL YEAR TO MONTH NOT NULL");
checkScalar(
"cast(interval '1' year as interval year)",
"+1",
"INTERVAL YEAR NOT NULL");
checkScalar(
"cast(interval '1' year as interval year to month)",
"+1-0",
"INTERVAL YEAR TO MONTH NOT NULL");
checkScalar(
"cast(interval '1-2' year to month as interval year to month)",
"+1-2",
"INTERVAL YEAR TO MONTH NOT NULL");
//day hour minute second with precision
checkScalar(
"cast(interval '1.123' second as interval second(6))",
"+1.123000",
"INTERVAL SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1.123' second as interval second(8,6))",
"+1.123000",
"INTERVAL SECOND(8, 6) NOT NULL");
checkScalar(
"cast(interval '1.123' second as interval minute(3) to second(6))",
"+0:01.123000",
"INTERVAL MINUTE(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1.123' second as interval hour(3) to second(6))",
"+0:00:01.123000",
"INTERVAL HOUR(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1.123' second as interval day(3) to second(6))",
"+0 0:00:01.123000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1' minute as interval minute(3))",
"+1",
"INTERVAL MINUTE(3) NOT NULL");
checkScalar(
"cast(interval '1' minute as interval minute(3) to second(6))",
"+1:00.000000",
"INTERVAL MINUTE(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1' minute as interval hour(3) to second(6))",
"+0:01:00.000000",
"INTERVAL HOUR(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1' minute as interval hour(3) to minute)",
"+0:01",
"INTERVAL HOUR(3) TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' minute as interval day(3) to second(6))",
"+0 0:01:00.000000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1' minute as interval day(3) to minute)",
"+0 0:01",
"INTERVAL DAY(3) TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' hour as interval hour(3))",
"+1",
"INTERVAL HOUR(3) NOT NULL");
checkScalar(
"cast(interval '1' hour as interval hour(3) to second(6))",
"+1:00:00.000000",
"INTERVAL HOUR(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1' hour as interval hour(3) to minute)",
"+1:00",
"INTERVAL HOUR(3) TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' hour as interval day(3) to second(6))",
"+0 1:00:00.000000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1' hour as interval day(3) to minute)",
"+0 1:00",
"INTERVAL DAY(3) TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' hour as interval day(3) to hour)",
"+0 1",
"INTERVAL DAY(3) TO HOUR NOT NULL");
checkScalar(
"cast(interval '1' day as interval day(3))",
"+1",
"INTERVAL DAY(3) NOT NULL");
checkScalar(
"cast(interval '1' day as interval day(3) to second(6))",
"+1 0:00:00.000000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1' day as interval day(3) to minute)",
"+1 0:00",
"INTERVAL DAY(3) TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' day as interval day(3) to hour)",
"+1 0",
"INTERVAL DAY(3) TO HOUR NOT NULL");
checkScalar(
"cast(interval '1:02.123' minute to second(3) as interval minute(3) to second(6))",
"+1:02.123000",
"INTERVAL MINUTE(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1:02.123' minute to second(3) as interval hour(3) to second(6))",
"+0:01:02.123000",
"INTERVAL HOUR(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1:02.123' minute to second(3) as interval day(3) to second(6))",
"+0 0:01:02.123000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1:02:03.123' hour to second(3) as interval hour(3) to second(6))",
"+1:02:03.123000",
"INTERVAL HOUR(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1:02:03.123' hour to second(3) as interval day(3) to second(6))",
"+0 1:02:03.123000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1:02' hour to minute as interval hour(3) to second(6))",
"+1:02:00.000000",
"INTERVAL HOUR(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1:02' hour to minute as interval hour(3) to minute)",
"+1:02",
"INTERVAL HOUR(3) TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1:02' hour to minute as interval day(3) to second(6))",
"+0 1:02:00.000000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1:02' hour to minute as interval day(3) to minute)",
"+0 1:02",
"INTERVAL DAY(3) TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1 2:3:4.123' day to second(3) as interval day(3) to second(6))",
"+1 2:03:04.123000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1 2:3' day to minute as interval day(3) to minute)",
"+1 2:03",
"INTERVAL DAY(3) TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1 2:3' day to minute as interval day(3) to second(6))",
"+1 2:03:00.000000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1 2' day to hour as interval day(3) to hour)",
"+1 2",
"INTERVAL DAY(3) TO HOUR NOT NULL");
checkScalar(
"cast(interval '1 2' day to hour as interval day(3) to second(6))",
"+1 2:00:00.000000",
"INTERVAL DAY(3) TO SECOND(6) NOT NULL");
checkScalar(
"cast(interval '1 2' day to hour as interval day(3) to minute)",
"+1 2:00",
"INTERVAL DAY(3) TO MINUTE NOT NULL");
checkScalar(
"cast(interval '1' month(3) as interval month(5))",
"+1",
"INTERVAL MONTH(5) NOT NULL");
checkScalar(
"cast(interval '1' month(3) as interval year(3) to month)",
"+0-1",
"INTERVAL YEAR(3) TO MONTH NOT NULL");
checkScalar(
"cast(interval '1' year(3) as interval year(5))",
"+1",
"INTERVAL YEAR(5) NOT NULL");
checkScalar(
"cast(interval '1' year(3) as interval year(5) to month)",
"+1-0",
"INTERVAL YEAR(5) TO MONTH NOT NULL");
checkScalar(
"cast(interval '1-2' year(3) to month as interval year(5) to month)",
"+1-2",
"INTERVAL YEAR(5) TO MONTH NOT NULL");
//todo: add the following casts:
//string as any of the above
//exact numeric to second
//exact numeric to minute
//exact numeric to hour
//exact numeric to day
//exact numeric to month
//exact numeric to year
//exact numeric to second(p,s)
//exact numeric to second(s)
//exact numeric to minute(p)
//exact numeric to hour(p)
//exact numeric to day(p)
//exact numeric to month(p)
//exact numeric to year(p)
}
public void testCastExactString()
{
setFor(SqlStdOperatorTable.castFunc);
// string to decimal
checkScalarExact(
"cast('1.29' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.3");
checkScalarExact(
"cast(' 1.25 ' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.3");
checkScalarExact(
"cast('1.21' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.2");
checkScalarExact(
"cast(' -1.29 ' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.3");
checkScalarExact(
"cast('-1.25' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.3");
checkScalarExact(
"cast(' -1.21 ' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.2");
checkFails(
"cast(' -1.21e' as decimal(2,1))",
invalidCharMessage,
true);
// decimal to string
checkString(
"cast(1.29 as varchar(10))",
"1.29",
"VARCHAR(10) NOT NULL");
checkString(
"cast(.48 as varchar(10))",
".48",
"VARCHAR(10) NOT NULL");
checkFails(
"cast(2.523 as char(2))",
stringTruncMessage,
true);
checkString(
"cast(-0.29 as varchar(10))",
"-.29",
"VARCHAR(10) NOT NULL");
checkString(
"cast(-1.29 as varchar(10))",
"-1.29",
"VARCHAR(10) NOT NULL");
// string to integer
checkScalarExact("cast('6543' as integer)", "6543");
if (Bug.Frg26Fixed) {
checkScalarExact("cast(' -123 ' as int)", "-123");
}
checkScalarExact(
"cast('654342432412312' as bigint)",
"BIGINT NOT NULL",
"654342432412312");
// integer to string
checkString(
"cast(9354 as varchar(10))",
"9354",
"VARCHAR(10) NOT NULL");
}
public void testCastApproxString()
{
setFor(SqlStdOperatorTable.castFunc);
// string to double/float/real
checkScalarApprox(
"cast('1' as double)",
"DOUBLE NOT NULL",
1,
0);
checkScalarApprox(
"cast('2.3' as float)",
"FLOAT NOT NULL",
2.3,
0);
checkScalarApprox(
"cast('-10.2' as real)",
"REAL NOT NULL",
-10.2,
0);
checkScalarApprox(
"cast('4e2' as double)",
"DOUBLE NOT NULL",
400,
0);
checkScalarApprox(
"cast('2.1e1' as float)",
"FLOAT NOT NULL",
21,
0);
checkScalarApprox(
"cast('-12e-1' as real)",
"REAL NOT NULL",
-1.2,
0);
checkScalarApprox(
"cast(' -43 ' as double)",
"DOUBLE NOT NULL",
-43,
0);
checkScalarApprox(
"cast(' 23e-1 ' as float)",
"FLOAT NOT NULL",
2.3,
0);
checkScalarApprox(
"cast(' 123e+1 ' as real)",
"REAL NOT NULL",
1230,
0);
// double/float/real to string
checkString(
"cast(0e0 as varchar(5))",
"0E0",
"VARCHAR(5) NOT NULL");
checkString(
"cast(4e1 as varchar(5))",
"4E1",
"VARCHAR(5) NOT NULL");
checkString(
"cast(45e1 as varchar(5))",
"4.5E2",
"VARCHAR(5) NOT NULL");
checkString(
"cast(4.6834e0 as varchar(50))",
"4.6834E0",
"VARCHAR(50) NOT NULL");
checkString(
"cast(4683442.3432498375e0 as varchar(20))",
"4.683442343249838E6",
"VARCHAR(20) NOT NULL");
checkString(
"cast(cast(0.1 as real) as char(10))",
"1E-1 ",
"CHAR(10) NOT NULL");
checkString(
"cast(cast(-0.0036 as float) as char(10))",
"-3.6E-3 ",
"CHAR(10) NOT NULL");
checkString(
"cast(cast(3.23e0 as real) as varchar(20))",
"3.23E0",
"VARCHAR(20) NOT NULL");
checkString(
"cast(cast(5.2365439 as real) as varchar(20))",
"5.236544E0",
"VARCHAR(20) NOT NULL");
checkString(
"cast(-1e0 as char(6))",
"-1E0 ",
"CHAR(6) NOT NULL");
checkFails(
"cast(1.3243232e0 as varchar(4))",
stringTruncMessage,
true);
checkFails(
"cast(1.9e5 as char(4))",
stringTruncMessage,
true);
}
public void testCastBooleanString()
{
setFor(SqlStdOperatorTable.castFunc);
// boolean to string (char)
checkString(
"cast(true as char(4))",
"TRUE",
"CHAR(4) NOT NULL");
checkString(
"cast(false as char(5))",
"FALSE",
"CHAR(5) NOT NULL");
checkString(
"cast(true as char(8))",
"TRUE ",
"CHAR(8) NOT NULL");
checkString(
"cast(false as char(8))",
"FALSE ",
"CHAR(8) NOT NULL");
checkFails(
"cast(true as char(3))",
invalidCharMessage,
true);
checkFails(
"cast(false as char(4))",
invalidCharMessage,
true);
// boolean to string (varchar)
checkString(
"cast(true as varchar(4))",
"TRUE",
"VARCHAR(4) NOT NULL");
checkString(
"cast(false as varchar(5))",
"FALSE",
"VARCHAR(5) NOT NULL");
checkString(
"cast(true as varchar(8))",
"TRUE",
"VARCHAR(8) NOT NULL");
checkString(
"cast(false as varchar(8))",
"FALSE",
"VARCHAR(8) NOT NULL");
checkFails(
"cast(true as varchar(3))",
invalidCharMessage,
true);
checkFails(
"cast(false as varchar(4))",
invalidCharMessage,
true);
// string to boolean
checkBoolean("cast('true' as boolean)", Boolean.TRUE);
checkBoolean("cast('false' as boolean)", Boolean.FALSE);
checkBoolean("cast(' trUe' as boolean)", Boolean.TRUE);
checkBoolean("cast(' fALse' as boolean)", Boolean.FALSE);
checkFails(
"cast('unknown' as boolean)",
invalidCharMessage,
true);
checkFails(
"cast('blah' as boolean)",
invalidCharMessage,
true);
checkBoolean(
"cast(cast('true' as varchar(10)) as boolean)",
Boolean.TRUE);
checkBoolean(
"cast(cast('false' as varchar(10)) as boolean)",
Boolean.FALSE);
checkFails(
"cast(cast('blah' as varchar(10)) as boolean)",
invalidCharMessage,
true);
}
public void testCase()
{
setFor(SqlStdOperatorTable.caseOperator);
checkScalarExact("case when 'a'='a' then 1 end", "1");
checkString(
"case 2 when 1 then 'a' when 2 then 'bcd' end",
"bcd",
"CHAR(3)");
checkString(
"case 1 when 1 then 'a' when 2 then 'bcd' end",
"a ",
"CHAR(3)");
checkString(
"case 1 when 1 then cast('a' as varchar(1)) "
+ "when 2 then cast('bcd' as varchar(3)) end",
"a",
"VARCHAR(3)");
checkScalarExact(
"case 2 when 1 then 11.2 when 2 then 4.543 else null end",
"DECIMAL(5, 3)",
"4.543");
checkScalarExact(
"case 1 when 1 then 11.2 when 2 then 4.543 else null end",
"DECIMAL(5, 3)",
"11.200");
checkScalarExact("case 'a' when 'a' then 1 end", "1");
checkScalarApprox(
"case 1 when 1 then 11.2e0 when 2 then cast(4 as bigint) else 3 end",
"DOUBLE NOT NULL",
11.2,
0);
checkScalarApprox(
"case 1 when 1 then 11.2e0 when 2 then 4 else null end",
"DOUBLE",
11.2,
0);
checkScalarApprox(
"case 2 when 1 then 11.2e0 when 2 then 4 else null end",
"DOUBLE",
4,
0);
checkScalarApprox(
"case 1 when 1 then 11.2e0 when 2 then 4.543 else null end",
"DOUBLE",
11.2,
0);
checkScalarApprox(
"case 2 when 1 then 11.2e0 when 2 then 4.543 else null end",
"DOUBLE",
4.543,
0);
checkNull("case 'a' when 'b' then 1 end");
checkScalarExact(
"case when 'a'=cast(null as varchar(1)) then 1 else 2 end",
"2");
if (todo) {
checkScalar(
"case 1 when 1 then row(1,2) when 2 then row(2,3) end",
"ROW(INTEGER NOT NULL, INTEGER NOT NULL)",
"row(1,2)");
checkScalar(
"case 1 when 1 then row('a','b') when 2 then row('ab','cd') end",
"ROW(CHAR(2) NOT NULL, CHAR(2) NOT NULL)",
"row('a ','b ')");
}
// TODO: Check case with multisets
}
public void testCaseType()
{
setFor(SqlStdOperatorTable.caseOperator);
checkType(
"case 1 when 1 then current_timestamp else null end",
"TIMESTAMP(0)");
checkType(
"case 1 when 1 then current_timestamp else current_timestamp end",
"TIMESTAMP(0) NOT NULL");
checkType(
"case when true then current_timestamp else null end",
"TIMESTAMP(0)");
checkType(
"case when true then current_timestamp end",
"TIMESTAMP(0)");
checkType(
"case 'x' when 'a' then 3 when 'b' then null else 4.5 end",
"DECIMAL(11, 1)");
}
public void testJdbcFn()
{
setFor(new SqlJdbcFunctionCall("dummy"));
}
public void testSelect()
{
setFor(SqlStdOperatorTable.selectOperator);
check(
"select * from (values(1))",
AbstractSqlTester.IntegerTypeChecker,
"1",
0);
// check return type on scalar subquery in select list. Note return
// type is always nullable even if subquery select value is NOT NULL.
if (Bug.Frg189Fixed) {
checkType(
"SELECT *,(SELECT * FROM (VALUES(1))) FROM (VALUES(2))",
"RecordType(INTEGER NOT NULL EXPR$0, INTEGER EXPR$1) NOT NULL");
checkType(
"SELECT *,(SELECT * FROM (VALUES(CAST(10 as BIGINT)))) "
+ "FROM (VALUES(CAST(10 as bigint)))",
"RecordType(BIGINT NOT NULL EXPR$0, BIGINT EXPR$1) NOT NULL");
checkType(
" SELECT *,(SELECT * FROM (VALUES(10.5))) FROM (VALUES(10.5))",
"RecordType(DECIMAL(3, 1) NOT NULL EXPR$0, DECIMAL(3, 1) EXPR$1) NOT NULL");
checkType(
"SELECT *,(SELECT * FROM (VALUES('this is a char'))) "
+ "FROM (VALUES('this is a char too'))",
"RecordType(CHAR(18) NOT NULL EXPR$0, CHAR(14) EXPR$1) NOT NULL");
checkType(
"SELECT *,(SELECT * FROM (VALUES(true))) FROM (values(false))",
"RecordType(BOOLEAN NOT NULL EXPR$0, BOOLEAN EXPR$1) NOT NULL");
checkType(
" SELECT *,(SELECT * FROM (VALUES(cast('abcd' as varchar(10))))) "
+ "FROM (VALUES(CAST('abcd' as varchar(10))))",
"RecordType(VARCHAR(10) NOT NULL EXPR$0, VARCHAR(10) EXPR$1) NOT NULL");
checkType(
"SELECT *,"
+ " (SELECT * FROM (VALUES(TIMESTAMP '2006-01-01 12:00:05'))) "
+ "FROM (VALUES(TIMESTAMP '2006-01-01 12:00:05'))",
"RecordType(TIMESTAMP(0) NOT NULL EXPR$0, TIMESTAMP(0) EXPR$1) NOT NULL");
}
}
public void testLiteralChain()
{
setFor(SqlStdOperatorTable.literalChainOperator);
checkString(
"'buttered'\n' toast'",
"buttered toast",
"CHAR(14) NOT NULL");
checkString(
"'corned'\n' beef'\n' on'\n' rye'",
"corned beef on rye",
"CHAR(18) NOT NULL");
checkString(
"_latin1'Spaghetti'\n' all''Amatriciana'",
"Spaghetti all'Amatriciana",
"CHAR(25) NOT NULL");
checkBoolean("x'1234'\n'abcd' = x'1234abcd'", Boolean.TRUE);
checkBoolean("x'1234'\n'' = x'1234'", Boolean.TRUE);
checkBoolean("x''\n'ab' = x'ab'", Boolean.TRUE);
}
public void testRow()
{
setFor(SqlStdOperatorTable.rowConstructor);
}
public void testAndOperator()
{
setFor(SqlStdOperatorTable.andOperator);
checkBoolean("true and false", Boolean.FALSE);
checkBoolean("true and true", Boolean.TRUE);
checkBoolean(
"cast(null as boolean) and false",
Boolean.FALSE);
checkBoolean(
"false and cast(null as boolean)",
Boolean.FALSE);
checkNull("cast(null as boolean) and true");
checkBoolean("true and (not false)", Boolean.TRUE);
}
public void testConcatOperator()
{
setFor(SqlStdOperatorTable.concatOperator);
checkString(" 'a'||'b' ", "ab", "CHAR(2) NOT NULL");
if (todo) {
// not yet implemented
checkString(
" x'f'||x'f' ",
"X'FF",
"BINARY(1) NOT NULL");
checkNull("x'ff' || cast(null as varbinary)");
}
}
public void testDivideOperator()
{
setFor(SqlStdOperatorTable.divideOperator);
checkScalarExact("10 / 5", "2");
checkScalarExact("-10 / 5", "-2");
checkScalarExact("1 / 3", "0");
checkScalarApprox(
" cast(10.0 as double) / 5",
"DOUBLE NOT NULL",
2.0,
0);
checkScalarApprox(
" cast(10.0 as real) / 5",
"REAL NOT NULL",
2.0,
0);
checkScalarApprox(
" 6.0 / cast(10.0 as real) ",
"DOUBLE NOT NULL",
0.6,
0);
checkScalarExact(
"10.0 / 5.0",
"DECIMAL(9, 6) NOT NULL",
"2.000000");
checkScalarExact(
"1.0 / 3.0",
"DECIMAL(8, 6) NOT NULL",
"0.333333");
checkScalarExact(
"100.1 / 0.0001",
"DECIMAL(14, 7) NOT NULL",
"1001000.0000000");
checkScalarExact(
"100.1 / 0.00000001",
"DECIMAL(19, 8) NOT NULL",
"10010000000.00000000");
checkNull("1e1 / cast(null as float)");
checkFails(
"100.1 / 0.00000000000000001",
outOfRangeMessage,
true);
checkNull(
"cast(null as interval month) / 2");
}
public void testIntervalDivide()
{
setFor(SqlStdOperatorTable.divideOperator);
checkScalar(
"interval '1:37' minute to second / 0.5",
"3:14",
"INTERVAL MINUTE TO SECOND NOT NULL");
checkScalar(
"interval '2:5:12' hour to second / 2 / -3",
"-0:20:52",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"interval '1 23:45:06' day to second / 42",
"0 01:08:13",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"interval '-2:2' hour to minute / 3",
"-0:40",
"INTERVAL HOUR TO MINUTE NOT NULL");
checkScalar(
"interval '-10 23:45' day to minute / 5",
"-2 04:45",
"INTERVAL DAY TO MINUTE NOT NULL");
checkScalar(
"interval '23 8' DAY TO HOUR / 14",
"1 16",
"INTERVAL DAY TO HOUR NOT NULL");
checkScalar(
"interval '-45' second / 9",
"-5",
"INTERVAL SECOND NOT NULL");
checkScalar(
"interval '12' minute / -3",
"-4",
"INTERVAL MINUTE NOT NULL");
checkScalar(
"interval '17' hour / -4",
"-4",
"INTERVAL HOUR NOT NULL");
checkScalar(
"interval '25' day / 5",
"5",
"INTERVAL DAY NOT NULL");
checkScalar(
"interval -'10' month / 6",
"-1",
"INTERVAL MONTH NOT NULL");
checkScalar(
"interval '45' year / 15",
"3",
"INTERVAL YEAR NOT NULL");
checkScalar(
"interval '39-8' year to month / 4",
"9-11",
"INTERVAL YEAR TO MONTH NOT NULL");
checkScalar(
"interval '3-3' year to month / 15e-1",
"+02-02",
"INTERVAL YEAR TO MONTH NOT NULL");
checkScalar(
"interval '3-4' year to month / 4.5",
"+00-08",
"INTERVAL YEAR TO MONTH NOT NULL");
checkNull(
"interval '2' day / cast(null as bigint)");
}
public void testEqualsOperator()
{
setFor(SqlStdOperatorTable.equalsOperator);
checkBoolean("1=1", Boolean.TRUE);
checkBoolean("1=1.0", Boolean.TRUE);
checkBoolean("1.34=1.34", Boolean.TRUE);
checkBoolean("1=1.34", Boolean.FALSE);
checkBoolean("1e2=100e0", Boolean.TRUE);
checkBoolean("1e2=101", Boolean.FALSE);
checkBoolean(
"cast(1e2 as real)=cast(101 as bigint)",
Boolean.FALSE);
checkBoolean("'a'='b'", Boolean.FALSE);
checkBoolean(
"cast('a' as varchar(30))=cast('a' as varchar(30))",
Boolean.TRUE);
checkBoolean(
"cast('a ' as varchar(30))=cast('a' as varchar(30))",
Boolean.TRUE);
checkBoolean(
"cast('a' as varchar(30))=cast('b' as varchar(30))",
Boolean.FALSE);
checkBoolean(
"cast('a' as varchar(30))=cast('a' as varchar(15))",
Boolean.TRUE);
checkNull("cast(null as boolean)=cast(null as boolean)");
checkNull("cast(null as integer)=1");
checkNull("cast(null as varchar(10))='a'");
}
public void testIntervalEqualsOperator()
{
setFor(SqlStdOperatorTable.equalsOperator);
checkBoolean(
"interval '2' day = interval '2' hour",
Boolean.FALSE);
checkBoolean(
"interval '2:2:2' hour to second = interval '2' hour",
Boolean.FALSE);
checkBoolean(
"interval '1' second = interval '1' second",
Boolean.TRUE);
checkBoolean(
"interval '1' minute = interval '2' minute",
Boolean.FALSE);
checkBoolean(
"interval '-2' hour = interval -'2' hour",
Boolean.TRUE);
checkBoolean(
"interval '3' day = interval -'3' day",
Boolean.FALSE);
checkBoolean(
"interval '-4' month = interval '-4' month",
Boolean.TRUE);
checkBoolean(
"interval '5' year = interval '-5' year",
Boolean.FALSE);
checkBoolean(
"interval '1:2' minute to second = interval '01:02' minute to second",
Boolean.TRUE);
checkBoolean(
"interval '-1:2:3' hour to second = interval '1:2:3' hour to second",
Boolean.FALSE);
checkBoolean(
"interval '1 2:3:4' day to second = interval '1 02:03:04' day to second",
Boolean.TRUE);
checkBoolean(
"interval '1:2' hour to minute = interval '1:0' hour to minute",
Boolean.FALSE);
checkBoolean(
"interval '-2 3:4' day to minute = interval '-2 03:04' day to minute",
Boolean.TRUE);
checkBoolean(
"interval '-1 1' day to hour = interval -'1 1' day to hour",
Boolean.FALSE);
checkBoolean(
"interval '1' month = interval '1' month",
Boolean.TRUE);
checkBoolean(
"interval '-2' year = interval '2' year",
Boolean.FALSE);
checkBoolean(
"interval '-1-1' year to month = interval '1-1' year to month",
Boolean.FALSE);
checkNull(
"cast(null as interval hour) = interval '2' minute");
}
public void testGreaterThanOperator()
{
setFor(SqlStdOperatorTable.greaterThanOperator);
checkBoolean("1>2", Boolean.FALSE);
checkBoolean(
"cast(-1 as TINYINT)>cast(1 as TINYINT)",
Boolean.FALSE);
checkBoolean(
"cast(1 as SMALLINT)>cast(1 as SMALLINT)",
Boolean.FALSE);
checkBoolean("2>1", Boolean.TRUE);
checkBoolean("1.1>1.2", Boolean.FALSE);
checkBoolean("-1.1>-1.2", Boolean.TRUE);
checkBoolean("1.1>1.1", Boolean.FALSE);
checkBoolean("1.2>1", Boolean.TRUE);
checkBoolean("1.1e1>1.2e1", Boolean.FALSE);
checkBoolean(
"cast(-1.1 as real) > cast(-1.2 as real)",
Boolean.TRUE);
checkBoolean("1.1e2>1.1e2", Boolean.FALSE);
checkBoolean("1.2e0>1", Boolean.TRUE);
checkBoolean("cast(1.2e0 as real)>1", Boolean.TRUE);
checkBoolean("true>false", Boolean.TRUE);
checkBoolean("true>true", Boolean.FALSE);
checkBoolean("false>false", Boolean.FALSE);
checkBoolean("false>true", Boolean.FALSE);
checkNull("3.0>cast(null as double)");
}
public void testIntervalGreaterThan()
{
setFor(SqlStdOperatorTable.greaterThanOperator);
checkBoolean(
"interval '2' day > interval '1' day",
Boolean.TRUE);
checkBoolean(
"interval '2' day > interval '5' day",
Boolean.FALSE);
checkBoolean(
"interval '2 2:2:2' day to second > interval '2' day",
Boolean.TRUE);
checkBoolean(
"interval '2' day > interval '2' day",
Boolean.FALSE);
checkBoolean(
"interval '2' day > interval '-2' day",
Boolean.TRUE);
checkBoolean(
"interval '2' day > interval '2' hour",
Boolean.TRUE);
checkBoolean(
"interval '2' minute > interval '2' hour",
Boolean.FALSE);
checkBoolean(
"interval '2' second > interval '2' minute",
Boolean.FALSE);
checkBoolean(
"interval '10' month > interval '9' month",
Boolean.TRUE);
checkBoolean(
"interval '-2' year > interval '-3' year",
Boolean.TRUE);
checkBoolean(
"interval '-2-2' year to month > interval '-2-1' year to month",
Boolean.FALSE);
checkNull(
"cast(null as interval hour) > interval '2' minute");
checkNull(
"interval '2:2' hour to minute > cast(null as interval second)");
}
public void testIsDistinctFromOperator()
{
setFor(SqlStdOperatorTable.isDistinctFromOperator);
checkBoolean("1 is distinct from 1", Boolean.FALSE);
checkBoolean("1 is distinct from 1.0", Boolean.FALSE);
checkBoolean("1 is distinct from 2", Boolean.TRUE);
checkBoolean(
"cast(null as integer) is distinct from 2",
Boolean.TRUE);
checkBoolean(
"cast(null as integer) is distinct from cast(null as integer)",
Boolean.FALSE);
checkBoolean("1.23 is distinct from 1.23", Boolean.FALSE);
checkBoolean("1.23 is distinct from 5.23", Boolean.TRUE);
checkBoolean(
"-23e0 is distinct from -2.3e1",
Boolean.FALSE);
//checkBoolean("row(1,1) is distinct from row(1,1)",
//Boolean.TRUE); checkBoolean("row(1,1) is distinct from
//row(1,2)", Boolean.FALSE);
// Intervals
checkBoolean(
"interval '2' day is distinct from interval '1' day",
Boolean.TRUE);
checkBoolean(
"interval '10' hour is distinct from interval '10' hour",
Boolean.FALSE);
checkBoolean(
"interval '1-1' year to month is distinct from interval '1-2' year to month",
Boolean.TRUE);
checkBoolean(
"interval '-2' year is distinct from interval -'2' year",
Boolean.FALSE);
}
public void testIsNotDistinctFromOperator()
{
setFor(SqlStdOperatorTable.isNotDistinctFromOperator);
checkBoolean("1 is not distinct from 1", Boolean.TRUE);
checkBoolean("1 is not distinct from 1.0", Boolean.TRUE);
checkBoolean("1 is not distinct from 2", Boolean.FALSE);
checkBoolean(
"cast(null as integer) is not distinct from 2",
Boolean.FALSE);
checkBoolean(
"cast(null as integer) is not distinct from cast(null as integer)",
Boolean.TRUE);
checkBoolean(
"1.23 is not distinct from 1.23",
Boolean.TRUE);
checkBoolean(
"1.23 is not distinct from 5.23",
Boolean.FALSE);
checkBoolean(
"-23e0 is not distinct from -2.3e1",
Boolean.TRUE);
//checkBoolean("row(1,1) is not distinct from row(1,1)",
//Boolean.FALSE); checkBoolean("row(1,1) is not distinct
//from row(1,2)", Boolean.TRUE);
// Intervals
checkBoolean(
"interval '2' day is not distinct from interval '1' day",
Boolean.FALSE);
checkBoolean(
"interval '10' hour is not distinct from interval '10' hour",
Boolean.TRUE);
checkBoolean(
"interval '2:2:2' hour to second is not distinct from interval '02:02:02' hour to second",
Boolean.TRUE);
checkBoolean(
"interval '-1-2' year to month is not distinct from interval '-1' year",
Boolean.FALSE);
}
public void testGreaterThanOrEqualOperator()
{
setFor(SqlStdOperatorTable.greaterThanOrEqualOperator);
checkBoolean("1>=2", Boolean.FALSE);
checkBoolean("-1>=1", Boolean.FALSE);
checkBoolean("1>=1", Boolean.TRUE);
checkBoolean("2>=1", Boolean.TRUE);
checkBoolean("1.1>=1.2", Boolean.FALSE);
checkBoolean("-1.1>=-1.2", Boolean.TRUE);
checkBoolean("1.1>=1.1", Boolean.TRUE);
checkBoolean("1.2>=1", Boolean.TRUE);
checkBoolean("1.2e4>=1e5", Boolean.FALSE);
checkBoolean("1.2e4>=cast(1e5 as real)", Boolean.FALSE);
checkBoolean("1.2>=cast(1e5 as double)", Boolean.FALSE);
checkBoolean("120000>=cast(1e5 as real)", Boolean.TRUE);
checkBoolean("true>=false", Boolean.TRUE);
checkBoolean("true>=true", Boolean.TRUE);
checkBoolean("false>=false", Boolean.TRUE);
checkBoolean("false>=true", Boolean.FALSE);
checkNull("cast(null as real)>=999");
// Intervals
checkBoolean(
"interval '2' day >= interval '1' day",
Boolean.TRUE);
checkBoolean(
"interval '2' day >= interval '5' day",
Boolean.FALSE);
checkBoolean(
"interval '2 2:2:2' day to second >= interval '2' day",
Boolean.TRUE);
checkBoolean(
"interval '2' day >= interval '2' day",
Boolean.TRUE);
checkBoolean(
"interval '2' day >= interval '-2' day",
Boolean.TRUE);
checkBoolean(
"interval '2' day >= interval '2' hour",
Boolean.TRUE);
checkBoolean(
"interval '2' minute >= interval '2' hour",
Boolean.FALSE);
checkBoolean(
"interval '2' second >= interval '2' minute",
Boolean.FALSE);
checkBoolean(
"interval '1-3' year to month >= interval '1' year",
Boolean.TRUE);
checkBoolean(
"interval '-1' year >= interval '1-1' year to month",
Boolean.FALSE);
checkNull(
"cast(null as interval hour) >= interval '2' minute");
checkNull(
"interval '2:2' hour to minute >= cast(null as interval second)");
}
public void testInOperator()
{
setFor(SqlStdOperatorTable.inOperator);
}
public void testOverlapsOperator()
{
setFor(SqlStdOperatorTable.overlapsOperator);
if (Bug.Frg187Fixed) {
checkBoolean(
"(date '1-2-3', date '1-2-3') overlaps (date '1-2-3', interval '1' year)",
Boolean.TRUE);
checkBoolean(
"(date '1-2-3', date '1-2-3') overlaps (date '4-5-6', interval '1' year)",
Boolean.FALSE);
checkBoolean(
"(date '1-2-3', date '4-5-6') overlaps (date '2-2-3', date '3-4-5')",
Boolean.TRUE);
checkNull(
"(cast(null as date), date '1-2-3') overlaps (date '1-2-3', interval '1' year)");
checkNull(
"(date '1-2-3', date '1-2-3') overlaps (date '1-2-3', cast(null as date))");
checkBoolean(
"(time '1:2:3', interval '1' second) overlaps (time '23:59:59', time '1:2:3')",
Boolean.TRUE);
checkBoolean(
"(time '1:2:3', interval '1' second) overlaps (time '23:59:59', time '1:2:2')",
Boolean.FALSE);
checkBoolean(
"(time '1:2:3', interval '1' second) overlaps (time '23:59:59', interval '2' hour)",
Boolean.TRUE);
checkNull(
"(time '1:2:3', cast(null as time)) overlaps (time '23:59:59', time '1:2:3')");
checkNull(
"(time '1:2:3', interval '1' second) overlaps (time '23:59:59', cast(null as interval hour))");
checkBoolean(
"(timestamp '1-2-3 4:5:6', timestamp '1-2-3 4:5:6' ) overlaps (timestamp '1-2-3 4:5:6', interval '1 2:3:4.5' day to second)",
Boolean.TRUE);
checkBoolean(
"(timestamp '1-2-3 4:5:6', timestamp '1-2-3 4:5:6' ) overlaps (timestamp '2-2-3 4:5:6', interval '1 2:3:4.5' day to second)",
Boolean.FALSE);
checkBoolean(
"(timestamp '1-2-3 4:5:6', timestamp '2-3-4 5:6:7') overlaps (timestamp '3-4-5 6:7:8', interval '1-2' year to month)",
Boolean.TRUE);
checkBoolean(
"(timestamp '1-2-3 4:5:6', interval '1-1' year to month) overlaps (timestamp '2-3-4 5:6:7', timestamp '3-4-5 6:7:8')",
Boolean.FALSE);
checkNull(
"(timestamp '1-2-3 4:5:6', cast(null as interval day) ) overlaps (timestamp '1-2-3 4:5:6', interval '1 2:3:4.5' day to second)");
checkNull(
"(timestamp '1-2-3 4:5:6', timestamp '1-2-3 4:5:6' ) overlaps (cast(null as timestamp), interval '1 2:3:4.5' day to second)");
}
}
public void testLessThanOperator()
{
setFor(SqlStdOperatorTable.lessThanOperator);
checkBoolean("1<2", Boolean.TRUE);
checkBoolean("-1<1", Boolean.TRUE);
checkBoolean("1<1", Boolean.FALSE);
checkBoolean("2<1", Boolean.FALSE);
checkBoolean("1.1<1.2", Boolean.TRUE);
checkBoolean("-1.1<-1.2", Boolean.FALSE);
checkBoolean("1.1<1.1", Boolean.FALSE);
checkBoolean("cast(1.1 as real)<1", Boolean.FALSE);
checkBoolean("cast(1.1 as real)<1.1", Boolean.FALSE);
checkBoolean(
"cast(1.1 as real)<cast(1.2 as real)",
Boolean.TRUE);
checkBoolean("-1.1e-1<-1.2e-1", Boolean.FALSE);
checkBoolean(
"cast(1.1 as real)<cast(1.1 as double)",
Boolean.FALSE);
checkBoolean("true<false", Boolean.FALSE);
checkBoolean("true<true", Boolean.FALSE);
checkBoolean("false<false", Boolean.FALSE);
checkBoolean("false<true", Boolean.TRUE);
checkNull("123<cast(null as bigint)");
checkNull("cast(null as tinyint)<123");
checkNull("cast(null as integer)<1.32");
}
public void testIntervalLessThan()
{
setFor(SqlStdOperatorTable.lessThanOperator);
// Intervals
checkBoolean(
"interval '2' day < interval '1' day",
Boolean.FALSE);
checkBoolean(
"interval '2' day < interval '5' day",
Boolean.TRUE);
checkBoolean(
"interval '2 2:2:2' day to second < interval '2' day",
Boolean.FALSE);
checkBoolean(
"interval '2' day < interval '2' day",
Boolean.FALSE);
checkBoolean(
"interval '2' day < interval '-2' day",
Boolean.FALSE);
checkBoolean(
"interval '2' day < interval '2' hour",
Boolean.FALSE);
checkBoolean(
"interval '2' minute < interval '2' hour",
Boolean.TRUE);
checkBoolean(
"interval '2' second < interval '2' minute",
Boolean.TRUE);
checkBoolean(
"interval '1-3' year to month < interval '1' year",
Boolean.FALSE);
checkBoolean(
"interval '-1' year < interval '1-1' year to month",
Boolean.TRUE);
checkNull(
"cast(null as interval hour) < interval '2' minute");
checkNull(
"interval '2:2' hour to minute < cast(null as interval second)");
}
public void testLessThanOrEqualOperator()
{
setFor(SqlStdOperatorTable.lessThanOrEqualOperator);
checkBoolean("1<=2", Boolean.TRUE);
checkBoolean("1<=1", Boolean.TRUE);
checkBoolean("-1<=1", Boolean.TRUE);
checkBoolean("2<=1", Boolean.FALSE);
checkBoolean("1.1<=1.2", Boolean.TRUE);
checkBoolean("-1.1<=-1.2", Boolean.FALSE);
checkBoolean("1.1<=1.1", Boolean.TRUE);
checkBoolean("1.2<=1", Boolean.FALSE);
checkBoolean("1<=cast(1e2 as real)", Boolean.TRUE);
checkBoolean("1000<=cast(1e2 as real)", Boolean.FALSE);
checkBoolean("1.2e1<=1e2", Boolean.TRUE);
checkBoolean("1.2e1<=cast(1e2 as real)", Boolean.TRUE);
checkBoolean("true<=false", Boolean.FALSE);
checkBoolean("true<=true", Boolean.TRUE);
checkBoolean("false<=false", Boolean.TRUE);
checkBoolean("false<=true", Boolean.TRUE);
checkNull("cast(null as real)<=cast(1 as real)");
checkNull("cast(null as integer)<=3");
checkNull("3<=cast(null as smallint)");
checkNull("cast(null as integer)<=1.32");
}
public void testIntervalLessThanOrEqual()
{
setFor(SqlStdOperatorTable.lessThanOrEqualOperator);
checkBoolean(
"interval '2' day <= interval '1' day",
Boolean.FALSE);
checkBoolean(
"interval '2' day <= interval '5' day",
Boolean.TRUE);
checkBoolean(
"interval '2 2:2:2' day to second <= interval '2' day",
Boolean.FALSE);
checkBoolean(
"interval '2' day <= interval '2' day",
Boolean.TRUE);
checkBoolean(
"interval '2' day <= interval '-2' day",
Boolean.FALSE);
checkBoolean(
"interval '2' day <= interval '2' hour",
Boolean.FALSE);
checkBoolean(
"interval '2' minute <= interval '2' hour",
Boolean.TRUE);
checkBoolean(
"interval '2' second <= interval '2' minute",
Boolean.TRUE);
checkBoolean(
"interval '-2' year <= interval '-3' year",
Boolean.FALSE);
checkBoolean(
"interval '-2-2' year to month <= interval '-2-1' year to month",
Boolean.TRUE);
checkNull(
"cast(null as interval hour) <= interval '2' minute");
checkNull(
"interval '2:2' hour to minute <= cast(null as interval second)");
}
public void testMinusOperator()
{
setFor(SqlStdOperatorTable.minusOperator);
checkScalarExact("-2-1", "-3");
checkScalarExact("-2-1-5", "-8");
checkScalarExact("2-1", "1");
checkScalarApprox(
"cast(2.0 as double) -1",
"DOUBLE NOT NULL",
1,
0);
checkScalarApprox(
"cast(1 as smallint)-cast(2.0 as real)",
"REAL NOT NULL",
-1,
0);
checkScalarApprox(
"2.4-cast(2.0 as real)",
"DOUBLE NOT NULL",
0.4,
0.00000001);
checkScalarExact("1-2", "-1");
checkScalarExact(
"10.0 - 5.0",
"DECIMAL(4, 1) NOT NULL",
"5.0");
checkScalarExact(
"19.68 - 4.2",
"DECIMAL(5, 2) NOT NULL",
"15.48");
checkNull("1e1-cast(null as double)");
checkNull("cast(null as tinyint) - cast(null as smallint)");
// TODO: Fix bug
if (Bug.Fn25Fixed) {
// Should throw out of range error
checkFails(
"cast(100 as tinyint) - cast(-100 as tinyint)",
outOfRangeMessage,
true);
checkFails(
"cast(-20000 as smallint) - cast(20000 as smallint)",
outOfRangeMessage,
true);
checkFails(
"cast(1.5e9 as integer) - cast(-1.5e9 as integer)",
outOfRangeMessage,
true);
checkFails(
"cast(-5e18 as bigint) - cast(5e18 as bigint)",
outOfRangeMessage,
true);
checkFails(
"cast(5e18 as decimal(19,0)) - cast(-5e18 as decimal(19,0))",
outOfRangeMessage,
true);
checkFails(
"cast(-5e8 as decimal(19,10)) - cast(5e8 as decimal(19,10))",
outOfRangeMessage,
true);
}
}
public void testMinusIntervalOperator()
{
setFor(SqlStdOperatorTable.minusOperator);
// Intervals
checkScalar(
"interval '2' day - interval '1' day",
"+1",
"INTERVAL DAY NOT NULL");
checkScalar(
"interval '2' day - interval '1' minute",
"+1 23:59",
"INTERVAL DAY TO MINUTE NOT NULL");
checkScalar(
"interval '2' year - interval '1' month",
"+1-11",
"INTERVAL YEAR TO MONTH NOT NULL");
checkScalar(
"interval '2' year - interval '1' month - interval '3' year",
"-1-01",
"INTERVAL YEAR TO MONTH NOT NULL");
checkNull(
"cast(null as interval day) + interval '2' hour");
// Datetime minus interval
checkScalar(
"time '12:03:01' - interval '1:1' hour to minute",
"11:02:01",
"TIME(0) NOT NULL");
checkScalar(
"date '2005-03-02' - interval '5' day",
"2005-02-25",
"DATE NOT NULL");
checkScalar(
"timestamp '2003-08-02 12:54:01' - interval '-4 2:4' day to minute",
"2003-08-06 14:58:01.0",
"TIMESTAMP(0) NOT NULL");
checkScalar(
"date '1864-07-04' - interval '87' year",
"1776-07-04",
"DATE NOT NULL");
checkScalar(
"date '1918-11-11' - interval '-11' month",
"1919-10-11",
"DATE NOT NULL");
checkScalar(
"timestamp '2007-07-18 12:34:56' - interval '4-2' year to month",
"2003-05-18 12:34:56.0",
"TIMESTAMP(0) NOT NULL");
}
public void testMinusDateOperator()
{
setFor(SqlStdOperatorTable.minusDateOperator);
checkScalar(
"(time '12:03:34' - time '11:57:23') minute to second",
"+6:11",
"INTERVAL MINUTE TO SECOND NOT NULL");
checkScalar(
"(time '12:03:23' - time '11:57:23') minute",
"+6",
"INTERVAL MINUTE NOT NULL");
checkScalar(
"(time '12:03:34' - time '11:57:23') minute",
"+6",
"INTERVAL MINUTE NOT NULL");
checkScalar(
"(timestamp '2004-05-01 12:03:34' - timestamp '2004-04-29 11:57:23') day to second",
"+2 00:06:11",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"(timestamp '2004-05-01 12:03:34' - timestamp '2004-04-29 11:57:23') day to hour",
"+2 00",
"INTERVAL DAY TO HOUR NOT NULL");
checkScalar(
"(date '2004-12-02' - date '2003-12-01') day",
"+367",
"INTERVAL DAY NOT NULL");
checkNull(
"(cast(null as date) - date '2003-12-01') day");
checkScalar(
"(date '1864-07-04' - date '1776-07-04') year",
"+87",
"INTERVAL YEAR NOT NULL");
checkScalar(
"(date '1968-04-15' - date '2007-08-27') month",
"-472",
"INTERVAL MONTH NOT NULL");
checkScalar(
"(date '1941-12-07' - date '1918-11-11') year to month",
"+23-01",
"INTERVAL YEAR TO MONTH NOT NULL");
}
public void testMultiplyOperator()
{
setFor(SqlStdOperatorTable.multiplyOperator);
checkScalarExact("2*3", "6");
checkScalarExact("2*-3", "-6");
checkScalarExact("+2*3", "6");
checkScalarExact("2*0", "0");
checkScalarApprox(
"cast(2.0 as float)*3",
"FLOAT NOT NULL",
6,
0);
checkScalarApprox(
"3*cast(2.0 as real)",
"REAL NOT NULL",
6,
0);
checkScalarApprox(
"cast(2.0 as real)*3.2",
"DOUBLE NOT NULL",
6.4,
0);
checkScalarExact(
"10.0 * 5.0",
"DECIMAL(5, 2) NOT NULL",
"50.00");
checkScalarExact(
"19.68 * 4.2",
"DECIMAL(6, 3) NOT NULL",
"82.656");
checkNull("cast(1 as real)*cast(null as real)");
checkNull("2e-3*cast(null as integer)");
checkNull("cast(null as tinyint) * cast(4 as smallint)");
if (Bug.Fn25Fixed) {
// Should throw out of range error
checkFails(
"cast(100 as tinyint) * cast(-2 as tinyint)",
outOfRangeMessage,
true);
checkFails(
"cast(200 as smallint) * cast(200 as smallint)",
outOfRangeMessage,
true);
checkFails(
"cast(1.5e9 as integer) * cast(-2 as integer)",
outOfRangeMessage,
true);
checkFails(
"cast(5e9 as bigint) * cast(2e9 as bigint)",
outOfRangeMessage,
true);
checkFails(
"cast(2e9 as decimal(19,0)) * cast(-5e9 as decimal(19,0))",
outOfRangeMessage,
true);
checkFails(
"cast(5e4 as decimal(19,10)) * cast(2e4 as decimal(19,10))",
outOfRangeMessage,
true);
}
}
public void testIntervalMultiply()
{
setFor(SqlStdOperatorTable.multiplyOperator);
checkScalar(
"interval '2:2' hour to minute * 3",
"+6:06",
"INTERVAL HOUR TO MINUTE NOT NULL");
checkScalar(
"3 * 2 * interval '2:5:12' hour to second",
"+12:31:12",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"interval '1 3:46:20' day to second * -0.001",
"-0 0:01:40",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"interval '-1 16' day to hour * 24",
"-40 0",
"INTERVAL DAY TO HOUR NOT NULL");
checkScalar(
"interval '23 13:47:52' day to second * 0",
"+0 0:00:00",
"INTERVAL DAY TO SECOND NOT NULL");
checkNull(
"interval '2' day * cast(null as bigint)");
checkNull(
"cast(null as interval month) * 2");
checkScalar(
"interval '3-2' year to month * 15e-1",
"+04-09",
"INTERVAL YEAR TO MONTH NOT NULL");
checkScalar(
"interval '3-4' year to month * 4.5",
"+15-00",
"INTERVAL YEAR TO MONTH NOT NULL");
checkScalar(
"interval '-44' year * 0.1",
"-4",
"INTERVAL YEAR NOT NULL");
checkScalar(
"interval '6' month * -4",
"-24",
"INTERVAL MONTH NOT NULL");
checkScalar(
"interval '17-9' year to month * 0",
"+0-0",
"INTERVAL YEAR TO MONTH NOT NULL");
}
public void testNotEqualsOperator()
{
setFor(SqlStdOperatorTable.notEqualsOperator);
checkBoolean("1<>1", Boolean.FALSE);
checkBoolean("'a'<>'A'", Boolean.TRUE);
checkBoolean("1e0<>1e1", Boolean.TRUE);
checkNull("'a'<>cast(null as varchar(1))");
// Intervals
checkBoolean(
"interval '2' day <> interval '1' day",
Boolean.TRUE);
checkBoolean(
"interval '2' day <> interval '2' day",
Boolean.FALSE);
checkBoolean(
"interval '2:2:2' hour to second <> interval '2' hour",
Boolean.TRUE);
checkBoolean(
"interval '-3' year <> interval '3' year",
Boolean.TRUE);
checkBoolean(
"interval '-3-3' year to month <> interval '-3' year",
Boolean.FALSE);
checkNull(
"cast(null as interval hour) <> interval '2' minute");
checkNull(
"cast(null as interval second) <> cast(null as interval second)");
// "!=" is not an acceptable alternative to "<>"
checkFails(
"1 ^!^= 1",
"(?s).*Encountered: \"!\" \\(33\\).*",
false);
}
public void testOrOperator()
{
setFor(SqlStdOperatorTable.orOperator);
checkBoolean("true or false", Boolean.TRUE);
checkBoolean("false or false", Boolean.FALSE);
checkBoolean("true or cast(null as boolean)", Boolean.TRUE);
checkNull("false or cast(null as boolean)");
}
public void testPlusOperator()
{
setFor(SqlStdOperatorTable.plusOperator);
checkScalarExact("1+2", "3");
checkScalarExact("-1+2", "1");
checkScalarExact("1+2+3", "6");
checkScalarApprox(
"1+cast(2.0 as double)",
"DOUBLE NOT NULL",
3,
0);
checkScalarApprox(
"1+cast(2.0 as double)+cast(6.0 as float)",
"DOUBLE NOT NULL",
9,
0);
checkScalarExact(
"10.0 + 5.0",
"DECIMAL(4, 1) NOT NULL",
"15.0");
checkScalarExact(
"19.68 + 4.2",
"DECIMAL(5, 2) NOT NULL",
"23.88");
checkScalarExact(
"19.68 + 4.2 + 6",
"DECIMAL(13, 2) NOT NULL",
"29.88");
checkScalarApprox(
"19.68 + cast(4.2 as float)",
"DOUBLE NOT NULL",
23.88,
0);
checkNull("cast(null as tinyint)+1");
checkNull("1e-2+cast(null as double)");
if (Bug.Fn25Fixed) {
// Should throw out of range error
checkFails(
"cast(100 as tinyint) + cast(100 as tinyint)",
outOfRangeMessage,
true);
checkFails(
"cast(-20000 as smallint) + cast(-20000 as smallint)",
outOfRangeMessage,
true);
checkFails(
"cast(1.5e9 as integer) + cast(1.5e9 as integer)",
outOfRangeMessage,
true);
checkFails(
"cast(5e18 as bigint) + cast(5e18 as bigint)",
outOfRangeMessage,
true);
checkFails(
"cast(-5e18 as decimal(19,0)) + cast(-5e18 as decimal(19,0))",
outOfRangeMessage,
true);
checkFails(
"cast(5e8 as decimal(19,10)) + cast(5e8 as decimal(19,10))",
outOfRangeMessage,
true);
}
}
public void testIntervalPlus()
{
setFor(SqlStdOperatorTable.plusOperator);
// Intervals
checkScalar(
"interval '2' day + interval '1' day",
"+3",
"INTERVAL DAY NOT NULL");
checkScalar(
"interval '2' day + interval '1' minute",
"+2 00:01",
"INTERVAL DAY TO MINUTE NOT NULL");
checkScalar(
"interval '2' day + interval '5' minute + interval '-3' second",
"+2 00:04:57",
"INTERVAL DAY TO SECOND NOT NULL");
checkScalar(
"interval '2' year + interval '1' month",
"+2-01",
"INTERVAL YEAR TO MONTH NOT NULL");
checkNull(
"interval '2' year + cast(null as interval month)");
// Datetime plus interval
checkScalar(
"time '12:03:01' + interval '1:1' hour to minute",
"13:04:01",
"TIME(0) NOT NULL");
checkScalar(
"interval '5' day + date '2005-03-02'",
"2005-03-07",
"DATE NOT NULL");
checkScalar(
"timestamp '2003-08-02 12:54:01' + interval '-4 2:4' day to minute",
"2003-07-29 10:50:01.0",
"TIMESTAMP(0) NOT NULL");
}
public void testDescendingOperator()
{
setFor(SqlStdOperatorTable.descendingOperator);
}
public void testIsNotNullOperator()
{
setFor(SqlStdOperatorTable.isNotNullOperator);
checkBoolean("true is not null", Boolean.TRUE);
checkBoolean(
"cast(null as boolean) is not null",
Boolean.FALSE);
}
public void testIsNullOperator()
{
setFor(SqlStdOperatorTable.isNullOperator);
checkBoolean("true is null", Boolean.FALSE);
checkBoolean("cast(null as boolean) is null",
Boolean.TRUE);
}
public void testIsNotTrueOperator()
{
setFor(SqlStdOperatorTable.isNotTrueOperator);
checkBoolean("true is not true", Boolean.FALSE);
checkBoolean("false is not true", Boolean.TRUE);
checkBoolean(
"cast(null as boolean) is not true",
Boolean.TRUE);
checkFails(
"select ^'a string' is not true^ from (values (1))",
"(?s)Cannot apply 'IS NOT TRUE' to arguments of type '<CHAR\\(8\\)> IS NOT TRUE'. Supported form\\(s\\): '<BOOLEAN> IS NOT TRUE'.*",
false);
}
public void testIsTrueOperator()
{
setFor(SqlStdOperatorTable.isTrueOperator);
checkBoolean("true is true", Boolean.TRUE);
checkBoolean("false is true", Boolean.FALSE);
checkBoolean(
"cast(null as boolean) is true",
Boolean.FALSE);
}
public void testIsNotFalseOperator()
{
setFor(SqlStdOperatorTable.isNotFalseOperator);
checkBoolean("false is not false", Boolean.FALSE);
checkBoolean("true is not false", Boolean.TRUE);
checkBoolean(
"cast(null as boolean) is not false",
Boolean.TRUE);
}
public void testIsFalseOperator()
{
setFor(SqlStdOperatorTable.isFalseOperator);
checkBoolean("false is false", Boolean.TRUE);
checkBoolean("true is false", Boolean.FALSE);
checkBoolean(
"cast(null as boolean) is false",
Boolean.FALSE);
}
public void testIsNotUnknownOperator()
{
setFor(SqlStdOperatorTable.isNotUnknownOperator);
checkBoolean("false is not unknown", Boolean.TRUE);
checkBoolean("true is not unknown", Boolean.TRUE);
checkBoolean(
"cast(null as boolean) is not unknown",
Boolean.FALSE);
checkBoolean("unknown is not unknown", Boolean.FALSE);
checkFails(
"^'abc' IS NOT UNKNOWN^",
"(?s).*Cannot apply 'IS NOT UNKNOWN'.*",
false);
}
public void testIsUnknownOperator()
{
setFor(SqlStdOperatorTable.isUnknownOperator);
checkBoolean("false is unknown", Boolean.FALSE);
checkBoolean("true is unknown", Boolean.FALSE);
checkBoolean(
"cast(null as boolean) is unknown",
Boolean.TRUE);
checkBoolean("unknown is unknown", Boolean.TRUE);
checkFails(
"0 = 1 AND ^2 IS UNKNOWN^ AND 3 > 4",
"(?s).*Cannot apply 'IS UNKNOWN'.*",
false);
}
public void testIsASetOperator()
{
setFor(SqlStdOperatorTable.isASetOperator);
}
public void testExistsOperator()
{
setFor(SqlStdOperatorTable.existsOperator);
}
public void testNotOperator()
{
setFor(SqlStdOperatorTable.notOperator);
checkBoolean("not true", Boolean.FALSE);
checkBoolean("not false", Boolean.TRUE);
checkBoolean("not unknown", null);
checkNull("not cast(null as boolean)");
}
public void testPrefixMinusOperator()
{
setFor(SqlStdOperatorTable.prefixMinusOperator);
checkFails(
"'a' + ^- 'b'^ + 'c'",
"(?s)Cannot apply '-' to arguments of type '-<CHAR\\(1\\)>'.*",
false);
checkScalarExact("-1", "-1");
checkScalarExact(
"-1.23",
"DECIMAL(3, 2) NOT NULL",
"-1.23");
checkScalarApprox("-1.0e0", "DOUBLE NOT NULL", -1, 0);
checkNull("-cast(null as integer)");
checkNull("-cast(null as tinyint)");
// Intervals
checkScalar(
"-interval '-6:2:8' hour to second",
"+6:02:08",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"- -interval '-6:2:8' hour to second",
"-6:02:08",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"-interval '5' month",
"-5",
"INTERVAL MONTH NOT NULL");
checkNull(
"-cast(null as interval day to minute)");
}
public void testPrefixPlusOperator()
{
setFor(SqlStdOperatorTable.prefixPlusOperator);
checkScalarExact("+1", "1");
checkScalarExact("+1.23", "DECIMAL(3, 2) NOT NULL", "1.23");
checkScalarApprox("+1.0e0", "DOUBLE NOT NULL", 1, 0);
checkNull("+cast(null as integer)");
checkNull("+cast(null as tinyint)");
// Intervals
checkScalar(
"+interval '-6:2:8' hour to second",
"-6:02:08",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"++interval '-6:2:8' hour to second",
"-6:02:08",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"+interval '6:2:8.234' hour to second",
"+6:02:08.234",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"+interval '5' month",
"+5",
"INTERVAL MONTH NOT NULL");
checkNull(
"+cast(null as interval day to minute)");
}
public void testExplicitTableOperator()
{
setFor(SqlStdOperatorTable.explicitTableOperator);
}
public void testValuesOperator()
{
setFor(SqlStdOperatorTable.valuesOperator);
check(
"select 'abc' from (values(true))",
new AbstractSqlTester.StringTypeChecker("CHAR(3) NOT NULL"),
"abc",
0);
}
public void testNotLikeOperator()
{
setFor(SqlStdOperatorTable.notLikeOperator);
checkBoolean("'abc' not like '_b_'", Boolean.FALSE);
}
public void testLikeOperator()
{
setFor(SqlStdOperatorTable.likeOperator);
checkBoolean("'' like ''", Boolean.TRUE);
checkBoolean("'a' like 'a'", Boolean.TRUE);
checkBoolean("'a' like 'b'", Boolean.FALSE);
checkBoolean("'a' like 'A'", Boolean.FALSE);
checkBoolean("'a' like 'a_'", Boolean.FALSE);
checkBoolean("'a' like '_a'", Boolean.FALSE);
checkBoolean("'a' like '%a'", Boolean.TRUE);
checkBoolean("'a' like '%a%'", Boolean.TRUE);
checkBoolean("'a' like 'a%'", Boolean.TRUE);
checkBoolean("'ab' like 'a_'", Boolean.TRUE);
checkBoolean("'abc' like 'a_'", Boolean.FALSE);
checkBoolean("'abcd' like 'a%'", Boolean.TRUE);
checkBoolean("'ab' like '_b'", Boolean.TRUE);
checkBoolean("'abcd' like '_d'", Boolean.FALSE);
checkBoolean("'abcd' like '%d'", Boolean.TRUE);
}
public void testNotSimilarToOperator()
{
setFor(SqlStdOperatorTable.notSimilarOperator);
checkBoolean("'ab' not similar to 'a_'", Boolean.FALSE);
}
public void testSimilarToOperator()
{
setFor(SqlStdOperatorTable.similarOperator);
// like LIKE
checkBoolean("'' similar to ''", Boolean.TRUE);
checkBoolean("'a' similar to 'a'", Boolean.TRUE);
checkBoolean("'a' similar to 'b'", Boolean.FALSE);
checkBoolean("'a' similar to 'A'", Boolean.FALSE);
checkBoolean("'a' similar to 'a_'", Boolean.FALSE);
checkBoolean("'a' similar to '_a'", Boolean.FALSE);
checkBoolean("'a' similar to '%a'", Boolean.TRUE);
checkBoolean("'a' similar to '%a%'", Boolean.TRUE);
checkBoolean("'a' similar to 'a%'", Boolean.TRUE);
checkBoolean("'ab' similar to 'a_'", Boolean.TRUE);
checkBoolean("'abc' similar to 'a_'", Boolean.FALSE);
checkBoolean("'abcd' similar to 'a%'", Boolean.TRUE);
checkBoolean("'ab' similar to '_b'", Boolean.TRUE);
checkBoolean("'abcd' similar to '_d'", Boolean.FALSE);
checkBoolean("'abcd' similar to '%d'", Boolean.TRUE);
// simple regular expressions
// ab*c+d matches acd, abcd, acccd, abcccd but not abd, aabc
checkBoolean("'acd' similar to 'ab*c+d'", Boolean.TRUE);
checkBoolean("'abcd' similar to 'ab*c+d'", Boolean.TRUE);
checkBoolean("'acccd' similar to 'ab*c+d'", Boolean.TRUE);
checkBoolean("'abcccd' similar to 'ab*c+d'", Boolean.TRUE);
checkBoolean("'abd' similar to 'ab*c+d'", Boolean.FALSE);
checkBoolean("'aabc' similar to 'ab*c+d'", Boolean.FALSE);
// compound regular expressions
// x(ab|c)*y matches xy, xccy, xababcy but not xbcy
checkBoolean(
"'xy' similar to 'x(ab|c)*y'",
Boolean.TRUE);
checkBoolean(
"'xccy' similar to 'x(ab|c)*y'",
Boolean.TRUE);
checkBoolean(
"'xababcy' similar to 'x(ab|c)*y'",
Boolean.TRUE);
checkBoolean(
"'xbcy' similar to 'x(ab|c)*y'",
Boolean.FALSE);
// x(ab|c)+y matches xccy, xababcy but not xy, xbcy
checkBoolean(
"'xy' similar to 'x(ab|c)+y'",
Boolean.FALSE);
checkBoolean(
"'xccy' similar to 'x(ab|c)+y'",
Boolean.TRUE);
checkBoolean(
"'xababcy' similar to 'x(ab|c)+y'",
Boolean.TRUE);
checkBoolean(
"'xbcy' similar to 'x(ab|c)+y'",
Boolean.FALSE);
}
public void testEscapeOperator()
{
setFor(SqlStdOperatorTable.escapeOperator);
}
public void testConvertFunc()
{
setFor(SqlStdOperatorTable.convertFunc);
}
public void testTranslateFunc()
{
setFor(SqlStdOperatorTable.translateFunc);
}
public void testOverlayFunc()
{
setFor(SqlStdOperatorTable.overlayFunc);
checkString(
"overlay('ABCdef' placing 'abc' from 1)",
"abcdef",
"VARCHAR(9) NOT NULL");
checkString(
"overlay('ABCdef' placing 'abc' from 1 for 2)",
"abcCdef",
"VARCHAR(9) NOT NULL");
checkString(
"overlay(cast('ABCdef' as varchar(10)) placing "
+ "cast('abc' as char(5)) from 1 for 2)",
"abc Cdef",
"VARCHAR(15) NOT NULL");
checkString(
"overlay(cast('ABCdef' as char(10)) placing "
+ "cast('abc' as char(5)) from 1 for 2)",
"abc Cdef ",
"VARCHAR(15) NOT NULL");
checkNull(
"overlay('ABCdef' placing 'abc' from 1 for cast(null as integer))");
checkNull(
"overlay(cast(null as varchar(1)) placing 'abc' from 1)");
if (todo) {
// todo: hex strings not yet implemented in calc
checkNull(
"overlay(x'abc' placing x'abc' from cast(null as integer))");
}
}
public void testPositionFunc()
{
setFor(SqlStdOperatorTable.positionFunc);
checkScalarExact("position('b' in 'abc')", "2");
checkScalarExact("position('' in 'abc')", "1");
// FRG-211
checkScalarExact("position('tra' in 'fdgjklewrtra')", "10");
checkNull("position(cast(null as varchar(1)) in '0010')");
checkNull("position('a' in cast(null as varchar(1)))");
checkScalar(
"position(cast('a' as char) in cast('bca' as varchar))",
0,
"INTEGER NOT NULL");
}
public void testCharLengthFunc()
{
setFor(SqlStdOperatorTable.charLengthFunc);
checkScalarExact("char_length('abc')", "3");
checkNull("char_length(cast(null as varchar(1)))");
}
public void testCharacterLengthFunc()
{
setFor(SqlStdOperatorTable.characterLengthFunc);
checkScalarExact("CHARACTER_LENGTH('abc')", "3");
checkNull("CHARACTER_LENGTH(cast(null as varchar(1)))");
}
public void testUpperFunc()
{
setFor(SqlStdOperatorTable.upperFunc);
checkString("upper('a')", "A", "CHAR(1) NOT NULL");
checkString("upper('A')", "A", "CHAR(1) NOT NULL");
checkString("upper('1')", "1", "CHAR(1) NOT NULL");
checkString("upper('aa')", "AA", "CHAR(2) NOT NULL");
checkNull("upper(cast(null as varchar(1)))");
}
public void testLowerFunc()
{
setFor(SqlStdOperatorTable.lowerFunc);
// SQL:2003 6.29.8 The type of lower is the type of its argument
checkString("lower('A')", "a", "CHAR(1) NOT NULL");
checkString("lower('a')", "a", "CHAR(1) NOT NULL");
checkString("lower('1')", "1", "CHAR(1) NOT NULL");
checkString("lower('AA')", "aa", "CHAR(2) NOT NULL");
checkNull("lower(cast(null as varchar(1)))");
}
public void testInitcapFunc()
{
// Note: the initcap function is an Oracle defined function and is not
// defined in the '03 standard
setFor(SqlStdOperatorTable.initcapFunc);
checkString("initcap('aA')", "Aa", "CHAR(2) NOT NULL");
checkString("initcap('Aa')", "Aa", "CHAR(2) NOT NULL");
checkString("initcap('1a')", "1a", "CHAR(2) NOT NULL");
checkString(
"initcap('ab cd Ef 12')",
"Ab Cd Ef 12",
"CHAR(11) NOT NULL");
checkNull("initcap(cast(null as varchar(1)))");
// dtbug 232
checkFails(
"^initcap(cast(null as date))^",
"Cannot apply 'INITCAP' to arguments of type 'INITCAP\\(<DATE>\\)'\\. Supported form\\(s\\): 'INITCAP\\(<CHARACTER>\\)'",
false);
}
public void testPowFunc()
{
setFor(SqlStdOperatorTable.powFunc);
checkScalarApprox("pow(2,-2)", "DOUBLE NOT NULL", 0.25, 0);
checkNull("pow(cast(null as integer),2)");
checkNull("pow(2,cast(null as double))");
}
public void testExpFunc()
{
setFor(SqlStdOperatorTable.expFunc);
checkScalarApprox(
"exp(2)",
"DOUBLE NOT NULL",
7.389056,
0.000001);
checkScalarApprox(
"exp(-2)",
"DOUBLE NOT NULL",
0.1353,
0.0001);
checkNull("exp(cast(null as integer))");
checkNull("exp(cast(null as double))");
}
public void testModFunc()
{
setFor(SqlStdOperatorTable.modFunc);
checkScalarExact("mod(4,2)", "0");
checkScalarExact("mod(8,5)", "3");
checkScalarExact("mod(-12,7)", "-5");
checkScalarExact("mod(-12,-7)", "-5");
checkScalarExact("mod(12,-7)", "5");
checkScalarExact(
"mod(cast(12 as tinyint), cast(-7 as tinyint))",
"TINYINT NOT NULL",
"5");
checkScalarExact(
"mod(cast(9 as decimal(2, 0)), 7)",
"INTEGER NOT NULL",
"2");
checkScalarExact(
"mod(7, cast(9 as decimal(2, 0)))",
"DECIMAL(2, 0) NOT NULL",
"7");
checkScalarExact(
"mod(cast(-9 as decimal(2, 0)), cast(7 as decimal(1, 0)))",
"DECIMAL(1, 0) NOT NULL",
"-2");
checkNull("mod(cast(null as integer),2)");
checkNull("mod(4,cast(null as tinyint))");
checkNull("mod(4,cast(null as decimal(12,0)))");
}
public void testModFuncDivByZero()
{
// The extra CASE expression is to fool Janino. It does constant
// reduction and will throw the divide by zero exception while
// compiling the expression. The test frame work would then issue
// unexpected exception occured during "validation". You cannot
// submit as non-runtime because the janino exception does not have
// error position information and the framework is unhappy with that.
checkFails("mod(3,case 'a' when 'a' then 0 end)", divisionByZeroMessage, true);
}
public void testLnFunc()
{
setFor(SqlStdOperatorTable.lnFunc);
checkScalarApprox(
"ln(2.71828)",
"DOUBLE NOT NULL",
1.0,
0.000001);
checkScalarApprox(
"ln(2.71828)",
"DOUBLE NOT NULL",
0.999999327,
0.0000001);
checkNull("ln(cast(null as tinyint))");
}
public void testLogFunc()
{
setFor(SqlStdOperatorTable.log10Func);
checkScalarApprox(
"log10(10)",
"DOUBLE NOT NULL",
1.0,
0.000001);
checkScalarApprox(
"log10(100.0)",
"DOUBLE NOT NULL",
2.0,
0.000001);
checkScalarApprox(
"log10(cast(10e8 as double))",
"DOUBLE NOT NULL",
9.0,
0.000001);
checkScalarApprox(
"log10(cast(10e2 as float))",
"DOUBLE NOT NULL",
3.0,
0.000001);
checkScalarApprox(
"log10(cast(10e-3 as real))",
"DOUBLE NOT NULL",
-2.0,
0.000001);
checkNull("log10(cast(null as real))");
}
public void testAbsFunc()
{
setFor(SqlStdOperatorTable.absFunc);
checkScalarExact("abs(-1)", "1");
checkScalarExact(
"abs(cast(10 as TINYINT))",
"TINYINT NOT NULL",
"10");
checkScalarExact(
"abs(cast(-20 as SMALLINT))",
"SMALLINT NOT NULL",
"20");
checkScalarExact(
"abs(cast(-100 as INT))",
"INTEGER NOT NULL",
"100");
checkScalarExact(
"abs(cast(1000 as BIGINT))",
"BIGINT NOT NULL",
"1000");
checkScalarExact(
"abs(54.4)",
"DECIMAL(3, 1) NOT NULL",
"54.4");
checkScalarExact(
"abs(-54.4)",
"DECIMAL(3, 1) NOT NULL",
"54.4");
checkScalarApprox(
"abs(-9.32E-2)",
"DOUBLE NOT NULL",
0.0932,
0);
checkScalarApprox(
"abs(cast(-3.5 as double))",
"DOUBLE NOT NULL",
3.5,
0);
checkScalarApprox(
"abs(cast(-3.5 as float))",
"FLOAT NOT NULL",
3.5,
0);
checkScalarApprox(
"abs(cast(3.5 as real))",
"REAL NOT NULL",
3.5,
0);
checkNull("abs(cast(null as double))");
// Intervals
checkScalar(
"abs(interval '-2' day)",
"+2",
"INTERVAL DAY NOT NULL");
checkScalar(
"abs(interval '-5-03' year to month)",
"+5-03",
"INTERVAL YEAR TO MONTH NOT NULL");
checkNull("abs(cast(null as interval hour))");
}
public void testNullifFunc()
{
setFor(SqlStdOperatorTable.nullIfFunc);
checkNull("nullif(1,1)");
checkScalarExact(
"nullif(1.5, 13.56)",
"DECIMAL(2, 1)",
"1.5");
checkScalarExact(
"nullif(13.56, 1.5)",
"DECIMAL(4, 2)",
"13.56");
checkScalarExact("nullif(1.5, 3)", "DECIMAL(2, 1)", "1.5");
checkScalarExact("nullif(3, 1.5)", "INTEGER", "3");
checkScalarApprox("nullif(1.5e0, 3e0)", "DOUBLE", 1.5, 0);
checkScalarApprox(
"nullif(1.5, cast(3e0 as REAL))",
"DECIMAL(2, 1)",
1.5,
0);
checkScalarExact("nullif(3, 1.5e0)", "INTEGER", "3");
checkScalarExact(
"nullif(3, cast(1.5e0 as REAL))",
"INTEGER",
"3");
checkScalarApprox("nullif(1.5e0, 3.4)", "DOUBLE", 1.5, 0);
checkScalarExact(
"nullif(3.4, 1.5e0)",
"DECIMAL(2, 1)",
"3.4");
checkString("nullif('a','bc')",
"a",
"CHAR(1)");
checkString(
"nullif('a',cast(null as varchar(1)))",
"a",
"CHAR(1)");
checkNull("nullif(cast(null as varchar(1)),'a')");
checkNull("nullif(cast(null as numeric(4,3)), 4.3)");
// Error message reflects the fact that Nullif is expanded before it is
// validated (like a C macro). Not perfect, but good enough.
checkFails(
"1 + ^nullif(1, date '2005-8-4')^ + 2",
"(?s)Cannot apply '=' to arguments of type '<INTEGER> = <DATE>'\\..*",
false);
// TODO: fix frg 65 (dtbug 324).
if (Bug.Frg65Fixed) {
checkFails(
"1 + ^nullif(1, 2, 3)^ + 2",
"invalid number of arguments to NULLIF",
false);
}
// Intervals
checkScalar(
"nullif(interval '2' month, interval '3' year)",
"+2",
"INTERVAL MONTH");
checkScalar(
"nullif(interval '2 5' day to hour, interval '5' second)",
"+2 05",
"INTERVAL DAY TO HOUR");
checkNull(
"nullif(interval '3' day, interval '3' day)");
}
public void testCoalesceFunc()
{
setFor(SqlStdOperatorTable.coalesceFunc);
checkString("coalesce('a','b')", "a", "CHAR(1) NOT NULL");
checkScalarExact("coalesce(null,null,3)", "3");
checkFails(
"1 + ^coalesce('a', 'b', 1, null)^ + 2",
"Illegal mixing of types in CASE or COALESCE statement",
false);
}
public void testUserFunc()
{
setFor(SqlStdOperatorTable.userFunc);
checkString("USER", "sa", "VARCHAR(2000) NOT NULL");
}
public void testCurrentUserFunc()
{
setFor(SqlStdOperatorTable.currentUserFunc);
checkString("CURRENT_USER", "sa", "VARCHAR(2000) NOT NULL");
}
public void testSessionUserFunc()
{
setFor(SqlStdOperatorTable.sessionUserFunc);
checkString("SESSION_USER", "sa", "VARCHAR(2000) NOT NULL");
}
public void testSystemUserFunc()
{
setFor(SqlStdOperatorTable.systemUserFunc);
String user = System.getProperty("user.name"); // e.g. "jhyde"
checkString("SYSTEM_USER", user, "VARCHAR(2000) NOT NULL");
}
public void testCurrentPathFunc()
{
setFor(SqlStdOperatorTable.currentPathFunc);
checkString("CURRENT_PATH", "", "VARCHAR(2000) NOT NULL");
}
public void testCurrentRoleFunc()
{
setFor(SqlStdOperatorTable.currentRoleFunc);
// By default, the CURRENT_ROLE function returns
// the empty string because a role has to be set explicitly.
checkString("CURRENT_ROLE", "", "VARCHAR(2000) NOT NULL");
}
public void testLocalTimeFunc()
{
setFor(SqlStdOperatorTable.localTimeFunc);
checkScalar("LOCALTIME", timePattern, "TIME(0) NOT NULL");
checkFails(
"^LOCALTIME()^",
"No match found for function signature LOCALTIME\\(\\)",
false);
checkScalar(
"LOCALTIME(1)",
timePattern,
"TIME(1) NOT NULL");
}
public void testLocalTimestampFunc()
{
setFor(SqlStdOperatorTable.localTimestampFunc);
checkScalar(
"LOCALTIMESTAMP",
timestampPattern,
"TIMESTAMP(0) NOT NULL");
checkFails(
"^LOCALTIMESTAMP()^",
"No match found for function signature LOCALTIMESTAMP\\(\\)",
false);
checkFails(
"LOCALTIMESTAMP(^4000000000^)",
literalOutOfRangeMessage,
false);
checkScalar(
"LOCALTIMESTAMP(1)",
timestampPattern,
"TIMESTAMP(1) NOT NULL");
}
public void testCurrentTimeFunc()
{
setFor(SqlStdOperatorTable.currentTimeFunc);
checkScalar(
"CURRENT_TIME",
timePattern,
"TIME(0) NOT NULL");
checkFails(
"^CURRENT_TIME()^",
"No match found for function signature CURRENT_TIME\\(\\)",
false);
checkScalar(
"CURRENT_TIME(1)",
timePattern,
"TIME(1) NOT NULL");
}
public void testCurrentTimestampFunc()
{
setFor(SqlStdOperatorTable.currentTimestampFunc);
checkScalar(
"CURRENT_TIMESTAMP",
timestampPattern,
"TIMESTAMP(0) NOT NULL");
checkFails(
"^CURRENT_TIMESTAMP()^",
"No match found for function signature CURRENT_TIMESTAMP\\(\\)",
false);
checkFails(
"CURRENT_TIMESTAMP(^4000000000^)",
literalOutOfRangeMessage,
false);
checkScalar(
"CURRENT_TIMESTAMP(1)",
timestampPattern,
"TIMESTAMP(1) NOT NULL");
}
public void testCurrentDateFunc()
{
setFor(SqlStdOperatorTable.currentDateFunc);
checkScalar("CURRENT_DATE", datePattern, "DATE NOT NULL");
checkFails(
"^CURRENT_DATE()^",
"No match found for function signature CURRENT_DATE\\(\\)",
false);
}
public void testSubstringFunction()
{
setFor(SqlStdOperatorTable.substringFunc);
checkString(
"substring('abc' from 1 for 2)",
"ab",
"VARCHAR(3) NOT NULL");
checkString(
"substring('abc' from 2)",
"bc",
"VARCHAR(3) NOT NULL");
//substring reg exp not yet supported
//checkString("substring('foobar' from '%#\"o_b#\"%' for
//'#')", "oob");
checkNull("substring(cast(null as varchar(1)),1,2)");
}
public void testTrimFunc()
{
setFor(SqlStdOperatorTable.trimFunc);
// SQL:2003 6.29.11 Trimming a CHAR yields a VARCHAR
checkString(
"trim('a' from 'aAa')",
"A",
"VARCHAR(3) NOT NULL");
checkString(
"trim(both 'a' from 'aAa')",
"A",
"VARCHAR(3) NOT NULL");
checkString(
"trim(leading 'a' from 'aAa')",
"Aa",
"VARCHAR(3) NOT NULL");
checkString(
"trim(trailing 'a' from 'aAa')",
"aA",
"VARCHAR(3) NOT NULL");
checkNull("trim(cast(null as varchar(1)) from 'a')");
checkNull("trim('a' from cast(null as varchar(1)))");
if (Bug.Fnl3Fixed) {
// SQL:2003 6.29.9: trim string must have length=1. Failure occurs
// at runtime.
//
// TODO: Change message to "Invalid argument\(s\) for 'TRIM' function",
// The message should come from a resource file, and should still
// have the SQL error code 22027.
checkFails(
"trim('xy' from 'abcde')",
"could not calculate results for the following row:" + NL
+ "\\[ 0 \\]" + NL
+ "Messages:" + NL
+ "\\[0\\]:PC=0 Code=22027 ",
true);
checkFails(
"trim('' from 'abcde')",
"could not calculate results for the following row:" + NL
+ "\\[ 0 \\]" + NL
+ "Messages:" + NL
+ "\\[0\\]:PC=0 Code=22027 ",
true);
}
}
public void testWindow()
{
setFor(SqlStdOperatorTable.windowOperator);
if (Bug.Frg188Fixed) {
check(
"select sum(1) over (order by x) from (select 1 as x, 2 as y from (values (true)))",
new AbstractSqlTester.StringTypeChecker("INTEGER"),
"1",
0);
}
}
public void testElementFunc()
{
setFor(SqlStdOperatorTable.elementFunc);
if (todo) {
checkString(
"element(multiset['abc']))",
"abc",
"char(3) not null");
checkNull("element(multiset[cast(null as integer)]))");
}
}
public void testCardinalityFunc()
{
setFor(SqlStdOperatorTable.cardinalityFunc);
if (todo) {
checkScalarExact(
"cardinality(multiset[cast(null as integer),2]))",
"2");
}
}
public void testMemberOfOperator()
{
setFor(SqlStdOperatorTable.memberOfOperator);
checkBoolean("1 member of multiset[1]", Boolean.TRUE);
checkBoolean(
"'2' member of multiset['1']",
Boolean.FALSE);
checkBoolean(
"cast(null as double) member of multiset[cast(null as double)]",
Boolean.TRUE);
checkBoolean(
"cast(null as double) member of multiset[1.1]",
Boolean.FALSE);
checkBoolean(
"1.1 member of multiset[cast(null as double)]",
Boolean.FALSE);
}
public void testCollectFunc()
{
setFor(SqlStdOperatorTable.collectFunc);
}
public void testFusionFunc()
{
setFor(SqlStdOperatorTable.fusionFunc);
}
public void testExtractFunc()
{
setFor(SqlStdOperatorTable.extractFunc);
// Intervals
checkScalar(
"extract(day from interval '2 3:4:5.678' day to second)",
"2",
"BIGINT NOT NULL");
checkScalar(
"extract(hour from interval '2 3:4:5.678' day to second)",
"3",
"BIGINT NOT NULL");
checkScalar(
"extract(minute from interval '2 3:4:5.678' day to second)",
"4",
"BIGINT NOT NULL");
// TODO: Seconds should include precision
checkScalar(
"extract(second from interval '2 3:4:5.678' day to second)",
"5",
"BIGINT NOT NULL");
checkScalar(
"extract(minute from interval '-1:2' hour to minute)",
"2",
"BIGINT NOT NULL");
checkScalar(
"extract(hour from interval '-1:2:3' hour to second)",
"-1",
"BIGINT NOT NULL");
checkScalar(
"extract(year from interval '4-2' year to month)",
"4",
"BIGINT NOT NULL");
checkScalar(
"extract(month from interval '4-2' year to month)",
"2",
"BIGINT NOT NULL");
checkNull(
"extract(month from cast(null as interval year))");
}
public void testCeilFunc()
{
setFor(SqlStdOperatorTable.ceilFunc);
checkScalarApprox("ceil(10.1e0)", "DOUBLE NOT NULL", 11, 0);
checkScalarApprox(
"ceil(cast(-11.2e0 as real))",
"REAL NOT NULL",
-11,
0);
checkScalarExact("ceil(100)", "INTEGER NOT NULL", "100");
checkScalarExact(
"ceil(1.3)",
"DECIMAL(2, 0) NOT NULL",
"2");
checkScalarExact(
"ceil(-1.7)",
"DECIMAL(2, 0) NOT NULL",
"-1");
checkNull("ceiling(cast(null as decimal(2,0)))");
checkNull("ceiling(cast(null as double))");
// Intervals
checkScalar(
"ceil(interval '3:4:5' hour to second)",
"+4:00:00",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"ceil(interval '-6.3' second)",
"-6",
"INTERVAL SECOND NOT NULL");
checkScalar(
"ceil(interval '5-1' year to month)",
"+6-00",
"INTERVAL YEAR TO MONTH NOT NULL");
checkScalar(
"ceil(interval '-5-1' year to month)",
"-5-00",
"INTERVAL YEAR TO MONTH NOT NULL");
checkNull(
"ceil(cast(null as interval year))");
}
public void testFloorFunc()
{
setFor(SqlStdOperatorTable.floorFunc);
checkScalarApprox("floor(2.5e0)", "DOUBLE NOT NULL", 2, 0);
checkScalarApprox(
"floor(cast(-1.2e0 as real))",
"REAL NOT NULL",
-2,
0);
checkScalarExact("floor(100)", "INTEGER NOT NULL", "100");
checkScalarExact(
"floor(1.7)",
"DECIMAL(2, 0) NOT NULL",
"1");
checkScalarExact(
"floor(-1.7)",
"DECIMAL(2, 0) NOT NULL",
"-2");
checkNull("floor(cast(null as decimal(2,0)))");
checkNull("floor(cast(null as real))");
// Intervals
checkScalar(
"floor(interval '3:4:5' hour to second)",
"+3:00:00",
"INTERVAL HOUR TO SECOND NOT NULL");
checkScalar(
"floor(interval '-6.3' second)",
"-7",
"INTERVAL SECOND NOT NULL");
checkScalar(
"floor(interval '5-1' year to month)",
"+5-00",
"INTERVAL YEAR TO MONTH NOT NULL");
checkScalar(
"floor(interval '-5-1' year to month)",
"-6-00",
"INTERVAL YEAR TO MONTH NOT NULL");
checkNull(
"floor(cast(null as interval year))");
}
public void testDenseRankFunc()
{
setFor(SqlStdOperatorTable.denseRankFunc);
}
public void testPercentRankFunc()
{
setFor(SqlStdOperatorTable.percentRankFunc);
}
public void testRankFunc()
{
setFor(SqlStdOperatorTable.rankFunc);
}
public void testCumeDistFunc()
{
setFor(SqlStdOperatorTable.cumeDistFunc);
}
public void testRowNumberFunc()
{
setFor(SqlStdOperatorTable.rowNumberFunc);
}
public void testCountFunc()
{
if (Bug.Frg188Fixed) {
setFor(SqlStdOperatorTable.countOperator);
checkType("count(*)", "BIGINT NOT NULL");
checkType("count('name')", "BIGINT NOT NULL");
checkType("count(1)", "BIGINT NOT NULL");
checkType("count(1.2)", "BIGINT NOT NULL");
checkType("COUNT(DISTINCT 'x')", "BIGINT NOT NULL");
checkFails(
"^COUNT()^",
"Invalid number of arguments to function 'COUNT'. Was expecting 1 arguments",
false);
checkFails(
"^COUNT(1, 2)^",
"Invalid number of arguments to function 'COUNT'. Was expecting 1 arguments",
false);
final String [] values = { "0", "CAST(null AS INTEGER)", "1", "0" };
checkAgg(
"COUNT(x)",
values,
3,
0);
checkAgg(
"COUNT(CASE x WHEN 0 THEN NULL ELSE -1 END)",
values,
2,
0);
checkAgg(
"COUNT(DISTINCT x)",
values,
2,
0);
// string values -- note that empty string is not null
final String [] stringValues =
{ "'a'", "CAST(NULL AS VARCHAR(1))", "''" };
checkAgg(
"COUNT(*)",
stringValues,
3,
0);
checkAgg(
"COUNT(x)",
stringValues,
2,
0);
checkAgg(
"COUNT(DISTINCT x)",
stringValues,
2,
0);
checkAgg(
"COUNT(DISTINCT 123)",
stringValues,
1,
0);
}
}
public void testSumFunc()
{
if (Bug.Frg188Fixed) {
setFor(SqlStdOperatorTable.sumOperator);
checkFails(
"sum(^*^)",
"Unknown identifier '\\*'",
false);
checkFails(
"^sum('name')^",
"(?s)Cannot apply 'SUM' to arguments of type 'SUM\\(<CHAR\\(4\\)>\\)'\\. Supported form\\(s\\): 'SUM\\(<NUMERIC>\\)'.*",
false);
checkType("sum(1)", "INTEGER");
checkType("sum(1.2)", "DECIMAL(2, 1)");
checkType("sum(DISTINCT 1.5)", "DECIMAL(2, 1)");
checkFails(
"^sum()^",
"Invalid number of arguments to function 'SUM'. Was expecting 1 arguments",
false);
checkFails(
"^sum(1, 2)^",
"Invalid number of arguments to function 'SUM'. Was expecting 1 arguments",
false);
checkFails(
"^sum(cast(null as varchar(2)))^",
"(?s)Cannot apply 'SUM' to arguments of type 'SUM\\(<VARCHAR\\(2\\)>\\)'\\. Supported form\\(s\\): 'SUM\\(<NUMERIC>\\)'.*",
false);
final String [] values = { "0", "CAST(null AS INTEGER)", "2", "2" };
checkAgg(
"sum(x)",
values,
4,
0);
checkAgg(
"sum(CASE x WHEN 0 THEN NULL ELSE -1 END)",
values,
-3,
0);
checkAgg(
"sum(DISTINCT CASE x WHEN 0 THEN NULL ELSE -1 END)",
values,
-1,
0);
checkAgg(
"sum(DISTINCT x)",
values,
2,
0);
}
}
public void testAvgFunc()
{
if (Bug.Frg188Fixed) {
setFor(SqlStdOperatorTable.avgOperator);
checkFails(
"avg(^*^)",
"Unknown identifier '\\*'",
false);
checkFails(
"^avg(cast(null as varchar(2)))^",
"(?s)Cannot apply 'AVG' to arguments of type 'AVG\\(<VARCHAR\\(2\\)>\\)'\\. Supported form\\(s\\): 'AVG\\(<NUMERIC>\\)'.*",
false);
checkType("AVG(CAST(NULL AS INTEGER))", "INTEGER");
checkType("AVG(DISTINCT 1.5)", "DECIMAL(2, 1)");
final String [] values = { "0", "CAST(null AS INTEGER)", "3", "3" };
checkAgg(
"AVG(x)",
values,
1.0,
0);
checkAgg(
"AVG(DISTINCT x)",
values,
1.5,
0);
checkAgg(
"avg(DISTINCT CASE x WHEN 0 THEN NULL ELSE -1 END)",
values,
-1,
0);
}
}
public void testLastValueFunc()
{
if (Bug.Frg188Fixed) {
setFor(SqlStdOperatorTable.lastValueOperator);
checkScalarExact("last_value(1)", "1");
checkScalarExact(
"last_value(1.2)",
"DECIMAL(2, 1) NOT NULL",
"1.2");
checkType("last_value('name')", "CHAR(4) NOT NULL");
checkString(
"last_value('name')",
"name",
"CHAR(4) NOT NULL");
}
}
public void testFirstValueFunc()
{
if (Bug.Frg188Fixed) {
setFor(SqlStdOperatorTable.firstValueOperator);
checkScalarExact("first_value(1)", "1");
checkScalarExact(
"first_value(1.2)",
"DECIMAL(2, 1) NOT NULL",
"1.2");
checkType("first_value('name')", "CHAR(4) NOT NULL");
checkString(
"first_value('name')",
"name",
"CHAR(4) NOT NULL");
}
}
/**
* Tests that CAST fails when given a value just outside the valid range for
* that type. For example,
*
* <ul>
* <li>CAST(-200 AS TINYINT) fails because the value is less than -128;
* <li>CAST(1E-999 AS FLOAT) fails because the value underflows;
* <li>CAST(123.4567891234567 AS FLOAT) fails because the value loses
* precision.
* </ul>
*/
public void testLiteralAtLimit()
{
final SqlTester tester = getTester();
tester.setFor(SqlStdOperatorTable.castFunc);
for (BasicSqlType type : SqlLimitsTest.getTypes()) {
for (Object o : getValues(type, true)) {
SqlLiteral literal =
type.getSqlTypeName().createLiteral(o, SqlParserPos.ZERO);
String literalString =
literal.toSqlString(SqlUtil.dummyDialect);
final String expr =
"CAST(" + literalString
+ " AS " + type + ")";
if (type.getSqlTypeName() == SqlTypeName.VARBINARY &&
!Bug.Frg283Fixed) {
continue;
}
try {
tester.checkType(
expr,
type.getFullTypeString());
if (type.getSqlTypeName() == SqlTypeName.BINARY) {
// Casting a string/binary values may change the value.
// For example, CAST(X'AB' AS BINARY(2)) yields
// X'AB00'.
} else {
tester.checkScalar(
expr + " = " + literalString,
true,
"BOOLEAN NOT NULL");
}
} catch (Error e) {
System.out.println("Failed for expr=[" + expr + "]");
throw e;
} catch (RuntimeException e) {
System.out.println("Failed for expr=[" + expr + "]");
throw e;
}
}
}
}
/**
* Tests that CAST fails when given a value just outside the valid range for
* that type. For example,
*
* <ul>
* <li>CAST(-200 AS TINYINT) fails because the value is less than -128;
* <li>CAST(1E-999 AS FLOAT) fails because the value underflows;
* <li>CAST(123.4567891234567 AS FLOAT) fails because the value loses
* precision.
* </ul>
*/
public void testLiteralBeyondLimit()
{
final SqlTester tester = getTester();
tester.setFor(SqlStdOperatorTable.castFunc);
for (BasicSqlType type : SqlLimitsTest.getTypes()) {
for (Object o : getValues(type, false)) {
SqlLiteral literal =
type.getSqlTypeName().createLiteral(o, SqlParserPos.ZERO);
String literalString =
literal.toSqlString(SqlUtil.dummyDialect);
if ((type.getSqlTypeName() == SqlTypeName.BIGINT)
|| ((type.getSqlTypeName() == SqlTypeName.DECIMAL)
&& (type.getPrecision() == 19)))
{
// Values which are too large to be literals fail at
// validate time.
tester.checkFails(
"CAST(^" + literalString + "^ AS " + type + ")",
"Numeric literal '.*' out of range",
false);
} else if (
(type.getSqlTypeName() == SqlTypeName.CHAR)
|| (type.getSqlTypeName() == SqlTypeName.VARCHAR)
|| (type.getSqlTypeName() == SqlTypeName.BINARY)
|| (type.getSqlTypeName() == SqlTypeName.VARBINARY))
{
// Casting overlarge string/binary values do not fail -
// they are truncated. See testCastTruncates().
} else {
// Value outside legal bound should fail at runtime (not
// validate time).
//
// NOTE: Because Java and Fennel calcs give
// different errors, the pattern hedges its bets.
tester.checkFails(
"CAST(" + literalString + " AS " + type + ")",
"(?s).*(Overflow during calculation or cast\\.|Code=22003).*",
true);
}
}
}
}
public void testCastTruncates()
{
final SqlTester tester = getTester();
tester.setFor(SqlStdOperatorTable.castFunc);
tester.checkScalar(
"CAST('ABCD' AS CHAR(2))",
"AB",
"CHAR(2) NOT NULL");
tester.checkScalar(
"CAST('ABCD' AS VARCHAR(2))",
"AB",
"VARCHAR(2) NOT NULL");
tester.checkScalar(
"CAST(x'ABCDEF12' AS BINARY(2))",
"ABCD",
"BINARY(2) NOT NULL");
if (Bug.Frg283Fixed)
tester.checkScalar(
"CAST(x'ABCDEF12' AS VARBINARY(2))",
"ABCD",
"VARBINARY(2) NOT NULL");
tester.checkBoolean(
"CAST(X'' AS BINARY(3)) = X'000000'",
true);
tester.checkBoolean(
"CAST(X'' AS BINARY(3)) = X''",
false);
}
private List<Object> getValues(BasicSqlType type, boolean inBound)
{
List<Object> values = new ArrayList<Object>();
for (boolean sign : FalseTrue) {
for (SqlTypeName.Limit limit : SqlTypeName.Limit.values()) {
Object o = type.getLimit(sign, limit, !inBound);
if (o == null) {
continue;
}
if (!values.contains(o)) {
values.add(o);
}
}
}
return values;
}
// TODO: Test other stuff
}
// End SqlOperatorTests.java
|
farrago/src/org/eigenbase/sql/test/SqlOperatorTests.java
|
/*
// $Id$
// Package org.eigenbase is a class library of data management components.
// Copyright (C) 2005-2007 The Eigenbase Project
// Copyright (C) 2002-2007 Disruptive Tech
// Copyright (C) 2005-2007 LucidEra, Inc.
// Portions Copyright (C) 2003-2007 John V. Sichi
//
// 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 approved by The Eigenbase Project.
//
// 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 org.eigenbase.sql.test;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import junit.framework.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.fun.*;
import org.eigenbase.sql.parser.*;
import org.eigenbase.sql.type.*;
import org.eigenbase.test.*;
import org.eigenbase.util.*;
/**
* Contains unit tests for all operators. Each of the methods is named after an
* operator.
*
* <p>The class is abstract. It contains a test for every operator, but does not
* provide a mechanism to execute the tests: parse, validate, and execute
* expressions on the operators. This is left to a {@link SqlTester} object
* which the derived class must provide.
*
* <p>Different implementations of {@link SqlTester} are possible, such as:
*
* <ul>
* <li>Execute against a real farrago database
* <li>Execute in pure java (parsing and validation can be done, but expression
* evaluation is not possible)
* <li>Generate a SQL script.
* <li>Analyze which operators are adequately tested.
* </ul>
*
* <p>A typical method will be named after the operator it is testing (say
* <code>testSubstringFunc</code>). It first calls {@link
* SqlTester#setFor(SqlOperator)} to declare which operator it is testing.
* <blockqoute>
*
* <pre><code>
* public void testSubstringFunc() {
* getTester().setFor(SqlStdOperatorTable.substringFunc);
* getTester().checkScalar("sin(0)", "0");
* getTester().checkScalar("sin(1.5707)", "1");
* }</code></pre>
*
* </blockqoute> The rest of the method contains calls to the various <code>
* checkXxx</code> methods in the {@link SqlTester} interface. For an operator
* to be adequately tested, there need to be tests for:
*
* <ul>
* <li>Parsing all of its the syntactic variants.
* <li>Deriving the type of in all combinations of arguments.
*
* <ul>
* <li>Pay particular attention to nullability. For example, the result of the
* "+" operator is NOT NULL if and only if both of its arguments are NOT
* NULL.</li>
* <li>Also pay attention to precsion/scale/length. For example, the maximum
* length of the "||" operator is the sum of the maximum lengths of its
* arguments.</li>
* </ul>
* </li>
* <li>Executing the function. Pay particular attention to corner cases such as
* null arguments or null results.</li>
* </ul>
*
* @author Julian Hyde
* @version $Id$
* @since October 1, 2004
*/
public abstract class SqlOperatorTests
extends TestCase
{
//~ Static fields/initializers ---------------------------------------------
public static final String NL = TestUtil.NL;
// TODO: Change message when Fnl3Fixed to something like
// "Invalid character for cast: PC=0 Code=22018"
public static final String invalidCharMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
// TODO: Change message when Fnl3Fixed to something like
// "Overflow during calculation or cast: PC=0 Code=22003"
public static final String outOfRangeMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
// TODO: Change message when Fnl3Fixed to something like
// "Division by zero: PC=0 Code=22012"
public static final String divisionByZeroMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
// TODO: Change message when Fnl3Fixed to something like
// "String right truncation: PC=0 Code=22001"
public static final String stringTruncMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
// TODO: Change message when Fnl3Fixed to something like
// "Invalid datetime format: PC=0 Code=22007"
public static final String badDatetimeMessage =
Bug.Fnl3Fixed ? null : "(?s).*";
public static final String literalOutOfRangeMessage =
"(?s).*Numeric literal.*out of range.*";
public static final boolean todo = false;
/**
* Regular expression for a SQL TIME(0) value.
*/
public static final Pattern timePattern =
Pattern.compile(
"[0-9][0-9]:[0-9][0-9]:[0-9][0-9]");
/**
* Regular expression for a SQL TIMESTAMP(3) value.
*/
public static final Pattern timestampPattern =
Pattern.compile(
"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] "
+ "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]\\.[0-9]+");
/**
* Regular expression for a SQL DATE value.
*/
public static final Pattern datePattern =
Pattern.compile(
"[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]");
public static final String [] numericTypeNames =
new String[] {
"TINYINT", "SMALLINT", "INTEGER", "BIGINT",
"DECIMAL(5, 2)", "REAL", "FLOAT", "DOUBLE"
};
// REVIEW jvs 27-Apr-2006: for Float and Double, MIN_VALUE
// is the smallest positive value, not the smallest negative value
public static final String [] minNumericStrings =
new String[] {
Long.toString(Byte.MIN_VALUE), Long.toString(
Short.MIN_VALUE), Long.toString(Integer.MIN_VALUE),
Long.toString(Long.MIN_VALUE), "-999.99",
// NOTE jvs 26-Apr-2006: Win32 takes smaller values from
// win32_values.h
"1E-37", /*Float.toString(Float.MIN_VALUE)*/
"2E-307", /*Double.toString(Double.MIN_VALUE)*/
"2E-307" /*Double.toString(Double.MIN_VALUE)*/,
};
public static final String [] minOverflowNumericStrings =
new String[] {
Long.toString(Byte.MIN_VALUE - 1),
Long.toString(Short.MIN_VALUE - 1),
Long.toString((long) Integer.MIN_VALUE - 1),
(new BigDecimal(Long.MIN_VALUE)).subtract(BigDecimal.ONE).toString(),
"-1000.00",
"1e-46",
"1e-324",
"1e-324"
};
public static final String [] maxNumericStrings =
new String[] {
Long.toString(Byte.MAX_VALUE), Long.toString(
Short.MAX_VALUE), Long.toString(Integer.MAX_VALUE),
Long.toString(Long.MAX_VALUE), "999.99",
// NOTE jvs 26-Apr-2006: use something slightly less than MAX_VALUE
// because roundtripping string to approx to string doesn't preserve
// MAX_VALUE on win32
"3.4028234E38", /*Float.toString(Float.MAX_VALUE)*/
"1.79769313486231E308", /*Double.toString(Double.MAX_VALUE)*/
"1.79769313486231E308" /*Double.toString(Double.MAX_VALUE)*/
};
public static final String [] maxOverflowNumericStrings =
new String[] {
Long.toString(Byte.MAX_VALUE + 1),
Long.toString(Short.MAX_VALUE + 1),
Long.toString((long) Integer.MAX_VALUE + 1),
(new BigDecimal(Long.MAX_VALUE)).add(BigDecimal.ONE).toString(),
"1000.00",
"1e39",
"-1e309",
"1e309"
};
private static final boolean [] FalseTrue = new boolean[] { false, true };
//~ Constructors -----------------------------------------------------------
public SqlOperatorTests(String testName)
{
super(testName);
}
//~ Methods ----------------------------------------------------------------
/**
* Derived class must implement this method to provide a means to validate,
* execute various statements.
*/
protected abstract SqlTester getTester();
protected void setUp()
throws Exception
{
getTester().setFor(null);
}
public void testBetween()
{
getTester().setFor(SqlStdOperatorTable.betweenOperator);
getTester().checkBoolean("2 between 1 and 3", Boolean.TRUE);
getTester().checkBoolean("2 between 3 and 2", Boolean.FALSE);
getTester().checkBoolean("2 between symmetric 3 and 2", Boolean.TRUE);
getTester().checkBoolean("3 between 1 and 3", Boolean.TRUE);
getTester().checkBoolean("4 between 1 and 3", Boolean.FALSE);
getTester().checkBoolean("1 between 4 and -3", Boolean.FALSE);
getTester().checkBoolean("1 between -1 and -3", Boolean.FALSE);
getTester().checkBoolean("1 between -1 and 3", Boolean.TRUE);
getTester().checkBoolean("1 between 1 and 1", Boolean.TRUE);
getTester().checkBoolean("1.5 between 1 and 3", Boolean.TRUE);
getTester().checkBoolean("1.2 between 1.1 and 1.3", Boolean.TRUE);
getTester().checkBoolean("1.5 between 2 and 3", Boolean.FALSE);
getTester().checkBoolean("1.5 between 1.6 and 1.7", Boolean.FALSE);
getTester().checkBoolean("1.2e1 between 1.1 and 1.3", Boolean.FALSE);
getTester().checkBoolean("1.2e0 between 1.1 and 1.3", Boolean.TRUE);
getTester().checkBoolean("1.5e0 between 2 and 3", Boolean.FALSE);
getTester().checkBoolean("1.5e0 between 2e0 and 3e0", Boolean.FALSE);
getTester().checkBoolean(
"1.5e1 between 1.6e1 and 1.7e1",
Boolean.FALSE);
getTester().checkBoolean("x'' between x'' and x''", Boolean.TRUE);
getTester().checkNull("cast(null as integer) between -1 and 2");
getTester().checkNull("1 between -1 and cast(null as integer)");
getTester().checkNull(
"1 between cast(null as integer) and cast(null as integer)");
getTester().checkNull("1 between cast(null as integer) and 1");
}
public void testNotBetween()
{
getTester().setFor(SqlStdOperatorTable.notBetweenOperator);
getTester().checkBoolean("2 not between 1 and 3", Boolean.FALSE);
getTester().checkBoolean("3 not between 1 and 3", Boolean.FALSE);
getTester().checkBoolean("4 not between 1 and 3", Boolean.TRUE);
getTester().checkBoolean(
"1.2e0 not between 1.1 and 1.3",
Boolean.FALSE);
getTester().checkBoolean("1.2e1 not between 1.1 and 1.3", Boolean.TRUE);
getTester().checkBoolean("1.5e0 not between 2 and 3", Boolean.TRUE);
getTester().checkBoolean("1.5e0 not between 2e0 and 3e0", Boolean.TRUE);
}
private String getCastString(
String value,
String targetType,
boolean errorLoc)
{
if (errorLoc) {
value = "^" + value + "^";
}
return "cast(" + value + " as " + targetType + ")";
}
private void checkCastToApproxOkay(
String value,
String targetType,
double expected,
double delta)
{
getTester().checkScalarApprox(
getCastString(value, targetType, false),
targetType + " NOT NULL",
expected,
delta);
}
private void checkCastToStringOkay(
String value,
String targetType,
String expected)
{
getTester().checkString(
getCastString(value, targetType, false),
expected,
targetType + " NOT NULL");
}
private void checkCastToScalarOkay(
String value,
String targetType,
String expected)
{
getTester().checkScalarExact(
getCastString(value, targetType, false),
targetType + " NOT NULL",
expected);
}
private void checkCastToScalarOkay(String value, String targetType)
{
checkCastToScalarOkay(value, targetType, value);
}
private void checkCastFails(
String value,
String targetType,
String expectedError,
boolean runtime)
{
getTester().checkFails(
getCastString(value, targetType, !runtime),
expectedError,
runtime);
}
private void checkCastToString(String value, String type, String expected)
{
String spaces = " ";
if (expected == null) {
expected = value.trim();
}
int len = expected.length();
if (type != null) {
value = getCastString(value, type, false);
}
checkCastFails(
value,
"VARCHAR(" + (len - 1) + ")",
stringTruncMessage,
true);
checkCastToStringOkay(value, "VARCHAR(" + len + ")", expected);
checkCastToStringOkay(value, "VARCHAR(" + (len + 5) + ")", expected);
checkCastFails(
value,
"CHAR(" + (len - 1) + ")",
stringTruncMessage,
true);
checkCastToStringOkay(value, "CHAR(" + len + ")", expected);
checkCastToStringOkay(
value,
"CHAR(" + (len + 5) + ")",
expected + spaces);
}
public void testCastChar()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
// "CHAR" is shorthand for "CHAR(1)"
getTester().checkString("CAST('abc' AS CHAR)", "a", "CHAR(1) NOT NULL");
getTester().checkString(
"CAST('abc' AS VARCHAR)",
"a",
"VARCHAR(1) NOT NULL");
}
public void testCastExactNumerics()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
// Test casting for min,max, out of range for exact numeric types
for (int i = 0; i < numericTypeNames.length; i++) {
String type = numericTypeNames[i];
if (type.equalsIgnoreCase("DOUBLE")
|| type.equalsIgnoreCase("FLOAT")
|| type.equalsIgnoreCase("REAL"))
{
// Skip approx types
continue;
}
// Convert from literal to type
checkCastToScalarOkay(maxNumericStrings[i], type);
checkCastToScalarOkay(minNumericStrings[i], type);
// Overflow test
if (type.equalsIgnoreCase("BIGINT")) {
// Literal of range
checkCastFails(
maxOverflowNumericStrings[i],
type,
literalOutOfRangeMessage,
false);
checkCastFails(
minOverflowNumericStrings[i],
type,
literalOutOfRangeMessage,
false);
} else {
checkCastFails(
maxOverflowNumericStrings[i],
type,
outOfRangeMessage,
true);
checkCastFails(
minOverflowNumericStrings[i],
type,
outOfRangeMessage,
true);
}
// Convert from string to type
checkCastToScalarOkay(
"'" + maxNumericStrings[i] + "'",
type,
maxNumericStrings[i]);
checkCastToScalarOkay(
"'" + minNumericStrings[i] + "'",
type,
minNumericStrings[i]);
checkCastFails(
"'" + maxOverflowNumericStrings[i] + "'",
type,
outOfRangeMessage,
true);
checkCastFails(
"'" + minOverflowNumericStrings[i] + "'",
type,
outOfRangeMessage,
true);
// Convert from type to string
checkCastToString(maxNumericStrings[i], null, null);
checkCastToString(maxNumericStrings[i], type, null);
checkCastToString(minNumericStrings[i], null, null);
checkCastToString(minNumericStrings[i], type, null);
checkCastFails("'notnumeric'", type, invalidCharMessage, true);
}
getTester().checkScalarExact(
"cast(1.0 as bigint)",
"BIGINT NOT NULL",
"1");
getTester().checkScalarExact("cast(1.0 as int)", "1");
}
public void testCastApproxNumerics()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
// Test casting for min,max, out of range for approx numeric types
for (int i = 0; i < numericTypeNames.length; i++) {
String type = numericTypeNames[i];
boolean isFloat;
if (type.equalsIgnoreCase("DOUBLE")
|| type.equalsIgnoreCase("FLOAT"))
{
isFloat = false;
} else if (type.equalsIgnoreCase("REAL")) {
isFloat = true;
} else {
// Skip non-approx types
continue;
}
// Convert from literal to type
checkCastToApproxOkay(
maxNumericStrings[i],
type,
Double.parseDouble(maxNumericStrings[i]),
isFloat ? 1E32 : 0);
checkCastToApproxOkay(
minNumericStrings[i],
type,
Double.parseDouble(minNumericStrings[i]),
0);
if (isFloat) {
checkCastFails(
maxOverflowNumericStrings[i],
type,
outOfRangeMessage,
true);
} else {
// Double: Literal out of range
checkCastFails(
maxOverflowNumericStrings[i],
type,
literalOutOfRangeMessage,
false);
}
// Underflow: goes to 0
checkCastToApproxOkay(minOverflowNumericStrings[i], type, 0, 0);
// Convert from string to type
checkCastToApproxOkay(
"'" + maxNumericStrings[i] + "'",
type,
Double.parseDouble(maxNumericStrings[i]),
isFloat ? 1E32 : 0);
checkCastToApproxOkay(
"'" + minNumericStrings[i] + "'",
type,
Double.parseDouble(minNumericStrings[i]),
0);
checkCastFails(
"'" + maxOverflowNumericStrings[i] + "'",
type,
outOfRangeMessage,
true);
// Underflow: goes to 0
checkCastToApproxOkay(
"'" + minOverflowNumericStrings[i] + "'",
type,
0,
0);
// Convert from type to string
// Treated as DOUBLE
checkCastToString(
maxNumericStrings[i],
null,
isFloat ? null : "1.79769313486231E308");
/*
// TODO: The following tests are slightly different depending on //
whether the java or fennel calc are used. // Try to make them
the same if (FennelCalc) { // Treated as FLOAT or DOUBLE
checkCastToString(maxNumericStrings[i], type, isFloat?
"3.402824E38": "1.797693134862316E308"); // Treated as DOUBLE
checkCastToString(minNumericStrings[i], null, isFloat? null:
"4.940656458412465E-324"); // Treated as FLOAT or DOUBLE
checkCastToString(minNumericStrings[i], type, isFloat?
"1.401299E-45": "4.940656458412465E-324"); } else if (JavaCalc) {
// Treated as FLOAT or DOUBLE
checkCastToString(maxNumericStrings[i], type, isFloat?
"3.402823E38": "1.797693134862316E308"); // Treated as DOUBLE
checkCastToString(minNumericStrings[i], null, isFloat? null:
null); // Treated as FLOAT or DOUBLE
checkCastToString(minNumericStrings[i], type, isFloat?
"1.401298E-45": null); }
*/
checkCastFails("'notnumeric'", type, invalidCharMessage, true);
}
getTester().checkScalarExact(
"cast(1.0e0 as bigint)",
"BIGINT NOT NULL",
"1");
getTester().checkScalarExact("cast(1.0e0 as int)", "1");
}
public void testCastDecimalToInteger()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
// decimal to integer
getTester().checkScalarExact("cast(1.25 as integer)", "1");
getTester().checkScalarExact("cast(-1.25 as integer)", "-1");
getTester().checkScalarExact("cast(1.75 as integer)", "2");
getTester().checkScalarExact("cast(-1.75 as integer)", "-2");
getTester().checkScalarExact("cast(1.5 as integer)", "2");
getTester().checkScalarExact("cast(-1.5 as integer)", "-2");
}
public void testCastDecimalToDecimal()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
// decimal to decimal
getTester().checkScalarExact(
"cast(1.29 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.3");
getTester().checkScalarExact(
"cast(1.25 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.3");
getTester().checkScalarExact(
"cast(1.21 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.2");
getTester().checkScalarExact(
"cast(-1.29 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.3");
getTester().checkScalarExact(
"cast(-1.25 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.3");
getTester().checkScalarExact(
"cast(-1.21 as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.2");
// decimal to decimal
getTester().checkScalarExact(
"cast(1.29 as decimal(7,5))",
"DECIMAL(7, 5) NOT NULL",
"1.29000");
getTester().checkScalarExact(
"cast(-1.21 as decimal(7,5))",
"DECIMAL(7, 5) NOT NULL",
"-1.21000");
getTester().checkScalarExact(
"cast(-1.21 as decimal)",
"DECIMAL(19, 0) NOT NULL",
"-1");
// 9.99 round to 10.0, should give out of range error
getTester().checkFails(
"cast(9.99 as decimal(2,1))",
outOfRangeMessage,
true);
}
public void testCastDecimalToDoubleToInteger()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
getTester().checkScalarExact(
"cast( cast(1.25 as double) as integer)",
"1");
getTester().checkScalarExact(
"cast( cast(-1.25 as double) as integer)",
"-1");
getTester().checkScalarExact(
"cast( cast(1.75 as double) as integer)",
"2");
getTester().checkScalarExact(
"cast( cast(-1.75 as double) as integer)",
"-2");
getTester().checkScalarExact(
"cast( cast(1.5 as double) as integer)",
"2");
getTester().checkScalarExact(
"cast( cast(-1.5 as double) as integer)",
"-2");
}
public void testCastToDouble()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
getTester().checkScalarApprox(
"cast(1 as double)",
"DOUBLE NOT NULL",
1,
0);
getTester().checkScalarApprox(
"cast(1.0 as double)",
"DOUBLE NOT NULL",
1,
0);
getTester().checkScalarApprox(
"cast(-5.9 as double)",
"DOUBLE NOT NULL",
-5.9,
0);
}
public void testCastNull()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
// null
getTester().checkNull("cast(null as decimal(4,3))");
getTester().checkNull("cast(null as double)");
getTester().checkNull("cast(null as varchar(10))");
getTester().checkNull("cast(null as char(10))");
}
public void testCastDateTime()
{
// Test cast for date/time/timestamp
getTester().setFor(SqlStdOperatorTable.castFunc);
getTester().checkScalar(
"cast(TIMESTAMP '1945-02-24 12:42:25.34' as TIMESTAMP)",
"1945-02-24 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
getTester().checkScalar(
"cast(TIME '12:42:25.34' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
// test rounding
getTester().checkScalar(
"cast(TIME '12:42:25.9' as TIME)",
"12:42:26",
"TIME(0) NOT NULL");
if (Bug.Frg282Fixed) {
// test precision
getTester().checkScalar(
"cast(TIME '12:42:25.34' as TIME(2))",
"12:42:25.34",
"TIME(2) NOT NULL");
}
getTester().checkScalar(
"cast(DATE '1945-02-24' as DATE)",
"1945-02-24",
"DATE NOT NULL");
// timestamp <-> time
getTester().checkScalar(
"cast(TIMESTAMP '1945-02-24 12:42:25.34' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
// Generate the current date as a string, e.g. "2007-04-18". The value
// is guaranteed to be good for at least 2 minutes, which should give
// us time to run the rest of the tests.
final String today;
while (true) {
final Calendar cal = Calendar.getInstance();
if ((cal.get(Calendar.HOUR_OF_DAY) == 23)
&& (cal.get(Calendar.MINUTE) >= 58))
{
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
// ignore
}
} else {
today =
new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
break;
}
}
// Note: Casting to time(0) should lose date info and fractional
// seconds, then casting back to timestamp should initialize to
// current_date.
if (Bug.Fnl66Fixed) {
getTester().checkScalar(
"cast(cast(TIMESTAMP '1945-02-24 12:42:25.34' as TIME) as TIMESTAMP)",
today + " 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
getTester().checkScalar(
"cast(TIME '12:42:25.34' as TIMESTAMP)",
today + " 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
}
// timestamp <-> date
getTester().checkScalar(
"cast(TIMESTAMP '1945-02-24 12:42:25.34' as DATE)",
"1945-02-24",
"DATE NOT NULL");
// Note: casting to Date discards Time fields
getTester().checkScalar(
"cast(cast(TIMESTAMP '1945-02-24 12:42:25.34' as DATE) as TIMESTAMP)",
"1945-02-24 00:00:00.0",
"TIMESTAMP(0) NOT NULL");
// TODO: precision should not be included
getTester().checkScalar(
"cast(DATE '1945-02-24' as TIMESTAMP)",
"1945-02-24 00:00:00.0",
"TIMESTAMP(0) NOT NULL");
// time <-> string
checkCastToString("TIME '12:42:25'", null, "12:42:25");
if (todo) {
checkCastToString("TIME '12:42:25.34'", null, "12:42:25.34");
}
getTester().checkScalar(
"cast('12:42:25' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
getTester().checkScalar(
"cast('1:42:25' as TIME)",
"01:42:25",
"TIME(0) NOT NULL");
getTester().checkScalar(
"cast('1:2:25' as TIME)",
"01:02:25",
"TIME(0) NOT NULL");
getTester().checkScalar(
"cast(' 12:42:25 ' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
getTester().checkScalar(
"cast('12:42:25.34' as TIME)",
"12:42:25",
"TIME(0) NOT NULL");
if (Bug.Frg282Fixed) {
getTester().checkScalar(
"cast('12:42:25.34' as TIME(2))",
"12:42:25.34",
"TIME(2) NOT NULL");
}
getTester().checkFails(
"cast('nottime' as TIME)",
badDatetimeMessage,
true);
getTester().checkFails(
"cast('1241241' as TIME)",
badDatetimeMessage,
true);
getTester().checkFails(
"cast('12:54:78' as TIME)",
badDatetimeMessage,
true);
// timestamp <-> string
if (todo) {
// TODO: Java calc displays ".0" while Fennel does not
checkCastToString(
"TIMESTAMP '1945-02-24 12:42:25'",
null,
"1945-02-24 12:42:25.0");
// TODO: casting allows one to discard precision without error
checkCastToString(
"TIMESTAMP '1945-02-24 12:42:25.34'",
null,
"1945-02-24 12:42:25.34");
}
getTester().checkScalar(
"cast('1945-02-24 12:42:25' as TIMESTAMP)",
"1945-02-24 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
getTester().checkScalar(
"cast('1945-2-2 12:2:5' as TIMESTAMP)",
"1945-02-02 12:02:05.0",
"TIMESTAMP(0) NOT NULL");
getTester().checkScalar(
"cast(' 1945-02-24 12:42:25 ' as TIMESTAMP)",
"1945-02-24 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
getTester().checkScalar(
"cast('1945-02-24 12:42:25.34' as TIMESTAMP)",
"1945-02-24 12:42:25.0",
"TIMESTAMP(0) NOT NULL");
if (Bug.Frg282Fixed) {
getTester().checkScalar(
"cast('1945-02-24 12:42:25.34' as TIMESTAMP(2))",
"1945-02-24 12:42:25.34",
"TIMESTAMP(2) NOT NULL");
}
getTester().checkFails(
"cast('nottime' as TIMESTAMP)",
badDatetimeMessage,
true);
getTester().checkFails(
"cast('1241241' as TIMESTAMP)",
badDatetimeMessage,
true);
getTester().checkFails(
"cast('1945-20-24 12:42:25.34' as TIMESTAMP)",
badDatetimeMessage,
true);
getTester().checkFails(
"cast('1945-01-24 25:42:25.34' as TIMESTAMP)",
badDatetimeMessage,
true);
// date <-> string
checkCastToString("DATE '1945-02-24'", null, "1945-02-24");
checkCastToString("DATE '1945-2-24'", null, "1945-02-24");
getTester().checkScalar(
"cast('1945-02-24' as DATE)",
"1945-02-24",
"DATE NOT NULL");
getTester().checkScalar(
"cast(' 1945-02-24 ' as DATE)",
"1945-02-24",
"DATE NOT NULL");
getTester().checkFails(
"cast('notdate' as DATE)",
badDatetimeMessage,
true);
getTester().checkFails(
"cast('52534253' as DATE)",
badDatetimeMessage,
true);
getTester().checkFails(
"cast('1945-30-24' as DATE)",
badDatetimeMessage,
true);
// cast null
getTester().checkNull("cast(null as date)");
getTester().checkNull("cast(null as timestamp)");
getTester().checkNull("cast(null as time)");
getTester().checkNull("cast(cast(null as varchar(10)) as time)");
getTester().checkNull("cast(cast(null as varchar(10)) as date)");
getTester().checkNull("cast(cast(null as varchar(10)) as timestamp)");
getTester().checkNull("cast(cast(null as date) as timestamp)");
getTester().checkNull("cast(cast(null as time) as timestamp)");
getTester().checkNull("cast(cast(null as timestamp) as date)");
getTester().checkNull("cast(cast(null as timestamp) as time)");
}
public void testCastExactString()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
// string to decimal
getTester().checkScalarExact(
"cast('1.29' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.3");
getTester().checkScalarExact(
"cast(' 1.25 ' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.3");
getTester().checkScalarExact(
"cast('1.21' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"1.2");
getTester().checkScalarExact(
"cast(' -1.29 ' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.3");
getTester().checkScalarExact(
"cast('-1.25' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.3");
getTester().checkScalarExact(
"cast(' -1.21 ' as decimal(2,1))",
"DECIMAL(2, 1) NOT NULL",
"-1.2");
getTester().checkFails(
"cast(' -1.21e' as decimal(2,1))",
invalidCharMessage,
true);
// decimal to string
getTester().checkString(
"cast(1.29 as varchar(10))",
"1.29",
"VARCHAR(10) NOT NULL");
getTester().checkString(
"cast(.48 as varchar(10))",
".48",
"VARCHAR(10) NOT NULL");
getTester().checkFails(
"cast(2.523 as char(2))",
stringTruncMessage,
true);
getTester().checkString(
"cast(-0.29 as varchar(10))",
"-.29",
"VARCHAR(10) NOT NULL");
getTester().checkString(
"cast(-1.29 as varchar(10))",
"-1.29",
"VARCHAR(10) NOT NULL");
// string to integer
getTester().checkScalarExact("cast('6543' as integer)", "6543");
if (Bug.Frg26Fixed) {
getTester().checkScalarExact("cast(' -123 ' as int)", "-123");
}
getTester().checkScalarExact(
"cast('654342432412312' as bigint)",
"BIGINT NOT NULL",
"654342432412312");
// integer to string
getTester().checkString(
"cast(9354 as varchar(10))",
"9354",
"VARCHAR(10) NOT NULL");
}
public void testCastApproxString()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
// string to double/float/real
getTester().checkScalarApprox(
"cast('1' as double)",
"DOUBLE NOT NULL",
1,
0);
getTester().checkScalarApprox(
"cast('2.3' as float)",
"FLOAT NOT NULL",
2.3,
0);
getTester().checkScalarApprox(
"cast('-10.2' as real)",
"REAL NOT NULL",
-10.2,
0);
getTester().checkScalarApprox(
"cast('4e2' as double)",
"DOUBLE NOT NULL",
400,
0);
getTester().checkScalarApprox(
"cast('2.1e1' as float)",
"FLOAT NOT NULL",
21,
0);
getTester().checkScalarApprox(
"cast('-12e-1' as real)",
"REAL NOT NULL",
-1.2,
0);
getTester().checkScalarApprox(
"cast(' -43 ' as double)",
"DOUBLE NOT NULL",
-43,
0);
getTester().checkScalarApprox(
"cast(' 23e-1 ' as float)",
"FLOAT NOT NULL",
2.3,
0);
getTester().checkScalarApprox(
"cast(' 123e+1 ' as real)",
"REAL NOT NULL",
1230,
0);
// double/float/real to string
getTester().checkString(
"cast(0e0 as varchar(5))",
"0E0",
"VARCHAR(5) NOT NULL");
getTester().checkString(
"cast(4e1 as varchar(5))",
"4E1",
"VARCHAR(5) NOT NULL");
getTester().checkString(
"cast(45e1 as varchar(5))",
"4.5E2",
"VARCHAR(5) NOT NULL");
getTester().checkString(
"cast(4.6834e0 as varchar(50))",
"4.6834E0",
"VARCHAR(50) NOT NULL");
getTester().checkString(
"cast(4683442.3432498375e0 as varchar(20))",
"4.683442343249838E6",
"VARCHAR(20) NOT NULL");
getTester().checkString(
"cast(cast(0.1 as real) as char(10))",
"1E-1 ",
"CHAR(10) NOT NULL");
getTester().checkString(
"cast(cast(-0.0036 as float) as char(10))",
"-3.6E-3 ",
"CHAR(10) NOT NULL");
getTester().checkString(
"cast(cast(3.23e0 as real) as varchar(20))",
"3.23E0",
"VARCHAR(20) NOT NULL");
getTester().checkString(
"cast(cast(5.2365439 as real) as varchar(20))",
"5.236544E0",
"VARCHAR(20) NOT NULL");
getTester().checkString(
"cast(-1e0 as char(6))",
"-1E0 ",
"CHAR(6) NOT NULL");
getTester().checkFails(
"cast(1.3243232e0 as varchar(4))",
stringTruncMessage,
true);
getTester().checkFails(
"cast(1.9e5 as char(4))",
stringTruncMessage,
true);
}
public void testCastBooleanString()
{
getTester().setFor(SqlStdOperatorTable.castFunc);
// boolean to string (char)
getTester().checkString(
"cast(true as char(4))",
"TRUE",
"CHAR(4) NOT NULL");
getTester().checkString(
"cast(false as char(5))",
"FALSE",
"CHAR(5) NOT NULL");
getTester().checkString(
"cast(true as char(8))",
"TRUE ",
"CHAR(8) NOT NULL");
getTester().checkString(
"cast(false as char(8))",
"FALSE ",
"CHAR(8) NOT NULL");
getTester().checkFails(
"cast(true as char(3))",
invalidCharMessage,
true);
getTester().checkFails(
"cast(false as char(4))",
invalidCharMessage,
true);
// boolean to string (varchar)
getTester().checkString(
"cast(true as varchar(4))",
"TRUE",
"VARCHAR(4) NOT NULL");
getTester().checkString(
"cast(false as varchar(5))",
"FALSE",
"VARCHAR(5) NOT NULL");
getTester().checkString(
"cast(true as varchar(8))",
"TRUE",
"VARCHAR(8) NOT NULL");
getTester().checkString(
"cast(false as varchar(8))",
"FALSE",
"VARCHAR(8) NOT NULL");
getTester().checkFails(
"cast(true as varchar(3))",
invalidCharMessage,
true);
getTester().checkFails(
"cast(false as varchar(4))",
invalidCharMessage,
true);
// string to boolean
getTester().checkBoolean("cast('true' as boolean)", Boolean.TRUE);
getTester().checkBoolean("cast('false' as boolean)", Boolean.FALSE);
getTester().checkBoolean("cast(' trUe' as boolean)", Boolean.TRUE);
getTester().checkBoolean("cast(' fALse' as boolean)", Boolean.FALSE);
getTester().checkFails(
"cast('unknown' as boolean)",
invalidCharMessage,
true);
getTester().checkFails(
"cast('blah' as boolean)",
invalidCharMessage,
true);
getTester().checkBoolean(
"cast(cast('true' as varchar(10)) as boolean)",
Boolean.TRUE);
getTester().checkBoolean(
"cast(cast('false' as varchar(10)) as boolean)",
Boolean.FALSE);
getTester().checkFails(
"cast(cast('blah' as varchar(10)) as boolean)",
invalidCharMessage,
true);
}
public void testCase()
{
getTester().setFor(SqlStdOperatorTable.caseOperator);
getTester().checkScalarExact("case when 'a'='a' then 1 end", "1");
getTester().checkString(
"case 2 when 1 then 'a' when 2 then 'bcd' end",
"bcd",
"CHAR(3)");
getTester().checkString(
"case 1 when 1 then 'a' when 2 then 'bcd' end",
"a ",
"CHAR(3)");
getTester().checkString(
"case 1 when 1 then cast('a' as varchar(1)) "
+ "when 2 then cast('bcd' as varchar(3)) end",
"a",
"VARCHAR(3)");
getTester().checkScalarExact(
"case 2 when 1 then 11.2 when 2 then 4.543 else null end",
"DECIMAL(5, 3)",
"4.543");
getTester().checkScalarExact(
"case 1 when 1 then 11.2 when 2 then 4.543 else null end",
"DECIMAL(5, 3)",
"11.200");
getTester().checkScalarExact("case 'a' when 'a' then 1 end", "1");
getTester().checkScalarApprox(
"case 1 when 1 then 11.2e0 when 2 then cast(4 as bigint) else 3 end",
"DOUBLE NOT NULL",
11.2,
0);
getTester().checkScalarApprox(
"case 1 when 1 then 11.2e0 when 2 then 4 else null end",
"DOUBLE",
11.2,
0);
getTester().checkScalarApprox(
"case 2 when 1 then 11.2e0 when 2 then 4 else null end",
"DOUBLE",
4,
0);
getTester().checkScalarApprox(
"case 1 when 1 then 11.2e0 when 2 then 4.543 else null end",
"DOUBLE",
11.2,
0);
getTester().checkScalarApprox(
"case 2 when 1 then 11.2e0 when 2 then 4.543 else null end",
"DOUBLE",
4.543,
0);
getTester().checkNull("case 'a' when 'b' then 1 end");
getTester().checkScalarExact(
"case when 'a'=cast(null as varchar(1)) then 1 else 2 end",
"2");
if (todo) {
getTester().checkScalar(
"case 1 when 1 then row(1,2) when 2 then row(2,3) end",
"ROW(INTEGER NOT NULL, INTEGER NOT NULL)",
"row(1,2)");
getTester().checkScalar(
"case 1 when 1 then row('a','b') when 2 then row('ab','cd') end",
"ROW(CHAR(2) NOT NULL, CHAR(2) NOT NULL)",
"row('a ','b ')");
}
// TODO: Check case with multisets
}
public void testCaseType()
{
getTester().setFor(SqlStdOperatorTable.caseOperator);
getTester().checkType(
"case 1 when 1 then current_timestamp else null end",
"TIMESTAMP(0)");
getTester().checkType(
"case 1 when 1 then current_timestamp else current_timestamp end",
"TIMESTAMP(0) NOT NULL");
getTester().checkType(
"case when true then current_timestamp else null end",
"TIMESTAMP(0)");
getTester().checkType(
"case when true then current_timestamp end",
"TIMESTAMP(0)");
getTester().checkType(
"case 'x' when 'a' then 3 when 'b' then null else 4.5 end",
"DECIMAL(11, 1)");
}
public void testJdbcFn()
{
getTester().setFor(new SqlJdbcFunctionCall("dummy"));
}
public void testSelect()
{
getTester().setFor(SqlStdOperatorTable.selectOperator);
getTester().check(
"select * from (values(1))",
AbstractSqlTester.IntegerTypeChecker,
"1",
0);
// check return type on scalar subquery in select list. Note return
// type is always nullable even if subquery select value is NOT NULL.
if (Bug.Frg189Fixed) {
getTester().checkType(
"SELECT *,(SELECT * FROM (VALUES(1))) FROM (VALUES(2))",
"RecordType(INTEGER NOT NULL EXPR$0, INTEGER EXPR$1) NOT NULL");
getTester().checkType(
"SELECT *,(SELECT * FROM (VALUES(CAST(10 as BIGINT)))) "
+ "FROM (VALUES(CAST(10 as bigint)))",
"RecordType(BIGINT NOT NULL EXPR$0, BIGINT EXPR$1) NOT NULL");
getTester().checkType(
" SELECT *,(SELECT * FROM (VALUES(10.5))) FROM (VALUES(10.5))",
"RecordType(DECIMAL(3, 1) NOT NULL EXPR$0, DECIMAL(3, 1) EXPR$1) NOT NULL");
getTester().checkType(
"SELECT *,(SELECT * FROM (VALUES('this is a char'))) "
+ "FROM (VALUES('this is a char too'))",
"RecordType(CHAR(18) NOT NULL EXPR$0, CHAR(14) EXPR$1) NOT NULL");
getTester().checkType(
"SELECT *,(SELECT * FROM (VALUES(true))) FROM (values(false))",
"RecordType(BOOLEAN NOT NULL EXPR$0, BOOLEAN EXPR$1) NOT NULL");
getTester().checkType(
" SELECT *,(SELECT * FROM (VALUES(cast('abcd' as varchar(10))))) "
+ "FROM (VALUES(CAST('abcd' as varchar(10))))",
"RecordType(VARCHAR(10) NOT NULL EXPR$0, VARCHAR(10) EXPR$1) NOT NULL");
getTester().checkType(
"SELECT *,"
+ " (SELECT * FROM (VALUES(TIMESTAMP '2006-01-01 12:00:05'))) "
+ "FROM (VALUES(TIMESTAMP '2006-01-01 12:00:05'))",
"RecordType(TIMESTAMP(0) NOT NULL EXPR$0, TIMESTAMP(0) EXPR$1) NOT NULL");
}
}
public void testLiteralChain()
{
getTester().setFor(SqlStdOperatorTable.literalChainOperator);
getTester().checkString(
"'buttered'\n' toast'",
"buttered toast",
"CHAR(14) NOT NULL");
getTester().checkString(
"'corned'\n' beef'\n' on'\n' rye'",
"corned beef on rye",
"CHAR(18) NOT NULL");
getTester().checkString(
"_latin1'Spaghetti'\n' all''Amatriciana'",
"Spaghetti all'Amatriciana",
"CHAR(25) NOT NULL");
getTester().checkBoolean("x'1234'\n'abcd' = x'1234abcd'", Boolean.TRUE);
getTester().checkBoolean("x'1234'\n'' = x'1234'", Boolean.TRUE);
getTester().checkBoolean("x''\n'ab' = x'ab'", Boolean.TRUE);
}
public void testRow()
{
getTester().setFor(SqlStdOperatorTable.rowConstructor);
}
public void testAndOperator()
{
getTester().setFor(SqlStdOperatorTable.andOperator);
getTester().checkBoolean("true and false", Boolean.FALSE);
getTester().checkBoolean("true and true", Boolean.TRUE);
getTester().checkBoolean(
"cast(null as boolean) and false",
Boolean.FALSE);
getTester().checkBoolean(
"false and cast(null as boolean)",
Boolean.FALSE);
getTester().checkNull("cast(null as boolean) and true");
getTester().checkBoolean("true and (not false)", Boolean.TRUE);
}
public void testConcatOperator()
{
getTester().setFor(SqlStdOperatorTable.concatOperator);
getTester().checkString(" 'a'||'b' ", "ab", "CHAR(2) NOT NULL");
if (todo) {
// not yet implemented
getTester().checkString(
" x'f'||x'f' ",
"X'FF",
"BINARY(1) NOT NULL");
getTester().checkNull("x'ff' || cast(null as varbinary)");
}
}
public void testDivideOperator()
{
getTester().setFor(SqlStdOperatorTable.divideOperator);
getTester().checkScalarExact("10 / 5", "2");
getTester().checkScalarExact("-10 / 5", "-2");
getTester().checkScalarExact("1 / 3", "0");
getTester().checkScalarApprox(
" cast(10.0 as double) / 5",
"DOUBLE NOT NULL",
2.0,
0);
getTester().checkScalarApprox(
" cast(10.0 as real) / 5",
"REAL NOT NULL",
2.0,
0);
getTester().checkScalarApprox(
" 6.0 / cast(10.0 as real) ",
"DOUBLE NOT NULL",
0.6,
0);
getTester().checkScalarExact(
"10.0 / 5.0",
"DECIMAL(9, 6) NOT NULL",
"2.000000");
getTester().checkScalarExact(
"1.0 / 3.0",
"DECIMAL(8, 6) NOT NULL",
"0.333333");
getTester().checkScalarExact(
"100.1 / 0.0001",
"DECIMAL(14, 7) NOT NULL",
"1001000.0000000");
getTester().checkScalarExact(
"100.1 / 0.00000001",
"DECIMAL(19, 8) NOT NULL",
"10010000000.00000000");
getTester().checkNull("1e1 / cast(null as float)");
getTester().checkFails(
"100.1 / 0.00000000000000001",
outOfRangeMessage,
true);
// Intervals
getTester().checkScalar(
"interval '-2:2' hour to minute / 3",
"-0:40",
"INTERVAL HOUR TO MINUTE NOT NULL");
getTester().checkScalar(
"interval '2:5:12' hour to second / 2 / -3",
"-0:20:52",
"INTERVAL HOUR TO SECOND NOT NULL");
getTester().checkNull(
"interval '2' day / cast(null as bigint)");
getTester().checkNull(
"cast(null as interval month) / 2");
if (todo) {
getTester().checkScalar(
"interval '3-3' year to month / 15e-1",
"+02-02",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkScalar(
"interval '3-4' year to month / 4.5",
"+00-08",
"INTERVAL YEAR TO MONTH NOT NULL");
}
}
public void testEqualsOperator()
{
getTester().setFor(SqlStdOperatorTable.equalsOperator);
getTester().checkBoolean("1=1", Boolean.TRUE);
getTester().checkBoolean("1=1.0", Boolean.TRUE);
getTester().checkBoolean("1.34=1.34", Boolean.TRUE);
getTester().checkBoolean("1=1.34", Boolean.FALSE);
getTester().checkBoolean("1e2=100e0", Boolean.TRUE);
getTester().checkBoolean("1e2=101", Boolean.FALSE);
getTester().checkBoolean(
"cast(1e2 as real)=cast(101 as bigint)",
Boolean.FALSE);
getTester().checkBoolean("'a'='b'", Boolean.FALSE);
getTester().checkBoolean(
"cast('a' as varchar(30))=cast('a' as varchar(30))",
Boolean.TRUE);
getTester().checkBoolean(
"cast('a ' as varchar(30))=cast('a' as varchar(30))",
Boolean.TRUE);
getTester().checkBoolean(
"cast('a' as varchar(30))=cast('b' as varchar(30))",
Boolean.FALSE);
getTester().checkBoolean(
"cast('a' as varchar(30))=cast('a' as varchar(15))",
Boolean.TRUE);
getTester().checkNull("cast(null as boolean)=cast(null as boolean)");
getTester().checkNull("cast(null as integer)=1");
getTester().checkNull("cast(null as varchar(10))='a'");
// Intervals
getTester().checkBoolean(
"interval '2' day = interval '1' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' day = interval '2' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2:2:2' hour to second = interval '2' hour",
Boolean.FALSE);
getTester().checkNull(
"cast(null as interval hour) = interval '2' minute");
}
public void testGreaterThanOperator()
{
getTester().setFor(SqlStdOperatorTable.greaterThanOperator);
getTester().checkBoolean("1>2", Boolean.FALSE);
getTester().checkBoolean(
"cast(-1 as TINYINT)>cast(1 as TINYINT)",
Boolean.FALSE);
getTester().checkBoolean(
"cast(1 as SMALLINT)>cast(1 as SMALLINT)",
Boolean.FALSE);
getTester().checkBoolean("2>1", Boolean.TRUE);
getTester().checkBoolean("1.1>1.2", Boolean.FALSE);
getTester().checkBoolean("-1.1>-1.2", Boolean.TRUE);
getTester().checkBoolean("1.1>1.1", Boolean.FALSE);
getTester().checkBoolean("1.2>1", Boolean.TRUE);
getTester().checkBoolean("1.1e1>1.2e1", Boolean.FALSE);
getTester().checkBoolean(
"cast(-1.1 as real) > cast(-1.2 as real)",
Boolean.TRUE);
getTester().checkBoolean("1.1e2>1.1e2", Boolean.FALSE);
getTester().checkBoolean("1.2e0>1", Boolean.TRUE);
getTester().checkBoolean("cast(1.2e0 as real)>1", Boolean.TRUE);
getTester().checkBoolean("true>false", Boolean.TRUE);
getTester().checkBoolean("true>true", Boolean.FALSE);
getTester().checkBoolean("false>false", Boolean.FALSE);
getTester().checkBoolean("false>true", Boolean.FALSE);
getTester().checkNull("3.0>cast(null as double)");
// Intervals
getTester().checkBoolean(
"interval '2' day > interval '1' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' day > interval '5' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2 2:2:2' day to second > interval '2' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' day > interval '2' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' day > interval '-2' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' day > interval '2' hour",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' minute > interval '2' hour",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' second > interval '2' minute",
Boolean.FALSE);
getTester().checkNull(
"cast(null as interval hour) > interval '2' minute");
getTester().checkNull(
"interval '2:2' hour to minute > cast(null as interval second)");
}
public void testIsDistinctFromOperator()
{
getTester().setFor(SqlStdOperatorTable.isDistinctFromOperator);
getTester().checkBoolean("1 is distinct from 1", Boolean.FALSE);
getTester().checkBoolean("1 is distinct from 1.0", Boolean.FALSE);
getTester().checkBoolean("1 is distinct from 2", Boolean.TRUE);
getTester().checkBoolean(
"cast(null as integer) is distinct from 2",
Boolean.TRUE);
getTester().checkBoolean(
"cast(null as integer) is distinct from cast(null as integer)",
Boolean.FALSE);
getTester().checkBoolean("1.23 is distinct from 1.23", Boolean.FALSE);
getTester().checkBoolean("1.23 is distinct from 5.23", Boolean.TRUE);
getTester().checkBoolean(
"-23e0 is distinct from -2.3e1",
Boolean.FALSE);
//getTester().checkBoolean("row(1,1) is distinct from row(1,1)",
//Boolean.TRUE); getTester().checkBoolean("row(1,1) is distinct from
//row(1,2)", Boolean.FALSE);
// Intervals
getTester().checkBoolean(
"interval '2' day is distinct from interval '1' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '10' hour is distinct from interval '10' hour",
Boolean.FALSE);
}
public void testIsNotDistinctFromOperator()
{
getTester().setFor(SqlStdOperatorTable.isNotDistinctFromOperator);
getTester().checkBoolean("1 is not distinct from 1", Boolean.TRUE);
getTester().checkBoolean("1 is not distinct from 1.0", Boolean.TRUE);
getTester().checkBoolean("1 is not distinct from 2", Boolean.FALSE);
getTester().checkBoolean(
"cast(null as integer) is not distinct from 2",
Boolean.FALSE);
getTester().checkBoolean(
"cast(null as integer) is not distinct from cast(null as integer)",
Boolean.TRUE);
getTester().checkBoolean(
"1.23 is not distinct from 1.23",
Boolean.TRUE);
getTester().checkBoolean(
"1.23 is not distinct from 5.23",
Boolean.FALSE);
getTester().checkBoolean(
"-23e0 is not distinct from -2.3e1",
Boolean.TRUE);
//getTester().checkBoolean("row(1,1) is not distinct from row(1,1)",
//Boolean.FALSE); getTester().checkBoolean("row(1,1) is not distinct
//from row(1,2)", Boolean.TRUE);
// Intervals
getTester().checkBoolean(
"interval '2' day is not distinct from interval '1' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '10' hour is not distinct from interval '10' hour",
Boolean.TRUE);
}
public void testGreaterThanOrEqualOperator()
{
getTester().setFor(SqlStdOperatorTable.greaterThanOrEqualOperator);
getTester().checkBoolean("1>=2", Boolean.FALSE);
getTester().checkBoolean("-1>=1", Boolean.FALSE);
getTester().checkBoolean("1>=1", Boolean.TRUE);
getTester().checkBoolean("2>=1", Boolean.TRUE);
getTester().checkBoolean("1.1>=1.2", Boolean.FALSE);
getTester().checkBoolean("-1.1>=-1.2", Boolean.TRUE);
getTester().checkBoolean("1.1>=1.1", Boolean.TRUE);
getTester().checkBoolean("1.2>=1", Boolean.TRUE);
getTester().checkBoolean("1.2e4>=1e5", Boolean.FALSE);
getTester().checkBoolean("1.2e4>=cast(1e5 as real)", Boolean.FALSE);
getTester().checkBoolean("1.2>=cast(1e5 as double)", Boolean.FALSE);
getTester().checkBoolean("120000>=cast(1e5 as real)", Boolean.TRUE);
getTester().checkBoolean("true>=false", Boolean.TRUE);
getTester().checkBoolean("true>=true", Boolean.TRUE);
getTester().checkBoolean("false>=false", Boolean.TRUE);
getTester().checkBoolean("false>=true", Boolean.FALSE);
getTester().checkNull("cast(null as real)>=999");
// Intervals
getTester().checkBoolean(
"interval '2' day >= interval '1' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' day >= interval '5' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2 2:2:2' day to second >= interval '2' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' day >= interval '2' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' day >= interval '-2' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' day >= interval '2' hour",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' minute >= interval '2' hour",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' second >= interval '2' minute",
Boolean.FALSE);
getTester().checkNull(
"cast(null as interval hour) >= interval '2' minute");
getTester().checkNull(
"interval '2:2' hour to minute >= cast(null as interval second)");
}
public void testInOperator()
{
getTester().setFor(SqlStdOperatorTable.inOperator);
}
public void testOverlapsOperator()
{
getTester().setFor(SqlStdOperatorTable.overlapsOperator);
if (Bug.Frg187Fixed) {
getTester().checkBoolean(
"(date '1-2-3', date '1-2-3') overlaps (date '1-2-3', interval '1' year)",
Boolean.TRUE);
getTester().checkBoolean(
"(date '1-2-3', date '1-2-3') overlaps (date '4-5-6', interval '1' year)",
Boolean.FALSE);
getTester().checkBoolean(
"(date '1-2-3', date '4-5-6') overlaps (date '2-2-3', date '3-4-5')",
Boolean.TRUE);
getTester().checkNull(
"(cast(null as date), date '1-2-3') overlaps (date '1-2-3', interval '1' year)");
getTester().checkNull(
"(date '1-2-3', date '1-2-3') overlaps (date '1-2-3', cast(null as date))");
getTester().checkBoolean(
"(time '1:2:3', interval '1' second) overlaps (time '23:59:59', time '1:2:3')",
Boolean.TRUE);
getTester().checkBoolean(
"(time '1:2:3', interval '1' second) overlaps (time '23:59:59', time '1:2:2')",
Boolean.FALSE);
getTester().checkBoolean(
"(time '1:2:3', interval '1' second) overlaps (time '23:59:59', interval '2' hour)",
Boolean.TRUE);
getTester().checkNull(
"(time '1:2:3', cast(null as time)) overlaps (time '23:59:59', time '1:2:3')");
getTester().checkNull(
"(time '1:2:3', interval '1' second) overlaps (time '23:59:59', cast(null as interval hour))");
getTester().checkBoolean(
"(timestamp '1-2-3 4:5:6', timestamp '1-2-3 4:5:6' ) overlaps (timestamp '1-2-3 4:5:6', interval '1 2:3:4.5' day to second)",
Boolean.TRUE);
getTester().checkBoolean(
"(timestamp '1-2-3 4:5:6', timestamp '1-2-3 4:5:6' ) overlaps (timestamp '2-2-3 4:5:6', interval '1 2:3:4.5' day to second)",
Boolean.FALSE);
getTester().checkNull(
"(timestamp '1-2-3 4:5:6', cast(null as interval day) ) overlaps (timestamp '1-2-3 4:5:6', interval '1 2:3:4.5' day to second)");
getTester().checkNull(
"(timestamp '1-2-3 4:5:6', timestamp '1-2-3 4:5:6' ) overlaps (cast(null as timestamp), interval '1 2:3:4.5' day to second)");
}
}
public void testLessThanOperator()
{
getTester().setFor(SqlStdOperatorTable.lessThanOperator);
getTester().checkBoolean("1<2", Boolean.TRUE);
getTester().checkBoolean("-1<1", Boolean.TRUE);
getTester().checkBoolean("1<1", Boolean.FALSE);
getTester().checkBoolean("2<1", Boolean.FALSE);
getTester().checkBoolean("1.1<1.2", Boolean.TRUE);
getTester().checkBoolean("-1.1<-1.2", Boolean.FALSE);
getTester().checkBoolean("1.1<1.1", Boolean.FALSE);
getTester().checkBoolean("cast(1.1 as real)<1", Boolean.FALSE);
getTester().checkBoolean("cast(1.1 as real)<1.1", Boolean.FALSE);
getTester().checkBoolean(
"cast(1.1 as real)<cast(1.2 as real)",
Boolean.TRUE);
getTester().checkBoolean("-1.1e-1<-1.2e-1", Boolean.FALSE);
getTester().checkBoolean(
"cast(1.1 as real)<cast(1.1 as double)",
Boolean.FALSE);
getTester().checkBoolean("true<false", Boolean.FALSE);
getTester().checkBoolean("true<true", Boolean.FALSE);
getTester().checkBoolean("false<false", Boolean.FALSE);
getTester().checkBoolean("false<true", Boolean.TRUE);
getTester().checkNull("123<cast(null as bigint)");
getTester().checkNull("cast(null as tinyint)<123");
getTester().checkNull("cast(null as integer)<1.32");
// Intervals
getTester().checkBoolean(
"interval '2' day < interval '1' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' day < interval '5' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2 2:2:2' day to second < interval '2' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' day < interval '2' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' day < interval '-2' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' day < interval '2' hour",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' minute < interval '2' hour",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' second < interval '2' minute",
Boolean.TRUE);
getTester().checkNull(
"cast(null as interval hour) < interval '2' minute");
getTester().checkNull(
"interval '2:2' hour to minute < cast(null as interval second)");
}
public void testLessThanOrEqualOperator()
{
getTester().setFor(SqlStdOperatorTable.lessThanOrEqualOperator);
getTester().checkBoolean("1<=2", Boolean.TRUE);
getTester().checkBoolean("1<=1", Boolean.TRUE);
getTester().checkBoolean("-1<=1", Boolean.TRUE);
getTester().checkBoolean("2<=1", Boolean.FALSE);
getTester().checkBoolean("1.1<=1.2", Boolean.TRUE);
getTester().checkBoolean("-1.1<=-1.2", Boolean.FALSE);
getTester().checkBoolean("1.1<=1.1", Boolean.TRUE);
getTester().checkBoolean("1.2<=1", Boolean.FALSE);
getTester().checkBoolean("1<=cast(1e2 as real)", Boolean.TRUE);
getTester().checkBoolean("1000<=cast(1e2 as real)", Boolean.FALSE);
getTester().checkBoolean("1.2e1<=1e2", Boolean.TRUE);
getTester().checkBoolean("1.2e1<=cast(1e2 as real)", Boolean.TRUE);
getTester().checkBoolean("true<=false", Boolean.FALSE);
getTester().checkBoolean("true<=true", Boolean.TRUE);
getTester().checkBoolean("false<=false", Boolean.TRUE);
getTester().checkBoolean("false<=true", Boolean.TRUE);
getTester().checkNull("cast(null as real)<=cast(1 as real)");
getTester().checkNull("cast(null as integer)<=3");
getTester().checkNull("3<=cast(null as smallint)");
getTester().checkNull("cast(null as integer)<=1.32");
// Intervals
getTester().checkBoolean(
"interval '2' day <= interval '1' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' day <= interval '5' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2 2:2:2' day to second <= interval '2' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' day <= interval '2' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' day <= interval '-2' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' day <= interval '2' hour",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2' minute <= interval '2' hour",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' second <= interval '2' minute",
Boolean.TRUE);
getTester().checkNull(
"cast(null as interval hour) <= interval '2' minute");
getTester().checkNull(
"interval '2:2' hour to minute <= cast(null as interval second)");
}
public void testMinusOperator()
{
getTester().setFor(SqlStdOperatorTable.minusOperator);
getTester().checkScalarExact("-2-1", "-3");
getTester().checkScalarExact("-2-1-5", "-8");
getTester().checkScalarExact("2-1", "1");
getTester().checkScalarApprox(
"cast(2.0 as double) -1",
"DOUBLE NOT NULL",
1,
0);
getTester().checkScalarApprox(
"cast(1 as smallint)-cast(2.0 as real)",
"REAL NOT NULL",
-1,
0);
getTester().checkScalarApprox(
"2.4-cast(2.0 as real)",
"DOUBLE NOT NULL",
0.4,
0.00000001);
getTester().checkScalarExact("1-2", "-1");
getTester().checkScalarExact(
"10.0 - 5.0",
"DECIMAL(4, 1) NOT NULL",
"5.0");
getTester().checkScalarExact(
"19.68 - 4.2",
"DECIMAL(5, 2) NOT NULL",
"15.48");
getTester().checkNull("1e1-cast(null as double)");
getTester().checkNull("cast(null as tinyint) - cast(null as smallint)");
// TODO: Fix bug
if (Bug.Fn25Fixed) {
// Should throw out of range error
getTester().checkFails(
"cast(100 as tinyint) - cast(-100 as tinyint)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(-20000 as smallint) - cast(20000 as smallint)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(1.5e9 as integer) - cast(-1.5e9 as integer)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(-5e18 as bigint) - cast(5e18 as bigint)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(5e18 as decimal(19,0)) - cast(-5e18 as decimal(19,0))",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(-5e8 as decimal(19,10)) - cast(5e8 as decimal(19,10))",
outOfRangeMessage,
true);
}
}
public void testMinusIntervalOperator()
{
getTester().setFor(SqlStdOperatorTable.minusOperator);
// Intervals
getTester().checkScalar(
"interval '2' day - interval '1' day",
"+1",
"INTERVAL DAY NOT NULL");
getTester().checkScalar(
"interval '2' day - interval '1' minute",
"+1 23:59",
"INTERVAL DAY TO MINUTE NOT NULL");
getTester().checkScalar(
"interval '2' year - interval '1' month",
"+1-11",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkScalar(
"interval '2' year - interval '1' month - interval '3' year",
"-1-01",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkNull(
"cast(null as interval day) + interval '2' hour");
// Datetime minus interval
getTester().checkScalar(
"time '12:03:01' - interval '1:1' hour to minute",
"11:02:01",
"TIME(0) NOT NULL");
getTester().checkScalar(
"date '2005-03-02' - interval '5' day",
"2005-02-25",
"DATE NOT NULL");
getTester().checkScalar(
"timestamp '2003-08-02 12:54:01' - interval '-4 2:4' day to minute",
"2003-08-06 14:58:01.0",
"TIMESTAMP(0) NOT NULL");
// TODO: Tests with interval year months (not supported)
}
public void testMinusDateOperator()
{
getTester().setFor(SqlStdOperatorTable.minusDateOperator);
getTester().checkScalar(
"(time '12:03:34' - time '11:57:23') minute to second",
"+6:11",
"INTERVAL MINUTE TO SECOND NOT NULL");
getTester().checkScalar(
"(time '12:03:23' - time '11:57:23') minute",
"+6",
"INTERVAL MINUTE NOT NULL");
getTester().checkScalar(
"(time '12:03:34' - time '11:57:23') minute",
"+6",
"INTERVAL MINUTE NOT NULL");
getTester().checkScalar(
"(timestamp '2004-05-01 12:03:34' - timestamp '2004-04-29 11:57:23') day to second",
"+2 00:06:11",
"INTERVAL DAY TO SECOND NOT NULL");
getTester().checkScalar(
"(timestamp '2004-05-01 12:03:34' - timestamp '2004-04-29 11:57:23') day to hour",
"+2 00",
"INTERVAL DAY TO HOUR NOT NULL");
getTester().checkScalar(
"(date '2004-12-02' - date '2003-12-01') day",
"+367",
"INTERVAL DAY NOT NULL");
getTester().checkNull(
"(cast(null as date) - date '2003-12-01') day");
// TODO: Add tests for year month intervals (currently not supported)
}
public void testMultiplyOperator()
{
getTester().setFor(SqlStdOperatorTable.multiplyOperator);
getTester().checkScalarExact("2*3", "6");
getTester().checkScalarExact("2*-3", "-6");
getTester().checkScalarExact("+2*3", "6");
getTester().checkScalarExact("2*0", "0");
getTester().checkScalarApprox(
"cast(2.0 as float)*3",
"FLOAT NOT NULL",
6,
0);
getTester().checkScalarApprox(
"3*cast(2.0 as real)",
"REAL NOT NULL",
6,
0);
getTester().checkScalarApprox(
"cast(2.0 as real)*3.2",
"DOUBLE NOT NULL",
6.4,
0);
getTester().checkScalarExact(
"10.0 * 5.0",
"DECIMAL(5, 2) NOT NULL",
"50.00");
getTester().checkScalarExact(
"19.68 * 4.2",
"DECIMAL(6, 3) NOT NULL",
"82.656");
getTester().checkNull("cast(1 as real)*cast(null as real)");
getTester().checkNull("2e-3*cast(null as integer)");
getTester().checkNull("cast(null as tinyint) * cast(4 as smallint)");
if (Bug.Fn25Fixed) {
// Should throw out of range error
getTester().checkFails(
"cast(100 as tinyint) * cast(-2 as tinyint)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(200 as smallint) * cast(200 as smallint)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(1.5e9 as integer) * cast(-2 as integer)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(5e9 as bigint) * cast(2e9 as bigint)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(2e9 as decimal(19,0)) * cast(-5e9 as decimal(19,0))",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(5e4 as decimal(19,10)) * cast(2e4 as decimal(19,10))",
outOfRangeMessage,
true);
}
// Intervals
getTester().checkScalar(
"interval '2:2' hour to minute * 3",
"+6:06",
"INTERVAL HOUR TO MINUTE NOT NULL");
getTester().checkScalar(
"3 * 2 * interval '2:5:12' hour to second",
"+12:31:12",
"INTERVAL HOUR TO SECOND NOT NULL");
getTester().checkNull(
"interval '2' day * cast(null as bigint)");
getTester().checkNull(
"cast(null as interval month) * 2");
if (todo) {
getTester().checkScalar(
"interval '3-2' year to month * 15e-1",
"+04-09",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkScalar(
"interval '3-4' year to month * 4.5",
"+15-00",
"INTERVAL YEAR TO MONTH NOT NULL");
}
}
public void testNotEqualsOperator()
{
getTester().setFor(SqlStdOperatorTable.notEqualsOperator);
getTester().checkBoolean("1<>1", Boolean.FALSE);
getTester().checkBoolean("'a'<>'A'", Boolean.TRUE);
getTester().checkBoolean("1e0<>1e1", Boolean.TRUE);
getTester().checkNull("'a'<>cast(null as varchar(1))");
// Intervals
getTester().checkBoolean(
"interval '2' day <> interval '1' day",
Boolean.TRUE);
getTester().checkBoolean(
"interval '2' day <> interval '2' day",
Boolean.FALSE);
getTester().checkBoolean(
"interval '2:2:2' hour to second <> interval '2' hour",
Boolean.TRUE);
getTester().checkNull(
"cast(null as interval hour) <> interval '2' minute");
// "!=" is not an acceptable alternative to "<>"
getTester().checkFails(
"1 ^!^= 1",
"(?s).*Encountered: \"!\" \\(33\\).*",
false);
}
public void testOrOperator()
{
getTester().setFor(SqlStdOperatorTable.orOperator);
getTester().checkBoolean("true or false", Boolean.TRUE);
getTester().checkBoolean("false or false", Boolean.FALSE);
getTester().checkBoolean("true or cast(null as boolean)", Boolean.TRUE);
getTester().checkNull("false or cast(null as boolean)");
}
public void testPlusOperator()
{
getTester().setFor(SqlStdOperatorTable.plusOperator);
getTester().checkScalarExact("1+2", "3");
getTester().checkScalarExact("-1+2", "1");
getTester().checkScalarExact("1+2+3", "6");
getTester().checkScalarApprox(
"1+cast(2.0 as double)",
"DOUBLE NOT NULL",
3,
0);
getTester().checkScalarApprox(
"1+cast(2.0 as double)+cast(6.0 as float)",
"DOUBLE NOT NULL",
9,
0);
getTester().checkScalarExact(
"10.0 + 5.0",
"DECIMAL(4, 1) NOT NULL",
"15.0");
getTester().checkScalarExact(
"19.68 + 4.2",
"DECIMAL(5, 2) NOT NULL",
"23.88");
getTester().checkScalarExact(
"19.68 + 4.2 + 6",
"DECIMAL(13, 2) NOT NULL",
"29.88");
getTester().checkScalarApprox(
"19.68 + cast(4.2 as float)",
"DOUBLE NOT NULL",
23.88,
0);
getTester().checkNull("cast(null as tinyint)+1");
getTester().checkNull("1e-2+cast(null as double)");
if (Bug.Fn25Fixed) {
// Should throw out of range error
getTester().checkFails(
"cast(100 as tinyint) + cast(100 as tinyint)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(-20000 as smallint) + cast(-20000 as smallint)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(1.5e9 as integer) + cast(1.5e9 as integer)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(5e18 as bigint) + cast(5e18 as bigint)",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(-5e18 as decimal(19,0)) + cast(-5e18 as decimal(19,0))",
outOfRangeMessage,
true);
getTester().checkFails(
"cast(5e8 as decimal(19,10)) + cast(5e8 as decimal(19,10))",
outOfRangeMessage,
true);
}
}
public void testPlusIntervalOperator()
{
getTester().setFor(SqlStdOperatorTable.plusOperator);
// Intervals
getTester().checkScalar(
"interval '2' day + interval '1' day",
"+3",
"INTERVAL DAY NOT NULL");
getTester().checkScalar(
"interval '2' day + interval '1' minute",
"+2 00:01",
"INTERVAL DAY TO MINUTE NOT NULL");
getTester().checkScalar(
"interval '2' day + interval '5' minute + interval '-3' second",
"+2 00:04:57",
"INTERVAL DAY TO SECOND NOT NULL");
getTester().checkScalar(
"interval '2' year + interval '1' month",
"+2-01",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkNull(
"interval '2' year + cast(null as interval month)");
// Datetime plus interval
getTester().checkScalar(
"time '12:03:01' + interval '1:1' hour to minute",
"13:04:01",
"TIME(0) NOT NULL");
getTester().checkScalar(
"interval '5' day + date '2005-03-02'",
"2005-03-07",
"DATE NOT NULL");
getTester().checkScalar(
"timestamp '2003-08-02 12:54:01' + interval '-4 2:4' day to minute",
"2003-07-29 10:50:01.0",
"TIMESTAMP(0) NOT NULL");
// TODO: Tests with interval year months (not supported)
}
public void testDescendingOperator()
{
getTester().setFor(SqlStdOperatorTable.descendingOperator);
}
public void testIsNotNullOperator()
{
getTester().setFor(SqlStdOperatorTable.isNotNullOperator);
getTester().checkBoolean("true is not null", Boolean.TRUE);
getTester().checkBoolean(
"cast(null as boolean) is not null",
Boolean.FALSE);
}
public void testIsNullOperator()
{
getTester().setFor(SqlStdOperatorTable.isNullOperator);
getTester().checkBoolean("true is null", Boolean.FALSE);
getTester().checkBoolean("cast(null as boolean) is null",
Boolean.TRUE);
}
public void testIsNotTrueOperator()
{
getTester().setFor(SqlStdOperatorTable.isNotTrueOperator);
getTester().checkBoolean("true is not true", Boolean.FALSE);
getTester().checkBoolean("false is not true", Boolean.TRUE);
getTester().checkBoolean(
"cast(null as boolean) is not true",
Boolean.TRUE);
getTester().checkFails(
"select ^'a string' is not true^ from (values (1))",
"(?s)Cannot apply 'IS NOT TRUE' to arguments of type '<CHAR\\(8\\)> IS NOT TRUE'. Supported form\\(s\\): '<BOOLEAN> IS NOT TRUE'.*",
false);
}
public void testIsTrueOperator()
{
getTester().setFor(SqlStdOperatorTable.isTrueOperator);
getTester().checkBoolean("true is true", Boolean.TRUE);
getTester().checkBoolean("false is true", Boolean.FALSE);
getTester().checkBoolean(
"cast(null as boolean) is true",
Boolean.FALSE);
}
public void testIsNotFalseOperator()
{
getTester().setFor(SqlStdOperatorTable.isNotFalseOperator);
getTester().checkBoolean("false is not false", Boolean.FALSE);
getTester().checkBoolean("true is not false", Boolean.TRUE);
getTester().checkBoolean(
"cast(null as boolean) is not false",
Boolean.TRUE);
}
public void testIsFalseOperator()
{
getTester().setFor(SqlStdOperatorTable.isFalseOperator);
getTester().checkBoolean("false is false", Boolean.TRUE);
getTester().checkBoolean("true is false", Boolean.FALSE);
getTester().checkBoolean(
"cast(null as boolean) is false",
Boolean.FALSE);
}
public void testIsNotUnknownOperator()
{
getTester().setFor(SqlStdOperatorTable.isNotUnknownOperator);
getTester().checkBoolean("false is not unknown", Boolean.TRUE);
getTester().checkBoolean("true is not unknown", Boolean.TRUE);
getTester().checkBoolean(
"cast(null as boolean) is not unknown",
Boolean.FALSE);
getTester().checkBoolean("unknown is not unknown", Boolean.FALSE);
getTester().checkFails(
"^'abc' IS NOT UNKNOWN^",
"(?s).*Cannot apply 'IS NOT UNKNOWN'.*",
false);
}
public void testIsUnknownOperator()
{
getTester().setFor(SqlStdOperatorTable.isUnknownOperator);
getTester().checkBoolean("false is unknown", Boolean.FALSE);
getTester().checkBoolean("true is unknown", Boolean.FALSE);
getTester().checkBoolean(
"cast(null as boolean) is unknown",
Boolean.TRUE);
getTester().checkBoolean("unknown is unknown", Boolean.TRUE);
getTester().checkFails(
"0 = 1 AND ^2 IS UNKNOWN^ AND 3 > 4",
"(?s).*Cannot apply 'IS UNKNOWN'.*",
false);
}
public void testIsASetOperator()
{
getTester().setFor(SqlStdOperatorTable.isASetOperator);
}
public void testExistsOperator()
{
getTester().setFor(SqlStdOperatorTable.existsOperator);
}
public void testNotOperator()
{
getTester().setFor(SqlStdOperatorTable.notOperator);
getTester().checkBoolean("not true", Boolean.FALSE);
getTester().checkBoolean("not false", Boolean.TRUE);
getTester().checkBoolean("not unknown", null);
getTester().checkNull("not cast(null as boolean)");
}
public void testPrefixMinusOperator()
{
getTester().setFor(SqlStdOperatorTable.prefixMinusOperator);
getTester().checkFails(
"'a' + ^- 'b'^ + 'c'",
"(?s)Cannot apply '-' to arguments of type '-<CHAR\\(1\\)>'.*",
false);
getTester().checkScalarExact("-1", "-1");
getTester().checkScalarExact(
"-1.23",
"DECIMAL(3, 2) NOT NULL",
"-1.23");
getTester().checkScalarApprox("-1.0e0", "DOUBLE NOT NULL", -1, 0);
getTester().checkNull("-cast(null as integer)");
getTester().checkNull("-cast(null as tinyint)");
// Intervals
getTester().checkScalar(
"-interval '-6:2:8' hour to second",
"+6:02:08",
"INTERVAL HOUR TO SECOND NOT NULL");
getTester().checkScalar(
"- -interval '-6:2:8' hour to second",
"-6:02:08",
"INTERVAL HOUR TO SECOND NOT NULL");
getTester().checkScalar(
"-interval '5' month",
"-5",
"INTERVAL MONTH NOT NULL");
getTester().checkNull(
"-cast(null as interval day to minute)");
}
public void testPrefixPlusOperator()
{
getTester().setFor(SqlStdOperatorTable.prefixPlusOperator);
getTester().checkScalarExact("+1", "1");
getTester().checkScalarExact("+1.23", "DECIMAL(3, 2) NOT NULL", "1.23");
getTester().checkScalarApprox("+1.0e0", "DOUBLE NOT NULL", 1, 0);
getTester().checkNull("+cast(null as integer)");
getTester().checkNull("+cast(null as tinyint)");
// Intervals
getTester().checkScalar(
"+interval '-6:2:8' hour to second",
"-6:02:08",
"INTERVAL HOUR TO SECOND NOT NULL");
getTester().checkScalar(
"++interval '-6:2:8' hour to second",
"-6:02:08",
"INTERVAL HOUR TO SECOND NOT NULL");
getTester().checkScalar(
"+interval '6:2:8.234' hour to second",
"+6:02:08.234",
"INTERVAL HOUR TO SECOND NOT NULL");
getTester().checkScalar(
"+interval '5' month",
"+5",
"INTERVAL MONTH NOT NULL");
getTester().checkNull(
"+cast(null as interval day to minute)");
}
public void testExplicitTableOperator()
{
getTester().setFor(SqlStdOperatorTable.explicitTableOperator);
}
public void testValuesOperator()
{
getTester().setFor(SqlStdOperatorTable.valuesOperator);
getTester().check(
"select 'abc' from (values(true))",
new AbstractSqlTester.StringTypeChecker("CHAR(3) NOT NULL"),
"abc",
0);
}
public void testNotLikeOperator()
{
getTester().setFor(SqlStdOperatorTable.notLikeOperator);
getTester().checkBoolean("'abc' not like '_b_'", Boolean.FALSE);
}
public void testLikeOperator()
{
getTester().setFor(SqlStdOperatorTable.likeOperator);
getTester().checkBoolean("'' like ''", Boolean.TRUE);
getTester().checkBoolean("'a' like 'a'", Boolean.TRUE);
getTester().checkBoolean("'a' like 'b'", Boolean.FALSE);
getTester().checkBoolean("'a' like 'A'", Boolean.FALSE);
getTester().checkBoolean("'a' like 'a_'", Boolean.FALSE);
getTester().checkBoolean("'a' like '_a'", Boolean.FALSE);
getTester().checkBoolean("'a' like '%a'", Boolean.TRUE);
getTester().checkBoolean("'a' like '%a%'", Boolean.TRUE);
getTester().checkBoolean("'a' like 'a%'", Boolean.TRUE);
getTester().checkBoolean("'ab' like 'a_'", Boolean.TRUE);
getTester().checkBoolean("'abc' like 'a_'", Boolean.FALSE);
getTester().checkBoolean("'abcd' like 'a%'", Boolean.TRUE);
getTester().checkBoolean("'ab' like '_b'", Boolean.TRUE);
getTester().checkBoolean("'abcd' like '_d'", Boolean.FALSE);
getTester().checkBoolean("'abcd' like '%d'", Boolean.TRUE);
}
public void testNotSimilarToOperator()
{
getTester().setFor(SqlStdOperatorTable.notSimilarOperator);
getTester().checkBoolean("'ab' not similar to 'a_'", Boolean.FALSE);
}
public void testSimilarToOperator()
{
getTester().setFor(SqlStdOperatorTable.similarOperator);
// like LIKE
getTester().checkBoolean("'' similar to ''", Boolean.TRUE);
getTester().checkBoolean("'a' similar to 'a'", Boolean.TRUE);
getTester().checkBoolean("'a' similar to 'b'", Boolean.FALSE);
getTester().checkBoolean("'a' similar to 'A'", Boolean.FALSE);
getTester().checkBoolean("'a' similar to 'a_'", Boolean.FALSE);
getTester().checkBoolean("'a' similar to '_a'", Boolean.FALSE);
getTester().checkBoolean("'a' similar to '%a'", Boolean.TRUE);
getTester().checkBoolean("'a' similar to '%a%'", Boolean.TRUE);
getTester().checkBoolean("'a' similar to 'a%'", Boolean.TRUE);
getTester().checkBoolean("'ab' similar to 'a_'", Boolean.TRUE);
getTester().checkBoolean("'abc' similar to 'a_'", Boolean.FALSE);
getTester().checkBoolean("'abcd' similar to 'a%'", Boolean.TRUE);
getTester().checkBoolean("'ab' similar to '_b'", Boolean.TRUE);
getTester().checkBoolean("'abcd' similar to '_d'", Boolean.FALSE);
getTester().checkBoolean("'abcd' similar to '%d'", Boolean.TRUE);
// simple regular expressions
// ab*c+d matches acd, abcd, acccd, abcccd but not abd, aabc
getTester().checkBoolean("'acd' similar to 'ab*c+d'", Boolean.TRUE);
getTester().checkBoolean("'abcd' similar to 'ab*c+d'", Boolean.TRUE);
getTester().checkBoolean("'acccd' similar to 'ab*c+d'", Boolean.TRUE);
getTester().checkBoolean("'abcccd' similar to 'ab*c+d'", Boolean.TRUE);
getTester().checkBoolean("'abd' similar to 'ab*c+d'", Boolean.FALSE);
getTester().checkBoolean("'aabc' similar to 'ab*c+d'", Boolean.FALSE);
// compound regular expressions
// x(ab|c)*y matches xy, xccy, xababcy but not xbcy
getTester().checkBoolean(
"'xy' similar to 'x(ab|c)*y'",
Boolean.TRUE);
getTester().checkBoolean(
"'xccy' similar to 'x(ab|c)*y'",
Boolean.TRUE);
getTester().checkBoolean(
"'xababcy' similar to 'x(ab|c)*y'",
Boolean.TRUE);
getTester().checkBoolean(
"'xbcy' similar to 'x(ab|c)*y'",
Boolean.FALSE);
// x(ab|c)+y matches xccy, xababcy but not xy, xbcy
getTester().checkBoolean(
"'xy' similar to 'x(ab|c)+y'",
Boolean.FALSE);
getTester().checkBoolean(
"'xccy' similar to 'x(ab|c)+y'",
Boolean.TRUE);
getTester().checkBoolean(
"'xababcy' similar to 'x(ab|c)+y'",
Boolean.TRUE);
getTester().checkBoolean(
"'xbcy' similar to 'x(ab|c)+y'",
Boolean.FALSE);
}
public void testEscapeOperator()
{
getTester().setFor(SqlStdOperatorTable.escapeOperator);
}
public void testConvertFunc()
{
getTester().setFor(SqlStdOperatorTable.convertFunc);
}
public void testTranslateFunc()
{
getTester().setFor(SqlStdOperatorTable.translateFunc);
}
public void testOverlayFunc()
{
getTester().setFor(SqlStdOperatorTable.overlayFunc);
getTester().checkString(
"overlay('ABCdef' placing 'abc' from 1)",
"abcdef",
"VARCHAR(9) NOT NULL");
getTester().checkString(
"overlay('ABCdef' placing 'abc' from 1 for 2)",
"abcCdef",
"VARCHAR(9) NOT NULL");
getTester().checkString(
"overlay(cast('ABCdef' as varchar(10)) placing "
+ "cast('abc' as char(5)) from 1 for 2)",
"abc Cdef",
"VARCHAR(15) NOT NULL");
getTester().checkString(
"overlay(cast('ABCdef' as char(10)) placing "
+ "cast('abc' as char(5)) from 1 for 2)",
"abc Cdef ",
"VARCHAR(15) NOT NULL");
getTester().checkNull(
"overlay('ABCdef' placing 'abc' from 1 for cast(null as integer))");
getTester().checkNull(
"overlay(cast(null as varchar(1)) placing 'abc' from 1)");
if (false) {
// hex strings not yet implemented in calc
getTester().checkNull(
"overlay(x'abc' placing x'abc' from cast(null as integer))");
}
}
public void testPositionFunc()
{
getTester().setFor(SqlStdOperatorTable.positionFunc);
getTester().checkScalarExact("position('b' in 'abc')", "2");
getTester().checkScalarExact("position('' in 'abc')", "1");
// FRG-211
getTester().checkScalarExact("position('tra' in 'fdgjklewrtra')", "10");
getTester().checkNull("position(cast(null as varchar(1)) in '0010')");
getTester().checkNull("position('a' in cast(null as varchar(1)))");
getTester().checkScalar(
"position(cast('a' as char) in cast('bca' as varchar))",
0,
"INTEGER NOT NULL");
}
public void testCharLengthFunc()
{
getTester().setFor(SqlStdOperatorTable.charLengthFunc);
getTester().checkScalarExact("char_length('abc')", "3");
getTester().checkNull("char_length(cast(null as varchar(1)))");
}
public void testCharacterLengthFunc()
{
getTester().setFor(SqlStdOperatorTable.characterLengthFunc);
getTester().checkScalarExact("CHARACTER_LENGTH('abc')", "3");
getTester().checkNull("CHARACTER_LENGTH(cast(null as varchar(1)))");
}
public void testUpperFunc()
{
getTester().setFor(SqlStdOperatorTable.upperFunc);
getTester().checkString("upper('a')", "A", "CHAR(1) NOT NULL");
getTester().checkString("upper('A')", "A", "CHAR(1) NOT NULL");
getTester().checkString("upper('1')", "1", "CHAR(1) NOT NULL");
getTester().checkString("upper('aa')", "AA", "CHAR(2) NOT NULL");
getTester().checkNull("upper(cast(null as varchar(1)))");
}
public void testLowerFunc()
{
getTester().setFor(SqlStdOperatorTable.lowerFunc);
// SQL:2003 6.29.8 The type of lower is the type of its argument
getTester().checkString("lower('A')", "a", "CHAR(1) NOT NULL");
getTester().checkString("lower('a')", "a", "CHAR(1) NOT NULL");
getTester().checkString("lower('1')", "1", "CHAR(1) NOT NULL");
getTester().checkString("lower('AA')", "aa", "CHAR(2) NOT NULL");
getTester().checkNull("lower(cast(null as varchar(1)))");
}
public void testInitcapFunc()
{
// Note: the initcap function is an Oracle defined function and is not
// defined in the '03 standard
getTester().setFor(SqlStdOperatorTable.initcapFunc);
getTester().checkString("initcap('aA')", "Aa", "CHAR(2) NOT NULL");
getTester().checkString("initcap('Aa')", "Aa", "CHAR(2) NOT NULL");
getTester().checkString("initcap('1a')", "1a", "CHAR(2) NOT NULL");
getTester().checkString(
"initcap('ab cd Ef 12')",
"Ab Cd Ef 12",
"CHAR(11) NOT NULL");
getTester().checkNull("initcap(cast(null as varchar(1)))");
// dtbug 232
getTester().checkFails(
"^initcap(cast(null as date))^",
"Cannot apply 'INITCAP' to arguments of type 'INITCAP\\(<DATE>\\)'\\. Supported form\\(s\\): 'INITCAP\\(<CHARACTER>\\)'",
false);
}
public void testPowFunc()
{
getTester().setFor(SqlStdOperatorTable.powFunc);
getTester().checkScalarApprox("pow(2,-2)", "DOUBLE NOT NULL", 0.25, 0);
getTester().checkNull("pow(cast(null as integer),2)");
getTester().checkNull("pow(2,cast(null as double))");
}
public void testExpFunc()
{
getTester().setFor(SqlStdOperatorTable.expFunc);
getTester().checkScalarApprox(
"exp(2)",
"DOUBLE NOT NULL",
7.389056,
0.000001);
getTester().checkScalarApprox(
"exp(-2)",
"DOUBLE NOT NULL",
0.1353,
0.0001);
getTester().checkNull("exp(cast(null as integer))");
getTester().checkNull("exp(cast(null as double))");
}
public void testModFunc()
{
getTester().setFor(SqlStdOperatorTable.modFunc);
getTester().checkScalarExact("mod(4,2)", "0");
getTester().checkScalarExact("mod(8,5)", "3");
getTester().checkScalarExact("mod(-12,7)", "-5");
getTester().checkScalarExact("mod(-12,-7)", "-5");
getTester().checkScalarExact("mod(12,-7)", "5");
getTester().checkScalarExact(
"mod(cast(12 as tinyint), cast(-7 as tinyint))",
"TINYINT NOT NULL",
"5");
getTester().checkScalarExact(
"mod(cast(9 as decimal(2, 0)), 7)",
"INTEGER NOT NULL",
"2");
getTester().checkScalarExact(
"mod(7, cast(9 as decimal(2, 0)))",
"DECIMAL(2, 0) NOT NULL",
"7");
getTester().checkScalarExact(
"mod(cast(-9 as decimal(2, 0)), cast(7 as decimal(1, 0)))",
"DECIMAL(1, 0) NOT NULL",
"-2");
getTester().checkNull("mod(cast(null as integer),2)");
getTester().checkNull("mod(4,cast(null as tinyint))");
getTester().checkNull("mod(4,cast(null as decimal(12,0)))");
}
public void testModFuncDivByZero()
{
// The extra CASE expression is to fool Janino. It does constant
// reduction and will throw the divide by zero exception while
// compiling the expression. The test frame work would then issue
// unexpected exception occured during "validation". You cannot
// submit as non-runtime because the janino exception does not have
// error position information and the framework is unhappy with that.
getTester().checkFails("mod(3,case 'a' when 'a' then 0 end)", divisionByZeroMessage, true);
}
public void testLnFunc()
{
getTester().setFor(SqlStdOperatorTable.lnFunc);
getTester().checkScalarApprox(
"ln(2.71828)",
"DOUBLE NOT NULL",
1.0,
0.000001);
getTester().checkScalarApprox(
"ln(2.71828)",
"DOUBLE NOT NULL",
0.999999327,
0.0000001);
getTester().checkNull("ln(cast(null as tinyint))");
}
public void testLogFunc()
{
getTester().setFor(SqlStdOperatorTable.log10Func);
getTester().checkScalarApprox(
"log10(10)",
"DOUBLE NOT NULL",
1.0,
0.000001);
getTester().checkScalarApprox(
"log10(100.0)",
"DOUBLE NOT NULL",
2.0,
0.000001);
getTester().checkScalarApprox(
"log10(cast(10e8 as double))",
"DOUBLE NOT NULL",
9.0,
0.000001);
getTester().checkScalarApprox(
"log10(cast(10e2 as float))",
"DOUBLE NOT NULL",
3.0,
0.000001);
getTester().checkScalarApprox(
"log10(cast(10e-3 as real))",
"DOUBLE NOT NULL",
-2.0,
0.000001);
getTester().checkNull("log10(cast(null as real))");
}
public void testAbsFunc()
{
getTester().setFor(SqlStdOperatorTable.absFunc);
getTester().checkScalarExact("abs(-1)", "1");
getTester().checkScalarExact(
"abs(cast(10 as TINYINT))",
"TINYINT NOT NULL",
"10");
getTester().checkScalarExact(
"abs(cast(-20 as SMALLINT))",
"SMALLINT NOT NULL",
"20");
getTester().checkScalarExact(
"abs(cast(-100 as INT))",
"INTEGER NOT NULL",
"100");
getTester().checkScalarExact(
"abs(cast(1000 as BIGINT))",
"BIGINT NOT NULL",
"1000");
getTester().checkScalarExact(
"abs(54.4)",
"DECIMAL(3, 1) NOT NULL",
"54.4");
getTester().checkScalarExact(
"abs(-54.4)",
"DECIMAL(3, 1) NOT NULL",
"54.4");
getTester().checkScalarApprox(
"abs(-9.32E-2)",
"DOUBLE NOT NULL",
0.0932,
0);
getTester().checkScalarApprox(
"abs(cast(-3.5 as double))",
"DOUBLE NOT NULL",
3.5,
0);
getTester().checkScalarApprox(
"abs(cast(-3.5 as float))",
"FLOAT NOT NULL",
3.5,
0);
getTester().checkScalarApprox(
"abs(cast(3.5 as real))",
"REAL NOT NULL",
3.5,
0);
getTester().checkNull("abs(cast(null as double))");
// Intervals
getTester().checkScalar(
"abs(interval '-2' day)",
"+2",
"INTERVAL DAY NOT NULL");
getTester().checkScalar(
"abs(interval '-5-03' year to month)",
"+5-03",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkNull("abs(cast(null as interval hour))");
}
public void testNullifFunc()
{
getTester().setFor(SqlStdOperatorTable.nullIfFunc);
getTester().checkNull("nullif(1,1)");
getTester().checkScalarExact(
"nullif(1.5, 13.56)",
"DECIMAL(2, 1)",
"1.5");
getTester().checkScalarExact(
"nullif(13.56, 1.5)",
"DECIMAL(4, 2)",
"13.56");
getTester().checkScalarExact("nullif(1.5, 3)", "DECIMAL(2, 1)", "1.5");
getTester().checkScalarExact("nullif(3, 1.5)", "INTEGER", "3");
getTester().checkScalarApprox("nullif(1.5e0, 3e0)", "DOUBLE", 1.5, 0);
getTester().checkScalarApprox(
"nullif(1.5, cast(3e0 as REAL))",
"DECIMAL(2, 1)",
1.5,
0);
getTester().checkScalarExact("nullif(3, 1.5e0)", "INTEGER", "3");
getTester().checkScalarExact(
"nullif(3, cast(1.5e0 as REAL))",
"INTEGER",
"3");
getTester().checkScalarApprox("nullif(1.5e0, 3.4)", "DOUBLE", 1.5, 0);
getTester().checkScalarExact(
"nullif(3.4, 1.5e0)",
"DECIMAL(2, 1)",
"3.4");
getTester().checkString("nullif('a','bc')",
"a",
"CHAR(1)");
getTester().checkString(
"nullif('a',cast(null as varchar(1)))",
"a",
"CHAR(1)");
getTester().checkNull("nullif(cast(null as varchar(1)),'a')");
getTester().checkNull("nullif(cast(null as numeric(4,3)), 4.3)");
// Error message reflects the fact that Nullif is expanded before it is
// validated (like a C macro). Not perfect, but good enough.
getTester().checkFails(
"1 + ^nullif(1, date '2005-8-4')^ + 2",
"(?s)Cannot apply '=' to arguments of type '<INTEGER> = <DATE>'\\..*",
false);
// TODO: fix frg 65 (dtbug 324).
if (Bug.Frg65Fixed) {
getTester().checkFails(
"1 + ^nullif(1, 2, 3)^ + 2",
"invalid number of arguments to NULLIF",
false);
}
// Intervals
getTester().checkScalar(
"nullif(interval '2' month, interval '3' year)",
"+2",
"INTERVAL MONTH");
getTester().checkScalar(
"nullif(interval '2 5' day to hour, interval '5' second)",
"+2 05",
"INTERVAL DAY TO HOUR");
getTester().checkNull(
"nullif(interval '3' day, interval '3' day)");
}
public void testCoalesceFunc()
{
getTester().setFor(SqlStdOperatorTable.coalesceFunc);
getTester().checkString("coalesce('a','b')", "a", "CHAR(1) NOT NULL");
getTester().checkScalarExact("coalesce(null,null,3)", "3");
getTester().checkFails(
"1 + ^coalesce('a', 'b', 1, null)^ + 2",
"Illegal mixing of types in CASE or COALESCE statement",
false);
}
public void testUserFunc()
{
getTester().setFor(SqlStdOperatorTable.userFunc);
getTester().checkString("USER", "sa", "VARCHAR(2000) NOT NULL");
}
public void testCurrentUserFunc()
{
getTester().setFor(SqlStdOperatorTable.currentUserFunc);
getTester().checkString("CURRENT_USER", "sa", "VARCHAR(2000) NOT NULL");
}
public void testSessionUserFunc()
{
getTester().setFor(SqlStdOperatorTable.sessionUserFunc);
getTester().checkString("SESSION_USER", "sa", "VARCHAR(2000) NOT NULL");
}
public void testSystemUserFunc()
{
getTester().setFor(SqlStdOperatorTable.systemUserFunc);
String user = System.getProperty("user.name"); // e.g. "jhyde"
getTester().checkString("SYSTEM_USER", user, "VARCHAR(2000) NOT NULL");
}
public void testCurrentPathFunc()
{
getTester().setFor(SqlStdOperatorTable.currentPathFunc);
getTester().checkString("CURRENT_PATH", "", "VARCHAR(2000) NOT NULL");
}
public void testCurrentRoleFunc()
{
getTester().setFor(SqlStdOperatorTable.currentRoleFunc);
// By default, the CURRENT_ROLE function returns
// the empty string because a role has to be set explicitly.
getTester().checkString("CURRENT_ROLE", "", "VARCHAR(2000) NOT NULL");
}
public void testLocalTimeFunc()
{
getTester().setFor(SqlStdOperatorTable.localTimeFunc);
getTester().checkScalar("LOCALTIME", timePattern, "TIME(0) NOT NULL");
getTester().checkFails(
"^LOCALTIME()^",
"No match found for function signature LOCALTIME\\(\\)",
false);
getTester().checkScalar(
"LOCALTIME(1)",
timePattern,
"TIME(1) NOT NULL");
}
public void testLocalTimestampFunc()
{
getTester().setFor(SqlStdOperatorTable.localTimestampFunc);
getTester().checkScalar(
"LOCALTIMESTAMP",
timestampPattern,
"TIMESTAMP(0) NOT NULL");
getTester().checkFails(
"^LOCALTIMESTAMP()^",
"No match found for function signature LOCALTIMESTAMP\\(\\)",
false);
getTester().checkFails(
"LOCALTIMESTAMP(^4000000000^)",
literalOutOfRangeMessage,
false);
getTester().checkScalar(
"LOCALTIMESTAMP(1)",
timestampPattern,
"TIMESTAMP(1) NOT NULL");
}
public void testCurrentTimeFunc()
{
getTester().setFor(SqlStdOperatorTable.currentTimeFunc);
getTester().checkScalar(
"CURRENT_TIME",
timePattern,
"TIME(0) NOT NULL");
getTester().checkFails(
"^CURRENT_TIME()^",
"No match found for function signature CURRENT_TIME\\(\\)",
false);
getTester().checkScalar(
"CURRENT_TIME(1)",
timePattern,
"TIME(1) NOT NULL");
}
public void testCurrentTimestampFunc()
{
getTester().setFor(SqlStdOperatorTable.currentTimestampFunc);
getTester().checkScalar(
"CURRENT_TIMESTAMP",
timestampPattern,
"TIMESTAMP(0) NOT NULL");
getTester().checkFails(
"^CURRENT_TIMESTAMP()^",
"No match found for function signature CURRENT_TIMESTAMP\\(\\)",
false);
getTester().checkFails(
"CURRENT_TIMESTAMP(^4000000000^)",
literalOutOfRangeMessage,
false);
getTester().checkScalar(
"CURRENT_TIMESTAMP(1)",
timestampPattern,
"TIMESTAMP(1) NOT NULL");
}
public void testCurrentDateFunc()
{
getTester().setFor(SqlStdOperatorTable.currentDateFunc);
getTester().checkScalar("CURRENT_DATE", datePattern, "DATE NOT NULL");
getTester().checkFails(
"^CURRENT_DATE()^",
"No match found for function signature CURRENT_DATE\\(\\)",
false);
}
public void testSubstringFunction()
{
getTester().setFor(SqlStdOperatorTable.substringFunc);
getTester().checkString(
"substring('abc' from 1 for 2)",
"ab",
"VARCHAR(3) NOT NULL");
getTester().checkString(
"substring('abc' from 2)",
"bc",
"VARCHAR(3) NOT NULL");
//substring reg exp not yet supported
//getTester().checkString("substring('foobar' from '%#\"o_b#\"%' for
//'#')", "oob");
getTester().checkNull("substring(cast(null as varchar(1)),1,2)");
}
public void testTrimFunc()
{
getTester().setFor(SqlStdOperatorTable.trimFunc);
// SQL:2003 6.29.11 Trimming a CHAR yields a VARCHAR
getTester().checkString(
"trim('a' from 'aAa')",
"A",
"VARCHAR(3) NOT NULL");
getTester().checkString(
"trim(both 'a' from 'aAa')",
"A",
"VARCHAR(3) NOT NULL");
getTester().checkString(
"trim(leading 'a' from 'aAa')",
"Aa",
"VARCHAR(3) NOT NULL");
getTester().checkString(
"trim(trailing 'a' from 'aAa')",
"aA",
"VARCHAR(3) NOT NULL");
getTester().checkNull("trim(cast(null as varchar(1)) from 'a')");
getTester().checkNull("trim('a' from cast(null as varchar(1)))");
if (Bug.Fnl3Fixed) {
// SQL:2003 6.29.9: trim string must have length=1. Failure occurs
// at runtime.
//
// TODO: Change message to "Invalid argument\(s\) for 'TRIM' function",
// The message should come from a resource file, and should still
// have the SQL error code 22027.
getTester().checkFails(
"trim('xy' from 'abcde')",
"could not calculate results for the following row:" + NL
+ "\\[ 0 \\]" + NL
+ "Messages:" + NL
+ "\\[0\\]:PC=0 Code=22027 ",
true);
getTester().checkFails(
"trim('' from 'abcde')",
"could not calculate results for the following row:" + NL
+ "\\[ 0 \\]" + NL
+ "Messages:" + NL
+ "\\[0\\]:PC=0 Code=22027 ",
true);
}
}
public void testWindow()
{
getTester().setFor(SqlStdOperatorTable.windowOperator);
if (Bug.Frg188Fixed) {
getTester().check(
"select sum(1) over (order by x) from (select 1 as x, 2 as y from (values (true)))",
new AbstractSqlTester.StringTypeChecker("INTEGER"),
"1",
0);
}
}
public void testElementFunc()
{
getTester().setFor(SqlStdOperatorTable.elementFunc);
if (todo) {
getTester().checkString(
"element(multiset['abc']))",
"abc",
"char(3) not null");
getTester().checkNull("element(multiset[cast(null as integer)]))");
}
}
public void testCardinalityFunc()
{
getTester().setFor(SqlStdOperatorTable.cardinalityFunc);
if (todo) {
getTester().checkScalarExact(
"cardinality(multiset[cast(null as integer),2]))",
"2");
}
}
public void testMemberOfOperator()
{
getTester().setFor(SqlStdOperatorTable.memberOfOperator);
if (todo) {
getTester().checkBoolean("1 member of multiset[1]", Boolean.TRUE);
getTester().checkBoolean(
"'2' member of multiset['1']",
Boolean.FALSE);
getTester().checkBoolean(
"cast(null as double) member of multiset[cast(null as double)]",
Boolean.TRUE);
getTester().checkBoolean(
"cast(null as double) member of multiset[1.1]",
Boolean.FALSE);
getTester().checkBoolean(
"1.1 member of multiset[cast(null as double)]",
Boolean.FALSE);
}
}
public void testCollectFunc()
{
getTester().setFor(SqlStdOperatorTable.collectFunc);
}
public void testFusionFunc()
{
getTester().setFor(SqlStdOperatorTable.fusionFunc);
}
public void testExtractFunc()
{
getTester().setFor(SqlStdOperatorTable.extractFunc);
// Intervals
getTester().checkScalar(
"extract(day from interval '2 3:4:5.678' day to second)",
"2",
"BIGINT NOT NULL");
getTester().checkScalar(
"extract(hour from interval '2 3:4:5.678' day to second)",
"3",
"BIGINT NOT NULL");
getTester().checkScalar(
"extract(minute from interval '2 3:4:5.678' day to second)",
"4",
"BIGINT NOT NULL");
// TODO: Seconds should include precision
getTester().checkScalar(
"extract(second from interval '2 3:4:5.678' day to second)",
"5",
"BIGINT NOT NULL");
getTester().checkScalar(
"extract(year from interval '4-2' year to month)",
"4",
"BIGINT NOT NULL");
getTester().checkScalar(
"extract(month from interval '4-2' year to month)",
"2",
"BIGINT NOT NULL");
getTester().checkNull(
"extract(month from cast(null as interval year))");
}
public void testCeilFunc()
{
getTester().setFor(SqlStdOperatorTable.ceilFunc);
getTester().checkScalarApprox("ceil(10.1e0)", "DOUBLE NOT NULL", 11, 0);
getTester().checkScalarApprox(
"ceil(cast(-11.2e0 as real))",
"REAL NOT NULL",
-11,
0);
getTester().checkScalarExact("ceil(100)", "INTEGER NOT NULL", "100");
getTester().checkScalarExact(
"ceil(1.3)",
"DECIMAL(2, 0) NOT NULL",
"2");
getTester().checkScalarExact(
"ceil(-1.7)",
"DECIMAL(2, 0) NOT NULL",
"-1");
getTester().checkNull("ceiling(cast(null as decimal(2,0)))");
getTester().checkNull("ceiling(cast(null as double))");
// Intervals
getTester().checkScalar(
"ceil(interval '3:4:5' hour to second)",
"+4:00:00",
"INTERVAL HOUR TO SECOND NOT NULL");
getTester().checkScalar(
"ceil(interval '-6.3' second)",
"-6",
"INTERVAL SECOND NOT NULL");
getTester().checkScalar(
"ceil(interval '5-1' year to month)",
"+6-00",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkScalar(
"ceil(interval '-5-1' year to month)",
"-5-00",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkNull(
"ceil(cast(null as interval year))");
}
public void testFloorFunc()
{
getTester().setFor(SqlStdOperatorTable.floorFunc);
getTester().checkScalarApprox("floor(2.5e0)", "DOUBLE NOT NULL", 2, 0);
getTester().checkScalarApprox(
"floor(cast(-1.2e0 as real))",
"REAL NOT NULL",
-2,
0);
getTester().checkScalarExact("floor(100)", "INTEGER NOT NULL", "100");
getTester().checkScalarExact(
"floor(1.7)",
"DECIMAL(2, 0) NOT NULL",
"1");
getTester().checkScalarExact(
"floor(-1.7)",
"DECIMAL(2, 0) NOT NULL",
"-2");
getTester().checkNull("floor(cast(null as decimal(2,0)))");
getTester().checkNull("floor(cast(null as real))");
// Intervals
getTester().checkScalar(
"floor(interval '3:4:5' hour to second)",
"+3:00:00",
"INTERVAL HOUR TO SECOND NOT NULL");
getTester().checkScalar(
"floor(interval '-6.3' second)",
"-7",
"INTERVAL SECOND NOT NULL");
getTester().checkScalar(
"floor(interval '5-1' year to month)",
"+5-00",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkScalar(
"floor(interval '-5-1' year to month)",
"-6-00",
"INTERVAL YEAR TO MONTH NOT NULL");
getTester().checkNull(
"floor(cast(null as interval year))");
}
public void testDenseRankFunc()
{
getTester().setFor(SqlStdOperatorTable.denseRankFunc);
}
public void testPercentRankFunc()
{
getTester().setFor(SqlStdOperatorTable.percentRankFunc);
}
public void testRankFunc()
{
getTester().setFor(SqlStdOperatorTable.rankFunc);
}
public void testCumeDistFunc()
{
getTester().setFor(SqlStdOperatorTable.cumeDistFunc);
}
public void testRowNumberFunc()
{
getTester().setFor(SqlStdOperatorTable.rowNumberFunc);
}
public void testCountFunc()
{
if (Bug.Frg188Fixed) {
getTester().setFor(SqlStdOperatorTable.countOperator);
getTester().checkType("count(*)", "BIGINT NOT NULL");
getTester().checkType("count('name')", "BIGINT NOT NULL");
getTester().checkType("count(1)", "BIGINT NOT NULL");
getTester().checkType("count(1.2)", "BIGINT NOT NULL");
getTester().checkType("COUNT(DISTINCT 'x')", "BIGINT NOT NULL");
getTester().checkFails(
"^COUNT()^",
"Invalid number of arguments to function 'COUNT'. Was expecting 1 arguments",
false);
getTester().checkFails(
"^COUNT(1, 2)^",
"Invalid number of arguments to function 'COUNT'. Was expecting 1 arguments",
false);
final String [] values = { "0", "CAST(null AS INTEGER)", "1", "0" };
getTester().checkAgg(
"COUNT(x)",
values,
3,
0);
getTester().checkAgg(
"COUNT(CASE x WHEN 0 THEN NULL ELSE -1 END)",
values,
2,
0);
getTester().checkAgg(
"COUNT(DISTINCT x)",
values,
2,
0);
// string values -- note that empty string is not null
final String [] stringValues =
{ "'a'", "CAST(NULL AS VARCHAR(1))", "''" };
getTester().checkAgg(
"COUNT(*)",
stringValues,
3,
0);
getTester().checkAgg(
"COUNT(x)",
stringValues,
2,
0);
getTester().checkAgg(
"COUNT(DISTINCT x)",
stringValues,
2,
0);
getTester().checkAgg(
"COUNT(DISTINCT 123)",
stringValues,
1,
0);
}
}
public void testSumFunc()
{
if (Bug.Frg188Fixed) {
getTester().setFor(SqlStdOperatorTable.sumOperator);
getTester().checkFails(
"sum(^*^)",
"Unknown identifier '\\*'",
false);
getTester().checkFails(
"^sum('name')^",
"(?s)Cannot apply 'SUM' to arguments of type 'SUM\\(<CHAR\\(4\\)>\\)'\\. Supported form\\(s\\): 'SUM\\(<NUMERIC>\\)'.*",
false);
getTester().checkType("sum(1)", "INTEGER");
getTester().checkType("sum(1.2)", "DECIMAL(2, 1)");
getTester().checkType("sum(DISTINCT 1.5)", "DECIMAL(2, 1)");
getTester().checkFails(
"^sum()^",
"Invalid number of arguments to function 'SUM'. Was expecting 1 arguments",
false);
getTester().checkFails(
"^sum(1, 2)^",
"Invalid number of arguments to function 'SUM'. Was expecting 1 arguments",
false);
getTester().checkFails(
"^sum(cast(null as varchar(2)))^",
"(?s)Cannot apply 'SUM' to arguments of type 'SUM\\(<VARCHAR\\(2\\)>\\)'\\. Supported form\\(s\\): 'SUM\\(<NUMERIC>\\)'.*",
false);
final String [] values = { "0", "CAST(null AS INTEGER)", "2", "2" };
getTester().checkAgg(
"sum(x)",
values,
4,
0);
getTester().checkAgg(
"sum(CASE x WHEN 0 THEN NULL ELSE -1 END)",
values,
-3,
0);
getTester().checkAgg(
"sum(DISTINCT CASE x WHEN 0 THEN NULL ELSE -1 END)",
values,
-1,
0);
getTester().checkAgg(
"sum(DISTINCT x)",
values,
2,
0);
}
}
public void testAvgFunc()
{
if (Bug.Frg188Fixed) {
getTester().setFor(SqlStdOperatorTable.avgOperator);
getTester().checkFails(
"avg(^*^)",
"Unknown identifier '\\*'",
false);
getTester().checkFails(
"^avg(cast(null as varchar(2)))^",
"(?s)Cannot apply 'AVG' to arguments of type 'AVG\\(<VARCHAR\\(2\\)>\\)'\\. Supported form\\(s\\): 'AVG\\(<NUMERIC>\\)'.*",
false);
getTester().checkType("AVG(CAST(NULL AS INTEGER))", "INTEGER");
getTester().checkType("AVG(DISTINCT 1.5)", "DECIMAL(2, 1)");
final String [] values = { "0", "CAST(null AS INTEGER)", "3", "3" };
getTester().checkAgg(
"AVG(x)",
values,
new Double(1),
0);
getTester().checkAgg(
"AVG(DISTINCT x)",
values,
new Double(1.5),
0);
getTester().checkAgg(
"avg(DISTINCT CASE x WHEN 0 THEN NULL ELSE -1 END)",
values,
-1,
0);
}
}
public void testLastValueFunc()
{
if (Bug.Frg188Fixed) {
getTester().setFor(SqlStdOperatorTable.lastValueOperator);
getTester().checkScalarExact("last_value(1)", "1");
getTester().checkScalarExact(
"last_value(1.2)",
"DECIMAL(2, 1) NOT NULL",
"1.2");
getTester().checkType("last_value('name')", "CHAR(4) NOT NULL");
getTester().checkString(
"last_value('name')",
"name",
"CHAR(4) NOT NULL");
}
}
public void testFirstValueFunc()
{
if (Bug.Frg188Fixed) {
getTester().setFor(SqlStdOperatorTable.firstValueOperator);
getTester().checkScalarExact("first_value(1)", "1");
getTester().checkScalarExact(
"first_value(1.2)",
"DECIMAL(2, 1) NOT NULL",
"1.2");
getTester().checkType("first_value('name')", "CHAR(4) NOT NULL");
getTester().checkString(
"first_value('name')",
"name",
"CHAR(4) NOT NULL");
}
}
/**
* Tests that CAST fails when given a value just outside the valid range for
* that type. For example,
*
* <ul>
* <li>CAST(-200 AS TINYINT) fails because the value is less than -128;
* <li>CAST(1E-999 AS FLOAT) fails because the value underflows;
* <li>CAST(123.4567891234567 AS FLOAT) fails because the value loses
* precision.
* </ul>
*/
public void testLiteralAtLimit()
{
final SqlTester tester = getTester();
tester.setFor(SqlStdOperatorTable.castFunc);
for (BasicSqlType type : SqlLimitsTest.getTypes()) {
for (Object o : getValues(type, true)) {
SqlLiteral literal =
type.getSqlTypeName().createLiteral(o, SqlParserPos.ZERO);
String literalString =
literal.toSqlString(SqlUtil.dummyDialect);
final String expr =
"CAST(" + literalString
+ " AS " + type + ")";
if (type.getSqlTypeName() == SqlTypeName.VARBINARY &&
!Bug.Frg283Fixed) {
continue;
}
try {
tester.checkType(
expr,
type.getFullTypeString());
if (type.getSqlTypeName() == SqlTypeName.BINARY) {
// Casting a string/binary values may change the value.
// For example, CAST(X'AB' AS BINARY(2)) yields
// X'AB00'.
} else {
tester.checkScalar(
expr + " = " + literalString,
true,
"BOOLEAN NOT NULL");
}
} catch (Error e) {
System.out.println("Failed for expr=[" + expr + "]");
throw e;
} catch (RuntimeException e) {
System.out.println("Failed for expr=[" + expr + "]");
throw e;
}
}
}
}
/**
* Tests that CAST fails when given a value just outside the valid range for
* that type. For example,
*
* <ul>
* <li>CAST(-200 AS TINYINT) fails because the value is less than -128;
* <li>CAST(1E-999 AS FLOAT) fails because the value underflows;
* <li>CAST(123.4567891234567 AS FLOAT) fails because the value loses
* precision.
* </ul>
*/
public void testLiteralBeyondLimit()
{
final SqlTester tester = getTester();
tester.setFor(SqlStdOperatorTable.castFunc);
for (BasicSqlType type : SqlLimitsTest.getTypes()) {
for (Object o : getValues(type, false)) {
SqlLiteral literal =
type.getSqlTypeName().createLiteral(o, SqlParserPos.ZERO);
String literalString =
literal.toSqlString(SqlUtil.dummyDialect);
if ((type.getSqlTypeName() == SqlTypeName.BIGINT)
|| ((type.getSqlTypeName() == SqlTypeName.DECIMAL)
&& (type.getPrecision() == 19)))
{
// Values which are too large to be literals fail at
// validate time.
tester.checkFails(
"CAST(^" + literalString + "^ AS " + type + ")",
"Numeric literal '.*' out of range",
false);
} else if (
(type.getSqlTypeName() == SqlTypeName.CHAR)
|| (type.getSqlTypeName() == SqlTypeName.VARCHAR)
|| (type.getSqlTypeName() == SqlTypeName.BINARY)
|| (type.getSqlTypeName() == SqlTypeName.VARBINARY))
{
// Casting overlarge string/binary values do not fail -
// they are truncated. See testCastTruncates().
} else {
// Value outside legal bound should fail at runtime (not
// validate time).
//
// NOTE: Because Java and Fennel calcs give
// different errors, the pattern hedges its bets.
tester.checkFails(
"CAST(" + literalString + " AS " + type + ")",
"(?s).*(Overflow during calculation or cast\\.|Code=22003).*",
true);
}
}
}
}
public void testCastTruncates()
{
final SqlTester tester = getTester();
tester.setFor(SqlStdOperatorTable.castFunc);
tester.checkScalar(
"CAST('ABCD' AS CHAR(2))",
"AB",
"CHAR(2) NOT NULL");
tester.checkScalar(
"CAST('ABCD' AS VARCHAR(2))",
"AB",
"VARCHAR(2) NOT NULL");
tester.checkScalar(
"CAST(x'ABCDEF12' AS BINARY(2))",
"ABCD",
"BINARY(2) NOT NULL");
if (Bug.Frg283Fixed)
tester.checkScalar(
"CAST(x'ABCDEF12' AS VARBINARY(2))",
"ABCD",
"VARBINARY(2) NOT NULL");
tester.checkBoolean(
"CAST(X'' AS BINARY(3)) = X'000000'",
true);
tester.checkBoolean(
"CAST(X'' AS BINARY(3)) = X''",
false);
}
private List<Object> getValues(BasicSqlType type, boolean inBound)
{
List<Object> values = new ArrayList<Object>();
for (boolean sign : FalseTrue) {
for (SqlTypeName.Limit limit : SqlTypeName.Limit.values()) {
Object o = type.getLimit(sign, limit, !inBound);
if (o == null) {
continue;
}
if (!values.contains(o)) {
values.add(o);
}
}
}
return values;
}
// TODO: Test other stuff
}
// End SqlOperatorTests.java
|
FARRAGO: Expand tests with intervals in SqlOperatorTests.
[git-p4: depot-paths = "//open/dt/dev/": change = 9865]
|
farrago/src/org/eigenbase/sql/test/SqlOperatorTests.java
|
FARRAGO: Expand tests with intervals in SqlOperatorTests.
|
|
Java
|
apache-2.0
|
0bae9f3808f337b046280023142ddcbc5f23b081
| 0
|
tomakehurst/wiremock,Mahoney/wiremock,tomakehurst/wiremock,Mahoney/wiremock,dlaha21/wiremock,tomakehurst/wiremock,Mahoney/wiremock,Mahoney/wiremock,tomakehurst/wiremock,dlaha21/wiremock,dlaha21/wiremock,dlaha21/wiremock,Mahoney/wiremock,dlaha21/wiremock,tomakehurst/wiremock
|
package com.github.tomakehurst.wiremock.http.ssl;
import sun.security.tools.keytool.CertAndKeyGen;
import sun.security.util.HostnameChecker;
import sun.security.x509.CertificateExtensions;
import sun.security.x509.DNSName;
import sun.security.x509.GeneralName;
import sun.security.x509.GeneralNames;
import sun.security.x509.SubjectAlternativeNameExtension;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
import javax.net.ssl.ExtendedSSLSession;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.X509ExtendedKeyManager;
import java.io.IOException;
import java.net.Socket;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import static java.util.Collections.emptyList;
@SuppressWarnings("sunapi")
public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509ExtendedKeyManager {
private final KeyStore keyStore;
private final char[] password;
public CertificateGeneratingX509ExtendedKeyManager(X509ExtendedKeyManager keyManager, KeyStore keyStore, char[] keyPassword) {
super(keyManager);
this.keyStore = keyStore;
this.password = keyPassword;
}
@Override
public PrivateKey getPrivateKey(String alias) {
PrivateKey original = super.getPrivateKey(alias);
if (original == null) {
return getDynamicPrivateKey(alias);
} else {
return original;
}
}
private PrivateKey getDynamicPrivateKey(String alias) {
try {
return (PrivateKey) keyStore.getKey(alias, password);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
return null;
}
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
X509Certificate[] original = super.getCertificateChain(alias);
if (original == null) {
return getDynamicCertificateChain(alias);
} else {
return original;
}
}
private X509Certificate[] getDynamicCertificateChain(String alias) {
try {
Certificate[] fromKeyStore = keyStore.getCertificateChain(alias);
if (fromKeyStore != null && areX509Certificates(fromKeyStore)) {
return convertToX509(fromKeyStore);
} else {
return null;
}
} catch (KeyStoreException e) {
return null;
}
}
private boolean areX509Certificates(Certificate[] fromKeyStore) {
return fromKeyStore.length == 0 || fromKeyStore[0] instanceof X509Certificate;
}
private static X509Certificate[] convertToX509(Certificate[] fromKeyStore) {
X509Certificate[] result = new X509Certificate[fromKeyStore.length];
for (int i = 0; i < fromKeyStore.length; i++) {
result[i] = (X509Certificate) fromKeyStore[i];
}
return result;
}
@Override
public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
String defaultAlias = super.chooseServerAlias(keyType, issuers, socket);
ExtendedSSLSession handshakeSession = getHandshakeSession(socket);
return tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);
}
private ExtendedSSLSession getHandshakeSession(Socket socket) {
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
SSLSession sslSession = getHandshakeSessionIfSupported(sslSocket);
return getHandshakeSession(sslSession);
} else {
return null;
}
}
private SSLSession getHandshakeSessionIfSupported(SSLSocket sslSocket) {
try {
return sslSocket.getHandshakeSession();
} catch (UnsupportedOperationException e) {
// TODO log that dynamically generating is not supported
return null;
}
}
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
String defaultAlias = super.chooseEngineServerAlias(keyType, issuers, engine);
ExtendedSSLSession handshakeSession = getHandshakeSession(engine);
return tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);
}
private ExtendedSSLSession getHandshakeSession(SSLEngine sslEngine) {
SSLSession sslSession = getHandshakeSessionIfSupported(sslEngine);
return getHandshakeSession(sslSession);
}
private SSLSession getHandshakeSessionIfSupported(SSLEngine sslEngine) {
try {
return sslEngine.getHandshakeSession();
} catch (UnsupportedOperationException | NullPointerException e) {
// TODO log that dynamically generating is not supported
return null;
}
}
private ExtendedSSLSession getHandshakeSession(SSLSession handshakeSession) {
if (handshakeSession instanceof ExtendedSSLSession) {
return (ExtendedSSLSession) handshakeSession;
} else {
return null;
}
}
/**
* @param keyType non null, may be invalid
* @param defaultAlias nullable
* @param handshakeSession nullable
*/
private String tryToChooseServerAlias(String keyType, String defaultAlias, ExtendedSSLSession handshakeSession) {
if (defaultAlias != null && handshakeSession != null) {
return chooseServerAlias(keyType, defaultAlias, handshakeSession);
} else {
return defaultAlias;
}
}
/**
* @param keyType non null, guaranteed to be valid
* @param defaultAlias non null, guaranteed to match a private key entry
* @param handshakeSession non null
*/
private String chooseServerAlias(String keyType, String defaultAlias, ExtendedSSLSession handshakeSession) {
List<SNIHostName> requestedServerNames = getSNIHostNames(handshakeSession);
if (requestedServerNames.isEmpty()) {
return defaultAlias;
} else {
return chooseServerAlias(keyType, defaultAlias, requestedServerNames);
}
}
private List<SNIHostName> getSNIHostNames(ExtendedSSLSession handshakeSession) {
List<SNIServerName> requestedServerNames = getRequestedServerNames(handshakeSession);
List<SNIHostName> requestedHostNames = new ArrayList<>(requestedServerNames.size());
for (SNIServerName serverName: requestedServerNames) {
if (serverName instanceof SNIHostName) {
requestedHostNames.add((SNIHostName) serverName);
}
}
return requestedHostNames;
}
private List<SNIServerName> getRequestedServerNames(ExtendedSSLSession handshakeSession) {
try {
return handshakeSession.getRequestedServerNames();
} catch (UnsupportedOperationException e) {
// TODO log that dynamically generating is not supported
return emptyList();
}
}
/**
* @param keyType non null, guaranteed to be valid
* @param defaultAlias non null, guaranteed to match a private key entry
* @param requestedServerNames non null, non empty
*/
private String chooseServerAlias(String keyType, String defaultAlias, List<SNIHostName> requestedServerNames) {
X509Certificate[] certificateChain = getCertificateChain(defaultAlias);
if (matches(certificateChain[0], requestedServerNames)) {
return defaultAlias;
} else {
return generateCertificate(keyType, defaultAlias, requestedServerNames.get(0));
}
}
/**
* @param keyType non null, guaranteed to be valid
* @param defaultAlias non null, guaranteed to match a private key entry
* @param requestedServerName non null
* @return an alias to a new private key & certificate for the first requested server name
*/
private String generateCertificate(
String keyType,
String defaultAlias,
SNIHostName requestedServerName
) {
try {
String requestedNameString = requestedServerName.getAsciiName();
CertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, "SHA256With"+keyType, null);
newCertAndKey.generate(2048);
PrivateKey newKey = newCertAndKey.getPrivateKey();
X509Certificate certificate = newCertAndKey.getSelfCertificate(
new X500Name("CN=" + requestedNameString),
new Date(),
(long) 365 * 24 * 60 * 60,
subjectAlternativeName(requestedNameString)
);
CertChainAndKey authority = findExistingCertificateAuthority();
if (authority != null) {
X509Certificate[] signingChain = authority.certificateChain;
PrivateKey signingKey = authority.key;
X509Certificate signed = createSignedCertificate(certificate, signingChain[0], signingKey);
X509Certificate[] fullChain = new X509Certificate[signingChain.length + 1];
fullChain[0] = signed;
System.arraycopy(signingChain, 0, fullChain, 1, signingChain.length);
keyStore.setKeyEntry(requestedNameString, newKey, password, fullChain);
return requestedNameString;
} else {
return defaultAlias;
}
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | IOException | SignatureException e) {
// TODO log?
return defaultAlias;
}
}
private CertificateExtensions subjectAlternativeName(String requestedNameString) throws IOException {
GeneralName name = new GeneralName(new DNSName(requestedNameString));
GeneralNames names = new GeneralNames();
names.add(name);
SubjectAlternativeNameExtension subjectAlternativeNameExtension = new SubjectAlternativeNameExtension(names);
CertificateExtensions extensions = new CertificateExtensions();
extensions.set(SubjectAlternativeNameExtension.NAME, subjectAlternativeNameExtension);
return extensions;
}
private CertChainAndKey findExistingCertificateAuthority() {
Enumeration<String> aliases;
try {
aliases = keyStore.aliases();
} catch (KeyStoreException e) {
aliases = Collections.emptyEnumeration();
}
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
CertChainAndKey key = getCertChainAndKey(alias);
if (key != null) return key;
}
return null;
}
private CertChainAndKey getCertChainAndKey(String alias) {
X509Certificate[] chain = getCertificateChain(alias);
PrivateKey key = getPrivateKey(alias);
if (isCertificateAuthority(chain[0]) && key != null) {
return new CertChainAndKey(chain, key);
} else {
return null;
}
}
private boolean isCertificateAuthority(X509Certificate certificate) {
boolean[] keyUsage = certificate.getKeyUsage();
return keyUsage != null && keyUsage.length > 5 && keyUsage[5];
}
private static class CertChainAndKey {
private final X509Certificate[] certificateChain;
private final PrivateKey key;
private CertChainAndKey(X509Certificate[] certificateChain, PrivateKey key) {
this.certificateChain = certificateChain;
this.key = key;
}
}
private static X509Certificate createSignedCertificate(X509Certificate certificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) {
try {
Principal issuer = issuerCertificate.getSubjectDN();
String issuerSigAlg = issuerCertificate.getSigAlgName();
byte[] inCertBytes = certificate.getTBSCertificate();
X509CertInfo info = new X509CertInfo(inCertBytes);
info.set(X509CertInfo.ISSUER, issuer);
X509CertImpl outCert = new X509CertImpl(info);
outCert.sign(issuerPrivateKey, issuerSigAlg);
return outCert;
} catch (Exception ex) {
// TODO log failure to generate certificate
}
return null;
}
private boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {
for (SNIHostName serverName : requestedServerNames) {
if (matches(x509Certificate, serverName)) {
return true;
}
}
return false;
}
private boolean matches(X509Certificate x509Certificate, SNIHostName hostName) {
try {
HostnameChecker instance = HostnameChecker.getInstance(HostnameChecker.TYPE_TLS);
instance.match(hostName.getAsciiName(), x509Certificate);
return true;
} catch (CertificateException e) {
return false;
}
}
}
|
java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java
|
package com.github.tomakehurst.wiremock.http.ssl;
import sun.security.tools.keytool.CertAndKeyGen;
import sun.security.util.HostnameChecker;
import sun.security.x509.CertificateExtensions;
import sun.security.x509.DNSName;
import sun.security.x509.GeneralName;
import sun.security.x509.GeneralNames;
import sun.security.x509.SubjectAlternativeNameExtension;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
import javax.net.ssl.ExtendedSSLSession;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.X509ExtendedKeyManager;
import java.io.IOException;
import java.net.Socket;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import static java.util.Collections.emptyList;
@SuppressWarnings("sunapi")
public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509ExtendedKeyManager {
private final KeyStore keyStore;
private final char[] password;
public CertificateGeneratingX509ExtendedKeyManager(X509ExtendedKeyManager keyManager, KeyStore keyStore, char[] keyPassword) {
super(keyManager);
this.keyStore = keyStore;
this.password = keyPassword;
}
@Override
public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
String defaultAlias = super.chooseServerAlias(keyType, issuers, socket);
ExtendedSSLSession handshakeSession = getHandshakeSession(socket);
return tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);
}
private ExtendedSSLSession getHandshakeSession(Socket socket) {
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
SSLSession sslSession = getHandshakeSessionIfSupported(sslSocket);
return getHandshakeSession(sslSession);
} else {
return null;
}
}
private SSLSession getHandshakeSessionIfSupported(SSLSocket sslSocket) {
try {
return sslSocket.getHandshakeSession();
} catch (UnsupportedOperationException e) {
// TODO log that dynamically generating is not supported
return null;
}
}
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
String defaultAlias = super.chooseEngineServerAlias(keyType, issuers, engine);
ExtendedSSLSession handshakeSession = getHandshakeSession(engine);
return tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);
}
@Override
public PrivateKey getPrivateKey(String alias) {
PrivateKey original = super.getPrivateKey(alias);
if (original == null) {
return getDynamicPrivateKey(alias);
} else {
return original;
}
}
private PrivateKey getDynamicPrivateKey(String alias) {
try {
return (PrivateKey) keyStore.getKey(alias, password);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
return null;
}
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
X509Certificate[] original = super.getCertificateChain(alias);
if (original == null) {
return getDynamicCertificateChain(alias);
} else {
return original;
}
}
private X509Certificate[] getDynamicCertificateChain(String alias) {
try {
Certificate[] fromKeyStore = keyStore.getCertificateChain(alias);
if (fromKeyStore != null && areX509Certificates(fromKeyStore)) {
return convertToX509(fromKeyStore);
} else {
return null;
}
} catch (KeyStoreException e) {
return null;
}
}
private boolean areX509Certificates(Certificate[] fromKeyStore) {
return fromKeyStore.length == 0 || fromKeyStore[0] instanceof X509Certificate;
}
private static X509Certificate[] convertToX509(Certificate[] fromKeyStore) {
X509Certificate[] result = new X509Certificate[fromKeyStore.length];
for (int i = 0; i < fromKeyStore.length; i++) {
result[i] = (X509Certificate) fromKeyStore[i];
}
return result;
}
private ExtendedSSLSession getHandshakeSession(SSLEngine sslEngine) {
SSLSession sslSession = getHandshakeSessionIfSupported(sslEngine);
return getHandshakeSession(sslSession);
}
private SSLSession getHandshakeSessionIfSupported(SSLEngine sslEngine) {
try {
return sslEngine.getHandshakeSession();
} catch (UnsupportedOperationException | NullPointerException e) {
// TODO log that dynamically generating is not supported
return null;
}
}
private ExtendedSSLSession getHandshakeSession(SSLSession handshakeSession) {
if (handshakeSession instanceof ExtendedSSLSession) {
return (ExtendedSSLSession) handshakeSession;
} else {
return null;
}
}
/**
* @param keyType non null, may be invalid
* @param defaultAlias nullable
* @param handshakeSession nullable
*/
private String tryToChooseServerAlias(String keyType, String defaultAlias, ExtendedSSLSession handshakeSession) {
if (defaultAlias != null && handshakeSession != null) {
return chooseServerAlias(keyType, defaultAlias, handshakeSession);
} else {
return defaultAlias;
}
}
/**
* @param keyType non null, guaranteed to be valid
* @param defaultAlias non null, guaranteed to match a private key entry
* @param handshakeSession non null
*/
private String chooseServerAlias(String keyType, String defaultAlias, ExtendedSSLSession handshakeSession) {
List<SNIHostName> requestedServerNames = getSNIHostNames(handshakeSession);
if (requestedServerNames.isEmpty()) {
return defaultAlias;
} else {
return chooseServerAlias(keyType, defaultAlias, requestedServerNames);
}
}
private List<SNIHostName> getSNIHostNames(ExtendedSSLSession handshakeSession) {
List<SNIServerName> requestedServerNames = getRequestedServerNames(handshakeSession);
List<SNIHostName> requestedHostNames = new ArrayList<>(requestedServerNames.size());
for (SNIServerName serverName: requestedServerNames) {
if (serverName instanceof SNIHostName) {
requestedHostNames.add((SNIHostName) serverName);
}
}
return requestedHostNames;
}
private List<SNIServerName> getRequestedServerNames(ExtendedSSLSession handshakeSession) {
try {
return handshakeSession.getRequestedServerNames();
} catch (UnsupportedOperationException e) {
// TODO log that dynamically generating is not supported
return emptyList();
}
}
/**
* @param keyType non null, guaranteed to be valid
* @param defaultAlias non null, guaranteed to match a private key entry
* @param requestedServerNames non null, non empty
*/
private String chooseServerAlias(String keyType, String defaultAlias, List<SNIHostName> requestedServerNames) {
X509Certificate[] certificateChain = getCertificateChain(defaultAlias);
if (matches(certificateChain[0], requestedServerNames)) {
return defaultAlias;
} else {
return generateCertificate(keyType, defaultAlias, requestedServerNames.get(0));
}
}
/**
* @param keyType non null, guaranteed to be valid
* @param defaultAlias non null, guaranteed to match a private key entry
* @param requestedServerName non null
* @return an alias to a new private key & certificate for the first requested server name
*/
private String generateCertificate(
String keyType,
String defaultAlias,
SNIHostName requestedServerName
) {
try {
String requestedNameString = requestedServerName.getAsciiName();
CertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, "SHA256With"+keyType, null);
newCertAndKey.generate(2048);
PrivateKey newKey = newCertAndKey.getPrivateKey();
X509Certificate certificate = newCertAndKey.getSelfCertificate(
new X500Name("CN=" + requestedNameString),
new Date(),
(long) 365 * 24 * 60 * 60,
subjectAlternativeName(requestedNameString)
);
CertChainAndKey authority = findExistingCertificateAuthority();
if (authority != null) {
X509Certificate[] signingChain = authority.certificateChain;
PrivateKey signingKey = authority.key;
X509Certificate signed = createSignedCertificate(certificate, signingChain[0], signingKey);
X509Certificate[] fullChain = new X509Certificate[signingChain.length + 1];
fullChain[0] = signed;
System.arraycopy(signingChain, 0, fullChain, 1, signingChain.length);
keyStore.setKeyEntry(requestedNameString, newKey, password, fullChain);
return requestedNameString;
} else {
return defaultAlias;
}
} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | IOException | SignatureException e) {
// TODO log?
return defaultAlias;
}
}
private CertificateExtensions subjectAlternativeName(String requestedNameString) throws IOException {
GeneralName name = new GeneralName(new DNSName(requestedNameString));
GeneralNames names = new GeneralNames();
names.add(name);
SubjectAlternativeNameExtension subjectAlternativeNameExtension = new SubjectAlternativeNameExtension(names);
CertificateExtensions extensions = new CertificateExtensions();
extensions.set(SubjectAlternativeNameExtension.NAME, subjectAlternativeNameExtension);
return extensions;
}
private CertChainAndKey findExistingCertificateAuthority() {
Enumeration<String> aliases;
try {
aliases = keyStore.aliases();
} catch (KeyStoreException e) {
aliases = Collections.emptyEnumeration();
}
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
CertChainAndKey key = getCertChainAndKey(alias);
if (key != null) return key;
}
return null;
}
private CertChainAndKey getCertChainAndKey(String alias) {
X509Certificate[] chain = getCertificateChain(alias);
PrivateKey key = getPrivateKey(alias);
if (isCertificateAuthority(chain[0]) && key != null) {
return new CertChainAndKey(chain, key);
} else {
return null;
}
}
private boolean isCertificateAuthority(X509Certificate certificate) {
boolean[] keyUsage = certificate.getKeyUsage();
return keyUsage != null && keyUsage.length > 5 && keyUsage[5];
}
private static class CertChainAndKey {
private final X509Certificate[] certificateChain;
private final PrivateKey key;
private CertChainAndKey(X509Certificate[] certificateChain, PrivateKey key) {
this.certificateChain = certificateChain;
this.key = key;
}
}
private static X509Certificate createSignedCertificate(X509Certificate certificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) {
try {
Principal issuer = issuerCertificate.getSubjectDN();
String issuerSigAlg = issuerCertificate.getSigAlgName();
byte[] inCertBytes = certificate.getTBSCertificate();
X509CertInfo info = new X509CertInfo(inCertBytes);
info.set(X509CertInfo.ISSUER, issuer);
X509CertImpl outCert = new X509CertImpl(info);
outCert.sign(issuerPrivateKey, issuerSigAlg);
return outCert;
} catch (Exception ex) {
// TODO log failure to generate certificate
}
return null;
}
private boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {
for (SNIHostName serverName : requestedServerNames) {
if (matches(x509Certificate, serverName)) {
return true;
}
}
return false;
}
private boolean matches(X509Certificate x509Certificate, SNIHostName hostName) {
try {
HostnameChecker instance = HostnameChecker.getInstance(HostnameChecker.TYPE_TLS);
instance.match(hostName.getAsciiName(), x509Certificate);
return true;
} catch (CertificateException e) {
return false;
}
}
}
|
Group related methods together
|
java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java
|
Group related methods together
|
|
Java
|
apache-2.0
|
0f61ea19c35da80e115484ea22193f7e5a65170b
| 0
|
swift-lang/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,swift-lang/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,ya7lelkom/swift-k
|
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------
/*
* Created on Jul 21, 2006
*/
package org.globus.cog.karajan.workflow.service.channels;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.globus.cog.karajan.workflow.service.RemoteConfiguration;
import org.globus.cog.karajan.workflow.service.RequestManager;
import org.globus.cog.karajan.workflow.service.commands.ChannelConfigurationCommand;
import edu.emory.mathcs.backport.java.util.Collections;
public abstract class AbstractStreamKarajanChannel extends AbstractKarajanChannel implements
Purgeable {
public static final Logger logger = Logger.getLogger(AbstractStreamKarajanChannel.class);
public static final int STATE_IDLE = 0;
public static final int STATE_RECEIVING_DATA = 1;
public static final int HEADER_LEN = 12;
private InputStream inputStream;
private OutputStream outputStream;
private URI contact;
private final byte[] rhdr;
private byte[] data;
private int dataPointer;
private int state, tag, flags, len;
protected AbstractStreamKarajanChannel(RequestManager requestManager,
ChannelContext channelContext, boolean client) {
super(requestManager, channelContext, client);
rhdr = new byte[HEADER_LEN];
}
protected InputStream getInputStream() {
return inputStream;
}
protected void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
protected OutputStream getOutputStream() {
return outputStream;
}
protected void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
public URI getContact() {
return contact;
}
public void setContact(URI contact) {
this.contact = contact;
}
protected abstract void reconnect() throws ChannelException;
protected synchronized void handleChannelException(Exception e) {
logger.info("Channel config: " + getChannelContext().getConfiguration());
ChannelManager.getManager().handleChannelException(this, e);
try {
getSender().purge(this, new NullChannel(true));
}
catch (IOException e1) {
logger.warn("Failed to purge queued messages", e1);
}
}
protected void configure() throws Exception {
URI callbackURI = null;
ChannelContext sc = getChannelContext();
if (sc.getConfiguration().hasOption(RemoteConfiguration.CALLBACK)) {
callbackURI = getCallbackURI();
}
String remoteID = sc.getChannelID().getRemoteID();
ChannelConfigurationCommand ccc = new ChannelConfigurationCommand(sc.getConfiguration(),
callbackURI);
ccc.execute(this);
logger.info("Channel configured");
}
public synchronized void sendTaggedData(int tag, int flags, byte[] data) {
getSender().enqueue(tag, flags, data, this);
}
protected boolean step() throws IOException {
int avail = inputStream.available();
if (avail == 0) {
return false;
}
if (state == STATE_IDLE && avail >= HEADER_LEN) {
readFromStream(inputStream, rhdr, 0);
tag = unpack(rhdr, 0);
flags = unpack(rhdr, 4);
len = unpack(rhdr, 8);
if (len > 20000) {
System.out.println("Big len: " + len);
}
data = new byte[len];
dataPointer = 0;
state = STATE_RECEIVING_DATA;
}
if (state == STATE_RECEIVING_DATA) {
while (avail > 0 && dataPointer < len) {
dataPointer += inputStream.read(data, dataPointer, Math.min(avail, len
- dataPointer));
avail = inputStream.available();
}
if (dataPointer == len) {
state = STATE_IDLE;
boolean fin = (flags & FINAL_FLAG) != 0;
boolean error = (flags & ERROR_FLAG) != 0;
if ((flags & REPLY_FLAG) != 0) {
// reply
handleReply(tag, fin, error, len, data);
}
else {
// request
handleRequest(tag, fin, error, len, data);
}
}
}
return true;
}
public void purge(KarajanChannel channel) throws IOException {
getSender().purge(this, channel);
}
protected void register() {
getMultiplexer(FAST).register(this);
}
protected void unregister() {
getMultiplexer(FAST).unregister(this);
}
public void flush() throws IOException {
outputStream.flush();
}
private static final int SENDER_COUNT = 1;
private static Sender[] sender;
private static int crtSender;
private static synchronized Sender getSender() {
if (sender == null) {
sender = new Sender[SENDER_COUNT];
for (int i = 0; i < SENDER_COUNT; i++) {
sender[i] = new Sender();
sender[i].start();
}
}
try {
return sender[crtSender++];
}
finally {
if (crtSender == SENDER_COUNT) {
crtSender = 0;
}
}
}
private static class SendEntry {
public final int tag, flags;
public final byte[] data;
public final AbstractStreamKarajanChannel channel;
public SendEntry(int tag, int flags, byte[] data, AbstractStreamKarajanChannel channel) {
this.tag = tag;
this.flags = flags;
this.data = data;
this.channel = channel;
}
}
private static class Sender extends Thread {
private final LinkedList queue;
private final byte[] shdr;
public Sender() {
super("Sender");
queue = new LinkedList();
setDaemon(true);
shdr = new byte[HEADER_LEN];
}
public synchronized void enqueue(int tag, int flags, byte[] data,
AbstractStreamKarajanChannel channel) {
queue.addLast(new SendEntry(tag, flags, data, channel));
notify();
}
public void run() {
try {
SendEntry e;
while (true) {
synchronized (this) {
while (queue.isEmpty()) {
wait();
}
e = (SendEntry) queue.removeFirst();
}
try {
send(e.tag, e.flags, e.data, e.channel.getOutputStream());
}
catch (IOException ex) {
logger.info("Channel IOException", ex);
synchronized (this) {
queue.addFirst(e);
}
e.channel.handleChannelException(ex);
}
catch (Exception ex) {
ex.printStackTrace();
try {
e.channel.getChannelContext().getRegisteredCommand(e.tag).errorReceived(
null, ex);
}
catch (Exception exx) {
logger.warn(exx);
}
}
}
}
catch (InterruptedException e) {
// exit
}
}
public void purge(KarajanChannel source, KarajanChannel channel) throws IOException {
SendEntry e;
synchronized (this) {
Iterator i = queue.iterator();
while (i.hasNext()) {
e = (SendEntry) i.next();
if (e.channel == source) {
channel.sendTaggedData(e.tag, e.flags, e.data);
i.remove();
}
}
}
}
private void send(int tag, int flags, byte[] data, OutputStream os) throws IOException {
pack(shdr, 0, tag);
pack(shdr, 4, flags);
pack(shdr, 8, data.length);
synchronized (os) {
os.write(shdr);
os.write(data);
if ((flags & FINAL_FLAG) != 0) {
os.flush();
}
}
}
}
private static final int MUX_COUNT = 2;
private static Multiplexer[] multiplexer;
public static final int FAST = 0;
public static final int SLOW = 1;
public static synchronized Multiplexer getMultiplexer(int n) {
if (multiplexer == null) {
multiplexer = new Multiplexer[MUX_COUNT];
for (int i = 0; i < MUX_COUNT; i++) {
multiplexer[i] = new Multiplexer(i);
multiplexer[i].start();
}
}
return multiplexer[n];
}
protected static class Multiplexer extends Thread {
public static final Logger logger = Logger.getLogger(Multiplexer.class);
private Set channels;
private List remove, add;
private boolean terminated;
private int id;
public Multiplexer(int id) {
super("Channel multiplexer " + id);
this.id = id;
setDaemon(true);
channels = new HashSet();
remove = Collections.synchronizedList(new ArrayList());
add = Collections.synchronizedList(new ArrayList());
}
public synchronized void register(AbstractStreamKarajanChannel channel) {
add.add(channel);
if (logger.isInfoEnabled()) {
logger.info("(" + id + ") Scheduling " + channel + " for addition");
}
if (terminated) {
logger.warn("Trying to add a channel to a stopped multiplexer");
}
}
public void run() {
logger.info("Multiplexer " + id + " started");
boolean any;
try {
while (true) {
any = false;
Iterator i = channels.iterator();
while (i.hasNext()) {
AbstractStreamKarajanChannel channel = (AbstractStreamKarajanChannel) i.next();
if (channel.isClosed()) {
i.remove();
}
try {
any |= channel.step();
}
catch (Exception e) {
try {
shutdown(channel, e);
}
catch (Exception ee) {
logger.warn("Failed to shut down channel", e);
}
}
}
synchronized (this) {
i = remove.iterator();
while (i.hasNext()) {
Object r = i.next();
channels.remove(r);
}
i = add.iterator();
while (i.hasNext()) {
Object a = i.next();
channels.add(a);
}
remove.clear();
add.clear();
}
if (!any) {
Thread.sleep(20);
}
}
}
catch (Exception e) {
logger.warn("Exception in channel multiplexer", e);
}
catch (Error e) {
logger.error("Error in multiplexer", e);
e.printStackTrace();
System.exit(10);
}
finally {
logger.info("Multiplexer finished");
terminated = true;
}
}
public void unregister(AbstractStreamKarajanChannel channel) {
remove.add(channel);
}
private void shutdown(AbstractStreamKarajanChannel channel, Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Channel exception caught", e);
}
channel.handleChannelException(e);
remove.add(channel);
}
}
}
|
src/cog/modules/karajan/src/org/globus/cog/karajan/workflow/service/channels/AbstractStreamKarajanChannel.java
|
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------
/*
* Created on Jul 21, 2006
*/
package org.globus.cog.karajan.workflow.service.channels;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.globus.cog.karajan.workflow.service.RemoteConfiguration;
import org.globus.cog.karajan.workflow.service.RequestManager;
import org.globus.cog.karajan.workflow.service.commands.ChannelConfigurationCommand;
public abstract class AbstractStreamKarajanChannel extends AbstractKarajanChannel implements
Purgeable {
public static final Logger logger = Logger.getLogger(AbstractStreamKarajanChannel.class);
public static final int STATE_IDLE = 0;
public static final int STATE_RECEIVING_DATA = 1;
public static final int HEADER_LEN = 12;
private InputStream inputStream;
private OutputStream outputStream;
private URI contact;
private final byte[] rhdr;
private byte[] data;
private int dataPointer;
private int state, tag, flags, len;
protected AbstractStreamKarajanChannel(RequestManager requestManager,
ChannelContext channelContext, boolean client) {
super(requestManager, channelContext, client);
rhdr = new byte[HEADER_LEN];
}
protected InputStream getInputStream() {
return inputStream;
}
protected void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
protected OutputStream getOutputStream() {
return outputStream;
}
protected void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
public URI getContact() {
return contact;
}
public void setContact(URI contact) {
this.contact = contact;
}
protected abstract void reconnect() throws ChannelException;
protected synchronized void handleChannelException(Exception e) {
logger.info("Channel config: " + getChannelContext().getConfiguration());
ChannelManager.getManager().handleChannelException(this, e);
try {
getSender().purge(this, new NullChannel(true));
}
catch (IOException e1) {
logger.warn("Failed to purge queued messages", e1);
}
}
protected void configure() throws Exception {
URI callbackURI = null;
ChannelContext sc = getChannelContext();
if (sc.getConfiguration().hasOption(RemoteConfiguration.CALLBACK)) {
callbackURI = getCallbackURI();
}
String remoteID = sc.getChannelID().getRemoteID();
ChannelConfigurationCommand ccc = new ChannelConfigurationCommand(sc.getConfiguration(),
callbackURI);
ccc.execute(this);
logger.info("Channel configured");
}
public synchronized void sendTaggedData(int tag, int flags, byte[] data) {
getSender().enqueue(tag, flags, data, this);
}
protected boolean step() throws IOException {
int avail = inputStream.available();
if (avail == 0) {
return false;
}
if (state == STATE_IDLE && avail >= HEADER_LEN) {
readFromStream(inputStream, rhdr, 0);
tag = unpack(rhdr, 0);
flags = unpack(rhdr, 4);
len = unpack(rhdr, 8);
if (len > 20000) {
System.out.println("Big len: " + len);
}
data = new byte[len];
dataPointer = 0;
state = STATE_RECEIVING_DATA;
}
if (state == STATE_RECEIVING_DATA) {
while (avail > 0 && dataPointer < len) {
dataPointer += inputStream.read(data, dataPointer, Math.min(avail, len
- dataPointer));
avail = inputStream.available();
}
if (dataPointer == len) {
state = STATE_IDLE;
boolean fin = (flags & FINAL_FLAG) != 0;
boolean error = (flags & ERROR_FLAG) != 0;
if ((flags & REPLY_FLAG) != 0) {
// reply
handleReply(tag, fin, error, len, data);
}
else {
// request
handleRequest(tag, fin, error, len, data);
}
}
}
return true;
}
public void purge(KarajanChannel channel) throws IOException {
getSender().purge(this, channel);
}
protected void register() {
getMultiplexer(FAST).register(this);
}
public void flush() throws IOException {
outputStream.flush();
}
private static final int SENDER_COUNT = 1;
private static Sender[] sender;
private static int crtSender;
private static synchronized Sender getSender() {
if (sender == null) {
sender = new Sender[SENDER_COUNT];
for (int i = 0; i < SENDER_COUNT; i++) {
sender[i] = new Sender();
sender[i].start();
}
}
try {
return sender[crtSender++];
}
finally {
if (crtSender == SENDER_COUNT) {
crtSender = 0;
}
}
}
private static class SendEntry {
public final int tag, flags;
public final byte[] data;
public final AbstractStreamKarajanChannel channel;
public SendEntry(int tag, int flags, byte[] data, AbstractStreamKarajanChannel channel) {
this.tag = tag;
this.flags = flags;
this.data = data;
this.channel = channel;
}
}
private static class Sender extends Thread {
private final LinkedList queue;
private final byte[] shdr;
public Sender() {
super("Sender");
queue = new LinkedList();
setDaemon(true);
shdr = new byte[HEADER_LEN];
}
public synchronized void enqueue(int tag, int flags, byte[] data,
AbstractStreamKarajanChannel channel) {
queue.addLast(new SendEntry(tag, flags, data, channel));
notify();
}
public void run() {
try {
SendEntry e;
while (true) {
synchronized (this) {
while (queue.isEmpty()) {
wait();
}
e = (SendEntry) queue.removeFirst();
}
try {
send(e.tag, e.flags, e.data, e.channel.getOutputStream());
}
catch (IOException ex) {
logger.info("Channel IOException", ex);
synchronized (this) {
queue.addFirst(e);
}
e.channel.handleChannelException(ex);
}
catch (Exception ex) {
ex.printStackTrace();
try {
e.channel.getChannelContext().getRegisteredCommand(e.tag).errorReceived(
null, ex);
}
catch (Exception exx) {
logger.warn(exx);
}
}
}
}
catch (InterruptedException e) {
// exit
}
}
public void purge(KarajanChannel source, KarajanChannel channel) throws IOException {
SendEntry e;
synchronized (this) {
Iterator i = queue.iterator();
while (i.hasNext()) {
e = (SendEntry) i.next();
if (e.channel == source) {
channel.sendTaggedData(e.tag, e.flags, e.data);
i.remove();
}
}
}
}
private void send(int tag, int flags, byte[] data, OutputStream os) throws IOException {
pack(shdr, 0, tag);
pack(shdr, 4, flags);
pack(shdr, 8, data.length);
synchronized (os) {
os.write(shdr);
os.write(data);
if ((flags & FINAL_FLAG) != 0) {
os.flush();
}
}
}
}
private static final int MUX_COUNT = 2;
private static Multiplexer[] multiplexer;
public static final int FAST = 0;
public static final int SLOW = 1;
public static synchronized Multiplexer getMultiplexer(int n) {
if (multiplexer == null) {
multiplexer = new Multiplexer[MUX_COUNT];
for (int i = 0; i < MUX_COUNT; i++) {
multiplexer[i] = new Multiplexer(i);
multiplexer[i].start();
}
}
return multiplexer[n];
}
protected static class Multiplexer extends Thread {
public static final Logger logger = Logger.getLogger(Multiplexer.class);
private Set channels;
private List remove, add;
private boolean terminated;
private int id;
public Multiplexer(int id) {
super("Channel multiplexer " + id);
this.id = id;
setDaemon(true);
channels = new HashSet();
remove = new ArrayList();
add = new ArrayList();
}
public synchronized void register(AbstractStreamKarajanChannel channel) {
add.add(channel);
if (logger.isInfoEnabled()) {
logger.info("(" + id + ") Scheduling " + channel + " for addition");
}
if (terminated) {
logger.warn("Trying to add a channel to a stopped multiplexer");
}
}
public void run() {
logger.info("Multiplexer " + id + " started");
boolean any;
try {
while (true) {
any = false;
Iterator i = channels.iterator();
while (i.hasNext()) {
AbstractStreamKarajanChannel channel = (AbstractStreamKarajanChannel) i.next();
if (channel.isClosed()) {
i.remove();
}
try {
any |= channel.step();
}
catch (Exception e) {
try {
shutdown(channel, e);
}
catch (Exception ee) {
logger.warn("Failed to shut down channel", e);
}
}
}
synchronized (this) {
i = remove.iterator();
while (i.hasNext()) {
Object r = i.next();
channels.remove(r);
}
i = add.iterator();
while (i.hasNext()) {
Object a = i.next();
channels.add(a);
}
remove.clear();
add.clear();
}
if (!any) {
Thread.sleep(20);
}
}
}
catch (Exception e) {
logger.warn("Exception in channel multiplexer", e);
}
catch (Error e) {
logger.error("Error in multiplexer", e);
e.printStackTrace();
System.exit(10);
}
finally {
logger.info("Multiplexer finished");
terminated = true;
}
}
private void shutdown(AbstractStreamKarajanChannel channel, Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Channel exception caught", e);
}
channel.handleChannelException(e);
remove.add(channel);
}
}
}
|
ehm, added relevant method used by previous commit
git-svn-id: 093fa4c7fa7b11ddcea9103fc581483144c30c11@2358 5b74d2a0-fa0e-0410-85ed-ffba77ec0bde
|
src/cog/modules/karajan/src/org/globus/cog/karajan/workflow/service/channels/AbstractStreamKarajanChannel.java
|
ehm, added relevant method used by previous commit
|
|
Java
|
apache-2.0
|
93b14ae6aaedf3a401aa186237b6a51bf6254351
| 0
|
Eventasia/eventasia
|
package com.github.eventasia.dynamodb;
import com.github.eventasia.framework.Aggregate;
import java.util.UUID;
public class EventasiaDynamoDBAggregateRepositoryImpl<A extends Aggregate> implements EventasiaDynamoDBAggregateRepository<A> {
private final EventasiaDynamoDBConfig config;
private final Class clazz;
public EventasiaDynamoDBAggregateRepositoryImpl(EventasiaDynamoDBConfig config, Class clazz) {
this.config = config;
this.clazz = clazz;
}
@Override
public void save(A aggregate) {
config.getMapper().save(aggregate);
}
@Override
public A get(UUID uuid) {
return (A) config.getMapper().load(clazz, uuid);
}
}
|
eventasia-store-dynamodb/src/main/java/com/github/eventasia/dynamodb/EventasiaDynamoDBAggregateRepositoryImpl.java
|
package com.github.eventasia.dynamodb;
import com.github.eventasia.framework.Aggregate;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
public class EventasiaDynamoDBAggregateRepositoryImpl<A extends Aggregate> implements EventasiaDynamoDBAggregateRepository<A> {
private final EventasiaDynamoDBConfig config;
private final Class clazz;
public EventasiaDynamoDBAggregateRepositoryImpl(EventasiaDynamoDBConfig config, Class clazz) {
this.config = config;
this.clazz = clazz;
}
@Override
public void save(A aggregate) {
config.getMapper().save(aggregate);
}
@Override
public A get(UUID uuid) {
return (A) config.getMapper().load(clazz, uuid);
}
}
|
remove component annotation from dynamo repo
|
eventasia-store-dynamodb/src/main/java/com/github/eventasia/dynamodb/EventasiaDynamoDBAggregateRepositoryImpl.java
|
remove component annotation from dynamo repo
|
|
Java
|
apache-2.0
|
679ea42ff5ea0f56f16ff8fb22ef2ce05501e820
| 0
|
Jonathan727/javarosa,Jonathan727/javarosa,Jonathan727/javarosa
|
package org.javarosa.core.model.data;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.util.Externalizable;
import org.javarosa.core.util.UnavailableExternalizerException;
public class Selection implements Externalizable {
public int index;
public QuestionDef question; //cannot hold reference directly to selectItems, as it is wiped out and rebuilt after every locale change
/**
* Note that this constructor should only be used for serialization/deserialization as
* selection is immutable
*/
public Selection() {
}
public Selection (int index, QuestionDef question) {
this.index = index;
this.question = question;
}
public String getText () {
return (String)question.getSelectItems().keyAt(index);
}
public String getValue () {
//NOTE: Not sure whether this is actually correct, we definitely
//should be returning what is in ItemIDs....
//droos: it doesn't matter; the 'element' portions of both these hashtables should be identical
//return (String)question.getSelectItems().elementAt(index);
return (String)question.getSelectItemIDs().elementAt(index);
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.utilities.Externalizable#readExternal(java.io.DataInputStream)
*/
public void readExternal(DataInputStream in) throws IOException,
InstantiationException, IllegalAccessException,
UnavailableExternalizerException {
index = in.readInt();
//setting QuestionDef in this way isn't correct; see note below
question = new QuestionDef();
question.readExternal(in);
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.utilities.Externalizable#writeExternal(java.io.DataOutputStream)
*/
/* TODO: serializing the referenced QuestionDef directly isn't correct, and we're lucky it's not causing us
* problems right now. The point of keeping a reference to the QuestionDef is so that we have easy access
* to the localized text in the current locale. However, for this to work, the referenced QuestionDef must be
* the SAME QuestionDef that the FormDef uses. Serializing/deserializing the QuestionDef like we are now results
* in this object pointing to a DIFFERENT QuestionDef -- one that does not receive localization updates. (In fact,
* a QuestionDef that is never properly localized in the first place). We need to change this so that this object
* will point to the proper QuestionDef object.
*
* The only reason this isn't biting us is because this Selection object will be discarded and rebuilt properly
* by the time we ever need to access the QuestionDef. We only call getText after the question has been
* skipped/answered, and when we answer/skip the select question, we create a new IAnswerData that overwrites this
* one. This invariance seems fragile, however.
*/
public void writeExternal(DataOutputStream out) throws IOException {
out.writeInt(index);
//TODO: fix this
question.writeExternal(out);
}
}
|
org.javarosa.core.model/src/org/javarosa/core/model/data/Selection.java
|
package org.javarosa.core.model.data;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.util.Externalizable;
import org.javarosa.core.util.UnavailableExternalizerException;
public class Selection implements Externalizable {
public int index;
public QuestionDef question; //cannot hold reference directly to selectItems, as it is wiped out and rebuilt after every locale change
/**
* Note that this constructor should only be used for serialization/deserialization as
* selection is immutable
*/
public Selection() {
}
public Selection (int index, QuestionDef question) {
this.index = index;
this.question = question;
}
public String getText () {
return (String)question.getSelectItems().keyAt(index);
}
public String getValue () {
//NOTE: Not sure whether this is actually correct, we definitely
//should be returning what is in ItemIDs....
//droos: it doesn't matter; the 'element' portions of both these hashtables should be identical
//return (String)question.getSelectItems().elementAt(index);
return (String)question.getSelectItemIDs().elementAt(index);
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.utilities.Externalizable#readExternal(java.io.DataInputStream)
*/
//TODO: this sucks!
public void readExternal(DataInputStream in) throws IOException,
InstantiationException, IllegalAccessException,
UnavailableExternalizerException {
index = in.readInt();
question = new QuestionDef();
question.readExternal(in); //i don't think this even works right: it has to reference the SAME QuestionDef that's in the FormDef
}
/* (non-Javadoc)
* @see org.javarosa.core.services.storage.utilities.Externalizable#writeExternal(java.io.DataOutputStream)
*/
//TODO: this sucks!
public void writeExternal(DataOutputStream out) throws IOException {
out.writeInt(index);
question.writeExternal(out);
}
}
|
[r960] [branches/dev] Explaining the nature of the brokenness with how we serialize Selections. Didn't actually fix anything, though
|
org.javarosa.core.model/src/org/javarosa/core/model/data/Selection.java
|
[r960] [branches/dev] Explaining the nature of the brokenness with how we serialize Selections. Didn't actually fix anything, though
|
|
Java
|
apache-2.0
|
33fe1793014e2193e49bbad4e787c1a3d3a8c727
| 0
|
wso2/carbon-business-process,nandika/carbon-business-process,nandika/carbon-business-process,milindaperera/carbon-business-process,milindaperera/carbon-business-process,nandika/carbon-business-process,milindaperera/carbon-business-process,wso2/carbon-business-process,wso2/carbon-business-process
|
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.bpel.core.ode.integration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.bpel.core.internal.BPELServiceComponent;
import org.wso2.carbon.core.ServerStartupObserver;
/**
* This class starts up the ode scheduler when the startup finalizer calls the invoke method
*/
public class BPELSchedulerInitializer implements ServerStartupObserver {
private static Log log = LogFactory.getLog(BPELSchedulerInitializer.class);
@Override
public void completingServerStartup() {
if (BPELServiceComponent.getBPELServer().getBpelServerConfiguration().getUseDistributedLock()) {
if (BPELServiceComponent.getHazelcastInstance() != null) {
log.info("HazelCast instance available and configured");
} else {
log.error("HazelCast instance not available, but distributed lock enabled");
}
}
}
@Override
public void completedServerStartup() {
if (log.isDebugEnabled()) {
log.debug("Competed server startup");
}
/**Need to start the scheduler after all BPEL processes get deployed to resume currently active process instances.
Hence start scheduler after completing server startup. Users should configure Node ID in the bps.xml*/
log.info("Starting BPS Scheduler");
((BPELServerImpl) BPELServiceComponent.getBPELServer()).getScheduler().start();
}
}
|
components/bpel/org.wso2.carbon.bpel/src/main/java/org/wso2/carbon/bpel/core/ode/integration/BPELSchedulerInitializer.java
|
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.bpel.core.ode.integration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.bpel.core.internal.BPELServiceComponent;
import org.wso2.carbon.core.ServerStartupObserver;
/**
* This class starts up the ode scheduler when the startup finalizer calls the invoke method
*/
public class BPELSchedulerInitializer implements ServerStartupObserver {
private static Log log = LogFactory.getLog(BPELSchedulerInitializer.class);
@Override
public void completingServerStartup() {
if (log.isInfoEnabled()) {
log.info("Starting BPS Scheduler");
if (BPELServiceComponent.getBPELServer().getBpelServerConfiguration().getUseDistributedLock()) {
if (BPELServiceComponent.getHazelcastInstance() != null) {
log.info("HazelCast instance available and configured");
} else {
log.error("HazelCast instance not available, but distributed lock enabled");
}
}
}
((BPELServerImpl) BPELServiceComponent.getBPELServer()).getScheduler().start();
}
@Override
public void completedServerStartup() {
if (log.isDebugEnabled()) {
log.debug("Competed server startup");
}
}
}
|
[BPS-1173] Fix:Resuming BPS process instances after server reboot
|
components/bpel/org.wso2.carbon.bpel/src/main/java/org/wso2/carbon/bpel/core/ode/integration/BPELSchedulerInitializer.java
|
[BPS-1173] Fix:Resuming BPS process instances after server reboot
|
|
Java
|
apache-2.0
|
62e07c2f2622e6c47c78e52742e14a7217cfe7b4
| 0
|
MovingBlocks/DestinationSol,MovingBlocks/DestinationSol
|
/*
* Copyright 2019 MovingBlocks
*
* 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.destinationsol.menu.background;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.World;
import org.destinationsol.assets.Assets;
import org.destinationsol.common.SolColorUtil;
import org.destinationsol.common.SolRandom;
import org.destinationsol.game.CollisionMeshLoader;
import org.destinationsol.game.drawables.DrawableLevel;
import org.destinationsol.ui.DisplayDimensions;
import org.destinationsol.ui.UiDrawer;
import java.util.ArrayList;
import java.util.List;
public class MenuBackgroundAsteroidManager {
private final DisplayDimensions displayDimensions;
private final CollisionMeshLoader asteroidMeshLoader;
private List<TextureAtlas.AtlasRegion> availableAsteroidTextures;
private List<MenuBackgroundObject> backgroundAsteroids;
private List<MenuBackgroundObject> retainedBackgroundAsteroids;
private World world;
private final int NUMBER_OF_ASTEROIDS = 10;
public MenuBackgroundAsteroidManager(DisplayDimensions displayDimensions, World world) {
this.displayDimensions = displayDimensions;
this.world = world;
asteroidMeshLoader = new CollisionMeshLoader("engine:asteroids");
availableAsteroidTextures = Assets.listTexturesMatching("engine:asteroid_.*");
backgroundAsteroids = new ArrayList<>();
retainedBackgroundAsteroids = new ArrayList<>();
for (int i = 0; i < NUMBER_OF_ASTEROIDS; i++) {
backgroundAsteroids.add(buildAsteroid());
}
}
public void update() {
retainedBackgroundAsteroids.clear();
float radius = (float) Math.sqrt(0.25 + Math.pow(displayDimensions.getRatio() / 2, 2));
for (MenuBackgroundObject backgroundObject : backgroundAsteroids) {
backgroundObject.update();
float distance = (float) Math.sqrt(Math.pow(backgroundObject.getPosition().x - displayDimensions.getRatio() / 2, 2) + Math.pow(backgroundObject.getPosition().y - 0.5f, 2));
if (distance < radius) {
retainedBackgroundAsteroids.add(backgroundObject);
} else {
retainedBackgroundAsteroids.add(buildAsteroid());
}
}
backgroundAsteroids.clear();
backgroundAsteroids.addAll(retainedBackgroundAsteroids);
}
public void draw(UiDrawer uiDrawer) {
for (MenuBackgroundObject backgroundObject : backgroundAsteroids) {
backgroundObject.draw(uiDrawer);
}
}
public MenuBackgroundObject buildAsteroid() {
TextureAtlas.AtlasRegion texture = SolRandom.randomElement(availableAsteroidTextures);
boolean small = SolRandom.test(.8f);
float size = (small ? .2f : .4f) * SolRandom.randomFloat(.5f, 1);
Color tint = new Color();
SolColorUtil.fromHSB(SolRandom.randomFloat(0, 1), .25f, 1, .7f, tint);
float radiusX = (float) (texture.originalHeight) / displayDimensions.getWidth() * size / 2;
float radiusY = (float) (texture.originalHeight) / displayDimensions.getHeight() * size / 2;
float r = displayDimensions.getRatio();
Vector2 velocity, position;
if (SolRandom.test(0.5f)) {
// Spawn from the left or right of screen
boolean fromLeft = SolRandom.test(0.5f);
velocity = new Vector2((fromLeft ? 1 : -1) * (float) Math.pow(SolRandom.randomFloat(0.025f, 0.1f), 2), (float) Math.pow(SolRandom.randomFloat(0.095f), 2));
position = new Vector2(r / 2 + (fromLeft ? -1 : 1) * (r / 2 + radiusX) - radiusX, 0.5f + SolRandom.randomFloat(0.5f + radiusY) - radiusY);
} else {
// Spawn from the top or bottom of screen
boolean fromTop = SolRandom.test(0.5f);
velocity = new Vector2((float) Math.pow(SolRandom.randomFloat(0.095f), 3), (fromTop ? 1 : -1) * (float) Math.pow(SolRandom.randomFloat(-0.025f, -0.1f), 2));
position = new Vector2(r / 2 + SolRandom.randomFloat(r / 2 + radiusX) - radiusX, 0.5f + (fromTop ? -1 : 1) * (0.5f + radiusY) - radiusY);
}
//Give random rotation to asteroid
float angle = SolRandom.randomFloat((float) Math.PI);
float angularVelocity = SolRandom.randomFloat(1.5f);
velocity.scl(50);
//Build the final asteroid body
Body body = asteroidMeshLoader.getBodyAndSprite(world, texture, size * 0.95f, BodyDef.BodyType.DynamicBody, position, angle, new ArrayList<>(), 10f, DrawableLevel.BODIES);
body.setLinearVelocity(velocity);
body.setAngularVelocity(angularVelocity);
MenuBackgroundObject asteroid = new MenuBackgroundObject(texture, size, tint, position, velocity, asteroidMeshLoader.getOrigin(texture.name, size).cpy(), angle, body);
body.setUserData(asteroid);
return asteroid;
}
}
|
engine/src/main/java/org/destinationsol/menu/background/MenuBackgroundAsteroidManager.java
|
/*
* Copyright 2019 MovingBlocks
*
* 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.destinationsol.menu.background;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.World;
import org.destinationsol.assets.Assets;
import org.destinationsol.common.SolColorUtil;
import org.destinationsol.common.SolRandom;
import org.destinationsol.game.CollisionMeshLoader;
import org.destinationsol.game.drawables.DrawableLevel;
import org.destinationsol.ui.DisplayDimensions;
import org.destinationsol.ui.UiDrawer;
import java.util.ArrayList;
import java.util.List;
public class MenuBackgroundAsteroidManager {
private final DisplayDimensions displayDimensions;
private final CollisionMeshLoader asteroidMeshLoader;
private List<TextureAtlas.AtlasRegion> availableAsteroidTextures;
private List<MenuBackgroundObject> backgroundAsteroids;
private List<MenuBackgroundObject> retainedBackgroundAsteroids;
private World world;
public MenuBackgroundAsteroidManager(DisplayDimensions displayDimensions, World world) {
this.displayDimensions = displayDimensions;
this.world = world;
asteroidMeshLoader = new CollisionMeshLoader("engine:asteroids");
availableAsteroidTextures = Assets.listTexturesMatching("engine:asteroid_.*");
backgroundAsteroids = new ArrayList<>();
retainedBackgroundAsteroids = new ArrayList<>();
for (int i = 0; i < 10; i++) {
backgroundAsteroids.add(buildAsteroid());
}
}
public void update() {
retainedBackgroundAsteroids.clear();
float radius = (float) Math.sqrt(0.25 + Math.pow(displayDimensions.getRatio() / 2, 2));
for (MenuBackgroundObject backgroundObject : backgroundAsteroids) {
backgroundObject.update();
float distance = (float) Math.sqrt(Math.pow(backgroundObject.getPosition().x - displayDimensions.getRatio() / 2, 2) + Math.pow(backgroundObject.getPosition().y - 0.5f, 2));
if (distance < radius) {
retainedBackgroundAsteroids.add(backgroundObject);
} else {
retainedBackgroundAsteroids.add(buildAsteroid());
}
}
backgroundAsteroids.clear();
backgroundAsteroids.addAll(retainedBackgroundAsteroids);
}
public void draw(UiDrawer uiDrawer) {
for (MenuBackgroundObject backgroundObject : backgroundAsteroids) {
backgroundObject.draw(uiDrawer);
}
}
public MenuBackgroundObject buildAsteroid() {
TextureAtlas.AtlasRegion texture = SolRandom.randomElement(availableAsteroidTextures);
boolean small = SolRandom.test(.8f);
float size = (small ? .2f : .4f) * SolRandom.randomFloat(.5f, 1);
Color tint = new Color();
SolColorUtil.fromHSB(SolRandom.randomFloat(0, 1), .25f, 1, .7f, tint);
float radiusX = (float) (texture.originalHeight) / displayDimensions.getWidth() * size / 2;
float radiusY = (float) (texture.originalHeight) / displayDimensions.getHeight() * size / 2;
float r = displayDimensions.getRatio();
Vector2 velocity, position;
if (SolRandom.test(0.5f)) {
// Spawn from the left or right of screen
boolean fromLeft = SolRandom.test(0.5f);
velocity = new Vector2((fromLeft ? 1 : -1) * (float) Math.pow(SolRandom.randomFloat(0.025f, 0.1f), 2), (float) Math.pow(SolRandom.randomFloat(0.095f), 2));
position = new Vector2(r / 2 + (fromLeft ? -1 : 1) * (r / 2 + radiusX) - radiusX, 0.5f + SolRandom.randomFloat(0.5f + radiusY) - radiusY);
} else {
// Spawn from the top or bottom of screen
boolean fromTop = SolRandom.test(0.5f);
velocity = new Vector2((float) Math.pow(SolRandom.randomFloat(0.095f), 3), (fromTop ? 1 : -1) * (float) Math.pow(SolRandom.randomFloat(-0.025f, -0.1f), 2));
position = new Vector2(r / 2 + SolRandom.randomFloat(r / 2 + radiusX) - radiusX, (fromTop ? -1 : 1) * (0.5f + (0.5f + radiusY) - radiusY));
}
//Give random rotation to asteroid
float angle = SolRandom.randomFloat((float) Math.PI);
float angularVelocity = SolRandom.randomFloat(1.5f);
velocity.scl(50);
//Build the final asteroid body
Body body = asteroidMeshLoader.getBodyAndSprite(world, texture, size * 0.95f, BodyDef.BodyType.DynamicBody, position, angle, new ArrayList<>(), 10f, DrawableLevel.BODIES);
body.setLinearVelocity(velocity);
body.setAngularVelocity(angularVelocity);
MenuBackgroundObject asteroid = new MenuBackgroundObject(texture, size, tint, position, velocity, asteroidMeshLoader.getOrigin(texture.name, size).cpy(), angle, body);
body.setUserData(asteroid);
return asteroid;
}
}
|
Added some final changes
|
engine/src/main/java/org/destinationsol/menu/background/MenuBackgroundAsteroidManager.java
|
Added some final changes
|
|
Java
|
apache-2.0
|
b95a66e055d596976c08be8320eba507a9a24d78
| 0
|
arquillian/arquillian-core
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2009 Red Hat Inc. and/or its affiliates and other contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.arquillian.testng.container;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jboss.arquillian.container.test.spi.TestRunner;
import org.jboss.arquillian.test.spi.TestResult;
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlInclude;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
/**
* TestNGTestRunner
*
* @author <a href="mailto:aslak@conduct.no">Aslak Knutsen</a>
* @version $Revision: $
*/
public class TestNGTestRunner implements TestRunner {
public TestResult execute(Class<?> testClass, String methodName) {
TestListener resultListener = new TestListener();
TestNG runner = new TestNG(false);
runner.setVerbose(0);
runner.addListener(resultListener);
runner.addListener(new RemoveDependsOnTransformer());
runner.setXmlSuites(
Collections.singletonList(createSuite(testClass, methodName)));
//we catch problems in executing run method, e.g. ClassDefNotFoundError and wrap it in TestResult
try {
runner.run();
} catch (Throwable ex) {
return TestResult.failed(ex);
}
return resultListener.getTestResult();
}
private XmlSuite createSuite(Class<?> className, String methodName) {
XmlSuite suite = new XmlSuite();
suite.setName("Arquillian");
XmlTest test = new XmlTest(suite);
test.setName("Arquillian - " + className);
List<XmlClass> testClasses = new ArrayList<XmlClass>();
XmlClass testClass = new XmlClass(className);
testClass.getIncludedMethods().add(new XmlInclude(methodName));
testClasses.add(testClass);
test.setXmlClasses(testClasses);
return suite;
}
}
|
testng/container/src/main/java/org/jboss/arquillian/testng/container/TestNGTestRunner.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2009 Red Hat Inc. and/or its affiliates and other contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.arquillian.testng.container;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jboss.arquillian.container.test.spi.TestRunner;
import org.jboss.arquillian.test.spi.TestResult;
import org.testng.TestNG;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlInclude;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
/**
* TestNGTestRunner
*
* @author <a href="mailto:aslak@conduct.no">Aslak Knutsen</a>
* @version $Revision: $
*/
public class TestNGTestRunner implements TestRunner {
public TestResult execute(Class<?> testClass, String methodName) {
TestListener resultListener = new TestListener();
TestNG runner = new TestNG(false);
runner.setVerbose(0);
runner.addListener(resultListener);
runner.addListener(new RemoveDependsOnTransformer());
runner.setXmlSuites(
Collections.singletonList(createSuite(testClass, methodName)));
runner.run();
return resultListener.getTestResult();
}
private XmlSuite createSuite(Class<?> className, String methodName) {
XmlSuite suite = new XmlSuite();
suite.setName("Arquillian");
XmlTest test = new XmlTest(suite);
test.setName("Arquillian - " + className);
List<XmlClass> testClasses = new ArrayList<XmlClass>();
XmlClass testClass = new XmlClass(className);
testClass.getIncludedMethods().add(new XmlInclude(methodName));
testClasses.add(testClass);
test.setXmlClasses(testClasses);
return suite;
}
}
|
fix: propagates exception from running runner.run() method (#184)
If someone omits required runtime class in a deployment archive there will be ClassDefNotFoundError when executing run() method in TestNGRunner. Arquillian servlet will return HTTP code 500 which is ignored in servlet protocol runner and consequently returned as a test which passed. But in reality the test did not even run and should be marked as failed.
|
testng/container/src/main/java/org/jboss/arquillian/testng/container/TestNGTestRunner.java
|
fix: propagates exception from running runner.run() method (#184)
|
|
Java
|
bsd-3-clause
|
b0a9cd861ecee126b2903a94f45e0bce30a3243b
| 0
|
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
|
/*
* Copyright (c) 2017, University of Oslo
*
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project 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 org.hisp.dhis.android.core.program;
import android.content.ContentValues;
import android.database.MatrixCursor;
import android.support.test.runner.AndroidJUnit4;
import org.hisp.dhis.android.core.common.BaseIdentifiableObject;
import org.hisp.dhis.android.core.program.ProgramStageSectionModel.Columns;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Date;
import static com.google.common.truth.Truth.assertThat;
@RunWith(AndroidJUnit4.class)
public class ProgramStageSectionModelsShould {
private static final long ID = 2L;
private static final String UID = "test_uid";
private static final String CODE = "test_code";
private static final String NAME = "test_name";
private static final String DISPLAY_NAME = "test_display_name";
private static final Integer SORT_ORDER = 7;
private static final String PROGRAM_STAGE = "test_program_stage";
private final Date date;
private final String dateString;
private final ProgramStageSectionRenderingType DESKTOP_RENDER_TYPE = ProgramStageSectionRenderingType.MATRIX;
private final ProgramStageSectionRenderingType MOBILE_RENDER_TYPE = ProgramStageSectionRenderingType.LISTING;
public ProgramStageSectionModelsShould() {
this.date = new Date();
this.dateString = BaseIdentifiableObject.DATE_FORMAT.format(date);
}
@Test
public void create_model_when_created_from_database_cursor() {
MatrixCursor cursor = new MatrixCursor(new String[]{
Columns.ID, Columns.UID, Columns.CODE, Columns.NAME,
Columns.DISPLAY_NAME, Columns.CREATED, Columns.LAST_UPDATED,
Columns.SORT_ORDER, Columns.PROGRAM_STAGE, Columns.DESKTOP_RENDER_TYPE, Columns.MOBILE_RENDER_TYPE
});
cursor.addRow(new Object[]{
ID, UID, CODE, NAME, DISPLAY_NAME, dateString, dateString,
SORT_ORDER, PROGRAM_STAGE, DESKTOP_RENDER_TYPE, MOBILE_RENDER_TYPE
});
cursor.moveToFirst();
ProgramStageSectionModel model = ProgramStageSectionModel.create(cursor);
cursor.close();
assertThat(model.id()).isEqualTo(ID);
assertThat(model.uid()).isEqualTo(UID);
assertThat(model.code()).isEqualTo(CODE);
assertThat(model.name()).isEqualTo(NAME);
assertThat(model.displayName()).isEqualTo(DISPLAY_NAME);
assertThat(model.created()).isEqualTo(date);
assertThat(model.lastUpdated()).isEqualTo(date);
assertThat(model.sortOrder()).isEqualTo(SORT_ORDER);
assertThat(model.programStage()).isEqualTo(PROGRAM_STAGE);
assertThat(model.desktopRenderType()).isEqualTo(DESKTOP_RENDER_TYPE);
assertThat(model.mobileRenderType()).isEqualTo(MOBILE_RENDER_TYPE);
}
@Test
public void create_content_values_when_created_from_builder() {
ProgramStageSectionModel model = ProgramStageSectionModel.builder()
.id(ID)
.uid(UID)
.code(CODE)
.name(NAME)
.displayName(DISPLAY_NAME)
.created(date)
.lastUpdated(date)
.sortOrder(SORT_ORDER)
.programStage(PROGRAM_STAGE)
.desktopRenderType(DESKTOP_RENDER_TYPE)
.mobileRenderType(MOBILE_RENDER_TYPE)
.build();
ContentValues contentValues = model.toContentValues();
assertThat(contentValues.getAsLong(Columns.ID)).isEqualTo(ID);
assertThat(contentValues.getAsString(Columns.UID)).isEqualTo(UID);
assertThat(contentValues.getAsString(Columns.CODE)).isEqualTo(CODE);
assertThat(contentValues.getAsString(Columns.NAME)).isEqualTo(NAME);
assertThat(contentValues.getAsString(Columns.DISPLAY_NAME)).isEqualTo(DISPLAY_NAME);
assertThat(contentValues.getAsString(Columns.CREATED)).isEqualTo(dateString);
assertThat(contentValues.getAsString(Columns.LAST_UPDATED)).isEqualTo(dateString);
assertThat(contentValues.getAsInteger(Columns.SORT_ORDER)).isEqualTo(SORT_ORDER);
assertThat(contentValues.getAsString(Columns.PROGRAM_STAGE)).isEqualTo(PROGRAM_STAGE);
assertThat(contentValues.getAsString(Columns.DESKTOP_RENDER_TYPE)).isEqualTo(DESKTOP_RENDER_TYPE.toString());
assertThat(contentValues.getAsString(Columns.MOBILE_RENDER_TYPE)).isEqualTo(MOBILE_RENDER_TYPE.toString());
}
}
|
core/src/androidTest/java/org/hisp/dhis/android/core/program/ProgramStageSectionModelsShould.java
|
/*
* Copyright (c) 2017, University of Oslo
*
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project 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 org.hisp.dhis.android.core.program;
import android.content.ContentValues;
import android.database.MatrixCursor;
import android.support.test.runner.AndroidJUnit4;
import org.hisp.dhis.android.core.common.BaseIdentifiableObject;
import org.hisp.dhis.android.core.program.ProgramStageSectionModel.Columns;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Date;
import static com.google.common.truth.Truth.assertThat;
@RunWith(AndroidJUnit4.class)
public class ProgramStageSectionModelsShould {
private static final long ID = 2L;
private static final String UID = "test_uid";
private static final String CODE = "test_code";
private static final String NAME = "test_name";
private static final String DISPLAY_NAME = "test_display_name";
private static final Integer SORT_ORDER = 7;
private static final String PROGRAM_STAGE = "test_program_stage";
private final Date date;
private final String dateString;
public ProgramStageSectionModelsShould() {
this.date = new Date();
this.dateString = BaseIdentifiableObject.DATE_FORMAT.format(date);
}
@Test
public void create_model_when_created_from_database_cursor() {
MatrixCursor cursor = new MatrixCursor(new String[]{
Columns.ID, Columns.UID, Columns.CODE, Columns.NAME,
Columns.DISPLAY_NAME, Columns.CREATED, Columns.LAST_UPDATED,
Columns.SORT_ORDER, Columns.PROGRAM_STAGE
});
cursor.addRow(new Object[]{
ID, UID, CODE, NAME, DISPLAY_NAME, dateString, dateString,
SORT_ORDER, PROGRAM_STAGE
});
cursor.moveToFirst();
ProgramStageSectionModel model = ProgramStageSectionModel.create(cursor);
cursor.close();
assertThat(model.id()).isEqualTo(ID);
assertThat(model.uid()).isEqualTo(UID);
assertThat(model.code()).isEqualTo(CODE);
assertThat(model.name()).isEqualTo(NAME);
assertThat(model.displayName()).isEqualTo(DISPLAY_NAME);
assertThat(model.created()).isEqualTo(date);
assertThat(model.lastUpdated()).isEqualTo(date);
assertThat(model.sortOrder()).isEqualTo(SORT_ORDER);
assertThat(model.programStage()).isEqualTo(PROGRAM_STAGE);
}
@Test
public void create_content_values_when_created_from_builder() {
ProgramStageSectionModel model = ProgramStageSectionModel.builder()
.id(ID)
.uid(UID)
.code(CODE)
.name(NAME)
.displayName(DISPLAY_NAME)
.created(date)
.lastUpdated(date)
.sortOrder(SORT_ORDER)
.programStage(PROGRAM_STAGE)
.build();
ContentValues contentValues = model.toContentValues();
assertThat(contentValues.getAsLong(Columns.ID)).isEqualTo(ID);
assertThat(contentValues.getAsString(Columns.UID)).isEqualTo(UID);
assertThat(contentValues.getAsString(Columns.CODE)).isEqualTo(CODE);
assertThat(contentValues.getAsString(Columns.NAME)).isEqualTo(NAME);
assertThat(contentValues.getAsString(Columns.DISPLAY_NAME)).isEqualTo(DISPLAY_NAME);
assertThat(contentValues.getAsString(Columns.CREATED)).isEqualTo(dateString);
assertThat(contentValues.getAsString(Columns.LAST_UPDATED)).isEqualTo(dateString);
assertThat(contentValues.getAsInteger(Columns.SORT_ORDER)).isEqualTo(SORT_ORDER);
assertThat(contentValues.getAsString(Columns.PROGRAM_STAGE)).isEqualTo(PROGRAM_STAGE);
}
}
|
render-type: adapt ProgramStageSectionModelsShould
|
core/src/androidTest/java/org/hisp/dhis/android/core/program/ProgramStageSectionModelsShould.java
|
render-type: adapt ProgramStageSectionModelsShould
|
|
Java
|
bsd-3-clause
|
e061d43b35755bff1d2c66033a3a826931ee4cfe
| 0
|
ngraczewski/motech,ngraczewski/motech,pgesek/motech,wstrzelczyk/motech,justin-hayes/motech,koshalt/motech,smalecki/motech,justin-hayes/motech,wstrzelczyk/motech,smalecki/motech,smalecki/motech,sebbrudzinski/motech,tstalka/motech,tstalka/motech,wstrzelczyk/motech,pgesek/motech,LukSkarDev/motech,LukSkarDev/motech,koshalt/motech,pgesek/motech,sebbrudzinski/motech,sebbrudzinski/motech,sebbrudzinski/motech,ngraczewski/motech,wstrzelczyk/motech,pgesek/motech,tstalka/motech,koshalt/motech,smalecki/motech,koshalt/motech,tstalka/motech,LukSkarDev/motech,ngraczewski/motech,justin-hayes/motech,justin-hayes/motech,LukSkarDev/motech
|
package org.motechproject.mds.builder.impl;
import javassist.ByteArrayClassPath;
import javassist.CannotCompileException;
import javassist.CtClass;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.motechproject.commons.sql.service.SqlDBManager;
import org.motechproject.mds.builder.EntityBuilder;
import org.motechproject.mds.builder.EntityInfrastructureBuilder;
import org.motechproject.mds.builder.EntityMetadataBuilder;
import org.motechproject.mds.builder.EnumBuilder;
import org.motechproject.mds.builder.MDSConstructor;
import org.motechproject.mds.config.MdsConfig;
import org.motechproject.mds.domain.ClassData;
import org.motechproject.mds.domain.ComboboxHolder;
import org.motechproject.mds.domain.Entity;
import org.motechproject.mds.domain.EntityType;
import org.motechproject.mds.dto.EntityDto;
import org.motechproject.mds.dto.FieldDto;
import org.motechproject.mds.dto.SchemaHolder;
import org.motechproject.mds.dto.TypeDto;
import org.motechproject.mds.enhancer.MdsJDOEnhancer;
import org.motechproject.mds.ex.entity.EntityCreationException;
import org.motechproject.mds.helper.ClassTableName;
import org.motechproject.mds.helper.EntitySorter;
import org.motechproject.mds.helper.MdsBundleHelper;
import org.motechproject.mds.javassist.JavassistLoader;
import org.motechproject.mds.javassist.MotechClassPool;
import org.motechproject.mds.repository.MetadataHolder;
import org.motechproject.mds.util.ClassName;
import org.motechproject.mds.util.Constants;
import org.motechproject.mds.util.JavassistUtil;
import org.motechproject.mds.util.MDSClassLoader;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.datastore.JDOConnection;
import javax.jdo.metadata.JDOMetadata;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Default implementation of {@link org.motechproject.mds.builder.MDSConstructor} interface.
*/
@Service
public class MDSConstructorImpl implements MDSConstructor {
private static final Logger LOGGER = LoggerFactory.getLogger(MDSConstructorImpl.class);
private MdsConfig mdsConfig;
private EntityBuilder entityBuilder;
private EntityInfrastructureBuilder infrastructureBuilder;
private EntityMetadataBuilder metadataBuilder;
private MetadataHolder metadataHolder;
private BundleContext bundleContext;
private EnumBuilder enumBuilder;
private PersistenceManagerFactory persistenceManagerFactory;
private SqlDBManager sqlDBManager;
@Override
public synchronized boolean constructEntities(SchemaHolder schemaHolder) {
// To be able to register updated class, we need to reload class loader
// and therefore add all the classes again
MotechClassPool.clearEnhancedData();
MDSClassLoader.reloadClassLoader();
// we need an jdo enhancer and a temporary classLoader
// to define classes in before enhancement
MDSClassLoader tmpClassLoader = MDSClassLoader.getStandaloneInstance();
MdsJDOEnhancer enhancer = createEnhancer(tmpClassLoader);
JavassistLoader loader = new JavassistLoader(tmpClassLoader);
// process only entities that are not drafts
List<EntityDto> entities = schemaHolder.getAllEntities();
filterEntities(entities);
sortEntities(entities, schemaHolder);
// create enum for appropriate combobox fields
for (EntityDto entity : entities) {
buildEnum(loader, enhancer, entity, schemaHolder);
}
// load entities interfaces
for (EntityDto entity : entities) {
buildInterfaces(loader, enhancer, entity);
}
// generate jdo metadata from scratch for our entities
JDOMetadata jdoMetadata = metadataHolder.reloadMetadata();
// First we build empty history and trash classes
// (We don't have to generate it for main class,
// since we just fetch fields from existing definition
for (EntityDto entity : entities) {
if (entity.isRecordHistory()) {
entityBuilder.prepareHistoryClass(entity);
}
entityBuilder.prepareTrashClass(entity);
}
// Build classes
Map<String, ClassData> classDataMap = buildClasses(entities, schemaHolder);
List<Class> classes = new ArrayList<>();
// We add the java classes to both
// the temporary ClassLoader and enhancer
for (EntityDto entity : entities) {
String className = entity.getClassName();
Class<?> definition = addClassData(loader, enhancer, classDataMap.get(className));
if (entity.isRecordHistory()) {
addClassData(loader, enhancer, classDataMap.get(ClassName.getHistoryClassName(className)));
}
addClassData(loader, enhancer, classDataMap.get(ClassName.getTrashClassName(className)));
classes.add(definition);
LOGGER.debug("Generated classes for {}", entity.getClassName());
}
for (Class<?> definition : classes) {
loader.loadFieldsAndMethodsOfClass(definition);
}
// Prepare metadata
buildMetadata(entities, jdoMetadata, classDataMap, classes, schemaHolder);
// after the classes are defined, we register their metadata
enhancer.registerMetadata(jdoMetadata);
// then, we commence with enhancement
enhancer.enhance();
// we register the enhanced class bytes
// and build the infrastructure classes
registerEnhancedClassBytes(entities, enhancer, schemaHolder);
metadataBuilder.fixEnhancerIssuesInMetadata(jdoMetadata, schemaHolder);
return CollectionUtils.isNotEmpty(entities);
}
private void registerEnhancedClassBytes(List<EntityDto> entities, MdsJDOEnhancer enhancer, SchemaHolder schemaHolder) {
for (EntityDto entity : entities) {
// register
String className = entity.getClassName();
LOGGER.debug("Registering {}", className);
registerClass(enhancer, entity);
if (entity.isRecordHistory()) {
registerHistoryClass(enhancer, className);
}
registerTrashClass(enhancer, className);
LOGGER.debug("Building infrastructure for {}", className);
buildInfrastructure(entity, schemaHolder);
}
}
private void sortEntities(List<EntityDto> entities, SchemaHolder schemaHolder) {
List<EntityDto> byInheritance = EntitySorter.sortByInheritance(entities);
List<EntityDto> byHasARelation = EntitySorter.sortByHasARelation(byInheritance, schemaHolder);
// for safe we clear entities list
entities.clear();
// for now the entities list will be sorted by inheritance and by 'has-a' relation
entities.addAll(byHasARelation);
}
private Map<String, ClassData> buildClasses(List<EntityDto> entities, SchemaHolder schemaHolder) {
Map<String, ClassData> classDataMap = new LinkedHashMap<>();
//We build classes for all entities
for (EntityDto entity : entities) {
List<FieldDto> fields = schemaHolder.getFields(entity);
ClassData classData = buildClass(entity, fields);
ClassData historyClassData = null;
if (entity.isRecordHistory()) {
historyClassData = entityBuilder.buildHistory(entity, fields);
}
ClassData trashClassData = entityBuilder.buildTrash(entity, fields);
String className = entity.getClassName();
classDataMap.put(className, classData);
if (historyClassData != null) {
classDataMap.put(ClassName.getHistoryClassName(className), historyClassData);
}
classDataMap.put(ClassName.getTrashClassName(className), trashClassData);
}
return classDataMap;
}
private void buildMetadata(List<EntityDto> entities, JDOMetadata jdoMetadata, Map<String, ClassData> classDataMap,
List<Class> classes, SchemaHolder schemaHolder) {
for (EntityDto entity : entities) {
String className = entity.getClassName();
Class definition = null;
for (Class clazz : classes) {
if (clazz.getName().equals(className)) {
definition = clazz;
break;
}
}
metadataBuilder.addEntityMetadata(jdoMetadata, entity, definition, schemaHolder);
if (entity.isRecordHistory()) {
metadataBuilder.addHelperClassMetadata(jdoMetadata, classDataMap.get(ClassName.getHistoryClassName(className)),
entity, EntityType.HISTORY, definition, schemaHolder);
}
metadataBuilder.addHelperClassMetadata(jdoMetadata, classDataMap.get(ClassName.getTrashClassName(className)),
entity, EntityType.TRASH, definition, schemaHolder);
}
}
private void buildEnum(JavassistLoader loader, MdsJDOEnhancer enhancer, EntityDto entity,
SchemaHolder schemaHolder) {
for (FieldDto field : schemaHolder.getFields(entity.getClassName())) {
TypeDto type = field.getType();
if (!type.isCombobox()) {
continue;
}
ComboboxHolder holder = new ComboboxHolder(entity, field);
if (holder.isEnum() || holder.isEnumCollection()) {
if (field.isReadOnly()) {
String enumName = holder.getEnumName();
Class<?> definition = loadClass(entity, enumName);
if (null != definition) {
MotechClassPool.registerEnum(enumName);
CtClass ctClass = MotechClassPool.getDefault().getOrNull(enumName);
if (null != ctClass) {
try {
ctClass.defrost();
byte[] bytecode = ctClass.toBytecode();
ClassData data = new ClassData(enumName, bytecode);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(data.getClassName(), data.getBytecode());
addClassData(loader, enhancer, data);
} catch (IOException | CannotCompileException e) {
LOGGER.error("Could not load enum: {}", enumName);
}
}
}
} else {
buildEnum(loader, enhancer, holder);
}
}
}
}
private void buildEnum(JavassistLoader loader, MdsJDOEnhancer enhancer, ComboboxHolder holder) {
ClassData data = enumBuilder.build(holder);
ByteArrayClassPath classPath = new ByteArrayClassPath(data.getClassName(), data.getBytecode());
MotechClassPool.getDefault().appendClassPath(classPath);
MotechClassPool.registerEnhancedClassData(data);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(data.getClassName(), data.getBytecode());
addClassData(loader, enhancer, data);
}
@Override
@Transactional("dataTransactionManager")
public void updateFields(Entity entity, Map<String, String> fieldNameChanges) {
for (String key : fieldNameChanges.keySet()) {
String tableName = ClassTableName.getTableName(entity.getClassName(), entity.getModule(), entity.getNamespace(), entity.getTableName(), null);
updateFieldName(key, fieldNameChanges.get(key), tableName);
if (entity.isRecordHistory()) {
updateFieldName(key, fieldNameChanges.get(key), ClassTableName.getTableName(entity, EntityType.HISTORY));
}
updateFieldName(key, fieldNameChanges.get(key), ClassTableName.getTableName(entity, EntityType.TRASH));
}
}
@Override
@Transactional("dataTransactionManager")
public void removeUniqueIndexes(Entity entity, Collection<String> fields) {
String tableName = ClassTableName.getTableName(entity.getClassName(), entity.getModule(),
entity.getNamespace(), entity.getTableName(), null);
PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
boolean isMySql = sqlDBManager.getChosenSQLDriver().equals(Constants.Config.MYSQL_DRIVER_CLASSNAME);
for (String field : fields) {
String constraintName = KeyNames.uniqueKeyName(entity.getName(), field);
String sql;
if (isMySql) {
sql = "DROP INDEX " + constraintName + " ON " + tableName;
} else {
sql = "ALTER TABLE \"" + tableName + "\" DROP CONSTRAINT IF EXISTS \"" + constraintName + "\"";
}
Query query = pm.newQuery(Constants.Util.SQL_QUERY, sql);
query.execute();
}
}
private void registerHistoryClass(MdsJDOEnhancer enhancer, String className) {
String historyClassName = ClassName.getHistoryClassName(className);
byte[] enhancedBytes = enhancer.getEnhancedBytes(historyClassName);
ClassData classData = new ClassData(historyClassName, enhancedBytes);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(classData.getClassName(), classData.getBytecode());
MotechClassPool.registerHistoryClassData(classData);
}
private void registerTrashClass(MdsJDOEnhancer enhancer, String className) {
String trashClassName = ClassName.getTrashClassName(className);
byte[] enhancedBytes = enhancer.getEnhancedBytes(trashClassName);
ClassData classData = new ClassData(trashClassName, enhancedBytes);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(classData.getClassName(), classData.getBytecode());
MotechClassPool.registerTrashClassData(classData);
}
private void registerClass(MdsJDOEnhancer enhancer, EntityDto entity) {
byte[] enhancedBytes = enhancer.getEnhancedBytes(entity.getClassName());
ClassData classData = new ClassData(entity, enhancedBytes);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(classData.getClassName(), classData.getBytecode());
MotechClassPool.registerEnhancedClassData(classData);
}
private Class<?> addClassData(JavassistLoader loader, MdsJDOEnhancer enhancer, ClassData data) {
Class<?> definition = loader.loadClass(data);
enhancer.addClass(data);
return definition;
}
private ClassData buildClass(EntityDto entity, List<FieldDto> fields) {
ClassData classData;
if (entity.isDDE()) {
// for DDE we load the class coming from the bundle
Bundle declaringBundle = MdsBundleHelper.searchForBundle(bundleContext, entity);
if (declaringBundle == null) {
throw new EntityCreationException("Declaring bundle unavailable for entity " + entity.getClassName());
}
classData = entityBuilder.buildDDE(entity, fields, declaringBundle);
} else {
classData = entityBuilder.build(entity, fields);
}
return classData;
}
private void buildInterfaces(JavassistLoader loader, MdsJDOEnhancer enhancer, EntityDto entity) {
List<ClassData> interfaces = new LinkedList<>();
if (entity.isDDE()) {
Bundle declaringBundle = MdsBundleHelper.searchForBundle(bundleContext, entity);
try {
Class<?> definition = declaringBundle.loadClass(entity.getClassName());
for (Class interfaceClass : definition.getInterfaces()) {
String classpath = JavassistUtil.toClassPath(interfaceClass.getName());
URL classResource = declaringBundle.getResource(classpath);
if (classResource != null) {
try (InputStream in = classResource.openStream()) {
interfaces.add(new ClassData(interfaceClass.getName(), IOUtils.toByteArray(in), true));
}
}
}
} catch (ClassNotFoundException e) {
LOGGER.error("Class {} not found in {} bundle", entity.getClassName(), declaringBundle.getSymbolicName());
} catch (IOException ioExc) {
LOGGER.error("Could not load interface for {} class", entity.getClassName());
}
}
for (ClassData data : interfaces) {
try {
MDSClassLoader.getInstance().loadClass(data.getClassName());
} catch (ClassNotFoundException e) {
// interfaces should be defined in the MDS class loader only if it does not exist
MDSClassLoader.getInstance().safeDefineClass(data.getClassName(), data.getBytecode());
ByteArrayClassPath classPath = new ByteArrayClassPath(data.getClassName(), data.getBytecode());
MotechClassPool.getDefault().appendClassPath(classPath);
MotechClassPool.registerEnhancedClassData(data);
addClassData(loader, enhancer, data);
}
}
}
private void buildInfrastructure(EntityDto entity, SchemaHolder schemaHolder) {
String className = entity.getClassName();
List<ClassData> infrastructure = infrastructureBuilder.buildInfrastructure(entity, schemaHolder);
for (ClassData classData : infrastructure) {
// if we have a DDE service registered, we register the enhanced bytecode
// so that the weaving hook can weave the interface class and add lookups
// coming from the UI
if (classData.isInterfaceClass() && MotechClassPool.isServiceInterfaceRegistered(className)) {
MotechClassPool.registerEnhancedClassData(classData);
}
}
}
private void filterEntities(List<EntityDto> entities) {
Iterator<EntityDto> it = entities.iterator();
while (it.hasNext()) {
EntityDto entity = it.next();
if (isSkippedDDE(entity)) {
it.remove();
} else if (entity.isDDE()) {
Class<?> definition = loadClass(entity, entity.getClassName());
if (null == definition) {
it.remove();
}
}
}
}
private boolean isSkippedDDE(EntityDto entity) {
return entity.isDDE() && !MotechClassPool.isDDEReady(entity.getClassName());
}
private void updateFieldName(String oldName, String newName, String tableName) {
LOGGER.info("Renaming column in {}: {} to {}", tableName, oldName, newName);
JDOConnection con = persistenceManagerFactory.getPersistenceManager().getDataStoreConnection();
Connection nativeCon = (Connection) con.getNativeConnection();
boolean isMySqlDriver = sqlDBManager.getChosenSQLDriver().equals(Constants.Config.MYSQL_DRIVER_CLASSNAME);
try {
Statement stmt = nativeCon.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
StringBuilder fieldTypeQuery = new StringBuilder("SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '");
fieldTypeQuery.append(tableName);
fieldTypeQuery.append("' AND COLUMN_NAME = '");
fieldTypeQuery.append(oldName);
fieldTypeQuery.append("';");
ResultSet resultSet = stmt.executeQuery(fieldTypeQuery.toString());
resultSet.first();
String fieldType = resultSet.getString("DATA_TYPE");
con.close();
con = persistenceManagerFactory.getPersistenceManager().getDataStoreConnection();
nativeCon = (Connection) con.getNativeConnection();
stmt = nativeCon.createStatement();
StringBuilder updateQuery = new StringBuilder("ALTER TABLE ");
updateQuery.append(getDatabaseValidName(tableName, isMySqlDriver));
updateQuery.append(isMySqlDriver ? " CHANGE " : " RENAME COLUMN ");
updateQuery.append(getDatabaseValidName(oldName, isMySqlDriver));
updateQuery.append(isMySqlDriver ? " " : " TO ");
updateQuery.append(getDatabaseValidName(newName, isMySqlDriver));
if (isMySqlDriver) {
updateQuery.append(" ");
updateQuery.append("varchar".equals(fieldType) ? "varchar(255)" : fieldType);
}
updateQuery.append(";");
stmt.executeUpdate(updateQuery.toString());
} catch (SQLException e) {
if ("S1000".equals(e.getSQLState())) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info(String.format("Column %s does not exist in %s", oldName, tableName), e);
}
} else {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(String.format("Unable to rename column in %s: %s to %s", tableName, oldName, newName), e);
}
}
} finally {
con.close();
}
}
private String getDatabaseValidName(String name, boolean isMySqlDriver) {
return isMySqlDriver ? name : "\"".concat(name).concat("\"");
}
private MdsJDOEnhancer createEnhancer(ClassLoader enhancerClassLoader) {
Properties config = mdsConfig.getDataNucleusProperties();
return new MdsJDOEnhancer(config, enhancerClassLoader);
}
private Class<?> loadClass(EntityDto entity, String className) {
Bundle declaringBundle = MdsBundleHelper.searchForBundle(bundleContext, entity);
Class<?> definition = null;
if (declaringBundle == null) {
LOGGER.warn("Declaring bundle unavailable for entity {}", className);
} else {
try {
definition = declaringBundle.loadClass(className);
} catch (ClassNotFoundException e) {
LOGGER.warn("Class declaration for {} not present in bundle {}",
className, declaringBundle.getSymbolicName());
}
}
return definition;
}
@Autowired
public void setSqlDBManager(SqlDBManager sqlDBManager) {
this.sqlDBManager = sqlDBManager;
}
@Autowired
public void setEntityBuilder(EntityBuilder entityBuilder) {
this.entityBuilder = entityBuilder;
}
@Autowired
public void setInfrastructureBuilder(EntityInfrastructureBuilder infrastructureBuilder) {
this.infrastructureBuilder = infrastructureBuilder;
}
@Autowired
public void setMetadataBuilder(EntityMetadataBuilder metadataBuilder) {
this.metadataBuilder = metadataBuilder;
}
@Autowired
public void setMdsConfig(MdsConfig mdsConfig) {
this.mdsConfig = mdsConfig;
}
@Autowired
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
@Autowired
public void setMetadataHolder(MetadataHolder metadataHolder) {
this.metadataHolder = metadataHolder;
}
@Autowired
public void setEnumBuilder(EnumBuilder enumBuilder) {
this.enumBuilder = enumBuilder;
}
@Autowired
@Qualifier("dataPersistenceManagerFactory")
public void setPersistenceManagerFactory(PersistenceManagerFactory persistenceManagerFactory) {
this.persistenceManagerFactory = persistenceManagerFactory;
}
}
|
platform/mds/mds/src/main/java/org/motechproject/mds/builder/impl/MDSConstructorImpl.java
|
package org.motechproject.mds.builder.impl;
import javassist.ByteArrayClassPath;
import javassist.CannotCompileException;
import javassist.CtClass;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.motechproject.commons.sql.service.SqlDBManager;
import org.motechproject.mds.builder.EntityBuilder;
import org.motechproject.mds.builder.EntityInfrastructureBuilder;
import org.motechproject.mds.builder.EntityMetadataBuilder;
import org.motechproject.mds.builder.EnumBuilder;
import org.motechproject.mds.builder.MDSConstructor;
import org.motechproject.mds.config.MdsConfig;
import org.motechproject.mds.domain.ClassData;
import org.motechproject.mds.domain.ComboboxHolder;
import org.motechproject.mds.domain.Entity;
import org.motechproject.mds.domain.EntityType;
import org.motechproject.mds.dto.EntityDto;
import org.motechproject.mds.dto.FieldDto;
import org.motechproject.mds.dto.SchemaHolder;
import org.motechproject.mds.dto.TypeDto;
import org.motechproject.mds.enhancer.MdsJDOEnhancer;
import org.motechproject.mds.ex.entity.EntityCreationException;
import org.motechproject.mds.helper.ClassTableName;
import org.motechproject.mds.helper.EntitySorter;
import org.motechproject.mds.helper.MdsBundleHelper;
import org.motechproject.mds.javassist.JavassistLoader;
import org.motechproject.mds.javassist.MotechClassPool;
import org.motechproject.mds.repository.MetadataHolder;
import org.motechproject.mds.util.ClassName;
import org.motechproject.mds.util.Constants;
import org.motechproject.mds.util.JavassistUtil;
import org.motechproject.mds.util.MDSClassLoader;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.datastore.JDOConnection;
import javax.jdo.metadata.JDOMetadata;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Default implementation of {@link org.motechproject.mds.builder.MDSConstructor} interface.
*/
@Service
public class MDSConstructorImpl implements MDSConstructor {
private static final Logger LOGGER = LoggerFactory.getLogger(MDSConstructorImpl.class);
private MdsConfig mdsConfig;
private EntityBuilder entityBuilder;
private EntityInfrastructureBuilder infrastructureBuilder;
private EntityMetadataBuilder metadataBuilder;
private MetadataHolder metadataHolder;
private BundleContext bundleContext;
private EnumBuilder enumBuilder;
private PersistenceManagerFactory persistenceManagerFactory;
private SqlDBManager sqlDBManager;
@Override
public synchronized boolean constructEntities(SchemaHolder schemaHolder) {
// To be able to register updated class, we need to reload class loader
// and therefore add all the classes again
MotechClassPool.clearEnhancedData();
MDSClassLoader.reloadClassLoader();
// we need an jdo enhancer and a temporary classLoader
// to define classes in before enhancement
MDSClassLoader tmpClassLoader = MDSClassLoader.getStandaloneInstance();
MdsJDOEnhancer enhancer = createEnhancer(tmpClassLoader);
JavassistLoader loader = new JavassistLoader(tmpClassLoader);
// process only entities that are not drafts
List<EntityDto> entities = schemaHolder.getAllEntities();
filterEntities(entities);
sortEntities(entities, schemaHolder);
// create enum for appropriate combobox fields
for (EntityDto entity : entities) {
buildEnum(loader, enhancer, entity, schemaHolder);
}
// load entities interfaces
for (EntityDto entity : entities) {
buildInterfaces(loader, enhancer, entity);
}
// generate jdo metadata from scratch for our entities
JDOMetadata jdoMetadata = metadataHolder.reloadMetadata();
// First we build empty history and trash classes
// (We don't have to generate it for main class,
// since we just fetch fields from existing definition
for (EntityDto entity : entities) {
if (entity.isRecordHistory()) {
entityBuilder.prepareHistoryClass(entity);
}
entityBuilder.prepareTrashClass(entity);
}
// Build classes
Map<String, ClassData> classDataMap = buildClasses(entities, schemaHolder);
List<Class> classes = new ArrayList<>();
// We add the java classes to both
// the temporary ClassLoader and enhancer
for (EntityDto entity : entities) {
String className = entity.getClassName();
Class<?> definition = addClassData(loader, enhancer, classDataMap.get(className));
if (entity.isRecordHistory()) {
addClassData(loader, enhancer, classDataMap.get(ClassName.getHistoryClassName(className)));
}
addClassData(loader, enhancer, classDataMap.get(ClassName.getTrashClassName(className)));
classes.add(definition);
LOGGER.debug("Generated classes for {}", entity.getClassName());
}
for (Class<?> definition : classes) {
loader.loadFieldsAndMethodsOfClass(definition);
}
// Prepare metadata
buildMetadata(entities, jdoMetadata, classDataMap, classes, schemaHolder);
// after the classes are defined, we register their metadata
enhancer.registerMetadata(jdoMetadata);
// then, we commence with enhancement
enhancer.enhance();
// we register the enhanced class bytes
// and build the infrastructure classes
registerEnhancedClassBytes(entities, enhancer, schemaHolder);
metadataBuilder.fixEnhancerIssuesInMetadata(jdoMetadata, schemaHolder);
return CollectionUtils.isNotEmpty(entities);
}
private void registerEnhancedClassBytes(List<EntityDto> entities, MdsJDOEnhancer enhancer, SchemaHolder schemaHolder) {
for (EntityDto entity : entities) {
// register
String className = entity.getClassName();
LOGGER.debug("Registering {}", className);
registerClass(enhancer, entity);
if (entity.isRecordHistory()) {
registerHistoryClass(enhancer, className);
}
registerTrashClass(enhancer, className);
LOGGER.debug("Building infrastructure for {}", className);
buildInfrastructure(entity, schemaHolder);
}
}
private void sortEntities(List<EntityDto> entities, SchemaHolder schemaHolder) {
List<EntityDto> byInheritance = EntitySorter.sortByInheritance(entities);
List<EntityDto> byHasARelation = EntitySorter.sortByHasARelation(byInheritance, schemaHolder);
// for safe we clear entities list
entities.clear();
// for now the entities list will be sorted by inheritance and by 'has-a' relation
entities.addAll(byHasARelation);
}
private Map<String, ClassData> buildClasses(List<EntityDto> entities, SchemaHolder schemaHolder) {
Map<String, ClassData> classDataMap = new LinkedHashMap<>();
//We build classes for all entities
for (EntityDto entity : entities) {
List<FieldDto> fields = schemaHolder.getFields(entity);
ClassData classData = buildClass(entity, fields);
ClassData historyClassData = null;
if (entity.isRecordHistory()) {
historyClassData = entityBuilder.buildHistory(entity, fields);
}
ClassData trashClassData = entityBuilder.buildTrash(entity, fields);
String className = entity.getClassName();
classDataMap.put(className, classData);
if (historyClassData != null) {
classDataMap.put(ClassName.getHistoryClassName(className), historyClassData);
}
classDataMap.put(ClassName.getTrashClassName(className), trashClassData);
}
return classDataMap;
}
private void buildMetadata(List<EntityDto> entities, JDOMetadata jdoMetadata, Map<String, ClassData> classDataMap,
List<Class> classes, SchemaHolder schemaHolder) {
for (EntityDto entity : entities) {
String className = entity.getClassName();
Class definition = null;
for (Class clazz : classes) {
if (clazz.getName().equals(className)) {
definition = clazz;
break;
}
}
metadataBuilder.addEntityMetadata(jdoMetadata, entity, definition, schemaHolder);
if (entity.isRecordHistory()) {
metadataBuilder.addHelperClassMetadata(jdoMetadata, classDataMap.get(ClassName.getHistoryClassName(className)),
entity, EntityType.HISTORY, definition, schemaHolder);
}
metadataBuilder.addHelperClassMetadata(jdoMetadata, classDataMap.get(ClassName.getTrashClassName(className)),
entity, EntityType.TRASH, definition, schemaHolder);
}
}
private void buildEnum(JavassistLoader loader, MdsJDOEnhancer enhancer, EntityDto entity,
SchemaHolder schemaHolder) {
for (FieldDto field : schemaHolder.getFields(entity.getClassName())) {
TypeDto type = field.getType();
if (!type.isCombobox()) {
continue;
}
ComboboxHolder holder = new ComboboxHolder(entity, field);
if (holder.isEnum() || holder.isEnumCollection()) {
if (field.isReadOnly()) {
String enumName = holder.getEnumName();
Class<?> definition = loadClass(entity, enumName);
if (null != definition) {
MotechClassPool.registerEnum(enumName);
CtClass ctClass = MotechClassPool.getDefault().getOrNull(enumName);
if (null != ctClass) {
try {
ctClass.defrost();
byte[] bytecode = ctClass.toBytecode();
ClassData data = new ClassData(enumName, bytecode);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(data.getClassName(), data.getBytecode());
addClassData(loader, enhancer, data);
} catch (IOException | CannotCompileException e) {
LOGGER.error("Could not load enum: {}", enumName);
}
}
}
} else {
buildEnum(loader, enhancer, holder);
}
}
}
}
private void buildEnum(JavassistLoader loader, MdsJDOEnhancer enhancer, ComboboxHolder holder) {
ClassData data = enumBuilder.build(holder);
ByteArrayClassPath classPath = new ByteArrayClassPath(data.getClassName(), data.getBytecode());
MotechClassPool.getDefault().appendClassPath(classPath);
MotechClassPool.registerEnhancedClassData(data);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(data.getClassName(), data.getBytecode());
addClassData(loader, enhancer, data);
}
@Override
@Transactional("dataTransactionManager")
public void updateFields(Entity entity, Map<String, String> fieldNameChanges) {
for (String key : fieldNameChanges.keySet()) {
String tableName = ClassTableName.getTableName(entity.getClassName(), entity.getModule(), entity.getNamespace(), entity.getTableName(), null);
updateFieldName(key, fieldNameChanges.get(key), tableName);
if (entity.isRecordHistory()) {
updateFieldName(key, fieldNameChanges.get(key), ClassTableName.getTableName(entity, EntityType.HISTORY));
}
updateFieldName(key, fieldNameChanges.get(key), ClassTableName.getTableName(entity, EntityType.TRASH));
}
}
@Override
@Transactional
public void removeUniqueIndexes(Entity entity, Collection<String> fields) {
String tableName = ClassTableName.getTableName(entity.getClassName(), entity.getModule(),
entity.getNamespace(), entity.getTableName(), null);
PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
boolean isMySql = sqlDBManager.getChosenSQLDriver().equals(Constants.Config.MYSQL_DRIVER_CLASSNAME);
for (String field : fields) {
String constraintName = KeyNames.uniqueKeyName(entity.getName(), field);
String sql;
if (isMySql) {
sql = "DROP INDEX " + constraintName + " ON " + tableName;
} else {
sql = "ALTER TABLE \"" + tableName + "\" DROP CONSTRAINT IF EXISTS \"" + constraintName + "\"";
}
Query query = pm.newQuery(Constants.Util.SQL_QUERY, sql);
query.execute();
}
}
private void registerHistoryClass(MdsJDOEnhancer enhancer, String className) {
String historyClassName = ClassName.getHistoryClassName(className);
byte[] enhancedBytes = enhancer.getEnhancedBytes(historyClassName);
ClassData classData = new ClassData(historyClassName, enhancedBytes);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(classData.getClassName(), classData.getBytecode());
MotechClassPool.registerHistoryClassData(classData);
}
private void registerTrashClass(MdsJDOEnhancer enhancer, String className) {
String trashClassName = ClassName.getTrashClassName(className);
byte[] enhancedBytes = enhancer.getEnhancedBytes(trashClassName);
ClassData classData = new ClassData(trashClassName, enhancedBytes);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(classData.getClassName(), classData.getBytecode());
MotechClassPool.registerTrashClassData(classData);
}
private void registerClass(MdsJDOEnhancer enhancer, EntityDto entity) {
byte[] enhancedBytes = enhancer.getEnhancedBytes(entity.getClassName());
ClassData classData = new ClassData(entity, enhancedBytes);
// register with the classloader so that we avoid issues with the persistence manager
MDSClassLoader.getInstance().safeDefineClass(classData.getClassName(), classData.getBytecode());
MotechClassPool.registerEnhancedClassData(classData);
}
private Class<?> addClassData(JavassistLoader loader, MdsJDOEnhancer enhancer, ClassData data) {
Class<?> definition = loader.loadClass(data);
enhancer.addClass(data);
return definition;
}
private ClassData buildClass(EntityDto entity, List<FieldDto> fields) {
ClassData classData;
if (entity.isDDE()) {
// for DDE we load the class coming from the bundle
Bundle declaringBundle = MdsBundleHelper.searchForBundle(bundleContext, entity);
if (declaringBundle == null) {
throw new EntityCreationException("Declaring bundle unavailable for entity " + entity.getClassName());
}
classData = entityBuilder.buildDDE(entity, fields, declaringBundle);
} else {
classData = entityBuilder.build(entity, fields);
}
return classData;
}
private void buildInterfaces(JavassistLoader loader, MdsJDOEnhancer enhancer, EntityDto entity) {
List<ClassData> interfaces = new LinkedList<>();
if (entity.isDDE()) {
Bundle declaringBundle = MdsBundleHelper.searchForBundle(bundleContext, entity);
try {
Class<?> definition = declaringBundle.loadClass(entity.getClassName());
for (Class interfaceClass : definition.getInterfaces()) {
String classpath = JavassistUtil.toClassPath(interfaceClass.getName());
URL classResource = declaringBundle.getResource(classpath);
if (classResource != null) {
try (InputStream in = classResource.openStream()) {
interfaces.add(new ClassData(interfaceClass.getName(), IOUtils.toByteArray(in), true));
}
}
}
} catch (ClassNotFoundException e) {
LOGGER.error("Class {} not found in {} bundle", entity.getClassName(), declaringBundle.getSymbolicName());
} catch (IOException ioExc) {
LOGGER.error("Could not load interface for {} class", entity.getClassName());
}
}
for (ClassData data : interfaces) {
try {
MDSClassLoader.getInstance().loadClass(data.getClassName());
} catch (ClassNotFoundException e) {
// interfaces should be defined in the MDS class loader only if it does not exist
MDSClassLoader.getInstance().safeDefineClass(data.getClassName(), data.getBytecode());
ByteArrayClassPath classPath = new ByteArrayClassPath(data.getClassName(), data.getBytecode());
MotechClassPool.getDefault().appendClassPath(classPath);
MotechClassPool.registerEnhancedClassData(data);
addClassData(loader, enhancer, data);
}
}
}
private void buildInfrastructure(EntityDto entity, SchemaHolder schemaHolder) {
String className = entity.getClassName();
List<ClassData> infrastructure = infrastructureBuilder.buildInfrastructure(entity, schemaHolder);
for (ClassData classData : infrastructure) {
// if we have a DDE service registered, we register the enhanced bytecode
// so that the weaving hook can weave the interface class and add lookups
// coming from the UI
if (classData.isInterfaceClass() && MotechClassPool.isServiceInterfaceRegistered(className)) {
MotechClassPool.registerEnhancedClassData(classData);
}
}
}
private void filterEntities(List<EntityDto> entities) {
Iterator<EntityDto> it = entities.iterator();
while (it.hasNext()) {
EntityDto entity = it.next();
if (isSkippedDDE(entity)) {
it.remove();
} else if (entity.isDDE()) {
Class<?> definition = loadClass(entity, entity.getClassName());
if (null == definition) {
it.remove();
}
}
}
}
private boolean isSkippedDDE(EntityDto entity) {
return entity.isDDE() && !MotechClassPool.isDDEReady(entity.getClassName());
}
private void updateFieldName(String oldName, String newName, String tableName) {
LOGGER.info("Renaming column in {}: {} to {}", tableName, oldName, newName);
JDOConnection con = persistenceManagerFactory.getPersistenceManager().getDataStoreConnection();
Connection nativeCon = (Connection) con.getNativeConnection();
boolean isMySqlDriver = sqlDBManager.getChosenSQLDriver().equals(Constants.Config.MYSQL_DRIVER_CLASSNAME);
try {
Statement stmt = nativeCon.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
StringBuilder fieldTypeQuery = new StringBuilder("SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '");
fieldTypeQuery.append(tableName);
fieldTypeQuery.append("' AND COLUMN_NAME = '");
fieldTypeQuery.append(oldName);
fieldTypeQuery.append("';");
ResultSet resultSet = stmt.executeQuery(fieldTypeQuery.toString());
resultSet.first();
String fieldType = resultSet.getString("DATA_TYPE");
con.close();
con = persistenceManagerFactory.getPersistenceManager().getDataStoreConnection();
nativeCon = (Connection) con.getNativeConnection();
stmt = nativeCon.createStatement();
StringBuilder updateQuery = new StringBuilder("ALTER TABLE ");
updateQuery.append(getDatabaseValidName(tableName, isMySqlDriver));
updateQuery.append(isMySqlDriver ? " CHANGE " : " RENAME COLUMN ");
updateQuery.append(getDatabaseValidName(oldName, isMySqlDriver));
updateQuery.append(isMySqlDriver ? " " : " TO ");
updateQuery.append(getDatabaseValidName(newName, isMySqlDriver));
if (isMySqlDriver) {
updateQuery.append(" ");
updateQuery.append("varchar".equals(fieldType) ? "varchar(255)" : fieldType);
}
updateQuery.append(";");
stmt.executeUpdate(updateQuery.toString());
} catch (SQLException e) {
if ("S1000".equals(e.getSQLState())) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info(String.format("Column %s does not exist in %s", oldName, tableName), e);
}
} else {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(String.format("Unable to rename column in %s: %s to %s", tableName, oldName, newName), e);
}
}
} finally {
con.close();
}
}
private String getDatabaseValidName(String name, boolean isMySqlDriver) {
return isMySqlDriver ? name : "\"".concat(name).concat("\"");
}
private MdsJDOEnhancer createEnhancer(ClassLoader enhancerClassLoader) {
Properties config = mdsConfig.getDataNucleusProperties();
return new MdsJDOEnhancer(config, enhancerClassLoader);
}
private Class<?> loadClass(EntityDto entity, String className) {
Bundle declaringBundle = MdsBundleHelper.searchForBundle(bundleContext, entity);
Class<?> definition = null;
if (declaringBundle == null) {
LOGGER.warn("Declaring bundle unavailable for entity {}", className);
} else {
try {
definition = declaringBundle.loadClass(className);
} catch (ClassNotFoundException e) {
LOGGER.warn("Class declaration for {} not present in bundle {}",
className, declaringBundle.getSymbolicName());
}
}
return definition;
}
@Autowired
public void setSqlDBManager(SqlDBManager sqlDBManager) {
this.sqlDBManager = sqlDBManager;
}
@Autowired
public void setEntityBuilder(EntityBuilder entityBuilder) {
this.entityBuilder = entityBuilder;
}
@Autowired
public void setInfrastructureBuilder(EntityInfrastructureBuilder infrastructureBuilder) {
this.infrastructureBuilder = infrastructureBuilder;
}
@Autowired
public void setMetadataBuilder(EntityMetadataBuilder metadataBuilder) {
this.metadataBuilder = metadataBuilder;
}
@Autowired
public void setMdsConfig(MdsConfig mdsConfig) {
this.mdsConfig = mdsConfig;
}
@Autowired
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
@Autowired
public void setMetadataHolder(MetadataHolder metadataHolder) {
this.metadataHolder = metadataHolder;
}
@Autowired
public void setEnumBuilder(EnumBuilder enumBuilder) {
this.enumBuilder = enumBuilder;
}
@Autowired
@Qualifier("dataPersistenceManagerFactory")
public void setPersistenceManagerFactory(PersistenceManagerFactory persistenceManagerFactory) {
this.persistenceManagerFactory = persistenceManagerFactory;
}
}
|
Fixed tansactional annotation
|
platform/mds/mds/src/main/java/org/motechproject/mds/builder/impl/MDSConstructorImpl.java
|
Fixed tansactional annotation
|
|
Java
|
mit
|
39d031cd16f958928b293a8923fe06e6972f270f
| 0
|
abicelis/Remindy
|
package ve.com.abicelis.remindy.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.math.BigDecimal;
import java.security.InvalidParameterException;
import java.sql.DatabaseMetaData;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import ve.com.abicelis.remindy.enums.ReminderCategory;
import ve.com.abicelis.remindy.enums.ReminderDateType;
import ve.com.abicelis.remindy.enums.ReminderExtraType;
import ve.com.abicelis.remindy.enums.ReminderSortType;
import ve.com.abicelis.remindy.enums.ReminderStatus;
import ve.com.abicelis.remindy.enums.ReminderTimeType;
import ve.com.abicelis.remindy.exception.CouldNotDeleteDataException;
import ve.com.abicelis.remindy.exception.CouldNotInsertDataException;
import ve.com.abicelis.remindy.exception.CouldNotUpdateDataException;
import ve.com.abicelis.remindy.exception.MalformedLinkException;
import ve.com.abicelis.remindy.exception.PlaceNotFoundException;
import ve.com.abicelis.remindy.model.Place;
import ve.com.abicelis.remindy.model.Reminder;
import ve.com.abicelis.remindy.model.ReminderByPlaceComparator;
import ve.com.abicelis.remindy.model.ReminderExtra;
import ve.com.abicelis.remindy.model.ReminderExtraAudio;
import ve.com.abicelis.remindy.model.ReminderExtraImage;
import ve.com.abicelis.remindy.model.ReminderExtraLink;
import ve.com.abicelis.remindy.model.ReminderExtraText;
import ve.com.abicelis.remindy.model.Time;
/**
* Created by Alex on 9/3/2017.
*/
public class RemindyDAO {
private RemindyDbHelper mDatabaseHelper;
public RemindyDAO(Context context) {
mDatabaseHelper = new RemindyDbHelper(context);
}
/* Get data from database */
/**
* Returns a List of OVERDUE Reminders.
* These are reminders which have an Active status, but will never trigger because of their set dates
* Examples:
* 1. Reminder is set to end in the past:
* endDate < today
* 2. Reminder is set to end sometime in the future, but on a day of the week that have passed:
* Today=Tuesday, endDate=Friday but Reminder is set to trigger only Mondays.
*/
public List<Reminder> getOverdueReminders() {
return getRemindersByStatus(ReminderStatus.OVERDUE, ReminderSortType.DATE);
}
/**
* Returns a List of ACTIVE Reminders.
* These are reminders which have an Active status, and will trigger sometime in the present or in the future
* Basically, all Reminders which are *NOT* OVERDUE (See function above)
*
* @param sortType ReminderSortType enum value with which to sort results. By date, by category or by Location
*/
public List<Reminder> getActiveReminders(@NonNull ReminderSortType sortType) {
return getRemindersByStatus(ReminderStatus.ACTIVE, sortType);
}
/**
* Returns a List of Reminders with a status of DONE.
*
* @param sortType ReminderSortType enum value with which to sort results. By date, by category or by Location
*/
public List<Reminder> getDoneReminders(@NonNull ReminderSortType sortType) {
return getRemindersByStatus(ReminderStatus.DONE, sortType);
}
/**
* Returns a List of Reminders with a status of ARCHIVED.
*
* @param sortType ReminderSortType enum value with which to sort results. By date, by category or by Location
*/
public List<Reminder> getArchivedReminders(@NonNull ReminderSortType sortType) {
return getRemindersByStatus(ReminderStatus.ARCHIVED, sortType);
}
/**
* Returns a List of Reminders given a specific ReminderStatus and ReminderSortType
*
* @param reminderStatus ReminderStatus enum value with which to filter Reminders.
* @param sortType ReminderSortType enum value with which to sort results. By date, by category or by Location
*/
private List<Reminder> getRemindersByStatus(@NonNull ReminderStatus reminderStatus, @NonNull ReminderSortType sortType) {
List<Reminder> reminders = new ArrayList<>();
String orderByClause = null;
switch (sortType) {
case DATE:
orderByClause = RemindyContract.ReminderTable.COLUMN_NAME_END_DATE.getName() + " DESC";
break;
case PLACE:
//Cant sort here, need the Place's name, dont have it.
break;
case CATEGORY:
orderByClause = RemindyContract.ReminderTable.COLUMN_NAME_CATEGORY.getName() + " DESC";
}
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(RemindyContract.ReminderTable.TABLE_NAME, null, RemindyContract.ReminderTable.COLUMN_NAME_STATUS.getName() + "=?",
new String[]{reminderStatus.name()}, null, null, orderByClause);
try {
while (cursor.moveToNext()) {
Reminder current = getReminderFromCursor(cursor);
//Try to get the Place, if there is one
try {
int placeId = cursor.getInt(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_PLACE_FK.getName()));
current.setPlace(getPlace(placeId));
} catch (Exception e) {/*Thrown if COLUMN_NAME_PLACE_FK is null, so do nothing.*/}
//Try to get the Extras, if there are any
current.setExtras(getReminderExtras(current.getId()));
reminders.add(current);
}
} finally {
cursor.close();
}
//Do sort by place if needed
if (sortType == ReminderSortType.PLACE) {
Collections.sort(reminders, new ReminderByPlaceComparator());
}
return reminders;
}
/**
* Returns a List of all the Places in the database.
*/
public List<Place> getPlaces() {
List<Place> places = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(RemindyContract.PlaceTable.TABLE_NAME, null, null, null, null, null, null);
try {
while (cursor.moveToNext()) {
places.add(getPlaceFromCursor(cursor));
}
} finally {
cursor.close();
}
return places;
}
/**
* Returns a Place given a placeId.
* @param placeId The id of the place
*/
public Place getPlace(int placeId) throws PlaceNotFoundException, SQLiteConstraintException {
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(RemindyContract.PlaceTable.TABLE_NAME, null, RemindyContract.PlaceTable._ID + "=?",
new String[]{String.valueOf(placeId)}, null, null, null);
if (cursor.getCount() == 0)
throw new PlaceNotFoundException("Specified Place not found in the database. Passed id=" + placeId);
if (cursor.getCount() > 1)
throw new SQLiteConstraintException("Database UNIQUE constraint failure, more than one record found. Passed value=" + placeId);
cursor.moveToNext();
return getPlaceFromCursor(cursor);
}
/**
* Returns a List of Extras associated to a Reminder.
* @param reminderId The id of the reminder, fk in ExtraTable
*/
public List<ReminderExtra> getReminderExtras(int reminderId) {
List<ReminderExtra> extras = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(RemindyContract.ExtraTable.TABLE_NAME, null, RemindyContract.ExtraTable.COLUMN_NAME_REMINDER_FK.getName() + "=?",
new String[]{String.valueOf(reminderId)}, null, null, null);
try {
while (cursor.moveToNext()) {
extras.add(getReminderExtraFromCursor(cursor));
}
} finally {
cursor.close();
}
return extras;
}
/* Delete data from database */
/**
* Deletes a single Place, given its ID
* @param placeId The ID of the place to delete
*/
public boolean deletePlace(int placeId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
return db.delete(RemindyContract.PlaceTable.TABLE_NAME,
RemindyContract.PlaceTable._ID + " =?",
new String[]{String.valueOf(placeId)}) > 0;
}
/**
* Deletes a single Extra, given its ID
* @param extraId The ID of the extra to delete
*/
public boolean deleteExtra(int extraId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
return db.delete(RemindyContract.ExtraTable.TABLE_NAME,
RemindyContract.ExtraTable._ID + " =?",
new String[]{String.valueOf(extraId)}) > 0;
}
/**
* Deletes all Extras linked to a Reminder, given the reminder's ID
* @param reminderId The ID of the reminder whos extras will be deleted
*/
public boolean deleteExtrasFromReminder(int reminderId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
return db.delete(RemindyContract.ExtraTable.TABLE_NAME,
RemindyContract.ExtraTable.COLUMN_NAME_REMINDER_FK.getName() + " =?",
new String[]{String.valueOf(reminderId)}) > 0;
}
/**
* Deletes a Reminder with its associated Extras, given the reminder's ID
* @param reminderId The ID of the reminder o delete
*/
public boolean deleteReminder(int reminderId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Delete the extras
deleteExtrasFromReminder(reminderId);
return db.delete(RemindyContract.ReminderTable.TABLE_NAME,
RemindyContract.ReminderTable._ID + " =?",
new String[]{String.valueOf(reminderId)}) > 0;
}
/* Update data on database */
/**
* Updates the information stored about a Place
* @param place The Place to update
*/
public long updatePlace(Place place) throws CouldNotUpdateDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Set values
ContentValues values = getValuesFromPlace(place);
//Which row to update
String selection = RemindyContract.PlaceTable._ID + " =? ";
String[] selectionArgs = {String.valueOf(place.getId())};
int count = db.update(
RemindyContract.PlaceTable.TABLE_NAME,
values,
selection,
selectionArgs);
return count;
}
/**
* Updates the information stored about an Extra
* @param extra The ReminderExtra to update
*/
public long updateReminderExtra(ReminderExtra extra) throws CouldNotUpdateDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Set values
ContentValues values = getValuesFromExtra(extra);
//Which row to update
String selection = RemindyContract.ExtraTable._ID + " =? ";
String[] selectionArgs = {String.valueOf(extra.getId())};
int count = db.update(
RemindyContract.ExtraTable.TABLE_NAME,
values,
selection,
selectionArgs);
return count;
}
/**
* Updates the information stored about a Reminder and its Extras.
* @param reminder The Reminder (and associated Extras) to update
*/
public long updateReminder(Reminder reminder) throws CouldNotUpdateDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Delete the extras
try {
deleteExtrasFromReminder(reminder.getId());
} catch (CouldNotDeleteDataException e) {
throw new CouldNotUpdateDataException("Failed trying to delete Extras associated with Reminder ID= " + reminder.getId(), e);
}
//Insert new Extras
try {
insertReminderExtras(reminder.getExtras());
} catch (CouldNotInsertDataException e) {
throw new CouldNotUpdateDataException("Failed trying to insert Extras associated with Reminder ID= " + reminder.getId(), e);
}
//Set reminder values
ContentValues values = getValuesFromReminder(reminder);
//Which row to update
String selection = RemindyContract.ReminderTable._ID + " =? ";
String[] selectionArgs = {String.valueOf(reminder.getId())};
int count = db.update(
RemindyContract.ReminderTable.TABLE_NAME,
values,
selection,
selectionArgs);
return count;
}
/* Insert data into database */
/**
* Inserts a new Place into the database.
* @param place The Place to be inserted
*/
public long insertPlace(Place place) throws CouldNotInsertDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
ContentValues values = getValuesFromPlace(place);
long newRowId;
newRowId = db.insert(RemindyContract.PlaceTable.TABLE_NAME, null, values);
if (newRowId == -1)
throw new CouldNotInsertDataException("There was a problem inserting the Place: " + place.toString());
return newRowId;
}
/**
* Inserts a List of Extras into the database.
* @param extras The List of Extras to be inserted
*/
public long[] insertReminderExtras(List<ReminderExtra> extras) throws CouldNotInsertDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
long[] newRowIds = new long[extras.size()];
for (int i = 0; i < extras.size(); i++) {
ContentValues values = getValuesFromExtra(extras.get(i));
newRowIds[i] = db.insert(RemindyContract.ExtraTable.TABLE_NAME, null, values);
if (newRowIds[i] == -1)
throw new CouldNotInsertDataException("There was a problem inserting the Extra: " + extras.toString());
}
return newRowIds;
}
/**
* Inserts a new Reminder and its associated Extras into the database.
* @param reminder The Reminder (and associated Extras) to insert
*/
public long insertReminder(Reminder reminder) throws CouldNotInsertDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Insert Extras
if (reminder.getExtras() != null && reminder.getExtras().size() > 0) {
try {
insertReminderExtras(reminder.getExtras());
} catch (CouldNotInsertDataException e) {
throw new CouldNotInsertDataException("There was a problem inserting the Extras while inserting the Reminder: " + reminder.toString(), e);
}
}
ContentValues values = getValuesFromReminder(reminder);
long newRowId;
newRowId = db.insert(RemindyContract.ReminderTable.TABLE_NAME, null, values);
if (newRowId == -1)
throw new CouldNotInsertDataException("There was a problem inserting the Reminder: " + reminder.toString());
return newRowId;
}
/* Model to ContentValues */
private ContentValues getValuesFromPlace(Place place) {
ContentValues values = new ContentValues();
values.put(RemindyContract.PlaceTable.COLUMN_NAME_ALIAS.getName(), place.getAlias());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_ADDRESS.getName(), place.getAddress());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_LATITUDE.getName(), place.getLatitude());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_LONGITUDE.getName(), place.getLongitude());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_RADIUS.getName(), place.getRadius());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_IS_ONE_OFF.getName(), place.isOneOff());
return values;
}
private ContentValues getValuesFromExtra(ReminderExtra extra) {
ContentValues values = new ContentValues();
values.put(RemindyContract.ExtraTable.COLUMN_NAME_REMINDER_FK.getName(), extra.getReminderId());
values.put(RemindyContract.ExtraTable.COLUMN_NAME_TYPE.getName(), extra.getType().name());
switch (extra.getType()) {
case AUDIO:
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_BLOB.getName(), ((ReminderExtraAudio) extra).getAudio());
break;
case IMAGE:
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_BLOB.getName(), ((ReminderExtraImage) extra).getThumbnail());
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_TEXT.getName(), ((ReminderExtraImage) extra).getFullImagePath());
break;
case TEXT:
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_TEXT.getName(), ((ReminderExtraText) extra).getText());
break;
case LINK:
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_TEXT.getName(), ((ReminderExtraLink) extra).getLink());
break;
default:
throw new InvalidParameterException("ReminderExtraType is invalid. Value = " + extra.getType());
}
return values;
}
private ContentValues getValuesFromReminder(Reminder reminder) {
ContentValues values = new ContentValues();
values.put(RemindyContract.ReminderTable.COLUMN_NAME_STATUS.getName(), reminder.getStatus().name());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_TITLE.getName(), reminder.getTitle());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_DESCRIPTION.getName(), reminder.getDescription());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_CATEGORY.getName(), reminder.getCategory().name());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_PLACE_FK.getName(), (reminder.getPlace() != null ? String.valueOf(reminder.getPlace().getId()) : "null"));
values.put(RemindyContract.ReminderTable.COLUMN_NAME_DATE_TYPE.getName(), reminder.getDateType().name());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_START_DATE.getName(), reminder.getStartDate().getTimeInMillis());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_END_DATE.getName(), reminder.getEndDate().getTimeInMillis());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_TIME_TYPE.getName(), reminder.getTimeType().name());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_START_TIME.getName(), reminder.getStartTime().getTimeInMinutes());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_END_TIME.getName(), reminder.getEndTime().getTimeInMinutes());
return values;
}
/* Cursor to Model */
private Reminder getReminderFromCursor(Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(RemindyContract.ReminderTable._ID));
ReminderStatus status = ReminderStatus.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_STATUS.getName())));
String title = cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_TITLE.getName()));
String description = cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_DESCRIPTION.getName()));
ReminderCategory category = ReminderCategory.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_CATEGORY.getName())));
ReminderDateType dateType = ReminderDateType.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_DATE_TYPE.getName())));
Calendar startDate = null;
int startDateIndex = cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_START_TIME.getName());
if (!cursor.getString(startDateIndex).isEmpty()) {
startDate = Calendar.getInstance();
startDate.setTimeInMillis(cursor.getLong(startDateIndex));
}
Calendar endDate = null;
int endDateIndex = cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_END_DATE.getName());
if (!cursor.getString(endDateIndex).isEmpty()) {
endDate = Calendar.getInstance();
endDate.setTimeInMillis(cursor.getLong(endDateIndex));
}
ReminderTimeType timeType = ReminderTimeType.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_TIME_TYPE.getName())));
Time startTime = new Time(cursor.getInt(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_START_TIME.getName())));
Time endTime = new Time(cursor.getInt(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_END_TIME.getName())));
return new Reminder(id, status, title, description, category, null, dateType, startDate, endDate, timeType, startTime, endTime);
}
private Place getPlaceFromCursor(Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(RemindyContract.PlaceTable._ID));
String alias = cursor.getString(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_ALIAS.getName()));
String address = cursor.getString(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_ADDRESS.getName()));
double latitude = cursor.getDouble(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_LATITUDE.getName()));
double longitude = cursor.getDouble(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_LONGITUDE.getName()));
float radius = cursor.getFloat(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_RADIUS.getName()));
boolean isOneOff = Boolean.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_IS_ONE_OFF.getName())));
return new Place(id, alias, address, latitude, longitude, radius, isOneOff);
}
private ReminderExtra getReminderExtraFromCursor(Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(RemindyContract.ExtraTable._ID));
int reminderId = cursor.getInt(cursor.getColumnIndex(RemindyContract.ExtraTable.COLUMN_NAME_REMINDER_FK.getName()));
ReminderExtraType extraType = ReminderExtraType.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ExtraTable.COLUMN_NAME_TYPE.getName())));
String textContent = cursor.getString(cursor.getColumnIndex(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_TEXT.getName()));
byte[] blobContent = cursor.getBlob(cursor.getColumnIndex(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_BLOB.getName()));
switch (extraType) {
case AUDIO:
return new ReminderExtraAudio(id, reminderId, blobContent);
case IMAGE:
return new ReminderExtraImage(id, reminderId, blobContent, textContent);
case TEXT:
return new ReminderExtraText(id, reminderId, textContent);
case LINK:
return new ReminderExtraLink(id, reminderId, textContent);
default:
throw new InvalidParameterException("ReminderExtraType is invalid. Value = " + extraType);
}
}
}
|
app/src/main/java/ve/com/abicelis/remindy/database/RemindyDAO.java
|
package ve.com.abicelis.remindy.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.math.BigDecimal;
import java.security.InvalidParameterException;
import java.sql.DatabaseMetaData;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import ve.com.abicelis.remindy.enums.ReminderCategory;
import ve.com.abicelis.remindy.enums.ReminderDateType;
import ve.com.abicelis.remindy.enums.ReminderExtraType;
import ve.com.abicelis.remindy.enums.ReminderSortType;
import ve.com.abicelis.remindy.enums.ReminderStatus;
import ve.com.abicelis.remindy.enums.ReminderTimeType;
import ve.com.abicelis.remindy.exception.CouldNotDeleteDataException;
import ve.com.abicelis.remindy.exception.CouldNotInsertDataException;
import ve.com.abicelis.remindy.exception.CouldNotUpdateDataException;
import ve.com.abicelis.remindy.exception.MalformedLinkException;
import ve.com.abicelis.remindy.exception.PlaceNotFoundException;
import ve.com.abicelis.remindy.model.Place;
import ve.com.abicelis.remindy.model.Reminder;
import ve.com.abicelis.remindy.model.ReminderByPlaceComparator;
import ve.com.abicelis.remindy.model.ReminderExtra;
import ve.com.abicelis.remindy.model.ReminderExtraAudio;
import ve.com.abicelis.remindy.model.ReminderExtraImage;
import ve.com.abicelis.remindy.model.ReminderExtraLink;
import ve.com.abicelis.remindy.model.ReminderExtraText;
import ve.com.abicelis.remindy.model.Time;
/**
* Created by Alex on 9/3/2017.
*/
public class RemindyDAO {
private RemindyDbHelper mDatabaseHelper;
public RemindyDAO(Context context) {
mDatabaseHelper = new RemindyDbHelper(context);
}
/* Get data from database */
/**
* Returns a List of OVERDUE Reminders.
* These are reminders which have an Active status, but will never trigger because of their set dates
* Examples:
* 1. Reminder is set to end in the past:
* endDate < today
* 2. Reminder is set to end sometime in the future, but on a day of the week that have passed:
* Today=Tuesday, endDate=Friday but Reminder is set to trigger only Mondays.
*/
public List<Reminder> getOverdueReminders() {
return getRemindersByStatus(ReminderStatus.OVERDUE, ReminderSortType.DATE);
}
/**
* Returns a List of ACTIVE Reminders.
* These are reminders which have an Active status, and will trigger sometime in the present or in the future
* Basically, all Reminders which are *NOT* OVERDUE (See function above)
*
* @param sortType ReminderSortType enum value with which to sort results. By date, by category or by Location
*/
public List<Reminder> getActiveReminders(@NonNull ReminderSortType sortType) {
return getRemindersByStatus(ReminderStatus.ACTIVE, sortType);
}
/**
* Returns a List of Reminders with a status of DONE.
*
* @param sortType ReminderSortType enum value with which to sort results. By date, by category or by Location
*/
public List<Reminder> getDoneReminders(@NonNull ReminderSortType sortType) {
return getRemindersByStatus(ReminderStatus.DONE, sortType);
}
/**
* Returns a List of Reminders with a status of ARCHIVED.
*
* @param sortType ReminderSortType enum value with which to sort results. By date, by category or by Location
*/
public List<Reminder> getArchivedReminders(@NonNull ReminderSortType sortType) {
return getRemindersByStatus(ReminderStatus.ARCHIVED, sortType);
}
/**
* Returns a List of Reminders given a specific ReminderStatus and ReminderSortType
*
* @param reminderStatus ReminderStatus enum value with which to filter Reminders.
* @param sortType ReminderSortType enum value with which to sort results. By date, by category or by Location
*/
private List<Reminder> getRemindersByStatus(@NonNull ReminderStatus reminderStatus, @NonNull ReminderSortType sortType) {
List<Reminder> reminders = new ArrayList<>();
String orderByClause = null;
switch (sortType) {
case DATE:
orderByClause = RemindyContract.ReminderTable.COLUMN_NAME_END_DATE + " DESC";
break;
case PLACE:
//Cant sort here, need the Place's name, dont have it.
break;
case CATEGORY:
orderByClause = RemindyContract.ReminderTable.COLUMN_NAME_CATEGORY + " DESC";
}
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(RemindyContract.ReminderTable.TABLE_NAME, null, RemindyContract.ReminderTable.COLUMN_NAME_STATUS + "=?",
new String[]{reminderStatus.name()}, null, null, orderByClause);
try {
while (cursor.moveToNext()) {
Reminder current = getReminderFromCursor(cursor);
//Try to get the Place, if there is one
try {
int placeId = cursor.getInt(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_PLACE_FK.getName()));
current.setPlace(getPlace(placeId));
} catch (Exception e) {/*Thrown if COLUMN_NAME_PLACE_FK is null, so do nothing.*/}
//Try to get the Extras, if there are any
current.setExtras(getReminderExtras(current.getId()));
reminders.add(current);
}
} finally {
cursor.close();
}
//Do sort by place if needed
if (sortType == ReminderSortType.PLACE) {
Collections.sort(reminders, new ReminderByPlaceComparator());
}
return reminders;
}
/**
* Returns a List of all the Places in the database.
*/
public List<Place> getPlaces() {
List<Place> places = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(RemindyContract.PlaceTable.TABLE_NAME, null, null, null, null, null, null);
try {
while (cursor.moveToNext()) {
places.add(getPlaceFromCursor(cursor));
}
} finally {
cursor.close();
}
return places;
}
/**
* Returns a Place given a placeId.
* @param placeId The id of the place
*/
public Place getPlace(int placeId) throws PlaceNotFoundException, SQLiteConstraintException {
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(RemindyContract.PlaceTable.TABLE_NAME, null, RemindyContract.PlaceTable._ID + "=?",
new String[]{String.valueOf(placeId)}, null, null, null);
if (cursor.getCount() == 0)
throw new PlaceNotFoundException("Specified Place not found in the database. Passed id=" + placeId);
if (cursor.getCount() > 1)
throw new SQLiteConstraintException("Database UNIQUE constraint failure, more than one record found. Passed value=" + placeId);
cursor.moveToNext();
return getPlaceFromCursor(cursor);
}
/**
* Returns a List of Extras associated to a Reminder.
* @param reminderId The id of the reminder, fk in ExtraTable
*/
public List<ReminderExtra> getReminderExtras(int reminderId) {
List<ReminderExtra> extras = new ArrayList<>();
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query(RemindyContract.ExtraTable.TABLE_NAME, null, RemindyContract.ExtraTable.COLUMN_NAME_REMINDER_FK + "=?",
new String[]{String.valueOf(reminderId)}, null, null, null);
try {
while (cursor.moveToNext()) {
extras.add(getReminderExtraFromCursor(cursor));
}
} finally {
cursor.close();
}
return extras;
}
/* Delete data from database */
/**
* Deletes a single Place, given its ID
* @param placeId The ID of the place to delete
*/
public boolean deletePlace(int placeId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
return db.delete(RemindyContract.PlaceTable.TABLE_NAME,
RemindyContract.PlaceTable._ID + " =?",
new String[]{String.valueOf(placeId)}) > 0;
}
/**
* Deletes a single Extra, given its ID
* @param extraId The ID of the extra to delete
*/
public boolean deleteExtra(int extraId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
return db.delete(RemindyContract.ExtraTable.TABLE_NAME,
RemindyContract.ExtraTable._ID + " =?",
new String[]{String.valueOf(extraId)}) > 0;
}
/**
* Deletes all Extras linked to a Reminder, given the reminder's ID
* @param reminderId The ID of the reminder whos extras will be deleted
*/
public boolean deleteExtrasFromReminder(int reminderId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
return db.delete(RemindyContract.ExtraTable.TABLE_NAME,
RemindyContract.ExtraTable.COLUMN_NAME_REMINDER_FK + " =?",
new String[]{String.valueOf(reminderId)}) > 0;
}
/**
* Deletes a Reminder with its associated Extras, given the reminder's ID
* @param reminderId The ID of the reminder o delete
*/
public boolean deleteReminder(int reminderId) throws CouldNotDeleteDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Delete the extras
deleteExtrasFromReminder(reminderId);
return db.delete(RemindyContract.ReminderTable.TABLE_NAME,
RemindyContract.ReminderTable._ID + " =?",
new String[]{String.valueOf(reminderId)}) > 0;
}
/* Update data on database */
/**
* Updates the information stored about a Place
* @param place The Place to update
*/
public long updatePlace(Place place) throws CouldNotUpdateDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Set values
ContentValues values = getValuesFromPlace(place);
//Which row to update
String selection = RemindyContract.PlaceTable._ID + " =? ";
String[] selectionArgs = {String.valueOf(place.getId())};
int count = db.update(
RemindyContract.PlaceTable.TABLE_NAME,
values,
selection,
selectionArgs);
return count;
}
/**
* Updates the information stored about an Extra
* @param extra The ReminderExtra to update
*/
public long updateReminderExtra(ReminderExtra extra) throws CouldNotUpdateDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Set values
ContentValues values = getValuesFromExtra(extra);
//Which row to update
String selection = RemindyContract.ExtraTable._ID + " =? ";
String[] selectionArgs = {String.valueOf(extra.getId())};
int count = db.update(
RemindyContract.ExtraTable.TABLE_NAME,
values,
selection,
selectionArgs);
return count;
}
/**
* Updates the information stored about a Reminder and its Extras.
* @param reminder The Reminder (and associated Extras) to update
*/
public long updateReminder(Reminder reminder) throws CouldNotUpdateDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Delete the extras
try {
deleteExtrasFromReminder(reminder.getId());
} catch (CouldNotDeleteDataException e) {
throw new CouldNotUpdateDataException("Failed trying to delete Extras associated with Reminder ID= " + reminder.getId(), e);
}
//Insert new Extras
try {
insertReminderExtras(reminder.getExtras());
} catch (CouldNotInsertDataException e) {
throw new CouldNotUpdateDataException("Failed trying to insert Extras associated with Reminder ID= " + reminder.getId(), e);
}
//Set reminder values
ContentValues values = getValuesFromReminder(reminder);
//Which row to update
String selection = RemindyContract.ReminderTable._ID + " =? ";
String[] selectionArgs = {String.valueOf(reminder.getId())};
int count = db.update(
RemindyContract.ReminderTable.TABLE_NAME,
values,
selection,
selectionArgs);
return count;
}
/* Insert data into database */
/**
* Inserts a new Place into the database.
* @param place The Place to be inserted
*/
public long insertPlace(Place place) throws CouldNotInsertDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
ContentValues values = getValuesFromPlace(place);
long newRowId;
newRowId = db.insert(RemindyContract.PlaceTable.TABLE_NAME, null, values);
if (newRowId == -1)
throw new CouldNotInsertDataException("There was a problem inserting the Place: " + place.toString());
return newRowId;
}
/**
* Inserts a List of Extras into the database.
* @param extras The List of Extras to be inserted
*/
public long[] insertReminderExtras(List<ReminderExtra> extras) throws CouldNotInsertDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
long[] newRowIds = new long[extras.size()];
for (int i = 0; i < extras.size(); i++) {
ContentValues values = getValuesFromExtra(extras.get(i));
newRowIds[i] = db.insert(RemindyContract.ExtraTable.TABLE_NAME, null, values);
if (newRowIds[i] == -1)
throw new CouldNotInsertDataException("There was a problem inserting the Extra: " + extras.toString());
}
return newRowIds;
}
/**
* Inserts a new Reminder and its associated Extras into the database.
* @param reminder The Reminder (and associated Extras) to insert
*/
public long insertReminder(Reminder reminder) throws CouldNotInsertDataException {
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
//Insert Extras
if (reminder.getExtras() != null && reminder.getExtras().size() > 0) {
try {
insertReminderExtras(reminder.getExtras());
} catch (CouldNotInsertDataException e) {
throw new CouldNotInsertDataException("There was a problem inserting the Extras while inserting the Reminder: " + reminder.toString(), e);
}
}
ContentValues values = getValuesFromReminder(reminder);
long newRowId;
newRowId = db.insert(RemindyContract.ReminderTable.TABLE_NAME, null, values);
if (newRowId == -1)
throw new CouldNotInsertDataException("There was a problem inserting the Reminder: " + reminder.toString());
return newRowId;
}
/* Model to ContentValues */
private ContentValues getValuesFromPlace(Place place) {
ContentValues values = new ContentValues();
values.put(RemindyContract.PlaceTable.COLUMN_NAME_ALIAS.getName(), place.getAlias());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_ADDRESS.getName(), place.getAddress());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_LATITUDE.getName(), place.getLatitude());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_LONGITUDE.getName(), place.getLongitude());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_RADIUS.getName(), place.getRadius());
values.put(RemindyContract.PlaceTable.COLUMN_NAME_IS_ONE_OFF.getName(), place.isOneOff());
return values;
}
private ContentValues getValuesFromExtra(ReminderExtra extra) {
ContentValues values = new ContentValues();
values.put(RemindyContract.ExtraTable.COLUMN_NAME_REMINDER_FK.getName(), extra.getReminderId());
values.put(RemindyContract.ExtraTable.COLUMN_NAME_TYPE.getName(), extra.getType().name());
switch (extra.getType()) {
case AUDIO:
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_BLOB.getName(), ((ReminderExtraAudio) extra).getAudio());
break;
case IMAGE:
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_BLOB.getName(), ((ReminderExtraImage) extra).getThumbnail());
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_TEXT.getName(), ((ReminderExtraImage) extra).getFullImagePath());
break;
case TEXT:
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_TEXT.getName(), ((ReminderExtraText) extra).getText());
break;
case LINK:
values.put(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_TEXT.getName(), ((ReminderExtraLink) extra).getLink());
break;
default:
throw new InvalidParameterException("ReminderExtraType is invalid. Value = " + extra.getType());
}
return values;
}
private ContentValues getValuesFromReminder(Reminder reminder) {
ContentValues values = new ContentValues();
values.put(RemindyContract.ReminderTable.COLUMN_NAME_STATUS.getName(), reminder.getStatus().name());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_TITLE.getName(), reminder.getTitle());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_DESCRIPTION.getName(), reminder.getDescription());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_CATEGORY.getName(), reminder.getCategory().name());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_PLACE_FK.getName(), (reminder.getPlace() != null ? String.valueOf(reminder.getPlace().getId()) : "null"));
values.put(RemindyContract.ReminderTable.COLUMN_NAME_DATE_TYPE.getName(), reminder.getDateType().name());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_START_DATE.getName(), reminder.getStartDate().getTimeInMillis());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_END_DATE.getName(), reminder.getEndDate().getTimeInMillis());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_TIME_TYPE.getName(), reminder.getTimeType().name());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_START_TIME.getName(), reminder.getStartTime().getTimeInMinutes());
values.put(RemindyContract.ReminderTable.COLUMN_NAME_END_TIME.getName(), reminder.getEndTime().getTimeInMinutes());
return values;
}
/* Cursor to Model */
private Reminder getReminderFromCursor(Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(RemindyContract.ReminderTable._ID));
ReminderStatus status = ReminderStatus.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_STATUS.getName())));
String title = cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_TITLE.getName()));
String description = cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_DESCRIPTION.getName()));
ReminderCategory category = ReminderCategory.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_CATEGORY.getName())));
ReminderDateType dateType = ReminderDateType.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_DATE_TYPE.getName())));
Calendar startDate = null;
int startDateIndex = cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_START_TIME.getName());
if (!cursor.getString(startDateIndex).isEmpty()) {
startDate = Calendar.getInstance();
startDate.setTimeInMillis(cursor.getLong(startDateIndex));
}
Calendar endDate = null;
int endDateIndex = cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_END_DATE.getName());
if (!cursor.getString(endDateIndex).isEmpty()) {
endDate = Calendar.getInstance();
endDate.setTimeInMillis(cursor.getLong(endDateIndex));
}
ReminderTimeType timeType = ReminderTimeType.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_TIME_TYPE.getName())));
Time startTime = new Time(cursor.getInt(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_START_TIME.getName())));
Time endTime = new Time(cursor.getInt(cursor.getColumnIndex(RemindyContract.ReminderTable.COLUMN_NAME_END_TIME.getName())));
return new Reminder(id, status, title, description, category, null, dateType, startDate, endDate, timeType, startTime, endTime);
}
private Place getPlaceFromCursor(Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(RemindyContract.PlaceTable._ID));
String alias = cursor.getString(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_ALIAS.getName()));
String address = cursor.getString(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_ADDRESS.getName()));
double latitude = cursor.getDouble(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_LATITUDE.getName()));
double longitude = cursor.getDouble(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_LONGITUDE.getName()));
float radius = cursor.getFloat(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_RADIUS.getName()));
boolean isOneOff = Boolean.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.PlaceTable.COLUMN_NAME_IS_ONE_OFF.getName())));
return new Place(id, alias, address, latitude, longitude, radius, isOneOff);
}
private ReminderExtra getReminderExtraFromCursor(Cursor cursor) {
int id = cursor.getInt(cursor.getColumnIndex(RemindyContract.ExtraTable._ID));
int reminderId = cursor.getInt(cursor.getColumnIndex(RemindyContract.ExtraTable.COLUMN_NAME_REMINDER_FK.getName()));
ReminderExtraType extraType = ReminderExtraType.valueOf(cursor.getString(cursor.getColumnIndex(RemindyContract.ExtraTable.COLUMN_NAME_TYPE.getName())));
String textContent = cursor.getString(cursor.getColumnIndex(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_TEXT.getName()));
byte[] blobContent = cursor.getBlob(cursor.getColumnIndex(RemindyContract.ExtraTable.COLUMN_NAME_CONTENT_BLOB.getName()));
switch (extraType) {
case AUDIO:
return new ReminderExtraAudio(id, reminderId, blobContent);
case IMAGE:
return new ReminderExtraImage(id, reminderId, blobContent, textContent);
case TEXT:
return new ReminderExtraText(id, reminderId, textContent);
case LINK:
return new ReminderExtraLink(id, reminderId, textContent);
default:
throw new InvalidParameterException("ReminderExtraType is invalid. Value = " + extraType);
}
}
}
|
Bugfixes
|
app/src/main/java/ve/com/abicelis/remindy/database/RemindyDAO.java
|
Bugfixes
|
|
Java
|
mit
|
07f31e892a50317de55a8d72df3b6877fdcfa89f
| 0
|
braintree/braintree_java,braintree/braintree_java,braintree/braintree_java
|
package com.braintreegateway.integrationtest;
import com.braintreegateway.*;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.*;
public class MerchantAccountIT {
private BraintreeGateway gateway;
@Before
public void createGateway() {
this.gateway = new BraintreeGateway(Environment.DEVELOPMENT, "integration_merchant_id", "integration_public_key",
"integration_private_key");
}
@Test
public void deprecatedCreateSucceeds() {
Result<MerchantAccount> result = gateway.merchantAccount().create(deprecatedCreationRequest());
assertTrue("merchant account creation should succeed", result.isSuccess());
MerchantAccount ma = result.getTarget();
assertEquals("account status should be pending", MerchantAccount.Status.PENDING, ma.getStatus());
assertEquals("sandbox_master_merchant_account", ma.getMasterMerchantAccount().getId());
assertTrue(ma.isSubMerchant());
assertFalse(ma.getMasterMerchantAccount().isSubMerchant());
}
@Test
public void createRequiresNoId() {
Result<MerchantAccount> result = gateway.merchantAccount().create(creationRequest());
assertTrue("merchant account creation should succeed", result.isSuccess());
MerchantAccount ma = result.getTarget();
assertEquals("account status should be pending", MerchantAccount.Status.PENDING, ma.getStatus());
assertEquals("sandbox_master_merchant_account", ma.getMasterMerchantAccount().getId());
assertTrue(ma.isSubMerchant());
assertFalse(ma.getMasterMerchantAccount().isSubMerchant());
}
@Test
public void createWillUseIdIfPassed() {
int randomNumber = new Random().nextInt() % 10000;
String subMerchantAccountId = String.format("sub_merchant_account_id_%d", randomNumber);
MerchantAccountRequest request = creationRequest().id(subMerchantAccountId);
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertTrue("merchant account creation should succeed", result.isSuccess());
MerchantAccount ma = result.getTarget();
assertEquals("account status should be pending", MerchantAccount.Status.PENDING, ma.getStatus());
assertEquals("submerchant id should be assigned", subMerchantAccountId, ma.getId());
assertEquals("sandbox_master_merchant_account", ma.getMasterMerchantAccount().getId());
assertTrue(ma.isSubMerchant());
assertFalse(ma.getMasterMerchantAccount().isSubMerchant());
}
@Test
public void handlesUnsuccessfulResults() {
Result<MerchantAccount> result = gateway.merchantAccount().create(new MerchantAccountRequest());
List<ValidationError> errors = result.getErrors().forObject("merchant-account").onField("master_merchant_account_id");
assertEquals(1, errors.size());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_REQUIRED, errors.get(0).getCode());
}
@Test
public void createAcceptsBankFundingDestination() {
MerchantAccountRequest request = creationRequest().
funding().
destination(MerchantAccount.FundingDestination.BANK).
routingNumber("122100024").
accountNumber("98479798798").
done();
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertTrue("merchant account creation should succeed", result.isSuccess());
}
@Test
public void createAcceptsEmailFundingDestination() {
MerchantAccountRequest request = creationRequest().
funding().
destination(MerchantAccount.FundingDestination.EMAIL).
email("joe@bloggs.com").
done();
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertTrue("merchant account creation should succeed", result.isSuccess());
}
@Test
public void createAcceptsMobilePhoneFundingDestination() {
MerchantAccountRequest request = creationRequest().
funding().
destination(MerchantAccount.FundingDestination.MOBILE_PHONE).
mobilePhone("3125551212").
done();
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertTrue("merchant account creation should succeed", result.isSuccess());
}
@Test
public void updateUpdatesAllFields() {
Result<MerchantAccount> result = gateway.merchantAccount().create(deprecatedCreationRequest());
assertTrue("merchant account creation should succeed", result.isSuccess());
MerchantAccountRequest request = creationRequest().
masterMerchantAccountId(null);
Result<MerchantAccount> updateResult = gateway.merchantAccount().update(result.getTarget().getId(), request);
assertTrue("merchant account update should succeed", updateResult.isSuccess());
MerchantAccount merchantAccount = updateResult.getTarget();
assertEquals("Job", merchantAccount.getIndividualDetails().getFirstName());
assertEquals("Leoggs", merchantAccount.getIndividualDetails().getLastName());
assertEquals("job@leoggs.com", merchantAccount.getIndividualDetails().getEmail());
assertEquals("5555551212", merchantAccount.getIndividualDetails().getPhone());
assertEquals("193 Credibility St.", merchantAccount.getIndividualDetails().getAddress().getStreetAddress());
assertEquals("60611", merchantAccount.getIndividualDetails().getAddress().getPostalCode());
assertEquals("Avondale", merchantAccount.getIndividualDetails().getAddress().getLocality());
assertEquals("IN", merchantAccount.getIndividualDetails().getAddress().getRegion());
assertEquals("1985-09-10", merchantAccount.getIndividualDetails().getDateOfBirth());
assertEquals("Calculon", merchantAccount.getBusinessDetails().getLegalName());
assertEquals("Calculon", merchantAccount.getBusinessDetails().getDbaName());
assertEquals("123456780", merchantAccount.getBusinessDetails().getTaxId());
assertEquals("135 Credibility St.", merchantAccount.getBusinessDetails().getAddress().getStreetAddress());
assertEquals("60602", merchantAccount.getBusinessDetails().getAddress().getPostalCode());
assertEquals("Gary", merchantAccount.getBusinessDetails().getAddress().getLocality());
assertEquals("OH", merchantAccount.getBusinessDetails().getAddress().getRegion());
assertEquals(MerchantAccount.FundingDestination.EMAIL, merchantAccount.getFundingDetails().getDestination());
assertEquals("joe+funding@bloggs.com", merchantAccount.getFundingDetails().getEmail());
assertEquals("3125551212", merchantAccount.getFundingDetails().getMobilePhone());
assertEquals("122100024", merchantAccount.getFundingDetails().getRoutingNumber());
assertEquals("8799", merchantAccount.getFundingDetails().getAccountNumberLast4());
}
@Test
public void createHandlesRequiredValidationErrors() {
MerchantAccountRequest request = new MerchantAccountRequest().
tosAccepted(true).
masterMerchantAccountId("sandbox_master_merchant_account");
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertFalse(result.isSuccess());
ValidationErrors errors = result.getErrors().forObject("merchant-account");
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_REQUIRED,
errors.forObject("individual").onField("first-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_REQUIRED,
errors.forObject("individual").onField("last-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_REQUIRED,
errors.forObject("individual").onField("date-of-birth").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_REQUIRED,
errors.forObject("individual").onField("email").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_REQUIRED,
errors.forObject("individual").forObject("address").onField("street-address").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_LOCALITY_IS_REQUIRED,
errors.forObject("individual").forObject("address").onField("locality").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_REQUIRED,
errors.forObject("individual").forObject("address").onField("postal-code").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_REQUIRED,
errors.forObject("individual").forObject("address").onField("region").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_REQUIRED,
errors.forObject("funding").onField("destination").get(0).getCode());
}
@Test
public void createHandlesInvalidValidationErrors() {
MerchantAccountRequest request = new MerchantAccountRequest().
individual().
firstName("<>").
lastName("<>").
email("bad").
phone("999").
address().
streetAddress("nope").
postalCode("1").
region("QQ").
done().
dateOfBirth("hah").
ssn("12345").
done().
business().
taxId("bad").
dbaName("{}``").
legalName("``{}").
address().
streetAddress("nope").
postalCode("1").
region("QQ").
done().
done().
funding().
destination(MerchantAccount.FundingDestination.UNRECOGNIZED).
routingNumber("LEATHER").
accountNumber("BACK POCKET").
email("BILLFOLD").
mobilePhone("TRIFOLD").
done().
tosAccepted(true).
masterMerchantAccountId("sandbox_master_merchant_account");
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertFalse(result.isSuccess());
ValidationErrors errors = result.getErrors().forObject("merchant-account");
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_INVALID,
errors.forObject("individual").onField("first-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_INVALID,
errors.forObject("individual").onField("last-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_INVALID,
errors.forObject("individual").onField("date-of-birth").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_PHONE_IS_INVALID,
errors.forObject("individual").onField("phone").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_SSN_IS_INVALID,
errors.forObject("individual").onField("ssn").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_INVALID,
errors.forObject("individual").onField("email").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_INVALID,
errors.forObject("individual").forObject("address").onField("street-address").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_INVALID,
errors.forObject("individual").forObject("address").onField("postal-code").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_INVALID,
errors.forObject("individual").forObject("address").onField("region").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_DBA_NAME_IS_INVALID,
errors.forObject("business").onField("dba-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_INVALID,
errors.forObject("business").onField("legal-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_INVALID,
errors.forObject("business").onField("tax-id").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_STREET_ADDRESS_IS_INVALID,
errors.forObject("business").forObject("address").onField("street-address").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_POSTAL_CODE_IS_INVALID,
errors.forObject("business").forObject("address").onField("postal-code").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_REGION_IS_INVALID,
errors.forObject("business").forObject("address").onField("region").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_INVALID,
errors.forObject("funding").onField("destination").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_INVALID,
errors.forObject("funding").onField("account-number").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_INVALID,
errors.forObject("funding").onField("routing-number").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_INVALID,
errors.forObject("funding").onField("email").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_INVALID,
errors.forObject("funding").onField("mobile-phone").get(0).getCode());
}
private MerchantAccountRequest deprecatedCreationRequest() {
return new MerchantAccountRequest().
applicantDetails().
firstName("Joe").
lastName("Bloggs").
email("joe@bloggs.com").
phone("555-555-5555").
address().
streetAddress("123 Credibility St.").
postalCode("60606").
locality("Chicago").
region("IL").
done().
dateOfBirth("10/9/1980").
ssn("123-45-7890").
routingNumber("122100024").
accountNumber("98479798798").
taxId("123456789").
companyName("Calculon's Drama School").
done().
tosAccepted(true).
masterMerchantAccountId("sandbox_master_merchant_account");
}
private MerchantAccountRequest creationRequest() {
return new MerchantAccountRequest().
individual().
firstName("Job").
lastName("Leoggs").
email("job@leoggs.com").
phone("555-555-1212").
address().
streetAddress("193 Credibility St.").
postalCode("60611").
locality("Avondale").
region("IN").
done().
dateOfBirth("10/9/1985").
ssn("123-45-1235").
done().
business().
taxId("123456780").
dbaName("Calculon").
legalName("Calculon").
address().
streetAddress("135 Credibility St.").
postalCode("60602").
locality("Gary").
region("OH").
done().
done().
funding().
destination(MerchantAccount.FundingDestination.EMAIL).
routingNumber("122100024").
accountNumber("98479798799").
email("joe+funding@bloggs.com").
mobilePhone("3125551212").
done().
tosAccepted(true).
masterMerchantAccountId("sandbox_master_merchant_account");
}
}
|
src/test/java/com/braintreegateway/integrationtest/MerchantAccountIT.java
|
package com.braintreegateway.integrationtest;
import com.braintreegateway.*;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.*;
public class MerchantAccountIT {
private BraintreeGateway gateway;
@Before
public void createGateway() {
this.gateway = new BraintreeGateway(Environment.DEVELOPMENT, "integration_merchant_id", "integration_public_key",
"integration_private_key");
}
@Test
public void deprecatedCreateSucceeds() {
Result<MerchantAccount> result = gateway.merchantAccount().create(deprecatedCreationRequest());
assertTrue("merchant account creation should succeed", result.isSuccess());
MerchantAccount ma = result.getTarget();
assertEquals("account status should be pending", MerchantAccount.Status.PENDING, ma.getStatus());
assertEquals("sandbox_master_merchant_account", ma.getMasterMerchantAccount().getId());
assertTrue(ma.isSubMerchant());
assertFalse(ma.getMasterMerchantAccount().isSubMerchant());
}
@Test
public void createRequiresNoId() {
Result<MerchantAccount> result = gateway.merchantAccount().create(creationRequest());
assertTrue("merchant account creation should succeed", result.isSuccess());
MerchantAccount ma = result.getTarget();
assertEquals("account status should be pending", MerchantAccount.Status.PENDING, ma.getStatus());
assertEquals("sandbox_master_merchant_account", ma.getMasterMerchantAccount().getId());
assertTrue(ma.isSubMerchant());
assertFalse(ma.getMasterMerchantAccount().isSubMerchant());
}
@Test
public void createWillUseIdIfPassed() {
int randomNumber = new Random().nextInt() % 10000;
String subMerchantAccountId = String.format("sub_merchant_account_id_%d", randomNumber);
MerchantAccountRequest request = creationRequest().id(subMerchantAccountId);
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertTrue("merchant account creation should succeed", result.isSuccess());
MerchantAccount ma = result.getTarget();
assertEquals("account status should be pending", MerchantAccount.Status.PENDING, ma.getStatus());
assertEquals("submerchant id should be assigned", subMerchantAccountId, ma.getId());
assertEquals("sandbox_master_merchant_account", ma.getMasterMerchantAccount().getId());
assertTrue(ma.isSubMerchant());
assertFalse(ma.getMasterMerchantAccount().isSubMerchant());
}
@Test
public void handlesUnsuccessfulResults() {
Result<MerchantAccount> result = gateway.merchantAccount().create(new MerchantAccountRequest());
List<ValidationError> errors = result.getErrors().forObject("merchant-account").onField("master_merchant_account_id");
assertEquals(1, errors.size());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_REQUIRED, errors.get(0).getCode());
}
@Test
public void createAcceptsBankFundingDestination() {
MerchantAccountRequest request = creationRequest().
funding().
destination(MerchantAccount.FundingDestination.BANK).
routingNumber("122100024").
accountNumber("98479798798").
done();
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertTrue("merchant account creation should succeed", result.isSuccess());
}
@Test
public void createAcceptsEmailFundingDestination() {
MerchantAccountRequest request = creationRequest().
funding().
destination(MerchantAccount.FundingDestination.EMAIL).
email("joe@bloggs.com").
done();
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertTrue("merchant account creation should succeed", result.isSuccess());
}
@Test
public void createAcceptsMobilePhoneFundingDestination() {
MerchantAccountRequest request = creationRequest().
funding().
destination(MerchantAccount.FundingDestination.MOBILE_PHONE).
mobilePhone("3125551212").
done();
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertTrue("merchant account creation should succeed", result.isSuccess());
}
@Test
public void updateUpdatesAllFields() {
Result<MerchantAccount> result = gateway.merchantAccount().create(deprecatedCreationRequest());
assertTrue("merchant account creation should succeed", result.isSuccess());
MerchantAccountRequest request = creationRequest().
masterMerchantAccountId(null);
Result<MerchantAccount> update_result = gateway.merchantAccount().update(result.getTarget().getId(), request);
assertTrue("merchant account update should succeed", update_result.isSuccess());
MerchantAccount merchant_account = update_result.getTarget();
assertEquals("Job", merchant_account.getIndividualDetails().getFirstName());
assertEquals("Leoggs", merchant_account.getIndividualDetails().getLastName());
assertEquals("job@leoggs.com", merchant_account.getIndividualDetails().getEmail());
assertEquals("5555551212", merchant_account.getIndividualDetails().getPhone());
assertEquals("193 Credibility St.", merchant_account.getIndividualDetails().getAddress().getStreetAddress());
assertEquals("60611", merchant_account.getIndividualDetails().getAddress().getPostalCode());
assertEquals("Avondale", merchant_account.getIndividualDetails().getAddress().getLocality());
assertEquals("IN", merchant_account.getIndividualDetails().getAddress().getRegion());
assertEquals("1985-09-10", merchant_account.getIndividualDetails().getDateOfBirth());
assertEquals("Calculon", merchant_account.getBusinessDetails().getLegalName());
assertEquals("Calculon", merchant_account.getBusinessDetails().getDbaName());
assertEquals("123456780", merchant_account.getBusinessDetails().getTaxId());
assertEquals("135 Credibility St.", merchant_account.getBusinessDetails().getAddress().getStreetAddress());
assertEquals("60602", merchant_account.getBusinessDetails().getAddress().getPostalCode());
assertEquals("Gary", merchant_account.getBusinessDetails().getAddress().getLocality());
assertEquals("OH", merchant_account.getBusinessDetails().getAddress().getRegion());
assertEquals(MerchantAccount.FundingDestination.EMAIL, merchant_account.getFundingDetails().getDestination());
assertEquals("joe+funding@bloggs.com", merchant_account.getFundingDetails().getEmail());
assertEquals("3125551212", merchant_account.getFundingDetails().getMobilePhone());
assertEquals("122100024", merchant_account.getFundingDetails().getRoutingNumber());
assertEquals("8799", merchant_account.getFundingDetails().getAccountNumberLast4());
}
@Test
public void createHandlesRequiredValidationErrors() {
MerchantAccountRequest request = new MerchantAccountRequest().
tosAccepted(true).
masterMerchantAccountId("sandbox_master_merchant_account");
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertFalse(result.isSuccess());
ValidationErrors errors = result.getErrors().forObject("merchant-account");
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_REQUIRED,
errors.forObject("individual").onField("first-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_REQUIRED,
errors.forObject("individual").onField("last-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_REQUIRED,
errors.forObject("individual").onField("date-of-birth").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_REQUIRED,
errors.forObject("individual").onField("email").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_REQUIRED,
errors.forObject("individual").forObject("address").onField("street-address").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_LOCALITY_IS_REQUIRED,
errors.forObject("individual").forObject("address").onField("locality").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_REQUIRED,
errors.forObject("individual").forObject("address").onField("postal-code").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_REQUIRED,
errors.forObject("individual").forObject("address").onField("region").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_REQUIRED,
errors.forObject("funding").onField("destination").get(0).getCode());
}
@Test
public void createHandlesInvalidValidationErrors() {
MerchantAccountRequest request = new MerchantAccountRequest().
individual().
firstName("<>").
lastName("<>").
email("bad").
phone("999").
address().
streetAddress("nope").
postalCode("1").
region("QQ").
done().
dateOfBirth("hah").
ssn("12345").
done().
business().
taxId("bad").
dbaName("{}``").
legalName("``{}").
address().
streetAddress("nope").
postalCode("1").
region("QQ").
done().
done().
funding().
destination(MerchantAccount.FundingDestination.UNRECOGNIZED).
routingNumber("LEATHER").
accountNumber("BACK POCKET").
email("BILLFOLD").
mobilePhone("TRIFOLD").
done().
tosAccepted(true).
masterMerchantAccountId("sandbox_master_merchant_account");
Result<MerchantAccount> result = gateway.merchantAccount().create(request);
assertFalse(result.isSuccess());
ValidationErrors errors = result.getErrors().forObject("merchant-account");
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_INVALID,
errors.forObject("individual").onField("first-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_INVALID,
errors.forObject("individual").onField("last-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_INVALID,
errors.forObject("individual").onField("date-of-birth").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_PHONE_IS_INVALID,
errors.forObject("individual").onField("phone").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_SSN_IS_INVALID,
errors.forObject("individual").onField("ssn").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_INVALID,
errors.forObject("individual").onField("email").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_INVALID,
errors.forObject("individual").forObject("address").onField("street-address").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_INVALID,
errors.forObject("individual").forObject("address").onField("postal-code").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_INVALID,
errors.forObject("individual").forObject("address").onField("region").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_DBA_NAME_IS_INVALID,
errors.forObject("business").onField("dba-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_INVALID,
errors.forObject("business").onField("legal-name").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_INVALID,
errors.forObject("business").onField("tax-id").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_STREET_ADDRESS_IS_INVALID,
errors.forObject("business").forObject("address").onField("street-address").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_POSTAL_CODE_IS_INVALID,
errors.forObject("business").forObject("address").onField("postal-code").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_BUSINESS_ADDRESS_REGION_IS_INVALID,
errors.forObject("business").forObject("address").onField("region").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_INVALID,
errors.forObject("funding").onField("destination").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_INVALID,
errors.forObject("funding").onField("account-number").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_INVALID,
errors.forObject("funding").onField("routing-number").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_INVALID,
errors.forObject("funding").onField("email").get(0).getCode());
assertEquals(ValidationErrorCode.MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_INVALID,
errors.forObject("funding").onField("mobile-phone").get(0).getCode());
}
private MerchantAccountRequest deprecatedCreationRequest() {
return new MerchantAccountRequest().
applicantDetails().
firstName("Joe").
lastName("Bloggs").
email("joe@bloggs.com").
phone("555-555-5555").
address().
streetAddress("123 Credibility St.").
postalCode("60606").
locality("Chicago").
region("IL").
done().
dateOfBirth("10/9/1980").
ssn("123-45-7890").
routingNumber("122100024").
accountNumber("98479798798").
taxId("123456789").
companyName("Calculon's Drama School").
done().
tosAccepted(true).
masterMerchantAccountId("sandbox_master_merchant_account");
}
private MerchantAccountRequest creationRequest() {
return new MerchantAccountRequest().
individual().
firstName("Job").
lastName("Leoggs").
email("job@leoggs.com").
phone("555-555-1212").
address().
streetAddress("193 Credibility St.").
postalCode("60611").
locality("Avondale").
region("IN").
done().
dateOfBirth("10/9/1985").
ssn("123-45-1235").
done().
business().
taxId("123456780").
dbaName("Calculon").
legalName("Calculon").
address().
streetAddress("135 Credibility St.").
postalCode("60602").
locality("Gary").
region("OH").
done().
done().
funding().
destination(MerchantAccount.FundingDestination.EMAIL).
routingNumber("122100024").
accountNumber("98479798799").
email("joe+funding@bloggs.com").
mobilePhone("3125551212").
done().
tosAccepted(true).
masterMerchantAccountId("sandbox_master_merchant_account");
}
}
|
Fixed style errors in test.
|
src/test/java/com/braintreegateway/integrationtest/MerchantAccountIT.java
|
Fixed style errors in test.
|
|
Java
|
mit
|
fa879106aa33fbe4f185298808ceccb7363a76c4
| 0
|
gazbert/openid-connect-spring-client,gazbert/openid-connect-spring-client,gazbert/openid-connect-spring-client
|
package org.gazbert.openidconnect.client.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import static java.util.Optional.empty;
/**
* Custom authentication filter for using OpenID Connect.
*
* @author gazbert
*/
public class OpenIdConnectAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final Logger log = LoggerFactory.getLogger(getClass());
private OAuth2RestOperations restTemplate;
public OpenIdConnectAuthenticationFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
setAuthenticationManager(new NoOpAuthenticationManager());
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
OAuth2AccessToken accessToken;
try {
accessToken = restTemplate.getAccessToken();
log.info("AccessToken: value: " + accessToken.getValue());
log.info("AccessToken: additionalInfo: " + accessToken.getAdditionalInformation());
log.info("AccessToken: tokenType: " + accessToken.getTokenType());
log.info("AccessToken: expiration: " + accessToken.getExpiration());
log.info("AccessToken: expiresIn: " + accessToken.getExpiresIn());
} catch (OAuth2Exception e) {
throw new BadCredentialsException("Could not obtain Access Token", e);
}
try {
final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
log.info("Encoded id_token from accessToken.additionalInformation: " + idToken);
final Jwt tokenDecoded = JwtHelper.decode(idToken);
log.info("Decoded JWT id_token: " + tokenDecoded);
log.info("Decoded JWT id_token -> claims: " + tokenDecoded.getClaims());
final Map authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);
@SuppressWarnings("unchecked")
final OpenIdConnectUserDetails userDetails = new OpenIdConnectUserDetails(authInfo, accessToken);
log.info("OpenIdConnectUserDetails -> userId: " + userDetails.getUsername());
return new PreAuthenticatedAuthenticationToken(userDetails, empty(), userDetails.getAuthorities());
} catch (InvalidTokenException e) {
throw new BadCredentialsException("Could not obtain user details from Access Token", e);
}
}
public void setRestTemplate(OAuth2RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
private static class NoOpAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication authentication) {
throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager");
}
}
}
|
src/main/java/org/gazbert/openidconnect/client/security/OpenIdConnectAuthenticationFilter.java
|
package org.gazbert.openidconnect.client.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import static java.util.Optional.empty;
/**
* Custom authentication filter for using OpenID Connect.
*
* @author gazbert
*/
public class OpenIdConnectAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final Logger log = LoggerFactory.getLogger(getClass());
private OAuth2RestOperations restTemplate;
public OpenIdConnectAuthenticationFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
setAuthenticationManager(new NoOpAuthenticationManager());
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
OAuth2AccessToken accessToken;
try {
accessToken = restTemplate.getAccessToken();
log.info("AccessToken: value: " + accessToken.getValue());
log.info("AccessToken: additionalInfo: " + accessToken.getAdditionalInformation());
log.info("AccessToken: tokenType: " + accessToken.getTokenType());
log.info("AccessToken: expiration: " + accessToken.getExpiration());
log.info("AccessToken: expiresIn: " + accessToken.getExpiresIn());
} catch (OAuth2Exception e) {
throw new BadCredentialsException("Could not obtain Access Token", e);
}
try {
final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
log.info("Encoded id_token from accessToken.additionalInformation: " + idToken);
final Jwt tokenDecoded = JwtHelper.decode(idToken);
log.info("Decoded JWT id_token: " + tokenDecoded);
log.info("Decoded JWT id_token -> claims: " + tokenDecoded.getClaims());
final Map authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);
@SuppressWarnings("unchecked")
final OpenIdConnectUserDetails userDetails = new OpenIdConnectUserDetails(authInfo, accessToken);
log.info("OpenIdConnectUserDetails -> userId: " + userDetails.getUsername());
return new PreAuthenticatedAuthenticationToken(userDetails, empty(), userDetails.getAuthorities());
} catch (InvalidTokenException e) {
throw new BadCredentialsException("Could not obtain user details from Access Token", e);
}
}
public void setRestTemplate(OAuth2RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
private static class NoOpAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication authentication) {
throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager");
}
}
}
|
Code formatting OCD ;-)
|
src/main/java/org/gazbert/openidconnect/client/security/OpenIdConnectAuthenticationFilter.java
|
Code formatting OCD ;-)
|
|
Java
|
mit
|
dcb8bcfad7b12ac8a761edde1be4622ec026a739
| 0
|
all4coding/NumberProgressBar,Sarfarazsajjad/NumberProgressBar,wyxacc/NumberProgressBar,tanweijiu/NumberProgressBar,YlJava110/NumberProgressBar,wangkang0627/NumberProgressBar,prashant31191/NumberProgressBar,xiaotaijun/NumberProgressBar,hzw1199/NumberProgressBar,xiaoshi316/NumberProgressBar,cemlyzone/NumberProgressBar,ZhaoYukai/NumberProgressBar,zhupengGitHub/NumberProgressBar,MalwinderSingh/NumberProgressBar,lstNull/NumberProgressBar,ylfonline/NumberProgressBar,yt7789451/NumberProgressBar,Bob1993/NumberProgressBar,GeorgeMe/NumberProgressBar,leerduo/NumberProgressBar,hgl888/NumberProgressBar,jyushion/NumberProgressBar,HKMOpen/NumberProgressBar,xjswxdx/NumberProgressBar,jaohoang/NumberProgressBar,duaiyun1314/NumberProgressBar,flylives/NumberProgressBar,wswenyue/NumberProgressBar,xiebaiyuan/NumberProgressBar,HiWong/NumberProgressBar,Zulqurnain/NumberProgressBar,daimajia/NumberProgressBar
|
package com.daimajia.numberprogressbar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by daimajia on 14-4-30.
*/
public class NumberProgressBar extends View {
/**
* The max progress, default is 100
*/
private int mMax = 100;
/**
* current progress, can not exceed the max progress.
*/
private int mProgress = 0;
/**
* the progress area bar color
*/
private int mReachedBarColor;
/**
* the bar unreached area color.
*/
private int mUnreachedBarColor;
/**
* the progress text color.
*/
private int mTextColor;
/**
* the progress text size
*/
private float mTextSize;
/**
* the height of the reached area
*/
private float mReachedBarHeight;
/**
* the height of the unreached area
*/
private float mUnreachedBarHeight;
/**
* the suffix of the number.
*/
private String mSuffix = "%";
/**
* the prefix.
*/
private String mPrefix = "";
private final int default_text_color = Color.rgb(66, 145, 241);
private final int default_reached_color = Color.rgb(66,145,241);
private final int default_unreached_color = Color.rgb(204, 204, 204);
private final float default_progress_text_offset;
private final float default_text_size;
private final float default_reached_bar_height;
private final float default_unreached_bar_height;
/**
* for save and restore instance of progressbar.
*/
private static final String INSTANCE_STATE = "saved_instance";
private static final String INSTANCE_TEXT_COLOR = "text_color";
private static final String INSTANCE_TEXT_SIZE = "text_size";
private static final String INSTANCE_REACHED_BAR_HEIGHT = "reached_bar_height";
private static final String INSTANCE_REACHED_BAR_COLOR = "reached_bar_color";
private static final String INSTANCE_UNREACHED_BAR_HEIGHT = "unreached_bar_height";
private static final String INSTANCE_UNREACHED_BAR_COLOR = "unreached_bar_color";
private static final String INSTANCE_MAX = "max";
private static final String INSTANCE_PROGRESS = "progress";
private static final String INSTANCE_SUFFIX = "suffix";
private static final String INSTANCE_PREFIX = "prefix";
private static final String INSTANCE_TEXT_VISIBILITY = "text_visibility";
private static final int PROGRESS_TEXT_VISIBLE = 0;
/**
* the width of the text that to be drawn
*/
private float mDrawTextWidth;
/**
* the drawn text start
*/
private float mDrawTextStart;
/**
*the drawn text end
*/
private float mDrawTextEnd;
/**
* the text that to be drawn in onDraw()
*/
private String mCurrentDrawText;
/**
* the Paint of the reached area.
*/
private Paint mReachedBarPaint;
/**
* the Painter of the unreached area.
*/
private Paint mUnreachedBarPaint;
/**
* the Painter of the progress text.
*/
private Paint mTextPaint;
/**
* Unreached Bar area to draw rect.
*/
private RectF mUnreachedRectF = new RectF(0,0,0,0);
/**
* reached bar area rect.
*/
private RectF mReachedRectF = new RectF(0,0,0,0);
/**
* the progress text offset.
*/
private float mOffset;
/**
* determine if need to draw unreached area
*/
private boolean mDrawUnreachedBar = true;
private boolean mDrawReachedBar = true;
private boolean mIfDrawText = true;
public enum ProgressTextVisibility{
Visible,Invisible
};
public NumberProgressBar(Context context) {
this(context, null);
}
public NumberProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.numberProgressBarStyle);
}
public NumberProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
default_reached_bar_height = dp2px(1.5f);
default_unreached_bar_height = dp2px(1.0f);
default_text_size = sp2px(10);
default_progress_text_offset = dp2px(3.0f);
//load styled attributes.
final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.NumberProgressBar,
defStyleAttr, 0);
mReachedBarColor = attributes.getColor(R.styleable.NumberProgressBar_progress_reached_color, default_reached_color);
mUnreachedBarColor = attributes.getColor(R.styleable.NumberProgressBar_progress_unreached_color,default_unreached_color);
mTextColor = attributes.getColor(R.styleable.NumberProgressBar_progress_text_color,default_text_color);
mTextSize = attributes.getDimension(R.styleable.NumberProgressBar_progress_text_size, default_text_size);
mReachedBarHeight = attributes.getDimension(R.styleable.NumberProgressBar_progress_reached_bar_height,default_reached_bar_height);
mUnreachedBarHeight = attributes.getDimension(R.styleable.NumberProgressBar_progress_unreached_bar_height,default_unreached_bar_height);
mOffset = attributes.getDimension(R.styleable.NumberProgressBar_progress_text_offset,default_progress_text_offset);
int textVisible = attributes.getInt(R.styleable.NumberProgressBar_progress_text_visibility,PROGRESS_TEXT_VISIBLE);
if(textVisible != PROGRESS_TEXT_VISIBLE){
mIfDrawText = false;
}
setProgress(attributes.getInt(R.styleable.NumberProgressBar_progress,0));
setMax(attributes.getInt(R.styleable.NumberProgressBar_max, 100));
//
attributes.recycle();
initializePainters();
}
@Override
protected int getSuggestedMinimumWidth() {
return (int)mTextSize;
}
@Override
protected int getSuggestedMinimumHeight() {
return Math.max((int)mTextSize,Math.max((int)mReachedBarHeight,(int)mUnreachedBarHeight));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measure(widthMeasureSpec,true), measure(heightMeasureSpec,false));
}
private int measure(int measureSpec,boolean isWidth){
int result;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
int padding = isWidth?getPaddingLeft()+getPaddingRight():getPaddingTop()+getPaddingBottom();
if(mode == MeasureSpec.EXACTLY){
result = size;
}else{
result = isWidth ? getSuggestedMinimumWidth() : getSuggestedMinimumHeight();
result += padding;
if(mode == MeasureSpec.AT_MOST){
if(isWidth) {
result = Math.max(result, size);
}
else{
result = Math.min(result, size);
}
}
}
return result;
}
@Override
protected void onDraw(Canvas canvas) {
if(mIfDrawText){
calculateDrawRectF();
}else{
calculateDrawRectFWithoutProgressText();
}
if(mDrawReachedBar){
canvas.drawRect(mReachedRectF,mReachedBarPaint);
}
if(mDrawUnreachedBar) {
canvas.drawRect(mUnreachedRectF, mUnreachedBarPaint);
}
if(mIfDrawText)
canvas.drawText(mCurrentDrawText,mDrawTextStart,mDrawTextEnd,mTextPaint);
}
private void initializePainters(){
mReachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mReachedBarPaint.setColor(mReachedBarColor);
mUnreachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mUnreachedBarPaint.setColor(mUnreachedBarColor);
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setColor(mTextColor);
mTextPaint.setTextSize(mTextSize);
}
private void calculateDrawRectFWithoutProgressText(){
mReachedRectF.left = getPaddingLeft();
mReachedRectF.top = getHeight()/2.0f - mReachedBarHeight / 2.0f;
mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight() )/(getMax()*1.0f) * getProgress() + getPaddingLeft();
mReachedRectF.bottom = getHeight()/2.0f + mReachedBarHeight / 2.0f;
mUnreachedRectF.left = mReachedRectF.right;
mUnreachedRectF.right = getWidth() - getPaddingRight();
mUnreachedRectF.top = getHeight()/2.0f + - mUnreachedBarHeight / 2.0f;
mUnreachedRectF.bottom = getHeight()/2.0f + mUnreachedBarHeight / 2.0f;
}
private void calculateDrawRectF(){
mCurrentDrawText = String.format("%d" ,getProgress()*100/getMax());
mCurrentDrawText = mPrefix + mCurrentDrawText + mSuffix;
mDrawTextWidth = mTextPaint.measureText(mCurrentDrawText);
if(getProgress() == 0){
mDrawReachedBar = false;
mDrawTextStart = getPaddingLeft();
}else{
mDrawReachedBar = true;
mReachedRectF.left = getPaddingLeft();
mReachedRectF.top = getHeight()/2.0f - mReachedBarHeight / 2.0f;
mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight() )/(getMax()*1.0f) * getProgress() - mOffset + getPaddingLeft();
mReachedRectF.bottom = getHeight()/2.0f + mReachedBarHeight / 2.0f;
mDrawTextStart = (mReachedRectF.right + mOffset);
}
mDrawTextEnd = (int) ((getHeight() / 2.0f) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2.0f)) ;
if((mDrawTextStart + mDrawTextWidth )>= getWidth() - getPaddingRight()){
mDrawTextStart = getWidth() - getPaddingRight() - mDrawTextWidth;
mReachedRectF.right = mDrawTextStart - mOffset;
}
float unreachedBarStart = mDrawTextStart + mDrawTextWidth + mOffset;
if(unreachedBarStart >= getWidth() - getPaddingRight()){
mDrawUnreachedBar = false;
}else{
mDrawUnreachedBar = true;
mUnreachedRectF.left = unreachedBarStart;
mUnreachedRectF.right = getWidth() - getPaddingRight();
mUnreachedRectF.top = getHeight()/2.0f + - mUnreachedBarHeight / 2.0f;
mUnreachedRectF.bottom = getHeight()/2.0f + mUnreachedBarHeight / 2.0f;
}
}
/**
* get progress text color
* @return progress text color
*/
public int getTextColor() {
return mTextColor;
}
/**
* get progress text size
* @return progress text size
*/
public float getProgressTextSize() {
return mTextSize;
}
public int getUnreachedBarColor() {
return mUnreachedBarColor;
}
public int getReachedBarColor() {
return mReachedBarColor;
}
public int getProgress() {
return mProgress;
}
public int getMax() {
return mMax;
}
public float getReachedBarHeight(){
return mReachedBarHeight;
}
public float getUnreachedBarHeight(){
return mUnreachedBarHeight;
}
public void setProgressTextSize(float textSize) {
this.mTextSize = textSize;
mTextPaint.setTextSize(mTextSize);
invalidate();
}
public void setProgressTextColor(int textColor) {
this.mTextColor = textColor;
mTextPaint.setColor(mTextColor);
invalidate();
}
public void setUnreachedBarColor(int barColor) {
this.mUnreachedBarColor = barColor;
mUnreachedBarPaint.setColor(mReachedBarColor);
invalidate();
}
public void setReachedBarColor(int progressColor) {
this.mReachedBarColor = progressColor;
mReachedBarPaint.setColor(mReachedBarColor);
invalidate();
}
public void setReachedBarHeight(float height){
mReachedBarHeight = height;
}
public void setUnreachedBarHeight(float height){
mUnreachedBarHeight = height;
}
public void setMax(int max) {
if(max > 0){
this.mMax = max;
invalidate();
}
}
public void setSuffix(String suffix){
if(suffix == null){
mSuffix = "";
}else{
mSuffix = suffix;
}
}
public String getSuffix(){
return mSuffix;
}
public void setPrefix(String prefix){
if(prefix == null)
mPrefix = "";
else{
mPrefix = prefix;
}
}
public String getPrefix(){
return mPrefix;
}
public void incrementProgressBy(int by){
if(by > 0){
setProgress(getProgress() + by);
}
}
public void setProgress(int progress) {
if(progress <= getMax() && progress >= 0){
this.mProgress = progress;
invalidate();
}
}
@Override
protected Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable(INSTANCE_STATE,super.onSaveInstanceState());
bundle.putInt(INSTANCE_TEXT_COLOR,getTextColor());
bundle.putFloat(INSTANCE_TEXT_SIZE, getProgressTextSize());
bundle.putFloat(INSTANCE_REACHED_BAR_HEIGHT,getReachedBarHeight());
bundle.putFloat(INSTANCE_UNREACHED_BAR_HEIGHT,getUnreachedBarHeight());
bundle.putInt(INSTANCE_REACHED_BAR_COLOR,getReachedBarColor());
bundle.putInt(INSTANCE_UNREACHED_BAR_COLOR,getUnreachedBarColor());
bundle.putInt(INSTANCE_MAX,getMax());
bundle.putInt(INSTANCE_PROGRESS,getProgress());
bundle.putString(INSTANCE_SUFFIX,getSuffix());
bundle.putString(INSTANCE_PREFIX,getPrefix());
bundle.putBoolean(INSTANCE_TEXT_VISIBILITY, getProgressTextVisibility());
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if(state instanceof Bundle){
final Bundle bundle = (Bundle)state;
mTextColor = bundle.getInt(INSTANCE_TEXT_COLOR);
mTextSize = bundle.getFloat(INSTANCE_TEXT_SIZE);
mReachedBarHeight = bundle.getFloat(INSTANCE_REACHED_BAR_HEIGHT);
mUnreachedBarHeight = bundle.getFloat(INSTANCE_UNREACHED_BAR_HEIGHT);
mReachedBarColor = bundle.getInt(INSTANCE_REACHED_BAR_COLOR);
mUnreachedBarColor = bundle.getInt(INSTANCE_UNREACHED_BAR_COLOR);
initializePainters();
setMax(bundle.getInt(INSTANCE_MAX));
setProgress(bundle.getInt(INSTANCE_PROGRESS));
setPrefix(bundle.getString(INSTANCE_PREFIX));
setSuffix(bundle.getString(INSTANCE_SUFFIX));
setProgressTextVisibility(bundle.getBoolean(INSTANCE_TEXT_VISIBILITY) ? ProgressTextVisibility.Visible : ProgressTextVisibility.Invisible);
super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE));
return;
}
super.onRestoreInstanceState(state);
}
public float dp2px(float dp) {
final float scale = getResources().getDisplayMetrics().density;
return dp * scale + 0.5f;
}
public float sp2px(float sp){
final float scale = getResources().getDisplayMetrics().scaledDensity;
return sp * scale;
}
public void setProgressTextVisibility(ProgressTextVisibility visibility){
mIfDrawText = visibility == ProgressTextVisibility.Visible;
invalidate();
}
public boolean getProgressTextVisibility() {
return mIfDrawText;
}
}
|
library/src/main/java/com/daimajia/numberprogressbar/NumberProgressBar.java
|
package com.daimajia.numberprogressbar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by daimajia on 14-4-30.
*/
public class NumberProgressBar extends View {
/**
* The max progress, default is 100
*/
private int mMax = 100;
/**
* current progress, can not exceed the max progress.
*/
private int mProgress = 0;
/**
* the progress area bar color
*/
private int mReachedBarColor;
/**
* the bar unreached area color.
*/
private int mUnreachedBarColor;
/**
* the progress text color.
*/
private int mTextColor;
/**
* the progress text size
*/
private float mTextSize;
/**
* the height of the reached area
*/
private float mReachedBarHeight;
/**
* the height of the unreached area
*/
private float mUnreachedBarHeight;
/**
* the suffix of the number.
*/
private String mSuffix = "%";
/**
* the prefix.
*/
private String mPrefix = "";
private final int default_text_color = Color.rgb(66, 145, 241);
private final int default_reached_color = Color.rgb(66,145,241);
private final int default_unreached_color = Color.rgb(204, 204, 204);
private final float default_progress_text_offset;
private final float default_text_size;
private final float default_reached_bar_height;
private final float default_unreached_bar_height;
/**
* for save and restore instance of progressbar.
*/
private static final String INSTANCE_STATE = "saved_instance";
private static final String INSTANCE_TEXT_COLOR = "text_color";
private static final String INSTANCE_TEXT_SIZE = "text_size";
private static final String INSTANCE_REACHED_BAR_HEIGHT = "reached_bar_height";
private static final String INSTANCE_REACHED_BAR_COLOR = "reached_bar_color";
private static final String INSTANCE_UNREACHED_BAR_HEIGHT = "unreached_bar_height";
private static final String INSTANCE_UNREACHED_BAR_COLOR = "unreached_bar_color";
private static final String INSTANCE_MAX = "max";
private static final String INSTANCE_PROGRESS = "progress";
private static final String INSTANCE_SUFFIX = "suffix";
private static final String INSTANCE_PREFIX = "prefix";
private static final String INSTANCE_TEXT_VISIBILITY = "text_visibility";
private static final int PROGRESS_TEXT_VISIBLE = 0;
/**
* the width of the text that to be drawn
*/
private float mDrawTextWidth;
/**
* the drawn text start
*/
private float mDrawTextStart;
/**
*the drawn text end
*/
private float mDrawTextEnd;
/**
* the text that to be drawn in onDraw()
*/
private String mCurrentDrawText;
/**
* the Paint of the reached area.
*/
private Paint mReachedBarPaint;
/**
* the Painter of the unreached area.
*/
private Paint mUnreachedBarPaint;
/**
* the Painter of the progress text.
*/
private Paint mTextPaint;
/**
* Unreached Bar area to draw rect.
*/
private RectF mUnreachedRectF = new RectF(0,0,0,0);
/**
* reached bar area rect.
*/
private RectF mReachedRectF = new RectF(0,0,0,0);
/**
* the progress text offset.
*/
private float mOffset;
/**
* determine if need to draw unreached area
*/
private boolean mDrawUnreachedBar = true;
private boolean mDrawReachedBar = true;
private boolean mIfDrawText = true;
public enum ProgressTextVisibility{
Visible,Invisible
};
public NumberProgressBar(Context context) {
this(context, null);
}
public NumberProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.numberProgressBarStyle);
}
public NumberProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
default_reached_bar_height = dp2px(1.5f);
default_unreached_bar_height = dp2px(1.0f);
default_text_size = sp2px(10);
default_progress_text_offset = dp2px(3.0f);
//load styled attributes.
final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.NumberProgressBar,
defStyleAttr, 0);
mReachedBarColor = attributes.getColor(R.styleable.NumberProgressBar_progress_reached_color, default_reached_color);
mUnreachedBarColor = attributes.getColor(R.styleable.NumberProgressBar_progress_unreached_color,default_unreached_color);
mTextColor = attributes.getColor(R.styleable.NumberProgressBar_progress_text_color,default_text_color);
mTextSize = attributes.getDimension(R.styleable.NumberProgressBar_progress_text_size, default_text_size);
mReachedBarHeight = attributes.getDimension(R.styleable.NumberProgressBar_progress_reached_bar_height,default_reached_bar_height);
mUnreachedBarHeight = attributes.getDimension(R.styleable.NumberProgressBar_progress_unreached_bar_height,default_unreached_bar_height);
mOffset = attributes.getDimension(R.styleable.NumberProgressBar_progress_text_offset,default_progress_text_offset);
int textVisible = attributes.getInt(R.styleable.NumberProgressBar_progress_text_visibility,PROGRESS_TEXT_VISIBLE);
if(textVisible != PROGRESS_TEXT_VISIBLE){
mIfDrawText = false;
}
setProgress(attributes.getInt(R.styleable.NumberProgressBar_progress,0));
setMax(attributes.getInt(R.styleable.NumberProgressBar_max, 100));
//
attributes.recycle();
initializePainters();
}
@Override
protected int getSuggestedMinimumWidth() {
return (int)mTextSize;
}
@Override
protected int getSuggestedMinimumHeight() {
return Math.max((int)mTextSize,Math.max((int)mReachedBarHeight,(int)mUnreachedBarHeight));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measure(widthMeasureSpec,true), measure(heightMeasureSpec,false));
}
private int measure(int measureSpec,boolean isWidth){
int result;
int mode = MeasureSpec.getMode(measureSpec);
int size = MeasureSpec.getSize(measureSpec);
int padding = isWidth?getPaddingLeft()+getPaddingRight():getPaddingTop()+getPaddingBottom();
if(mode == MeasureSpec.EXACTLY){
result = size;
}else{
result = isWidth ? getSuggestedMinimumWidth() : getSuggestedMinimumHeight();
result += padding;
if(mode == MeasureSpec.AT_MOST){
if(isWidth) {
result = Math.max(result, size);
}
else{
result = Math.min(result, size);
}
}
}
return result;
}
@Override
protected void onDraw(Canvas canvas) {
if(mIfDrawText){
calculateDrawRectF();
}else{
calculateDrawRectFWithoutProgressText();
}
if(mDrawReachedBar){
canvas.drawRect(mReachedRectF,mReachedBarPaint);
}
if(mDrawUnreachedBar) {
canvas.drawRect(mUnreachedRectF, mUnreachedBarPaint);
}
if(mIfDrawText)
canvas.drawText(mCurrentDrawText,mDrawTextStart,mDrawTextEnd,mTextPaint);
}
private void initializePainters(){
mReachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mReachedBarPaint.setColor(mReachedBarColor);
mUnreachedBarPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mUnreachedBarPaint.setColor(mUnreachedBarColor);
mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setColor(mTextColor);
mTextPaint.setTextSize(mTextSize);
}
private void calculateDrawRectFWithoutProgressText(){
mReachedRectF.left = getPaddingLeft();
mReachedRectF.top = getHeight()/2.0f - mReachedBarHeight / 2.0f;
mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight() )/(getMax()*1.0f) * getProgress() + getPaddingLeft();
mReachedRectF.bottom = getHeight()/2.0f + mReachedBarHeight / 2.0f;
mUnreachedRectF.left = mReachedRectF.right;
mUnreachedRectF.right = getWidth() - getPaddingRight();
mUnreachedRectF.top = getHeight()/2.0f + - mUnreachedBarHeight / 2.0f;
mUnreachedRectF.bottom = getHeight()/2.0f + mUnreachedBarHeight / 2.0f;
}
private void calculateDrawRectF(){
mCurrentDrawText = String.format("%d" ,getProgress()*100/getMax());
mCurrentDrawText = mPrefix + mCurrentDrawText + mSuffix;
mDrawTextWidth = mTextPaint.measureText(mCurrentDrawText);
if(getProgress() == 0){
mDrawReachedBar = false;
mDrawTextStart = getPaddingLeft();
}else{
mDrawReachedBar = true;
mReachedRectF.left = getPaddingLeft();
mReachedRectF.top = getHeight()/2.0f - mReachedBarHeight / 2.0f;
mReachedRectF.right = (getWidth() - getPaddingLeft() - getPaddingRight() )/(getMax()*1.0f) * getProgress() - mOffset + getPaddingLeft();
mReachedRectF.bottom = getHeight()/2.0f + mReachedBarHeight / 2.0f;
mDrawTextStart = (mReachedRectF.right + mOffset);
}
mDrawTextEnd = (int) ((getHeight() / 2.0f) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2.0f)) ;
if((mDrawTextStart + mDrawTextWidth )>= getWidth() - getPaddingRight()){
mDrawTextStart = getWidth() - getPaddingRight() - mDrawTextWidth;
mReachedRectF.right = mDrawTextStart - mOffset;
}
float unreachedBarStart = mDrawTextStart + mDrawTextWidth + mOffset;
if(unreachedBarStart >= getWidth() - getPaddingRight()){
mDrawUnreachedBar = false;
}else{
mDrawUnreachedBar = true;
mUnreachedRectF.left = unreachedBarStart;
mUnreachedRectF.right = getWidth() - getPaddingRight();
mUnreachedRectF.top = getHeight()/2.0f + - mUnreachedBarHeight / 2.0f;
mUnreachedRectF.bottom = getHeight()/2.0f + mUnreachedBarHeight / 2.0f;
}
}
/**
* get progress text color
* @return progress text color
*/
public int getTextColor() {
return mTextColor;
}
/**
* get progress text size
* @return progress text size
*/
public float getProgressTextSize() {
return mTextSize;
}
public int getUnreachedBarColor() {
return mUnreachedBarColor;
}
public int getReachedBarColor() {
return mReachedBarColor;
}
public int getProgress() {
return mProgress;
}
public int getMax() {
return mMax;
}
public float getReachedBarHeight(){
return mReachedBarHeight;
}
public float getUnreachedBarHeight(){
return mUnreachedBarHeight;
}
public void setProgressTextSize(float TextSize) {
this.mTextSize = TextSize;
mTextPaint.setTextSize(mTextSize);
invalidate();
}
public void setProgressTextColor(int TextColor) {
this.mTextColor = TextColor;
mTextPaint.setColor(mTextColor);
invalidate();
}
public void setUnreachedBarColor(int BarColor) {
this.mUnreachedBarColor = BarColor;
mUnreachedBarPaint.setColor(mReachedBarColor);
invalidate();
}
public void setReachedBarColor(int ProgressColor) {
this.mReachedBarColor = ProgressColor;
mReachedBarPaint.setColor(mReachedBarColor);
invalidate();
}
public void setReachedBarHeight(float height){
mReachedBarHeight = height;
}
public void setUnreachedBarHeight(float height){
mUnreachedBarHeight = height;
}
public void setMax(int Max) {
if(Max > 0){
this.mMax = Max;
invalidate();
}
}
public void setSuffix(String suffix){
if(suffix == null){
mSuffix = "";
}else{
mSuffix = suffix;
}
}
public String getSuffix(){
return mSuffix;
}
public void setPrefix(String prefix){
if(prefix == null)
mPrefix = "";
else{
mPrefix = prefix;
}
}
public String getPrefix(){
return mPrefix;
}
public void incrementProgressBy(int by){
if(by > 0){
setProgress(getProgress() + by);
}
}
public void setProgress(int Progress) {
if(Progress <= getMax() && Progress >= 0){
this.mProgress = Progress;
invalidate();
}
}
@Override
protected Parcelable onSaveInstanceState() {
final Bundle bundle = new Bundle();
bundle.putParcelable(INSTANCE_STATE,super.onSaveInstanceState());
bundle.putInt(INSTANCE_TEXT_COLOR,getTextColor());
bundle.putFloat(INSTANCE_TEXT_SIZE, getProgressTextSize());
bundle.putFloat(INSTANCE_REACHED_BAR_HEIGHT,getReachedBarHeight());
bundle.putFloat(INSTANCE_UNREACHED_BAR_HEIGHT,getUnreachedBarHeight());
bundle.putInt(INSTANCE_REACHED_BAR_COLOR,getReachedBarColor());
bundle.putInt(INSTANCE_UNREACHED_BAR_COLOR,getUnreachedBarColor());
bundle.putInt(INSTANCE_MAX,getMax());
bundle.putInt(INSTANCE_PROGRESS,getProgress());
bundle.putString(INSTANCE_SUFFIX,getSuffix());
bundle.putString(INSTANCE_PREFIX,getPrefix());
bundle.putBoolean(INSTANCE_TEXT_VISIBILITY, getProgressTextVisibility());
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if(state instanceof Bundle){
final Bundle bundle = (Bundle)state;
mTextColor = bundle.getInt(INSTANCE_TEXT_COLOR);
mTextSize = bundle.getFloat(INSTANCE_TEXT_SIZE);
mReachedBarHeight = bundle.getFloat(INSTANCE_REACHED_BAR_HEIGHT);
mUnreachedBarHeight = bundle.getFloat(INSTANCE_UNREACHED_BAR_HEIGHT);
mReachedBarColor = bundle.getInt(INSTANCE_REACHED_BAR_COLOR);
mUnreachedBarColor = bundle.getInt(INSTANCE_UNREACHED_BAR_COLOR);
initializePainters();
setMax(bundle.getInt(INSTANCE_MAX));
setProgress(bundle.getInt(INSTANCE_PROGRESS));
setPrefix(bundle.getString(INSTANCE_PREFIX));
setSuffix(bundle.getString(INSTANCE_SUFFIX));
setProgressTextVisibility(bundle.getBoolean(INSTANCE_TEXT_VISIBILITY) ? ProgressTextVisibility.Visible : ProgressTextVisibility.Invisible);
super.onRestoreInstanceState(bundle.getParcelable(INSTANCE_STATE));
return;
}
super.onRestoreInstanceState(state);
}
public float dp2px(float dp) {
final float scale = getResources().getDisplayMetrics().density;
return dp * scale + 0.5f;
}
public float sp2px(float sp){
final float scale = getResources().getDisplayMetrics().scaledDensity;
return sp * scale;
}
public void setProgressTextVisibility(ProgressTextVisibility visibility){
mIfDrawText = visibility == ProgressTextVisibility.Visible;
invalidate();
}
public boolean getProgressTextVisibility() {
return mIfDrawText;
}
}
|
rename arguments to meet Java naming convention
|
library/src/main/java/com/daimajia/numberprogressbar/NumberProgressBar.java
|
rename arguments to meet Java naming convention
|
|
Java
|
mit
|
0eec71a08c59f7969ebf0f75902dcb76bf001900
| 0
|
joansmith/ontrack,dcoraboeuf/ontrack,joansmith/ontrack,dcoraboeuf/ontrack,dcoraboeuf/ontrack,joansmith/ontrack,joansmith/ontrack,joansmith/ontrack,dcoraboeuf/ontrack
|
package net.ontrack.client.support;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.netbeetle.jackson.ObjectMapperFactory;
import net.ontrack.client.Client;
import net.ontrack.core.model.Ack;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public abstract class AbstractClient implements Client {
private final String url;
private final DefaultHttpClient client;
public AbstractClient(String url) {
this.url = url;
this.client = new DefaultHttpClient(new PoolingClientConnectionManager());
}
public String getUrl() {
return url;
}
@Override
public void logout() {
// Executes the call
request(new HttpGet(getUrl("/logout")), new NOPResponseHandler());
}
@Override
public void login(String name, String password) {
// Forces the logout
logout();
// Configures the client for the credentials
client.getCredentialsProvider().setCredentials(
new AuthScope(null, -1),
new UsernamePasswordCredentials(name, password));
// Gets the server to send a challenge back
get("/ui/login", Ack.class);
}
protected <T> T get(String path, Class<T> returnType) {
return request(new HttpGet(getUrl(path)), returnType);
}
protected <T> List<T> list(final String path, final Class<T> elementType) {
return request(new HttpGet(getUrl(path)), new ResponseParser<List<T>>() {
@Override
public List<T> parse(final String content) throws IOException {
final ObjectMapper mapper = ObjectMapperFactory.createObjectMapper();
JsonNode node = mapper.readTree(content);
if (node.isArray()) {
return Lists.newArrayList(
Iterables.transform(node, new Function<JsonNode, T>() {
@Override
public T apply(JsonNode input) {
try {
return mapper.readValue(input, elementType);
} catch (IOException e) {
throw new ClientGeneralException(path, e);
}
}
})
);
} else {
throw new IOException("Did not receive a JSON array");
}
}
});
}
protected <T> T put(String path, Class<T> returnType) {
return request(new HttpPut(getUrl(path)), returnType);
}
protected <T> T post(String path, Class<T> returnType, Map<String, String> parameters) {
HttpPost post = new HttpPost(getUrl(path));
if (parameters != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> param : parameters.entrySet()) {
nvps.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
try {
post.setEntity(new UrlEncodedFormEntity(nvps));
} catch (UnsupportedEncodingException e) {
throw new ClientGeneralException(post, e);
}
}
return request(post, returnType);
}
protected <T> T post(String path, Class<T> returnType, Object body) {
HttpPost post = new HttpPost(getUrl(path));
if (body != null) {
try {
String json = ObjectMapperFactory.createObjectMapper().writeValueAsString(body);
post.setEntity(new StringEntity(json, ContentType.create("application/json", "UTF-8")));
} catch (IOException e) {
throw new ClientGeneralException(post, e);
}
}
return request(post, returnType);
}
protected <T> T delete(String path, Class<T> returnType) {
return request(new HttpDelete(getUrl(path)), returnType);
}
protected String getUrl(String path) {
return url + path;
}
protected <T> T request(HttpRequestBase request, Class<T> returnType) {
return request(request, new SimpleTypeResponseParser<T>(returnType));
}
protected <T> T request(HttpRequestBase request, final ResponseParser<T> responseParser) {
return request(request, new BaseResponseHandler<T>() {
@Override
protected T handleEntity(HttpEntity entity) throws ParseException, IOException {
// Gets the content as a JSON string
String content = EntityUtils.toString(entity, "UTF-8");
// Parses the response
return responseParser.parse(content);
}
});
}
protected <T> T request(HttpRequestBase request, ResponseHandler<T> responseHandler) {
// Executes the call
try {
HttpResponse response = client.execute(request);
// Entity response
HttpEntity entity = response.getEntity();
try {
return responseHandler.handleResponse(request, response, entity);
} finally {
EntityUtils.consume(entity);
}
} catch (IOException e) {
throw new ClientGeneralException(request, e);
} finally {
request.releaseConnection();
}
}
protected static interface ResponseParser<T> {
T parse(String content) throws IOException;
}
protected static interface ResponseHandler<T> {
T handleResponse(HttpRequestBase request, HttpResponse response, HttpEntity entity) throws ParseException, IOException;
}
protected static class NullResponseParser<T> implements ResponseParser<Object> {
public static final NullResponseParser<Object> INSTANCE = new NullResponseParser<Object>();
@Override
public Object parse(String content) throws IOException {
return null;
}
}
protected static class StringResponseParser<T> implements ResponseParser<String> {
public static final StringResponseParser INSTANCE = new StringResponseParser();
@Override
public String parse(String content) throws IOException {
return content;
}
}
protected static class SimpleTypeResponseParser<T> implements ResponseParser<T> {
private final Class<T> type;
public SimpleTypeResponseParser(Class<T> type) {
this.type = type;
}
@Override
public T parse(String content) throws IOException {
ObjectMapper mapper = ObjectMapperFactory.createObjectMapper();
return mapper.readValue(content, type);
}
}
protected static class NOPResponseHandler implements ResponseHandler<Void> {
@Override
public Void handleResponse(HttpRequestBase request, HttpResponse response, HttpEntity entity) throws ParseException, IOException {
return null;
}
}
protected static abstract class BaseResponseHandler<T> implements ResponseHandler<T> {
@Override
public T handleResponse(HttpRequestBase request, HttpResponse response, HttpEntity entity) throws ParseException, IOException {
// Parses the response
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
return handleEntity(entity);
} else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
throw new ClientCannotLoginException(request);
} else if (statusCode == HttpStatus.SC_FORBIDDEN) {
throw new ClientForbiddenException(request);
} else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
if (StringUtils.isNotBlank(content)) {
throw new ClientMessageException(content);
} else {
// Generic error
throw new ClientServerException(
request,
statusCode,
response.getStatusLine().getReasonPhrase());
}
} else {
// Generic error
throw new ClientServerException(
request,
statusCode,
response.getStatusLine().getReasonPhrase());
}
}
protected abstract T handleEntity(HttpEntity entity) throws ParseException, IOException;
}
}
|
ontrack-client/src/main/java/net/ontrack/client/support/AbstractClient.java
|
package net.ontrack.client.support;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.netbeetle.jackson.ObjectMapperFactory;
import net.ontrack.client.Client;
import net.ontrack.core.model.Ack;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public abstract class AbstractClient implements Client {
private final String url;
private final DefaultHttpClient client;
public AbstractClient(String url) {
this.url = url;
this.client = new DefaultHttpClient();
}
public String getUrl() {
return url;
}
@Override
public void logout() {
// Executes the call
request(new HttpGet(getUrl("/logout")), new NOPResponseHandler());
}
@Override
public void login(String name, String password) {
// Forces the logout
logout();
// Configures the client for the credentials
client.getCredentialsProvider().setCredentials(
new AuthScope(null, -1),
new UsernamePasswordCredentials(name, password));
// Gets the server to send a challenge back
get("/ui/login", Ack.class);
}
protected <T> T get(String path, Class<T> returnType) {
return request(new HttpGet(getUrl(path)), returnType);
}
protected <T> List<T> list(final String path, final Class<T> elementType) {
return request(new HttpGet(getUrl(path)), new ResponseParser<List<T>>() {
@Override
public List<T> parse(final String content) throws IOException {
final ObjectMapper mapper = ObjectMapperFactory.createObjectMapper();
JsonNode node = mapper.readTree(content);
if (node.isArray()) {
return Lists.newArrayList(
Iterables.transform(node, new Function<JsonNode, T>() {
@Override
public T apply(JsonNode input) {
try {
return mapper.readValue(input, elementType);
} catch (IOException e) {
throw new ClientGeneralException(path, e);
}
}
})
);
} else {
throw new IOException("Did not receive a JSON array");
}
}
});
}
protected <T> T put(String path, Class<T> returnType) {
return request(new HttpPut(getUrl(path)), returnType);
}
protected <T> T post(String path, Class<T> returnType, Map<String, String> parameters) {
HttpPost post = new HttpPost(getUrl(path));
if (parameters != null) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> param : parameters.entrySet()) {
nvps.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
try {
post.setEntity(new UrlEncodedFormEntity(nvps));
} catch (UnsupportedEncodingException e) {
throw new ClientGeneralException(post, e);
}
}
return request(post, returnType);
}
protected <T> T post(String path, Class<T> returnType, Object body) {
HttpPost post = new HttpPost(getUrl(path));
if (body != null) {
try {
String json = ObjectMapperFactory.createObjectMapper().writeValueAsString(body);
post.setEntity(new StringEntity(json, ContentType.create("application/json", "UTF-8")));
} catch (IOException e) {
throw new ClientGeneralException(post, e);
}
}
return request(post, returnType);
}
protected <T> T delete(String path, Class<T> returnType) {
return request(new HttpDelete(getUrl(path)), returnType);
}
protected String getUrl(String path) {
return url + path;
}
protected <T> T request(HttpRequestBase request, Class<T> returnType) {
return request(request, new SimpleTypeResponseParser<T>(returnType));
}
protected <T> T request(HttpRequestBase request, final ResponseParser<T> responseParser) {
return request(request, new BaseResponseHandler<T>() {
@Override
protected T handleEntity(HttpEntity entity) throws ParseException, IOException {
// Gets the content as a JSON string
String content = EntityUtils.toString(entity, "UTF-8");
// Parses the response
return responseParser.parse(content);
}
});
}
protected <T> T request(HttpRequestBase request, ResponseHandler<T> responseHandler) {
// Executes the call
try {
HttpResponse response = client.execute(request);
// Entity response
HttpEntity entity = response.getEntity();
try {
return responseHandler.handleResponse(request, response, entity);
} finally {
EntityUtils.consume(entity);
}
} catch (IOException e) {
throw new ClientGeneralException(request, e);
} finally {
request.releaseConnection();
}
}
protected static interface ResponseParser<T> {
T parse(String content) throws IOException;
}
protected static interface ResponseHandler<T> {
T handleResponse(HttpRequestBase request, HttpResponse response, HttpEntity entity) throws ParseException, IOException;
}
protected static class NullResponseParser<T> implements ResponseParser<Object> {
public static final NullResponseParser<Object> INSTANCE = new NullResponseParser<Object>();
@Override
public Object parse(String content) throws IOException {
return null;
}
}
protected static class StringResponseParser<T> implements ResponseParser<String> {
public static final StringResponseParser INSTANCE = new StringResponseParser();
@Override
public String parse(String content) throws IOException {
return content;
}
}
protected static class SimpleTypeResponseParser<T> implements ResponseParser<T> {
private final Class<T> type;
public SimpleTypeResponseParser(Class<T> type) {
this.type = type;
}
@Override
public T parse(String content) throws IOException {
ObjectMapper mapper = ObjectMapperFactory.createObjectMapper();
return mapper.readValue(content, type);
}
}
protected static class NOPResponseHandler implements ResponseHandler<Void> {
@Override
public Void handleResponse(HttpRequestBase request, HttpResponse response, HttpEntity entity) throws ParseException, IOException {
return null;
}
}
protected static abstract class BaseResponseHandler<T> implements ResponseHandler<T> {
@Override
public T handleResponse(HttpRequestBase request, HttpResponse response, HttpEntity entity) throws ParseException, IOException {
// Parses the response
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
return handleEntity(entity);
} else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
throw new ClientCannotLoginException(request);
} else if (statusCode == HttpStatus.SC_FORBIDDEN) {
throw new ClientForbiddenException(request);
} else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
if (StringUtils.isNotBlank(content)) {
throw new ClientMessageException(content);
} else {
// Generic error
throw new ClientServerException(
request,
statusCode,
response.getStatusLine().getReasonPhrase());
}
} else {
// Generic error
throw new ClientServerException(
request,
statusCode,
response.getStatusLine().getReasonPhrase());
}
}
protected abstract T handleEntity(HttpEntity entity) throws ParseException, IOException;
}
}
|
Client: better management of the http connections
|
ontrack-client/src/main/java/net/ontrack/client/support/AbstractClient.java
|
Client: better management of the http connections
|
|
Java
|
mit
|
91d6a413ee0ccaecdd0569a3c49f3a439bfceb6b
| 0
|
akonring/multibit-hd-modified,bitcoin-solutions/multibit-hd,akonring/multibit-hd-modified,akonring/multibit-hd-modified,bitcoin-solutions/multibit-hd,bitcoin-solutions/multibit-hd
|
package org.multibit.hd.core.managers;
/**
* Copyright 2015 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.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.
*/
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.Uninterruptibles;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Wallet;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.wallet.KeyChain;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.multibit.commons.files.SecureFiles;
import org.multibit.commons.utils.Dates;
import org.multibit.hd.brit.core.seed_phrase.Bip39SeedPhraseGenerator;
import org.multibit.hd.brit.core.seed_phrase.SeedPhraseGenerator;
import org.multibit.hd.core.config.Configurations;
import org.multibit.hd.core.crypto.EncryptedFileReaderWriter;
import org.multibit.hd.core.dto.*;
import org.multibit.hd.core.events.ShutdownEvent;
import org.multibit.hd.core.extensions.WalletTypeExtension;
import org.multibit.hd.core.services.CoreServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.crypto.params.KeyParameter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.fest.assertions.Assertions.assertThat;
public class WalletManagerTest {
private static final Logger log = LoggerFactory.getLogger(WalletManagerTest.class);
private final static String WALLET_DIRECTORY_1 = "mbhd-11111111-22222222-33333333-44444444-55555555";
private final static String WALLET_DIRECTORY_2 = "mbhd-66666666-77777777-88888888-99999999-aaaaaaaa";
private final static String EXPECTED_WALLET_ID_1 = "11111111-22222222-33333333-44444444-55555555";
private final static String EXPECTED_WALLET_ID_2 = "66666666-77777777-88888888-99999999-aaaaaaaa";
private final static String INVALID_WALLET_DIRECTORY_1 = "not-mbhd-66666666-77777777-88888888-99999999-aaaaaaaa";
private final static String INVALID_WALLET_DIRECTORY_2 = "mbhd-66666666-77777777-88888888-99999999-gggggggg";
private final static String INVALID_WALLET_DIRECTORY_3 = "mbhd-1166666666-77777777-88888888-99999999-aaaaaaaa";
private final static String SIGNING_PASSWORD = "throgmorton999";
private final static String MESSAGE_TO_SIGN = "The quick brown fox jumps over the lazy dog.\n1234567890!@#$%^&*()";
private final static String SHORT_PASSWORD = "a"; // 1
private final static String MEDIUM_PASSWORD = "abcefghijklm"; // 12
private final static String LONG_PASSWORD = "abcefghijklmnopqrstuvwxyz"; // 26
private final static String LONGER_PASSWORD = "abcefghijklmnopqrstuvwxyz1234567890"; // 36
private final static String LONGEST_PASSWORD = "abcefghijklmnopqrstuvwxyzabcefghijklmnopqrstuvwxyz"; // 52
/**
* The seed phrase for the Trezor 'Abandon' wallet
*/
public final static String TREZOR_SEED_PHRASE = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
// The generated Trezor addresses for the 'Abandon' wallet
public final static String TREZOR_ADDRESS_M_44H_0H_0H_0_0 = "1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA"; // Receiving funds
public final static String TREZOR_ADDRESS_M_44H_0H_0H_1_0 = "1J3J6EvPrv8q6AC3VCjWV45Uf3nssNMRtH"; // Change
public final static String TREZOR_ADDRESS_M_44H_0H_0H_0_1 = "1Ak8PffB2meyfYnbXZR9EGfLfFZVpzJvQP";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_1_1 = "13vKxXzHXXd8HquAYdpkJoi9ULVXUgfpS5";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_0_2 = "1MNF5RSaabFwcbtJirJwKnDytsXXEsVsNb";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_1_2 = "1M21Wx1nGrHMPaz52N2En7c624nzL4MYTk";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_0_3 = "1MVGa13XFvvpKGZdX389iU8b3qwtmAyrsJ";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_1_3 = "1DzVLMA4HzjXPAr6aZoaacDPHXXntsZ2zL";
/**
* The 'skin' seed phrase used in the issue: https://github.com/bitcoin-solutions/multibit-hd/issues/445
*/
public static final String SKIN_SEED_PHRASE = "skin join dog sponsor camera puppy ritual diagram arrow poverty boy elbow";
// The receiving address being generated in Beta 7 and previous MBHD (not BIP32 compliant)
private static final String NON_COMPLIANT_SKIN_ADDRESS_M_0H_0_0 = "1LQ8XnNKqC7Vu7atH5k4X8qVCc9ug2q7WE";
// The correct BIP32 addresses, generated from https://dcpos.github.io/bip39/ with the skin seed and derivation path m/0'/0
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_0 = "12QxtuyEM8KBG3ngNRe2CZE28hFw3b1KMJ";
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_1 = "16mN2Bjap7vSb6Cp4sjV3BrUiCMP3ixo5A";
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_2 = "1LrC33bZVTHTHMqw8p1NWUoHVArKFwB3mp";
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_3 = "17Czu38CcLwWr8jFZrDJBHWiEDd2QWhPSU";
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_4 = "18dbiNgyHKEY4TtynEDZGEDhS9fdYqeZWG";
private NetworkParameters mainNet;
@SuppressFBWarnings({"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", "NP_NONNULL_PARAM_VIOLATION"})
@Before
public void setUp() throws Exception {
InstallationManager.unrestricted = true;
Configurations.currentConfiguration = Configurations.newDefaultConfiguration();
// Start the core services
CoreServices.main(null);
mainNet = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
assertThat(mainNet).isNotNull();
}
@After
public void tearDown() throws Exception {
// Order is important here
CoreServices.shutdownNow(ShutdownEvent.ShutdownType.SOFT);
InstallationManager.shutdownNow(ShutdownEvent.ShutdownType.SOFT);
BackupManager.INSTANCE.shutdownNow();
WalletManager.INSTANCE.shutdownNow(ShutdownEvent.ShutdownType.HARD);
}
@Ignore
public void testCreateWallet() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary1 = walletManager
.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory,
entropy,
seed,
nowInSeconds,
"credentials",
"Example",
"Example",
false); // No need to sync
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Uncomment this next line if you want a wallet created in your MultiBitHD user data directory.
//walletManager.createWallet( seed, "credentials");
assertThat(walletSummary1).isNotNull();
// Create another wallet - it should have the same wallet id and the private key should be the same
File applicationDirectory2 = SecureFiles.createTemporaryDirectory();
BackupManager.INSTANCE.initialise(applicationDirectory2, Optional.<File>absent());
WalletSummary walletSummary2 = walletManager
.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory2,
entropy,
seed,
nowInSeconds,
"credentials",
"Example",
"Example",
false); // No need to sync
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(walletSummary2).isNotNull();
ECKey key1 = walletSummary1.getWallet().freshReceiveKey();
ECKey key2 = walletSummary2.getWallet().freshReceiveKey();
assertThat(key1).isEqualTo(key2);
File expectedFile = new File(
applicationDirectory2.getAbsolutePath()
+ File.separator
+ "mbhd-"
+ walletSummary2.getWalletId().toFormattedString()
+ File.separator
+ WalletManager.MBHD_WALLET_NAME
+ WalletManager.MBHD_AES_SUFFIX
);
assertThat(expectedFile.exists()).isTrue();
assertThat(WalletType.MBHD_SOFT_WALLET_BIP32.equals(walletSummary1.getWalletType()));
assertThat(WalletType.MBHD_SOFT_WALLET_BIP32.equals(walletSummary2.getWalletType()));
}
@Test
/**
* Test creation of a Trezor (soft) wallet.
*/
public void testCreateSoftTrezorWallet() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary = walletManager.getOrCreateTrezorSoftWalletSummaryFromSeedPhrase(
applicationDirectory,
TREZOR_SEED_PHRASE,
nowInSeconds,
"aPassword",
"Abandon",
"Abandon", true);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(walletSummary).isNotNull();
assertThat(WalletType.TREZOR_SOFT_WALLET.equals(walletSummary.getWalletType()));
// Check that the generated addresses match the list of addresses you get directly from the Trezor
// (Either from myTrezor.com or from the multibit-hardware test TrezorV1GetAddressExample)
Wallet trezorWallet = walletSummary.getWallet();
DeterministicKey trezorKeyM44H_0H_0H_0_0 = trezorWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
String addressM44H_0H_0H_0_0 = trezorKeyM44H_0H_0H_0_0.toAddress(mainNet).toString();
log.debug("WalletManagerTest - trezorKeyM44H_0H_0H_0_0 = " + trezorKeyM44H_0H_0H_0_0.toString());
log.debug("WalletManagerTest - addressM44H_0H_0H_0_0 = " + addressM44H_0H_0H_0_0);
DeterministicKey trezorKeyM44H_0H_0H_1_0 = trezorWallet.freshKey(KeyChain.KeyPurpose.CHANGE);
String addressM44H_0H_0H_1_0 = trezorKeyM44H_0H_0H_1_0.toAddress(mainNet).toString();
log.debug("WalletManagerTest - trezorKeyM44H_0H_0H_1_0 = " + trezorKeyM44H_0H_0H_1_0.toString());
log.debug("WalletManagerTest - addressM44H_0H_0H_1_0 = " + addressM44H_0H_0H_1_0);
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_0_0.equals(addressM44H_0H_0H_0_0)).isTrue();
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_1_0.equals(addressM44H_0H_0H_1_0)).isTrue();
Address trezorAddressM44H_0H_0H_0_1 = trezorWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
Address trezorAddressM44H_0H_0H_1_1 = trezorWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_0_1.equals(trezorAddressM44H_0H_0H_0_1.toString())).isTrue();
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_1_1.equals(trezorAddressM44H_0H_0H_1_1.toString())).isTrue();
Address trezorAddressM44H_0H_0H_0_2 = trezorWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
Address trezorAddressM44H_0H_0H_1_2 = trezorWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_0_2.equals(trezorAddressM44H_0H_0H_0_2.toString())).isTrue();
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_1_2.equals(trezorAddressM44H_0H_0H_1_2.toString())).isTrue();
Address trezorAddressM44H_0H_0H_0_3 = trezorWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
Address trezorAddressM44H_0H_0H_1_3 = trezorWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_0_3.equals(trezorAddressM44H_0H_0H_0_3.toString())).isTrue();
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_1_3.equals(trezorAddressM44H_0H_0H_1_3.toString())).isTrue();
log.debug("Original trezor wallet, number of keys: " + trezorWallet.getActiveKeychain().numKeys());
log.debug("Original trezor wallet : {}", trezorWallet.toString());
// Check the wallet can be reloaded ok i.e. the protobuf round trips
File temporaryFile = File.createTempFile("WalletManagerTest", ".wallet");
trezorWallet.saveToFile(temporaryFile);
File encryptedWalletFile = EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(temporaryFile, "aPassword");
Wallet rebornWallet = WalletManager.INSTANCE.loadWalletFromFile(encryptedWalletFile, "aPassword");
log.debug("Reborn trezor wallet, number of keys: " + rebornWallet.getActiveKeychain().numKeys());
log.debug("Reborn trezor wallet : {}", rebornWallet.toString());
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Check the first keys above are in the wallet
assertThat(rebornWallet.hasKey(trezorKeyM44H_0H_0H_0_0)).isTrue();
assertThat(rebornWallet.hasKey(trezorKeyM44H_0H_0H_1_0)).isTrue();
// Create a fresh receiving and change address
Address freshReceivingAddress = rebornWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertThat(freshReceivingAddress).isNotNull();
Address freshChangeAddress = rebornWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(freshChangeAddress).isNotNull();
log.debug("Reborn trezor wallet with more keys, number of keys: " + rebornWallet.getActiveKeychain().numKeys());
log.debug("Reborn trezor wallet with more keys : {}", rebornWallet.toString());
// Round trip it again
File temporaryFile2 = File.createTempFile("WalletManagerTest2", ".wallet");
rebornWallet.saveToFile(temporaryFile2);
File encryptedWalletFile2 = EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(temporaryFile2, "aPassword2");
Wallet rebornWallet2 = WalletManager.INSTANCE.loadWalletFromFile(encryptedWalletFile2, "aPassword2");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Check the first keys above are in the wallet
assertThat(rebornWallet2.hasKey(trezorKeyM44H_0H_0H_0_0)).isTrue();
assertThat(rebornWallet2.hasKey(trezorKeyM44H_0H_0H_1_0)).isTrue();
}
@Test
/**
* Test creation of an MBHD soft wallet with the 'skin' seed phrase
* This replicates the non-BIP32 compliant code we have at the moment
*/
public void testCreateSkinSeedPhraseWalletInABadWay() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(SKIN_SEED_PHRASE));
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary = walletManager.badlyGetOrCreateMBHDSoftWalletSummaryFromSeed(
applicationDirectory,
seed,
nowInSeconds,
"aPassword",
"Skin",
"Skin", true);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(walletSummary).isNotNull();
assertThat(WalletType.MBHD_SOFT_WALLET.equals(walletSummary.getWalletType()));
// Check that the generated addresses match the expected
Wallet skinWallet = walletSummary.getWallet();
DeterministicKey skinKeyM0H_0_0 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_1 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_2 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_3 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_4 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
String skinAddressM0H_0_0 = skinKeyM0H_0_0.toAddress(mainNet).toString();
String skinAddressM0H_0_1 = skinKeyM0H_0_1.toAddress(mainNet).toString();
String skinAddressM0H_0_2 = skinKeyM0H_0_2.toAddress(mainNet).toString();
String skinAddressM0H_0_3 = skinKeyM0H_0_3.toAddress(mainNet).toString();
String skinAddressM0H_0_4 = skinKeyM0H_0_4.toAddress(mainNet).toString();
log.debug("WalletManagerTest - BAD skinAddressM0H_0_0 = {}", skinAddressM0H_0_0);
log.debug("WalletManagerTest - BAD skinAddressM0H_0_1 = {}", skinAddressM0H_0_1);
log.debug("WalletManagerTest - BAD skinAddressM0H_0_2 = {}", skinAddressM0H_0_2);
log.debug("WalletManagerTest - BAD skinAddressM0H_0_3 = {}", skinAddressM0H_0_3);
log.debug("WalletManagerTest - BAD skinAddressM0H_0_4 = {}", skinAddressM0H_0_4);
// This test passes now but the address is incorrect in real life - not BIP32 compliant
assertThat(NON_COMPLIANT_SKIN_ADDRESS_M_0H_0_0.equals(skinAddressM0H_0_0)).isTrue();
// These asserts should all be isTrue were the wallet BIP32 complaint - the addresses in MBHD wallets are currently wrong
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_0.equals(skinAddressM0H_0_0)).isFalse();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_1.equals(skinAddressM0H_0_1)).isFalse();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_2.equals(skinAddressM0H_0_2)).isFalse();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_3.equals(skinAddressM0H_0_3)).isFalse();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_4.equals(skinAddressM0H_0_4)).isFalse();
}
@Test
/**
* Test creation of an MBHD soft wallet with the 'skin' seed phrase
* This constructs a BIP32 compliant wallet
*/
public void testCreateSkinSeedPhraseWalletInAGoodWay() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Bip39SeedPhraseGenerator.split(SKIN_SEED_PHRASE));
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(SKIN_SEED_PHRASE));
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary = walletManager.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory,
entropy,
seed,
nowInSeconds,
"aPassword",
"Skin",
"Skin", true);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(walletSummary).isNotNull();
assertThat(WalletType.MBHD_SOFT_WALLET_BIP32.equals(walletSummary.getWalletType()));
// Check that the generated addresses match the expected
Wallet skinWallet = walletSummary.getWallet();
DeterministicKey skinKeyM0H_0_0 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_1 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_2 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_3 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_4 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
String skinAddressM0H_0_0 = skinKeyM0H_0_0.toAddress(mainNet).toString();
String skinAddressM0H_0_1 = skinKeyM0H_0_1.toAddress(mainNet).toString();
String skinAddressM0H_0_2 = skinKeyM0H_0_2.toAddress(mainNet).toString();
String skinAddressM0H_0_3 = skinKeyM0H_0_3.toAddress(mainNet).toString();
String skinAddressM0H_0_4 = skinKeyM0H_0_4.toAddress(mainNet).toString();
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_0 = {}", skinAddressM0H_0_0);
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_1 = {}", skinAddressM0H_0_1);
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_2 = {}", skinAddressM0H_0_2);
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_3 = {}", skinAddressM0H_0_3);
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_4 = {}", skinAddressM0H_0_4);
// This is the Beta 7 address that was not BIP32 compliant
assertThat(NON_COMPLIANT_SKIN_ADDRESS_M_0H_0_0.equals(skinAddressM0H_0_0)).isFalse();
// These are BIP32 compliant addresses
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_0.equals(skinAddressM0H_0_0)).isTrue();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_1.equals(skinAddressM0H_0_1)).isTrue();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_2.equals(skinAddressM0H_0_2)).isTrue();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_3.equals(skinAddressM0H_0_3)).isTrue();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_4.equals(skinAddressM0H_0_4)).isTrue();
// Check the wallet can be reloaded ok i.e. the protobuf round trips
File temporaryFile = File.createTempFile("WalletManagerTest", ".wallet");
skinWallet.saveToFile(temporaryFile);
File encryptedWalletFile = EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(temporaryFile, "aPassword");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
Wallet rebornWallet = WalletManager.INSTANCE.loadWalletFromFile(encryptedWalletFile, "aPassword");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
log.debug("Reborn skin wallet, number of keys: " + rebornWallet.getActiveKeychain().numKeys());
log.debug("Reborn skin wallet : {}", rebornWallet.toString());
// Check the first keys above are in the wallet
assertThat(rebornWallet.hasKey(skinKeyM0H_0_0)).isTrue();
assertThat(rebornWallet.hasKey(skinKeyM0H_0_1)).isTrue();
// Create a fresh receiving and change address
Address freshReceivingAddress = rebornWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertThat(freshReceivingAddress).isNotNull();
Address freshChangeAddress = rebornWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(freshChangeAddress).isNotNull();
log.debug("Reborn skin wallet with more keys, number of keys: " + rebornWallet.getActiveKeychain().numKeys());
log.debug("Reborn skin wallet with more keys : {}", rebornWallet.toString());
// Round trip it again
File temporaryFile2 = File.createTempFile("WalletManagerTest2", ".wallet");
rebornWallet.saveToFile(temporaryFile2);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
File encryptedWalletFile2 = EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(temporaryFile2, "aPassword2");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
Wallet rebornWallet2 = WalletManager.INSTANCE.loadWalletFromFile(encryptedWalletFile2, "aPassword2");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Check the first keys above are in the wallet
assertThat(rebornWallet2.hasKey(skinKeyM0H_0_0)).isTrue();
assertThat(rebornWallet2.hasKey(skinKeyM0H_0_0)).isTrue();
}
@Test
public void testBackwardsCompatibility_MBHD_SOFT_WALLET_BIP32() throws Exception {
backwardsCompatibilityCheck("/wallets/MBHD_SOFT_WALLET_BIP32.wallet.aes", "abc123", WalletType.MBHD_SOFT_WALLET_BIP32);
}
@Test
public void testBackwardsCompatibility_MBHD_SOFT_WALLET() throws Exception {
backwardsCompatibilityCheck("/wallets/MBHD_SOFT_WALLET.wallet.aes", "abc123", WalletType.MBHD_SOFT_WALLET);
}
private void backwardsCompatibilityCheck(String walletLocation, String password, WalletType expectedWalletType) throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
// Copy the extant test wallet to the application directory
copyTestWallet(walletLocation, applicationDirectory);
File walletFile = new File(applicationDirectory.getAbsolutePath() + "/mbhd.wallet.aes");
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
Wallet wallet = walletManager.loadWalletFromFile(walletFile, password);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(wallet).isNotNull();
WalletTypeExtension probeWalletTypeExtension = new WalletTypeExtension();
WalletTypeExtension existingWalletTypeExtension = (WalletTypeExtension) wallet.addOrGetExistingExtension(probeWalletTypeExtension);
assertThat(expectedWalletType.equals(existingWalletTypeExtension.getWalletType()));
}
@Test
public void testFindWalletDirectories() throws Exception {
// Create a random temporary directory
File temporaryDirectory = SecureFiles.createTemporaryDirectory();
File walletDirectory1 = SecureFiles.verifyOrCreateDirectory(temporaryDirectory, WALLET_DIRECTORY_1);
File walletDirectory2 = SecureFiles.verifyOrCreateDirectory(temporaryDirectory, WALLET_DIRECTORY_2);
SecureFiles.verifyOrCreateDirectory(temporaryDirectory, INVALID_WALLET_DIRECTORY_1);
SecureFiles.verifyOrCreateDirectory(temporaryDirectory, INVALID_WALLET_DIRECTORY_2);
SecureFiles.verifyOrCreateDirectory(temporaryDirectory, INVALID_WALLET_DIRECTORY_3);
List<File> walletDirectories = WalletManager.findWalletDirectories(temporaryDirectory);
assertThat(walletDirectories).isNotNull();
assertThat(walletDirectories.size()).isEqualTo(2);
// Order of discovery is not guaranteed
boolean foundWalletPath1First = walletDirectories.get(0).getAbsolutePath().equals(walletDirectory1.getAbsolutePath());
if (foundWalletPath1First) {
assertThat(walletDirectories.get(0).getAbsolutePath()).isEqualTo(walletDirectory1.getAbsolutePath());
assertThat(walletDirectories.get(1).getAbsolutePath()).isEqualTo(walletDirectory2.getAbsolutePath());
} else {
assertThat(walletDirectories.get(1).getAbsolutePath()).isEqualTo(walletDirectory1.getAbsolutePath());
assertThat(walletDirectories.get(0).getAbsolutePath()).isEqualTo(walletDirectory2.getAbsolutePath());
}
}
@Test
public void testFindWallets() throws Exception {
// Create a random temporary directory
File temporaryDirectory = SecureFiles.createTemporaryDirectory();
File walletDirectory1 = SecureFiles.verifyOrCreateDirectory(temporaryDirectory, WALLET_DIRECTORY_1);
File walletDirectory2 = SecureFiles.verifyOrCreateDirectory(temporaryDirectory, WALLET_DIRECTORY_2);
List<File> walletDirectories = WalletManager.findWalletDirectories(temporaryDirectory);
assertThat(walletDirectories).isNotNull();
assertThat(walletDirectories.size()).isEqualTo(2);
// Order of discovery is not guaranteed
boolean foundWalletPath1First = walletDirectories.get(0).getAbsolutePath().equals(walletDirectory1.getAbsolutePath());
if (foundWalletPath1First) {
assertThat(walletDirectories.get(0).getAbsolutePath()).isEqualTo(walletDirectory1.getAbsolutePath());
assertThat(walletDirectories.get(1).getAbsolutePath()).isEqualTo(walletDirectory2.getAbsolutePath());
} else {
assertThat(walletDirectories.get(1).getAbsolutePath()).isEqualTo(walletDirectory1.getAbsolutePath());
assertThat(walletDirectories.get(0).getAbsolutePath()).isEqualTo(walletDirectory2.getAbsolutePath());
}
// Attempt to retrieve the wallet summary
List<WalletSummary> wallets = WalletManager.findWalletSummaries(walletDirectories, Optional.of(WALLET_DIRECTORY_2));
assertThat(wallets).isNotNull();
assertThat(wallets.size()).isEqualTo(2);
// Expect the current wallet root to be first
assertThat(wallets.get(0).getWalletId().toFormattedString()).isEqualTo(EXPECTED_WALLET_ID_2);
assertThat(wallets.get(1).getWalletId().toFormattedString()).isEqualTo(EXPECTED_WALLET_ID_1);
}
@Test
public void testSignAndVerifyMessage() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
// Create a random temporary directory in which to store the cloud backups
File temporaryCloudBackupDirectory = SecureFiles.createTemporaryDirectory();
BackupManager backupManager = BackupManager.INSTANCE;
// Initialise the backup manager to point at the temporary cloud backup directory
backupManager.initialise(applicationDirectory, Optional.of(temporaryCloudBackupDirectory));
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
long nowInSeconds = Dates.nowInSeconds();
log.debug("");
WalletSummary walletSummary = walletManager.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory,
entropy,
seed,
nowInSeconds,
SIGNING_PASSWORD,
"Signing Example",
"Signing Example",
false); // No need to sync
// Address not in wallet
ECKey ecKey = new ECKey();
String addressNotInWalletString = ecKey.toAddress(mainNet).toString();
Wallet wallet = walletSummary.getWallet();
// Create a signing key
DeterministicKey key = wallet.freshReceiveKey();
Address signingAddress = key.toAddress(mainNet);
// Successfully sign the address
log.debug("Expect successful signature");
SignMessageResult signMessageResult = walletManager.signMessage(signingAddress.toString(), MESSAGE_TO_SIGN, SIGNING_PASSWORD);
assertThat(signMessageResult.isSigningWasSuccessful()).isTrue();
assertThat(signMessageResult.getSignatureKey()).isEqualTo(CoreMessageKey.SIGN_MESSAGE_SUCCESS);
assertThat(signMessageResult.getSignatureData()).isNull();
assertThat(signMessageResult.getSignature().isPresent()).isTrue();
assertThat(signMessageResult.getSignature().get()).isNotNull();
// Successfully verify the message
log.debug("Expect successful verification");
VerifyMessageResult verifyMessageResult = walletManager.verifyMessage(signingAddress.toString(), MESSAGE_TO_SIGN, signMessageResult.getSignature().get());
assertThat(verifyMessageResult.isVerifyWasSuccessful()).isTrue();
assertThat(verifyMessageResult.getVerifyKey()).isEqualTo(CoreMessageKey.VERIFY_MESSAGE_VERIFY_SUCCESS);
assertThat(verifyMessageResult.getVerifyData()).isNull();
// Incorrect verify of the message - wrong message
log.debug("Expect wrong message");
verifyMessageResult = walletManager.verifyMessage(signingAddress.toString(), MESSAGE_TO_SIGN + "a", signMessageResult.getSignature().get());
assertThat(verifyMessageResult.isVerifyWasSuccessful()).isFalse();
assertThat(verifyMessageResult.getVerifyKey()).isEqualTo(CoreMessageKey.VERIFY_MESSAGE_VERIFY_FAILURE);
assertThat(verifyMessageResult.getVerifyData()).isNull();
// Incorrect verify of the message - wrong address
log.debug("Expect wrong address");
verifyMessageResult = walletManager.verifyMessage(addressNotInWalletString, MESSAGE_TO_SIGN, signMessageResult.getSignature().get());
assertThat(verifyMessageResult.isVerifyWasSuccessful()).isFalse();
assertThat(verifyMessageResult.getVerifyKey()).isEqualTo(CoreMessageKey.VERIFY_MESSAGE_VERIFY_FAILURE);
assertThat(verifyMessageResult.getVerifyData()).isNull();
// Incorrect verify of the message - wrong signature
log.debug("Expect bad signature");
verifyMessageResult = walletManager.verifyMessage(signingAddress.toString(), MESSAGE_TO_SIGN, signMessageResult.getSignature().get() + "b");
assertThat(verifyMessageResult.isVerifyWasSuccessful()).isFalse();
assertThat(verifyMessageResult.getVerifyKey()).isEqualTo(CoreMessageKey.VERIFY_MESSAGE_FAILURE);
assertThat(verifyMessageResult.getVerifyData()).isNull();
// Bad signing credentials
log.debug("Expect bad credentials");
signMessageResult = walletManager.signMessage(signingAddress.toString(), MESSAGE_TO_SIGN, "badPassword");
assertThat(signMessageResult.isSigningWasSuccessful()).isFalse();
assertThat(signMessageResult.getSignatureKey()).isEqualTo(CoreMessageKey.SIGN_MESSAGE_NO_PASSWORD);
assertThat(signMessageResult.getSignatureData()).isNull();
assertThat(signMessageResult.getSignature().isPresent()).isFalse();
// Signed with address not in wallet
log.debug("Expect bad address (not in wallet)");
signMessageResult = walletManager.signMessage(addressNotInWalletString, MESSAGE_TO_SIGN, SIGNING_PASSWORD);
assertThat(signMessageResult.isSigningWasSuccessful()).isFalse();
assertThat(signMessageResult.getSignatureKey()).isEqualTo(CoreMessageKey.SIGN_MESSAGE_NO_SIGNING_KEY);
assertThat(signMessageResult.getSignatureData()).isEqualTo(new Object[]{addressNotInWalletString});
assertThat(signMessageResult.getSignature().isPresent()).isFalse();
}
@Test
public void testWriteOfEncryptedPasswordAndSeed() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
List<String> passwordList = Lists.newArrayList();
passwordList.add(SHORT_PASSWORD);
passwordList.add(MEDIUM_PASSWORD);
passwordList.add(LONG_PASSWORD);
passwordList.add(LONGER_PASSWORD);
passwordList.add(LONGEST_PASSWORD);
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
for (String passwordToCheck : passwordList) {
log.info("Testing password: {}", passwordToCheck);
// Get the application directory (should be fresh due to unit test cycle earlier)
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary = walletManager
.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory,
entropy,
seed,
nowInSeconds,
passwordToCheck,
"Password/seed encryption Example",
"Password/seed encryption Example",
false); // No need to sync
// Check the encrypted wallet credentials and seed are correct
byte[] foundEncryptedBackupKey = walletSummary.getEncryptedBackupKey();
byte[] foundEncryptedPaddedPassword = walletSummary.getEncryptedPassword();
log.debug("Length of padded encrypted credentials: {}", foundEncryptedPaddedPassword.length);
// Check that the encrypted credentials length is always equal to at least 3 x the AES block size of 16 bytes i.e 48 bytes.
// This ensures that the existence of short passwords is not leaked from the length of the encrypted credentials
assertThat(foundEncryptedPaddedPassword.length).isGreaterThanOrEqualTo(48);
KeyParameter seedDerivedAESKey = org.multibit.commons.crypto.AESUtils.createAESKey(seed, WalletManager.scryptSalt());
byte[] passwordBytes = passwordToCheck.getBytes(Charsets.UTF_8);
byte[] decryptedFoundPaddedPasswordBytes = org.multibit.commons.crypto.AESUtils.decrypt(
foundEncryptedPaddedPassword,
seedDerivedAESKey,
WalletManager.aesInitialisationVector()
);
byte[] decryptedFoundPasswordBytes = WalletManager.unpadPasswordBytes(decryptedFoundPaddedPasswordBytes);
assertThat(Arrays.equals(passwordBytes, decryptedFoundPasswordBytes)).isTrue();
KeyParameter walletPasswordDerivedAESKey = org.multibit.commons.crypto.AESUtils.createAESKey(passwordBytes, WalletManager.scryptSalt());
byte[] decryptedFoundBackupAESKey = org.multibit.commons.crypto.AESUtils.decrypt(
foundEncryptedBackupKey,
walletPasswordDerivedAESKey,
WalletManager.aesInitialisationVector()
);
assertThat(Arrays.equals(seedDerivedAESKey.getKey(), decryptedFoundBackupAESKey)).isTrue();
// Perform a unit test cycle to ensure we reset all services correctly
tearDown();
setUp();
}
}
/**
* Copy the named test wallet to the (temporary) installation directory
*
* @param testWalletPath
* @throws IOException
*/
private void copyTestWallet(String testWalletPath, File installationDirectory) throws IOException {
log.debug("Copying test wallet {} to '{}'", testWalletPath, installationDirectory.getAbsolutePath());
// Prepare an input stream to the checkpoints
final InputStream sourceCheckpointsStream = InstallationManager.class.getResourceAsStream(testWalletPath);
// Create the output stream
long bytes;
try (FileOutputStream sinkCheckpointsStream = new FileOutputStream(installationDirectory.getAbsolutePath() + "/mbhd.wallet.aes")) {
// Copy the wallet
bytes = ByteStreams.copy(sourceCheckpointsStream, sinkCheckpointsStream);
// Clean up
sourceCheckpointsStream.close();
sinkCheckpointsStream.flush();
sinkCheckpointsStream.close();
} finally {
if (sourceCheckpointsStream != null) {
sourceCheckpointsStream.close();
}
}
log.debug("Wallet {} bytes in length.", bytes);
}
}
|
mbhd-core/src/test/java/org/multibit/hd/core/managers/WalletManagerTest.java
|
package org.multibit.hd.core.managers;
/**
* Copyright 2015 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.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.
*/
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.Uninterruptibles;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Wallet;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.wallet.KeyChain;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.multibit.commons.files.SecureFiles;
import org.multibit.commons.utils.Dates;
import org.multibit.hd.brit.core.seed_phrase.Bip39SeedPhraseGenerator;
import org.multibit.hd.brit.core.seed_phrase.SeedPhraseGenerator;
import org.multibit.hd.core.config.Configurations;
import org.multibit.hd.core.crypto.EncryptedFileReaderWriter;
import org.multibit.hd.core.dto.*;
import org.multibit.hd.core.events.ShutdownEvent;
import org.multibit.hd.core.extensions.WalletTypeExtension;
import org.multibit.hd.core.services.CoreServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.crypto.params.KeyParameter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.fest.assertions.Assertions.assertThat;
public class WalletManagerTest {
private static final Logger log = LoggerFactory.getLogger(WalletManagerTest.class);
private final static String WALLET_DIRECTORY_1 = "mbhd-11111111-22222222-33333333-44444444-55555555";
private final static String WALLET_DIRECTORY_2 = "mbhd-66666666-77777777-88888888-99999999-aaaaaaaa";
private final static String EXPECTED_WALLET_ID_1 = "11111111-22222222-33333333-44444444-55555555";
private final static String EXPECTED_WALLET_ID_2 = "66666666-77777777-88888888-99999999-aaaaaaaa";
private final static String INVALID_WALLET_DIRECTORY_1 = "not-mbhd-66666666-77777777-88888888-99999999-aaaaaaaa";
private final static String INVALID_WALLET_DIRECTORY_2 = "mbhd-66666666-77777777-88888888-99999999-gggggggg";
private final static String INVALID_WALLET_DIRECTORY_3 = "mbhd-1166666666-77777777-88888888-99999999-aaaaaaaa";
private final static String SIGNING_PASSWORD = "throgmorton999";
private final static String MESSAGE_TO_SIGN = "The quick brown fox jumps over the lazy dog.\n1234567890!@#$%^&*()";
private final static String SHORT_PASSWORD = "a"; // 1
private final static String MEDIUM_PASSWORD = "abcefghijklm"; // 12
private final static String LONG_PASSWORD = "abcefghijklmnopqrstuvwxyz"; // 26
private final static String LONGER_PASSWORD = "abcefghijklmnopqrstuvwxyz1234567890"; // 36
private final static String LONGEST_PASSWORD = "abcefghijklmnopqrstuvwxyzabcefghijklmnopqrstuvwxyz"; // 52
/**
* The seed phrase for the Trezor 'Abandon' wallet
*/
public final static String TREZOR_SEED_PHRASE = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
// The generated Trezor addresses for the 'Abandon' wallet
public final static String TREZOR_ADDRESS_M_44H_0H_0H_0_0 = "1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA"; // Receiving funds
public final static String TREZOR_ADDRESS_M_44H_0H_0H_1_0 = "1J3J6EvPrv8q6AC3VCjWV45Uf3nssNMRtH"; // Change
public final static String TREZOR_ADDRESS_M_44H_0H_0H_0_1 = "1Ak8PffB2meyfYnbXZR9EGfLfFZVpzJvQP";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_1_1 = "13vKxXzHXXd8HquAYdpkJoi9ULVXUgfpS5";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_0_2 = "1MNF5RSaabFwcbtJirJwKnDytsXXEsVsNb";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_1_2 = "1M21Wx1nGrHMPaz52N2En7c624nzL4MYTk";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_0_3 = "1MVGa13XFvvpKGZdX389iU8b3qwtmAyrsJ";
public final static String TREZOR_ADDRESS_M_44H_0H_0H_1_3 = "1DzVLMA4HzjXPAr6aZoaacDPHXXntsZ2zL";
/**
* The 'skin' seed phrase used in the issue: https://github.com/bitcoin-solutions/multibit-hd/issues/445
*/
public static final String SKIN_SEED_PHRASE = "skin join dog sponsor camera puppy ritual diagram arrow poverty boy elbow";
// The receiving address being generated in Beta 7 and previous MBHD (not BIP32 compliant)
private static final String NON_COMPLIANT_SKIN_ADDRESS_M_0H_0_0 = "1LQ8XnNKqC7Vu7atH5k4X8qVCc9ug2q7WE";
// The correct BIP32 addresses, generated from https://dcpos.github.io/bip39/ with the skin seed and derivation path m/0'/0
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_0 = "12QxtuyEM8KBG3ngNRe2CZE28hFw3b1KMJ";
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_1 = "16mN2Bjap7vSb6Cp4sjV3BrUiCMP3ixo5A";
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_2 = "1LrC33bZVTHTHMqw8p1NWUoHVArKFwB3mp";
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_3 = "17Czu38CcLwWr8jFZrDJBHWiEDd2QWhPSU";
private static final String COMPLIANT_SKIN_ADDRESS_M_0H_0_4 = "18dbiNgyHKEY4TtynEDZGEDhS9fdYqeZWG";
private NetworkParameters mainNet;
@SuppressFBWarnings({"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", "NP_NONNULL_PARAM_VIOLATION"})
@Before
public void setUp() throws Exception {
InstallationManager.unrestricted = true;
Configurations.currentConfiguration = Configurations.newDefaultConfiguration();
// Start the core services
CoreServices.main(null);
mainNet = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
assertThat(mainNet).isNotNull();
}
@After
public void tearDown() throws Exception {
// Order is important here
CoreServices.shutdownNow(ShutdownEvent.ShutdownType.SOFT);
InstallationManager.shutdownNow(ShutdownEvent.ShutdownType.SOFT);
BackupManager.INSTANCE.shutdownNow();
WalletManager.INSTANCE.shutdownNow(ShutdownEvent.ShutdownType.HARD);
}
@Test
public void testCreateWallet() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary1 = walletManager
.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory,
entropy,
seed,
nowInSeconds,
"credentials",
"Example",
"Example",
false); // No need to sync
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Uncomment this next line if you want a wallet created in your MultiBitHD user data directory.
//walletManager.createWallet( seed, "credentials");
assertThat(walletSummary1).isNotNull();
// Create another wallet - it should have the same wallet id and the private key should be the same
File applicationDirectory2 = SecureFiles.createTemporaryDirectory();
BackupManager.INSTANCE.initialise(applicationDirectory2, Optional.<File>absent());
WalletSummary walletSummary2 = walletManager
.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory2,
entropy,
seed,
nowInSeconds,
"credentials",
"Example",
"Example",
false); // No need to sync
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(walletSummary2).isNotNull();
ECKey key1 = walletSummary1.getWallet().freshReceiveKey();
ECKey key2 = walletSummary2.getWallet().freshReceiveKey();
assertThat(key1).isEqualTo(key2);
File expectedFile = new File(
applicationDirectory2.getAbsolutePath()
+ File.separator
+ "mbhd-"
+ walletSummary2.getWalletId().toFormattedString()
+ File.separator
+ WalletManager.MBHD_WALLET_NAME
+ WalletManager.MBHD_AES_SUFFIX
);
assertThat(expectedFile.exists()).isTrue();
assertThat(WalletType.MBHD_SOFT_WALLET_BIP32.equals(walletSummary1.getWalletType()));
assertThat(WalletType.MBHD_SOFT_WALLET_BIP32.equals(walletSummary2.getWalletType()));
}
@Test
/**
* Test creation of a Trezor (soft) wallet.
*/
public void testCreateSoftTrezorWallet() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary = walletManager.getOrCreateTrezorSoftWalletSummaryFromSeedPhrase(
applicationDirectory,
TREZOR_SEED_PHRASE,
nowInSeconds,
"aPassword",
"Abandon",
"Abandon", true);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(walletSummary).isNotNull();
assertThat(WalletType.TREZOR_SOFT_WALLET.equals(walletSummary.getWalletType()));
// Check that the generated addresses match the list of addresses you get directly from the Trezor
// (Either from myTrezor.com or from the multibit-hardware test TrezorV1GetAddressExample)
Wallet trezorWallet = walletSummary.getWallet();
DeterministicKey trezorKeyM44H_0H_0H_0_0 = trezorWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
String addressM44H_0H_0H_0_0 = trezorKeyM44H_0H_0H_0_0.toAddress(mainNet).toString();
log.debug("WalletManagerTest - trezorKeyM44H_0H_0H_0_0 = " + trezorKeyM44H_0H_0H_0_0.toString());
log.debug("WalletManagerTest - addressM44H_0H_0H_0_0 = " + addressM44H_0H_0H_0_0);
DeterministicKey trezorKeyM44H_0H_0H_1_0 = trezorWallet.freshKey(KeyChain.KeyPurpose.CHANGE);
String addressM44H_0H_0H_1_0 = trezorKeyM44H_0H_0H_1_0.toAddress(mainNet).toString();
log.debug("WalletManagerTest - trezorKeyM44H_0H_0H_1_0 = " + trezorKeyM44H_0H_0H_1_0.toString());
log.debug("WalletManagerTest - addressM44H_0H_0H_1_0 = " + addressM44H_0H_0H_1_0);
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_0_0.equals(addressM44H_0H_0H_0_0)).isTrue();
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_1_0.equals(addressM44H_0H_0H_1_0)).isTrue();
Address trezorAddressM44H_0H_0H_0_1 = trezorWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
Address trezorAddressM44H_0H_0H_1_1 = trezorWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_0_1.equals(trezorAddressM44H_0H_0H_0_1.toString())).isTrue();
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_1_1.equals(trezorAddressM44H_0H_0H_1_1.toString())).isTrue();
Address trezorAddressM44H_0H_0H_0_2 = trezorWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
Address trezorAddressM44H_0H_0H_1_2 = trezorWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_0_2.equals(trezorAddressM44H_0H_0H_0_2.toString())).isTrue();
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_1_2.equals(trezorAddressM44H_0H_0H_1_2.toString())).isTrue();
Address trezorAddressM44H_0H_0H_0_3 = trezorWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
Address trezorAddressM44H_0H_0H_1_3 = trezorWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_0_3.equals(trezorAddressM44H_0H_0H_0_3.toString())).isTrue();
assertThat(TREZOR_ADDRESS_M_44H_0H_0H_1_3.equals(trezorAddressM44H_0H_0H_1_3.toString())).isTrue();
log.debug("Original trezor wallet, number of keys: " + trezorWallet.getActiveKeychain().numKeys());
log.debug("Original trezor wallet : {}", trezorWallet.toString());
// Check the wallet can be reloaded ok i.e. the protobuf round trips
File temporaryFile = File.createTempFile("WalletManagerTest", ".wallet");
trezorWallet.saveToFile(temporaryFile);
File encryptedWalletFile = EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(temporaryFile, "aPassword");
Wallet rebornWallet = WalletManager.INSTANCE.loadWalletFromFile(encryptedWalletFile, "aPassword");
log.debug("Reborn trezor wallet, number of keys: " + rebornWallet.getActiveKeychain().numKeys());
log.debug("Reborn trezor wallet : {}", rebornWallet.toString());
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Check the first keys above are in the wallet
assertThat(rebornWallet.hasKey(trezorKeyM44H_0H_0H_0_0)).isTrue();
assertThat(rebornWallet.hasKey(trezorKeyM44H_0H_0H_1_0)).isTrue();
// Create a fresh receiving and change address
Address freshReceivingAddress = rebornWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertThat(freshReceivingAddress).isNotNull();
Address freshChangeAddress = rebornWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(freshChangeAddress).isNotNull();
log.debug("Reborn trezor wallet with more keys, number of keys: " + rebornWallet.getActiveKeychain().numKeys());
log.debug("Reborn trezor wallet with more keys : {}", rebornWallet.toString());
// Round trip it again
File temporaryFile2 = File.createTempFile("WalletManagerTest2", ".wallet");
rebornWallet.saveToFile(temporaryFile2);
File encryptedWalletFile2 = EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(temporaryFile2, "aPassword2");
Wallet rebornWallet2 = WalletManager.INSTANCE.loadWalletFromFile(encryptedWalletFile2, "aPassword2");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Check the first keys above are in the wallet
assertThat(rebornWallet2.hasKey(trezorKeyM44H_0H_0H_0_0)).isTrue();
assertThat(rebornWallet2.hasKey(trezorKeyM44H_0H_0H_1_0)).isTrue();
}
@Test
/**
* Test creation of an MBHD soft wallet with the 'skin' seed phrase
* This replicates the non-BIP32 compliant code we have at the moment
*/
public void testCreateSkinSeedPhraseWalletInABadWay() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(SKIN_SEED_PHRASE));
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary = walletManager.badlyGetOrCreateMBHDSoftWalletSummaryFromSeed(
applicationDirectory,
seed,
nowInSeconds,
"aPassword",
"Skin",
"Skin", true);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(walletSummary).isNotNull();
assertThat(WalletType.MBHD_SOFT_WALLET.equals(walletSummary.getWalletType()));
// Check that the generated addresses match the expected
Wallet skinWallet = walletSummary.getWallet();
DeterministicKey skinKeyM0H_0_0 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_1 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_2 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_3 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_4 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
String skinAddressM0H_0_0 = skinKeyM0H_0_0.toAddress(mainNet).toString();
String skinAddressM0H_0_1 = skinKeyM0H_0_1.toAddress(mainNet).toString();
String skinAddressM0H_0_2 = skinKeyM0H_0_2.toAddress(mainNet).toString();
String skinAddressM0H_0_3 = skinKeyM0H_0_3.toAddress(mainNet).toString();
String skinAddressM0H_0_4 = skinKeyM0H_0_4.toAddress(mainNet).toString();
log.debug("WalletManagerTest - BAD skinAddressM0H_0_0 = {}", skinAddressM0H_0_0);
log.debug("WalletManagerTest - BAD skinAddressM0H_0_1 = {}", skinAddressM0H_0_1);
log.debug("WalletManagerTest - BAD skinAddressM0H_0_2 = {}", skinAddressM0H_0_2);
log.debug("WalletManagerTest - BAD skinAddressM0H_0_3 = {}", skinAddressM0H_0_3);
log.debug("WalletManagerTest - BAD skinAddressM0H_0_4 = {}", skinAddressM0H_0_4);
// This test passes now but the address is incorrect in real life - not BIP32 compliant
assertThat(NON_COMPLIANT_SKIN_ADDRESS_M_0H_0_0.equals(skinAddressM0H_0_0)).isTrue();
// These asserts should all be isTrue were the wallet BIP32 complaint - the addresses in MBHD wallets are currently wrong
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_0.equals(skinAddressM0H_0_0)).isFalse();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_1.equals(skinAddressM0H_0_1)).isFalse();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_2.equals(skinAddressM0H_0_2)).isFalse();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_3.equals(skinAddressM0H_0_3)).isFalse();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_4.equals(skinAddressM0H_0_4)).isFalse();
}
@Test
/**
* Test creation of an MBHD soft wallet with the 'skin' seed phrase
* This constructs a BIP32 compliant wallet
*/
public void testCreateSkinSeedPhraseWalletInAGoodWay() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Bip39SeedPhraseGenerator.split(SKIN_SEED_PHRASE));
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(SKIN_SEED_PHRASE));
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary = walletManager.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory,
entropy,
seed,
nowInSeconds,
"aPassword",
"Skin",
"Skin", true);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(walletSummary).isNotNull();
assertThat(WalletType.MBHD_SOFT_WALLET_BIP32.equals(walletSummary.getWalletType()));
// Check that the generated addresses match the expected
Wallet skinWallet = walletSummary.getWallet();
DeterministicKey skinKeyM0H_0_0 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_1 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_2 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_3 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey skinKeyM0H_0_4 = skinWallet.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
String skinAddressM0H_0_0 = skinKeyM0H_0_0.toAddress(mainNet).toString();
String skinAddressM0H_0_1 = skinKeyM0H_0_1.toAddress(mainNet).toString();
String skinAddressM0H_0_2 = skinKeyM0H_0_2.toAddress(mainNet).toString();
String skinAddressM0H_0_3 = skinKeyM0H_0_3.toAddress(mainNet).toString();
String skinAddressM0H_0_4 = skinKeyM0H_0_4.toAddress(mainNet).toString();
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_0 = {}", skinAddressM0H_0_0);
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_1 = {}", skinAddressM0H_0_1);
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_2 = {}", skinAddressM0H_0_2);
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_3 = {}", skinAddressM0H_0_3);
log.debug("WalletManagerTest - GOOD skinAddressM0H_0_4 = {}", skinAddressM0H_0_4);
// This is the Beta 7 address that was not BIP32 compliant
assertThat(NON_COMPLIANT_SKIN_ADDRESS_M_0H_0_0.equals(skinAddressM0H_0_0)).isFalse();
// These are BIP32 compliant addresses
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_0.equals(skinAddressM0H_0_0)).isTrue();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_1.equals(skinAddressM0H_0_1)).isTrue();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_2.equals(skinAddressM0H_0_2)).isTrue();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_3.equals(skinAddressM0H_0_3)).isTrue();
assertThat(COMPLIANT_SKIN_ADDRESS_M_0H_0_4.equals(skinAddressM0H_0_4)).isTrue();
// Check the wallet can be reloaded ok i.e. the protobuf round trips
File temporaryFile = File.createTempFile("WalletManagerTest", ".wallet");
skinWallet.saveToFile(temporaryFile);
File encryptedWalletFile = EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(temporaryFile, "aPassword");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
Wallet rebornWallet = WalletManager.INSTANCE.loadWalletFromFile(encryptedWalletFile, "aPassword");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
log.debug("Reborn skin wallet, number of keys: " + rebornWallet.getActiveKeychain().numKeys());
log.debug("Reborn skin wallet : {}", rebornWallet.toString());
// Check the first keys above are in the wallet
assertThat(rebornWallet.hasKey(skinKeyM0H_0_0)).isTrue();
assertThat(rebornWallet.hasKey(skinKeyM0H_0_1)).isTrue();
// Create a fresh receiving and change address
Address freshReceivingAddress = rebornWallet.freshAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertThat(freshReceivingAddress).isNotNull();
Address freshChangeAddress = rebornWallet.freshAddress(KeyChain.KeyPurpose.CHANGE);
assertThat(freshChangeAddress).isNotNull();
log.debug("Reborn skin wallet with more keys, number of keys: " + rebornWallet.getActiveKeychain().numKeys());
log.debug("Reborn skin wallet with more keys : {}", rebornWallet.toString());
// Round trip it again
File temporaryFile2 = File.createTempFile("WalletManagerTest2", ".wallet");
rebornWallet.saveToFile(temporaryFile2);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
File encryptedWalletFile2 = EncryptedFileReaderWriter.makeAESEncryptedCopyAndDeleteOriginal(temporaryFile2, "aPassword2");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
Wallet rebornWallet2 = WalletManager.INSTANCE.loadWalletFromFile(encryptedWalletFile2, "aPassword2");
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Check the first keys above are in the wallet
assertThat(rebornWallet2.hasKey(skinKeyM0H_0_0)).isTrue();
assertThat(rebornWallet2.hasKey(skinKeyM0H_0_0)).isTrue();
}
@Test
public void testBackwardsCompatibility_MBHD_SOFT_WALLET_BIP32() throws Exception {
backwardsCompatibilityCheck("/wallets/MBHD_SOFT_WALLET_BIP32.wallet.aes", "abc123", WalletType.MBHD_SOFT_WALLET_BIP32);
}
@Test
public void testBackwardsCompatibility_MBHD_SOFT_WALLET() throws Exception {
backwardsCompatibilityCheck("/wallets/MBHD_SOFT_WALLET.wallet.aes", "abc123", WalletType.MBHD_SOFT_WALLET);
}
private void backwardsCompatibilityCheck(String walletLocation, String password, WalletType expectedWalletType) throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
// Copy the extant test wallet to the application directory
copyTestWallet(walletLocation, applicationDirectory);
File walletFile = new File(applicationDirectory.getAbsolutePath() + "/mbhd.wallet.aes");
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
Wallet wallet = walletManager.loadWalletFromFile(walletFile, password);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
assertThat(wallet).isNotNull();
WalletTypeExtension probeWalletTypeExtension = new WalletTypeExtension();
WalletTypeExtension existingWalletTypeExtension = (WalletTypeExtension) wallet.addOrGetExistingExtension(probeWalletTypeExtension);
assertThat(expectedWalletType.equals(existingWalletTypeExtension.getWalletType()));
}
@Test
public void testFindWalletDirectories() throws Exception {
// Create a random temporary directory
File temporaryDirectory = SecureFiles.createTemporaryDirectory();
File walletDirectory1 = SecureFiles.verifyOrCreateDirectory(temporaryDirectory, WALLET_DIRECTORY_1);
File walletDirectory2 = SecureFiles.verifyOrCreateDirectory(temporaryDirectory, WALLET_DIRECTORY_2);
SecureFiles.verifyOrCreateDirectory(temporaryDirectory, INVALID_WALLET_DIRECTORY_1);
SecureFiles.verifyOrCreateDirectory(temporaryDirectory, INVALID_WALLET_DIRECTORY_2);
SecureFiles.verifyOrCreateDirectory(temporaryDirectory, INVALID_WALLET_DIRECTORY_3);
List<File> walletDirectories = WalletManager.findWalletDirectories(temporaryDirectory);
assertThat(walletDirectories).isNotNull();
assertThat(walletDirectories.size()).isEqualTo(2);
// Order of discovery is not guaranteed
boolean foundWalletPath1First = walletDirectories.get(0).getAbsolutePath().equals(walletDirectory1.getAbsolutePath());
if (foundWalletPath1First) {
assertThat(walletDirectories.get(0).getAbsolutePath()).isEqualTo(walletDirectory1.getAbsolutePath());
assertThat(walletDirectories.get(1).getAbsolutePath()).isEqualTo(walletDirectory2.getAbsolutePath());
} else {
assertThat(walletDirectories.get(1).getAbsolutePath()).isEqualTo(walletDirectory1.getAbsolutePath());
assertThat(walletDirectories.get(0).getAbsolutePath()).isEqualTo(walletDirectory2.getAbsolutePath());
}
}
@Test
public void testFindWallets() throws Exception {
// Create a random temporary directory
File temporaryDirectory = SecureFiles.createTemporaryDirectory();
File walletDirectory1 = SecureFiles.verifyOrCreateDirectory(temporaryDirectory, WALLET_DIRECTORY_1);
File walletDirectory2 = SecureFiles.verifyOrCreateDirectory(temporaryDirectory, WALLET_DIRECTORY_2);
List<File> walletDirectories = WalletManager.findWalletDirectories(temporaryDirectory);
assertThat(walletDirectories).isNotNull();
assertThat(walletDirectories.size()).isEqualTo(2);
// Order of discovery is not guaranteed
boolean foundWalletPath1First = walletDirectories.get(0).getAbsolutePath().equals(walletDirectory1.getAbsolutePath());
if (foundWalletPath1First) {
assertThat(walletDirectories.get(0).getAbsolutePath()).isEqualTo(walletDirectory1.getAbsolutePath());
assertThat(walletDirectories.get(1).getAbsolutePath()).isEqualTo(walletDirectory2.getAbsolutePath());
} else {
assertThat(walletDirectories.get(1).getAbsolutePath()).isEqualTo(walletDirectory1.getAbsolutePath());
assertThat(walletDirectories.get(0).getAbsolutePath()).isEqualTo(walletDirectory2.getAbsolutePath());
}
// Attempt to retrieve the wallet summary
List<WalletSummary> wallets = WalletManager.findWalletSummaries(walletDirectories, Optional.of(WALLET_DIRECTORY_2));
assertThat(wallets).isNotNull();
assertThat(wallets.size()).isEqualTo(2);
// Expect the current wallet root to be first
assertThat(wallets.get(0).getWalletId().toFormattedString()).isEqualTo(EXPECTED_WALLET_ID_2);
assertThat(wallets.get(1).getWalletId().toFormattedString()).isEqualTo(EXPECTED_WALLET_ID_1);
}
@Test
public void testSignAndVerifyMessage() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
// Get the application directory
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
// Create a random temporary directory in which to store the cloud backups
File temporaryCloudBackupDirectory = SecureFiles.createTemporaryDirectory();
BackupManager backupManager = BackupManager.INSTANCE;
// Initialise the backup manager to point at the temporary cloud backup directory
backupManager.initialise(applicationDirectory, Optional.of(temporaryCloudBackupDirectory));
WalletManager walletManager = WalletManager.INSTANCE;
BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent());
byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
long nowInSeconds = Dates.nowInSeconds();
log.debug("");
WalletSummary walletSummary = walletManager.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory,
entropy,
seed,
nowInSeconds,
SIGNING_PASSWORD,
"Signing Example",
"Signing Example",
false); // No need to sync
// Address not in wallet
ECKey ecKey = new ECKey();
String addressNotInWalletString = ecKey.toAddress(mainNet).toString();
Wallet wallet = walletSummary.getWallet();
// Create a signing key
DeterministicKey key = wallet.freshReceiveKey();
Address signingAddress = key.toAddress(mainNet);
// Successfully sign the address
log.debug("Expect successful signature");
SignMessageResult signMessageResult = walletManager.signMessage(signingAddress.toString(), MESSAGE_TO_SIGN, SIGNING_PASSWORD);
assertThat(signMessageResult.isSigningWasSuccessful()).isTrue();
assertThat(signMessageResult.getSignatureKey()).isEqualTo(CoreMessageKey.SIGN_MESSAGE_SUCCESS);
assertThat(signMessageResult.getSignatureData()).isNull();
assertThat(signMessageResult.getSignature().isPresent()).isTrue();
assertThat(signMessageResult.getSignature().get()).isNotNull();
// Successfully verify the message
log.debug("Expect successful verification");
VerifyMessageResult verifyMessageResult = walletManager.verifyMessage(signingAddress.toString(), MESSAGE_TO_SIGN, signMessageResult.getSignature().get());
assertThat(verifyMessageResult.isVerifyWasSuccessful()).isTrue();
assertThat(verifyMessageResult.getVerifyKey()).isEqualTo(CoreMessageKey.VERIFY_MESSAGE_VERIFY_SUCCESS);
assertThat(verifyMessageResult.getVerifyData()).isNull();
// Incorrect verify of the message - wrong message
log.debug("Expect wrong message");
verifyMessageResult = walletManager.verifyMessage(signingAddress.toString(), MESSAGE_TO_SIGN + "a", signMessageResult.getSignature().get());
assertThat(verifyMessageResult.isVerifyWasSuccessful()).isFalse();
assertThat(verifyMessageResult.getVerifyKey()).isEqualTo(CoreMessageKey.VERIFY_MESSAGE_VERIFY_FAILURE);
assertThat(verifyMessageResult.getVerifyData()).isNull();
// Incorrect verify of the message - wrong address
log.debug("Expect wrong address");
verifyMessageResult = walletManager.verifyMessage(addressNotInWalletString, MESSAGE_TO_SIGN, signMessageResult.getSignature().get());
assertThat(verifyMessageResult.isVerifyWasSuccessful()).isFalse();
assertThat(verifyMessageResult.getVerifyKey()).isEqualTo(CoreMessageKey.VERIFY_MESSAGE_VERIFY_FAILURE);
assertThat(verifyMessageResult.getVerifyData()).isNull();
// Incorrect verify of the message - wrong signature
log.debug("Expect bad signature");
verifyMessageResult = walletManager.verifyMessage(signingAddress.toString(), MESSAGE_TO_SIGN, signMessageResult.getSignature().get() + "b");
assertThat(verifyMessageResult.isVerifyWasSuccessful()).isFalse();
assertThat(verifyMessageResult.getVerifyKey()).isEqualTo(CoreMessageKey.VERIFY_MESSAGE_FAILURE);
assertThat(verifyMessageResult.getVerifyData()).isNull();
// Bad signing credentials
log.debug("Expect bad credentials");
signMessageResult = walletManager.signMessage(signingAddress.toString(), MESSAGE_TO_SIGN, "badPassword");
assertThat(signMessageResult.isSigningWasSuccessful()).isFalse();
assertThat(signMessageResult.getSignatureKey()).isEqualTo(CoreMessageKey.SIGN_MESSAGE_NO_PASSWORD);
assertThat(signMessageResult.getSignatureData()).isNull();
assertThat(signMessageResult.getSignature().isPresent()).isFalse();
// Signed with address not in wallet
log.debug("Expect bad address (not in wallet)");
signMessageResult = walletManager.signMessage(addressNotInWalletString, MESSAGE_TO_SIGN, SIGNING_PASSWORD);
assertThat(signMessageResult.isSigningWasSuccessful()).isFalse();
assertThat(signMessageResult.getSignatureKey()).isEqualTo(CoreMessageKey.SIGN_MESSAGE_NO_SIGNING_KEY);
assertThat(signMessageResult.getSignatureData()).isEqualTo(new Object[]{addressNotInWalletString});
assertThat(signMessageResult.getSignature().isPresent()).isFalse();
}
@Test
public void testWriteOfEncryptedPasswordAndSeed() throws Exception {
// Delay a second to ensure unique temporary directory
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
List<String> passwordList = Lists.newArrayList();
passwordList.add(SHORT_PASSWORD);
passwordList.add(MEDIUM_PASSWORD);
passwordList.add(LONG_PASSWORD);
passwordList.add(LONGER_PASSWORD);
passwordList.add(LONGEST_PASSWORD);
SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator();
byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1));
for (String passwordToCheck : passwordList) {
log.info("Testing password: {}", passwordToCheck);
// Get the application directory (should be fresh due to unit test cycle earlier)
File applicationDirectory = InstallationManager.getOrCreateApplicationDataDirectory();
WalletManager walletManager = WalletManager.INSTANCE;
long nowInSeconds = Dates.nowInSeconds();
WalletSummary walletSummary = walletManager
.getOrCreateMBHDSoftWalletSummaryFromEntropy(
applicationDirectory,
entropy,
seed,
nowInSeconds,
passwordToCheck,
"Password/seed encryption Example",
"Password/seed encryption Example",
false); // No need to sync
// Check the encrypted wallet credentials and seed are correct
byte[] foundEncryptedBackupKey = walletSummary.getEncryptedBackupKey();
byte[] foundEncryptedPaddedPassword = walletSummary.getEncryptedPassword();
log.debug("Length of padded encrypted credentials: {}", foundEncryptedPaddedPassword.length);
// Check that the encrypted credentials length is always equal to at least 3 x the AES block size of 16 bytes i.e 48 bytes.
// This ensures that the existence of short passwords is not leaked from the length of the encrypted credentials
assertThat(foundEncryptedPaddedPassword.length).isGreaterThanOrEqualTo(48);
KeyParameter seedDerivedAESKey = org.multibit.commons.crypto.AESUtils.createAESKey(seed, WalletManager.scryptSalt());
byte[] passwordBytes = passwordToCheck.getBytes(Charsets.UTF_8);
byte[] decryptedFoundPaddedPasswordBytes = org.multibit.commons.crypto.AESUtils.decrypt(
foundEncryptedPaddedPassword,
seedDerivedAESKey,
WalletManager.aesInitialisationVector()
);
byte[] decryptedFoundPasswordBytes = WalletManager.unpadPasswordBytes(decryptedFoundPaddedPasswordBytes);
assertThat(Arrays.equals(passwordBytes, decryptedFoundPasswordBytes)).isTrue();
KeyParameter walletPasswordDerivedAESKey = org.multibit.commons.crypto.AESUtils.createAESKey(passwordBytes, WalletManager.scryptSalt());
byte[] decryptedFoundBackupAESKey = org.multibit.commons.crypto.AESUtils.decrypt(
foundEncryptedBackupKey,
walletPasswordDerivedAESKey,
WalletManager.aesInitialisationVector()
);
assertThat(Arrays.equals(seedDerivedAESKey.getKey(), decryptedFoundBackupAESKey)).isTrue();
// Perform a unit test cycle to ensure we reset all services correctly
tearDown();
setUp();
}
}
/**
* Copy the named test wallet to the (temporary) installation directory
*
* @param testWalletPath
* @throws IOException
*/
private void copyTestWallet(String testWalletPath, File installationDirectory) throws IOException {
log.debug("Copying test wallet {} to '{}'", testWalletPath, installationDirectory.getAbsolutePath());
// Prepare an input stream to the checkpoints
final InputStream sourceCheckpointsStream = InstallationManager.class.getResourceAsStream(testWalletPath);
// Create the output stream
long bytes;
try (FileOutputStream sinkCheckpointsStream = new FileOutputStream(installationDirectory.getAbsolutePath() + "/mbhd.wallet.aes")) {
// Copy the wallet
bytes = ByteStreams.copy(sourceCheckpointsStream, sinkCheckpointsStream);
// Clean up
sourceCheckpointsStream.close();
sinkCheckpointsStream.flush();
sinkCheckpointsStream.close();
} finally {
if (sourceCheckpointsStream != null) {
sourceCheckpointsStream.close();
}
}
log.debug("Wallet {} bytes in length.", bytes);
}
}
|
entered temporary Ignore
|
mbhd-core/src/test/java/org/multibit/hd/core/managers/WalletManagerTest.java
|
entered temporary Ignore
|
|
Java
|
mit
|
088dbae776ecae4a9f952b84c889e4902568e698
| 0
|
psjava/psjava,psjava/psjava
|
package org.psjava.ds.array;
import org.junit.Assert;
import org.junit.Test;
import org.psjava.TestUtil;
public class MutableSubArrayTest {
@Test
public void test() {
MutableArray<Integer> a = MutableArrayFromValues.create(1, 2, 3, 4);
MutableArray<Integer> sub = MutableSubArray.wrap(a, 1, 3);
Assert.assertEquals(TestUtil.toArrayList(2, 3), TestUtil.toArrayListFromIterable(sub));
sub.set(1, 100);
Assert.assertEquals(TestUtil.toArrayList(1, 2, 100, 4), TestUtil.toArrayListFromIterable(a));
}
}
|
src/test/java/org/psjava/ds/array/MutableSubArrayTest.java
|
package org.psjava.ds.array;
import org.junit.Assert;
import org.junit.Test;
import org.psjava.TestUtil;
public class MutableSubArrayTest {
@Test
public void test() {
DynamicArray<Integer> a = DynamicArray.create();
AddToLastAll.add(a, TestUtil.toArrayList(1, 2, 3, 4));
MutableArray<Integer> sub = MutableSubArray.wrap(a, 1, 3);
Assert.assertEquals(TestUtil.toArrayList(2, 3), TestUtil.toArrayListFromIterable(sub));
sub.set(1, 100);
Assert.assertEquals(TestUtil.toArrayList(1, 2, 100, 4), TestUtil.toArrayListFromIterable(a));
}
}
|
simple adjust - make more simpler MutableSubArrayTest
|
src/test/java/org/psjava/ds/array/MutableSubArrayTest.java
|
simple adjust - make more simpler MutableSubArrayTest
|
|
Java
|
epl-1.0
|
744a266f60bd189dfa78fbfe795fafffa2d53437
| 0
|
boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor
|
// The MIT License (MIT)
//
// Copyright (c) 2015, 2018 Arian Fornaris
//
// 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 phasereditor.scene.ui.editor;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DragDetectEvent;
import org.eclipse.swt.events.DragDetectListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.wb.swt.SWTResourceManager;
import org.json.JSONObject;
import phasereditor.assetpack.core.BitmapFontAssetModel;
import phasereditor.assetpack.core.IAssetFrameModel;
import phasereditor.assetpack.core.ImageAssetModel;
import phasereditor.scene.core.BitmapTextComponent;
import phasereditor.scene.core.BitmapTextModel;
import phasereditor.scene.core.EditorComponent;
import phasereditor.scene.core.FlipComponent;
import phasereditor.scene.core.ImageModel;
import phasereditor.scene.core.NameComputer;
import phasereditor.scene.core.ObjectModel;
import phasereditor.scene.core.ParentComponent;
import phasereditor.scene.core.SceneModel;
import phasereditor.scene.core.SpriteModel;
import phasereditor.scene.core.TextualComponent;
import phasereditor.scene.core.TextureComponent;
import phasereditor.scene.core.TransformComponent;
import phasereditor.scene.ui.editor.interactive.InteractiveTool;
import phasereditor.scene.ui.editor.undo.WorldSnapshotOperation;
import phasereditor.ui.PhaserEditorUI;
import phasereditor.ui.ZoomCanvas;
/**
* @author arian
*
*/
public class SceneCanvas extends ZoomCanvas implements MouseListener, MouseMoveListener, DragDetectListener {
private static final String SCENE_COPY_STAMP = "--scene--copy--stamp--";
public static final int X_LABELS_HEIGHT = 18;
public static final int Y_LABEL_WIDTH = 18;
private SceneEditor _editor;
private SceneObjectRenderer _renderer;
private float _renderModelSnapX;
private float _renderModelSnapY;
List<Object> _selection;
private SceneModel _sceneModel;
private DragObjectsEvents _dragObjectsEvents;
private SelectionEvents _selectionEvents;
private List<InteractiveTool> _interactiveTools;
private boolean _transformLocalCoords;
private boolean _isInteractiveDragging;
public SceneCanvas(Composite parent, int style) {
super(parent, style);
_selection = new ArrayList<>();
addPaintListener(this);
_dragObjectsEvents = new DragObjectsEvents(this);
_selectionEvents = new SelectionEvents(this);
addDragDetectListener(this);
addMouseListener(this);
addMouseMoveListener(this);
init_DND();
setZoomWhenShiftPressed(false);
_interactiveTools = new ArrayList<>();
_transformLocalCoords = true;
}
public boolean isTransformLocalCoords() {
return _transformLocalCoords;
}
public void setTransformLocalCoords(boolean transformLocalCoords) {
_transformLocalCoords = transformLocalCoords;
}
public List<InteractiveTool> getInteractiveTools() {
return _interactiveTools;
}
public void setInteractiveTools(InteractiveTool... tools) {
_interactiveTools = Arrays.asList(tools);
getEditor().updatePropertyPagesContentWithSelection();
redraw();
}
public boolean hasInteractiveTool(Class<?> cls) {
for (var tool : _interactiveTools) {
if (cls.isInstance(tool)) {
return true;
}
}
return false;
}
private void init_DND() {
{
int options = DND.DROP_MOVE | DND.DROP_DEFAULT;
DropTarget target = new DropTarget(this, options);
Transfer[] types = { LocalSelectionTransfer.getTransfer() };
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
@Override
public void drop(DropTargetEvent event) {
var loc = toDisplay(0, 0);
var x = event.x - loc.x;
var y = event.y - loc.y;
if (event.data instanceof Object[]) {
selectionDropped(x, y, (Object[]) event.data);
}
if (event.data instanceof IStructuredSelection) {
selectionDropped(x, y, ((IStructuredSelection) event.data).toArray());
}
}
});
}
}
public float[] viewToModel(int x, int y) {
var calc = calc();
var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH;
var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT;
return new float[] { modelX, modelY };
}
public float[] modelToView(int x, int y) {
var calc = calc();
var viewX = calc.modelToViewX(x) + Y_LABEL_WIDTH;
var viewY = calc.modelToViewY(y) + X_LABELS_HEIGHT;
return new float[] { viewX, viewY };
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void selectionDropped(int x, int y, Object[] data) {
var nameComputer = new NameComputer(_sceneModel.getRootObject());
var beforeSnapshot = WorldSnapshotOperation.takeSnapshot(_editor);
var calc = calc();
var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH;
var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT;
var newModels = new ArrayList<ObjectModel>();
for (var obj : data) {
if (obj instanceof ImageAssetModel) {
obj = ((ImageAssetModel) obj).getFrame();
}
if (obj instanceof IAssetFrameModel) {
var frame = (IAssetFrameModel) obj;
var sprite = new ImageModel();
var name = nameComputer.newName(frame.getKey());
EditorComponent.set_editorName(sprite, name);
TransformComponent.set_x(sprite, modelX);
TransformComponent.set_y(sprite, modelY);
TextureComponent.set_frame(sprite, (IAssetFrameModel) obj);
newModels.add(sprite);
} else if (obj instanceof BitmapFontAssetModel) {
var asset = (BitmapFontAssetModel) obj;
var textModel = new BitmapTextModel();
var name = nameComputer.newName(asset.getKey());
EditorComponent.set_editorName(textModel, name);
TransformComponent.set_x(textModel, modelX);
TransformComponent.set_y(textModel, modelY);
BitmapTextComponent.set_font(textModel, asset);
TextualComponent.set_text(textModel, "BitmapText");
textModel.updateSizeFromBitmapFont();
newModels.add(textModel);
}
}
for (var model : newModels) {
ParentComponent.addChild(_sceneModel.getRootObject(), model);
}
var afterSnapshot = WorldSnapshotOperation.takeSnapshot(_editor);
_editor.executeOperation(new WorldSnapshotOperation(beforeSnapshot, afterSnapshot, "Drop assets"));
setSelection_from_internal((List) newModels);
redraw();
_editor.refreshOutline();
_editor.setDirty(true);
_editor.getEditorSite().getPage().activate(_editor);
}
public void init(SceneEditor editor) {
_editor = editor;
_sceneModel = editor.getSceneModel();
_renderer = new SceneObjectRenderer(this);
}
public SceneEditor getEditor() {
return _editor;
}
public SceneObjectRenderer getSceneRenderer() {
return _renderer;
}
@Override
public void dispose() {
super.dispose();
_renderer.dispose();
}
@Override
protected void customPaintControl(PaintEvent e) {
_isInteractiveDragging = isInteractiveDragging();
// I dont know why the line width affects the transform in angles of 45.5.
e.gc.setLineWidth(1);
renderBackground(e);
var calc = calc();
renderGrid(e, calc);
var tx = new Transform(e.gc.getDevice());
tx.translate(Y_LABEL_WIDTH, X_LABELS_HEIGHT);
_renderer.renderScene(e.gc, tx, _editor.getSceneModel());
renderBorders(e.gc, calc);
renderSelection(e.gc);
renderInteractiveElements(e.gc);
renderLabels(e, calc);
tx.dispose();
}
private void renderInteractiveElements(GC gc) {
for (var elem : _interactiveTools) {
if (!elem.getModels().isEmpty()) {
elem.render(gc);
}
}
}
private void renderBorders(GC gc, ZoomCalculator calc) {
var view = calc.modelToView(_sceneModel.getBorderX(), _sceneModel.getBorderY(), _sceneModel.getBorderWidth(),
_sceneModel.getBorderHeight());
view.x += Y_LABEL_WIDTH;
view.y += X_LABELS_HEIGHT;
gc.setAlpha(150);
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
gc.drawRectangle(view.x + 1, view.y + 1, view.width, view.height);
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
gc.drawRectangle(view);
gc.setAlpha(255);
}
private void renderSelection(GC gc) {
var selectionColor = SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION);
// var selectionColor = SWTResourceManager.getColor(ColorUtil.WHITE.rgb);
for (var obj : _selection) {
if (obj instanceof ObjectModel) {
var model = (ObjectModel) obj;
gc.setForeground(selectionColor);
var size = _renderer.getObjectSize(model);
var p0 = _renderer.localToScene(model, 0, 0);
var p1 = _renderer.localToScene(model, size[0], 0);
var p2 = _renderer.localToScene(model, size[0], size[1]);
var p3 = _renderer.localToScene(model, 0, size[1]);
drawCorner(gc, p0, p1);
drawCorner(gc, p1, p2);
drawCorner(gc, p2, p3);
drawCorner(gc, p3, p0);
if (!_isInteractiveDragging) {
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
var dxy = PhaserEditorUI.distance(0, 0, size[0], size[1]) * 0.05f;
p0 = _renderer.localToScene(model, -dxy, -dxy);
p1 = _renderer.localToScene(model, size[0] + dxy, -dxy);
p2 = _renderer.localToScene(model, size[0] + dxy, size[1] + dxy);
p3 = _renderer.localToScene(model, -dxy, size[1] + dxy);
drawCorner(gc, p0, p1);
drawCorner(gc, p1, p2);
drawCorner(gc, p2, p3);
drawCorner(gc, p3, p0);
{
dxy *= 4;
p0 = _renderer.localToScene(model, 0, -dxy);
p1 = _renderer.localToScene(model, size[0] + dxy, -dxy);
p2 = _renderer.localToScene(model, size[0] + dxy, size[1] + dxy);
p3 = _renderer.localToScene(model, 0, size[1] + dxy);
var angle = _renderer.globalAngle(model);
var p = p0;
var flipX = model instanceof FlipComponent && FlipComponent.get_flipX(model);
var flipY = model instanceof FlipComponent && FlipComponent.get_flipY(model);
if (flipX && flipY) {
p = p2;
} else if (flipX) {
p = p1;
} else if (flipY) {
p = p3;
}
var tx = new Transform(gc.getDevice());
tx.translate(p[0], p[1]);
tx.rotate(angle);
gc.setTransform(tx);
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
gc.drawText(" " + EditorComponent.get_editorName(model), 0, 0, true);
gc.setTransform(null);
tx.dispose();
}
}
}
}
}
private static void drawCorner(GC gc, float[] p1, float[] p2) {
var vector = new float[] { p2[0] - p1[0], p2[1] - p1[1] };
var d = PhaserEditorUI.distance(0, 0, vector[0], vector[1]);
vector[0] /= d;
vector[1] /= d;
var len = d * 0.2;
gc.drawLine((int) p1[0], (int) p1[1], (int) (p1[0] + vector[0] * len), (int) (p1[1] + vector[1] * len));
gc.drawLine((int) p2[0], (int) p2[1], (int) (p2[0] - vector[0] * len), (int) (p2[1] - vector[1] * len));
}
private void renderBackground(PaintEvent e) {
var gc = e.gc;
gc.setBackground(getBackgroundColor());
gc.setForeground(getGridColor());
gc.fillRectangle(0, 0, e.width, e.height);
}
private Color getGridColor() {
return SWTResourceManager.getColor(_sceneModel.getForegroundColor());
}
private Color getBackgroundColor() {
return SWTResourceManager.getColor(_sceneModel.getBackgroundColor());
}
private void renderGrid(PaintEvent e, ZoomCalculator calc) {
var gc = e.gc;
gc.setForeground(getGridColor());
// paint labels
var initialModelSnapX = 5f;
var initialModelSnapY = 5f;
if (_sceneModel.isSnapEnabled()) {
initialModelSnapX = _sceneModel.getSnapWidth();
initialModelSnapY = _sceneModel.getSnapHeight();
}
var modelSnapX = 10f;
var modelSnapY = 10f;
var viewSnapX = 0f;
var viewSnapY = 0f;
int i = 1;
while (viewSnapX < 30) {
modelSnapX = initialModelSnapX * i;
viewSnapX = calc.modelToViewWidth(modelSnapX);
i++;
}
i = 1;
while (viewSnapY < 30) {
modelSnapY = initialModelSnapY * i;
viewSnapY = calc.modelToViewHeight(modelSnapY);
i++;
}
_renderModelSnapX = modelSnapX;
_renderModelSnapY = modelSnapY;
var modelNextSnapX = modelSnapX * 4;
var modelNextNextSnapX = modelSnapX * 8;
var modelNextSnapY = modelSnapY * 4;
var modelNextNextSnapY = modelSnapY * 8;
var modelStartX = calc.viewToModelX(0);
var modelStartY = calc.viewToModelY(0);
var modelRight = calc.viewToModelX(e.width);
var modelBottom = calc.viewToModelY(e.height);
modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX;
modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY;
i = 0;
while (true) {
var modelX = modelStartX + i * modelSnapX;
if (modelX > modelRight) {
break;
}
if (modelX % modelNextNextSnapX == 0) {
gc.setAlpha(255);
} else if (modelX % modelNextSnapX == 0) {
gc.setAlpha(150);
} else {
gc.setAlpha(100);
}
var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH;
gc.drawLine((int) viewX, X_LABELS_HEIGHT, (int) viewX, e.height);
i++;
}
gc.setAlpha(255);
i = 0;
while (true) {
var modelY = modelStartY + i * modelSnapY;
if (modelY > modelBottom) {
break;
}
var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT;
if (modelY % modelNextNextSnapY == 0) {
gc.setAlpha(255);
} else if (modelY % modelNextSnapY == 0) {
gc.setAlpha(150);
} else {
gc.setAlpha(100);
}
gc.drawLine(X_LABELS_HEIGHT, (int) viewY, e.width, (int) viewY);
i++;
}
gc.setAlpha(255);
}
private void renderLabels(PaintEvent e, ZoomCalculator calc) {
var gc = e.gc;
gc.setForeground(getGridColor());
gc.setBackground(getBackgroundColor());
gc.setAlpha(220);
gc.fillRectangle(0, 0, e.width, X_LABELS_HEIGHT);
gc.fillRectangle(0, 0, Y_LABEL_WIDTH, e.height);
gc.setAlpha(255);
// paint labels
var modelSnapX = _renderModelSnapX;
var modelSnapY = _renderModelSnapY;
var modelStartX = calc.viewToModelX(0);
var modelStartY = calc.viewToModelY(0);
var modelRight = calc.viewToModelX(e.width);
var modelBottom = calc.viewToModelY(e.height);
int i;
i = 2;
while (true) {
float viewSnapX = calc.modelToViewWidth(modelSnapX);
if (viewSnapX > 80) {
break;
}
modelSnapX = _renderModelSnapX * i;
i++;
}
i = 2;
while (true) {
float viewSnapY = calc.modelToViewWidth(modelSnapY);
if (viewSnapY > 80) {
break;
}
modelSnapY = _renderModelSnapY * i;
i++;
}
modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX;
modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY;
i = 0;
while (true) {
var modelX = modelStartX + i * modelSnapX;
if (modelX > modelRight) {
break;
}
var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH;
if (viewX >= Y_LABEL_WIDTH && viewX <= e.width - Y_LABEL_WIDTH) {
String label = Integer.toString((int) modelX);
gc.drawString(label, (int) viewX + 5, 0, true);
gc.drawLine((int) viewX, 0, (int) viewX, X_LABELS_HEIGHT);
}
i++;
}
gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, e.width, X_LABELS_HEIGHT);
i = 0;
while (true) {
var modelY = modelStartY + i * modelSnapY;
if (modelY > modelBottom) {
break;
}
var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT;
if (viewY >= X_LABELS_HEIGHT && viewY <= e.height - X_LABELS_HEIGHT) {
String label = Integer.toString((int) modelY);
var labelExtent = gc.stringExtent(label);
var tx = new Transform(getDisplay());
tx.translate(0, viewY + 5 + labelExtent.x);
tx.rotate(-90);
gc.setTransform(tx);
gc.drawString(label, 0, 0, true);
gc.setTransform(null);
tx.dispose();
gc.drawLine(0, (int) viewY, Y_LABEL_WIDTH, (int) viewY);
}
i++;
}
gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, Y_LABEL_WIDTH, e.height);
gc.setAlpha(255);
}
@Override
protected Point getImageSize() {
return new Point(1, 1);
}
ObjectModel pickObject(int x, int y) {
return pickObject(_sceneModel.getRootObject(), x, y);
}
private ObjectModel pickObject(ObjectModel model, int x, int y) {
if (model instanceof ParentComponent) {
if (EditorComponent.get_editorClosed(model) /* || groupModel.isPrefabInstance() */) {
var polygon = _renderer.getObjectChildrenBounds(model);
if (hitsPolygon(x, y, polygon)) {
if (hitsImage(x, y, model)) {
return model;
}
}
} else {
var children = ParentComponent.get_children(model);
for (int i = children.size() - 1; i >= 0; i--) {
var model2 = children.get(i);
var pick = pickObject(model2, x, y);
if (pick != null) {
return pick;
}
}
}
}
var polygon = _renderer.getObjectBounds(model);
if (hitsPolygon(x, y, polygon)) {
if (hitsImage(x, y, model)) {
return model;
}
}
return null;
}
private boolean hitsImage(int x, int y, ObjectModel model) {
var renderer = getSceneRenderer();
var img = renderer.getModelImageFromCache(model);
var xy = renderer.sceneToLocal(model, x, y);
var imgX = (int) xy[0];
var imgY = (int) xy[1];
if (img == null) {
if (model instanceof ImageModel || model instanceof SpriteModel) {
var frame = TextureComponent.get_frame(model);
if (frame == null) {
return false;
}
img = loadImage(frame.getImageFile());
if (img == null) {
return false;
}
var frameData = frame.getFrameData();
imgX = imgX + frameData.src.x - frameData.dst.x;
imgY = imgY + frameData.src.y - frameData.dst.y;
}
}
if (img == null) {
return false;
}
if (img.getBounds().contains(imgX, imgY)) {
var data = img.getImageData();
var pixel = data.getAlpha(imgX, imgY);
return pixel != 0;
}
return false;
}
void setSelection_from_internal(List<Object> list) {
var sel = new StructuredSelection(list);
_selection = list;
_editor.getEditorSite().getSelectionProvider().setSelection(sel);
if (_editor.getOutline() != null) {
_editor.getOutline().setSelection_from_external(sel);
}
}
private static boolean hitsPolygon(int x, int y, float[] polygon) {
if (polygon == null) {
return false;
}
int npoints = polygon.length / 2;
if (npoints <= 2) {
return false;
}
var xpoints = new int[npoints];
var ypoints = new int[npoints];
for (int i = 0; i < npoints; i++) {
xpoints[i] = (int) polygon[i * 2];
ypoints[i] = (int) polygon[i * 2 + 1];
}
int hits = 0;
int lastx = xpoints[npoints - 1];
int lasty = ypoints[npoints - 1];
int curx, cury;
// Walk the edges of the polygon
for (int i = 0; i < npoints; lastx = curx, lasty = cury, i++) {
curx = xpoints[i];
cury = ypoints[i];
if (cury == lasty) {
continue;
}
int leftx;
if (curx < lastx) {
if (x >= lastx) {
continue;
}
leftx = curx;
} else {
if (x >= curx) {
continue;
}
leftx = lastx;
}
double test1, test2;
if (cury < lasty) {
if (y < cury || y >= lasty) {
continue;
}
if (x < leftx) {
hits++;
continue;
}
test1 = x - curx;
test2 = y - cury;
} else {
if (y < lasty || y >= cury) {
continue;
}
if (x < leftx) {
hits++;
continue;
}
test1 = x - lastx;
test2 = y - lasty;
}
if (test1 < (test2 / (lasty - cury) * (lastx - curx))) {
hits++;
}
}
return ((hits & 1) != 0);
}
public void setSelection_from_external(IStructuredSelection selection) {
_selection = new ArrayList<>(List.of(selection.toArray()));
redraw();
}
public void reveal(ObjectModel model) {
var objBounds = _renderer.getObjectBounds(model);
if (objBounds == null) {
return;
}
var x1 = objBounds[0];
var y1 = objBounds[1];
var x2 = objBounds[4];
var y2 = objBounds[5];
var w = x2 - x1;
var h = y2 - y1;
var canvasBounds = getBounds();
setOffsetX((int) (getOffsetX() - x1 + Y_LABEL_WIDTH + canvasBounds.width / 2 - w / 2));
setOffsetY((int) (getOffsetY() - y1 + X_LABELS_HEIGHT + canvasBounds.height / 2 - h / 2));
redraw();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void selectAll() {
var list = new ArrayList<ObjectModel>();
var root = getEditor().getSceneModel().getRootObject();
root.visitChildren(model -> list.add(model));
setSelection_from_internal((List) list);
redraw();
}
public void delete() {
var beforeData = WorldSnapshotOperation.takeSnapshot(_editor);
for (var obj : _selection) {
var model = (ObjectModel) obj;
ParentComponent.removeFromParent(model);
}
redraw();
_editor.setDirty(true);
_editor.setSelection(StructuredSelection.EMPTY);
var afterData = WorldSnapshotOperation.takeSnapshot(_editor);
_editor.executeOperation(new WorldSnapshotOperation(beforeData, afterData, "Delete objects"));
}
public void copy() {
var sel = new StructuredSelection(
filterChidlren(_selection.stream().map(o -> (ObjectModel) o).collect(toList()))
.stream().map(model -> {
var data = new JSONObject();
data.put(SCENE_COPY_STAMP, true);
model.write(data);
// convert the local position to a global position
if (model instanceof TransformComponent) {
var parent = ParentComponent.get_parent(model);
var globalPoint = new float[] { 0, 0 };
if (parent != null) {
globalPoint = _renderer.localToScene(parent, TransformComponent.get_x(model),
TransformComponent.get_y(model));
}
data.put(TransformComponent.x_name, globalPoint[0]);
data.put(TransformComponent.y_name, globalPoint[1]);
}
return data;
}).toArray());
LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer();
transfer.setSelection(sel);
Clipboard cb = new Clipboard(getDisplay());
cb.setContents(new Object[] { sel.toArray() }, new Transfer[] { transfer });
cb.dispose();
}
public void cut() {
copy();
delete();
}
public void paste() {
var root = getEditor().getSceneModel().getRootObject();
paste(root, true);
}
public void paste(ObjectModel parent, boolean placeAtCursorPosition) {
var beforeData = WorldSnapshotOperation.takeSnapshot(_editor);
LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer();
Clipboard cb = new Clipboard(getDisplay());
Object content = cb.getContents(transfer);
cb.dispose();
if (content == null) {
return;
}
var editor = getEditor();
var project = editor.getEditorInput().getFile().getProject();
var copyElements = ((IStructuredSelection) content).toArray();
List<ObjectModel> pasteModels = new ArrayList<>();
// create the copies
for (var obj : copyElements) {
if (obj instanceof JSONObject) {
var data = (JSONObject) obj;
if (data.has(SCENE_COPY_STAMP)) {
String type = data.getString("-type");
var newModel = SceneModel.createModel(type);
newModel.read(data, project);
pasteModels.add(newModel);
}
}
}
// remove the children
pasteModels = filterChidlren(pasteModels);
var cursorPoint = toControl(getDisplay().getCursorLocation());
var localCursorPoint = _renderer.sceneToLocal(parent, cursorPoint.x, cursorPoint.y);
// set new id and editorName
var nameComputer = new NameComputer(_sceneModel.getRootObject());
float[] offsetPoint;
{
var minX = Float.MAX_VALUE;
var minY = Float.MAX_VALUE;
for (var model : pasteModels) {
if (model instanceof TransformComponent) {
var x = TransformComponent.get_x(model);
var y = TransformComponent.get_y(model);
minX = Math.min(minX, x);
minY = Math.min(minY, y);
}
}
offsetPoint = new float[] { minX - localCursorPoint[0], minY - localCursorPoint[1] };
}
for (var model : pasteModels) {
model.visit(model2 -> {
model2.setId(UUID.randomUUID().toString());
var name = EditorComponent.get_editorName(model2);
name = nameComputer.newName(name);
EditorComponent.set_editorName(model2, name);
});
if (model instanceof TransformComponent) {
// TODO: honor the snapping settings
var x = TransformComponent.get_x(model);
var y = TransformComponent.get_y(model);
if (placeAtCursorPosition) {
// if (offsetPoint == null) {
// offsetPoint = new float[] { x - localCursorPoint[0], y - localCursorPoint[1]
// };
// }
TransformComponent.set_x(model, x - offsetPoint[0]);
TransformComponent.set_y(model, y - offsetPoint[1]);
} else {
var point = _renderer.sceneToLocal(parent, x, y);
TransformComponent.set_x(model, point[0]);
TransformComponent.set_y(model, point[1]);
}
}
}
// add to the root object
for (var model : pasteModels) {
ParentComponent.addChild(parent, model);
}
editor.setSelection(new StructuredSelection(pasteModels));
editor.setDirty(true);
var afterData = WorldSnapshotOperation.takeSnapshot(_editor);
_editor.executeOperation(new WorldSnapshotOperation(beforeData, afterData, "Paste objects."));
}
public static List<ObjectModel> filterChidlren(List<ObjectModel> models) {
var result = new ArrayList<>(models);
for (var i = 0; i < models.size(); i++) {
for (var j = 0; j < models.size(); j++) {
if (i != j) {
var a = models.get(i);
var b = models.get(j);
if (ParentComponent.isDescendentOf(a, b)) {
result.remove(a);
}
}
}
}
return result;
}
@Override
public void mouseDoubleClick(MouseEvent e) {
//
}
@Override
public void mouseDown(MouseEvent e) {
if (e.button != 1) {
return;
}
for (var elem : _interactiveTools) {
elem.mouseDown(e);
}
}
@Override
public void mouseUp(MouseEvent e) {
if (e.button != 1) {
return;
}
boolean contains = false;
for (var elem : _interactiveTools) {
if (elem.contains(e.x, e.y)) {
contains = true;
break;
}
}
if (contains) {
for (var elem : _interactiveTools) {
elem.mouseUp(e);
}
}
if (_dragDetected) {
_dragDetected = false;
if (_dragObjectsEvents.isDragging()) {
_dragObjectsEvents.done();
}
return;
}
if (!contains) {
_selectionEvents.updateSelection(e);
}
}
@Override
public void mouseMove(MouseEvent e) {
boolean contains = false;
for (var elem : _interactiveTools) {
if (elem.contains(e.x, e.y)) {
contains = true;
}
}
if (contains) {
for (var elem : _interactiveTools) {
elem.mouseMove(e);
}
} else {
if (_dragObjectsEvents.isDragging()) {
_dragObjectsEvents.update(e);
}
}
if (!_interactiveTools.isEmpty()) {
redraw();
}
}
private boolean _dragDetected;
@Override
public void dragDetected(DragDetectEvent e) {
_dragDetected = true;
var obj = pickObject(e.x, e.y);
if (_selection.contains(obj)) {
_dragObjectsEvents.start(e);
}
}
public boolean isInteractiveDragging() {
for (var elem : _interactiveTools) {
if (elem.isDragging()) {
return true;
}
}
return false;
}
public List<Object> getSelection() {
return _selection;
}
}
|
source/v2/phasereditor/phasereditor.scene.ui/src/phasereditor/scene/ui/editor/SceneCanvas.java
|
// The MIT License (MIT)
//
// Copyright (c) 2015, 2018 Arian Fornaris
//
// 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 phasereditor.scene.ui.editor;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DragDetectEvent;
import org.eclipse.swt.events.DragDetectListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.wb.swt.SWTResourceManager;
import org.json.JSONObject;
import phasereditor.assetpack.core.BitmapFontAssetModel;
import phasereditor.assetpack.core.IAssetFrameModel;
import phasereditor.assetpack.core.ImageAssetModel;
import phasereditor.scene.core.BitmapTextComponent;
import phasereditor.scene.core.BitmapTextModel;
import phasereditor.scene.core.EditorComponent;
import phasereditor.scene.core.ImageModel;
import phasereditor.scene.core.NameComputer;
import phasereditor.scene.core.ObjectModel;
import phasereditor.scene.core.ParentComponent;
import phasereditor.scene.core.SceneModel;
import phasereditor.scene.core.SpriteModel;
import phasereditor.scene.core.TextualComponent;
import phasereditor.scene.core.TextureComponent;
import phasereditor.scene.core.TransformComponent;
import phasereditor.scene.ui.editor.interactive.InteractiveTool;
import phasereditor.scene.ui.editor.undo.WorldSnapshotOperation;
import phasereditor.ui.PhaserEditorUI;
import phasereditor.ui.ZoomCanvas;
/**
* @author arian
*
*/
public class SceneCanvas extends ZoomCanvas implements MouseListener, MouseMoveListener, DragDetectListener {
private static final String SCENE_COPY_STAMP = "--scene--copy--stamp--";
public static final int X_LABELS_HEIGHT = 18;
public static final int Y_LABEL_WIDTH = 18;
private SceneEditor _editor;
private SceneObjectRenderer _renderer;
private float _renderModelSnapX;
private float _renderModelSnapY;
List<Object> _selection;
private SceneModel _sceneModel;
private DragObjectsEvents _dragObjectsEvents;
private SelectionEvents _selectionEvents;
private List<InteractiveTool> _interactiveTools;
private boolean _transformLocalCoords;
public SceneCanvas(Composite parent, int style) {
super(parent, style);
_selection = new ArrayList<>();
addPaintListener(this);
_dragObjectsEvents = new DragObjectsEvents(this);
_selectionEvents = new SelectionEvents(this);
addDragDetectListener(this);
addMouseListener(this);
addMouseMoveListener(this);
init_DND();
setZoomWhenShiftPressed(false);
_interactiveTools = new ArrayList<>();
_transformLocalCoords = true;
}
public boolean isTransformLocalCoords() {
return _transformLocalCoords;
}
public void setTransformLocalCoords(boolean transformLocalCoords) {
_transformLocalCoords = transformLocalCoords;
}
public List<InteractiveTool> getInteractiveTools() {
return _interactiveTools;
}
public void setInteractiveTools(InteractiveTool... tools) {
_interactiveTools = Arrays.asList(tools);
getEditor().updatePropertyPagesContentWithSelection();
redraw();
}
public boolean hasInteractiveTool(Class<?> cls) {
for (var tool : _interactiveTools) {
if (cls.isInstance(tool)) {
return true;
}
}
return false;
}
private void init_DND() {
{
int options = DND.DROP_MOVE | DND.DROP_DEFAULT;
DropTarget target = new DropTarget(this, options);
Transfer[] types = { LocalSelectionTransfer.getTransfer() };
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
@Override
public void drop(DropTargetEvent event) {
var loc = toDisplay(0, 0);
var x = event.x - loc.x;
var y = event.y - loc.y;
if (event.data instanceof Object[]) {
selectionDropped(x, y, (Object[]) event.data);
}
if (event.data instanceof IStructuredSelection) {
selectionDropped(x, y, ((IStructuredSelection) event.data).toArray());
}
}
});
}
}
public float[] viewToModel(int x, int y) {
var calc = calc();
var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH;
var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT;
return new float[] { modelX, modelY };
}
public float[] modelToView(int x, int y) {
var calc = calc();
var viewX = calc.modelToViewX(x) + Y_LABEL_WIDTH;
var viewY = calc.modelToViewY(y) + X_LABELS_HEIGHT;
return new float[] { viewX, viewY };
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void selectionDropped(int x, int y, Object[] data) {
var nameComputer = new NameComputer(_sceneModel.getRootObject());
var beforeSnapshot = WorldSnapshotOperation.takeSnapshot(_editor);
var calc = calc();
var modelX = calc.viewToModelX(x) - Y_LABEL_WIDTH;
var modelY = calc.viewToModelY(y) - X_LABELS_HEIGHT;
var newModels = new ArrayList<ObjectModel>();
for (var obj : data) {
if (obj instanceof ImageAssetModel) {
obj = ((ImageAssetModel) obj).getFrame();
}
if (obj instanceof IAssetFrameModel) {
var frame = (IAssetFrameModel) obj;
var sprite = new ImageModel();
var name = nameComputer.newName(frame.getKey());
EditorComponent.set_editorName(sprite, name);
TransformComponent.set_x(sprite, modelX);
TransformComponent.set_y(sprite, modelY);
TextureComponent.set_frame(sprite, (IAssetFrameModel) obj);
newModels.add(sprite);
} else if (obj instanceof BitmapFontAssetModel) {
var asset = (BitmapFontAssetModel) obj;
var textModel = new BitmapTextModel();
var name = nameComputer.newName(asset.getKey());
EditorComponent.set_editorName(textModel, name);
TransformComponent.set_x(textModel, modelX);
TransformComponent.set_y(textModel, modelY);
BitmapTextComponent.set_font(textModel, asset);
TextualComponent.set_text(textModel, "BitmapText");
textModel.updateSizeFromBitmapFont();
newModels.add(textModel);
}
}
for (var model : newModels) {
ParentComponent.addChild(_sceneModel.getRootObject(), model);
}
var afterSnapshot = WorldSnapshotOperation.takeSnapshot(_editor);
_editor.executeOperation(new WorldSnapshotOperation(beforeSnapshot, afterSnapshot, "Drop assets"));
setSelection_from_internal((List) newModels);
redraw();
_editor.refreshOutline();
_editor.setDirty(true);
_editor.getEditorSite().getPage().activate(_editor);
}
public void init(SceneEditor editor) {
_editor = editor;
_sceneModel = editor.getSceneModel();
_renderer = new SceneObjectRenderer(this);
}
public SceneEditor getEditor() {
return _editor;
}
public SceneObjectRenderer getSceneRenderer() {
return _renderer;
}
@Override
public void dispose() {
super.dispose();
_renderer.dispose();
}
@Override
protected void customPaintControl(PaintEvent e) {
// I dont know why the line width affects the transform in angles of 45.5.
e.gc.setLineWidth(1);
renderBackground(e);
var calc = calc();
renderGrid(e, calc);
var tx = new Transform(e.gc.getDevice());
tx.translate(Y_LABEL_WIDTH, X_LABELS_HEIGHT);
_renderer.renderScene(e.gc, tx, _editor.getSceneModel());
renderBorders(e.gc, calc);
renderSelection(e.gc);
renderInteractiveElements(e.gc);
renderLabels(e, calc);
tx.dispose();
}
private void renderInteractiveElements(GC gc) {
for (var elem : _interactiveTools) {
if (!elem.getModels().isEmpty()) {
elem.render(gc);
}
}
}
private void renderBorders(GC gc, ZoomCalculator calc) {
var view = calc.modelToView(_sceneModel.getBorderX(), _sceneModel.getBorderY(), _sceneModel.getBorderWidth(),
_sceneModel.getBorderHeight());
view.x += Y_LABEL_WIDTH;
view.y += X_LABELS_HEIGHT;
gc.setAlpha(150);
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
gc.drawRectangle(view.x + 1, view.y + 1, view.width, view.height);
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
gc.drawRectangle(view);
gc.setAlpha(255);
}
private void renderSelection(GC gc) {
var selectionColor = SWTResourceManager.getColor(SWT.COLOR_LIST_SELECTION);
// var selectionColor = SWTResourceManager.getColor(ColorUtil.WHITE.rgb);
for (var obj : _selection) {
if (obj instanceof ObjectModel) {
var model = (ObjectModel) obj;
// var bounds = _renderer.getObjectBounds(model);
//
// if (obj instanceof ParentComponent) {
// if (!ParentComponent.get_children(model).isEmpty()) {
// var childrenBounds = _renderer.getObjectChildrenBounds(model);
//
// if (childrenBounds != null) {
//
// var merge = SceneObjectRenderer.joinBounds(bounds, childrenBounds);
//
// gc.setForeground(selectionColor);
//
// gc.drawPolygon(new int[] { (int) merge[0], (int) merge[1], (int) merge[2],
// (int) merge[3],
// (int) merge[4], (int) merge[5], (int) merge[6], (int) merge[7] });
// }
//
// }
// }
{
// paint selection borders
gc.setForeground(selectionColor);
var size = _renderer.getObjectSize(model);
var p0 = _renderer.localToScene(model, 0, 0);
var p1 = _renderer.localToScene(model, size[0], 0);
var p2 = _renderer.localToScene(model, size[0], size[1]);
var p3 = _renderer.localToScene(model, 0, size[1]);
drawCorner(gc, p0, p1);
drawCorner(gc, p1, p2);
drawCorner(gc, p2, p3);
drawCorner(gc, p3, p0);
if (!isInteractiveDragging()) {
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
var dxy = PhaserEditorUI.distance(0, 0, size[0], size[1]) * 0.05f;
p0 = _renderer.localToScene(model, -dxy, -dxy);
p1 = _renderer.localToScene(model, size[0] + dxy, -dxy);
p2 = _renderer.localToScene(model, size[0] + dxy, size[1] + dxy);
p3 = _renderer.localToScene(model, -dxy, size[1] + dxy);
drawCorner(gc, p0, p1);
drawCorner(gc, p1, p2);
drawCorner(gc, p2, p3);
drawCorner(gc, p3, p0);
}
}
}
}
}
private static void drawCorner(GC gc, float[] p1, float[] p2) {
var vector = new float[] { p2[0] - p1[0], p2[1] - p1[1] };
var d = PhaserEditorUI.distance(0, 0, vector[0], vector[1]);
vector[0] /= d;
vector[1] /= d;
var len = d * 0.2;
gc.drawLine((int) p1[0], (int) p1[1], (int) (p1[0] + vector[0] * len), (int) (p1[1] + vector[1] * len));
gc.drawLine((int) p2[0], (int) p2[1], (int) (p2[0] - vector[0] * len), (int) (p2[1] - vector[1] * len));
}
private void renderBackground(PaintEvent e) {
var gc = e.gc;
gc.setBackground(getBackgroundColor());
gc.setForeground(getGridColor());
gc.fillRectangle(0, 0, e.width, e.height);
}
private Color getGridColor() {
return SWTResourceManager.getColor(_sceneModel.getForegroundColor());
}
private Color getBackgroundColor() {
return SWTResourceManager.getColor(_sceneModel.getBackgroundColor());
}
private void renderGrid(PaintEvent e, ZoomCalculator calc) {
var gc = e.gc;
gc.setForeground(getGridColor());
// paint labels
var initialModelSnapX = 5f;
var initialModelSnapY = 5f;
if (_sceneModel.isSnapEnabled()) {
initialModelSnapX = _sceneModel.getSnapWidth();
initialModelSnapY = _sceneModel.getSnapHeight();
}
var modelSnapX = 10f;
var modelSnapY = 10f;
var viewSnapX = 0f;
var viewSnapY = 0f;
int i = 1;
while (viewSnapX < 30) {
modelSnapX = initialModelSnapX * i;
viewSnapX = calc.modelToViewWidth(modelSnapX);
i++;
}
i = 1;
while (viewSnapY < 30) {
modelSnapY = initialModelSnapY * i;
viewSnapY = calc.modelToViewHeight(modelSnapY);
i++;
}
_renderModelSnapX = modelSnapX;
_renderModelSnapY = modelSnapY;
var modelNextSnapX = modelSnapX * 4;
var modelNextNextSnapX = modelSnapX * 8;
var modelNextSnapY = modelSnapY * 4;
var modelNextNextSnapY = modelSnapY * 8;
var modelStartX = calc.viewToModelX(0);
var modelStartY = calc.viewToModelY(0);
var modelRight = calc.viewToModelX(e.width);
var modelBottom = calc.viewToModelY(e.height);
modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX;
modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY;
i = 0;
while (true) {
var modelX = modelStartX + i * modelSnapX;
if (modelX > modelRight) {
break;
}
if (modelX % modelNextNextSnapX == 0) {
gc.setAlpha(255);
} else if (modelX % modelNextSnapX == 0) {
gc.setAlpha(150);
} else {
gc.setAlpha(100);
}
var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH;
gc.drawLine((int) viewX, X_LABELS_HEIGHT, (int) viewX, e.height);
i++;
}
gc.setAlpha(255);
i = 0;
while (true) {
var modelY = modelStartY + i * modelSnapY;
if (modelY > modelBottom) {
break;
}
var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT;
if (modelY % modelNextNextSnapY == 0) {
gc.setAlpha(255);
} else if (modelY % modelNextSnapY == 0) {
gc.setAlpha(150);
} else {
gc.setAlpha(100);
}
gc.drawLine(X_LABELS_HEIGHT, (int) viewY, e.width, (int) viewY);
i++;
}
gc.setAlpha(255);
}
private void renderLabels(PaintEvent e, ZoomCalculator calc) {
var gc = e.gc;
gc.setForeground(getGridColor());
gc.setBackground(getBackgroundColor());
gc.setAlpha(220);
gc.fillRectangle(0, 0, e.width, X_LABELS_HEIGHT);
gc.fillRectangle(0, 0, Y_LABEL_WIDTH, e.height);
gc.setAlpha(255);
// paint labels
var modelSnapX = _renderModelSnapX;
var modelSnapY = _renderModelSnapY;
var modelStartX = calc.viewToModelX(0);
var modelStartY = calc.viewToModelY(0);
var modelRight = calc.viewToModelX(e.width);
var modelBottom = calc.viewToModelY(e.height);
int i;
i = 2;
while (true) {
float viewSnapX = calc.modelToViewWidth(modelSnapX);
if (viewSnapX > 80) {
break;
}
modelSnapX = _renderModelSnapX * i;
i++;
}
i = 2;
while (true) {
float viewSnapY = calc.modelToViewWidth(modelSnapY);
if (viewSnapY > 80) {
break;
}
modelSnapY = _renderModelSnapY * i;
i++;
}
modelStartX = (int) (modelStartX / modelSnapX) * modelSnapX;
modelStartY = (int) (modelStartY / modelSnapY) * modelSnapY;
i = 0;
while (true) {
var modelX = modelStartX + i * modelSnapX;
if (modelX > modelRight) {
break;
}
var viewX = calc.modelToViewX(modelX) + Y_LABEL_WIDTH;
if (viewX >= Y_LABEL_WIDTH && viewX <= e.width - Y_LABEL_WIDTH) {
String label = Integer.toString((int) modelX);
gc.drawString(label, (int) viewX + 5, 0, true);
gc.drawLine((int) viewX, 0, (int) viewX, X_LABELS_HEIGHT);
}
i++;
}
gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, e.width, X_LABELS_HEIGHT);
i = 0;
while (true) {
var modelY = modelStartY + i * modelSnapY;
if (modelY > modelBottom) {
break;
}
var viewY = calc.modelToViewY(modelY) + X_LABELS_HEIGHT;
if (viewY >= X_LABELS_HEIGHT && viewY <= e.height - X_LABELS_HEIGHT) {
String label = Integer.toString((int) modelY);
var labelExtent = gc.stringExtent(label);
var tx = new Transform(getDisplay());
tx.translate(0, viewY + 5 + labelExtent.x);
tx.rotate(-90);
gc.setTransform(tx);
gc.drawString(label, 0, 0, true);
gc.setTransform(null);
tx.dispose();
gc.drawLine(0, (int) viewY, Y_LABEL_WIDTH, (int) viewY);
}
i++;
}
gc.drawLine(Y_LABEL_WIDTH, X_LABELS_HEIGHT, Y_LABEL_WIDTH, e.height);
gc.setAlpha(255);
}
@Override
protected Point getImageSize() {
return new Point(1, 1);
}
ObjectModel pickObject(int x, int y) {
return pickObject(_sceneModel.getRootObject(), x, y);
}
private ObjectModel pickObject(ObjectModel model, int x, int y) {
if (model instanceof ParentComponent) {
if (EditorComponent.get_editorClosed(model) /* || groupModel.isPrefabInstance() */) {
var polygon = _renderer.getObjectChildrenBounds(model);
if (hitsPolygon(x, y, polygon)) {
if (hitsImage(x, y, model)) {
return model;
}
}
} else {
var children = ParentComponent.get_children(model);
for (int i = children.size() - 1; i >= 0; i--) {
var model2 = children.get(i);
var pick = pickObject(model2, x, y);
if (pick != null) {
return pick;
}
}
}
}
var polygon = _renderer.getObjectBounds(model);
if (hitsPolygon(x, y, polygon)) {
if (hitsImage(x, y, model)) {
return model;
}
}
return null;
}
private boolean hitsImage(int x, int y, ObjectModel model) {
var renderer = getSceneRenderer();
var img = renderer.getModelImageFromCache(model);
var xy = renderer.sceneToLocal(model, x, y);
var imgX = (int) xy[0];
var imgY = (int) xy[1];
if (img == null) {
if (model instanceof ImageModel || model instanceof SpriteModel) {
var frame = TextureComponent.get_frame(model);
if (frame == null) {
return false;
}
img = loadImage(frame.getImageFile());
if (img == null) {
return false;
}
var frameData = frame.getFrameData();
imgX = imgX + frameData.src.x - frameData.dst.x;
imgY = imgY + frameData.src.y - frameData.dst.y;
}
}
if (img == null) {
return false;
}
if (img.getBounds().contains(imgX, imgY)) {
var data = img.getImageData();
var pixel = data.getAlpha(imgX, imgY);
return pixel != 0;
}
return false;
}
void setSelection_from_internal(List<Object> list) {
var sel = new StructuredSelection(list);
_selection = list;
_editor.getEditorSite().getSelectionProvider().setSelection(sel);
if (_editor.getOutline() != null) {
_editor.getOutline().setSelection_from_external(sel);
}
}
private static boolean hitsPolygon(int x, int y, float[] polygon) {
if (polygon == null) {
return false;
}
int npoints = polygon.length / 2;
if (npoints <= 2) {
return false;
}
var xpoints = new int[npoints];
var ypoints = new int[npoints];
for (int i = 0; i < npoints; i++) {
xpoints[i] = (int) polygon[i * 2];
ypoints[i] = (int) polygon[i * 2 + 1];
}
int hits = 0;
int lastx = xpoints[npoints - 1];
int lasty = ypoints[npoints - 1];
int curx, cury;
// Walk the edges of the polygon
for (int i = 0; i < npoints; lastx = curx, lasty = cury, i++) {
curx = xpoints[i];
cury = ypoints[i];
if (cury == lasty) {
continue;
}
int leftx;
if (curx < lastx) {
if (x >= lastx) {
continue;
}
leftx = curx;
} else {
if (x >= curx) {
continue;
}
leftx = lastx;
}
double test1, test2;
if (cury < lasty) {
if (y < cury || y >= lasty) {
continue;
}
if (x < leftx) {
hits++;
continue;
}
test1 = x - curx;
test2 = y - cury;
} else {
if (y < lasty || y >= cury) {
continue;
}
if (x < leftx) {
hits++;
continue;
}
test1 = x - lastx;
test2 = y - lasty;
}
if (test1 < (test2 / (lasty - cury) * (lastx - curx))) {
hits++;
}
}
return ((hits & 1) != 0);
}
public void setSelection_from_external(IStructuredSelection selection) {
_selection = new ArrayList<>(List.of(selection.toArray()));
redraw();
}
public void reveal(ObjectModel model) {
var objBounds = _renderer.getObjectBounds(model);
if (objBounds == null) {
return;
}
var x1 = objBounds[0];
var y1 = objBounds[1];
var x2 = objBounds[4];
var y2 = objBounds[5];
var w = x2 - x1;
var h = y2 - y1;
var canvasBounds = getBounds();
setOffsetX((int) (getOffsetX() - x1 + Y_LABEL_WIDTH + canvasBounds.width / 2 - w / 2));
setOffsetY((int) (getOffsetY() - y1 + X_LABELS_HEIGHT + canvasBounds.height / 2 - h / 2));
redraw();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void selectAll() {
var list = new ArrayList<ObjectModel>();
var root = getEditor().getSceneModel().getRootObject();
root.visitChildren(model -> list.add(model));
setSelection_from_internal((List) list);
redraw();
}
public void delete() {
var beforeData = WorldSnapshotOperation.takeSnapshot(_editor);
for (var obj : _selection) {
var model = (ObjectModel) obj;
ParentComponent.removeFromParent(model);
}
redraw();
_editor.setDirty(true);
_editor.setSelection(StructuredSelection.EMPTY);
var afterData = WorldSnapshotOperation.takeSnapshot(_editor);
_editor.executeOperation(new WorldSnapshotOperation(beforeData, afterData, "Delete objects"));
}
public void copy() {
var sel = new StructuredSelection(
filterChidlren(_selection.stream().map(o -> (ObjectModel) o).collect(toList()))
.stream().map(model -> {
var data = new JSONObject();
data.put(SCENE_COPY_STAMP, true);
model.write(data);
// convert the local position to a global position
if (model instanceof TransformComponent) {
var parent = ParentComponent.get_parent(model);
var globalPoint = new float[] { 0, 0 };
if (parent != null) {
globalPoint = _renderer.localToScene(parent, TransformComponent.get_x(model),
TransformComponent.get_y(model));
}
data.put(TransformComponent.x_name, globalPoint[0]);
data.put(TransformComponent.y_name, globalPoint[1]);
}
return data;
}).toArray());
LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer();
transfer.setSelection(sel);
Clipboard cb = new Clipboard(getDisplay());
cb.setContents(new Object[] { sel.toArray() }, new Transfer[] { transfer });
cb.dispose();
}
public void cut() {
copy();
delete();
}
public void paste() {
var root = getEditor().getSceneModel().getRootObject();
paste(root, true);
}
public void paste(ObjectModel parent, boolean placeAtCursorPosition) {
var beforeData = WorldSnapshotOperation.takeSnapshot(_editor);
LocalSelectionTransfer transfer = LocalSelectionTransfer.getTransfer();
Clipboard cb = new Clipboard(getDisplay());
Object content = cb.getContents(transfer);
cb.dispose();
if (content == null) {
return;
}
var editor = getEditor();
var project = editor.getEditorInput().getFile().getProject();
var copyElements = ((IStructuredSelection) content).toArray();
List<ObjectModel> pasteModels = new ArrayList<>();
// create the copies
for (var obj : copyElements) {
if (obj instanceof JSONObject) {
var data = (JSONObject) obj;
if (data.has(SCENE_COPY_STAMP)) {
String type = data.getString("-type");
var newModel = SceneModel.createModel(type);
newModel.read(data, project);
pasteModels.add(newModel);
}
}
}
// remove the children
pasteModels = filterChidlren(pasteModels);
var cursorPoint = toControl(getDisplay().getCursorLocation());
var localCursorPoint = _renderer.sceneToLocal(parent, cursorPoint.x, cursorPoint.y);
// set new id and editorName
var nameComputer = new NameComputer(_sceneModel.getRootObject());
float[] offsetPoint;
{
var minX = Float.MAX_VALUE;
var minY = Float.MAX_VALUE;
for (var model : pasteModels) {
if (model instanceof TransformComponent) {
var x = TransformComponent.get_x(model);
var y = TransformComponent.get_y(model);
minX = Math.min(minX, x);
minY = Math.min(minY, y);
}
}
offsetPoint = new float[] { minX - localCursorPoint[0], minY - localCursorPoint[1] };
}
for (var model : pasteModels) {
model.visit(model2 -> {
model2.setId(UUID.randomUUID().toString());
var name = EditorComponent.get_editorName(model2);
name = nameComputer.newName(name);
EditorComponent.set_editorName(model2, name);
});
if (model instanceof TransformComponent) {
// TODO: honor the snapping settings
var x = TransformComponent.get_x(model);
var y = TransformComponent.get_y(model);
if (placeAtCursorPosition) {
// if (offsetPoint == null) {
// offsetPoint = new float[] { x - localCursorPoint[0], y - localCursorPoint[1]
// };
// }
TransformComponent.set_x(model, x - offsetPoint[0]);
TransformComponent.set_y(model, y - offsetPoint[1]);
} else {
var point = _renderer.sceneToLocal(parent, x, y);
TransformComponent.set_x(model, point[0]);
TransformComponent.set_y(model, point[1]);
}
}
}
// add to the root object
for (var model : pasteModels) {
ParentComponent.addChild(parent, model);
}
editor.setSelection(new StructuredSelection(pasteModels));
editor.setDirty(true);
var afterData = WorldSnapshotOperation.takeSnapshot(_editor);
_editor.executeOperation(new WorldSnapshotOperation(beforeData, afterData, "Paste objects."));
}
public static List<ObjectModel> filterChidlren(List<ObjectModel> models) {
var result = new ArrayList<>(models);
for (var i = 0; i < models.size(); i++) {
for (var j = 0; j < models.size(); j++) {
if (i != j) {
var a = models.get(i);
var b = models.get(j);
if (ParentComponent.isDescendentOf(a, b)) {
result.remove(a);
}
}
}
}
return result;
}
@Override
public void mouseDoubleClick(MouseEvent e) {
//
}
@Override
public void mouseDown(MouseEvent e) {
if (e.button != 1) {
return;
}
for (var elem : _interactiveTools) {
elem.mouseDown(e);
}
}
@Override
public void mouseUp(MouseEvent e) {
if (e.button != 1) {
return;
}
boolean contains = false;
for (var elem : _interactiveTools) {
if (elem.contains(e.x, e.y)) {
contains = true;
break;
}
}
if (contains) {
for (var elem : _interactiveTools) {
elem.mouseUp(e);
}
}
if (_dragDetected) {
_dragDetected = false;
if (_dragObjectsEvents.isDragging()) {
_dragObjectsEvents.done();
}
return;
}
if (!contains) {
_selectionEvents.updateSelection(e);
}
}
@Override
public void mouseMove(MouseEvent e) {
boolean contains = false;
for (var elem : _interactiveTools) {
if (elem.contains(e.x, e.y)) {
contains = true;
}
}
if (contains) {
for (var elem : _interactiveTools) {
elem.mouseMove(e);
}
} else {
if (_dragObjectsEvents.isDragging()) {
_dragObjectsEvents.update(e);
}
}
if (!_interactiveTools.isEmpty()) {
redraw();
}
}
private boolean _dragDetected;
@Override
public void dragDetected(DragDetectEvent e) {
_dragDetected = true;
var obj = pickObject(e.x, e.y);
if (_selection.contains(obj)) {
_dragObjectsEvents.start(e);
}
}
public boolean isInteractiveDragging() {
for (var elem : _interactiveTools) {
if (elem.isDragging()) {
return true;
}
}
return false;
}
public List<Object> getSelection() {
return _selection;
}
}
|
(v2) Scene editor: fix regression to render selection labels.
|
source/v2/phasereditor/phasereditor.scene.ui/src/phasereditor/scene/ui/editor/SceneCanvas.java
|
(v2) Scene editor: fix regression to render selection labels.
|
|
Java
|
epl-1.0
|
08f27c067bfdd1e59a19b036e4e07f96c2822c51
| 0
|
subclipse/subclipse,subclipse/subclipse,subclipse/subclipse
|
/*******************************************************************************
* Copyright (c) 2006 Subclipse project and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subclipse project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.subclipse.ui.history;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextViewer;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.jface.text.hyperlink.IHyperlinkDetector;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.variants.IResourceVariant;
import org.eclipse.team.ui.history.HistoryPage;
import org.eclipse.team.ui.history.IHistoryPageSite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.TextSourceViewerConfiguration;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.tigris.subversion.subclipse.core.IResourceStateChangeListener;
import org.tigris.subversion.subclipse.core.ISVNLocalFile;
import org.tigris.subversion.subclipse.core.ISVNLocalResource;
import org.tigris.subversion.subclipse.core.ISVNRemoteFile;
import org.tigris.subversion.subclipse.core.ISVNRemoteResource;
import org.tigris.subversion.subclipse.core.ISVNResource;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.SVNProviderPlugin;
import org.tigris.subversion.subclipse.core.SVNStatus;
import org.tigris.subversion.subclipse.core.SVNTeamProvider;
import org.tigris.subversion.subclipse.core.commands.ChangeCommitPropertiesCommand;
import org.tigris.subversion.subclipse.core.commands.GetLogsCommand;
import org.tigris.subversion.subclipse.core.history.AliasManager;
import org.tigris.subversion.subclipse.core.history.ILogEntry;
import org.tigris.subversion.subclipse.core.history.LogEntry;
import org.tigris.subversion.subclipse.core.history.LogEntryChangePath;
import org.tigris.subversion.subclipse.core.resources.LocalResourceStatus;
import org.tigris.subversion.subclipse.core.resources.RemoteFolder;
import org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot;
import org.tigris.subversion.subclipse.ui.IHelpContextIds;
import org.tigris.subversion.subclipse.ui.ISVNUIConstants;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.subclipse.ui.SVNUIPlugin;
import org.tigris.subversion.subclipse.ui.actions.ExportRemoteFolderAction;
import org.tigris.subversion.subclipse.ui.actions.GenerateChangeLogAction;
import org.tigris.subversion.subclipse.ui.actions.OpenRemoteFileAction;
import org.tigris.subversion.subclipse.ui.actions.ShowAnnotationAction;
import org.tigris.subversion.subclipse.ui.actions.ShowDifferencesAsUnifiedDiffAction;
import org.tigris.subversion.subclipse.ui.actions.ShowHistoryAction;
import org.tigris.subversion.subclipse.ui.actions.WorkspaceAction;
import org.tigris.subversion.subclipse.ui.console.TextViewerAction;
import org.tigris.subversion.subclipse.ui.dialogs.HistorySearchDialog;
import org.tigris.subversion.subclipse.ui.dialogs.SetCommitPropertiesDialog;
import org.tigris.subversion.subclipse.ui.dialogs.ShowRevisionsDialog;
import org.tigris.subversion.subclipse.ui.internal.Utils;
import org.tigris.subversion.subclipse.ui.operations.BranchTagOperation;
import org.tigris.subversion.subclipse.ui.operations.MergeOperation;
import org.tigris.subversion.subclipse.ui.operations.ReplaceOperation;
import org.tigris.subversion.subclipse.ui.operations.SwitchOperation;
import org.tigris.subversion.subclipse.ui.settings.ProjectProperties;
import org.tigris.subversion.subclipse.ui.util.EmptySearchViewerFilter;
import org.tigris.subversion.subclipse.ui.util.LinkList;
import org.tigris.subversion.subclipse.ui.wizards.BranchTagWizard;
import org.tigris.subversion.subclipse.ui.wizards.ClosableWizardDialog;
import org.tigris.subversion.subclipse.ui.wizards.dialogs.SvnWizard;
import org.tigris.subversion.subclipse.ui.wizards.dialogs.SvnWizardDialog;
import org.tigris.subversion.subclipse.ui.wizards.dialogs.SvnWizardSwitchPage;
import org.tigris.subversion.svnclientadapter.ISVNClientAdapter;
import org.tigris.subversion.svnclientadapter.ISVNProperty;
import org.tigris.subversion.svnclientadapter.SVNRevision;
import org.tigris.subversion.svnclientadapter.SVNUrl;
/**
* <code>IHistoryPage</code> for generic history view
*
* @author Eugene Kuleshov (migration from legacy history view)
*/
public class SVNHistoryPage extends HistoryPage implements IResourceStateChangeListener, KeyListener {
private SashForm svnHistoryPageControl;
private SashForm innerSashForm;
private HistorySearchDialog historySearchDialog;
HistoryTableProvider historyTableProvider;
TableViewer tableHistoryViewer;
StructuredViewer changePathsViewer;
TextViewer textViewer;
private boolean showComments;
private boolean showAffectedPaths;
private boolean wrapCommentsText;
boolean shutdown = false;
private ProjectProperties projectProperties;
private Composite tableParent;
private static HistorySearchViewerFilter historySearchViewerFilter;
// cached for efficiency
ILogEntry[] entries;
LogEntryChangePath[] currentLogEntryChangePath;
ILogEntry lastEntry;
SVNRevision revisionStart = SVNRevision.HEAD;
AbstractFetchJob fetchLogEntriesJob = null;
AbstractFetchJob fetchAllLogEntriesJob = null;
AbstractFetchJob fetchNextLogEntriesJob = null;
FetchChangePathJob fetchChangePathJob = null;
AliasManager tagManager;
IResource resource;
ISVNRemoteResource remoteResource;
ISelection selection;
private IAction searchAction;
private IAction clearSearchAction;
private IAction getNextAction;
private IAction getAllAction;
private IAction toggleStopOnCopyAction;
private IAction toggleIncludeMergedRevisionsAction;
private IAction toggleShowComments;
private IAction toggleWrapCommentsAction;
private IAction toggleShowAffectedPathsAction;
private IAction openAction;
private IAction getContentsAction;
private IAction updateToRevisionAction;
private IAction openChangedPathAction;
private IAction showHistoryAction;
private IAction compareAction;
private IAction showAnnotationAction;
private IAction exportAction;
private IAction createTagFromRevisionChangedPathAction;
// private IAction switchChangedPathAction;
// private IAction revertChangesChangedPathAction;
private IAction createTagFromRevisionAction;
private IAction setCommitPropertiesAction;
private IAction showRevisionsAction;
private IAction revertChangesAction;
private IAction refreshAction;
private IAction switchAction;
private GenerateChangeLogAction generateChangeLogAction;
private ToggleAffectedPathsOptionAction[] toggleAffectedPathsLayoutActions;
private ToggleAffectedPathsOptionAction[] toggleAffectedPathsModeActions;
private TextViewerAction copyAction;
private TextViewerAction selectAllAction;
private LinkList linkList;
private Cursor handCursor;
private Cursor busyCursor;
private IPreferenceStore store = SVNUIPlugin.getPlugin().getPreferenceStore();
private boolean includeTags = true;
private boolean includeBugs = false;
public SVNHistoryPage(Object object) {
SVNProviderPlugin.addResourceStateChangeListener(this);
}
public void dispose() {
super.dispose();
SVNProviderPlugin.removeResourceStateChangeListener(this);
if(busyCursor!=null) {
busyCursor.dispose();
}
if(handCursor!=null) {
handCursor.dispose();
}
}
public Control getControl() {
return svnHistoryPageControl;
}
public void setFocus() {
// TODO Auto-generated method stub
}
public String getDescription() {
// TODO Auto-generated method stub
return null;
}
public String getName() {
return remoteResource == null ? null : remoteResource.getRepositoryRelativePath() + " in "
+ remoteResource.getRepository();
}
public boolean isValidInput(Object object) {
if(object instanceof IResource) {
RepositoryProvider provider = RepositoryProvider.getProvider(((IResource) object).getProject());
return provider instanceof SVNTeamProvider;
} else if(object instanceof ISVNRemoteResource) {
return true;
}
// TODO
// } else if(object instanceof CVSFileRevision) {
// return true;
// } else if(object instanceof CVSLocalFileRevision) {
// return true;
return false;
}
public void refresh() {
entries = null;
lastEntry = null;
revisionStart = SVNRevision.HEAD;
// show a Busy Cursor during refresh
BusyIndicator.showWhile(tableHistoryViewer.getTable().getDisplay(), new Runnable() {
public void run() {
if(resource != null) {
try {
remoteResource = SVNWorkspaceRoot.getBaseResourceFor(resource);
historyTableProvider.setRemoteResource(remoteResource);
projectProperties = ProjectProperties.getProjectProperties(resource);
historyTableProvider.setProjectProperties(projectProperties);
} catch(SVNException e) {
}
}
if (tableHistoryViewer.getInput() == null) tableHistoryViewer.setInput(remoteResource);
tableHistoryViewer.refresh();
tableHistoryViewer.resetFilters();
getClearSearchAction().setEnabled(false);
}
});
}
public Object getAdapter(Class adapter) {
// TODO Auto-generated method stub
return null;
}
public boolean inputSet() {
Object input = getInput();
if(input instanceof IResource) {
IResource res = (IResource) input;
RepositoryProvider teamProvider = RepositoryProvider.getProvider(res.getProject(), SVNProviderPlugin.getTypeId());
if(teamProvider != null) {
try {
ISVNLocalResource localResource = SVNWorkspaceRoot.getSVNResourceFor(res);
LocalResourceStatus localResourceStatus = (localResource != null) ? localResource.getStatus() : null;
if(localResource != null && localResourceStatus.isManaged() && (!localResourceStatus.isAdded() || localResourceStatus.isCopied())) {
this.resource = res;
this.remoteResource = localResource.getBaseResource();
this.projectProperties = ProjectProperties.getProjectProperties(res);
boolean includeBugs = projectProperties != null;
boolean includeTags = tagsPropertySet(res);
if (includeTags != this.includeTags || this.includeBugs != includeBugs ) {
this.includeTags = includeTags;
this.includeBugs = includeBugs;
refreshTable();
}
this.historyTableProvider.setRemoteResource(this.remoteResource);
this.historyTableProvider.setProjectProperties(this.projectProperties);
if (historySearchViewerFilter != null) {
// HistorySearchViewerFilter[] filters = { historySearchViewerFilter };
// this.tableHistoryViewer.setFilters(filters);
this.tableHistoryViewer.resetFilters();
this.tableHistoryViewer.addFilter(historySearchViewerFilter);
historySearchDialog = new HistorySearchDialog(getSite().getShell(), remoteResource);
historySearchDialog.setSearchAll(false);
historySearchDialog.setStartRevision(historySearchViewerFilter.getStartRevision());
historySearchDialog.setEndRevision(historySearchViewerFilter.getEndRevision());
historySearchViewerFilter = null;
getClearSearchAction().setEnabled(true);
}
else {
this.tableHistoryViewer.resetFilters();
getClearSearchAction().setEnabled(false);
}
this.tableHistoryViewer.setInput(this.remoteResource);
// setContentDescription(Policy.bind("HistoryView.titleWithArgument",
// baseResource.getName())); //$NON-NLS-1$
// setTitleToolTip(baseResource.getRepositoryRelativePath());
return true;
}
} catch(TeamException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e);
}
}
} else if(input instanceof ISVNRemoteResource) {
this.resource = null;
this.remoteResource = (ISVNRemoteResource) input;
boolean includeTags = tagsPropertySet(remoteResource);
if (includeTags != this.includeTags) {
this.includeTags = includeTags;
refreshTable();
}
try {
this.projectProperties = ProjectProperties.getProjectProperties(this.remoteResource);
} catch (SVNException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e);
}
boolean includeBugs = projectProperties != null;
if (includeTags != this.includeTags || this.includeBugs != includeBugs ) {
this.includeTags = includeTags;
this.includeBugs = includeBugs;
refreshTable();
}
this.historyTableProvider.setRemoteResource(this.remoteResource);
this.historyTableProvider.setProjectProperties(this.projectProperties);
if (historySearchViewerFilter != null) {
// HistorySearchViewerFilter[] filters = { historySearchViewerFilter };
// this.tableHistoryViewer.setFilters(filters);
this.tableHistoryViewer.resetFilters();
this.tableHistoryViewer.addFilter(historySearchViewerFilter);
historySearchDialog = new HistorySearchDialog(getSite().getShell(), remoteResource);
historySearchDialog.setSearchAll(false);
historySearchDialog.setStartRevision(historySearchViewerFilter.getStartRevision());
historySearchDialog.setEndRevision(historySearchViewerFilter.getEndRevision());
historySearchViewerFilter = null;
getClearSearchAction().setEnabled(true);
}
else {
this.tableHistoryViewer.resetFilters();
getClearSearchAction().setEnabled(false);
}
this.tableHistoryViewer.setInput(this.remoteResource);
// setContentDescription(Policy.bind("HistoryView.titleWithArgument",
// remoteResource.getName())); //$NON-NLS-1$
// setTitleToolTip(remoteResource.getRepositoryRelativePath());
return true;
}
return false;
}
private boolean tagsPropertySet(IResource resource) {
if (resource == null) return false;
ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
try {
if (svnResource.isManaged()) {
ISVNProperty property = null;
property = svnResource.getSvnProperty("subclipse:tags"); //$NON-NLS-1$
if (property != null && property.getValue() != null) return true;
}
} catch (SVNException e) {}
IResource checkResource = resource;
while (checkResource.getParent() != null) {
checkResource = checkResource.getParent();
if (checkResource.getParent() == null) return false;
svnResource = SVNWorkspaceRoot.getSVNResourceFor(checkResource);
try {
if (svnResource.isManaged()) {
ISVNProperty property = null;
property = svnResource.getSvnProperty("subclipse:tags"); //$NON-NLS-1$
if (property != null && property.getValue() != null) return true;
}
} catch (SVNException e) {}
}
return false;
}
private boolean tagsPropertySet(ISVNRemoteResource resource) {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClient();
ISVNProperty property = null;
SVNProviderPlugin.disableConsoleLogging();
property = client.propertyGet(resource.getUrl(), "subclipse:tags"); //$NON-NLS-1$
if (property != null && property.getValue() != null) {
SVNProviderPlugin.enableConsoleLogging();
return true;
}
ISVNRemoteResource checkResource = resource;
while (checkResource.getParent() != null) {
checkResource = checkResource.getParent();
property = client.propertyGet(checkResource.getUrl(), "subclipse:tags"); //$NON-NLS-1$
if (property != null && property.getValue() != null) {
SVNProviderPlugin.enableConsoleLogging();
return true;
}
}
} catch (Exception e) {
SVNProviderPlugin.enableConsoleLogging();
}
return false;
}
public void createControl(Composite parent) {
this.busyCursor = new Cursor(parent.getDisplay(), SWT.CURSOR_WAIT);
this.handCursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND);
this.showComments = store.getBoolean(ISVNUIConstants.PREF_SHOW_COMMENTS);
this.wrapCommentsText = store.getBoolean(ISVNUIConstants.PREF_WRAP_COMMENTS);
this.showAffectedPaths = store.getBoolean(ISVNUIConstants.PREF_SHOW_PATHS);
this.svnHistoryPageControl = new SashForm(parent, SWT.VERTICAL);
this.svnHistoryPageControl.setLayoutData(new GridData(GridData.FILL_BOTH));
this.toggleAffectedPathsModeActions = new ToggleAffectedPathsOptionAction[] {
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsTableLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_TABLE_MODE,
ISVNUIConstants.PREF_AFFECTED_PATHS_MODE,
ISVNUIConstants.MODE_FLAT),
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsFlatLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_FLAT_MODE,
ISVNUIConstants.PREF_AFFECTED_PATHS_MODE,
ISVNUIConstants.MODE_FLAT2),
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsCompressedLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_COMPRESSED_MODE,
ISVNUIConstants.PREF_AFFECTED_PATHS_MODE,
ISVNUIConstants.MODE_COMPRESSED),
};
this.toggleAffectedPathsLayoutActions = new ToggleAffectedPathsOptionAction[] {
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsHorizontalLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_HORIZONTAL_LAYOUT,
ISVNUIConstants.PREF_AFFECTED_PATHS_LAYOUT,
ISVNUIConstants.LAYOUT_HORIZONTAL),
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsVerticalLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_VERTICAL_LAYOUT,
ISVNUIConstants.PREF_AFFECTED_PATHS_LAYOUT,
ISVNUIConstants.LAYOUT_VERTICAL),
};
createTableHistory(svnHistoryPageControl);
createAffectedPathsViewer();
contributeActions();
svnHistoryPageControl.setWeights(new int[] { 70, 30});
// set F1 help
// PlatformUI.getWorkbench().getHelpSystem().setHelp(svnHistoryPageControl,
// IHelpContextIds.RESOURCE_HISTORY_VIEW);
// initDragAndDrop();
// add listener for editor page activation - this is to support editor
// linking
// getSite().getPage().addPartListener(partListener);
// getSite().getPage().addPartListener(partListener2);
}
protected void createTableHistory(Composite parent) {
boolean redraw = false;
if (tableParent == null) {
tableParent = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.marginHeight = 0;
layout.marginWidth = 0;
tableParent.setLayout(layout);
GridData gridData = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL);
gridData.horizontalIndent = 0;
gridData.verticalIndent = 0;
tableParent.setLayoutData(gridData);
} else {
Control[] children = tableParent.getChildren();
for (int i = 0; i < children.length; i++) {
children[i].dispose();
}
redraw = true;
}
this.historyTableProvider = new HistoryTableProvider(SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION, "SVNHistoryPage"); //$NON-NLS-1$
this.historyTableProvider.setProjectProperties( this.projectProperties );
historyTableProvider.setIncludeMergeRevisions(store.getBoolean(ISVNUIConstants.PREF_INCLUDE_MERGED_REVISIONS));
historyTableProvider.setIncludeTags(includeTags);
historyTableProvider.setIncludeBugs(includeBugs);
this.tableHistoryViewer = historyTableProvider.createTable(tableParent);
if (redraw) {
tableParent.layout(true);
tableParent.redraw();
}
this.tableHistoryViewer.getTable().addKeyListener(this);
// set the content provider for the table
this.tableHistoryViewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
// Short-circuit to optimize
if(entries != null)
return entries;
if( !(inputElement instanceof ISVNRemoteResource))
return null;
final ISVNRemoteResource remoteResource = (ISVNRemoteResource) inputElement;
int entriesToFetch = store.getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
// If we are filtering by revision range, override entries to fetch.
if (historySearchDialog != null && !historySearchDialog.getSearchAllLogs()) {
if (historySearchDialog.getStartRevision() != null || historySearchDialog.getEndRevision() != null) {
if (getClearSearchAction().isEnabled()) entriesToFetch = 0;
}
}
if (entriesToFetch > 0)
fetchLogEntriesJob = new FetchLogEntriesJob();
else
fetchLogEntriesJob = new FetchAllLogEntriesJob();
if(fetchLogEntriesJob.getState() != Job.NONE) {
fetchLogEntriesJob.cancel();
try {
fetchLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(
Policy.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchLogEntriesJob, SVNUIPlugin.getPlugin().getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActivePart().getSite());
return new Object[ 0];
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
entries = null;
lastEntry = null;
revisionStart = SVNRevision.HEAD;
}
});
// set the selectionchanged listener for the table
// updates the comments and affected paths when selection changes
this.tableHistoryViewer.addSelectionChangedListener(new ISelectionChangedListener() {
private ILogEntry currentLogEntry;
private int currentSelectionSize = -1;
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
ILogEntry logEntry = getLogEntry((IStructuredSelection) selection);
if(logEntry != currentLogEntry || ((IStructuredSelection) selection).size() != currentSelectionSize) {
this.currentLogEntry = logEntry;
this.currentSelectionSize = ((IStructuredSelection) selection).size();
updatePanels(selection);
}
SVNHistoryPage.this.selection = selection;
}
});
// Double click open action
this.tableHistoryViewer.getTable().addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
getOpenRemoteFileAction().run();
}
});
// Contribute actions to popup menu for the table
{
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(tableHistoryViewer.getTable());
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
fillTableMenu(menuMgr);
}
});
menuMgr.setRemoveAllWhenShown(true);
tableHistoryViewer.getTable().setMenu(menu);
getHistoryPageSite().getPart().getSite().registerContextMenu(menuMgr, tableHistoryViewer);
}
if (redraw) {
parent.layout(true);
parent.redraw();
}
}
public void refreshTable() {
createTableHistory(svnHistoryPageControl);
}
private void fillChangePathsMenu(IMenuManager manager) {
//
// Commented out Get Contents, Revert and Switch options until when/if
// they can be fixed. Problem is that we need a way to get the local
// resource from the LogEntryChangePath.
//
IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
if (sel.size() == 1) {
if (sel.getFirstElement() instanceof LogEntryChangePath) {
// manager.add(getGetContentsAction());
}
manager.add(getCreateTagFromRevisionChangedPathAction());
}
// manager.add(getRevertChangesChangedPathAction());
// manager.add(getSwitchChangedPathAction());
manager.add(new Separator("exportImportGroup")); //$NON-NLS-1$
if (sel.size() == 1) {
if (sel.getFirstElement() instanceof LogEntryChangePath) {
manager.add(getExportAction());
}
}
manager.add(new Separator("openGroup")); //$NON-NLS-1$
if (sel.size() == 1) {
if (sel.getFirstElement() instanceof LogEntryChangePath) {
manager.add(getShowAnnotationAction());
}
manager.add(getCompareAction());
}
if (sel.getFirstElement() instanceof LogEntryChangePath) {
manager.add(getOpenChangedPathAction());
}
if (sel.size() == 1) manager.add(getShowHistoryAction());
}
private void fillTableMenu(IMenuManager manager) {
// file actions go first (view file)
manager.add(new Separator(IWorkbenchActionConstants.GROUP_FILE));
// Add the "Add to Workspace" action if 1 revision is selected.
ISelection sel = tableHistoryViewer.getSelection();
if( !sel.isEmpty()) {
if(sel instanceof IStructuredSelection) {
if(((IStructuredSelection) sel).size() == 1) {
if(resource != null && resource instanceof IFile) {
manager.add(getGetContentsAction());
manager.add(getUpdateToRevisionAction());
}
// manager.add(getShowDifferencesAsUnifiedDiffAction());
// if (resource != null) {
manager.add(getCreateTagFromRevisionAction());
// }
manager.add(getSetCommitPropertiesAction());
ILogEntry logEntry = (ILogEntry)((IStructuredSelection)sel).getFirstElement();
if (logEntry.getNumberOfChildren() > 0)
manager.add(getShowRevisionsAction());
}
if(resource != null) {
manager.add(getRevertChangesAction());
if(((IStructuredSelection) sel).size() == 1) manager.add(getSwitchAction());
}
manager.add(new Separator("exportImportGroup")); //$NON-NLS-1$
getGenerateChangeLogAction().setEnabled(!store.getBoolean(ISVNUIConstants.PREF_FETCH_CHANGE_PATH_ON_DEMAND));
manager.add(getGenerateChangeLogAction());
}
}
manager.add(new Separator("additions")); //$NON-NLS-1$
manager.add(getRefreshAction());
manager.add(new Separator("additions-end")); //$NON-NLS-1$
}
public void createAffectedPathsViewer() {
int[] weights = null;
weights = svnHistoryPageControl.getWeights();
if(innerSashForm != null) {
innerSashForm.dispose();
}
if(changePathsViewer != null) {
changePathsViewer.getControl().dispose();
}
int mode = store.getInt(ISVNUIConstants.PREF_AFFECTED_PATHS_MODE);
int layout = store.getInt(ISVNUIConstants.PREF_AFFECTED_PATHS_LAYOUT);
if(layout==ISVNUIConstants.LAYOUT_HORIZONTAL) {
innerSashForm = new SashForm(svnHistoryPageControl, SWT.HORIZONTAL);
} else {
innerSashForm = new SashForm(svnHistoryPageControl, SWT.VERTICAL);
createText(innerSashForm);
}
switch(mode) {
case ISVNUIConstants.MODE_COMPRESSED:
changePathsViewer = new ChangePathsTreeViewer(innerSashForm, this);
break;
case ISVNUIConstants.MODE_FLAT2:
changePathsViewer = new ChangePathsFlatViewer(innerSashForm, this);
break;
default:
changePathsViewer = new ChangePathsTableProvider(innerSashForm, this);
break;
}
changePathsViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
SVNHistoryPage.this.selection = changePathsViewer.getSelection();
}
});
changePathsViewer.getControl().addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
getOpenChangedPathAction().run();
}
});
// Contribute actions to changed paths pane
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(changePathsViewer.getControl());
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
fillChangePathsMenu(menuMgr);
}
});
menuMgr.setRemoveAllWhenShown(true);
changePathsViewer.getControl().setMenu(menu);
if(layout==ISVNUIConstants.LAYOUT_HORIZONTAL) {
createText(innerSashForm);
}
setViewerVisibility();
innerSashForm.layout();
if(weights!=null && weights.length==2) {
svnHistoryPageControl.setWeights(weights);
}
svnHistoryPageControl.layout();
updatePanels(tableHistoryViewer.getSelection());
}
/**
* Create the TextViewer for the logEntry comments
*/
protected void createText(Composite parent) {
// this.textViewer = new TextViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY);
SourceViewer result = new SourceViewer(parent, null, null, true, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY);
result.getTextWidget().setIndent(2);
result.configure(new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore()) {
public Map getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
return Collections.singletonMap("org.eclipse.ui.DefaultTextEditor", //$NON-NLS-1$
new IAdaptable() {
public Object getAdapter(Class adapter) {
if(adapter==IResource.class && getInput() instanceof IResource) {
return getInput();
} else if(adapter==ISVNRemoteResource.class && getInput() instanceof ISVNRemoteResource) {
return getInput();
}
return Platform.getAdapterManager().getAdapter(SVNHistoryPage.this, adapter);
}
});
}
public int getHyperlinkStateMask(ISourceViewer sourceViewer) {
return SWT.NONE;
}
public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) {
IHyperlinkDetector[] detectors = super.getHyperlinkDetectors(sourceViewer);
IHyperlinkDetector[] newDetectors;
if(detectors==null) {
newDetectors = new IHyperlinkDetector[1];
} else {
newDetectors = new IHyperlinkDetector[detectors.length + 1];
System.arraycopy(detectors, 0, newDetectors, 0, detectors.length);
}
newDetectors[newDetectors.length - 1] = new IHyperlinkDetector() {
public IHyperlink[] detectHyperlinks(ITextViewer textViewer,
IRegion region, boolean canShowMultipleHyperlinks) {
if(linkList==null || !linkList.isLinkAt(region.getOffset())) {
return null;
}
final String linkUrl = linkList.getLinkAt(region.getOffset());
final int[] linkRange = linkList.getLinkRange(region.getOffset());
return new IHyperlink[] { new IHyperlink() {
public IRegion getHyperlinkRegion() {
return new Region(linkRange[0], linkRange[1]);
}
public void open() {
try {
URL url = new URL(linkUrl);
PlatformUI.getWorkbench().getBrowserSupport().createBrowser("Subclipse").openURL(url);
} catch (Exception e1) {
Program.launch(linkUrl);
}
}
public String getHyperlinkText() {
return null;
}
public String getTypeLabel() {
return null;
}
}};
}
};
return newDetectors;
}
});
this.textViewer = result;
this.textViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
copyAction.update();
}
});
Font font = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getFontRegistry().get(
ISVNUIConstants.SVN_COMMENT_FONT);
if(font != null) {
this.textViewer.getTextWidget().setFont(font);
}
// Create actions for the text editor (copy and select all)
copyAction = new TextViewerAction(this.textViewer, ITextOperationTarget.COPY);
copyAction.setText(Policy.bind("HistoryView.copy")); //$NON-NLS-1$
selectAllAction = new TextViewerAction(this.textViewer, ITextOperationTarget.SELECT_ALL);
selectAllAction.setText(Policy.bind("HistoryView.selectAll")); //$NON-NLS-1$
IHistoryPageSite parentSite = getHistoryPageSite();
IPageSite pageSite = parentSite.getWorkbenchPageSite();
IActionBars actionBars = pageSite.getActionBars();
actionBars.setGlobalActionHandler(ITextEditorActionConstants.COPY, copyAction);
actionBars.setGlobalActionHandler(ITextEditorActionConstants.SELECT_ALL, selectAllAction);
actionBars.updateActionBars();
// Contribute actions to popup menu for the comments area
{
MenuManager menuMgr = new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
menuMgr.add(copyAction);
menuMgr.add(selectAllAction);
}
});
StyledText text = this.textViewer.getTextWidget();
Menu menu = menuMgr.createContextMenu(text);
text.setMenu(menu);
}
}
private void contributeActions() {
toggleShowComments = new Action(Policy.bind("HistoryView.showComments"), //$NON-NLS-1$
SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_COMMENTS)) {
public void run() {
showComments = isChecked();
setViewerVisibility();
store.setValue(ISVNUIConstants.PREF_SHOW_COMMENTS, showComments);
}
};
toggleShowComments.setChecked(showComments);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleTextAction,
// IHelpContextIds.SHOW_COMMENT_IN_HISTORY_ACTION);
// Toggle wrap comments action
toggleWrapCommentsAction = new Action(Policy.bind("HistoryView.wrapComments")) { //$NON-NLS-1$
public void run() {
wrapCommentsText = isChecked();
setViewerVisibility();
store.setValue(ISVNUIConstants.PREF_WRAP_COMMENTS, wrapCommentsText);
}
};
toggleWrapCommentsAction.setChecked(wrapCommentsText);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleTextWrapAction,
// IHelpContextIds.SHOW_TAGS_IN_HISTORY_ACTION);
// Toggle path visible action
toggleShowAffectedPathsAction = new Action(Policy.bind("HistoryView.showAffectedPaths"), //$NON-NLS-1$
SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_AFFECTED_PATHS_FLAT_MODE)) {
public void run() {
showAffectedPaths = isChecked();
setViewerVisibility();
store.setValue(ISVNUIConstants.PREF_SHOW_PATHS, showAffectedPaths);
}
};
toggleShowAffectedPathsAction.setChecked(showAffectedPaths);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleListAction,
// IHelpContextIds.SHOW_TAGS_IN_HISTORY_ACTION);
// Toggle stop on copy action
toggleStopOnCopyAction = new Action(Policy.bind("HistoryView.stopOnCopy")) { //$NON-NLS-1$
public void run() {
refresh();
SVNUIPlugin.getPlugin().getPreferenceStore().setValue(ISVNUIConstants.PREF_STOP_ON_COPY,
toggleStopOnCopyAction.isChecked());
}
};
toggleStopOnCopyAction.setChecked(store.getBoolean(ISVNUIConstants.PREF_STOP_ON_COPY));
// Toggle include merged revisions action
toggleIncludeMergedRevisionsAction = new Action(Policy.bind("HistoryView.includeMergedRevisions")) { //$NON-NLS-1$
public void run() {
store.setValue(ISVNUIConstants.PREF_INCLUDE_MERGED_REVISIONS, toggleIncludeMergedRevisionsAction.isChecked());
refreshTable();
refresh();
}
};
toggleIncludeMergedRevisionsAction.setChecked(store.getBoolean(ISVNUIConstants.PREF_INCLUDE_MERGED_REVISIONS));
IHistoryPageSite parentSite = getHistoryPageSite();
IPageSite pageSite = parentSite.getWorkbenchPageSite();
IActionBars actionBars = pageSite.getActionBars();
// Contribute toggle text visible to the toolbar drop-down
IMenuManager actionBarsMenu = actionBars.getMenuManager();
actionBarsMenu.add(getGetNextAction());
actionBarsMenu.add(getGetAllAction());
actionBarsMenu.add(toggleStopOnCopyAction);
actionBarsMenu.add(toggleIncludeMergedRevisionsAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(toggleWrapCommentsAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(toggleShowComments);
actionBarsMenu.add(toggleShowAffectedPathsAction);
actionBarsMenu.add(new Separator());
for (int i = 0; i < toggleAffectedPathsModeActions.length; i++) {
actionBarsMenu.add(toggleAffectedPathsModeActions[i]);
}
actionBarsMenu.add(new Separator());
for (int i = 0; i < toggleAffectedPathsLayoutActions.length; i++) {
actionBarsMenu.add(toggleAffectedPathsLayoutActions[i]);
}
// Create the local tool bar
IToolBarManager tbm = actionBars.getToolBarManager();
// tbm.add(getRefreshAction());
tbm.add(new Separator());
tbm.add(getSearchAction());
tbm.add(getClearSearchAction());
tbm.add(new Separator());
tbm.add(toggleShowComments);
tbm.add(toggleShowAffectedPathsAction);
tbm.add(new Separator());
tbm.add(getGetNextAction());
tbm.add(getGetAllAction());
// tbm.add(getLinkWithEditorAction());
tbm.update(false);
actionBars.updateActionBars();
}
ILogEntry getLogEntry(IStructuredSelection ss) {
if(ss.getFirstElement() instanceof LogEntryChangePath) {
return ((LogEntryChangePath) ss.getFirstElement()).getLogEntry();
}
return (ILogEntry) ss.getFirstElement();
}
void updatePanels(ISelection selection) {
if(selection == null || !(selection instanceof IStructuredSelection)) {
textViewer.setDocument(new Document("")); //$NON-NLS-1$
changePathsViewer.setInput(null);
return;
}
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() != 1) {
textViewer.setDocument(new Document("")); //$NON-NLS-1$
changePathsViewer.setInput(null);
return;
}
LogEntry entry = (LogEntry) ss.getFirstElement();
textViewer.setDocument(new Document(entry.getComment()));
StyledText text = textViewer.getTextWidget();
// TODO move this logic into the hyperlink detector created in createText()
if(projectProperties == null) {
linkList = ProjectProperties.getUrls(entry.getComment());
} else {
linkList = projectProperties.getLinkList(entry.getComment());
}
if(linkList != null) {
int[][] linkRanges = linkList.getLinkRanges();
// String[] urls = linkList.getUrls();
for(int i = 0; i < linkRanges.length; i++) {
text.setStyleRange(new StyleRange(linkRanges[ i][ 0], linkRanges[ i][ 1],
JFaceColors.getHyperlinkText(Display.getCurrent()), null));
}
}
if (changePathsViewer instanceof ChangePathsTreeViewer) {
((ChangePathsTreeViewer)changePathsViewer).setCurrentLogEntry(entry);
}
if (changePathsViewer instanceof ChangePathsFlatViewer) {
((ChangePathsFlatViewer)changePathsViewer).setCurrentLogEntry(entry);
}
if (changePathsViewer instanceof ChangePathsTableProvider) {
((ChangePathsTableProvider)changePathsViewer).setCurrentLogEntry(entry);
}
changePathsViewer.setInput(entry);
}
void setViewerVisibility() {
if(showComments && showAffectedPaths) {
svnHistoryPageControl.setMaximizedControl(null);
innerSashForm.setMaximizedControl(null);
} else if(showComments) {
svnHistoryPageControl.setMaximizedControl(null);
innerSashForm.setMaximizedControl(textViewer.getTextWidget());
} else if(showAffectedPaths) {
svnHistoryPageControl.setMaximizedControl(null);
innerSashForm.setMaximizedControl(changePathsViewer.getControl());
} else {
svnHistoryPageControl.setMaximizedControl(tableParent);
}
changePathsViewer.refresh();
textViewer.getTextWidget().setWordWrap(wrapCommentsText);
}
void setCurrentLogEntryChangePath(final LogEntryChangePath[] currentLogEntryChangePath) {
this.currentLogEntryChangePath = currentLogEntryChangePath;
if( !shutdown) {
// Getting the changePaths
/*
* final SVNRevision.Number revisionId =
* remoteResource.getLastChangedRevision();
*/
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(currentLogEntryChangePath != null && changePathsViewer != null
&& !changePathsViewer.getControl().isDisposed()) {
// once we got the changePath, we refresh the table
changePathsViewer.refresh();
// selectRevision(revisionId);
}
}
});
}
}
/**
* Select the revision in the receiver.
*/
public void selectRevision(SVNRevision.Number revision) {
if(entries == null) {
return;
}
ILogEntry entry = null;
for(int i = 0; i < entries.length; i++) {
if(entries[ i].getRevision().equals(revision)) {
entry = entries[ i];
break;
}
}
if(entry != null) {
IStructuredSelection selection = new StructuredSelection(entry);
tableHistoryViewer.setSelection(selection, true);
}
}
public void scheduleFetchChangePathJob(ILogEntry logEntry) {
if(fetchChangePathJob == null) {
fetchChangePathJob = new FetchChangePathJob();
}
if(fetchChangePathJob.getState() != Job.NONE) {
fetchChangePathJob.cancel();
try {
fetchChangePathJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(IStatus.ERROR, e.getMessage(), e);
// SVNUIPlugin.log(new
// SVNException(Policy.bind("HistoryView.errorFetchingEntries",
// remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchChangePathJob.setLogEntry(logEntry);
Utils.schedule(fetchChangePathJob, getSite());
}
public boolean isShowChangePaths() {
return showAffectedPaths;
}
private SVNRevision getSelectedRevision() {
IStructuredSelection sel = (IStructuredSelection)tableHistoryViewer.getSelection();
if (sel.getFirstElement() instanceof ILogEntry) {
return ((ILogEntry)sel.getFirstElement()).getRevision();
}
return null;
}
private IAction getOpenRemoteFileAction() {
if(openAction == null) {
openAction = new Action() {
public void run() {
OpenRemoteFileAction delegate = new OpenRemoteFileAction();
delegate.init(this);
delegate.selectionChanged(this, tableHistoryViewer.getSelection());
if(isEnabled()) {
try {
// disableEditorActivation = true;
delegate.run(this);
} finally {
// disableEditorActivation = false;
}
}
}
};
}
return openAction;
}
private boolean isFile() {
IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
if (sel.size() == 1 && sel.getFirstElement() instanceof LogEntryChangePath) {
LogEntryChangePath changePath = (LogEntryChangePath)sel.getFirstElement();
try {
return changePath.getRemoteResource() instanceof ISVNRemoteFile;
} catch (SVNException e) {}
}
return false;
}
private boolean deleteSelected() {
IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
return (sel.size() == 1 && sel.getFirstElement() instanceof LogEntryChangePath &&
((LogEntryChangePath)sel.getFirstElement()).getAction() == 'D');
}
// open changed Path (double-click)
private IAction getOpenChangedPathAction() {
if(openChangedPathAction == null) {
openChangedPathAction = new Action("Open") { //$NON-NLS-1$
public void run() {
OpenRemoteFileAction delegate = new OpenRemoteFileAction();
delegate.setUsePegRevision(true);
delegate.init(this);
delegate.selectionChanged(this, changePathsViewer.getSelection());
if(isEnabled()) {
try {
// disableEditorActivation = true;
delegate.run(this);
} finally {
// disableEditorActivation = false;
}
}
}
};
}
openChangedPathAction.setEnabled(!deleteSelected() && isFile());
return openChangedPathAction;
}
private IAction getShowHistoryAction() {
if(showHistoryAction == null) {
showHistoryAction = new Action("Show History", SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_SHOWHISTORY)) { //$NON-NLS-1$
public void run() {
HistoryAction delegate = new HistoryAction();
delegate.selectionChanged(this, changePathsViewer.getSelection());
delegate.run(this);
}
};
}
showHistoryAction.setEnabled(!deleteSelected());
return showHistoryAction;
}
private IAction getExportAction() {
if(exportAction == null) {
exportAction = new Action("Export...", SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_EXPORT)) { //$NON-NLS-1$
public void run() {
ExportAction delegate = new ExportAction();
delegate.selectionChanged(this, changePathsViewer.getSelection());
delegate.run(this);
}
};
}
exportAction.setEnabled(!deleteSelected());
return exportAction;
}
private IAction getShowAnnotationAction() {
if(showAnnotationAction == null) {
showAnnotationAction = new Action("Show Annotation", SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_ANNOTATE)) { //$NON-NLS-1$
public void run() {
AnnotationAction delegate = new AnnotationAction();
delegate.selectionChanged(this, changePathsViewer.getSelection());
delegate.run(this);
}
};
}
showAnnotationAction.setEnabled(!deleteSelected() && isFile());
return showAnnotationAction;
}
private IAction getCompareAction() {
if(compareAction == null) {
compareAction = new Action("Compare...") { //$NON-NLS-1$
public void run() {
CompareAction delegate = new CompareAction();
delegate.selectionChanged(this, changePathsViewer.getSelection());
delegate.run(this);
}
};
}
compareAction.setEnabled(!deleteSelected());
return compareAction;
}
private IAction getCreateTagFromRevisionChangedPathAction() {
if(createTagFromRevisionChangedPathAction == null) {
createTagFromRevisionChangedPathAction = new Action() { //$NON-NLS-1$
public void run() {
SVNRevision selectedRevision = null;
ISelection selection = changePathsViewer.getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection sel = (IStructuredSelection)selection;
ISVNRemoteResource remoteResource = null;
if (sel.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
selectedRevision = remoteResource.getRevision();
} catch (SVNException e) {}
}
else if (sel.getFirstElement() instanceof HistoryFolder) {
HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
Object[] children = historyFolder.getChildren();
if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
LogEntryChangePath changePath = (LogEntryChangePath)children[0];
try {
remoteResource = changePath.getRemoteResource().getRepository().getRemoteFolder(historyFolder.getPath());
selectedRevision = getSelectedRevision();
} catch (SVNException e) {}
}
}
if (remoteResource == null) return;
ISVNRemoteResource[] remoteResources = { remoteResource };
BranchTagWizard wizard = new BranchTagWizard(remoteResources);
wizard.setRevisionNumber(Long.parseLong(selectedRevision.toString()));
WizardDialog dialog = new ClosableWizardDialog(getSite().getShell(), wizard);
if (dialog.open() == WizardDialog.OK) {
final SVNUrl sourceUrl = wizard.getUrl();
final SVNUrl destinationUrl = wizard.getToUrl();
final String message = wizard.getComment();
final SVNRevision revision = wizard.getRevision();
final boolean makeParents = wizard.isMakeParents();
try {
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().getSVNClient();
client.copy(sourceUrl, destinationUrl, message, revision, makeParents);
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
});
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
// SvnWizardBranchTagPage branchTagPage = new SvnWizardBranchTagPage(remoteResource);
// branchTagPage.setRevisionNumber(Long.parseLong(selectedRevision.toString()));
// SvnWizard wizard = new SvnWizard(branchTagPage);
// SvnWizardDialog dialog = new SvnWizardDialog(getSite().getShell(), wizard);
// wizard.setParentDialog(dialog);
// if (!(dialog.open() == SvnWizardDialog.OK)) return;
// final SVNUrl sourceUrl = branchTagPage.getUrl();
// final SVNUrl destinationUrl = branchTagPage.getToUrl();
// final String message = branchTagPage.getComment();
// final SVNRevision revision = branchTagPage.getRevision();
// final boolean makeParents = branchTagPage.isMakeParents();
// try {
// BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
// public void run() {
// try {
// ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().createSVNClient();
// client.copy(sourceUrl, destinationUrl, message, revision, makeParents);
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
// .getMessage());
// }
// }
// });
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
// .getMessage());
// }
}
};
}
ISelection selection = changePathsViewer.getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection sel = (IStructuredSelection) selection;
SVNRevision selectedRevision = null;
if(sel.size() == 1) {
ISVNRemoteResource remoteResource = null;
if (sel.getFirstElement() instanceof LogEntryChangePath && ((LogEntryChangePath)sel.getFirstElement()).getAction() != 'D') {
try {
remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
selectedRevision = remoteResource.getRevision();
} catch (SVNException e) {}
}
else if (sel.getFirstElement() instanceof HistoryFolder) {
HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
Object[] children = historyFolder.getChildren();
if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
selectedRevision = getSelectedRevision();
}
}
createTagFromRevisionChangedPathAction.setEnabled(selectedRevision != null);
if (selectedRevision == null) {
createTagFromRevisionChangedPathAction.setText(Policy.bind("HistoryView.createTagFromRevision", ""
+ ((LogEntryChangePath)sel.getFirstElement()).getRevision()));
} else {
createTagFromRevisionChangedPathAction.setText(Policy.bind("HistoryView.createTagFromRevision", ""
+ selectedRevision));
}
}
}
createTagFromRevisionChangedPathAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_BRANCHTAG));
return createTagFromRevisionChangedPathAction;
}
class AnnotationAction extends ShowAnnotationAction {
public IStructuredSelection fSelection;
public AnnotationAction() {
super();
}
protected ISVNRemoteFile getSingleSelectedSVNRemoteFile() {
ISVNRemoteResource remoteResource = null;
if (fSelection.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)fSelection.getFirstElement()).getRemoteResource();
} catch (SVNException e) {}
}
return (ISVNRemoteFile)remoteResource;
}
protected boolean isEnabled() {
return true;
}
public void selectionChanged(IAction action, ISelection sel) {
if (sel instanceof IStructuredSelection) {
fSelection= (IStructuredSelection) sel;
}
}
}
class HistoryAction extends ShowHistoryAction {
public IStructuredSelection fSelection;
public HistoryAction() {
super();
}
protected ISVNRemoteResource[] getSelectedRemoteResources() {
ISVNRemoteResource remoteResource = null;
if (fSelection.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)fSelection.getFirstElement()).getRemoteResource();
} catch (SVNException e) {}
}
else if (fSelection.getFirstElement() instanceof HistoryFolder) {
HistoryFolder historyFolder = (HistoryFolder)fSelection.getFirstElement();
Object[] children = historyFolder.getChildren();
if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
LogEntryChangePath changePath = (LogEntryChangePath)children[0];
try {
remoteResource = changePath.getRemoteResource().getRepository().getRemoteFolder(historyFolder.getPath());
} catch (SVNException e) {}
}
}
if (remoteResource != null) {
ISVNRemoteResource[] selectedResource = { remoteResource };
return selectedResource;
}
return new ISVNRemoteResource[0];
}
protected boolean isEnabled() {
return true;
}
public void selectionChanged(IAction action, ISelection sel) {
if (sel instanceof IStructuredSelection) {
fSelection= (IStructuredSelection) sel;
}
}
}
class ExportAction extends ExportRemoteFolderAction {
public IStructuredSelection fSelection;
public ExportAction() {
super();
}
protected ISVNRemoteResource[] getSelectedRemoteResources() {
ISVNRemoteResource remoteResource = null;
if (fSelection.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)fSelection.getFirstElement()).getRemoteResource();
} catch (SVNException e) {}
}
if (remoteResource != null) {
ISVNRemoteResource[] selectedResource = { remoteResource };
return selectedResource;
}
return new ISVNRemoteResource[0];
}
protected boolean isEnabled() {
return true;
}
public void selectionChanged(IAction action, ISelection sel) {
if (sel instanceof IStructuredSelection) {
fSelection= (IStructuredSelection) sel;
}
}
}
class CompareAction extends ShowDifferencesAsUnifiedDiffAction {
public IStructuredSelection fSelection;
public CompareAction() {
super();
}
protected ISVNRemoteResource[] getSelectedRemoteResources() {
ISVNRemoteResource remoteResource = null;
if (fSelection.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)fSelection.getFirstElement()).getRemoteResource();
} catch (SVNException e) {}
}
else if (fSelection.getFirstElement() instanceof HistoryFolder) {
HistoryFolder historyFolder = (HistoryFolder)fSelection.getFirstElement();
Object[] children = historyFolder.getChildren();
if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
LogEntryChangePath changePath = (LogEntryChangePath)children[0];
try {
ISVNRemoteResource changePathResource = changePath.getRemoteResource();
ISVNRemoteResource remoteFolder = changePathResource.getRepository().getRemoteFolder(historyFolder.getPath());
remoteResource = new RemoteFolder(null, changePathResource.getRepository(), remoteFolder.getUrl(), changePathResource.getRevision(), (SVNRevision.Number)changePathResource.getRevision(), null, null);
} catch (SVNException e) {}
}
}
if (remoteResource != null) {
ISVNRemoteResource[] selectedResource = { remoteResource };
return selectedResource;
}
return new ISVNRemoteResource[0];
}
protected boolean isEnabled() {
return true;
}
public void selectionChanged(IAction action, ISelection sel) {
if (sel instanceof IStructuredSelection) {
fSelection= (IStructuredSelection) sel;
}
}
}
// get contents Action (context menu)
private IAction getGetContentsAction() {
if(getContentsAction == null) {
getContentsAction = getContextMenuAction(Policy.bind("HistoryView.getContentsAction"), new IWorkspaceRunnable() { //$NON-NLS-1$
public void run(IProgressMonitor monitor) throws CoreException {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection ss = (IStructuredSelection) selection;
ISVNRemoteFile remoteFile = (ISVNRemoteFile) getLogEntry(ss).getRemoteResource();
monitor.beginTask(null, 100);
try {
if(remoteFile != null) {
if(confirmOverwrite()) {
InputStream in = ((IResourceVariant) remoteFile).getStorage(new SubProgressMonitor(monitor, 50))
.getContents();
IFile file = (IFile) resource;
file.setContents(in, false, true, new SubProgressMonitor(monitor, 50));
}
}
} catch(TeamException e) {
throw new CoreException(e.getStatus());
} finally {
monitor.done();
}
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(getContentsAction, IHelpContextIds.GET_FILE_CONTENTS_ACTION);
}
return getContentsAction;
}
// update to the selected revision (context menu)
private IAction getUpdateToRevisionAction() {
if(updateToRevisionAction == null) {
updateToRevisionAction = getContextMenuAction(
Policy.bind("HistoryView.getRevisionAction"), new IWorkspaceRunnable() { //$NON-NLS-1$
public void run(IProgressMonitor monitor) throws CoreException {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection ss = (IStructuredSelection) selection;
ISVNRemoteFile remoteFile = (ISVNRemoteFile) getLogEntry(ss).getRemoteResource();
try {
if(remoteFile != null) {
if(confirmOverwrite()) {
IFile file = (IFile) resource;
new ReplaceOperation(getSite().getPage().getActivePart(), file, remoteFile.getLastChangedRevision())
.run(monitor);
historyTableProvider.setRemoteResource(remoteFile);
historyTableProvider.setProjectProperties(ProjectProperties.getProjectProperties(resource));
Display.getDefault().asyncExec(new Runnable() {
public void run() {
tableHistoryViewer.refresh();
}
});
}
}
} catch(InvocationTargetException e) {
throw new CoreException(new SVNStatus(IStatus.ERROR, 0, e.getMessage()));
} catch(InterruptedException e) {
// Cancelled by user
}
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(updateToRevisionAction,
IHelpContextIds.GET_FILE_REVISION_ACTION);
}
return updateToRevisionAction;
}
// private IAction getRevertChangesChangedPathAction() {
// if(revertChangesChangedPathAction == null) {
// revertChangesChangedPathAction = new Action() {
// public void run() {
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// if (sel.size() == 1) {
// String resourcePath = null;
// if (sel.getFirstElement() instanceof LogEntryChangePath)
// resourcePath = ((LogEntryChangePath)sel.getFirstElement()).getPath();
// else if (sel.getFirstElement() instanceof HistoryFolder)
// resourcePath = ((HistoryFolder)sel.getFirstElement()).getPath();
// if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
// "HistoryView.confirmRevertChangedPathRevision", resourcePath))) return;
// } else {
// if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
// "HistoryView.confirmRevertChangedPathsRevision"))) return;
// }
// BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
// public void run() {
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// SVNRevision selectedRevision = null;
// ISVNRemoteResource remoteResource = null;
// if (sel.getFirstElement() instanceof LogEntryChangePath) {
// try {
// remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
// selectedRevision = remoteResource.getRevision();
// } catch (SVNException e) {}
// }
// else if (sel.getFirstElement() instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// selectedRevision = getSelectedRevision();
// }
// }
// final SVNRevision revision1 = selectedRevision;
// final SVNRevision revision2 = new SVNRevision.Number(((SVNRevision.Number)selectedRevision).getNumber() - 1);
// Iterator iter = sel.iterator();
// while (iter.hasNext()) {
// remoteResource = null;
// IResource selectedResource = null;
// Object selectedItem = iter.next();
// if (selectedItem instanceof LogEntryChangePath) {
// try {
// LogEntryChangePath changePath = (LogEntryChangePath)selectedItem;
// remoteResource = changePath.getRemoteResource();
// if (remoteResource.isFolder()) selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(changePath.getPath()));
// else selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(changePath.getPath()));
// } catch (SVNException e) {}
// }
// else if (selectedItem instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)selectedItem;
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// LogEntryChangePath changePath = (LogEntryChangePath)children[0];
// try {
// remoteResource = changePath.getRemoteResource().getRepository().getRemoteFolder(historyFolder.getPath());
// if (selectedRevision == null) selectedRevision = getSelectedRevision();
// if (remoteResource.isFolder()) selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(historyFolder.getPath()));
// else selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(historyFolder.getPath()));
// } catch (SVNException e) {}
// }
// }
// final SVNUrl path1 = remoteResource.getUrl();
// final SVNUrl path2 = path1;
// final IResource[] resources = { selectedResource };
// try {
// WorkspaceAction mergeAction = new WorkspaceAction() {
// protected void execute(IAction action) throws InvocationTargetException, InterruptedException {
// new MergeOperation(getSite().getPage().getActivePart(), resources, path1, revision1, path2,
// revision2).run();
// }
// };
// mergeAction.run(null);
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), revertChangesAction.getText(), e.getMessage());
// }
// }
// }
// });
// }
// };
// }
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// SVNRevision selectedRevision = null;
// ISVNRemoteResource remoteResource = null;
// if (sel.getFirstElement() instanceof LogEntryChangePath) {
// try {
// remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
// selectedRevision = remoteResource.getRevision();
// } catch (SVNException e) {}
// }
// else if (sel.getFirstElement() instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// selectedRevision = getSelectedRevision();
// }
// }
// revertChangesChangedPathAction.setText(Policy.bind("HistoryView.revertChangesFromRevision", ""
// + selectedRevision));
// revertChangesChangedPathAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_MARKMERGED));
// return revertChangesChangedPathAction;
// }
// private IAction getSwitchChangedPathAction() {
// if (switchChangedPathAction == null) {
// switchChangedPathAction = new Action() {
// public void run() {
// SVNRevision selectedRevision = null;
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// ArrayList selectedResources = new ArrayList();
// Iterator iter = sel.iterator();
// while (iter.hasNext()) {
// ISVNRemoteResource remoteResource = null;
// IResource selectedResource = null;
// Object selectedItem = iter.next();
// if (selectedItem instanceof LogEntryChangePath) {
// try {
// LogEntryChangePath changePath = (LogEntryChangePath)selectedItem;
// remoteResource = changePath.getRemoteResource();
// if (remoteResource.isFolder()) selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(changePath.getPath()));
// else selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(changePath.getPath()));
// selectedResources.add(selectedResource);
// if (selectedRevision == null) selectedRevision = remoteResource.getRevision();
// } catch (SVNException e) {}
// }
// else if (selectedItem instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)selectedItem;
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// LogEntryChangePath changePath = (LogEntryChangePath)children[0];
// try {
// remoteResource = changePath.getRemoteResource().getRepository().getRemoteFolder(historyFolder.getPath());
// if (selectedRevision == null) selectedRevision = getSelectedRevision();
// if (remoteResource.isFolder()) selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(historyFolder.getPath()));
// else selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(historyFolder.getPath()));
// selectedResources.add(selectedResource);
// } catch (SVNException e) {}
// }
// }
// }
// IResource[] resources = new IResource[selectedResources.size()];
// selectedResources.toArray(resources);
// SvnWizardSwitchPage switchPage = new SvnWizardSwitchPage(resources, Long.parseLong(selectedRevision.toString()));
// SvnWizard wizard = new SvnWizard(switchPage);
// SvnWizardDialog dialog = new SvnWizardDialog(getSite().getShell(), wizard);
// wizard.setParentDialog(dialog);
// if (dialog.open() == SvnWizardDialog.OK) {
// SVNUrl[] svnUrls = switchPage.getUrls();
// SVNRevision svnRevision = switchPage.getRevision();
// SwitchOperation switchOperation = new SwitchOperation(getSite().getPage().getActivePart(), resources, svnUrls, svnRevision);
// switchOperation.setDepth(switchPage.getDepth());
// switchOperation.setIgnoreExternals(switchPage.isIgnoreExternals());
// switchOperation.setForce(switchPage.isForce());
// try {
// switchOperation.run();
// } catch (Exception e) {
// MessageDialog.openError(getSite().getShell(), switchAction.getText(), e
// .getMessage());
// }
// }
// }
// };
// }
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// SVNRevision selectedRevision = null;
// ISVNRemoteResource remoteResource = null;
// if (sel.getFirstElement() instanceof LogEntryChangePath) {
// try {
// remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
// selectedRevision = remoteResource.getRevision();
// } catch (SVNException e) {}
// }
// else if (sel.getFirstElement() instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// selectedRevision = getSelectedRevision();
// }
// }
// switchChangedPathAction.setText(Policy.bind("HistoryView.switchToRevision", ""
// + selectedRevision));
// switchChangedPathAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_SWITCH));
// return switchChangedPathAction;
// }
// get switch action (context menu)
private IAction getSwitchAction() {
if (switchAction == null) {
switchAction = new Action() {
public void run() {
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
ILogEntry currentSelection = getLogEntry(ss);
IResource[] resources = { resource };
SvnWizardSwitchPage switchPage = new SvnWizardSwitchPage(resources, currentSelection.getRevision().getNumber());
SvnWizard wizard = new SvnWizard(switchPage);
SvnWizardDialog dialog = new SvnWizardDialog(getSite().getShell(), wizard);
wizard.setParentDialog(dialog);
if (dialog.open() == SvnWizardDialog.OK) {
SVNUrl[] svnUrls = switchPage.getUrls();
SVNRevision svnRevision = switchPage.getRevision();
SwitchOperation switchOperation = new SwitchOperation(getSite().getPage().getActivePart(), resources, svnUrls, svnRevision);
switchOperation.setDepth(switchPage.getDepth());
switchOperation.setSetDepth(switchPage.isSetDepth());
switchOperation.setIgnoreExternals(switchPage.isIgnoreExternals());
switchOperation.setForce(switchPage.isForce());
try {
switchOperation.run();
} catch (Exception e) {
MessageDialog.openError(getSite().getShell(), switchAction.getText(), e
.getMessage());
}
}
}
}
}
};
}
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
ILogEntry currentSelection = getLogEntry(ss);
switchAction.setText(Policy.bind("HistoryView.switchToRevision", ""
+ currentSelection.getRevision().getNumber()));
}
}
switchAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_SWITCH));
return switchAction;
}
// get create tag from revision action (context menu)
private IAction getCreateTagFromRevisionAction() {
if(createTagFromRevisionAction == null) {
createTagFromRevisionAction = new Action() {
public void run() {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
ILogEntry currentSelection = getLogEntry((IStructuredSelection) selection);
BranchTagWizard wizard;
if (resource == null) {
ISVNRemoteResource[] remoteResources = { historyTableProvider.getRemoteResource() };
wizard = new BranchTagWizard(remoteResources);
} else {
IResource[] resources = { resource };
wizard = new BranchTagWizard(resources);
}
wizard.setRevisionNumber(currentSelection.getRevision().getNumber());
WizardDialog dialog = new ClosableWizardDialog(getSite().getShell(), wizard);
if (dialog.open() == WizardDialog.OK) {
final SVNUrl sourceUrl =wizard.getUrl();
final SVNUrl destinationUrl = wizard.getToUrl();
final String message = wizard.getComment();
final SVNRevision revision = wizard.getRevision();
final boolean makeParents = wizard.isMakeParents();
boolean createOnServer = wizard.isCreateOnServer();
IResource[] resources = { resource };
try {
if(resource == null) {
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().getSVNClient();
client.copy(sourceUrl, destinationUrl, message, revision, makeParents);
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
});
} else {
BranchTagOperation branchTagOperation = new BranchTagOperation(getSite().getPage().getActivePart(), resources, new SVNUrl[] { sourceUrl }, destinationUrl,
createOnServer, wizard.getRevision(), message);
branchTagOperation.setMakeParents(makeParents);
branchTagOperation.setNewAlias(wizard.getNewAlias());
branchTagOperation.run();
}
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
// SvnWizardBranchTagPage branchTagPage;
// if (resource == null)
// branchTagPage = new SvnWizardBranchTagPage(historyTableProvider.getRemoteResource());
// else
// branchTagPage = new SvnWizardBranchTagPage(resource);
// branchTagPage.setRevisionNumber(currentSelection.getRevision().getNumber());
// SvnWizard wizard = new SvnWizard(branchTagPage);
// SvnWizardDialog dialog = new SvnWizardDialog(getSite().getShell(), wizard);
// wizard.setParentDialog(dialog);
// if (!(dialog.open() == SvnWizardDialog.OK)) return;
// final SVNUrl sourceUrl = branchTagPage.getUrl();
// final SVNUrl destinationUrl = branchTagPage.getToUrl();
// final String message = branchTagPage.getComment();
// final SVNRevision revision = branchTagPage.getRevision();
// final boolean makeParents = branchTagPage.isMakeParents();
// boolean createOnServer = branchTagPage.isCreateOnServer();
// IResource[] resources = { resource};
// try {
// if(resource == null) {
// BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
// public void run() {
// try {
// ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().createSVNClient();
// client.copy(sourceUrl, destinationUrl, message, revision, makeParents);
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
// .getMessage());
// }
// }
// });
// } else {
// BranchTagOperation branchTagOperation = new BranchTagOperation(getSite().getPage().getActivePart(), resources, sourceUrl, destinationUrl,
// createOnServer, branchTagPage.getRevision(), message);
// branchTagOperation.setMakeParents(makeParents);
// branchTagOperation.run();
// }
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
// .getMessage());
// }
}
};
}
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
ILogEntry currentSelection = getLogEntry(ss);
createTagFromRevisionAction.setText(Policy.bind("HistoryView.createTagFromRevision", ""
+ currentSelection.getRevision().getNumber()));
}
}
createTagFromRevisionAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_BRANCHTAG));
return createTagFromRevisionAction;
}
private IAction getSetCommitPropertiesAction() {
// set Action (context menu)
if(setCommitPropertiesAction == null) {
setCommitPropertiesAction = new Action(Policy.bind("HistoryView.setCommitProperties")) {
public void run() {
try {
final ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
final ILogEntry ourSelection = getLogEntry((IStructuredSelection) selection);
// Failing that, try the resource originally selected by the user if
// from the Team menu
// TODO: Search all paths from currentSelection and find the
// shortest path and
// get the resources for that instance (in order to get the 'best'
// "bugtraq" properties)
final ProjectProperties projectProperties = (resource != null) ? ProjectProperties
.getProjectProperties(resource) : ProjectProperties.getProjectProperties(ourSelection
.getRemoteResource()); // will return null!
final ISVNResource svnResource = ourSelection.getRemoteResource() != null ? ourSelection
.getRemoteResource() : ourSelection.getResource();
SetCommitPropertiesDialog dialog = new SetCommitPropertiesDialog(getSite().getShell(), ourSelection
.getRevision(), resource, projectProperties);
// Set previous text - the text to edit
dialog.setOldAuthor(ourSelection.getAuthor());
dialog.setOldComment(ourSelection.getComment());
boolean doCommit = (dialog.open() == Window.OK);
if(doCommit) {
final String author;
final String commitComment;
if(ourSelection.getAuthor().equals(dialog.getAuthor()))
author = null;
else
author = dialog.getAuthor();
if(ourSelection.getComment().equals(dialog.getComment()))
commitComment = null;
else
commitComment = dialog.getComment();
final ChangeCommitPropertiesCommand command = new ChangeCommitPropertiesCommand(svnResource
.getRepository(), ourSelection.getRevision(), commitComment, author);
PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
command.run(monitor);
} catch(SVNException e) {
throw new InvocationTargetException(e);
} finally {
if(ourSelection instanceof LogEntry) {
LogEntry logEntry = (LogEntry) ourSelection;
if (command.isLogMessageChanged()) logEntry.setComment(commitComment);
if (command.isAuthorChanged()) logEntry.setAuthor(author);
}
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
tableHistoryViewer.refresh();
tableHistoryViewer.setSelection(selection, true);
}
});
}
}
});
}
} catch(InvocationTargetException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e, SVNUIPlugin.LOG_NONTEAM_EXCEPTIONS);
} catch(InterruptedException e) {
// Do nothing
} catch(SVNException e) {
// TODO Auto-generated catch block
SVNUIPlugin.openError(getSite().getShell(), null, null, e, SVNUIPlugin.LOG_TEAM_EXCEPTIONS);
}
}
// we don't allow multiple selection
public boolean isEnabled() {
ISelection selection = getSelection();
return selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() == 1;
}
};
}
return setCommitPropertiesAction;
}
private IAction getShowRevisionsAction() {
if (showRevisionsAction == null) {
showRevisionsAction = new Action(Policy.bind("HistoryView.showMergedRevisions")) {
public void run() {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection ss = (IStructuredSelection) selection;
ILogEntry logEntry = (ILogEntry)ss.getFirstElement();
ShowRevisionsDialog dialog = null;
if (resource != null) dialog = new ShowRevisionsDialog(getSite().getShell(), logEntry, resource, includeTags, SVNHistoryPage.this);
else if (remoteResource != null) dialog = new ShowRevisionsDialog(getSite().getShell(), logEntry, remoteResource, includeTags, SVNHistoryPage.this);
if (dialog != null) dialog.open();
}
};
}
return showRevisionsAction;
}
// get revert changes action (context menu)
private IAction getRevertChangesAction() {
if(revertChangesAction == null) {
revertChangesAction = new Action() {
public void run() {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
final IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
"HistoryView.confirmRevertRevision", resource.getFullPath().toString())))
return;
} else {
if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
"HistoryView.confirmRevertRevisions", resource.getFullPath().toString())))
return;
}
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
ILogEntry firstElement = getFirstElement();
ILogEntry lastElement = getLastElement();
final SVNUrl path1 = firstElement.getResource().getUrl();
final SVNRevision revision1 = firstElement.getRevision();
final SVNUrl path2 = lastElement.getResource().getUrl();
final SVNRevision revision2 = new SVNRevision.Number(lastElement.getRevision().getNumber() - 1);
final IResource[] resources = { resource};
try {
WorkspaceAction mergeAction = new WorkspaceAction() {
protected void execute(IAction action) throws InvocationTargetException, InterruptedException {
new MergeOperation(getSite().getPage().getActivePart(), resources, path1, revision1, path2,
revision2).run();
}
};
mergeAction.run(null);
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), revertChangesAction.getText(), e.getMessage());
}
}
});
}
};
}
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
ILogEntry currentSelection = getLogEntry(ss);
revertChangesAction.setText(Policy.bind("HistoryView.revertChangesFromRevision", ""
+ currentSelection.getRevision().getNumber()));
}
if(ss.size() > 1) {
ILogEntry firstElement = getFirstElement();
ILogEntry lastElement = getLastElement();
revertChangesAction.setText(Policy.bind("HistoryView.revertChangesFromRevisions", ""
+ lastElement.getRevision().getNumber(), "" + firstElement.getRevision().getNumber()));
}
}
revertChangesAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_MARKMERGED));
return revertChangesAction;
}
private GenerateChangeLogAction getGenerateChangeLogAction() {
if (generateChangeLogAction == null) generateChangeLogAction = new GenerateChangeLogAction(new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
}
public ISelection getSelection() {
return SVNHistoryPage.this.getSelection();
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
}
public void setSelection(ISelection selection) {
}
});
return generateChangeLogAction;
}
// Refresh action (toolbar)
private IAction getRefreshAction() {
if(refreshAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
refreshAction = new Action(
Policy.bind("HistoryView.refreshLabel"), plugin.getImageDescriptor(ISVNUIConstants.IMG_REFRESH_ENABLED)) { //$NON-NLS-1$
public void run() {
refresh();
}
};
refreshAction.setToolTipText(Policy.bind("HistoryView.refresh")); //$NON-NLS-1$
refreshAction.setDisabledImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_REFRESH_DISABLED));
refreshAction.setHoverImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_REFRESH));
}
return refreshAction;
}
// Search action (toolbar)
private IAction getSearchAction() {
if (searchAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
searchAction = new Action(
Policy.bind("HistoryView.search"), plugin.getImageDescriptor(ISVNUIConstants.IMG_FILTER_HISTORY)) { //$NON-NLS-1$
public void run() {
if (historySearchDialog == null) {
historySearchDialog = new HistorySearchDialog(getSite().getShell(), remoteResource);
}
historySearchDialog.setRemoteResource(remoteResource);
if (historySearchDialog.open() == Window.OK) {
searchAction.setEnabled(false);
Utils.schedule(new SearchHistoryJob(), SVNUIPlugin.getPlugin().getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActivePart().getSite());
}
}
};
searchAction.setDisabledImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_FILTER_HISTORY_DISABLED));
}
return searchAction;
}
// Clear search action (toolbar)
private IAction getClearSearchAction() {
if (clearSearchAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
clearSearchAction = new Action(
Policy.bind("HistoryView.clearSearch"), plugin.getImageDescriptor(ISVNUIConstants.IMG_CLEAR)) { //$NON-NLS-1$
public void run() {
BusyIndicator.showWhile(tableHistoryViewer.getTable().getDisplay(), new Runnable() {
public void run() {
ViewerFilter[] filters = tableHistoryViewer.getFilters();
for (int i=0; i<filters.length; i++) {
ViewerFilter filter = filters[i];
if (filter instanceof HistorySearchViewerFilter) {
tableHistoryViewer.removeFilter(filter);
}
else if (filter instanceof EmptySearchViewerFilter) {
tableHistoryViewer.removeFilter(filter);
}
}
setEnabled(false);
if (!historySearchDialog.getSearchAllLogs() && (historySearchDialog.getStartRevision() != null || historySearchDialog.getEndRevision() != null)) {
getRefreshAction().run();
}
}
});
}
};
clearSearchAction.setDisabledImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_CLEAR_DISABLED));
}
return clearSearchAction;
}
// Get Get All action (toolbar)
private IAction getGetAllAction() {
if(getAllAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
getAllAction = new Action(
Policy.bind("HistoryView.getAll"), plugin.getImageDescriptor(ISVNUIConstants.IMG_GET_ALL)) { //$NON-NLS-1$
public void run() {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchAllLogEntriesJob == null) {
fetchAllLogEntriesJob = new FetchAllLogEntriesJob();
}
if(fetchAllLogEntriesJob.getState() != Job.NONE) {
fetchAllLogEntriesJob.cancel();
try {
fetchAllLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(Policy
.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchAllLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchAllLogEntriesJob, getSite());
}
};
getAllAction.setToolTipText(Policy.bind("HistoryView.getAll")); //$NON-NLS-1$
}
return getAllAction;
}
// Get Get Next action (toolbar)
public IAction getGetNextAction() {
if(getNextAction == null) {
getNextAction = new GetNextAction();
}
return getNextAction;
}
/**
* All context menu actions use this class This action : - updates
* currentSelection - action.run
*/
private Action getContextMenuAction(String title, final IWorkspaceRunnable action) {
return new Action(title) {
public void run() {
try {
if(resource == null)
return;
PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
action.run(monitor);
} catch(CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch(InvocationTargetException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e, SVNUIPlugin.LOG_NONTEAM_EXCEPTIONS);
} catch(InterruptedException e) {
// Do nothing
}
}
// we don't allow multiple selection
public boolean isEnabled() {
ISelection selection = getSelection();
return selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() == 1;
}
};
}
/**
* Ask the user to confirm the overwrite of the file if the file has been
* modified since last commit
*/
private boolean confirmOverwrite() {
IFile file = (IFile) resource;
if(file != null && file.exists()) {
ISVNLocalFile svnFile = SVNWorkspaceRoot.getSVNFileFor(file);
try {
if(svnFile.isDirty()) {
String title = Policy.bind("HistoryView.overwriteTitle"); //$NON-NLS-1$
String msg = Policy.bind("HistoryView.overwriteMsg"); //$NON-NLS-1$
final MessageDialog dialog = new MessageDialog(getSite().getShell(), title, null, msg,
MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.CANCEL_LABEL}, 0);
final int[] result = new int[ 1];
getSite().getShell().getDisplay().syncExec(new Runnable() {
public void run() {
result[ 0] = dialog.open();
}
});
if(result[ 0] != 0) {
// cancel
return false;
}
}
} catch(SVNException e) {
SVNUIPlugin.log(e.getStatus());
}
}
return true;
}
private ISelection getSelection() {
return selection;
}
private ILogEntry getFirstElement() {
ILogEntry firstElement = null;
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
Iterator iter = ss.iterator();
while(iter.hasNext()) {
ILogEntry element = (ILogEntry) iter.next();
if(firstElement == null || element.getRevision().getNumber() > firstElement.getRevision().getNumber())
firstElement = element;
}
}
return firstElement;
}
private ILogEntry getLastElement() {
ILogEntry lastElement = null;
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
Iterator iter = ss.iterator();
while(iter.hasNext()) {
ILogEntry element = (ILogEntry) iter.next();
if(lastElement == null || element.getRevision().getNumber() < lastElement.getRevision().getNumber())
lastElement = element;
}
}
return lastElement;
}
private final class GetNextAction extends Action implements IPropertyChangeListener {
GetNextAction() {
super(Policy.bind("HistoryView.getNext"), SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_GET_NEXT));
updateFromProperties();
SVNUIPlugin.getPlugin().getPreferenceStore().addPropertyChangeListener(this);
}
public void run() {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchNextLogEntriesJob == null) {
fetchNextLogEntriesJob = new FetchNextLogEntriesJob();
}
if(fetchNextLogEntriesJob.getState() != Job.NONE) {
fetchNextLogEntriesJob.cancel();
try {
fetchNextLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(Policy
.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchNextLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchNextLogEntriesJob, getSite());
}
public void propertyChange(PropertyChangeEvent event) {
if(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH.equals(event.getProperty())) {
updateFromProperties();
}
}
private void updateFromProperties() {
int entriesToFetch = SVNUIPlugin.getPlugin().getPreferenceStore().getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
setToolTipText(Policy.bind("HistoryView.getNext") + " " + entriesToFetch); //$NON-NLS-1$
if(entriesToFetch <= 0) {
setEnabled(false);
}
}
}
private class FetchLogEntriesJob extends AbstractFetchJob {
public ISVNRemoteResource remoteResource;
public FetchLogEntriesJob() {
super(Policy.bind("HistoryView.fetchHistoryJob")); //$NON-NLS-1$;
}
public void setRemoteFile(ISVNRemoteResource resource) {
this.remoteResource = resource;
}
public IStatus run(IProgressMonitor monitor) {
try {
if(remoteResource != null && !shutdown) {
if(resource == null) {
if(remoteResource == null
|| !SVNUIPlugin.getPlugin().getPreferenceStore().getBoolean(ISVNUIConstants.PREF_SHOW_TAGS_IN_REMOTE)) {
tagManager = null;
} else {
tagManager = new AliasManager(remoteResource.getUrl());
}
} else {
tagManager = new AliasManager(resource);
}
SVNRevision pegRevision = remoteResource.getRevision();
SVNRevision revisionEnd = new SVNRevision.Number(0);
boolean stopOnCopy = toggleStopOnCopyAction.isChecked();
boolean includeMergedRevisions = toggleIncludeMergedRevisionsAction.isChecked();
int entriesToFetch = store.getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
long limit = entriesToFetch;
entries = getLogEntries(monitor, remoteResource, pegRevision, revisionStart, revisionEnd, stopOnCopy,
limit + 1, tagManager, includeMergedRevisions);
long entriesLength = entries.length;
if(entriesLength > limit) {
ILogEntry[] fetchedEntries = new ILogEntry[ entries.length - 1];
for(int i = 0; i < entries.length - 1; i++) {
fetchedEntries[ i] = entries[ i];
}
entries = fetchedEntries;
getNextAction.setEnabled(true);
} else {
getNextAction.setEnabled(false);
}
final SVNRevision.Number revisionId = remoteResource.getLastChangedRevision();
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(entries != null && tableHistoryViewer != null && !tableHistoryViewer.getTable().isDisposed()) {
// once we got the entries, we refresh the table
if(entries.length > 0) {
lastEntry = entries[ entries.length - 1];
long lastEntryNumber = lastEntry.getRevision().getNumber();
revisionStart = new SVNRevision.Number(lastEntryNumber - 1);
}
tableHistoryViewer.refresh();
selectRevision(revisionId);
}
}
});
}
return Status.OK_STATUS;
} catch(TeamException e) {
return e.getStatus();
}
}
}
private class FetchNextLogEntriesJob extends AbstractFetchJob {
public ISVNRemoteResource remoteResource;
public FetchNextLogEntriesJob() {
super(Policy.bind("HistoryView.fetchHistoryJob")); //$NON-NLS-1$;
}
public void setRemoteFile(ISVNRemoteResource resource) {
this.remoteResource = resource;
}
public IStatus run(IProgressMonitor monitor) {
try {
if(remoteResource != null && !shutdown) {
SVNRevision pegRevision = remoteResource.getRevision();
SVNRevision revisionEnd = new SVNRevision.Number(0);
boolean stopOnCopy = toggleStopOnCopyAction.isChecked();
boolean includeMergedRevisions = toggleIncludeMergedRevisionsAction.isChecked();
int entriesToFetch = store.getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
long limit = entriesToFetch;
ILogEntry[] nextEntries = getLogEntries(monitor, remoteResource, pegRevision, revisionStart, revisionEnd,
stopOnCopy, limit + 1, tagManager, includeMergedRevisions);
long entriesLength = nextEntries.length;
ILogEntry[] fetchedEntries = null;
if(entriesLength > limit) {
fetchedEntries = new ILogEntry[ nextEntries.length - 1];
for(int i = 0; i < nextEntries.length - 1; i++)
fetchedEntries[ i] = nextEntries[ i];
getNextAction.setEnabled(true);
} else {
fetchedEntries = new ILogEntry[ nextEntries.length];
for(int i = 0; i < nextEntries.length; i++)
fetchedEntries[ i] = nextEntries[ i];
getNextAction.setEnabled(false);
}
ArrayList entryArray = new ArrayList();
if(entries == null)
entries = new ILogEntry[ 0];
for(int i = 0; i < entries.length; i++)
entryArray.add(entries[ i]);
for(int i = 0; i < fetchedEntries.length; i++)
entryArray.add(fetchedEntries[ i]);
entries = new ILogEntry[ entryArray.size()];
entryArray.toArray(entries);
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(entries != null && tableHistoryViewer != null && !tableHistoryViewer.getTable().isDisposed()) {
// once we got the entries, we refresh the table
ISelection selection = tableHistoryViewer.getSelection();
tableHistoryViewer.refresh();
tableHistoryViewer.setSelection(selection);
}
}
});
if(entries.length > 0) {
lastEntry = entries[ entries.length - 1];
long lastEntryNumber = lastEntry.getRevision().getNumber();
revisionStart = new SVNRevision.Number(lastEntryNumber - 1);
}
}
return Status.OK_STATUS;
} catch(TeamException e) {
return e.getStatus();
}
}
}
private abstract class AbstractFetchJob extends Job {
public AbstractFetchJob(String name) {
super(name);
}
public abstract void setRemoteFile(ISVNRemoteResource resource);
protected ILogEntry[] getLogEntries(IProgressMonitor monitor, ISVNRemoteResource remoteResource, SVNRevision pegRevision, SVNRevision revisionStart, SVNRevision revisionEnd, boolean stopOnCopy, long limit, AliasManager tagManager, boolean includeMergedRevisions) throws TeamException
{
// If filtering by revision range, pass upper/lower revisions to API and override limit.
SVNRevision start = revisionStart;
SVNRevision end = revisionEnd;
long fetchLimit = limit;
if (historySearchDialog != null && !historySearchDialog.getSearchAllLogs()) {
if (historySearchDialog.getStartRevision() != null || historySearchDialog.getEndRevision() != null) {
if (getClearSearchAction().isEnabled()) {
if (historySearchDialog.getStartRevision() != null) end = historySearchDialog.getStartRevision();
if (historySearchDialog.getEndRevision() != null) start = historySearchDialog.getEndRevision();
fetchLimit = 0;
getGetNextAction().setEnabled(false);
}
}
}
GetLogsCommand logCmd = new GetLogsCommand(remoteResource, pegRevision, start, end, stopOnCopy, fetchLimit, tagManager, includeMergedRevisions);
logCmd.run(monitor);
return logCmd.getLogEntries();
}
}
private class FetchAllLogEntriesJob extends AbstractFetchJob {
public ISVNRemoteResource remoteResource;
public FetchAllLogEntriesJob() {
super(Policy.bind("HistoryView.fetchHistoryJob")); //$NON-NLS-1$;
}
public void setRemoteFile(ISVNRemoteResource resource) {
this.remoteResource = resource;
}
public IStatus run(IProgressMonitor monitor) {
try {
if(remoteResource != null && !shutdown) {
if(resource == null) {
if(remoteResource == null
|| !SVNUIPlugin.getPlugin().getPreferenceStore().getBoolean(ISVNUIConstants.PREF_SHOW_TAGS_IN_REMOTE))
tagManager = null;
else
tagManager = new AliasManager(remoteResource.getUrl());
} else
tagManager = new AliasManager(resource);
SVNRevision pegRevision = remoteResource.getRevision();
revisionStart = SVNRevision.HEAD;
SVNRevision revisionEnd = new SVNRevision.Number(0);
boolean stopOnCopy = toggleStopOnCopyAction.isChecked();
boolean includeMergedRevisions = toggleIncludeMergedRevisionsAction.isChecked();
long limit = 0;
entries = getLogEntries(monitor, remoteResource, pegRevision, revisionStart, revisionEnd, stopOnCopy, limit,
tagManager, includeMergedRevisions);
final SVNRevision.Number revisionId = remoteResource.getLastChangedRevision();
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(entries != null && tableHistoryViewer != null && !tableHistoryViewer.getTable().isDisposed()) {
// once we got the entries, we refresh the table
if(entries.length > 0) {
lastEntry = entries[ entries.length - 1];
long lastEntryNumber = lastEntry.getRevision().getNumber();
revisionStart = new SVNRevision.Number(lastEntryNumber - 1);
}
tableHistoryViewer.refresh();
selectRevision(revisionId);
}
}
});
}
return Status.OK_STATUS;
} catch(TeamException e) {
return e.getStatus();
}
}
}
private class SearchHistoryJob extends Job {
public SearchHistoryJob() {
super(Policy.bind("HistoryView.searchHistoryJob")); //$NON-NLS-1$
}
public IStatus run(IProgressMonitor monitor) {
if (!historySearchDialog.getSearchAllLogs() && (historySearchDialog.getStartRevision() != null || historySearchDialog.getEndRevision() != null)) {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchAllLogEntriesJob == null) {
fetchAllLogEntriesJob = new FetchAllLogEntriesJob();
}
if(fetchAllLogEntriesJob.getState() != Job.NONE) {
fetchAllLogEntriesJob.cancel();
}
fetchAllLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchAllLogEntriesJob, getSite());
} else {
Date startDate = historySearchDialog.getStartDate();
setEmptyViewerFilter();
// Fetch log entries until start date
if (historySearchDialog.getAutoFetchLogs()) {
if (!historySearchDialog.getSearchAllLogs()) {
Date lastDate = null;
if (lastEntry != null) {
lastDate = lastEntry.getDate();
}
int numEntries = entries.length;
int prevNumEntries = -1;
while ((numEntries != prevNumEntries) &&
((lastDate == null) ||
(startDate == null) ||
(startDate.compareTo(lastDate) <= 0))) {
if (monitor.isCanceled()) {
getSearchAction().setEnabled(true);
removeEmptyViewerFilter();
return Status.CANCEL_STATUS;
}
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchNextLogEntriesJob == null) {
fetchNextLogEntriesJob = new FetchNextLogEntriesJob();
}
if(fetchNextLogEntriesJob.getState() != Job.NONE) {
fetchNextLogEntriesJob.cancel();
}
fetchNextLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchNextLogEntriesJob, getSite());
try {
fetchNextLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(
Policy.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
if (entries.length == 0) {
break;
}
lastDate = lastEntry.getDate();
prevNumEntries = numEntries;
numEntries = entries.length;
}
}
else {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchAllLogEntriesJob == null) {
fetchAllLogEntriesJob = new FetchAllLogEntriesJob();
}
if(fetchAllLogEntriesJob.getState() != Job.NONE) {
fetchAllLogEntriesJob.cancel();
}
fetchAllLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchAllLogEntriesJob, getSite());
}
}
}
final HistorySearchViewerFilter viewerFilter = new HistorySearchViewerFilter(
historySearchDialog.getUser(),
historySearchDialog.getComment(),
historySearchDialog.getStartDate(),
historySearchDialog.getEndDate(),
historySearchDialog.getRegExp(),
historySearchDialog.getStartRevision(),
historySearchDialog.getEndRevision());
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
BusyIndicator.showWhile(tableHistoryViewer.getTable().getDisplay(), new Runnable() {
public void run() {
getClearSearchAction().run();
tableHistoryViewer.addFilter(viewerFilter);
getClearSearchAction().setEnabled(true);
getSearchAction().setEnabled(true);
}
});
}
});
removeEmptyViewerFilter();
return Status.OK_STATUS;
}
private void setEmptyViewerFilter() {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
tableHistoryViewer.addFilter(new EmptySearchViewerFilter());
}
});
}
private void removeEmptyViewerFilter() {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
ViewerFilter[] filters = tableHistoryViewer.getFilters();
for (int i=0; i<filters.length; i++) {
if (filters[i] instanceof EmptySearchViewerFilter) {
tableHistoryViewer.removeFilter(filters[i]);
}
}
}
});
}
}
class FetchChangePathJob extends Job {
public ILogEntry logEntry;
public FetchChangePathJob() {
super(Policy.bind("HistoryView.fetchChangePathJob")); //$NON-NLS-1$;
}
public void setLogEntry(ILogEntry logEntry) {
this.logEntry = logEntry;
}
public IStatus run(IProgressMonitor monitor) {
if(logEntry.getResource() != null) {
setCurrentLogEntryChangePath(logEntry.getLogEntryChangePaths());
}
return Status.OK_STATUS;
}
}
public static class ToggleAffectedPathsOptionAction extends Action {
private final SVNHistoryPage page;
private final String preferenceName;
private final int value;
public ToggleAffectedPathsOptionAction(SVNHistoryPage page,
String label, String icon, String preferenceName, int value) {
super(Policy.bind(label), AS_RADIO_BUTTON);
this.page = page;
this.preferenceName = preferenceName;
this.value = value;
setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(icon));
IPreferenceStore store = SVNUIPlugin.getPlugin().getPreferenceStore();
setChecked(value==store.getInt(preferenceName));
}
public int getValue() {
return this.value;
}
public void run() {
if (isChecked()) {
SVNUIPlugin.getPlugin().getPreferenceStore().setValue(preferenceName, value);
page.createAffectedPathsViewer();
}
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.core.IResourceStateChangeListener#resourceSyncInfoChanged(org.eclipse.core.resources.IResource[])
*/
public void resourceSyncInfoChanged(IResource[] changedResources) {
for (int i = 0; i < changedResources.length; i++) {
IResource changedResource = changedResources[i];
if( changedResource.equals( resource ) ) {
resourceChanged();
}
}
}
/**
* This method updates the history table, highlighting the current revison
* without refetching the log entries to preserve bandwidth.
* The user has to a manual refresh to get the new log entries.
*/
private void resourceChanged() {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
revisionStart = SVNRevision.HEAD;
ISVNLocalResource localResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
try {
if (localResource != null && !localResource.getStatus().isAdded()) {
ISVNRemoteResource baseResource = localResource.getBaseResource();
historyTableProvider.setRemoteResource(baseResource);
historyTableProvider.setProjectProperties(null);
tableHistoryViewer.refresh();
}
} catch (SVNException e) {
SVNUIPlugin.openError(getHistoryPageSite().getShell(), null, null, e);
}
}
});
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent e) {
if (e.keyCode == 'f' && e.stateMask == SWT.CTRL) {
getSearchAction().run();
}
}
/*
* (non-Javadoc)
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent e) {
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.core.IResourceStateChangeListener#resourceModified(org.eclipse.core.resources.IResource[])
*/
public void resourceModified(IResource[] changedResources) {
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.core.IResourceStateChangeListener#projectConfigured(org.eclipse.core.resources.IProject)
*/
public void projectConfigured(IProject project) {
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.core.IResourceStateChangeListener#projectDeconfigured(org.eclipse.core.resources.IProject)
*/
public void projectDeconfigured(IProject project) {
}
public static void setHistorySearchViewerFilter(
HistorySearchViewerFilter historySearchViewerFilter) {
SVNHistoryPage.historySearchViewerFilter = historySearchViewerFilter;
}
}
|
org.tigris.subversion.subclipse.ui/src/org/tigris/subversion/subclipse/ui/history/SVNHistoryPage.java
|
/*******************************************************************************
* Copyright (c) 2006 Subclipse project and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subclipse project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.subclipse.ui.history;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextViewer;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.jface.text.hyperlink.IHyperlinkDetector;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.variants.IResourceVariant;
import org.eclipse.team.ui.history.HistoryPage;
import org.eclipse.team.ui.history.IHistoryPageSite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.TextSourceViewerConfiguration;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.tigris.subversion.subclipse.core.IResourceStateChangeListener;
import org.tigris.subversion.subclipse.core.ISVNLocalFile;
import org.tigris.subversion.subclipse.core.ISVNLocalResource;
import org.tigris.subversion.subclipse.core.ISVNRemoteFile;
import org.tigris.subversion.subclipse.core.ISVNRemoteResource;
import org.tigris.subversion.subclipse.core.ISVNResource;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.SVNProviderPlugin;
import org.tigris.subversion.subclipse.core.SVNStatus;
import org.tigris.subversion.subclipse.core.SVNTeamProvider;
import org.tigris.subversion.subclipse.core.commands.ChangeCommitPropertiesCommand;
import org.tigris.subversion.subclipse.core.commands.GetLogsCommand;
import org.tigris.subversion.subclipse.core.history.AliasManager;
import org.tigris.subversion.subclipse.core.history.ILogEntry;
import org.tigris.subversion.subclipse.core.history.LogEntry;
import org.tigris.subversion.subclipse.core.history.LogEntryChangePath;
import org.tigris.subversion.subclipse.core.resources.LocalResourceStatus;
import org.tigris.subversion.subclipse.core.resources.RemoteFolder;
import org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot;
import org.tigris.subversion.subclipse.ui.IHelpContextIds;
import org.tigris.subversion.subclipse.ui.ISVNUIConstants;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.subclipse.ui.SVNUIPlugin;
import org.tigris.subversion.subclipse.ui.actions.ExportRemoteFolderAction;
import org.tigris.subversion.subclipse.ui.actions.GenerateChangeLogAction;
import org.tigris.subversion.subclipse.ui.actions.OpenRemoteFileAction;
import org.tigris.subversion.subclipse.ui.actions.ShowAnnotationAction;
import org.tigris.subversion.subclipse.ui.actions.ShowDifferencesAsUnifiedDiffAction;
import org.tigris.subversion.subclipse.ui.actions.ShowHistoryAction;
import org.tigris.subversion.subclipse.ui.actions.WorkspaceAction;
import org.tigris.subversion.subclipse.ui.console.TextViewerAction;
import org.tigris.subversion.subclipse.ui.dialogs.HistorySearchDialog;
import org.tigris.subversion.subclipse.ui.dialogs.SetCommitPropertiesDialog;
import org.tigris.subversion.subclipse.ui.dialogs.ShowRevisionsDialog;
import org.tigris.subversion.subclipse.ui.internal.Utils;
import org.tigris.subversion.subclipse.ui.operations.BranchTagOperation;
import org.tigris.subversion.subclipse.ui.operations.MergeOperation;
import org.tigris.subversion.subclipse.ui.operations.ReplaceOperation;
import org.tigris.subversion.subclipse.ui.operations.SwitchOperation;
import org.tigris.subversion.subclipse.ui.settings.ProjectProperties;
import org.tigris.subversion.subclipse.ui.util.EmptySearchViewerFilter;
import org.tigris.subversion.subclipse.ui.util.LinkList;
import org.tigris.subversion.subclipse.ui.wizards.BranchTagWizard;
import org.tigris.subversion.subclipse.ui.wizards.ClosableWizardDialog;
import org.tigris.subversion.subclipse.ui.wizards.dialogs.SvnWizard;
import org.tigris.subversion.subclipse.ui.wizards.dialogs.SvnWizardDialog;
import org.tigris.subversion.subclipse.ui.wizards.dialogs.SvnWizardSwitchPage;
import org.tigris.subversion.svnclientadapter.ISVNClientAdapter;
import org.tigris.subversion.svnclientadapter.ISVNProperty;
import org.tigris.subversion.svnclientadapter.SVNRevision;
import org.tigris.subversion.svnclientadapter.SVNUrl;
/**
* <code>IHistoryPage</code> for generic history view
*
* @author Eugene Kuleshov (migration from legacy history view)
*/
public class SVNHistoryPage extends HistoryPage implements IResourceStateChangeListener, KeyListener {
private SashForm svnHistoryPageControl;
private SashForm innerSashForm;
private HistorySearchDialog historySearchDialog;
HistoryTableProvider historyTableProvider;
TableViewer tableHistoryViewer;
StructuredViewer changePathsViewer;
TextViewer textViewer;
private boolean showComments;
private boolean showAffectedPaths;
private boolean wrapCommentsText;
boolean shutdown = false;
private ProjectProperties projectProperties;
private Composite tableParent;
private static HistorySearchViewerFilter historySearchViewerFilter;
// cached for efficiency
ILogEntry[] entries;
LogEntryChangePath[] currentLogEntryChangePath;
ILogEntry lastEntry;
SVNRevision revisionStart = SVNRevision.HEAD;
AbstractFetchJob fetchLogEntriesJob = null;
AbstractFetchJob fetchAllLogEntriesJob = null;
AbstractFetchJob fetchNextLogEntriesJob = null;
FetchChangePathJob fetchChangePathJob = null;
AliasManager tagManager;
IResource resource;
ISVNRemoteResource remoteResource;
ISelection selection;
private IAction searchAction;
private IAction clearSearchAction;
private IAction getNextAction;
private IAction getAllAction;
private IAction toggleStopOnCopyAction;
private IAction toggleIncludeMergedRevisionsAction;
private IAction toggleShowComments;
private IAction toggleWrapCommentsAction;
private IAction toggleShowAffectedPathsAction;
private IAction openAction;
private IAction getContentsAction;
private IAction updateToRevisionAction;
private IAction openChangedPathAction;
private IAction showHistoryAction;
private IAction compareAction;
private IAction showAnnotationAction;
private IAction exportAction;
private IAction createTagFromRevisionChangedPathAction;
// private IAction switchChangedPathAction;
// private IAction revertChangesChangedPathAction;
private IAction createTagFromRevisionAction;
private IAction setCommitPropertiesAction;
private IAction showRevisionsAction;
private IAction revertChangesAction;
private IAction refreshAction;
private IAction switchAction;
private GenerateChangeLogAction generateChangeLogAction;
private ToggleAffectedPathsOptionAction[] toggleAffectedPathsLayoutActions;
private ToggleAffectedPathsOptionAction[] toggleAffectedPathsModeActions;
private TextViewerAction copyAction;
private TextViewerAction selectAllAction;
private LinkList linkList;
private Cursor handCursor;
private Cursor busyCursor;
private IPreferenceStore store = SVNUIPlugin.getPlugin().getPreferenceStore();
private boolean includeTags = true;
private boolean includeBugs = false;
public SVNHistoryPage(Object object) {
SVNProviderPlugin.addResourceStateChangeListener(this);
}
public void dispose() {
super.dispose();
SVNProviderPlugin.removeResourceStateChangeListener(this);
if(busyCursor!=null) {
busyCursor.dispose();
}
if(handCursor!=null) {
handCursor.dispose();
}
}
public Control getControl() {
return svnHistoryPageControl;
}
public void setFocus() {
// TODO Auto-generated method stub
}
public String getDescription() {
// TODO Auto-generated method stub
return null;
}
public String getName() {
return remoteResource == null ? null : remoteResource.getRepositoryRelativePath() + " in "
+ remoteResource.getRepository();
}
public boolean isValidInput(Object object) {
if(object instanceof IResource) {
RepositoryProvider provider = RepositoryProvider.getProvider(((IResource) object).getProject());
return provider instanceof SVNTeamProvider;
} else if(object instanceof ISVNRemoteResource) {
return true;
}
// TODO
// } else if(object instanceof CVSFileRevision) {
// return true;
// } else if(object instanceof CVSLocalFileRevision) {
// return true;
return false;
}
public void refresh() {
entries = null;
lastEntry = null;
revisionStart = SVNRevision.HEAD;
// show a Busy Cursor during refresh
BusyIndicator.showWhile(tableHistoryViewer.getTable().getDisplay(), new Runnable() {
public void run() {
if(resource != null) {
try {
remoteResource = SVNWorkspaceRoot.getBaseResourceFor(resource);
historyTableProvider.setRemoteResource(remoteResource);
projectProperties = ProjectProperties.getProjectProperties(resource);
historyTableProvider.setProjectProperties(projectProperties);
} catch(SVNException e) {
}
}
if (tableHistoryViewer.getInput() == null) tableHistoryViewer.setInput(remoteResource);
tableHistoryViewer.refresh();
tableHistoryViewer.resetFilters();
getClearSearchAction().setEnabled(false);
}
});
}
public Object getAdapter(Class adapter) {
// TODO Auto-generated method stub
return null;
}
public boolean inputSet() {
Object input = getInput();
if(input instanceof IResource) {
IResource res = (IResource) input;
RepositoryProvider teamProvider = RepositoryProvider.getProvider(res.getProject(), SVNProviderPlugin.getTypeId());
if(teamProvider != null) {
try {
ISVNLocalResource localResource = SVNWorkspaceRoot.getSVNResourceFor(res);
LocalResourceStatus localResourceStatus = (localResource != null) ? localResource.getStatus() : null;
if(localResource != null && localResourceStatus.isManaged() && (!localResourceStatus.isAdded() || localResourceStatus.isCopied())) {
this.resource = res;
this.remoteResource = localResource.getBaseResource();
this.projectProperties = ProjectProperties.getProjectProperties(res);
boolean includeBugs = projectProperties != null;
boolean includeTags = tagsPropertySet(res);
if (includeTags != this.includeTags || this.includeBugs != includeBugs ) {
this.includeTags = includeTags;
this.includeBugs = includeBugs;
refreshTable();
}
this.historyTableProvider.setRemoteResource(this.remoteResource);
this.historyTableProvider.setProjectProperties(this.projectProperties);
if (historySearchViewerFilter != null) {
// HistorySearchViewerFilter[] filters = { historySearchViewerFilter };
// this.tableHistoryViewer.setFilters(filters);
this.tableHistoryViewer.resetFilters();
this.tableHistoryViewer.addFilter(historySearchViewerFilter);
historySearchDialog = new HistorySearchDialog(getSite().getShell(), remoteResource);
historySearchDialog.setSearchAll(false);
historySearchDialog.setStartRevision(historySearchViewerFilter.getStartRevision());
historySearchDialog.setEndRevision(historySearchViewerFilter.getEndRevision());
historySearchViewerFilter = null;
getClearSearchAction().setEnabled(true);
}
else {
this.tableHistoryViewer.resetFilters();
getClearSearchAction().setEnabled(false);
}
this.tableHistoryViewer.setInput(this.remoteResource);
// setContentDescription(Policy.bind("HistoryView.titleWithArgument",
// baseResource.getName())); //$NON-NLS-1$
// setTitleToolTip(baseResource.getRepositoryRelativePath());
return true;
}
} catch(TeamException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e);
}
}
} else if(input instanceof ISVNRemoteResource) {
this.resource = null;
this.remoteResource = (ISVNRemoteResource) input;
boolean includeTags = tagsPropertySet(remoteResource);
if (includeTags != this.includeTags) {
this.includeTags = includeTags;
refreshTable();
}
try {
this.projectProperties = ProjectProperties.getProjectProperties(this.remoteResource);
} catch (SVNException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e);
}
boolean includeBugs = projectProperties != null;
if (includeTags != this.includeTags || this.includeBugs != includeBugs ) {
this.includeTags = includeTags;
this.includeBugs = includeBugs;
refreshTable();
}
this.historyTableProvider.setRemoteResource(this.remoteResource);
this.historyTableProvider.setProjectProperties(this.projectProperties);
if (historySearchViewerFilter != null) {
// HistorySearchViewerFilter[] filters = { historySearchViewerFilter };
// this.tableHistoryViewer.setFilters(filters);
this.tableHistoryViewer.resetFilters();
this.tableHistoryViewer.addFilter(historySearchViewerFilter);
historySearchDialog = new HistorySearchDialog(getSite().getShell(), remoteResource);
historySearchDialog.setSearchAll(false);
historySearchDialog.setStartRevision(historySearchViewerFilter.getStartRevision());
historySearchDialog.setEndRevision(historySearchViewerFilter.getEndRevision());
historySearchViewerFilter = null;
getClearSearchAction().setEnabled(true);
}
else {
this.tableHistoryViewer.resetFilters();
getClearSearchAction().setEnabled(false);
}
this.tableHistoryViewer.setInput(this.remoteResource);
// setContentDescription(Policy.bind("HistoryView.titleWithArgument",
// remoteResource.getName())); //$NON-NLS-1$
// setTitleToolTip(remoteResource.getRepositoryRelativePath());
return true;
}
return false;
}
private boolean tagsPropertySet(IResource resource) {
if (resource == null) return false;
ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
try {
if (svnResource.isManaged()) {
ISVNProperty property = null;
property = svnResource.getSvnProperty("subclipse:tags"); //$NON-NLS-1$
if (property != null && property.getValue() != null) return true;
}
} catch (SVNException e) {}
IResource checkResource = resource;
while (checkResource.getParent() != null) {
checkResource = checkResource.getParent();
if (checkResource.getParent() == null) return false;
svnResource = SVNWorkspaceRoot.getSVNResourceFor(checkResource);
try {
if (svnResource.isManaged()) {
ISVNProperty property = null;
property = svnResource.getSvnProperty("subclipse:tags"); //$NON-NLS-1$
if (property != null && property.getValue() != null) return true;
}
} catch (SVNException e) {}
}
return false;
}
private boolean tagsPropertySet(ISVNRemoteResource resource) {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClient();
ISVNProperty property = null;
SVNProviderPlugin.disableConsoleLogging();
property = client.propertyGet(resource.getUrl(), "subclipse:tags"); //$NON-NLS-1$
if (property != null && property.getValue() != null) {
SVNProviderPlugin.enableConsoleLogging();
return true;
}
ISVNRemoteResource checkResource = resource;
while (checkResource.getParent() != null) {
checkResource = checkResource.getParent();
property = client.propertyGet(checkResource.getUrl(), "subclipse:tags"); //$NON-NLS-1$
if (property != null && property.getValue() != null) {
SVNProviderPlugin.enableConsoleLogging();
return true;
}
}
} catch (Exception e) {
SVNProviderPlugin.enableConsoleLogging();
}
return false;
}
public void createControl(Composite parent) {
this.busyCursor = new Cursor(parent.getDisplay(), SWT.CURSOR_WAIT);
this.handCursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND);
this.showComments = store.getBoolean(ISVNUIConstants.PREF_SHOW_COMMENTS);
this.wrapCommentsText = store.getBoolean(ISVNUIConstants.PREF_WRAP_COMMENTS);
this.showAffectedPaths = store.getBoolean(ISVNUIConstants.PREF_SHOW_PATHS);
this.svnHistoryPageControl = new SashForm(parent, SWT.VERTICAL);
this.svnHistoryPageControl.setLayoutData(new GridData(GridData.FILL_BOTH));
this.toggleAffectedPathsModeActions = new ToggleAffectedPathsOptionAction[] {
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsTableLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_TABLE_MODE,
ISVNUIConstants.PREF_AFFECTED_PATHS_MODE,
ISVNUIConstants.MODE_FLAT),
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsFlatLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_FLAT_MODE,
ISVNUIConstants.PREF_AFFECTED_PATHS_MODE,
ISVNUIConstants.MODE_FLAT2),
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsCompressedLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_COMPRESSED_MODE,
ISVNUIConstants.PREF_AFFECTED_PATHS_MODE,
ISVNUIConstants.MODE_COMPRESSED),
};
this.toggleAffectedPathsLayoutActions = new ToggleAffectedPathsOptionAction[] {
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsHorizontalLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_HORIZONTAL_LAYOUT,
ISVNUIConstants.PREF_AFFECTED_PATHS_LAYOUT,
ISVNUIConstants.LAYOUT_HORIZONTAL),
new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsVerticalLayout",
ISVNUIConstants.IMG_AFFECTED_PATHS_VERTICAL_LAYOUT,
ISVNUIConstants.PREF_AFFECTED_PATHS_LAYOUT,
ISVNUIConstants.LAYOUT_VERTICAL),
};
createTableHistory(svnHistoryPageControl);
createAffectedPathsViewer();
contributeActions();
svnHistoryPageControl.setWeights(new int[] { 70, 30});
// set F1 help
// PlatformUI.getWorkbench().getHelpSystem().setHelp(svnHistoryPageControl,
// IHelpContextIds.RESOURCE_HISTORY_VIEW);
// initDragAndDrop();
// add listener for editor page activation - this is to support editor
// linking
// getSite().getPage().addPartListener(partListener);
// getSite().getPage().addPartListener(partListener2);
}
protected void createTableHistory(Composite parent) {
boolean redraw = false;
if (tableParent == null) {
tableParent = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.marginHeight = 0;
layout.marginWidth = 0;
tableParent.setLayout(layout);
GridData gridData = new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL);
gridData.horizontalIndent = 0;
gridData.verticalIndent = 0;
tableParent.setLayoutData(gridData);
} else {
Control[] children = tableParent.getChildren();
for (int i = 0; i < children.length; i++) {
children[i].dispose();
}
redraw = true;
}
this.historyTableProvider = new HistoryTableProvider(SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION, "SVNHistoryPage"); //$NON-NLS-1$
this.historyTableProvider.setProjectProperties( this.projectProperties );
historyTableProvider.setIncludeMergeRevisions(store.getBoolean(ISVNUIConstants.PREF_INCLUDE_MERGED_REVISIONS));
historyTableProvider.setIncludeTags(includeTags);
historyTableProvider.setIncludeBugs(includeBugs);
this.tableHistoryViewer = historyTableProvider.createTable(tableParent);
if (redraw) {
tableParent.layout(true);
tableParent.redraw();
}
this.tableHistoryViewer.getTable().addKeyListener(this);
// set the content provider for the table
this.tableHistoryViewer.setContentProvider(new IStructuredContentProvider() {
public Object[] getElements(Object inputElement) {
// Short-circuit to optimize
if(entries != null)
return entries;
if( !(inputElement instanceof ISVNRemoteResource))
return null;
final ISVNRemoteResource remoteResource = (ISVNRemoteResource) inputElement;
int entriesToFetch = store.getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
// If we are filtering by revision range, override entries to fetch.
if (historySearchDialog != null && !historySearchDialog.getSearchAllLogs()) {
if (historySearchDialog.getStartRevision() != null || historySearchDialog.getEndRevision() != null) {
if (getClearSearchAction().isEnabled()) entriesToFetch = 0;
}
}
if (entriesToFetch > 0)
fetchLogEntriesJob = new FetchLogEntriesJob();
else
fetchLogEntriesJob = new FetchAllLogEntriesJob();
if(fetchLogEntriesJob.getState() != Job.NONE) {
fetchLogEntriesJob.cancel();
try {
fetchLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(
Policy.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchLogEntriesJob, SVNUIPlugin.getPlugin().getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActivePart().getSite());
return new Object[ 0];
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
entries = null;
lastEntry = null;
revisionStart = SVNRevision.HEAD;
}
});
// set the selectionchanged listener for the table
// updates the comments and affected paths when selection changes
this.tableHistoryViewer.addSelectionChangedListener(new ISelectionChangedListener() {
private ILogEntry currentLogEntry;
private int currentSelectionSize = -1;
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
ILogEntry logEntry = getLogEntry((IStructuredSelection) selection);
if(logEntry != currentLogEntry || ((IStructuredSelection) selection).size() != currentSelectionSize) {
this.currentLogEntry = logEntry;
this.currentSelectionSize = ((IStructuredSelection) selection).size();
updatePanels(selection);
}
SVNHistoryPage.this.selection = selection;
}
});
// Double click open action
this.tableHistoryViewer.getTable().addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
getOpenRemoteFileAction().run();
}
});
// Contribute actions to popup menu for the table
{
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(tableHistoryViewer.getTable());
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
fillTableMenu(menuMgr);
}
});
menuMgr.setRemoveAllWhenShown(true);
tableHistoryViewer.getTable().setMenu(menu);
getHistoryPageSite().getPart().getSite().registerContextMenu(menuMgr, tableHistoryViewer);
}
if (redraw) {
parent.layout(true);
parent.redraw();
}
}
public void refreshTable() {
createTableHistory(svnHistoryPageControl);
}
private void fillChangePathsMenu(IMenuManager manager) {
//
// Commented out Get Contents, Revert and Switch options until when/if
// they can be fixed. Problem is that we need a way to get the local
// resource from the LogEntryChangePath.
//
IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
if (sel.size() == 1) {
if (sel.getFirstElement() instanceof LogEntryChangePath) {
// manager.add(getGetContentsAction());
}
manager.add(getCreateTagFromRevisionChangedPathAction());
}
// manager.add(getRevertChangesChangedPathAction());
// manager.add(getSwitchChangedPathAction());
manager.add(new Separator("exportImportGroup")); //$NON-NLS-1$
if (sel.size() == 1) {
if (sel.getFirstElement() instanceof LogEntryChangePath) {
manager.add(getExportAction());
}
}
manager.add(new Separator("openGroup")); //$NON-NLS-1$
if (sel.size() == 1) {
if (sel.getFirstElement() instanceof LogEntryChangePath) {
manager.add(getShowAnnotationAction());
}
manager.add(getCompareAction());
}
if (sel.getFirstElement() instanceof LogEntryChangePath) {
manager.add(getOpenChangedPathAction());
}
if (sel.size() == 1) manager.add(getShowHistoryAction());
}
private void fillTableMenu(IMenuManager manager) {
// file actions go first (view file)
manager.add(new Separator(IWorkbenchActionConstants.GROUP_FILE));
// Add the "Add to Workspace" action if 1 revision is selected.
ISelection sel = tableHistoryViewer.getSelection();
if( !sel.isEmpty()) {
if(sel instanceof IStructuredSelection) {
if(((IStructuredSelection) sel).size() == 1) {
if(resource != null && resource instanceof IFile) {
manager.add(getGetContentsAction());
manager.add(getUpdateToRevisionAction());
}
// manager.add(getShowDifferencesAsUnifiedDiffAction());
// if (resource != null) {
manager.add(getCreateTagFromRevisionAction());
// }
manager.add(getSetCommitPropertiesAction());
ILogEntry logEntry = (ILogEntry)((IStructuredSelection)sel).getFirstElement();
if (logEntry.getNumberOfChildren() > 0)
manager.add(getShowRevisionsAction());
}
if(resource != null) {
manager.add(getRevertChangesAction());
if(((IStructuredSelection) sel).size() == 1) manager.add(getSwitchAction());
}
manager.add(new Separator("exportImportGroup")); //$NON-NLS-1$
getGenerateChangeLogAction().setEnabled(!store.getBoolean(ISVNUIConstants.PREF_FETCH_CHANGE_PATH_ON_DEMAND));
manager.add(getGenerateChangeLogAction());
}
}
manager.add(new Separator("additions")); //$NON-NLS-1$
manager.add(getRefreshAction());
manager.add(new Separator("additions-end")); //$NON-NLS-1$
}
public void createAffectedPathsViewer() {
int[] weights = null;
weights = svnHistoryPageControl.getWeights();
if(innerSashForm != null) {
innerSashForm.dispose();
}
if(changePathsViewer != null) {
changePathsViewer.getControl().dispose();
}
int mode = store.getInt(ISVNUIConstants.PREF_AFFECTED_PATHS_MODE);
int layout = store.getInt(ISVNUIConstants.PREF_AFFECTED_PATHS_LAYOUT);
if(layout==ISVNUIConstants.LAYOUT_HORIZONTAL) {
innerSashForm = new SashForm(svnHistoryPageControl, SWT.HORIZONTAL);
} else {
innerSashForm = new SashForm(svnHistoryPageControl, SWT.VERTICAL);
createText(innerSashForm);
}
switch(mode) {
case ISVNUIConstants.MODE_COMPRESSED:
changePathsViewer = new ChangePathsTreeViewer(innerSashForm, this);
break;
case ISVNUIConstants.MODE_FLAT2:
changePathsViewer = new ChangePathsFlatViewer(innerSashForm, this);
break;
default:
changePathsViewer = new ChangePathsTableProvider(innerSashForm, this);
break;
}
changePathsViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
SVNHistoryPage.this.selection = changePathsViewer.getSelection();
}
});
changePathsViewer.getControl().addListener(SWT.DefaultSelection, new Listener() {
public void handleEvent(Event e) {
getOpenChangedPathAction().run();
}
});
// Contribute actions to changed paths pane
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(changePathsViewer.getControl());
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
fillChangePathsMenu(menuMgr);
}
});
menuMgr.setRemoveAllWhenShown(true);
changePathsViewer.getControl().setMenu(menu);
if(layout==ISVNUIConstants.LAYOUT_HORIZONTAL) {
createText(innerSashForm);
}
setViewerVisibility();
innerSashForm.layout();
if(weights!=null && weights.length==2) {
svnHistoryPageControl.setWeights(weights);
}
svnHistoryPageControl.layout();
updatePanels(tableHistoryViewer.getSelection());
}
/**
* Create the TextViewer for the logEntry comments
*/
protected void createText(Composite parent) {
// this.textViewer = new TextViewer(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY);
SourceViewer result = new SourceViewer(parent, null, null, true, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY);
result.getTextWidget().setIndent(2);
result.configure(new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore()) {
public Map getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
return Collections.singletonMap("org.eclipse.ui.DefaultTextEditor", //$NON-NLS-1$
new IAdaptable() {
public Object getAdapter(Class adapter) {
if(adapter==IResource.class && getInput() instanceof IResource) {
return getInput();
} else if(adapter==ISVNRemoteResource.class && getInput() instanceof ISVNRemoteResource) {
return getInput();
}
return Platform.getAdapterManager().getAdapter(SVNHistoryPage.this, adapter);
}
});
}
public int getHyperlinkStateMask(ISourceViewer sourceViewer) {
return SWT.NONE;
}
public IHyperlinkDetector[] getHyperlinkDetectors(ISourceViewer sourceViewer) {
IHyperlinkDetector[] detectors = super.getHyperlinkDetectors(sourceViewer);
IHyperlinkDetector[] newDetectors;
if(detectors==null) {
newDetectors = new IHyperlinkDetector[1];
} else {
newDetectors = new IHyperlinkDetector[detectors.length + 1];
System.arraycopy(detectors, 0, newDetectors, 0, detectors.length);
}
newDetectors[newDetectors.length - 1] = new IHyperlinkDetector() {
public IHyperlink[] detectHyperlinks(ITextViewer textViewer,
IRegion region, boolean canShowMultipleHyperlinks) {
if(linkList==null || !linkList.isLinkAt(region.getOffset())) {
return null;
}
final String linkUrl = linkList.getLinkAt(region.getOffset());
final int[] linkRange = linkList.getLinkRange(region.getOffset());
return new IHyperlink[] { new IHyperlink() {
public IRegion getHyperlinkRegion() {
return new Region(linkRange[0], linkRange[1]);
}
public void open() {
try {
URL url = new URL(linkUrl);
PlatformUI.getWorkbench().getBrowserSupport().createBrowser("Subclipse").openURL(url);
} catch (Exception e1) {
Program.launch(linkUrl);
}
}
public String getHyperlinkText() {
return null;
}
public String getTypeLabel() {
return null;
}
}};
}
};
return newDetectors;
}
});
this.textViewer = result;
this.textViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
copyAction.update();
}
});
Font font = PlatformUI.getWorkbench().getThemeManager().getCurrentTheme().getFontRegistry().get(
ISVNUIConstants.SVN_COMMENT_FONT);
if(font != null) {
this.textViewer.getTextWidget().setFont(font);
}
// Create actions for the text editor (copy and select all)
copyAction = new TextViewerAction(this.textViewer, ITextOperationTarget.COPY);
copyAction.setText(Policy.bind("HistoryView.copy")); //$NON-NLS-1$
selectAllAction = new TextViewerAction(this.textViewer, ITextOperationTarget.SELECT_ALL);
selectAllAction.setText(Policy.bind("HistoryView.selectAll")); //$NON-NLS-1$
IHistoryPageSite parentSite = getHistoryPageSite();
IPageSite pageSite = parentSite.getWorkbenchPageSite();
IActionBars actionBars = pageSite.getActionBars();
actionBars.setGlobalActionHandler(ITextEditorActionConstants.COPY, copyAction);
actionBars.setGlobalActionHandler(ITextEditorActionConstants.SELECT_ALL, selectAllAction);
actionBars.updateActionBars();
// Contribute actions to popup menu for the comments area
{
MenuManager menuMgr = new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager menuMgr) {
menuMgr.add(copyAction);
menuMgr.add(selectAllAction);
}
});
StyledText text = this.textViewer.getTextWidget();
Menu menu = menuMgr.createContextMenu(text);
text.setMenu(menu);
}
}
private void contributeActions() {
toggleShowComments = new Action(Policy.bind("HistoryView.showComments"), //$NON-NLS-1$
SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_COMMENTS)) {
public void run() {
showComments = isChecked();
setViewerVisibility();
store.setValue(ISVNUIConstants.PREF_SHOW_COMMENTS, showComments);
}
};
toggleShowComments.setChecked(showComments);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleTextAction,
// IHelpContextIds.SHOW_COMMENT_IN_HISTORY_ACTION);
// Toggle wrap comments action
toggleWrapCommentsAction = new Action(Policy.bind("HistoryView.wrapComments")) { //$NON-NLS-1$
public void run() {
wrapCommentsText = isChecked();
setViewerVisibility();
store.setValue(ISVNUIConstants.PREF_WRAP_COMMENTS, wrapCommentsText);
}
};
toggleWrapCommentsAction.setChecked(wrapCommentsText);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleTextWrapAction,
// IHelpContextIds.SHOW_TAGS_IN_HISTORY_ACTION);
// Toggle path visible action
toggleShowAffectedPathsAction = new Action(Policy.bind("HistoryView.showAffectedPaths"), //$NON-NLS-1$
SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_AFFECTED_PATHS_FLAT_MODE)) {
public void run() {
showAffectedPaths = isChecked();
setViewerVisibility();
store.setValue(ISVNUIConstants.PREF_SHOW_PATHS, showAffectedPaths);
}
};
toggleShowAffectedPathsAction.setChecked(showAffectedPaths);
// PlatformUI.getWorkbench().getHelpSystem().setHelp(toggleListAction,
// IHelpContextIds.SHOW_TAGS_IN_HISTORY_ACTION);
// Toggle stop on copy action
toggleStopOnCopyAction = new Action(Policy.bind("HistoryView.stopOnCopy")) { //$NON-NLS-1$
public void run() {
refresh();
SVNUIPlugin.getPlugin().getPreferenceStore().setValue(ISVNUIConstants.PREF_STOP_ON_COPY,
toggleStopOnCopyAction.isChecked());
}
};
toggleStopOnCopyAction.setChecked(store.getBoolean(ISVNUIConstants.PREF_STOP_ON_COPY));
// Toggle include merged revisions action
toggleIncludeMergedRevisionsAction = new Action(Policy.bind("HistoryView.includeMergedRevisions")) { //$NON-NLS-1$
public void run() {
store.setValue(ISVNUIConstants.PREF_INCLUDE_MERGED_REVISIONS, toggleIncludeMergedRevisionsAction.isChecked());
refreshTable();
refresh();
}
};
toggleIncludeMergedRevisionsAction.setChecked(store.getBoolean(ISVNUIConstants.PREF_INCLUDE_MERGED_REVISIONS));
IHistoryPageSite parentSite = getHistoryPageSite();
IPageSite pageSite = parentSite.getWorkbenchPageSite();
IActionBars actionBars = pageSite.getActionBars();
// Contribute toggle text visible to the toolbar drop-down
IMenuManager actionBarsMenu = actionBars.getMenuManager();
actionBarsMenu.add(getGetNextAction());
actionBarsMenu.add(getGetAllAction());
actionBarsMenu.add(toggleStopOnCopyAction);
actionBarsMenu.add(toggleIncludeMergedRevisionsAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(toggleWrapCommentsAction);
actionBarsMenu.add(new Separator());
actionBarsMenu.add(toggleShowComments);
actionBarsMenu.add(toggleShowAffectedPathsAction);
actionBarsMenu.add(new Separator());
for (int i = 0; i < toggleAffectedPathsModeActions.length; i++) {
actionBarsMenu.add(toggleAffectedPathsModeActions[i]);
}
actionBarsMenu.add(new Separator());
for (int i = 0; i < toggleAffectedPathsLayoutActions.length; i++) {
actionBarsMenu.add(toggleAffectedPathsLayoutActions[i]);
}
// Create the local tool bar
IToolBarManager tbm = actionBars.getToolBarManager();
// tbm.add(getRefreshAction());
tbm.add(new Separator());
tbm.add(getSearchAction());
tbm.add(getClearSearchAction());
tbm.add(new Separator());
tbm.add(toggleShowComments);
tbm.add(toggleShowAffectedPathsAction);
tbm.add(new Separator());
tbm.add(getGetNextAction());
tbm.add(getGetAllAction());
// tbm.add(getLinkWithEditorAction());
tbm.update(false);
actionBars.updateActionBars();
}
ILogEntry getLogEntry(IStructuredSelection ss) {
if(ss.getFirstElement() instanceof LogEntryChangePath) {
return ((LogEntryChangePath) ss.getFirstElement()).getLogEntry();
}
return (ILogEntry) ss.getFirstElement();
}
void updatePanels(ISelection selection) {
if(selection == null || !(selection instanceof IStructuredSelection)) {
textViewer.setDocument(new Document("")); //$NON-NLS-1$
changePathsViewer.setInput(null);
return;
}
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() != 1) {
textViewer.setDocument(new Document("")); //$NON-NLS-1$
changePathsViewer.setInput(null);
return;
}
LogEntry entry = (LogEntry) ss.getFirstElement();
textViewer.setDocument(new Document(entry.getComment()));
StyledText text = textViewer.getTextWidget();
// TODO move this logic into the hyperlink detector created in createText()
if(projectProperties == null) {
linkList = ProjectProperties.getUrls(entry.getComment());
} else {
linkList = projectProperties.getLinkList(entry.getComment());
}
if(linkList != null) {
int[][] linkRanges = linkList.getLinkRanges();
// String[] urls = linkList.getUrls();
for(int i = 0; i < linkRanges.length; i++) {
text.setStyleRange(new StyleRange(linkRanges[ i][ 0], linkRanges[ i][ 1],
JFaceColors.getHyperlinkText(Display.getCurrent()), null));
}
}
if (changePathsViewer instanceof ChangePathsTreeViewer) {
((ChangePathsTreeViewer)changePathsViewer).setCurrentLogEntry(entry);
}
if (changePathsViewer instanceof ChangePathsFlatViewer) {
((ChangePathsFlatViewer)changePathsViewer).setCurrentLogEntry(entry);
}
if (changePathsViewer instanceof ChangePathsTableProvider) {
((ChangePathsTableProvider)changePathsViewer).setCurrentLogEntry(entry);
}
changePathsViewer.setInput(entry);
}
void setViewerVisibility() {
if(showComments && showAffectedPaths) {
svnHistoryPageControl.setMaximizedControl(null);
innerSashForm.setMaximizedControl(null);
} else if(showComments) {
svnHistoryPageControl.setMaximizedControl(null);
innerSashForm.setMaximizedControl(textViewer.getTextWidget());
} else if(showAffectedPaths) {
svnHistoryPageControl.setMaximizedControl(null);
innerSashForm.setMaximizedControl(changePathsViewer.getControl());
} else {
svnHistoryPageControl.setMaximizedControl(tableParent);
}
changePathsViewer.refresh();
textViewer.getTextWidget().setWordWrap(wrapCommentsText);
}
void setCurrentLogEntryChangePath(final LogEntryChangePath[] currentLogEntryChangePath) {
this.currentLogEntryChangePath = currentLogEntryChangePath;
if( !shutdown) {
// Getting the changePaths
/*
* final SVNRevision.Number revisionId =
* remoteResource.getLastChangedRevision();
*/
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(currentLogEntryChangePath != null && changePathsViewer != null
&& !changePathsViewer.getControl().isDisposed()) {
// once we got the changePath, we refresh the table
changePathsViewer.refresh();
// selectRevision(revisionId);
}
}
});
}
}
/**
* Select the revision in the receiver.
*/
public void selectRevision(SVNRevision.Number revision) {
if(entries == null) {
return;
}
ILogEntry entry = null;
for(int i = 0; i < entries.length; i++) {
if(entries[ i].getRevision().equals(revision)) {
entry = entries[ i];
break;
}
}
if(entry != null) {
IStructuredSelection selection = new StructuredSelection(entry);
tableHistoryViewer.setSelection(selection, true);
}
}
public void scheduleFetchChangePathJob(ILogEntry logEntry) {
if(fetchChangePathJob == null) {
fetchChangePathJob = new FetchChangePathJob();
}
if(fetchChangePathJob.getState() != Job.NONE) {
fetchChangePathJob.cancel();
try {
fetchChangePathJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(IStatus.ERROR, e.getMessage(), e);
// SVNUIPlugin.log(new
// SVNException(Policy.bind("HistoryView.errorFetchingEntries",
// remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchChangePathJob.setLogEntry(logEntry);
Utils.schedule(fetchChangePathJob, getSite());
}
public boolean isShowChangePaths() {
return showAffectedPaths;
}
private SVNRevision getSelectedRevision() {
IStructuredSelection sel = (IStructuredSelection)tableHistoryViewer.getSelection();
if (sel.getFirstElement() instanceof ILogEntry) {
return ((ILogEntry)sel.getFirstElement()).getRevision();
}
return null;
}
private IAction getOpenRemoteFileAction() {
if(openAction == null) {
openAction = new Action() {
public void run() {
OpenRemoteFileAction delegate = new OpenRemoteFileAction();
delegate.init(this);
delegate.selectionChanged(this, tableHistoryViewer.getSelection());
if(isEnabled()) {
try {
// disableEditorActivation = true;
delegate.run(this);
} finally {
// disableEditorActivation = false;
}
}
}
};
}
return openAction;
}
private boolean deleteSelected() {
IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
return (sel.size() == 1 && sel.getFirstElement() instanceof LogEntryChangePath &&
((LogEntryChangePath)sel.getFirstElement()).getAction() == 'D');
}
// open changed Path (double-click)
private IAction getOpenChangedPathAction() {
if(openChangedPathAction == null) {
openChangedPathAction = new Action("Open") { //$NON-NLS-1$
public void run() {
OpenRemoteFileAction delegate = new OpenRemoteFileAction();
delegate.setUsePegRevision(true);
delegate.init(this);
delegate.selectionChanged(this, changePathsViewer.getSelection());
if(isEnabled()) {
try {
// disableEditorActivation = true;
delegate.run(this);
} finally {
// disableEditorActivation = false;
}
}
}
};
}
openChangedPathAction.setEnabled(!deleteSelected());
return openChangedPathAction;
}
private IAction getShowHistoryAction() {
if(showHistoryAction == null) {
showHistoryAction = new Action("Show History", SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_SHOWHISTORY)) { //$NON-NLS-1$
public void run() {
HistoryAction delegate = new HistoryAction();
delegate.selectionChanged(this, changePathsViewer.getSelection());
delegate.run(this);
}
};
}
showHistoryAction.setEnabled(!deleteSelected());
return showHistoryAction;
}
private IAction getExportAction() {
if(exportAction == null) {
exportAction = new Action("Export...", SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_EXPORT)) { //$NON-NLS-1$
public void run() {
ExportAction delegate = new ExportAction();
delegate.selectionChanged(this, changePathsViewer.getSelection());
delegate.run(this);
}
};
}
exportAction.setEnabled(!deleteSelected());
return exportAction;
}
private IAction getShowAnnotationAction() {
if(showAnnotationAction == null) {
showAnnotationAction = new Action("Show Annotation", SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_ANNOTATE)) { //$NON-NLS-1$
public void run() {
AnnotationAction delegate = new AnnotationAction();
delegate.selectionChanged(this, changePathsViewer.getSelection());
delegate.run(this);
}
};
}
showAnnotationAction.setEnabled(!deleteSelected());
return showAnnotationAction;
}
private IAction getCompareAction() {
if(compareAction == null) {
compareAction = new Action("Compare...") { //$NON-NLS-1$
public void run() {
CompareAction delegate = new CompareAction();
delegate.selectionChanged(this, changePathsViewer.getSelection());
delegate.run(this);
}
};
}
compareAction.setEnabled(!deleteSelected());
return compareAction;
}
private IAction getCreateTagFromRevisionChangedPathAction() {
if(createTagFromRevisionChangedPathAction == null) {
createTagFromRevisionChangedPathAction = new Action() { //$NON-NLS-1$
public void run() {
SVNRevision selectedRevision = null;
ISelection selection = changePathsViewer.getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection sel = (IStructuredSelection)selection;
ISVNRemoteResource remoteResource = null;
if (sel.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
selectedRevision = remoteResource.getRevision();
} catch (SVNException e) {}
}
else if (sel.getFirstElement() instanceof HistoryFolder) {
HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
Object[] children = historyFolder.getChildren();
if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
LogEntryChangePath changePath = (LogEntryChangePath)children[0];
try {
remoteResource = changePath.getRemoteResource().getRepository().getRemoteFolder(historyFolder.getPath());
selectedRevision = getSelectedRevision();
} catch (SVNException e) {}
}
}
if (remoteResource == null) return;
ISVNRemoteResource[] remoteResources = { remoteResource };
BranchTagWizard wizard = new BranchTagWizard(remoteResources);
wizard.setRevisionNumber(Long.parseLong(selectedRevision.toString()));
WizardDialog dialog = new ClosableWizardDialog(getSite().getShell(), wizard);
if (dialog.open() == WizardDialog.OK) {
final SVNUrl sourceUrl = wizard.getUrl();
final SVNUrl destinationUrl = wizard.getToUrl();
final String message = wizard.getComment();
final SVNRevision revision = wizard.getRevision();
final boolean makeParents = wizard.isMakeParents();
try {
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().getSVNClient();
client.copy(sourceUrl, destinationUrl, message, revision, makeParents);
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
});
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
// SvnWizardBranchTagPage branchTagPage = new SvnWizardBranchTagPage(remoteResource);
// branchTagPage.setRevisionNumber(Long.parseLong(selectedRevision.toString()));
// SvnWizard wizard = new SvnWizard(branchTagPage);
// SvnWizardDialog dialog = new SvnWizardDialog(getSite().getShell(), wizard);
// wizard.setParentDialog(dialog);
// if (!(dialog.open() == SvnWizardDialog.OK)) return;
// final SVNUrl sourceUrl = branchTagPage.getUrl();
// final SVNUrl destinationUrl = branchTagPage.getToUrl();
// final String message = branchTagPage.getComment();
// final SVNRevision revision = branchTagPage.getRevision();
// final boolean makeParents = branchTagPage.isMakeParents();
// try {
// BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
// public void run() {
// try {
// ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().createSVNClient();
// client.copy(sourceUrl, destinationUrl, message, revision, makeParents);
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
// .getMessage());
// }
// }
// });
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
// .getMessage());
// }
}
};
}
ISelection selection = changePathsViewer.getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection sel = (IStructuredSelection) selection;
SVNRevision selectedRevision = null;
if(sel.size() == 1) {
ISVNRemoteResource remoteResource = null;
if (sel.getFirstElement() instanceof LogEntryChangePath && ((LogEntryChangePath)sel.getFirstElement()).getAction() != 'D') {
try {
remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
selectedRevision = remoteResource.getRevision();
} catch (SVNException e) {}
}
else if (sel.getFirstElement() instanceof HistoryFolder) {
HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
Object[] children = historyFolder.getChildren();
if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
selectedRevision = getSelectedRevision();
}
}
createTagFromRevisionChangedPathAction.setEnabled(selectedRevision != null);
if (selectedRevision == null) {
createTagFromRevisionChangedPathAction.setText(Policy.bind("HistoryView.createTagFromRevision", ""
+ ((LogEntryChangePath)sel.getFirstElement()).getRevision()));
} else {
createTagFromRevisionChangedPathAction.setText(Policy.bind("HistoryView.createTagFromRevision", ""
+ selectedRevision));
}
}
}
createTagFromRevisionChangedPathAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_BRANCHTAG));
return createTagFromRevisionChangedPathAction;
}
class AnnotationAction extends ShowAnnotationAction {
public IStructuredSelection fSelection;
public AnnotationAction() {
super();
}
protected ISVNRemoteFile getSingleSelectedSVNRemoteFile() {
ISVNRemoteResource remoteResource = null;
if (fSelection.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)fSelection.getFirstElement()).getRemoteResource();
} catch (SVNException e) {}
}
return (ISVNRemoteFile)remoteResource;
}
protected boolean isEnabled() {
return true;
}
public void selectionChanged(IAction action, ISelection sel) {
if (sel instanceof IStructuredSelection) {
fSelection= (IStructuredSelection) sel;
}
}
}
class HistoryAction extends ShowHistoryAction {
public IStructuredSelection fSelection;
public HistoryAction() {
super();
}
protected ISVNRemoteResource[] getSelectedRemoteResources() {
ISVNRemoteResource remoteResource = null;
if (fSelection.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)fSelection.getFirstElement()).getRemoteResource();
} catch (SVNException e) {}
}
else if (fSelection.getFirstElement() instanceof HistoryFolder) {
HistoryFolder historyFolder = (HistoryFolder)fSelection.getFirstElement();
Object[] children = historyFolder.getChildren();
if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
LogEntryChangePath changePath = (LogEntryChangePath)children[0];
try {
remoteResource = changePath.getRemoteResource().getRepository().getRemoteFolder(historyFolder.getPath());
} catch (SVNException e) {}
}
}
if (remoteResource != null) {
ISVNRemoteResource[] selectedResource = { remoteResource };
return selectedResource;
}
return new ISVNRemoteResource[0];
}
protected boolean isEnabled() {
return true;
}
public void selectionChanged(IAction action, ISelection sel) {
if (sel instanceof IStructuredSelection) {
fSelection= (IStructuredSelection) sel;
}
}
}
class ExportAction extends ExportRemoteFolderAction {
public IStructuredSelection fSelection;
public ExportAction() {
super();
}
protected ISVNRemoteResource[] getSelectedRemoteResources() {
ISVNRemoteResource remoteResource = null;
if (fSelection.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)fSelection.getFirstElement()).getRemoteResource();
} catch (SVNException e) {}
}
if (remoteResource != null) {
ISVNRemoteResource[] selectedResource = { remoteResource };
return selectedResource;
}
return new ISVNRemoteResource[0];
}
protected boolean isEnabled() {
return true;
}
public void selectionChanged(IAction action, ISelection sel) {
if (sel instanceof IStructuredSelection) {
fSelection= (IStructuredSelection) sel;
}
}
}
class CompareAction extends ShowDifferencesAsUnifiedDiffAction {
public IStructuredSelection fSelection;
public CompareAction() {
super();
}
protected ISVNRemoteResource[] getSelectedRemoteResources() {
ISVNRemoteResource remoteResource = null;
if (fSelection.getFirstElement() instanceof LogEntryChangePath) {
try {
remoteResource = ((LogEntryChangePath)fSelection.getFirstElement()).getRemoteResource();
} catch (SVNException e) {}
}
else if (fSelection.getFirstElement() instanceof HistoryFolder) {
HistoryFolder historyFolder = (HistoryFolder)fSelection.getFirstElement();
Object[] children = historyFolder.getChildren();
if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
LogEntryChangePath changePath = (LogEntryChangePath)children[0];
try {
ISVNRemoteResource changePathResource = changePath.getRemoteResource();
ISVNRemoteResource remoteFolder = changePathResource.getRepository().getRemoteFolder(historyFolder.getPath());
remoteResource = new RemoteFolder(null, changePathResource.getRepository(), remoteFolder.getUrl(), changePathResource.getRevision(), (SVNRevision.Number)changePathResource.getRevision(), null, null);
} catch (SVNException e) {}
}
}
if (remoteResource != null) {
ISVNRemoteResource[] selectedResource = { remoteResource };
return selectedResource;
}
return new ISVNRemoteResource[0];
}
protected boolean isEnabled() {
return true;
}
public void selectionChanged(IAction action, ISelection sel) {
if (sel instanceof IStructuredSelection) {
fSelection= (IStructuredSelection) sel;
}
}
}
// get contents Action (context menu)
private IAction getGetContentsAction() {
if(getContentsAction == null) {
getContentsAction = getContextMenuAction(Policy.bind("HistoryView.getContentsAction"), new IWorkspaceRunnable() { //$NON-NLS-1$
public void run(IProgressMonitor monitor) throws CoreException {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection ss = (IStructuredSelection) selection;
ISVNRemoteFile remoteFile = (ISVNRemoteFile) getLogEntry(ss).getRemoteResource();
monitor.beginTask(null, 100);
try {
if(remoteFile != null) {
if(confirmOverwrite()) {
InputStream in = ((IResourceVariant) remoteFile).getStorage(new SubProgressMonitor(monitor, 50))
.getContents();
IFile file = (IFile) resource;
file.setContents(in, false, true, new SubProgressMonitor(monitor, 50));
}
}
} catch(TeamException e) {
throw new CoreException(e.getStatus());
} finally {
monitor.done();
}
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(getContentsAction, IHelpContextIds.GET_FILE_CONTENTS_ACTION);
}
return getContentsAction;
}
// update to the selected revision (context menu)
private IAction getUpdateToRevisionAction() {
if(updateToRevisionAction == null) {
updateToRevisionAction = getContextMenuAction(
Policy.bind("HistoryView.getRevisionAction"), new IWorkspaceRunnable() { //$NON-NLS-1$
public void run(IProgressMonitor monitor) throws CoreException {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection ss = (IStructuredSelection) selection;
ISVNRemoteFile remoteFile = (ISVNRemoteFile) getLogEntry(ss).getRemoteResource();
try {
if(remoteFile != null) {
if(confirmOverwrite()) {
IFile file = (IFile) resource;
new ReplaceOperation(getSite().getPage().getActivePart(), file, remoteFile.getLastChangedRevision())
.run(monitor);
historyTableProvider.setRemoteResource(remoteFile);
historyTableProvider.setProjectProperties(ProjectProperties.getProjectProperties(resource));
Display.getDefault().asyncExec(new Runnable() {
public void run() {
tableHistoryViewer.refresh();
}
});
}
}
} catch(InvocationTargetException e) {
throw new CoreException(new SVNStatus(IStatus.ERROR, 0, e.getMessage()));
} catch(InterruptedException e) {
// Cancelled by user
}
}
});
PlatformUI.getWorkbench().getHelpSystem().setHelp(updateToRevisionAction,
IHelpContextIds.GET_FILE_REVISION_ACTION);
}
return updateToRevisionAction;
}
// private IAction getRevertChangesChangedPathAction() {
// if(revertChangesChangedPathAction == null) {
// revertChangesChangedPathAction = new Action() {
// public void run() {
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// if (sel.size() == 1) {
// String resourcePath = null;
// if (sel.getFirstElement() instanceof LogEntryChangePath)
// resourcePath = ((LogEntryChangePath)sel.getFirstElement()).getPath();
// else if (sel.getFirstElement() instanceof HistoryFolder)
// resourcePath = ((HistoryFolder)sel.getFirstElement()).getPath();
// if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
// "HistoryView.confirmRevertChangedPathRevision", resourcePath))) return;
// } else {
// if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
// "HistoryView.confirmRevertChangedPathsRevision"))) return;
// }
// BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
// public void run() {
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// SVNRevision selectedRevision = null;
// ISVNRemoteResource remoteResource = null;
// if (sel.getFirstElement() instanceof LogEntryChangePath) {
// try {
// remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
// selectedRevision = remoteResource.getRevision();
// } catch (SVNException e) {}
// }
// else if (sel.getFirstElement() instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// selectedRevision = getSelectedRevision();
// }
// }
// final SVNRevision revision1 = selectedRevision;
// final SVNRevision revision2 = new SVNRevision.Number(((SVNRevision.Number)selectedRevision).getNumber() - 1);
// Iterator iter = sel.iterator();
// while (iter.hasNext()) {
// remoteResource = null;
// IResource selectedResource = null;
// Object selectedItem = iter.next();
// if (selectedItem instanceof LogEntryChangePath) {
// try {
// LogEntryChangePath changePath = (LogEntryChangePath)selectedItem;
// remoteResource = changePath.getRemoteResource();
// if (remoteResource.isFolder()) selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(changePath.getPath()));
// else selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(changePath.getPath()));
// } catch (SVNException e) {}
// }
// else if (selectedItem instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)selectedItem;
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// LogEntryChangePath changePath = (LogEntryChangePath)children[0];
// try {
// remoteResource = changePath.getRemoteResource().getRepository().getRemoteFolder(historyFolder.getPath());
// if (selectedRevision == null) selectedRevision = getSelectedRevision();
// if (remoteResource.isFolder()) selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(historyFolder.getPath()));
// else selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(historyFolder.getPath()));
// } catch (SVNException e) {}
// }
// }
// final SVNUrl path1 = remoteResource.getUrl();
// final SVNUrl path2 = path1;
// final IResource[] resources = { selectedResource };
// try {
// WorkspaceAction mergeAction = new WorkspaceAction() {
// protected void execute(IAction action) throws InvocationTargetException, InterruptedException {
// new MergeOperation(getSite().getPage().getActivePart(), resources, path1, revision1, path2,
// revision2).run();
// }
// };
// mergeAction.run(null);
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), revertChangesAction.getText(), e.getMessage());
// }
// }
// }
// });
// }
// };
// }
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// SVNRevision selectedRevision = null;
// ISVNRemoteResource remoteResource = null;
// if (sel.getFirstElement() instanceof LogEntryChangePath) {
// try {
// remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
// selectedRevision = remoteResource.getRevision();
// } catch (SVNException e) {}
// }
// else if (sel.getFirstElement() instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// selectedRevision = getSelectedRevision();
// }
// }
// revertChangesChangedPathAction.setText(Policy.bind("HistoryView.revertChangesFromRevision", ""
// + selectedRevision));
// revertChangesChangedPathAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_MARKMERGED));
// return revertChangesChangedPathAction;
// }
// private IAction getSwitchChangedPathAction() {
// if (switchChangedPathAction == null) {
// switchChangedPathAction = new Action() {
// public void run() {
// SVNRevision selectedRevision = null;
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// ArrayList selectedResources = new ArrayList();
// Iterator iter = sel.iterator();
// while (iter.hasNext()) {
// ISVNRemoteResource remoteResource = null;
// IResource selectedResource = null;
// Object selectedItem = iter.next();
// if (selectedItem instanceof LogEntryChangePath) {
// try {
// LogEntryChangePath changePath = (LogEntryChangePath)selectedItem;
// remoteResource = changePath.getRemoteResource();
// if (remoteResource.isFolder()) selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(changePath.getPath()));
// else selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(changePath.getPath()));
// selectedResources.add(selectedResource);
// if (selectedRevision == null) selectedRevision = remoteResource.getRevision();
// } catch (SVNException e) {}
// }
// else if (selectedItem instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)selectedItem;
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// LogEntryChangePath changePath = (LogEntryChangePath)children[0];
// try {
// remoteResource = changePath.getRemoteResource().getRepository().getRemoteFolder(historyFolder.getPath());
// if (selectedRevision == null) selectedRevision = getSelectedRevision();
// if (remoteResource.isFolder()) selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(historyFolder.getPath()));
// else selectedResource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(historyFolder.getPath()));
// selectedResources.add(selectedResource);
// } catch (SVNException e) {}
// }
// }
// }
// IResource[] resources = new IResource[selectedResources.size()];
// selectedResources.toArray(resources);
// SvnWizardSwitchPage switchPage = new SvnWizardSwitchPage(resources, Long.parseLong(selectedRevision.toString()));
// SvnWizard wizard = new SvnWizard(switchPage);
// SvnWizardDialog dialog = new SvnWizardDialog(getSite().getShell(), wizard);
// wizard.setParentDialog(dialog);
// if (dialog.open() == SvnWizardDialog.OK) {
// SVNUrl[] svnUrls = switchPage.getUrls();
// SVNRevision svnRevision = switchPage.getRevision();
// SwitchOperation switchOperation = new SwitchOperation(getSite().getPage().getActivePart(), resources, svnUrls, svnRevision);
// switchOperation.setDepth(switchPage.getDepth());
// switchOperation.setIgnoreExternals(switchPage.isIgnoreExternals());
// switchOperation.setForce(switchPage.isForce());
// try {
// switchOperation.run();
// } catch (Exception e) {
// MessageDialog.openError(getSite().getShell(), switchAction.getText(), e
// .getMessage());
// }
// }
// }
// };
// }
// IStructuredSelection sel = (IStructuredSelection)changePathsViewer.getSelection();
// SVNRevision selectedRevision = null;
// ISVNRemoteResource remoteResource = null;
// if (sel.getFirstElement() instanceof LogEntryChangePath) {
// try {
// remoteResource = ((LogEntryChangePath)sel.getFirstElement()).getRemoteResource();
// selectedRevision = remoteResource.getRevision();
// } catch (SVNException e) {}
// }
// else if (sel.getFirstElement() instanceof HistoryFolder) {
// HistoryFolder historyFolder = (HistoryFolder)sel.getFirstElement();
// Object[] children = historyFolder.getChildren();
// if (children != null && children.length > 0 && children[0] instanceof LogEntryChangePath) {
// selectedRevision = getSelectedRevision();
// }
// }
// switchChangedPathAction.setText(Policy.bind("HistoryView.switchToRevision", ""
// + selectedRevision));
// switchChangedPathAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_SWITCH));
// return switchChangedPathAction;
// }
// get switch action (context menu)
private IAction getSwitchAction() {
if (switchAction == null) {
switchAction = new Action() {
public void run() {
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
ILogEntry currentSelection = getLogEntry(ss);
IResource[] resources = { resource };
SvnWizardSwitchPage switchPage = new SvnWizardSwitchPage(resources, currentSelection.getRevision().getNumber());
SvnWizard wizard = new SvnWizard(switchPage);
SvnWizardDialog dialog = new SvnWizardDialog(getSite().getShell(), wizard);
wizard.setParentDialog(dialog);
if (dialog.open() == SvnWizardDialog.OK) {
SVNUrl[] svnUrls = switchPage.getUrls();
SVNRevision svnRevision = switchPage.getRevision();
SwitchOperation switchOperation = new SwitchOperation(getSite().getPage().getActivePart(), resources, svnUrls, svnRevision);
switchOperation.setDepth(switchPage.getDepth());
switchOperation.setSetDepth(switchPage.isSetDepth());
switchOperation.setIgnoreExternals(switchPage.isIgnoreExternals());
switchOperation.setForce(switchPage.isForce());
try {
switchOperation.run();
} catch (Exception e) {
MessageDialog.openError(getSite().getShell(), switchAction.getText(), e
.getMessage());
}
}
}
}
}
};
}
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
ILogEntry currentSelection = getLogEntry(ss);
switchAction.setText(Policy.bind("HistoryView.switchToRevision", ""
+ currentSelection.getRevision().getNumber()));
}
}
switchAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_SWITCH));
return switchAction;
}
// get create tag from revision action (context menu)
private IAction getCreateTagFromRevisionAction() {
if(createTagFromRevisionAction == null) {
createTagFromRevisionAction = new Action() {
public void run() {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
ILogEntry currentSelection = getLogEntry((IStructuredSelection) selection);
BranchTagWizard wizard;
if (resource == null) {
ISVNRemoteResource[] remoteResources = { historyTableProvider.getRemoteResource() };
wizard = new BranchTagWizard(remoteResources);
} else {
IResource[] resources = { resource };
wizard = new BranchTagWizard(resources);
}
wizard.setRevisionNumber(currentSelection.getRevision().getNumber());
WizardDialog dialog = new ClosableWizardDialog(getSite().getShell(), wizard);
if (dialog.open() == WizardDialog.OK) {
final SVNUrl sourceUrl =wizard.getUrl();
final SVNUrl destinationUrl = wizard.getToUrl();
final String message = wizard.getComment();
final SVNRevision revision = wizard.getRevision();
final boolean makeParents = wizard.isMakeParents();
boolean createOnServer = wizard.isCreateOnServer();
IResource[] resources = { resource };
try {
if(resource == null) {
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().getSVNClient();
client.copy(sourceUrl, destinationUrl, message, revision, makeParents);
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
});
} else {
BranchTagOperation branchTagOperation = new BranchTagOperation(getSite().getPage().getActivePart(), resources, new SVNUrl[] { sourceUrl }, destinationUrl,
createOnServer, wizard.getRevision(), message);
branchTagOperation.setMakeParents(makeParents);
branchTagOperation.setNewAlias(wizard.getNewAlias());
branchTagOperation.run();
}
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
.getMessage());
}
}
// SvnWizardBranchTagPage branchTagPage;
// if (resource == null)
// branchTagPage = new SvnWizardBranchTagPage(historyTableProvider.getRemoteResource());
// else
// branchTagPage = new SvnWizardBranchTagPage(resource);
// branchTagPage.setRevisionNumber(currentSelection.getRevision().getNumber());
// SvnWizard wizard = new SvnWizard(branchTagPage);
// SvnWizardDialog dialog = new SvnWizardDialog(getSite().getShell(), wizard);
// wizard.setParentDialog(dialog);
// if (!(dialog.open() == SvnWizardDialog.OK)) return;
// final SVNUrl sourceUrl = branchTagPage.getUrl();
// final SVNUrl destinationUrl = branchTagPage.getToUrl();
// final String message = branchTagPage.getComment();
// final SVNRevision revision = branchTagPage.getRevision();
// final boolean makeParents = branchTagPage.isMakeParents();
// boolean createOnServer = branchTagPage.isCreateOnServer();
// IResource[] resources = { resource};
// try {
// if(resource == null) {
// BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
// public void run() {
// try {
// ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().createSVNClient();
// client.copy(sourceUrl, destinationUrl, message, revision, makeParents);
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
// .getMessage());
// }
// }
// });
// } else {
// BranchTagOperation branchTagOperation = new BranchTagOperation(getSite().getPage().getActivePart(), resources, sourceUrl, destinationUrl,
// createOnServer, branchTagPage.getRevision(), message);
// branchTagOperation.setMakeParents(makeParents);
// branchTagOperation.run();
// }
// } catch(Exception e) {
// MessageDialog.openError(getSite().getShell(), Policy.bind("HistoryView.createTagFromRevision"), e
// .getMessage());
// }
}
};
}
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
ILogEntry currentSelection = getLogEntry(ss);
createTagFromRevisionAction.setText(Policy.bind("HistoryView.createTagFromRevision", ""
+ currentSelection.getRevision().getNumber()));
}
}
createTagFromRevisionAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_BRANCHTAG));
return createTagFromRevisionAction;
}
private IAction getSetCommitPropertiesAction() {
// set Action (context menu)
if(setCommitPropertiesAction == null) {
setCommitPropertiesAction = new Action(Policy.bind("HistoryView.setCommitProperties")) {
public void run() {
try {
final ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
final ILogEntry ourSelection = getLogEntry((IStructuredSelection) selection);
// Failing that, try the resource originally selected by the user if
// from the Team menu
// TODO: Search all paths from currentSelection and find the
// shortest path and
// get the resources for that instance (in order to get the 'best'
// "bugtraq" properties)
final ProjectProperties projectProperties = (resource != null) ? ProjectProperties
.getProjectProperties(resource) : ProjectProperties.getProjectProperties(ourSelection
.getRemoteResource()); // will return null!
final ISVNResource svnResource = ourSelection.getRemoteResource() != null ? ourSelection
.getRemoteResource() : ourSelection.getResource();
SetCommitPropertiesDialog dialog = new SetCommitPropertiesDialog(getSite().getShell(), ourSelection
.getRevision(), resource, projectProperties);
// Set previous text - the text to edit
dialog.setOldAuthor(ourSelection.getAuthor());
dialog.setOldComment(ourSelection.getComment());
boolean doCommit = (dialog.open() == Window.OK);
if(doCommit) {
final String author;
final String commitComment;
if(ourSelection.getAuthor().equals(dialog.getAuthor()))
author = null;
else
author = dialog.getAuthor();
if(ourSelection.getComment().equals(dialog.getComment()))
commitComment = null;
else
commitComment = dialog.getComment();
final ChangeCommitPropertiesCommand command = new ChangeCommitPropertiesCommand(svnResource
.getRepository(), ourSelection.getRevision(), commitComment, author);
PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
command.run(monitor);
} catch(SVNException e) {
throw new InvocationTargetException(e);
} finally {
if(ourSelection instanceof LogEntry) {
LogEntry logEntry = (LogEntry) ourSelection;
if (command.isLogMessageChanged()) logEntry.setComment(commitComment);
if (command.isAuthorChanged()) logEntry.setAuthor(author);
}
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
tableHistoryViewer.refresh();
tableHistoryViewer.setSelection(selection, true);
}
});
}
}
});
}
} catch(InvocationTargetException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e, SVNUIPlugin.LOG_NONTEAM_EXCEPTIONS);
} catch(InterruptedException e) {
// Do nothing
} catch(SVNException e) {
// TODO Auto-generated catch block
SVNUIPlugin.openError(getSite().getShell(), null, null, e, SVNUIPlugin.LOG_TEAM_EXCEPTIONS);
}
}
// we don't allow multiple selection
public boolean isEnabled() {
ISelection selection = getSelection();
return selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() == 1;
}
};
}
return setCommitPropertiesAction;
}
private IAction getShowRevisionsAction() {
if (showRevisionsAction == null) {
showRevisionsAction = new Action(Policy.bind("HistoryView.showMergedRevisions")) {
public void run() {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
IStructuredSelection ss = (IStructuredSelection) selection;
ILogEntry logEntry = (ILogEntry)ss.getFirstElement();
ShowRevisionsDialog dialog = null;
if (resource != null) dialog = new ShowRevisionsDialog(getSite().getShell(), logEntry, resource, includeTags, SVNHistoryPage.this);
else if (remoteResource != null) dialog = new ShowRevisionsDialog(getSite().getShell(), logEntry, remoteResource, includeTags, SVNHistoryPage.this);
if (dialog != null) dialog.open();
}
};
}
return showRevisionsAction;
}
// get revert changes action (context menu)
private IAction getRevertChangesAction() {
if(revertChangesAction == null) {
revertChangesAction = new Action() {
public void run() {
ISelection selection = getSelection();
if( !(selection instanceof IStructuredSelection))
return;
final IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
"HistoryView.confirmRevertRevision", resource.getFullPath().toString())))
return;
} else {
if( !MessageDialog.openConfirm(getSite().getShell(), getText(), Policy.bind(
"HistoryView.confirmRevertRevisions", resource.getFullPath().toString())))
return;
}
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
ILogEntry firstElement = getFirstElement();
ILogEntry lastElement = getLastElement();
final SVNUrl path1 = firstElement.getResource().getUrl();
final SVNRevision revision1 = firstElement.getRevision();
final SVNUrl path2 = lastElement.getResource().getUrl();
final SVNRevision revision2 = new SVNRevision.Number(lastElement.getRevision().getNumber() - 1);
final IResource[] resources = { resource};
try {
WorkspaceAction mergeAction = new WorkspaceAction() {
protected void execute(IAction action) throws InvocationTargetException, InterruptedException {
new MergeOperation(getSite().getPage().getActivePart(), resources, path1, revision1, path2,
revision2).run();
}
};
mergeAction.run(null);
} catch(Exception e) {
MessageDialog.openError(getSite().getShell(), revertChangesAction.getText(), e.getMessage());
}
}
});
}
};
}
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if(ss.size() == 1) {
ILogEntry currentSelection = getLogEntry(ss);
revertChangesAction.setText(Policy.bind("HistoryView.revertChangesFromRevision", ""
+ currentSelection.getRevision().getNumber()));
}
if(ss.size() > 1) {
ILogEntry firstElement = getFirstElement();
ILogEntry lastElement = getLastElement();
revertChangesAction.setText(Policy.bind("HistoryView.revertChangesFromRevisions", ""
+ lastElement.getRevision().getNumber(), "" + firstElement.getRevision().getNumber()));
}
}
revertChangesAction.setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_MENU_MARKMERGED));
return revertChangesAction;
}
private GenerateChangeLogAction getGenerateChangeLogAction() {
if (generateChangeLogAction == null) generateChangeLogAction = new GenerateChangeLogAction(new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
}
public ISelection getSelection() {
return SVNHistoryPage.this.getSelection();
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
}
public void setSelection(ISelection selection) {
}
});
return generateChangeLogAction;
}
// Refresh action (toolbar)
private IAction getRefreshAction() {
if(refreshAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
refreshAction = new Action(
Policy.bind("HistoryView.refreshLabel"), plugin.getImageDescriptor(ISVNUIConstants.IMG_REFRESH_ENABLED)) { //$NON-NLS-1$
public void run() {
refresh();
}
};
refreshAction.setToolTipText(Policy.bind("HistoryView.refresh")); //$NON-NLS-1$
refreshAction.setDisabledImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_REFRESH_DISABLED));
refreshAction.setHoverImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_REFRESH));
}
return refreshAction;
}
// Search action (toolbar)
private IAction getSearchAction() {
if (searchAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
searchAction = new Action(
Policy.bind("HistoryView.search"), plugin.getImageDescriptor(ISVNUIConstants.IMG_FILTER_HISTORY)) { //$NON-NLS-1$
public void run() {
if (historySearchDialog == null) {
historySearchDialog = new HistorySearchDialog(getSite().getShell(), remoteResource);
}
historySearchDialog.setRemoteResource(remoteResource);
if (historySearchDialog.open() == Window.OK) {
searchAction.setEnabled(false);
Utils.schedule(new SearchHistoryJob(), SVNUIPlugin.getPlugin().getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActivePart().getSite());
}
}
};
searchAction.setDisabledImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_FILTER_HISTORY_DISABLED));
}
return searchAction;
}
// Clear search action (toolbar)
private IAction getClearSearchAction() {
if (clearSearchAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
clearSearchAction = new Action(
Policy.bind("HistoryView.clearSearch"), plugin.getImageDescriptor(ISVNUIConstants.IMG_CLEAR)) { //$NON-NLS-1$
public void run() {
BusyIndicator.showWhile(tableHistoryViewer.getTable().getDisplay(), new Runnable() {
public void run() {
ViewerFilter[] filters = tableHistoryViewer.getFilters();
for (int i=0; i<filters.length; i++) {
ViewerFilter filter = filters[i];
if (filter instanceof HistorySearchViewerFilter) {
tableHistoryViewer.removeFilter(filter);
}
else if (filter instanceof EmptySearchViewerFilter) {
tableHistoryViewer.removeFilter(filter);
}
}
setEnabled(false);
if (!historySearchDialog.getSearchAllLogs() && (historySearchDialog.getStartRevision() != null || historySearchDialog.getEndRevision() != null)) {
getRefreshAction().run();
}
}
});
}
};
clearSearchAction.setDisabledImageDescriptor(plugin.getImageDescriptor(ISVNUIConstants.IMG_CLEAR_DISABLED));
}
return clearSearchAction;
}
// Get Get All action (toolbar)
private IAction getGetAllAction() {
if(getAllAction == null) {
SVNUIPlugin plugin = SVNUIPlugin.getPlugin();
getAllAction = new Action(
Policy.bind("HistoryView.getAll"), plugin.getImageDescriptor(ISVNUIConstants.IMG_GET_ALL)) { //$NON-NLS-1$
public void run() {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchAllLogEntriesJob == null) {
fetchAllLogEntriesJob = new FetchAllLogEntriesJob();
}
if(fetchAllLogEntriesJob.getState() != Job.NONE) {
fetchAllLogEntriesJob.cancel();
try {
fetchAllLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(Policy
.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchAllLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchAllLogEntriesJob, getSite());
}
};
getAllAction.setToolTipText(Policy.bind("HistoryView.getAll")); //$NON-NLS-1$
}
return getAllAction;
}
// Get Get Next action (toolbar)
public IAction getGetNextAction() {
if(getNextAction == null) {
getNextAction = new GetNextAction();
}
return getNextAction;
}
/**
* All context menu actions use this class This action : - updates
* currentSelection - action.run
*/
private Action getContextMenuAction(String title, final IWorkspaceRunnable action) {
return new Action(title) {
public void run() {
try {
if(resource == null)
return;
PlatformUI.getWorkbench().getProgressService().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
action.run(monitor);
} catch(CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch(InvocationTargetException e) {
SVNUIPlugin.openError(getSite().getShell(), null, null, e, SVNUIPlugin.LOG_NONTEAM_EXCEPTIONS);
} catch(InterruptedException e) {
// Do nothing
}
}
// we don't allow multiple selection
public boolean isEnabled() {
ISelection selection = getSelection();
return selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() == 1;
}
};
}
/**
* Ask the user to confirm the overwrite of the file if the file has been
* modified since last commit
*/
private boolean confirmOverwrite() {
IFile file = (IFile) resource;
if(file != null && file.exists()) {
ISVNLocalFile svnFile = SVNWorkspaceRoot.getSVNFileFor(file);
try {
if(svnFile.isDirty()) {
String title = Policy.bind("HistoryView.overwriteTitle"); //$NON-NLS-1$
String msg = Policy.bind("HistoryView.overwriteMsg"); //$NON-NLS-1$
final MessageDialog dialog = new MessageDialog(getSite().getShell(), title, null, msg,
MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.CANCEL_LABEL}, 0);
final int[] result = new int[ 1];
getSite().getShell().getDisplay().syncExec(new Runnable() {
public void run() {
result[ 0] = dialog.open();
}
});
if(result[ 0] != 0) {
// cancel
return false;
}
}
} catch(SVNException e) {
SVNUIPlugin.log(e.getStatus());
}
}
return true;
}
private ISelection getSelection() {
return selection;
}
private ILogEntry getFirstElement() {
ILogEntry firstElement = null;
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
Iterator iter = ss.iterator();
while(iter.hasNext()) {
ILogEntry element = (ILogEntry) iter.next();
if(firstElement == null || element.getRevision().getNumber() > firstElement.getRevision().getNumber())
firstElement = element;
}
}
return firstElement;
}
private ILogEntry getLastElement() {
ILogEntry lastElement = null;
ISelection selection = getSelection();
if(selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
Iterator iter = ss.iterator();
while(iter.hasNext()) {
ILogEntry element = (ILogEntry) iter.next();
if(lastElement == null || element.getRevision().getNumber() < lastElement.getRevision().getNumber())
lastElement = element;
}
}
return lastElement;
}
private final class GetNextAction extends Action implements IPropertyChangeListener {
GetNextAction() {
super(Policy.bind("HistoryView.getNext"), SVNUIPlugin.getPlugin().getImageDescriptor(ISVNUIConstants.IMG_GET_NEXT));
updateFromProperties();
SVNUIPlugin.getPlugin().getPreferenceStore().addPropertyChangeListener(this);
}
public void run() {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchNextLogEntriesJob == null) {
fetchNextLogEntriesJob = new FetchNextLogEntriesJob();
}
if(fetchNextLogEntriesJob.getState() != Job.NONE) {
fetchNextLogEntriesJob.cancel();
try {
fetchNextLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(Policy
.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
}
fetchNextLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchNextLogEntriesJob, getSite());
}
public void propertyChange(PropertyChangeEvent event) {
if(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH.equals(event.getProperty())) {
updateFromProperties();
}
}
private void updateFromProperties() {
int entriesToFetch = SVNUIPlugin.getPlugin().getPreferenceStore().getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
setToolTipText(Policy.bind("HistoryView.getNext") + " " + entriesToFetch); //$NON-NLS-1$
if(entriesToFetch <= 0) {
setEnabled(false);
}
}
}
private class FetchLogEntriesJob extends AbstractFetchJob {
public ISVNRemoteResource remoteResource;
public FetchLogEntriesJob() {
super(Policy.bind("HistoryView.fetchHistoryJob")); //$NON-NLS-1$;
}
public void setRemoteFile(ISVNRemoteResource resource) {
this.remoteResource = resource;
}
public IStatus run(IProgressMonitor monitor) {
try {
if(remoteResource != null && !shutdown) {
if(resource == null) {
if(remoteResource == null
|| !SVNUIPlugin.getPlugin().getPreferenceStore().getBoolean(ISVNUIConstants.PREF_SHOW_TAGS_IN_REMOTE)) {
tagManager = null;
} else {
tagManager = new AliasManager(remoteResource.getUrl());
}
} else {
tagManager = new AliasManager(resource);
}
SVNRevision pegRevision = remoteResource.getRevision();
SVNRevision revisionEnd = new SVNRevision.Number(0);
boolean stopOnCopy = toggleStopOnCopyAction.isChecked();
boolean includeMergedRevisions = toggleIncludeMergedRevisionsAction.isChecked();
int entriesToFetch = store.getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
long limit = entriesToFetch;
entries = getLogEntries(monitor, remoteResource, pegRevision, revisionStart, revisionEnd, stopOnCopy,
limit + 1, tagManager, includeMergedRevisions);
long entriesLength = entries.length;
if(entriesLength > limit) {
ILogEntry[] fetchedEntries = new ILogEntry[ entries.length - 1];
for(int i = 0; i < entries.length - 1; i++) {
fetchedEntries[ i] = entries[ i];
}
entries = fetchedEntries;
getNextAction.setEnabled(true);
} else {
getNextAction.setEnabled(false);
}
final SVNRevision.Number revisionId = remoteResource.getLastChangedRevision();
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(entries != null && tableHistoryViewer != null && !tableHistoryViewer.getTable().isDisposed()) {
// once we got the entries, we refresh the table
if(entries.length > 0) {
lastEntry = entries[ entries.length - 1];
long lastEntryNumber = lastEntry.getRevision().getNumber();
revisionStart = new SVNRevision.Number(lastEntryNumber - 1);
}
tableHistoryViewer.refresh();
selectRevision(revisionId);
}
}
});
}
return Status.OK_STATUS;
} catch(TeamException e) {
return e.getStatus();
}
}
}
private class FetchNextLogEntriesJob extends AbstractFetchJob {
public ISVNRemoteResource remoteResource;
public FetchNextLogEntriesJob() {
super(Policy.bind("HistoryView.fetchHistoryJob")); //$NON-NLS-1$;
}
public void setRemoteFile(ISVNRemoteResource resource) {
this.remoteResource = resource;
}
public IStatus run(IProgressMonitor monitor) {
try {
if(remoteResource != null && !shutdown) {
SVNRevision pegRevision = remoteResource.getRevision();
SVNRevision revisionEnd = new SVNRevision.Number(0);
boolean stopOnCopy = toggleStopOnCopyAction.isChecked();
boolean includeMergedRevisions = toggleIncludeMergedRevisionsAction.isChecked();
int entriesToFetch = store.getInt(ISVNUIConstants.PREF_LOG_ENTRIES_TO_FETCH);
long limit = entriesToFetch;
ILogEntry[] nextEntries = getLogEntries(monitor, remoteResource, pegRevision, revisionStart, revisionEnd,
stopOnCopy, limit + 1, tagManager, includeMergedRevisions);
long entriesLength = nextEntries.length;
ILogEntry[] fetchedEntries = null;
if(entriesLength > limit) {
fetchedEntries = new ILogEntry[ nextEntries.length - 1];
for(int i = 0; i < nextEntries.length - 1; i++)
fetchedEntries[ i] = nextEntries[ i];
getNextAction.setEnabled(true);
} else {
fetchedEntries = new ILogEntry[ nextEntries.length];
for(int i = 0; i < nextEntries.length; i++)
fetchedEntries[ i] = nextEntries[ i];
getNextAction.setEnabled(false);
}
ArrayList entryArray = new ArrayList();
if(entries == null)
entries = new ILogEntry[ 0];
for(int i = 0; i < entries.length; i++)
entryArray.add(entries[ i]);
for(int i = 0; i < fetchedEntries.length; i++)
entryArray.add(fetchedEntries[ i]);
entries = new ILogEntry[ entryArray.size()];
entryArray.toArray(entries);
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(entries != null && tableHistoryViewer != null && !tableHistoryViewer.getTable().isDisposed()) {
// once we got the entries, we refresh the table
ISelection selection = tableHistoryViewer.getSelection();
tableHistoryViewer.refresh();
tableHistoryViewer.setSelection(selection);
}
}
});
if(entries.length > 0) {
lastEntry = entries[ entries.length - 1];
long lastEntryNumber = lastEntry.getRevision().getNumber();
revisionStart = new SVNRevision.Number(lastEntryNumber - 1);
}
}
return Status.OK_STATUS;
} catch(TeamException e) {
return e.getStatus();
}
}
}
private abstract class AbstractFetchJob extends Job {
public AbstractFetchJob(String name) {
super(name);
}
public abstract void setRemoteFile(ISVNRemoteResource resource);
protected ILogEntry[] getLogEntries(IProgressMonitor monitor, ISVNRemoteResource remoteResource, SVNRevision pegRevision, SVNRevision revisionStart, SVNRevision revisionEnd, boolean stopOnCopy, long limit, AliasManager tagManager, boolean includeMergedRevisions) throws TeamException
{
// If filtering by revision range, pass upper/lower revisions to API and override limit.
SVNRevision start = revisionStart;
SVNRevision end = revisionEnd;
long fetchLimit = limit;
if (historySearchDialog != null && !historySearchDialog.getSearchAllLogs()) {
if (historySearchDialog.getStartRevision() != null || historySearchDialog.getEndRevision() != null) {
if (getClearSearchAction().isEnabled()) {
if (historySearchDialog.getStartRevision() != null) end = historySearchDialog.getStartRevision();
if (historySearchDialog.getEndRevision() != null) start = historySearchDialog.getEndRevision();
fetchLimit = 0;
getGetNextAction().setEnabled(false);
}
}
}
GetLogsCommand logCmd = new GetLogsCommand(remoteResource, pegRevision, start, end, stopOnCopy, fetchLimit, tagManager, includeMergedRevisions);
logCmd.run(monitor);
return logCmd.getLogEntries();
}
}
private class FetchAllLogEntriesJob extends AbstractFetchJob {
public ISVNRemoteResource remoteResource;
public FetchAllLogEntriesJob() {
super(Policy.bind("HistoryView.fetchHistoryJob")); //$NON-NLS-1$;
}
public void setRemoteFile(ISVNRemoteResource resource) {
this.remoteResource = resource;
}
public IStatus run(IProgressMonitor monitor) {
try {
if(remoteResource != null && !shutdown) {
if(resource == null) {
if(remoteResource == null
|| !SVNUIPlugin.getPlugin().getPreferenceStore().getBoolean(ISVNUIConstants.PREF_SHOW_TAGS_IN_REMOTE))
tagManager = null;
else
tagManager = new AliasManager(remoteResource.getUrl());
} else
tagManager = new AliasManager(resource);
SVNRevision pegRevision = remoteResource.getRevision();
revisionStart = SVNRevision.HEAD;
SVNRevision revisionEnd = new SVNRevision.Number(0);
boolean stopOnCopy = toggleStopOnCopyAction.isChecked();
boolean includeMergedRevisions = toggleIncludeMergedRevisionsAction.isChecked();
long limit = 0;
entries = getLogEntries(monitor, remoteResource, pegRevision, revisionStart, revisionEnd, stopOnCopy, limit,
tagManager, includeMergedRevisions);
final SVNRevision.Number revisionId = remoteResource.getLastChangedRevision();
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
if(entries != null && tableHistoryViewer != null && !tableHistoryViewer.getTable().isDisposed()) {
// once we got the entries, we refresh the table
if(entries.length > 0) {
lastEntry = entries[ entries.length - 1];
long lastEntryNumber = lastEntry.getRevision().getNumber();
revisionStart = new SVNRevision.Number(lastEntryNumber - 1);
}
tableHistoryViewer.refresh();
selectRevision(revisionId);
}
}
});
}
return Status.OK_STATUS;
} catch(TeamException e) {
return e.getStatus();
}
}
}
private class SearchHistoryJob extends Job {
public SearchHistoryJob() {
super(Policy.bind("HistoryView.searchHistoryJob")); //$NON-NLS-1$
}
public IStatus run(IProgressMonitor monitor) {
if (!historySearchDialog.getSearchAllLogs() && (historySearchDialog.getStartRevision() != null || historySearchDialog.getEndRevision() != null)) {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchAllLogEntriesJob == null) {
fetchAllLogEntriesJob = new FetchAllLogEntriesJob();
}
if(fetchAllLogEntriesJob.getState() != Job.NONE) {
fetchAllLogEntriesJob.cancel();
}
fetchAllLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchAllLogEntriesJob, getSite());
} else {
Date startDate = historySearchDialog.getStartDate();
setEmptyViewerFilter();
// Fetch log entries until start date
if (historySearchDialog.getAutoFetchLogs()) {
if (!historySearchDialog.getSearchAllLogs()) {
Date lastDate = null;
if (lastEntry != null) {
lastDate = lastEntry.getDate();
}
int numEntries = entries.length;
int prevNumEntries = -1;
while ((numEntries != prevNumEntries) &&
((lastDate == null) ||
(startDate == null) ||
(startDate.compareTo(lastDate) <= 0))) {
if (monitor.isCanceled()) {
getSearchAction().setEnabled(true);
removeEmptyViewerFilter();
return Status.CANCEL_STATUS;
}
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchNextLogEntriesJob == null) {
fetchNextLogEntriesJob = new FetchNextLogEntriesJob();
}
if(fetchNextLogEntriesJob.getState() != Job.NONE) {
fetchNextLogEntriesJob.cancel();
}
fetchNextLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchNextLogEntriesJob, getSite());
try {
fetchNextLogEntriesJob.join();
} catch(InterruptedException e) {
SVNUIPlugin.log(new SVNException(
Policy.bind("HistoryView.errorFetchingEntries", remoteResource.getName()), e)); //$NON-NLS-1$
}
if (entries.length == 0) {
break;
}
lastDate = lastEntry.getDate();
prevNumEntries = numEntries;
numEntries = entries.length;
}
}
else {
final ISVNRemoteResource remoteResource = historyTableProvider.getRemoteResource();
if(fetchAllLogEntriesJob == null) {
fetchAllLogEntriesJob = new FetchAllLogEntriesJob();
}
if(fetchAllLogEntriesJob.getState() != Job.NONE) {
fetchAllLogEntriesJob.cancel();
}
fetchAllLogEntriesJob.setRemoteFile(remoteResource);
Utils.schedule(fetchAllLogEntriesJob, getSite());
}
}
}
final HistorySearchViewerFilter viewerFilter = new HistorySearchViewerFilter(
historySearchDialog.getUser(),
historySearchDialog.getComment(),
historySearchDialog.getStartDate(),
historySearchDialog.getEndDate(),
historySearchDialog.getRegExp(),
historySearchDialog.getStartRevision(),
historySearchDialog.getEndRevision());
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
BusyIndicator.showWhile(tableHistoryViewer.getTable().getDisplay(), new Runnable() {
public void run() {
getClearSearchAction().run();
tableHistoryViewer.addFilter(viewerFilter);
getClearSearchAction().setEnabled(true);
getSearchAction().setEnabled(true);
}
});
}
});
removeEmptyViewerFilter();
return Status.OK_STATUS;
}
private void setEmptyViewerFilter() {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
tableHistoryViewer.addFilter(new EmptySearchViewerFilter());
}
});
}
private void removeEmptyViewerFilter() {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
ViewerFilter[] filters = tableHistoryViewer.getFilters();
for (int i=0; i<filters.length; i++) {
if (filters[i] instanceof EmptySearchViewerFilter) {
tableHistoryViewer.removeFilter(filters[i]);
}
}
}
});
}
}
class FetchChangePathJob extends Job {
public ILogEntry logEntry;
public FetchChangePathJob() {
super(Policy.bind("HistoryView.fetchChangePathJob")); //$NON-NLS-1$;
}
public void setLogEntry(ILogEntry logEntry) {
this.logEntry = logEntry;
}
public IStatus run(IProgressMonitor monitor) {
if(logEntry.getResource() != null) {
setCurrentLogEntryChangePath(logEntry.getLogEntryChangePaths());
}
return Status.OK_STATUS;
}
}
public static class ToggleAffectedPathsOptionAction extends Action {
private final SVNHistoryPage page;
private final String preferenceName;
private final int value;
public ToggleAffectedPathsOptionAction(SVNHistoryPage page,
String label, String icon, String preferenceName, int value) {
super(Policy.bind(label), AS_RADIO_BUTTON);
this.page = page;
this.preferenceName = preferenceName;
this.value = value;
setImageDescriptor(SVNUIPlugin.getPlugin().getImageDescriptor(icon));
IPreferenceStore store = SVNUIPlugin.getPlugin().getPreferenceStore();
setChecked(value==store.getInt(preferenceName));
}
public int getValue() {
return this.value;
}
public void run() {
if (isChecked()) {
SVNUIPlugin.getPlugin().getPreferenceStore().setValue(preferenceName, value);
page.createAffectedPathsViewer();
}
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.core.IResourceStateChangeListener#resourceSyncInfoChanged(org.eclipse.core.resources.IResource[])
*/
public void resourceSyncInfoChanged(IResource[] changedResources) {
for (int i = 0; i < changedResources.length; i++) {
IResource changedResource = changedResources[i];
if( changedResource.equals( resource ) ) {
resourceChanged();
}
}
}
/**
* This method updates the history table, highlighting the current revison
* without refetching the log entries to preserve bandwidth.
* The user has to a manual refresh to get the new log entries.
*/
private void resourceChanged() {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
revisionStart = SVNRevision.HEAD;
ISVNLocalResource localResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
try {
if (localResource != null && !localResource.getStatus().isAdded()) {
ISVNRemoteResource baseResource = localResource.getBaseResource();
historyTableProvider.setRemoteResource(baseResource);
historyTableProvider.setProjectProperties(null);
tableHistoryViewer.refresh();
}
} catch (SVNException e) {
SVNUIPlugin.openError(getHistoryPageSite().getShell(), null, null, e);
}
}
});
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent e) {
if (e.keyCode == 'f' && e.stateMask == SWT.CTRL) {
getSearchAction().run();
}
}
/*
* (non-Javadoc)
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent e) {
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.core.IResourceStateChangeListener#resourceModified(org.eclipse.core.resources.IResource[])
*/
public void resourceModified(IResource[] changedResources) {
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.core.IResourceStateChangeListener#projectConfigured(org.eclipse.core.resources.IProject)
*/
public void projectConfigured(IProject project) {
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.core.IResourceStateChangeListener#projectDeconfigured(org.eclipse.core.resources.IProject)
*/
public void projectDeconfigured(IProject project) {
}
public static void setHistorySearchViewerFilter(
HistorySearchViewerFilter historySearchViewerFilter) {
SVNHistoryPage.historySearchViewerFilter = historySearchViewerFilter;
}
}
|
Disable Open and Show Annotation actions when folder selected in history view
change paths section.
Issue #: 902
|
org.tigris.subversion.subclipse.ui/src/org/tigris/subversion/subclipse/ui/history/SVNHistoryPage.java
|
Disable Open and Show Annotation actions when folder selected in history view change paths section. Issue #: 902
|
|
Java
|
mpl-2.0
|
ba890cd0f620dcd28efc6ab5f99f602b0b6e54c1
| 0
|
powsybl/powsybl-core,powsybl/powsybl-core,powsybl/powsybl-core
|
/**
* Copyright (c) 2017-2018, RTE (http://www.rte-france.com)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.powsybl.triplestore.impl.rdf4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.rdf4j.IsolationLevels;
import org.eclipse.rdf4j.common.iteration.Iterations;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Namespace;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.QueryResults;
import org.eclipse.rdf4j.query.TupleQuery;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.query.algebra.evaluation.function.rdfterm.UUID;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.RepositoryResult;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFWriter;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.BasicParserSettings;
import org.eclipse.rdf4j.rio.helpers.BasicWriterSettings;
import org.eclipse.rdf4j.rio.helpers.XMLParserSettings;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.powsybl.commons.datasource.DataSource;
import com.powsybl.triplestore.api.AbstractPowsyblTripleStore;
import com.powsybl.triplestore.api.PropertyBag;
import com.powsybl.triplestore.api.PropertyBags;
import com.powsybl.triplestore.api.TripleStoreException;
/**
* @author Luma Zamarreño <zamarrenolm at aia.es>
*/
public class TripleStoreRDF4J extends AbstractPowsyblTripleStore {
public TripleStoreRDF4J() {
repo = new SailRepository(new MemoryStore());
repo.initialize();
}
@Override
public void read(String base, String contextName, InputStream is) {
try (RepositoryConnection conn = repo.getConnection()) {
conn.setIsolationLevel(IsolationLevels.NONE);
// Report invalid identifiers but do not fail
// (sometimes RDF identifiers contain spaces or begin with #)
// This is the default behavior for other triple store engines (Jena)
conn.getParserConfig().addNonFatalError(XMLParserSettings.FAIL_ON_INVALID_NCNAME);
conn.getParserConfig().addNonFatalError(BasicParserSettings.VERIFY_URI_SYNTAX);
Resource context = context(conn, contextName);
// We add data with a context (graph) to keep the source of information
// When we write we want to keep data split by graph
conn.add(is, base, formatFromName(contextName), context);
addNamespaceForBase(conn, base);
} catch (IOException x) {
throw new TripleStoreException(String.format("Reading %s %s", base, contextName), x);
}
}
private static RDFFormat formatFromName(String name) {
if (name.endsWith(".ttl")) {
return RDFFormat.TURTLE;
} else if (name.endsWith(".xml")) {
return RDFFormat.RDFXML;
}
return RDFFormat.RDFXML;
}
@Override
public void write(DataSource ds) {
try (RepositoryConnection conn = repo.getConnection()) {
RepositoryResult<Resource> contexts = conn.getContextIDs();
while (contexts.hasNext()) {
Resource context = contexts.next();
LOGGER.info("Writing context {}", context);
RepositoryResult<Statement> statements;
statements = conn.getStatements(null, null, null, context);
Model model = QueryResults.asModel(statements);
copyNamespacesToModel(conn, model);
String outname = context.toString();
write(model, outputStream(ds, outname));
}
}
}
@Override
public void print(PrintStream out) {
out.println("TripleStore based on RDF4J. Graph names and sizes");
try (RepositoryConnection conn = repo.getConnection()) {
RepositoryResult<Resource> ctxs = conn.getContextIDs();
while (ctxs.hasNext()) {
Resource ctx = ctxs.next();
int size = statementsCount(conn, ctx);
out.println(" " + ctx + " : " + size);
}
}
}
@Override
public Set<String> contextNames() {
try (RepositoryConnection conn = repo.getConnection()) {
return Iterations.stream(conn.getContextIDs()).map(Resource::stringValue).collect(Collectors.toSet());
}
}
@Override
public void clear(String contextName) {
try (RepositoryConnection conn = repo.getConnection()) {
Resource context = context(conn, contextName);
conn.clear(context);
}
}
@Override
public PropertyBags query(String query) {
String query1 = adjustedQuery(query);
PropertyBags results = new PropertyBags();
try (RepositoryConnection conn = repo.getConnection()) {
// Default language is SPARQL
TupleQuery q = conn.prepareTupleQuery(query1);
// Duplicated triplets are returned in queries
// when an object is defined in a file and referrenced in another (rdf:ID and
// rdf:about)
// and data has been added to repository with contexts
// and we query without using explicit GRAPH clauses
// This means that we have to filter distinct results
try (TupleQueryResult r = QueryResults.distinctResults(q.evaluate())) {
List<String> names = r.getBindingNames();
while (r.hasNext()) {
BindingSet s = r.next();
PropertyBag result = new PropertyBag(names);
names.forEach(name -> {
if (s.hasBinding(name)) {
String value = s.getBinding(name).getValue().stringValue();
result.put(name, value);
}
});
if (result.size() > 0) {
results.add(result);
}
}
}
}
return results;
}
@Override
public void add(String graph, String objType, PropertyBags statements) {
try (RepositoryConnection conn = repo.getConnection()) {
conn.setIsolationLevel(IsolationLevels.NONE);
String name = null;
RepositoryResult<Resource> ctxs = conn.getContextIDs();
while (ctxs.hasNext()) {
String ctx = ctxs.next().stringValue();
if (ctx.contains("EQ")) {
name = ctx.replace("EQ", graph);
break;
}
}
Resource context = conn.getValueFactory().createIRI(name);
statements.forEach(statement -> createStatements(conn, objType, statement, context));
}
}
private static void createStatements(RepositoryConnection cnx, String objType, PropertyBag statement,
Resource context) {
UUID uuid = new UUID();
IRI resource = uuid.evaluate(cnx.getValueFactory());
IRI parentPredicate = RDF.TYPE;
IRI parentObject = cnx.getValueFactory().createIRI(objType);
Statement parentSt = cnx.getValueFactory().createStatement(resource, parentPredicate, parentObject);
cnx.add(parentSt, context);
List<String> names = statement.propertyNames();
names.forEach(name -> {
IRI predicate = cnx.getValueFactory().createIRI(objType + "." + name);
Statement st;
if (statement.isResource(name)) {
String namespace = cnx.getNamespace(statement.namespacePrefix(name));
IRI object = cnx.getValueFactory().createIRI(namespace, statement.get(name));
st = cnx.getValueFactory().createStatement(resource, predicate, object);
} else {
Literal object = cnx.getValueFactory().createLiteral(statement.get(name));
st = cnx.getValueFactory().createStatement(resource, predicate, object);
}
cnx.add(st, context);
});
}
private static void write(Model m, OutputStream out) {
try (PrintStream pout = new PrintStream(out)) {
RDFWriter w = new PowsyblWriter(pout);
w.getWriterConfig().set(BasicWriterSettings.PRETTY_PRINT, true);
Rio.write(m, w);
}
}
private static int statementsCount(RepositoryConnection conn, Resource ctx) {
RepositoryResult<Statement> statements = conn.getStatements(null, null, null, ctx);
int counter = 0;
while (statements.hasNext()) {
counter++;
statements.next();
}
return counter;
}
private static void copyNamespacesToModel(RepositoryConnection conn, Model m) {
RepositoryResult<Namespace> ns = conn.getNamespaces();
while (ns.hasNext()) {
m.setNamespace(ns.next());
}
}
private static void addNamespaceForBase(RepositoryConnection cnx, String base) {
cnx.setNamespace("data", base + "/#");
}
private Resource context(RepositoryConnection conn, String contextName) {
// Remove the namespaceForContexts from contextName if it already starts with it
String name1 = contextName.replace(namespaceForContexts(), "");
return conn.getValueFactory().createIRI(namespaceForContexts(), name1);
}
private final Repository repo;
private static final Logger LOGGER = LoggerFactory.getLogger(TripleStoreRDF4J.class);
}
|
triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/TripleStoreRDF4J.java
|
/**
* Copyright (c) 2017-2018, RTE (http://www.rte-france.com)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.powsybl.triplestore.impl.rdf4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.eclipse.rdf4j.IsolationLevels;
import org.eclipse.rdf4j.common.iteration.Iterations;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Literal;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.Namespace;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.QueryResults;
import org.eclipse.rdf4j.query.TupleQuery;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.query.algebra.evaluation.function.rdfterm.UUID;
import org.eclipse.rdf4j.repository.Repository;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.RepositoryResult;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFWriter;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.helpers.BasicWriterSettings;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.powsybl.commons.datasource.DataSource;
import com.powsybl.triplestore.api.AbstractPowsyblTripleStore;
import com.powsybl.triplestore.api.PropertyBag;
import com.powsybl.triplestore.api.PropertyBags;
import com.powsybl.triplestore.api.TripleStoreException;
/**
* @author Luma Zamarreño <zamarrenolm at aia.es>
*/
public class TripleStoreRDF4J extends AbstractPowsyblTripleStore {
public TripleStoreRDF4J() {
repo = new SailRepository(new MemoryStore());
repo.initialize();
}
@Override
public void read(String base, String contextName, InputStream is) {
try (RepositoryConnection conn = repo.getConnection()) {
conn.setIsolationLevel(IsolationLevels.NONE);
Resource context = context(conn, contextName);
// We add data with a context (graph) to keep the source of information
// When we write we want to keep data split by graph
conn.add(is, base, formatFromName(contextName), context);
addNamespaceForBase(conn, base);
} catch (IOException x) {
throw new TripleStoreException(String.format("Reading %s %s", base, contextName), x);
}
}
private static RDFFormat formatFromName(String name) {
if (name.endsWith(".ttl")) {
return RDFFormat.TURTLE;
} else if (name.endsWith(".xml")) {
return RDFFormat.RDFXML;
}
return RDFFormat.RDFXML;
}
@Override
public void write(DataSource ds) {
try (RepositoryConnection conn = repo.getConnection()) {
RepositoryResult<Resource> contexts = conn.getContextIDs();
while (contexts.hasNext()) {
Resource context = contexts.next();
LOGGER.info("Writing context {}", context);
RepositoryResult<Statement> statements;
statements = conn.getStatements(null, null, null, context);
Model model = QueryResults.asModel(statements);
copyNamespacesToModel(conn, model);
String outname = context.toString();
write(model, outputStream(ds, outname));
}
}
}
@Override
public void print(PrintStream out) {
out.println("TripleStore based on RDF4J. Graph names and sizes");
try (RepositoryConnection conn = repo.getConnection()) {
RepositoryResult<Resource> ctxs = conn.getContextIDs();
while (ctxs.hasNext()) {
Resource ctx = ctxs.next();
int size = statementsCount(conn, ctx);
out.println(" " + ctx + " : " + size);
}
}
}
@Override
public Set<String> contextNames() {
try (RepositoryConnection conn = repo.getConnection()) {
return Iterations.stream(conn.getContextIDs()).map(Resource::stringValue).collect(Collectors.toSet());
}
}
@Override
public void clear(String contextName) {
try (RepositoryConnection conn = repo.getConnection()) {
Resource context = context(conn, contextName);
conn.clear(context);
}
}
@Override
public PropertyBags query(String query) {
String query1 = adjustedQuery(query);
PropertyBags results = new PropertyBags();
try (RepositoryConnection conn = repo.getConnection()) {
// Default language is SPARQL
TupleQuery q = conn.prepareTupleQuery(query1);
// Duplicated triplets are returned in queries
// when an object is defined in a file and referrenced in another (rdf:ID and
// rdf:about)
// and data has been added to repository with contexts
// and we query without using explicit GRAPH clauses
// This means that we have to filter distinct results
try (TupleQueryResult r = QueryResults.distinctResults(q.evaluate())) {
List<String> names = r.getBindingNames();
while (r.hasNext()) {
BindingSet s = r.next();
PropertyBag result = new PropertyBag(names);
names.forEach(name -> {
if (s.hasBinding(name)) {
String value = s.getBinding(name).getValue().stringValue();
result.put(name, value);
}
});
if (result.size() > 0) {
results.add(result);
}
}
}
}
return results;
}
@Override
public void add(String graph, String objType, PropertyBags statements) {
try (RepositoryConnection conn = repo.getConnection()) {
conn.setIsolationLevel(IsolationLevels.NONE);
String name = null;
RepositoryResult<Resource> ctxs = conn.getContextIDs();
while (ctxs.hasNext()) {
String ctx = ctxs.next().stringValue();
if (ctx.contains("EQ")) {
name = ctx.replace("EQ", graph);
break;
}
}
Resource context = conn.getValueFactory().createIRI(name);
statements.forEach(statement -> createStatements(conn, objType, statement, context));
}
}
private static void createStatements(RepositoryConnection cnx, String objType, PropertyBag statement,
Resource context) {
UUID uuid = new UUID();
IRI resource = uuid.evaluate(cnx.getValueFactory());
IRI parentPredicate = RDF.TYPE;
IRI parentObject = cnx.getValueFactory().createIRI(objType);
Statement parentSt = cnx.getValueFactory().createStatement(resource, parentPredicate, parentObject);
cnx.add(parentSt, context);
List<String> names = statement.propertyNames();
names.forEach(name -> {
IRI predicate = cnx.getValueFactory().createIRI(objType + "." + name);
Statement st;
if (statement.isResource(name)) {
String namespace = cnx.getNamespace(statement.namespacePrefix(name));
IRI object = cnx.getValueFactory().createIRI(namespace, statement.get(name));
st = cnx.getValueFactory().createStatement(resource, predicate, object);
} else {
Literal object = cnx.getValueFactory().createLiteral(statement.get(name));
st = cnx.getValueFactory().createStatement(resource, predicate, object);
}
cnx.add(st, context);
});
}
private static void write(Model m, OutputStream out) {
try (PrintStream pout = new PrintStream(out)) {
RDFWriter w = new PowsyblWriter(pout);
w.getWriterConfig().set(BasicWriterSettings.PRETTY_PRINT, true);
Rio.write(m, w);
}
}
private static int statementsCount(RepositoryConnection conn, Resource ctx) {
RepositoryResult<Statement> statements = conn.getStatements(null, null, null, ctx);
int counter = 0;
while (statements.hasNext()) {
counter++;
statements.next();
}
return counter;
}
private static void copyNamespacesToModel(RepositoryConnection conn, Model m) {
RepositoryResult<Namespace> ns = conn.getNamespaces();
while (ns.hasNext()) {
m.setNamespace(ns.next());
}
}
private static void addNamespaceForBase(RepositoryConnection cnx, String base) {
cnx.setNamespace("data", base + "/#");
}
private Resource context(RepositoryConnection conn, String contextName) {
// Remove the namespaceForContexts from contextName if it already starts with it
String name1 = contextName.replace(namespaceForContexts(), "");
return conn.getValueFactory().createIRI(namespaceForContexts(), name1);
}
private final Repository repo;
private static final Logger LOGGER = LoggerFactory.getLogger(TripleStoreRDF4J.class);
}
|
CGMES using RDF4J triple store engine: non-fatal errors on invalid identifiers (#644)
|
triple-store/triple-store-impl-rdf4j/src/main/java/com/powsybl/triplestore/impl/rdf4j/TripleStoreRDF4J.java
|
CGMES using RDF4J triple store engine: non-fatal errors on invalid identifiers (#644)
|
|
Java
|
agpl-3.0
|
df632f92353392c397defb84249777d3a6acdaa7
| 0
|
acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling
|
package functionaltests;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.objectweb.proactive.core.config.CentralPAPropertyRepository;
import org.ow2.proactive.resourcemanager.common.event.RMEventType;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.nodesource.NodeSource;
import org.ow2.proactive.scheduler.common.util.FileUtils;
import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties;
import org.ow2.proactive.utils.FileToBytesConverter;
import org.ow2.tests.FunctionalTest;
public class MultipleRMTBase extends FunctionalTest {
protected File config1;
protected File config2;
private List<File> tempFiles = new ArrayList<File>();
@Before
public void initConfigs() throws Exception {
/*
* Create two copies of default test RM configurations, change path to the directory used by
* Derby (two resource managers should use two different directories)
*/
File configurationFile = new File(RMTHelper.functionalTestRMProperties.toURI());
Properties config = new Properties();
config.load(new FileInputStream(configurationFile));
String hibernateConfigFile = config.getProperty(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG
.getKey());
if (hibernateConfigFile == null) {
Assert.fail("Can't find hibernate config");
}
hibernateConfigFile = PASchedulerProperties.getAbsolutePath(hibernateConfigFile);
String hibernateConfig = new String(FileToBytesConverter.convertFileToByteArray(new File(
hibernateConfigFile)));
String defaultDB = "jdbc:derby:RM_DB;create=true";
if (!hibernateConfig.contains(defaultDB)) {
Assert.fail("Hibernate config doesn't contain expected string");
}
File derbyDir1 = new File("RM_DB1");
if (derbyDir1.isDirectory()) {
FileUtils.removeDir(derbyDir1);
}
tempFiles.add(derbyDir1);
File derbyDir2 = new File("RM_DB2");
if (derbyDir2.isDirectory()) {
FileUtils.removeDir(derbyDir2);
}
tempFiles.add(derbyDir2);
File hibernateConfig1 = new File(System.getProperty("java.io.tmpdir") + File.separator +
"dbconfig1.xml");
tempFiles.add(hibernateConfig1);
File hibernateConfig2 = new File(System.getProperty("java.io.tmpdir") + File.separator +
"dbconfig2.xml");
tempFiles.add(hibernateConfig2);
writeStringToFile(hibernateConfig1, hibernateConfig.replace(defaultDB,
"jdbc:derby:RM_DB1;create=true"));
writeStringToFile(hibernateConfig2, hibernateConfig.replace(defaultDB,
"jdbc:derby:RM_DB2;create=true"));
config1 = new File(System.getProperty("java.io.tmpdir") + File.separator + "rmconfig1.txt");
tempFiles.add(config1);
config2 = new File(System.getProperty("java.io.tmpdir") + File.separator + "rmconfig2.txt");
tempFiles.add(config2);
config.put(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getKey(), hibernateConfig1
.getAbsolutePath());
config.store(new FileOutputStream(config1), null);
config.put(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getKey(), hibernateConfig2
.getAbsolutePath());
config.store(new FileOutputStream(config2), null);
}
@After
public void cleanup() {
for (File tmpFile : tempFiles) {
if (tmpFile.isDirectory()) {
FileUtils.removeDir(tmpFile);
} else {
tmpFile.delete();
}
}
}
protected void createNodeSource(RMTHelper helper, int rmiPort, int nodesNumber) throws Exception {
Map<String, String> map = new HashMap<String, String>(1);
map.put(CentralPAPropertyRepository.PA_RMI_PORT.getName(), String.valueOf(rmiPort));
for (int i = 0; i < nodesNumber; i++) {
String nodeName = "node-" + i;
String nodeUrl = "rmi://localhost:" + rmiPort + "/" + nodeName;
helper.createNode(nodeName, nodeUrl, map);
helper.getResourceManager().addNode(nodeUrl);
}
helper.waitForNodeSourceEvent(RMEventType.NODESOURCE_CREATED, NodeSource.DEFAULT);
for (int i = 0; i < nodesNumber; i++) {
helper.waitForAnyNodeEvent(RMEventType.NODE_STATE_CHANGED);
}
}
private static void writeStringToFile(File file, String string) throws IOException {
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
out.write(string.getBytes());
} finally {
out.close();
}
}
}
|
src/scheduler/tests/functionaltests/MultipleRMTBase.java
|
package functionaltests;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.objectweb.proactive.core.config.CentralPAPropertyRepository;
import org.ow2.proactive.resourcemanager.common.event.RMEventType;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.nodesource.NodeSource;
import org.ow2.proactive.scheduler.common.util.FileUtils;
import org.ow2.proactive.utils.FileToBytesConverter;
import org.ow2.tests.FunctionalTest;
public class MultipleRMTBase extends FunctionalTest {
protected File config1;
protected File config2;
private List<File> tempFiles = new ArrayList<File>();
@Before
public void initConfigs() throws Exception {
/*
* Create two copies of default test RM configurations, change path to the directory used by
* Derby (two resource managers should use two different directories)
*/
File configurationFile = new File(RMTHelper.functionalTestRMProperties.toURI());
Properties config = new Properties();
config.load(new FileInputStream(configurationFile));
String hibernateConfigFile = config.getProperty(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG
.getKey());
if (hibernateConfigFile == null) {
Assert.fail("Can't find hibernate config");
}
String hibernateConfig = new String(FileToBytesConverter.convertFileToByteArray(new File(
hibernateConfigFile)));
String defaultDB = "jdbc:derby:RM_DB;create=true";
if (!hibernateConfig.contains(defaultDB)) {
Assert.fail("Hibernate config doesn't contain expected string");
}
File derbyDir1 = new File("RM_DB1");
if (derbyDir1.isDirectory()) {
FileUtils.removeDir(derbyDir1);
}
tempFiles.add(derbyDir1);
File derbyDir2 = new File("RM_DB2");
if (derbyDir2.isDirectory()) {
FileUtils.removeDir(derbyDir2);
}
tempFiles.add(derbyDir2);
File hibernateConfig1 = new File(System.getProperty("java.io.tmpdir") + File.separator +
"dbconfig1.xml");
tempFiles.add(hibernateConfig1);
File hibernateConfig2 = new File(System.getProperty("java.io.tmpdir") + File.separator +
"dbconfig2.xml");
tempFiles.add(hibernateConfig2);
writeStringToFile(hibernateConfig1, hibernateConfig.replace(defaultDB,
"jdbc:derby:RM_DB1;create=true"));
writeStringToFile(hibernateConfig2, hibernateConfig.replace(defaultDB,
"jdbc:derby:RM_DB2;create=true"));
config1 = new File(System.getProperty("java.io.tmpdir") + File.separator + "rmconfig1.txt");
tempFiles.add(config1);
config2 = new File(System.getProperty("java.io.tmpdir") + File.separator + "rmconfig2.txt");
tempFiles.add(config2);
config.put(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getKey(), hibernateConfig1
.getAbsolutePath());
config.store(new FileOutputStream(config1), null);
config.put(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getKey(), hibernateConfig2
.getAbsolutePath());
config.store(new FileOutputStream(config2), null);
}
@After
public void cleanup() {
for (File tmpFile : tempFiles) {
if (tmpFile.isDirectory()) {
FileUtils.removeDir(tmpFile);
} else {
tmpFile.delete();
}
}
}
protected void createNodeSource(RMTHelper helper, int rmiPort, int nodesNumber) throws Exception {
Map<String, String> map = new HashMap<String, String>(1);
map.put(CentralPAPropertyRepository.PA_RMI_PORT.getName(), String.valueOf(rmiPort));
for (int i = 0; i < nodesNumber; i++) {
String nodeName = "node-" + i;
String nodeUrl = "rmi://localhost:" + rmiPort + "/" + nodeName;
helper.createNode(nodeName, nodeUrl, map);
helper.getResourceManager().addNode(nodeUrl);
}
helper.waitForNodeSourceEvent(RMEventType.NODESOURCE_CREATED, NodeSource.DEFAULT);
for (int i = 0; i < nodesNumber; i++) {
helper.waitForAnyNodeEvent(RMEventType.NODE_STATE_CHANGED);
}
}
private static void writeStringToFile(File file, String string) throws IOException {
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
out.write(string.getBytes());
} finally {
out.close();
}
}
}
|
SCHEDULING-1604 MultipleRMTBase uses relative path to hibernate config,
causing test failures in Jenkins
Fixed test to convert relative path to absolute.
|
src/scheduler/tests/functionaltests/MultipleRMTBase.java
|
SCHEDULING-1604 MultipleRMTBase uses relative path to hibernate config, causing test failures in Jenkins
|
|
Java
|
agpl-3.0
|
284f1a843463c6c8f9f93fb834dd0865d578daba
| 0
|
ProtocolSupport/ProtocolSupport,ridalarry/ProtocolSupport
|
package protocolsupport.zplatform.impl.glowstone;
import java.lang.reflect.Field;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.WorldType;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.flowpowered.network.Codec.CodecRegistration;
import com.flowpowered.network.Message;
import com.flowpowered.network.service.CodecLookupService;
import net.glowstone.GlowServer;
import net.glowstone.entity.meta.profile.PlayerProfile;
import net.glowstone.net.message.KickMessage;
import net.glowstone.net.message.SetCompressionMessage;
import net.glowstone.net.message.handshake.HandshakeMessage;
import net.glowstone.net.message.login.EncryptionKeyRequestMessage;
import net.glowstone.net.message.login.EncryptionKeyResponseMessage;
import net.glowstone.net.message.login.LoginStartMessage;
import net.glowstone.net.message.login.LoginSuccessMessage;
import net.glowstone.net.message.play.entity.AnimateEntityMessage;
import net.glowstone.net.message.play.entity.AttachEntityMessage;
import net.glowstone.net.message.play.entity.CollectItemMessage;
import net.glowstone.net.message.play.entity.DestroyEntitiesMessage;
import net.glowstone.net.message.play.entity.EntityEffectMessage;
import net.glowstone.net.message.play.entity.EntityEquipmentMessage;
import net.glowstone.net.message.play.entity.EntityHeadRotationMessage;
import net.glowstone.net.message.play.entity.EntityMetadataMessage;
import net.glowstone.net.message.play.entity.EntityPropertyMessage;
import net.glowstone.net.message.play.entity.EntityRemoveEffectMessage;
import net.glowstone.net.message.play.entity.EntityRotationMessage;
import net.glowstone.net.message.play.entity.EntityStatusMessage;
import net.glowstone.net.message.play.entity.EntityTeleportMessage;
import net.glowstone.net.message.play.entity.EntityVelocityMessage;
import net.glowstone.net.message.play.entity.RelativeEntityPositionMessage;
import net.glowstone.net.message.play.entity.RelativeEntityPositionRotationMessage;
import net.glowstone.net.message.play.entity.SetCooldownMessage;
import net.glowstone.net.message.play.entity.SetPassengerMessage;
import net.glowstone.net.message.play.entity.SpawnLightningStrikeMessage;
import net.glowstone.net.message.play.entity.SpawnMobMessage;
import net.glowstone.net.message.play.entity.SpawnObjectMessage;
import net.glowstone.net.message.play.entity.SpawnPaintingMessage;
import net.glowstone.net.message.play.entity.SpawnPlayerMessage;
import net.glowstone.net.message.play.entity.SpawnXpOrbMessage;
import net.glowstone.net.message.play.entity.VehicleMoveMessage;
import net.glowstone.net.message.play.game.BlockActionMessage;
import net.glowstone.net.message.play.game.BlockChangeMessage;
import net.glowstone.net.message.play.game.ChatMessage;
import net.glowstone.net.message.play.game.ChunkDataMessage;
import net.glowstone.net.message.play.game.ClientSettingsMessage;
import net.glowstone.net.message.play.game.ExperienceMessage;
import net.glowstone.net.message.play.game.ExplosionMessage;
import net.glowstone.net.message.play.game.HealthMessage;
import net.glowstone.net.message.play.game.IncomingChatMessage;
import net.glowstone.net.message.play.game.JoinGameMessage;
import net.glowstone.net.message.play.game.MapDataMessage;
import net.glowstone.net.message.play.game.MultiBlockChangeMessage;
import net.glowstone.net.message.play.game.NamedSoundEffectMessage;
import net.glowstone.net.message.play.game.PingMessage;
import net.glowstone.net.message.play.game.PlayEffectMessage;
import net.glowstone.net.message.play.game.PlayParticleMessage;
import net.glowstone.net.message.play.game.PluginMessage;
import net.glowstone.net.message.play.game.PositionRotationMessage;
import net.glowstone.net.message.play.game.RespawnMessage;
import net.glowstone.net.message.play.game.SignEditorMessage;
import net.glowstone.net.message.play.game.SoundEffectMessage;
import net.glowstone.net.message.play.game.SpawnPositionMessage;
import net.glowstone.net.message.play.game.StateChangeMessage;
import net.glowstone.net.message.play.game.StatisticMessage;
import net.glowstone.net.message.play.game.TimeMessage;
import net.glowstone.net.message.play.game.TitleMessage;
import net.glowstone.net.message.play.game.UnloadChunkMessage;
import net.glowstone.net.message.play.game.UpdateBlockEntityMessage;
import net.glowstone.net.message.play.game.UpdateSignMessage;
import net.glowstone.net.message.play.game.UserListHeaderFooterMessage;
import net.glowstone.net.message.play.game.UserListItemMessage;
import net.glowstone.net.message.play.game.WorldBorderMessage;
import net.glowstone.net.message.play.inv.CloseWindowMessage;
import net.glowstone.net.message.play.inv.CreativeItemMessage;
import net.glowstone.net.message.play.inv.EnchantItemMessage;
import net.glowstone.net.message.play.inv.HeldItemMessage;
import net.glowstone.net.message.play.inv.OpenWindowMessage;
import net.glowstone.net.message.play.inv.SetWindowContentsMessage;
import net.glowstone.net.message.play.inv.SetWindowSlotMessage;
import net.glowstone.net.message.play.inv.TransactionMessage;
import net.glowstone.net.message.play.inv.WindowClickMessage;
import net.glowstone.net.message.play.inv.WindowPropertyMessage;
import net.glowstone.net.message.play.player.BlockPlacementMessage;
import net.glowstone.net.message.play.player.BossBarMessage;
import net.glowstone.net.message.play.player.CameraMessage;
import net.glowstone.net.message.play.player.ClientStatusMessage;
import net.glowstone.net.message.play.player.CombatEventMessage;
import net.glowstone.net.message.play.player.DiggingMessage;
import net.glowstone.net.message.play.player.InteractEntityMessage;
import net.glowstone.net.message.play.player.PlayerAbilitiesMessage;
import net.glowstone.net.message.play.player.PlayerActionMessage;
import net.glowstone.net.message.play.player.PlayerLookMessage;
import net.glowstone.net.message.play.player.PlayerPositionLookMessage;
import net.glowstone.net.message.play.player.PlayerPositionMessage;
import net.glowstone.net.message.play.player.PlayerSwingArmMessage;
import net.glowstone.net.message.play.player.PlayerUpdateMessage;
import net.glowstone.net.message.play.player.ResourcePackSendMessage;
import net.glowstone.net.message.play.player.ResourcePackStatusMessage;
import net.glowstone.net.message.play.player.ServerDifficultyMessage;
import net.glowstone.net.message.play.player.SpectateMessage;
import net.glowstone.net.message.play.player.SteerVehicleMessage;
import net.glowstone.net.message.play.player.TabCompleteMessage;
import net.glowstone.net.message.play.player.TabCompleteResponseMessage;
import net.glowstone.net.message.play.player.TeleportConfirmMessage;
import net.glowstone.net.message.play.player.UseBedMessage;
import net.glowstone.net.message.play.player.UseItemMessage;
import net.glowstone.net.message.play.scoreboard.ScoreboardDisplayMessage;
import net.glowstone.net.message.play.scoreboard.ScoreboardObjectiveMessage;
import net.glowstone.net.message.play.scoreboard.ScoreboardScoreMessage;
import net.glowstone.net.message.play.scoreboard.ScoreboardTeamMessage;
import net.glowstone.net.message.status.StatusPingMessage;
import net.glowstone.net.message.status.StatusRequestMessage;
import net.glowstone.net.message.status.StatusResponseMessage;
import net.glowstone.net.protocol.GlowProtocol;
import net.glowstone.net.protocol.ProtocolType;
import net.glowstone.util.TextMessage;
import protocolsupport.api.chat.components.BaseComponent;
import protocolsupport.api.events.ServerPingResponseEvent;
import protocolsupport.protocol.utils.authlib.GameProfile;
import protocolsupport.protocol.utils.types.Position;
import protocolsupport.utils.ReflectionUtils;
import protocolsupport.zplatform.PlatformPacketFactory;
public class GlowStonePacketFactory implements PlatformPacketFactory {
@Override
public Message createInboundInventoryClosePacket() {
return new CloseWindowMessage(0);
}
@Override
public Message createOutboundChatPacket(String message, int position) {
return new ChatMessage(new TextMessage(message), position);
}
@Override
public Message createTabHeaderFooterPacket(BaseComponent header, BaseComponent footer) {
//TODO: Change to use BaseComponent when it will be possible
return new UserListHeaderFooterMessage(new TextMessage(header.toLegacyText()), new TextMessage(header.toLegacyText()));
}
@Override
public Message createTitleResetPacket() {
return new TitleMessage(TitleMessage.Action.RESET);
}
@Override
public Message createTitleClearPacket() {
return new TitleMessage(TitleMessage.Action.CLEAR);
}
@Override
public Message createTitleMainPacket(String title) {
return new TitleMessage(TitleMessage.Action.TITLE, new TextMessage(title));
}
@Override
public Message createTitleSubPacket(String title) {
return new TitleMessage(TitleMessage.Action.SUBTITLE, new TextMessage(title));
}
@Override
public Message createTitleParamsPacket(int fadeIn, int stay, int fadeOut) {
return new TitleMessage(TitleMessage.Action.TIMES, fadeIn, stay, fadeOut);
}
@Override
public Message createLoginDisconnectPacket(String message) {
return new KickMessage(message);
}
@Override
public Message createPlayDisconnectPacket(String message) {
return new KickMessage(message);
}
@Override
public Message createLoginEncryptionBeginPacket(PublicKey publicKey, byte[] randomBytes) {
return new EncryptionKeyRequestMessage("", publicKey.getEncoded(), randomBytes);
}
@Override
public Message createSetCompressionPacket(int threshold) {
return new SetCompressionMessage(threshold);
}
@Override
public Message createBlockBreakSoundPacket(Position pos, Material type) {
return null; // todo: create a getStepSound() equivalent
}
@Override
public Message createStatusPongPacket(long pingId) {
return new StatusPingMessage(pingId);
}
@SuppressWarnings("unchecked")
@Override
public Message createStausServerInfoPacket(List<String> profiles, ServerPingResponseEvent.ProtocolInfo info, String icon, String motd, int maxPlayers) {
GlowServer server = (GlowServer) Bukkit.getServer();
JSONObject json = new JSONObject();
JSONObject version = new JSONObject();
version.put("name", info.getName());
version.put("protocol", info.getId());
json.put("version", version);
JSONObject players = new JSONObject();
players.put("max", maxPlayers);
players.put("online", profiles.size());
if (!profiles.isEmpty()) {
JSONArray playerSample = new JSONArray();
UUID randomUUID = UUID.randomUUID();
PlayerProfile[] playerProfiles = new PlayerProfile[profiles.size()];
for (int i = 0; i < profiles.size(); i++) {
playerProfiles[i] = new PlayerProfile(profiles.get(i), randomUUID);
}
playerProfiles = Arrays.copyOfRange(playerProfiles, 0, Math.min(playerProfiles.length, server.getPlayerSampleCount()));
for (PlayerProfile profile : playerProfiles) {
JSONObject sample = new JSONObject();
sample.put("name", profile.getName());
sample.put("id", profile.getUniqueId().toString());
playerSample.add(sample);
}
players.put("sample", playerSample);
}
json.put("players", players);
JSONObject description = new JSONObject();
description.put("text", motd);
json.put("description", description);
if ((icon != null) && !icon.isEmpty()) {
json.put("favicon", icon);
}
JSONArray modList = new JSONArray();
JSONObject modinfo = new JSONObject();
modinfo.put("type", "vanilla");
modinfo.put("modList", modList);
modinfo.put("clientModsAllowed", true);
json.put("modinfo", modinfo);
return new StatusResponseMessage(json);
}
@Override
public Message createLoginSuccessPacket(GameProfile profile) {
return new LoginSuccessMessage(profile.getUUID().toString(), profile.getName());
}
@Override
public Message createEmptyCustomPayloadPacket(String tag) {
return new PluginMessage(tag, new byte[0]);
}
@Override
public Message createFakeJoinGamePacket() {
return new JoinGameMessage(0, 0, 0, 0, 0, WorldType.NORMAL.name(), false);
}
@Override
public int getOutLoginDisconnectPacketId() {
return getOpcode(ProtocolType.LOGIN, OUTBOUND, KickMessage.class);
}
@Override
public int getOutLoginEncryptionBeginPacketId() {
return getOpcode(ProtocolType.LOGIN, OUTBOUND, EncryptionKeyRequestMessage.class);
}
@Override
public int getOutLoginSuccessPacketId() {
return getOpcode(ProtocolType.LOGIN, OUTBOUND, LoginSuccessMessage.class);
}
@Override
public int getOutLoginSetCompressionPacketId() {
return getOpcode(ProtocolType.LOGIN, OUTBOUND, SetCompressionMessage.class);
}
@Override
public int getOutStatusServerInfoPacketId() {
return getOpcode(ProtocolType.STATUS, OUTBOUND, StatusResponseMessage.class);
}
@Override
public int getOutStatusPongPacketId() {
return getOpcode(ProtocolType.STATUS, OUTBOUND, StatusPingMessage.class);
}
@Override
public int getOutPlayKeepAlivePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PingMessage.class);
}
@Override
public int getOutPlayLoginPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, JoinGameMessage.class);
}
@Override
public int getOutPlayChatPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ChatMessage.class);
}
@Override
public int getOutPlayUpdateTimePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, TimeMessage.class);
}
@Override
public int getOutPlayEntityEquipmentPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityEquipmentMessage.class);
}
@Override
public int getOutPlaySpawnPositionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnPositionMessage.class);
}
@Override
public int getOutPlayUpdateHealthPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, HealthMessage.class);
}
@Override
public int getOutPlayRespawnPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, RespawnMessage.class);
}
@Override
public int getOutPlayPositionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PositionRotationMessage.class);
}
@Override
public int getOutPlayHeldSlotPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, HeldItemMessage.class);
}
@Override
public int getOutPlayBedPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UseBedMessage.class);
}
@Override
public int getOutPlayAnimationPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, AnimateEntityMessage.class);
}
@Override
public int getOutPlaySpawnNamedPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnPlayerMessage.class);
}
@Override
public int getOutPlayCollectEffectPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, CollectItemMessage.class);
}
@Override
public int getOutPlaySpawnObjectPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnObjectMessage.class);
}
@Override
public int getOutPlaySpawnLivingPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnMobMessage.class);
}
@Override
public int getOutPlaySpawnPaintingPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnPaintingMessage.class);
}
@Override
public int getOutPlaySpawnExpOrbPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnXpOrbMessage.class);
}
@Override
public int getOutPlayEntityVelocityPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityVelocityMessage.class);
}
@Override
public int getOutPlayEntityDestroyPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, DestroyEntitiesMessage.class);
}
@Override
public int getOutPlayEntityPacketId() {
return 0x28; // not implemented in Glowstone
}
@Override
public int getOutPlayEntityRelMovePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, RelativeEntityPositionMessage.class);
}
@Override
public int getOutPlayEntityLookPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityRotationMessage.class);
}
@Override
public int getOutPlayEntityRelMoveLookPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, RelativeEntityPositionRotationMessage.class);
}
@Override
public int getOutPlayEntityTeleportPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityTeleportMessage.class);
}
@Override
public int getOutPlayEntityHeadRotationPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityHeadRotationMessage.class);
}
@Override
public int getOutPlayEntityStatusPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityStatusMessage.class);
}
@Override
public int getOutPlayEntityLeashPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, AttachEntityMessage.class);
}
@Override
public int getOutPlayEntityMetadataPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityMetadataMessage.class);
}
@Override
public int getOutPlayEntityEffectAddPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityEffectMessage.class);
}
@Override
public int getOutPlayEntityEffectRemovePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityRemoveEffectMessage.class);
}
@Override
public int getOutPlayExperiencePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ExperienceMessage.class);
}
@Override
public int getOutPlayEntityAttributesPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityPropertyMessage.class);
}
@Override
public int getOutPlayChunkSinglePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ChunkDataMessage.class);
}
@Override
public int getOutPlayBlockChangeMultiPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, MultiBlockChangeMessage.class);
}
@Override
public int getOutPlayBlockChangeSinglePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, BlockChangeMessage.class);
}
@Override
public int getOutPlayBlockActionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, BlockActionMessage.class);
}
@Override
public int getOutPlayBlockBreakAnimationPacketId() {
return 0x08; // not implemented in Glowstone
}
@Override
public int getOutPlayExplosionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ExplosionMessage.class);
}
@Override
public int getOutPlayWorldEventPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PlayEffectMessage.class);
}
@Override
public int getOutPlayWorldSoundPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SoundEffectMessage.class);
}
@Override
public int getOutPlayWorldParticlesPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PlayParticleMessage.class);
}
@Override
public int getOutPlayGameStateChangePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, StateChangeMessage.class);
}
@Override
public int getOutPlaySpawnWeatherPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnLightningStrikeMessage.class);
}
@Override
public int getOutPlayWindowOpenPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, OpenWindowMessage.class);
}
@Override
public int getOutPlayWindowClosePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, CloseWindowMessage.class);
}
@Override
public int getOutPlayWindowSetSlotPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SetWindowSlotMessage.class);
}
@Override
public int getOutPlayWindowSetItemsPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SetWindowContentsMessage.class);
}
@Override
public int getOutPlayWindowDataPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, WindowPropertyMessage.class);
}
@Override
public int getOutPlayWindowTransactionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, TransactionMessage.class);
}
@Override
public int getOutPlayMapPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, MapDataMessage.class);
}
@Override
public int getOutPlayUpdateTilePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UpdateBlockEntityMessage.class);
}
@Override
public int getOutPlaySignEditorPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SignEditorMessage.class);
}
@Override
public int getOutPlayStatisticsPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, StatisticMessage.class);
}
@Override
public int getOutPlayPlayerInfoPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UserListItemMessage.class);
}
@Override
public int getOutPlayAbilitiesPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PlayerAbilitiesMessage.class);
}
@Override
public int getOutPlayTabCompletePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, TabCompleteResponseMessage.class);
}
@Override
public int getOutPlayScoreboardObjectivePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ScoreboardObjectiveMessage.class);
}
@Override
public int getOutPlayScoreboardScorePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ScoreboardScoreMessage.class);
}
@Override
public int getOutPlayScoreboardDisplaySlotPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ScoreboardDisplayMessage.class);
}
@Override
public int getOutPlayScoreboardTeamPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ScoreboardTeamMessage.class);
}
@Override
public int getOutPlayCustomPayloadPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PluginMessage.class);
}
@Override
public int getOutPlayKickDisconnectPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, KickMessage.class);
}
@Override
public int getOutPlayResourcePackPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ResourcePackSendMessage.class);
}
@Override
public int getOutPlayCameraPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, CameraMessage.class);
}
@Override
public int getOutPlayWorldBorderPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, WorldBorderMessage.class);
}
@Override
public int getOutPlayTitlePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, TitleMessage.class);
}
@Override
public int getOutPlayPlayerListHeaderFooterPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UserListHeaderFooterMessage.class);
}
@Override
public int getOutPlaySetPassengersPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SetPassengerMessage.class);
}
@Override
public int getOutPlayChunkUnloadPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UnloadChunkMessage.class);
}
@Override
public int getOutPlayWorldCustomSoundPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, NamedSoundEffectMessage.class);
}
@Override
public int getOutPlayServerDifficultyPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ServerDifficultyMessage.class);
}
@Override
public int getOutPlayCombatEventPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, CombatEventMessage.class);
}
@Override
public int getOutPlayBossBarPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, BossBarMessage.class);
}
@Override
public int getOutPlaySetCooldownPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SetCooldownMessage.class);
}
@Override
public int getOutPlayVehicleMovePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, VehicleMoveMessage.class);
}
@Override
public int getInHandshakeStartPacketId() {
return getOpcode(ProtocolType.HANDSHAKE, INBOUND, HandshakeMessage.class);
}
@Override
public int getInStatusRequestPacketId() {
return getOpcode(ProtocolType.STATUS, INBOUND, StatusRequestMessage.class);
}
@Override
public int getInStatusPingPacketId() {
return getOpcode(ProtocolType.STATUS, INBOUND, StatusPingMessage.class);
}
@Override
public int getInLoginStartPacketId() {
return getOpcode(ProtocolType.LOGIN, INBOUND, LoginStartMessage.class);
}
@Override
public int getInLoginEncryptionBeginPacketId() {
return getOpcode(ProtocolType.LOGIN, INBOUND, EncryptionKeyResponseMessage.class);
}
@Override
public int getInPlayKeepAlivePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PingMessage.class);
}
@Override
public int getInPlayChatPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, IncomingChatMessage.class);
}
@Override
public int getInPlayUseEntityPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, InteractEntityMessage.class);
}
@Override
public int getInPlayPlayerPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerUpdateMessage.class);
}
@Override
public int getInPlayPositionPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerPositionMessage.class);
}
@Override
public int getInPlayLookPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerLookMessage.class);
}
@Override
public int getInPlayPositionLookPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerPositionLookMessage.class);
}
@Override
public int getInPlayBlockDigPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, DiggingMessage.class);
}
@Override
public int getInPlayBlockPlacePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, UseItemMessage.class);
}
@Override
public int getInPlayHeldSlotPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, HeldItemMessage.class);
}
@Override
public int getInPlayAnimationPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerSwingArmMessage.class);
}
@Override
public int getInPlayEntityActionPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerActionMessage.class);
}
@Override
public int getInPlayMoveVehiclePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, VehicleMoveMessage.class);
}
@Override
public int getInPlaySteerBoatPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, SteerVehicleMessage.class);
}
@Override
public int getInPlaySteerVehiclePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, SteerVehicleMessage.class);
}
@Override
public int getInPlayWindowClosePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, CloseWindowMessage.class);
}
@Override
public int getInPlayWindowClickPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, WindowClickMessage.class);
}
@Override
public int getInPlayWindowTransactionPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, TransactionMessage.class);
}
@Override
public int getInPlayCreativeSetSlotPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, CreativeItemMessage.class);
}
@Override
public int getInPlayEnchantSelectPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, EnchantItemMessage.class);
}
@Override
public int getInPlayUpdateSignPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, UpdateSignMessage.class);
}
@Override
public int getInPlayAbilitiesPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerAbilitiesMessage.class);
}
@Override
public int getInPlayTabCompletePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, TabCompleteMessage.class);
}
@Override
public int getInPlaySettingsPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, ClientSettingsMessage.class);
}
@Override
public int getInPlayClientCommandPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, ClientStatusMessage.class);
}
@Override
public int getInPlayCustomPayloadPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PluginMessage.class);
}
@Override
public int getInPlayUseItemPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, BlockPlacementMessage.class);
}
@Override
public int getInPlaySpectatePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, SpectateMessage.class);
}
@Override
public int getInPlayResourcePackStatusPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, ResourcePackStatusMessage.class);
}
@Override
public int getInPlayTeleportAcceptPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, TeleportConfirmMessage.class);
}
private static final int INBOUND = 0, OUTBOUND = 1;
@SuppressWarnings("unchecked")
private static int getOpcode(ProtocolType protocolType, int direction, Class<? extends Message> messageClass) {
try {
GlowProtocol protocol = protocolType.getProtocol();
Class<? extends GlowProtocol> protocolClass = protocol.getClass();
Field lookupServiceField = ReflectionUtils.getField(protocolClass, direction == INBOUND ? "inboundCodecs" : "outboundCodecs");
lookupServiceField.setAccessible(true);
CodecLookupService service = (CodecLookupService) lookupServiceField.get(protocol);
Field messagesField = ReflectionUtils.getField(service.getClass(), "messages");
messagesField.setAccessible(true);
ConcurrentMap<Class<? extends Message>, CodecRegistration> messageMap = (ConcurrentMap<Class<? extends Message>, CodecRegistration>) messagesField.get(service);
return messageMap.get(messageClass).getOpcode();
} catch (Throwable ignored) {
throw new RuntimeException("Unable to get opcode");
}
}
}
|
src/protocolsupport/zplatform/impl/glowstone/GlowStonePacketFactory.java
|
package protocolsupport.zplatform.impl.glowstone;
import java.lang.reflect.Field;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.WorldType;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.flowpowered.network.Codec.CodecRegistration;
import com.flowpowered.network.Message;
import com.flowpowered.network.service.CodecLookupService;
import net.glowstone.GlowServer;
import net.glowstone.entity.meta.profile.PlayerProfile;
import net.glowstone.net.message.KickMessage;
import net.glowstone.net.message.SetCompressionMessage;
import net.glowstone.net.message.handshake.HandshakeMessage;
import net.glowstone.net.message.login.EncryptionKeyRequestMessage;
import net.glowstone.net.message.login.EncryptionKeyResponseMessage;
import net.glowstone.net.message.login.LoginStartMessage;
import net.glowstone.net.message.login.LoginSuccessMessage;
import net.glowstone.net.message.play.entity.AnimateEntityMessage;
import net.glowstone.net.message.play.entity.AttachEntityMessage;
import net.glowstone.net.message.play.entity.CollectItemMessage;
import net.glowstone.net.message.play.entity.DestroyEntitiesMessage;
import net.glowstone.net.message.play.entity.EntityEffectMessage;
import net.glowstone.net.message.play.entity.EntityEquipmentMessage;
import net.glowstone.net.message.play.entity.EntityHeadRotationMessage;
import net.glowstone.net.message.play.entity.EntityMetadataMessage;
import net.glowstone.net.message.play.entity.EntityPropertyMessage;
import net.glowstone.net.message.play.entity.EntityRemoveEffectMessage;
import net.glowstone.net.message.play.entity.EntityRotationMessage;
import net.glowstone.net.message.play.entity.EntityStatusMessage;
import net.glowstone.net.message.play.entity.EntityTeleportMessage;
import net.glowstone.net.message.play.entity.EntityVelocityMessage;
import net.glowstone.net.message.play.entity.RelativeEntityPositionMessage;
import net.glowstone.net.message.play.entity.RelativeEntityPositionRotationMessage;
import net.glowstone.net.message.play.entity.SetCooldownMessage;
import net.glowstone.net.message.play.entity.SetPassengerMessage;
import net.glowstone.net.message.play.entity.SpawnLightningStrikeMessage;
import net.glowstone.net.message.play.entity.SpawnMobMessage;
import net.glowstone.net.message.play.entity.SpawnObjectMessage;
import net.glowstone.net.message.play.entity.SpawnPaintingMessage;
import net.glowstone.net.message.play.entity.SpawnXpOrbMessage;
import net.glowstone.net.message.play.entity.VehicleMoveMessage;
import net.glowstone.net.message.play.game.BlockActionMessage;
import net.glowstone.net.message.play.game.BlockChangeMessage;
import net.glowstone.net.message.play.game.ChatMessage;
import net.glowstone.net.message.play.game.ChunkDataMessage;
import net.glowstone.net.message.play.game.ClientSettingsMessage;
import net.glowstone.net.message.play.game.ExperienceMessage;
import net.glowstone.net.message.play.game.ExplosionMessage;
import net.glowstone.net.message.play.game.HealthMessage;
import net.glowstone.net.message.play.game.IncomingChatMessage;
import net.glowstone.net.message.play.game.JoinGameMessage;
import net.glowstone.net.message.play.game.MapDataMessage;
import net.glowstone.net.message.play.game.MultiBlockChangeMessage;
import net.glowstone.net.message.play.game.NamedSoundEffectMessage;
import net.glowstone.net.message.play.game.PingMessage;
import net.glowstone.net.message.play.game.PlayEffectMessage;
import net.glowstone.net.message.play.game.PlayParticleMessage;
import net.glowstone.net.message.play.game.PluginMessage;
import net.glowstone.net.message.play.game.PositionRotationMessage;
import net.glowstone.net.message.play.game.RespawnMessage;
import net.glowstone.net.message.play.game.SignEditorMessage;
import net.glowstone.net.message.play.game.SoundEffectMessage;
import net.glowstone.net.message.play.game.SpawnPositionMessage;
import net.glowstone.net.message.play.game.StateChangeMessage;
import net.glowstone.net.message.play.game.StatisticMessage;
import net.glowstone.net.message.play.game.TimeMessage;
import net.glowstone.net.message.play.game.TitleMessage;
import net.glowstone.net.message.play.game.UnloadChunkMessage;
import net.glowstone.net.message.play.game.UpdateBlockEntityMessage;
import net.glowstone.net.message.play.game.UpdateSignMessage;
import net.glowstone.net.message.play.game.UserListHeaderFooterMessage;
import net.glowstone.net.message.play.game.UserListItemMessage;
import net.glowstone.net.message.play.game.WorldBorderMessage;
import net.glowstone.net.message.play.inv.CloseWindowMessage;
import net.glowstone.net.message.play.inv.CreativeItemMessage;
import net.glowstone.net.message.play.inv.EnchantItemMessage;
import net.glowstone.net.message.play.inv.HeldItemMessage;
import net.glowstone.net.message.play.inv.OpenWindowMessage;
import net.glowstone.net.message.play.inv.SetWindowContentsMessage;
import net.glowstone.net.message.play.inv.SetWindowSlotMessage;
import net.glowstone.net.message.play.inv.TransactionMessage;
import net.glowstone.net.message.play.inv.WindowClickMessage;
import net.glowstone.net.message.play.inv.WindowPropertyMessage;
import net.glowstone.net.message.play.player.BlockPlacementMessage;
import net.glowstone.net.message.play.player.BossBarMessage;
import net.glowstone.net.message.play.player.CameraMessage;
import net.glowstone.net.message.play.player.ClientStatusMessage;
import net.glowstone.net.message.play.player.CombatEventMessage;
import net.glowstone.net.message.play.player.DiggingMessage;
import net.glowstone.net.message.play.player.InteractEntityMessage;
import net.glowstone.net.message.play.player.PlayerAbilitiesMessage;
import net.glowstone.net.message.play.player.PlayerActionMessage;
import net.glowstone.net.message.play.player.PlayerLookMessage;
import net.glowstone.net.message.play.player.PlayerPositionLookMessage;
import net.glowstone.net.message.play.player.PlayerPositionMessage;
import net.glowstone.net.message.play.player.PlayerSwingArmMessage;
import net.glowstone.net.message.play.player.PlayerUpdateMessage;
import net.glowstone.net.message.play.player.ResourcePackSendMessage;
import net.glowstone.net.message.play.player.ResourcePackStatusMessage;
import net.glowstone.net.message.play.player.ServerDifficultyMessage;
import net.glowstone.net.message.play.player.SpectateMessage;
import net.glowstone.net.message.play.player.SteerVehicleMessage;
import net.glowstone.net.message.play.player.TabCompleteMessage;
import net.glowstone.net.message.play.player.TabCompleteResponseMessage;
import net.glowstone.net.message.play.player.TeleportConfirmMessage;
import net.glowstone.net.message.play.player.UseBedMessage;
import net.glowstone.net.message.play.player.UseItemMessage;
import net.glowstone.net.message.play.scoreboard.ScoreboardDisplayMessage;
import net.glowstone.net.message.play.scoreboard.ScoreboardObjectiveMessage;
import net.glowstone.net.message.play.scoreboard.ScoreboardScoreMessage;
import net.glowstone.net.message.play.scoreboard.ScoreboardTeamMessage;
import net.glowstone.net.message.status.StatusPingMessage;
import net.glowstone.net.message.status.StatusRequestMessage;
import net.glowstone.net.message.status.StatusResponseMessage;
import net.glowstone.net.protocol.GlowProtocol;
import net.glowstone.net.protocol.ProtocolType;
import net.glowstone.util.TextMessage;
import protocolsupport.api.chat.components.BaseComponent;
import protocolsupport.api.events.ServerPingResponseEvent;
import protocolsupport.protocol.utils.authlib.GameProfile;
import protocolsupport.protocol.utils.types.Position;
import protocolsupport.utils.ReflectionUtils;
import protocolsupport.zplatform.PlatformPacketFactory;
public class GlowStonePacketFactory implements PlatformPacketFactory {
@Override
public Message createInboundInventoryClosePacket() {
return new CloseWindowMessage(0);
}
@Override
public Message createOutboundChatPacket(String message, int position) {
return new ChatMessage(new TextMessage(message), position);
}
@Override
public Message createTabHeaderFooterPacket(BaseComponent header, BaseComponent footer) {
//TODO: Change to use BaseComponent when it will be possible
return new UserListHeaderFooterMessage(new TextMessage(header.toLegacyText()), new TextMessage(header.toLegacyText()));
}
@Override
public Message createTitleResetPacket() {
return new TitleMessage(TitleMessage.Action.RESET);
}
@Override
public Message createTitleClearPacket() {
return new TitleMessage(TitleMessage.Action.CLEAR);
}
@Override
public Message createTitleMainPacket(String title) {
return new TitleMessage(TitleMessage.Action.TITLE, new TextMessage(title));
}
@Override
public Message createTitleSubPacket(String title) {
return new TitleMessage(TitleMessage.Action.SUBTITLE, new TextMessage(title));
}
@Override
public Message createTitleParamsPacket(int fadeIn, int stay, int fadeOut) {
return new TitleMessage(TitleMessage.Action.TIMES, fadeIn, stay, fadeOut);
}
@Override
public Message createLoginDisconnectPacket(String message) {
return new KickMessage(message);
}
@Override
public Message createPlayDisconnectPacket(String message) {
return new KickMessage(message);
}
@Override
public Message createLoginEncryptionBeginPacket(PublicKey publicKey, byte[] randomBytes) {
return new EncryptionKeyRequestMessage("", publicKey.getEncoded(), randomBytes);
}
@Override
public Message createSetCompressionPacket(int threshold) {
return new SetCompressionMessage(threshold);
}
@Override
public Message createBlockBreakSoundPacket(Position pos, Material type) {
return null; // todo: create a getStepSound() equivalent
}
@Override
public Message createStatusPongPacket(long pingId) {
return new StatusPingMessage(pingId);
}
@SuppressWarnings("unchecked")
@Override
public Message createStausServerInfoPacket(List<String> profiles, ServerPingResponseEvent.ProtocolInfo info, String icon, String motd, int maxPlayers) {
GlowServer server = (GlowServer) Bukkit.getServer();
JSONObject json = new JSONObject();
JSONObject version = new JSONObject();
version.put("name", info.getName());
version.put("protocol", info.getId());
json.put("version", version);
JSONObject players = new JSONObject();
players.put("max", maxPlayers);
players.put("online", profiles.size());
if (!profiles.isEmpty()) {
JSONArray playerSample = new JSONArray();
UUID randomUUID = UUID.randomUUID();
PlayerProfile[] playerProfiles = new PlayerProfile[profiles.size()];
for (int i = 0; i < profiles.size(); i++) {
playerProfiles[i] = new PlayerProfile(profiles.get(i), randomUUID);
}
playerProfiles = Arrays.copyOfRange(playerProfiles, 0, Math.min(playerProfiles.length, server.getPlayerSampleCount()));
for (PlayerProfile profile : playerProfiles) {
JSONObject sample = new JSONObject();
sample.put("name", profile.getName());
sample.put("id", profile.getUniqueId().toString());
playerSample.add(sample);
}
players.put("sample", playerSample);
}
json.put("players", players);
JSONObject description = new JSONObject();
description.put("text", motd);
json.put("description", description);
if ((icon != null) && !icon.isEmpty()) {
json.put("favicon", icon);
}
JSONArray modList = new JSONArray();
JSONObject modinfo = new JSONObject();
modinfo.put("type", "vanilla");
modinfo.put("modList", modList);
modinfo.put("clientModsAllowed", true);
json.put("modinfo", modinfo);
return new StatusResponseMessage(json);
}
@Override
public Message createLoginSuccessPacket(GameProfile profile) {
return new LoginSuccessMessage(profile.getUUID().toString(), profile.getName());
}
@Override
public Message createEmptyCustomPayloadPacket(String tag) {
return new PluginMessage(tag, new byte[0]);
}
@Override
public Message createFakeJoinGamePacket() {
return new JoinGameMessage(0, 0, 0, 0, 0, WorldType.NORMAL.name(), false);
}
@Override
public int getOutLoginDisconnectPacketId() {
return getOpcode(ProtocolType.LOGIN, OUTBOUND, KickMessage.class);
}
@Override
public int getOutLoginEncryptionBeginPacketId() {
return getOpcode(ProtocolType.LOGIN, OUTBOUND, EncryptionKeyRequestMessage.class);
}
@Override
public int getOutLoginSuccessPacketId() {
return getOpcode(ProtocolType.LOGIN, OUTBOUND, LoginSuccessMessage.class);
}
@Override
public int getOutLoginSetCompressionPacketId() {
return getOpcode(ProtocolType.LOGIN, OUTBOUND, SetCompressionMessage.class);
}
@Override
public int getOutStatusServerInfoPacketId() {
return getOpcode(ProtocolType.STATUS, OUTBOUND, StatusResponseMessage.class);
}
@Override
public int getOutStatusPongPacketId() {
return getOpcode(ProtocolType.STATUS, OUTBOUND, StatusPingMessage.class);
}
@Override
public int getOutPlayKeepAlivePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PingMessage.class);
}
@Override
public int getOutPlayLoginPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, JoinGameMessage.class);
}
@Override
public int getOutPlayChatPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ChatMessage.class);
}
@Override
public int getOutPlayUpdateTimePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, TimeMessage.class);
}
@Override
public int getOutPlayEntityEquipmentPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityEquipmentMessage.class);
}
@Override
public int getOutPlaySpawnPositionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnPositionMessage.class);
}
@Override
public int getOutPlayUpdateHealthPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, HealthMessage.class);
}
@Override
public int getOutPlayRespawnPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, RespawnMessage.class);
}
@Override
public int getOutPlayPositionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PositionRotationMessage.class);
}
@Override
public int getOutPlayHeldSlotPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, HeldItemMessage.class);
}
@Override
public int getOutPlayBedPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UseBedMessage.class);
}
@Override
public int getOutPlayAnimationPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, AnimateEntityMessage.class);
}
@Override
public int getOutPlaySpawnNamedPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnMobMessage.class);
}
@Override
public int getOutPlayCollectEffectPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, CollectItemMessage.class);
}
@Override
public int getOutPlaySpawnObjectPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnObjectMessage.class);
}
@Override
public int getOutPlaySpawnLivingPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnMobMessage.class);
}
@Override
public int getOutPlaySpawnPaintingPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnPaintingMessage.class);
}
@Override
public int getOutPlaySpawnExpOrbPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnXpOrbMessage.class);
}
@Override
public int getOutPlayEntityVelocityPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityVelocityMessage.class);
}
@Override
public int getOutPlayEntityDestroyPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, DestroyEntitiesMessage.class);
}
@Override
public int getOutPlayEntityPacketId() {
return 0x28; // not implemented in Glowstone
}
@Override
public int getOutPlayEntityRelMovePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, RelativeEntityPositionMessage.class);
}
@Override
public int getOutPlayEntityLookPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityRotationMessage.class);
}
@Override
public int getOutPlayEntityRelMoveLookPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, RelativeEntityPositionRotationMessage.class);
}
@Override
public int getOutPlayEntityTeleportPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityTeleportMessage.class);
}
@Override
public int getOutPlayEntityHeadRotationPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityHeadRotationMessage.class);
}
@Override
public int getOutPlayEntityStatusPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityStatusMessage.class);
}
@Override
public int getOutPlayEntityLeashPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, AttachEntityMessage.class);
}
@Override
public int getOutPlayEntityMetadataPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityMetadataMessage.class);
}
@Override
public int getOutPlayEntityEffectAddPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityEffectMessage.class);
}
@Override
public int getOutPlayEntityEffectRemovePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityRemoveEffectMessage.class);
}
@Override
public int getOutPlayExperiencePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ExperienceMessage.class);
}
@Override
public int getOutPlayEntityAttributesPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, EntityPropertyMessage.class);
}
@Override
public int getOutPlayChunkSinglePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ChunkDataMessage.class);
}
@Override
public int getOutPlayBlockChangeMultiPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, MultiBlockChangeMessage.class);
}
@Override
public int getOutPlayBlockChangeSinglePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, BlockChangeMessage.class);
}
@Override
public int getOutPlayBlockActionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, BlockActionMessage.class);
}
@Override
public int getOutPlayBlockBreakAnimationPacketId() {
return 0x08; // not implemented in Glowstone
}
@Override
public int getOutPlayExplosionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ExplosionMessage.class);
}
@Override
public int getOutPlayWorldEventPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PlayEffectMessage.class);
}
@Override
public int getOutPlayWorldSoundPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SoundEffectMessage.class);
}
@Override
public int getOutPlayWorldParticlesPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PlayParticleMessage.class);
}
@Override
public int getOutPlayGameStateChangePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, StateChangeMessage.class);
}
@Override
public int getOutPlaySpawnWeatherPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SpawnLightningStrikeMessage.class);
}
@Override
public int getOutPlayWindowOpenPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, OpenWindowMessage.class);
}
@Override
public int getOutPlayWindowClosePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, CloseWindowMessage.class);
}
@Override
public int getOutPlayWindowSetSlotPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SetWindowSlotMessage.class);
}
@Override
public int getOutPlayWindowSetItemsPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SetWindowContentsMessage.class);
}
@Override
public int getOutPlayWindowDataPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, WindowPropertyMessage.class);
}
@Override
public int getOutPlayWindowTransactionPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, TransactionMessage.class);
}
@Override
public int getOutPlayMapPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, MapDataMessage.class);
}
@Override
public int getOutPlayUpdateTilePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UpdateBlockEntityMessage.class);
}
@Override
public int getOutPlaySignEditorPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SignEditorMessage.class);
}
@Override
public int getOutPlayStatisticsPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, StatisticMessage.class);
}
@Override
public int getOutPlayPlayerInfoPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UserListItemMessage.class);
}
@Override
public int getOutPlayAbilitiesPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PlayerAbilitiesMessage.class);
}
@Override
public int getOutPlayTabCompletePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, TabCompleteResponseMessage.class);
}
@Override
public int getOutPlayScoreboardObjectivePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ScoreboardObjectiveMessage.class);
}
@Override
public int getOutPlayScoreboardScorePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ScoreboardScoreMessage.class);
}
@Override
public int getOutPlayScoreboardDisplaySlotPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ScoreboardDisplayMessage.class);
}
@Override
public int getOutPlayScoreboardTeamPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ScoreboardTeamMessage.class);
}
@Override
public int getOutPlayCustomPayloadPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, PluginMessage.class);
}
@Override
public int getOutPlayKickDisconnectPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, KickMessage.class);
}
@Override
public int getOutPlayResourcePackPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ResourcePackSendMessage.class);
}
@Override
public int getOutPlayCameraPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, CameraMessage.class);
}
@Override
public int getOutPlayWorldBorderPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, WorldBorderMessage.class);
}
@Override
public int getOutPlayTitlePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, TitleMessage.class);
}
@Override
public int getOutPlayPlayerListHeaderFooterPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UserListHeaderFooterMessage.class);
}
@Override
public int getOutPlaySetPassengersPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SetPassengerMessage.class);
}
@Override
public int getOutPlayChunkUnloadPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, UnloadChunkMessage.class);
}
@Override
public int getOutPlayWorldCustomSoundPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, NamedSoundEffectMessage.class);
}
@Override
public int getOutPlayServerDifficultyPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, ServerDifficultyMessage.class);
}
@Override
public int getOutPlayCombatEventPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, CombatEventMessage.class);
}
@Override
public int getOutPlayBossBarPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, BossBarMessage.class);
}
@Override
public int getOutPlaySetCooldownPacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, SetCooldownMessage.class);
}
@Override
public int getOutPlayVehicleMovePacketId() {
return getOpcode(ProtocolType.PLAY, OUTBOUND, VehicleMoveMessage.class);
}
@Override
public int getInHandshakeStartPacketId() {
return getOpcode(ProtocolType.HANDSHAKE, INBOUND, HandshakeMessage.class);
}
@Override
public int getInStatusRequestPacketId() {
return getOpcode(ProtocolType.STATUS, INBOUND, StatusRequestMessage.class);
}
@Override
public int getInStatusPingPacketId() {
return getOpcode(ProtocolType.STATUS, INBOUND, StatusPingMessage.class);
}
@Override
public int getInLoginStartPacketId() {
return getOpcode(ProtocolType.LOGIN, INBOUND, LoginStartMessage.class);
}
@Override
public int getInLoginEncryptionBeginPacketId() {
return getOpcode(ProtocolType.LOGIN, INBOUND, EncryptionKeyResponseMessage.class);
}
@Override
public int getInPlayKeepAlivePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PingMessage.class);
}
@Override
public int getInPlayChatPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, IncomingChatMessage.class);
}
@Override
public int getInPlayUseEntityPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, InteractEntityMessage.class);
}
@Override
public int getInPlayPlayerPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerUpdateMessage.class);
}
@Override
public int getInPlayPositionPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerPositionMessage.class);
}
@Override
public int getInPlayLookPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerLookMessage.class);
}
@Override
public int getInPlayPositionLookPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerPositionLookMessage.class);
}
@Override
public int getInPlayBlockDigPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, DiggingMessage.class);
}
@Override
public int getInPlayBlockPlacePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, UseItemMessage.class);
}
@Override
public int getInPlayHeldSlotPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, HeldItemMessage.class);
}
@Override
public int getInPlayAnimationPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerSwingArmMessage.class);
}
@Override
public int getInPlayEntityActionPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerActionMessage.class);
}
@Override
public int getInPlayMoveVehiclePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, VehicleMoveMessage.class);
}
@Override
public int getInPlaySteerBoatPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, SteerVehicleMessage.class);
}
@Override
public int getInPlaySteerVehiclePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, SteerVehicleMessage.class);
}
@Override
public int getInPlayWindowClosePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, CloseWindowMessage.class);
}
@Override
public int getInPlayWindowClickPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, WindowClickMessage.class);
}
@Override
public int getInPlayWindowTransactionPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, TransactionMessage.class);
}
@Override
public int getInPlayCreativeSetSlotPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, CreativeItemMessage.class);
}
@Override
public int getInPlayEnchantSelectPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, EnchantItemMessage.class);
}
@Override
public int getInPlayUpdateSignPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, UpdateSignMessage.class);
}
@Override
public int getInPlayAbilitiesPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PlayerAbilitiesMessage.class);
}
@Override
public int getInPlayTabCompletePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, TabCompleteMessage.class);
}
@Override
public int getInPlaySettingsPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, ClientSettingsMessage.class);
}
@Override
public int getInPlayClientCommandPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, ClientStatusMessage.class);
}
@Override
public int getInPlayCustomPayloadPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, PluginMessage.class);
}
@Override
public int getInPlayUseItemPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, BlockPlacementMessage.class);
}
@Override
public int getInPlaySpectatePacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, SpectateMessage.class);
}
@Override
public int getInPlayResourcePackStatusPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, ResourcePackStatusMessage.class);
}
@Override
public int getInPlayTeleportAcceptPacketId() {
return getOpcode(ProtocolType.PLAY, INBOUND, TeleportConfirmMessage.class);
}
private static final int INBOUND = 0, OUTBOUND = 1;
@SuppressWarnings("unchecked")
private static int getOpcode(ProtocolType protocolType, int direction, Class<? extends Message> messageClass) {
try {
GlowProtocol protocol = protocolType.getProtocol();
Class<? extends GlowProtocol> protocolClass = protocol.getClass();
Field lookupServiceField = ReflectionUtils.getField(protocolClass, direction == INBOUND ? "inboundCodecs" : "outboundCodecs");
lookupServiceField.setAccessible(true);
CodecLookupService service = (CodecLookupService) lookupServiceField.get(protocol);
Field messagesField = ReflectionUtils.getField(service.getClass(), "messages");
messagesField.setAccessible(true);
ConcurrentMap<Class<? extends Message>, CodecRegistration> messageMap = (ConcurrentMap<Class<? extends Message>, CodecRegistration>) messagesField.get(service);
return messageMap.get(messageClass).getOpcode();
} catch (Throwable ignored) {
throw new RuntimeException("Unable to get opcode");
}
}
}
|
Fix glowstone spawn named packet id
|
src/protocolsupport/zplatform/impl/glowstone/GlowStonePacketFactory.java
|
Fix glowstone spawn named packet id
|
|
Java
|
apache-2.0
|
39359f7edf2e58a88a3f2a37e88aa0fec60dcb96
| 0
|
jbduncan/spotless,gdecaso/spotless,gdecaso/spotless,diffplug/spotless,nedtwigg/spotless,diffplug/spotless,nedtwigg/spotless,diffplug/spotless,diffplug/spotless,jbduncan/spotless,diffplug/spotless,diffplug/spotless,jbduncan/spotless
|
/*
* Copyright 2016 DiffPlug
*
* 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.diffplug.spotless.java;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
// From https://github.com/krasa/EclipseCodeFormatter
/*not thread safe*/
final class ImportSorterImpl {
private final List<String> template = new ArrayList<>();
private final Map<String, List<String>> matchingImports = new HashMap<>();
private final List<String> notMatching = new ArrayList<>();
private final Set<String> allImportOrderItems = new HashSet<>();
static List<String> sort(List<String> imports, List<String> importsOrder) {
ImportSorterImpl importsSorter = new ImportSorterImpl(importsOrder);
return importsSorter.sort(imports);
}
private List<String> sort(List<String> imports) {
filterMatchingImports(imports);
mergeNotMatchingItems(false);
mergeNotMatchingItems(true);
mergeMatchingItems();
return getResult();
}
private ImportSorterImpl(List<String> importOrder) {
List<String> importOrderCopy = new ArrayList<>(importOrder);
normalizeStaticOrderItems(importOrderCopy);
putStaticItemIfNotExists(importOrderCopy);
template.addAll(importOrderCopy);
this.allImportOrderItems.addAll(importOrderCopy);
}
private static void putStaticItemIfNotExists(List<String> allImportOrderItems) {
boolean contains = false;
int indexOfFirstStatic = 0;
for (int i = 0; i < allImportOrderItems.size(); i++) {
String allImportOrderItem = allImportOrderItems.get(i);
if (allImportOrderItem.equals("static ")) {
contains = true;
}
if (allImportOrderItem.startsWith("static ")) {
indexOfFirstStatic = i;
}
}
if (!contains) {
allImportOrderItems.add(indexOfFirstStatic, "static ");
}
}
private static void normalizeStaticOrderItems(List<String> allImportOrderItems) {
for (int i = 0; i < allImportOrderItems.size(); i++) {
String s = allImportOrderItems.get(i);
if (s.startsWith("\\#")) {
allImportOrderItems.set(i, s.replace("\\#", "static "));
}
}
}
/**
* returns not matching items and initializes internal state
*/
private void filterMatchingImports(List<String> imports) {
for (String anImport : imports) {
String orderItem = getBestMatchingImportOrderItem(anImport);
if (orderItem != null) {
if (!matchingImports.containsKey(orderItem)) {
matchingImports.put(orderItem, new ArrayList<>());
}
matchingImports.get(orderItem).add(anImport);
} else {
notMatching.add(anImport);
}
}
notMatching.addAll(allImportOrderItems);
}
private String getBestMatchingImportOrderItem(String anImport) {
String matchingImport = null;
for (String orderItem : allImportOrderItems) {
if (anImport.startsWith(orderItem)) {
if (matchingImport == null) {
matchingImport = orderItem;
} else {
matchingImport = betterMatching(matchingImport, orderItem, anImport);
}
}
}
return matchingImport;
}
/**
* not matching means it does not match any order item, so it will be appended before or after order items
*/
private void mergeNotMatchingItems(boolean staticItems) {
Collections.sort(notMatching);
int firstIndexOfOrderItem = getFirstIndexOfOrderItem(notMatching, staticItems);
int indexOfOrderItem = 0;
for (String notMatchingItem : notMatching) {
if (!matchesStatic(staticItems, notMatchingItem)) {
continue;
}
boolean isOrderItem = isOrderItem(notMatchingItem, staticItems);
if (isOrderItem) {
indexOfOrderItem = template.indexOf(notMatchingItem);
} else {
if (indexOfOrderItem == 0 && firstIndexOfOrderItem != 0) {
// insert before alphabetically first order item
template.add(firstIndexOfOrderItem, notMatchingItem);
firstIndexOfOrderItem++;
} else if (firstIndexOfOrderItem == 0) {
// no order is specified
if (template.size() > 0 && (template.get(template.size() - 1).startsWith("static"))) {
// insert N after last static import
template.add(ImportSorterStep.N);
}
template.add(notMatchingItem);
} else {
// insert after the previous order item
template.add(indexOfOrderItem + 1, notMatchingItem);
indexOfOrderItem++;
}
}
}
}
private boolean isOrderItem(String notMatchingItem, boolean staticItems) {
boolean contains = allImportOrderItems.contains(notMatchingItem);
return contains && matchesStatic(staticItems, notMatchingItem);
}
/**
* gets first order item from sorted input list, and finds out it's index in template.
*/
private int getFirstIndexOfOrderItem(List<String> notMatching, boolean staticItems) {
int firstIndexOfOrderItem = 0;
for (String notMatchingItem : notMatching) {
if (!matchesStatic(staticItems, notMatchingItem)) {
continue;
}
boolean isOrderItem = isOrderItem(notMatchingItem, staticItems);
if (isOrderItem) {
firstIndexOfOrderItem = template.indexOf(notMatchingItem);
break;
}
}
return firstIndexOfOrderItem;
}
private static boolean matchesStatic(boolean staticItems, String notMatchingItem) {
boolean isStatic = notMatchingItem.startsWith("static ");
return (isStatic && staticItems) || (!isStatic && !staticItems);
}
private void mergeMatchingItems() {
for (int i = 0; i < template.size(); i++) {
String item = template.get(i);
if (allImportOrderItems.contains(item)) {
// find matching items for order item
List<String> strings = matchingImports.get(item);
if (strings == null || strings.isEmpty()) {
// if there is none, just remove order item
template.remove(i);
i--;
continue;
}
List<String> matchingItems = new ArrayList<>(strings);
Collections.sort(matchingItems);
// replace order item by matching import statements
// this is a mess and it is only a luck that it works :-]
template.remove(i);
if (i != 0 && !template.get(i - 1).equals(ImportSorterStep.N)) {
template.add(i, ImportSorterStep.N);
i++;
}
if (i + 1 < template.size() && !template.get(i + 1).equals(ImportSorterStep.N)
&& !template.get(i).equals(ImportSorterStep.N)) {
template.add(i, ImportSorterStep.N);
}
template.addAll(i, matchingItems);
if (i != 0 && !template.get(i - 1).equals(ImportSorterStep.N)) {
template.add(i, ImportSorterStep.N);
}
}
}
// if there is \n on the end, remove it
if (template.size() > 0 && template.get(template.size() - 1).equals(ImportSorterStep.N)) {
template.remove(template.size() - 1);
}
}
private List<String> getResult() {
List<String> strings = new ArrayList<>();
for (String s : template) {
if (s.equals(ImportSorterStep.N)) {
strings.add(s);
} else {
strings.add("import " + s + ";" + ImportSorterStep.N);
}
}
return strings;
}
private static String betterMatching(String order1, String order2, String anImport) {
if (order1.equals(order2)) {
throw new IllegalArgumentException("orders are same");
}
for (int i = 0; i < anImport.length() - 1; i++) {
if (order1.length() - 1 == i && order2.length() - 1 != i) {
return order2;
}
if (order2.length() - 1 == i && order1.length() - 1 != i) {
return order1;
}
char orderChar1 = order1.length() != 0 ? order1.charAt(i) : ' ';
char orderChar2 = order2.length() != 0 ? order2.charAt(i) : ' ';
char importChar = anImport.charAt(i);
if (importChar == orderChar1 && importChar != orderChar2) {
return order1;
} else if (importChar != orderChar1 && importChar == orderChar2) {
return order2;
}
}
return null;
}
}
|
lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java
|
/*
* Copyright 2016 DiffPlug
*
* 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.diffplug.spotless.java;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
// From https://github.com/krasa/EclipseCodeFormatter
/*not thread safe*/
final class ImportSorterImpl {
private final List<String> template = new ArrayList<>();
private final Map<String, List<String>> matchingImports = new HashMap<>();
private final ArrayList<String> notMatching = new ArrayList<>();
private final Set<String> allImportOrderItems = new HashSet<>();
static List<String> sort(List<String> imports, List<String> importsOrder) {
ImportSorterImpl importsSorter = new ImportSorterImpl(importsOrder);
return importsSorter.sort(imports);
}
private List<String> sort(List<String> imports) {
filterMatchingImports(imports);
mergeNotMatchingItems(false);
mergeNotMatchingItems(true);
mergeMatchingItems();
return getResult();
}
private ImportSorterImpl(List<String> importOrder) {
List<String> importOrderCopy = new ArrayList<>(importOrder);
normalizeStaticOrderItems(importOrderCopy);
putStaticItemIfNotExists(importOrderCopy);
template.addAll(importOrderCopy);
this.allImportOrderItems.addAll(importOrderCopy);
}
private static void putStaticItemIfNotExists(List<String> allImportOrderItems) {
boolean contains = false;
int indexOfFirstStatic = 0;
for (int i = 0; i < allImportOrderItems.size(); i++) {
String allImportOrderItem = allImportOrderItems.get(i);
if (allImportOrderItem.equals("static ")) {
contains = true;
}
if (allImportOrderItem.startsWith("static ")) {
indexOfFirstStatic = i;
}
}
if (!contains) {
allImportOrderItems.add(indexOfFirstStatic, "static ");
}
}
private static void normalizeStaticOrderItems(List<String> allImportOrderItems) {
for (int i = 0; i < allImportOrderItems.size(); i++) {
String s = allImportOrderItems.get(i);
if (s.startsWith("\\#")) {
allImportOrderItems.set(i, s.replace("\\#", "static "));
}
}
}
/**
* returns not matching items and initializes internal state
*/
private void filterMatchingImports(List<String> imports) {
for (String anImport : imports) {
String orderItem = getBestMatchingImportOrderItem(anImport);
if (orderItem != null) {
if (!matchingImports.containsKey(orderItem)) {
matchingImports.put(orderItem, new ArrayList<>());
}
matchingImports.get(orderItem).add(anImport);
} else {
notMatching.add(anImport);
}
}
notMatching.addAll(allImportOrderItems);
}
private String getBestMatchingImportOrderItem(String anImport) {
String matchingImport = null;
for (String orderItem : allImportOrderItems) {
if (anImport.startsWith(orderItem)) {
if (matchingImport == null) {
matchingImport = orderItem;
} else {
matchingImport = betterMatching(matchingImport, orderItem, anImport);
}
}
}
return matchingImport;
}
/**
* not matching means it does not match any order item, so it will be appended before or after order items
*/
private void mergeNotMatchingItems(boolean staticItems) {
Collections.sort(notMatching);
int firstIndexOfOrderItem = getFirstIndexOfOrderItem(notMatching, staticItems);
int indexOfOrderItem = 0;
for (String notMatchingItem : notMatching) {
if (!matchesStatic(staticItems, notMatchingItem)) {
continue;
}
boolean isOrderItem = isOrderItem(notMatchingItem, staticItems);
if (isOrderItem) {
indexOfOrderItem = template.indexOf(notMatchingItem);
} else {
if (indexOfOrderItem == 0 && firstIndexOfOrderItem != 0) {
// insert before alphabetically first order item
template.add(firstIndexOfOrderItem, notMatchingItem);
firstIndexOfOrderItem++;
} else if (firstIndexOfOrderItem == 0) {
// no order is specified
if (template.size() > 0 && (template.get(template.size() - 1).startsWith("static"))) {
// insert N after last static import
template.add(ImportSorterStep.N);
}
template.add(notMatchingItem);
} else {
// insert after the previous order item
template.add(indexOfOrderItem + 1, notMatchingItem);
indexOfOrderItem++;
}
}
}
}
private boolean isOrderItem(String notMatchingItem, boolean staticItems) {
boolean contains = allImportOrderItems.contains(notMatchingItem);
return contains && matchesStatic(staticItems, notMatchingItem);
}
/**
* gets first order item from sorted input list, and finds out it's index in template.
*/
private int getFirstIndexOfOrderItem(List<String> notMatching, boolean staticItems) {
int firstIndexOfOrderItem = 0;
for (String notMatchingItem : notMatching) {
if (!matchesStatic(staticItems, notMatchingItem)) {
continue;
}
boolean isOrderItem = isOrderItem(notMatchingItem, staticItems);
if (isOrderItem) {
firstIndexOfOrderItem = template.indexOf(notMatchingItem);
break;
}
}
return firstIndexOfOrderItem;
}
private static boolean matchesStatic(boolean staticItems, String notMatchingItem) {
boolean isStatic = notMatchingItem.startsWith("static ");
return (isStatic && staticItems) || (!isStatic && !staticItems);
}
private void mergeMatchingItems() {
for (int i = 0; i < template.size(); i++) {
String item = template.get(i);
if (allImportOrderItems.contains(item)) {
// find matching items for order item
List<String> strings = matchingImports.get(item);
if (strings == null || strings.isEmpty()) {
// if there is none, just remove order item
template.remove(i);
i--;
continue;
}
List<String> matchingItems = new ArrayList<>(strings);
Collections.sort(matchingItems);
// replace order item by matching import statements
// this is a mess and it is only a luck that it works :-]
template.remove(i);
if (i != 0 && !template.get(i - 1).equals(ImportSorterStep.N)) {
template.add(i, ImportSorterStep.N);
i++;
}
if (i + 1 < template.size() && !template.get(i + 1).equals(ImportSorterStep.N)
&& !template.get(i).equals(ImportSorterStep.N)) {
template.add(i, ImportSorterStep.N);
}
template.addAll(i, matchingItems);
if (i != 0 && !template.get(i - 1).equals(ImportSorterStep.N)) {
template.add(i, ImportSorterStep.N);
}
}
}
// if there is \n on the end, remove it
if (template.size() > 0 && template.get(template.size() - 1).equals(ImportSorterStep.N)) {
template.remove(template.size() - 1);
}
}
private List<String> getResult() {
List<String> strings = new ArrayList<>();
for (String s : template) {
if (s.equals(ImportSorterStep.N)) {
strings.add(s);
} else {
strings.add("import " + s + ";" + ImportSorterStep.N);
}
}
return strings;
}
private static String betterMatching(String order1, String order2, String anImport) {
if (order1.equals(order2)) {
throw new IllegalArgumentException("orders are same");
}
for (int i = 0; i < anImport.length() - 1; i++) {
if (order1.length() - 1 == i && order2.length() - 1 != i) {
return order2;
}
if (order2.length() - 1 == i && order1.length() - 1 != i) {
return order1;
}
char orderChar1 = order1.length() != 0 ? order1.charAt(i) : ' ';
char orderChar2 = order2.length() != 0 ? order2.charAt(i) : ' ';
char importChar = anImport.charAt(i);
if (importChar == orderChar1 && importChar != orderChar2) {
return order1;
} else if (importChar != orderChar1 && importChar == orderChar2) {
return order2;
}
}
return null;
}
}
|
Performed minor polishing of code.
|
lib/src/main/java/com/diffplug/spotless/java/ImportSorterImpl.java
|
Performed minor polishing of code.
|
|
Java
|
apache-2.0
|
571745f8a879c23648d83824d401bd85eb5d543f
| 0
|
kantega/Flyt-cms,kantega/Flyt-cms,kantega/Flyt-cms
|
/*
* Copyright 2009 Kantega AS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package no.kantega.commons.util;
import no.kantega.commons.log.Log;
import java.util.*;
public class LocaleLabels {
static public String DEFAULT_BUNDLE = "TextLabels";
private static Map bundles = new HashMap();
private static PropertyResourceBundle getBundle(String bundleName, String locale) {
PropertyResourceBundle bundle = null;
synchronized (bundles) {
bundle = (PropertyResourceBundle)bundles.get(bundleName + "_" + locale);
if (bundle == null) {
String[] locArr = locale.split("_");
try {
if (locArr.length > 2) {
bundle = (PropertyResourceBundle)ResourceBundle.getBundle(bundleName, new Locale(locArr[0], locArr[1], locArr[2]));
} else {
bundle = (PropertyResourceBundle)ResourceBundle.getBundle(bundleName, new Locale(locArr[0], locArr[1]));
}
bundles.put(bundleName + "_" + locale, bundle);
} catch (MissingResourceException e) {
Log.error("LocaleLabels", e, null, null);
}
}
}
return bundle;
}
private static String getLabel(String key, String bundleName, String locale, Map parameters) {
String msg = key;
PropertyResourceBundle bundle = getBundle(bundleName, locale);
if (bundle == null) {
return msg;
}
try {
msg = bundle.getString(key);
} catch (MissingResourceException e) {
// Do nothing
}
if (parameters != null) {
Iterator paramNames = parameters.keySet().iterator();
while (paramNames.hasNext()) {
String pName = (String)paramNames.next();
Object pValue = parameters.get(pName);
if (pValue != null) {
msg = msg.replaceAll("\\$\\{" + pName + "\\}", pValue.toString());
}
}
}
return msg;
}
/**
* Get label from bundle with specified locale
* @param key - key to look up
* @param bundleName - bundle (property-file) to use
* @param locale - locale
* @return - localized string
*/
public static String getLabel(String key, String bundleName, Locale locale) {
String loc = locale.getLanguage() + "_" + locale.getCountry();
if (locale.getVariant() != null) {
loc += "_" + locale.getVariant();
}
return getLabel(key, bundleName, loc, null);
}
/**
* Get label from bundle with specified locale, replaces parameters found in string
* @param key - key to look up
* @param bundleName - bundle (property-file) to use
* @param locale - locale
* @param parameters - parameters
* @return - localized string
*/
public static String getLabel(String key, String bundleName, Locale locale, Map parameters) {
String loc = locale.getLanguage() + "_" + locale.getCountry();
if (locale.getVariant() != null) {
loc += "_" + locale.getVariant();
}
return getLabel(key, bundleName, loc, parameters);
}
/**
* Get label from default bundle with specified locale
* @param key - key to look up
* @param locale - locale
* @return - localized string
*/
public static String getLabel(String key, Locale locale) {
return getLabel(key, DEFAULT_BUNDLE, locale, null);
}
/**
* Get label from default bundle with specified locale, replaces parameters found in string
* @param key - key to look up
* @param locale - locale
* @param parameters - parameters
* @return - localized string
*/
public static String getLabel(String key, Locale locale, Map parameters) {
return getLabel(key, DEFAULT_BUNDLE, locale, parameters);
}
public static Enumeration getKeys(String bundleName, Locale locale) {
String loc = locale.getLanguage() + "_" + locale.getCountry();
if (locale.getVariant() != null) {
loc += "_" + locale.getVariant();
}
PropertyResourceBundle bundle = getBundle(bundleName, loc);
if (bundle == null) {
return null;
}
return bundle.getKeys();
}
}
|
modules/commons/src/java/no/kantega/commons/util/LocaleLabels.java
|
/*
* Copyright 2009 Kantega AS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package no.kantega.commons.util;
import no.kantega.commons.log.Log;
import java.util.*;
public class LocaleLabels {
static public String DEFAULT_BUNDLE = "TextLabels";
private static Map bundles = new HashMap();
private static PropertyResourceBundle getBundle(String bundleName, String locale) {
PropertyResourceBundle bundle = null;
synchronized (bundles) {
bundle = (PropertyResourceBundle)bundles.get(bundleName + "_" + locale);
if (bundle == null) {
String[] locArr = locale.split("_");
try {
if (locArr.length > 2) {
bundle = (PropertyResourceBundle)ResourceBundle.getBundle(bundleName, new Locale(locArr[0], locArr[1], locArr[2]));
} else {
bundle = (PropertyResourceBundle)ResourceBundle.getBundle(bundleName, new Locale(locArr[0], locArr[1]));
}
bundles.put(bundleName + "_" + locale, bundle);
} catch (MissingResourceException e) {
Log.error("LocaleLabels", e, null, null);
}
}
}
return bundle;
}
private static String getLabel(String key, String bundleName, String locale, Map parameters) {
String msg = key;
PropertyResourceBundle bundle = getBundle(bundleName, locale);
if (bundle == null) {
return msg;
}
try {
msg = bundle.getString(key);
} catch (MissingResourceException e) {
// Do nothing
}
if (parameters != null) {
Iterator paramNames = parameters.keySet().iterator();
while (paramNames.hasNext()) {
String pName = (String)paramNames.next();
msg = msg.replaceAll("\\$\\{" + pName + "\\}", parameters.get(pName).toString());
}
}
return msg;
}
/**
* Get label from bundle with specified locale
* @param key - key to look up
* @param bundleName - bundle (property-file) to use
* @param locale - locale
* @return - localized string
*/
public static String getLabel(String key, String bundleName, Locale locale) {
String loc = locale.getLanguage() + "_" + locale.getCountry();
if (locale.getVariant() != null) {
loc += "_" + locale.getVariant();
}
return getLabel(key, bundleName, loc, null);
}
/**
* Get label from bundle with specified locale, replaces parameters found in string
* @param key - key to look up
* @param bundleName - bundle (property-file) to use
* @param locale - locale
* @param parameters - parameters
* @return - localized string
*/
public static String getLabel(String key, String bundleName, Locale locale, Map parameters) {
String loc = locale.getLanguage() + "_" + locale.getCountry();
if (locale.getVariant() != null) {
loc += "_" + locale.getVariant();
}
return getLabel(key, bundleName, loc, parameters);
}
/**
* Get label from default bundle with specified locale
* @param key - key to look up
* @param locale - locale
* @return - localized string
*/
public static String getLabel(String key, Locale locale) {
return getLabel(key, DEFAULT_BUNDLE, locale, null);
}
/**
* Get label from default bundle with specified locale, replaces parameters found in string
* @param key - key to look up
* @param locale - locale
* @param parameters - parameters
* @return - localized string
*/
public static String getLabel(String key, Locale locale, Map parameters) {
return getLabel(key, DEFAULT_BUNDLE, locale, parameters);
}
public static Enumeration getKeys(String bundleName, Locale locale) {
String loc = locale.getLanguage() + "_" + locale.getCountry();
if (locale.getVariant() != null) {
loc += "_" + locale.getVariant();
}
PropertyResourceBundle bundle = getBundle(bundleName, loc);
if (bundle == null) {
return null;
}
return bundle.getKeys();
}
}
|
AP-1271
git-svn-id: 8def386c603904b39326d3fc08add479b8279298@3085 fd808399-8219-4f14-9d4c-37719d9ec93d
|
modules/commons/src/java/no/kantega/commons/util/LocaleLabels.java
|
AP-1271
|
|
Java
|
apache-2.0
|
cd725b9eaf74df8aa6b7194616cf1f26de5fb8a8
| 0
|
fge/grappa,fge/grappa
|
/*
* Copyright (C) 2014 Francis Galiegue <fgaliegue@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.parboiled1.grappa.matchers.join;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import org.parboiled.MatcherContext;
import org.parboiled.Rule;
import org.parboiled.errors.GrammarException;
import org.parboiled.matchers.CustomDefaultLabelMatcher;
import org.parboiled.matchers.Matcher;
import org.parboiled.matchervisitors.CanMatchEmptyVisitor;
import org.parboiled.matchervisitors.MatcherVisitor;
/**
* A joining matcher
*
* <p>Such a matcher has two submatchers: a "joined" matcher and a "joining"
* matcher.</p>
*
* <p>This matcher will run cycles through both of these; the first will be a
* run of the "joined" matcher, subsequent cycles will be ("joining", "joined").
* </p>
*
* <p>Therefore:</p>
*
* <ul>
* <li>one cycle is {@code joined};</li>
* <li>two cycles is {@code joined, joining, joined};</li>
* <li>etc etc.</li>
* </ul>
*
* <p>This matcher will correctly reset the index to the last successful
* match; for instance, if the match sequence is {@code joined, joining, joined,
* joining} and two cycles are enough, it will reset the index to before the
* last {@code joining} so that subsequent matchers can proceed from there.</p>
*
* <p>It is <strong>forbidden</strong> for the "joining" matcher to match an
* empty sequence. Unfortunately, due to current limitations, this can only
* be detected at runtime (but also by the {@link CanMatchEmptyVisitor} when
* used).</p>
*
* <p>This matcher is not built directly; its build is initiated by a {@link
* JoinMatcherBootstrap}. Using the {@code JoinParser} base parser mentioned
* above, here is how you would, for instance, build a rule where you want a
* sequence of three digits separated by dots:</p>
*
* <pre>
* Rule threeDigitsExactly()
* {
* return join(digit()).using('.').times(3);
* }
* </pre>
*
* @see JoinMatcherBootstrap
*/
@Beta
public abstract class JoinMatcher
extends CustomDefaultLabelMatcher<JoinMatcher>
{
private static final int JOINED_CHILD_INDEX = 0;
private static final int JOINING_CHILD_INDEX = 1;
protected final Matcher joined;
protected final Matcher joining;
protected JoinMatcher(final Rule joined, final Rule joining)
{
super(new Rule[] { joined, joining }, "join");
this.joined = getChildren().get(JOINED_CHILD_INDEX);
this.joining = getChildren().get(JOINING_CHILD_INDEX);
}
public final Matcher getJoined()
{
return joined;
}
public final Matcher getJoining()
{
return joining;
}
/**
* Accepts the given matcher visitor.
*
* @param visitor the visitor
* @return the value returned by the given visitor
*/
@Override
public final <R> R accept(final MatcherVisitor<R> visitor)
{
Preconditions.checkNotNull(visitor);
return visitor.visit(this);
}
/**
* Tries a match on the given MatcherContext.
*
* @param context the MatcherContext
* @return true if the match was successful
*/
@Override
public final <V> boolean match(final MatcherContext<V> context)
{
/*
* TODO! Check logic
*
* At this point, if we have enough cycles, we can't determined whether
* our joining rule would match empty... Which is illegal.
*/
int cycles = 0;
if (!joined.getSubContext(context).runMatcher()) {
if (!enoughCycles(cycles))
return false;
context.createNode();
return true;
}
cycles++;
Object snapshot = context.getValueStack().takeSnapshot();
int beforeCycle = context.getCurrentIndex();
while (runAgain(cycles) && matchCycle(context, beforeCycle)) {
beforeCycle = context.getCurrentIndex();
snapshot = context.getValueStack().takeSnapshot();
cycles++;
}
context.getValueStack().restoreSnapshot(snapshot);
context.setCurrentIndex(beforeCycle);
if (!enoughCycles(cycles))
return false;
context.createNode();
return true;
}
protected abstract boolean runAgain(final int cycles);
protected abstract boolean enoughCycles(final int cycles);
protected final <V> boolean matchCycle(final MatcherContext<V> context,
final int beforeCycle)
{
if (!joining.getSubContext(context).runMatcher())
return false;
if (context.getCurrentIndex() == beforeCycle)
throw new GrammarException("joining rule (%s) of a JoinMatcher" +
" cannot match an empty character sequence!", joining);
return joined.getSubContext(context).runMatcher();
}
}
|
src/main/java/com/github/parboiled1/grappa/matchers/join/JoinMatcher.java
|
/*
* Copyright (C) 2014 Francis Galiegue <fgaliegue@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.parboiled1.grappa.matchers.join;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import org.parboiled.MatcherContext;
import org.parboiled.Rule;
import org.parboiled.errors.GrammarException;
import org.parboiled.matchers.CustomDefaultLabelMatcher;
import org.parboiled.matchers.Matcher;
import org.parboiled.matchervisitors.CanMatchEmptyVisitor;
import org.parboiled.matchervisitors.MatcherVisitor;
/**
* A joining matcher
*
* <p>Such a matcher has two submatchers: a "joined" matcher and a "joining"
* matcher.</p>
*
* <p>This matcher will run cycles through both of these; the first will be a
* run of the "joined" matcher, subsequent cycles will be ("joining", "joined").
* </p>
*
* <p>Therefore:</p>
*
* <ul>
* <li>one cycle is {@code joined};</li>
* <li>two cycles is {@code joined, joining, joined};</li>
* <li>etc etc.</li>
* </ul>
*
* <p>This matcher will correctly reset the index to the last successful
* match; for instance, if the match sequence is {@code joined, joining, joined,
* joining} and two cycles are enough, it will reset the index to before the
* last {@code joining} so that subsequent matchers can proceed from there.</p>
*
* <p>It is <strong>forbidden</strong> for the "joining" matcher to match an
* empty sequence. Unfortunately, due to current limitations, this can only
* be detected at runtime (but also by the {@link CanMatchEmptyVisitor} when
* used).</p>
*
* <p>This matcher is not built directly; its build is initiated by a {@link
* JoinMatcherBootstrap}. Using the {@code JoinParser} base parser mentioned
* above, here is how you would, for instance, build a rule where you want a
* sequence of three digits separated by dots:</p>
*
* <pre>
* Rule threeDigitsExactly()
* {
* return join(digit()).using('.').times(3);
* }
* </pre>
*
* @see JoinMatcherBootstrap
*/
@Beta
public abstract class JoinMatcher
extends CustomDefaultLabelMatcher<JoinMatcher>
{
private static final int JOINED_CHILD_INDEX = 0;
private static final int JOINING_CHILD_INDEX = 1;
protected final Matcher joined;
protected final Matcher joining;
protected JoinMatcher(final Rule joined, final Rule joining)
{
super(new Rule[] { joined, joining }, "Join");
this.joined = getChildren().get(JOINED_CHILD_INDEX);
this.joining = getChildren().get(JOINING_CHILD_INDEX);
}
public final Matcher getJoined()
{
return joined;
}
public final Matcher getJoining()
{
return joining;
}
/**
* Accepts the given matcher visitor.
*
* @param visitor the visitor
* @return the value returned by the given visitor
*/
@Override
public final <R> R accept(final MatcherVisitor<R> visitor)
{
Preconditions.checkNotNull(visitor);
return visitor.visit(this);
}
/**
* Tries a match on the given MatcherContext.
*
* @param context the MatcherContext
* @return true if the match was successful
*/
@Override
public final <V> boolean match(final MatcherContext<V> context)
{
/*
* TODO! Check logic
*
* At this point, if we have enough cycles, we can't determined whether
* our joining rule would match empty... Which is illegal.
*/
int cycles = 0;
if (!joined.getSubContext(context).runMatcher()) {
if (!enoughCycles(cycles))
return false;
context.createNode();
return true;
}
cycles++;
Object snapshot = context.getValueStack().takeSnapshot();
int beforeCycle = context.getCurrentIndex();
while (runAgain(cycles) && matchCycle(context, beforeCycle)) {
beforeCycle = context.getCurrentIndex();
snapshot = context.getValueStack().takeSnapshot();
cycles++;
}
context.getValueStack().restoreSnapshot(snapshot);
context.setCurrentIndex(beforeCycle);
if (!enoughCycles(cycles))
return false;
context.createNode();
return true;
}
protected abstract boolean runAgain(final int cycles);
protected abstract boolean enoughCycles(final int cycles);
protected final <V> boolean matchCycle(final MatcherContext<V> context,
final int beforeCycle)
{
if (!joining.getSubContext(context).runMatcher())
return false;
if (context.getCurrentIndex() == beforeCycle)
throw new GrammarException("joining rule (%s) of a JoinMatcher" +
" cannot match an empty character sequence!", joining);
return joined.getSubContext(context).runMatcher();
}
}
|
Lowercase: join
|
src/main/java/com/github/parboiled1/grappa/matchers/join/JoinMatcher.java
|
Lowercase: join
|
|
Java
|
apache-2.0
|
bdf753ef0a289b00446754dd81994f5c0669e3fa
| 0
|
TDesjardins/gwt-ol3,TDesjardins/GWT-OL3-Playground,TDesjardins/gwt-ol3,sebasbaumh/gwt-ol3,TDesjardins/GWT-OL3-Playground,sebasbaumh/gwt-ol3,TDesjardins/gwt-ol3,sebasbaumh/gwt-ol3,TDesjardins/GWT-OL3-Playground
|
/*******************************************************************************
* Copyright 2014, 2017 gwt-ol3
*
* 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.github.tdesjardins.ol3.demo.client.example;
import com.github.tdesjardins.ol3.demo.client.utils.DemoUtils;
import com.google.gwt.core.client.JavaScriptObject;
import ol.Collection;
import ol.Coordinate;
import ol.Feature;
import ol.FeatureOptions;
import ol.Map;
import ol.MapOptions;
import ol.OLFactory;
import ol.View;
import ol.control.Rotate;
import ol.control.ScaleLine;
import ol.format.GeoJson;
import ol.geom.LineString;
import ol.interaction.KeyboardPan;
import ol.interaction.KeyboardZoom;
import ol.layer.Base;
import ol.layer.LayerOptions;
import ol.layer.Tile;
import ol.layer.VectorLayerOptions;
import ol.source.Osm;
import ol.source.Vector;
import ol.source.VectorOptions;
import ol.source.XyzOptions;
/**
* Example of GeoJSON format.
*
* @author Tobias Lochmann
*/
public class GeoJsonExample implements Example {
/* (non-Javadoc)
* @see de.desjardins.ol3.demo.client.example.Example#show() */
@Override
public void show(String exampleId) {
// create linestring
Coordinate coordinate1 = OLFactory.createCoordinate(4e6, 2e6);
Coordinate coordinate2 = OLFactory.createCoordinate(8e6, -2e6);
Coordinate[] coordinates = { coordinate1, coordinate2 };
LineString lineString = new LineString(coordinates);
// create feature
FeatureOptions featureOptions = new FeatureOptions();
featureOptions.setGeometry(lineString);
Feature feature = new Feature(featureOptions);
// convert feature to GeoJSON
GeoJson geoJsonFormat = new GeoJson();
JavaScriptObject geoJson = geoJsonFormat.writeFeatureObject(feature, null);
// convert features from GeoJSON
Feature featureGeoJson = geoJsonFormat.readFeature(geoJson, null);
// show converted features
Collection<Feature> lstFeatures = new Collection<Feature>();
lstFeatures.push(featureGeoJson);
VectorOptions vectorSourceOptions = new VectorOptions();
vectorSourceOptions.setFeatures(lstFeatures);
Vector vectorSource = new Vector(vectorSourceOptions);
VectorLayerOptions vectorLayerOptions = new VectorLayerOptions();
vectorLayerOptions.setSource(vectorSource);
ol.layer.Vector vectorLayer = new ol.layer.Vector(vectorLayerOptions);
// create a OSM-layer
XyzOptions osmSourceOptions = new XyzOptions();
Osm osmSource = new Osm(osmSourceOptions);
LayerOptions osmLayerOptions = new LayerOptions();
osmLayerOptions.setSource(osmSource);
Tile osmLayer = new Tile(osmLayerOptions);
// create a view
View view = new View();
Coordinate centerCoordinate = OLFactory.createCoordinate(0, 0);
view.setCenter(centerCoordinate);
view.setZoom(2);
// create the map
MapOptions mapOptions = new MapOptions();
mapOptions.setTarget(exampleId);
mapOptions.setView(view);
Collection<Base> lstLayer = new Collection<Base>();
lstLayer.push(osmLayer);
lstLayer.push(vectorLayer);
mapOptions.setLayers(lstLayer);
Map map = new Map(mapOptions);
// add some controls
map.addControl(new ScaleLine());
DemoUtils.addDefaultControls(map.getControls());
// add some interactions
map.addInteraction(new KeyboardPan());
map.addInteraction(new KeyboardZoom());
map.addControl(new Rotate());
}
}
|
gwt-ol3-demo/src/main/java/com/github/tdesjardins/ol3/demo/client/example/GeoJsonExample.java
|
/*******************************************************************************
* Copyright 2014, 2017 gwt-ol3
*
* 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.github.tdesjardins.ol3.demo.client.example;
import com.github.tdesjardins.ol3.demo.client.utils.DemoUtils;
import com.google.gwt.core.client.JavaScriptObject;
import ol.Collection;
import ol.Coordinate;
import ol.Feature;
import ol.FeatureOptions;
import ol.Map;
import ol.MapOptions;
import ol.OLFactory;
import ol.View;
import ol.control.Rotate;
import ol.control.ScaleLine;
import ol.format.GeoJson;
import ol.geom.LineString;
import ol.interaction.KeyboardPan;
import ol.interaction.KeyboardZoom;
import ol.layer.Base;
import ol.layer.LayerOptions;
import ol.layer.Tile;
import ol.layer.VectorLayerOptions;
import ol.source.Osm;
import ol.source.Vector;
import ol.source.VectorOptions;
import ol.source.XyzOptions;
/**
* Example of GeoJSON format.
*
* @author Tobias Lochmann
*/
public class GeoJsonExample implements Example {
/* (non-Javadoc)
* @see de.desjardins.ol3.demo.client.example.Example#show() */
@Override
public void show(String exampleId) {
// create linestring
Coordinate coordinate1 = OLFactory.createCoordinate(4e6, 2e6);
Coordinate coordinate2 = OLFactory.createCoordinate(8e6, -2e6);
Coordinate[] coordinates = { coordinate1, coordinate2 };
LineString lineString = new LineString(coordinates);
// create feature
FeatureOptions featureOptions = OLFactory.createOptions();
featureOptions.setGeometry(lineString);
Feature feature = new Feature(featureOptions);
// convert feature to GeoJSON
GeoJson geoJsonFormat = new GeoJson();
JavaScriptObject geoJson = geoJsonFormat.writeFeatureObject(feature, null);
// convert features from GeoJSON
Feature featureGeoJson = geoJsonFormat.readFeature(geoJson, null);
// show converted features
Collection<Feature> lstFeatures = new Collection<Feature>();
lstFeatures.push(featureGeoJson);
VectorOptions vectorSourceOptions = OLFactory.createOptions();
vectorSourceOptions.setFeatures(lstFeatures);
Vector vectorSource = new Vector(vectorSourceOptions);
VectorLayerOptions vectorLayerOptions = OLFactory.createOptions();
vectorLayerOptions.setSource(vectorSource);
ol.layer.Vector vectorLayer = new ol.layer.Vector(vectorLayerOptions);
// create a OSM-layer
XyzOptions osmSourceOptions = OLFactory.createOptions();
Osm osmSource = new Osm(osmSourceOptions);
LayerOptions osmLayerOptions = OLFactory.createOptions();
osmLayerOptions.setSource(osmSource);
Tile osmLayer = new Tile(osmLayerOptions);
// create a view
View view = new View();
Coordinate centerCoordinate = OLFactory.createCoordinate(0, 0);
view.setCenter(centerCoordinate);
view.setZoom(2);
// create the map
MapOptions mapOptions = new MapOptions();
mapOptions.setTarget(exampleId);
mapOptions.setView(view);
Collection<Base> lstLayer = new Collection<Base>();
lstLayer.push(osmLayer);
lstLayer.push(vectorLayer);
mapOptions.setLayers(lstLayer);
Map map = new Map(mapOptions);
// add some controls
map.addControl(new ScaleLine());
DemoUtils.addDefaultControls(map.getControls());
// add some interactions
map.addInteraction(new KeyboardPan());
map.addInteraction(new KeyboardZoom());
map.addControl(new Rotate());
}
}
|
Use constructors
|
gwt-ol3-demo/src/main/java/com/github/tdesjardins/ol3/demo/client/example/GeoJsonExample.java
|
Use constructors
|
|
Java
|
apache-2.0
|
b41661cca4c2928dd69725221ef3d415fda71130
| 0
|
RanjithKumar5550/RanMifos,Vishwa1311/incubator-fineract,RanjithKumar5550/RanMifos,Vishwa1311/incubator-fineract,Vishwa1311/incubator-fineract,RanjithKumar5550/RanMifos
|
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.dataqueries.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
@Table(name = "stretchy_report", uniqueConstraints = { @UniqueConstraint(columnNames = { "report_name" }, name = "unq_report_name") })
public class Report extends AbstractPersistable<Long> {
@Column(name = "report_name", nullable = false, unique = true)
private String reportName;
@Column(name = "report_type", nullable = false)
private String reportType;
@Column(name = "report_subtype")
private String reportSubType;
@Column(name = "report_category")
private String reportCategory;
@Column(name = "description")
private String description;
@Column(name = "core_report", nullable = false)
private boolean core_Report;
//only defines if report should appear in reference app UI List
@Column(name = "use_report", nullable = false)
private boolean useReport;
@Column(name = "report_sql")
private String reportSql;
/*
@ManyToMany
@JoinTable(name = "stretchy_report_parameter", joinColumns = @JoinColumn(name = "reportn_id"), inverseJoinColumns = @JoinColumn(name = "parameter_id"))
private List<Charge> charges;
*/
public Report(final String reportName, final String reportType, final String reportSubType, final String reportCategory, final String description,
final boolean core_Report, final boolean useReport, final String reportSql) {
this.reportName = reportName;
this.reportType = reportType;
this.reportSubType = reportSubType;
this.reportCategory = reportCategory;
this.description = description;
this.core_Report = core_Report;
this.useReport = useReport;
this.reportSql = reportSql;
}
public String getReportName() {
return reportName;
}
public void setReportName(String reportName) {
this.reportName = reportName;
}
public String getReportType() {
return reportType;
}
public void setReportType(String reportType) {
this.reportType = reportType;
}
public String getReportSubType() {
return reportSubType;
}
public void setReportSubType(String reportSubType) {
this.reportSubType = reportSubType;
}
public String getReportCategory() {
return reportCategory;
}
public void setReportCategory(String reportCategory) {
this.reportCategory = reportCategory;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isCore_Report() {
return core_Report;
}
public void setCore_Report(boolean core_Report) {
this.core_Report = core_Report;
}
public boolean isUseReport() {
return useReport;
}
public void setUseReport(boolean useReport) {
this.useReport = useReport;
}
public String getReportSql() {
return reportSql;
}
public void setReportSql(String reportSql) {
this.reportSql = reportSql;
}
}
|
mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/Report.java
|
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.dataqueries.domain;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency;
import org.mifosplatform.organisation.monetary.domain.Money;
import org.mifosplatform.portfolio.charge.domain.Charge;
import org.mifosplatform.portfolio.fund.domain.Fund;
import org.mifosplatform.portfolio.loanaccount.loanschedule.domain.AprCalculator;
import org.springframework.data.jpa.domain.AbstractPersistable;
import com.google.gson.JsonArray;
/*
@Entity
@Table(name = "stretchy_report", uniqueConstraints = { @UniqueConstraint(columnNames = { "report_name" }, name = "unq_report_name") })
public class Report extends AbstractPersistable<Long> {
@Column(name = "report_name", nullable = false, unique = true)
private String reportName;
@Column(name = "report_type", nullable = false)
private String reportType;
@Column(name = "report_subtype")
private String reportSubType;
@Column(name = "report_category")
private String reportCategory;
@Column(name = "description")
private String description;
@Column(name = "core_report", nullable = false)
private boolean core_Report;
//only defines if report should appear in reference app UI List
@Column(name = "use_report", nullable = false)
private boolean useReport;
@Column(name = "report_sql")
private String reportSql;
@ManyToMany
@JoinTable(name = "stretchy_report_parameter", joinColumns = @JoinColumn(name = "product_loan_id"), inverseJoinColumns = @JoinColumn(name = "charge_id"))
private List<Charge> charges;
public static Report assembleFromJson(final Fund fund, final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy,
final List<Charge> productCharges, final JsonCommand command, final AprCalculator aprCalculator) {
final String name = command.stringValueOfParameterNamed("name");
final String description = command.stringValueOfParameterNamed("description");
final String currencyCode = command.stringValueOfParameterNamed("currencyCode");
final Integer digitsAfterDecimal = command.integerValueOfParameterNamed("digitsAfterDecimal");
final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal);
final BigDecimal principal = command.bigDecimalValueOfParameterNamed("principal");
final BigDecimal minPrincipal = command.bigDecimalValueOfParameterNamed("minPrincipal");
final BigDecimal maxPrincipal = command.bigDecimalValueOfParameterNamed("maxPrincipal");
final InterestMethod interestMethod = InterestMethod.fromInt(command.integerValueOfParameterNamed("interestType"));
final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.fromInt(command
.integerValueOfParameterNamed("interestCalculationPeriodType"));
final AmortizationMethod amortizationMethod = AmortizationMethod.fromInt(command.integerValueOfParameterNamed("amortizationType"));
final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.fromInt(command
.integerValueOfParameterNamed("repaymentFrequencyType"));
final PeriodFrequencyType interestFrequencyType = PeriodFrequencyType.fromInt(command
.integerValueOfParameterNamed("interestRateFrequencyType"));
final BigDecimal interestRatePerPeriod = command.bigDecimalValueOfParameterNamed("interestRatePerPeriod");
final BigDecimal minInterestRatePerPeriod = command.bigDecimalValueOfParameterNamed("minInterestRatePerPeriod");
final BigDecimal maxInterestRatePerPeriod = command.bigDecimalValueOfParameterNamed("maxInterestRatePerPeriod");
final BigDecimal annualInterestRate = aprCalculator.calculateFrom(interestFrequencyType, interestRatePerPeriod);
final Integer repaymentEvery = command.integerValueOfParameterNamed("repaymentEvery");
final Integer numberOfRepayments = command.integerValueOfParameterNamed("numberOfRepayments");
final Integer minNumberOfRepayments = command.integerValueOfParameterNamed("minNumberOfRepayments");
final Integer maxNumberOfRepayments = command.integerValueOfParameterNamed("maxNumberOfRepayments");
final BigDecimal inArrearsTolerance = command.bigDecimalValueOfParameterNamed("inArrearsTolerance");
final AccountingRuleType accountingRuleType = AccountingRuleType.fromInt(command.integerValueOfParameterNamed("accountingRule"));
return new Report(fund, loanTransactionProcessingStrategy, name, description, currency, principal, minPrincipal, maxPrincipal,
interestRatePerPeriod, minInterestRatePerPeriod, maxInterestRatePerPeriod, interestFrequencyType, annualInterestRate, interestMethod, interestCalculationPeriodMethod,
repaymentEvery, repaymentFrequencyType, numberOfRepayments, minNumberOfRepayments, maxNumberOfRepayments, amortizationMethod, inArrearsTolerance, productCharges,
accountingRuleType);
}
protected Report() {
this.loanProductRelatedDetail = null;
this.loanProductMinMaxConstraints = null;
}
public Report(final Fund fund, final LoanTransactionProcessingStrategy transactionProcessingStrategy, final String name,
final String description, final MonetaryCurrency currency, final BigDecimal defaultPrincipal,
final BigDecimal defaultMinPrincipal, final BigDecimal defaultMaxPrincipal,
final BigDecimal defaultNominalInterestRatePerPeriod, final BigDecimal defaultMinNominalInterestRatePerPeriod,
final BigDecimal defaultMaxNominalInterestRatePerPeriod, final PeriodFrequencyType interestPeriodFrequencyType,
final BigDecimal defaultAnnualNominalInterestRate, final InterestMethod interestMethod,
final InterestCalculationPeriodMethod interestCalculationPeriodMethod, final Integer repayEvery,
final PeriodFrequencyType repaymentFrequencyType, final Integer defaultNumberOfInstallments,
final Integer defaultMinNumberOfInstallments, final Integer defaultMaxNumberOfInstallments,
final AmortizationMethod amortizationMethod, final BigDecimal inArrearsTolerance, final List<Charge> charges,
final AccountingRuleType accountingRuleType) {
this.fund = fund;
this.transactionProcessingStrategy = transactionProcessingStrategy;
this.name = name.trim();
if (StringUtils.isNotBlank(description)) {
this.description = description.trim();
} else {
this.description = null;
}
if (charges != null) {
this.charges = charges;
}
this.loanProductRelatedDetail = new LoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod,
interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, repayEvery,
repaymentFrequencyType, defaultNumberOfInstallments, amortizationMethod, inArrearsTolerance);
this.loanProductMinMaxConstraints = new LoanProductMinMaxConstraints(defaultMinPrincipal, defaultMaxPrincipal,
defaultMinNominalInterestRatePerPeriod, defaultMaxNominalInterestRatePerPeriod, defaultMinNumberOfInstallments,
defaultMaxNumberOfInstallments);
if (accountingRuleType != null) {
this.accountingRule = accountingRuleType.getValue();
}
}
public MonetaryCurrency getCurrency() {
return this.loanProductRelatedDetail.getCurrency();
}
public boolean update(final List<Charge> newProductCharges) {
boolean updated = false;
if (this.charges != null) {
final Set<Charge> setOfCharges = new HashSet<Charge>(this.charges);
updated = setOfCharges.addAll(newProductCharges);
if (updated) {
this.charges = newProductCharges;
}
}
return updated;
}
public Integer getAccountingType() {
return this.accountingRule;
}
public Map<String, Object> update(final JsonCommand command, final AprCalculator aprCalculator) {
final Map<String, Object> actualChanges = this.loanProductRelatedDetail.update(command, aprCalculator);
actualChanges.putAll(this.loanProductMinMaxConstraints().update(command));
final String accountingTypeParamName = "accountingRule";
if (command.isChangeInIntegerParameterNamed(accountingTypeParamName, this.accountingRule)) {
final Integer newValue = command.integerValueOfParameterNamed(accountingTypeParamName);
actualChanges.put(accountingTypeParamName, newValue);
this.accountingRule = newValue;
}
final String nameParamName = "name";
if (command.isChangeInStringParameterNamed(nameParamName, this.name)) {
final String newValue = command.stringValueOfParameterNamed(nameParamName);
actualChanges.put(nameParamName, newValue);
this.name = newValue;
}
final String descriptionParamName = "description";
if (command.isChangeInStringParameterNamed(descriptionParamName, this.description)) {
final String newValue = command.stringValueOfParameterNamed(descriptionParamName);
actualChanges.put(descriptionParamName, newValue);
this.description = newValue;
}
Long existingFundId = null;
if (this.fund != null) {
existingFundId = this.fund.getId();
}
final String fundIdParamName = "fundId";
if (command.isChangeInLongParameterNamed(fundIdParamName, existingFundId)) {
final Long newValue = command.longValueOfParameterNamed(fundIdParamName);
actualChanges.put(fundIdParamName, newValue);
}
Long existingStrategyId = null;
if (this.transactionProcessingStrategy != null) {
existingStrategyId = this.transactionProcessingStrategy.getId();
}
final String transactionProcessingStrategyParamName = "transactionProcessingStrategyId";
if (command.isChangeInLongParameterNamed(transactionProcessingStrategyParamName, existingStrategyId)) {
final Long newValue = command.longValueOfParameterNamed(transactionProcessingStrategyParamName);
actualChanges.put(transactionProcessingStrategyParamName, newValue);
}
final String chargesParamName = "charges";
if (command.hasParameter(chargesParamName)) {
JsonArray jsonArray = command.arrayOfParameterNamed(chargesParamName);
if (jsonArray != null) {
}
actualChanges.put(chargesParamName, command.jsonFragment(chargesParamName));
}
return actualChanges;
}
public boolean isCashBasedAccountingEnabled() {
return AccountingRuleType.CASH_BASED.getValue().equals(this.accountingRule);
}
public boolean isAccrualBasedAccountingEnabled() {
return AccountingRuleType.ACCRUAL_BASED.getValue().equals(this.accountingRule);
}
public Money getPrincipalAmount(){
return this.loanProductRelatedDetail.getPrincipal();
}
public Money getMinPrincipalAmount(){
return Money.of(this.loanProductRelatedDetail.getCurrency(), this.loanProductMinMaxConstraints().getMinPrincipal());
}
public Money getMaxPrincipalAmount(){
return Money.of(this.loanProductRelatedDetail.getCurrency(), this.loanProductMinMaxConstraints().getMaxPrincipal());
}
public BigDecimal getNominalInterestRatePerPeriod() {
return this.loanProductRelatedDetail.getNominalInterestRatePerPeriod();
}
public BigDecimal getMinNominalInterestRatePerPeriod() {
return this.loanProductMinMaxConstraints().getMinNominalInterestRatePerPeriod();
}
public BigDecimal getMaxNominalInterestRatePerPeriod(){
return this.loanProductMinMaxConstraints().getMaxNominalInterestRatePerPeriod();
}
public Integer getNumberOfRepayments(){
return this.loanProductRelatedDetail().getNumberOfRepayments();
}
public Integer getMinNumberOfRepayments() {
return this.loanProductMinMaxConstraints().getMinNumberOfRepayments();
}
public Integer getMaxNumberOfRepayments() {
return this.loanProductMinMaxConstraints().getMaxNumberOfRepayments();
}
public LoanProductRelatedDetail loanProductRelatedDetail(){
return this.loanProductRelatedDetail;
}
public LoanProductMinMaxConstraints loanProductMinMaxConstraints() {
//If all min and max fields are null then loanProductMinMaxConstraints initialising to null
//Reset LoanProductMinMaxConstraints with null values.
this.loanProductMinMaxConstraints = (this.loanProductMinMaxConstraints == null) ? new LoanProductMinMaxConstraints(null, null, null, null, null, null)
: this.loanProductMinMaxConstraints;
return loanProductMinMaxConstraints;
}
}
*/
|
wip mifosx-195 - report class
|
mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/Report.java
|
wip mifosx-195 - report class
|
|
Java
|
apache-2.0
|
3a9808e96c734ea4a79dc5b6d5524d349a55fb90
| 0
|
zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/hadoop,zrccxyb62/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.fs;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* Interface for class that can tell estimate much space
* is used in a directory.
* <p>
* The implementor is fee to cache space used. As such there
* are methods to update the cached value with any known changes.
*/
@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
@InterfaceStability.Evolving
public abstract class CachingGetSpaceUsed implements Closeable, GetSpaceUsed {
static final Logger LOG = LoggerFactory.getLogger(CachingGetSpaceUsed.class);
protected final AtomicLong used = new AtomicLong();
private final AtomicBoolean running = new AtomicBoolean(true);
private final long refreshInterval;
private final long jitter;
private final String dirPath;
private Thread refreshUsed;
/**
* This is the constructor used by the builder.
* All overriding classes should implement this.
*/
public CachingGetSpaceUsed(CachingGetSpaceUsed.Builder builder)
throws IOException {
this(builder.getPath(),
builder.getInterval(),
builder.getJitter(),
builder.getInitialUsed());
}
/**
* Keeps track of disk usage.
*
* @param path the path to check disk usage in
* @param interval refresh the disk usage at this interval
* @param initialUsed use this value until next refresh
* @throws IOException if we fail to refresh the disk usage
*/
CachingGetSpaceUsed(File path,
long interval,
long jitter,
long initialUsed) throws IOException {
this.dirPath = path.getCanonicalPath();
this.refreshInterval = interval;
this.jitter = jitter;
this.used.set(initialUsed);
}
void init() {
if (used.get() < 0) {
used.set(0);
refresh();
}
if (refreshInterval > 0) {
refreshUsed = new Thread(new RefreshThread(this),
"refreshUsed-" + dirPath);
refreshUsed.setDaemon(true);
refreshUsed.start();
} else {
running.set(false);
refreshUsed = null;
}
}
protected abstract void refresh();
/**
* @return an estimate of space used in the directory path.
*/
@Override public long getUsed() throws IOException {
return Math.max(used.get(), 0);
}
/**
* @return The directory path being monitored.
*/
public String getDirPath() {
return dirPath;
}
/**
* Increment the cached value of used space.
*/
public void incDfsUsed(long value) {
used.addAndGet(value);
}
/**
* Is the background thread running.
*/
boolean running() {
return running.get();
}
/**
* How long in between runs of the background refresh.
*/
long getRefreshInterval() {
return refreshInterval;
}
/**
* Reset the current used data amount. This should be called
* when the cached value is re-computed.
*
* @param usedValue new value that should be the disk usage.
*/
protected void setUsed(long usedValue) {
this.used.set(usedValue);
}
@Override
public void close() throws IOException {
running.set(false);
if (refreshUsed != null) {
refreshUsed.interrupt();
}
}
private static final class RefreshThread implements Runnable {
final CachingGetSpaceUsed spaceUsed;
RefreshThread(CachingGetSpaceUsed spaceUsed) {
this.spaceUsed = spaceUsed;
}
@Override
public void run() {
while (spaceUsed.running()) {
try {
long refreshInterval = spaceUsed.refreshInterval;
if (spaceUsed.jitter > 0) {
long jitter = spaceUsed.jitter;
// add/subtract the jitter.
refreshInterval +=
ThreadLocalRandom.current()
.nextLong(-jitter, jitter);
}
// Make sure that after the jitter we didn't end up at 0.
refreshInterval = Math.max(refreshInterval, 1);
Thread.sleep(refreshInterval);
// update the used variable
spaceUsed.refresh();
} catch (InterruptedException e) {
LOG.warn("Thread Interrupted waiting to refresh disk information: "
+ e.getMessage());
Thread.currentThread().interrupt();
}
}
}
}
}
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/CachingGetSpaceUsed.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.fs;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* Interface for class that can tell estimate much space
* is used in a directory.
* <p>
* The implementor is fee to cache space used. As such there
* are methods to update the cached value with any known changes.
*/
@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
@InterfaceStability.Evolving
public abstract class CachingGetSpaceUsed implements Closeable, GetSpaceUsed {
static final Logger LOG = LoggerFactory.getLogger(CachingGetSpaceUsed.class);
protected final AtomicLong used = new AtomicLong();
private final AtomicBoolean running = new AtomicBoolean(true);
private final long refreshInterval;
private final long jitter;
private final String dirPath;
private Thread refreshUsed;
/**
* This is the constructor used by the builder.
* All overriding classes should implement this.
*/
public CachingGetSpaceUsed(CachingGetSpaceUsed.Builder builder)
throws IOException {
this(builder.getPath(),
builder.getInterval(),
builder.getJitter(),
builder.getInitialUsed());
}
/**
* Keeps track of disk usage.
*
* @param path the path to check disk usage in
* @param interval refresh the disk usage at this interval
* @param initialUsed use this value until next refresh
* @throws IOException if we fail to refresh the disk usage
*/
CachingGetSpaceUsed(File path,
long interval,
long jitter,
long initialUsed) throws IOException {
this.dirPath = path.getCanonicalPath();
this.refreshInterval = interval;
this.jitter = jitter;
this.used.set(initialUsed);
}
void init() {
if (used.get() < 0) {
used.set(0);
refresh();
}
if (refreshInterval > 0) {
refreshUsed = new Thread(new RefreshThread(this),
"refreshUsed-" + dirPath);
refreshUsed.setDaemon(true);
refreshUsed.start();
} else {
running.set(false);
refreshUsed = null;
}
}
protected abstract void refresh();
/**
* @return an estimate of space used in the directory path.
*/
@Override public long getUsed() throws IOException {
return Math.max(used.get(), 0);
}
/**
* @return The directory path being monitored.
*/
public String getDirPath() {
return dirPath;
}
/**
* Increment the cached value of used space.
*/
public void incDfsUsed(long value) {
used.addAndGet(value);
}
/**
* Is the background thread running.
*/
boolean running() {
return running.get();
}
/**
* How long in between runs of the background refresh.
*/
long getRefreshInterval() {
return refreshInterval;
}
/**
* Reset the current used data amount. This should be called
* when the cached value is re-computed.
*
* @param usedValue new value that should be the disk usage.
*/
protected void setUsed(long usedValue) {
this.used.set(usedValue);
}
@Override
public void close() throws IOException {
running.set(false);
if (refreshUsed != null) {
refreshUsed.interrupt();
}
}
private static final class RefreshThread implements Runnable {
final CachingGetSpaceUsed spaceUsed;
RefreshThread(CachingGetSpaceUsed spaceUsed) {
this.spaceUsed = spaceUsed;
}
@Override
public void run() {
while (spaceUsed.running()) {
try {
long refreshInterval = spaceUsed.refreshInterval;
if (spaceUsed.jitter > 0) {
long jitter = spaceUsed.jitter;
// add/subtract the jitter.
refreshInterval +=
ThreadLocalRandom.current()
.nextLong(-jitter, jitter);
}
// Make sure that after the jitter we didn't end up at 0.
refreshInterval = Math.max(refreshInterval, 1);
Thread.sleep(refreshInterval);
// update the used variable
spaceUsed.refresh();
} catch (InterruptedException e) {
LOG.warn("Thread Interrupted waiting to refresh disk information", e);
Thread.currentThread().interrupt();
}
}
}
}
}
|
HADOOP-13710. Supress CachingGetSpaceUsed from logging interrupted exception stacktrace. Contributed by Hanisha Koneru.
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/CachingGetSpaceUsed.java
|
HADOOP-13710. Supress CachingGetSpaceUsed from logging interrupted exception stacktrace. Contributed by Hanisha Koneru.
|
|
Java
|
apache-2.0
|
37437303690e56f0d1c37396dbb39f67d412fb0a
| 0
|
box/box-android-sdk,seema-at-box/box-android-sdk,box/box-android-sdk,box/box-android-sdk,seema-at-box/box-android-sdk,seema-at-box/box-android-sdk
|
package com.box.androidsdk.content;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import com.box.androidsdk.content.models.BoxObject;
import com.box.androidsdk.content.requests.BoxRequest;
import com.box.androidsdk.content.requests.BoxResponse;
/**
* A task that can be executed asynchronously to fetch results. This is generally created using
* {@link BoxRequest#toTask()}
*
* @param <E> the BoxObject result of the request
*/
public class BoxFutureTask<E extends BoxObject> extends FutureTask<BoxResponse<E>> {
protected final BoxRequest mRequest;
protected ArrayList<OnCompletedListener<E>> mCompletedListeners = new ArrayList<OnCompletedListener<E>>();
/**
* Creates an instance of a task that can be executed asynchronously
*
* @param clazz the class of the return type
* @param request the original request that was used to create the future task
*/
public BoxFutureTask(final Class<E> clazz, final BoxRequest request) {
super(new Callable<BoxResponse<E>>() {
@Override
public BoxResponse<E> call() throws Exception {
E ret = null;
Exception ex = null;
try {
ret = (E) request.send();
} catch (Exception e) {
ex = e;
}
return new BoxResponse<E>(ret, ex, request);
}
});
mRequest = request;
}
/**
* Protected constructor for BoxFutureTask so that child classes can provide their own callable
* implementation
*
* @param callable what will be executed when the future task is run
* @param request the original request that the future task was created from
*/
protected BoxFutureTask(final Callable<BoxResponse<E>> callable, final BoxRequest request) {
super(callable);
mRequest = request;
}
@Override
protected synchronized void done() {
BoxResponse<E> response = null;
Exception ex = null;
try {
response = this.get();
} catch (InterruptedException e) {
ex = e;
} catch (ExecutionException e) {
ex = e;
} catch (CancellationException e) {
ex = e;
}
if (ex != null) {
response = new BoxResponse<E>(null, new BoxException("Unable to retrieve response from FutureTask.", ex), mRequest);
}
ArrayList<OnCompletedListener<E>> listener = mCompletedListeners;
for (OnCompletedListener<E> l : listener) {
l.onCompleted(response);
}
}
@SuppressWarnings("unchecked")
public synchronized BoxFutureTask<E> addOnCompletedListener(OnCompletedListener<E> listener) {
mCompletedListeners.add(listener);
return this;
}
public interface OnCompletedListener<E extends BoxObject> {
void onCompleted(BoxResponse<E> response);
}
}
|
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxFutureTask.java
|
package com.box.androidsdk.content;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import com.box.androidsdk.content.models.BoxObject;
import com.box.androidsdk.content.requests.BoxRequest;
import com.box.androidsdk.content.requests.BoxResponse;
/**
* A task that can be executed asynchronously to fetch results. This is generally created using
* {@link BoxRequest#toTask()}
*
* @param <E> the BoxObject result of the request
*/
public class BoxFutureTask<E extends BoxObject> extends FutureTask<BoxResponse<E>> {
protected final BoxRequest mRequest;
protected ArrayList<OnCompletedListener<E>> mCompletedListeners = new ArrayList<OnCompletedListener<E>>();
/**
* Creates an instance of a task that can be executed asynchronously
*
* @param clazz the class of the return type
* @param request the original request that was used to create the future task
*/
public BoxFutureTask(final Class<E> clazz, final BoxRequest request) {
super(new Callable<BoxResponse<E>>() {
@Override
public BoxResponse<E> call() throws Exception {
E ret = null;
Exception ex = null;
try {
ret = (E) request.send();
} catch (Exception e) {
ex = e;
}
return new BoxResponse<E>(ret, ex, request);
}
});
mRequest = request;
}
/**
* Protected constructor for BoxFutureTask so that child classes can provide their own callable
* implementation
*
* @param callable what will be executed when the future task is run
* @param request the original request that the future task was created from
*/
protected BoxFutureTask(final Callable<BoxResponse<E>> callable, final BoxRequest request) {
super(callable);
mRequest = request;
}
@Override
protected void done() {
BoxResponse<E> response = null;
Exception ex = null;
try {
response = this.get();
} catch (InterruptedException e) {
ex = e;
} catch (ExecutionException e) {
ex = e;
} catch (CancellationException e) {
ex = e;
}
if (ex != null) {
response = new BoxResponse<E>(null, new BoxException("Unable to retrieve response from FutureTask.", ex), mRequest);
}
ArrayList<OnCompletedListener<E>> listener = getCompletionListeners();
for (OnCompletedListener<E> l : listener) {
l.onCompleted(response);
}
}
public ArrayList<OnCompletedListener<E>> getCompletionListeners() {
return mCompletedListeners;
}
@SuppressWarnings("unchecked")
public BoxFutureTask<E> addOnCompletedListener(OnCompletedListener<E> listener) {
mCompletedListeners.add(listener);
return this;
}
public interface OnCompletedListener<E extends BoxObject> {
void onCompleted(BoxResponse<E> response);
}
}
|
AND-6912 [Baymax][Passcode+Redirection]: Box app crashes when user redirects to Box app via Shared link on freshly installed app
|
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxFutureTask.java
|
AND-6912 [Baymax][Passcode+Redirection]: Box app crashes when user redirects to Box app via Shared link on freshly installed app
|
|
Java
|
apache-2.0
|
3bef5ba967dff11632b01d37a369d40639a018f0
| 0
|
blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle
|
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.tasks.scala;
import org.gradle.api.Incubating;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.LocalState;
import javax.inject.Inject;
/**
* Options for incremental compilation of Scala code. Only used for compilation with Zinc.
*
* This is not sent to the compiler daemon as options.
*/
public class IncrementalCompileOptions {
private final RegularFileProperty analysisFile;
private final RegularFileProperty classfileBackupDir;
private final RegularFileProperty publishedCode;
@Inject
public IncrementalCompileOptions(ObjectFactory objectFactory) {
this.analysisFile = objectFactory.fileProperty();
this.classfileBackupDir = objectFactory.fileProperty();
this.publishedCode = objectFactory.fileProperty();
}
/**
* Returns the file path where results of code analysis are to be stored.
*/
@LocalState
public RegularFileProperty getAnalysisFile() {
return analysisFile;
}
/**
* Returns the path to the directory where previously generated class files are backed up during the next, incremental compilation.
* If the compilation fails, class files are restored from the backup.
*
* @since 6.6
*/
@LocalState
@Incubating
public RegularFileProperty getClassfileBackupDir() {
return classfileBackupDir;
}
/**
* Returns the directory or archive path by which the code produced by this task
* is published to other {@code ScalaCompile} tasks.
*/
// only an input for other task instances
@Internal
public RegularFileProperty getPublishedCode() {
return publishedCode;
}
}
|
subprojects/language-scala/src/main/java/org/gradle/api/tasks/scala/IncrementalCompileOptions.java
|
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.tasks.scala;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.LocalState;
import javax.inject.Inject;
/**
* Options for incremental compilation of Scala code. Only used for compilation with Zinc.
*
* This is not sent to the compiler daemon as options.
*/
public class IncrementalCompileOptions {
private final RegularFileProperty analysisFile;
private final RegularFileProperty classfileBackupDir;
private final RegularFileProperty publishedCode;
@Inject
public IncrementalCompileOptions(ObjectFactory objectFactory) {
this.analysisFile = objectFactory.fileProperty();
this.classfileBackupDir = objectFactory.fileProperty();
this.publishedCode = objectFactory.fileProperty();
}
/**
* Returns the file path where results of code analysis are to be stored.
*/
@LocalState
public RegularFileProperty getAnalysisFile() {
return analysisFile;
}
/**
* Returns the path to the directory where previously generated class files are backed up during the next, incremental compilation.
* If the compilation fails, class files are restored from the backup.
*/
@LocalState
public RegularFileProperty getClassfileBackupDir() {
return classfileBackupDir;
}
/**
* Returns the directory or archive path by which the code produced by this task
* is published to other {@code ScalaCompile} tasks.
*/
// only an input for other task instances
@Internal
public RegularFileProperty getPublishedCode() {
return publishedCode;
}
}
|
Add missing incubating mentions
Issue #13392
|
subprojects/language-scala/src/main/java/org/gradle/api/tasks/scala/IncrementalCompileOptions.java
|
Add missing incubating mentions
|
|
Java
|
apache-2.0
|
e91319d6e2ca5e7eb9d6905496c57c7b53e53775
| 0
|
ol-loginov/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,signed/intellij-community,signed/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,holmes/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,clumsy/intellij-community,ernestp/consulo,amith01994/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,blademainer/intellij-community,hurricup/intellij-community,dslomov/intellij-community,diorcety/intellij-community,kool79/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,signed/intellij-community,consulo/consulo,ibinti/intellij-community,slisson/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,semonte/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,kdwink/intellij-community,semonte/intellij-community,dslomov/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,samthor/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,holmes/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,da1z/intellij-community,amith01994/intellij-community,caot/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,caot/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,da1z/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,semonte/intellij-community,asedunov/intellij-community,petteyg/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,supersven/intellij-community,amith01994/intellij-community,kool79/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,da1z/intellij-community,izonder/intellij-community,caot/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,signed/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,kool79/intellij-community,allotria/intellij-community,FHannes/intellij-community,jagguli/intellij-community,robovm/robovm-studio,apixandru/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,kool79/intellij-community,adedayo/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,da1z/intellij-community,jagguli/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,dslomov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,semonte/intellij-community,ryano144/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,ernestp/consulo,wreckJ/intellij-community,semonte/intellij-community,akosyakov/intellij-community,slisson/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,allotria/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,holmes/intellij-community,signed/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,signed/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,allotria/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,fitermay/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ibinti/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,dslomov/intellij-community,clumsy/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,vladmm/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,caot/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,retomerz/intellij-community,asedunov/intellij-community,fnouama/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,vladmm/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,consulo/consulo,SerCeMan/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,consulo/consulo,samthor/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,ernestp/consulo,TangHao1987/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,semonte/intellij-community,ryano144/intellij-community,asedunov/intellij-community,signed/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,fnouama/intellij-community,adedayo/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,ernestp/consulo,clumsy/intellij-community,diorcety/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,hurricup/intellij-community,da1z/intellij-community,caot/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,consulo/consulo,muntasirsyed/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,fnouama/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,slisson/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,consulo/consulo,kool79/intellij-community,da1z/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,samthor/intellij-community,fitermay/intellij-community,vladmm/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,supersven/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,supersven/intellij-community,caot/intellij-community,fitermay/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,holmes/intellij-community,semonte/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,signed/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,clumsy/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,fitermay/intellij-community,clumsy/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,supersven/intellij-community,fnouama/intellij-community,robovm/robovm-studio,FHannes/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,allotria/intellij-community,consulo/consulo,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,allotria/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,kool79/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,slisson/intellij-community,asedunov/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,supersven/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,semonte/intellij-community,allotria/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,izonder/intellij-community,jagguli/intellij-community,retomerz/intellij-community,signed/intellij-community,ryano144/intellij-community,hurricup/intellij-community,kool79/intellij-community,holmes/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,fnouama/intellij-community,vladmm/intellij-community,blademainer/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,slisson/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,asedunov/intellij-community,supersven/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,kool79/intellij-community,semonte/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,allotria/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,slisson/intellij-community,vvv1559/intellij-community,samthor/intellij-community,wreckJ/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,apixandru/intellij-community,clumsy/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,signed/intellij-community,asedunov/intellij-community,petteyg/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,ryano144/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,holmes/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,xfournet/intellij-community,vladmm/intellij-community,FHannes/intellij-community,vladmm/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,dslomov/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,supersven/intellij-community,apixandru/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.extapi.psi;
import com.intellij.lang.ASTNode;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.NonCancelableSection;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiInvalidElementAccessException;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.impl.source.tree.SharedImplUtil;
import com.intellij.psi.stubs.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Array;
public class StubBasedPsiElementBase<T extends StubElement> extends ASTDelegatePsiElement {
private volatile T myStub;
private volatile ASTNode myNode;
private final IElementType myElementType;
public StubBasedPsiElementBase(@NotNull T stub, @NotNull IStubElementType nodeType) {
myStub = stub;
myElementType = nodeType;
myNode = null;
}
public StubBasedPsiElementBase(@NotNull ASTNode node) {
myNode = node;
myElementType = node.getElementType();
}
@Override
@NotNull
public ASTNode getNode() {
ASTNode node = myNode;
if (node == null) {
ApplicationManager.getApplication().assertReadAccessAllowed();
PsiFileImpl file = (PsiFileImpl)getContainingFile();
synchronized (file.getStubLock()) {
node = myNode;
if (node == null) {
NonCancelableSection criticalSection = ProgressIndicatorProvider.getInstance().startNonCancelableSection();
try {
if (!file.isValid()) throw new PsiInvalidElementAccessException(this);
FileElement treeElement = file.getTreeElement();
StubTree stubTree = file.getStubTree();
if (treeElement != null) {
return notBoundInExistingAst(file, treeElement, stubTree);
}
final FileElement fileElement = file.loadTreeElement();
node = myNode;
if (node == null) {
String message = new StringBuilder().
append("Failed to bind stub to AST for element ").
append(getClass()).
append(" in ").
append(file.getVirtualFile() == null ? "<unknown file>" : file.getVirtualFile().getPath()).
append("\nFile stub tree:\n").
append(stubTree != null ? StringUtil.trimLog(((PsiFileStubImpl)stubTree.getRoot()).printTree(), 1024) : " is null").
append("\nLoaded file AST:\n").
append(StringUtil.trimLog(DebugUtil.treeToString(fileElement, true), 1024)).
toString();
throw new IllegalArgumentException(message);
}
}
finally {
criticalSection.done();
}
}
}
}
return node;
}
private ASTNode notBoundInExistingAst(PsiFileImpl file, FileElement treeElement, StubTree stubTree) {
String message = "this=" + this +
"; file.isPhysical=" + file.isPhysical() +
"; node=" + myNode +
"; file=" + file +
"; tree=" + treeElement +
"; stubTree=" + stubTree;
PsiElement each = this;
while (each != null) {
message += "\n each=" + each + " of class " + each.getClass();
if (each instanceof StubBasedPsiElementBase) {
message += "; node=" + ((StubBasedPsiElementBase)each).myNode + "; stub=" + ((StubBasedPsiElementBase)each).myStub;
each = ((StubBasedPsiElementBase)each).getParentByStub();
} else {
break;
}
}
throw new AssertionError(message);
}
public void setNode(final ASTNode node) {
myNode = node;
}
@NotNull
@Override
public Language getLanguage() {
return myElementType.getLanguage();
}
@Override
public PsiFile getContainingFile() {
StubElement stub = myStub;
if (stub != null) {
while (!(stub instanceof PsiFileStub)) {
stub = stub.getParentStub();
}
return (PsiFile)stub.getPsi();
}
return super.getContainingFile();
}
@Override
public boolean isWritable() {
return getContainingFile().isWritable();
}
@Override
public boolean isValid() {
T stub = myStub;
if (stub != null) {
if (stub instanceof PsiFileStub) {
return stub.getPsi().isValid();
}
return stub.getParentStub().getPsi().isValid();
}
return super.isValid();
}
@Override
public PsiManagerEx getManager() {
return (PsiManagerEx)getContainingFile().getManager();
}
@Override
@NotNull
public Project getProject() {
return getContainingFile().getProject();
}
@Override
public boolean isPhysical() {
return getContainingFile().isPhysical();
}
@Override
public PsiElement getContext() {
T stub = myStub;
if (stub != null) {
if (!(stub instanceof PsiFileStub)) {
return stub.getParentStub().getPsi();
}
}
return super.getContext();
}
protected final PsiElement getParentByStub() {
final StubElement<?> stub = getStub();
if (stub != null) {
return stub.getParentStub().getPsi();
}
return SharedImplUtil.getParent(getNode());
}
@Override
public void subtreeChanged() {
super.subtreeChanged();
setStub(null);
}
protected final PsiElement getParentByTree() {
return SharedImplUtil.getParent(getNode());
}
@Override
public PsiElement getParent() {
return getParentByTree();
}
@NotNull
public IStubElementType getElementType() {
if (!(myElementType instanceof IStubElementType)) {
throw new AssertionError("Not a stub type: " + myElementType + " in " + getClass());
}
return (IStubElementType)myElementType;
}
public T getStub() {
ProgressIndicatorProvider.checkCanceled(); // Hope, this is called often
return myStub;
}
public void setStub(T stub) {
myStub = stub;
}
@Nullable
public <Stub extends StubElement, Psi extends PsiElement> Psi getStubOrPsiChild(final IStubElementType<Stub, Psi> elementType) {
T stub = myStub;
if (stub != null) {
final StubElement<Psi> element = stub.findChildStubByType(elementType);
if (element != null) {
return element.getPsi();
}
}
else {
final ASTNode childNode = getNode().findChildByType(elementType);
if (childNode != null) {
return (Psi)childNode.getPsi();
}
}
return null;
}
@NotNull
public <Stub extends StubElement, Psi extends PsiElement> Psi getRequiredStubOrPsiChild(final IStubElementType<Stub, Psi> elementType) {
Psi result = getStubOrPsiChild(elementType);
assert result != null: "Missing required child of type " + elementType + "; tree: "+DebugUtil.psiToString(this, false);
return result;
}
public <Stub extends StubElement, Psi extends PsiElement> Psi[] getStubOrPsiChildren(final IStubElementType<Stub, Psi> elementType, Psi[] array) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (Psi[])stub.getChildrenByType(elementType, array);
}
else {
final ASTNode[] nodes = SharedImplUtil.getChildrenOfType(getNode(), elementType);
Psi[] psiElements = (Psi[])Array.newInstance(array.getClass().getComponentType(), nodes.length);
for (int i = 0; i < nodes.length; i++) {
psiElements[i] = (Psi)nodes[i].getPsi();
}
return psiElements;
}
}
public <Stub extends StubElement, Psi extends PsiElement> Psi[] getStubOrPsiChildren(final IStubElementType<Stub, Psi> elementType, ArrayFactory<Psi> f) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (Psi[])stub.getChildrenByType(elementType, f);
}
else {
final ASTNode[] nodes = SharedImplUtil.getChildrenOfType(getNode(), elementType);
Psi[] psiElements = f.create(nodes.length);
for (int i = 0; i < nodes.length; i++) {
psiElements[i] = (Psi)nodes[i].getPsi();
}
return psiElements;
}
}
public <Psi extends PsiElement> Psi[] getStubOrPsiChildren(TokenSet filter, Psi[] array) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (Psi[])stub.getChildrenByType(filter, array);
}
else {
final ASTNode[] nodes = getNode().getChildren(filter);
Psi[] psiElements = (Psi[])Array.newInstance(array.getClass().getComponentType(), nodes.length);
for (int i = 0; i < nodes.length; i++) {
psiElements[i] = (Psi)nodes[i].getPsi();
}
return psiElements;
}
}
public <Psi extends PsiElement> Psi[] getStubOrPsiChildren(TokenSet filter, ArrayFactory<Psi> f) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (Psi[])stub.getChildrenByType(filter, f);
}
else {
final ASTNode[] nodes = getNode().getChildren(filter);
Psi[] psiElements = f.create(nodes.length);
for (int i = 0; i < nodes.length; i++) {
psiElements[i] = (Psi)nodes[i].getPsi();
}
return psiElements;
}
}
@Nullable
protected <E extends PsiElement> E getStubOrPsiParentOfType(final Class<E> parentClass) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (E)stub.getParentStubOfType(parentClass);
}
return PsiTreeUtil.getParentOfType(this, parentClass);
}
@Nullable
protected PsiElement getStubOrPsiParent() {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return stub.getParentStub().getPsi();
}
return getParent();
}
@Override
protected Object clone() {
final StubBasedPsiElementBase stubbless = (StubBasedPsiElementBase)super.clone();
stubbless.myStub = null;
return stubbless;
}
}
|
platform/core-impl/src/com/intellij/extapi/psi/StubBasedPsiElementBase.java
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.extapi.psi;
import com.intellij.lang.ASTNode;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.NonCancelableSection;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiInvalidElementAccessException;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.impl.source.tree.SharedImplUtil;
import com.intellij.psi.stubs.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Array;
public class StubBasedPsiElementBase<T extends StubElement> extends ASTDelegatePsiElement {
private volatile T myStub;
private volatile ASTNode myNode;
private final IElementType myElementType;
public StubBasedPsiElementBase(@NotNull T stub, @NotNull IStubElementType nodeType) {
myStub = stub;
myElementType = nodeType;
myNode = null;
}
public StubBasedPsiElementBase(@NotNull ASTNode node) {
myNode = node;
myElementType = node.getElementType();
}
@Override
@NotNull
public ASTNode getNode() {
ASTNode node = myNode;
if (node == null) {
ApplicationManager.getApplication().assertReadAccessAllowed();
PsiFileImpl file = (PsiFileImpl)getContainingFile();
synchronized (file.getStubLock()) {
node = myNode;
if (node == null) {
NonCancelableSection criticalSection = ProgressIndicatorProvider.getInstance().startNonCancelableSection();
try {
if (!file.isValid()) throw new PsiInvalidElementAccessException(this);
FileElement treeElement = file.getTreeElement();
StubTree stubTree = file.getStubTree();
if (treeElement != null) {
throw new AssertionError("this="+this+"; file.isPhysical="+file.isPhysical() + "; node=" + myNode + "; file=" + file + "; tree=" + treeElement + "; stubTree=" + stubTree);
}
final FileElement fileElement = file.loadTreeElement();
node = myNode;
if (node == null) {
String message = new StringBuilder().
append("Failed to bind stub to AST for element ").
append(getClass()).
append(" in ").
append(file.getVirtualFile() == null ? "<unknown file>" : file.getVirtualFile().getPath()).
append("\nFile stub tree:\n").
append(stubTree != null ? StringUtil.trimLog(((PsiFileStubImpl)stubTree.getRoot()).printTree(), 1024) : " is null").
append("\nLoaded file AST:\n").
append(StringUtil.trimLog(DebugUtil.treeToString(fileElement, true), 1024)).
toString();
throw new IllegalArgumentException(message);
}
}
finally {
criticalSection.done();
}
}
}
}
return node;
}
public void setNode(final ASTNode node) {
myNode = node;
}
@NotNull
@Override
public Language getLanguage() {
return myElementType.getLanguage();
}
@Override
public PsiFile getContainingFile() {
StubElement stub = myStub;
if (stub != null) {
while (!(stub instanceof PsiFileStub)) {
stub = stub.getParentStub();
}
return (PsiFile)stub.getPsi();
}
return super.getContainingFile();
}
@Override
public boolean isWritable() {
return getContainingFile().isWritable();
}
@Override
public boolean isValid() {
T stub = myStub;
if (stub != null) {
if (stub instanceof PsiFileStub) {
return stub.getPsi().isValid();
}
return stub.getParentStub().getPsi().isValid();
}
return super.isValid();
}
@Override
public PsiManagerEx getManager() {
return (PsiManagerEx)getContainingFile().getManager();
}
@Override
@NotNull
public Project getProject() {
return getContainingFile().getProject();
}
@Override
public boolean isPhysical() {
return getContainingFile().isPhysical();
}
@Override
public PsiElement getContext() {
T stub = myStub;
if (stub != null) {
if (!(stub instanceof PsiFileStub)) {
return stub.getParentStub().getPsi();
}
}
return super.getContext();
}
protected final PsiElement getParentByStub() {
final StubElement<?> stub = getStub();
if (stub != null) {
return stub.getParentStub().getPsi();
}
return SharedImplUtil.getParent(getNode());
}
@Override
public void subtreeChanged() {
super.subtreeChanged();
setStub(null);
}
protected final PsiElement getParentByTree() {
return SharedImplUtil.getParent(getNode());
}
@Override
public PsiElement getParent() {
return getParentByTree();
}
@NotNull
public IStubElementType getElementType() {
if (!(myElementType instanceof IStubElementType)) {
throw new AssertionError("Not a stub type: " + myElementType + " in " + getClass());
}
return (IStubElementType)myElementType;
}
public T getStub() {
ProgressIndicatorProvider.checkCanceled(); // Hope, this is called often
return myStub;
}
public void setStub(T stub) {
myStub = stub;
}
@Nullable
public <Stub extends StubElement, Psi extends PsiElement> Psi getStubOrPsiChild(final IStubElementType<Stub, Psi> elementType) {
T stub = myStub;
if (stub != null) {
final StubElement<Psi> element = stub.findChildStubByType(elementType);
if (element != null) {
return element.getPsi();
}
}
else {
final ASTNode childNode = getNode().findChildByType(elementType);
if (childNode != null) {
return (Psi)childNode.getPsi();
}
}
return null;
}
@NotNull
public <Stub extends StubElement, Psi extends PsiElement> Psi getRequiredStubOrPsiChild(final IStubElementType<Stub, Psi> elementType) {
Psi result = getStubOrPsiChild(elementType);
assert result != null: "Missing required child of type " + elementType + "; tree: "+DebugUtil.psiToString(this, false);
return result;
}
public <Stub extends StubElement, Psi extends PsiElement> Psi[] getStubOrPsiChildren(final IStubElementType<Stub, Psi> elementType, Psi[] array) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (Psi[])stub.getChildrenByType(elementType, array);
}
else {
final ASTNode[] nodes = SharedImplUtil.getChildrenOfType(getNode(), elementType);
Psi[] psiElements = (Psi[])Array.newInstance(array.getClass().getComponentType(), nodes.length);
for (int i = 0; i < nodes.length; i++) {
psiElements[i] = (Psi)nodes[i].getPsi();
}
return psiElements;
}
}
public <Stub extends StubElement, Psi extends PsiElement> Psi[] getStubOrPsiChildren(final IStubElementType<Stub, Psi> elementType, ArrayFactory<Psi> f) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (Psi[])stub.getChildrenByType(elementType, f);
}
else {
final ASTNode[] nodes = SharedImplUtil.getChildrenOfType(getNode(), elementType);
Psi[] psiElements = f.create(nodes.length);
for (int i = 0; i < nodes.length; i++) {
psiElements[i] = (Psi)nodes[i].getPsi();
}
return psiElements;
}
}
public <Psi extends PsiElement> Psi[] getStubOrPsiChildren(TokenSet filter, Psi[] array) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (Psi[])stub.getChildrenByType(filter, array);
}
else {
final ASTNode[] nodes = getNode().getChildren(filter);
Psi[] psiElements = (Psi[])Array.newInstance(array.getClass().getComponentType(), nodes.length);
for (int i = 0; i < nodes.length; i++) {
psiElements[i] = (Psi)nodes[i].getPsi();
}
return psiElements;
}
}
public <Psi extends PsiElement> Psi[] getStubOrPsiChildren(TokenSet filter, ArrayFactory<Psi> f) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (Psi[])stub.getChildrenByType(filter, f);
}
else {
final ASTNode[] nodes = getNode().getChildren(filter);
Psi[] psiElements = f.create(nodes.length);
for (int i = 0; i < nodes.length; i++) {
psiElements[i] = (Psi)nodes[i].getPsi();
}
return psiElements;
}
}
@Nullable
protected <E extends PsiElement> E getStubOrPsiParentOfType(final Class<E> parentClass) {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return (E)stub.getParentStubOfType(parentClass);
}
return PsiTreeUtil.getParentOfType(this, parentClass);
}
@Nullable
protected PsiElement getStubOrPsiParent() {
T stub = myStub;
if (stub != null) {
//noinspection unchecked
return stub.getParentStub().getPsi();
}
return getParent();
}
@Override
protected Object clone() {
final StubBasedPsiElementBase stubbless = (StubBasedPsiElementBase)super.clone();
stubbless.myStub = null;
return stubbless;
}
}
|
EA-31247 more diagnostics for failed stub-ast binding
|
platform/core-impl/src/com/intellij/extapi/psi/StubBasedPsiElementBase.java
|
EA-31247 more diagnostics for failed stub-ast binding
|
|
Java
|
apache-2.0
|
96af8433e7c918f9192ce043cc8876694ff2c696
| 0
|
atkjumedia/dcsync,atkjumedia/dcsync,atkjumedia/dcsync
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package at.kju.datacollector;
import android.content.Context;
public class Constants {
/**
* Account type string.
*/
public static String getAccountType(Context ctx) {
return (String) ctx.getResources().getText(R.string.aam_account_type);
}
public static String getAuthTokenType(Context ctx) {
return (String) ctx.getResources().getText(R.string.aam_account_type);
}
public static String getContentAuthority(Context ctx) {
return (String) ctx.getResources().getText(R.string.aam_account_type);
}
public static String HTML_ROOT = "file:///android_asset/common/";
}
|
src/android/Constants.java
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package at.kju.datacollector;
import android.content.Context;
import at.kju.dcbootstrap.R;
public class Constants {
/**
* Account type string.
*/
public static String getAccountType(Context ctx) {
return (String) ctx.getResources().getText(R.string.aam_account_type);
}
public static String getAuthTokenType(Context ctx) {
return (String) ctx.getResources().getText(R.string.aam_account_type);
}
public static String getContentAuthority(Context ctx) {
return (String) ctx.getResources().getText(R.string.aam_account_type);
}
public static String HTML_ROOT = "file:///android_asset/common/";
}
|
Update Constants.java
|
src/android/Constants.java
|
Update Constants.java
|
|
Java
|
apache-2.0
|
c7cad2e7dab5bc05ba74e5679b7cbc0f67ab1160
| 0
|
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2009-2013 Ausenco Engineering Canada 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.Graphics;
import java.util.ArrayList;
import com.jaamsim.Samples.SampleListInput;
import com.jaamsim.input.BooleanInput;
import com.jaamsim.input.ColorListInput;
import com.jaamsim.input.ColourInput;
import com.jaamsim.input.Keyword;
import com.jaamsim.math.Color4d;
import com.jaamsim.units.UserSpecifiedUnit;
public class XYGraph extends GraphBasics {
// Key Inputs category
@Keyword(description = "One or more sources of data to be graphed on the primary y-axis.\n"
+ "Each source is graphed as a separate line or bar and is specified by an Entity and its Output.",
exampleList = {"{ Entity1 Output1 } { Entity2 Output2 }"})
protected final SampleListInput dataSource;
@Keyword(description = "A list of colors for the primary series to be displayed.\n"
+ "Each color can be specified by either a color keyword or an RGB value.\n"
+ "For multiple series, each color must be enclosed in braces.\n"
+ "If only one color is provided, it is used for all the series.",
exampleList = "XYGraph1 SeriesColors { { red } { green } }")
protected final ColorListInput seriesColorsList;
@Keyword(description = "Set to TRUE if the primary series are to be shown as bars instead of lines.",
exampleList = {"TRUE"})
protected final BooleanInput showBars;
@Keyword(description = "One or more sources of data to be graphed on the secondary y-axis.\n"
+ "Each source is graphed as a separate line or bar and is specified by an Entity and its Output.",
exampleList = {"{ Entity1 Output1 } { Entity2 Output2 }"})
protected final SampleListInput secondaryDataSource;
@Keyword(description = "A list of colors for the secondary series to be displayed.\n"
+ "Each color can be specified by either a color keyword or an RGB value.\n"
+ "For multiple series, each color must be enclosed in braces.\n"
+ "If only one color is provided, it is used for all the series.",
exampleList = {"{ red } { green }"})
protected final ColorListInput secondarySeriesColorsList;
@Keyword(description = "Set to TRUE if the secondary series are to be shown as bars instead of lines.",
exampleList = {"TRUE"})
protected final BooleanInput secondaryShowBars;
{
// Key Inputs category
dataSource = new SampleListInput("DataSource", "Key Inputs", null);
dataSource.setUnitType(UserSpecifiedUnit.class);
dataSource.setEntity(this);
this.addInput(dataSource);
ArrayList<Color4d> defSeriesColor = new ArrayList<>(0);
defSeriesColor.add(ColourInput.getColorWithName("red"));
seriesColorsList = new ColorListInput("SeriesColours", "Key Inputs", defSeriesColor);
seriesColorsList.setValidCountRange(1, Integer.MAX_VALUE);
this.addInput(seriesColorsList);
this.addSynonym(seriesColorsList, "LineColors");
showBars = new BooleanInput("ShowBars", "Key Inputs", false);
this.addInput(showBars);
secondaryDataSource = new SampleListInput("SecondaryDataSource", "Key Inputs", null);
secondaryDataSource.setUnitType(UserSpecifiedUnit.class);
secondaryDataSource.setEntity(this);
this.addInput(secondaryDataSource);
ArrayList<Color4d> defSecondaryLineColor = new ArrayList<>(0);
defSecondaryLineColor.add(ColourInput.getColorWithName("black"));
secondarySeriesColorsList = new ColorListInput("SecondarySeriesColours", "Key Inputs", defSecondaryLineColor);
secondarySeriesColorsList.setValidCountRange(1, Integer.MAX_VALUE);
this.addInput(secondarySeriesColorsList);
this.addSynonym(secondarySeriesColorsList, "SecondaryLineColors");
secondaryShowBars = new BooleanInput("SecondaryShowBars", "Key Inputs", false);
this.addInput(secondaryShowBars);
}
}
|
src/main/java/com/jaamsim/Graphics/XYGraph.java
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2009-2013 Ausenco Engineering Canada 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.Graphics;
import java.util.ArrayList;
import com.jaamsim.Samples.SampleListInput;
import com.jaamsim.input.BooleanInput;
import com.jaamsim.input.ColorListInput;
import com.jaamsim.input.ColourInput;
import com.jaamsim.input.Keyword;
import com.jaamsim.math.Color4d;
import com.jaamsim.units.UserSpecifiedUnit;
public class XYGraph extends GraphBasics {
// Key Inputs category
@Keyword(description = "One or more sources of data to be graphed on the primary y-axis.\n" +
"Each source is graphed as a separate line or bar and is specified by an Entity and its Output.",
example = "XYGraph1 DataSource { { Entity1 Output1 } { Entity2 Output2 } }")
protected final SampleListInput dataSource;
@Keyword(description = "A list of colors for the primary series to be displayed.\n" +
"Each color can be specified by either a color keyword or an RGB value.\n" +
"For multiple series, each color must be enclosed in braces.\n" +
"If only one color is provided, it is used for all the series.",
example = "XYGraph1 SeriesColors { { red } { green } }")
protected final ColorListInput seriesColorsList;
@Keyword(description = "Set to TRUE if the primary series are to be shown as bars instead of lines.",
example = "XYGraph1 ShowBars { TRUE }")
protected final BooleanInput showBars;
@Keyword(description = "One or more sources of data to be graphed on the secondary y-axis.\n" +
"Each source is graphed as a separate line or bar and is specified by an Entity and its Output.",
example = "XYGraph1 SecondaryDataSource { { Entity1 Output1 } { Entity2 Output2 } }")
protected final SampleListInput secondaryDataSource;
@Keyword(description = "A list of colors for the secondary series to be displayed.\n" +
"Each color can be specified by either a color keyword or an RGB value.\n" +
"For multiple series, each color must be enclosed in braces.\n" +
"If only one color is provided, it is used for all the series.",
example = "XYGraph1 SecondarySeriesColors { { red } { green } }")
protected final ColorListInput secondarySeriesColorsList;
@Keyword(description = "Set to TRUE if the secondary series are to be shown as bars instead of lines.",
example = "XYGraph1 SecondaryShowBars { TRUE }")
protected final BooleanInput secondaryShowBars;
{
// Key Inputs category
dataSource = new SampleListInput("DataSource", "Key Inputs", null);
dataSource.setUnitType(UserSpecifiedUnit.class);
dataSource.setEntity(this);
this.addInput(dataSource);
ArrayList<Color4d> defSeriesColor = new ArrayList<>(0);
defSeriesColor.add(ColourInput.getColorWithName("red"));
seriesColorsList = new ColorListInput("SeriesColours", "Key Inputs", defSeriesColor);
seriesColorsList.setValidCountRange(1, Integer.MAX_VALUE);
this.addInput(seriesColorsList);
this.addSynonym(seriesColorsList, "LineColors");
showBars = new BooleanInput("ShowBars", "Key Inputs", false);
this.addInput(showBars);
secondaryDataSource = new SampleListInput("SecondaryDataSource", "Key Inputs", null);
secondaryDataSource.setUnitType(UserSpecifiedUnit.class);
secondaryDataSource.setEntity(this);
this.addInput(secondaryDataSource);
ArrayList<Color4d> defSecondaryLineColor = new ArrayList<>(0);
defSecondaryLineColor.add(ColourInput.getColorWithName("black"));
secondarySeriesColorsList = new ColorListInput("SecondarySeriesColours", "Key Inputs", defSecondaryLineColor);
secondarySeriesColorsList.setValidCountRange(1, Integer.MAX_VALUE);
this.addInput(secondarySeriesColorsList);
this.addSynonym(secondarySeriesColorsList, "SecondaryLineColors");
secondaryShowBars = new BooleanInput("SecondaryShowBars", "Key Inputs", false);
this.addInput(secondaryShowBars);
}
}
|
JS: use exampleList input for XYGraph keywords
Signed-off-by: Harry King <409587b9e6671aa0763646191d292852dc49a658@gmail.com>
|
src/main/java/com/jaamsim/Graphics/XYGraph.java
|
JS: use exampleList input for XYGraph keywords
|
|
Java
|
apache-2.0
|
2c3521cfeaa86214ebdeceaa88f26bf694b43ab3
| 0
|
tmess567/syncope,securny/syncope,NuwanSameera/syncope,ilgrosso/syncope,securny/syncope,ilgrosso/syncope,securny/syncope,nscendoni/syncope,tmess567/syncope,ilgrosso/syncope,nscendoni/syncope,nscendoni/syncope,securny/syncope,giacomolm/syncope,apache/syncope,massx1/syncope,NuwanSameera/syncope,giacomolm/syncope,giacomolm/syncope,tmess567/syncope,NuwanSameera/syncope,apache/syncope,tmess567/syncope,ilgrosso/syncope,NuwanSameera/syncope,nscendoni/syncope,massx1/syncope,massx1/syncope,apache/syncope,apache/syncope,giacomolm/syncope
|
/*
* 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.syncope.hibernate;
import java.lang.reflect.Field;
import java.util.List;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.AttributeInfo;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.EnumMemberValue;
import javassist.bytecode.annotation.StringMemberValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
/**
* Enhance JPA entities for usage with Hibernate.
*/
public final class HibernateEnhancer {
/**
* Private empty constructor: this is an utility class!
*/
private HibernateEnhancer() {
}
public static void main(final String[] args) throws Exception {
if (args.length != 1) {
throw new IllegalArgumentException("Expecting classpath as single argument");
}
ClassPool classPool = ClassPool.getDefault();
classPool.appendClassPath(args[0]);
PathMatchingResourcePatternResolver resResolver =
new PathMatchingResourcePatternResolver(classPool.getClassLoader());
CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();
for (Resource resource : resResolver.getResources("classpath*:org/syncope/core/**/*.class")) {
MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader(resource);
if (metadataReader.getAnnotationMetadata().isAnnotated(Entity.class.getName())) {
Class entity = Class.forName(metadataReader.getClassMetadata().getClassName());
classPool.appendClassPath(new ClassClassPath(entity));
CtClass ctClass = ClassPool.getDefault().get(entity.getName());
if (ctClass.isFrozen()) {
ctClass.defrost();
}
ClassFile classFile = ctClass.getClassFile();
ConstPool constPool = classFile.getConstPool();
for (Field field : entity.getDeclaredFields()) {
AnnotationsAttribute annotAttr = null;
// Add Hibernate's @Type to each entity String field labeled @Lob,
// in order to enable PostgreSQL's LOB support.
if (field.isAnnotationPresent(Lob.class)) {
Annotation typeAnnot = new Annotation("org.hibernate.annotations.Type", constPool);
typeAnnot.addMemberValue("type",
new StringMemberValue("org.hibernate.type.StringClobType", constPool));
annotAttr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
annotAttr.addAnnotation(typeAnnot);
}
// Workaround for https://hibernate.onjira.com/browse/EJB-346
if (field.isAnnotationPresent(OneToMany.class) && field.getType().isAssignableFrom(List.class)
&& FetchType.EAGER == field.getAnnotation(OneToMany.class).fetch()) {
Annotation fetchAnnot = new Annotation("org.hibernate.annotations.Fetch", constPool);
EnumMemberValue emb = new EnumMemberValue(constPool);
emb.setType("org.hibernate.annotations.FetchMode");
emb.setValue("SUBSELECT");
fetchAnnot.addMemberValue("value", emb);
annotAttr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
annotAttr.addAnnotation(fetchAnnot);
}
if (annotAttr != null) {
CtField ctField = ctClass.getDeclaredField(field.getName());
List<AttributeInfo> formerAttrs = ctField.getFieldInfo().getAttributes();
for (AttributeInfo formerAttr : formerAttrs) {
if (formerAttr instanceof AnnotationsAttribute) {
for (Annotation annotation : ((AnnotationsAttribute) formerAttr).getAnnotations()) {
annotAttr.addAnnotation(annotation);
}
}
}
ctField.getFieldInfo().addAttribute(annotAttr);
}
}
ctClass.writeFile(args[0]);
}
}
}
}
|
hibernate-enhancer/src/main/java/org/syncope/hibernate/HibernateEnhancer.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.syncope.hibernate;
import java.lang.reflect.Field;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.StringMemberValue;
import javax.persistence.Entity;
import javax.persistence.Lob;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
/**
* Add Hibernate's @Type to each entity String field labeled @Lob, in order to
* enable PostgreSQL's LOB support.
*/
public final class HibernateEnhancer {
/**
* Private empty constructor: this is an utility class!
*/
private HibernateEnhancer() {
}
public static void main(final String[] args) throws Exception {
if (args.length != 1) {
throw new IllegalArgumentException("Expecting classpath as single argument");
}
ClassPool classPool = ClassPool.getDefault();
classPool.appendClassPath(args[0]);
PathMatchingResourcePatternResolver resResolver = new PathMatchingResourcePatternResolver(classPool
.getClassLoader());
CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();
for (Resource resource : resResolver.getResources("classpath*:org/syncope/core/**/*.class")) {
MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader(resource);
if (metadataReader.getAnnotationMetadata().isAnnotated(Entity.class.getName())) {
Class entity = Class.forName(metadataReader.getClassMetadata().getClassName());
classPool.appendClassPath(new ClassClassPath(entity));
CtClass ctClass = ClassPool.getDefault().get(entity.getName());
if (ctClass.isFrozen()) {
ctClass.defrost();
}
ClassFile classFile = ctClass.getClassFile();
ConstPool constPool = classFile.getConstPool();
for (Field field : entity.getDeclaredFields()) {
if (field.isAnnotationPresent(Lob.class)) {
AnnotationsAttribute typeAttr = new AnnotationsAttribute(constPool,
AnnotationsAttribute.visibleTag);
Annotation typeAnnot = new Annotation("org.hibernate.annotations.Type", constPool);
typeAnnot.addMemberValue("type", new StringMemberValue("org.hibernate.type.StringClobType",
constPool));
typeAttr.addAnnotation(typeAnnot);
CtField lobField = ctClass.getDeclaredField(field.getName());
lobField.getFieldInfo().addAttribute(typeAttr);
}
}
ctClass.writeFile(args[0]);
}
}
}
}
|
Adding workaround for https://hibernate.onjira.com/browse/EJB-346
git-svn-id: 51e9c0635e05060c2a7639df764e0b3ebb09013f@1305377 13f79535-47bb-0310-9956-ffa450edef68
|
hibernate-enhancer/src/main/java/org/syncope/hibernate/HibernateEnhancer.java
|
Adding workaround for https://hibernate.onjira.com/browse/EJB-346
|
|
Java
|
apache-2.0
|
da889efde74720a1fa5e4e1fd9e503d0a34364c6
| 0
|
izestrea/spring-boot,tsachev/spring-boot,xwjxwj30abc/spring-boot,roymanish/spring-boot,nandakishorm/spring-boot,existmaster/spring-boot,ractive/spring-boot,yuxiaole/spring-boot,jack-luj/spring-boot,VitDevelop/spring-boot,jjankar/spring-boot,bjornlindstrom/spring-boot,johnktims/spring-boot,forestqqqq/spring-boot,felipeg48/spring-boot,linead/spring-boot,simonnordberg/spring-boot,tan9/spring-boot,philwebb/spring-boot,nurkiewicz/spring-boot,lexandro/spring-boot,qerub/spring-boot,lucassaldanha/spring-boot,nisuhw/spring-boot,eonezhang/spring-boot,srinivasan01/spring-boot,nebhale/spring-boot,yuxiaole/spring-boot,hehuabing/spring-boot,satheeshmb/spring-boot,yuxiaole/spring-boot,yangdd1205/spring-boot,Makhlab/spring-boot,prasenjit-net/spring-boot,meftaul/spring-boot,tan9/spring-boot,simonnordberg/spring-boot,roberthafner/spring-boot,designreuse/spring-boot,srikalyan/spring-boot,MasterRoots/spring-boot,RainPlanter/spring-boot,kdvolder/spring-boot,RobertNickens/spring-boot,mebinjacob/spring-boot,htynkn/spring-boot,clarklj001/spring-boot,lingounet/spring-boot,sbcoba/spring-boot,kiranbpatil/spring-boot,zorosteven/spring-boot,ractive/spring-boot,balajinsr/spring-boot,Xaerxess/spring-boot,mdeinum/spring-boot,tiarebalbi/spring-boot,mouadtk/spring-boot,roymanish/spring-boot,hello2009chen/spring-boot,wwadge/spring-boot,mbnshankar/spring-boot,jayarampradhan/spring-boot,SPNilsen/spring-boot,nurkiewicz/spring-boot,javyzheng/spring-boot,hklv/spring-boot,deki/spring-boot,hklv/spring-boot,jxblum/spring-boot,Charkui/spring-boot,ralenmandao/spring-boot,navarrogabriela/spring-boot,rmoorman/spring-boot,MrMitchellMoore/spring-boot,tbadie/spring-boot,mevasaroj/jenkins2-course-spring-boot,ractive/spring-boot,crackien/spring-boot,lexandro/spring-boot,candrews/spring-boot,linead/spring-boot,lingounet/spring-boot,durai145/spring-boot,rstirling/spring-boot,herau/spring-boot,ojacquemart/spring-boot,htynkn/spring-boot,na-na/spring-boot,Pokbab/spring-boot,domix/spring-boot,cmsandiga/spring-boot,joansmith/spring-boot,ollie314/spring-boot,panbiping/spring-boot,habuma/spring-boot,lcardito/spring-boot,lif123/spring-boot,hqrt/jenkins2-course-spring-boot,jack-luj/spring-boot,donhuvy/spring-boot,rickeysu/spring-boot,fjlopez/spring-boot,jeremiahmarks/spring-boot,thomasdarimont/spring-boot,lingounet/spring-boot,Buzzardo/spring-boot,jayeshmuralidharan/spring-boot,johnktims/spring-boot,sankin/spring-boot,mbenson/spring-boot,fogone/spring-boot,na-na/spring-boot,balajinsr/spring-boot,kdvolder/spring-boot,fogone/spring-boot,jjankar/spring-boot,nisuhw/spring-boot,satheeshmb/spring-boot,drunklite/spring-boot,huangyugui/spring-boot,zhanhb/spring-boot,bbrouwer/spring-boot,balajinsr/spring-boot,paweldolecinski/spring-boot,zorosteven/spring-boot,yhj630520/spring-boot,xwjxwj30abc/spring-boot,ilayaperumalg/spring-boot,Charkui/spring-boot,prakashme/spring-boot,philwebb/spring-boot,jbovet/spring-boot,NetoDevel/spring-boot,hklv/spring-boot,rams2588/spring-boot,lenicliu/spring-boot,designreuse/spring-boot,mohican0607/spring-boot,mohican0607/spring-boot,izestrea/spring-boot,donhuvy/spring-boot,krmcbride/spring-boot,tan9/spring-boot,eonezhang/spring-boot,mohican0607/spring-boot,meloncocoo/spring-boot,vandan16/Vandan,eliudiaz/spring-boot,gorcz/spring-boot,orangesdk/spring-boot,jrrickard/spring-boot,cbtpro/spring-boot,lif123/spring-boot,ydsakyclguozi/spring-boot,lenicliu/spring-boot,master-slave/spring-boot,nareshmiriyala/spring-boot,javyzheng/spring-boot,damoyang/spring-boot,rmoorman/spring-boot,artembilan/spring-boot,axelfontaine/spring-boot,hqrt/jenkins2-course-spring-boot,5zzang/spring-boot,smilence1986/spring-boot,herau/spring-boot,hello2009chen/spring-boot,afroje-reshma/spring-boot-sample,RainPlanter/spring-boot,htynkn/spring-boot,vakninr/spring-boot,meloncocoo/spring-boot,artembilan/spring-boot,chrylis/spring-boot,marcellodesales/spring-boot,JiweiWong/spring-boot,axibase/spring-boot,DONIKAN/spring-boot,minmay/spring-boot,felipeg48/spring-boot,zhanhb/spring-boot,VitDevelop/spring-boot,felipeg48/spring-boot,eric-stanley/spring-boot,candrews/spring-boot,ojacquemart/spring-boot,jorgepgjr/spring-boot,tbbost/spring-boot,rickeysu/spring-boot,tiarebalbi/spring-boot,gorcz/spring-boot,prasenjit-net/spring-boot,izeye/spring-boot,rams2588/spring-boot,ChunPIG/spring-boot,javyzheng/spring-boot,mackeprm/spring-boot,pvorb/spring-boot,srikalyan/spring-boot,damoyang/spring-boot,tiarebalbi/spring-boot,balajinsr/spring-boot,jayeshmuralidharan/spring-boot,bclozel/spring-boot,jvz/spring-boot,vaseemahmed01/spring-boot,linead/spring-boot,wilkinsona/spring-boot,Buzzardo/spring-boot,tan9/spring-boot,chrylis/spring-boot,mevasaroj/jenkins2-course-spring-boot,spring-projects/spring-boot,paweldolecinski/spring-boot,durai145/spring-boot,kiranbpatil/spring-boot,PraveenkumarShethe/spring-boot,mdeinum/spring-boot,rams2588/spring-boot,mabernardo/spring-boot,xialeizhou/spring-boot,keithsjohnson/spring-boot,thomasdarimont/spring-boot,nandakishorm/spring-boot,olivergierke/spring-boot,M3lkior/spring-boot,jmnarloch/spring-boot,roymanish/spring-boot,sbcoba/spring-boot,AngusZhu/spring-boot,paddymahoney/spring-boot,lenicliu/spring-boot,tbadie/spring-boot,MrMitchellMoore/spring-boot,trecloux/spring-boot,meftaul/spring-boot,balajinsr/spring-boot,mackeprm/spring-boot,na-na/spring-boot,end-user/spring-boot,raiamber1/spring-boot,nevenc-pivotal/spring-boot,pvorb/spring-boot,kayelau/spring-boot,Buzzardo/spring-boot,nghiavo/spring-boot,SPNilsen/spring-boot,drunklite/spring-boot,wilkinsona/spring-boot,zorosteven/spring-boot,trecloux/spring-boot,mohican0607/spring-boot,AngusZhu/spring-boot,lburgazzoli/spring-boot,ApiSecRay/spring-boot,Nowheresly/spring-boot,smilence1986/spring-boot,jeremiahmarks/spring-boot,wilkinsona/spring-boot,michael-simons/spring-boot,artembilan/spring-boot,xialeizhou/spring-boot,lokbun/spring-boot,mbogoevici/spring-boot,eonezhang/spring-boot,hello2009chen/spring-boot,ameraljovic/spring-boot,SPNilsen/spring-boot,i007422/jenkins2-course-spring-boot,bbrouwer/spring-boot,mosoft521/spring-boot,kdvolder/spring-boot,felipeg48/spring-boot,xingguang2013/spring-boot,habuma/spring-boot,christian-posta/spring-boot,okba1/spring-boot,cleverjava/jenkins2-course-spring-boot,liupugong/spring-boot,Chomeh/spring-boot,mebinjacob/spring-boot,sungha/spring-boot,dreis2211/spring-boot,joshiste/spring-boot,imranansari/spring-boot,bsodzik/spring-boot,cmsandiga/spring-boot,trecloux/spring-boot,brettwooldridge/spring-boot,tiarebalbi/spring-boot,JiweiWong/spring-boot,liupd/spring-boot,akmaharshi/jenkins,patrikbeno/spring-boot,dfa1/spring-boot,xwjxwj30abc/spring-boot,DeezCashews/spring-boot,jxblum/spring-boot,mlc0202/spring-boot,imranansari/spring-boot,candrews/spring-boot,ollie314/spring-boot,master-slave/spring-boot,gorcz/spring-boot,spring-projects/spring-boot,durai145/spring-boot,joshthornhill/spring-boot,pnambiarsf/spring-boot,sbuettner/spring-boot,philwebb/spring-boot-concourse,buobao/spring-boot,mosen11/spring-boot,meftaul/spring-boot,ameraljovic/spring-boot,fireshort/spring-boot,jeremiahmarks/spring-boot,sbuettner/spring-boot,bijukunjummen/spring-boot,joshiste/spring-boot,prasenjit-net/spring-boot,gauravbrills/spring-boot,isopov/spring-boot,bijukunjummen/spring-boot,lexandro/spring-boot,paddymahoney/spring-boot,satheeshmb/spring-boot,domix/spring-boot,eddumelendez/spring-boot,DeezCashews/spring-boot,jorgepgjr/spring-boot,Nowheresly/spring-boot,yangdd1205/spring-boot,paweldolecinski/spring-boot,ractive/spring-boot,buobao/spring-boot,eddumelendez/spring-boot,nebhale/spring-boot,xingguang2013/spring-boot,sungha/spring-boot,mdeinum/spring-boot,playleud/spring-boot,domix/spring-boot,philwebb/spring-boot-concourse,xc145214/spring-boot,lenicliu/spring-boot,zhanhb/spring-boot,xiaoleiPENG/my-project,lucassaldanha/spring-boot,prasenjit-net/spring-boot,drunklite/spring-boot,rweisleder/spring-boot,murilobr/spring-boot,gregturn/spring-boot,raiamber1/spring-boot,bclozel/spring-boot,frost2014/spring-boot,pnambiarsf/spring-boot,RichardCSantana/spring-boot,rizwan18/spring-boot,rajendra-chola/jenkins2-course-spring-boot,huangyugui/spring-boot,mabernardo/spring-boot,dnsw83/spring-boot,M3lkior/spring-boot,kamilszymanski/spring-boot,zhanhb/spring-boot,marcellodesales/spring-boot,NetoDevel/spring-boot,patrikbeno/spring-boot,tsachev/spring-boot,neo4j-contrib/spring-boot,Xaerxess/spring-boot,ollie314/spring-boot,christian-posta/spring-boot,marcellodesales/spring-boot,nisuhw/spring-boot,smilence1986/spring-boot,sebastiankirsch/spring-boot,nandakishorm/spring-boot,clarklj001/spring-boot,shakuzen/spring-boot,bclozel/spring-boot,joansmith/spring-boot,frost2014/spring-boot,yhj630520/spring-boot,jayeshmuralidharan/spring-boot,imranansari/spring-boot,xingguang2013/spring-boot,joansmith/spring-boot,sbcoba/spring-boot,michael-simons/spring-boot,akmaharshi/jenkins,pnambiarsf/spring-boot,yunbian/spring-boot,jvz/spring-boot,npcode/spring-boot,shakuzen/spring-boot,yangdd1205/spring-boot,nurkiewicz/spring-boot,kdvolder/spring-boot,ptahchiev/spring-boot,Charkui/spring-boot,izeye/spring-boot,PraveenkumarShethe/spring-boot,AngusZhu/spring-boot,gauravbrills/spring-boot,SaravananParthasarathy/SPSDemo,dnsw83/spring-boot,vaseemahmed01/spring-boot,VitDevelop/spring-boot,prakashme/spring-boot,mabernardo/spring-boot,ojacquemart/spring-boot,mbnshankar/spring-boot,jorgepgjr/spring-boot,mbnshankar/spring-boot,akmaharshi/jenkins,xialeizhou/spring-boot,deki/spring-boot,ralenmandao/spring-boot,smayoorans/spring-boot,mbrukman/spring-boot,mbogoevici/spring-boot,soul2zimate/spring-boot,wwadge/spring-boot,nebhale/spring-boot,joshiste/spring-boot,mbrukman/spring-boot,krmcbride/spring-boot,xc145214/spring-boot,lenicliu/spring-boot,yuxiaole/spring-boot,kayelau/spring-boot,DONIKAN/spring-boot,izeye/spring-boot,jxblum/spring-boot,johnktims/spring-boot,sungha/spring-boot,mabernardo/spring-boot,snicoll/spring-boot,lif123/spring-boot,mackeprm/spring-boot,duandf35/spring-boot,patrikbeno/spring-boot,ralenmandao/spring-boot,AstaTus/spring-boot,fjlopez/spring-boot,mrumpf/spring-boot,forestqqqq/spring-boot,paddymahoney/spring-boot,ptahchiev/spring-boot,mbrukman/spring-boot,lburgazzoli/spring-boot,SaravananParthasarathy/SPSDemo,jrrickard/spring-boot,keithsjohnson/spring-boot,master-slave/spring-boot,axelfontaine/spring-boot,paweldolecinski/spring-boot,huangyugui/spring-boot,RishikeshDarandale/spring-boot,cleverjava/jenkins2-course-spring-boot,mbogoevici/spring-boot,frost2014/spring-boot,xc145214/spring-boot,johnktims/spring-boot,auvik/spring-boot,habuma/spring-boot,eliudiaz/spring-boot,MasterRoots/spring-boot,liupugong/spring-boot,donhuvy/spring-boot,pvorb/spring-boot,shakuzen/spring-boot,DONIKAN/spring-boot,mlc0202/spring-boot,jayarampradhan/spring-boot,sbcoba/spring-boot,auvik/spring-boot,RobertNickens/spring-boot,mosen11/spring-boot,mike-kukla/spring-boot,crackien/spring-boot,RobertNickens/spring-boot,isopov/spring-boot,npcode/spring-boot,peteyan/spring-boot,rweisleder/spring-boot,srinivasan01/spring-boot,end-user/spring-boot,rmoorman/spring-boot,eddumelendez/spring-boot,dreis2211/spring-boot,kdvolder/spring-boot,kdvolder/spring-boot,orangesdk/spring-boot,forestqqqq/spring-boot,nghiavo/spring-boot,rizwan18/spring-boot,htynkn/spring-boot,paddymahoney/spring-boot,eliudiaz/spring-boot,master-slave/spring-boot,eonezhang/spring-boot,Xaerxess/spring-boot,PraveenkumarShethe/spring-boot,lingounet/spring-boot,mdeinum/spring-boot,johnktims/spring-boot,nisuhw/spring-boot,nevenc-pivotal/spring-boot,rstirling/spring-boot,5zzang/spring-boot,clarklj001/spring-boot,Chomeh/spring-boot,xdweleven/spring-boot,mbenson/spring-boot,drunklite/spring-boot,vpavic/spring-boot,bjornlindstrom/spring-boot,Pokbab/spring-boot,prakashme/spring-boot,vpavic/spring-boot,aahlenst/spring-boot,joshiste/spring-boot,Buzzardo/spring-boot,Xaerxess/spring-boot,herau/spring-boot,jmnarloch/spring-boot,isopov/spring-boot,yhj630520/spring-boot,SaravananParthasarathy/SPSDemo,bjornlindstrom/spring-boot,spring-projects/spring-boot,M3lkior/spring-boot,murilobr/spring-boot,peteyan/spring-boot,qq83387856/spring-boot,jayarampradhan/spring-boot,joansmith/spring-boot,philwebb/spring-boot-concourse,liupd/spring-boot,zorosteven/spring-boot,tsachev/spring-boot,raiamber1/spring-boot,dfa1/spring-boot,nghialunhaiha/spring-boot,jxblum/spring-boot,paddymahoney/spring-boot,trecloux/spring-boot,xingguang2013/spring-boot,joshthornhill/spring-boot,joshthornhill/spring-boot,ChunPIG/spring-boot,frost2014/spring-boot,cbtpro/spring-boot,rams2588/spring-boot,joansmith/spring-boot,fogone/spring-boot,ameraljovic/spring-boot,rizwan18/spring-boot,shakuzen/spring-boot,hqrt/jenkins2-course-spring-boot,vakninr/spring-boot,eddumelendez/spring-boot,eric-stanley/spring-boot,bjornlindstrom/spring-boot,vakninr/spring-boot,allyjunio/spring-boot,wwadge/spring-boot,drumonii/spring-boot,xiaoleiPENG/my-project,dnsw83/spring-boot,mouadtk/spring-boot,linead/spring-boot,eric-stanley/spring-boot,designreuse/spring-boot,artembilan/spring-boot,prakashme/spring-boot,nghialunhaiha/spring-boot,mbenson/spring-boot,hello2009chen/spring-boot,smayoorans/spring-boot,jcastaldoFoodEssentials/spring-boot,tbbost/spring-boot,166yuan/spring-boot,ihoneymon/spring-boot,rweisleder/spring-boot,vandan16/Vandan,wwadge/spring-boot,sbuettner/spring-boot,panbiping/spring-boot,MasterRoots/spring-boot,playleud/spring-boot,qerub/spring-boot,jack-luj/spring-boot,na-na/spring-boot,tiarebalbi/spring-boot,afroje-reshma/spring-boot-sample,fjlopez/spring-boot,habuma/spring-boot,royclarkson/spring-boot,wilkinsona/spring-boot,jorgepgjr/spring-boot,AstaTus/spring-boot,michael-simons/spring-boot,meftaul/spring-boot,Chomeh/spring-boot,sungha/spring-boot,artembilan/spring-boot,xiaoleiPENG/my-project,bijukunjummen/spring-boot,kiranbpatil/spring-boot,mevasaroj/jenkins2-course-spring-boot,soul2zimate/spring-boot,cbtpro/spring-boot,nareshmiriyala/spring-boot,jforge/spring-boot,npcode/spring-boot,shakuzen/spring-boot,nghiavo/spring-boot,pnambiarsf/spring-boot,liupugong/spring-boot,nghialunhaiha/spring-boot,sankin/spring-boot,rstirling/spring-boot,candrews/spring-boot,deki/spring-boot,qerub/spring-boot,zhangshuangquan/spring-root,drumonii/spring-boot,hklv/spring-boot,thomasdarimont/spring-boot,candrews/spring-boot,jvz/spring-boot,tsachev/spring-boot,minmay/spring-boot,axibase/spring-boot,coolcao/spring-boot,navarrogabriela/spring-boot,peteyan/spring-boot,nareshmiriyala/spring-boot,existmaster/spring-boot,bclozel/spring-boot,mebinjacob/spring-boot,joshiste/spring-boot,rajendra-chola/jenkins2-course-spring-boot,vpavic/spring-boot,hqrt/jenkins2-course-spring-boot,kayelau/spring-boot,i007422/jenkins2-course-spring-boot,vandan16/Vandan,damoyang/spring-boot,end-user/spring-boot,AstaTus/spring-boot,scottfrederick/spring-boot,rstirling/spring-boot,bsodzik/spring-boot,huangyugui/spring-boot,drumonii/spring-boot,mbrukman/spring-boot,MasterRoots/spring-boot,mbenson/spring-boot,qq83387856/spring-boot,xiaoleiPENG/my-project,mike-kukla/spring-boot,keithsjohnson/spring-boot,RainPlanter/spring-boot,christian-posta/spring-boot,gauravbrills/spring-boot,qerub/spring-boot,rweisleder/spring-boot,mevasaroj/jenkins2-course-spring-boot,mike-kukla/spring-boot,mlc0202/spring-boot,soul2zimate/spring-boot,xwjxwj30abc/spring-boot,Chomeh/spring-boot,rmoorman/spring-boot,hehuabing/spring-boot,lokbun/spring-boot,fulvio-m/spring-boot,scottfrederick/spring-boot,jforge/spring-boot,philwebb/spring-boot,sebastiankirsch/spring-boot,RishikeshDarandale/spring-boot,ptahchiev/spring-boot,domix/spring-boot,donthadineshkumar/spring-boot,ydsakyclguozi/spring-boot,gorcz/spring-boot,MrMitchellMoore/spring-boot,ojacquemart/spring-boot,ihoneymon/spring-boot,fogone/spring-boot,michael-simons/spring-boot,isopov/spring-boot,yunbian/spring-boot,166yuan/spring-boot,eliudiaz/spring-boot,mackeprm/spring-boot,rmoorman/spring-boot,zorosteven/spring-boot,lburgazzoli/spring-boot,kamilszymanski/spring-boot,ChunPIG/spring-boot,aahlenst/spring-boot,AstaTus/spring-boot,nareshmiriyala/spring-boot,wilkinsona/spring-boot,aahlenst/spring-boot,linead/spring-boot,Charkui/spring-boot,5zzang/spring-boot,joshthornhill/spring-boot,kamilszymanski/spring-boot,donthadineshkumar/spring-boot,drumonii/spring-boot,ChunPIG/spring-boot,sankin/spring-boot,ydsakyclguozi/spring-boot,mohican0607/spring-boot,mbnshankar/spring-boot,akmaharshi/jenkins,aahlenst/spring-boot,buobao/spring-boot,jrrickard/spring-boot,felipeg48/spring-boot,rickeysu/spring-boot,okba1/spring-boot,lokbun/spring-boot,zhangshuangquan/spring-root,10045125/spring-boot,sebastiankirsch/spring-boot,lcardito/spring-boot,minmay/spring-boot,ameraljovic/spring-boot,lucassaldanha/spring-boot,playleud/spring-boot,deki/spring-boot,JiweiWong/spring-boot,designreuse/spring-boot,mbnshankar/spring-boot,Makhlab/spring-boot,qq83387856/spring-boot,gorcz/spring-boot,ApiSecRay/spring-boot,afroje-reshma/spring-boot-sample,rajendra-chola/jenkins2-course-spring-boot,10045125/spring-boot,soul2zimate/spring-boot,philwebb/spring-boot,dfa1/spring-boot,mackeprm/spring-boot,Pokbab/spring-boot,xc145214/spring-boot,jack-luj/spring-boot,eliudiaz/spring-boot,AngusZhu/spring-boot,nareshmiriyala/spring-boot,mrumpf/spring-boot,jbovet/spring-boot,roymanish/spring-boot,orangesdk/spring-boot,axelfontaine/spring-boot,xiaoleiPENG/my-project,mevasaroj/jenkins2-course-spring-boot,bclozel/spring-boot,cleverjava/jenkins2-course-spring-boot,lexandro/spring-boot,DeezCashews/spring-boot,shangyi0102/spring-boot,lif123/spring-boot,ApiSecRay/spring-boot,jcastaldoFoodEssentials/spring-boot,jayeshmuralidharan/spring-boot,xdweleven/spring-boot,brettwooldridge/spring-boot,na-na/spring-boot,duandf35/spring-boot,philwebb/spring-boot-concourse,chrylis/spring-boot,ptahchiev/spring-boot,vakninr/spring-boot,jforge/spring-boot,izeye/spring-boot,nghialunhaiha/spring-boot,ihoneymon/spring-boot,M3lkior/spring-boot,sungha/spring-boot,RobertNickens/spring-boot,PraveenkumarShethe/spring-boot,5zzang/spring-boot,rweisleder/spring-boot,shangyi0102/spring-boot,playleud/spring-boot,axelfontaine/spring-boot,mebinjacob/spring-boot,afroje-reshma/spring-boot-sample,166yuan/spring-boot,coolcao/spring-boot,thomasdarimont/spring-boot,javyzheng/spring-boot,mdeinum/spring-boot,RainPlanter/spring-boot,drumonii/spring-boot,lcardito/spring-boot,xdweleven/spring-boot,aahlenst/spring-boot,trecloux/spring-boot,lcardito/spring-boot,vaseemahmed01/spring-boot,PraveenkumarShethe/spring-boot,philwebb/spring-boot,DONIKAN/spring-boot,tbadie/spring-boot,javyzheng/spring-boot,dreis2211/spring-boot,M3lkior/spring-boot,mrumpf/spring-boot,fulvio-m/spring-boot,nevenc-pivotal/spring-boot,dreis2211/spring-boot,NetoDevel/spring-boot,bclozel/spring-boot,tiarebalbi/spring-boot,fireshort/spring-boot,rizwan18/spring-boot,chrylis/spring-boot,cleverjava/jenkins2-course-spring-boot,qq83387856/spring-boot,jjankar/spring-boot,VitDevelop/spring-boot,jorgepgjr/spring-boot,nghiavo/spring-boot,srinivasan01/spring-boot,liupd/spring-boot,wilkinsona/spring-boot,sankin/spring-boot,JiweiWong/spring-boot,jforge/spring-boot,zhangshuangquan/spring-root,tbbost/spring-boot,joshiste/spring-boot,jrrickard/spring-boot,nandakishorm/spring-boot,vpavic/spring-boot,Buzzardo/spring-boot,brettwooldridge/spring-boot,jayeshmuralidharan/spring-boot,gauravbrills/spring-boot,existmaster/spring-boot,gauravbrills/spring-boot,zhangshuangquan/spring-root,vaseemahmed01/spring-boot,duandf35/spring-boot,durai145/spring-boot,ollie314/spring-boot,nevenc-pivotal/spring-boot,sbuettner/spring-boot,snicoll/spring-boot,neo4j-contrib/spring-boot,meloncocoo/spring-boot,simonnordberg/spring-boot,chrylis/spring-boot,lexandro/spring-boot,AngusZhu/spring-boot,damoyang/spring-boot,meloncocoo/spring-boot,rizwan18/spring-boot,ptahchiev/spring-boot,minmay/spring-boot,nelswadycki/spring-boot,lif123/spring-boot,philwebb/spring-boot,ractive/spring-boot,fulvio-m/spring-boot,clarklj001/spring-boot,xialeizhou/spring-boot,mbenson/spring-boot,jeremiahmarks/spring-boot,nelswadycki/spring-boot,ApiSecRay/spring-boot,smayoorans/spring-boot,jayarampradhan/spring-boot,rajendra-chola/jenkins2-course-spring-boot,chrylis/spring-boot,jmnarloch/spring-boot,fulvio-m/spring-boot,mebinjacob/spring-boot,habuma/spring-boot,Nowheresly/spring-boot,eddumelendez/spring-boot,izeye/spring-boot,meftaul/spring-boot,clarklj001/spring-boot,Makhlab/spring-boot,coolcao/spring-boot,i007422/jenkins2-course-spring-boot,marcellodesales/spring-boot,gregturn/spring-boot,deki/spring-boot,jforge/spring-boot,kamilszymanski/spring-boot,ilayaperumalg/spring-boot,axibase/spring-boot,vakninr/spring-boot,wwadge/spring-boot,end-user/spring-boot,marcellodesales/spring-boot,MasterRoots/spring-boot,bsodzik/spring-boot,coolcao/spring-boot,mabernardo/spring-boot,satheeshmb/spring-boot,NetoDevel/spring-boot,SPNilsen/spring-boot,mike-kukla/spring-boot,Xaerxess/spring-boot,ilayaperumalg/spring-boot,liupugong/spring-boot,satheeshmb/spring-boot,i007422/jenkins2-course-spring-boot,donthadineshkumar/spring-boot,dreis2211/spring-boot,forestqqqq/spring-boot,lucassaldanha/spring-boot,RichardCSantana/spring-boot,aahlenst/spring-boot,dfa1/spring-boot,okba1/spring-boot,buobao/spring-boot,VitDevelop/spring-boot,DONIKAN/spring-boot,donhuvy/spring-boot,sankin/spring-boot,dnsw83/spring-boot,lokbun/spring-boot,nghialunhaiha/spring-boot,ameraljovic/spring-boot,rickeysu/spring-boot,liupd/spring-boot,brettwooldridge/spring-boot,mosen11/spring-boot,patrikbeno/spring-boot,existmaster/spring-boot,Makhlab/spring-boot,auvik/spring-boot,cmsandiga/spring-boot,mosoft521/spring-boot,mbogoevici/spring-boot,kayelau/spring-boot,shakuzen/spring-boot,mdeinum/spring-boot,nisuhw/spring-boot,fireshort/spring-boot,simonnordberg/spring-boot,donthadineshkumar/spring-boot,playleud/spring-boot,fireshort/spring-boot,Chomeh/spring-boot,tsachev/spring-boot,olivergierke/spring-boot,jvz/spring-boot,mosoft521/spring-boot,ydsakyclguozi/spring-boot,axibase/spring-boot,damoyang/spring-boot,zhangshuangquan/spring-root,christian-posta/spring-boot,scottfrederick/spring-boot,ilayaperumalg/spring-boot,cmsandiga/spring-boot,krmcbride/spring-boot,nebhale/spring-boot,yunbian/spring-boot,smilence1986/spring-boot,durai145/spring-boot,hehuabing/spring-boot,michael-simons/spring-boot,duandf35/spring-boot,srikalyan/spring-boot,vandan16/Vandan,lokbun/spring-boot,olivergierke/spring-boot,RainPlanter/spring-boot,scottfrederick/spring-boot,npcode/spring-boot,NetoDevel/spring-boot,fireshort/spring-boot,bijukunjummen/spring-boot,royclarkson/spring-boot,RichardCSantana/spring-boot,Makhlab/spring-boot,tbbost/spring-boot,donhuvy/spring-boot,SaravananParthasarathy/SPSDemo,panbiping/spring-boot,lburgazzoli/spring-boot,minmay/spring-boot,166yuan/spring-boot,Buzzardo/spring-boot,SPNilsen/spring-boot,panbiping/spring-boot,SaravananParthasarathy/SPSDemo,cbtpro/spring-boot,navarrogabriela/spring-boot,mosen11/spring-boot,mlc0202/spring-boot,vandan16/Vandan,jayarampradhan/spring-boot,raiamber1/spring-boot,cleverjava/jenkins2-course-spring-boot,tbadie/spring-boot,yhj630520/spring-boot,xdweleven/spring-boot,sebastiankirsch/spring-boot,royclarkson/spring-boot,orangesdk/spring-boot,RichardCSantana/spring-boot,htynkn/spring-boot,hqrt/jenkins2-course-spring-boot,yunbian/spring-boot,sbuettner/spring-boot,srinivasan01/spring-boot,izestrea/spring-boot,scottfrederick/spring-boot,royclarkson/spring-boot,eonezhang/spring-boot,panbiping/spring-boot,fulvio-m/spring-boot,jack-luj/spring-boot,mosoft521/spring-boot,ihoneymon/spring-boot,ydsakyclguozi/spring-boot,nelswadycki/spring-boot,RishikeshDarandale/spring-boot,nandakishorm/spring-boot,herau/spring-boot,jcastaldoFoodEssentials/spring-boot,rstirling/spring-boot,bsodzik/spring-boot,dreis2211/spring-boot,keithsjohnson/spring-boot,allyjunio/spring-boot,pvorb/spring-boot,yuxiaole/spring-boot,AstaTus/spring-boot,rams2588/spring-boot,lingounet/spring-boot,fogone/spring-boot,jjankar/spring-boot,allyjunio/spring-boot,jeremiahmarks/spring-boot,vpavic/spring-boot,neo4j-contrib/spring-boot,mosoft521/spring-boot,neo4j-contrib/spring-boot,ilayaperumalg/spring-boot,donthadineshkumar/spring-boot,xdweleven/spring-boot,domix/spring-boot,zhanhb/spring-boot,jmnarloch/spring-boot,ralenmandao/spring-boot,kiranbpatil/spring-boot,afroje-reshma/spring-boot-sample,isopov/spring-boot,Pokbab/spring-boot,nghiavo/spring-boot,forestqqqq/spring-boot,yhj630520/spring-boot,xwjxwj30abc/spring-boot,smayoorans/spring-boot,hklv/spring-boot,dfa1/spring-boot,joshthornhill/spring-boot,axelfontaine/spring-boot,end-user/spring-boot,master-slave/spring-boot,royclarkson/spring-boot,imranansari/spring-boot,roymanish/spring-boot,soul2zimate/spring-boot,roberthafner/spring-boot,DeezCashews/spring-boot,crackien/spring-boot,i007422/jenkins2-course-spring-boot,crackien/spring-boot,murilobr/spring-boot,qq83387856/spring-boot,brettwooldridge/spring-boot,liupd/spring-boot,tbbost/spring-boot,Nowheresly/spring-boot,Charkui/spring-boot,ojacquemart/spring-boot,roberthafner/spring-boot,mrumpf/spring-boot,kamilszymanski/spring-boot,drunklite/spring-boot,Nowheresly/spring-boot,mrumpf/spring-boot,nurkiewicz/spring-boot,jmnarloch/spring-boot,jvz/spring-boot,huangyugui/spring-boot,roberthafner/spring-boot,npcode/spring-boot,buobao/spring-boot,ptahchiev/spring-boot,mouadtk/spring-boot,christian-posta/spring-boot,5zzang/spring-boot,eddumelendez/spring-boot,nebhale/spring-boot,ApiSecRay/spring-boot,prasenjit-net/spring-boot,raiamber1/spring-boot,RishikeshDarandale/spring-boot,patrikbeno/spring-boot,mouadtk/spring-boot,frost2014/spring-boot,ihoneymon/spring-boot,hehuabing/spring-boot,okba1/spring-boot,thomasdarimont/spring-boot,hehuabing/spring-boot,jcastaldoFoodEssentials/spring-boot,designreuse/spring-boot,imranansari/spring-boot,izestrea/spring-boot,scottfrederick/spring-boot,jxblum/spring-boot,mosen11/spring-boot,tan9/spring-boot,tbadie/spring-boot,vpavic/spring-boot,krmcbride/spring-boot,jbovet/spring-boot,gregturn/spring-boot,lcardito/spring-boot,hello2009chen/spring-boot,RishikeshDarandale/spring-boot,tsachev/spring-boot,liupugong/spring-boot,paweldolecinski/spring-boot,ChunPIG/spring-boot,RichardCSantana/spring-boot,mbrukman/spring-boot,vaseemahmed01/spring-boot,rajendra-chola/jenkins2-course-spring-boot,yunbian/spring-boot,kiranbpatil/spring-boot,duandf35/spring-boot,rweisleder/spring-boot,spring-projects/spring-boot,olivergierke/spring-boot,prakashme/spring-boot,jcastaldoFoodEssentials/spring-boot,srikalyan/spring-boot,smilence1986/spring-boot,crackien/spring-boot,pnambiarsf/spring-boot,xingguang2013/spring-boot,bbrouwer/spring-boot,htynkn/spring-boot,jbovet/spring-boot,philwebb/spring-boot-concourse,mike-kukla/spring-boot,navarrogabriela/spring-boot,peteyan/spring-boot,166yuan/spring-boot,eric-stanley/spring-boot,drumonii/spring-boot,akmaharshi/jenkins,zhanhb/spring-boot,axibase/spring-boot,bijukunjummen/spring-boot,Pokbab/spring-boot,MrMitchellMoore/spring-boot,RobertNickens/spring-boot,felipeg48/spring-boot,shangyi0102/spring-boot,qerub/spring-boot,habuma/spring-boot,mlc0202/spring-boot,meloncocoo/spring-boot,coolcao/spring-boot,nelswadycki/spring-boot,shangyi0102/spring-boot,isopov/spring-boot,roberthafner/spring-boot,allyjunio/spring-boot,jrrickard/spring-boot,krmcbride/spring-boot,lucassaldanha/spring-boot,sebastiankirsch/spring-boot,jxblum/spring-boot,peteyan/spring-boot,JiweiWong/spring-boot,snicoll/spring-boot,nelswadycki/spring-boot,navarrogabriela/spring-boot,olivergierke/spring-boot,ralenmandao/spring-boot,bbrouwer/spring-boot,bjornlindstrom/spring-boot,fjlopez/spring-boot,bbrouwer/spring-boot,bsodzik/spring-boot,izestrea/spring-boot,murilobr/spring-boot,pvorb/spring-boot,mbogoevici/spring-boot,ilayaperumalg/spring-boot,cmsandiga/spring-boot,shangyi0102/spring-boot,neo4j-contrib/spring-boot,srikalyan/spring-boot,existmaster/spring-boot,sbcoba/spring-boot,kayelau/spring-boot,spring-projects/spring-boot,spring-projects/spring-boot,ihoneymon/spring-boot,eric-stanley/spring-boot,jjankar/spring-boot,michael-simons/spring-boot,auvik/spring-boot,lburgazzoli/spring-boot,mbenson/spring-boot,simonnordberg/spring-boot,rickeysu/spring-boot,donhuvy/spring-boot,ollie314/spring-boot,nevenc-pivotal/spring-boot,dnsw83/spring-boot,srinivasan01/spring-boot,fjlopez/spring-boot,MrMitchellMoore/spring-boot,murilobr/spring-boot,auvik/spring-boot,DeezCashews/spring-boot,cbtpro/spring-boot,smayoorans/spring-boot,orangesdk/spring-boot,nurkiewicz/spring-boot,xc145214/spring-boot,herau/spring-boot,jbovet/spring-boot,mouadtk/spring-boot,xialeizhou/spring-boot,keithsjohnson/spring-boot,okba1/spring-boot,allyjunio/spring-boot,10045125/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.loader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import org.springframework.boot.loader.archive.Archive;
import org.springframework.boot.loader.archive.Archive.Entry;
import org.springframework.boot.loader.archive.Archive.EntryFilter;
import org.springframework.boot.loader.archive.ExplodedArchive;
import org.springframework.boot.loader.archive.FilteredArchive;
import org.springframework.boot.loader.archive.JarFileArchive;
import org.springframework.boot.loader.util.SystemPropertyUtils;
/**
* {@link Launcher} for archives with user-configured classpath and main class via a
* properties file. This model is often more flexible and more amenable to creating
* well-behaved OS-level services than a model based on executable jars.
*
* <p>
* Looks in various places for a properties file to extract loader settings, defaulting to
* <code>application.properties</code> either on the current classpath or in the current
* working directory. The name of the properties file can be changed by setting a System
* property <code>loader.config.name</code> (e.g. <code>-Dloader.config.name=foo</code>
* will look for <code>foo.properties</code>. If that file doesn't exist then tries
* <code>loader.config.location</code> (with allowed prefixes <code>classpath:</code> and
* <code>file:</code> or any valid URL). Once that file is located turns it into
* Properties and extracts optional values (which can also be provided overridden as
* System properties in case the file doesn't exist):
*
* <ul>
* <li><code>loader.path</code>: a comma-separated list of directories to append to the
* classpath (containing file resources and/or nested archives in *.jar or *.zip).
* Defaults to <code>lib</code> (i.e. a directory in the current working directory)</li>
* <li><code>loader.main</code>: the main method to delegate execution to once the class
* loader is set up. No default, but will fall back to looking for a
* <code>Start-Class</code> in a <code>MANIFEST.MF</code>, if there is one in
* <code>${loader.home}/META-INF</code>.</li>
* </ul>
*
* @author Dave Syer
*/
public class PropertiesLauncher extends Launcher {
private Logger logger = Logger.getLogger(Launcher.class.getName());
/**
* Properties key for main class
*/
public static final String MAIN = "loader.main";
/**
* Properties key for classpath entries (directories possibly containing jars).
* Defaults to "lib/" (relative to {@link #HOME loader home directory}).
*/
public static final String PATH = "loader.path";
/**
* Properties key for home directory. This is the location of external configuration
* if not on classpath, and also the base path for any relative paths in the
* {@link #PATH loader path}. Defaults to current working directory (
* <code>${user.home}</code>).
*/
public static final String HOME = "loader.home";
/**
* Properties key for name of external configuration file (excluding suffix). Defaults
* to "application". Ignored if {@link #CONFIG_LOCATION loader config location} is
* provided instead.
*/
public static final String CONFIG_NAME = "loader.config.name";
/**
* Properties key for config file location (including optional classpath:, file: or
* URL prefix)
*/
public static final String CONFIG_LOCATION = "loader.config.location";
/**
* Properties key for boolean flag (default false) which if set will cause the
* external configuration properties to be copied to System properties (assuming that
* is allowed by Java security).
*/
public static final String SET_SYSTEM_PROPERTIES = "loader.system";
private static final List<String> DEFAULT_PATHS = Arrays.asList("lib/");
private final File home;
private List<String> paths = new ArrayList<String>(DEFAULT_PATHS);
private Properties properties = new Properties();
public PropertiesLauncher() {
try {
this.home = getHomeDirectory();
initializeProperties(this.home);
initializePaths();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
protected File getHomeDirectory() {
return new File(SystemPropertyUtils.resolvePlaceholders(System.getProperty(HOME,
"${user.dir}")));
}
private void initializeProperties(File home) throws Exception, IOException {
String config = "classpath:"
+ SystemPropertyUtils.resolvePlaceholders(SystemPropertyUtils
.getProperty(CONFIG_NAME, "application")) + ".properties";
config = SystemPropertyUtils.resolvePlaceholders(SystemPropertyUtils.getProperty(
CONFIG_LOCATION, config));
InputStream resource = getResource(config);
if (resource != null) {
this.logger.info("Found: " + config);
try {
this.properties.load(resource);
}
finally {
resource.close();
}
for (Object key : Collections.list(this.properties.propertyNames())) {
String text = this.properties.getProperty((String) key);
String value = SystemPropertyUtils.resolvePlaceholders(this.properties,
text);
if (value != null) {
this.properties.put(key, value);
}
}
if (SystemPropertyUtils.resolvePlaceholders(
"${" + SET_SYSTEM_PROPERTIES + ":false}").equals("true")) {
this.logger.info("Adding resolved properties to System properties");
for (Object key : Collections.list(this.properties.propertyNames())) {
String value = this.properties.getProperty((String) key);
System.setProperty((String) key, value);
}
}
}
else {
this.logger.info("Not found: " + config);
}
}
private InputStream getResource(String config) throws Exception {
if (config.startsWith("classpath:")) {
return getClasspathResource(config.substring("classpath:".length()));
}
config = stripFileUrlPrefix(config);
if (isUrl(config)) {
return getURLResource(config);
}
return getFileResource(config);
}
private String stripFileUrlPrefix(String config) {
if (config.startsWith("file:")) {
config = config.substring("file:".length());
if (config.startsWith("//")) {
config = config.substring(2);
}
}
return config;
}
private boolean isUrl(String config) {
return config.contains("://");
}
private InputStream getClasspathResource(String config) {
while (config.startsWith("/")) {
config = config.substring(1);
}
config = "/" + config;
this.logger.fine("Trying classpath: " + config);
return getClass().getResourceAsStream(config);
}
private InputStream getFileResource(String config) throws Exception {
File file = new File(config);
this.logger.fine("Trying file: " + config);
if (file.canRead()) {
return new FileInputStream(file);
}
return null;
}
private InputStream getURLResource(String config) throws Exception {
URL url = new URL(config);
if (exists(url)) {
URLConnection con = url.openConnection();
try {
return con.getInputStream();
}
catch (IOException ex) {
// Close the HTTP connection (if applicable).
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).disconnect();
}
throw ex;
}
}
return null;
}
private boolean exists(URL url) throws IOException {
// Try a URL connection content-length header...
URLConnection connection = url.openConnection();
try {
connection.setUseCaches(connection.getClass().getSimpleName()
.startsWith("JNLP"));
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("HEAD");
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return true;
}
else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
}
return (connection.getContentLength() >= 0);
}
finally {
if (connection instanceof HttpURLConnection) {
((HttpURLConnection) connection).disconnect();
}
}
}
private void initializePaths() throws IOException {
String path = SystemPropertyUtils.getProperty(PATH);
if (path == null) {
path = this.properties.getProperty(PATH);
}
if (path != null) {
this.paths = parsePathsProperty(SystemPropertyUtils.resolvePlaceholders(path));
}
this.logger.info("Nested archive paths: " + this.paths);
}
private List<String> parsePathsProperty(String commaSeparatedPaths) {
List<String> paths = new ArrayList<String>();
for (String path : commaSeparatedPaths.split(",")) {
path = cleanupPath(path);
// Empty path is always on the classpath so no need for it to be explicitly
// listed here
if (!(path.equals(".") || path.equals(""))) {
paths.add(path);
}
}
return paths;
}
@Override
protected String getMainClass() throws Exception {
String property = SystemPropertyUtils.getProperty(MAIN);
if (property != null) {
String mainClass = SystemPropertyUtils.resolvePlaceholders(property);
this.logger.info("Main class from environment: " + mainClass);
return mainClass;
}
if (this.properties.containsKey(MAIN)) {
String mainClass = SystemPropertyUtils.resolvePlaceholders(this.properties
.getProperty(MAIN));
this.logger.info("Main class from properties: " + mainClass);
return mainClass;
}
try {
// Prefer home dir for MANIFEST if there is one
String mainClass = new ExplodedArchive(this.home).getMainClass();
this.logger.info("Main class from home directory manifest: " + mainClass);
return mainClass;
}
catch (IllegalStateException ex) {
// Otherwise try the parent archive
String mainClass = createArchive().getMainClass();
this.logger.info("Main class from archive manifest: " + mainClass);
return mainClass;
}
}
@Override
protected List<Archive> getClassPathArchives() throws Exception {
List<Archive> lib = new ArrayList<Archive>();
for (String path : this.paths) {
for (Archive archive : getClassPathArchives(path)) {
List<Archive> nested = new ArrayList<Archive>(
archive.getNestedArchives(new ArchiveEntryFilter()));
nested.add(0, archive);
lib.addAll(nested);
}
}
addParentClassLoaderEntries(lib);
return lib;
}
private List<Archive> getClassPathArchives(String path) throws Exception {
String root = cleanupPath(stripFileUrlPrefix(path));
List<Archive> lib = new ArrayList<Archive>();
File file = new File(root);
if (!root.startsWith("/")) {
file = new File(this.home, root);
}
if (file.isDirectory()) {
this.logger.info("Adding classpath entries from " + file);
Archive archive = new ExplodedArchive(file);
lib.add(archive);
}
Archive archive = getArchive(file);
if (archive != null) {
this.logger.info("Adding classpath entries from nested " + archive.getUrl()
+ root);
lib.add(archive);
}
Archive nested = getNestedArchive(root);
if (nested != null) {
this.logger.info("Adding classpath entries from nested " + nested.getUrl()
+ root);
lib.add(nested);
}
return lib;
}
private Archive getArchive(File file) throws IOException {
String name = file.getName().toLowerCase();
if (name.endsWith(".jar") || name.endsWith(".zip")) {
return new JarFileArchive(file);
}
return null;
}
private Archive getNestedArchive(final String root) throws Exception {
Archive parent = createArchive();
if (root.startsWith("/") || parent.getUrl().equals(this.home.toURI().toURL())) {
// If home dir is same as parent archive, no need to add it twice.
return null;
}
EntryFilter filter = new PrefixMatchingArchiveFilter(root);
if (parent.getNestedArchives(filter).isEmpty()) {
return null;
}
// If there are more archives nested in this subdirectory (root) then create a new
// virtual archive for them, and have it added to the classpath
return new FilteredArchive(parent, filter);
}
private Archive createArchive() throws Exception {
ProtectionDomain protectionDomain = getClass().getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
URI location = (codeSource == null ? null : codeSource.getLocation().toURI());
String path = (location == null ? null : location.getPath());
if (path == null) {
throw new IllegalStateException("Unable to determine code source archive");
}
File root = new File(path);
if (!root.exists()) {
throw new IllegalStateException(
"Unable to determine code source archive from " + root);
}
return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root));
}
private void addParentClassLoaderEntries(List<Archive> lib) throws IOException,
URISyntaxException {
ClassLoader parentClassLoader = getClass().getClassLoader();
if (parentClassLoader instanceof URLClassLoader) {
URLClassLoader urlClassLoader = (URLClassLoader) parentClassLoader;
for (URL url : urlClassLoader.getURLs()) {
if (url.toString().endsWith(".jar") || url.toString().endsWith(".zip")) {
lib.add(0, new JarFileArchive(new File(url.toURI())));
}
else if (url.toString().endsWith("/*")) {
String name = url.getFile();
lib.add(0,
new ExplodedArchive(new File(name.substring(0,
name.length() - 1))));
}
else {
lib.add(0, new ExplodedArchive(new File(url.getFile())));
}
}
}
}
private String cleanupPath(String path) {
path = path.trim();
if (path.toLowerCase().endsWith(".jar") || path.toLowerCase().endsWith(".zip")) {
return path;
}
if (path.endsWith("/*")) {
path = path.substring(0, path.length() - 1);
}
else {
// It's a directory
if (!path.endsWith("/")) {
path = path + "/";
}
}
// No need for current dir path
if (path.startsWith("./")) {
path = path.substring(2);
}
return path;
}
public static void main(String[] args) {
new PropertiesLauncher().launch(args);
}
/**
* Convenience class for finding nested archives (archive entries that can be
* classpath entries).
*/
private static final class ArchiveEntryFilter implements EntryFilter {
private static final AsciiBytes DOT_JAR = new AsciiBytes(".jar");
private static final AsciiBytes DOT_ZIP = new AsciiBytes(".zip");
@Override
public boolean matches(Entry entry) {
return entry.isDirectory() || entry.getName().endsWith(DOT_JAR)
|| entry.getName().endsWith(DOT_ZIP);
}
}
/**
* Convenience class for finding nested archives that have a prefix in their file path
* (e.g. "lib/").
*/
private static final class PrefixMatchingArchiveFilter implements EntryFilter {
private final AsciiBytes prefix;
private final ArchiveEntryFilter filter = new ArchiveEntryFilter();
private PrefixMatchingArchiveFilter(String prefix) {
this.prefix = new AsciiBytes(prefix);
}
@Override
public boolean matches(Entry entry) {
return entry.getName().startsWith(this.prefix) && this.filter.matches(entry);
}
}
}
|
spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.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.loader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import org.springframework.boot.loader.archive.Archive;
import org.springframework.boot.loader.archive.Archive.Entry;
import org.springframework.boot.loader.archive.Archive.EntryFilter;
import org.springframework.boot.loader.archive.ExplodedArchive;
import org.springframework.boot.loader.archive.FilteredArchive;
import org.springframework.boot.loader.archive.JarFileArchive;
import org.springframework.boot.loader.util.SystemPropertyUtils;
/**
* {@link Launcher} for archives with user-configured classpath and main class via a
* properties file. This model is often more flexible and more amenable to creating
* well-behaved OS-level services than a model based on executable jars.
*
* <p>
* Looks in various places for a properties file to extract loader settings, defaulting to
* <code>application.properties</code> either on the current classpath or in the current
* working directory. The name of the properties file can be changed by setting a System
* property <code>loader.config.name</code> (e.g. <code>-Dloader.config.name=foo</code>
* will look for <code>foo.properties</code>. If that file doesn't exist then tries
* <code>loader.config.location</code> (with allowed prefixes <code>classpath:</code> and
* <code>file:</code> or any valid URL). Once that file is located turns it into
* Properties and extracts optional values (which can also be provided overridden as
* System properties in case the file doesn't exist):
*
* <ul>
* <li><code>loader.path</code>: a comma-separated list of directories to append to the
* classpath (containing file resources and/or nested archives in *.jar or *.zip).
* Defaults to <code>lib</code> (i.e. a directory in the current working directory)</li>
* <li><code>loader.main</code>: the main method to delegate execution to once the class
* loader is set up. No default, but will fall back to looking for a
* <code>Start-Class</code> in a <code>MANIFEST.MF</code>, if there is one in
* <code>${loader.home}/META-INF</code>.</li>
* </ul>
*
* @author Dave Syer
*/
public class PropertiesLauncher extends Launcher {
private Logger logger = Logger.getLogger(Launcher.class.getName());
/**
* Properties key for main class
*/
public static final String MAIN = "loader.main";
/**
* Properties key for classpath entries (directories possibly containing jars).
* Defaults to "lib/" (relative to {@link #HOME loader home directory}).
*/
public static final String PATH = "loader.path";
/**
* Properties key for home directory. This is the location of external configuration
* if not on classpath, and also the base path for any relative paths in the
* {@link #PATH loader path}. Defaults to current working directory (
* <code>${user.home}</code>).
*/
public static final String HOME = "loader.home";
/**
* Properties key for name of external configuration file (excluding suffix). Defaults
* to "application". Ignored if {@link #CONFIG_LOCATION loader config location} is
* provided instead.
*/
public static final String CONFIG_NAME = "loader.config.name";
/**
* Properties key for config file location (including optional classpath:, file: or
* URL prefix)
*/
public static final String CONFIG_LOCATION = "loader.config.location";
/**
* Properties key for boolean flag (default false) which if set will cause the
* external configuration properties to be copied to System properties (assuming that
* is allowed by Java security).
*/
public static final String SET_SYSTEM_PROPERTIES = "loader.system";
private static final List<String> DEFAULT_PATHS = Arrays.asList("lib/");
private final File home;
private List<String> paths = new ArrayList<String>(DEFAULT_PATHS);
private Properties properties = new Properties();
public PropertiesLauncher() {
try {
this.home = getHomeDirectory();
initializeProperties(this.home);
initializePaths();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
protected File getHomeDirectory() {
return new File(SystemPropertyUtils.resolvePlaceholders(System.getProperty(HOME,
"${user.dir}")));
}
private void initializeProperties(File home) throws Exception, IOException {
String config = "classpath:"
+ SystemPropertyUtils.resolvePlaceholders(SystemPropertyUtils
.getProperty(CONFIG_NAME, "application")) + ".properties";
config = SystemPropertyUtils.resolvePlaceholders(SystemPropertyUtils.getProperty(
CONFIG_LOCATION, config));
InputStream resource = getResource(config);
if (resource != null) {
this.logger.info("Found: " + config);
try {
this.properties.load(resource);
}
finally {
resource.close();
}
for (Object key : Collections.list(this.properties.propertyNames())) {
String text = this.properties.getProperty((String) key);
String value = SystemPropertyUtils.resolvePlaceholders(this.properties,
text);
if (value != null) {
this.properties.put(key, value);
}
}
if (SystemPropertyUtils.resolvePlaceholders(
"${" + SET_SYSTEM_PROPERTIES + ":false}").equals("true")) {
this.logger.info("Adding resolved properties to System properties");
for (Object key : Collections.list(this.properties.propertyNames())) {
String value = this.properties.getProperty((String) key);
System.setProperty((String) key, value);
}
}
}
else {
this.logger.info("Not found: " + config);
}
}
private InputStream getResource(String config) throws Exception {
if (config.startsWith("classpath:")) {
return getClasspathResource(config.substring("classpath:".length()));
}
config = stripFileUrlPrefix(config);
if (isUrl(config)) {
return getURLResource(config);
}
return getFileResource(config);
}
private String stripFileUrlPrefix(String config) {
if (config.startsWith("file:")) {
config = config.substring("file:".length());
if (config.startsWith("//")) {
config = config.substring(2);
}
}
return config;
}
private boolean isUrl(String config) {
return config.contains("://");
}
private InputStream getClasspathResource(String config) {
while (config.startsWith("/")) {
config = config.substring(1);
}
config = "/" + config;
this.logger.fine("Trying classpath: " + config);
return getClass().getResourceAsStream(config);
}
private InputStream getFileResource(String config) throws Exception {
File file = new File(config);
this.logger.fine("Trying file: " + config);
if (file.canRead()) {
return new FileInputStream(file);
}
return null;
}
private InputStream getURLResource(String config) throws Exception {
URL url = new URL(config);
if (exists(url)) {
URLConnection con = url.openConnection();
try {
return con.getInputStream();
}
catch (IOException ex) {
// Close the HTTP connection (if applicable).
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).disconnect();
}
throw ex;
}
}
return null;
}
private boolean exists(URL url) throws IOException {
// Try a URL connection content-length header...
URLConnection connection = url.openConnection();
try {
connection.setUseCaches(connection.getClass().getSimpleName()
.startsWith("JNLP"));
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("HEAD");
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
return true;
}
else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
}
return (connection.getContentLength() >= 0);
}
finally {
if (connection instanceof HttpURLConnection) {
((HttpURLConnection) connection).disconnect();
}
}
}
private void initializePaths() throws IOException {
String path = SystemPropertyUtils.getProperty(PATH);
if (path == null) {
path = this.properties.getProperty(PATH);
}
if (path != null) {
this.paths = parsePathsProperty(SystemPropertyUtils.resolvePlaceholders(path));
}
this.logger.info("Nested archive paths: " + this.paths);
}
private List<String> parsePathsProperty(String commaSeparatedPaths) {
List<String> paths = new ArrayList<String>();
for (String path : commaSeparatedPaths.split(",")) {
path = cleanupPath(path);
// Empty path is always on the classpath so no need for it to be explicitly
// listed here
if (!(path.equals(".") || path.equals(""))) {
paths.add(path);
}
}
return paths;
}
@Override
protected String getMainClass() throws Exception {
String property = SystemPropertyUtils.getProperty(MAIN);
if (property != null) {
String mainClass = SystemPropertyUtils.resolvePlaceholders(property);
this.logger.info("Main class from environment: " + mainClass);
return mainClass;
}
if (this.properties.containsKey(MAIN)) {
String mainClass = SystemPropertyUtils.resolvePlaceholders(this.properties
.getProperty(MAIN));
this.logger.info("Main class from properties: " + mainClass);
return mainClass;
}
try {
// Prefer home dir for MANIFEST if there is one
String mainClass = new ExplodedArchive(this.home).getMainClass();
this.logger.info("Main class from home directory manifest: " + mainClass);
return mainClass;
}
catch (IllegalStateException ex) {
// Otherwise try the parent archive
String mainClass = createArchive().getMainClass();
this.logger.info("Main class from archive manifest: " + mainClass);
return mainClass;
}
}
@Override
protected List<Archive> getClassPathArchives() throws Exception {
List<Archive> lib = new ArrayList<Archive>();
for (String path : this.paths) {
for (Archive archive : getClassPathArchives(path)) {
List<Archive> nested = new ArrayList<Archive>(
archive.getNestedArchives(new ArchiveEntryFilter()));
nested.add(0, archive);
lib.addAll(nested);
}
}
addParentClassLoaderEntries(lib);
return lib;
}
private List<Archive> getClassPathArchives(String path) throws Exception {
String root = cleanupPath(stripFileUrlPrefix(path));
List<Archive> lib = new ArrayList<Archive>();
File file = new File(root);
if (!root.startsWith("/")) {
file = new File(this.home, root);
}
if (file.isDirectory()) {
this.logger.info("Adding classpath entries from " + file);
Archive archive = new ExplodedArchive(file);
lib.add(archive);
}
Archive archive = getArchive(file);
if (archive != null) {
this.logger.info("Adding classpath entries from nested " + archive.getUrl()
+ root);
lib.add(archive);
}
Archive nested = getNestedArchive(root);
if (nested != null) {
this.logger.info("Adding classpath entries from nested " + nested.getUrl()
+ root);
lib.add(nested);
}
return lib;
}
private Archive getArchive(File file) throws IOException {
String name = file.getName().toLowerCase();
if (name.endsWith(".jar") || name.endsWith(".zip")) {
return new JarFileArchive(file);
}
return null;
}
private Archive getNestedArchive(final String root) throws Exception {
Archive parent = createArchive();
if (root.startsWith("/") || parent.getUrl().equals(this.home.toURI().toURL())) {
// If home dir is same as parent archive, no need to add it twice.
return null;
}
EntryFilter filter = new PrefixMatchingArchiveFilter(root);
if (parent.getNestedArchives(filter).isEmpty()) {
return null;
}
// If there are more archives nested in this subdirectory (root) then create a new
// virtual archive for them, and have it added to the classpath
return new FilteredArchive(parent, filter);
}
private Archive createArchive() throws Exception {
ProtectionDomain protectionDomain = getClass().getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
URI location = (codeSource == null ? null : codeSource.getLocation().toURI());
String path = (location == null ? null : location.getPath());
if (path == null) {
throw new IllegalStateException("Unable to determine code source archive");
}
File root = new File(path);
if (!root.exists()) {
throw new IllegalStateException(
"Unable to determine code source archive from " + root);
}
return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root));
}
private void addParentClassLoaderEntries(List<Archive> lib) throws IOException,
URISyntaxException {
ClassLoader parentClassLoader = getClass().getClassLoader();
if (parentClassLoader instanceof URLClassLoader) {
URLClassLoader urlClassLoader = (URLClassLoader) parentClassLoader;
for (URL url : urlClassLoader.getURLs()) {
if (url.toString().endsWith(".jar") || url.toString().endsWith(".zip")) {
lib.add(0, new JarFileArchive(new File(url.toURI())));
}
else {
lib.add(0, new ExplodedArchive(new File(url.getFile())));
}
}
}
}
private String cleanupPath(String path) {
path = path.trim();
if (path.toLowerCase().endsWith(".jar") || path.toLowerCase().endsWith(".zip")) {
return path;
}
if (path.endsWith("/*")) {
path = path.substring(0, path.length() - 1);
}
else {
// It's a directory
if (!path.endsWith("/")) {
path = path + "/";
}
}
// No need for current dir path
if (path.startsWith("./")) {
path = path.substring(2);
}
return path;
}
public static void main(String[] args) {
new PropertiesLauncher().launch(args);
}
/**
* Convenience class for finding nested archives (archive entries that can be
* classpath entries).
*/
private static final class ArchiveEntryFilter implements EntryFilter {
private static final AsciiBytes DOT_JAR = new AsciiBytes(".jar");
private static final AsciiBytes DOT_ZIP = new AsciiBytes(".zip");
@Override
public boolean matches(Entry entry) {
return entry.isDirectory() || entry.getName().endsWith(DOT_JAR)
|| entry.getName().endsWith(DOT_ZIP);
}
}
/**
* Convenience class for finding nested archives that have a prefix in their file path
* (e.g. "lib/").
*/
private static final class PrefixMatchingArchiveFilter implements EntryFilter {
private final AsciiBytes prefix;
private final ArchiveEntryFilter filter = new ArchiveEntryFilter();
private PrefixMatchingArchiveFilter(String prefix) {
this.prefix = new AsciiBytes(prefix);
}
@Override
public boolean matches(Entry entry) {
return entry.getName().startsWith(this.prefix) && this.filter.matches(entry);
}
}
}
|
Fix PropertiesLauncher for wildcard entries in parent classpath
This small change now plays nice with wildcard classpath
entries coming from a parent classloader as its urls.
|
spring-boot-tools/spring-boot-loader/src/main/java/org/springframework/boot/loader/PropertiesLauncher.java
|
Fix PropertiesLauncher for wildcard entries in parent classpath
|
|
Java
|
apache-2.0
|
7f5afe36cbe738ac6f9c1df8567544bb33a89da2
| 0
|
USCDataScience/sparkler,USCDataScience/sparkler,USCDataScience/sparkler,USCDataScience/sparkler,USCDataScience/sparkler
|
/*
* 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 edu.usc.irds.sparkler.plugin;
import edu.usc.irds.sparkler.JobContext;
import edu.usc.irds.sparkler.SparklerConfiguration;
import edu.usc.irds.sparkler.SparklerException;
import edu.usc.irds.sparkler.model.FetchedData;
import edu.usc.irds.sparkler.model.Resource;
import edu.usc.irds.sparkler.model.ResourceStatus;
import edu.usc.irds.sparkler.util.FetcherDefault;
import org.apache.commons.lang.ArrayUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.pf4j.Extension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map;
import java.util.Set;
import com.browserup.bup.BrowserUpProxy;
import com.browserup.bup.BrowserUpProxyServer;
import com.browserup.bup.client.ClientUtil;
import com.browserup.bup.filters.ResponseFilter;
import com.browserup.bup.proxy.CaptureType;
import com.browserup.bup.util.HttpMessageContents;
import com.browserup.bup.util.HttpMessageInfo;
import io.netty.handler.codec.http.HttpResponse;
import org.openqa.selenium.Proxy;
import static java.lang.Thread.sleep;
@Extension
public class FetcherChrome extends FetcherDefault {
private static final Logger LOG = LoggerFactory.getLogger(FetcherChrome.class);
private Map<String, Object> pluginConfig;
private WebDriver driver;
private WebElement clickedEl = null;
private int latestStatus;
private Proxy seleniumProxy;
@Override
public void init(JobContext context, String pluginId) throws SparklerException {
super.init(context, pluginId);
SparklerConfiguration config = jobContext.getConfiguration();
// TODO should change everywhere
pluginConfig = config.getPluginConfiguration(pluginId);
try {
System.out.println("Initializing Chrome Driver");
startDriver(true);
} catch (UnknownHostException | MalformedURLException e) {
e.printStackTrace();
System.out.println("Failed to init Chrome Session");
}
}
private void checkSession() {
for(int retryloop = 0; retryloop < 10; retryloop++){
try{
driver.getCurrentUrl();
} catch (Exception e) {
System.out.println("Failed session, restarting");
try {
startDriver(false);
} catch (UnknownHostException | MalformedURLException unknownHostException) {
unknownHostException.printStackTrace();
}
}
}
}
private void startDriver(Boolean restartproxy) throws UnknownHostException, MalformedURLException {
String loc = (String) pluginConfig.getOrDefault("chrome.dns", "");
if (loc.equals("")) {
driver = new ChromeDriver();
} else {
BrowserUpProxy proxy = new BrowserUpProxyServer();
proxy.setTrustAllServers(true);
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
proxy.addResponseFilter(new ResponseFilter() {
@Override
public void filterResponse(HttpResponse response, HttpMessageContents contents,
HttpMessageInfo messageInfo) {
latestStatus = response.getStatus().code();
}
});
String paddress = (String) pluginConfig.getOrDefault("chrome.proxy.address", "auto");
if (paddress.equals("auto")) {
proxy.start();
int port = proxy.getPort();
seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
} else {
if(restartproxy) {
String[] s = paddress.split(":");
proxy.start(Integer.parseInt(s[1]));
InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(s[0]), Integer.parseInt(s[1]));
seleniumProxy = ClientUtil.createSeleniumProxy(addr);
}
}
// seleniumProxy.setHttpProxy("172.17.146.238:"+Integer.toString(port));
// seleniumProxy.setSslProxy("172.17.146.238:"+Integer.toString(port));
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--ignore-certificate-errors");
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
driver = new RemoteWebDriver(new URL(loc), capabilities);
}
}
@Override
public FetchedData fetch(Resource resource) throws Exception {
LOG.info("Chrome FETCHER {}", resource.getUrl());
FetchedData fetchedData;
JSONObject json = null;
/*
* In this plugin we will work on only HTML data If data is of any other data
* type like image, pdf etc plugin will return client error so it can be fetched
* using default Fetcher
*/
if (!isWebPage(resource.getUrl())) {
LOG.debug("{} not a html. Falling back to default fetcher.", resource.getUrl());
// This should be true for all URLS ending with 4 character file extension
// return new FetchedData("".getBytes(), "application/html", ERROR_CODE) ;
return super.fetch(resource);
}
long start = System.currentTimeMillis();
LOG.debug("Time taken to create driver- {}", (System.currentTimeMillis() - start));
if(resource.getMetadata()!=null && !resource.getMetadata().equals("")){
json = processMetadata(resource.getMetadata());
}
// This will block for the page load and any
// associated AJAX requests
try {
checkSession();
} catch (Exception e){
System.out.println("failed to start selenium session");
}
driver.get(resource.getUrl());
int waittimeout = (int) pluginConfig.getOrDefault("chrome.wait.timeout", "-1");
String waittype = (String) pluginConfig.getOrDefault("chrome.wait.type", "");
String waitelement = (String) pluginConfig.getOrDefault("chrome.wait.element", "");
if (waittimeout > -1) {
LOG.debug("Waiting {} seconds for element {} of type {} to become visible", waittimeout, waitelement,
waittype);
WebDriverWait wait = new WebDriverWait(driver, waittimeout);
if (waittype.equals("class")) {
LOG.debug("waiting for class...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(waitelement)));
} else if (waittype.equals("name")) {
LOG.debug("waiting for name...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name(waitelement)));
} else if (waittype.equals("id")) {
LOG.debug("waiting for id...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(waitelement)));
}
}
String seleniumenabled = (String) pluginConfig.getOrDefault("chrome.selenium.enabled", "false");
if (seleniumenabled.equals("true")) {
runScript(pluginConfig.get("chrome.selenium.script"));
}
if(json != null && json.containsKey("selenium")){
runScript(json.get("selenium"));
}
String html = driver.getPageSource();
LOG.debug("Time taken to load {} - {} ", resource.getUrl(), (System.currentTimeMillis() - start));
System.out.println("LATEST STATUS: "+latestStatus);
if (!(latestStatus >= 200 && latestStatus < 300) && latestStatus != 0) {
// If not fetched through plugin successfully
// Falling back to default fetcher
LOG.info("{} Failed to fetch the page. Falling back to default fetcher.", resource.getUrl());
return super.fetch(resource);
}
fetchedData = new FetchedData(html.getBytes(), "application/html", latestStatus);
resource.setStatus(ResourceStatus.FETCHED.toString());
fetchedData.setResource(resource);
return fetchedData;
}
private void processJson(JSONObject object, HttpURLConnection conn) {
}
private void processForm(JSONObject object, HttpURLConnection conn) {
Set keys = object.keySet();
Iterator keyIter = keys.iterator();
String content = "";
for (int i = 0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if (i != 0) {
content += "&";
}
try {
content += key + "=" + URLEncoder.encode((String) object.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
System.out.println(content);
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//out.writeBytes(content);
//out.flush();
//out.close();
}
private JSONObject processMetadata(String metadata) {
if(metadata != null){
JSONParser parser = new JSONParser();
JSONObject json;
try {
json = (JSONObject) parser.parse(metadata);
return json;
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
private void runScript(Object orDefault) {
if(orDefault != null && orDefault instanceof Map){
Map mp = (Map) orDefault;
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
Map submap = (Map) pair.getValue();
runSubScript(submap);
it.remove();
}
}
LOG.debug("");
}
private void runSubScript(Map mp){
Iterator it = mp.entrySet().iterator();
String type = null;
String value = null;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
if(pair.getKey().equals("input")){
type = (String) pair.getValue();
} else if(pair.getKey().equals("value")){
value = (String) pair.getValue();
} else if(pair.getKey().equals("operation")){
type = (String) pair.getValue();
} else if(pair.getKey().equals("wait")){
type = (String) pair.getValue();
}
it.remove();
}
switch (type) {
case "click":
clickElement(value);
break;
case "keys":
typeCharacters(value);
break;
case "wait":
waitElement(value);
break;
}
}
private void clickElement(String el){
String splits[] = el.split(":");
String type = splits[0];
Object pruned[] = ArrayUtils.remove(splits, 0);
String element = "";
for (Object obj : pruned){
element = element + obj + " ";
}
element = element.substring(0, element.length() - 1);
switch (type) {
case "id":
clickedEl = driver.findElement(By.id(element));
break;
case "class":
clickedEl = driver.findElement(By.className(element));
break;
case "name":
clickedEl = driver.findElement(By.name(element));
break;
case "xpath":
clickedEl = driver.findElement(By.xpath(element));
break;
}
clickedEl.click();
}
private void waitElement(String el){
String[] splits = el.split(":");
String waittype = splits[0];
String waitelement = splits[1];
String waittime = splits[2];
int waittimeout = Integer.parseInt(waittime);
System.out.println("Waiting time is: "+ waittime);
System.out.println("Wait type is: "+ waittype);
System.out.println("Wait element is: "+ waitelement);
if (waittimeout > -1) {
LOG.debug("Waiting {} seconds for element {} of type {} to become visible", waittimeout, waitelement,
waittype);
WebDriverWait wait = new WebDriverWait(driver, waittimeout);
switch (waittype) {
case "class":
LOG.debug("waiting for class...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(waitelement)));
break;
case "name":
LOG.debug("waiting for name...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name(waitelement)));
break;
case "id":
LOG.debug("waiting for id...");
System.out.println("Waiting for id");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(waitelement)));
System.out.println("Wait over.....");
break;
}
}
}
private void typeCharacters(String chars){
if(chars.startsWith("id:")){
String[] s = chars.split(":");
driver.findElement(By.id(s[1])).sendKeys(s[2]);
}
else if(chars.startsWith("name:")){
String[] s = chars.split(":");
driver.findElement(By.name(s[1])).sendKeys(s[2]);
} else if(chars.startsWith("xpath:")){
String[] s = chars.split(":");
driver.findElement(By.xpath(s[1])).sendKeys(s[2]);
} else if(clickedEl != null){
clickedEl.sendKeys(chars);
}
}
public void closeResources() {
quitBrowserInstance(driver);
}
private boolean isWebPage(String webUrl) {
try {
URLConnection conn = new URL(webUrl).openConnection();
String contentType = conn.getHeaderField("Content-Type");
return contentType.contains("text") || contentType.contains("ml");
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
}
return false;
}
private boolean hasDriverQuit() {
try {
String result = driver.toString();
return result.contains("(null)");
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
}
return false;
}
public void quitBrowserInstance(WebDriver driver) {
if (driver != null) {
if (!hasDriverQuit()) {
try {
// FIXME - Exception when closing the driver. Adding an unused GET request
driver.get("http://www.apache.org/");
driver.quit();
} catch (Exception e) {
LOG.debug("Exception {} raised. The driver is either already closed " +
"or this is an unknown exception", e.getMessage());
}
} else {
LOG.debug("Driver is already quit");
}
} else {
LOG.debug("Driver was null");
}
}
}
|
sparkler-core/sparkler-plugins/fetcher-chrome/src/main/java/edu/usc/irds/sparkler/plugin/FetcherChrome.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 edu.usc.irds.sparkler.plugin;
import edu.usc.irds.sparkler.JobContext;
import edu.usc.irds.sparkler.SparklerConfiguration;
import edu.usc.irds.sparkler.SparklerException;
import edu.usc.irds.sparkler.model.FetchedData;
import edu.usc.irds.sparkler.model.Resource;
import edu.usc.irds.sparkler.model.ResourceStatus;
import edu.usc.irds.sparkler.util.FetcherDefault;
import org.apache.commons.lang.ArrayUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.pf4j.Extension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map;
import java.util.Set;
import com.browserup.bup.BrowserUpProxy;
import com.browserup.bup.BrowserUpProxyServer;
import com.browserup.bup.client.ClientUtil;
import com.browserup.bup.filters.ResponseFilter;
import com.browserup.bup.proxy.CaptureType;
import com.browserup.bup.util.HttpMessageContents;
import com.browserup.bup.util.HttpMessageInfo;
import io.netty.handler.codec.http.HttpResponse;
import org.openqa.selenium.Proxy;
import static java.lang.Thread.sleep;
@Extension
public class FetcherChrome extends FetcherDefault {
private static final Logger LOG = LoggerFactory.getLogger(FetcherChrome.class);
private Map<String, Object> pluginConfig;
private WebDriver driver;
private WebElement clickedEl = null;
private int latestStatus;
@Override
public void init(JobContext context, String pluginId) throws SparklerException {
super.init(context, pluginId);
SparklerConfiguration config = jobContext.getConfiguration();
// TODO should change everywhere
pluginConfig = config.getPluginConfiguration(pluginId);
try {
startDriver();
} catch (UnknownHostException | MalformedURLException e) {
e.printStackTrace();
System.out.println("Failed to init Chrome Session");
}
}
private void checkSession() {
for(int retryloop = 0; retryloop < 10; retryloop++){
try{
driver.getCurrentUrl();
} catch (Exception e) {
System.out.println("Failed session, restarting");
try {
startDriver();
} catch (UnknownHostException | MalformedURLException unknownHostException) {
unknownHostException.printStackTrace();
}
}
}
}
private void startDriver() throws UnknownHostException, MalformedURLException {
String loc = (String) pluginConfig.getOrDefault("chrome.dns", "");
if (loc.equals("")) {
driver = new ChromeDriver();
} else {
BrowserUpProxy proxy = new BrowserUpProxyServer();
proxy.setTrustAllServers(true);
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
proxy.addResponseFilter(new ResponseFilter() {
@Override
public void filterResponse(HttpResponse response, HttpMessageContents contents,
HttpMessageInfo messageInfo) {
latestStatus = response.getStatus().code();
}
});
String paddress = (String) pluginConfig.getOrDefault("chrome.proxy.address", "auto");
Proxy seleniumProxy;
if (paddress.equals("auto")) {
proxy.start();
int port = proxy.getPort();
seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
} else {
String[] s = paddress.split(":");
proxy.start(Integer.parseInt(s[1]));
InetSocketAddress addr = new InetSocketAddress(InetAddress.getByName(s[0]), Integer.parseInt(s[1]));
seleniumProxy = ClientUtil.createSeleniumProxy(addr);
}
// seleniumProxy.setHttpProxy("172.17.146.238:"+Integer.toString(port));
// seleniumProxy.setSslProxy("172.17.146.238:"+Integer.toString(port));
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--ignore-certificate-errors");
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
driver = new RemoteWebDriver(new URL(loc), capabilities);
}
}
@Override
public FetchedData fetch(Resource resource) throws Exception {
LOG.info("Chrome FETCHER {}", resource.getUrl());
FetchedData fetchedData;
JSONObject json = null;
/*
* In this plugin we will work on only HTML data If data is of any other data
* type like image, pdf etc plugin will return client error so it can be fetched
* using default Fetcher
*/
if (!isWebPage(resource.getUrl())) {
LOG.debug("{} not a html. Falling back to default fetcher.", resource.getUrl());
// This should be true for all URLS ending with 4 character file extension
// return new FetchedData("".getBytes(), "application/html", ERROR_CODE) ;
return super.fetch(resource);
}
long start = System.currentTimeMillis();
LOG.debug("Time taken to create driver- {}", (System.currentTimeMillis() - start));
if(resource.getMetadata()!=null && !resource.getMetadata().equals("")){
json = processMetadata(resource.getMetadata());
}
// This will block for the page load and any
// associated AJAX requests
try {
checkSession();
} catch (Exception e){
System.out.println("failed to start selenium session");
}
driver.get(resource.getUrl());
int waittimeout = (int) pluginConfig.getOrDefault("chrome.wait.timeout", "-1");
String waittype = (String) pluginConfig.getOrDefault("chrome.wait.type", "");
String waitelement = (String) pluginConfig.getOrDefault("chrome.wait.element", "");
if (waittimeout > -1) {
LOG.debug("Waiting {} seconds for element {} of type {} to become visible", waittimeout, waitelement,
waittype);
WebDriverWait wait = new WebDriverWait(driver, waittimeout);
if (waittype.equals("class")) {
LOG.debug("waiting for class...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(waitelement)));
} else if (waittype.equals("name")) {
LOG.debug("waiting for name...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name(waitelement)));
} else if (waittype.equals("id")) {
LOG.debug("waiting for id...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(waitelement)));
}
}
String seleniumenabled = (String) pluginConfig.getOrDefault("chrome.selenium.enabled", "false");
if (seleniumenabled.equals("true")) {
runScript(pluginConfig.get("chrome.selenium.script"));
}
if(json != null && json.containsKey("selenium")){
runScript(json.get("selenium"));
}
String html = driver.getPageSource();
LOG.debug("Time taken to load {} - {} ", resource.getUrl(), (System.currentTimeMillis() - start));
System.out.println("LATEST STATUS: "+latestStatus);
if (!(latestStatus >= 200 && latestStatus < 300) && latestStatus != 0) {
// If not fetched through plugin successfully
// Falling back to default fetcher
LOG.info("{} Failed to fetch the page. Falling back to default fetcher.", resource.getUrl());
return super.fetch(resource);
}
fetchedData = new FetchedData(html.getBytes(), "application/html", latestStatus);
resource.setStatus(ResourceStatus.FETCHED.toString());
fetchedData.setResource(resource);
return fetchedData;
}
private void processJson(JSONObject object, HttpURLConnection conn) {
}
private void processForm(JSONObject object, HttpURLConnection conn) {
Set keys = object.keySet();
Iterator keyIter = keys.iterator();
String content = "";
for (int i = 0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if (i != 0) {
content += "&";
}
try {
content += key + "=" + URLEncoder.encode((String) object.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
System.out.println(content);
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//out.writeBytes(content);
//out.flush();
//out.close();
}
private JSONObject processMetadata(String metadata) {
if(metadata != null){
JSONParser parser = new JSONParser();
JSONObject json;
try {
json = (JSONObject) parser.parse(metadata);
return json;
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
private void runScript(Object orDefault) {
if(orDefault != null && orDefault instanceof Map){
Map mp = (Map) orDefault;
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
Map submap = (Map) pair.getValue();
runSubScript(submap);
it.remove();
}
}
LOG.debug("");
}
private void runSubScript(Map mp){
Iterator it = mp.entrySet().iterator();
String type = null;
String value = null;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
if(pair.getKey().equals("input")){
type = (String) pair.getValue();
} else if(pair.getKey().equals("value")){
value = (String) pair.getValue();
} else if(pair.getKey().equals("operation")){
type = (String) pair.getValue();
} else if(pair.getKey().equals("wait")){
type = (String) pair.getValue();
}
it.remove();
}
switch (type) {
case "click":
clickElement(value);
break;
case "keys":
typeCharacters(value);
break;
case "wait":
waitElement(value);
break;
}
}
private void clickElement(String el){
String splits[] = el.split(":");
String type = splits[0];
Object pruned[] = ArrayUtils.remove(splits, 0);
String element = "";
for (Object obj : pruned){
element = element + obj + " ";
}
element = element.substring(0, element.length() - 1);
switch (type) {
case "id":
clickedEl = driver.findElement(By.id(element));
break;
case "class":
clickedEl = driver.findElement(By.className(element));
break;
case "name":
clickedEl = driver.findElement(By.name(element));
break;
case "xpath":
clickedEl = driver.findElement(By.xpath(element));
break;
}
clickedEl.click();
}
private void waitElement(String el){
String[] splits = el.split(":");
String waittype = splits[0];
String waitelement = splits[1];
String waittime = splits[2];
int waittimeout = Integer.parseInt(waittime);
System.out.println("Waiting time is: "+ waittime);
System.out.println("Wait type is: "+ waittype);
System.out.println("Wait element is: "+ waitelement);
if (waittimeout > -1) {
LOG.debug("Waiting {} seconds for element {} of type {} to become visible", waittimeout, waitelement,
waittype);
WebDriverWait wait = new WebDriverWait(driver, waittimeout);
switch (waittype) {
case "class":
LOG.debug("waiting for class...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(waitelement)));
break;
case "name":
LOG.debug("waiting for name...");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name(waitelement)));
break;
case "id":
LOG.debug("waiting for id...");
System.out.println("Waiting for id");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(waitelement)));
System.out.println("Wait over.....");
break;
}
}
}
private void typeCharacters(String chars){
if(chars.startsWith("id:")){
String[] s = chars.split(":");
driver.findElement(By.id(s[1])).sendKeys(s[2]);
}
else if(chars.startsWith("name:")){
String[] s = chars.split(":");
driver.findElement(By.name(s[1])).sendKeys(s[2]);
} else if(chars.startsWith("xpath:")){
String[] s = chars.split(":");
driver.findElement(By.xpath(s[1])).sendKeys(s[2]);
} else if(clickedEl != null){
clickedEl.sendKeys(chars);
}
}
public void closeResources() {
quitBrowserInstance(driver);
}
private boolean isWebPage(String webUrl) {
try {
URLConnection conn = new URL(webUrl).openConnection();
String contentType = conn.getHeaderField("Content-Type");
return contentType.contains("text") || contentType.contains("ml");
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
}
return false;
}
private boolean hasDriverQuit() {
try {
String result = driver.toString();
return result.contains("(null)");
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
}
return false;
}
public void quitBrowserInstance(WebDriver driver) {
if (driver != null) {
if (!hasDriverQuit()) {
try {
// FIXME - Exception when closing the driver. Adding an unused GET request
driver.get("http://www.apache.org/");
driver.quit();
} catch (Exception e) {
LOG.debug("Exception {} raised. The driver is either already closed " +
"or this is an unknown exception", e.getMessage());
}
} else {
LOG.debug("Driver is already quit");
}
} else {
LOG.debug("Driver was null");
}
}
}
|
add wait to metalookup
|
sparkler-core/sparkler-plugins/fetcher-chrome/src/main/java/edu/usc/irds/sparkler/plugin/FetcherChrome.java
|
add wait to metalookup
|
|
Java
|
bsd-2-clause
|
54912ca31c00f5e929ec5968f5326966c498fcae
| 0
|
Sethtroll/runelite,runelite/runelite,Sethtroll/runelite,runelite/runelite,abelbriggs1/runelite,l2-/runelite,l2-/runelite,abelbriggs1/runelite,runelite/runelite,abelbriggs1/runelite
|
/*
* Copyright (c) 2017, Adam <Adam@sigterm.info>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 net.runelite.api.widgets;
/**
* Represents a group-child {@link Widget} relationship.
* <p>
* For getting a specific widget from the client, see {@link net.runelite.api.Client#getWidget(WidgetInfo)}.
*/
public enum WidgetInfo
{
FAIRY_RING_LEFT_ORB_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.LEFT_ORB_CLOCKWISE),
FAIRY_RING_LEFT_ORB_COUNTER_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.LEFT_ORB_COUNTER_CLOCKWISE),
FAIRY_RING_MIDDLE_ORB_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.MIDDLE_ORB_CLOCKWISE),
FAIRY_RING_MIDDLE_ORB_COUNTER_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.MIDDLE_ORB_COUNTER_CLOCKWISE),
FAIRY_RING_RIGHT_ORB_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.RIGHT_ORB_CLOCKWISE),
FAIRY_RING_RIGHT_ORB_COUNTER_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.RIGHT_ORB_COUNTER_CLOCKWISE),
FAIRY_RING_TELEPORT_BUTTON(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.TELEPORT_BUTTON),
WORLD_SWITCHER_BUTTON(WidgetID.LOGOUT_PANEL_ID, WidgetID.LogoutPanel.WORLD_SWITCHER_BUTTON),
LOGOUT_BUTTON(WidgetID.LOGOUT_PANEL_ID, WidgetID.LogoutPanel.LOGOUT_BUTTON),
INVENTORY(WidgetID.INVENTORY_GROUP_ID, 0),
FRIENDS_LIST(WidgetID.FRIENDS_LIST_GROUP_ID, 0),
CLAN_CHAT(WidgetID.CLAN_CHAT_GROUP_ID, 0),
RAIDING_PARTY(WidgetID.RAIDING_PARTY_GROUP_ID, 0),
WORLD_MAP_VIEW(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.MAPVIEW),
WORLD_MAP_OVERVIEW_MAP(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.OVERVIEW_MAP),
WORLD_MAP_SEARCH(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.SEARCH),
WORLD_MAP_SURFACE_SELECTOR(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.SURFACE_SELECTOR),
WORLD_MAP_TOOLTIP(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.TOOLTIP),
WORLD_MAP_OPTION(WidgetID.WORLD_MAP_MENU_GROUP_ID, WidgetID.WorldMap.OPTION),
CLUE_SCROLL_TEXT(WidgetID.CLUE_SCROLL_GROUP_ID, WidgetID.Cluescroll.CLUE_TEXT),
CLUE_SCROLL_REWARD_ITEM_CONTAINER(WidgetID.CLUE_SCROLL_REWARD_GROUP_ID, WidgetID.Cluescroll.CLUE_SCROLL_ITEM_CONTAINER),
EQUIPMENT(WidgetID.EQUIPMENT_GROUP_ID, 0),
EQUIPMENT_INVENTORY_ITEMS_CONTAINER(WidgetID.EQUIPMENT_INVENTORY_GROUP_ID, WidgetID.Equipment.INVENTORY_ITEM_CONTAINER),
EQUIPMENT_HELMET(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.HELMET),
EQUIPMENT_CAPE(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.CAPE),
EQUIPMENT_AMULET(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.AMULET),
EQUIPMENT_WEAPON(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.WEAPON),
EQUIPMENT_BODY(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.BODY),
EQUIPMENT_SHIELD(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.SHIELD),
EQUIPMENT_LEGS(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.LEGS),
EQUIPMENT_GLOVES(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.GLOVES),
EQUIPMENT_BOOTS(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.BOOTS),
EQUIPMENT_RING(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.RING),
EQUIPMENT_AMMO(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.AMMO),
EMOTE_WINDOW(WidgetID.EMOTES_GROUP_ID, WidgetID.Emotes.EMOTE_WINDOW),
EMOTE_CONTAINER(WidgetID.EMOTES_GROUP_ID, WidgetID.Emotes.EMOTE_CONTAINER),
DIARY_LIST(WidgetID.DIARY_GROUP_ID, 10),
DIARY_QUEST_WIDGET_TITLE(WidgetID.DIARY_QUEST_GROUP_ID, WidgetID.Diary.DIARY_TITLE),
DIARY_QUEST_WIDGET_TEXT(WidgetID.DIARY_QUEST_GROUP_ID, WidgetID.Diary.DIARY_TEXT),
PEST_CONTROL_BOAT_INFO(WidgetID.PEST_CONTROL_BOAT_GROUP_ID, WidgetID.PestControlBoat.INFO),
PEST_CONTROL_INFO(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.INFO),
PEST_CONTROL_PURPLE_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.PURPLE_SHIELD),
PEST_CONTROL_BLUE_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.BLUE_SHIELD),
PEST_CONTROL_YELLOW_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.YELLOW_SHIELD),
PEST_CONTROL_RED_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.RED_SHIELD),
PEST_CONTROL_PURPLE_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.PURPLE_HEALTH),
PEST_CONTROL_BLUE_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.BLUE_HEALTH),
PEST_CONTROL_YELLOW_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.YELLOW_HEALTH),
PEST_CONTROL_RED_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.RED_HEALTH),
PEST_CONTROL_PURPLE_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.PURPLE_ICON),
PEST_CONTROL_BLUE_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.BLUE_ICON),
PEST_CONTROL_YELLOW_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.YELLOW_ICON),
PEST_CONTROL_RED_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.RED_ICON),
PEST_CONTROL_ACTIVITY_BAR(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.ACTIVITY_BAR),
PEST_CONTROL_ACTIVITY_PROGRESS(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.ACTIVITY_PROGRESS),
VOLCANIC_MINE_GENERAL_INFOBOX_GROUP(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.GENERAL_INFOBOX_GROUP_ID),
VOLCANIC_MINE_TIME_LEFT(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.TIME_LEFT),
VOLCANIC_MINE_POINTS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.POINTS),
VOLCANIC_MINE_STABILITY(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.STABILITY),
VOLCANIC_MINE_PLAYER_COUNT(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.PLAYER_COUNT),
VOLCANIC_MINE_VENTS_INFOBOX_GROUP(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENTS_INFOBOX_GROUP_ID),
VOLCANIC_MINE_VENT_A_PERCENTAGE(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_A_PERCENTAGE),
VOLCANIC_MINE_VENT_B_PERCENTAGE(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_B_PERCENTAGE),
VOLCANIC_MINE_VENT_C_PERCENTAGE(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_C_PERCENTAGE),
VOLCANIC_MINE_VENT_A_STATUS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_A_STATUS),
VOLCANIC_MINE_VENT_B_STATUS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_B_STATUS),
VOLCANIC_MINE_VENT_C_STATUS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_C_STATUS),
FRIEND_CHAT_TITLE(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.TITLE),
IGNORE_TITLE(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.TITLE),
CLAN_CHAT_TITLE(WidgetID.CLAN_CHAT_GROUP_ID, WidgetID.ClanChat.TITLE),
CLAN_CHAT_NAME(WidgetID.CLAN_CHAT_GROUP_ID, WidgetID.ClanChat.NAME),
CLAN_CHAT_OWNER(WidgetID.CLAN_CHAT_GROUP_ID, WidgetID.ClanChat.OWNER),
CLAN_CHAT_LIST(WidgetID.CLAN_CHAT_GROUP_ID, WidgetID.ClanChat.LIST),
BANK_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.BANK_CONTAINER),
BANK_SEARCH_BUTTON_BACKGROUND(WidgetID.BANK_GROUP_ID, WidgetID.Bank.SEARCH_BUTTON_BACKGROUND),
BANK_ITEM_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.ITEM_CONTAINER),
BANK_INVENTORY_ITEMS_CONTAINER(WidgetID.BANK_INVENTORY_GROUP_ID, WidgetID.Bank.INVENTORY_ITEM_CONTAINER),
BANK_TITLE_BAR(WidgetID.BANK_GROUP_ID, WidgetID.Bank.BANK_TITLE_BAR),
BANK_INCINERATOR(WidgetID.BANK_GROUP_ID, WidgetID.Bank.INCINERATOR),
BANK_INCINERATOR_CONFIRM(WidgetID.BANK_GROUP_ID, WidgetID.Bank.INCINERATOR_CONFIRM),
BANK_CONTENT_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.CONTENT_CONTAINER),
BANK_DEPOSIT_EQUIPMENT(WidgetID.BANK_GROUP_ID, WidgetID.Bank.DEPOSIT_EQUIPMENT),
BANK_DEPOSIT_INVENTORY(WidgetID.BANK_GROUP_ID, WidgetID.Bank.DEPOSIT_INVENTORY),
GRAND_EXCHANGE_WINDOW_CONTAINER(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.WINDOW_CONTAINER),
GRAND_EXCHANGE_OFFER_CONTAINER(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.OFFER_CONTAINER),
GRAND_EXCHANGE_OFFER_TEXT(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.OFFER_DESCRIPTION),
GRAND_EXCHANGE_OFFER_PRICE(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.OFFER_PRICE),
GRAND_EXCHANGE_INVENTORY_ITEMS_CONTAINER(WidgetID.GRAND_EXCHANGE_INVENTORY_GROUP_ID, WidgetID.GrandExchangeInventory.INVENTORY_ITEM_CONTAINER),
DEPOSIT_BOX_INVENTORY_ITEMS_CONTAINER(WidgetID.DEPOSIT_BOX_GROUP_ID, WidgetID.DepositBox.INVENTORY_ITEM_CONTAINER),
SHOP_ITEMS_CONTAINER(WidgetID.SHOP_GROUP_ID, WidgetID.Shop.ITEMS_CONTAINER),
SHOP_INVENTORY_ITEMS_CONTAINER(WidgetID.SHOP_INVENTORY_GROUP_ID, WidgetID.Shop.INVENTORY_ITEM_CONTAINER),
SMITHING_INVENTORY_ITEMS_CONTAINER(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.INVENTORY_ITEM_CONTAINER),
GUIDE_PRICES_ITEMS_CONTAINER(WidgetID.GUIDE_PRICES_GROUP_ID, WidgetID.GuidePrices.ITEM_CONTAINER),
GUIDE_PRICES_INVENTORY_ITEMS_CONTAINER(WidgetID.GUIDE_PRICES_INVENTORY_GROUP_ID, WidgetID.GuidePrices.INVENTORY_ITEM_CONTAINER),
RUNE_POUCH_ITEM_CONTAINER(WidgetID.RUNE_POUCH_GROUP_ID, 0),
MINIMAP_ORBS(WidgetID.MINIMAP_GROUP_ID, 0),
MINIMAP_XP_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.XP_ORB),
MINIMAP_PRAYER_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.PRAYER_ORB),
MINIMAP_QUICK_PRAYER_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.QUICK_PRAYER_ORB),
MINIMAP_RUN_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.RUN_ORB),
MINIMAP_TOGGLE_RUN_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.TOGGLE_RUN_ORB),
MINIMAP_RUN_ORB_TEXT(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.RUN_ORB_TEXT),
MINIMAP_HEALTH_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.HEALTH_ORB),
MINIMAP_SPEC_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.SPEC_ORB),
MINIMAP_WORLDMAP_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.WORLDMAP_ORB),
LOGIN_CLICK_TO_PLAY_SCREEN(WidgetID.LOGIN_CLICK_TO_PLAY_GROUP_ID, 0),
LOGIN_CLICK_TO_PLAY_SCREEN_MESSAGE_OF_THE_DAY(WidgetID.LOGIN_CLICK_TO_PLAY_GROUP_ID, WidgetID.LoginClickToPlayScreen.MESSAGE_OF_THE_DAY),
FIXED_VIEWPORT(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.Viewport.FIXED_VIEWPORT),
FIXED_VIEWPORT_ROOT_INTERFACE_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.ROOT_INTERFACE_CONTAINER),
FIXED_VIEWPORT_BANK_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.BANK_CONTAINER),
FIXED_VIEWPORT_INTERFACE_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INTERFACE_CONTAINER),
FIXED_VIEWPORT_COMBAT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.COMBAT_TAB),
FIXED_VIEWPORT_STATS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.STATS_TAB),
FIXED_VIEWPORT_QUESTS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.QUESTS_TAB),
FIXED_VIEWPORT_INVENTORY_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INVENTORY_TAB),
FIXED_VIEWPORT_EQUIPMENT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EQUIPMENT_TAB),
FIXED_VIEWPORT_PRAYER_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.PRAYER_TAB),
FIXED_VIEWPORT_MAGIC_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MAGIC_TAB),
FIXED_VIEWPORT_CLAN_CHAT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.CLAN_CHAT_TAB),
FIXED_VIEWPORT_FRIENDS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.FRIENDS_TAB),
FIXED_VIEWPORT_IGNORES_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.IGNORES_TAB),
FIXED_VIEWPORT_LOGOUT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.LOGOUT_TAB),
FIXED_VIEWPORT_OPTIONS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.OPTIONS_TAB),
FIXED_VIEWPORT_EMOTES_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EMOTES_TAB),
FIXED_VIEWPORT_MUSIC_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MUSIC_TAB),
FIXED_VIEWPORT_COMBAT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.COMBAT_ICON),
FIXED_VIEWPORT_STATS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.STATS_ICON),
FIXED_VIEWPORT_QUESTS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.QUESTS_ICON),
FIXED_VIEWPORT_INVENTORY_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INVENTORY_ICON),
FIXED_VIEWPORT_EQUIPMENT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EQUIPMENT_ICON),
FIXED_VIEWPORT_PRAYER_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.PRAYER_ICON),
FIXED_VIEWPORT_MAGIC_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MAGIC_ICON),
FIXED_VIEWPORT_CLAN_CHAT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.CLAN_CHAT_ICON),
FIXED_VIEWPORT_FRIENDS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.FRIENDS_ICON),
FIXED_VIEWPORT_IGNORES_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.IGNORES_ICON),
FIXED_VIEWPORT_LOGOUT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.LOGOUT_ICON),
FIXED_VIEWPORT_OPTIONS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.OPTIONS_ICON),
FIXED_VIEWPORT_EMOTES_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EMOTES_ICON),
FIXED_VIEWPORT_MUSIC_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MUSIC_ICON),
FIXED_VIEWPORT_MINIMAP(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MINIMAP),
FIXED_VIEWPORT_MINIMAP_DRAW_AREA(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MINIMAP_DRAW_AREA),
RESIZABLE_MINIMAP_WIDGET(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_WIDGET),
RESIZABLE_MINIMAP_CLICKBOX(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_CLICKBOX),
RESIZABLE_MINIMAP_DRAW_AREA(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DRAW_AREA),
RESIZABLE_MINIMAP_DECORATIONS(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DECORATIONS),
RESIZABLE_MINIMAP_ORB_HOLDER(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_ORB_HOLDER),
RESIZABLE_MINIMAP_LOGOUT_BUTTON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_LOGOUT_BUTTON),
RESIZABLE_MINIMAP_STONES_WIDGET(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_WIDGET),
RESIZABLE_MINIMAP_STONES_CLICKBOX(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_CLICKBOX),
RESIZABLE_MINIMAP_STONES_DRAW_AREA(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DRAW_AREA),
RESIZABLE_MINIMAP_STONES_DECORATIONS(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DECORATIONS),
RESIZABLE_MINIMAP_STONES_ORB_HOLDER(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_ORB_HOLDER),
RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX),
RESIZABLE_VIEWPORT_COMBAT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.COMBAT_TAB),
RESIZABLE_VIEWPORT_STATS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.STATS_TAB),
RESIZABLE_VIEWPORT_QUESTS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.QUESTS_TAB),
RESIZABLE_VIEWPORT_INVENTORY_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INVENTORY_TAB),
RESIZABLE_VIEWPORT_EQUIPMENT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EQUIPMENT_TAB),
RESIZABLE_VIEWPORT_PRAYER_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.PRAYER_TAB),
RESIZABLE_VIEWPORT_MAGIC_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MAGIC_TAB),
RESIZABLE_VIEWPORT_CLAN_CHAT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.CLAN_CHAT_TAB),
RESIZABLE_VIEWPORT_FRIENDS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.FRIENDS_TAB),
RESIZABLE_VIEWPORT_IGNORES_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.IGNORES_TAB),
RESIZABLE_VIEWPORT_LOGOUT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.LOGOUT_TAB),
RESIZABLE_VIEWPORT_OPTIONS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.OPTIONS_TAB),
RESIZABLE_VIEWPORT_EMOTES_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EMOTES_TAB),
RESIZABLE_VIEWPORT_MUSIC_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MUSIC_TAB),
RESIZABLE_VIEWPORT_COMBAT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.COMBAT_ICON),
RESIZABLE_VIEWPORT_STATS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.STATS_ICON),
RESIZABLE_VIEWPORT_QUESTS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.QUESTS_ICON),
RESIZABLE_VIEWPORT_INVENTORY_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INVENTORY_ICON),
RESIZABLE_VIEWPORT_EQUIPMENT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EQUIPMENT_ICON),
RESIZABLE_VIEWPORT_PRAYER_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.PRAYER_ICON),
RESIZABLE_VIEWPORT_MAGIC_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MAGIC_ICON),
RESIZABLE_VIEWPORT_CLAN_CHAT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.CLAN_CHAT_ICON),
RESIZABLE_VIEWPORT_FRIENDS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.FRIENDS_ICON),
RESIZABLE_VIEWPORT_IGNORES_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.IGNORES_ICON),
RESIZABLE_VIEWPORT_LOGOUT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.LOGOUT_ICON),
RESIZABLE_VIEWPORT_OPTIONS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.OPTIONS_ICON),
RESIZABLE_VIEWPORT_EMOTES_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EMOTES_ICON),
RESIZABLE_VIEWPORT_MUSIC_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MUSIC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.RESIZABLE_VIEWPORT_BOTTOM_LINE),
RESIZABLE_VIEWPORT_BOTTOM_LINE_LOGOUT_BUTTON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.LOGOUT_BUTTON_OVERLAY),
RESIZABLE_VIEWPORT_BOTTOM_LINE_QUESTS_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.QUESTS_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.INVENTORY_TAB),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.INVENTORY_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_PRAYER_TAB(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.PRAYER_TAB),
RESIZABLE_VIEWPORT_BOTTOM_LINE_PRAYER_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.PRAYER_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_EQUIPMENT_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.EQUIP_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_COMBAT_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.CMB_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_STATS_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.SKILLS_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_MAGIC_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.MAGIC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_FRIEND_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.FRIEND_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_FRIEND_CHAT_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.FC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_OPTIONS_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.SETTINGS_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_EMOTES_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.EMOTE_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_MUSIC_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.MUSIC_ICON),
RESIZABLE_VIEWPORT_INTERFACE_CONTAINER(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INTERFACE_CONTAINER),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INTERFACE_CONTAINER(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewport.INTERFACE_CONTAINER),
PRAYER_THICK_SKIN(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.THICK_SKIN),
PRAYER_BURST_OF_STRENGTH(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.BURST_OF_STRENGTH),
PRAYER_CLARITY_OF_THOUGHT(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.CLARITY_OF_THOUGHT),
PRAYER_SHARP_EYE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.SHARP_EYE),
PRAYER_MYSTIC_WILL(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.MYSTIC_WILL),
PRAYER_ROCK_SKIN(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.ROCK_SKIN),
PRAYER_SUPERHUMAN_STRENGTH(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.SUPERHUMAN_STRENGTH),
PRAYER_IMPROVED_REFLEXES(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.IMPROVED_REFLEXES),
PRAYER_RAPID_RESTORE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RAPID_RESTORE),
PRAYER_RAPID_HEAL(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RAPID_HEAL),
PRAYER_PROTECT_ITEM(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_ITEM),
PRAYER_HAWK_EYE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.HAWK_EYE),
PRAYER_MYSTIC_LORE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.MYSTIC_LORE),
PRAYER_STEEL_SKIN(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.STEEL_SKIN),
PRAYER_ULTIMATE_STRENGTH(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.ULTIMATE_STRENGTH),
PRAYER_INCREDIBLE_REFLEXES(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.INCREDIBLE_REFLEXES),
PRAYER_PROTECT_FROM_MAGIC(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_FROM_MAGIC),
PRAYER_PROTECT_FROM_MISSILES(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_FROM_MISSILES),
PRAYER_PROTECT_FROM_MELEE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_FROM_MELEE),
PRAYER_EAGLE_EYE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.EAGLE_EYE),
PRAYER_MYSTIC_MIGHT(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.MYSTIC_MIGHT),
PRAYER_RETRIBUTION(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RETRIBUTION),
PRAYER_REDEMPTION(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.REDEMPTION),
PRAYER_SMITE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.SMITE),
PRAYER_PRESERVE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PRESERVE),
PRAYER_CHIVALRY(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.CHIVALRY),
PRAYER_PIETY(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PIETY),
PRAYER_RIGOUR(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RIGOUR),
PRAYER_AUGURY(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.AUGURY),
QUICK_PRAYER_PRAYERS(WidgetID.QUICK_PRAYERS_GROUP_ID, WidgetID.QuickPrayer.PRAYERS),
COMBAT_LEVEL(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.LEVEL),
COMBAT_STYLE_ONE(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_ONE),
COMBAT_STYLE_TWO(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_TWO),
COMBAT_STYLE_THREE(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_THREE),
COMBAT_STYLE_FOUR(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_FOUR),
COMBAT_SPELLS(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELLS),
COMBAT_DEFENSIVE_SPELL_BOX(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_BOX),
COMBAT_DEFENSIVE_SPELL_ICON(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_ICON),
COMBAT_DEFENSIVE_SPELL_SHIELD(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_SHIELD),
COMBAT_DEFENSIVE_SPELL_TEXT(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_TEXT),
COMBAT_SPELL_BOX(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELL_BOX),
COMBAT_SPELL_ICON(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELL_ICON),
COMBAT_SPELL_TEXT(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELL_TEXT),
COMBAT_AUTO_RETALIATE(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.AUTO_RETALIATE),
DIALOG_OPTION(WidgetID.DIALOG_OPTION_GROUP_ID, 0),
DIALOG_SPRITE(WidgetID.DIALOG_SPRITE_GROUP_ID, 0),
DIALOG_SPRITE_SPRITE(WidgetID.DIALOG_SPRITE_GROUP_ID, WidgetID.DialogSprite.SPRITE),
DIALOG_SPRITE_TEXT(WidgetID.DIALOG_SPRITE_GROUP_ID, WidgetID.DialogSprite.TEXT),
DIALOG_NPC(WidgetID.DIALOG_NPC_GROUP_ID, 0),
DIALOG_NPC_NAME(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.NAME),
DIALOG_NPC_TEXT(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.TEXT),
DIALOG_NPC_HEAD_MODEL(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.HEAD_MODEL),
DIALOG_NPC_CONTINUE(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.CONTINUE),
DIALOG_PLAYER(WidgetID.DIALOG_PLAYER_GROUP_ID, 0),
PRIVATE_CHAT_MESSAGE(WidgetID.PRIVATE_CHAT, 0),
SLAYER_REWARDS_TOPBAR(WidgetID.SLAYER_REWARDS_GROUP_ID, WidgetID.SlayerRewards.TOP_BAR),
CHATBOX_PARENT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.PARENT),
CHATBOX(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.FRAME),
CHATBOX_MESSAGES(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.MESSAGES),
CHATBOX_BUTTONS(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.BUTTONS),
CHATBOX_TITLE(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TITLE),
CHATBOX_FULL_INPUT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.FULL_INPUT),
CHATBOX_CONTAINER(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.CONTAINER),
CHATBOX_REPORT_TEXT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.REPORT_TEXT),
CHATBOX_INPUT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.INPUT),
CHATBOX_TRANSPARENT_BACKGROUND(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TRANSPARENT_BACKGROUND),
CHATBOX_TRANSPARENT_LINES(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TRANSPARENT_BACKGROUND_LINES),
BA_HEAL_WAVE_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_HEAL_CALL_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.TO_CALL),
BA_HEAL_LISTEN_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.CORRECT_STYLE),
BA_HEAL_ROLE_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.ROLE),
BA_HEAL_ROLE_SPRITE(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.ROLE_SPRITE),
BA_COLL_WAVE_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_COLL_CALL_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.TO_CALL),
BA_COLL_LISTEN_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.CORRECT_STYLE),
BA_COLL_ROLE_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.ROLE),
BA_COLL_ROLE_SPRITE(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.ROLE_SPRITE),
BA_ATK_WAVE_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_ATK_CALL_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.TO_CALL),
BA_ATK_LISTEN_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.CORRECT_STYLE),
BA_ATK_ROLE_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.ROLE),
BA_ATK_ROLE_SPRITE(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.ROLE_SPRITE),
BA_DEF_WAVE_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_DEF_CALL_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.TO_CALL),
BA_DEF_LISTEN_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.CORRECT_STYLE),
BA_DEF_ROLE_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.ROLE),
BA_DEF_ROLE_SPRITE(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.ROLE_SPRITE),
BA_REWARD_TEXT(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_TEXT),
LEVEL_UP(WidgetID.LEVEL_UP_GROUP_ID, 0),
LEVEL_UP_SKILL(WidgetID.LEVEL_UP_GROUP_ID, WidgetID.LevelUp.SKILL),
LEVEL_UP_LEVEL(WidgetID.LEVEL_UP_GROUP_ID, WidgetID.LevelUp.LEVEL),
QUEST_COMPLETED(WidgetID.QUEST_COMPLETED_GROUP_ID, 0),
QUEST_COMPLETED_NAME_TEXT(WidgetID.QUEST_COMPLETED_GROUP_ID, WidgetID.QuestCompleted.NAME_TEXT),
MOTHERLODE_MINE(WidgetID.MOTHERLODE_MINE_GROUP_ID, 0),
PUZZLE_BOX(WidgetID.PUZZLE_BOX_GROUP_ID, WidgetID.PuzzleBox.VISIBLE_BOX),
LIGHT_BOX(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BOX),
LIGHT_BOX_CONTENTS(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BULB_CONTAINER),
LIGHT_BOX_BUTTON_A(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_A),
LIGHT_BOX_BUTTON_B(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_B),
LIGHT_BOX_BUTTON_C(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_C),
LIGHT_BOX_BUTTON_D(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_D),
LIGHT_BOX_BUTTON_E(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_E),
LIGHT_BOX_BUTTON_F(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_F),
LIGHT_BOX_BUTTON_G(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_G),
LIGHT_BOX_BUTTON_H(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_H),
LIGHT_BOX_WINDOW(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BOX_WINDOW),
NIGHTMARE_ZONE(WidgetID.NIGHTMARE_ZONE_GROUP_ID, 0),
RAIDS_POINTS_INFOBOX(WidgetID.RAIDS_GROUP_ID, WidgetID.Raids.POINTS_INFOBOX),
BLAST_FURNACE_COFFER(WidgetID.BLAST_FURNACE_GROUP_ID, 2),
PYRAMID_PLUNDER_DATA(WidgetID.PYRAMID_PLUNDER_GROUP_ID, 2),
EXPERIENCE_TRACKER(WidgetID.EXPERIENCE_TRACKER_GROUP_ID, 0),
EXPERIENCE_TRACKER_WIDGET(WidgetID.EXPERIENCE_TRACKER_GROUP_ID, WidgetID.ExperienceTracker.WIDGET),
EXPERIENCE_TRACKER_BOTTOM_BAR(WidgetID.EXPERIENCE_TRACKER_GROUP_ID, WidgetID.ExperienceTracker.BOTTOM_BAR),
TITHE_FARM(WidgetID.TITHE_FARM_GROUP_ID, 1),
BARROWS_INFO(WidgetID.BARROWS_GROUP_ID, 0),
BARROWS_BROTHERS(WidgetID.BARROWS_GROUP_ID, WidgetID.Barrows.BARROWS_BROTHERS),
BARROWS_POTENTIAL(WidgetID.BARROWS_GROUP_ID, WidgetID.Barrows.BARROWS_POTENTIAL),
BARROWS_REWARD_INVENTORY(WidgetID.BARROWS_REWARD_GROUP_ID, WidgetID.Barrows.BARROWS_REWARD_INVENTORY),
BLAST_MINE(WidgetID.BLAST_MINE_GROUP_ID, 2),
FAIRY_RING(WidgetID.FAIRY_RING_GROUP_ID, 0),
FAIRY_RING_HEADER(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.HEADER),
FAIRY_RING_LIST(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.LIST),
FAIRY_RING_FAVORITES(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.FAVORITES),
FAIRY_RING_LIST_SEPARATOR(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.SEPARATOR),
FAIRY_RING_LIST_SCROLLBAR(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.SCROLLBAR),
DESTROY_ITEM(WidgetID.DESTROY_ITEM_GROUP_ID, 0),
DESTROY_ITEM_NAME(WidgetID.DESTROY_ITEM_GROUP_ID, WidgetID.DestroyItem.DESTROY_ITEM_NAME),
DESTROY_ITEM_YES(WidgetID.DESTROY_ITEM_GROUP_ID, WidgetID.DestroyItem.DESTROY_ITEM_YES),
DESTROY_ITEM_NO(WidgetID.DESTROY_ITEM_GROUP_ID, WidgetID.DestroyItem.DESTROY_ITEM_NO),
VARROCK_MUSEUM_QUESTION(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_QUESTION),
VARROCK_MUSEUM_FIRST_ANSWER(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_FIRST_ANSWER),
VARROCK_MUSEUM_SECOND_ANSWER(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_SECOND_ANSWER),
VARROCK_MUSEUM_THIRD_ANSWER(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_THIRD_ANSWER),
KILL_LOG_TITLE(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.TITLE),
KILL_LOG_MONSTER(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.MONSTER),
KILL_LOG_KILLS(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.KILLS),
KILL_LOG_STREAK(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.STREAK),
WORLD_SWITCHER_LIST(WidgetID.WORLD_SWITCHER_GROUP_ID, WidgetID.WorldSwitcher.WORLD_LIST),
FOSSIL_ISLAND_OXYGENBAR(WidgetID.FOSSIL_ISLAND_OXYGENBAR_ID, WidgetID.FossilOxygen.FOSSIL_ISLAND_OXYGEN_BAR),
MINIGAME_TELEPORT_BUTTON(WidgetID.MINIGAME_TAB_ID, WidgetID.Minigames.TELEPORT_BUTTON),
SPELL_LUMBRIDGE_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.StandardSpellBook.LUMBRIDGE_HOME_TELEPORT),
SPELL_EDGEVILLE_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.AncientSpellBook.EDGEVILLE_HOME_TELEPORT),
SPELL_LUNAR_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.LunarSpellBook.LUNAR_HOME_TELEPORT),
SPELL_ARCEUUS_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.ArceuusSpellBook.ARCEUUS_HOME_TELEPORT),
PVP_CONTAINER(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.PVP_WIDGET_CONTAINER),
PVP_SKULL_CONTAINER(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.SKULL_CONTAINER),
PVP_SKULL(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.SKULL),
PVP_WILDERNESS_LEVEL(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.WILDERNESS_LEVEL),
PVP_BOUNTY_HUNTER_INFO(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.BOUNTY_HUNTER_INFO),
PVP_BOUNTY_HUNTER_STATS(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.BOUNTY_HUNTER_STATS),
PVP_KILLDEATH_COUNTER(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.KILLDEATH_RATIO),
PVP_WORLD_SAFE_ZONE(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.SAFE_ZONE),
PVP_WORLD_ATTACK_RANGE(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.ATTACK_RANGE),
DEADMAN_PROTECTION_TEXT(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.WILDERNESS_LEVEL),
DEADMAN_PROTECTION_TIME(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.DEADMAN_PROTECTION_TIME),
KOUREND_FAVOUR_OVERLAY(WidgetID.KOUREND_FAVOUR_GROUP_ID, WidgetID.KourendFavour.KOUREND_FAVOUR_OVERLAY),
ZEAH_MESS_HALL_COOKING_DISPLAY(WidgetID.ZEAH_MESS_HALL_GROUP_ID, WidgetID.Zeah.MESS_HALL_COOKING_DISPLAY),
LOOTING_BAG_CONTAINER(WidgetID.LOOTING_BAG_GROUP_ID, WidgetID.LootingBag.LOOTING_BAG_INVENTORY),
SKOTIZO_CONTAINER(WidgetID.SKOTIZO_GROUP_ID, WidgetID.Skotizo.CONTAINER),
FULLSCREEN_MAP_ROOT(WidgetID.FULLSCREEN_MAP_GROUP_ID, WidgetID.FullScreenMap.ROOT),
QUESTLIST_FREE_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.FREE_CONTAINER),
QUESTLIST_MEMBERS_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.MEMBERS_CONTAINER),
QUESTLIST_MINIQUEST_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.MINIQUEST_CONTAINER);
private final int groupId;
private final int childId;
WidgetInfo(int groupId, int childId)
{
this.groupId = groupId;
this.childId = childId;
}
/**
* Gets the ID of the group-child pairing.
*
* @return the ID
*/
public int getId()
{
return groupId << 16 | childId;
}
/**
* Gets the group ID of the pair.
*
* @return the group ID
*/
public int getGroupId()
{
return groupId;
}
/**
* Gets the ID of the child in the group.
*
* @return the child ID
*/
public int getChildId()
{
return childId;
}
/**
* Gets the packed widget ID.
*
* @return the packed ID
*/
public int getPackedId()
{
return groupId << 16 | childId;
}
/**
* Utility method that converts an ID returned by {@link #getId()} back
* to its group ID.
*
* @param id passed group-child ID
* @return the group ID
*/
public static int TO_GROUP(int id)
{
return id >>> 16;
}
/**
* Utility method that converts an ID returned by {@link #getId()} back
* to its child ID.
*
* @param id passed group-child ID
* @return the child ID
*/
public static int TO_CHILD(int id)
{
return id & 0xFFFF;
}
/**
* Packs the group and child IDs into a single integer.
*
* @param groupId the group ID
* @param childId the child ID
* @return the packed ID
*/
public static int PACK(int groupId, int childId)
{
return groupId << 16 | childId;
}
}
|
runelite-api/src/main/java/net/runelite/api/widgets/WidgetInfo.java
|
/*
* Copyright (c) 2017, Adam <Adam@sigterm.info>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 net.runelite.api.widgets;
/**
* Represents a group-child {@link Widget} relationship.
* <p>
* For getting a specific widget from the client, see {@link net.runelite.api.Client#getWidget(WidgetInfo)}.
*/
public enum WidgetInfo
{
FAIRY_RING_LEFT_ORB_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.LEFT_ORB_CLOCKWISE),
FAIRY_RING_LEFT_ORB_COUNTER_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.LEFT_ORB_COUNTER_CLOCKWISE),
FAIRY_RING_MIDDLE_ORB_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.MIDDLE_ORB_CLOCKWISE),
FAIRY_RING_MIDDLE_ORB_COUNTER_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.MIDDLE_ORB_COUNTER_CLOCKWISE),
FAIRY_RING_RIGHT_ORB_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.RIGHT_ORB_CLOCKWISE),
FAIRY_RING_RIGHT_ORB_COUNTER_CLOCKWISE(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.RIGHT_ORB_COUNTER_CLOCKWISE),
FAIRY_RING_TELEPORT_BUTTON(WidgetID.FAIRY_RING_GROUP_ID, WidgetID.FairyRing.TELEPORT_BUTTON),
WORLD_SWITCHER_BUTTON(WidgetID.LOGOUT_PANEL_ID, WidgetID.LogoutPanel.WORLD_SWITCHER_BUTTON),
LOGOUT_BUTTON(WidgetID.LOGOUT_PANEL_ID, WidgetID.LogoutPanel.LOGOUT_BUTTON),
INVENTORY(WidgetID.INVENTORY_GROUP_ID, 0),
FRIENDS_LIST(WidgetID.FRIENDS_LIST_GROUP_ID, 0),
CLAN_CHAT(WidgetID.CLAN_CHAT_GROUP_ID, 0),
RAIDING_PARTY(WidgetID.RAIDING_PARTY_GROUP_ID, 0),
WORLD_MAP_VIEW(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.MAPVIEW),
WORLD_MAP_OVERVIEW_MAP(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.OVERVIEW_MAP),
WORLD_MAP_SEARCH(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.SEARCH),
WORLD_MAP_SURFACE_SELECTOR(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.SURFACE_SELECTOR),
WORLD_MAP_TOOLTIP(WidgetID.WORLD_MAP_GROUP_ID, WidgetID.WorldMap.TOOLTIP),
WORLD_MAP_OPTION(WidgetID.WORLD_MAP_MENU_GROUP_ID, WidgetID.WorldMap.OPTION),
CLUE_SCROLL_TEXT(WidgetID.CLUE_SCROLL_GROUP_ID, WidgetID.Cluescroll.CLUE_TEXT),
CLUE_SCROLL_REWARD_ITEM_CONTAINER(WidgetID.CLUE_SCROLL_REWARD_GROUP_ID, WidgetID.Cluescroll.CLUE_SCROLL_ITEM_CONTAINER),
EQUIPMENT(WidgetID.EQUIPMENT_GROUP_ID, 0),
EQUIPMENT_INVENTORY_ITEMS_CONTAINER(WidgetID.EQUIPMENT_INVENTORY_GROUP_ID, WidgetID.Equipment.INVENTORY_ITEM_CONTAINER),
EQUIPMENT_HELMET(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.HELMET),
EQUIPMENT_CAPE(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.CAPE),
EQUIPMENT_AMULET(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.AMULET),
EQUIPMENT_WEAPON(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.WEAPON),
EQUIPMENT_BODY(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.BODY),
EQUIPMENT_SHIELD(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.SHIELD),
EQUIPMENT_LEGS(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.LEGS),
EQUIPMENT_GLOVES(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.GLOVES),
EQUIPMENT_BOOTS(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.BOOTS),
EQUIPMENT_RING(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.RING),
EQUIPMENT_AMMO(WidgetID.EQUIPMENT_GROUP_ID, WidgetID.Equipment.AMMO),
EMOTE_WINDOW(WidgetID.EMOTES_GROUP_ID, WidgetID.Emotes.EMOTE_WINDOW),
EMOTE_CONTAINER(WidgetID.EMOTES_GROUP_ID, WidgetID.Emotes.EMOTE_CONTAINER),
DIARY_LIST(WidgetID.DIARY_GROUP_ID, 10),
DIARY_QUEST_WIDGET_TITLE(WidgetID.DIARY_QUEST_GROUP_ID, WidgetID.Diary.DIARY_TITLE),
DIARY_QUEST_WIDGET_TEXT(WidgetID.DIARY_QUEST_GROUP_ID, WidgetID.Diary.DIARY_TEXT),
PEST_CONTROL_BOAT_INFO(WidgetID.PEST_CONTROL_BOAT_GROUP_ID, WidgetID.PestControlBoat.INFO),
PEST_CONTROL_INFO(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.INFO),
PEST_CONTROL_PURPLE_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.PURPLE_SHIELD),
PEST_CONTROL_BLUE_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.BLUE_SHIELD),
PEST_CONTROL_YELLOW_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.YELLOW_SHIELD),
PEST_CONTROL_RED_SHIELD(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.RED_SHIELD),
PEST_CONTROL_PURPLE_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.PURPLE_HEALTH),
PEST_CONTROL_BLUE_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.BLUE_HEALTH),
PEST_CONTROL_YELLOW_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.YELLOW_HEALTH),
PEST_CONTROL_RED_HEALTH(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.RED_HEALTH),
PEST_CONTROL_PURPLE_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.PURPLE_ICON),
PEST_CONTROL_BLUE_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.BLUE_ICON),
PEST_CONTROL_YELLOW_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.YELLOW_ICON),
PEST_CONTROL_RED_ICON(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.RED_ICON),
PEST_CONTROL_ACTIVITY_BAR(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.ACTIVITY_BAR),
PEST_CONTROL_ACTIVITY_PROGRESS(WidgetID.PEST_CONTROL_GROUP_ID, WidgetID.PestControl.ACTIVITY_PROGRESS),
VOLCANIC_MINE_GENERAL_INFOBOX_GROUP(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.GENERAL_INFOBOX_GROUP_ID),
VOLCANIC_MINE_TIME_LEFT(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.TIME_LEFT),
VOLCANIC_MINE_POINTS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.POINTS),
VOLCANIC_MINE_STABILITY(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.STABILITY),
VOLCANIC_MINE_PLAYER_COUNT(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.PLAYER_COUNT),
VOLCANIC_MINE_VENTS_INFOBOX_GROUP(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENTS_INFOBOX_GROUP_ID),
VOLCANIC_MINE_VENT_A_PERCENTAGE(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_A_PERCENTAGE),
VOLCANIC_MINE_VENT_B_PERCENTAGE(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_B_PERCENTAGE),
VOLCANIC_MINE_VENT_C_PERCENTAGE(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_C_PERCENTAGE),
VOLCANIC_MINE_VENT_A_STATUS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_A_STATUS),
VOLCANIC_MINE_VENT_B_STATUS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_B_STATUS),
VOLCANIC_MINE_VENT_C_STATUS(WidgetID.VOLCANIC_MINE_GROUP_ID, WidgetID.VolcanicMine.VENT_C_STATUS),
FRIEND_CHAT_TITLE(WidgetID.FRIENDS_LIST_GROUP_ID, WidgetID.FriendList.TITLE),
IGNORE_TITLE(WidgetID.IGNORE_LIST_GROUP_ID, WidgetID.IgnoreList.TITLE),
CLAN_CHAT_TITLE(WidgetID.CLAN_CHAT_GROUP_ID, WidgetID.ClanChat.TITLE),
CLAN_CHAT_NAME(WidgetID.CLAN_CHAT_GROUP_ID, WidgetID.ClanChat.NAME),
CLAN_CHAT_OWNER(WidgetID.CLAN_CHAT_GROUP_ID, WidgetID.ClanChat.OWNER),
CLAN_CHAT_LIST(WidgetID.CLAN_CHAT_GROUP_ID, WidgetID.ClanChat.LIST),
BANK_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.BANK_CONTAINER),
BANK_SEARCH_BUTTON_BACKGROUND(WidgetID.BANK_GROUP_ID, WidgetID.Bank.SEARCH_BUTTON_BACKGROUND),
BANK_ITEM_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.ITEM_CONTAINER),
BANK_INVENTORY_ITEMS_CONTAINER(WidgetID.BANK_INVENTORY_GROUP_ID, WidgetID.Bank.INVENTORY_ITEM_CONTAINER),
BANK_TITLE_BAR(WidgetID.BANK_GROUP_ID, WidgetID.Bank.BANK_TITLE_BAR),
BANK_INCINERATOR(WidgetID.BANK_GROUP_ID, WidgetID.Bank.INCINERATOR),
BANK_INCINERATOR_CONFIRM(WidgetID.BANK_GROUP_ID, WidgetID.Bank.INCINERATOR_CONFIRM),
BANK_CONTENT_CONTAINER(WidgetID.BANK_GROUP_ID, WidgetID.Bank.CONTENT_CONTAINER),
BANK_DEPOSIT_EQUIPMENT(WidgetID.BANK_GROUP_ID, WidgetID.Bank.DEPOSIT_EQUIPMENT),
BANK_DEPOSIT_INVENTORY(WidgetID.BANK_GROUP_ID, WidgetID.Bank.DEPOSIT_INVENTORY),
GRAND_EXCHANGE_WINDOW_CONTAINER(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.WINDOW_CONTAINER),
GRAND_EXCHANGE_OFFER_CONTAINER(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.OFFER_CONTAINER),
GRAND_EXCHANGE_OFFER_TEXT(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.OFFER_DESCRIPTION),
GRAND_EXCHANGE_OFFER_PRICE(WidgetID.GRAND_EXCHANGE_GROUP_ID, WidgetID.GrandExchange.OFFER_PRICE),
GRAND_EXCHANGE_INVENTORY_ITEMS_CONTAINER(WidgetID.GRAND_EXCHANGE_INVENTORY_GROUP_ID, WidgetID.GrandExchangeInventory.INVENTORY_ITEM_CONTAINER),
DEPOSIT_BOX_INVENTORY_ITEMS_CONTAINER(WidgetID.DEPOSIT_BOX_GROUP_ID, WidgetID.DepositBox.INVENTORY_ITEM_CONTAINER),
SHOP_ITEMS_CONTAINER(WidgetID.SHOP_GROUP_ID, WidgetID.Shop.ITEMS_CONTAINER),
SHOP_INVENTORY_ITEMS_CONTAINER(WidgetID.SHOP_INVENTORY_GROUP_ID, WidgetID.Shop.INVENTORY_ITEM_CONTAINER),
SMITHING_INVENTORY_ITEMS_CONTAINER(WidgetID.SMITHING_GROUP_ID, WidgetID.Smithing.INVENTORY_ITEM_CONTAINER),
GUIDE_PRICES_ITEMS_CONTAINER(WidgetID.GUIDE_PRICES_GROUP_ID, WidgetID.GuidePrices.ITEM_CONTAINER),
GUIDE_PRICES_INVENTORY_ITEMS_CONTAINER(WidgetID.GUIDE_PRICES_INVENTORY_GROUP_ID, WidgetID.GuidePrices.INVENTORY_ITEM_CONTAINER),
RUNE_POUCH_ITEM_CONTAINER(WidgetID.RUNE_POUCH_GROUP_ID, 0),
MINIMAP_ORBS(WidgetID.MINIMAP_GROUP_ID, 0),
MINIMAP_XP_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.XP_ORB),
MINIMAP_PRAYER_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.PRAYER_ORB),
MINIMAP_QUICK_PRAYER_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.QUICK_PRAYER_ORB),
MINIMAP_RUN_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.RUN_ORB),
MINIMAP_TOGGLE_RUN_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.TOGGLE_RUN_ORB),
MINIMAP_RUN_ORB_TEXT(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.RUN_ORB_TEXT),
MINIMAP_HEALTH_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.HEALTH_ORB),
MINIMAP_SPEC_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.SPEC_ORB),
MINIMAP_WORLDMAP_ORB(WidgetID.MINIMAP_GROUP_ID, WidgetID.Minimap.WORLDMAP_ORB),
LOGIN_CLICK_TO_PLAY_SCREEN(WidgetID.LOGIN_CLICK_TO_PLAY_GROUP_ID, 0),
LOGIN_CLICK_TO_PLAY_SCREEN_MESSAGE_OF_THE_DAY(WidgetID.LOGIN_CLICK_TO_PLAY_GROUP_ID, WidgetID.LoginClickToPlayScreen.MESSAGE_OF_THE_DAY),
FIXED_VIEWPORT(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.Viewport.FIXED_VIEWPORT),
FIXED_VIEWPORT_ROOT_INTERFACE_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.ROOT_INTERFACE_CONTAINER),
FIXED_VIEWPORT_BANK_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.BANK_CONTAINER),
FIXED_VIEWPORT_INTERFACE_CONTAINER(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INTERFACE_CONTAINER),
FIXED_VIEWPORT_COMBAT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.COMBAT_TAB),
FIXED_VIEWPORT_STATS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.STATS_TAB),
FIXED_VIEWPORT_QUESTS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.QUESTS_TAB),
FIXED_VIEWPORT_INVENTORY_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INVENTORY_TAB),
FIXED_VIEWPORT_EQUIPMENT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EQUIPMENT_TAB),
FIXED_VIEWPORT_PRAYER_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.PRAYER_TAB),
FIXED_VIEWPORT_MAGIC_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MAGIC_TAB),
FIXED_VIEWPORT_CLAN_CHAT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.CLAN_CHAT_TAB),
FIXED_VIEWPORT_FRIENDS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.FRIENDS_TAB),
FIXED_VIEWPORT_IGNORES_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.IGNORES_TAB),
FIXED_VIEWPORT_LOGOUT_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.LOGOUT_TAB),
FIXED_VIEWPORT_OPTIONS_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.OPTIONS_TAB),
FIXED_VIEWPORT_EMOTES_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EMOTES_TAB),
FIXED_VIEWPORT_MUSIC_TAB(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MUSIC_TAB),
FIXED_VIEWPORT_COMBAT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.COMBAT_ICON),
FIXED_VIEWPORT_STATS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.STATS_ICON),
FIXED_VIEWPORT_QUESTS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.QUESTS_ICON),
FIXED_VIEWPORT_INVENTORY_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.INVENTORY_ICON),
FIXED_VIEWPORT_EQUIPMENT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EQUIPMENT_ICON),
FIXED_VIEWPORT_PRAYER_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.PRAYER_ICON),
FIXED_VIEWPORT_MAGIC_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MAGIC_ICON),
FIXED_VIEWPORT_CLAN_CHAT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.CLAN_CHAT_ICON),
FIXED_VIEWPORT_FRIENDS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.FRIENDS_ICON),
FIXED_VIEWPORT_IGNORES_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.IGNORES_ICON),
FIXED_VIEWPORT_LOGOUT_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.LOGOUT_ICON),
FIXED_VIEWPORT_OPTIONS_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.OPTIONS_ICON),
FIXED_VIEWPORT_EMOTES_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.EMOTES_ICON),
FIXED_VIEWPORT_MUSIC_ICON(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MUSIC_ICON),
FIXED_VIEWPORT_MINIMAP(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MINIMAP),
FIXED_VIEWPORT_MINIMAP_DRAW_AREA(WidgetID.FIXED_VIEWPORT_GROUP_ID, WidgetID.FixedViewport.MINIMAP_DRAW_AREA),
RESIZABLE_MINIMAP_WIDGET(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_WIDGET),
RESIZABLE_MINIMAP_CLICKBOX(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_CLICKBOX),
RESIZABLE_MINIMAP_DRAW_AREA(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DRAW_AREA),
RESIZABLE_MINIMAP_DECORATIONS(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DECORATIONS),
RESIZABLE_MINIMAP_ORB_HOLDER(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_ORB_HOLDER),
RESIZABLE_MINIMAP_LOGOUT_BUTTON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_LOGOUT_BUTTON),
RESIZABLE_MINIMAP_STONES_WIDGET(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_WIDGET),
RESIZABLE_MINIMAP_STONES_CLICKBOX(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_CLICKBOX),
RESIZABLE_MINIMAP_STONES_DRAW_AREA(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DRAW_AREA),
RESIZABLE_MINIMAP_STONES_DECORATIONS(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_DECORATIONS),
RESIZABLE_MINIMAP_STONES_ORB_HOLDER(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.MINIMAP_RESIZABLE_ORB_HOLDER),
RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.Viewport.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX),
RESIZABLE_VIEWPORT_COMBAT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.COMBAT_TAB),
RESIZABLE_VIEWPORT_STATS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.STATS_TAB),
RESIZABLE_VIEWPORT_QUESTS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.QUESTS_TAB),
RESIZABLE_VIEWPORT_INVENTORY_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INVENTORY_TAB),
RESIZABLE_VIEWPORT_EQUIPMENT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EQUIPMENT_TAB),
RESIZABLE_VIEWPORT_PRAYER_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.PRAYER_TAB),
RESIZABLE_VIEWPORT_MAGIC_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MAGIC_TAB),
RESIZABLE_VIEWPORT_CLAN_CHAT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.CLAN_CHAT_TAB),
RESIZABLE_VIEWPORT_FRIENDS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.FRIENDS_TAB),
RESIZABLE_VIEWPORT_IGNORES_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.IGNORES_TAB),
RESIZABLE_VIEWPORT_LOGOUT_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.LOGOUT_TAB),
RESIZABLE_VIEWPORT_OPTIONS_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.OPTIONS_TAB),
RESIZABLE_VIEWPORT_EMOTES_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EMOTES_TAB),
RESIZABLE_VIEWPORT_MUSIC_TAB(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MUSIC_TAB),
RESIZABLE_VIEWPORT_COMBAT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.COMBAT_ICON),
RESIZABLE_VIEWPORT_STATS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.STATS_ICON),
RESIZABLE_VIEWPORT_QUESTS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.QUESTS_ICON),
RESIZABLE_VIEWPORT_INVENTORY_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INVENTORY_ICON),
RESIZABLE_VIEWPORT_EQUIPMENT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EQUIPMENT_ICON),
RESIZABLE_VIEWPORT_PRAYER_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.PRAYER_ICON),
RESIZABLE_VIEWPORT_MAGIC_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MAGIC_ICON),
RESIZABLE_VIEWPORT_CLAN_CHAT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.CLAN_CHAT_ICON),
RESIZABLE_VIEWPORT_FRIENDS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.FRIENDS_ICON),
RESIZABLE_VIEWPORT_IGNORES_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.IGNORES_ICON),
RESIZABLE_VIEWPORT_LOGOUT_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.LOGOUT_ICON),
RESIZABLE_VIEWPORT_OPTIONS_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.OPTIONS_ICON),
RESIZABLE_VIEWPORT_EMOTES_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.EMOTES_ICON),
RESIZABLE_VIEWPORT_MUSIC_ICON(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.MUSIC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.Viewport.RESIZABLE_VIEWPORT_BOTTOM_LINE),
RESIZABLE_VIEWPORT_BOTTOM_LINE_LOGOUT_BUTTON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.LOGOUT_BUTTON_OVERLAY),
RESIZABLE_VIEWPORT_BOTTOM_LINE_QUESTS_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.QUESTS_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.INVENTORY_TAB),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.INVENTORY_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_PRAYER_TAB(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.PRAYER_TAB),
RESIZABLE_VIEWPORT_BOTTOM_LINE_PRAYER_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.PRAYER_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_EQUIPMENT_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.EQUIP_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_COMBAT_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.CMB_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_STATS_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.SKILLS_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_MAGIC_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.MAGIC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_FRIEND_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.FRIEND_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_FRIEND_CHAT_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.FC_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_OPTIONS_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.SETTINGS_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_EMOTES_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.EMOTE_ICON),
RESIZABLE_VIEWPORT_BOTTOM_LINE_MUSIC_ICON(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewportBottomLine.MUSIC_ICON),
RESIZABLE_VIEWPORT_INTERFACE_CONTAINER(WidgetID.RESIZABLE_VIEWPORT_OLD_SCHOOL_BOX_GROUP_ID, WidgetID.ResizableViewport.INTERFACE_CONTAINER),
RESIZABLE_VIEWPORT_BOTTOM_LINE_INTERFACE_CONTAINER(WidgetID.RESIZABLE_VIEWPORT_BOTTOM_LINE_GROUP_ID, WidgetID.ResizableViewport.INTERFACE_CONTAINER),
PRAYER_THICK_SKIN(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.THICK_SKIN),
PRAYER_BURST_OF_STRENGTH(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.BURST_OF_STRENGTH),
PRAYER_CLARITY_OF_THOUGHT(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.CLARITY_OF_THOUGHT),
PRAYER_SHARP_EYE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.SHARP_EYE),
PRAYER_MYSTIC_WILL(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.MYSTIC_WILL),
PRAYER_ROCK_SKIN(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.ROCK_SKIN),
PRAYER_SUPERHUMAN_STRENGTH(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.SUPERHUMAN_STRENGTH),
PRAYER_IMPROVED_REFLEXES(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.IMPROVED_REFLEXES),
PRAYER_RAPID_RESTORE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RAPID_RESTORE),
PRAYER_RAPID_HEAL(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RAPID_HEAL),
PRAYER_PROTECT_ITEM(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_ITEM),
PRAYER_HAWK_EYE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.HAWK_EYE),
PRAYER_MYSTIC_LORE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.MYSTIC_LORE),
PRAYER_STEEL_SKIN(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.STEEL_SKIN),
PRAYER_ULTIMATE_STRENGTH(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.ULTIMATE_STRENGTH),
PRAYER_INCREDIBLE_REFLEXES(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.INCREDIBLE_REFLEXES),
PRAYER_PROTECT_FROM_MAGIC(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_FROM_MAGIC),
PRAYER_PROTECT_FROM_MISSILES(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_FROM_MISSILES),
PRAYER_PROTECT_FROM_MELEE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PROTECT_FROM_MELEE),
PRAYER_EAGLE_EYE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.EAGLE_EYE),
PRAYER_MYSTIC_MIGHT(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.MYSTIC_MIGHT),
PRAYER_RETRIBUTION(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RETRIBUTION),
PRAYER_REDEMPTION(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.REDEMPTION),
PRAYER_SMITE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.SMITE),
PRAYER_PRESERVE(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PRESERVE),
PRAYER_CHIVALRY(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.CHIVALRY),
PRAYER_PIETY(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.PIETY),
PRAYER_RIGOUR(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.RIGOUR),
PRAYER_AUGURY(WidgetID.PRAYER_GROUP_ID, WidgetID.Prayer.AUGURY),
QUICK_PRAYER_PRAYERS(WidgetID.QUICK_PRAYERS_GROUP_ID, WidgetID.QuickPrayer.PRAYERS),
COMBAT_LEVEL(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.LEVEL),
COMBAT_STYLE_ONE(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_ONE),
COMBAT_STYLE_TWO(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_TWO),
COMBAT_STYLE_THREE(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_THREE),
COMBAT_STYLE_FOUR(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.STYLE_FOUR),
COMBAT_SPELLS(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELLS),
COMBAT_DEFENSIVE_SPELL_BOX(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_BOX),
COMBAT_DEFENSIVE_SPELL_ICON(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_ICON),
COMBAT_DEFENSIVE_SPELL_SHIELD(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_SHIELD),
COMBAT_DEFENSIVE_SPELL_TEXT(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.DEFENSIVE_SPELL_TEXT),
COMBAT_SPELL_BOX(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELL_BOX),
COMBAT_SPELL_ICON(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELL_ICON),
COMBAT_SPELL_TEXT(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.SPELL_TEXT),
COMBAT_AUTO_RETALIATE(WidgetID.COMBAT_GROUP_ID, WidgetID.Combat.AUTO_RETALIATE),
DIALOG_OPTION(WidgetID.DIALOG_OPTION_GROUP_ID, 0),
DIALOG_SPRITE(WidgetID.DIALOG_SPRITE_GROUP_ID, 0),
DIALOG_SPRITE_SPRITE(WidgetID.DIALOG_SPRITE_GROUP_ID, WidgetID.DialogSprite.SPRITE),
DIALOG_SPRITE_TEXT(WidgetID.DIALOG_SPRITE_GROUP_ID, WidgetID.DialogSprite.TEXT),
DIALOG_NPC(WidgetID.DIALOG_NPC_GROUP_ID, 0),
DIALOG_NPC_NAME(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.NAME),
DIALOG_NPC_TEXT(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.TEXT),
DIALOG_NPC_HEAD_MODEL(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.HEAD_MODEL),
DIALOG_NPC_CONTINUE(WidgetID.DIALOG_NPC_GROUP_ID, WidgetID.DialogNPC.CONTINUE),
DIALOG_PLAYER(WidgetID.DIALOG_PLAYER_GROUP_ID, 0),
PRIVATE_CHAT_MESSAGE(WidgetID.PRIVATE_CHAT, 0),
SLAYER_REWARDS_TOPBAR(WidgetID.SLAYER_REWARDS_GROUP_ID, WidgetID.SlayerRewards.TOP_BAR),
CHATBOX_PARENT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.PARENT),
CHATBOX(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.FRAME),
CHATBOX_MESSAGES(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.MESSAGES),
CHATBOX_BUTTONS(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.BUTTONS),
CHATBOX_TITLE(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TITLE),
CHATBOX_FULL_INPUT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.FULL_INPUT),
CHATBOX_CONTAINER(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.CONTAINER),
CHATBOX_REPORT_TEXT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.REPORT_TEXT),
CHATBOX_INPUT(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.INPUT),
CHATBOX_TRANSPARENT_BACKGROUND(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TRANSPARENT_BACKGROUND),
CHATBOX_TRANSPARENT_LINES(WidgetID.CHATBOX_GROUP_ID, WidgetID.Chatbox.TRANSPARENT_BACKGROUND_LINES),
BA_HEAL_WAVE_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_HEAL_CALL_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.TO_CALL),
BA_HEAL_LISTEN_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.CORRECT_STYLE),
BA_HEAL_ROLE_TEXT(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.ROLE),
BA_HEAL_ROLE_SPRITE(WidgetID.BA_HEALER_GROUP_ID, WidgetID.BarbarianAssault.ROLE_SPRITE),
BA_COLL_WAVE_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_COLL_CALL_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.TO_CALL),
BA_COLL_LISTEN_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.CORRECT_STYLE),
BA_COLL_ROLE_TEXT(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.ROLE),
BA_COLL_ROLE_SPRITE(WidgetID.BA_COLLECTOR_GROUP_ID, WidgetID.BarbarianAssault.ROLE_SPRITE),
BA_ATK_WAVE_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_ATK_CALL_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.TO_CALL),
BA_ATK_LISTEN_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.CORRECT_STYLE),
BA_ATK_ROLE_TEXT(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.ROLE),
BA_ATK_ROLE_SPRITE(WidgetID.BA_ATTACKER_GROUP_ID, WidgetID.BarbarianAssault.ATK.ROLE_SPRITE),
BA_DEF_WAVE_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.CURRENT_WAVE),
BA_DEF_CALL_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.TO_CALL),
BA_DEF_LISTEN_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.CORRECT_STYLE),
BA_DEF_ROLE_TEXT(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.ROLE),
BA_DEF_ROLE_SPRITE(WidgetID.BA_DEFENDER_GROUP_ID, WidgetID.BarbarianAssault.ROLE_SPRITE),
BA_REWARD_TEXT(WidgetID.BA_REWARD_GROUP_ID, WidgetID.BarbarianAssault.REWARD_TEXT),
LEVEL_UP(WidgetID.LEVEL_UP_GROUP_ID, 0),
LEVEL_UP_SKILL(WidgetID.LEVEL_UP_GROUP_ID, WidgetID.LevelUp.SKILL),
LEVEL_UP_LEVEL(WidgetID.LEVEL_UP_GROUP_ID, WidgetID.LevelUp.LEVEL),
QUEST_COMPLETED(WidgetID.QUEST_COMPLETED_GROUP_ID, 0),
QUEST_COMPLETED_NAME_TEXT(WidgetID.QUEST_COMPLETED_GROUP_ID, WidgetID.QuestCompleted.NAME_TEXT),
MOTHERLODE_MINE(WidgetID.MOTHERLODE_MINE_GROUP_ID, 0),
PUZZLE_BOX(WidgetID.PUZZLE_BOX_GROUP_ID, WidgetID.PuzzleBox.VISIBLE_BOX),
LIGHT_BOX(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BOX),
LIGHT_BOX_CONTENTS(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BULB_CONTAINER),
LIGHT_BOX_BUTTON_A(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_A),
LIGHT_BOX_BUTTON_B(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_B),
LIGHT_BOX_BUTTON_C(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_C),
LIGHT_BOX_BUTTON_D(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_D),
LIGHT_BOX_BUTTON_E(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_E),
LIGHT_BOX_BUTTON_F(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_F),
LIGHT_BOX_BUTTON_G(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_G),
LIGHT_BOX_BUTTON_H(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.BUTTON_H),
LIGHT_BOX_WINDOW(WidgetID.LIGHT_BOX_GROUP_ID, WidgetID.LightBox.LIGHT_BOX_WINDOW),
NIGHTMARE_ZONE(WidgetID.NIGHTMARE_ZONE_GROUP_ID, 0),
RAIDS_POINTS_INFOBOX(WidgetID.RAIDS_GROUP_ID, WidgetID.Raids.POINTS_INFOBOX),
BLAST_FURNACE_COFFER(WidgetID.BLAST_FURNACE_GROUP_ID, 2),
PYRAMID_PLUNDER_DATA(WidgetID.PYRAMID_PLUNDER_GROUP_ID, 2),
EXPERIENCE_TRACKER(WidgetID.EXPERIENCE_TRACKER_GROUP_ID, 0),
EXPERIENCE_TRACKER_WIDGET(WidgetID.EXPERIENCE_TRACKER_GROUP_ID, WidgetID.ExperienceTracker.WIDGET),
EXPERIENCE_TRACKER_BOTTOM_BAR(WidgetID.EXPERIENCE_TRACKER_GROUP_ID, WidgetID.ExperienceTracker.BOTTOM_BAR),
TITHE_FARM(WidgetID.TITHE_FARM_GROUP_ID, 1),
BARROWS_INFO(WidgetID.BARROWS_GROUP_ID, 0),
BARROWS_BROTHERS(WidgetID.BARROWS_GROUP_ID, WidgetID.Barrows.BARROWS_BROTHERS),
BARROWS_POTENTIAL(WidgetID.BARROWS_GROUP_ID, WidgetID.Barrows.BARROWS_POTENTIAL),
BARROWS_REWARD_INVENTORY(WidgetID.BARROWS_REWARD_GROUP_ID, WidgetID.Barrows.BARROWS_REWARD_INVENTORY),
BLAST_MINE(WidgetID.BLAST_MINE_GROUP_ID, 2),
FAIRY_RING(WidgetID.FAIRY_RING_GROUP_ID, 0),
FAIRY_RING_HEADER(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.HEADER),
FAIRY_RING_LIST(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.LIST),
FAIRY_RING_FAVORITES(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.FAVORITES),
FAIRY_RING_LIST_SEPARATOR(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.SEPARATOR),
FAIRY_RING_LIST_SCROLLBAR(WidgetID.FAIRY_RING_PANEL_GROUP_ID, WidgetID.FairyRingPanel.SCROLLBAR),
DESTROY_ITEM(WidgetID.DESTROY_ITEM_GROUP_ID, 0),
DESTROY_ITEM_NAME(WidgetID.DESTROY_ITEM_GROUP_ID, WidgetID.DestroyItem.DESTROY_ITEM_NAME),
DESTROY_ITEM_YES(WidgetID.DESTROY_ITEM_GROUP_ID, WidgetID.DestroyItem.DESTROY_ITEM_YES),
DESTROY_ITEM_NO(WidgetID.DESTROY_ITEM_GROUP_ID, WidgetID.DestroyItem.DESTROY_ITEM_NO),
VARROCK_MUSEUM_QUESTION(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_QUESTION),
VARROCK_MUSEUM_FIRST_ANSWER(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_FIRST_ANSWER),
VARROCK_MUSEUM_SECOND_ANSWER(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_SECOND_ANSWER),
VARROCK_MUSEUM_THIRD_ANSWER(WidgetID.VARROCK_MUSEUM_QUIZ_GROUP_ID, WidgetID.VarrockMuseum.VARROCK_MUSEUM_THIRD_ANSWER),
KILL_LOG_TITLE(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.TITLE),
KILL_LOG_MONSTER(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.MONSTER),
KILL_LOG_KILLS(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.KILLS),
KILL_LOG_STREAK(WidgetID.KILL_LOGS_GROUP_ID, WidgetID.KillLog.STREAK),
WORLD_SWITCHER_LIST(WidgetID.WORLD_SWITCHER_GROUP_ID, WidgetID.WorldSwitcher.WORLD_LIST),
FOSSIL_ISLAND_OXYGENBAR(WidgetID.FOSSIL_ISLAND_OXYGENBAR_ID, WidgetID.FossilOxygen.FOSSIL_ISLAND_OXYGEN_BAR),
MINIGAME_TELEPORT_BUTTON(WidgetID.MINIGAME_TAB_ID, WidgetID.Minigames.TELEPORT_BUTTON),
SPELL_LUMBRIDGE_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.StandardSpellBook.LUMBRIDGE_HOME_TELEPORT),
SPELL_EDGEVILLE_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.AncientSpellBook.EDGEVILLE_HOME_TELEPORT),
SPELL_LUNAR_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.LunarSpellBook.LUNAR_HOME_TELEPORT),
SPELL_ARCEUUS_HOME_TELEPORT(WidgetID.SPELLBOOK_GROUP_ID, WidgetID.ArceuusSpellBook.ARCEUUS_HOME_TELEPORT),
PVP_CONTAINER(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.PVP_WIDGET_CONTAINER),
PVP_SKULL_CONTAINER(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.SKULL_CONTAINER),
PVP_SKULL(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.SKULL),
PVP_WILDERNESS_LEVEL(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.ATTACK_RANGE),
PVP_BOUNTY_HUNTER_INFO(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.BOUNTY_HUNTER_INFO),
PVP_BOUNTY_HUNTER_STATS(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.BOUNTY_HUNTER_STATS),
PVP_KILLDEATH_COUNTER(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.KILLDEATH_RATIO),
PVP_WORLD_SAFE_ZONE(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.SAFE_ZONE),
PVP_WORLD_ATTACK_RANGE(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.ATTACK_RANGE),
DEADMAN_PROTECTION_TEXT(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.WILDERNESS_LEVEL),
DEADMAN_PROTECTION_TIME(WidgetID.PVP_GROUP_ID, WidgetID.Pvp.DEADMAN_PROTECTION_TIME),
KOUREND_FAVOUR_OVERLAY(WidgetID.KOUREND_FAVOUR_GROUP_ID, WidgetID.KourendFavour.KOUREND_FAVOUR_OVERLAY),
ZEAH_MESS_HALL_COOKING_DISPLAY(WidgetID.ZEAH_MESS_HALL_GROUP_ID, WidgetID.Zeah.MESS_HALL_COOKING_DISPLAY),
LOOTING_BAG_CONTAINER(WidgetID.LOOTING_BAG_GROUP_ID, WidgetID.LootingBag.LOOTING_BAG_INVENTORY),
SKOTIZO_CONTAINER(WidgetID.SKOTIZO_GROUP_ID, WidgetID.Skotizo.CONTAINER),
FULLSCREEN_MAP_ROOT(WidgetID.FULLSCREEN_MAP_GROUP_ID, WidgetID.FullScreenMap.ROOT),
QUESTLIST_FREE_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.FREE_CONTAINER),
QUESTLIST_MEMBERS_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.MEMBERS_CONTAINER),
QUESTLIST_MINIQUEST_CONTAINER(WidgetID.QUESTLIST_GROUP_ID, WidgetID.QuestList.MINIQUEST_CONTAINER);
private final int groupId;
private final int childId;
WidgetInfo(int groupId, int childId)
{
this.groupId = groupId;
this.childId = childId;
}
/**
* Gets the ID of the group-child pairing.
*
* @return the ID
*/
public int getId()
{
return groupId << 16 | childId;
}
/**
* Gets the group ID of the pair.
*
* @return the group ID
*/
public int getGroupId()
{
return groupId;
}
/**
* Gets the ID of the child in the group.
*
* @return the child ID
*/
public int getChildId()
{
return childId;
}
/**
* Gets the packed widget ID.
*
* @return the packed ID
*/
public int getPackedId()
{
return groupId << 16 | childId;
}
/**
* Utility method that converts an ID returned by {@link #getId()} back
* to its group ID.
*
* @param id passed group-child ID
* @return the group ID
*/
public static int TO_GROUP(int id)
{
return id >>> 16;
}
/**
* Utility method that converts an ID returned by {@link #getId()} back
* to its child ID.
*
* @param id passed group-child ID
* @return the child ID
*/
public static int TO_CHILD(int id)
{
return id & 0xFFFF;
}
/**
* Packs the group and child IDs into a single integer.
*
* @param groupId the group ID
* @param childId the child ID
* @return the packed ID
*/
public static int PACK(int groupId, int childId)
{
return groupId << 16 | childId;
}
}
|
widgetinfo: Fix wilderness level definition
|
runelite-api/src/main/java/net/runelite/api/widgets/WidgetInfo.java
|
widgetinfo: Fix wilderness level definition
|
|
Java
|
bsd-3-clause
|
dd54793d3d7c18b1eaf106329654555716f38ed1
| 0
|
jbobnar/TwelveMonkeys,jbobnar/TwelveMonkeys,haraldk/TwelveMonkeys,jbobnar/TwelveMonkeys,haraldk/TwelveMonkeys,haraldk/TwelveMonkeys,jbobnar/TwelveMonkeys
|
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.imageio.plugins.psd;
import com.twelvemonkeys.imageio.spi.ProviderInfo;
import com.twelvemonkeys.imageio.util.IIOUtil;
import javax.imageio.ImageReader;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;
import java.io.IOException;
import java.util.Locale;
/**
* PSDImageReaderSpi
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: PSDImageReaderSpi.java,v 1.0 Apr 29, 2008 4:49:03 PM haraldk Exp$
*/
public class PSDImageReaderSpi extends ImageReaderSpi {
/**
* Creates a {@code PSDImageReaderSpi}.
*/
public PSDImageReaderSpi() {
this(IIOUtil.getProviderInfo(PSDImageReaderSpi.class));
}
private PSDImageReaderSpi(final ProviderInfo providerInfo) {
super(
providerInfo.getVendorName(),
providerInfo.getVersion(),
new String[]{"psd", "PSD"},
new String[]{"psd"},
new String[]{
"image/vnd.adobe.photoshop", // Official, IANA registered
"application/vnd.adobe.photoshop", // Used in XMP
"image/x-psd",
"application/x-photoshop",
"image/x-photoshop"
},
"com.twelvemkonkeys.imageio.plugins.psd.PSDImageReader",
new Class[] {ImageInputStream.class},
// new String[]{"com.twelvemkonkeys.imageio.plugins.psd.PSDImageWriterSpi"},
null,
true, // supports standard stream metadata
null, null, // native stream format name and class
null, null, // extra stream formats
true, // supports standard image metadata
PSDMetadata.NATIVE_METADATA_FORMAT_NAME, PSDMetadata.NATIVE_METADATA_FORMAT_CLASS_NAME,
null, null // extra image metadata formats
);
}
public boolean canDecodeInput(final Object pSource) throws IOException {
if (!(pSource instanceof ImageInputStream)) {
return false;
}
ImageInputStream stream = (ImageInputStream) pSource;
stream.mark();
try {
return stream.readInt() == PSD.SIGNATURE_8BPS;
// TODO: Test more of the header, see PSDImageReader#readHeader
}
finally {
stream.reset();
}
}
public ImageReader createReaderInstance(final Object pExtension) throws IOException {
return new PSDImageReader(this);
}
public String getDescription(final Locale pLocale) {
return "Adobe Photoshop Document (PSD) image reader";
}
}
|
imageio/imageio-psd/src/main/java/com/twelvemonkeys/imageio/plugins/psd/PSDImageReaderSpi.java
|
/*
* Copyright (c) 2008, Harald Kuhr
* 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 "TwelveMonkeys" 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 com.twelvemonkeys.imageio.plugins.psd;
import com.twelvemonkeys.imageio.spi.ProviderInfo;
import com.twelvemonkeys.imageio.util.IIOUtil;
import javax.imageio.ImageReader;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;
import java.io.IOException;
import java.util.Locale;
/**
* PSDImageReaderSpi
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: PSDImageReaderSpi.java,v 1.0 Apr 29, 2008 4:49:03 PM haraldk Exp$
*/
public class PSDImageReaderSpi extends ImageReaderSpi {
/**
* Creates a {@code PSDImageReaderSpi}.
*/
public PSDImageReaderSpi() {
this(IIOUtil.getProviderInfo(PSDImageReaderSpi.class));
}
private PSDImageReaderSpi(final ProviderInfo providerInfo) {
super(
providerInfo.getVendorName(),
providerInfo.getVersion(),
new String[]{"psd", "PSD"},
new String[]{"psd"},
new String[]{
"image/vnd.adobe.photoshop", // This one seems official
"application/vnd.adobe.photoshop",
"image/x-psd", "application/x-photoshop", "image/x-photoshop"
},
"com.twelvemkonkeys.imageio.plugins.psd.PSDImageReader",
new Class[] {ImageInputStream.class},
// new String[]{"com.twelvemkonkeys.imageio.plugins.psd.PSDImageWriterSpi"},
null,
true, // supports standard stream metadata
null, null, // native stream format name and class
null, null, // extra stream formats
true, // supports standard image metadata
PSDMetadata.NATIVE_METADATA_FORMAT_NAME, PSDMetadata.NATIVE_METADATA_FORMAT_CLASS_NAME,
null, null // extra image metadata formats
);
}
public boolean canDecodeInput(final Object pSource) throws IOException {
if (!(pSource instanceof ImageInputStream)) {
return false;
}
ImageInputStream stream = (ImageInputStream) pSource;
stream.mark();
try {
return stream.readInt() == PSD.SIGNATURE_8BPS;
// TODO: Test more of the header, see PSDImageReader#readHeader
}
finally {
stream.reset();
}
}
public ImageReader createReaderInstance(final Object pExtension) throws IOException {
return new PSDImageReader(this);
}
public String getDescription(final Locale pLocale) {
return "Adobe Photoshop Document (PSD) image reader";
}
}
|
TMI-57: Clean up after merge.
|
imageio/imageio-psd/src/main/java/com/twelvemonkeys/imageio/plugins/psd/PSDImageReaderSpi.java
|
TMI-57: Clean up after merge.
|
|
Java
|
bsd-3-clause
|
cd1c5afc7919edc7597b80e99d0fde25b77167ce
| 0
|
NCIP/cadsr-sentinel,NCIP/cadsr-sentinel,NCIP/cadsr-sentinel
|
// Copyright (c) 2004 ScenPro, Inc.
// $Header: /share/content/gforge/sentinel/sentinel/src/gov/nih/nci/cadsr/sentinel/database/DBAlertOracle.java,v 1.13 2008-01-14 15:35:27 hebell Exp $
// $Name: not supported by cvs2svn $
package gov.nih.nci.cadsr.sentinel.database;
import gov.nih.nci.cadsr.sentinel.audits.AuditReport;
import gov.nih.nci.cadsr.sentinel.tool.ACData;
import gov.nih.nci.cadsr.sentinel.tool.AlertRec;
import gov.nih.nci.cadsr.sentinel.tool.AutoProcessData;
import gov.nih.nci.cadsr.sentinel.tool.ConceptItem;
import gov.nih.nci.cadsr.sentinel.tool.Constants;
import gov.nih.nci.cadsr.sentinel.ui.AlertPlugIn;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import oracle.jdbc.pool.OracleConnectionPoolDataSource;
import oracle.jdbc.pool.OracleDataSource;
import org.apache.log4j.Logger;
/**
* Encapsulate all database access to the tables relating to the Sentinel Alert
* definitions.
* <p>
* For all access, the SQL statements are NOT placed in the properties file as
* internationalization and translation should not affect them. We also want to
* ease the maintenance by keeping the SQL with the database execute function
* calls. If some SQL becomes duplicated, a single method with appropriate
* parameters should be created to avoid difficulties with changing the SQL
* statements over time as the table definitions evolve.
* <p>
* Start with setupPool() which only needs to be executed once. Then open() and
* close() every time a new DBAlert object is created.
* <p>
* Also, just a reminder, all JDBC set...() and get...() methods use 1 (one)
* based indexing unlike the Java language which uses 0 (zero) based.
*
* @author Larry Hebel
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(HttpServletRequest, String, String) open() with HTTP request
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(ServletContext, String, String) open() with Servlet Context
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(String, String, String) open()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public class DBAlertOracle implements DBAlert
{
// Class data
private String _namesList[];
private String _namesVals[];
private String _namesExempt;
private String _contextList[];
private String _contextVals[];
private String _schemeList[];
private String _schemeVals[];
private String _schemeContext[];
private String _protoList[];
private String _protoVals[];
private String _protoContext[];
private String _schemeItemList[];
private String _schemeItemVals[];
private String _schemeItemSchemes[];
private Connection _conn;
private String _user;
private ServletContext _sc;
private boolean _needCommit;
private String _groupsList[];
private String _groupsVals[];
private String _formsList[];
private String _formsVals[];
private String _formsContext[];
private String _workflowList[];
private String _workflowVals[];
private String _cworkflowList[];
private String _cworkflowVals[];
private String _regStatusList[];
private String _regStatusVals[];
private String _regCStatusList[];
private String _regCStatusVals[];
private String _nameID[];
private String _nameText[];
private int _errorCode;
private String _errorMsg;
private String _actypesList[];
private String _actypesVals[];
/**
* The internal code for Version.
*/
public static final String _VERSION = "VERSION";
/**
* The internal code for Workflow Status.
*/
public static final String _WFS = "ASL_NAME";
/**
* The internal code for Registration Status.
*/
public static final String _RS = "REGISTRATION_STATUS";
/**
* The internal code for User ID.
*/
public static final String _UNAME = "UA_NAME";
/**
* Version Any Change value.
*/
public static final char _VERANYCHG = 'C';
/**
* Version Major (whole) number change value.
*/
public static final char _VERMAJCHG = 'M';
/**
* Version Ignore change value.
*/
public static final char _VERIGNCHG = 'I';
/**
* Version Specific Value change value.
*/
public static final char _VERSPECHG = 'S';
/**
* Maximum length of the Alert Definition Name.
*/
public static final int _MAXNAMELEN = 30;
/**
* Maximum length of the Inaction Reason description.
*/
public static final int _MAXREASONLEN = 2000;
/**
* Maximum length of the Report Introduction description.
*/
public static final int _MAXINTROLEN = 2000;
/**
* Maximum length of a freeform email address.
*/
public static final int _MAXEMAILLEN = 255;
/**
* The Date comparison Created Only value.
*/
public static final int _DATECONLY = 0;
/**
* The Date comparison Modified Only value.
*/
public static final int _DATEMONLY = 1;
/**
* The Date comparison Created and Modified value.
*/
public static final int _DATECM = 2;
private static boolean _poolWarning = true;
private static final String _DATECHARS[][] = {
{"<", ">", ">=", "<"},
{">=", "<", "<", ">"},
{">=", "<", ">=", "<"}
};
private static final String _CONTEXT = "CONTEXT";
private static final String _FORM = "FORM";
private static final String _PROTOCOL = "PROTOCOL";
private static final String _SCHEME = "CS";
private static final String _SCHEMEITEM = "CSI";
private static final String _CREATOR = "CREATOR";
private static final String _MODIFIER = "MODIFIER";
private static final String _REGISTER = "REG_STATUS";
private static final String _STATUS = "AC_STATUS";
private static final String _ACTYPE = "ACTYPE";
private static final String _DATEFILTER = "DATEFILTER";
private static final char _CRITERIA = 'C';
private static final char _MONITORS = 'M';
private static final String _orderbyACH =
"order by id asc, "
// + "cid asc, "
// + "zz.date_modified asc, "
+ "ach.change_datetimestamp asc, "
+ "ach.changed_table asc, "
+ "ach.changed_table_idseq asc, "
+ "ach.changed_column asc";
private static final DBAlertOracleMap1[] _DBMAP1 =
{
new DBAlertOracleMap1("ASL_NAME", "Workflow Status"),
new DBAlertOracleMap1("BEGIN_DATE", "Begin Date"),
new DBAlertOracleMap1("CDE_ID", "Public ID"),
new DBAlertOracleMap1("CDR_IDSEQ", "Complex DE association"),
new DBAlertOracleMap1("CD_IDSEQ", "Conceptual Domain association"),
new DBAlertOracleMap1("CHANGE_NOTE", "Change Note"),
new DBAlertOracleMap1("CONDR_IDSEQ", "Concept Class association"),
new DBAlertOracleMap1("CON_IDSEQ", "Concept Class association"),
new DBAlertOracleMap1("CREATED_BY", "Created By"),
new DBAlertOracleMap1("CSTL_NAME", "Category"),
new DBAlertOracleMap1("CS_ID", "Public ID"),
new DBAlertOracleMap1("C_DEC_IDSEQ", "Child DEC association"),
new DBAlertOracleMap1("C_DE_IDSEQ", "Child DE association"),
new DBAlertOracleMap1("C_VD_IDSEQ", "Child VD association"),
new DBAlertOracleMap1("DATE_CREATED", "Created Date"),
new DBAlertOracleMap1("DATE_MODIFIED", "Modified Date"),
new DBAlertOracleMap1("DECIMAL_PLACE", "Number of Decimal Places"),
new DBAlertOracleMap1("DEC_ID", "Public ID"),
new DBAlertOracleMap1("DEC_IDSEQ", "Data Element Concept association"),
new DBAlertOracleMap1("DEC_REC_IDSEQ", "DEC_REC_IDSEQ"),
new DBAlertOracleMap1("DEFINITION_SOURCE", "Definition Source"),
new DBAlertOracleMap1("DELETED_IND", "Deleted Indicator"),
new DBAlertOracleMap1("DESCRIPTION", "Description"),
new DBAlertOracleMap1("DESIG_IDSEQ", "Designation association"),
new DBAlertOracleMap1("DE_IDSEQ", "Data Element association"),
new DBAlertOracleMap1("DE_REC_IDSEQ", "DE_REC_IDSEQ"),
new DBAlertOracleMap1("DISPLAY_ORDER", "Display Order"),
new DBAlertOracleMap1("DTL_NAME", "Data Type"),
new DBAlertOracleMap1("END_DATE", "End Date"),
new DBAlertOracleMap1("FORML_NAME", "Data Format"),
new DBAlertOracleMap1("HIGH_VALUE_NUM", "Maximum Value"),
new DBAlertOracleMap1("LABEL_TYPE_FLAG", "Label Type"),
new DBAlertOracleMap1("LATEST_VERSION_IND", "Latest Version Indicator"),
new DBAlertOracleMap1("LONG_NAME", "Long Name"),
new DBAlertOracleMap1("LOW_VALUE_NUM", "Minimum Value"),
new DBAlertOracleMap1("MAX_LENGTH_NUM", "Maximum Length"),
new DBAlertOracleMap1("METHODS", "Methods"),
new DBAlertOracleMap1("MIN_LENGTH_NUM", "Minimum Length"),
new DBAlertOracleMap1("MODIFIED_BY", "Modified By"),
new DBAlertOracleMap1("OBJ_CLASS_QUALIFIER", "Object Class Qualifier"),
new DBAlertOracleMap1("OCL_NAME", "Object Class Name"),
new DBAlertOracleMap1("OC_ID", "Public ID"),
new DBAlertOracleMap1("OC_IDSEQ", "Object Class association"),
new DBAlertOracleMap1("ORIGIN", "Origin"),
new DBAlertOracleMap1("PREFERRED_DEFINITION", "Preferred Definition"),
new DBAlertOracleMap1("PREFERRED_NAME", "Preferred Name"),
new DBAlertOracleMap1("PROPERTY_QUALIFIER", "Property Qualifier"),
new DBAlertOracleMap1("PROPL_NAME", "Property Name"),
new DBAlertOracleMap1("PROP_ID", "Public ID"),
new DBAlertOracleMap1("PROP_IDSEQ", "Property"),
new DBAlertOracleMap1("PV_IDSEQ", "Permissible Value"),
new DBAlertOracleMap1("P_DEC_IDSEQ", "Parent DEC association"),
new DBAlertOracleMap1("P_DE_IDSEQ", "Parent DE association"),
new DBAlertOracleMap1("P_VD_IDSEQ", "Parent VD association"),
new DBAlertOracleMap1("QUALIFIER_NAME", "Qualifier"),
new DBAlertOracleMap1("QUESTION", "Question"),
new DBAlertOracleMap1("RD_IDSEQ", "Reference Document association"),
new DBAlertOracleMap1("REP_IDSEQ", "Representation association"),
new DBAlertOracleMap1("RL_NAME", "Relationship Name"),
new DBAlertOracleMap1("RULE", "Rule"),
new DBAlertOracleMap1("SHORT_MEANING", "Meaning"),
new DBAlertOracleMap1("UOML_NAME", "Unit Of Measure"),
new DBAlertOracleMap1("URL", "URL"),
new DBAlertOracleMap1("VALUE", "Value"),
new DBAlertOracleMap1("VD_ID", "Public ID"),
new DBAlertOracleMap1("VD_IDSEQ", "Value Domain association"),
new DBAlertOracleMap1("VD_REC_IDSEQ", "VD_REC_IDSEQ"),
new DBAlertOracleMap1("VD_TYPE_FLAG", "Enumerated/Non-enumerated"),
new DBAlertOracleMap1("VERSION", "Version")
};
private static final DBAlertOracleMap1[] _DBMAP1OTHER =
{
new DBAlertOracleMap1("CONTE_IDSEQ", "Owned By Context"),
new DBAlertOracleMap1("LAE_NAME", "Language"),
new DBAlertOracleMap1("NAME", "Name")
};
private static final DBAlertOracleMap1[] _DBMAP1DESIG =
{
new DBAlertOracleMap1("CONTE_IDSEQ", "Designation Context"),
new DBAlertOracleMap1("DETL_NAME", "Designation Type"),
new DBAlertOracleMap1("LAE_NAME", "Designation Language")
};
private static final DBAlertOracleMap1[] _DBMAP1CSI =
{
new DBAlertOracleMap1("CS_CSI_IDSEQ", "Classification Scheme Item association")
};
private static final DBAlertOracleMap1[] _DBMAP1RD =
{
new DBAlertOracleMap1("DCTL_NAME","Document Type"),
new DBAlertOracleMap1("DISPLAY_ORDER", "Document Display Order"),
new DBAlertOracleMap1("DOC_TEXT", "Document Text"),
new DBAlertOracleMap1("RDTL_NAME", "Document Text Type"),
new DBAlertOracleMap1("URL", "Document URL")
};
private static final DBAlertOracleMap1[] _DBMAP1COMPLEX =
{
new DBAlertOracleMap1("CONCAT_CHAR", "Concatenation Character"),
new DBAlertOracleMap1("CRTL_NAME", "Complex Type")
};
private static final DBAlertOracleMap2[] _DBMAP2 =
{
new DBAlertOracleMap2("CD_IDSEQ", "sbr.conceptual_domains_view", "cd_idseq", "", "long_name || ' (' || cd_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("CONDR_IDSEQ", "sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext cv", "ccv.condr_idseq", " and cv.con_idseq = ccv.con_idseq order by ccv.display_order desc",
"cv.long_name || ' (' || cv.con_id || 'v' || cv.version || ') (' || cv.origin || ':' || cv.preferred_name || ')' as label"),
new DBAlertOracleMap2("CONTE_IDSEQ", "sbr.contexts_view", "conte_idseq", "", "name || ' (v' || version || ')' as label"),
new DBAlertOracleMap2("CON_IDSEQ", "sbrext.concepts_view_ext", "con_idseq", "", "long_name || ' (' || con_id || 'v' || version || ') (' || origin || ':' || preferred_name || ')' as label"),
new DBAlertOracleMap2("CREATED_BY", "sbr.user_accounts_view", "ua_name", "", "name as label"),
new DBAlertOracleMap2("CS_CSI_IDSEQ", "sbr.cs_csi_view cci, sbr.class_scheme_items_view csi", "cci.cs_csi_idseq", " and csi.csi_idseq = cci.csi_idseq","csi.csi_name as label"),
new DBAlertOracleMap2("DEC_IDSEQ", "sbr.data_element_concepts_view", "dec_idseq", "", "long_name || ' (' || dec_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("DE_IDSEQ", "sbr.data_elements_view", "de_idseq", "", "long_name || ' (' || cde_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("MODIFIED_BY", "sbr.user_accounts_view", "ua_name", "", "name as label"),
new DBAlertOracleMap2("OC_IDSEQ", "sbrext.object_classes_view_ext", "oc_idseq", "", "long_name || ' (' || oc_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("PROP_IDSEQ", "sbrext.properties_view_ext", "prop_idseq", "", "long_name || ' (' || prop_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("PV_IDSEQ", "sbr.permissible_values_view", "pv_idseq", "", "value || ' (' || short_meaning || ')' as label"),
new DBAlertOracleMap2("RD_IDSEQ", "sbr.reference_documents_view", "rd_idseq", "", "name || ' (' || nvl(doc_text, url) || ')' as label"),
new DBAlertOracleMap2("REP_IDSEQ", "sbrext.representations_view_ext", "rep_idseq", "", "long_name || ' (' || rep_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("UA_NAME", "sbr.user_accounts_view", "ua_name", "", "name as label"),
new DBAlertOracleMap2("VD_IDSEQ", "sbr.value_domains_view", "vd_idseq", "", "long_name || ' (' || vd_id || 'v' || version || ')' as label")
};
private static final DBAlertOracleMap3[] _DBMAP3 =
{
new DBAlertOracleMap3("cd", "Conceptual Domain", "sbr.conceptual_domains_view", null),
new DBAlertOracleMap3("con", "Concept", "sbrext.concepts_view_ext", null),
new DBAlertOracleMap3("conte", "Context", "sbr.contexts_view", null),
new DBAlertOracleMap3("cs", "Classification Scheme", "sbr.classification_schemes_view", "CLASSIFICATION_SCHEMES"),
new DBAlertOracleMap3("csi", "Classification Scheme Item", "sbr.class_scheme_items_view", null),
new DBAlertOracleMap3("de", "Data Element", "sbr.data_elements_view", "DATA_ELEMENTS"),
new DBAlertOracleMap3("dec", "Data Element Concept", "sbr.data_element_concepts_view", "DATA_ELEMENT_CONCEPTS"),
new DBAlertOracleMap3("oc", "Object Class", "sbrext.object_classes_view_ext", "OBJECT_CLASSES_EXT"),
new DBAlertOracleMap3("prop", "Property", "sbrext.properties_view_ext", "PROPERTIES_EXT"),
new DBAlertOracleMap3("proto", "Protocol", "sbrext.protocols_view_ext", null),
new DBAlertOracleMap3("pv", "Permissible Value", "sbr.permissible_values_view", "PERMISSIBLE_VALUES"),
new DBAlertOracleMap3("qc", "Form/Template", "sbrext.quest_contents_view_ext", null),
new DBAlertOracleMap3("qcm", "Module", null, null),
new DBAlertOracleMap3("qcq", "Question", null, null),
new DBAlertOracleMap3("qcv", "Valid Value", null, null),
new DBAlertOracleMap3("vd", "Value Domain", "sbr.value_domains_view", "VALUE_DOMAINS"),
new DBAlertOracleMap3("vm", "Value Meaning", "sbr.value_meanings_view", null)
};
private static final Logger _logger = Logger.getLogger(DBAlert.class.getName());
/**
* Entry for development testing of the class
*
* @param args program arguments
*/
public static void main(String args[])
{
DBAlertOracle var = new DBAlertOracle();
var.concat(_DBMAP1, _DBMAP1DESIG,_DBMAP1RD, _DBMAP1CSI , _DBMAP1COMPLEX , _DBMAP1OTHER);
}
/**
* Constructor.
*/
public DBAlertOracle()
{
_errorCode = 0;
_nameID = new String[1];
_nameID[0] = "";
_nameText = new String[1];
_nameText[0] = "";
_conn = null;
_sc = null;
}
/**
* Required prior to using any other methods within this class. This method
* checks for the existence of the pool attached to the Servlet Context.
* Once the pool is successfully created subsequent invocations perform no
* action. The method is static and synchronized to allow for possible
* multiple invocations of the Sentinel Tool simultaneously. Although the
* data referenced is not static we don't want to take the chance that the
* ServletContext.getAttribute() is called, we loose the time slice and upon
* return from the VM one invocation thinks the pool is missing when another
* invocation has just successfully created it. This is only called from the
* Logon Action currently so the overhead inherit with synchronized
* functions is minimized.
* <p>
* To use this from non-browser servlet logic use the method which requires
* the driver as the first argument.
*
* @param session_
* The session object.
* @param dsurl_
* The URL entry for the desired database.
* @param username_
* The default database user logon id.
* @param password_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int setupPool(HttpSession session_,
String dsurl_, String username_, String password_)
{
return setupPoolX(session_, dsurl_, username_, password_);
}
static private synchronized int setupPoolX(HttpSession session_,
String dsurl_, String username_, String password_)
{
// Get the Servlet Context and see if a pool already exists.
ServletContext sc = session_.getServletContext();
if (sc.getAttribute(DBAlert._DATASOURCE) != null)
return 0;
OracleConnectionPoolDataSource ocpds = (OracleConnectionPoolDataSource) sc
.getAttribute(_DBPOOL);
if (ocpds != null)
return 0;
ocpds = setupPool(dsurl_, username_, password_);
if (ocpds != null)
{
// Remember the pool in the Servlet Context.
sc.setAttribute(_DBPOOL + ".ds", ocpds);
sc.setAttribute(_DBPOOL + ".user", username_);
sc.setAttribute(_DBPOOL + ".pswd", password_);
return 0;
}
return -1;
}
/**
* Required prior to using any other methods within this class. This method
* checks for the existence of the pool attached to the Servlet Context.
* Once the pool is successfully created subsequent invocations perform no
* action. The method is static and synchronized to allow for possible
* multiple invocations of the Sentinel Tool simultaneously. Although the
* data referenced is not static we don't want to take the chance that the
* ServletContext.getAttribute() is called, we loose the time slice and upon
* return from the VM one invocation thinks the pool is missing when another
* invocation has just successfully created it. This is only called from the
* Logon Action currently so the overhead inherit with synchronized
* functions is minimized.
* <p>
* To use this from non-browser servlet logic use the method which requires
* the driver as the first argument.
*
* @param request_
* The servlet request object.
* @param dsurl_
* The URL entry for the desired database.
* @param username_
* The default database user logon id.
* @param password_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int setupPool(HttpServletRequest request_,
String dsurl_, String username_, String password_)
{
// Pass it on...
return setupPool(request_.getSession(), dsurl_, username_,
password_);
}
/**
* Required prior to using any other methods within this class. This method
* checks for the existence of the pool attached to the Servlet Context.
* Once the pool is successfully created subsequent invocations perform no
* action. The method is static and synchronized to allow for possible
* multiple invocations of the Sentinel Tool simultaneously. Although the
* data referenced is not static we don't want to take the chance that the
* ServletContext.getAttribute() is called, we loose the time slice and upon
* return from the VM one invocation thinks the pool is missing when another
* invocation has just successfully created it. This is only called from the
* Logon Action currently so the overhead inherit with synchronized
* functions is minimized.
* <p>
* To use this from a browser servlet, use the method which requires an
* HttpServletRequest as the first argument to the method.
*
* @param dsurl_
* The URL entry for the desired database.
* @param username_
* The default database user logon id.
* @param password_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
*/
private static synchronized OracleConnectionPoolDataSource setupPool(
String dsurl_, String username_, String password_)
{
// First register the database driver.
OracleConnectionPoolDataSource ocpds = null;
int rc = 0;
String rcTxt = null;
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
}
catch (SQLException ex)
{
rc = ex.getErrorCode();
rcTxt = rc + ": " + ex.toString();
}
try
{
// Create an the connection pool data source and set the parameters.
ocpds = new OracleConnectionPoolDataSource();
if (dsurl_.indexOf(':') > 0)
{
String parts[] = dsurl_.split("[:]");
ocpds.setDriverType("thin");
ocpds.setServerName(parts[0]);
ocpds.setPortNumber(Integer.parseInt(parts[1]));
ocpds.setServiceName(parts[2]);
}
else
{
ocpds.setDriverType("oci8");
ocpds.setTNSEntryName(dsurl_);
}
ocpds.setUser(username_);
ocpds.setPassword(password_);
}
catch (SQLException ex)
{
// We have a problem.
rc = ex.getErrorCode();
rcTxt = rc + ": " + ex.toString();
ocpds = null;
}
if (rc != 0)
{
// Send a user friendly message to the Logon window and the more
// detailed
// message to the console.
_logger.error(rcTxt);
}
return ocpds;
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param sc_
* The servlet context which holds the data source pool reference
* created by the DBAlert.setupPool() method.
* @param user_
* The database user logon id.
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(ServletContext sc_, String user_)
{
return open(sc_, user_, null);
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param sc_
* The servlet context which holds the data source pool reference
* created by the DBAlert.setupPool() method.
* @param user_
* The database user logon id.
* @param pswd_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(ServletContext sc_, String user_, String pswd_)
{
// If we already have a connection, don't bother.
if (_conn != null)
return 0;
try
{
// Get a connection from the pool, if anything unexpected happens
// the catch is
// run.
_sc = sc_;
_user = user_;
AlertPlugIn var = (AlertPlugIn)_sc.getAttribute(DBAlert._DATASOURCE);
if (var == null)
{
OracleConnectionPoolDataSource ocpds =
(OracleConnectionPoolDataSource) _sc.getAttribute(_DBPOOL);
_conn = ocpds.getConnection(user_, pswd_);
if (_poolWarning)
{
_poolWarning = false;
_logger.warn("============ Could not find JBoss datasource using internal connection pool.");
}
}
else if (pswd_ == null)
_conn = var.getDataSource().getConnection();
else
_conn = var.getAuthenticate().getConnection(user_, pswd_);
// We handle the commit once in the close.
_conn.setAutoCommit(false);
_needCommit = false;
return 0;
}
catch (SQLException ex)
{
// There seems to be a problem.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
_sc = null;
_conn = null;
return _errorCode;
}
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param ds_
* The datasource for database connections.
* @param user_
* The database user logon id.
* @return 0 if successful, otherwise the error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(DataSource ds_, String user_)
{
try
{
_user = user_;
_conn = ds_.getConnection();
_conn.setAutoCommit(false);
_needCommit = false;
}
catch (SQLException ex)
{
_logger.error(ex.toString(), ex);
return ex.getErrorCode();
}
return 0;
}
/**
* Open a single simple connection to the database. No pooling is necessary.
*
* @param dsurl_
* The Oracle TNSNAME entry describing the database location.
* @param user_
* The ORACLE user id.
* @param pswd_
* The password which must match 'user_'.
* @return The database error code.
*/
public int open(String dsurl_, String user_, String pswd_)
{
// If we already have a connection, don't bother.
if (_conn != null)
return 0;
try
{
OracleDataSource ods = new OracleDataSource();
if (dsurl_.indexOf(':') > 0)
{
String parts[] = dsurl_.split("[:]");
ods.setDriverType("thin");
ods.setServerName(parts[0]);
ods.setPortNumber(Integer.parseInt(parts[1]));
ods.setServiceName(parts[2]);
}
else
{
ods.setDriverType("oci8");
ods.setTNSEntryName(dsurl_);
}
_user = user_;
_conn = ods.getConnection(user_, pswd_);
_conn.setAutoCommit(false);
_needCommit = false;
return 0;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param request_
* The servlet request object.
* @param user_
* The database user logon id.
* @param pswd_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(HttpServletRequest request_, String user_, String pswd_)
{
return open(request_.getSession().getServletContext(), user_, pswd_);
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param request_
* The servlet request object.
* @param user_
* The database user logon id.
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(HttpServletRequest request_, String user_)
{
return open(request_.getSession().getServletContext(), user_, null);
}
/**
* Required upon a successful return from open. When all database access is
* completed for this user request. To optimize the database access, all
* methods which perform actions that require a commmit only set a flag. It
* is in the close() method the flag is interrogated and the commit actually
* occurs.
*
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(HttpServletRequest, String, String) open() with HTTP request
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(ServletContext, String, String) open() with Servlet Context
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(String, String, String) open()
*/
public int close()
{
/*
try
{
throw new Exception("Trace");
}
catch (Exception ex)
{
_logger.debug("Trace", ex);
}
*/
// We only need to do something if a connection is obtained.
if (_conn != null)
{
try
{
// Don't forget to commit if needed.
if (_needCommit)
_conn.commit();
}
catch (SQLException ex)
{
// There seems to be a problem.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": "
+ ex.toString();
_logger.error(_errorMsg);
}
try
{
// Close the connection and release all pointers.
_conn.close();
_conn = null;
_sc = null;
}
catch (SQLException ex)
{
// There seems to be a problem.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": "
+ ex.toString();
_logger.error(_errorMsg);
_conn = null;
_sc = null;
return _errorCode;
}
}
return 0;
}
/**
* Get the database connection opened for this object.
*
* @return java.sql.Connection opened by this object.
*/
public Connection getConnection()
{
return _conn;
}
/**
* Retrieves the abbreviated list of all alerts. The AlertRec objects
* returned are not fully populated with all the details of each alert. Only
* basic information such as the database id, name, creator and a few other
* basic properties are guaranteed.
*
* @param user_
* The user id with which to qualify the results. This must be as it
* appears in the "created_by" column of the Alert tables. If null is
* used, a list of all Alerts is retrieved.
* @return The array of Alerts retrieved.
*/
public AlertRec[] selectAlerts(String user_)
{
// Define the SQL Select
String select = "select a.al_idseq, a.name, a.last_auto_run, a.auto_freq_unit, a.al_status, a.auto_freq_value, a.created_by, u.name "
+ "from sbrext.sn_alert_view_ext a, sbr.user_accounts_view u "
+ "where ";
// If a user id was given, qualify the list with it.
if (user_ != null)
select = select + "a.created_by = ? and ";
select = select + "u.ua_name = a.created_by";
PreparedStatement pstmt = null;
ResultSet rs = null;
Vector<AlertRec> results = new Vector<AlertRec>();
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select);
if (user_ != null)
pstmt.setString(1, user_);
// Get the list.
rs = pstmt.executeQuery();
while (rs.next())
{
// For the list of alerts we only need basic information.
AlertRec rec = new AlertRec();
rec.setAlertRecNum(rs.getString(1));
rec.setName(rs.getString(2));
rec.setAdate(rs.getTimestamp(3));
rec.setFreq(rs.getString(4));
rec.setActive(rs.getString(5));
rec.setDay(rs.getInt(6));
rec.setCreator(rs.getString(7));
rec.setCreatorName(rs.getString(8));
// After much consideration, I thought it best to dynamically
// generate the textual summary of the alert. This
// could be done at the time the alert is saved and stored in
// the database, however, the descriptions could become
// very large and we have to worry about some things changing
// and not being updated. For the first implementation
// it seems best to generate it. In the future this may change.
selectQuery(rec);
select = rec.getSummary(false);
rec.clearQuery();
rec.setSummary(select);
results.add(rec);
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select + "\n\n"
+ ex.toString();
_logger.error(_errorMsg);
return null;
}
// Now that we have the full results we can create a single simple array
// to contain
// them. This greatly simplifies access throughout the code.
AlertRec database[] = null;
int count = results.size();
if (count > 0)
{
database = new AlertRec[count];
for (int ndx = 0; ndx < count; ++ndx)
database[ndx] = (AlertRec) results.get(ndx);
}
// Return the results.
return database;
}
/**
* Pull the list of recipients for a specific alert.
*
* @param rec_
* The alert for the desired recipients. The alertRecNum must be set
* prior to this method.
* @return 0 if successful, otherwise the database error code.
*/
private int selectRecipients(AlertRec rec_)
{
// A Report has a list of one or more recipients.
String select = "select ua_name, email, conte_idseq "
+ "from sbrext.sn_recipient_view_ext " + "where rep_idseq = ?";
try
{
// Get ready...
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, rec_.getReportRecNum());
// Go!
Vector<String> rlist = new Vector<String>();
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
String temp = rs.getString(1);
// We use the ua_name as is.
if (temp != null)
rlist.add(temp);
else
{
temp = rs.getString(2);
// The email address must have an "@" in it somewhere so no
// change.
if (temp != null)
rlist.add(temp);
else
{
temp = rs.getString(3);
// To distinguish groups from a ua_name we use a "/" as
// a prefix.
if (temp != null)
rlist.add("/" + temp);
}
}
}
rs.close();
pstmt.close();
// Move the data to an array and drop the Vector.
if (rlist.size() > 0)
{
String temp[] = new String[rlist.size()];
for (int ndx = 0; ndx < temp.length; ++ndx)
{
temp[ndx] = (String) rlist.get(ndx);
}
rec_.setRecipients(temp);
}
else
{
rec_.setRecipients(null);
}
return 0;
}
catch (SQLException ex)
{
// We've got trouble.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select + "\n\n"
+ ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Pull the report information for a specific alert definition.
*
* @param rec_
* The alert for the desired report. The alertRecNum must be set
* prior to this method.
* @return 0 if successful, otherwise the database error code.
*/
private int selectReport(AlertRec rec_)
{
// Each Alert has one Report definition.
String select = "select rep_idseq, include_property_ind, style, send, acknowledge_ind, comments, assoc_lvl_num "
+ "from sbrext.sn_report_view_ext " + "where al_idseq = ?";
try
{
// Get ready...
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, rec_.getAlertRecNum());
// Strictly speaking if a record is not found it is a violation of a
// business rule, however,
// the code is written to default all values to avoid these types of
// quirks.
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
rec_.setReportRecNum(rs.getString(1));
rec_.setIncPropSect(rs.getString(2));
rec_.setReportAck(rs.getString(3));
rec_.setReportEmpty(rs.getString(4));
rec_.setReportAck(rs.getString(5));
rec_.setIntro(rs.getString(6), true);
rec_.setIAssocLvl(rs.getInt(7));
}
rs.close();
pstmt.close();
return selectRecipients(rec_);
}
catch (SQLException ex)
{
// We've got trouble.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select + "\n\n"
+ ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Pull the properties for a specific alert definition.
*
* @param rec_
* The alert for the desired property values. The alertRecNum must be
* set prior to this method.
* @return 0 if successful, otherwise the database error code.
*/
private int selectProperties(AlertRec rec_)
{
// Define the SQL Select. The column names are expanded to ensure the
// order of retrieval. If asterisk (*) is used
// and the database definition changes it could rearrange the columns
// and the subsequent ResultSet.get...() method
// calls will fail.
String select = "select a.name, a.last_auto_run, a.last_manual_run, a.auto_freq_unit, a.al_status, a.begin_date, a.end_date, "
+ "a.status_reason, a.date_created, nvl(a.date_modified, a.date_created) as mdate, nvl(a.modified_by, a.created_by) as mby, "
+ "a.created_by, a.auto_freq_value, u1.name, nvl(u2.name, u1.name) as name2 "
+ "from sbrext.sn_alert_view_ext a, sbr.user_accounts_view u1, sbr.user_accounts_view u2 "
+ "where a.al_idseq = ? and u1.ua_name = a.created_by and u2.ua_name(+) = a.modified_by";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
// Get ready...
pstmt = _conn.prepareStatement(select);
pstmt.setString(1, rec_.getAlertRecNum());
// Go!
rs = pstmt.executeQuery();
if (rs.next())
{
// As the where clause uses a specific ID we should only
// retrieve one result. And there's the
// one (1) based indexing again.
rec_.setName(rs.getString(1));
rec_.setAdate(rs.getTimestamp(2));
rec_.setRdate(rs.getTimestamp(3));
rec_.setFreq(rs.getString(4));
rec_.setActive(rs.getString(5));
rec_.setStart(rs.getTimestamp(6));
rec_.setEnd(rs.getTimestamp(7));
rec_.setInactiveReason(rs.getString(8));
rec_.setCdate(rs.getTimestamp(9));
rec_.setMdate(rs.getTimestamp(10));
//rec_.setModifier(rs.getString(11));
rec_.setCreator(rs.getString(12));
rec_.setDay(rs.getInt(13));
rec_.setCreatorName(rs.getString(14));
//rec_.setModifierName(rs.getString(15));
}
else
{
// This shouldn't happen but just in case...
rec_.setAlertRecNum(null);
}
rs.close();
pstmt.close();
return 0;
}
catch (SQLException ex)
{
// We've got trouble.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select + "\n\n"
+ ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Retrieve a full single Alert definition. All data elements of the
* AlertRec will be populated to reflect the database content.
*
* @param id_
* The database id (al_idseq) of the Alert definitions.
* @return A complete definition record if successful or null if an error
* occurs.
*/
public AlertRec selectAlert(String id_)
{
AlertRec rec = new AlertRec();
rec.setAlertRecNum(id_);
if (selectProperties(rec) != 0)
{
rec = null;
}
else if (selectReport(rec) != 0)
{
rec = null;
}
else if (selectQuery(rec) != 0)
{
rec = null;
}
// Give 'em what we've got.
return rec;
}
/**
* Update the database with the Alert properties stored in a memory record.
*
* @param rec_
* The Alert definition to be stored.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On an error with rollback().
*/
private int updateProperties(AlertRec rec_) throws SQLException
{
// Define the update statement. Some columns are not updated as they are
// controlled
// by triggers, specifically date_created, date_modified, creator and
// modifier.
String update = "update sbrext.sn_alert_view_ext set " + "name = ?, "
+ "auto_freq_unit = ?, " + "al_status = ?, " + "begin_date = ?, "
+ "end_date = ?, " + "status_reason = ?, " + "auto_freq_value = ?, "
+ "modified_by = ? "
+ "where al_idseq = ?";
cleanRec(rec_);
PreparedStatement pstmt = null;
try
{
// Set all the SQL arguments.
pstmt = _conn.prepareStatement(update);
pstmt.setString(1, rec_.getName());
pstmt.setString(2, rec_.getFreqString());
pstmt.setString(3, rec_.getActiveString());
pstmt.setTimestamp(4, rec_.getStart());
pstmt.setTimestamp(5, rec_.getEnd());
pstmt.setString(6, rec_.getInactiveReason(false));
pstmt.setInt(7, rec_.getDay());
pstmt.setString(8, _user);
pstmt.setString(9, rec_.getAlertRecNum());
// Send it to the database. And remember to flag a commit for later.
pstmt.executeUpdate();
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// It's bad...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + update
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Update the Report information for an Alert within the database.
*
* @param rec_
* The Alert definition to be written to the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int updateReport(AlertRec rec_) throws SQLException
{
// Update the related Report definition.
String update = "update sbrext.sn_report_view_ext set "
+ "comments = ?, include_property_ind = ?, style = ?, send = ?, acknowledge_ind = ?, assoc_lvl_num = ?, "
+ "modified_by = ? "
+ "where rep_idseq = ?";
try
{
// Set all the SQL arguments.
PreparedStatement pstmt = _conn.prepareStatement(update);
pstmt.setString(1, rec_.getIntro(false));
pstmt.setString(2, rec_.getIncPropSectString());
pstmt.setString(3, rec_.getReportStyleString());
pstmt.setString(4, rec_.getReportEmptyString());
pstmt.setString(5, rec_.getReportAckString());
pstmt.setInt(6, rec_.getIAssocLvl());
pstmt.setString(7, _user);
pstmt.setString(8, rec_.getReportRecNum());
pstmt.executeUpdate();
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// It's bad...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + update
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Perform an update on the complete record. No attempt is made to isolate
* the specific changes so many times values will not actually be changed.
*
* @param rec_
* The record containing the updated information. All data elements
* must be populated and correct.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int updateAlert(AlertRec rec_)
{
// Ensure data is clean.
rec_.setDependancies();
// Update database.
try
{
int xxx = updateProperties(rec_);
if (xxx != 0)
return xxx;
xxx = updateReport(rec_);
if (xxx != 0)
return xxx;
xxx = updateRecipients(rec_);
if (xxx != 0)
return xxx;
return updateQuery(rec_);
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Delete the Alert Definitions specified by the caller. The values must be
* existing al_idseq values within the Alert table.
*
* @param list_
* The al_idseq values which identify the definitions to delete.
* Other dependant tables in the database will automatically be
* cleaned up via cascades and triggers.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int deleteAlerts(Vector list_)
{
// Be sure we have something to do.
int count = list_.size();
if (count == 0)
return 0;
// Create an array.
String list[] = new String[count];
for (count = 0; count < list_.size(); ++count)
{
list[count] = (String) list_.get(count);
}
return deleteAlerts(list);
}
/**
* Delete the Alert Definitions specified by the caller. The values must be
* existing al_idseq values within the Alert table.
*
* @param id_
* The al_idseq value which identifies the definition to delete.
* Other dependant tables in the database will automatically be
* cleaned up via cascades and triggers.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int deleteAlert(String id_)
{
// Be sure we have something to do.
if (id_ == null || id_.length() == 0)
return 0;
String list[] = new String[1];
list[0] = id_;
return deleteAlerts(list);
}
/**
* Delete the Alert Definitions specified by the caller. The values must be
* existing al_idseq values within the Alert table.
*
* @param list_
* The al_idseq values which identify the definitions to delete.
* Other dependant tables in the database will automatically be
* cleaned up via cascades and triggers.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int deleteAlerts(String list_[])
{
// Be sure we have something to do.
if (list_ == null || list_.length == 0)
return 0;
// Build the delete SQL statement.
String delete = "delete " + "from sbrext.sn_alert_view_ext "
+ "where al_idseq in (?";
for (int ndx = 1; ndx < list_.length; ++ndx)
{
delete = delete + ",?";
}
delete = delete + ")";
// Delete all the specified definitions. We rely on cascades or triggers
// to clean up
// all related tables.
PreparedStatement pstmt = null;
try
{
// Set all the SQL arguments.
pstmt = _conn.prepareStatement(delete);
for (int ndx = 0; ndx < list_.length; ++ndx)
{
pstmt.setString(ndx + 1, list_[ndx]);
}
// Send it to the database. And remember to flag a commit for later.
pstmt.executeUpdate();
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// It's bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + delete
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Add the Report display attributes to the sn_rep_contents_view_ext table.
* One (1) row per attribute.
*
* @param rec_
* The Alert definition to store in the database.
* @return 0 if successful, otherwise the Oracle error code.
* @throws java.sql.SQLException
*/
private int insertDisplay(AlertRec rec_) throws SQLException
{
return 0;
}
/**
* Update the recipients list for the Alert report.
*
* @param rec_
* The Alert definition to be saved to the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int updateRecipients(AlertRec rec_) throws SQLException
{
// We do not try to keep up with individual changes to the list. We
// simply
// wipe out the existing list and replace it with the new one.
String delete = "delete " + "from sn_recipient_view_ext "
+ "where rep_idseq = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(delete);
pstmt.setString(1, rec_.getReportRecNum());
pstmt.executeUpdate();
pstmt.close();
return insertRecipients(rec_);
}
catch (SQLException ex)
{
// Ooops...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + delete
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Add the Report recipients to the sn_report_view_ext table. One (1) row
* per recipient.
*
* @param rec_
* The Alert definition to store in the database.
* @return 0 if successful, otherwise the Oracle error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int insertRecipients(AlertRec rec_) throws SQLException
{
// Add the Recipient record(s).
String insert = "";
try
{
for (int ndx = 0; ndx < rec_.getRecipients().length; ++ndx)
{
// As we only populate 1 of possible 3 columns, the Insert
// statement
// will be dynamically configured.
insert = "insert into sbrext.sn_recipient_view_ext ";
String temp = rec_.getRecipients(ndx);
if (temp.charAt(0) == '/')
{
// It must be a Context name.
insert = insert + "(rep_idseq, conte_idseq, created_by)";
temp = temp.substring(1);
}
else if (temp.indexOf('@') > -1)
{
// It must be an email address.
insert = insert + "(rep_idseq, email, created_by)";
if (temp.length() > DBAlert._MAXEMAILLEN)
{
temp = temp.substring(0, DBAlert._MAXEMAILLEN);
rec_.setRecipients(ndx, temp);
}
}
else if (temp.startsWith("http://") || temp.startsWith("https://"))
{
// It is an process URL remove the slash at the end of URL if it exists
if (temp.endsWith("/"))
{
temp = temp.substring(0, temp.lastIndexOf("/"));
}
insert = insert + "(rep_idseq, email, created_by)";
if (temp.length() > DBAlert._MAXEMAILLEN)
{
temp = temp.substring(0, DBAlert._MAXEMAILLEN);
rec_.setRecipients(ndx, temp);
}
}
else
{
// It's a user name.
insert = insert + "(rep_idseq, ua_name, created_by)";
}
insert = insert + " values (?, ?, ?)";
// Update
PreparedStatement pstmt = _conn.prepareStatement(insert);
pstmt.setString(1, rec_.getReportRecNum());
pstmt.setString(2, temp);
pstmt.setString(3, _user);
pstmt.executeUpdate();
pstmt.close();
}
// Remember to commit. It appears that we may flagging a commit when
// the recipients list
// is empty, however, the recipients list is never to be empty and
// the other calling methods
// depend on this to set the flag.
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// Ooops...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + insert
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* A utility function that will modify the "in" clause on a SQL select to
* contain the correct number of argument replacements to match the value
* array provided.
*
* @param select_
* The SQL select that must contain a single "?" replacement within
* an "in" clause as this is the placeholder for expansion to the
* appropriate number of "?" arguments to match the length of the
* values array. Of course if the array only has a single value the
* "in" can be an "=" (equals) operator.
* @param values_
* The array of values to use as bind arguments in the select.
* @return The comma separated string containing the concatenated results
* from the select query.
*/
private String selectText(String select_, String values_[])
{
return selectText(select_, values_, 0);
}
/**
* A utility function that will modify the "in" clause on a SQL select to
* contain the correct number of argument replacements to match the value
* array provided.
*
* @param select_
* The SQL select that must contain a single "?" replacement within
* an "in" clause as this is the placeholder for expansion to the
* appropriate number of "?" arguments to match the length of the
* values array. Of course if the array only has a single value the
* "in" can be an "=" (equals) operator.
* @param values_
* The array of values to use as bind arguments in the select.
* @param flag_
* The separator to use in the concatenated string.
* @return The comma separated string containing the concatenated results
* from the select query.
*/
private String selectText(String select_, String values_[], int flag_)
{
// There must be a single "?" in the select to start the method.
int pos = select_.indexOf('?');
if (pos < 0)
return "";
// As one "?" is already in the select we only add more if the array
// length is greater than 1.
String tSelect = select_.substring(0, pos + 1);
for (int ndx = 1; ndx < values_.length; ++ndx)
tSelect = tSelect + ",?";
tSelect = tSelect + select_.substring(pos + 1);
try
{
// Now bind each value in the array to the expanded "?" list.
PreparedStatement pstmt = _conn.prepareStatement(tSelect);
for (int ndx = 0; ndx < values_.length; ++ndx)
{
pstmt.setString(ndx + 1, values_[ndx]);
}
ResultSet rs = pstmt.executeQuery();
// Concatenate the results into a single comma separated string.
tSelect = "";
String sep = (flag_ == 0) ? ", " : "\" OR \"";
while (rs.next())
{
tSelect = tSelect + sep + rs.getString(1).replaceAll("[\\r\\n]", " ");
}
rs.close();
pstmt.close();
// We always start the string with a comma so be sure to remove it
// before returning.
if (tSelect.length() > 0)
{
tSelect = tSelect.substring(sep.length());
if (flag_ == 1)
tSelect = "\"" + tSelect + "\"";
}
else
tSelect = "\"(unknown)\"";
}
catch (SQLException ex)
{
tSelect = ex.toString();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + tSelect;
_logger.error(_errorMsg);
}
return tSelect;
}
/**
* Build the summary text from the content of the alert definition.
*
* @param rec_
* The alert definition.
* @return The Alert Definition summary.
*/
public String buildSummary(AlertRec rec_)
{
String select;
// Build the Summary text. You may wonder why we access the database
// multiple times when it
// is possible to collapse all of this into a single query. The
// additional complexity of the
// SQL and resulting logic made it unmanageable. If this proves to be a
// performance problem
// we can revisit it again in the future. Remember as more features are
// added for the criteria
// and monitors the complexity lever will increase.
String criteria = "";
int specific = 0;
int marker = 1;
if (rec_.getContexts() != null)
{
if (rec_.isCONTall())
criteria = criteria + "Context may be anything ";
else
{
select = "select name || ' (v' || version || ')' as label from sbr.contexts_view "
+ "where conte_idseq in (?) order by upper(name) ASC";
criteria = criteria + "Context must be "
+ selectText(select, rec_.getContexts(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getProtocols() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isPROTOall())
criteria = criteria + "Protocols may be anything ";
else
{
select = "select long_name || ' (' || proto_id || 'v' || version || ')' as label "
+ "from sbrext.protocols_view_ext "
+ "where proto_idseq in (?) order by upper(long_name) ASC";
criteria = criteria + "Protocols must be "
+ selectText(select, rec_.getProtocols(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getForms() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isFORMSall())
criteria = criteria + "Forms / Templates may be anything ";
else
{
select = "select long_name || ' (' || qc_id || 'v' || version || ')' as label "
+ "from sbrext.quest_contents_view_ext "
+ "where qc_idseq in (?) order by upper(long_name) ASC";
criteria = criteria + "Forms / Templates must be "
+ selectText(select, rec_.getForms(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getSchemes() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isCSall())
criteria = criteria + "Classification Schemes may be anything ";
else
{
select = "select long_name || ' (' || cs_id || 'v' || version || ')' as label "
+ "from sbr.classification_schemes_view "
+ "where cs_idseq in (?) order by upper(long_name) ASC";
criteria = criteria + "Classification Schemes must be "
+ selectText(select, rec_.getSchemes(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getSchemeItems() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isCSIall())
criteria = criteria
+ "Classification Scheme Items may be anything ";
else
{
select = "select csi_name "
+ "from sbr.class_scheme_items_view "
+ "where csi_idseq in (?) order by upper(csi_name) ASC";
criteria = criteria + "Classification Scheme Items must be "
+ selectText(select, rec_.getSchemeItems(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getACTypes() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isACTYPEall())
criteria = criteria + "Administered Component Types may be anything ";
else
{
criteria = criteria + "Administered Component Types must be ";
String list = "";
for (int ndx = 0; ndx < rec_.getACTypes().length; ++ndx)
{
list = list + " OR \"" + DBAlertUtil.binarySearchS(_DBMAP3, rec_.getACTypes(ndx)) + "\"";
}
criteria = criteria + list.substring(4);
specific += marker;
}
}
marker *= 2;
if (rec_.getCWorkflow() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isCWFSall())
criteria = criteria + "Workflow Status may be anything ";
else
{
select = "select asl_name from sbr.ac_status_lov_view "
+ "where asl_name in (?) order by upper(asl_name) ASC";
criteria = criteria + "Workflow Status must be "
+ selectText(select, rec_.getCWorkflow(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getCRegStatus() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isCRSall())
criteria = criteria + "Registration Status may be anything ";
else
{
select = "select registration_status "
+ "from sbr.reg_status_lov_view "
+ "where registration_status in (?) "
+ "order by upper(registration_status) ASC";
String txt = selectText(select, rec_.getCRegStatus(), 1);
criteria = criteria + "Registration Status must be ";
if (rec_.isCRSnone())
{
criteria = criteria + "\"(none)\"";
if (txt.length() > 0)
criteria = criteria + " OR ";
}
criteria = criteria + txt;
specific += marker;
}
}
marker *= 2;
if (rec_.getCreators() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.getCreators(0).charAt(0) == '(')
criteria = criteria + "Created By may be anyone ";
else
{
select = "select name from sbr.user_accounts_view "
+ "where ua_name in (?) order by upper(name) ASC";
criteria = criteria + "Created By must be "
+ selectText(select, rec_.getCreators(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getModifiers() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.getModifiers(0).charAt(0) == '(')
criteria = criteria + "Modified By may be anyone ";
else
{
select = "select name from sbr.user_accounts_view "
+ "where ua_name in (?) order by upper(name) ASC";
criteria = criteria + "Modified By must be "
+ selectText(select, rec_.getModifiers(), 1);
specific += marker;
}
}
marker *= 2;
if (criteria.length() > 0)
criteria = criteria + " AND\n";
switch (rec_.getDateFilter())
{
case _DATECONLY:
criteria = criteria + "Reporting Dates are compared to Date Created only ";
specific += marker;
break;
case _DATEMONLY:
criteria = criteria + "Reporting Dates are compared to Date Modified only ";
specific += marker;
break;
case _DATECM:
default:
criteria = criteria + "Reporting Dates are compared to Date Created and Date Modified ";
break;
}
if (specific > 0)
criteria = "Criteria:\n" + criteria + "\n";
else
criteria = "Criteria:\nAll records within the caDSR\n";
String monitors = "";
specific = 0;
marker = 1;
if (rec_.getAWorkflow() != null)
{
if (rec_.getAWorkflow(0).charAt(0) != '(')
{
select = "select asl_name from sbr.ac_status_lov_view "
+ "where asl_name in (?) order by upper(asl_name) ASC";
monitors = monitors + "Workflow Status changes to "
+ selectText(select, rec_.getAWorkflow(), 1);
}
else if (rec_.getAWorkflow(0).equals("(Ignore)"))
monitors = monitors + ""; // "Workflow Status changes are
// ignored ";
else
{
monitors = monitors + "Workflow Status changes to anything ";
specific += marker;
}
}
marker *= 2;
if (rec_.getARegis() != null)
{
if (rec_.getARegis(0).charAt(0) != '(')
{
select = "select registration_status "
+ "from sbr.reg_status_lov_view "
+ "where registration_status in (?) "
+ "order by upper(registration_status) ASC";
if (monitors.length() > 0)
monitors = monitors + " OR\n";
monitors = monitors + "Registration Status changes to "
+ selectText(select, rec_.getARegis(), 1);
}
else if (rec_.getARegis(0).equals("(Ignore)"))
monitors = monitors + ""; // "Registration Status changes are
// ignored ";
else
{
if (monitors.length() > 0)
monitors = monitors + " OR\n";
monitors = monitors
+ "Registration Status changes to anything ";
specific += marker;
}
}
marker *= 2;
if (rec_.getAVersion() != DBAlert._VERIGNCHG)
{
if (rec_.getAVersion() == DBAlert._VERANYCHG)
specific += marker;
if (monitors.length() > 0)
monitors = monitors + " OR\n";
switch (rec_.getAVersion())
{
case DBAlert._VERANYCHG:
monitors = monitors + "Version changes to anything\n";
break;
case DBAlert._VERMAJCHG:
monitors = monitors
+ "Version Major Revision changes to anything\n";
break;
case DBAlert._VERIGNCHG:
monitors = monitors + "";
break; // "Version changes are ignored\n"; break;
case DBAlert._VERSPECHG:
monitors = monitors + "Version changes to \""
+ rec_.getActVerNum() + "\"\n";
break;
}
}
if (monitors.length() == 0)
monitors = "\nMonitors:\nIgnore all changes. Reports are always empty.\n";
else if (specific == 7)
monitors = "\nMonitors:\nAll Change Activities\n";
else
monitors = "\nMonitors:\n" + monitors;
return criteria + monitors;
}
/**
* Set the owner of the Alert Definition.
*
* @param rec_ The Alert Definition with the new creator already set.
*/
public void setOwner(AlertRec rec_)
{
// Ensure data is clean.
rec_.setDependancies();
// Update creator in database.
String update = "update sbrext.sn_alert_view_ext set created_by = ?, modified_by = ? where al_idseq = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(update);
pstmt.setString(1, rec_.getCreator());
pstmt.setString(2, _user);
pstmt.setString(3, rec_.getAlertRecNum());
pstmt.executeUpdate();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
int errorCode = ex.getErrorCode();
String errorMsg = errorCode + ": " + update
+ "\n\n" + ex.toString();
_logger.error(errorMsg);
}
}
/**
* Get the type of the AC id from the database.
* @param id_ The AC id.
* @return The [0] is the type and the [1] is the name of the AC.
*/
public String [] getACtype(String id_)
{
String out[] = new String[2];
String select =
"select 'conte', name from sbr.contexts_view where conte_idseq = ? "
+ "union "
+ "select 'cs', long_name from sbr.classification_schemes_view where cs_idseq = ? "
+ "union "
+ "select 'csi', csi_name from sbr.class_scheme_items_view where csi_idseq = ? "
+ "union "
+ "select 'qc', long_name from sbrext.quest_contents_view_ext where qc_idseq = ? and qtl_name in ('TEMPLATE','CRF') "
+ "union "
+ "select 'proto', long_name from sbrext.protocols_view_ext where proto_idseq = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, id_);
pstmt.setString(2, id_);
pstmt.setString(3, id_);
pstmt.setString(4, id_);
pstmt.setString(5, id_);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
out[0] = rs.getString(1);
out[1] = rs.getString(2);
}
else
{
out[0] = null;
out[1] = null;
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
int errorCode = ex.getErrorCode();
String errorMsg = errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(errorMsg);
}
return out;
}
/**
* Look for an Alert owned by the user with a Query which
* references the id specified.
*
* @param id_ The Context, Form, CS, etc ID_SEQ value.
* @param user_ The user who should own the Alert if it exists.
* @return true if the user already watches the id, otherwise false.
*/
public String checkQuery(String id_, String user_)
{
String select = "select al.name "
+ "from sbrext.sn_alert_view_ext al, sbrext.sn_query_view_ext qur "
+ "where al.created_by = ? and qur.al_idseq = al.al_idseq and qur.value = ?";
String rc = null;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, user_);
pstmt.setString(2, id_);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
rc = rs.getString(1);
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
int errorCode = ex.getErrorCode();
String errorMsg = errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(errorMsg);
}
return rc;
}
/**
* Check the specified user id for Sentinel Tool Administration privileges.
*
* @param user_ The user id as used during Sentinel Tool Login.
* @return true if the user has administration privileges, otherwise false.
*/
public boolean checkToolAdministrator(String user_)
{
String select = "select 1 from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' "
+ "and property like 'ADMIN.%' "
+ "and value like '%0%' "
+ "and ua_name = '" + user_ + "' "
+ "and rownum < 2";
int rows = testDB(select);
return rows == 1;
}
/**
* Retrieve the CDE Browser URL if available.
*
* @return The URL string.
*/
public String selectBrowserURL()
{
String select = "select value from sbrext.tool_options_view_ext "
+ "where tool_name = 'CDEBrowser' and property = 'URL'";
String rc = null;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
rc = rs.getString(1);
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
}
return rc;
}
/**
* Retrieve the Report Threshold
*
* @return The number of rows to allow in a report.
*/
public int selectReportThreshold()
{
String select = "select value from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' and property = 'REPORT.THRESHOLD.LIMIT'";
int rc = 100;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
rc = rs.getInt(1);
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
}
return rc;
}
/**
* Read the Query clause from the database for the Alert definition
* specified.
*
* @param rec_
* The Alert record to contain the Query clause.
* @return 0 if successful, otherwise the database error code.
*/
private int selectQuery(AlertRec rec_)
{
String select = "select record_type, data_type, property, value "
+ "from sbrext.sn_query_view_ext " + "where al_idseq = ?"; // order
// by
// record_type
// ASC,
// data_type
// ASC,
// property
// ASC";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, rec_.getAlertRecNum());
ResultSet rs = pstmt.executeQuery();
Vector<String> context = new Vector<String>();
Vector<String> actype = new Vector<String>();
Vector<String> scheme = new Vector<String>();
Vector<String> schemeitem = new Vector<String>();
Vector<String> form = new Vector<String>();
Vector<String> protocol = new Vector<String>();
Vector<String> creator = new Vector<String>();
Vector<String> modifier = new Vector<String>();
Vector<String> workflow = new Vector<String>();
Vector<String> regis = new Vector<String>();
Vector<String> cregis = new Vector<String>();
Vector<String> cwork = new Vector<String>();
// After reading the query set we have to partition it into the
// appropriate individual
// variables. As the data stored in the query is internal
// representations there is
// no point to attempting to order it. Also for any one Alert there
// isn't enough rows
// to warrant the extra coding or logical overhead.
while (rs.next())
{
char rtype = rs.getString(1).charAt(0);
String dtype = rs.getString(2);
String value = rs.getString(4);
if (rtype == _CRITERIA)
{
if (dtype.equals(_CONTEXT))
context.add(value);
else if (dtype.equals(_FORM))
form.add(value);
else if (dtype.equals(_PROTOCOL))
protocol.add(value);
else if (dtype.equals(_SCHEME))
scheme.add(value);
else if (dtype.equals(_SCHEMEITEM))
schemeitem.add(value);
else if (dtype.equals(_CREATOR))
creator.add(value);
else if (dtype.equals(_MODIFIER))
modifier.add(value);
else if (dtype.equals(_ACTYPE))
actype.add(value);
else if (dtype.equals(_REGISTER))
cregis.add(value);
else if (dtype.equals(_STATUS))
cwork.add(value);
else if (dtype.equals(_DATEFILTER))
{
rec_.setDateFilter(value);
}
}
else if (rtype == _MONITORS)
{
if (dtype.equals(_STATUS))
workflow.add(value);
else if (dtype.equals(_REGISTER))
regis.add(value);
else if (dtype.equals(_VERSION))
{
rec_.setAVersion(rs.getString(3));
rec_.setActVerNum(value);
}
}
}
rs.close();
pstmt.close();
// Move the data into appropriate arrays within the Alert record to
// simplify use
// downstream.
String list[] = null;
if (context.size() == 0)
{
rec_.setContexts(null);
}
else
{
list = new String[context.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) context.get(ndx);
rec_.setContexts(list);
}
if (actype.size() == 0)
{
rec_.setACTypes(null);
}
else
{
list = new String[actype.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) actype.get(ndx);
rec_.setACTypes(list);
}
if (protocol.size() == 0)
{
rec_.setProtocols(null);
}
else
{
list = new String[protocol.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) protocol.get(ndx);
rec_.setProtocols(list);
}
if (form.size() == 0)
{
rec_.setForms(null);
}
else
{
list = new String[form.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) form.get(ndx);
rec_.setForms(list);
}
if (scheme.size() == 0)
{
rec_.setSchemes(null);
}
else
{
list = new String[scheme.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) scheme.get(ndx);
rec_.setSchemes(list);
}
if (schemeitem.size() == 0)
{
rec_.setSchemeItems(null);
}
else
{
list = new String[schemeitem.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) schemeitem.get(ndx);
rec_.setSchemeItems(list);
}
if (cregis.size() == 0)
{
rec_.setCRegStatus(null);
}
else
{
list = new String[cregis.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) cregis.get(ndx);
rec_.setCRegStatus(list);
}
if (cwork.size() == 0)
{
rec_.setCWorkflow(null);
}
else
{
list = new String[cwork.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) cwork.get(ndx);
rec_.setCWorkflow(list);
}
if (creator.size() == 0)
{
rec_.setCreators(null);
}
else
{
list = new String[creator.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) creator.get(ndx);
rec_.setCreators(list);
}
if (modifier.size() == 0)
{
rec_.setModifiers(null);
}
else
{
list = new String[modifier.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) modifier.get(ndx);
rec_.setModifiers(list);
}
if (workflow.size() == 0)
{
rec_.setAWorkflow(null);
}
else
{
list = new String[workflow.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) workflow.get(ndx);
rec_.setAWorkflow(list);
}
if (regis.size() == 0)
{
rec_.setARegis(null);
}
else
{
list = new String[regis.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) regis.get(ndx);
rec_.setARegis(list);
}
// Create the summary string now the data is loaded.
rec_.setSummary(buildSummary(rec_));
return 0;
}
catch (SQLException ex)
{
// Ooops...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Update the Query details for the Alert.
*
* @param rec_
* The Alert definition to be updated.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int updateQuery(AlertRec rec_) throws SQLException
{
// First we delete the existing Query details as it's easier to wipe out
// the old and add
// the new than trying to track individual changes.
String delete = "delete " + "from sbrext.sn_query_view_ext "
+ "where al_idseq = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(delete);
pstmt.setString(1, rec_.getAlertRecNum());
pstmt.executeUpdate();
pstmt.close();
return insertQuery(rec_);
}
catch (SQLException ex)
{
// Ooops...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + delete
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Add the Query details to the Alert in the database.
*
* @param rec_
* The Alert definition to be added to the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int insertQuery(AlertRec rec_) throws SQLException
{
String insert = "insert into sbrext.sn_query_view_ext (al_idseq, record_type, data_type, property, value, created_by) "
+ "values (?, ?, ?, ?, ?, ?)";
int marker = 0;
try
{
PreparedStatement pstmt = _conn.prepareStatement(insert);
pstmt.setString(1, rec_.getAlertRecNum());
pstmt.setString(2, "C");
pstmt.setString(6, _user);
// We only want to record those items selected by the user that
// require special processing. For
// example, if (All) contexts were selected by the user we do not
// record (All) in the database
// because the downstream processing of the Alert only cares about
// looking for specific criteria
// and monitors. In other words, we don't want to waste time
// checking the context when (All) was
// selected because it will always logically test true.
++marker;
if (!rec_.isCONTall())
{
pstmt.setString(3, _CONTEXT);
pstmt.setString(4, "CONTE_IDSEQ");
for (int ndx = 0; ndx < rec_.getContexts().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getContexts(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isPROTOall())
{
pstmt.setString(3, _PROTOCOL);
pstmt.setString(4, "PROTO_IDSEQ");
for (int ndx = 0; ndx < rec_.getProtocols().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getProtocols(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isFORMSall())
{
pstmt.setString(3, _FORM);
pstmt.setString(4, "QC_IDSEQ");
for (int ndx = 0; ndx < rec_.getForms().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getForms(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isCSall())
{
pstmt.setString(3, _SCHEME);
pstmt.setString(4, "CS_IDSEQ");
for (int ndx = 0; ndx < rec_.getSchemes().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getSchemes(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isCSIall())
{
pstmt.setString(3, _SCHEMEITEM);
pstmt.setString(4, "CSI_IDSEQ");
for (int ndx = 0; ndx < rec_.getSchemeItems().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getSchemeItems(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getCreators(0).equals(Constants._STRALL) == false)
{
pstmt.setString(3, _CREATOR);
pstmt.setString(4, "UA_NAME");
for (int ndx = 0; ndx < rec_.getCreators().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getCreators(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getModifiers(0).equals(Constants._STRALL) == false)
{
pstmt.setString(3, _MODIFIER);
pstmt.setString(4, "UA_NAME");
for (int ndx = 0; ndx < rec_.getModifiers().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getModifiers(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isACTYPEall())
{
pstmt.setString(3, _ACTYPE);
pstmt.setString(4, "ABBREV");
for (int ndx = 0; ndx < rec_.getACTypes().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getACTypes(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getDateFilter() != DBAlert._DATECM)
{
pstmt.setString(3, _DATEFILTER);
pstmt.setString(4, "CODE");
pstmt.setString(5, Integer.toString(rec_.getDateFilter()));
pstmt.executeUpdate();
}
++marker;
if (!rec_.isCRSall())
{
pstmt.setString(3, _REGISTER);
pstmt.setString(4, "REGISTRATION_STATUS");
for (int ndx = 0; ndx < rec_.getCRegStatus().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getCRegStatus(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isCWFSall())
{
pstmt.setString(3, _STATUS);
pstmt.setString(4, "ASL_NAME");
for (int ndx = 0; ndx < rec_.getCWorkflow().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getCWorkflow(ndx));
pstmt.executeUpdate();
}
}
marker += 100;
pstmt.setString(2, "M");
++marker;
if (rec_.getAWorkflow(0).equals(Constants._STRANY) == false)
{
pstmt.setString(3, _STATUS);
pstmt.setString(4, "ASL_NAME");
for (int ndx = 0; ndx < rec_.getAWorkflow().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getAWorkflow(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getARegis(0).equals(Constants._STRANY) == false)
{
pstmt.setString(3, _REGISTER);
pstmt.setString(4, "REGISTRATION_STATUS");
for (int ndx = 0; ndx < rec_.getARegis().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getARegis(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getAVersion() != DBAlert._VERANYCHG)
{
pstmt.setString(3, _VERSION);
pstmt.setString(4, rec_.getAVersionString());
pstmt.setString(5, rec_.getActVerNum());
pstmt.executeUpdate();
}
// Remember to commit.
++marker;
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// Ooops...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = "(" + marker + "): " + _errorCode + ": "
+ insert + "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Clean the name of any illegal characters and truncate if needed.
*
* @param name_
* The name of the Alert.
* @return The corrected name.
*/
private String cleanName(String name_)
{
String name = null;
if (name_ != null)
{
name = name_.replaceAll("[\"]", "");
if (name.length() > DBAlert._MAXNAMELEN)
name = name.substring(0, DBAlert._MAXNAMELEN);
}
return name;
}
/**
* Clean the inactive reason and truncate if needed.
*
* @param reason_
* The reason message.
* @return The corrected message.
private String cleanReason(String reason_)
{
String reason = reason_;
if (reason != null && reason.length() > DBAlert._MAXREASONLEN)
{
reason = reason.substring(0, DBAlert._MAXREASONLEN);
}
return reason;
}
*/
/**
* Clean the Alert Report introduction and truncate if needed.
*
* @param intro_
* The introduction.
* @return The cleaned introduction.
*/
private String cleanIntro(String intro_)
{
String intro = intro_;
if (intro != null && intro.length() > DBAlert._MAXINTROLEN)
{
intro = intro.substring(0, DBAlert._MAXINTROLEN);
}
return intro;
}
/**
* Clean all the user enterable parts of an Alert and truncate to the
* database allowed length.
*
* @param rec_
* The Alert to be cleaned.
*/
private void cleanRec(AlertRec rec_)
{
String temp = cleanName(rec_.getName());
rec_.setName(temp);
temp = rec_.getInactiveReason(false);
rec_.setInactiveReason(temp);
temp = cleanIntro(rec_.getIntro(false));
rec_.setIntro(temp, false);
}
/**
* Insert the properties for the Alert definition and retrieve the new
* database generated ID for this Alert.
*
* @param rec_
* The Alert to be stored in the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int insertProperties(AlertRec rec_) throws SQLException
{
// Define the SQL insert. Remember date_created, date_modified, creator
// and modifier are controlled
// by triggers. Also (as of 10/21/2004) after the insert the
// date_modified is still set by the insert
// trigger.
String insert = "begin insert into sbrext.sn_alert_view_ext "
+ "(name, auto_freq_unit, al_status, begin_date, end_date, status_reason, auto_freq_value, created_by) "
+ "values (?, ?, ?, ?, ?, ?, ?, ?) return al_idseq into ?; end;";
CallableStatement pstmt = null;
cleanRec(rec_);
try
{
// Set all the SQL arguments.
pstmt = _conn.prepareCall(insert);
pstmt.setString(1, rec_.getName());
pstmt.setString(2, rec_.getFreqString());
pstmt.setString(3, rec_.getActiveString());
pstmt.setTimestamp(4, rec_.getStart());
pstmt.setTimestamp(5, rec_.getEnd());
pstmt.setString(6, rec_.getInactiveReason(false));
pstmt.setInt(7, rec_.getDay());
pstmt.setString(8, _user);
pstmt.registerOutParameter(9, Types.CHAR);
// Insert the new record and flag a commit for later.
pstmt.executeUpdate();
// We need the record id to populate the foreign keys for other
// tables.
rec_.setAlertRecNum(pstmt.getString(9));
pstmt.close();
return 0;
}
catch (SQLException ex)
{
// Ooops...
rec_.setAlertRecNum(null);
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + insert
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Insert the Report details for the Alert definition into the database and
* retrieve the new report id.
*
* @param rec_
* The Alert definition to be stored in the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int insertReport(AlertRec rec_) throws SQLException
{
// Add the Report record.
String insert = "begin insert into sbrext.sn_report_view_ext "
+ "(al_idseq, comments, include_property_ind, style, send, acknowledge_ind, assoc_lvl_num, created_by) "
+ "values (?, ?, ?, ?, ?, ?, ?, ?) return rep_idseq into ?; end;";
CallableStatement pstmt = null;
try
{
pstmt = _conn.prepareCall(insert);
pstmt.setString(1, rec_.getAlertRecNum());
pstmt.setString(2, rec_.getIntro(false));
pstmt.setString(3, rec_.getIncPropSectString());
pstmt.setString(4, rec_.getReportStyleString());
pstmt.setString(5, rec_.getReportEmptyString());
pstmt.setString(6, rec_.getReportAckString());
pstmt.setInt(7, rec_.getIAssocLvl());
pstmt.setString(8, _user);
pstmt.registerOutParameter(9, Types.CHAR);
pstmt.executeUpdate();
// We need the record id to populate the foreign keys for other
// tables.
rec_.setReportRecNum(pstmt.getString(9));
pstmt.close();
return 0;
}
catch (SQLException ex)
{
// Ooops...
rec_.setAlertRecNum(null);
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + insert
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Insert a DE, DEC or VD into the user reserved CSI to be monitored.
*
* @param idseq_ the database id of the AC to be monitored.
* @param user_ the user id for the reserved CSI
* @return the id of the CSI if successful, null if a problem.
*/
public String insertAC(String idseq_, String user_)
{
String user = user_.toUpperCase();
try
{
CallableStatement stmt;
stmt = _conn.prepareCall("begin SBREXT_CDE_CURATOR_PKG.ADD_TO_SENTINEL_CS(?,?,?); end;");
stmt.registerOutParameter(3, java.sql.Types.VARCHAR);
stmt.setString(2, user);
stmt.setString(1, idseq_);
stmt.execute();
String csi = stmt.getString(3);
stmt.close();
_needCommit = true;
return csi;
}
catch (SQLException ex)
{
// Ooops...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Perform an insert of a new record. The record number element of the class
* is not used AND it is not returned by this method. All other elements
* must be complete and correct.
*
* @param rec_
* The Alert definition to insert into the database table.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int insertAlert(AlertRec rec_)
{
// Ensure required data dependancies.
rec_.setDependancies();
// Update the database.
try
{
int xxx = insertProperties(rec_);
if (xxx == 0)
{
xxx = insertReport(rec_);
if (xxx == 0)
{
xxx = insertRecipients(rec_);
if (xxx == 0)
{
xxx = insertDisplay(rec_);
if (xxx == 0)
{
xxx = insertQuery(rec_);
if (xxx != 0)
rec_.setAlertRecNum(null);
}
else
rec_.setAlertRecNum(null);
}
else
rec_.setAlertRecNum(null);
}
else
rec_.setAlertRecNum(null);
}
else
rec_.setAlertRecNum(null);
return xxx;
}
catch (SQLException ex)
{
// Ooops...
rec_.setAlertRecNum(null);
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Retrieve a more user friendly version of the user id.
*
* @param id_
* The id as would be entered at logon.
* @return null if the user id was not found in the sbr.user_accounts table,
* otherwise the 'name' value of the matching row.
*/
public String selectUserName(String id_)
{
// Define the SQL select.
String select = "select uav.name "
+ "from sbr.user_accounts_view uav, sbrext.user_contexts_view ucv "
+ "where uav.ua_name = ? and ucv.ua_name = uav.ua_name and ucv.privilege = 'W'";
PreparedStatement pstmt = null;
String result;
ResultSet rs = null;
try
{
// Get ready...
pstmt = _conn.prepareStatement(select);
pstmt.setString(1, id_);
// Go!
rs = pstmt.executeQuery();
if (rs.next())
{
// Get the name, remember 1 indexing.
result = rs.getString(1);
}
else
{
// User must have some kind of write permissions.
result = null;
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// We've got trouble.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
result = null;
}
return result;
}
private class ResultsData1
{
/**
* The label
*/
public String _label;
/**
* The key
*/
public String _val;
}
/**
* Used for method return values.
*
*/
private class Results1
{
/**
* The return code from the database.
*/
public int _rc;
/**
* The data
*/
public ResultsData1[] _data;
}
/**
* Do a basic search with a single column result.
*
* @param select_ the SQL select
* @return the array of results
*/
private String[] getBasicData0(String select_)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select_);
// Get the list.
rs = pstmt.executeQuery();
Vector<String> data = new Vector<String>();
while (rs.next())
{
data.add(rs.getString(1));
}
String[] list = new String[data.size()];
for (int i = 0; i < list.length; ++i)
{
list[i] = data.get(i);
}
rs.close();
pstmt.close();
return (list.length > 0) ? list : null;
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Execute the specified SQL select query and return a label/value pair.
*
* @param select_
* The SQL select statement.
* @param flag_
* True to prefix "(All)" to the result set. False to return the
* result set unaltered.
* @return 0 if successful, otherwise the Oracle error code.
*/
private Results1 getBasicData1(String select_, boolean flag_)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
Vector<ResultsData1> results = new Vector<ResultsData1>();
Results1 data = new Results1();
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select_);
// Get the list.
rs = pstmt.executeQuery();
ResultsData1 rec;
while (rs.next())
{
// Remember about the 1 (one) based indexing.
rec = new ResultsData1();
rec._val = rs.getString(1);
rec._label = rs.getString(2);
results.add(rec);
}
rs.close();
pstmt.close();
// We know there will always be someone in the table but we should
// follow good
// programming.
if (results.size() == 0)
{
data._data = null;
}
else
{
// Move the list from a Vector to an array and add "(All)" to
// the beginning.
int count = results.size() + ((flag_) ? 1 : 0);
data._data = new ResultsData1[count];
int ndx;
if (flag_)
{
data._data[0] = new ResultsData1();
data._data[0]._label = Constants._STRALL;
data._data[0]._val = Constants._STRALL;
ndx = 1;
}
else
{
ndx = 0;
}
int cnt = 0;
for (; ndx < count; ++ndx)
{
rec = (ResultsData1) results.get(cnt++);
data._data[ndx] = new ResultsData1();
data._data[ndx]._label = rec._label.replaceAll("[\\s]", " ");
data._data[ndx]._val = rec._val;
}
}
data._rc = 0;
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
data._rc = _errorCode;
}
return data;
}
/**
* Retrieve all the context id's for which a specific user has write
* permission.
*
* @param user_
* The user id as stored in user_accounts_view.ua_name.
* @return The array of context id values.
*/
public String[] selectContexts(String user_)
{
String select = "select cv.conte_idseq "
+ "from sbr.contexts_view cv, sbrext.user_contexts_view ucv "
+ "where ucv.ua_name = ? and ucv.privilege = 'W' and ucv.name not in ('TEST','Test','TRAINING','Training') and cv.name = ucv.name";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, user_);
ResultSet rs = pstmt.executeQuery();
Vector<String> list = new Vector<String>();
while (rs.next())
{
list.add(rs.getString(1));
}
rs.close();
pstmt.close();
String temp[] = new String[list.size()];
for (int ndx = 0; ndx < temp.length; ++ndx)
{
temp[ndx] = (String) list.get(ndx);
}
return temp;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Retrieve the list of contexts for which a user has write permission.
*
* @param user_
* The user id as stored in user_accounts_view.ua_name.
* @return The concatenated comma separated string listing the context
* names.
*/
public String selectContextString(String user_)
{
String select = "select name "
+ "from sbrext.user_contexts_view "
+ "where ua_name in (?) and privilege = 'W' and name not in ('TEST','Test','TRAINING','Training') "
+ "order by upper(name) ASC";
String temp[] = new String[1];
temp[0] = user_;
return selectText(select, temp);
}
/**
* Retrieve the list of all users from the database with a suffix of the
* context names for which each has write permission. An asterisk following
* the name indicates the email address is missing.
* <p>
* The getUsers, getUserList and getUserVals are a set of methods that must
* be used in a specific way. The getUsers() method is called first to
* populate a set of temporary data elements which can be retrieved later.
* The getUserList() method accesses the user names of the returned data and
* subsequently sets the data element to null so the memory may be
* reclaimed. The getUserVals() method accesses the user ids of the returned
* data and subsequently sets the data element to null so the memory may be
* reclaimed. Consequently getUsers() must be called first, followed by
* either getUserList() or getUserVals(). Further getUserList() and
* getUserVals() should be called only once after each invocation of
* getUsers() as additional calls will always result in a null return. See
* the comments for these other methods for more details.
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUserList getUserList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUserVals getUserVals()
*/
public int getUsers()
{
// Get the user names and id's.
String select = "select ua_name, nvl2(electronic_mail_address, 'y', 'n') || alert_ind as eflag, name "
+ "from sbr.user_accounts_view order by upper(name) ASC";
Results2 rec2 = getBasicData2(select);
if (rec2._rc == 0)
{
_namesList = new String[rec2._data.length];
_namesVals = new String[rec2._data.length];
for (int i = 0; i < _namesList.length; ++i)
{
_namesList[i] = rec2._data[i]._label;
_namesVals[i] = rec2._data[i]._id1;
}
// Build the list of names that are exempt from Context Curator
// Group broadcasts.
_namesExempt = "";
// Get the context names for which each id has write permission.
select = "select distinct uav.name, ucv.name "
+ "from sbrext.user_contexts_view ucv, sbr.user_accounts_view uav "
+ "where ucv.privilege = 'W' and ucv.ua_name = uav.ua_name "
+ "order by upper(uav.name) ASC, upper(ucv.name) ASC";
Results1 rec = getBasicData1(select, false);
if (rec._rc == 0)
{
// Build the user list in the format <user name>[*] [(context
// list)] where <user name> is the
// in user presentable form followed by an optional asterisk to
// indicate the email address is missing
// from the user record followed by an optional list of context
// names for those contexts which the
// user has write permissions.
int vcnt = 0;
int ncnt = 1;
String prefix = " (";
String fixname = "";
while (ncnt < _namesList.length && vcnt < rec._data.length)
{
int test = _namesList[ncnt].compareToIgnoreCase(rec._data[vcnt]._val);
if (test < 0)
{
// Add the missing email flag to the suffix.
String suffix = "";
if (rec2._data[ncnt]._id2.charAt(0) == 'n')
suffix = "*";
// Add the Context list to the suffix.
if (prefix.charAt(0) == ',')
{
if (rec2._data[ncnt]._id2.charAt(1) == 'N')
_namesExempt = _namesExempt + ", "
+ _namesList[ncnt];
suffix = suffix + fixname + ")";
prefix = " (";
fixname = "";
}
// Add the suffix to the name.
_namesList[ncnt] = _namesList[ncnt] + suffix;
++ncnt;
}
else if (test > 0)
{
++vcnt;
}
else
{
fixname = fixname + prefix + rec._data[vcnt]._label;
prefix = ", ";
++vcnt;
}
}
}
// Fix the exempt list.
if (_namesExempt.length() == 0)
_namesExempt = null;
else
_namesExempt = _namesExempt.substring(2);
}
return rec2._rc;
}
/**
* Retrieve the valid user list. The method getUsers() must be called first.
* Once this method is used the internal copy is deleted to reclaim the
* memory space.
*
* @return An array of strings from the sbr.user_accounts.name column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
*/
public String[] getUserList()
{
String temp[] = _namesList;
_namesList = null;
return temp;
}
/**
* Retrieve the list of users exempt from Context Curator broadcasts. The
* method getUsers() must be called first. Once this method is used the
* internal copy is deleted to reclaim the memory space.
*
* @return A comma separated list of names.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
*/
public String getUserExempts()
{
String temp = _namesExempt;
_namesExempt = null;
return temp;
}
/**
* Retrieve the valid user list. The method getUsers() must be called first.
* Once this method is used the internal copy is deleted to reclaim the
* memory space.
*
* @return An array of strings from the sbr.user_accounts.ua_name column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
*/
public String[] getUserVals()
{
String temp[] = _namesVals;
_namesVals = null;
return temp;
}
/**
* Retrieve the Context names and id's from the database. This follows the
* pattern documented with getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getGroupList getGroupList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getGroupVals getGroupVals()
*/
public int getGroups()
{
String select = "select uav.ua_name, '/' || cv.conte_idseq as id, 0, "
+ "uav.name || nvl2(uav.electronic_mail_address, '', '*') as name, ucv.name "
+ "from sbrext.user_contexts_view ucv, sbr.user_accounts_view uav, sbr.contexts_view cv "
+ "where ucv.privilege = 'W' "
+ "and ucv.ua_name = uav.ua_name "
+ "and uav.alert_ind = 'Yes' "
+ "and ucv.name = cv.name "
+ "and cv.conte_idseq NOT IN ( "
+ "select tov.value "
+ "from sbrext.tool_options_view_ext tov "
+ "where tov.tool_name = 'SENTINEL' and "
+ "tov.property like 'BROADCAST.EXCLUDE.CONTEXT.%.CONTE_IDSEQ') "
+ "order by upper(ucv.name) ASC, upper(uav.name) ASC";
Results3 rec = getBasicData3(select, false);
if (rec._rc == 0)
{
// Count the number of groups.
String temp = rec._data[0]._id2;
int cnt = 1;
for (int ndx = 1; ndx < rec._data.length; ++ndx)
{
if (!temp.equals(rec._data[ndx]._id2))
{
temp = rec._data[ndx]._id2;
++cnt;
}
}
// Allocate space for the lists.
_groupsList = new String[cnt + rec._data.length];
_groupsVals = new String[_groupsList.length];
// Copy the data.
temp = "";
cnt = 0;
for (int ndx = 0; ndx < rec._data.length; ++ndx)
{
if (!temp.equals(rec._data[ndx]._id2))
{
temp = rec._data[ndx]._id2;
_groupsList[cnt] = rec._data[ndx]._label2;
_groupsVals[cnt] = rec._data[ndx]._id2;
++cnt;
}
_groupsList[cnt] = rec._data[ndx]._label1;
_groupsVals[cnt] = rec._data[ndx]._id1;
++cnt;
}
return 0;
}
return rec._rc;
}
/**
* Retrieve the valid context list. The method getGroups() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.contexts_view.name column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getGroups getGroups()
*/
public String[] getGroupList()
{
String temp[] = _groupsList;
_groupsList = null;
return temp;
}
/**
* Retrieve the valid context id list. The method getGroups() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.contexts_view.conte_idseq column
* and prefixed with a '/' character.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getGroups getGroups()
*/
public String[] getGroupVals()
{
String temp[] = _groupsVals;
_groupsVals = null;
return temp;
}
/**
* Get the list of unused concepts
*
* @param ids_ the list of unused concept ids
* @return the list of name, public id and version
*/
public String[] reportUnusedConcepts(String[] ids_)
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Version" + cs1
+ "Date Accessed" + cs1 + "Workflow Status" + cs1 + "EVS Source" + cs1
+ "Concept Code' as title, ' ' as lname from dual UNION ALL "
+ "SELECT con.long_name" + cs2 + "con.con_id" + cs2 + "con.version" + cs2
+ "nvl(date_modified, date_created)" + cs2 + "con.asl_name" + cs2 + "nvl(con.evs_source, ' ')" + cs2
+ "nvl(con.preferred_name, ' ') as title, upper(con.long_name) as lname "
+ "FROM sbrext.concepts_view_ext con "
+ "WHERE con.asl_name NOT LIKE 'RETIRED%' and con.con_idseq in (";
String temp = "";
for (int i = 0; i < ids_.length && i < 1000; ++i)
{
temp += ",'" + ids_[i] + "'";
}
select += temp.substring(1) + ") order by lname asc";
return getBasicData0(select);
}
/**
* Get the list of unused property records.
*
* @return The list of name, public id and version
*/
public String[] reportUnusedProperties()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Date Created" + cs1 + "Workflow Status" + cs1 + "Context" + cs1
+ "Display" + cs1 + "Concept" + cs1 + "Concept Code" + cs1 + "Origin" + cs1 + "Public ID" + cs1 + "Date Created" + cs1 + "Workflow Status' "
+ "as title, ' ' as lname, 0 as pid, ' ' as pidseq, 0 as dorder from dual UNION ALL "
+ "SELECT prop.long_name" + cs2 + "prop.prop_id || 'v' || prop.version" + cs2 + "prop.date_created" + cs2 + "prop.asl_name" + cs2 + "c.name " + cs2
+ "ccv.display_order" + cs2 + "con.long_name" + cs2 + "con.preferred_name" + cs2 + " con.origin" + cs2 + "con.con_id || 'v' || con.version" + cs2 + "con.date_created" + cs2 + "con.asl_name "
+ "as title, upper(prop.long_name) as lname, prop.prop_id as pid, prop.prop_idseq as pidseq, ccv.display_order as dorder "
+ "FROM sbrext.properties_view_ext prop, sbr.contexts_view c, "
+ "sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext con "
+ "WHERE prop.asl_name NOT LIKE 'RETIRED%' and prop.prop_idseq NOT IN "
+ "(SELECT decv.prop_idseq "
+ "FROM sbr.data_element_concepts_view decv "
+ "WHERE decv.prop_idseq = prop.prop_idseq) "
+ "AND c.conte_idseq = prop.conte_idseq "
+ "AND ccv.condr_idseq = prop.condr_idseq "
+ "AND con.con_idseq = ccv.con_idseq "
+ "order by lname asc, pid ASC, pidseq ASC, dorder DESC";
return getBasicData0(select);
}
/**
* Get the list of Administered Component which do not have a public id.
*
* @return the list of ac type, name, and idseq.
*/
public String[] reportMissingPublicID()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'AC Type" + cs1 + "Name" + cs1 + "ID" + cs1 + "Context' as title, ' ' as tname, ' ' as lname from dual UNION ALL "
+ "select ac.actl_name" + cs2 + "ac.long_name" + cs2 + "ac.ac_idseq" + cs2 + "c.name as title, upper(ac.actl_name) as tname, upper(ac.long_name) as lname "
+ "from sbr.admin_components_view ac, sbr.contexts_view c where ac.public_id is null "
+ "and ac.asl_name NOT LIKE 'RETIRED%' "
+ "and c.conte_idseq = ac.conte_idseq "
+ "order by tname asc";
return getBasicData0(select);
}
/**
* Get the list of unused data element concept records.
*
* @return The list of name, public id and version
*/
public String[] reportUnusedDEC()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Version" + cs1 + "Workflow Status" + cs1 + "Context' as title, ' ' as lname from dual UNION ALL "
+ "SELECT dec.long_name" + cs2 + "dec.dec_id" + cs2 + "dec.version" + cs2 + "dec.asl_name" + cs2 + "c.name as title, upper(dec.long_name) as lname "
+ "FROM sbr.data_element_concepts_view dec, sbr.contexts_view c "
+ "WHERE dec.asl_name NOT LIKE 'RETIRED%' and dec.dec_idseq NOT IN "
+ "(SELECT de.dec_idseq FROM sbr.data_elements_view de WHERE de.dec_idseq = dec.dec_idseq) "
+ "and c.conte_idseq = dec.conte_idseq "
+ "order by lname asc";
return getBasicData0(select);
}
/**
* Get the list of unused object class records.
*
* @return The list of name, public id and version
*/
public String[] reportUnusedObjectClasses()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Date Created" + cs1 + "Workflow Status" + cs1 + "Context" + cs1
+ "Display" + cs1 + "Concept" + cs1 + "Concept Code" + cs1 + "Origin" + cs1 + "Public ID" + cs1 + "Date Created" + cs1 + "Workflow Status' "
+ "as title, ' ' as lname, 0 as ocid, ' ' as ocidseq, 0 as dorder from dual UNION ALL "
+ "SELECT oc.long_name" + cs2 + "oc.oc_id || 'v' || oc.version" + cs2 + "oc.date_created" + cs2 + "oc.asl_name" + cs2 + "c.name" + cs2
+ "ccv.display_order" + cs2 + "con.long_name" + cs2 + "con.preferred_name" + cs2 + " con.origin" + cs2 + "con.con_id || 'v' || con.version" + cs2 + "con.date_created" + cs2 + "con.asl_name "
+ "as title, upper(oc.long_name) as lname, oc.oc_id as ocid, oc.oc_idseq as ocidseq, ccv.display_order as dorder "
+ "FROM sbrext.object_classes_view_ext oc, sbr.contexts_view c, "
+ "sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext con "
+ "WHERE oc.asl_name NOT LIKE 'RETIRED%' and oc.oc_idseq NOT IN "
+ "(SELECT decv.oc_idseq "
+ "FROM sbr.data_element_concepts_view decv "
+ "WHERE decv.OC_IDSEQ = oc.oc_idseq) "
+ "AND c.conte_idseq = oc.conte_idseq "
+ "AND ccv.condr_idseq = oc.condr_idseq "
+ "AND con.con_idseq = ccv.con_idseq "
+ "order by lname asc, ocid ASC, ocidseq ASC, dorder DESC";
return getBasicData0(select);
}
/**
* Get the list of Data Elements which do not have question text and are referenced by a Form.
*
* @return the list of name, public id and version.
*/
public String[] reportMissingQuestionText()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Version" + cs1 + "Workflow Status" + cs1 + "Context' as title, ' ' as lname from dual UNION ALL "
+ "select de.long_name" + cs2 + "de.cde_id" + cs2 + "de.version" + cs2 + "de.asl_name" + cs2 + "c.name as title, upper(de.long_name) as lname "
+ "from sbr.data_elements_view de, sbr.contexts_view c "
+ "where de.asl_name NOT LIKE 'RETIRED%' "
+ "and de.de_idseq in (select qc.de_idseq from sbrext.quest_contents_view_ext qc where qc.de_idseq = de.de_idseq) "
+ "and de.de_idseq not in (select rd.ac_idseq from sbr.reference_documents_view rd where rd.ac_idseq = de.de_idseq and dctl_name in ('Alternate Question Text','Preferred Question Text')) "
+ "and c.conte_idseq = de.conte_idseq "
+ "order by lname asc";
return getBasicData0(select);
}
/**
* Retrieve the Context names and id's from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getContextList getContextList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getContextVals getContextVals()
*/
public int getContexts()
{
// Get the context names and id's.
String select = "select conte_idseq, name from sbr.contexts_view "
+ "order by upper(name) ASC";
Results1 rec = getBasicData1(select, true);
if (rec._rc == 0)
{
_contextList = new String[rec._data.length];
_contextVals = new String[rec._data.length];
for (int i = 0; i < _contextList.length; ++i)
{
_contextList[i] = rec._data[i]._label;
_contextVals[i] = rec._data[i]._val;
}
return 0;
}
return rec._rc;
}
/**
* Retrieve the EVS properties in the tool options table
*
* @return the array of properties.
*/
public DBProperty[] selectEVSVocabs()
{
String select = "select opt.value, opt.property from sbrext.tool_options_view_ext opt where opt.tool_name = 'CURATION' and ("
+ "opt.property like 'EVS.VOCAB.%.PROPERTY.NAMESEARCH' or "
+ "opt.property like 'EVS.VOCAB.%.EVSNAME' or "
+ "opt.property like 'EVS.VOCAB.%.DISPLAY' or "
+ "opt.property like 'EVS.VOCAB.%.PROPERTY.DEFINITION' or "
+ "opt.property like 'EVS.VOCAB.%.ACCESSREQUIRED' "
+ ") order by opt.property";
Results1 rs = getBasicData1(select, false);
if (rs._rc == 0 && rs._data.length > 0)
{
DBProperty[] props = new DBProperty[rs._data.length];
for (int i = 0; i < rs._data.length; ++i)
{
props[i] = new DBProperty(rs._data[i]._label, rs._data[i]._val);;
}
return props;
}
return null;
}
/**
* Select all the caDSR Concepts
*
* @return the Concepts
*/
public Vector<ConceptItem> selectConcepts()
{
// Get the context names and id's.
String select = "SELECT con_idseq, con_id, version, evs_source, preferred_name, long_name, definition_source, preferred_definition "
+ "FROM sbrext.concepts_view_ext WHERE asl_name NOT LIKE 'RETIRED%' "
+ "ORDER BY upper(long_name) ASC";
Statement stmt = null;
Vector<ConceptItem> list = new Vector<ConceptItem>();
try
{
// Prepare the statement.
stmt = _conn.createStatement();
ResultSet rs = stmt.executeQuery(select);
// Get the list.
while (rs.next())
{
ConceptItem rec = new ConceptItem();
rec._idseq = rs.getString(1);
rec._publicID = rs.getString(2);
rec._version = rs.getString(3);
rec._evsSource = rs.getString(4);
rec._preferredName = rs.getString(5);
rec._longName = rs.getString(6);
rec._definitionSource = rs.getString(7);
rec._preferredDefinition = rs.getString(8);
list.add(rec);
}
rs.close();
stmt.close();
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
return list;
}
/**
* Retrieve the valid context list. The method getGroups() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.contexts_view.name column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getContexts getContexts()
*/
public String[] getContextList()
{
String temp[] = _contextList;
_contextList = null;
return temp;
}
/**
* Retrieve the valid context id list. The method getGroups() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.contexts_view.conte_idseq
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getContexts getContexts()
*/
public String[] getContextVals()
{
String temp[] = _contextVals;
_contextVals = null;
return temp;
}
/**
* Get the complete Workflow Status value list from the database. Follows
* the pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflowList getWorkflowList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflowVals getWorkflowVals()
*/
public int getWorkflow()
{
// For compatibility and consistency we treat this view as all others as
// if it has id and name
// columns. For some reason this view is designed to expose the real id
// to the end user.
String select = "select asl_name, 'C' "
+ "from sbr.ac_status_lov_view order by upper(asl_name) ASC";
Results1 rec = getBasicData1(select, false);
if (rec._rc == 0)
{
// Add the special values "(All)", "(Any Change)" and "(Ignore)"
_workflowList = new String[rec._data.length + 3];
_workflowVals = new String[rec._data.length + 3];
int ndx = 0;
_workflowList[ndx] = Constants._STRALL;
_workflowVals[ndx++] = Constants._STRALL;
_workflowList[ndx] = Constants._STRANY;
_workflowVals[ndx++] = Constants._STRANY;
_workflowList[ndx] = Constants._STRIGNORE;
_workflowVals[ndx++] = Constants._STRIGNORE;
for (int cnt = 0; cnt < rec._data.length; ++cnt)
{
_workflowList[ndx] = rec._data[cnt]._val;
_workflowVals[ndx++] = rec._data[cnt]._val;
}
// Add the special values "(All)", "(Any Change)" and "(Ignore)"
_cworkflowList = new String[rec._data.length + 1];
_cworkflowVals = new String[rec._data.length + 1];
ndx = 0;
_cworkflowList[ndx] = Constants._STRALL;
_cworkflowVals[ndx++] = Constants._STRALL;
for (int cnt = 0; cnt < rec._data.length; ++cnt)
{
_cworkflowList[ndx] = rec._data[cnt]._val;
_cworkflowVals[ndx++] = rec._data[cnt]._val;
}
}
return rec._rc;
}
/**
* Retrieve the valid workflow list. The method getWorkflow() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.ac_status_lov_view.asl_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflow getWorkflow()
*/
public String[] getWorkflowList()
{
String temp[] = _workflowList;
_workflowList = null;
return temp;
}
/**
* Retrieve the valid workflow values. The method getWorkflow() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the sbr.ac_status_lov_view.asl_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflow getWorkflow()
*/
public String[] getWorkflowVals()
{
String temp[] = _workflowVals;
_workflowVals = null;
return temp;
}
/**
* Retrieve the valid workflow list. The method getWorkflow() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.ac_status_lov_view.asl_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflow getWorkflow()
*/
public String[] getCWorkflowList()
{
String temp[] = _cworkflowList;
_cworkflowList = null;
return temp;
}
/**
* Retrieve the valid workflow values. The method getWorkflow() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the sbr.ac_status_lov_view.asl_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflow getWorkflow()
*/
public String[] getCWorkflowVals()
{
String temp[] = _cworkflowVals;
_cworkflowVals = null;
return temp;
}
/**
* Retrieve the valid registration statuses. Follows the pattern documented
* in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegStatusList getRegStatusList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegStatusVals getRegStatusVals()
*/
public int getRegistrations()
{
// For compatibility and consistency we treat this view as all others as
// if it has id and name
// columns. For some reason this view is designed to expose the real id
// to the end user.
String select = "select registration_status, 'C' "
+ "from sbr.reg_status_lov_view "
+ "order by upper(registration_status) ASC";
Results1 rec = getBasicData1(select, false);
if (rec._rc == 0)
{
// Add the special values "(All)", "(Any Change)" and "(Ignore)"
_regStatusList = new String[rec._data.length + 3];
_regStatusVals = new String[rec._data.length + 3];
int ndx = 0;
_regStatusList[ndx] = Constants._STRALL;
_regStatusVals[ndx++] = Constants._STRALL;
_regStatusList[ndx] = Constants._STRANY;
_regStatusVals[ndx++] = Constants._STRANY;
_regStatusList[ndx] = Constants._STRIGNORE;
_regStatusVals[ndx++] = Constants._STRIGNORE;
for (int cnt = 0; cnt < rec._data.length; ++cnt)
{
_regStatusList[ndx] = rec._data[cnt]._val;
_regStatusVals[ndx++] = rec._data[cnt]._val;
}
// Add the special value "(All)" and "(none)" for the Criteria entries
_regCStatusList = new String[rec._data.length + 2];
_regCStatusVals = new String[rec._data.length + 2];
ndx = 0;
_regCStatusList[ndx] = Constants._STRALL;
_regCStatusVals[ndx++] = Constants._STRALL;
_regCStatusList[ndx] = Constants._STRNONE;
_regCStatusVals[ndx++] = Constants._STRNONE;
for (int cnt = 0; cnt < rec._data.length; ++cnt)
{
_regCStatusList[ndx] = rec._data[cnt]._val;
_regCStatusVals[ndx++] = rec._data[cnt]._val;
}
}
return rec._rc;
}
/**
* Retrieve the registration status list. The method getRegistrations() must
* be called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbr.reg_status_lov_view.registration_status column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegistrations getRegistrations()
*/
public String[] getRegStatusList()
{
String temp[] = _regStatusList;
_regStatusList = null;
return temp;
}
/**
* Retrieve the registration status values list. The method
* getRegistrations() must be called first. Once this method is used the
* internal copy is deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbr.reg_status_lov_view.registration_status column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegistrations getRegistrations()
*/
public String[] getRegStatusVals()
{
String temp[] = _regStatusVals;
_regStatusVals = null;
return temp;
}
/**
* Retrieve the registration status list. The method getRegistrations() must
* be called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbr.reg_status_lov_view.registration_status column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegistrations getRegistrations()
*/
public String[] getRegCStatusList()
{
String temp[] = _regCStatusList;
_regCStatusList = null;
return temp;
}
/**
* Retrieve the registration status values list. The method
* getRegistrations() must be called first. Once this method is used the
* internal copy is deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbr.reg_status_lov_view.registration_status column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegistrations getRegistrations()
*/
public String[] getRegCStatusVals()
{
String temp[] = _regCStatusVals;
_regCStatusVals = null;
return temp;
}
/**
* Retrieve the Protocols from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtoList getProtoList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtoVals getProtoVals()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtoContext getProtoContext()
*/
public int getProtos()
{
String select = "select pr.conte_idseq, pr.proto_idseq, pr.long_name || ' (v' || pr.version || ' / ' || CV.name || ')' AS lname "
+ "from sbrext.protocols_view_ext pr, sbr.contexts_view cv "
+ "where cv.conte_idseq = pr.conte_idseq order by UPPER(lname) asc";
Results2 rec = getBasicData2(select);
if (rec._rc == 0)
{
_protoList = new String[rec._data.length];
_protoVals = new String[rec._data.length];
_protoContext = new String[rec._data.length];
for (int i = 0; i < _protoList.length; ++i)
{
_protoList[i] = rec._data[i]._label;
_protoVals[i] = rec._data[i]._id2;
_protoContext[i] = rec._data[i]._id1;
}
}
return rec._rc;
}
/**
* Retrieve the protocol list. The method getProtos() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.protocols_view_ext.long_name, version and context
* columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtos getProtos()
*/
public String[] getProtoList()
{
String temp[] = _protoList;
_protoList = null;
return temp;
}
/**
* Retrieve the protocol list. The method getProtos() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.protocols_view_ext.proto_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtos getProtos()
*/
public String[] getProtoVals()
{
String temp[] = _protoVals;
_protoVals = null;
return temp;
}
/**
* Retrieve the protocol list. The method getProtos() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.protocols_view_ext.conte_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtos getProtos()
*/
public String[] getProtoContext()
{
String temp[] = _protoContext;
_protoContext = null;
return temp;
}
/**
* Retrieve the Classification Schemes from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeList getSchemeList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeVals getSchemeVals()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeContext getSchemeContext()
*/
public int getSchemes()
{
String select = "select csv.conte_idseq, csv.cs_idseq, csv.long_name || ' (v' || csv.version || ' / ' || cv.name || ')' as lname "
+ "from sbr.classification_schemes_view csv, sbr.contexts_view cv "
+ "where cv.conte_idseq = csv.conte_idseq order by upper(lname) ASC";
Results2 rec = getBasicData2(select);
if (rec._rc == 0)
{
_schemeList = new String[rec._data.length];
_schemeVals = new String[rec._data.length];
_schemeContext = new String[rec._data.length];
for (int i = 0; i < _schemeList.length; ++i)
{
_schemeList[i] = rec._data[i]._label;
_schemeVals[i] = rec._data[i]._id2;
_schemeContext[i] = rec._data[i]._id1;
}
}
return rec._rc;
}
/**
* Retrieve the classification scheme list. The method getSchemes() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbr.classification_schemes_view.long_name, version and context
* columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemes getSchemes()
*/
public String[] getSchemeList()
{
String temp[] = _schemeList;
_schemeList = null;
return temp;
}
/**
* Retrieve the classification scheme id's. The method getSchemes() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbr.classification_schemes_view.cs_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemes getSchemes()
*/
public String[] getSchemeVals()
{
String temp[] = _schemeVals;
_schemeVals = null;
return temp;
}
/**
* Retrieve the context id's associated with the classification scheme id's
* retrieved above. The method getSchemes() must be called first. Once this
* method is used the internal copy is deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbr.classification_schemes_view.conte_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemes getSchemes()
*/
public String[] getSchemeContext()
{
String temp[] = _schemeContext;
_schemeContext = null;
return temp;
}
private class schemeTree
{
/**
* Constructor.
*
* @param name_ The composite name for sorting.
* @param ndx_ The index of the scheme item in the original list.
*/
public schemeTree(String name_, int ndx_)
{
_fullName = name_;
_ndx = ndx_;
}
/**
* The composite name used for sorting.
*/
public String _fullName;
/**
* The index in the original list.
*/
public int _ndx;
}
/**
* Build the concatenated strings for the Class Scheme Items display.
*
* @param rec_
* The data returned from Oracle.
* @return An array of the full concatenated names for sorting later.
*/
private schemeTree[] buildSchemeItemList(Results3 rec_)
{
// Get the maximum number of levels and the maximum length of a single
// name.
int maxLvl = 0;
int maxLen = 0;
for (int ndx = 1; ndx < rec_._data.length; ++ndx)
{
if (maxLvl < rec_._data[ndx]._id3)
maxLvl = rec_._data[ndx]._id3;
if (rec_._data[ndx]._label1 != null
&& maxLen < rec_._data[ndx]._label1.length())
maxLen = rec_._data[ndx]._label1.length();
if (rec_._data[ndx]._label2 != null
&& maxLen < rec_._data[ndx]._label2.length())
maxLen = rec_._data[ndx]._label2.length();
}
++maxLvl;
// Build and array of prefixes for the levels.
String prefix[] = new String[maxLvl];
prefix[0] = "";
if (maxLvl > 1)
{
prefix[1] = "";
for (int ndx = 2; ndx < prefix.length; ++ndx)
{
prefix[ndx] = prefix[ndx - 1] + " ";
}
}
// In addition to creating the display labels we must also
// create an array used to sort everything alphabetically.
// The easiest is to create a fully concatenated label of a
// individuals hierarchy.
_schemeItemList = new String[rec_._data.length];
maxLvl *= maxLen;
StringBuffer fullBuff = new StringBuffer(maxLvl);
fullBuff.setLength(maxLvl);
schemeTree tree[] = new schemeTree[_schemeItemList.length];
// Loop through the name list.
_schemeItemList[0] = rec_._data[0]._label1;
tree[0] = new schemeTree("", 0);
for (int ndx = 1; ndx < _schemeItemList.length; ++ndx)
{
// Create the concatenated sort string.
int buffOff = (rec_._data[ndx]._id3 < 2) ? 0 : (rec_._data[ndx]._id3 * maxLen);
fullBuff.replace(buffOff, maxLvl, rec_._data[ndx]._label1);
fullBuff.setLength(maxLvl);
// Create the display label.
if (rec_._data[ndx]._id3 == 1)
{
if (rec_._data[ndx]._label2 == null)
{
_schemeItemList[ndx] = rec_._data[ndx]._label1;
}
else
{
_schemeItemList[ndx] = rec_._data[ndx]._label1 + " ("
+ rec_._data[ndx]._label2 + ")";
fullBuff.replace(buffOff + maxLen, maxLvl,
rec_._data[ndx]._label2);
fullBuff.setLength(maxLvl);
}
}
else
{
_schemeItemList[ndx] = prefix[rec_._data[ndx]._id3]
+ rec_._data[ndx]._label1;
}
tree[ndx] = new schemeTree(fullBuff.toString(), ndx);
}
return tree;
}
/**
* Retrieve the Classification Scheme Items from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItemList getSchemeItemList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItemVals getSchemeItemVals()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItemSchemes
* getSchemeItemScheme()
*/
public int getSchemeItems()
{
String select = "select cv.cs_idseq, cv.csi_idseq, level as lvl, "
+ "(select csi.csi_name from sbr.class_scheme_items_view csi where csi.csi_idseq = cv.csi_idseq), "
+ "(select cs.long_name || ' / v' || cs.version as xname from sbr.classification_schemes_view cs where cs.cs_idseq = cv.cs_idseq) "
+ "from sbr.cs_csi_view cv "
+ "start with cv.p_cs_csi_idseq is null "
+ "connect by prior cv.cs_csi_idseq = cv.p_cs_csi_idseq";
Results3 rec = getBasicData3(select, true);
if (rec._rc == 0)
{
schemeTree tree[] = buildSchemeItemList(rec);
_schemeItemVals = new String[rec._data.length];
_schemeItemSchemes = new String[rec._data.length];
for (int i = 0; i < rec._data.length; ++i)
{
_schemeItemVals[i] = rec._data[i]._id2;
_schemeItemSchemes[i] = rec._data[i]._id1;
}
sortSchemeItems(tree);
}
return rec._rc;
}
/**
* Sort the scheme items lists and make everything right on the display.
*
* @param tree_
* The concatenated name tree list.
*/
private void sortSchemeItems(schemeTree tree_[])
{
// Too few items don't bother.
if (tree_.length < 2)
return;
// The first element is the "All" indicator, so don't include it.
schemeTree sort[] = new schemeTree[tree_.length];
sort[0] = tree_[0];
sort[1] = tree_[1];
int top = 2;
// Perform a binary search-insert.
for (int ndx = 2; ndx < tree_.length; ++ndx)
{
int min = 1;
int max = top;
int check = 0;
while (true)
{
check = (max + min) / 2;
int test = tree_[ndx]._fullName
.compareToIgnoreCase(sort[check]._fullName);
if (test == 0)
break;
else if (test > 0)
{
if (min == check)
{
++check;
break;
}
min = check;
}
else
{
if (max == check)
break;
max = check;
}
}
// Add the record to the proper position in the sorted array.
if (check < top)
System.arraycopy(sort, check, sort, check + 1, top - check);
++top;
sort[check] = tree_[ndx];
}
// Now arrange all the arrays based on the sorted index.
String tempList[] = new String[_schemeItemList.length];
String tempVals[] = new String[_schemeItemList.length];
String tempSchemes[] = new String[_schemeItemList.length];
for (int ndx = 0; ndx < sort.length; ++ndx)
{
int pos = sort[ndx]._ndx;
tempList[ndx] = _schemeItemList[pos];
tempVals[ndx] = _schemeItemVals[pos];
tempSchemes[ndx] = _schemeItemSchemes[pos];
}
_schemeItemList = tempList;
_schemeItemVals = tempVals;
_schemeItemSchemes = tempSchemes;
}
/**
* Retrieve the classification scheme item list. The method getSchemeItems()
* must be called first. Once this method is used the internal copy is
* deleted to reclaim the memory space.
*
* @return An array of strings from the sbr.class_scheme_items_view.csi_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItems getSchemeItems()
*/
public String[] getSchemeItemList()
{
String temp[] = _schemeItemList;
_schemeItemList = null;
return temp;
}
/**
* Retrieve the classification scheme item id's. The method getSchemeItems()
* must be called first. Once this method is used the internal copy is
* deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbr.class_scheme_items_view.csi_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItems getSchemeItems()
*/
public String[] getSchemeItemVals()
{
String temp[] = _schemeItemVals;
_schemeItemVals = null;
return temp;
}
/**
* Retrieve the class scheme id's associated with the classification scheme
* item id's retrieved above. The method getSchemeItems() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.class_scheme_items_view.cs_idseq
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItems getSchemeItems()
*/
public String[] getSchemeItemSchemes()
{
String temp[] = _schemeItemSchemes;
_schemeItemSchemes = null;
return temp;
}
private class ResultsData2
{
/**
* id1
*/
public String _id1;
/**
* id2
*/
public String _id2;
/**
* label
*/
public String _label;
}
/**
* Class used to return method results.
*/
private class Results2
{
/**
* The database return code.
*/
public int _rc;
/**
* data
*/
public ResultsData2[] _data;
}
/**
* Perform the database access for a simple query which results in a 3
* column value per returned row.
*
* @param select_
* The SQL select to run.
* @return 0 if successful, otherwise the database error code.
*/
private Results2 getBasicData2(String select_)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
Vector<ResultsData2> results = new Vector<ResultsData2>();
Results2 data = new Results2();
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select_);
// Get the list.
rs = pstmt.executeQuery();
ResultsData2 rec;
while (rs.next())
{
// Remember about the 1 (one) based indexing.
rec = new ResultsData2();
rec._id1 = rs.getString(1);
rec._id2 = rs.getString(2);
rec._label = rs.getString(3);
results.add(rec);
}
rs.close();
pstmt.close();
// Move the list from a Vector to an array and add "(All)" to
// the beginning.
int count = results.size() + 1;
data._data = new ResultsData2[count];
data._data[0] = new ResultsData2();
data._data[0]._label = Constants._STRALL;
data._data[0]._id1 = Constants._STRALL;
data._data[0]._id2 = Constants._STRALL;
int cnt = 0;
for (int ndx = 1; ndx < count; ++ndx)
{
rec = (ResultsData2) results.get(cnt++);
data._data[ndx] = new ResultsData2();
data._data[ndx]._label = rec._label.replaceAll("[\\s]", " ");
data._data[ndx]._id1 = rec._id1;
data._data[ndx]._id2 = rec._id2;
}
data._rc = 0;
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
data._rc = _errorCode;
}
return data;
}
class ResultsData3
{
/**
*
*/
public String _id1;
/**
*
*/
public String _id2;
/**
*
*/
public int _id3;
/**
*
*/
public String _label1;
/**
*
*/
public String _label2;
}
;
/**
* Class used to return method results.
*/
private class Results3
{
/**
* The database return code.
*/
public int _rc;
/**
* The data
*/
public ResultsData3[] _data;
}
/**
* Perform the database access for a simple query which results in a 4
* column value per returned row.
*
* @param select_
* The SQL select to run.
* @param flag_ true if the list should be prefixed with "All".
* @return 0 if successful, otherwise the database error code.
*/
private Results3 getBasicData3(String select_, boolean flag_)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
Vector<ResultsData3> results = new Vector<ResultsData3>();
Results3 data = new Results3();
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select_);
// Get the list.
rs = pstmt.executeQuery();
ResultsData3 rec;
while (rs.next())
{
// Remember about the 1 (one) based indexing.
rec = new ResultsData3();
rec._id1 = rs.getString(1);
rec._id2 = rs.getString(2);
rec._id3 = rs.getInt(3);
rec._label1 = rs.getString(4);
rec._label2 = rs.getString(5);
results.add(rec);
}
rs.close();
pstmt.close();
// Move the list from a Vector to an array and add "(All)" to
// the beginning.
int offset = (flag_) ? 1 : 0;
int count = results.size() + offset;
data._data = new ResultsData3[count];
if (flag_)
{
data._data[0] = new ResultsData3();
data._data[0]._label1 = Constants._STRALL;
data._data[0]._label2 = Constants._STRALL;
data._data[0]._id1 = Constants._STRALL;
data._data[0]._id2 = Constants._STRALL;
data._data[0]._id3 = 0;
}
int cnt = 0;
for (int ndx = offset; ndx < count; ++ndx)
{
rec = (ResultsData3) results.get(cnt++);
data._data[ndx] = new ResultsData3();
data._data[ndx]._label1 = rec._label1.replaceAll("[\\s]", " ");
data._data[ndx]._label2 = rec._label2.replaceAll("[\\s]", " ");
data._data[ndx]._id1 = rec._id1;
data._data[ndx]._id2 = rec._id2;
data._data[ndx]._id3 = rec._id3;
}
data._rc = 0;
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
data._rc = _errorCode;
}
return data;
}
/**
* Retrieve the list of record types. As this is coded in a constant
* array, no database access is required.
*
* @return 0 if successful.
*/
public int getACTypes()
{
String[] list = new String[_DBMAP3.length + 1];
String[] vals = new String[_DBMAP3.length + 1];
list[0] = Constants._STRALL;
vals[0] = Constants._STRALL;
list[1] = _DBMAP3[0]._val;
vals[1] = _DBMAP3[0]._key;
// Put the descriptive text in alphabetic order for display.
// Of course we have to keep the key-value pairs intact.
for (int ndx = 1; ndx < _DBMAP3.length; ++ndx)
{
int min = 1;
int max = ndx + 1;
int pos = 1;
while (true)
{
pos = (max + min) / 2;
int compare = _DBMAP3[ndx]._val.compareTo(list[pos]);
if (compare == 0)
{
// Can't happen.
}
else if (compare > 0)
{
if (min == pos)
{
++pos;
break;
}
min = pos;
}
else
{
if (max == pos)
{
break;
}
max = pos;
}
}
// Preserve existing entries - an insert.
if (pos <= ndx)
{
System.arraycopy(list, pos, list, pos + 1, ndx - pos + 1);
System.arraycopy(vals, pos, vals, pos + 1, ndx - pos + 1);
}
// Insert new item in list.
list[pos] = _DBMAP3[ndx]._val;
vals[pos] = _DBMAP3[ndx]._key;
}
// Keep the results.
_actypesList = list;
_actypesVals = vals;
return 0;
}
/**
* Return the descriptive names for the record types.
*
* @return The list of display values.
*/
public String[] getACTypesList()
{
String temp[] = _actypesList;
_actypesList = null;
return temp;
}
/**
* Return the internal values used to identify the record types.
*
* @return The list of internal record types.
*/
public String[] getACTypesVals()
{
String temp[] = _actypesVals;
_actypesVals = null;
return temp;
}
/**
* Retrieve the list of forms and templates from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getFormsList getFormsList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getFormsVals getFormsVals()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getFormsContext getFormsContext()
*/
public int getForms()
{
// Build a composite descriptive string for this form.
String select =
"select qcv.conte_idseq, qcv.qc_idseq, qcv.long_name || "
+ "' (v' || qcv.version || ' / ' || qcv.qtl_name || ' / ' || nvl(proto.long_name, '(' || cv.name || ')') || ')' as lname "
+ "from sbrext.quest_contents_view_ext qcv, sbr.contexts_view cv, "
+ "sbrext.protocol_qc_ext pq, sbrext.protocols_view_ext proto "
+ "where qcv.qtl_name in ('TEMPLATE','CRF') "
+ "and cv.conte_idseq = qcv.conte_idseq "
+ "and qcv.qc_idseq = pq.qc_idseq(+) "
+ "and pq.proto_idseq = proto.proto_idseq(+) "
+ "order by upper(lname)";
Results2 rec = getBasicData2(select);
if (rec._rc == 0)
{
_formsList = new String[rec._data.length];
_formsVals = new String[rec._data.length];
_formsContext = new String[rec._data.length];
for (int ndx = 0; ndx < _formsList.length; ++ndx)
{
// Can you believe that some people put quotes in the name? We
// have to escape them or it causes
// problems downstream.
_formsList[ndx] = rec._data[ndx]._label;
_formsList[ndx] = _formsList[ndx].replaceAll("[\"]", "\\\\\"");
_formsList[ndx] = _formsList[ndx].replaceAll("[\\r\\n]", " ");
_formsVals[ndx] = rec._data[ndx]._id2;
_formsContext[ndx] = rec._data[ndx]._id1;
}
}
return rec._rc;
}
/**
* Return the forms/templates composite names. The method getForms() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.quest_contents_view_ext.long_name, ... columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getForms getForms()
*/
public String[] getFormsList()
{
String temp[] = _formsList;
_formsList = null;
return temp;
}
/**
* Return the forms/templates id values. The method getForms() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.quest_contents_view_ext.qc_idseq columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getForms getForms()
*/
public String[] getFormsVals()
{
String temp[] = _formsVals;
_formsVals = null;
return temp;
}
/**
* Return the context id's associated with the forms/templates. The method
* getForms() must be called first. Once this method is used the internal
* copy is deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbrext.quest_contents_view_ext.conte_idseq columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getForms getForms()
*/
public String[] getFormsContext()
{
String temp[] = _formsContext;
_formsContext = null;
return temp;
}
/**
* Return the last recorded database error message. If the current error
* code is zero (0) an empty string is returned.
*
* @return The last database error message or an empty string.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getErrorCode getErrorCode()
*/
public String getErrorMsg()
{
return (_errorCode != 0) ? _errorMsg : null;
}
/**
* Return the last recorded database error message. If the current error
* code is zero (0) an empty string is returned.
*
* @param flag_
* True if the new lines ('\n') should be expanded to text for use in
* script. False to return the message unaltered.
* @return The last database error message or an empty string.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getErrorCode getErrorCode()
*/
public String getErrorMsg(boolean flag_)
{
return (_errorCode != 0) ? ((flag_) ? _errorMsg.replaceAll("[\\n]",
"\\\\n") : _errorMsg) : null;
}
/**
* Return the last recorded database error code and then reset it to zero
* (0).
*
* @return The database error code.
*/
public int getErrorCode()
{
int rc = _errorCode;
_errorCode = 0;
return rc;
}
/**
* Return any error message and reset the error code to zero for the next
* possible error.
*
* @return The database error message.
*/
public String getError()
{
String temp = getErrorMsg();
if (temp != null)
_errorCode = 0;
return temp;
}
/**
* Get the Alerts which are active for the target date provided.
*
* @param target_
* The target date, typically the date an Auto Run process is
* started.
* @return null if an error, otherwise the list of valid alert definitions.
*/
public AlertRec[] selectAlerts(Timestamp target_)
{
String select = "select al_idseq, name, created_by "
+ "from sbrext.sn_alert_view_ext " + "where al_status <> 'I' AND "
+ "(auto_freq_unit = 'D' OR "
+ "(auto_freq_unit = 'W' AND auto_freq_value = ?) OR "
+ "(auto_freq_unit = 'M' AND auto_freq_value = ?)) "
+ "order by upper(created_by) asc, upper(name) asc";
// Get day and date from target to qualify the select.
GregorianCalendar tdate = new GregorianCalendar();
tdate.setTimeInMillis(target_.getTime());
int dayWeek = tdate.get(Calendar.DAY_OF_WEEK);
int dayMonth = tdate.get(Calendar.DAY_OF_MONTH);
try
{
// Set SQL arguments
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setInt(1, dayWeek);
pstmt.setInt(2, dayMonth);
// Retrieve all applicable definition ids.
ResultSet rs = pstmt.executeQuery();
Vector<String> list = new Vector<String>();
while (rs.next())
{
list.add(rs.getString(1));
}
rs.close();
pstmt.close();
// There may be nothing to do.
if (list.size() == 0)
return new AlertRec[0];
// retrieve the full alert definition, we will need it.
AlertRec recs[] = new AlertRec[list.size()];
int keep = 0;
int ndx;
for (ndx = 0; ndx < recs.length; ++ndx)
{
// Be sure we can read the Alert Definition.
recs[keep] = selectAlert((String) list.get(ndx));
if (recs[keep] == null)
return null;
// Check the date. We do this here and not in the SQL because
// 99.99% of the time this will return true and complicating the
// SQL isn't necessary.
if (recs[keep].isActive(target_))
++keep;
// In the RARE situation that the alert is inactive at this
// point,
// we reset the object pointer to release the memory.
else
recs[keep] = null;
}
// Return the results. It is possible that sometimes the last entry
// in the
// list will be null. Consequently the use of the list should be in
// a loop
// with the following condition: "cnt < recs.length && recs[cnt] !=
// null"
if (keep == ndx)
return recs;
// Only process the ones that are Active.
AlertRec trecs[] = new AlertRec[keep];
for (ndx = 0; ndx < keep; ++ndx)
trecs[ndx] = recs[ndx];
return trecs;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Convert a Vector of Strings to an array.
*
* @param list_
* The vector.
* @return The string array.
*/
private String[] paste(Vector<String> list_)
{
String temp[] = new String[list_.size()];
for (int ndx = 0; ndx < temp.length; ++ndx)
temp[ndx] = list_.get(ndx);
return temp;
}
/**
* Convert a Vector of Timestamps to an array.
*
* @param list_ The vector.
* @return The Timestamp array.
*/
private Timestamp[] paste(Vector<Timestamp> list_)
{
Timestamp temp[] = new Timestamp[list_.size()];
for (int ndx = 0; ndx < temp.length; ++ndx)
temp[ndx] = list_.get(ndx);
return temp;
}
/**
* Copy the result set to an ACData array.
*
* @param rs_
* The query result set.
* @return The ACData array if successful, otherwise null.
* @throws java.sql.SQLException
* When there is a problem with the result set.
*/
private ACData[] copyResults(ResultSet rs_) throws SQLException
{
Vector<ACData> data = new Vector<ACData>();
Vector<String> changes = new Vector<String>();
Vector<String> oval = new Vector<String>();
Vector<String> nval = new Vector<String>();
Vector<String> tabl = new Vector<String>();
Vector<String> chgby = new Vector<String>();
Vector<Timestamp> dval = new Vector<Timestamp>();
String clist[] = null;
String olist[] = null;
String nlist[] = null;
String tlist[] = null;
String blist[] = null;
Timestamp dlist[] = null;
ACData oldrec = null;
int cols = rs_.getMetaData().getColumnCount();
while (rs_.next())
{
ACData rec = new ACData();
rec.set(
rs_.getString(1).charAt(0),
rs_.getInt(2),
rs_.getString(3),
rs_.getString(4),
rs_.getString(5),
rs_.getInt(6),
rs_.getString(7),
rs_.getString(8),
rs_.getTimestamp(9),
rs_.getTimestamp(10),
rs_.getString(11),
rs_.getString(12),
rs_.getString(13),
rs_.getString(14),
rs_.getString(15));
// We don't want to waste time or space with records that are
// identical. We can't use a SELECT DISTINCT for this logic as the
// ACData.equals doesn't look at all data elements but only specific ones.
if (oldrec != null)
{
if (!oldrec.isEquivalent(rec))
{
clist = paste(changes);
olist = paste(oval);
nlist = paste(nval);
dlist = paste(dval);
tlist = paste(tabl);
blist = paste(chgby);
oldrec.setChanges(clist, olist, nlist, dlist, tlist, blist);
data.add(oldrec);
changes = new Vector<String>();
oval = new Vector<String>();
nval = new Vector<String>();
dval = new Vector<Timestamp>();
tabl = new Vector<String>();
chgby = new Vector<String>();
}
}
// Build the list of specific changes if we can get them. We must
// save
// always save the information if present.
//
// NOTE we only record the first 18 columns of the result set but
// there may be
// more to make the SQL work as desired.
if (cols > 17)
{
String ctext = rs_.getString(16);
// If the "change" column is blank don't waste the space.
if (ctext != null && ctext.length() > 0)
{
changes.add(ctext);
oval.add(rs_.getString(17));
nval.add(rs_.getString(18));
dval.add(rs_.getTimestamp(19));
tabl.add(rs_.getString(20));
chgby.add(rs_.getString(21));
}
}
oldrec = rec;
}
if (oldrec != null)
{
clist = paste(changes);
olist = paste(oval);
nlist = paste(nval);
dlist = paste(dval);
tlist = paste(tabl);
blist = paste(chgby);
oldrec.setChanges(clist, olist, nlist, dlist, tlist, blist);
data.add(oldrec);
}
ACData list[] = new ACData[data.size()];
if (data.size() > 0)
{
for (int ndx = 0; ndx < list.length; ++ndx)
{
list[ndx] = (ACData) data.get(ndx);
}
}
return list;
}
/**
* Pull rows changed in the date range specified. There are 3 different
* patterns to handle:
* <p>
* <ul>
* <li>[from/to, from/to] {2, 4} - This represents the from/to date pair
* which may occur 2 or 4 times in the SQL. This pattern is handled by this
* method argument list.</li>
* <li>[in, from/to, from/to] {2, 4} - This represents a single "in" clause
* of creators or modifiers followed by the from/to pair which may occur 2
* or 4 times in the SQL in this order.</li>
* <li>[in, in, from/to, from/to] {2,4} - This represents an "in" clause
* for the creators and an "in" clause for the modifiers followed by the
* from/to pair which in total may appear 1 or 2 times.</li>
* </ul>
* </p>
*
* @param select_
* The SQL select for the specific data and table.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param pairs_
* The number of pairs of (start, end) that appear in the SQL.
* @return 0 if successful, otherwise the database error code.
*/
private ACData[] selectAC(String select_, Timestamp start_, Timestamp end_,
int pairs_)
{
try
{
PreparedStatement pstmt = _conn.prepareStatement(select_);
for (int ndx = 0; ndx < pairs_; ++ndx)
{
pstmt.setTimestamp((ndx * 2) + 1, start_);
pstmt.setTimestamp((ndx * 2) + 2, end_);
}
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Generate a string of comma separated SQL arguments for us in an "in"
* clause.
*
* @param cnt_
* The number of place holders needed.
* @return String The comma separated string without parentheses.
*/
private String expandMarkers(int cnt_)
{
String markers = "?";
for (int ndx = 1; ndx < cnt_; ++ndx)
{
markers = markers + ",?";
}
return markers;
}
/**
* Pull rows changed in the date range specified. There are 3 different
* patterns to handle:
* <p>
* <ul>
* <li>[from/to, from/to] {2, 4} - This represents the from/to date pair
* which may occur 2 or 4 times in the SQL.</li>
* <li>[in, from/to, from/to] {2, 4} - This represents a single "in" clause
* of creators or modifiers followed by the from/to pair which may occur 2
* or 4 times in the SQL in this order. This pattern is handled by this
* method argument list.</li>
* <li>[in, in, from/to, from/to] {2,4} - This represents an "in" clause
* for the creators and an "in" clause for the modifiers followed by the
* from/to pair which in total may appear 1 or 2 times.</li>
* </ul>
* </p>
*
* @param select_
* The SQL select for the specific data and table.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param pairs_
* The number of pairs of (start, end) that appear in the SQL.
* @param vals_
* The additional values used by an "in" clause.
* @return 0 if successful, otherwise the database error code.
*/
private ACData[] selectAC(String select_, Timestamp start_, Timestamp end_,
int pairs_, String vals_[])
{
// Expand the "in" clause.
int loop = pairs_ / 2;
String markers = expandMarkers(vals_.length);
String parts[] = select_.split("\\?");
int pos = 0;
String select = parts[pos++];
for (int cnt = 0; cnt < loop; ++cnt)
{
select = select + markers + parts[pos++];
for (int ndx = 0; ndx < 2; ++ndx)
{
select = select + "?" + parts[pos++] + "?" + parts[pos++];
}
}
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
int arg = 1;
for (int cnt = 0; cnt < loop; ++cnt)
{
for (int ndx = 0; ndx < vals_.length; ++ndx)
{
pstmt.setString(arg++, vals_[ndx]);
}
for (int ndx = 0; ndx < 2; ++ndx)
{
pstmt.setTimestamp(arg++, start_);
pstmt.setTimestamp(arg++, end_);
}
}
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Pull rows changed in the date range specified. There are 3 different
* patterns to handle:
* <p>
* <ul>
* <li>[from/to, from/to] {2, 4} - This represents the from/to date pair
* which may occur 2 or 4 times in the SQL.</li>
* <li>[in, from/to, from/to] {2, 4} - This represents a single "in" clause
* of creators or modifiers followed by the from/to pair which may occur 2
* or 4 times in the SQL in this order.</li>
* <li>[in, in, from/to, from/to] {2,4} - This represents an "in" clause
* for the creators and an "in" clause for the modifiers followed by the
* from/to pair which in total may appear 1 or 2 times. This pattern is
* handled by this method argument list.</li>
* </ul>
* </p>
*
* @param select_
* The SQL select for the specific data and table.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param pairs_
* The number of pairs of (start, end) that appear in the SQL.
* @param vals1_
* The additional values used by an "in" clause.
* @param vals2_
* The additional values used by a second "in" clause.
* @return 0 if successful, otherwise the database error code.
*/
private ACData[] selectAC(String select_, Timestamp start_, Timestamp end_,
int pairs_, String vals1_[], String vals2_[])
{
// Expand the "in" clauses.
String parts[] = select_.split("\\?");
int loop = pairs_ / 2;
String markers1 = expandMarkers(vals1_.length);
String markers2 = expandMarkers(vals2_.length);
int pos = 0;
String select = parts[pos++];
for (int cnt = 0; cnt < loop; ++cnt)
{
select = select + markers1 + parts[pos++] + markers2 + parts[pos++];
for (int ndx = 0; ndx < 2; ++ndx)
{
select = select + "?" + parts[pos++] + "?" + parts[pos++];
}
}
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
int arg = 1;
for (int cnt = 0; cnt < loop; ++cnt)
{
for (int ndx = 0; ndx < vals1_.length; ++ndx)
{
pstmt.setString(arg++, vals1_[ndx]);
}
for (int ndx = 0; ndx < vals2_.length; ++ndx)
{
pstmt.setString(arg++, vals2_[ndx]);
}
for (int ndx = 0; ndx < 2; ++ndx)
{
pstmt.setTimestamp(arg++, start_);
pstmt.setTimestamp(arg++, end_);
}
}
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
private ACData[] selectAC(String select_)
{
try
{
PreparedStatement pstmt = _conn.prepareStatement(select_);
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
private int selectChangedTableType(String idseq_)
{
String select = "select changed_table from sbrext.ac_change_history_ext "
+ "where changed_table_idseq = ? and rownum < 2";
int itype = -1;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, idseq_);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
String stype = rs.getString(1);
if (stype.equals("CLASSIFICATION_SCHEMES"))
itype = _ACTYPE_CS;
else if (stype.equals("DATA_ELEMENTS"))
itype = _ACTYPE_DE;
else if (stype.equals("DATA_ELEMENT_CONCEPTS"))
itype = _ACTYPE_DEC;
else if (stype.equals("OBJECT_CLASSES_EXT"))
itype = _ACTYPE_OC;
else if (stype.equals("PROPERTIES_EXT"))
itype = _ACTYPE_PROP;
else if (stype.equals("VALUE_DOMAINS"))
itype = _ACTYPE_VD;
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
}
return itype;
}
/**
* Build a complex SQL from individual phrases. The calling method provides
* an array of strings for the SQL SELECT with each representing a specific
* part of the combined statement. Using the presence or absence of other
* argument values, a composite statement is formed and executed.
*
* @param select_
* The array of component parts of the SQL SELECT.
* @param start_
* The start date of the date range. The record date must be greater
* than or equal to this value.
* @param end_
* The end date of the date range. The record date must be less than
* this value.
* @param pairs_
* The number of date pairs that appear in the master array.
* @param creators_
* The creator (created by) ids of the records or null.
* @param modifiers_
* The modifier (modified by) ids of the records or null.
* @return The result of the composite SQL.
*/
private ACData[] selectAC(String select_[], Timestamp start_,
Timestamp end_, int pairs_, String creators_[], String modifiers_[])
{
String select = select_[0];
int pattern = 0;
if (creators_ != null && creators_[0].charAt(0) != '(')
{
pattern += 1;
select = select + select_[1];
}
if (modifiers_ != null && modifiers_[0].charAt(0) != '(')
{
pattern += 2;
select = select + select_[2];
}
select = select + select_[3];
if (pairs_ == 4)
{
if (creators_ != null && creators_[0].charAt(0) != '(')
select = select + select_[4];
if (modifiers_ != null && modifiers_[0].charAt(0) != '(')
select = select + select_[5];
select = select + select_[6];
}
switch (pattern)
{
case 1:
return selectAC(select, start_, end_, pairs_, creators_);
case 2:
return selectAC(select, start_, end_, pairs_, modifiers_);
case 3:
return selectAC(select, start_, end_, pairs_, creators_,
modifiers_);
default:
return selectAC(select, start_, end_, pairs_);
}
}
/**
* Pull all Permissible Values changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectPV(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[])
{
// There's always one that doesn't fit the pattern. Any changes to
// selectBuild() must also be checked here for consistency.
String start = "to_date('" + start_.toString().substring(0, 10) + "', 'yyyy/mm/dd')";
String end = "to_date('" + end_.toString().substring(0, 10) + "', 'yyyy/mm/dd')";
String select =
"select 'p', 1, 'pv', zz.pv_idseq as id, '', -1, zz.value, '', "
+ "zz.date_modified, zz.date_created, zz.modified_by, zz.created_by, '', "
+ "'', '', ach.changed_column, ach.old_value, ach.new_value, ach.change_datetimestamp, ach.changed_table, ach.changed_by "
+ "from sbrext.ac_change_history_ext ach, sbr.permissible_values_view zz ";
select = select + "where ach.change_datetimestamp >= " + start + " and ach.change_datetimestamp < " + end + " ";
if (modifiers_ != null && modifiers_.length > 0 && modifiers_[0].charAt(0) != '(')
select = select + "AND ach.changed_by in " + selectIN(modifiers_);
select = select + whereACH(_ACTYPE_PV)
+ "AND zz.pv_idseq = ach.ac_idseq ";
if (creators_ != null && creators_.length > 0 && creators_[0].charAt(0) != '(')
select = select + "AND zz.created_by in " + selectIN(creators_);
if (dates_ == _DATECONLY)
select = select + "AND zz.date_created >= " + start + " and zz.date_created < " + end + " ";
else if (dates_ == _DATEMONLY)
select = select + "AND zz.date_modified is not NULL ";
select = select + _orderbyACH;
return selectAC(select);
}
/**
* Pull all Value Meanings changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectVM(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND zz.asl_name IN " + selectIN(wstatus_);
}
String[] select = new String[4];
select[0] =
"select 'p', 1, 'vm', zz.short_meaning as id, zz.version, zz.vm_id, zz.long_name, zz.conte_idseq as cid, "
+ "zz.date_modified as ctime, zz.date_created, zz.modified_by, zz.created_by, zz.comments, c.name, '' "
+ "from sbr.value_meanings_view zz, sbr.contexts_view c where ";
select[1] = "zz.created_by in (?) and ";
select[2] = "zz.modified_by in (?) and ";
select[3] = "((zz.date_modified is not null and zz.date_modified "
+ _DATECHARS[dates_][0] + " ? and zz.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (zz.date_created is not null and zz.date_created "
+ _DATECHARS[dates_][2] + " ? and zz.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ "and c.conte_idseq = zz.conte_idseq " + wfs_clause
+ " order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Concepts changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCON(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND zz.asl_name IN " + selectIN(wstatus_);
}
String[] select = new String[4];
select[0] =
"select 'p', 1, 'con', zz.con_idseq as id, zz.version, zz.con_id, zz.long_name, zz.conte_idseq as cid, "
+ "zz.date_modified as ctime, zz.date_created, zz.modified_by, zz.created_by, zz.change_note, c.name, '' "
+ "from sbrext.concepts_view_ext zz, sbr.contexts_view c where ";
select[1] = "zz.created_by in (?) and ";
select[2] = "zz.modified_by in (?) and ";
select[3] = "((zz.date_modified is not null and zz.date_modified "
+ _DATECHARS[dates_][0] + " ? and zz.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (zz.date_created is not null and zz.date_created "
+ _DATECHARS[dates_][2] + " ? and zz.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ "and c.conte_idseq = zz.conte_idseq " + wfs_clause
+ " order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Value Domains changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectVD(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_VD,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Pull all Conceptual Domain changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCD(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND cd.asl_name IN " + selectIN(wstatus_);
}
int pairs;
String select[] = new String[7];
select[0] = "(select 'p', 1, 'cd', cd.cd_idseq as id, cd.version, cd.cd_id, cd.long_name, cd.conte_idseq as cid, "
+ "cd.date_modified as ctime, cd.date_created, cd.modified_by, cd.created_by, cd.change_note, c.name, '' "
+ "from sbr.conceptual_domains_view cd, sbr.contexts_view c "
+ "where c.conte_idseq = cd.conte_idseq and ";
select[1] = "cd.created_by in (?) and ";
select[2] = "cd.modified_by in (?) and ";
pairs = 2;
select[3] = "((cd.date_modified is not null and cd.date_modified "
+ _DATECHARS[dates_][0] + " ? and cd.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (cd.date_created is not null and cd.date_created "
+ _DATECHARS[dates_][2] + " ? and cd.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ ") order by id asc, cid asc";
return selectAC(select, start_, end_, pairs, creators_, modifiers_);
}
/**
* Pull all Classification Schemes changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCS(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_CS,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Pull all Property changes in the date range
* specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectPROP(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_PROP,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Pull all Object Class changes in the date range
* specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectOC(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_OC,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Pull all Forms/Templates Value Values changed in the date range
* specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectQCV(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND qc.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'qcv', qc.qc_idseq as id, qc.version, qc.qc_id, "
+ "qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified as ctime, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, '' "
+ "from sbrext.quest_contents_view_ext qc, sbr.contexts_view c "
+ "where qc.qtl_name = 'VALID_VALUE' and c.conte_idseq = qc.conte_idseq and ";
select[1] = "qc.created_by in (?) and ";
select[2] = "qc.modified_by in (?) and ";
select[3] = "((qc.date_modified is not null and qc.date_modified "
+ _DATECHARS[dates_][0] + " ? and qc.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (qc.date_created is not null and qc.date_created "
+ _DATECHARS[dates_][2] + " ? and qc.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Forms/Templates Questions changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectQCQ(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND qc.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'qcq', qc.qc_idseq as id, qc.version, qc.qc_id, "
+ "qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified as ctime, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, '' "
+ "from sbrext.quest_contents_view_ext qc, sbr.contexts_view c "
+ "where qc.qtl_name in ('QUESTION', 'QUESTION_INSTR') and c.conte_idseq = qc.conte_idseq and ";
select[1] = "qc.created_by in (?) and ";
select[2] = "qc.modified_by in (?) and ";
select[3] = "((qc.date_modified is not null and qc.date_modified "
+ _DATECHARS[dates_][0] + " ? and qc.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (qc.date_created is not null and qc.date_created "
+ _DATECHARS[dates_][2] + " ? and qc.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Forms/Templates Modules changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectQCM(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND qc.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'qcm', qc.qc_idseq as id, qc.version, qc.qc_id, "
+ "qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified as ctime, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, '' "
+ "from sbrext.quest_contents_view_ext qc, sbr.contexts_view c "
+ "where qc.qtl_name = 'MODULE' and c.conte_idseq = qc.conte_idseq and ";
select[1] = "qc.created_by in (?) and ";
select[2] = "qc.modified_by in (?) and ";
select[3] = "((qc.date_modified is not null and qc.date_modified "
+ _DATECHARS[dates_][0] + " ? and qc.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (qc.date_created is not null and qc.date_created "
+ _DATECHARS[dates_][2] + " ? and qc.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Protocols changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectPROTO(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND proto.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'proto', proto.proto_idseq as id, proto.version, proto.proto_id, "
+ "proto.long_name, proto.conte_idseq as cid, "
+ "proto.date_modified as ctime, proto.date_created, proto.modified_by, proto.created_by, proto.change_note, c.name, '' "
+ "from sbrext.protocols_view_ext proto, sbr.contexts_view c "
+ "where c.conte_idseq = proto.conte_idseq and ";
select[1] = "proto.created_by in (?) and ";
select[2] = "proto.modified_by in (?) and ";
select[3] = "((proto.date_modified is not null and proto.date_modified "
+ _DATECHARS[dates_][0] + " ? and proto.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (proto.date_created is not null and proto.date_created "
+ _DATECHARS[dates_][2] + " ? and proto.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Forms/Templates changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectQC(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND qc.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'qc', qc.qc_idseq as id, qc.version, qc.qc_id, "
+ "qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified as ctime, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, '' "
+ "from sbrext.quest_contents_view_ext qc, sbr.contexts_view c "
+ "where qc.qtl_name in ('FORM', 'TEMPLATE') and c.conte_idseq = qc.conte_idseq and ";
select[1] = "qc.created_by in (?) and ";
select[2] = "qc.modified_by in (?) and ";
select[3] = "((qc.date_modified is not null and qc.date_modified "
+ _DATECHARS[dates_][0] + " ? and qc.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (qc.date_created is not null and qc.date_created "
+ _DATECHARS[dates_][2] + " ? and qc.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Classification Scheme Items changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCSI(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[])
{
String select[] = new String[4];
select[0] = "select 'p', 1, 'csi', csi_idseq as id, '', -1, csi_name, '', "
+ "date_modified, date_created, modified_by, created_by, comments, '', '' "
+ "from sbr.class_scheme_items_view " + "where ";
select[1] = "created_by in (?) and ";
select[2] = "modified_by in (?) and ";
select[3] = "((date_modified is not null and date_modified "
+ _DATECHARS[dates_][0] + " ? and date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (date_created is not null and date_created "
+ _DATECHARS[dates_][2] + " ? and date_created " + _DATECHARS[dates_][3] + " ?)) "
+ "order by id asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Expand the list to an IN clause.
*
* @param regs_ The list of DE registration statuses.
* @return The expanded IN clause.
*/
private String selectIN(String regs_[])
{
String temp = "";
for (int ndx = 0; ndx < regs_.length; ++ndx)
{
temp = temp + ", '" + regs_[ndx] + "'";
}
return "(" + temp.substring(2) + ") ";
}
/**
* Construct the standard change history table where clause.
*
* @param table_ The primary changed_table value, one of _ACTYPE_...
* @return The where clause.
*/
private String whereACH(int table_)
{
String temp = "AND ach.ac_idseq in "
+ "(select distinct ch2.changed_table_idseq from sbrext.ac_change_history_ext ch2 "
+ "where ch2.changed_table = '" + _DBMAP3[table_]._col + "' and ch2.changed_table_idseq = ach.ac_idseq) "
+ "and ach.changed_column not in ('DATE_CREATED', 'DATE_MODIFIED', 'LAE_NAME') "
+ "and (ach.changed_table = '" + _DBMAP3[table_]._col + "' or "
+ "(ach.changed_table = 'AC_CSI' and ach.changed_column = 'CS_CSI_IDSEQ') or "
+ "(ach.changed_table = 'DESIGNATIONS' and ach.changed_column in ('CONTE_IDSEQ', 'DETL_NAME', 'LAE_NAME')) or "
+ "(ach.changed_table = 'REFERENCE_DOCUMENTS' and ach.changed_column in ('DCTL_NAME', 'DISPLAY_ORDER', 'DOC_TEXT', 'RDTL_NAME', 'URL')) or "
+ "(ach.changed_table = 'VD_PVS' and ach.changed_column = 'PV_IDSEQ')) ";
return temp;
}
/**
* Pull all Data Elements changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @param rstatus_
* The list of desired Registration Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectDE(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[], String rstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_DE,
dates_, start_, end_, creators_, modifiers_, wstatus_, rstatus_));
}
/**
* Return the CON_IDSEQ for referenced (used) concepts.
*
* @return the con_idseq list
*/
public String[] selectUsedConcepts()
{
String select = "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbr.value_domains_view zz "
+ "where cv.condr_idseq = zz.condr_idseq "
+ "union "
+ "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbrext.object_classes_view_ext zz "
+ "where cv.condr_idseq = zz.condr_idseq "
+ "union "
+ "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbrext.properties_view_ext zz "
+ "where cv.condr_idseq = zz.condr_idseq "
+ "union "
+ "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbr.value_meanings_view zz "
+ "where cv.condr_idseq = zz.condr_idseq "
+ "union "
+ "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbrext.representations_ext zz "
+ "where cv.condr_idseq = zz.condr_idseq";
return getBasicData0(select);
}
/**
* Return the CON_IDSEQ for all concepts.
*
* @return the con_idseq list
*/
public String[] selectAllConcepts()
{
String select = "select con_idseq from sbrext.concepts_view_ext order by con_idseq";
return getBasicData0(select);
}
/**
* Pull the change history log for a single record.
*
* @param idseq_ The idseq of the record.
*
* @return The data if any (array length of zero if none found).
*/
public ACData[] selectWithIDSEQ(String idseq_)
{
int itype = selectChangedTableType(idseq_);
if (itype < 0)
{
return new ACData[0];
}
return selectAC(
selectBuild(idseq_, itype, _DATECM, null, null, null, null, null, null));
}
/**
* Pull all Contexts changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCONTE(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[])
{
String select[] = new String[4];
select[0] = "select 'p', 1, 'conte', conte_idseq as id, version, -1, name, '', "
+ "date_modified, date_created, modified_by, created_by, '', '', '' "
+ "from sbr.contexts_view " + "where ";
select[1] = "created_by in (?) and ";
select[2] = "modified_by in (?) and ";
select[3] = "((date_modified is not null and date_modified "
+ _DATECHARS[dates_][0] + " ? and date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (date_created is not null and date_created "
+ _DATECHARS[dates_][2] + " ? and date_created " + _DATECHARS[dates_][3] + " ?)) "
+ "order by id asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Build the SQL select to retrieve changes for an Administered Component.
*
* @param idseq_ The idseq of a speciifc record of interest.
* @param type_ The AC type, one of _ACTYPE_...
* @param dates_ The flag for how dates are compared, _DATECM, _DATECONLY, _DATEMONLY
* @param start_ The start date for the query.
* @param end_ The end date for the query.
* @param creators_ The specific created_by if any.
* @param modifiers_ The specific modified_by if any.
* @param wstatus_ The specific Workflow Status if any.
* @param rstatus_ The specific Registration Status if any.
* @return The SQL select string.
*/
private String selectBuild(String idseq_, int type_,
int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[], String rstatus_[])
{
// For consistency of reporting and ease of maintenance the idseq parameter
// is provided to ignore the date range and pull all information about a
// specific record.
if (idseq_ != null && idseq_.length() > 0)
{
dates_ = _DATECM;
start_ = new Timestamp(0);
end_ = start_;
creators_ = null;
modifiers_ = null;
wstatus_ = null;
rstatus_ = null;
}
// Due to the very conditional nature of this logic, the SQL SELECT is built
// without the use of substitution arguments ('?').
String prefix = _DBMAP3[type_]._key;
// The 'de' type is the only one that doesn't use the same prefix for the public id
// database column - ugh.
String prefix2 = (type_ == _ACTYPE_DE) ? "cde" : prefix;
// Build the basic select and from.
String select =
"select 'p', 1, '" + prefix
+ "', zz." + prefix
+ "_idseq as id, zz.version, zz." + prefix2
+ "_id, zz.long_name, zz.conte_idseq, "
+ "zz.date_modified, zz.date_created, zz.modified_by, zz.created_by, zz.change_note, "
+ "c.name, '', ach.changed_column, ach.old_value, ach.new_value, ach.change_datetimestamp, ach.changed_table, ach.changed_by "
+ "from sbrext.ac_change_history_ext ach, " + _DBMAP3[type_]._table + " zz, ";
// If registration status is not used we only need to add the context
// table.
String reg_clause;
if (rstatus_ == null || rstatus_.length == 0)
{
select = select + "sbr.contexts_view c ";
reg_clause = "";
}
// If registration status is used we need to add the context and registration
// status tables.
else
{
select = select + "sbr.contexts_view c, sbr.ac_registrations_view ar ";
reg_clause = "AND ar.ac_idseq = zz." + prefix
+ "_idseq AND NVL(ar.registration_status, '(none)') IN " + selectIN(rstatus_);
}
// If workflow status is not used we need to be sure and use an empty
// string.
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
// If workflow status is used we need to qualify by the content of the list.
else
{
wfs_clause = "AND zz.asl_name IN " + selectIN(wstatus_);
}
// Building the 'where' clause should be done to keep all qualifications together, e.g.
// first qualify all for ACH then join to the primary table (ZZ) complete the qualifications
// then join to the context table.
// Build the start and end dates.
String start = "to_date('" + start_.toString().substring(0, 10) + "', 'yyyy/mm/dd')";
String end = "to_date('" + end_.toString().substring(0, 10) + "', 'yyyy/mm/dd')";
// Always checking the date range first.
if (idseq_ == null || idseq_.length() == 0)
select = select + "where ach.change_datetimestamp >= " + start + " and ach.change_datetimestamp < " + end + " ";
else
select = select + "where ach.ac_idseq = '" + idseq_ + "' ";
// If modifiers are provided be sure to get everything.
if (modifiers_ != null && modifiers_.length > 0 && modifiers_[0].charAt(0) != '(')
select = select + "AND ach.changed_by in " + selectIN(modifiers_);
// Now qualify by the record type of interest and join to the primary table.
select = select + whereACH(type_)
+ "AND zz." + prefix + "_idseq = ach.ac_idseq ";
// If creators are provided they must be qualified by the primary table not the change table.
if (creators_ != null && creators_.length > 0 && creators_[0].charAt(0) != '(')
select = select + "AND zz.created_by in " + selectIN(creators_);
// When looking for both create and modified dates no extra clause is needed. For create
// date only qualify against the primary table.
if (dates_ == _DATECONLY)
select = select + "AND zz.date_created >= " + start + " and zz.date_created < " + end + " ";
// For modify date only qualify the primary table. The actual date is not important because we
// qualified the records from the history table by date already.
else if (dates_ == _DATEMONLY)
select = select + "AND zz.date_modified is not NULL ";
// Put everything together including the join to the context table and the sort order clause.
return select + wfs_clause + reg_clause + "AND c.conte_idseq = zz.conte_idseq " + _orderbyACH;
}
/**
* Pull all Data Element Concepts changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectDEC(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_DEC,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Select the dependant data. In Oracle an "in" clause may have a maximum of
* 1000 items. If the array length (ids_) is greater than 1000 it is broken
* up into pieces. The result is that should an order by clause also appear,
* the end result may not be correct as the SQL had to be performed in
* multiple pieces.
*
* @param select_
* The SQL select.
* @param ids_
* The array holding the id's for the query.
* @return The ACData array of the results.
*/
private ACData[] selectAC(String select_, ACData ids_[])
{
if (ids_ == null || ids_.length == 0)
return new ACData[0];
// Oracle limit on "in" clauses.
int limit = 1000;
if (ids_.length < limit)
return selectAC2(select_, ids_);
// When more than 1000 we have to break up the list
// and merge the results together.
ACData results[] = new ACData[0];
int group = limit;
int indx = 0;
while (indx < ids_.length)
{
ACData tset[] = new ACData[group];
System.arraycopy(ids_, indx, tset, 0, group);
indx += group;
ACData rset[] = selectAC2(select_, tset);
tset = results;
results = new ACData[tset.length + rset.length];
// Now that we have a place to store the composite
// list perform a simple merge as both are already
// sorted.
int tndx = 0;
int rndx = 0;
int ndx = 0;
if (tset.length > 0 && rset.length > 0)
{
while (ndx < results.length)
{
if (tset[tndx].compareUsingIDS(rset[rndx]) <= 0)
{
results[ndx++] = tset[tndx++];
if (tndx == tset.length)
break;
}
else
{
results[ndx++] = rset[rndx++];
if (rndx == rset.length)
break;
}
}
}
// We've exhausted the 'temp' list so copy the rest of the
// 'rc' list.
if (tndx == tset.length)
System.arraycopy(rset, rndx, results, ndx, rset.length - rndx);
// We've exhausted the 'rc' list so copy the rest of the
// 'temp' list.
else
System.arraycopy(tset, tndx, results, ndx, tset.length - tndx);
// Do next group.
tndx = ids_.length - indx;
if (group > tndx)
group = tndx;
// Force conservation of memory.
tset = null;
rset = null;
}
return results;
}
/**
* Select the dependant data. This method does not test the length of the
* array (ids_) and therefore should only be called when 1000 ids or less
* are needed.
*
* @param select_
* The SQL containing the "in" clause.
* @param ids_
* The id values to be bound.
* @return The result of the query.
*/
private ACData[] selectAC2(String select_, ACData ids_[])
{
String markers = expandMarkers(ids_.length);
// Split the string based on "?" markers.
String parts[] = select_.split("\\?");
String select = null;
if (parts.length == 2)
{
select = parts[0] + markers + parts[1];
}
else if (parts.length == 3)
{
select = parts[0] + markers + parts[1] + markers + parts[2];
}
else
{
// Only needed during development.
_logger.error("DEVELOPMENT ERROR 1: ==>\n" + select_
+ "\n<== unexpected SQL form.");
return null;
}
try
{
// Build, bind and execute the statement.
PreparedStatement pstmt = _conn.prepareStatement(select);
int cnt = 1;
for (int ndx = 0; ndx < ids_.length; ++ndx)
{
pstmt.setString(cnt++, ids_[ndx].getIDseq());
}
if (parts.length == 3)
{
for (int ndx = 0; ndx < ids_.length; ++ndx)
{
pstmt.setString(cnt++, ids_[ndx].getIDseq());
}
}
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Find the Value Domains that are affected by changes to the Permissible
* Values.
*
* @param pv_
* The list of permissible values identified as changed or created.
* @return The array of value domains.
*/
public ACData[] selectVDfromPV(ACData pv_[])
{
String select = "(select 's', 1, 'vd', vd.vd_idseq as id, vd.version, vd.vd_id, vd.long_name, vd.conte_idseq as cid, "
+ "vd.date_modified, vd.date_created, vd.modified_by, vd.created_by, vd.change_note, c.name, pv.pv_idseq "
+ "from sbr.value_domains_view vd, sbr.vd_pvs_view vp, sbr.permissible_values_view pv, sbr.contexts_view c "
+ "where pv.pv_idseq in (?) and vp.pv_idseq = pv.pv_idseq and vd.vd_idseq = vp.vd_idseq and "
+ "c.conte_idseq = vd.conte_idseq "
+ "union "
+ "select 's', 1, 'vd', ac.ac_idseq as id, ac.version, xx.vd_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, pv.pv_idseq "
+ "from sbr.permissible_values_view pv, sbr.vd_pvs_view vp, sbr.value_domains_view xx, "
+ "sbr.admin_components_view ac, sbr.designations_view dv, sbr.contexts_view c "
+ "where pv.pv_idseq in (?) and vp.pv_idseq = pv.pv_idseq and xx.vd_idseq = vp.vd_idseq "
+ "and ac.ac_idseq = xx.vd_idseq and ac.actl_name = 'VALUEDOMAIN' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, pv_);
}
/**
* Find the Permissible Values that are affected by changes to the Value Meanings.
*
* @param vm_
* The list of value meanings identified as changed or created.
* @return The array of value domains.
*/
public ACData[] selectPVfromVM(ACData vm_[])
{
String select = "select 's', 1, 'pv', pv.pv_idseq as id, '', -1, pv.value, '', "
+ "pv.date_modified, pv.date_created, pv.modified_by, pv.created_by, '', '', vm.short_meaning "
+ "from sbr.permissible_values_view pv, sbr.value_meanings_view vm "
+ "where vm.short_meaning in (?) and pv.short_meaning = vm.short_meaning ";
return selectAC(select, vm_);
}
/**
* Find the Conceptual Domains affected by changes to the Value Domains
* provided.
*
* @param vd_
* The list of value domains.
* @return The array of conceptual domains.
*/
public ACData[] selectCDfromVD(ACData vd_[])
{
String select = "(select 's', 1, 'cd', cd.cd_idseq as id, cd.version, cd.cd_id, cd.long_name, cd.conte_idseq as cid, "
+ "cd.date_modified, cd.date_created, cd.modified_by, cd.created_by, cd.change_note, c.name, vd.vd_idseq "
+ "from sbr.conceptual_domains_view cd, sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and cd.cd_idseq = vd.cd_idseq and c.conte_idseq = cd.conte_idseq "
+ "union "
+ "select 's', 1, 'cd', ac.ac_idseq as id, ac.version, xx.cd_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, vd.vd_idseq "
+ "from sbr.admin_components_view ac, sbr.conceptual_domains_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and xx.cd_idseq = vd.cd_idseq and ac.ac_idseq = xx.cd_idseq and "
+ "ac.actl_name = 'CONCEPTUALDOMAIN' and dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, vd_);
}
/**
* Find the Conceptual Domains affected by changes to the Data Element Concepts
* provided.
*
* @param dec_
* The list of data element concepts.
* @return The array of conceptual domains.
*/
public ACData[] selectCDfromDEC(ACData dec_[])
{
String select = "(select 's', 1, 'cd', cd.cd_idseq as id, cd.version, cd.cd_id, cd.long_name, cd.conte_idseq as cid, "
+ "cd.date_modified, cd.date_created, cd.modified_by, cd.created_by, cd.change_note, c.name, dec.dec_idseq "
+ "from sbr.conceptual_domains_view cd, sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and cd.cd_idseq = dec.dec_idseq and c.conte_idseq = cd.conte_idseq "
+ "union "
+ "select 's', 1, 'cd', ac.ac_idseq as id, ac.version, xx.cd_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, dec.dec_idseq "
+ "from sbr.admin_components_view ac, sbr.conceptual_domains_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and xx.cd_idseq = dec.cd_idseq and ac.ac_idseq = xx.cd_idseq and "
+ "ac.actl_name = 'CONCEPTUALDOMAIN' and dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, dec_);
}
/**
* Select the Data Elements affected by the Value Domains provided.
*
* @param vd_
* The value domain list.
* @return The array of related data elements.
*/
public ACData[] selectDEfromVD(ACData vd_[])
{
String select = "(select 's', 1, 'de', de.de_idseq as id, de.version, de.cde_id, de.long_name, de.conte_idseq as cid, "
+ "de.date_modified, de.date_created, de.modified_by, de.created_by, de.change_note, c.name, vd.vd_idseq "
+ "from sbr.data_elements_view de, sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and de.vd_idseq = vd.vd_idseq and c.conte_idseq = de.conte_idseq "
+ "union "
+ "select 's', 1, 'de', ac.ac_idseq as id, ac.version, xx.cde_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, vd.vd_idseq "
+ "from sbr.admin_components_view ac, sbr.data_elements_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and xx.vd_idseq = vd.vd_idseq and xx.de_idseq = ac.ac_idseq and ac.actl_name = 'DATAELEMENT' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, vd_);
}
/**
* Select the Data Element Concepts affected by the Properties provided.
*
* @param prop_
* The property list.
* @return The array of related data element concepts.
*/
public ACData[] selectDECfromPROP(ACData prop_[])
{
String select = "(select 's', 1, 'dec', dec.dec_idseq as id, dec.version, dec.dec_id, dec.long_name, dec.conte_idseq as cid, "
+ "dec.date_modified, dec.date_created, dec.modified_by, dec.created_by, dec.change_note, c.name, prop.prop_idseq "
+ "from sbr.data_element_concepts_view dec, sbr.contexts_view c, sbrext.properties_view_ext prop "
+ "where prop.prop_idseq in (?) and dec.prop_idseq = prop.prop_idseq and c.conte_idseq = dec.conte_idseq "
+ "union "
+ "select 's', 1, 'dec', ac.ac_idseq as id, ac.version, xx.dec_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, prop.prop_idseq "
+ "from sbr.admin_components_view ac, sbr.data_element_concepts_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbrext.properties_view_ext prop "
+ "where prop.prop_idseq in (?) and xx.prop_idseq = prop.prop_idseq and xx.dec_idseq = ac.ac_idseq and ac.actl_name = 'DE_CONCEPT' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, prop_);
}
/**
* Select the Properties affected by the Concepts provided.
*
* @param con_
* The concept list.
* @return The array of related properties.
*/
public ACData[] selectPROPfromCON(ACData con_[])
{
String select = "select 's', 1, 'prop', prop.prop_idseq as id, prop.version, prop.prop_id, prop.long_name, prop.conte_idseq as cid, "
+ "prop.date_modified, prop.date_created, prop.modified_by, prop.created_by, prop.change_note, c.name, con.con_idseq "
+ "from sbrext.properties_view_ext prop, sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext con, sbr.contexts_view c "
+ "where con.con_idseq in (?) and ccv.con_idseq = con.con_idseq and prop.condr_idseq = ccv.condr_idseq and c.conte_idseq = prop.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, con_);
}
/**
* Select the Object Classes affected by the Concepts provided.
*
* @param con_
* The concept list.
* @return The array of related object classes.
*/
public ACData[] selectOCfromCON(ACData con_[])
{
String select = "select 's', 1, 'oc', oc.oc_idseq as id, oc.version, oc.oc_id, oc.long_name, oc.conte_idseq as cid, "
+ "oc.date_modified, oc.date_created, oc.modified_by, oc.created_by, oc.change_note, c.name, con.con_idseq "
+ "from sbrext.object_classes_view_ext oc, sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext con, sbr.contexts_view c "
+ "where con.con_idseq in (?) and ccv.con_idseq = con.con_idseq and oc.condr_idseq = ccv.condr_idseq and c.conte_idseq = oc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, con_);
}
/**
* Select the Data Element Concepts affected by the Object Classes provided.
*
* @param oc_
* The object class list.
* @return The array of related data element concepts.
*/
public ACData[] selectDECfromOC(ACData oc_[])
{
String select = "(select 's', 1, 'dec', dec.dec_idseq as id, dec.version, dec.dec_id, dec.long_name, dec.conte_idseq as cid, "
+ "dec.date_modified, dec.date_created, dec.modified_by, dec.created_by, dec.change_note, c.name, oc.oc_idseq "
+ "from sbr.data_element_concepts_view dec, sbr.contexts_view c, sbrext.object_classes_view_ext oc "
+ "where oc.oc_idseq in (?) and dec.oc_idseq = oc.oc_idseq and c.conte_idseq = dec.conte_idseq "
+ "union "
+ "select 's', 1, 'dec', ac.ac_idseq as id, ac.version, xx.dec_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, oc.oc_idseq "
+ "from sbr.admin_components_view ac, sbr.data_element_concepts_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbrext.object_classes_view_ext oc "
+ "where oc.oc_idseq in (?) and xx.oc_idseq = oc.oc_idseq and xx.dec_idseq = ac.ac_idseq and ac.actl_name = 'DE_CONCEPT' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, oc_);
}
/**
* Select the Data Elements affected by the Data Element Concepts provided.
*
* @param dec_
* The data element concepts list.
* @return The array of related data elements.
*/
public ACData[] selectDEfromDEC(ACData dec_[])
{
String select = "(select 's', 1, 'de', de.de_idseq as id, de.version, de.cde_id, de.long_name, de.conte_idseq as cid, "
+ "de.date_modified, de.date_created, de.modified_by, de.created_by, de.change_note, c.name, dec.dec_idseq "
+ "from sbr.data_elements_view de, sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and de.dec_idseq = dec.dec_idseq and c.conte_idseq = de.conte_idseq "
+ "union "
+ "select 's', 1, 'de', ac.ac_idseq as id, ac.version, xx.cde_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, dec.dec_idseq "
+ "from sbr.admin_components_view ac, sbr.data_elements_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and xx.dec_idseq = dec.dec_idseq and xx.de_idseq = ac.ac_idseq and ac.actl_name = 'DATAELEMENT' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, dec_);
}
/**
* Select the Classification Scheme Item affected by the Data Elements
* provided.
*
* @param de_
* The data element list.
* @return The array of related classification scheme items.
*/
public ACData[] selectCSIfromDE(ACData de_[])
{
String select = "select 's', 1, 'csi', civ.csi_idseq as id, '', -1, civ.csi_name, '', "
+ "civ.date_modified, civ.date_created, civ.modified_by, civ.created_by, civ.comments, '', de.de_idseq "
+ "from sbr.class_scheme_items_view civ, sbr.data_elements_view de, sbr.admin_components_view ac, "
+ "sbr.ac_csi_view ai, sbr.cs_csi_view ci "
+ "where de.de_idseq in (?) and ac.ac_idseq = de.de_idseq and ai.ac_idseq = ac.ac_idseq and "
+ "ci.cs_csi_idseq = ai.cs_csi_idseq and civ.csi_idseq = ci.csi_idseq "
+ "order by id asc";
return selectAC(select, de_);
}
/**
* Select the Classification Scheme Item affected by the Data Element Concepts
* provided.
*
* @param dec_
* The data element concept list.
* @return The array of related classification scheme items.
*/
public ACData[] selectCSIfromDEC(ACData dec_[])
{
String select = "select 's', 1, 'csi', civ.csi_idseq as id, '', -1, civ.csi_name, '', "
+ "civ.date_modified, civ.date_created, civ.modified_by, civ.created_by, civ.comments, '', dec.dec_idseq "
+ "from sbr.class_scheme_items_view civ, sbr.data_element_concepts_view dec, sbr.admin_components_view ac, "
+ "sbr.ac_csi_view ai, sbr.cs_csi_view ci "
+ "where dec.dec_idseq in (?) and ac.ac_idseq = dec.dec_idseq and ai.ac_idseq = ac.ac_idseq and "
+ "ci.cs_csi_idseq = ai.cs_csi_idseq and civ.csi_idseq = ci.csi_idseq "
+ "order by id asc";
return selectAC(select, dec_);
}
/**
* Select the Classification Scheme Item affected by the Value Domains
* provided.
*
* @param vd_
* The value domain list.
* @return The array of related classification scheme items.
*/
public ACData[] selectCSIfromVD(ACData vd_[])
{
String select = "select 's', 1, 'csi', civ.csi_idseq as id, '', -1, civ.csi_name, '', "
+ "civ.date_modified, civ.date_created, civ.modified_by, civ.created_by, civ.comments, '', vd.vd_idseq "
+ "from sbr.class_scheme_items_view civ, sbr.value_domains_view vd, sbr.admin_components_view ac, "
+ "sbr.ac_csi_view ai, sbr.cs_csi_view ci "
+ "where vd.vd_idseq in (?) and ac.ac_idseq = vd.vd_idseq and ai.ac_idseq = ac.ac_idseq and "
+ "ci.cs_csi_idseq = ai.cs_csi_idseq and civ.csi_idseq = ci.csi_idseq "
+ "order by id asc";
return selectAC(select, vd_);
}
/**
* Select the Forms/Templates affected by the Data Elements provided.
*
* @param de_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCQfromDE(ACData de_[])
{
String select = "select 's', 1, 'qcq', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, de.de_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbr.data_elements_view de, sbr.contexts_view c "
+ "where de.de_idseq in (?) and qc.de_idseq = de.de_idseq and qc.qtl_name in ('QUESTION', 'QUESTION_INSTR') and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, de_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param vd_
* The value domain list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCQfromVD(ACData vd_[])
{
String select = "select 's', 1, 'qcq', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, vd.vd_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbr.value_domains_view vd, sbr.contexts_view c "
+ "where vd.vd_idseq in (?) and qc.dn_vd_idseq = vd.vd_idseq and qc.qtl_name in ('QUESTION', 'QUESTION_INSTR') and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, vd_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param vd_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCVfromVD(ACData vd_[])
{
String select = "select 's', 1, 'qcv', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, vd.vd_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbr.value_domains_view vd, sbr.vd_pvs_view vp, sbr.contexts_view c "
+ "where vd.vd_idseq in (?) and vp.vd_idseq = vd.vd_idseq and qc.vp_idseq = vp.vp_idseq and "
+ "qc.qtl_name = 'VALID_VALUE' and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, vd_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param qcv_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCQfromQCV(ACData qcv_[])
{
String select = "select 's', 1, 'qcq', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, qc2.qc_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbrext.quest_contents_view_ext qc2, sbr.contexts_view c "
+ "where qc2.qc_idseq in (?) and qc2.qtl_name = 'VALID_VALUE' and qc.qc_idseq = qc2.p_qst_idseq and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, qcv_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param qcq_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCMfromQCQ(ACData qcq_[])
{
String select = "select 's', 1, 'qcm', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, qc2.qc_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbrext.quest_contents_view_ext qc2, sbr.contexts_view c "
+ "where qc2.qc_idseq in (?) and qc2.qtl_name in ('QUESTION', 'QUESTION_INSTR') and qc.qc_idseq = qc2.p_mod_idseq and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, qcq_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param qcm_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCfromQCM(ACData qcm_[])
{
String select = "select 's', 1, 'qc', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, qc2.qc_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbrext.quest_contents_view_ext qc2, sbr.contexts_view c "
+ "where qc2.qc_idseq in (?) and qc2.qtl_name = 'MODULE' and qc.qc_idseq = qc2.dn_crf_idseq and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, qcm_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param qcq_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCfromQCQ(ACData qcq_[])
{
String select = "select 's', 1, 'qc', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, qc2.qc_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbrext.quest_contents_view_ext qc2, sbr.contexts_view c "
+ "where qc2.qc_idseq in (?) and qc2.qtl_name in ('QUESTION', 'QUESTION_INSTR') and qc2.p_mod_idseq is null and "
+ "qc.qc_idseq = qc2.dn_crf_idseq and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, qcq_);
}
/**
* Select the Classification Schemes affected by the Classification Scheme
* Items provided.
*
* @param csi_
* The classification scheme items list.
* @return The array of related classification schemes.
*/
public ACData[] selectCSfromCSI(ACData csi_[])
{
String select = "(select 's', 1, 'cs', cs.cs_idseq as id, cs.version, cs.cs_id, cs.long_name, cs.conte_idseq as cid, "
+ "cs.date_modified, cs.date_created, cs.modified_by, cs.created_by, cs.change_note, c.name, civ.csi_idseq "
+ "from sbr.classification_schemes_view cs, sbr.contexts_view c, sbr.cs_csi_view ci, "
+ "sbr.class_scheme_items_view civ "
+ "where civ.csi_idseq in (?) and ci.csi_idseq = civ.csi_idseq and cs.cs_idseq = ci.cs_idseq and "
+ "c.conte_idseq = cs.conte_idseq "
+ "union "
+ "select 's', 1, 'cs', ac.ac_idseq as id, ac.version, xx.cs_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, civ.csi_idseq "
+ "from sbr.admin_components_view ac, sbr.classification_schemes_view xx, sbr.cs_csi_view ci, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.class_scheme_items_view civ "
+ "where civ.csi_idseq in (?) and ci.csi_idseq = civ.csi_idseq and xx.cs_idseq = ci.cs_idseq and "
+ "ac.ac_idseq = xx.cs_idseq and ac.actl_name = 'CLASSIFICATION' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, csi_);
}
/**
* Select the Contexts affected by the Classification Schemes provided.
*
* @param cs_
* The classification schemes list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromCS(ACData cs_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', cs.cs_idseq "
+ "from sbr.contexts_view c, sbr.classification_schemes_view cs "
+ "where cs.cs_idseq in (?) and c.conte_idseq = cs.conte_idseq "
+ "order by id asc";
return selectAC(select, cs_);
}
/**
* Select the Contexts affected by the Conceptual Domains provided.
*
* @param cd_
* The conceptual domains list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromCD(ACData cd_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', cd.cd_idseq "
+ "from sbr.contexts_view c, sbr.conceptual_domains_view cd "
+ "where cd.cd_idseq in (?) and c.conte_idseq = cd.conte_idseq "
+ "order by id asc";
return selectAC(select, cd_);
}
/**
* Select the Contexts affected by the Value Domains provided.
*
* @param vd_
* The value domains list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromVD(ACData vd_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', vd.vd_idseq "
+ "from sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and c.conte_idseq = vd.conte_idseq "
+ "order by id asc";
return selectAC(select, vd_);
}
/**
* Select the Contexts affected by the Data Elements provided.
*
* @param de_
* The data elements list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromDE(ACData de_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', de.de_idseq "
+ "from sbr.contexts_view c, sbr.data_elements_view de "
+ "where de.de_idseq in (?) and c.conte_idseq = de.conte_idseq "
+ "order by id asc";
return selectAC(select, de_);
}
/**
* Select the Contexts affected by the Properties provided.
*
* @param prop_
* The properties list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromPROP(ACData prop_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', prop.prop_idseq "
+ "from sbr.contexts_view c, sbrext.properties_view_ext prop "
+ "where prop.prop_idseq in (?) and c.conte_idseq = prop.conte_idseq "
+ "order by id asc";
return selectAC(select, prop_);
}
/**
* Select the Contexts affected by the Object Classes provided.
*
* @param oc_
* The object class list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromOC(ACData oc_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', oc.oc_idseq "
+ "from sbr.contexts_view c, sbrext.object_classes_view_ext oc "
+ "where oc.oc_idseq in (?) and c.conte_idseq = oc.conte_idseq "
+ "order by id asc";
return selectAC(select, oc_);
}
/**
* Select the Contexts affected by the Concepts provided.
*
* @param con_
* The object class list.
* @return The array of related concepts.
*/
public ACData[] selectCONTEfromCON(ACData con_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', con.con_idseq "
+ "from sbr.contexts_view c, sbrext.concepts_view_ext con "
+ "where con.con_idseq in (?) and c.conte_idseq = con.conte_idseq "
+ "order by id asc";
return selectAC(select, con_);
}
/**
* Select the Contexts affected by the Protocols provided.
*
* @param proto_
* The protocols list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromPROTO(ACData proto_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', proto.proto_idseq "
+ "from sbr.contexts_view c, sbrext.protocols_view_ext proto "
+ "where proto.proto_idseq in (?) and c.conte_idseq = proto.conte_idseq "
+ "order by id asc";
return selectAC(select, proto_);
}
/**
* Select the Protocols affected by the Forms/Templates provided.
*
* @param qc_
* The forms/templates list.
* @return The array of related contexts.
*/
public ACData[] selectPROTOfromQC(ACData qc_[])
{
String select = "select 's', 1, 'proto', proto.proto_idseq as id, proto.version, proto.proto_id, proto.long_name, c.conte_idseq, "
+ "proto.date_modified, proto.date_created, proto.modified_by, proto.created_by, proto.change_note, c.name, qc.qc_idseq "
+ "from sbr.contexts_view c, sbrext.protocols_view_ext proto, sbrext.protocol_qc_ext pq, sbrext.quest_contents_view_ext qc "
+ "where qc.qc_idseq in (?) "
+ "and pq.qc_idseq = qc.qc_idseq "
+ "and proto.proto_idseq = pq.proto_idseq "
+ "and c.conte_idseq = proto.conte_idseq "
+ "order by id asc";
return selectAC(select, qc_);
}
/**
* Select the Contexts affected by the Forms/Templates provided.
*
* @param qc_
* The forms/templates list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromQC(ACData qc_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', qc.qc_idseq "
+ "from sbr.contexts_view c, sbrext.quest_contents_view_ext qc "
+ "where qc.qc_idseq in (?) and c.conte_idseq = qc.conte_idseq "
+ "order by id asc";
return selectAC(select, qc_);
}
/**
* Select the Contexts affected by the Data Element Concepts provided.
*
* @param dec_
* The data element concepts list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromDEC(ACData dec_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', dec.dec_idseq "
+ "from sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and c.conte_idseq = dec.conte_idseq "
+ "order by id asc";
return selectAC(select, dec_);
}
/**
* For performance reasons as "names" are the most common data required, a
* cache is created to avoid hitting the database with too many individual
* requests. This cache is good for the life of this DBAlert object and will
* be rebuilt as needed with each new DBAlert.
*
* @param id_
* The name id to look up in the database.
* @return When > 0, the position of the name in the cache. When < 0, the
* position it should be in the cache when added later.
*/
private int findName(String id_)
{
int min = 0;
int max = _nameID.length;
// Use a binary search. It seems the most efficient for this purpose.
while (true)
{
int ndx = (max + min) / 2;
int compare = id_.compareTo(_nameID[ndx]);
if (compare == 0)
{
return ndx;
}
else if (compare > 0)
{
if (min == ndx)
{
++min;
return -min;
}
min = ndx;
}
else
{
if (max == ndx)
return -max;
max = ndx;
}
}
}
/**
* Cache names internally as they are encountered. If the findName() method
* can not locate a name in the cache it will be added by this method.
*
* @param pos_
* The insert position returned from findName().
* @param id_
* The name id to use as a key.
* @param name_
* The name to return for this id.
*/
private void cacheName(int pos_, String id_, String name_)
{
// Don't save null names, use the id if needed.
if (name_ == null)
name_ = id_;
// Move all existing records down to make room for the new name.
String nid[] = new String[_nameID.length + 1];
String ntxt[] = new String[nid.length];
int ndx;
int ndx2 = 0;
for (ndx = 0; ndx < pos_; ++ndx)
{
nid[ndx] = _nameID[ndx2];
ntxt[ndx] = _nameText[ndx2++];
}
// Add the new name.
nid[ndx] = new String(id_);
ntxt[ndx] = new String(name_);
// Copy the rest and reset the arrays.
for (++ndx; ndx < nid.length; ++ndx)
{
nid[ndx] = _nameID[ndx2];
ntxt[ndx] = _nameText[ndx2++];
}
_nameID = nid;
_nameText = ntxt;
}
/**
* Retrieve a string name representation for the "object" id provided.
*
* @param table_
* The known database table name or null if the method should use a
* default based on the col_ value.
* @param col_
* The column name which corresponds to the id_ provided.
* @param id_
* The id of the specific database record desired.
* @return The "name" from the record, this may correspond to the long_name,
* prefferred_name, etc database columns depending on the table
* being used.
*/
public String selectName(String table_, String col_, String id_)
{
// Can't work without a column name.
if (col_ == null)
return id_;
if (id_ == null || id_.length() == 0)
return null;
// Determine the real table and column names to use.
int npos = 0;
String table = table_;
String name = "long_name";
String col = col_;
String extra = "";
if (table == null || table.length() == 0)
{
int ndx = DBAlertUtil.binarySearch(_DBMAP2, col);
if (ndx == -1)
return id_;
table = _DBMAP2[ndx]._val;
name = _DBMAP2[ndx]._subs;
col = _DBMAP2[ndx]._col;
extra = _DBMAP2[ndx]._xtra;
if (col.equals("ua_name"))
{
// Is the name cached?
npos = findName(id_);
if (npos >= 0)
return _nameText[npos];
}
}
// Build a select and retrieve the "name".
String select = "select " + name + " from " + table + " where " + col
+ " = ?" + extra;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, id_);
ResultSet rs = pstmt.executeQuery();
name = "";
while (rs.next())
name = name + "\n" + rs.getString(1);
if (name.length() == 0)
name = null;
else
name = name.substring(1);
rs.close();
pstmt.close();
if (col.equals("ua_name") && npos < 0)
{
cacheName(-npos, id_, name);
}
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
name = "(*error*)";
}
return (name == null) ? id_ : name;
}
/**
* Retrieve the "names" for a list of columns and ids. WARNING this is a
* destructive method. It changes the content of ids_ by replacing the
* original value with the retrieved name.
*
* @param cols_
* The names of the columns corresponding to the ids.
* @param ids_
* On input the ids of the specific records to query. On return the
* names of the records if they could be determined.
*/
public void selectNames(String cols_[], String ids_[])
{
for (int ndx = 0; ndx < cols_.length; ++ndx)
{
ids_[ndx] = selectName(null, cols_[ndx], ids_[ndx]);
}
}
/**
* Update the Auto Run or Manual Run timestamp.
*
* @param id_
* The alert id to update.
* @param stamp_
* The new time.
* @param run_
* true to update the auto run time, false to update the manual run
* time
* @param setInactive_
* true to set the alert status to inactive, false to leave the
* status unchanged
* @return 0 if successful, otherwise the database error code.
*/
public int updateRun(String id_, Timestamp stamp_, boolean run_,
boolean setInactive_)
{
String update = "update sbrext.sn_alert_view_ext set "
+ ((run_) ? "last_auto_run" : "last_manual_run") + " = ?,"
+ ((setInactive_) ? " al_status = 'I', " : "")
+ "modified_by = ? where al_idseq = ?";
try
{
PreparedStatement pstmt = null;
// Set all the SQL arguments.
pstmt = _conn.prepareStatement(update);
pstmt.setTimestamp(1, stamp_);
pstmt.setString(2, _user);
pstmt.setString(3, id_);
pstmt.executeUpdate();
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + update
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Return the recipients names in ascending order by first name as a single
* string. If the recipient is a broadcast context group the group is expanded.
* Those who have elected not to receive broadcasts from a context group are
* not included. All freeform email addresses are listed after the names
* retrieved from the account table.
*
* @param recipients_ The Alert recipient list.
* @return A single comma separate list of names and email addresses with
* the broadcast context groups expanded.
*/
public String selectRecipientNames(String recipients_[])
{
// Check input.
if (recipients_ == null || recipients_.length == 0)
return "(none)";
// Break the recipients list apart.
String contexts = "";
String users = "";
String emails = "";
for (int ndx = 0; ndx < recipients_.length; ++ndx)
{
if (recipients_[ndx].charAt(0) == '/')
contexts = contexts + ", '" + recipients_[ndx].substring(1) + "'";
else if (recipients_[ndx].indexOf('@') < 0)
users = users + ", '" + recipients_[ndx] + "'";
else
emails = emails + ", " + recipients_[ndx];
}
// Build the select for user names
String select = "";
if (users.length() > 0)
select += "select ua.name as lname from sbr.user_accounts_view ua where ua.ua_name in ("
+ users.substring(2)
+ ") and ua.electronic_mail_address is not null ";
// Build the select for a Context group
if (contexts.length() > 0)
{
if (select.length() > 0)
select += "union ";
select += "select ua.name as lname from sbr.user_accounts_view ua, sbrext.user_contexts_view uc, sbr.contexts_view c where c.conte_idseq in ("
+ contexts.substring(2)
+ ") and uc.name = c.name and uc.privilege = 'W' and ua.ua_name = uc.ua_name and ua.alert_ind = 'Yes' and ua.electronic_mail_address is not null ";
}
String names = "";
if (select.length() > 0)
{
// Sort the results.
select = "select lname from (" + select + ") order by upper(lname) asc";
try
{
// Retrieve the user names from the database.
PreparedStatement pstmt = _conn.prepareStatement(select);
ResultSet rs = pstmt.executeQuery();
// Make this a comma separated list.
while (rs.next())
{
names += ", " + rs.getString(1);
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
// Append the freeform email addresses.
if (emails.length() > 0)
names += emails;
return (names.length() > 0) ? names.substring(2) : "(none)";
}
/**
* Given the idseq of a Context, retrieve all the users with write access to
* that context.
*
* @param conte_
* The context idseq.
* @return The array of user ids with write access.
*/
public String[] selectEmailsFromConte(String conte_)
{
String select = "select ua.electronic_mail_address "
+ "from sbrext.user_contexts_view uc, sbr.user_accounts_view ua, sbr.contexts_view c "
+ "where c.conte_idseq = ? and uc.name = c.name and uc.privilege = 'W' and ua.ua_name = uc.ua_name "
+ "and ua.alert_ind = 'Yes'";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
if (conte_.charAt(0) == '/')
pstmt.setString(1, conte_.substring(1));
else
pstmt.setString(1, conte_);
ResultSet rs = pstmt.executeQuery();
Vector<String> temp = new Vector<String>();
while (rs.next())
{
temp.add(rs.getString(1));
}
rs.close();
pstmt.close();
String curators[] = new String[temp.size()];
for (int ndx = 0; ndx < curators.length; ++ndx)
curators[ndx] = (String) temp.get(ndx);
return curators;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Given the id for a user, retrieve the email address.
*
* @param user_
* The user id.
* @return The array of user ids with write access.
*/
public String selectEmailFromUser(String user_)
{
String select = "select ua.electronic_mail_address "
+ "from sbr.user_accounts_view ua " + "where ua.ua_name = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, user_);
ResultSet rs = pstmt.executeQuery();
String temp = null;
if (rs.next())
{
temp = rs.getString(1);
}
rs.close();
pstmt.close();
return temp;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Run a specific SELECT for the testDBdependancies() method.
*
* @param select_
* The select statement.
* @return >0 if successful with the number of rows returned, otherwise
* failed.
*/
private int testDB(String select_)
{
try
{
PreparedStatement pstmt = _conn.prepareStatement(select_);
ResultSet rs = pstmt.executeQuery();
int rows;
for (rows = 0; rs.next(); ++rows)
;
rs.close();
pstmt.close();
return rows;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = select_ + "\n" + ex.toString();
return -1;
}
}
/**
* Run a specific SELECT for the testDBdependancies() method.
*
* @param select_
* The select statement.
* @return the first row found
*/
private String testDB2(String select_)
{
try
{
PreparedStatement pstmt = _conn.prepareStatement(select_);
ResultSet rs = pstmt.executeQuery();
String result = null;
int rows;
for (rows = 0; rs.next(); ++rows)
result = rs.getString(1);
rs.close();
pstmt.close();
return result;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = select_ + "\n" + ex.toString();
return null;
}
}
/**
* Test the database dependencies within this class. This method will check
* the existence of tables, columns and required values.
*
* @return null if all dependencies are present, otherwise a string
* detailing those that failed.
*/
public String testDBdependancies()
{
String results = "";
String select = "select ua_name, name, electronic_mail_address, alert_ind "
+ "from sbr.user_accounts_view "
+ "where (ua_name is null or name is null or alert_ind is null) and rownum < 2";
int rows = testDB(select);
if (rows != 0)
{
if (rows < 0)
results += _errorMsg;
else
results += "One of the columns ua_name, name or alert_ind in the table sbr.user_accounts_view is NULL";
results += "\n\n";
}
select = "select * from sbrext.sn_alert_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select * from sbrext.sn_query_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select * from sbrext.sn_recipient_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select * from sbrext.sn_report_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select ua_name, name, privilege from sbrext.user_contexts_view where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select tool_name, property, ua_name, value from sbrext.tool_options_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
_errorCode = 0;
_errorMsg = "";
return (results.length() == 0) ? null : results;
}
/**
* Test the content of the tool options table.
*
* @param url_ the URL used to access the Sentinel from a browser. If not null it is compared to the caDSR
* tool options entry to ensure they match.
* @return null if no errors, otherwise the error message.
*/
public String testSentinelOptions(String url_)
{
String results = "";
int rows;
AutoProcessData apd = new AutoProcessData();
apd.getOptions(this);
if (apd._adminEmail == null || apd._adminEmail.length == 0)
results += "Missing the Sentinel Tool Alert Administrators email address.\n\n";
if (apd._adminIntro == null || apd._adminIntro.length() == 0)
results += "Missing the Sentinel Tool email introduction.\n\n";
if (apd._adminIntroError == null || apd._adminIntroError.length() == 0)
results += "Missing the Sentinel Tool email error introduction.\n\n";
if (apd._adminName == null || apd._adminName.length() == 0)
results += "Missing the Sentinel Tool Alert Administrators email name.\n\n";
if (apd._dbname == null || apd._dbname.length() == 0)
results += "Missing the Sentinel Tool database name.\n\n";
if (apd._emailAddr == null || apd._emailAddr.length() == 0)
results += "Missing the Sentinel Tool email Reply To address.\n\n";
if (apd._emailHost == null || apd._emailHost.length() == 0)
results += "Missing the Sentinel Tool email host address.\n\n";
if (apd._emailUser != null && apd._emailUser.length() > 0)
{
if (apd._emailPswd == null || apd._emailPswd.length() == 0)
results += "Missing the Sentinel Tool email host account password.\n\n";
}
if (apd._http == null || apd._http.length() == 0)
results += "Missing the Sentinel Tool HTTP prefix.\n\n";
if (apd._subject == null || apd._subject.length() == 0)
results += "Missing the Sentinel Tool email subject.\n\n";
if (apd._work == null || apd._work.length() == 0)
results += "Missing the Sentinel Tool working folder prefix.\n\n";
String select = "select value from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' and property = 'URL' and value is not null";
select = testDB2(select);
if (select == null)
results += "Missing the Sentinel Tool URL setting.\n\n";
else if (url_ != null)
{
int pos = url_.indexOf('/', 8);
if (pos > 0)
url_ = url_.substring(0, pos);
if (url_.startsWith("http://localhost"))
;
else if (url_.startsWith("https://localhost"))
;
else if (select.startsWith(url_, 0))
;
else
results += "Sentinel Tool URL \"" + url_ + "\"does not match configuration value \"" + select + "\".\n\n";
}
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property LIKE 'ADMIN.%' and value like '%0%'";
rows = testDB(select);
if (rows < 1)
results += "Missing the Sentinel Tool Alert Administrator setting.\n\n";
select = "select value from sbrext.tool_options_view_ext where tool_name = 'caDSR' and property = 'RAI'";
rows = testDB(select);
if (rows != 1)
results += "Missing the caDSR RAI (Registration Authority Identifier).\n\n";
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property LIKE 'ADMIN.%' and value like '%1%'";
rows = testDB(select);
if (rows < 1)
results += "Missing the Sentinel Tool Report Administrator setting.\n\n";
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property = 'ALERT.NAME.FORMAT' and value is not null";
rows = testDB(select);
if (rows != 1)
results += "Missing the Sentinel Tool ALERT.NAME.FORMAT setting.\n\n";
if (selectAlertReportAdminEmails() == null)
results += "Missing email addresses for the specified Alert Report Administrator(s) setting.\n\n";
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property LIKE 'BROADCAST.EXCLUDE.CONTEXT.%.NAME'";
rows = testDB(select);
if (rows > 0)
{
int optcnt = rows;
select = "select cov.name "
+ "from sbrext.tool_options_view_ext to1, sbrext.tool_options_view_ext to2, sbr.contexts_view cov "
+ "where to1.tool_name = 'SENTINEL' AND to2.tool_name = to1.tool_name "
+ "and to1.property LIKE 'BROADCAST.EXCLUDE.CONTEXT.%.NAME' "
+ "and to2.property LIKE 'BROADCAST.EXCLUDE.CONTEXT.%.CONTE_IDSEQ' "
+ "and SUBSTR(to1.property, 1, 29) = SUBSTR(to2.property, 1, 29) "
+ "and to1.value = cov.name "
+ "and to2.value = cov.conte_idseq";
rows = testDB(select);
if (rows != optcnt)
results += "Missing or invalid BROADCAST.EXCLUDE.CONTEXT settings.\n\n";
}
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property like 'RSVD.CS.%'";
rows = testDB(select);
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property = 'RSVD.CSI.FORMAT' AND value like '%$ua_name$%'";
rows += testDB(select);
if (rows > 0)
{
if (rows == 3)
{
select = "select cs.long_name "
+ "from sbrext.tool_options_view_ext to1, sbrext.tool_options_view_ext to2, sbr.classification_schemes_view cs "
+ "where to1.tool_name = 'SENTINEL' AND to2.tool_name = to1.tool_name "
+ "and to1.property = 'RSVD.CS.LONG_NAME' "
+ "and to2.property = 'RSVD.CS.CS_IDSEQ' "
+ "and to1.value = cs.long_name "
+ "and to2.value = cs.cs_idseq";
rows = testDB(select);
if (rows != 1)
results += "Missing or invalid RSVD.CS settings.\n\n";
}
else
results += "Missing or invalid RSVD.CS settings.\n\n";
}
_errorCode = 0;
_errorMsg = "";
return (results.length() == 0) ? null : results;
}
/**
* Return the email addresses for all the administrators that should receive a log report.
*
* @return The list of email addresses.
*/
public String[] selectAlertReportAdminEmails()
{
String select = "select ua.electronic_mail_address "
+ "from sbr.user_accounts_view ua, sbrext.tool_options_view_ext opt "
+ "where opt.tool_name = 'SENTINEL' and "
+ "opt.property like 'ADMIN.%' and "
+ "opt.value like '%1%' and ua.ua_name = opt.ua_name "
+ "and ua.electronic_mail_address is not null "
+ "order by opt.property";
String[] list = getBasicData0(select);
if (list != null)
return list;
// Fall back to the default.
select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.ADDR'";
return getBasicData0(select);
}
/**
* Return the Alert Report email reply to address
*
* @return The reply to address.
*/
public String selectAlertReportEmailAddr()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.ADDR'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email introduction for the Alert Report
*
* @return The introduction.
*/
public String selectAlertReportEmailIntro()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.INTRO'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email error introduction for the Alert Report
*
* @return The error introduction.
*/
public String selectAlertReportEmailError()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.ERROR'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email admin title which appears in the "From:" field.
*
* @return The admin title.
*/
public String selectAlertReportAdminTitle()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.ADMIN.NAME'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email SMTP host.
*
* @return The email SMTP host.
*/
public String selectAlertReportEmailHost()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.HOST'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email SMTP host user account.
*
* @return The email SMTP host user account.
*/
public String selectAlertReportEmailHostUser()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.HOST.USER'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email SMTP host user account password.
*
* @return The email SMTP host user account password.
*/
public String selectAlertReportEmailHostPswd()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.HOST.PSWD'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email subject.
*
* @return The email subject.
*/
public String selectAlertReportEmailSubject()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.SUBJECT'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the HTTP link prefix for all report output references.
*
* @return The HTTP link prefix
*/
public String selectAlertReportHTTP()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'URL'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] + "/AlertReports/" : "";
}
/**
* Return the HTTP link prefix for all Sentinel DTD files.
*
* @return The HTTP link prefix
*/
public String selectDtdHTTP()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'URL'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] + "/dtd/" : "";
}
/**
* Return the output directory for all generated files.
*
* @return The output directory prefix
*/
public String selectAlertReportOutputDir()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'OUTPUT.DIR'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the database name as it should appear on reports.
*
* @return The database name
*/
public String selectAlertReportDBName()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'DB.NAME'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email addresses for all the recipients of the statistic report.
*
* @return The list of email addresses.
*/
public String[] selectStatReportEmails()
{
String select = "select ua.electronic_mail_address "
+ "from sbr.user_accounts_view ua, sbrext.tool_options_view_ext opt "
+ "where opt.tool_name = 'SENTINEL' and "
+ "opt.property like 'ADMIN.%' and "
+ "opt.value like '%2%' and ua.ua_name = opt.ua_name "
+ "and ua.electronic_mail_address is not null "
+ "order by opt.property";
return getBasicData0(select);
}
/**
* Return the EVS URL from the tool options.
*
* @return The EVS URL.
*/
public String selectEvsUrl()
{
String select = "select value from sbrext.tool_options_view_ext where tool_name = 'EVS' and property = 'URL'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : null;
}
/**
* Return the Alert Definition name format string.
*
* @return The list of email addresses.
*/
public String selectAlertNameFormat()
{
String select = "select opt.value "
+ "from sbrext.tool_options_view_ext opt "
+ "where opt.tool_name = 'SENTINEL' and "
+ "opt.property = 'ALERT.NAME.FORMAT' ";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : null;
}
/**
* Return the reserved CS id if the reserved CSI is passed to the method.
*
* @param idseq_ The CSI id to check.
*
* @return The reserved CS id or null if the CSI is not reserved.
*/
public String selectCSfromReservedCSI(String idseq_)
{
String select = "select opt.value "
+ "from sbrext.tool_options_view_ext opt, sbr.classification_schemes_view cs, "
+ "sbr.cs_csi_view ci "
+ "where ci.csi_idseq = '" + idseq_ + "' and cs.cs_idseq = ci.cs_idseq and opt.value = cs.cs_idseq and "
+ "opt.tool_name = 'SENTINEL' and opt.property = 'RSVD.CS.CS_IDSEQ'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : null;
}
/**
* Format the integer to include comma thousand separators.
*
* @param val_ The number in string format.
* @return the number in string format with separators.
*/
private String formatInt(String val_)
{
int loop = val_.length() / 3;
int start = val_.length() % 3;
String text = val_.substring(0, start);
for (int i = 0; i < loop; ++i)
{
text = text + "," + val_.substring(start, start + 3);
start += 3;
}
return (text.charAt(0) == ',') ? text.substring(1) : text;
}
/**
* Retrieve the row counts for all the tables used by the Alert Report.
* The values may be indexed using the _ACTYPE_* variables and an index
* of _ACTYPE_LENGTH is the count of the change history table.
*
* @return The numbers for each table.
*/
public String[] reportRowCounts()
{
String[] extraTables = {"sbrext.ac_change_history_ext", "sbrext.gs_tokens", "sbrext.gs_composite" };
String[] extraNames = {"History Table", "Freestyle Token Index", "Freestyle Concatenation Index" };
int total = _DBMAP3.length + extraTables.length;
String counts[] = new String[total];
String select = "select count(*) from ";
String table;
String name;
int extraNdx = 0;
for (int ndx = 0; ndx < counts.length; ++ndx)
{
if (ndx >= _DBMAP3.length)
{
table = extraTables[extraNdx];
name = extraNames[extraNdx];
++extraNdx;
}
else if (_DBMAP3[ndx]._table == null)
{
counts[ndx] = null;
continue;
}
else
{
table = _DBMAP3[ndx]._table;
name = _DBMAP3[ndx]._val;
}
String temp = select + table;
try
{
PreparedStatement pstmt = _conn.prepareStatement(temp);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
counts[ndx] = name + AuditReport._ColSeparator + formatInt(rs.getString(1));
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = temp + "\n" + ex.toString();
counts[ndx] = name + ": " + _errorMsg;
}
}
return counts;
}
/**
* Translate the internal column names to something the user can easily
* read.
*
* @param namespace_
* The scope of the namespace to lookup the val_.
* @param val_
* The internal column name.
* @return The translated value.
*/
public String translateColumn(String namespace_, String val_)
{
// First search global name space as most are consistent.
String rc = DBAlertUtil.binarySearchS(_DBMAP1, val_);
if (rc == val_)
{
// We didn't find it in global now look in the specific name space.
if (namespace_.compareTo("DESIGNATIONS") == 0)
rc = DBAlertUtil.binarySearchS(_DBMAP1DESIG, val_);
else if (namespace_.compareTo("REFERENCE_DOCUMENTS") == 0)
rc = DBAlertUtil.binarySearchS(_DBMAP1RD, val_);
else if (namespace_.compareTo("AC_CSI") == 0)
rc = DBAlertUtil.binarySearchS(_DBMAP1CSI, val_);
else if (namespace_.compareTo("COMPLEX_DATA_ELEMENTS") == 0)
rc = DBAlertUtil.binarySearchS(_DBMAP1COMPLEX, val_);
else
rc = DBAlertUtil.binarySearchS(_DBMAP1OTHER, val_);
return rc;
}
return rc;
}
/**
* Translate the table names for the user.
*
* @param val_
* The internal table name.
* @return The user readable name.
*/
public String translateTable(String val_)
{
if (val_ == null)
return "<null>";
return DBAlertUtil.binarySearchS(_DBMAP3, val_);
}
/**
* Look for the selection of a specific record type.
*
* @param val_ The AC type code.
* @return false if the record type is not found.
*/
public int isACTypeUsed(String val_)
{
return DBAlertUtil.binarySearch(_DBMAP3, val_);
}
/**
* Test if the string table code represents the record type of interest.
*
* @param type_ One of the DBAlert._ACTYPE* constants.
* @param tableCode_ The string type to test.
* @return true if the type and string are equivalent.
*/
public boolean isACType(int type_, String tableCode_)
{
return tableCode_.equals(_DBMAP3[type_]._key);
}
/**
* Get the used (referenced) RELEASED object classes not owned by caBIG
*
* @return the list of object classes
*/
public String[] reportUsedObjectClasses()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Version" + cs1 + "Workflow Status" + cs1
+ "Short Name" + cs1 + "Context" + cs1 + "Created" + cs1
+ "Modified" + cs1 + "References" + cs1 + "Order" + cs1
+ "Concept" + cs1 + "Code" + cs1 + "Origin' as title, ' ' AS lname, 0 AS dorder, ' ' AS ocidseq "
+ "from dual UNION ALL "
+ "SELECT oc.long_name" + cs2 + "oc.oc_id" + cs2 + "oc.VERSION" + cs2 + "oc.asl_name" + cs2
+ "oc.preferred_name" + cs2 + "c.NAME" + cs2 + "oc.date_created" + cs2
+ "oc.date_modified" + cs2 + "ocset.cnt" + cs2 + "cc.display_order" + cs2
+ "con.long_name" + cs2 + "con.preferred_name" + cs2 + "con.origin as title, "
+ "LOWER (oc.long_name) AS lname, cc.display_order AS dorder, oc.oc_idseq AS ocidseq "
+ "FROM (SELECT ocv.oc_idseq, COUNT (*) AS cnt "
+ "FROM sbrext.object_classes_view_ext ocv, "
+ "sbr.data_element_concepts_view DEC "
+ "WHERE ocv.asl_name NOT LIKE 'RETIRED%' "
+ "AND ocv.conte_idseq NOT IN ( "
+ "SELECT VALUE "
+ "FROM sbrext.tool_options_view_ext "
+ "WHERE tool_name = 'caDSR' "
+ "AND property = 'DEFAULT_CONTEXT') "
+ "AND DEC.oc_idseq = ocv.oc_idseq "
+ "AND DEC.asl_name NOT LIKE 'RETIRED%' "
+ "GROUP BY ocv.oc_idseq) ocset, "
+ "sbrext.object_classes_view_ext oc, "
+ "sbrext.component_concepts_view_ext cc, "
+ "sbrext.concepts_view_ext con, "
+ "sbr.contexts_view c "
+ "WHERE oc.oc_idseq = ocset.oc_idseq "
+ "AND c.conte_idseq = oc.conte_idseq "
+ "AND cc.condr_idseq = oc.condr_idseq "
+ "AND con.con_idseq = cc.con_idseq "
+ "ORDER BY lname ASC, ocidseq ASC, dorder DESC";
return getBasicData0(select);
}
/**
* Pull the name and email address for all the recipients on a specific Alert Definition.
*
* @param idseq_ the database id of the Alert Definition
*/
public void selectAlertRecipients(String idseq_)
{
//TODO use this method to retrieve the name and emails for the distribution. It will
// guarantee that the pair only appears once in the list. The method signature must be
// changed to return the values.
String select = "SELECT ua.NAME, ua.electronic_mail_address "
+ "FROM sbr.user_accounts_view ua "
+ "WHERE ua.ua_name IN ( "
+ "SELECT rc.ua_name "
+ "FROM sbrext.sn_report_view_ext rep, "
+ "sbrext.sn_recipient_view_ext rc "
+ "WHERE rep.al_idseq = '"+ idseq_ + "' "
+ "AND rc.rep_idseq = rep.rep_idseq "
+ "UNION "
+ "SELECT uc.ua_name "
+ "FROM sbrext.user_contexts_view uc, "
+ "sbr.contexts_view c, "
+ "sbrext.sn_report_view_ext rep, "
+ "sbrext.sn_recipient_view_ext rc "
+ "WHERE rep.al_idseq = '"+ idseq_ + "' "
+ "AND rc.rep_idseq = rep.rep_idseq "
+ "AND c.conte_idseq = rc.conte_idseq "
+ "AND uc.NAME = c.NAME "
+ "AND uc.PRIVILEGE = 'W') "
+ "AND ua.electronic_mail_address IS NOT NULL "
+ "UNION "
+ "SELECT rc.email, rc.email "
+ "FROM sbrext.sn_report_view_ext rep, sbrext.sn_recipient_view_ext rc "
+ "WHERE rep.al_idseq = '"+ idseq_ + "' "
+ "AND rc.rep_idseq = rep.rep_idseq "
+ "AND email IS NOT NULL";
Results1 temp = getBasicData1(select, false);
}
/**
* Retrieve the database Registration Authority Identifier (RAI)
*
* @return the server value
*/
public String getDatabaseRAI()
{
String[] list = getBasicData0("select value from sbrext.tool_options_view_ext where tool_name = 'caDSR' and property = 'RAI'");
return (list != null) ? list[0] : null;
}
/**
* Convert all meaning full names back to the internal codes for the XML generation
*
* @param changes -
* array of names for changes
* @return - array of the corresponding key values
*/
@SuppressWarnings("unchecked")
public String[] getKeyNames(String[] changes)
{
// Convert to list
List<DBAlertOracleMap1> list = new ArrayList<DBAlertOracleMap1>(Arrays.asList(concat(_DBMAP1, _DBMAP1DESIG, _DBMAP1RD, _DBMAP1CSI, _DBMAP1COMPLEX,
_DBMAP1OTHER)));
// Ensure list sorted
Collections.sort(list);
// Convert it back to array as this is how the binary search is implemented
DBAlertOracleMap1[] tempMap = list.toArray(new DBAlertOracleMap1[list.size()]);
// Store the values into the new array and return the array
String[] temp = new String[changes.length];
for (int i = 0; i < changes.length; i++)
{
int rowID = DBAlertUtil.binarySearchValues(tempMap, changes[i]);
temp[i] = tempMap[rowID]._key;
}
return temp; // To change body of implemented methods use File | Settings | File Templates.
}
/**
* Concatenate all map arrays
*
* @param maps the list of maps to concatenate
* @return a single map
*/
private DBAlertOracleMap1[] concat(DBAlertOracleMap1[] ... maps)
{
int total = 0;
for (DBAlertOracleMap1[] map : maps)
{
total += map.length;
}
DBAlertOracleMap1[] concatMap = new DBAlertOracleMap1[total];
total = 0;
for (DBAlertOracleMap1[] map : maps)
{
System.arraycopy(map, 0, concatMap, total, map.length);
total += map.length;
}
return concatMap;
}
}
|
sentinel/src/gov/nih/nci/cadsr/sentinel/database/DBAlertOracle.java
|
// Copyright (c) 2004 ScenPro, Inc.
// $Header: /share/content/gforge/sentinel/sentinel/src/gov/nih/nci/cadsr/sentinel/database/DBAlertOracle.java,v 1.12 2007-12-17 18:13:54 hebell Exp $
// $Name: not supported by cvs2svn $
package gov.nih.nci.cadsr.sentinel.database;
import gov.nih.nci.cadsr.sentinel.audits.AuditReport;
import gov.nih.nci.cadsr.sentinel.tool.ACData;
import gov.nih.nci.cadsr.sentinel.tool.AlertRec;
import gov.nih.nci.cadsr.sentinel.tool.AutoProcessData;
import gov.nih.nci.cadsr.sentinel.tool.ConceptItem;
import gov.nih.nci.cadsr.sentinel.tool.Constants;
import gov.nih.nci.cadsr.sentinel.ui.AlertPlugIn;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import oracle.jdbc.pool.OracleConnectionPoolDataSource;
import oracle.jdbc.pool.OracleDataSource;
import org.apache.log4j.Logger;
/**
* Encapsulate all database access to the tables relating to the Sentinel Alert
* definitions.
* <p>
* For all access, the SQL statements are NOT placed in the properties file as
* internationalization and translation should not affect them. We also want to
* ease the maintenance by keeping the SQL with the database execute function
* calls. If some SQL becomes duplicated, a single method with appropriate
* parameters should be created to avoid difficulties with changing the SQL
* statements over time as the table definitions evolve.
* <p>
* Start with setupPool() which only needs to be executed once. Then open() and
* close() every time a new DBAlert object is created.
* <p>
* Also, just a reminder, all JDBC set...() and get...() methods use 1 (one)
* based indexing unlike the Java language which uses 0 (zero) based.
*
* @author Larry Hebel
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(HttpServletRequest, String, String) open() with HTTP request
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(ServletContext, String, String) open() with Servlet Context
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(String, String, String) open()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public class DBAlertOracle implements DBAlert
{
// Class data
private String _namesList[];
private String _namesVals[];
private String _namesExempt;
private String _contextList[];
private String _contextVals[];
private String _schemeList[];
private String _schemeVals[];
private String _schemeContext[];
private String _protoList[];
private String _protoVals[];
private String _protoContext[];
private String _schemeItemList[];
private String _schemeItemVals[];
private String _schemeItemSchemes[];
private Connection _conn;
private String _user;
private ServletContext _sc;
private boolean _needCommit;
private String _groupsList[];
private String _groupsVals[];
private String _formsList[];
private String _formsVals[];
private String _formsContext[];
private String _workflowList[];
private String _workflowVals[];
private String _cworkflowList[];
private String _cworkflowVals[];
private String _regStatusList[];
private String _regStatusVals[];
private String _regCStatusList[];
private String _regCStatusVals[];
private String _nameID[];
private String _nameText[];
private int _errorCode;
private String _errorMsg;
private String _actypesList[];
private String _actypesVals[];
/**
* The internal code for Version.
*/
public static final String _VERSION = "VERSION";
/**
* The internal code for Workflow Status.
*/
public static final String _WFS = "ASL_NAME";
/**
* The internal code for Registration Status.
*/
public static final String _RS = "REGISTRATION_STATUS";
/**
* The internal code for User ID.
*/
public static final String _UNAME = "UA_NAME";
/**
* Version Any Change value.
*/
public static final char _VERANYCHG = 'C';
/**
* Version Major (whole) number change value.
*/
public static final char _VERMAJCHG = 'M';
/**
* Version Ignore change value.
*/
public static final char _VERIGNCHG = 'I';
/**
* Version Specific Value change value.
*/
public static final char _VERSPECHG = 'S';
/**
* Maximum length of the Alert Definition Name.
*/
public static final int _MAXNAMELEN = 30;
/**
* Maximum length of the Inaction Reason description.
*/
public static final int _MAXREASONLEN = 2000;
/**
* Maximum length of the Report Introduction description.
*/
public static final int _MAXINTROLEN = 2000;
/**
* Maximum length of a freeform email address.
*/
public static final int _MAXEMAILLEN = 255;
/**
* The Date comparison Created Only value.
*/
public static final int _DATECONLY = 0;
/**
* The Date comparison Modified Only value.
*/
public static final int _DATEMONLY = 1;
/**
* The Date comparison Created and Modified value.
*/
public static final int _DATECM = 2;
private static boolean _poolWarning = true;
private static final String _DATECHARS[][] = {
{"<", ">", ">=", "<"},
{">=", "<", "<", ">"},
{">=", "<", ">=", "<"}
};
private static final String _CONTEXT = "CONTEXT";
private static final String _FORM = "FORM";
private static final String _PROTOCOL = "PROTOCOL";
private static final String _SCHEME = "CS";
private static final String _SCHEMEITEM = "CSI";
private static final String _CREATOR = "CREATOR";
private static final String _MODIFIER = "MODIFIER";
private static final String _REGISTER = "REG_STATUS";
private static final String _STATUS = "AC_STATUS";
private static final String _ACTYPE = "ACTYPE";
private static final String _DATEFILTER = "DATEFILTER";
private static final char _CRITERIA = 'C';
private static final char _MONITORS = 'M';
private static final String _orderbyACH =
"order by id asc, "
// + "cid asc, "
// + "zz.date_modified asc, "
+ "ach.change_datetimestamp asc, "
+ "ach.changed_table asc, "
+ "ach.changed_table_idseq asc, "
+ "ach.changed_column asc";
private static final DBAlertOracleMap1[] _DBMAP1 =
{
new DBAlertOracleMap1("ASL_NAME", "Workflow Status"),
new DBAlertOracleMap1("BEGIN_DATE", "Begin Date"),
new DBAlertOracleMap1("CDE_ID", "Public ID"),
new DBAlertOracleMap1("CDR_IDSEQ", "Complex DE association"),
new DBAlertOracleMap1("CD_IDSEQ", "Conceptual Domain association"),
new DBAlertOracleMap1("CHANGE_NOTE", "Change Note"),
new DBAlertOracleMap1("CONDR_IDSEQ", "Concept Class association"),
new DBAlertOracleMap1("CON_IDSEQ", "Concept Class association"),
new DBAlertOracleMap1("CREATED_BY", "Created By"),
new DBAlertOracleMap1("CSTL_NAME", "Category"),
new DBAlertOracleMap1("CS_ID", "Public ID"),
new DBAlertOracleMap1("C_DEC_IDSEQ", "Child DEC association"),
new DBAlertOracleMap1("C_DE_IDSEQ", "Child DE association"),
new DBAlertOracleMap1("C_VD_IDSEQ", "Child VD association"),
new DBAlertOracleMap1("DATE_CREATED", "Created Date"),
new DBAlertOracleMap1("DATE_MODIFIED", "Modified Date"),
new DBAlertOracleMap1("DECIMAL_PLACE", "Number of Decimal Places"),
new DBAlertOracleMap1("DEC_ID", "Public ID"),
new DBAlertOracleMap1("DEC_IDSEQ", "Data Element Concept association"),
new DBAlertOracleMap1("DEC_REC_IDSEQ", "DEC_REC_IDSEQ"),
new DBAlertOracleMap1("DEFINITION_SOURCE", "Definition Source"),
new DBAlertOracleMap1("DELETED_IND", "Deleted Indicator"),
new DBAlertOracleMap1("DESCRIPTION", "Description"),
new DBAlertOracleMap1("DESIG_IDSEQ", "Designation association"),
new DBAlertOracleMap1("DE_IDSEQ", "Data Element association"),
new DBAlertOracleMap1("DE_REC_IDSEQ", "DE_REC_IDSEQ"),
new DBAlertOracleMap1("DISPLAY_ORDER", "Display Order"),
new DBAlertOracleMap1("DTL_NAME", "Data Type"),
new DBAlertOracleMap1("END_DATE", "End Date"),
new DBAlertOracleMap1("FORML_NAME", "Data Format"),
new DBAlertOracleMap1("HIGH_VALUE_NUM", "Maximum Value"),
new DBAlertOracleMap1("LABEL_TYPE_FLAG", "Label Type"),
new DBAlertOracleMap1("LATEST_VERSION_IND", "Latest Version Indicator"),
new DBAlertOracleMap1("LONG_NAME", "Long Name"),
new DBAlertOracleMap1("LOW_VALUE_NUM", "Minimum Value"),
new DBAlertOracleMap1("MAX_LENGTH_NUM", "Maximum Length"),
new DBAlertOracleMap1("METHODS", "Methods"),
new DBAlertOracleMap1("MIN_LENGTH_NUM", "Minimum Length"),
new DBAlertOracleMap1("MODIFIED_BY", "Modified By"),
new DBAlertOracleMap1("OBJ_CLASS_QUALIFIER", "Object Class Qualifier"),
new DBAlertOracleMap1("OCL_NAME", "Object Class Name"),
new DBAlertOracleMap1("OC_ID", "Public ID"),
new DBAlertOracleMap1("OC_IDSEQ", "Object Class association"),
new DBAlertOracleMap1("ORIGIN", "Origin"),
new DBAlertOracleMap1("PREFERRED_DEFINITION", "Preferred Definition"),
new DBAlertOracleMap1("PREFERRED_NAME", "Preferred Name"),
new DBAlertOracleMap1("PROPERTY_QUALIFIER", "Property Qualifier"),
new DBAlertOracleMap1("PROPL_NAME", "Property Name"),
new DBAlertOracleMap1("PROP_ID", "Public ID"),
new DBAlertOracleMap1("PROP_IDSEQ", "Property"),
new DBAlertOracleMap1("PV_IDSEQ", "Permissible Value"),
new DBAlertOracleMap1("P_DEC_IDSEQ", "Parent DEC association"),
new DBAlertOracleMap1("P_DE_IDSEQ", "Parent DE association"),
new DBAlertOracleMap1("P_VD_IDSEQ", "Parent VD association"),
new DBAlertOracleMap1("QUALIFIER_NAME", "Qualifier"),
new DBAlertOracleMap1("QUESTION", "Question"),
new DBAlertOracleMap1("RD_IDSEQ", "Reference Document association"),
new DBAlertOracleMap1("REP_IDSEQ", "Representation association"),
new DBAlertOracleMap1("RL_NAME", "Relationship Name"),
new DBAlertOracleMap1("RULE", "Rule"),
new DBAlertOracleMap1("SHORT_MEANING", "Meaning"),
new DBAlertOracleMap1("UOML_NAME", "Unit Of Measure"),
new DBAlertOracleMap1("URL", "URL"),
new DBAlertOracleMap1("VALUE", "Value"),
new DBAlertOracleMap1("VD_ID", "Public ID"),
new DBAlertOracleMap1("VD_IDSEQ", "Value Domain association"),
new DBAlertOracleMap1("VD_REC_IDSEQ", "VD_REC_IDSEQ"),
new DBAlertOracleMap1("VD_TYPE_FLAG", "Enumerated/Non-enumerated"),
new DBAlertOracleMap1("VERSION", "Version")
};
private static final DBAlertOracleMap1[] _DBMAP1OTHER =
{
new DBAlertOracleMap1("CONTE_IDSEQ", "Owned By Context"),
new DBAlertOracleMap1("LAE_NAME", "Language"),
new DBAlertOracleMap1("NAME", "Name")
};
private static final DBAlertOracleMap1[] _DBMAP1DESIG =
{
new DBAlertOracleMap1("CONTE_IDSEQ", "Designation Context"),
new DBAlertOracleMap1("DETL_NAME", "Designation Type"),
new DBAlertOracleMap1("LAE_NAME", "Designation Language")
};
private static final DBAlertOracleMap1[] _DBMAP1CSI =
{
new DBAlertOracleMap1("CS_CSI_IDSEQ", "Classification Scheme Item association")
};
private static final DBAlertOracleMap1[] _DBMAP1RD =
{
new DBAlertOracleMap1("DCTL_NAME","Document Type"),
new DBAlertOracleMap1("DISPLAY_ORDER", "Document Display Order"),
new DBAlertOracleMap1("DOC_TEXT", "Document Text"),
new DBAlertOracleMap1("RDTL_NAME", "Document Text Type"),
new DBAlertOracleMap1("URL", "Document URL")
};
private static final DBAlertOracleMap1[] _DBMAP1COMPLEX =
{
new DBAlertOracleMap1("CONCAT_CHAR", "Concatenation Character"),
new DBAlertOracleMap1("CRTL_NAME", "Complex Type")
};
private static final DBAlertOracleMap2[] _DBMAP2 =
{
new DBAlertOracleMap2("CD_IDSEQ", "sbr.conceptual_domains_view", "cd_idseq", "", "long_name || ' (' || cd_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("CONDR_IDSEQ", "sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext cv", "ccv.condr_idseq", " and cv.con_idseq = ccv.con_idseq order by ccv.display_order desc",
"cv.long_name || ' (' || cv.con_id || 'v' || cv.version || ') (' || cv.origin || ':' || cv.preferred_name || ')' as label"),
new DBAlertOracleMap2("CONTE_IDSEQ", "sbr.contexts_view", "conte_idseq", "", "name || ' (v' || version || ')' as label"),
new DBAlertOracleMap2("CON_IDSEQ", "sbrext.concepts_view_ext", "con_idseq", "", "long_name || ' (' || con_id || 'v' || version || ') (' || origin || ':' || preferred_name || ')' as label"),
new DBAlertOracleMap2("CREATED_BY", "sbr.user_accounts_view", "ua_name", "", "name as label"),
new DBAlertOracleMap2("CS_CSI_IDSEQ", "sbr.cs_csi_view cci, sbr.class_scheme_items_view csi", "cci.cs_csi_idseq", " and csi.csi_idseq = cci.csi_idseq","csi.csi_name as label"),
new DBAlertOracleMap2("DEC_IDSEQ", "sbr.data_element_concepts_view", "dec_idseq", "", "long_name || ' (' || dec_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("DE_IDSEQ", "sbr.data_elements_view", "de_idseq", "", "long_name || ' (' || cde_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("MODIFIED_BY", "sbr.user_accounts_view", "ua_name", "", "name as label"),
new DBAlertOracleMap2("OC_IDSEQ", "sbrext.object_classes_view_ext", "oc_idseq", "", "long_name || ' (' || oc_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("PROP_IDSEQ", "sbrext.properties_view_ext", "prop_idseq", "", "long_name || ' (' || prop_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("PV_IDSEQ", "sbr.permissible_values_view", "pv_idseq", "", "value || ' (' || short_meaning || ')' as label"),
new DBAlertOracleMap2("RD_IDSEQ", "sbr.reference_documents_view", "rd_idseq", "", "name || ' (' || nvl(doc_text, url) || ')' as label"),
new DBAlertOracleMap2("REP_IDSEQ", "sbrext.representations_view_ext", "rep_idseq", "", "long_name || ' (' || rep_id || 'v' || version || ')' as label"),
new DBAlertOracleMap2("UA_NAME", "sbr.user_accounts_view", "ua_name", "", "name as label"),
new DBAlertOracleMap2("VD_IDSEQ", "sbr.value_domains_view", "vd_idseq", "", "long_name || ' (' || vd_id || 'v' || version || ')' as label")
};
private static final DBAlertOracleMap3[] _DBMAP3 =
{
new DBAlertOracleMap3("cd", "Conceptual Domain", "sbr.conceptual_domains_view", null),
new DBAlertOracleMap3("con", "Concept", "sbrext.concepts_view_ext", null),
new DBAlertOracleMap3("conte", "Context", "sbr.contexts_view", null),
new DBAlertOracleMap3("cs", "Classification Scheme", "sbr.classification_schemes_view", "CLASSIFICATION_SCHEMES"),
new DBAlertOracleMap3("csi", "Classification Scheme Item", "sbr.class_scheme_items_view", null),
new DBAlertOracleMap3("de", "Data Element", "sbr.data_elements_view", "DATA_ELEMENTS"),
new DBAlertOracleMap3("dec", "Data Element Concept", "sbr.data_element_concepts_view", "DATA_ELEMENT_CONCEPTS"),
new DBAlertOracleMap3("oc", "Object Class", "sbrext.object_classes_view_ext", "OBJECT_CLASSES_EXT"),
new DBAlertOracleMap3("prop", "Property", "sbrext.properties_view_ext", "PROPERTIES_EXT"),
new DBAlertOracleMap3("proto", "Protocol", "sbrext.protocols_view_ext", null),
new DBAlertOracleMap3("pv", "Permissible Value", "sbr.permissible_values_view", "PERMISSIBLE_VALUES"),
new DBAlertOracleMap3("qc", "Form/Template", "sbrext.quest_contents_view_ext", null),
new DBAlertOracleMap3("qcm", "Module", null, null),
new DBAlertOracleMap3("qcq", "Question", null, null),
new DBAlertOracleMap3("qcv", "Valid Value", null, null),
new DBAlertOracleMap3("vd", "Value Domain", "sbr.value_domains_view", "VALUE_DOMAINS"),
new DBAlertOracleMap3("vm", "Value Meaning", "sbr.value_meanings_view", null)
};
private static final Logger _logger = Logger.getLogger(DBAlert.class.getName());
/**
* Entry for development testing of the class
*
* @param args program arguments
*/
public static void main(String args[])
{
DBAlertOracle var = new DBAlertOracle();
var.concat(_DBMAP1, _DBMAP1DESIG,_DBMAP1RD, _DBMAP1CSI , _DBMAP1COMPLEX , _DBMAP1OTHER);
}
/**
* Constructor.
*/
public DBAlertOracle()
{
_errorCode = 0;
_nameID = new String[1];
_nameID[0] = "";
_nameText = new String[1];
_nameText[0] = "";
_conn = null;
_sc = null;
}
/**
* Required prior to using any other methods within this class. This method
* checks for the existence of the pool attached to the Servlet Context.
* Once the pool is successfully created subsequent invocations perform no
* action. The method is static and synchronized to allow for possible
* multiple invocations of the Sentinel Tool simultaneously. Although the
* data referenced is not static we don't want to take the chance that the
* ServletContext.getAttribute() is called, we loose the time slice and upon
* return from the VM one invocation thinks the pool is missing when another
* invocation has just successfully created it. This is only called from the
* Logon Action currently so the overhead inherit with synchronized
* functions is minimized.
* <p>
* To use this from non-browser servlet logic use the method which requires
* the driver as the first argument.
*
* @param session_
* The session object.
* @param dsurl_
* The URL entry for the desired database.
* @param username_
* The default database user logon id.
* @param password_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int setupPool(HttpSession session_,
String dsurl_, String username_, String password_)
{
return setupPoolX(session_, dsurl_, username_, password_);
}
static private synchronized int setupPoolX(HttpSession session_,
String dsurl_, String username_, String password_)
{
// Get the Servlet Context and see if a pool already exists.
ServletContext sc = session_.getServletContext();
if (sc.getAttribute(DBAlert._DATASOURCE) != null)
return 0;
OracleConnectionPoolDataSource ocpds = (OracleConnectionPoolDataSource) sc
.getAttribute(_DBPOOL);
if (ocpds != null)
return 0;
ocpds = setupPool(dsurl_, username_, password_);
if (ocpds != null)
{
// Remember the pool in the Servlet Context.
sc.setAttribute(_DBPOOL + ".ds", ocpds);
sc.setAttribute(_DBPOOL + ".user", username_);
sc.setAttribute(_DBPOOL + ".pswd", password_);
return 0;
}
return -1;
}
/**
* Required prior to using any other methods within this class. This method
* checks for the existence of the pool attached to the Servlet Context.
* Once the pool is successfully created subsequent invocations perform no
* action. The method is static and synchronized to allow for possible
* multiple invocations of the Sentinel Tool simultaneously. Although the
* data referenced is not static we don't want to take the chance that the
* ServletContext.getAttribute() is called, we loose the time slice and upon
* return from the VM one invocation thinks the pool is missing when another
* invocation has just successfully created it. This is only called from the
* Logon Action currently so the overhead inherit with synchronized
* functions is minimized.
* <p>
* To use this from non-browser servlet logic use the method which requires
* the driver as the first argument.
*
* @param request_
* The servlet request object.
* @param dsurl_
* The URL entry for the desired database.
* @param username_
* The default database user logon id.
* @param password_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int setupPool(HttpServletRequest request_,
String dsurl_, String username_, String password_)
{
// Pass it on...
return setupPool(request_.getSession(), dsurl_, username_,
password_);
}
/**
* Required prior to using any other methods within this class. This method
* checks for the existence of the pool attached to the Servlet Context.
* Once the pool is successfully created subsequent invocations perform no
* action. The method is static and synchronized to allow for possible
* multiple invocations of the Sentinel Tool simultaneously. Although the
* data referenced is not static we don't want to take the chance that the
* ServletContext.getAttribute() is called, we loose the time slice and upon
* return from the VM one invocation thinks the pool is missing when another
* invocation has just successfully created it. This is only called from the
* Logon Action currently so the overhead inherit with synchronized
* functions is minimized.
* <p>
* To use this from a browser servlet, use the method which requires an
* HttpServletRequest as the first argument to the method.
*
* @param dsurl_
* The URL entry for the desired database.
* @param username_
* The default database user logon id.
* @param password_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
*/
private static synchronized OracleConnectionPoolDataSource setupPool(
String dsurl_, String username_, String password_)
{
// First register the database driver.
OracleConnectionPoolDataSource ocpds = null;
int rc = 0;
String rcTxt = null;
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
}
catch (SQLException ex)
{
rc = ex.getErrorCode();
rcTxt = rc + ": " + ex.toString();
}
try
{
// Create an the connection pool data source and set the parameters.
ocpds = new OracleConnectionPoolDataSource();
if (dsurl_.indexOf(':') > 0)
{
String parts[] = dsurl_.split("[:]");
ocpds.setDriverType("thin");
ocpds.setServerName(parts[0]);
ocpds.setPortNumber(Integer.parseInt(parts[1]));
ocpds.setServiceName(parts[2]);
}
else
{
ocpds.setDriverType("oci8");
ocpds.setTNSEntryName(dsurl_);
}
ocpds.setUser(username_);
ocpds.setPassword(password_);
}
catch (SQLException ex)
{
// We have a problem.
rc = ex.getErrorCode();
rcTxt = rc + ": " + ex.toString();
ocpds = null;
}
if (rc != 0)
{
// Send a user friendly message to the Logon window and the more
// detailed
// message to the console.
_logger.error(rcTxt);
}
return ocpds;
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param sc_
* The servlet context which holds the data source pool reference
* created by the DBAlert.setupPool() method.
* @param user_
* The database user logon id.
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(ServletContext sc_, String user_)
{
return open(sc_, user_, null);
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param sc_
* The servlet context which holds the data source pool reference
* created by the DBAlert.setupPool() method.
* @param user_
* The database user logon id.
* @param pswd_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(ServletContext sc_, String user_, String pswd_)
{
// If we already have a connection, don't bother.
if (_conn != null)
return 0;
try
{
// Get a connection from the pool, if anything unexpected happens
// the catch is
// run.
_sc = sc_;
_user = user_;
AlertPlugIn var = (AlertPlugIn)_sc.getAttribute(DBAlert._DATASOURCE);
if (var == null)
{
OracleConnectionPoolDataSource ocpds =
(OracleConnectionPoolDataSource) _sc.getAttribute(_DBPOOL);
_conn = ocpds.getConnection(user_, pswd_);
if (_poolWarning)
{
_poolWarning = false;
_logger.warn("============ Could not find JBoss datasource using internal connection pool.");
}
}
else if (pswd_ == null)
_conn = var.getDataSource().getConnection();
else
_conn = var.getAuthenticate().getConnection(user_, pswd_);
// We handle the commit once in the close.
_conn.setAutoCommit(false);
_needCommit = false;
return 0;
}
catch (SQLException ex)
{
// There seems to be a problem.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
_sc = null;
_conn = null;
return _errorCode;
}
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param ds_
* The datasource for database connections.
* @param user_
* The database user logon id.
* @return 0 if successful, otherwise the error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(DataSource ds_, String user_)
{
try
{
_user = user_;
_conn = ds_.getConnection();
_conn.setAutoCommit(false);
_needCommit = false;
}
catch (SQLException ex)
{
_logger.error(ex.toString(), ex);
return ex.getErrorCode();
}
return 0;
}
/**
* Open a single simple connection to the database. No pooling is necessary.
*
* @param dsurl_
* The Oracle TNSNAME entry describing the database location.
* @param user_
* The ORACLE user id.
* @param pswd_
* The password which must match 'user_'.
* @return The database error code.
*/
public int open(String dsurl_, String user_, String pswd_)
{
// If we already have a connection, don't bother.
if (_conn != null)
return 0;
try
{
OracleDataSource ods = new OracleDataSource();
if (dsurl_.indexOf(':') > 0)
{
String parts[] = dsurl_.split("[:]");
ods.setDriverType("thin");
ods.setServerName(parts[0]);
ods.setPortNumber(Integer.parseInt(parts[1]));
ods.setServiceName(parts[2]);
}
else
{
ods.setDriverType("oci8");
ods.setTNSEntryName(dsurl_);
}
_user = user_;
_conn = ods.getConnection(user_, pswd_);
_conn.setAutoCommit(false);
_needCommit = false;
return 0;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param request_
* The servlet request object.
* @param user_
* The database user logon id.
* @param pswd_
* The password to match the user.
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(HttpServletRequest request_, String user_, String pswd_)
{
return open(request_.getSession().getServletContext(), user_, pswd_);
}
/**
* Create a connection from the pool. This is not part of the constructor to
* allow the method to have return codes that can be interrogated by the
* caller. If Exception are desired, appropriate wrapper methods can be
* created to provide both features and give the caller the flexibility to
* use either without additional coding.
* <p>
* Be sure to call DBAlert.close() to complete the request before returning
* to the client or loosing the object focus in the caller to "new
* DBAlert()".
*
* @param request_
* The servlet request object.
* @param user_
* The database user logon id.
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#close close()
*/
public int open(HttpServletRequest request_, String user_)
{
return open(request_.getSession().getServletContext(), user_, null);
}
/**
* Required upon a successful return from open. When all database access is
* completed for this user request. To optimize the database access, all
* methods which perform actions that require a commmit only set a flag. It
* is in the close() method the flag is interrogated and the commit actually
* occurs.
*
* @return 0 if successful, otherwise the Oracle error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(HttpServletRequest, String, String) open() with HTTP request
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(ServletContext, String, String) open() with Servlet Context
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#open(String, String, String) open()
*/
public int close()
{
/*
try
{
throw new Exception("Trace");
}
catch (Exception ex)
{
_logger.debug("Trace", ex);
}
*/
// We only need to do something if a connection is obtained.
if (_conn != null)
{
try
{
// Don't forget to commit if needed.
if (_needCommit)
_conn.commit();
}
catch (SQLException ex)
{
// There seems to be a problem.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": "
+ ex.toString();
_logger.error(_errorMsg);
}
try
{
// Close the connection and release all pointers.
_conn.close();
_conn = null;
_sc = null;
}
catch (SQLException ex)
{
// There seems to be a problem.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": "
+ ex.toString();
_logger.error(_errorMsg);
_conn = null;
_sc = null;
return _errorCode;
}
}
return 0;
}
/**
* Get the database connection opened for this object.
*
* @return java.sql.Connection opened by this object.
*/
public Connection getConnection()
{
return _conn;
}
/**
* Retrieves the abbreviated list of all alerts. The AlertRec objects
* returned are not fully populated with all the details of each alert. Only
* basic information such as the database id, name, creator and a few other
* basic properties are guaranteed.
*
* @param user_
* The user id with which to qualify the results. This must be as it
* appears in the "created_by" column of the Alert tables. If null is
* used, a list of all Alerts is retrieved.
* @return The array of Alerts retrieved.
*/
public AlertRec[] selectAlerts(String user_)
{
// Define the SQL Select
String select = "select a.al_idseq, a.name, a.last_auto_run, a.auto_freq_unit, a.al_status, a.auto_freq_value, a.created_by, u.name "
+ "from sbrext.sn_alert_view_ext a, sbr.user_accounts_view u "
+ "where ";
// If a user id was given, qualify the list with it.
if (user_ != null)
select = select + "a.created_by = ? and ";
select = select + "u.ua_name = a.created_by";
PreparedStatement pstmt = null;
ResultSet rs = null;
Vector<AlertRec> results = new Vector<AlertRec>();
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select);
if (user_ != null)
pstmt.setString(1, user_);
// Get the list.
rs = pstmt.executeQuery();
while (rs.next())
{
// For the list of alerts we only need basic information.
AlertRec rec = new AlertRec();
rec.setAlertRecNum(rs.getString(1));
rec.setName(rs.getString(2));
rec.setAdate(rs.getTimestamp(3));
rec.setFreq(rs.getString(4));
rec.setActive(rs.getString(5));
rec.setDay(rs.getInt(6));
rec.setCreator(rs.getString(7));
rec.setCreatorName(rs.getString(8));
// After much consideration, I thought it best to dynamically
// generate the textual summary of the alert. This
// could be done at the time the alert is saved and stored in
// the database, however, the descriptions could become
// very large and we have to worry about some things changing
// and not being updated. For the first implementation
// it seems best to generate it. In the future this may change.
selectQuery(rec);
select = rec.getSummary(false);
rec.clearQuery();
rec.setSummary(select);
results.add(rec);
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select + "\n\n"
+ ex.toString();
_logger.error(_errorMsg);
return null;
}
// Now that we have the full results we can create a single simple array
// to contain
// them. This greatly simplifies access throughout the code.
AlertRec database[] = null;
int count = results.size();
if (count > 0)
{
database = new AlertRec[count];
for (int ndx = 0; ndx < count; ++ndx)
database[ndx] = (AlertRec) results.get(ndx);
}
// Return the results.
return database;
}
/**
* Pull the list of recipients for a specific alert.
*
* @param rec_
* The alert for the desired recipients. The alertRecNum must be set
* prior to this method.
* @return 0 if successful, otherwise the database error code.
*/
private int selectRecipients(AlertRec rec_)
{
// A Report has a list of one or more recipients.
String select = "select ua_name, email, conte_idseq "
+ "from sbrext.sn_recipient_view_ext " + "where rep_idseq = ?";
try
{
// Get ready...
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, rec_.getReportRecNum());
// Go!
Vector<String> rlist = new Vector<String>();
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
String temp = rs.getString(1);
// We use the ua_name as is.
if (temp != null)
rlist.add(temp);
else
{
temp = rs.getString(2);
// The email address must have an "@" in it somewhere so no
// change.
if (temp != null)
rlist.add(temp);
else
{
temp = rs.getString(3);
// To distinguish groups from a ua_name we use a "/" as
// a prefix.
if (temp != null)
rlist.add("/" + temp);
}
}
}
rs.close();
pstmt.close();
// Move the data to an array and drop the Vector.
if (rlist.size() > 0)
{
String temp[] = new String[rlist.size()];
for (int ndx = 0; ndx < temp.length; ++ndx)
{
temp[ndx] = (String) rlist.get(ndx);
}
rec_.setRecipients(temp);
}
else
{
rec_.setRecipients(null);
}
return 0;
}
catch (SQLException ex)
{
// We've got trouble.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select + "\n\n"
+ ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Pull the report information for a specific alert definition.
*
* @param rec_
* The alert for the desired report. The alertRecNum must be set
* prior to this method.
* @return 0 if successful, otherwise the database error code.
*/
private int selectReport(AlertRec rec_)
{
// Each Alert has one Report definition.
String select = "select rep_idseq, include_property_ind, style, send, acknowledge_ind, comments, assoc_lvl_num "
+ "from sbrext.sn_report_view_ext " + "where al_idseq = ?";
try
{
// Get ready...
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, rec_.getAlertRecNum());
// Strictly speaking if a record is not found it is a violation of a
// business rule, however,
// the code is written to default all values to avoid these types of
// quirks.
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
rec_.setReportRecNum(rs.getString(1));
rec_.setIncPropSect(rs.getString(2));
rec_.setReportAck(rs.getString(3));
rec_.setReportEmpty(rs.getString(4));
rec_.setReportAck(rs.getString(5));
rec_.setIntro(rs.getString(6), true);
rec_.setIAssocLvl(rs.getInt(7));
}
rs.close();
pstmt.close();
return selectRecipients(rec_);
}
catch (SQLException ex)
{
// We've got trouble.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select + "\n\n"
+ ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Pull the properties for a specific alert definition.
*
* @param rec_
* The alert for the desired property values. The alertRecNum must be
* set prior to this method.
* @return 0 if successful, otherwise the database error code.
*/
private int selectProperties(AlertRec rec_)
{
// Define the SQL Select. The column names are expanded to ensure the
// order of retrieval. If asterisk (*) is used
// and the database definition changes it could rearrange the columns
// and the subsequent ResultSet.get...() method
// calls will fail.
String select = "select a.name, a.last_auto_run, a.last_manual_run, a.auto_freq_unit, a.al_status, a.begin_date, a.end_date, "
+ "a.status_reason, a.date_created, nvl(a.date_modified, a.date_created) as mdate, nvl(a.modified_by, a.created_by) as mby, "
+ "a.created_by, a.auto_freq_value, u1.name, nvl(u2.name, u1.name) as name2 "
+ "from sbrext.sn_alert_view_ext a, sbr.user_accounts_view u1, sbr.user_accounts_view u2 "
+ "where a.al_idseq = ? and u1.ua_name = a.created_by and u2.ua_name(+) = a.modified_by";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
// Get ready...
pstmt = _conn.prepareStatement(select);
pstmt.setString(1, rec_.getAlertRecNum());
// Go!
rs = pstmt.executeQuery();
if (rs.next())
{
// As the where clause uses a specific ID we should only
// retrieve one result. And there's the
// one (1) based indexing again.
rec_.setName(rs.getString(1));
rec_.setAdate(rs.getTimestamp(2));
rec_.setRdate(rs.getTimestamp(3));
rec_.setFreq(rs.getString(4));
rec_.setActive(rs.getString(5));
rec_.setStart(rs.getTimestamp(6));
rec_.setEnd(rs.getTimestamp(7));
rec_.setInactiveReason(rs.getString(8));
rec_.setCdate(rs.getTimestamp(9));
rec_.setMdate(rs.getTimestamp(10));
//rec_.setModifier(rs.getString(11));
rec_.setCreator(rs.getString(12));
rec_.setDay(rs.getInt(13));
rec_.setCreatorName(rs.getString(14));
//rec_.setModifierName(rs.getString(15));
}
else
{
// This shouldn't happen but just in case...
rec_.setAlertRecNum(null);
}
rs.close();
pstmt.close();
return 0;
}
catch (SQLException ex)
{
// We've got trouble.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select + "\n\n"
+ ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Retrieve a full single Alert definition. All data elements of the
* AlertRec will be populated to reflect the database content.
*
* @param id_
* The database id (al_idseq) of the Alert definitions.
* @return A complete definition record if successful or null if an error
* occurs.
*/
public AlertRec selectAlert(String id_)
{
AlertRec rec = new AlertRec();
rec.setAlertRecNum(id_);
if (selectProperties(rec) != 0)
{
rec = null;
}
else if (selectReport(rec) != 0)
{
rec = null;
}
else if (selectQuery(rec) != 0)
{
rec = null;
}
// Give 'em what we've got.
return rec;
}
/**
* Update the database with the Alert properties stored in a memory record.
*
* @param rec_
* The Alert definition to be stored.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On an error with rollback().
*/
private int updateProperties(AlertRec rec_) throws SQLException
{
// Define the update statement. Some columns are not updated as they are
// controlled
// by triggers, specifically date_created, date_modified, creator and
// modifier.
String update = "update sbrext.sn_alert_view_ext set " + "name = ?, "
+ "auto_freq_unit = ?, " + "al_status = ?, " + "begin_date = ?, "
+ "end_date = ?, " + "status_reason = ?, " + "auto_freq_value = ?, "
+ "modified_by = ? "
+ "where al_idseq = ?";
cleanRec(rec_);
PreparedStatement pstmt = null;
try
{
// Set all the SQL arguments.
pstmt = _conn.prepareStatement(update);
pstmt.setString(1, rec_.getName());
pstmt.setString(2, rec_.getFreqString());
pstmt.setString(3, rec_.getActiveString());
pstmt.setTimestamp(4, rec_.getStart());
pstmt.setTimestamp(5, rec_.getEnd());
pstmt.setString(6, rec_.getInactiveReason(false));
pstmt.setInt(7, rec_.getDay());
pstmt.setString(8, _user);
pstmt.setString(9, rec_.getAlertRecNum());
// Send it to the database. And remember to flag a commit for later.
pstmt.executeUpdate();
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// It's bad...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + update
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Update the Report information for an Alert within the database.
*
* @param rec_
* The Alert definition to be written to the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int updateReport(AlertRec rec_) throws SQLException
{
// Update the related Report definition.
String update = "update sbrext.sn_report_view_ext set "
+ "comments = ?, include_property_ind = ?, style = ?, send = ?, acknowledge_ind = ?, assoc_lvl_num = ?, "
+ "modified_by = ? "
+ "where rep_idseq = ?";
try
{
// Set all the SQL arguments.
PreparedStatement pstmt = _conn.prepareStatement(update);
pstmt.setString(1, rec_.getIntro(false));
pstmt.setString(2, rec_.getIncPropSectString());
pstmt.setString(3, rec_.getReportStyleString());
pstmt.setString(4, rec_.getReportEmptyString());
pstmt.setString(5, rec_.getReportAckString());
pstmt.setInt(6, rec_.getIAssocLvl());
pstmt.setString(7, _user);
pstmt.setString(8, rec_.getReportRecNum());
pstmt.executeUpdate();
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// It's bad...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + update
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Perform an update on the complete record. No attempt is made to isolate
* the specific changes so many times values will not actually be changed.
*
* @param rec_
* The record containing the updated information. All data elements
* must be populated and correct.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int updateAlert(AlertRec rec_)
{
// Ensure data is clean.
rec_.setDependancies();
// Update database.
try
{
int xxx = updateProperties(rec_);
if (xxx != 0)
return xxx;
xxx = updateReport(rec_);
if (xxx != 0)
return xxx;
xxx = updateRecipients(rec_);
if (xxx != 0)
return xxx;
return updateQuery(rec_);
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Delete the Alert Definitions specified by the caller. The values must be
* existing al_idseq values within the Alert table.
*
* @param list_
* The al_idseq values which identify the definitions to delete.
* Other dependant tables in the database will automatically be
* cleaned up via cascades and triggers.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int deleteAlerts(Vector list_)
{
// Be sure we have something to do.
int count = list_.size();
if (count == 0)
return 0;
// Create an array.
String list[] = new String[count];
for (count = 0; count < list_.size(); ++count)
{
list[count] = (String) list_.get(count);
}
return deleteAlerts(list);
}
/**
* Delete the Alert Definitions specified by the caller. The values must be
* existing al_idseq values within the Alert table.
*
* @param id_
* The al_idseq value which identifies the definition to delete.
* Other dependant tables in the database will automatically be
* cleaned up via cascades and triggers.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int deleteAlert(String id_)
{
// Be sure we have something to do.
if (id_ == null || id_.length() == 0)
return 0;
String list[] = new String[1];
list[0] = id_;
return deleteAlerts(list);
}
/**
* Delete the Alert Definitions specified by the caller. The values must be
* existing al_idseq values within the Alert table.
*
* @param list_
* The al_idseq values which identify the definitions to delete.
* Other dependant tables in the database will automatically be
* cleaned up via cascades and triggers.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int deleteAlerts(String list_[])
{
// Be sure we have something to do.
if (list_ == null || list_.length == 0)
return 0;
// Build the delete SQL statement.
String delete = "delete " + "from sbrext.sn_alert_view_ext "
+ "where al_idseq in (?";
for (int ndx = 1; ndx < list_.length; ++ndx)
{
delete = delete + ",?";
}
delete = delete + ")";
// Delete all the specified definitions. We rely on cascades or triggers
// to clean up
// all related tables.
PreparedStatement pstmt = null;
try
{
// Set all the SQL arguments.
pstmt = _conn.prepareStatement(delete);
for (int ndx = 0; ndx < list_.length; ++ndx)
{
pstmt.setString(ndx + 1, list_[ndx]);
}
// Send it to the database. And remember to flag a commit for later.
pstmt.executeUpdate();
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// It's bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + delete
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Add the Report display attributes to the sn_rep_contents_view_ext table.
* One (1) row per attribute.
*
* @param rec_
* The Alert definition to store in the database.
* @return 0 if successful, otherwise the Oracle error code.
* @throws java.sql.SQLException
*/
private int insertDisplay(AlertRec rec_) throws SQLException
{
return 0;
}
/**
* Update the recipients list for the Alert report.
*
* @param rec_
* The Alert definition to be saved to the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int updateRecipients(AlertRec rec_) throws SQLException
{
// We do not try to keep up with individual changes to the list. We
// simply
// wipe out the existing list and replace it with the new one.
String delete = "delete " + "from sn_recipient_view_ext "
+ "where rep_idseq = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(delete);
pstmt.setString(1, rec_.getReportRecNum());
pstmt.executeUpdate();
pstmt.close();
return insertRecipients(rec_);
}
catch (SQLException ex)
{
// Ooops...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + delete
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Add the Report recipients to the sn_report_view_ext table. One (1) row
* per recipient.
*
* @param rec_
* The Alert definition to store in the database.
* @return 0 if successful, otherwise the Oracle error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int insertRecipients(AlertRec rec_) throws SQLException
{
// Add the Recipient record(s).
String insert = "";
try
{
for (int ndx = 0; ndx < rec_.getRecipients().length; ++ndx)
{
// As we only populate 1 of possible 3 columns, the Insert
// statement
// will be dynamically configured.
insert = "insert into sbrext.sn_recipient_view_ext ";
String temp = rec_.getRecipients(ndx);
if (temp.charAt(0) == '/')
{
// It must be a Context name.
insert = insert + "(rep_idseq, conte_idseq, created_by)";
temp = temp.substring(1);
}
else if (temp.indexOf('@') > -1)
{
// It must be an email address.
insert = insert + "(rep_idseq, email, created_by)";
if (temp.length() > DBAlert._MAXEMAILLEN)
{
temp = temp.substring(0, DBAlert._MAXEMAILLEN);
rec_.setRecipients(ndx, temp);
}
}
else if (temp.startsWith("http://") || temp.startsWith("https://"))
{
// It is an process URL remove the slash at the end of URL if it exists
if (temp.endsWith("/"))
{
temp = temp.substring(0, temp.lastIndexOf("/"));
}
insert = insert + "(rep_idseq, email, created_by)";
if (temp.length() > DBAlert._MAXEMAILLEN)
{
temp = temp.substring(0, DBAlert._MAXEMAILLEN);
rec_.setRecipients(ndx, temp);
}
}
else
{
// It's a user name.
insert = insert + "(rep_idseq, ua_name, created_by)";
}
insert = insert + " values (?, ?, ?)";
// Update
PreparedStatement pstmt = _conn.prepareStatement(insert);
pstmt.setString(1, rec_.getReportRecNum());
pstmt.setString(2, temp);
pstmt.setString(3, _user);
pstmt.executeUpdate();
pstmt.close();
}
// Remember to commit. It appears that we may flagging a commit when
// the recipients list
// is empty, however, the recipients list is never to be empty and
// the other calling methods
// depend on this to set the flag.
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// Ooops...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + insert
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* A utility function that will modify the "in" clause on a SQL select to
* contain the correct number of argument replacements to match the value
* array provided.
*
* @param select_
* The SQL select that must contain a single "?" replacement within
* an "in" clause as this is the placeholder for expansion to the
* appropriate number of "?" arguments to match the length of the
* values array. Of course if the array only has a single value the
* "in" can be an "=" (equals) operator.
* @param values_
* The array of values to use as bind arguments in the select.
* @return The comma separated string containing the concatenated results
* from the select query.
*/
private String selectText(String select_, String values_[])
{
return selectText(select_, values_, 0);
}
/**
* A utility function that will modify the "in" clause on a SQL select to
* contain the correct number of argument replacements to match the value
* array provided.
*
* @param select_
* The SQL select that must contain a single "?" replacement within
* an "in" clause as this is the placeholder for expansion to the
* appropriate number of "?" arguments to match the length of the
* values array. Of course if the array only has a single value the
* "in" can be an "=" (equals) operator.
* @param values_
* The array of values to use as bind arguments in the select.
* @param flag_
* The separator to use in the concatenated string.
* @return The comma separated string containing the concatenated results
* from the select query.
*/
private String selectText(String select_, String values_[], int flag_)
{
// There must be a single "?" in the select to start the method.
int pos = select_.indexOf('?');
if (pos < 0)
return "";
// As one "?" is already in the select we only add more if the array
// length is greater than 1.
String tSelect = select_.substring(0, pos + 1);
for (int ndx = 1; ndx < values_.length; ++ndx)
tSelect = tSelect + ",?";
tSelect = tSelect + select_.substring(pos + 1);
try
{
// Now bind each value in the array to the expanded "?" list.
PreparedStatement pstmt = _conn.prepareStatement(tSelect);
for (int ndx = 0; ndx < values_.length; ++ndx)
{
pstmt.setString(ndx + 1, values_[ndx]);
}
ResultSet rs = pstmt.executeQuery();
// Concatenate the results into a single comma separated string.
tSelect = "";
String sep = (flag_ == 0) ? ", " : "\" OR \"";
while (rs.next())
{
tSelect = tSelect + sep + rs.getString(1).replaceAll("[\\r\\n]", " ");
}
rs.close();
pstmt.close();
// We always start the string with a comma so be sure to remove it
// before returning.
if (tSelect.length() > 0)
{
tSelect = tSelect.substring(sep.length());
if (flag_ == 1)
tSelect = "\"" + tSelect + "\"";
}
else
tSelect = "\"(unknown)\"";
}
catch (SQLException ex)
{
tSelect = ex.toString();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + tSelect;
_logger.error(_errorMsg);
}
return tSelect;
}
/**
* Build the summary text from the content of the alert definition.
*
* @param rec_
* The alert definition.
* @return The Alert Definition summary.
*/
public String buildSummary(AlertRec rec_)
{
String select;
// Build the Summary text. You may wonder why we access the database
// multiple times when it
// is possible to collapse all of this into a single query. The
// additional complexity of the
// SQL and resulting logic made it unmanageable. If this proves to be a
// performance problem
// we can revisit it again in the future. Remember as more features are
// added for the criteria
// and monitors the complexity lever will increase.
String criteria = "";
int specific = 0;
int marker = 1;
if (rec_.getContexts() != null)
{
if (rec_.isCONTall())
criteria = criteria + "Context may be anything ";
else
{
select = "select name || ' (v' || version || ')' as label from sbr.contexts_view "
+ "where conte_idseq in (?) order by upper(name) ASC";
criteria = criteria + "Context must be "
+ selectText(select, rec_.getContexts(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getProtocols() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isPROTOall())
criteria = criteria + "Protocols may be anything ";
else
{
select = "select long_name || ' (' || proto_id || 'v' || version || ')' as label "
+ "from sbrext.protocols_view_ext "
+ "where proto_idseq in (?) order by upper(long_name) ASC";
criteria = criteria + "Protocols must be "
+ selectText(select, rec_.getProtocols(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getForms() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isFORMSall())
criteria = criteria + "Forms / Templates may be anything ";
else
{
select = "select long_name || ' (' || qc_id || 'v' || version || ')' as label "
+ "from sbrext.quest_contents_view_ext "
+ "where qc_idseq in (?) order by upper(long_name) ASC";
criteria = criteria + "Forms / Templates must be "
+ selectText(select, rec_.getForms(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getSchemes() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isCSall())
criteria = criteria + "Classification Schemes may be anything ";
else
{
select = "select long_name || ' (' || cs_id || 'v' || version || ')' as label "
+ "from sbr.classification_schemes_view "
+ "where cs_idseq in (?) order by upper(long_name) ASC";
criteria = criteria + "Classification Schemes must be "
+ selectText(select, rec_.getSchemes(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getSchemeItems() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isCSIall())
criteria = criteria
+ "Classification Scheme Items may be anything ";
else
{
select = "select csi_name "
+ "from sbr.class_scheme_items_view "
+ "where csi_idseq in (?) order by upper(csi_name) ASC";
criteria = criteria + "Classification Scheme Items must be "
+ selectText(select, rec_.getSchemeItems(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getACTypes() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isACTYPEall())
criteria = criteria + "Administered Component Types may be anything ";
else
{
criteria = criteria + "Administered Component Types must be ";
String list = "";
for (int ndx = 0; ndx < rec_.getACTypes().length; ++ndx)
{
list = list + " OR \"" + DBAlertUtil.binarySearchS(_DBMAP3, rec_.getACTypes(ndx)) + "\"";
}
criteria = criteria + list.substring(4);
specific += marker;
}
}
marker *= 2;
if (rec_.getCWorkflow() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isCWFSall())
criteria = criteria + "Workflow Status may be anything ";
else
{
select = "select asl_name from sbr.ac_status_lov_view "
+ "where asl_name in (?) order by upper(asl_name) ASC";
criteria = criteria + "Workflow Status must be "
+ selectText(select, rec_.getCWorkflow(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getCRegStatus() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.isCRSall())
criteria = criteria + "Registration Status may be anything ";
else
{
select = "select registration_status "
+ "from sbr.reg_status_lov_view "
+ "where registration_status in (?) "
+ "order by upper(registration_status) ASC";
String txt = selectText(select, rec_.getCRegStatus(), 1);
criteria = criteria + "Registration Status must be ";
if (rec_.isCRSnone())
{
criteria = criteria + "\"(none)\"";
if (txt.length() > 0)
criteria = criteria + " OR ";
}
criteria = criteria + txt;
specific += marker;
}
}
marker *= 2;
if (rec_.getCreators() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.getCreators(0).charAt(0) == '(')
criteria = criteria + "Created By may be anyone ";
else
{
select = "select name from sbr.user_accounts_view "
+ "where ua_name in (?) order by upper(name) ASC";
criteria = criteria + "Created By must be "
+ selectText(select, rec_.getCreators(), 1);
specific += marker;
}
}
marker *= 2;
if (rec_.getModifiers() != null)
{
if (criteria.length() > 0)
criteria = criteria + " AND\n";
if (rec_.getModifiers(0).charAt(0) == '(')
criteria = criteria + "Modified By may be anyone ";
else
{
select = "select name from sbr.user_accounts_view "
+ "where ua_name in (?) order by upper(name) ASC";
criteria = criteria + "Modified By must be "
+ selectText(select, rec_.getModifiers(), 1);
specific += marker;
}
}
marker *= 2;
if (criteria.length() > 0)
criteria = criteria + " AND\n";
switch (rec_.getDateFilter())
{
case _DATECONLY:
criteria = criteria + "Reporting Dates are compared to Date Created only ";
specific += marker;
break;
case _DATEMONLY:
criteria = criteria + "Reporting Dates are compared to Date Modified only ";
specific += marker;
break;
case _DATECM:
default:
criteria = criteria + "Reporting Dates are compared to Date Created and Date Modified ";
break;
}
if (specific > 0)
criteria = "Criteria:\n" + criteria + "\n";
else
criteria = "Criteria:\nAll records within the caDSR\n";
String monitors = "";
specific = 0;
marker = 1;
if (rec_.getAWorkflow() != null)
{
if (rec_.getAWorkflow(0).charAt(0) != '(')
{
select = "select asl_name from sbr.ac_status_lov_view "
+ "where asl_name in (?) order by upper(asl_name) ASC";
monitors = monitors + "Workflow Status changes to "
+ selectText(select, rec_.getAWorkflow(), 1);
}
else if (rec_.getAWorkflow(0).equals("(Ignore)"))
monitors = monitors + ""; // "Workflow Status changes are
// ignored ";
else
{
monitors = monitors + "Workflow Status changes to anything ";
specific += marker;
}
}
marker *= 2;
if (rec_.getARegis() != null)
{
if (rec_.getARegis(0).charAt(0) != '(')
{
select = "select registration_status "
+ "from sbr.reg_status_lov_view "
+ "where registration_status in (?) "
+ "order by upper(registration_status) ASC";
if (monitors.length() > 0)
monitors = monitors + " OR\n";
monitors = monitors + "Registration Status changes to "
+ selectText(select, rec_.getARegis(), 1);
}
else if (rec_.getARegis(0).equals("(Ignore)"))
monitors = monitors + ""; // "Registration Status changes are
// ignored ";
else
{
if (monitors.length() > 0)
monitors = monitors + " OR\n";
monitors = monitors
+ "Registration Status changes to anything ";
specific += marker;
}
}
marker *= 2;
if (rec_.getAVersion() != DBAlert._VERIGNCHG)
{
if (rec_.getAVersion() == DBAlert._VERANYCHG)
specific += marker;
if (monitors.length() > 0)
monitors = monitors + " OR\n";
switch (rec_.getAVersion())
{
case DBAlert._VERANYCHG:
monitors = monitors + "Version changes to anything\n";
break;
case DBAlert._VERMAJCHG:
monitors = monitors
+ "Version Major Revision changes to anything\n";
break;
case DBAlert._VERIGNCHG:
monitors = monitors + "";
break; // "Version changes are ignored\n"; break;
case DBAlert._VERSPECHG:
monitors = monitors + "Version changes to \""
+ rec_.getActVerNum() + "\"\n";
break;
}
}
if (monitors.length() == 0)
monitors = "\nMonitors:\nIgnore all changes. Reports are always empty.\n";
else if (specific == 7)
monitors = "\nMonitors:\nAll Change Activities\n";
else
monitors = "\nMonitors:\n" + monitors;
return criteria + monitors;
}
/**
* Set the owner of the Alert Definition.
*
* @param rec_ The Alert Definition with the new creator already set.
*/
public void setOwner(AlertRec rec_)
{
// Ensure data is clean.
rec_.setDependancies();
// Update creator in database.
String update = "update sbrext.sn_alert_view_ext set created_by = ?, modified_by = ? where al_idseq = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(update);
pstmt.setString(1, rec_.getCreator());
pstmt.setString(2, _user);
pstmt.setString(3, rec_.getAlertRecNum());
pstmt.executeUpdate();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
int errorCode = ex.getErrorCode();
String errorMsg = errorCode + ": " + update
+ "\n\n" + ex.toString();
_logger.error(errorMsg);
}
}
/**
* Get the type of the AC id from the database.
* @param id_ The AC id.
* @return The [0] is the type and the [1] is the name of the AC.
*/
public String [] getACtype(String id_)
{
String out[] = new String[2];
String select =
"select 'conte', name from sbr.contexts_view where conte_idseq = ? "
+ "union "
+ "select 'cs', long_name from sbr.classification_schemes_view where cs_idseq = ? "
+ "union "
+ "select 'csi', csi_name from sbr.class_scheme_items_view where csi_idseq = ? "
+ "union "
+ "select 'qc', long_name from sbrext.quest_contents_view_ext where qc_idseq = ? and qtl_name in ('TEMPLATE','CRF') "
+ "union "
+ "select 'proto', long_name from sbrext.protocols_view_ext where proto_idseq = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, id_);
pstmt.setString(2, id_);
pstmt.setString(3, id_);
pstmt.setString(4, id_);
pstmt.setString(5, id_);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
out[0] = rs.getString(1);
out[1] = rs.getString(2);
}
else
{
out[0] = null;
out[1] = null;
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
int errorCode = ex.getErrorCode();
String errorMsg = errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(errorMsg);
}
return out;
}
/**
* Look for an Alert owned by the user with a Query which
* references the id specified.
*
* @param id_ The Context, Form, CS, etc ID_SEQ value.
* @param user_ The user who should own the Alert if it exists.
* @return true if the user already watches the id, otherwise false.
*/
public String checkQuery(String id_, String user_)
{
String select = "select al.name "
+ "from sbrext.sn_alert_view_ext al, sbrext.sn_query_view_ext qur "
+ "where al.created_by = ? and qur.al_idseq = al.al_idseq and qur.value = ?";
String rc = null;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, user_);
pstmt.setString(2, id_);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
rc = rs.getString(1);
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
int errorCode = ex.getErrorCode();
String errorMsg = errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(errorMsg);
}
return rc;
}
/**
* Check the specified user id for Sentinel Tool Administration privileges.
*
* @param user_ The user id as used during Sentinel Tool Login.
* @return true if the user has administration privileges, otherwise false.
*/
public boolean checkToolAdministrator(String user_)
{
String select = "select 1 from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' "
+ "and property like 'ADMIN.%' "
+ "and value like '%0%' "
+ "and ua_name = '" + user_ + "' "
+ "and rownum < 2";
int rows = testDB(select);
return rows == 1;
}
/**
* Retrieve the CDE Browser URL if available.
*
* @return The URL string.
*/
public String selectBrowserURL()
{
String select = "select value from sbrext.tool_options_view_ext "
+ "where tool_name = 'CDEBrowser' and property = 'URL'";
String rc = null;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
rc = rs.getString(1);
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
}
return rc;
}
/**
* Retrieve the Report Threshold
*
* @return The number of rows to allow in a report.
*/
public int selectReportThreshold()
{
String select = "select value from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' and property = 'REPORT.THRESHOLD.LIMIT'";
int rc = 100;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
rc = rs.getInt(1);
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// Ooops...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
}
return rc;
}
/**
* Read the Query clause from the database for the Alert definition
* specified.
*
* @param rec_
* The Alert record to contain the Query clause.
* @return 0 if successful, otherwise the database error code.
*/
private int selectQuery(AlertRec rec_)
{
String select = "select record_type, data_type, property, value "
+ "from sbrext.sn_query_view_ext " + "where al_idseq = ?"; // order
// by
// record_type
// ASC,
// data_type
// ASC,
// property
// ASC";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, rec_.getAlertRecNum());
ResultSet rs = pstmt.executeQuery();
Vector<String> context = new Vector<String>();
Vector<String> actype = new Vector<String>();
Vector<String> scheme = new Vector<String>();
Vector<String> schemeitem = new Vector<String>();
Vector<String> form = new Vector<String>();
Vector<String> protocol = new Vector<String>();
Vector<String> creator = new Vector<String>();
Vector<String> modifier = new Vector<String>();
Vector<String> workflow = new Vector<String>();
Vector<String> regis = new Vector<String>();
Vector<String> cregis = new Vector<String>();
Vector<String> cwork = new Vector<String>();
// After reading the query set we have to partition it into the
// appropriate individual
// variables. As the data stored in the query is internal
// representations there is
// no point to attempting to order it. Also for any one Alert there
// isn't enough rows
// to warrant the extra coding or logical overhead.
while (rs.next())
{
char rtype = rs.getString(1).charAt(0);
String dtype = rs.getString(2);
String value = rs.getString(4);
if (rtype == _CRITERIA)
{
if (dtype.equals(_CONTEXT))
context.add(value);
else if (dtype.equals(_FORM))
form.add(value);
else if (dtype.equals(_PROTOCOL))
protocol.add(value);
else if (dtype.equals(_SCHEME))
scheme.add(value);
else if (dtype.equals(_SCHEMEITEM))
schemeitem.add(value);
else if (dtype.equals(_CREATOR))
creator.add(value);
else if (dtype.equals(_MODIFIER))
modifier.add(value);
else if (dtype.equals(_ACTYPE))
actype.add(value);
else if (dtype.equals(_REGISTER))
cregis.add(value);
else if (dtype.equals(_STATUS))
cwork.add(value);
else if (dtype.equals(_DATEFILTER))
{
rec_.setDateFilter(value);
}
}
else if (rtype == _MONITORS)
{
if (dtype.equals(_STATUS))
workflow.add(value);
else if (dtype.equals(_REGISTER))
regis.add(value);
else if (dtype.equals(_VERSION))
{
rec_.setAVersion(rs.getString(3));
rec_.setActVerNum(value);
}
}
}
rs.close();
pstmt.close();
// Move the data into appropriate arrays within the Alert record to
// simplify use
// downstream.
String list[] = null;
if (context.size() == 0)
{
rec_.setContexts(null);
}
else
{
list = new String[context.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) context.get(ndx);
rec_.setContexts(list);
}
if (actype.size() == 0)
{
rec_.setACTypes(null);
}
else
{
list = new String[actype.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) actype.get(ndx);
rec_.setACTypes(list);
}
if (protocol.size() == 0)
{
rec_.setProtocols(null);
}
else
{
list = new String[protocol.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) protocol.get(ndx);
rec_.setProtocols(list);
}
if (form.size() == 0)
{
rec_.setForms(null);
}
else
{
list = new String[form.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) form.get(ndx);
rec_.setForms(list);
}
if (scheme.size() == 0)
{
rec_.setSchemes(null);
}
else
{
list = new String[scheme.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) scheme.get(ndx);
rec_.setSchemes(list);
}
if (schemeitem.size() == 0)
{
rec_.setSchemeItems(null);
}
else
{
list = new String[schemeitem.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) schemeitem.get(ndx);
rec_.setSchemeItems(list);
}
if (cregis.size() == 0)
{
rec_.setCRegStatus(null);
}
else
{
list = new String[cregis.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) cregis.get(ndx);
rec_.setCRegStatus(list);
}
if (cwork.size() == 0)
{
rec_.setCWorkflow(null);
}
else
{
list = new String[cwork.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) cwork.get(ndx);
rec_.setCWorkflow(list);
}
if (creator.size() == 0)
{
rec_.setCreators(null);
}
else
{
list = new String[creator.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) creator.get(ndx);
rec_.setCreators(list);
}
if (modifier.size() == 0)
{
rec_.setModifiers(null);
}
else
{
list = new String[modifier.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) modifier.get(ndx);
rec_.setModifiers(list);
}
if (workflow.size() == 0)
{
rec_.setAWorkflow(null);
}
else
{
list = new String[workflow.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) workflow.get(ndx);
rec_.setAWorkflow(list);
}
if (regis.size() == 0)
{
rec_.setARegis(null);
}
else
{
list = new String[regis.size()];
for (int ndx = 0; ndx < list.length; ++ndx)
list[ndx] = (String) regis.get(ndx);
rec_.setARegis(list);
}
// Create the summary string now the data is loaded.
rec_.setSummary(buildSummary(rec_));
return 0;
}
catch (SQLException ex)
{
// Ooops...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Update the Query details for the Alert.
*
* @param rec_
* The Alert definition to be updated.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int updateQuery(AlertRec rec_) throws SQLException
{
// First we delete the existing Query details as it's easier to wipe out
// the old and add
// the new than trying to track individual changes.
String delete = "delete " + "from sbrext.sn_query_view_ext "
+ "where al_idseq = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(delete);
pstmt.setString(1, rec_.getAlertRecNum());
pstmt.executeUpdate();
pstmt.close();
return insertQuery(rec_);
}
catch (SQLException ex)
{
// Ooops...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + delete
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Add the Query details to the Alert in the database.
*
* @param rec_
* The Alert definition to be added to the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int insertQuery(AlertRec rec_) throws SQLException
{
String insert = "insert into sbrext.sn_query_view_ext (al_idseq, record_type, data_type, property, value, created_by) "
+ "values (?, ?, ?, ?, ?, ?)";
int marker = 0;
try
{
PreparedStatement pstmt = _conn.prepareStatement(insert);
pstmt.setString(1, rec_.getAlertRecNum());
pstmt.setString(2, "C");
pstmt.setString(6, _user);
// We only want to record those items selected by the user that
// require special processing. For
// example, if (All) contexts were selected by the user we do not
// record (All) in the database
// because the downstream processing of the Alert only cares about
// looking for specific criteria
// and monitors. In other words, we don't want to waste time
// checking the context when (All) was
// selected because it will always logically test true.
++marker;
if (!rec_.isCONTall())
{
pstmt.setString(3, _CONTEXT);
pstmt.setString(4, "CONTE_IDSEQ");
for (int ndx = 0; ndx < rec_.getContexts().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getContexts(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isPROTOall())
{
pstmt.setString(3, _PROTOCOL);
pstmt.setString(4, "PROTO_IDSEQ");
for (int ndx = 0; ndx < rec_.getProtocols().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getProtocols(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isFORMSall())
{
pstmt.setString(3, _FORM);
pstmt.setString(4, "QC_IDSEQ");
for (int ndx = 0; ndx < rec_.getForms().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getForms(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isCSall())
{
pstmt.setString(3, _SCHEME);
pstmt.setString(4, "CS_IDSEQ");
for (int ndx = 0; ndx < rec_.getSchemes().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getSchemes(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isCSIall())
{
pstmt.setString(3, _SCHEMEITEM);
pstmt.setString(4, "CSI_IDSEQ");
for (int ndx = 0; ndx < rec_.getSchemeItems().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getSchemeItems(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getCreators(0).equals(Constants._STRALL) == false)
{
pstmt.setString(3, _CREATOR);
pstmt.setString(4, "UA_NAME");
for (int ndx = 0; ndx < rec_.getCreators().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getCreators(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getModifiers(0).equals(Constants._STRALL) == false)
{
pstmt.setString(3, _MODIFIER);
pstmt.setString(4, "UA_NAME");
for (int ndx = 0; ndx < rec_.getModifiers().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getModifiers(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isACTYPEall())
{
pstmt.setString(3, _ACTYPE);
pstmt.setString(4, "ABBREV");
for (int ndx = 0; ndx < rec_.getACTypes().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getACTypes(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getDateFilter() != DBAlert._DATECM)
{
pstmt.setString(3, _DATEFILTER);
pstmt.setString(4, "CODE");
pstmt.setString(5, Integer.toString(rec_.getDateFilter()));
pstmt.executeUpdate();
}
++marker;
if (!rec_.isCRSall())
{
pstmt.setString(3, _REGISTER);
pstmt.setString(4, "REGISTRATION_STATUS");
for (int ndx = 0; ndx < rec_.getCRegStatus().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getCRegStatus(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (!rec_.isCWFSall())
{
pstmt.setString(3, _STATUS);
pstmt.setString(4, "ASL_NAME");
for (int ndx = 0; ndx < rec_.getCWorkflow().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getCWorkflow(ndx));
pstmt.executeUpdate();
}
}
marker += 100;
pstmt.setString(2, "M");
++marker;
if (rec_.getAWorkflow(0).equals(Constants._STRANY) == false)
{
pstmt.setString(3, _STATUS);
pstmt.setString(4, "ASL_NAME");
for (int ndx = 0; ndx < rec_.getAWorkflow().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getAWorkflow(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getARegis(0).equals(Constants._STRANY) == false)
{
pstmt.setString(3, _REGISTER);
pstmt.setString(4, "REGISTRATION_STATUS");
for (int ndx = 0; ndx < rec_.getARegis().length; ++ndx)
{
// Update
pstmt.setString(5, rec_.getARegis(ndx));
pstmt.executeUpdate();
}
}
++marker;
if (rec_.getAVersion() != DBAlert._VERANYCHG)
{
pstmt.setString(3, _VERSION);
pstmt.setString(4, rec_.getAVersionString());
pstmt.setString(5, rec_.getActVerNum());
pstmt.executeUpdate();
}
// Remember to commit.
++marker;
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
// Ooops...
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = "(" + marker + "): " + _errorCode + ": "
+ insert + "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Clean the name of any illegal characters and truncate if needed.
*
* @param name_
* The name of the Alert.
* @return The corrected name.
*/
private String cleanName(String name_)
{
String name = null;
if (name_ != null)
{
name = name_.replaceAll("[\"]", "");
if (name.length() > DBAlert._MAXNAMELEN)
name = name.substring(0, DBAlert._MAXNAMELEN);
}
return name;
}
/**
* Clean the inactive reason and truncate if needed.
*
* @param reason_
* The reason message.
* @return The corrected message.
private String cleanReason(String reason_)
{
String reason = reason_;
if (reason != null && reason.length() > DBAlert._MAXREASONLEN)
{
reason = reason.substring(0, DBAlert._MAXREASONLEN);
}
return reason;
}
*/
/**
* Clean the Alert Report introduction and truncate if needed.
*
* @param intro_
* The introduction.
* @return The cleaned introduction.
*/
private String cleanIntro(String intro_)
{
String intro = intro_;
if (intro != null && intro.length() > DBAlert._MAXINTROLEN)
{
intro = intro.substring(0, DBAlert._MAXINTROLEN);
}
return intro;
}
/**
* Clean all the user enterable parts of an Alert and truncate to the
* database allowed length.
*
* @param rec_
* The Alert to be cleaned.
*/
private void cleanRec(AlertRec rec_)
{
String temp = cleanName(rec_.getName());
rec_.setName(temp);
temp = rec_.getInactiveReason(false);
rec_.setInactiveReason(temp);
temp = cleanIntro(rec_.getIntro(false));
rec_.setIntro(temp, false);
}
/**
* Insert the properties for the Alert definition and retrieve the new
* database generated ID for this Alert.
*
* @param rec_
* The Alert to be stored in the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int insertProperties(AlertRec rec_) throws SQLException
{
// Define the SQL insert. Remember date_created, date_modified, creator
// and modifier are controlled
// by triggers. Also (as of 10/21/2004) after the insert the
// date_modified is still set by the insert
// trigger.
String insert = "begin insert into sbrext.sn_alert_view_ext "
+ "(name, auto_freq_unit, al_status, begin_date, end_date, status_reason, auto_freq_value, created_by) "
+ "values (?, ?, ?, ?, ?, ?, ?, ?) return al_idseq into ?; end;";
CallableStatement pstmt = null;
cleanRec(rec_);
try
{
// Set all the SQL arguments.
pstmt = _conn.prepareCall(insert);
pstmt.setString(1, rec_.getName());
pstmt.setString(2, rec_.getFreqString());
pstmt.setString(3, rec_.getActiveString());
pstmt.setTimestamp(4, rec_.getStart());
pstmt.setTimestamp(5, rec_.getEnd());
pstmt.setString(6, rec_.getInactiveReason(false));
pstmt.setInt(7, rec_.getDay());
pstmt.setString(8, _user);
pstmt.registerOutParameter(9, Types.CHAR);
// Insert the new record and flag a commit for later.
pstmt.executeUpdate();
// We need the record id to populate the foreign keys for other
// tables.
rec_.setAlertRecNum(pstmt.getString(9));
pstmt.close();
return 0;
}
catch (SQLException ex)
{
// Ooops...
rec_.setAlertRecNum(null);
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + insert
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Insert the Report details for the Alert definition into the database and
* retrieve the new report id.
*
* @param rec_
* The Alert definition to be stored in the database.
* @return 0 if successful, otherwise the database error code.
* @throws java.sql.SQLException
* On error with rollback().
*/
private int insertReport(AlertRec rec_) throws SQLException
{
// Add the Report record.
String insert = "begin insert into sbrext.sn_report_view_ext "
+ "(al_idseq, comments, include_property_ind, style, send, acknowledge_ind, assoc_lvl_num, created_by) "
+ "values (?, ?, ?, ?, ?, ?, ?, ?) return rep_idseq into ?; end;";
CallableStatement pstmt = null;
try
{
pstmt = _conn.prepareCall(insert);
pstmt.setString(1, rec_.getAlertRecNum());
pstmt.setString(2, rec_.getIntro(false));
pstmt.setString(3, rec_.getIncPropSectString());
pstmt.setString(4, rec_.getReportStyleString());
pstmt.setString(5, rec_.getReportEmptyString());
pstmt.setString(6, rec_.getReportAckString());
pstmt.setInt(7, rec_.getIAssocLvl());
pstmt.setString(8, _user);
pstmt.registerOutParameter(9, Types.CHAR);
pstmt.executeUpdate();
// We need the record id to populate the foreign keys for other
// tables.
rec_.setReportRecNum(pstmt.getString(9));
pstmt.close();
return 0;
}
catch (SQLException ex)
{
// Ooops...
rec_.setAlertRecNum(null);
_conn.rollback();
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + insert
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Insert a DE, DEC or VD into the user reserved CSI to be monitored.
*
* @param idseq_ the database id of the AC to be monitored.
* @param user_ the user id for the reserved CSI
* @return the id of the CSI if successful, null if a problem.
*/
public String insertAC(String idseq_, String user_)
{
String user = user_.toUpperCase();
try
{
CallableStatement stmt;
stmt = _conn.prepareCall("begin SBREXT_CDE_CURATOR_PKG.ADD_TO_SENTINEL_CS(?,?,?); end;");
stmt.registerOutParameter(3, java.sql.Types.VARCHAR);
stmt.setString(2, user);
stmt.setString(1, idseq_);
stmt.execute();
String csi = stmt.getString(3);
stmt.close();
_needCommit = true;
return csi;
}
catch (SQLException ex)
{
// Ooops...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Perform an insert of a new record. The record number element of the class
* is not used AND it is not returned by this method. All other elements
* must be complete and correct.
*
* @param rec_
* The Alert definition to insert into the database table.
* @return 0 if successful, otherwise the Oracle error code.
*/
public int insertAlert(AlertRec rec_)
{
// Ensure required data dependancies.
rec_.setDependancies();
// Update the database.
try
{
int xxx = insertProperties(rec_);
if (xxx == 0)
{
xxx = insertReport(rec_);
if (xxx == 0)
{
xxx = insertRecipients(rec_);
if (xxx == 0)
{
xxx = insertDisplay(rec_);
if (xxx == 0)
{
xxx = insertQuery(rec_);
if (xxx != 0)
rec_.setAlertRecNum(null);
}
else
rec_.setAlertRecNum(null);
}
else
rec_.setAlertRecNum(null);
}
else
rec_.setAlertRecNum(null);
}
else
rec_.setAlertRecNum(null);
return xxx;
}
catch (SQLException ex)
{
// Ooops...
rec_.setAlertRecNum(null);
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Retrieve a more user friendly version of the user id.
*
* @param id_
* The id as would be entered at logon.
* @return null if the user id was not found in the sbr.user_accounts table,
* otherwise the 'name' value of the matching row.
*/
public String selectUserName(String id_)
{
// Define the SQL select.
String select = "select uav.name "
+ "from sbr.user_accounts_view uav, sbrext.user_contexts_view ucv "
+ "where uav.ua_name = ? and ucv.ua_name = uav.ua_name and ucv.privilege = 'W'";
PreparedStatement pstmt = null;
String result;
ResultSet rs = null;
try
{
// Get ready...
pstmt = _conn.prepareStatement(select);
pstmt.setString(1, id_);
// Go!
rs = pstmt.executeQuery();
if (rs.next())
{
// Get the name, remember 1 indexing.
result = rs.getString(1);
}
else
{
// User must have some kind of write permissions.
result = null;
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
// We've got trouble.
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
result = null;
}
return result;
}
private class ResultsData1
{
/**
* The label
*/
public String _label;
/**
* The key
*/
public String _val;
}
/**
* Used for method return values.
*
*/
private class Results1
{
/**
* The return code from the database.
*/
public int _rc;
/**
* The data
*/
public ResultsData1[] _data;
}
/**
* Do a basic search with a single column result.
*
* @param select_ the SQL select
* @return the array of results
*/
private String[] getBasicData0(String select_)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select_);
// Get the list.
rs = pstmt.executeQuery();
Vector<String> data = new Vector<String>();
while (rs.next())
{
data.add(rs.getString(1));
}
String[] list = new String[data.size()];
for (int i = 0; i < list.length; ++i)
{
list[i] = data.get(i);
}
rs.close();
pstmt.close();
return (list.length > 0) ? list : null;
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Execute the specified SQL select query and return a label/value pair.
*
* @param select_
* The SQL select statement.
* @param flag_
* True to prefix "(All)" to the result set. False to return the
* result set unaltered.
* @return 0 if successful, otherwise the Oracle error code.
*/
private Results1 getBasicData1(String select_, boolean flag_)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
Vector<ResultsData1> results = new Vector<ResultsData1>();
Results1 data = new Results1();
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select_);
// Get the list.
rs = pstmt.executeQuery();
ResultsData1 rec;
while (rs.next())
{
// Remember about the 1 (one) based indexing.
rec = new ResultsData1();
rec._val = rs.getString(1);
rec._label = rs.getString(2);
results.add(rec);
}
rs.close();
pstmt.close();
// We know there will always be someone in the table but we should
// follow good
// programming.
if (results.size() == 0)
{
data._data = null;
}
else
{
// Move the list from a Vector to an array and add "(All)" to
// the beginning.
int count = results.size() + ((flag_) ? 1 : 0);
data._data = new ResultsData1[count];
int ndx;
if (flag_)
{
data._data[0] = new ResultsData1();
data._data[0]._label = Constants._STRALL;
data._data[0]._val = Constants._STRALL;
ndx = 1;
}
else
{
ndx = 0;
}
int cnt = 0;
for (; ndx < count; ++ndx)
{
rec = (ResultsData1) results.get(cnt++);
data._data[ndx] = new ResultsData1();
data._data[ndx]._label = rec._label.replaceAll("[\\s]", " ");
data._data[ndx]._val = rec._val;
}
}
data._rc = 0;
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
data._rc = _errorCode;
}
return data;
}
/**
* Retrieve all the context id's for which a specific user has write
* permission.
*
* @param user_
* The user id as stored in user_accounts_view.ua_name.
* @return The array of context id values.
*/
public String[] selectContexts(String user_)
{
String select = "select cv.conte_idseq "
+ "from sbr.contexts_view cv, sbrext.user_contexts_view ucv "
+ "where ucv.ua_name = ? and ucv.privilege = 'W' and ucv.name not in ('TEST','Test','TRAINING','Training') and cv.name = ucv.name";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, user_);
ResultSet rs = pstmt.executeQuery();
Vector<String> list = new Vector<String>();
while (rs.next())
{
list.add(rs.getString(1));
}
rs.close();
pstmt.close();
String temp[] = new String[list.size()];
for (int ndx = 0; ndx < temp.length; ++ndx)
{
temp[ndx] = (String) list.get(ndx);
}
return temp;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Retrieve the list of contexts for which a user has write permission.
*
* @param user_
* The user id as stored in user_accounts_view.ua_name.
* @return The concatenated comma separated string listing the context
* names.
*/
public String selectContextString(String user_)
{
String select = "select name "
+ "from sbrext.user_contexts_view "
+ "where ua_name in (?) and privilege = 'W' and name not in ('TEST','Test','TRAINING','Training') "
+ "order by upper(name) ASC";
String temp[] = new String[1];
temp[0] = user_;
return selectText(select, temp);
}
/**
* Retrieve the list of all users from the database with a suffix of the
* context names for which each has write permission. An asterisk following
* the name indicates the email address is missing.
* <p>
* The getUsers, getUserList and getUserVals are a set of methods that must
* be used in a specific way. The getUsers() method is called first to
* populate a set of temporary data elements which can be retrieved later.
* The getUserList() method accesses the user names of the returned data and
* subsequently sets the data element to null so the memory may be
* reclaimed. The getUserVals() method accesses the user ids of the returned
* data and subsequently sets the data element to null so the memory may be
* reclaimed. Consequently getUsers() must be called first, followed by
* either getUserList() or getUserVals(). Further getUserList() and
* getUserVals() should be called only once after each invocation of
* getUsers() as additional calls will always result in a null return. See
* the comments for these other methods for more details.
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUserList getUserList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUserVals getUserVals()
*/
public int getUsers()
{
// Get the user names and id's.
String select = "select ua_name, nvl2(electronic_mail_address, 'y', 'n') || alert_ind as eflag, name "
+ "from sbr.user_accounts_view order by upper(name) ASC";
Results2 rec2 = getBasicData2(select);
if (rec2._rc == 0)
{
_namesList = new String[rec2._data.length];
_namesVals = new String[rec2._data.length];
for (int i = 0; i < _namesList.length; ++i)
{
_namesList[i] = rec2._data[i]._label;
_namesVals[i] = rec2._data[i]._id1;
}
// Build the list of names that are exempt from Context Curator
// Group broadcasts.
_namesExempt = "";
// Get the context names for which each id has write permission.
select = "select distinct uav.name, ucv.name "
+ "from sbrext.user_contexts_view ucv, sbr.user_accounts_view uav "
+ "where ucv.privilege = 'W' and ucv.ua_name = uav.ua_name "
+ "order by upper(uav.name) ASC, upper(ucv.name) ASC";
Results1 rec = getBasicData1(select, false);
if (rec._rc == 0)
{
// Build the user list in the format <user name>[*] [(context
// list)] where <user name> is the
// in user presentable form followed by an optional asterisk to
// indicate the email address is missing
// from the user record followed by an optional list of context
// names for those contexts which the
// user has write permissions.
int vcnt = 0;
int ncnt = 1;
String prefix = " (";
String fixname = "";
while (ncnt < _namesList.length && vcnt < rec._data.length)
{
int test = _namesList[ncnt].compareToIgnoreCase(rec._data[vcnt]._val);
if (test < 0)
{
// Add the missing email flag to the suffix.
String suffix = "";
if (rec2._data[ncnt]._id2.charAt(0) == 'n')
suffix = "*";
// Add the Context list to the suffix.
if (prefix.charAt(0) == ',')
{
if (rec2._data[ncnt]._id2.charAt(1) == 'N')
_namesExempt = _namesExempt + ", "
+ _namesList[ncnt];
suffix = suffix + fixname + ")";
prefix = " (";
fixname = "";
}
// Add the suffix to the name.
_namesList[ncnt] = _namesList[ncnt] + suffix;
++ncnt;
}
else if (test > 0)
{
++vcnt;
}
else
{
fixname = fixname + prefix + rec._data[vcnt]._label;
prefix = ", ";
++vcnt;
}
}
}
// Fix the exempt list.
if (_namesExempt.length() == 0)
_namesExempt = null;
else
_namesExempt = _namesExempt.substring(2);
}
return rec2._rc;
}
/**
* Retrieve the valid user list. The method getUsers() must be called first.
* Once this method is used the internal copy is deleted to reclaim the
* memory space.
*
* @return An array of strings from the sbr.user_accounts.name column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
*/
public String[] getUserList()
{
String temp[] = _namesList;
_namesList = null;
return temp;
}
/**
* Retrieve the list of users exempt from Context Curator broadcasts. The
* method getUsers() must be called first. Once this method is used the
* internal copy is deleted to reclaim the memory space.
*
* @return A comma separated list of names.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
*/
public String getUserExempts()
{
String temp = _namesExempt;
_namesExempt = null;
return temp;
}
/**
* Retrieve the valid user list. The method getUsers() must be called first.
* Once this method is used the internal copy is deleted to reclaim the
* memory space.
*
* @return An array of strings from the sbr.user_accounts.ua_name column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
*/
public String[] getUserVals()
{
String temp[] = _namesVals;
_namesVals = null;
return temp;
}
/**
* Retrieve the Context names and id's from the database. This follows the
* pattern documented with getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getGroupList getGroupList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getGroupVals getGroupVals()
*/
public int getGroups()
{
String select = "select uav.ua_name, '/' || cv.conte_idseq as id, 0, "
+ "uav.name || nvl2(uav.electronic_mail_address, '', '*') as name, ucv.name "
+ "from sbrext.user_contexts_view ucv, sbr.user_accounts_view uav, sbr.contexts_view cv "
+ "where ucv.privilege = 'W' "
+ "and ucv.ua_name = uav.ua_name "
+ "and uav.alert_ind = 'Yes' "
+ "and ucv.name = cv.name "
+ "and cv.conte_idseq NOT IN ( "
+ "select tov.value "
+ "from sbrext.tool_options_view_ext tov "
+ "where tov.tool_name = 'SENTINEL' and "
+ "tov.property like 'BROADCAST.EXCLUDE.CONTEXT.%.CONTE_IDSEQ') "
+ "order by upper(ucv.name) ASC, upper(uav.name) ASC";
Results3 rec = getBasicData3(select, false);
if (rec._rc == 0)
{
// Count the number of groups.
String temp = rec._data[0]._id2;
int cnt = 1;
for (int ndx = 1; ndx < rec._data.length; ++ndx)
{
if (!temp.equals(rec._data[ndx]._id2))
{
temp = rec._data[ndx]._id2;
++cnt;
}
}
// Allocate space for the lists.
_groupsList = new String[cnt + rec._data.length];
_groupsVals = new String[_groupsList.length];
// Copy the data.
temp = "";
cnt = 0;
for (int ndx = 0; ndx < rec._data.length; ++ndx)
{
if (!temp.equals(rec._data[ndx]._id2))
{
temp = rec._data[ndx]._id2;
_groupsList[cnt] = rec._data[ndx]._label2;
_groupsVals[cnt] = rec._data[ndx]._id2;
++cnt;
}
_groupsList[cnt] = rec._data[ndx]._label1;
_groupsVals[cnt] = rec._data[ndx]._id1;
++cnt;
}
return 0;
}
return rec._rc;
}
/**
* Retrieve the valid context list. The method getGroups() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.contexts_view.name column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getGroups getGroups()
*/
public String[] getGroupList()
{
String temp[] = _groupsList;
_groupsList = null;
return temp;
}
/**
* Retrieve the valid context id list. The method getGroups() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.contexts_view.conte_idseq column
* and prefixed with a '/' character.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getGroups getGroups()
*/
public String[] getGroupVals()
{
String temp[] = _groupsVals;
_groupsVals = null;
return temp;
}
/**
* Get the list of unused concepts
*
* @param ids_ the list of unused concept ids
* @return the list of name, public id and version
*/
public String[] reportUnusedConcepts(String[] ids_)
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Version" + cs1
+ "Date Accessed" + cs1 + "Workflow Status" + cs1 + "EVS Source" + cs1
+ "Concept Code' as title, ' ' as lname from dual UNION ALL "
+ "SELECT con.long_name" + cs2 + "con.con_id" + cs2 + "con.version" + cs2
+ "nvl(date_modified, date_created)" + cs2 + "con.asl_name" + cs2 + "nvl(con.evs_source, ' ')" + cs2
+ "nvl(con.preferred_name, ' ') as title, upper(con.long_name) as lname "
+ "FROM sbrext.concepts_view_ext con "
+ "WHERE con.asl_name NOT LIKE 'RETIRED%' and con.con_idseq in (";
String temp = "";
for (int i = 0; i < ids_.length && i < 1000; ++i)
{
temp += ",'" + ids_[i] + "'";
}
select += temp.substring(1) + ") order by lname asc";
return getBasicData0(select);
}
/**
* Get the list of unused property records.
*
* @return The list of name, public id and version
*/
public String[] reportUnusedProperties()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Date Created" + cs1 + "Workflow Status" + cs1 + "Context" + cs1
+ "Display" + cs1 + "Concept" + cs1 + "Concept Code" + cs1 + "Origin" + cs1 + "Public ID" + cs1 + "Date Created" + cs1 + "Workflow Status' "
+ "as title, ' ' as lname, 0 as pid, ' ' as pidseq, 0 as dorder from dual UNION ALL "
+ "SELECT prop.long_name" + cs2 + "prop.prop_id || 'v' || prop.version" + cs2 + "prop.date_created" + cs2 + "prop.asl_name" + cs2 + "c.name " + cs2
+ "ccv.display_order" + cs2 + "con.long_name" + cs2 + "con.preferred_name" + cs2 + " con.origin" + cs2 + "con.con_id || 'v' || con.version" + cs2 + "con.date_created" + cs2 + "con.asl_name "
+ "as title, upper(prop.long_name) as lname, prop.prop_id as pid, prop.prop_idseq as pidseq, ccv.display_order as dorder "
+ "FROM sbrext.properties_view_ext prop, sbr.contexts_view c, "
+ "sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext con "
+ "WHERE prop.asl_name NOT LIKE 'RETIRED%' and prop.prop_idseq NOT IN "
+ "(SELECT decv.prop_idseq "
+ "FROM sbr.data_element_concepts_view decv "
+ "WHERE decv.prop_idseq = prop.prop_idseq) "
+ "AND c.conte_idseq = prop.conte_idseq "
+ "AND ccv.condr_idseq = prop.condr_idseq "
+ "AND con.con_idseq = ccv.con_idseq "
+ "order by lname asc, pid ASC, pidseq ASC, dorder DESC";
return getBasicData0(select);
}
/**
* Get the list of Administered Component which do not have a public id.
*
* @return the list of ac type, name, and idseq.
*/
public String[] reportMissingPublicID()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'AC Type" + cs1 + "Name" + cs1 + "ID" + cs1 + "Context' as title, ' ' as tname, ' ' as lname from dual UNION ALL "
+ "select ac.actl_name" + cs2 + "ac.long_name" + cs2 + "ac.ac_idseq" + cs2 + "c.name as title, upper(ac.actl_name) as tname, upper(ac.long_name) as lname "
+ "from sbr.admin_components_view ac, sbr.contexts_view c where ac.public_id is null "
+ "and ac.asl_name NOT LIKE 'RETIRED%' "
+ "and c.conte_idseq = ac.conte_idseq "
+ "order by tname asc";
return getBasicData0(select);
}
/**
* Get the list of unused data element concept records.
*
* @return The list of name, public id and version
*/
public String[] reportUnusedDEC()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Version" + cs1 + "Workflow Status" + cs1 + "Context' as title, ' ' as lname from dual UNION ALL "
+ "SELECT dec.long_name" + cs2 + "dec.dec_id" + cs2 + "dec.version" + cs2 + "dec.asl_name" + cs2 + "c.name as title, upper(dec.long_name) as lname "
+ "FROM sbr.data_element_concepts_view dec, sbr.contexts_view c "
+ "WHERE dec.asl_name NOT LIKE 'RETIRED%' and dec.dec_idseq NOT IN "
+ "(SELECT de.dec_idseq FROM sbr.data_elements_view de WHERE de.dec_idseq = dec.dec_idseq) "
+ "and c.conte_idseq = dec.conte_idseq "
+ "order by lname asc";
return getBasicData0(select);
}
/**
* Get the list of unused object class records.
*
* @return The list of name, public id and version
*/
public String[] reportUnusedObjectClasses()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Date Created" + cs1 + "Workflow Status" + cs1 + "Context" + cs1
+ "Display" + cs1 + "Concept" + cs1 + "Concept Code" + cs1 + "Origin" + cs1 + "Public ID" + cs1 + "Date Created" + cs1 + "Workflow Status' "
+ "as title, ' ' as lname, 0 as ocid, ' ' as ocidseq, 0 as dorder from dual UNION ALL "
+ "SELECT oc.long_name" + cs2 + "oc.oc_id || 'v' || oc.version" + cs2 + "oc.date_created" + cs2 + "oc.asl_name" + cs2 + "c.name" + cs2
+ "ccv.display_order" + cs2 + "con.long_name" + cs2 + "con.preferred_name" + cs2 + " con.origin" + cs2 + "con.con_id || 'v' || con.version" + cs2 + "con.date_created" + cs2 + "con.asl_name "
+ "as title, upper(oc.long_name) as lname, oc.oc_id as ocid, oc.oc_idseq as ocidseq, ccv.display_order as dorder "
+ "FROM sbrext.object_classes_view_ext oc, sbr.contexts_view c, "
+ "sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext con "
+ "WHERE oc.asl_name NOT LIKE 'RETIRED%' and oc.oc_idseq NOT IN "
+ "(SELECT decv.oc_idseq "
+ "FROM sbr.data_element_concepts_view decv "
+ "WHERE decv.OC_IDSEQ = oc.oc_idseq) "
+ "AND c.conte_idseq = oc.conte_idseq "
+ "AND ccv.condr_idseq = oc.condr_idseq "
+ "AND con.con_idseq = ccv.con_idseq "
+ "order by lname asc, ocid ASC, ocidseq ASC, dorder DESC";
return getBasicData0(select);
}
/**
* Get the list of Data Elements which do not have question text and are referenced by a Form.
*
* @return the list of name, public id and version.
*/
public String[] reportMissingQuestionText()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Version" + cs1 + "Workflow Status" + cs1 + "Context' as title, ' ' as lname from dual UNION ALL "
+ "select de.long_name" + cs2 + "de.cde_id" + cs2 + "de.version" + cs2 + "de.asl_name" + cs2 + "c.name as title, upper(de.long_name) as lname "
+ "from sbr.data_elements_view de, sbr.contexts_view c "
+ "where de.asl_name NOT LIKE 'RETIRED%' "
+ "and de.de_idseq in (select qc.de_idseq from sbrext.quest_contents_view_ext qc where qc.de_idseq = de.de_idseq) "
+ "and de.de_idseq not in (select rd.ac_idseq from sbr.reference_documents_view rd where rd.ac_idseq = de.de_idseq and dctl_name in ('Alternate Question Text','Preferred Question Text')) "
+ "and c.conte_idseq = de.conte_idseq "
+ "order by lname asc";
return getBasicData0(select);
}
/**
* Retrieve the Context names and id's from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getContextList getContextList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getContextVals getContextVals()
*/
public int getContexts()
{
// Get the context names and id's.
String select = "select conte_idseq, name from sbr.contexts_view "
+ "order by upper(name) ASC";
Results1 rec = getBasicData1(select, true);
if (rec._rc == 0)
{
_contextList = new String[rec._data.length];
_contextVals = new String[rec._data.length];
for (int i = 0; i < _contextList.length; ++i)
{
_contextList[i] = rec._data[i]._label;
_contextVals[i] = rec._data[i]._val;
}
return 0;
}
return rec._rc;
}
/**
* Retrieve the EVS properties in the tool options table
*
* @return the array of properties.
*/
public DBProperty[] selectEVSVocabs()
{
String select = "select opt.value, opt.property from sbrext.tool_options_view_ext opt where opt.tool_name = 'CURATION' and ("
+ "opt.property like 'EVS.VOCAB.%.PROPERTY.NAMESEARCH' or "
+ "opt.property like 'EVS.VOCAB.%.EVSNAME' or "
+ "opt.property like 'EVS.VOCAB.%.DISPLAY' or "
+ "opt.property like 'EVS.VOCAB.%.PROPERTY.DEFINITION' or "
+ "opt.property like 'EVS.VOCAB.%.ACCESSREQUIRED' "
+ ") order by opt.property";
Results1 rs = getBasicData1(select, false);
if (rs._rc == 0 && rs._data.length > 0)
{
DBProperty[] props = new DBProperty[rs._data.length];
for (int i = 0; i < rs._data.length; ++i)
{
props[i] = new DBProperty(rs._data[i]._label, rs._data[i]._val);;
}
return props;
}
return null;
}
/**
* Select all the caDSR Concepts
*
* @return the Concepts
*/
public Vector<ConceptItem> selectConcepts()
{
// Get the context names and id's.
String select = "SELECT con_idseq, con_id, version, evs_source, preferred_name, long_name, definition_source, preferred_definition "
+ "FROM sbrext.concepts_view_ext WHERE asl_name NOT LIKE 'RETIRED%' "
+ "ORDER BY upper(long_name) ASC";
Statement stmt = null;
Vector<ConceptItem> list = new Vector<ConceptItem>();
try
{
// Prepare the statement.
stmt = _conn.createStatement();
ResultSet rs = stmt.executeQuery(select);
// Get the list.
while (rs.next())
{
ConceptItem rec = new ConceptItem();
rec._idseq = rs.getString(1);
rec._publicID = rs.getString(2);
rec._version = rs.getString(3);
rec._evsSource = rs.getString(4);
rec._preferredName = rs.getString(5);
rec._longName = rs.getString(6);
rec._definitionSource = rs.getString(7);
rec._preferredDefinition = rs.getString(8);
list.add(rec);
}
rs.close();
stmt.close();
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
return list;
}
/**
* Retrieve the valid context list. The method getGroups() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.contexts_view.name column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getContexts getContexts()
*/
public String[] getContextList()
{
String temp[] = _contextList;
_contextList = null;
return temp;
}
/**
* Retrieve the valid context id list. The method getGroups() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.contexts_view.conte_idseq
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getContexts getContexts()
*/
public String[] getContextVals()
{
String temp[] = _contextVals;
_contextVals = null;
return temp;
}
/**
* Get the complete Workflow Status value list from the database. Follows
* the pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflowList getWorkflowList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflowVals getWorkflowVals()
*/
public int getWorkflow()
{
// For compatibility and consistency we treat this view as all others as
// if it has id and name
// columns. For some reason this view is designed to expose the real id
// to the end user.
String select = "select asl_name, 'C' "
+ "from sbr.ac_status_lov_view order by upper(asl_name) ASC";
Results1 rec = getBasicData1(select, false);
if (rec._rc == 0)
{
// Add the special values "(All)", "(Any Change)" and "(Ignore)"
_workflowList = new String[rec._data.length + 3];
_workflowVals = new String[rec._data.length + 3];
int ndx = 0;
_workflowList[ndx] = Constants._STRALL;
_workflowVals[ndx++] = Constants._STRALL;
_workflowList[ndx] = Constants._STRANY;
_workflowVals[ndx++] = Constants._STRANY;
_workflowList[ndx] = Constants._STRIGNORE;
_workflowVals[ndx++] = Constants._STRIGNORE;
for (int cnt = 0; cnt < rec._data.length; ++cnt)
{
_workflowList[ndx] = rec._data[cnt]._val;
_workflowVals[ndx++] = rec._data[cnt]._val;
}
// Add the special values "(All)", "(Any Change)" and "(Ignore)"
_cworkflowList = new String[rec._data.length + 1];
_cworkflowVals = new String[rec._data.length + 1];
ndx = 0;
_cworkflowList[ndx] = Constants._STRALL;
_cworkflowVals[ndx++] = Constants._STRALL;
for (int cnt = 0; cnt < rec._data.length; ++cnt)
{
_cworkflowList[ndx] = rec._data[cnt]._val;
_cworkflowVals[ndx++] = rec._data[cnt]._val;
}
}
return rec._rc;
}
/**
* Retrieve the valid workflow list. The method getWorkflow() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.ac_status_lov_view.asl_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflow getWorkflow()
*/
public String[] getWorkflowList()
{
String temp[] = _workflowList;
_workflowList = null;
return temp;
}
/**
* Retrieve the valid workflow values. The method getWorkflow() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the sbr.ac_status_lov_view.asl_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflow getWorkflow()
*/
public String[] getWorkflowVals()
{
String temp[] = _workflowVals;
_workflowVals = null;
return temp;
}
/**
* Retrieve the valid workflow list. The method getWorkflow() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.ac_status_lov_view.asl_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflow getWorkflow()
*/
public String[] getCWorkflowList()
{
String temp[] = _cworkflowList;
_cworkflowList = null;
return temp;
}
/**
* Retrieve the valid workflow values. The method getWorkflow() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the sbr.ac_status_lov_view.asl_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getWorkflow getWorkflow()
*/
public String[] getCWorkflowVals()
{
String temp[] = _cworkflowVals;
_cworkflowVals = null;
return temp;
}
/**
* Retrieve the valid registration statuses. Follows the pattern documented
* in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegStatusList getRegStatusList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegStatusVals getRegStatusVals()
*/
public int getRegistrations()
{
// For compatibility and consistency we treat this view as all others as
// if it has id and name
// columns. For some reason this view is designed to expose the real id
// to the end user.
String select = "select registration_status, 'C' "
+ "from sbr.reg_status_lov_view "
+ "order by upper(registration_status) ASC";
Results1 rec = getBasicData1(select, false);
if (rec._rc == 0)
{
// Add the special values "(All)", "(Any Change)" and "(Ignore)"
_regStatusList = new String[rec._data.length + 3];
_regStatusVals = new String[rec._data.length + 3];
int ndx = 0;
_regStatusList[ndx] = Constants._STRALL;
_regStatusVals[ndx++] = Constants._STRALL;
_regStatusList[ndx] = Constants._STRANY;
_regStatusVals[ndx++] = Constants._STRANY;
_regStatusList[ndx] = Constants._STRIGNORE;
_regStatusVals[ndx++] = Constants._STRIGNORE;
for (int cnt = 0; cnt < rec._data.length; ++cnt)
{
_regStatusList[ndx] = rec._data[cnt]._val;
_regStatusVals[ndx++] = rec._data[cnt]._val;
}
// Add the special value "(All)" and "(none)" for the Criteria entries
_regCStatusList = new String[rec._data.length + 2];
_regCStatusVals = new String[rec._data.length + 2];
ndx = 0;
_regCStatusList[ndx] = Constants._STRALL;
_regCStatusVals[ndx++] = Constants._STRALL;
_regCStatusList[ndx] = Constants._STRNONE;
_regCStatusVals[ndx++] = Constants._STRNONE;
for (int cnt = 0; cnt < rec._data.length; ++cnt)
{
_regCStatusList[ndx] = rec._data[cnt]._val;
_regCStatusVals[ndx++] = rec._data[cnt]._val;
}
}
return rec._rc;
}
/**
* Retrieve the registration status list. The method getRegistrations() must
* be called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbr.reg_status_lov_view.registration_status column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegistrations getRegistrations()
*/
public String[] getRegStatusList()
{
String temp[] = _regStatusList;
_regStatusList = null;
return temp;
}
/**
* Retrieve the registration status values list. The method
* getRegistrations() must be called first. Once this method is used the
* internal copy is deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbr.reg_status_lov_view.registration_status column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegistrations getRegistrations()
*/
public String[] getRegStatusVals()
{
String temp[] = _regStatusVals;
_regStatusVals = null;
return temp;
}
/**
* Retrieve the registration status list. The method getRegistrations() must
* be called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbr.reg_status_lov_view.registration_status column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegistrations getRegistrations()
*/
public String[] getRegCStatusList()
{
String temp[] = _regCStatusList;
_regCStatusList = null;
return temp;
}
/**
* Retrieve the registration status values list. The method
* getRegistrations() must be called first. Once this method is used the
* internal copy is deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbr.reg_status_lov_view.registration_status column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getRegistrations getRegistrations()
*/
public String[] getRegCStatusVals()
{
String temp[] = _regCStatusVals;
_regCStatusVals = null;
return temp;
}
/**
* Retrieve the Protocols from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtoList getProtoList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtoVals getProtoVals()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtoContext getProtoContext()
*/
public int getProtos()
{
String select = "select pr.conte_idseq, pr.proto_idseq, pr.long_name || ' (v' || pr.version || ' / ' || CV.name || ')' AS lname "
+ "from sbrext.protocols_view_ext pr, sbr.contexts_view cv "
+ "where cv.conte_idseq = pr.conte_idseq order by UPPER(lname) asc";
Results2 rec = getBasicData2(select);
if (rec._rc == 0)
{
_protoList = new String[rec._data.length];
_protoVals = new String[rec._data.length];
_protoContext = new String[rec._data.length];
for (int i = 0; i < _protoList.length; ++i)
{
_protoList[i] = rec._data[i]._label;
_protoVals[i] = rec._data[i]._id2;
_protoContext[i] = rec._data[i]._id1;
}
}
return rec._rc;
}
/**
* Retrieve the protocol list. The method getProtos() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.protocols_view_ext.long_name, version and context
* columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtos getProtos()
*/
public String[] getProtoList()
{
String temp[] = _protoList;
_protoList = null;
return temp;
}
/**
* Retrieve the protocol list. The method getProtos() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.protocols_view_ext.proto_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtos getProtos()
*/
public String[] getProtoVals()
{
String temp[] = _protoVals;
_protoVals = null;
return temp;
}
/**
* Retrieve the protocol list. The method getProtos() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.protocols_view_ext.conte_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getProtos getProtos()
*/
public String[] getProtoContext()
{
String temp[] = _protoContext;
_protoContext = null;
return temp;
}
/**
* Retrieve the Classification Schemes from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeList getSchemeList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeVals getSchemeVals()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeContext getSchemeContext()
*/
public int getSchemes()
{
String select = "select csv.conte_idseq, csv.cs_idseq, csv.long_name || ' (v' || csv.version || ' / ' || cv.name || ')' as lname "
+ "from sbr.classification_schemes_view csv, sbr.contexts_view cv "
+ "where cv.conte_idseq = csv.conte_idseq order by upper(lname) ASC";
Results2 rec = getBasicData2(select);
if (rec._rc == 0)
{
_schemeList = new String[rec._data.length];
_schemeVals = new String[rec._data.length];
_schemeContext = new String[rec._data.length];
for (int i = 0; i < _schemeList.length; ++i)
{
_schemeList[i] = rec._data[i]._label;
_schemeVals[i] = rec._data[i]._id2;
_schemeContext[i] = rec._data[i]._id1;
}
}
return rec._rc;
}
/**
* Retrieve the classification scheme list. The method getSchemes() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbr.classification_schemes_view.long_name, version and context
* columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemes getSchemes()
*/
public String[] getSchemeList()
{
String temp[] = _schemeList;
_schemeList = null;
return temp;
}
/**
* Retrieve the classification scheme id's. The method getSchemes() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbr.classification_schemes_view.cs_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemes getSchemes()
*/
public String[] getSchemeVals()
{
String temp[] = _schemeVals;
_schemeVals = null;
return temp;
}
/**
* Retrieve the context id's associated with the classification scheme id's
* retrieved above. The method getSchemes() must be called first. Once this
* method is used the internal copy is deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbr.classification_schemes_view.conte_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemes getSchemes()
*/
public String[] getSchemeContext()
{
String temp[] = _schemeContext;
_schemeContext = null;
return temp;
}
private class schemeTree
{
/**
* Constructor.
*
* @param name_ The composite name for sorting.
* @param ndx_ The index of the scheme item in the original list.
*/
public schemeTree(String name_, int ndx_)
{
_fullName = name_;
_ndx = ndx_;
}
/**
* The composite name used for sorting.
*/
public String _fullName;
/**
* The index in the original list.
*/
public int _ndx;
}
/**
* Build the concatenated strings for the Class Scheme Items display.
*
* @param rec_
* The data returned from Oracle.
* @return An array of the full concatenated names for sorting later.
*/
private schemeTree[] buildSchemeItemList(Results3 rec_)
{
// Get the maximum number of levels and the maximum length of a single
// name.
int maxLvl = 0;
int maxLen = 0;
for (int ndx = 1; ndx < rec_._data.length; ++ndx)
{
if (maxLvl < rec_._data[ndx]._id3)
maxLvl = rec_._data[ndx]._id3;
if (rec_._data[ndx]._label1 != null
&& maxLen < rec_._data[ndx]._label1.length())
maxLen = rec_._data[ndx]._label1.length();
if (rec_._data[ndx]._label2 != null
&& maxLen < rec_._data[ndx]._label2.length())
maxLen = rec_._data[ndx]._label2.length();
}
++maxLvl;
// Build and array of prefixes for the levels.
String prefix[] = new String[maxLvl];
prefix[0] = "";
if (maxLvl > 1)
{
prefix[1] = "";
for (int ndx = 2; ndx < prefix.length; ++ndx)
{
prefix[ndx] = prefix[ndx - 1] + " ";
}
}
// In addition to creating the display labels we must also
// create an array used to sort everything alphabetically.
// The easiest is to create a fully concatenated label of a
// individuals hierarchy.
_schemeItemList = new String[rec_._data.length];
maxLvl *= maxLen;
StringBuffer fullBuff = new StringBuffer(maxLvl);
fullBuff.setLength(maxLvl);
schemeTree tree[] = new schemeTree[_schemeItemList.length];
// Loop through the name list.
_schemeItemList[0] = rec_._data[0]._label1;
tree[0] = new schemeTree("", 0);
for (int ndx = 1; ndx < _schemeItemList.length; ++ndx)
{
// Create the concatenated sort string.
int buffOff = (rec_._data[ndx]._id3 < 2) ? 0 : (rec_._data[ndx]._id3 * maxLen);
fullBuff.replace(buffOff, maxLvl, rec_._data[ndx]._label1);
fullBuff.setLength(maxLvl);
// Create the display label.
if (rec_._data[ndx]._id3 == 1)
{
if (rec_._data[ndx]._label2 == null)
{
_schemeItemList[ndx] = rec_._data[ndx]._label1;
}
else
{
_schemeItemList[ndx] = rec_._data[ndx]._label1 + " ("
+ rec_._data[ndx]._label2 + ")";
fullBuff.replace(buffOff + maxLen, maxLvl,
rec_._data[ndx]._label2);
fullBuff.setLength(maxLvl);
}
}
else
{
_schemeItemList[ndx] = prefix[rec_._data[ndx]._id3]
+ rec_._data[ndx]._label1;
}
tree[ndx] = new schemeTree(fullBuff.toString(), ndx);
}
return tree;
}
/**
* Retrieve the Classification Scheme Items from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItemList getSchemeItemList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItemVals getSchemeItemVals()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItemSchemes
* getSchemeItemScheme()
*/
public int getSchemeItems()
{
String select = "select cv.cs_idseq, cv.csi_idseq, level as lvl, "
+ "(select csi.csi_name from sbr.class_scheme_items_view csi where csi.csi_idseq = cv.csi_idseq), "
+ "(select cs.long_name || ' / v' || cs.version as xname from sbr.classification_schemes_view cs where cs.cs_idseq = cv.cs_idseq) "
+ "from sbr.cs_csi_view cv "
+ "start with cv.p_cs_csi_idseq is null "
+ "connect by prior cv.cs_csi_idseq = cv.p_cs_csi_idseq";
Results3 rec = getBasicData3(select, true);
if (rec._rc == 0)
{
schemeTree tree[] = buildSchemeItemList(rec);
_schemeItemVals = new String[rec._data.length];
_schemeItemSchemes = new String[rec._data.length];
for (int i = 0; i < rec._data.length; ++i)
{
_schemeItemVals[i] = rec._data[i]._id2;
_schemeItemSchemes[i] = rec._data[i]._id1;
}
sortSchemeItems(tree);
}
return rec._rc;
}
/**
* Sort the scheme items lists and make everything right on the display.
*
* @param tree_
* The concatenated name tree list.
*/
private void sortSchemeItems(schemeTree tree_[])
{
// Too few items don't bother.
if (tree_.length < 2)
return;
// The first element is the "All" indicator, so don't include it.
schemeTree sort[] = new schemeTree[tree_.length];
sort[0] = tree_[0];
sort[1] = tree_[1];
int top = 2;
// Perform a binary search-insert.
for (int ndx = 2; ndx < tree_.length; ++ndx)
{
int min = 1;
int max = top;
int check = 0;
while (true)
{
check = (max + min) / 2;
int test = tree_[ndx]._fullName
.compareToIgnoreCase(sort[check]._fullName);
if (test == 0)
break;
else if (test > 0)
{
if (min == check)
{
++check;
break;
}
min = check;
}
else
{
if (max == check)
break;
max = check;
}
}
// Add the record to the proper position in the sorted array.
if (check < top)
System.arraycopy(sort, check, sort, check + 1, top - check);
++top;
sort[check] = tree_[ndx];
}
// Now arrange all the arrays based on the sorted index.
String tempList[] = new String[_schemeItemList.length];
String tempVals[] = new String[_schemeItemList.length];
String tempSchemes[] = new String[_schemeItemList.length];
for (int ndx = 0; ndx < sort.length; ++ndx)
{
int pos = sort[ndx]._ndx;
tempList[ndx] = _schemeItemList[pos];
tempVals[ndx] = _schemeItemVals[pos];
tempSchemes[ndx] = _schemeItemSchemes[pos];
}
_schemeItemList = tempList;
_schemeItemVals = tempVals;
_schemeItemSchemes = tempSchemes;
}
/**
* Retrieve the classification scheme item list. The method getSchemeItems()
* must be called first. Once this method is used the internal copy is
* deleted to reclaim the memory space.
*
* @return An array of strings from the sbr.class_scheme_items_view.csi_name
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItems getSchemeItems()
*/
public String[] getSchemeItemList()
{
String temp[] = _schemeItemList;
_schemeItemList = null;
return temp;
}
/**
* Retrieve the classification scheme item id's. The method getSchemeItems()
* must be called first. Once this method is used the internal copy is
* deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbr.class_scheme_items_view.csi_idseq column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItems getSchemeItems()
*/
public String[] getSchemeItemVals()
{
String temp[] = _schemeItemVals;
_schemeItemVals = null;
return temp;
}
/**
* Retrieve the class scheme id's associated with the classification scheme
* item id's retrieved above. The method getSchemeItems() must be called
* first. Once this method is used the internal copy is deleted to reclaim
* the memory space.
*
* @return An array of strings from the sbr.class_scheme_items_view.cs_idseq
* column.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getSchemeItems getSchemeItems()
*/
public String[] getSchemeItemSchemes()
{
String temp[] = _schemeItemSchemes;
_schemeItemSchemes = null;
return temp;
}
private class ResultsData2
{
/**
* id1
*/
public String _id1;
/**
* id2
*/
public String _id2;
/**
* label
*/
public String _label;
}
/**
* Class used to return method results.
*/
private class Results2
{
/**
* The database return code.
*/
public int _rc;
/**
* data
*/
public ResultsData2[] _data;
}
/**
* Perform the database access for a simple query which results in a 3
* column value per returned row.
*
* @param select_
* The SQL select to run.
* @return 0 if successful, otherwise the database error code.
*/
private Results2 getBasicData2(String select_)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
Vector<ResultsData2> results = new Vector<ResultsData2>();
Results2 data = new Results2();
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select_);
// Get the list.
rs = pstmt.executeQuery();
ResultsData2 rec;
while (rs.next())
{
// Remember about the 1 (one) based indexing.
rec = new ResultsData2();
rec._id1 = rs.getString(1);
rec._id2 = rs.getString(2);
rec._label = rs.getString(3);
results.add(rec);
}
rs.close();
pstmt.close();
// Move the list from a Vector to an array and add "(All)" to
// the beginning.
int count = results.size() + 1;
data._data = new ResultsData2[count];
data._data[0] = new ResultsData2();
data._data[0]._label = Constants._STRALL;
data._data[0]._id1 = Constants._STRALL;
data._data[0]._id2 = Constants._STRALL;
int cnt = 0;
for (int ndx = 1; ndx < count; ++ndx)
{
rec = (ResultsData2) results.get(cnt++);
data._data[ndx] = new ResultsData2();
data._data[ndx]._label = rec._label.replaceAll("[\\s]", " ");
data._data[ndx]._id1 = rec._id1;
data._data[ndx]._id2 = rec._id2;
}
data._rc = 0;
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
data._rc = _errorCode;
}
return data;
}
class ResultsData3
{
/**
*
*/
public String _id1;
/**
*
*/
public String _id2;
/**
*
*/
public int _id3;
/**
*
*/
public String _label1;
/**
*
*/
public String _label2;
}
;
/**
* Class used to return method results.
*/
private class Results3
{
/**
* The database return code.
*/
public int _rc;
/**
* The data
*/
public ResultsData3[] _data;
}
/**
* Perform the database access for a simple query which results in a 4
* column value per returned row.
*
* @param select_
* The SQL select to run.
* @param flag_ true if the list should be prefixed with "All".
* @return 0 if successful, otherwise the database error code.
*/
private Results3 getBasicData3(String select_, boolean flag_)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
Vector<ResultsData3> results = new Vector<ResultsData3>();
Results3 data = new Results3();
try
{
// Prepare the statement.
pstmt = _conn.prepareStatement(select_);
// Get the list.
rs = pstmt.executeQuery();
ResultsData3 rec;
while (rs.next())
{
// Remember about the 1 (one) based indexing.
rec = new ResultsData3();
rec._id1 = rs.getString(1);
rec._id2 = rs.getString(2);
rec._id3 = rs.getInt(3);
rec._label1 = rs.getString(4);
rec._label2 = rs.getString(5);
results.add(rec);
}
rs.close();
pstmt.close();
// Move the list from a Vector to an array and add "(All)" to
// the beginning.
int offset = (flag_) ? 1 : 0;
int count = results.size() + offset;
data._data = new ResultsData3[count];
if (flag_)
{
data._data[0] = new ResultsData3();
data._data[0]._label1 = Constants._STRALL;
data._data[0]._label2 = Constants._STRALL;
data._data[0]._id1 = Constants._STRALL;
data._data[0]._id2 = Constants._STRALL;
data._data[0]._id3 = 0;
}
int cnt = 0;
for (int ndx = offset; ndx < count; ++ndx)
{
rec = (ResultsData3) results.get(cnt++);
data._data[ndx] = new ResultsData3();
data._data[ndx]._label1 = rec._label1.replaceAll("[\\s]", " ");
data._data[ndx]._label2 = rec._label2.replaceAll("[\\s]", " ");
data._data[ndx]._id1 = rec._id1;
data._data[ndx]._id2 = rec._id2;
data._data[ndx]._id3 = rec._id3;
}
data._rc = 0;
}
catch (SQLException ex)
{
// Bad...
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
data._rc = _errorCode;
}
return data;
}
/**
* Retrieve the list of record types. As this is coded in a constant
* array, no database access is required.
*
* @return 0 if successful.
*/
public int getACTypes()
{
String[] list = new String[_DBMAP3.length + 1];
String[] vals = new String[_DBMAP3.length + 1];
list[0] = Constants._STRALL;
vals[0] = Constants._STRALL;
list[1] = _DBMAP3[0]._val;
vals[1] = _DBMAP3[0]._key;
// Put the descriptive text in alphabetic order for display.
// Of course we have to keep the key-value pairs intact.
for (int ndx = 1; ndx < _DBMAP3.length; ++ndx)
{
int min = 1;
int max = ndx + 1;
int pos = 1;
while (true)
{
pos = (max + min) / 2;
int compare = _DBMAP3[ndx]._val.compareTo(list[pos]);
if (compare == 0)
{
// Can't happen.
}
else if (compare > 0)
{
if (min == pos)
{
++pos;
break;
}
min = pos;
}
else
{
if (max == pos)
{
break;
}
max = pos;
}
}
// Preserve existing entries - an insert.
if (pos <= ndx)
{
System.arraycopy(list, pos, list, pos + 1, ndx - pos + 1);
System.arraycopy(vals, pos, vals, pos + 1, ndx - pos + 1);
}
// Insert new item in list.
list[pos] = _DBMAP3[ndx]._val;
vals[pos] = _DBMAP3[ndx]._key;
}
// Keep the results.
_actypesList = list;
_actypesVals = vals;
return 0;
}
/**
* Return the descriptive names for the record types.
*
* @return The list of display values.
*/
public String[] getACTypesList()
{
String temp[] = _actypesList;
_actypesList = null;
return temp;
}
/**
* Return the internal values used to identify the record types.
*
* @return The list of internal record types.
*/
public String[] getACTypesVals()
{
String temp[] = _actypesVals;
_actypesVals = null;
return temp;
}
/**
* Retrieve the list of forms and templates from the database. Follows the
* pattern documented in getUsers().
*
* @return 0 if successful, otherwise the database error code.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getUsers getUsers()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getFormsList getFormsList()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getFormsVals getFormsVals()
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getFormsContext getFormsContext()
*/
public int getForms()
{
// Build a composite descriptive string for this form.
String select =
"select qcv.conte_idseq, qcv.qc_idseq, qcv.long_name || "
+ "' (v' || qcv.version || ' / ' || qcv.qtl_name || ' / ' || nvl(proto.long_name, '(' || cv.name || ')') || ')' as lname "
+ "from sbrext.quest_contents_view_ext qcv, sbr.contexts_view cv, "
+ "sbrext.protocol_qc_ext pq, sbrext.protocols_view_ext proto "
+ "where qcv.qtl_name in ('TEMPLATE','CRF') "
+ "and cv.conte_idseq = qcv.conte_idseq "
+ "and qcv.qc_idseq = pq.qc_idseq(+) "
+ "and pq.proto_idseq = proto.proto_idseq(+) "
+ "order by upper(lname)";
Results2 rec = getBasicData2(select);
if (rec._rc == 0)
{
_formsList = new String[rec._data.length];
_formsVals = new String[rec._data.length];
_formsContext = new String[rec._data.length];
for (int ndx = 0; ndx < _formsList.length; ++ndx)
{
// Can you believe that some people put quotes in the name? We
// have to escape them or it causes
// problems downstream.
_formsList[ndx] = rec._data[ndx]._label;
_formsList[ndx] = _formsList[ndx].replaceAll("[\"]", "\\\\\"");
_formsList[ndx] = _formsList[ndx].replaceAll("[\\r\\n]", " ");
_formsVals[ndx] = rec._data[ndx]._id2;
_formsContext[ndx] = rec._data[ndx]._id1;
}
}
return rec._rc;
}
/**
* Return the forms/templates composite names. The method getForms() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.quest_contents_view_ext.long_name, ... columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getForms getForms()
*/
public String[] getFormsList()
{
String temp[] = _formsList;
_formsList = null;
return temp;
}
/**
* Return the forms/templates id values. The method getForms() must be
* called first. Once this method is used the internal copy is deleted to
* reclaim the memory space.
*
* @return An array of strings from the
* sbrext.quest_contents_view_ext.qc_idseq columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getForms getForms()
*/
public String[] getFormsVals()
{
String temp[] = _formsVals;
_formsVals = null;
return temp;
}
/**
* Return the context id's associated with the forms/templates. The method
* getForms() must be called first. Once this method is used the internal
* copy is deleted to reclaim the memory space.
*
* @return An array of strings from the
* sbrext.quest_contents_view_ext.conte_idseq columns.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getForms getForms()
*/
public String[] getFormsContext()
{
String temp[] = _formsContext;
_formsContext = null;
return temp;
}
/**
* Return the last recorded database error message. If the current error
* code is zero (0) an empty string is returned.
*
* @return The last database error message or an empty string.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getErrorCode getErrorCode()
*/
public String getErrorMsg()
{
return (_errorCode != 0) ? _errorMsg : null;
}
/**
* Return the last recorded database error message. If the current error
* code is zero (0) an empty string is returned.
*
* @param flag_
* True if the new lines ('\n') should be expanded to text for use in
* script. False to return the message unaltered.
* @return The last database error message or an empty string.
* @see gov.nih.nci.cadsr.sentinel.database.DBAlert#getErrorCode getErrorCode()
*/
public String getErrorMsg(boolean flag_)
{
return (_errorCode != 0) ? ((flag_) ? _errorMsg.replaceAll("[\\n]",
"\\\\n") : _errorMsg) : null;
}
/**
* Return the last recorded database error code and then reset it to zero
* (0).
*
* @return The database error code.
*/
public int getErrorCode()
{
int rc = _errorCode;
_errorCode = 0;
return rc;
}
/**
* Return any error message and reset the error code to zero for the next
* possible error.
*
* @return The database error message.
*/
public String getError()
{
String temp = getErrorMsg();
if (temp != null)
_errorCode = 0;
return temp;
}
/**
* Get the Alerts which are active for the target date provided.
*
* @param target_
* The target date, typically the date an Auto Run process is
* started.
* @return null if an error, otherwise the list of valid alert definitions.
*/
public AlertRec[] selectAlerts(Timestamp target_)
{
String select = "select al_idseq, name, created_by "
+ "from sbrext.sn_alert_view_ext " + "where al_status <> 'I' AND "
+ "(auto_freq_unit = 'D' OR "
+ "(auto_freq_unit = 'W' AND auto_freq_value = ?) OR "
+ "(auto_freq_unit = 'M' AND auto_freq_value = ?)) "
+ "order by upper(created_by) asc, upper(name) asc";
// Get day and date from target to qualify the select.
GregorianCalendar tdate = new GregorianCalendar();
tdate.setTimeInMillis(target_.getTime());
int dayWeek = tdate.get(Calendar.DAY_OF_WEEK);
int dayMonth = tdate.get(Calendar.DAY_OF_MONTH);
try
{
// Set SQL arguments
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setInt(1, dayWeek);
pstmt.setInt(2, dayMonth);
// Retrieve all applicable definition ids.
ResultSet rs = pstmt.executeQuery();
Vector<String> list = new Vector<String>();
while (rs.next())
{
list.add(rs.getString(1));
}
rs.close();
pstmt.close();
// There may be nothing to do.
if (list.size() == 0)
return new AlertRec[0];
// retrieve the full alert definition, we will need it.
AlertRec recs[] = new AlertRec[list.size()];
int keep = 0;
int ndx;
for (ndx = 0; ndx < recs.length; ++ndx)
{
// Be sure we can read the Alert Definition.
recs[keep] = selectAlert((String) list.get(ndx));
if (recs[keep] == null)
return null;
// Check the date. We do this here and not in the SQL because
// 99.99% of the time this will return true and complicating the
// SQL isn't necessary.
if (recs[keep].isActive(target_))
++keep;
// In the RARE situation that the alert is inactive at this
// point,
// we reset the object pointer to release the memory.
else
recs[keep] = null;
}
// Return the results. It is possible that sometimes the last entry
// in the
// list will be null. Consequently the use of the list should be in
// a loop
// with the following condition: "cnt < recs.length && recs[cnt] !=
// null"
if (keep == ndx)
return recs;
// Only process the ones that are Active.
AlertRec trecs[] = new AlertRec[keep];
for (ndx = 0; ndx < keep; ++ndx)
trecs[ndx] = recs[ndx];
return trecs;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Convert a Vector of Strings to an array.
*
* @param list_
* The vector.
* @return The string array.
*/
private String[] paste(Vector<String> list_)
{
String temp[] = new String[list_.size()];
for (int ndx = 0; ndx < temp.length; ++ndx)
temp[ndx] = list_.get(ndx);
return temp;
}
/**
* Convert a Vector of Timestamps to an array.
*
* @param list_ The vector.
* @return The Timestamp array.
*/
private Timestamp[] paste(Vector<Timestamp> list_)
{
Timestamp temp[] = new Timestamp[list_.size()];
for (int ndx = 0; ndx < temp.length; ++ndx)
temp[ndx] = list_.get(ndx);
return temp;
}
/**
* Copy the result set to an ACData array.
*
* @param rs_
* The query result set.
* @return The ACData array if successful, otherwise null.
* @throws java.sql.SQLException
* When there is a problem with the result set.
*/
private ACData[] copyResults(ResultSet rs_) throws SQLException
{
Vector<ACData> data = new Vector<ACData>();
Vector<String> changes = new Vector<String>();
Vector<String> oval = new Vector<String>();
Vector<String> nval = new Vector<String>();
Vector<String> tabl = new Vector<String>();
Vector<String> chgby = new Vector<String>();
Vector<Timestamp> dval = new Vector<Timestamp>();
String clist[] = null;
String olist[] = null;
String nlist[] = null;
String tlist[] = null;
String blist[] = null;
Timestamp dlist[] = null;
ACData oldrec = null;
int cols = rs_.getMetaData().getColumnCount();
while (rs_.next())
{
ACData rec = new ACData();
rec.set(
rs_.getString(1).charAt(0),
rs_.getInt(2),
rs_.getString(3),
rs_.getString(4),
rs_.getString(5),
rs_.getInt(6),
rs_.getString(7),
rs_.getString(8),
rs_.getTimestamp(9),
rs_.getTimestamp(10),
rs_.getString(11),
rs_.getString(12),
rs_.getString(13),
rs_.getString(14),
rs_.getString(15));
// We don't want to waste time or space with records that are
// identical. We can't use a SELECT DISTINCT for this logic as the
// ACData.equals doesn't look at all data elements but only specific ones.
if (oldrec != null)
{
if (!oldrec.isEquivalent(rec))
{
clist = paste(changes);
olist = paste(oval);
nlist = paste(nval);
dlist = paste(dval);
tlist = paste(tabl);
blist = paste(chgby);
oldrec.setChanges(clist, olist, nlist, dlist, tlist, blist);
data.add(oldrec);
changes = new Vector<String>();
oval = new Vector<String>();
nval = new Vector<String>();
dval = new Vector<Timestamp>();
tabl = new Vector<String>();
chgby = new Vector<String>();
}
}
// Build the list of specific changes if we can get them. We must
// save
// always save the information if present.
//
// NOTE we only record the first 18 columns of the result set but
// there may be
// more to make the SQL work as desired.
if (cols > 17)
{
String ctext = rs_.getString(16);
// If the "change" column is blank don't waste the space.
if (ctext != null && ctext.length() > 0)
{
changes.add(ctext);
oval.add(rs_.getString(17));
nval.add(rs_.getString(18));
dval.add(rs_.getTimestamp(19));
tabl.add(rs_.getString(20));
chgby.add(rs_.getString(21));
}
}
oldrec = rec;
}
if (oldrec != null)
{
clist = paste(changes);
olist = paste(oval);
nlist = paste(nval);
dlist = paste(dval);
tlist = paste(tabl);
blist = paste(chgby);
oldrec.setChanges(clist, olist, nlist, dlist, tlist, blist);
data.add(oldrec);
}
ACData list[] = new ACData[data.size()];
if (data.size() > 0)
{
for (int ndx = 0; ndx < list.length; ++ndx)
{
list[ndx] = (ACData) data.get(ndx);
}
}
return list;
}
/**
* Pull rows changed in the date range specified. There are 3 different
* patterns to handle:
* <p>
* <ul>
* <li>[from/to, from/to] {2, 4} - This represents the from/to date pair
* which may occur 2 or 4 times in the SQL. This pattern is handled by this
* method argument list.</li>
* <li>[in, from/to, from/to] {2, 4} - This represents a single "in" clause
* of creators or modifiers followed by the from/to pair which may occur 2
* or 4 times in the SQL in this order.</li>
* <li>[in, in, from/to, from/to] {2,4} - This represents an "in" clause
* for the creators and an "in" clause for the modifiers followed by the
* from/to pair which in total may appear 1 or 2 times.</li>
* </ul>
* </p>
*
* @param select_
* The SQL select for the specific data and table.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param pairs_
* The number of pairs of (start, end) that appear in the SQL.
* @return 0 if successful, otherwise the database error code.
*/
private ACData[] selectAC(String select_, Timestamp start_, Timestamp end_,
int pairs_)
{
try
{
PreparedStatement pstmt = _conn.prepareStatement(select_);
for (int ndx = 0; ndx < pairs_; ++ndx)
{
pstmt.setTimestamp((ndx * 2) + 1, start_);
pstmt.setTimestamp((ndx * 2) + 2, end_);
}
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Generate a string of comma separated SQL arguments for us in an "in"
* clause.
*
* @param cnt_
* The number of place holders needed.
* @return String The comma separated string without parentheses.
*/
private String expandMarkers(int cnt_)
{
String markers = "?";
for (int ndx = 1; ndx < cnt_; ++ndx)
{
markers = markers + ",?";
}
return markers;
}
/**
* Pull rows changed in the date range specified. There are 3 different
* patterns to handle:
* <p>
* <ul>
* <li>[from/to, from/to] {2, 4} - This represents the from/to date pair
* which may occur 2 or 4 times in the SQL.</li>
* <li>[in, from/to, from/to] {2, 4} - This represents a single "in" clause
* of creators or modifiers followed by the from/to pair which may occur 2
* or 4 times in the SQL in this order. This pattern is handled by this
* method argument list.</li>
* <li>[in, in, from/to, from/to] {2,4} - This represents an "in" clause
* for the creators and an "in" clause for the modifiers followed by the
* from/to pair which in total may appear 1 or 2 times.</li>
* </ul>
* </p>
*
* @param select_
* The SQL select for the specific data and table.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param pairs_
* The number of pairs of (start, end) that appear in the SQL.
* @param vals_
* The additional values used by an "in" clause.
* @return 0 if successful, otherwise the database error code.
*/
private ACData[] selectAC(String select_, Timestamp start_, Timestamp end_,
int pairs_, String vals_[])
{
// Expand the "in" clause.
int loop = pairs_ / 2;
String markers = expandMarkers(vals_.length);
String parts[] = select_.split("\\?");
int pos = 0;
String select = parts[pos++];
for (int cnt = 0; cnt < loop; ++cnt)
{
select = select + markers + parts[pos++];
for (int ndx = 0; ndx < 2; ++ndx)
{
select = select + "?" + parts[pos++] + "?" + parts[pos++];
}
}
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
int arg = 1;
for (int cnt = 0; cnt < loop; ++cnt)
{
for (int ndx = 0; ndx < vals_.length; ++ndx)
{
pstmt.setString(arg++, vals_[ndx]);
}
for (int ndx = 0; ndx < 2; ++ndx)
{
pstmt.setTimestamp(arg++, start_);
pstmt.setTimestamp(arg++, end_);
}
}
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Pull rows changed in the date range specified. There are 3 different
* patterns to handle:
* <p>
* <ul>
* <li>[from/to, from/to] {2, 4} - This represents the from/to date pair
* which may occur 2 or 4 times in the SQL.</li>
* <li>[in, from/to, from/to] {2, 4} - This represents a single "in" clause
* of creators or modifiers followed by the from/to pair which may occur 2
* or 4 times in the SQL in this order.</li>
* <li>[in, in, from/to, from/to] {2,4} - This represents an "in" clause
* for the creators and an "in" clause for the modifiers followed by the
* from/to pair which in total may appear 1 or 2 times. This pattern is
* handled by this method argument list.</li>
* </ul>
* </p>
*
* @param select_
* The SQL select for the specific data and table.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param pairs_
* The number of pairs of (start, end) that appear in the SQL.
* @param vals1_
* The additional values used by an "in" clause.
* @param vals2_
* The additional values used by a second "in" clause.
* @return 0 if successful, otherwise the database error code.
*/
private ACData[] selectAC(String select_, Timestamp start_, Timestamp end_,
int pairs_, String vals1_[], String vals2_[])
{
// Expand the "in" clauses.
String parts[] = select_.split("\\?");
int loop = pairs_ / 2;
String markers1 = expandMarkers(vals1_.length);
String markers2 = expandMarkers(vals2_.length);
int pos = 0;
String select = parts[pos++];
for (int cnt = 0; cnt < loop; ++cnt)
{
select = select + markers1 + parts[pos++] + markers2 + parts[pos++];
for (int ndx = 0; ndx < 2; ++ndx)
{
select = select + "?" + parts[pos++] + "?" + parts[pos++];
}
}
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
int arg = 1;
for (int cnt = 0; cnt < loop; ++cnt)
{
for (int ndx = 0; ndx < vals1_.length; ++ndx)
{
pstmt.setString(arg++, vals1_[ndx]);
}
for (int ndx = 0; ndx < vals2_.length; ++ndx)
{
pstmt.setString(arg++, vals2_[ndx]);
}
for (int ndx = 0; ndx < 2; ++ndx)
{
pstmt.setTimestamp(arg++, start_);
pstmt.setTimestamp(arg++, end_);
}
}
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
private ACData[] selectAC(String select_)
{
try
{
PreparedStatement pstmt = _conn.prepareStatement(select_);
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select_
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
private int selectChangedTableType(String idseq_)
{
String select = "select changed_table from sbrext.ac_change_history_ext "
+ "where changed_table_idseq = ? and rownum < 2";
int itype = -1;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, idseq_);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
String stype = rs.getString(1);
if (stype.equals("CLASSIFICATION_SCHEMES"))
itype = _ACTYPE_CS;
else if (stype.equals("DATA_ELEMENTS"))
itype = _ACTYPE_DE;
else if (stype.equals("DATA_ELEMENT_CONCEPTS"))
itype = _ACTYPE_DEC;
else if (stype.equals("OBJECT_CLASSES_EXT"))
itype = _ACTYPE_OC;
else if (stype.equals("PROPERTIES_EXT"))
itype = _ACTYPE_PROP;
else if (stype.equals("VALUE_DOMAINS"))
itype = _ACTYPE_VD;
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
}
return itype;
}
/**
* Build a complex SQL from individual phrases. The calling method provides
* an array of strings for the SQL SELECT with each representing a specific
* part of the combined statement. Using the presence or absence of other
* argument values, a composite statement is formed and executed.
*
* @param select_
* The array of component parts of the SQL SELECT.
* @param start_
* The start date of the date range. The record date must be greater
* than or equal to this value.
* @param end_
* The end date of the date range. The record date must be less than
* this value.
* @param pairs_
* The number of date pairs that appear in the master array.
* @param creators_
* The creator (created by) ids of the records or null.
* @param modifiers_
* The modifier (modified by) ids of the records or null.
* @return The result of the composite SQL.
*/
private ACData[] selectAC(String select_[], Timestamp start_,
Timestamp end_, int pairs_, String creators_[], String modifiers_[])
{
String select = select_[0];
int pattern = 0;
if (creators_ != null && creators_[0].charAt(0) != '(')
{
pattern += 1;
select = select + select_[1];
}
if (modifiers_ != null && modifiers_[0].charAt(0) != '(')
{
pattern += 2;
select = select + select_[2];
}
select = select + select_[3];
if (pairs_ == 4)
{
if (creators_ != null && creators_[0].charAt(0) != '(')
select = select + select_[4];
if (modifiers_ != null && modifiers_[0].charAt(0) != '(')
select = select + select_[5];
select = select + select_[6];
}
switch (pattern)
{
case 1:
return selectAC(select, start_, end_, pairs_, creators_);
case 2:
return selectAC(select, start_, end_, pairs_, modifiers_);
case 3:
return selectAC(select, start_, end_, pairs_, creators_,
modifiers_);
default:
return selectAC(select, start_, end_, pairs_);
}
}
/**
* Pull all Permissible Values changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectPV(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[])
{
// There's always one that doesn't fit the pattern. Any changes to
// selectBuild() must also be checked here for consistency.
String start = "to_date('" + start_.toString().substring(0, 10) + "', 'yyyy/mm/dd')";
String end = "to_date('" + end_.toString().substring(0, 10) + "', 'yyyy/mm/dd')";
String select =
"select 'p', 1, 'pv', zz.pv_idseq as id, '', -1, zz.value, '', "
+ "zz.date_modified, zz.date_created, zz.modified_by, zz.created_by, '', "
+ "'', '', ach.changed_column, ach.old_value, ach.new_value, ach.change_datetimestamp, ach.changed_table, ach.changed_by "
+ "from sbrext.ac_change_history_ext ach, sbr.permissible_values_view zz ";
select = select + "where ach.change_datetimestamp >= " + start + " and ach.change_datetimestamp < " + end + " ";
if (modifiers_ != null && modifiers_.length > 0 && modifiers_[0].charAt(0) != '(')
select = select + "AND ach.changed_by in " + selectIN(modifiers_);
select = select + whereACH(_ACTYPE_PV)
+ "AND zz.pv_idseq = ach.ac_idseq ";
if (creators_ != null && creators_.length > 0 && creators_[0].charAt(0) != '(')
select = select + "AND zz.created_by in " + selectIN(creators_);
if (dates_ == _DATECONLY)
select = select + "AND zz.date_created >= " + start + " and zz.date_created < " + end + " ";
else if (dates_ == _DATEMONLY)
select = select + "AND zz.date_modified is not NULL ";
select = select + _orderbyACH;
return selectAC(select);
}
/**
* Pull all Value Meanings changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectVM(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND zz.asl_name IN " + selectIN(wstatus_);
}
String[] select = new String[4];
select[0] =
"select 'p', 1, 'vm', zz.short_meaning as id, zz.version, zz.vm_id, zz.long_name, zz.conte_idseq as cid, "
+ "zz.date_modified as ctime, zz.date_created, zz.modified_by, zz.created_by, zz.comments, c.name, '' "
+ "from sbr.value_meanings_view zz, sbr.contexts_view c where ";
select[1] = "zz.created_by in (?) and ";
select[2] = "zz.modified_by in (?) and ";
select[3] = "((zz.date_modified is not null and zz.date_modified "
+ _DATECHARS[dates_][0] + " ? and zz.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (zz.date_created is not null and zz.date_created "
+ _DATECHARS[dates_][2] + " ? and zz.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ "and c.conte_idseq = zz.conte_idseq " + wfs_clause
+ " order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Concepts changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCON(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND zz.asl_name IN " + selectIN(wstatus_);
}
String[] select = new String[4];
select[0] =
"select 'p', 1, 'con', zz.con_idseq as id, zz.version, zz.con_id, zz.long_name, zz.conte_idseq as cid, "
+ "zz.date_modified as ctime, zz.date_created, zz.modified_by, zz.created_by, zz.change_note, c.name, '' "
+ "from sbrext.concepts_view_ext zz, sbr.contexts_view c where ";
select[1] = "zz.created_by in (?) and ";
select[2] = "zz.modified_by in (?) and ";
select[3] = "((zz.date_modified is not null and zz.date_modified "
+ _DATECHARS[dates_][0] + " ? and zz.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (zz.date_created is not null and zz.date_created "
+ _DATECHARS[dates_][2] + " ? and zz.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ "and c.conte_idseq = zz.conte_idseq " + wfs_clause
+ " order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Value Domains changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectVD(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_VD,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Pull all Conceptual Domain changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCD(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND cd.asl_name IN " + selectIN(wstatus_);
}
int pairs;
String select[] = new String[7];
select[0] = "(select 'p', 1, 'cd', cd.cd_idseq as id, cd.version, cd.cd_id, cd.long_name, cd.conte_idseq as cid, "
+ "cd.date_modified as ctime, cd.date_created, cd.modified_by, cd.created_by, cd.change_note, c.name, '' "
+ "from sbr.conceptual_domains_view cd, sbr.contexts_view c "
+ "where c.conte_idseq = cd.conte_idseq and ";
select[1] = "cd.created_by in (?) and ";
select[2] = "cd.modified_by in (?) and ";
pairs = 2;
select[3] = "((cd.date_modified is not null and cd.date_modified "
+ _DATECHARS[dates_][0] + " ? and cd.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (cd.date_created is not null and cd.date_created "
+ _DATECHARS[dates_][2] + " ? and cd.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ ") order by id asc, cid asc";
return selectAC(select, start_, end_, pairs, creators_, modifiers_);
}
/**
* Pull all Classification Schemes changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCS(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_CS,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Pull all Property changes in the date range
* specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectPROP(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_PROP,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Pull all Object Class changes in the date range
* specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectOC(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_OC,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Pull all Forms/Templates Value Values changed in the date range
* specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectQCV(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND qc.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'qcv', qc.qc_idseq as id, qc.version, qc.qc_id, "
+ "qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified as ctime, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, '' "
+ "from sbrext.quest_contents_view_ext qc, sbr.contexts_view c "
+ "where qc.qtl_name = 'VALID_VALUE' and c.conte_idseq = qc.conte_idseq and ";
select[1] = "qc.created_by in (?) and ";
select[2] = "qc.modified_by in (?) and ";
select[3] = "((qc.date_modified is not null and qc.date_modified "
+ _DATECHARS[dates_][0] + " ? and qc.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (qc.date_created is not null and qc.date_created "
+ _DATECHARS[dates_][2] + " ? and qc.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Forms/Templates Questions changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectQCQ(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND qc.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'qcq', qc.qc_idseq as id, qc.version, qc.qc_id, "
+ "qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified as ctime, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, '' "
+ "from sbrext.quest_contents_view_ext qc, sbr.contexts_view c "
+ "where qc.qtl_name in ('QUESTION', 'QUESTION_INSTR') and c.conte_idseq = qc.conte_idseq and ";
select[1] = "qc.created_by in (?) and ";
select[2] = "qc.modified_by in (?) and ";
select[3] = "((qc.date_modified is not null and qc.date_modified "
+ _DATECHARS[dates_][0] + " ? and qc.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (qc.date_created is not null and qc.date_created "
+ _DATECHARS[dates_][2] + " ? and qc.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Forms/Templates Modules changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectQCM(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND qc.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'qcm', qc.qc_idseq as id, qc.version, qc.qc_id, "
+ "qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified as ctime, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, '' "
+ "from sbrext.quest_contents_view_ext qc, sbr.contexts_view c "
+ "where qc.qtl_name = 'MODULE' and c.conte_idseq = qc.conte_idseq and ";
select[1] = "qc.created_by in (?) and ";
select[2] = "qc.modified_by in (?) and ";
select[3] = "((qc.date_modified is not null and qc.date_modified "
+ _DATECHARS[dates_][0] + " ? and qc.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (qc.date_created is not null and qc.date_created "
+ _DATECHARS[dates_][2] + " ? and qc.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Protocols changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectPROTO(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND proto.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'proto', proto.proto_idseq as id, proto.version, proto.proto_id, "
+ "proto.long_name, proto.conte_idseq as cid, "
+ "proto.date_modified as ctime, proto.date_created, proto.modified_by, proto.created_by, proto.change_note, c.name, '' "
+ "from sbrext.protocols_view_ext proto, sbr.contexts_view c "
+ "where c.conte_idseq = proto.conte_idseq and ";
select[1] = "proto.created_by in (?) and ";
select[2] = "proto.modified_by in (?) and ";
select[3] = "((proto.date_modified is not null and proto.date_modified "
+ _DATECHARS[dates_][0] + " ? and proto.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (proto.date_created is not null and proto.date_created "
+ _DATECHARS[dates_][2] + " ? and proto.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Forms/Templates changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectQC(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
else
{
wfs_clause = "AND qc.asl_name IN " + selectIN(wstatus_);
}
String select[] = new String[4];
select[0] = "select 'p', 1, 'qc', qc.qc_idseq as id, qc.version, qc.qc_id, "
+ "qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified as ctime, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, '' "
+ "from sbrext.quest_contents_view_ext qc, sbr.contexts_view c "
+ "where qc.qtl_name in ('FORM', 'TEMPLATE') and c.conte_idseq = qc.conte_idseq and ";
select[1] = "qc.created_by in (?) and ";
select[2] = "qc.modified_by in (?) and ";
select[3] = "((qc.date_modified is not null and qc.date_modified "
+ _DATECHARS[dates_][0] + " ? and qc.date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (qc.date_created is not null and qc.date_created "
+ _DATECHARS[dates_][2] + " ? and qc.date_created " + _DATECHARS[dates_][3] + " ?)) "
+ wfs_clause
+ "order by id asc, cid asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Pull all Classification Scheme Items changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCSI(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[])
{
String select[] = new String[4];
select[0] = "select 'p', 1, 'csi', csi_idseq as id, '', -1, csi_name, '', "
+ "date_modified, date_created, modified_by, created_by, comments, '', '' "
+ "from sbr.class_scheme_items_view " + "where ";
select[1] = "created_by in (?) and ";
select[2] = "modified_by in (?) and ";
select[3] = "((date_modified is not null and date_modified "
+ _DATECHARS[dates_][0] + " ? and date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (date_created is not null and date_created "
+ _DATECHARS[dates_][2] + " ? and date_created " + _DATECHARS[dates_][3] + " ?)) "
+ "order by id asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Expand the list to an IN clause.
*
* @param regs_ The list of DE registration statuses.
* @return The expanded IN clause.
*/
private String selectIN(String regs_[])
{
String temp = "";
for (int ndx = 0; ndx < regs_.length; ++ndx)
{
temp = temp + ", '" + regs_[ndx] + "'";
}
return "(" + temp.substring(2) + ") ";
}
/**
* Construct the standard change history table where clause.
*
* @param table_ The primary changed_table value, one of _ACTYPE_...
* @return The where clause.
*/
private String whereACH(int table_)
{
String temp = "AND ach.ac_idseq in "
+ "(select distinct ch2.changed_table_idseq from sbrext.ac_change_history_ext ch2 "
+ "where ch2.changed_table = '" + _DBMAP3[table_]._col + "' and ch2.changed_table_idseq = ach.ac_idseq) "
+ "and ach.changed_column not in ('DATE_CREATED', 'DATE_MODIFIED', 'LAE_NAME') "
+ "and (ach.changed_table = '" + _DBMAP3[table_]._col + "' or "
+ "(ach.changed_table = 'AC_CSI' and ach.changed_column = 'CS_CSI_IDSEQ') or "
+ "(ach.changed_table = 'DESIGNATIONS' and ach.changed_column in ('CONTE_IDSEQ', 'DETL_NAME', 'LAE_NAME')) or "
+ "(ach.changed_table = 'REFERENCE_DOCUMENTS' and ach.changed_column in ('DCTL_NAME', 'DISPLAY_ORDER', 'DOC_TEXT', 'RDTL_NAME', 'URL')) or "
+ "(ach.changed_table = 'VD_PVS' and ach.changed_column = 'PV_IDSEQ')) ";
return temp;
}
/**
* Pull all Data Elements changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @param rstatus_
* The list of desired Registration Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectDE(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[], String rstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_DE,
dates_, start_, end_, creators_, modifiers_, wstatus_, rstatus_));
}
/**
* Return the CON_IDSEQ for referenced (used) concepts.
*
* @return the con_idseq list
*/
public String[] selectUsedConcepts()
{
String select = "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbr.value_domains_view zz "
+ "where cv.condr_idseq = zz.condr_idseq "
+ "union "
+ "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbrext.object_classes_view_ext zz "
+ "where cv.condr_idseq = zz.condr_idseq "
+ "union "
+ "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbrext.properties_view_ext zz "
+ "where cv.condr_idseq = zz.condr_idseq "
+ "union "
+ "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbr.value_meanings_view zz "
+ "where cv.condr_idseq = zz.condr_idseq "
+ "union "
+ "select cv.con_idseq "
+ "from sbrext.component_concepts_view_ext cv, sbrext.representations_ext zz "
+ "where cv.condr_idseq = zz.condr_idseq";
return getBasicData0(select);
}
/**
* Return the CON_IDSEQ for all concepts.
*
* @return the con_idseq list
*/
public String[] selectAllConcepts()
{
String select = "select con_idseq from sbrext.concepts_view_ext order by con_idseq";
return getBasicData0(select);
}
/**
* Pull the change history log for a single record.
*
* @param idseq_ The idseq of the record.
*
* @return The data if any (array length of zero if none found).
*/
public ACData[] selectWithIDSEQ(String idseq_)
{
int itype = selectChangedTableType(idseq_);
if (itype < 0)
{
return new ACData[0];
}
return selectAC(
selectBuild(idseq_, itype, _DATECM, null, null, null, null, null, null));
}
/**
* Pull all Contexts changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectCONTE(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[])
{
String select[] = new String[4];
select[0] = "select 'p', 1, 'conte', conte_idseq as id, version, -1, name, '', "
+ "date_modified, date_created, modified_by, created_by, '', '', '' "
+ "from sbr.contexts_view " + "where ";
select[1] = "created_by in (?) and ";
select[2] = "modified_by in (?) and ";
select[3] = "((date_modified is not null and date_modified "
+ _DATECHARS[dates_][0] + " ? and date_modified " + _DATECHARS[dates_][1] + " ?) "
+ "or (date_created is not null and date_created "
+ _DATECHARS[dates_][2] + " ? and date_created " + _DATECHARS[dates_][3] + " ?)) "
+ "order by id asc";
return selectAC(select, start_, end_, 2, creators_, modifiers_);
}
/**
* Build the SQL select to retrieve changes for an Administered Component.
*
* @param idseq_ The idseq of a speciifc record of interest.
* @param type_ The AC type, one of _ACTYPE_...
* @param dates_ The flag for how dates are compared, _DATECM, _DATECONLY, _DATEMONLY
* @param start_ The start date for the query.
* @param end_ The end date for the query.
* @param creators_ The specific created_by if any.
* @param modifiers_ The specific modified_by if any.
* @param wstatus_ The specific Workflow Status if any.
* @param rstatus_ The specific Registration Status if any.
* @return The SQL select string.
*/
private String selectBuild(String idseq_, int type_,
int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[], String rstatus_[])
{
// For consistency of reporting and ease of maintenance the idseq parameter
// is provided to ignore the date range and pull all information about a
// specific record.
if (idseq_ != null && idseq_.length() > 0)
{
dates_ = _DATECM;
start_ = new Timestamp(0);
end_ = start_;
creators_ = null;
modifiers_ = null;
wstatus_ = null;
rstatus_ = null;
}
// Due to the very conditional nature of this logic, the SQL SELECT is built
// without the use of substitution arguments ('?').
String prefix = _DBMAP3[type_]._key;
// The 'de' type is the only one that doesn't use the same prefix for the public id
// database column - ugh.
String prefix2 = (type_ == _ACTYPE_DE) ? "cde" : prefix;
// Build the basic select and from.
String select =
"select 'p', 1, '" + prefix
+ "', zz." + prefix
+ "_idseq as id, zz.version, zz." + prefix2
+ "_id, zz.long_name, zz.conte_idseq, "
+ "zz.date_modified, zz.date_created, zz.modified_by, zz.created_by, zz.change_note, "
+ "c.name, '', ach.changed_column, ach.old_value, ach.new_value, ach.change_datetimestamp, ach.changed_table, ach.changed_by "
+ "from sbrext.ac_change_history_ext ach, " + _DBMAP3[type_]._table + " zz, ";
// If registration status is not used we only need to add the context
// table.
String reg_clause;
if (rstatus_ == null || rstatus_.length == 0)
{
select = select + "sbr.contexts_view c ";
reg_clause = "";
}
// If registration status is used we need to add the context and registration
// status tables.
else
{
select = select + "sbr.contexts_view c, sbr.ac_registrations_view ar ";
reg_clause = "AND ar.ac_idseq = zz." + prefix
+ "_idseq AND NVL(ar.registration_status, '(none)') IN " + selectIN(rstatus_);
}
// If workflow status is not used we need to be sure and use an empty
// string.
String wfs_clause;
if (wstatus_ == null || wstatus_.length == 0)
{
wfs_clause = "";
}
// If workflow status is used we need to qualify by the content of the list.
else
{
wfs_clause = "AND zz.asl_name IN " + selectIN(wstatus_);
}
// Building the 'where' clause should be done to keep all qualifications together, e.g.
// first qualify all for ACH then join to the primary table (ZZ) complete the qualifications
// then join to the context table.
// Build the start and end dates.
String start = "to_date('" + start_.toString().substring(0, 10) + "', 'yyyy/mm/dd')";
String end = "to_date('" + end_.toString().substring(0, 10) + "', 'yyyy/mm/dd')";
// Always checking the date range first.
if (idseq_ == null || idseq_.length() == 0)
select = select + "where ach.change_datetimestamp >= " + start + " and ach.change_datetimestamp < " + end + " ";
else
select = select + "where ach.ac_idseq = '" + idseq_ + "' ";
// If modifiers are provided be sure to get everything.
if (modifiers_ != null && modifiers_.length > 0 && modifiers_[0].charAt(0) != '(')
select = select + "AND ach.changed_by in " + selectIN(modifiers_);
// Now qualify by the record type of interest and join to the primary table.
select = select + whereACH(type_)
+ "AND zz." + prefix + "_idseq = ach.ac_idseq ";
// If creators are provided they must be qualified by the primary table not the change table.
if (creators_ != null && creators_.length > 0 && creators_[0].charAt(0) != '(')
select = select + "AND zz.created_by in " + selectIN(creators_);
// When looking for both create and modified dates no extra clause is needed. For create
// date only qualify against the primary table.
if (dates_ == _DATECONLY)
select = select + "AND zz.date_created >= " + start + " and zz.date_created < " + end + " ";
// For modify date only qualify the primary table. The actual date is not important because we
// qualified the records from the history table by date already.
else if (dates_ == _DATEMONLY)
select = select + "AND zz.date_modified is not NULL ";
// Put everything together including the join to the context table and the sort order clause.
return select + wfs_clause + reg_clause + "AND c.conte_idseq = zz.conte_idseq " + _orderbyACH;
}
/**
* Pull all Data Element Concepts changed in the date range specified.
*
* @param dates_
* The date comparison index.
* @param start_
* The date to start.
* @param end_
* The date to end.
* @param creators_
* The list of desired creator user ids.
* @param modifiers_
* The list of desired modifier user ids.
* @param wstatus_
* The list of desired Workflow Statuses.
* @return 0 if successful, otherwise the database error code.
*/
public ACData[] selectDEC(int dates_, Timestamp start_, Timestamp end_,
String creators_[], String modifiers_[], String wstatus_[])
{
return selectAC(
selectBuild(null, _ACTYPE_DEC,
dates_, start_, end_, creators_, modifiers_, wstatus_, null));
}
/**
* Select the dependant data. In Oracle an "in" clause may have a maximum of
* 1000 items. If the array length (ids_) is greater than 1000 it is broken
* up into pieces. The result is that should an order by clause also appear,
* the end result may not be correct as the SQL had to be performed in
* multiple pieces.
*
* @param select_
* The SQL select.
* @param ids_
* The array holding the id's for the query.
* @return The ACData array of the results.
*/
private ACData[] selectAC(String select_, ACData ids_[])
{
if (ids_ == null || ids_.length == 0)
return new ACData[0];
// Oracle limit on "in" clauses.
int limit = 1000;
if (ids_.length < limit)
return selectAC2(select_, ids_);
// When more than 1000 we have to break up the list
// and merge the results together.
ACData results[] = new ACData[0];
int group = limit;
int indx = 0;
while (indx < ids_.length)
{
ACData tset[] = new ACData[group];
System.arraycopy(ids_, indx, tset, 0, group);
indx += group;
ACData rset[] = selectAC2(select_, tset);
tset = results;
results = new ACData[tset.length + rset.length];
// Now that we have a place to store the composite
// list perform a simple merge as both are already
// sorted.
int tndx = 0;
int rndx = 0;
int ndx = 0;
if (tset.length > 0 && rset.length > 0)
{
while (ndx < results.length)
{
if (tset[tndx].compareUsingIDS(rset[rndx]) <= 0)
{
results[ndx++] = tset[tndx++];
if (tndx == tset.length)
break;
}
else
{
results[ndx++] = rset[rndx++];
if (rndx == rset.length)
break;
}
}
}
// We've exhausted the 'temp' list so copy the rest of the
// 'rc' list.
if (tndx == tset.length)
System.arraycopy(rset, rndx, results, ndx, rset.length - rndx);
// We've exhausted the 'rc' list so copy the rest of the
// 'temp' list.
else
System.arraycopy(tset, tndx, results, ndx, tset.length - tndx);
// Do next group.
tndx = ids_.length - indx;
if (group > tndx)
group = tndx;
// Force conservation of memory.
tset = null;
rset = null;
}
return results;
}
/**
* Select the dependant data. This method does not test the length of the
* array (ids_) and therefore should only be called when 1000 ids or less
* are needed.
*
* @param select_
* The SQL containing the "in" clause.
* @param ids_
* The id values to be bound.
* @return The result of the query.
*/
private ACData[] selectAC2(String select_, ACData ids_[])
{
String markers = expandMarkers(ids_.length);
// Split the string based on "?" markers.
String parts[] = select_.split("\\?");
String select = null;
if (parts.length == 2)
{
select = parts[0] + markers + parts[1];
}
else if (parts.length == 3)
{
select = parts[0] + markers + parts[1] + markers + parts[2];
}
else
{
// Only needed during development.
_logger.error("DEVELOPMENT ERROR 1: ==>\n" + select_
+ "\n<== unexpected SQL form.");
return null;
}
try
{
// Build, bind and execute the statement.
PreparedStatement pstmt = _conn.prepareStatement(select);
int cnt = 1;
for (int ndx = 0; ndx < ids_.length; ++ndx)
{
pstmt.setString(cnt++, ids_[ndx].getIDseq());
}
if (parts.length == 3)
{
for (int ndx = 0; ndx < ids_.length; ++ndx)
{
pstmt.setString(cnt++, ids_[ndx].getIDseq());
}
}
ResultSet rs = pstmt.executeQuery();
ACData list[] = copyResults(rs);
rs.close();
pstmt.close();
return list;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Find the Value Domains that are affected by changes to the Permissible
* Values.
*
* @param pv_
* The list of permissible values identified as changed or created.
* @return The array of value domains.
*/
public ACData[] selectVDfromPV(ACData pv_[])
{
String select = "(select 's', 1, 'vd', vd.vd_idseq as id, vd.version, vd.vd_id, vd.long_name, vd.conte_idseq as cid, "
+ "vd.date_modified, vd.date_created, vd.modified_by, vd.created_by, vd.change_note, c.name, pv.pv_idseq "
+ "from sbr.value_domains_view vd, sbr.vd_pvs_view vp, sbr.permissible_values_view pv, sbr.contexts_view c "
+ "where pv.pv_idseq in (?) and vp.pv_idseq = pv.pv_idseq and vd.vd_idseq = vp.vd_idseq and "
+ "c.conte_idseq = vd.conte_idseq "
+ "union "
+ "select 's', 1, 'vd', ac.ac_idseq as id, ac.version, xx.vd_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, pv.pv_idseq "
+ "from sbr.permissible_values_view pv, sbr.vd_pvs_view vp, sbr.value_domains_view xx, "
+ "sbr.admin_components_view ac, sbr.designations_view dv, sbr.contexts_view c "
+ "where pv.pv_idseq in (?) and vp.pv_idseq = pv.pv_idseq and xx.vd_idseq = vp.vd_idseq "
+ "and ac.ac_idseq = xx.vd_idseq and ac.actl_name = 'VALUEDOMAIN' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, pv_);
}
/**
* Find the Permissible Values that are affected by changes to the Value Meanings.
*
* @param vm_
* The list of value meanings identified as changed or created.
* @return The array of value domains.
*/
public ACData[] selectPVfromVM(ACData vm_[])
{
String select = "select 's', 1, 'pv', pv.pv_idseq as id, '', -1, pv.value, '', "
+ "pv.date_modified, pv.date_created, pv.modified_by, pv.created_by, '', '', vm.short_meaning "
+ "from sbr.permissible_values_view pv, sbr.value_meanings_view vm "
+ "where vm.short_meaning in (?) and pv.short_meaning = vm.short_meaning ";
return selectAC(select, vm_);
}
/**
* Find the Conceptual Domains affected by changes to the Value Domains
* provided.
*
* @param vd_
* The list of value domains.
* @return The array of conceptual domains.
*/
public ACData[] selectCDfromVD(ACData vd_[])
{
String select = "(select 's', 1, 'cd', cd.cd_idseq as id, cd.version, cd.cd_id, cd.long_name, cd.conte_idseq as cid, "
+ "cd.date_modified, cd.date_created, cd.modified_by, cd.created_by, cd.change_note, c.name, vd.vd_idseq "
+ "from sbr.conceptual_domains_view cd, sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and cd.cd_idseq = vd.cd_idseq and c.conte_idseq = cd.conte_idseq "
+ "union "
+ "select 's', 1, 'cd', ac.ac_idseq as id, ac.version, xx.cd_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, vd.vd_idseq "
+ "from sbr.admin_components_view ac, sbr.conceptual_domains_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and xx.cd_idseq = vd.cd_idseq and ac.ac_idseq = xx.cd_idseq and "
+ "ac.actl_name = 'CONCEPTUALDOMAIN' and dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, vd_);
}
/**
* Find the Conceptual Domains affected by changes to the Data Element Concepts
* provided.
*
* @param dec_
* The list of data element concepts.
* @return The array of conceptual domains.
*/
public ACData[] selectCDfromDEC(ACData dec_[])
{
String select = "(select 's', 1, 'cd', cd.cd_idseq as id, cd.version, cd.cd_id, cd.long_name, cd.conte_idseq as cid, "
+ "cd.date_modified, cd.date_created, cd.modified_by, cd.created_by, cd.change_note, c.name, dec.dec_idseq "
+ "from sbr.conceptual_domains_view cd, sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and cd.cd_idseq = dec.dec_idseq and c.conte_idseq = cd.conte_idseq "
+ "union "
+ "select 's', 1, 'cd', ac.ac_idseq as id, ac.version, xx.cd_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, dec.dec_idseq "
+ "from sbr.admin_components_view ac, sbr.conceptual_domains_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and xx.cd_idseq = dec.cd_idseq and ac.ac_idseq = xx.cd_idseq and "
+ "ac.actl_name = 'CONCEPTUALDOMAIN' and dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, dec_);
}
/**
* Select the Data Elements affected by the Value Domains provided.
*
* @param vd_
* The value domain list.
* @return The array of related data elements.
*/
public ACData[] selectDEfromVD(ACData vd_[])
{
String select = "(select 's', 1, 'de', de.de_idseq as id, de.version, de.cde_id, de.long_name, de.conte_idseq as cid, "
+ "de.date_modified, de.date_created, de.modified_by, de.created_by, de.change_note, c.name, vd.vd_idseq "
+ "from sbr.data_elements_view de, sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and de.vd_idseq = vd.vd_idseq and c.conte_idseq = de.conte_idseq "
+ "union "
+ "select 's', 1, 'de', ac.ac_idseq as id, ac.version, xx.cde_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, vd.vd_idseq "
+ "from sbr.admin_components_view ac, sbr.data_elements_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and xx.vd_idseq = vd.vd_idseq and xx.de_idseq = ac.ac_idseq and ac.actl_name = 'DATAELEMENT' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, vd_);
}
/**
* Select the Data Element Concepts affected by the Properties provided.
*
* @param prop_
* The property list.
* @return The array of related data element concepts.
*/
public ACData[] selectDECfromPROP(ACData prop_[])
{
String select = "(select 's', 1, 'dec', dec.dec_idseq as id, dec.version, dec.dec_id, dec.long_name, dec.conte_idseq as cid, "
+ "dec.date_modified, dec.date_created, dec.modified_by, dec.created_by, dec.change_note, c.name, prop.prop_idseq "
+ "from sbr.data_element_concepts_view dec, sbr.contexts_view c, sbrext.properties_view_ext prop "
+ "where prop.prop_idseq in (?) and dec.prop_idseq = prop.prop_idseq and c.conte_idseq = dec.conte_idseq "
+ "union "
+ "select 's', 1, 'dec', ac.ac_idseq as id, ac.version, xx.dec_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, prop.prop_idseq "
+ "from sbr.admin_components_view ac, sbr.data_element_concepts_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbrext.properties_view_ext prop "
+ "where prop.prop_idseq in (?) and xx.prop_idseq = prop.prop_idseq and xx.dec_idseq = ac.ac_idseq and ac.actl_name = 'DE_CONCEPT' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, prop_);
}
/**
* Select the Properties affected by the Concepts provided.
*
* @param con_
* The concept list.
* @return The array of related properties.
*/
public ACData[] selectPROPfromCON(ACData con_[])
{
String select = "select 's', 1, 'prop', prop.prop_idseq as id, prop.version, prop.prop_id, prop.long_name, prop.conte_idseq as cid, "
+ "prop.date_modified, prop.date_created, prop.modified_by, prop.created_by, prop.change_note, c.name, con.con_idseq "
+ "from sbrext.properties_view_ext prop, sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext con, sbr.contexts_view c "
+ "where con.con_idseq in (?) and ccv.con_idseq = con.con_idseq and prop.condr_idseq = ccv.condr_idseq and c.conte_idseq = prop.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, con_);
}
/**
* Select the Object Classes affected by the Concepts provided.
*
* @param con_
* The concept list.
* @return The array of related object classes.
*/
public ACData[] selectOCfromCON(ACData con_[])
{
String select = "select 's', 1, 'oc', oc.oc_idseq as id, oc.version, oc.oc_id, oc.long_name, oc.conte_idseq as cid, "
+ "oc.date_modified, oc.date_created, oc.modified_by, oc.created_by, oc.change_note, c.name, con.con_idseq "
+ "from sbrext.object_classes_view_ext oc, sbrext.component_concepts_view_ext ccv, sbrext.concepts_view_ext con, sbr.contexts_view c "
+ "where con.con_idseq in (?) and ccv.con_idseq = con.con_idseq and oc.condr_idseq = ccv.condr_idseq and c.conte_idseq = oc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, con_);
}
/**
* Select the Data Element Concepts affected by the Object Classes provided.
*
* @param oc_
* The object class list.
* @return The array of related data element concepts.
*/
public ACData[] selectDECfromOC(ACData oc_[])
{
String select = "(select 's', 1, 'dec', dec.dec_idseq as id, dec.version, dec.dec_id, dec.long_name, dec.conte_idseq as cid, "
+ "dec.date_modified, dec.date_created, dec.modified_by, dec.created_by, dec.change_note, c.name, oc.oc_idseq "
+ "from sbr.data_element_concepts_view dec, sbr.contexts_view c, sbrext.object_classes_view_ext oc "
+ "where oc.oc_idseq in (?) and dec.oc_idseq = oc.oc_idseq and c.conte_idseq = dec.conte_idseq "
+ "union "
+ "select 's', 1, 'dec', ac.ac_idseq as id, ac.version, xx.dec_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, oc.oc_idseq "
+ "from sbr.admin_components_view ac, sbr.data_element_concepts_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbrext.object_classes_view_ext oc "
+ "where oc.oc_idseq in (?) and xx.oc_idseq = oc.oc_idseq and xx.dec_idseq = ac.ac_idseq and ac.actl_name = 'DE_CONCEPT' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, oc_);
}
/**
* Select the Data Elements affected by the Data Element Concepts provided.
*
* @param dec_
* The data element concepts list.
* @return The array of related data elements.
*/
public ACData[] selectDEfromDEC(ACData dec_[])
{
String select = "(select 's', 1, 'de', de.de_idseq as id, de.version, de.cde_id, de.long_name, de.conte_idseq as cid, "
+ "de.date_modified, de.date_created, de.modified_by, de.created_by, de.change_note, c.name, dec.dec_idseq "
+ "from sbr.data_elements_view de, sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and de.dec_idseq = dec.dec_idseq and c.conte_idseq = de.conte_idseq "
+ "union "
+ "select 's', 1, 'de', ac.ac_idseq as id, ac.version, xx.cde_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, dec.dec_idseq "
+ "from sbr.admin_components_view ac, sbr.data_elements_view xx, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and xx.dec_idseq = dec.dec_idseq and xx.de_idseq = ac.ac_idseq and ac.actl_name = 'DATAELEMENT' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, dec_);
}
/**
* Select the Classification Scheme Item affected by the Data Elements
* provided.
*
* @param de_
* The data element list.
* @return The array of related classification scheme items.
*/
public ACData[] selectCSIfromDE(ACData de_[])
{
String select = "select 's', 1, 'csi', civ.csi_idseq as id, '', -1, civ.csi_name, '', "
+ "civ.date_modified, civ.date_created, civ.modified_by, civ.created_by, civ.comments, '', de.de_idseq "
+ "from sbr.class_scheme_items_view civ, sbr.data_elements_view de, sbr.admin_components_view ac, "
+ "sbr.ac_csi_view ai, sbr.cs_csi_view ci "
+ "where de.de_idseq in (?) and ac.ac_idseq = de.de_idseq and ai.ac_idseq = ac.ac_idseq and "
+ "ci.cs_csi_idseq = ai.cs_csi_idseq and civ.csi_idseq = ci.csi_idseq "
+ "order by id asc";
return selectAC(select, de_);
}
/**
* Select the Classification Scheme Item affected by the Data Element Concepts
* provided.
*
* @param dec_
* The data element concept list.
* @return The array of related classification scheme items.
*/
public ACData[] selectCSIfromDEC(ACData dec_[])
{
String select = "select 's', 1, 'csi', civ.csi_idseq as id, '', -1, civ.csi_name, '', "
+ "civ.date_modified, civ.date_created, civ.modified_by, civ.created_by, civ.comments, '', dec.dec_idseq "
+ "from sbr.class_scheme_items_view civ, sbr.data_element_concepts_view dec, sbr.admin_components_view ac, "
+ "sbr.ac_csi_view ai, sbr.cs_csi_view ci "
+ "where dec.dec_idseq in (?) and ac.ac_idseq = dec.dec_idseq and ai.ac_idseq = ac.ac_idseq and "
+ "ci.cs_csi_idseq = ai.cs_csi_idseq and civ.csi_idseq = ci.csi_idseq "
+ "order by id asc";
return selectAC(select, dec_);
}
/**
* Select the Classification Scheme Item affected by the Value Domains
* provided.
*
* @param vd_
* The value domain list.
* @return The array of related classification scheme items.
*/
public ACData[] selectCSIfromVD(ACData vd_[])
{
String select = "select 's', 1, 'csi', civ.csi_idseq as id, '', -1, civ.csi_name, '', "
+ "civ.date_modified, civ.date_created, civ.modified_by, civ.created_by, civ.comments, '', vd.vd_idseq "
+ "from sbr.class_scheme_items_view civ, sbr.value_domains_view vd, sbr.admin_components_view ac, "
+ "sbr.ac_csi_view ai, sbr.cs_csi_view ci "
+ "where vd.vd_idseq in (?) and ac.ac_idseq = vd.vd_idseq and ai.ac_idseq = ac.ac_idseq and "
+ "ci.cs_csi_idseq = ai.cs_csi_idseq and civ.csi_idseq = ci.csi_idseq "
+ "order by id asc";
return selectAC(select, vd_);
}
/**
* Select the Forms/Templates affected by the Data Elements provided.
*
* @param de_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCQfromDE(ACData de_[])
{
String select = "select 's', 1, 'qcq', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, de.de_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbr.data_elements_view de, sbr.contexts_view c "
+ "where de.de_idseq in (?) and qc.de_idseq = de.de_idseq and qc.qtl_name in ('QUESTION', 'QUESTION_INSTR') and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, de_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param vd_
* The value domain list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCQfromVD(ACData vd_[])
{
String select = "select 's', 1, 'qcq', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, vd.vd_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbr.value_domains_view vd, sbr.contexts_view c "
+ "where vd.vd_idseq in (?) and qc.dn_vd_idseq = vd.vd_idseq and qc.qtl_name in ('QUESTION', 'QUESTION_INSTR') and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, vd_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param vd_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCVfromVD(ACData vd_[])
{
String select = "select 's', 1, 'qcv', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, vd.vd_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbr.value_domains_view vd, sbr.vd_pvs_view vp, sbr.contexts_view c "
+ "where vd.vd_idseq in (?) and vp.vd_idseq = vd.vd_idseq and qc.vp_idseq = vp.vp_idseq and "
+ "qc.qtl_name = 'VALID_VALUE' and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, vd_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param qcv_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCQfromQCV(ACData qcv_[])
{
String select = "select 's', 1, 'qcq', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, qc2.qc_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbrext.quest_contents_view_ext qc2, sbr.contexts_view c "
+ "where qc2.qc_idseq in (?) and qc2.qtl_name = 'VALID_VALUE' and qc.qc_idseq = qc2.p_qst_idseq and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, qcv_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param qcq_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCMfromQCQ(ACData qcq_[])
{
String select = "select 's', 1, 'qcm', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, qc2.qc_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbrext.quest_contents_view_ext qc2, sbr.contexts_view c "
+ "where qc2.qc_idseq in (?) and qc2.qtl_name in ('QUESTION', 'QUESTION_INSTR') and qc.qc_idseq = qc2.p_mod_idseq and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, qcq_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param qcm_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCfromQCM(ACData qcm_[])
{
String select = "select 's', 1, 'qc', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, qc2.qc_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbrext.quest_contents_view_ext qc2, sbr.contexts_view c "
+ "where qc2.qc_idseq in (?) and qc2.qtl_name = 'MODULE' and qc.qc_idseq = qc2.dn_crf_idseq and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, qcm_);
}
/**
* Select the Forms/Templates affected by the Value Domains provided.
*
* @param qcq_
* The data element list.
* @return The array of related forms/templates.
*/
public ACData[] selectQCfromQCQ(ACData qcq_[])
{
String select = "select 's', 1, 'qc', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, "
+ "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, qc2.qc_idseq "
+ "from sbrext.quest_contents_view_ext qc, sbrext.quest_contents_view_ext qc2, sbr.contexts_view c "
+ "where qc2.qc_idseq in (?) and qc2.qtl_name in ('QUESTION', 'QUESTION_INSTR') and qc2.p_mod_idseq is null and "
+ "qc.qc_idseq = qc2.dn_crf_idseq and c.conte_idseq = qc.conte_idseq "
+ "order by id asc, cid asc";
return selectAC(select, qcq_);
}
/**
* Select the Classification Schemes affected by the Classification Scheme
* Items provided.
*
* @param csi_
* The classification scheme items list.
* @return The array of related classification schemes.
*/
public ACData[] selectCSfromCSI(ACData csi_[])
{
String select = "(select 's', 1, 'cs', cs.cs_idseq as id, cs.version, cs.cs_id, cs.long_name, cs.conte_idseq as cid, "
+ "cs.date_modified, cs.date_created, cs.modified_by, cs.created_by, cs.change_note, c.name, civ.csi_idseq "
+ "from sbr.classification_schemes_view cs, sbr.contexts_view c, sbr.cs_csi_view ci, "
+ "sbr.class_scheme_items_view civ "
+ "where civ.csi_idseq in (?) and ci.csi_idseq = civ.csi_idseq and cs.cs_idseq = ci.cs_idseq and "
+ "c.conte_idseq = cs.conte_idseq "
+ "union "
+ "select 's', 1, 'cs', ac.ac_idseq as id, ac.version, xx.cs_id, ac.long_name, dv.conte_idseq as cid, "
+ "ac.date_modified, ac.date_created, ac.modified_by, ac.created_by, ac.change_note, c.name, civ.csi_idseq "
+ "from sbr.admin_components_view ac, sbr.classification_schemes_view xx, sbr.cs_csi_view ci, "
+ "sbr.designations_view dv, sbr.contexts_view c, sbr.class_scheme_items_view civ "
+ "where civ.csi_idseq in (?) and ci.csi_idseq = civ.csi_idseq and xx.cs_idseq = ci.cs_idseq and "
+ "ac.ac_idseq = xx.cs_idseq and ac.actl_name = 'CLASSIFICATION' and "
+ "dv.ac_idseq = ac.ac_idseq and c.conte_idseq = dv.conte_idseq) "
+ "order by id asc, cid asc";
return selectAC(select, csi_);
}
/**
* Select the Contexts affected by the Classification Schemes provided.
*
* @param cs_
* The classification schemes list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromCS(ACData cs_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', cs.cs_idseq "
+ "from sbr.contexts_view c, sbr.classification_schemes_view cs "
+ "where cs.cs_idseq in (?) and c.conte_idseq = cs.conte_idseq "
+ "order by id asc";
return selectAC(select, cs_);
}
/**
* Select the Contexts affected by the Conceptual Domains provided.
*
* @param cd_
* The conceptual domains list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromCD(ACData cd_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', cd.cd_idseq "
+ "from sbr.contexts_view c, sbr.conceptual_domains_view cd "
+ "where cd.cd_idseq in (?) and c.conte_idseq = cd.conte_idseq "
+ "order by id asc";
return selectAC(select, cd_);
}
/**
* Select the Contexts affected by the Value Domains provided.
*
* @param vd_
* The value domains list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromVD(ACData vd_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', vd.vd_idseq "
+ "from sbr.contexts_view c, sbr.value_domains_view vd "
+ "where vd.vd_idseq in (?) and c.conte_idseq = vd.conte_idseq "
+ "order by id asc";
return selectAC(select, vd_);
}
/**
* Select the Contexts affected by the Data Elements provided.
*
* @param de_
* The data elements list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromDE(ACData de_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', de.de_idseq "
+ "from sbr.contexts_view c, sbr.data_elements_view de "
+ "where de.de_idseq in (?) and c.conte_idseq = de.conte_idseq "
+ "order by id asc";
return selectAC(select, de_);
}
/**
* Select the Contexts affected by the Properties provided.
*
* @param prop_
* The properties list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromPROP(ACData prop_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', prop.prop_idseq "
+ "from sbr.contexts_view c, sbrext.properties_view_ext prop "
+ "where prop.prop_idseq in (?) and c.conte_idseq = prop.conte_idseq "
+ "order by id asc";
return selectAC(select, prop_);
}
/**
* Select the Contexts affected by the Object Classes provided.
*
* @param oc_
* The object class list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromOC(ACData oc_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', oc.oc_idseq "
+ "from sbr.contexts_view c, sbrext.object_classes_view_ext oc "
+ "where oc.oc_idseq in (?) and c.conte_idseq = oc.conte_idseq "
+ "order by id asc";
return selectAC(select, oc_);
}
/**
* Select the Contexts affected by the Concepts provided.
*
* @param con_
* The object class list.
* @return The array of related concepts.
*/
public ACData[] selectCONTEfromCON(ACData con_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', con.con_idseq "
+ "from sbr.contexts_view c, sbrext.concepts_view_ext con "
+ "where con.con_idseq in (?) and c.conte_idseq = con.conte_idseq "
+ "order by id asc";
return selectAC(select, con_);
}
/**
* Select the Contexts affected by the Protocols provided.
*
* @param proto_
* The protocols list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromPROTO(ACData proto_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', proto.proto_idseq "
+ "from sbr.contexts_view c, sbrext.protocols_view_ext proto "
+ "where proto.proto_idseq in (?) and c.conte_idseq = proto.conte_idseq "
+ "order by id asc";
return selectAC(select, proto_);
}
/**
* Select the Protocols affected by the Forms/Templates provided.
*
* @param qc_
* The forms/templates list.
* @return The array of related contexts.
*/
public ACData[] selectPROTOfromQC(ACData qc_[])
{
String select = "select 's', 1, 'proto', proto.proto_idseq as id, proto.version, proto.proto_id, proto.long_name, c.conte_idseq, "
+ "proto.date_modified, proto.date_created, proto.modified_by, proto.created_by, proto.change_note, c.name, qc.qc_idseq "
+ "from sbr.contexts_view c, sbrext.protocols_view_ext proto, sbrext.protocol_qc_ext pq, sbrext.quest_contents_view_ext qc "
+ "where qc.qc_idseq in (?) "
+ "and pq.qc_idseq = qc.qc_idseq "
+ "and proto.proto_idseq = pq.proto_idseq "
+ "and c.conte_idseq = proto.conte_idseq "
+ "order by id asc";
return selectAC(select, qc_);
}
/**
* Select the Contexts affected by the Forms/Templates provided.
*
* @param qc_
* The forms/templates list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromQC(ACData qc_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', qc.qc_idseq "
+ "from sbr.contexts_view c, sbrext.quest_contents_view_ext qc "
+ "where qc.qc_idseq in (?) and c.conte_idseq = qc.conte_idseq "
+ "order by id asc";
return selectAC(select, qc_);
}
/**
* Select the Contexts affected by the Data Element Concepts provided.
*
* @param dec_
* The data element concepts list.
* @return The array of related contexts.
*/
public ACData[] selectCONTEfromDEC(ACData dec_[])
{
String select = "select 's', 1, 'conte', c.conte_idseq as id, c.version, -1, c.name, '', "
+ "c.date_modified, c.date_created, c.modified_by, c.created_by, '', '', dec.dec_idseq "
+ "from sbr.contexts_view c, sbr.data_element_concepts_view dec "
+ "where dec.dec_idseq in (?) and c.conte_idseq = dec.conte_idseq "
+ "order by id asc";
return selectAC(select, dec_);
}
/**
* For performance reasons as "names" are the most common data required, a
* cache is created to avoid hitting the database with too many individual
* requests. This cache is good for the life of this DBAlert object and will
* be rebuilt as needed with each new DBAlert.
*
* @param id_
* The name id to look up in the database.
* @return When > 0, the position of the name in the cache. When < 0, the
* position it should be in the cache when added later.
*/
private int findName(String id_)
{
int min = 0;
int max = _nameID.length;
// Use a binary search. It seems the most efficient for this purpose.
while (true)
{
int ndx = (max + min) / 2;
int compare = id_.compareTo(_nameID[ndx]);
if (compare == 0)
{
return ndx;
}
else if (compare > 0)
{
if (min == ndx)
{
++min;
return -min;
}
min = ndx;
}
else
{
if (max == ndx)
return -max;
max = ndx;
}
}
}
/**
* Cache names internally as they are encountered. If the findName() method
* can not locate a name in the cache it will be added by this method.
*
* @param pos_
* The insert position returned from findName().
* @param id_
* The name id to use as a key.
* @param name_
* The name to return for this id.
*/
private void cacheName(int pos_, String id_, String name_)
{
// Don't save null names, use the id if needed.
if (name_ == null)
name_ = id_;
// Move all existing records down to make room for the new name.
String nid[] = new String[_nameID.length + 1];
String ntxt[] = new String[nid.length];
int ndx;
int ndx2 = 0;
for (ndx = 0; ndx < pos_; ++ndx)
{
nid[ndx] = _nameID[ndx2];
ntxt[ndx] = _nameText[ndx2++];
}
// Add the new name.
nid[ndx] = new String(id_);
ntxt[ndx] = new String(name_);
// Copy the rest and reset the arrays.
for (++ndx; ndx < nid.length; ++ndx)
{
nid[ndx] = _nameID[ndx2];
ntxt[ndx] = _nameText[ndx2++];
}
_nameID = nid;
_nameText = ntxt;
}
/**
* Retrieve a string name representation for the "object" id provided.
*
* @param table_
* The known database table name or null if the method should use a
* default based on the col_ value.
* @param col_
* The column name which corresponds to the id_ provided.
* @param id_
* The id of the specific database record desired.
* @return The "name" from the record, this may correspond to the long_name,
* prefferred_name, etc database columns depending on the table
* being used.
*/
public String selectName(String table_, String col_, String id_)
{
// Can't work without a column name.
if (col_ == null)
return id_;
if (id_ == null || id_.length() == 0)
return null;
// Determine the real table and column names to use.
int npos = 0;
String table = table_;
String name = "long_name";
String col = col_;
String extra = "";
if (table == null || table.length() == 0)
{
int ndx = DBAlertUtil.binarySearch(_DBMAP2, col);
if (ndx == -1)
return id_;
table = _DBMAP2[ndx]._val;
name = _DBMAP2[ndx]._subs;
col = _DBMAP2[ndx]._col;
extra = _DBMAP2[ndx]._xtra;
if (col.equals("ua_name"))
{
// Is the name cached?
npos = findName(id_);
if (npos >= 0)
return _nameText[npos];
}
}
// Build a select and retrieve the "name".
String select = "select " + name + " from " + table + " where " + col
+ " = ?" + extra;
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, id_);
ResultSet rs = pstmt.executeQuery();
name = "";
while (rs.next())
name = name + "\n" + rs.getString(1);
if (name.length() == 0)
name = null;
else
name = name.substring(1);
rs.close();
pstmt.close();
if (col.equals("ua_name") && npos < 0)
{
cacheName(-npos, id_, name);
}
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
name = "(*error*)";
}
return (name == null) ? id_ : name;
}
/**
* Retrieve the "names" for a list of columns and ids. WARNING this is a
* destructive method. It changes the content of ids_ by replacing the
* original value with the retrieved name.
*
* @param cols_
* The names of the columns corresponding to the ids.
* @param ids_
* On input the ids of the specific records to query. On return the
* names of the records if they could be determined.
*/
public void selectNames(String cols_[], String ids_[])
{
for (int ndx = 0; ndx < cols_.length; ++ndx)
{
ids_[ndx] = selectName(null, cols_[ndx], ids_[ndx]);
}
}
/**
* Update the Auto Run or Manual Run timestamp.
*
* @param id_
* The alert id to update.
* @param stamp_
* The new time.
* @param run_
* true to update the auto run time, false to update the manual run
* time
* @param setInactive_
* true to set the alert status to inactive, false to leave the
* status unchanged
* @return 0 if successful, otherwise the database error code.
*/
public int updateRun(String id_, Timestamp stamp_, boolean run_,
boolean setInactive_)
{
String update = "update sbrext.sn_alert_view_ext set "
+ ((run_) ? "last_auto_run" : "last_manual_run") + " = ?,"
+ ((setInactive_) ? " al_status = 'I', " : "")
+ "modified_by = ? where al_idseq = ?";
try
{
PreparedStatement pstmt = null;
// Set all the SQL arguments.
pstmt = _conn.prepareStatement(update);
pstmt.setTimestamp(1, stamp_);
pstmt.setString(2, _user);
pstmt.setString(3, id_);
pstmt.executeUpdate();
pstmt.close();
_needCommit = true;
return 0;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + update
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return _errorCode;
}
}
/**
* Return the recipients names in ascending order by first name as a single
* string. If the recipient is a broadcast context group the group is expanded.
* Those who have elected not to receive broadcasts from a context group are
* not included. All freeform email addresses are listed after the names
* retrieved from the account table.
*
* @param recipients_ The Alert recipient list.
* @return A single comma separate list of names and email addresses with
* the broadcast context groups expanded.
*/
public String selectRecipientNames(String recipients_[])
{
// Check input.
if (recipients_ == null || recipients_.length == 0)
return "(none)";
// Break the recipients list apart.
String contexts = "";
String users = "";
String emails = "";
for (int ndx = 0; ndx < recipients_.length; ++ndx)
{
if (recipients_[ndx].charAt(0) == '/')
contexts = contexts + ", '" + recipients_[ndx].substring(1) + "'";
else if (recipients_[ndx].indexOf('@') < 0)
users = users + ", '" + recipients_[ndx] + "'";
else
emails = emails + ", " + recipients_[ndx];
}
// Build the select for user names
String select = "";
if (users.length() > 0)
select += "select ua.name as lname from sbr.user_accounts_view ua where ua.ua_name in ("
+ users.substring(2)
+ ") and ua.electronic_mail_address is not null ";
// Build the select for a Context group
if (contexts.length() > 0)
{
if (select.length() > 0)
select += "union ";
select += "select ua.name as lname from sbr.user_accounts_view ua, sbrext.user_contexts_view uc, sbr.contexts_view c where c.conte_idseq in ("
+ contexts.substring(2)
+ ") and uc.name = c.name and uc.privilege = 'W' and ua.ua_name = uc.ua_name and ua.alert_ind = 'Yes' and ua.electronic_mail_address is not null ";
}
String names = "";
if (select.length() > 0)
{
// Sort the results.
select = "select lname from (" + select + ") order by upper(lname) asc";
try
{
// Retrieve the user names from the database.
PreparedStatement pstmt = _conn.prepareStatement(select);
ResultSet rs = pstmt.executeQuery();
// Make this a comma separated list.
while (rs.next())
{
names += ", " + rs.getString(1);
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
// Append the freeform email addresses.
if (emails.length() > 0)
names += emails;
return (names.length() > 0) ? names.substring(2) : "(none)";
}
/**
* Given the idseq of a Context, retrieve all the users with write access to
* that context.
*
* @param conte_
* The context idseq.
* @return The array of user ids with write access.
*/
public String[] selectEmailsFromConte(String conte_)
{
String select = "select ua.electronic_mail_address "
+ "from sbrext.user_contexts_view uc, sbr.user_accounts_view ua, sbr.contexts_view c "
+ "where c.conte_idseq = ? and uc.name = c.name and uc.privilege = 'W' and ua.ua_name = uc.ua_name "
+ "and ua.alert_ind = 'Yes'";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
if (conte_.charAt(0) == '/')
pstmt.setString(1, conte_.substring(1));
else
pstmt.setString(1, conte_);
ResultSet rs = pstmt.executeQuery();
Vector<String> temp = new Vector<String>();
while (rs.next())
{
temp.add(rs.getString(1));
}
rs.close();
pstmt.close();
String curators[] = new String[temp.size()];
for (int ndx = 0; ndx < curators.length; ++ndx)
curators[ndx] = (String) temp.get(ndx);
return curators;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Given the id for a user, retrieve the email address.
*
* @param user_
* The user id.
* @return The array of user ids with write access.
*/
public String selectEmailFromUser(String user_)
{
String select = "select ua.electronic_mail_address "
+ "from sbr.user_accounts_view ua " + "where ua.ua_name = ?";
try
{
PreparedStatement pstmt = _conn.prepareStatement(select);
pstmt.setString(1, user_);
ResultSet rs = pstmt.executeQuery();
String temp = null;
if (rs.next())
{
temp = rs.getString(1);
}
rs.close();
pstmt.close();
return temp;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = _errorCode + ": " + select
+ "\n\n" + ex.toString();
_logger.error(_errorMsg);
return null;
}
}
/**
* Run a specific SELECT for the testDBdependancies() method.
*
* @param select_
* The select statement.
* @return >0 if successful with the number of rows returned, otherwise
* failed.
*/
private int testDB(String select_)
{
try
{
PreparedStatement pstmt = _conn.prepareStatement(select_);
ResultSet rs = pstmt.executeQuery();
int rows;
for (rows = 0; rs.next(); ++rows)
;
rs.close();
pstmt.close();
return rows;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = select_ + "\n" + ex.toString();
return -1;
}
}
/**
* Run a specific SELECT for the testDBdependancies() method.
*
* @param select_
* The select statement.
* @return the first row found
*/
private String testDB2(String select_)
{
try
{
PreparedStatement pstmt = _conn.prepareStatement(select_);
ResultSet rs = pstmt.executeQuery();
String result = null;
int rows;
for (rows = 0; rs.next(); ++rows)
result = rs.getString(1);
rs.close();
pstmt.close();
return result;
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = select_ + "\n" + ex.toString();
return null;
}
}
/**
* Test the database dependencies within this class. This method will check
* the existence of tables, columns and required values.
*
* @return null if all dependencies are present, otherwise a string
* detailing those that failed.
*/
public String testDBdependancies()
{
String results = "";
String select = "select ua_name, name, electronic_mail_address, alert_ind "
+ "from sbr.user_accounts_view "
+ "where (ua_name is null or name is null or alert_ind is null) and rownum < 2";
int rows = testDB(select);
if (rows != 0)
{
if (rows < 0)
results += _errorMsg;
else
results += "One of the columns ua_name, name or alert_ind in the table sbr.user_accounts_view is NULL";
results += "\n\n";
}
select = "select * from sbrext.sn_alert_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select * from sbrext.sn_query_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select * from sbrext.sn_recipient_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select * from sbrext.sn_report_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select ua_name, name, privilege from sbrext.user_contexts_view where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
select = "select tool_name, property, ua_name, value from sbrext.tool_options_view_ext where rownum < 2";
rows = testDB(select);
if (rows < 0)
results += _errorMsg + "\n\n";
_errorCode = 0;
_errorMsg = "";
return (results.length() == 0) ? null : results;
}
/**
* Test the content of the tool options table.
*
* @param url_ the URL used to access the Sentinel from a browser. If not null it is compared to the caDSR
* tool options entry to ensure they match.
* @return null if no errors, otherwise the error message.
*/
public String testSentinelOptions(String url_)
{
String results = "";
int rows;
AutoProcessData apd = new AutoProcessData();
apd.getOptions(this);
if (apd._adminEmail == null || apd._adminEmail.length == 0)
results += "Missing the Sentinel Tool Alert Administrators email address.\n\n";
if (apd._adminIntro == null || apd._adminIntro.length() == 0)
results += "Missing the Sentinel Tool email introduction.\n\n";
if (apd._adminIntroError == null || apd._adminIntroError.length() == 0)
results += "Missing the Sentinel Tool email error introduction.\n\n";
if (apd._adminName == null || apd._adminName.length() == 0)
results += "Missing the Sentinel Tool Alert Administrators email name.\n\n";
if (apd._dbname == null || apd._dbname.length() == 0)
results += "Missing the Sentinel Tool database name.\n\n";
if (apd._emailAddr == null || apd._emailAddr.length() == 0)
results += "Missing the Sentinel Tool email Reply To address.\n\n";
if (apd._emailHost == null || apd._emailHost.length() == 0)
results += "Missing the Sentinel Tool email host address.\n\n";
if (apd._emailUser != null && apd._emailUser.length() > 0)
{
if (apd._emailPswd == null || apd._emailPswd.length() == 0)
results += "Missing the Sentinel Tool email host account password.\n\n";
}
if (apd._http == null || apd._http.length() == 0)
results += "Missing the Sentinel Tool HTTP prefix.\n\n";
if (apd._subject == null || apd._subject.length() == 0)
results += "Missing the Sentinel Tool email subject.\n\n";
if (apd._work == null || apd._work.length() == 0)
results += "Missing the Sentinel Tool working folder prefix.\n\n";
String select = "select value from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' and property = 'URL' and value is not null";
select = testDB2(select);
if (select == null)
results += "Missing the Sentinel Tool URL setting.\n\n";
else if (url_ != null)
{
int pos = url_.indexOf('/', 8);
if (pos > 0)
url_ = url_.substring(0, pos);
if (url_.startsWith("http://localhost"))
;
else if (url_.startsWith("https://localhost"))
;
else if (select.startsWith(url_, 0))
;
else
results += "Sentinel Tool URL \"" + url_ + "\"does not match configuration value \"" + select + "\".\n\n";
}
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property LIKE 'ADMIN.%' and value like '%0%'";
rows = testDB(select);
if (rows < 1)
results += "Missing the Sentinel Tool Alert Administrator setting.\n\n";
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property LIKE 'ADMIN.%' and value like '%1%'";
rows = testDB(select);
if (rows < 1)
results += "Missing the Sentinel Tool Report Administrator setting.\n\n";
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property = 'ALERT.NAME.FORMAT' and value is not null";
rows = testDB(select);
if (rows != 1)
results += "Missing the Sentinel Tool ALERT.NAME.FORMAT setting.\n\n";
if (selectAlertReportAdminEmails() == null)
results += "Missing email addresses for the specified Alert Report Administrator(s) setting.\n\n";
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property LIKE 'BROADCAST.EXCLUDE.CONTEXT.%.NAME'";
rows = testDB(select);
if (rows > 0)
{
int optcnt = rows;
select = "select cov.name "
+ "from sbrext.tool_options_view_ext to1, sbrext.tool_options_view_ext to2, sbr.contexts_view cov "
+ "where to1.tool_name = 'SENTINEL' AND to2.tool_name = to1.tool_name "
+ "and to1.property LIKE 'BROADCAST.EXCLUDE.CONTEXT.%.NAME' "
+ "and to2.property LIKE 'BROADCAST.EXCLUDE.CONTEXT.%.CONTE_IDSEQ' "
+ "and SUBSTR(to1.property, 1, 29) = SUBSTR(to2.property, 1, 29) "
+ "and to1.value = cov.name "
+ "and to2.value = cov.conte_idseq";
rows = testDB(select);
if (rows != optcnt)
results += "Missing or invalid BROADCAST.EXCLUDE.CONTEXT settings.\n\n";
}
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property like 'RSVD.CS.%'";
rows = testDB(select);
select = "select tool_idseq from sbrext.tool_options_view_ext "
+ "where tool_name = 'SENTINEL' AND property = 'RSVD.CSI.FORMAT' AND value like '%$ua_name$%'";
rows += testDB(select);
if (rows > 0)
{
if (rows == 3)
{
select = "select cs.long_name "
+ "from sbrext.tool_options_view_ext to1, sbrext.tool_options_view_ext to2, sbr.classification_schemes_view cs "
+ "where to1.tool_name = 'SENTINEL' AND to2.tool_name = to1.tool_name "
+ "and to1.property = 'RSVD.CS.LONG_NAME' "
+ "and to2.property = 'RSVD.CS.CS_IDSEQ' "
+ "and to1.value = cs.long_name "
+ "and to2.value = cs.cs_idseq";
rows = testDB(select);
if (rows != 1)
results += "Missing or invalid RSVD.CS settings.\n\n";
}
else
results += "Missing or invalid RSVD.CS settings.\n\n";
}
_errorCode = 0;
_errorMsg = "";
return (results.length() == 0) ? null : results;
}
/**
* Return the email addresses for all the administrators that should receive a log report.
*
* @return The list of email addresses.
*/
public String[] selectAlertReportAdminEmails()
{
String select = "select ua.electronic_mail_address "
+ "from sbr.user_accounts_view ua, sbrext.tool_options_view_ext opt "
+ "where opt.tool_name = 'SENTINEL' and "
+ "opt.property like 'ADMIN.%' and "
+ "opt.value like '%1%' and ua.ua_name = opt.ua_name "
+ "and ua.electronic_mail_address is not null "
+ "order by opt.property";
String[] list = getBasicData0(select);
if (list != null)
return list;
// Fall back to the default.
select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.ADDR'";
return getBasicData0(select);
}
/**
* Return the Alert Report email reply to address
*
* @return The reply to address.
*/
public String selectAlertReportEmailAddr()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.ADDR'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email introduction for the Alert Report
*
* @return The introduction.
*/
public String selectAlertReportEmailIntro()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.INTRO'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email error introduction for the Alert Report
*
* @return The error introduction.
*/
public String selectAlertReportEmailError()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.ERROR'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email admin title which appears in the "From:" field.
*
* @return The admin title.
*/
public String selectAlertReportAdminTitle()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.ADMIN.NAME'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email SMTP host.
*
* @return The email SMTP host.
*/
public String selectAlertReportEmailHost()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.HOST'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email SMTP host user account.
*
* @return The email SMTP host user account.
*/
public String selectAlertReportEmailHostUser()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.HOST.USER'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email SMTP host user account password.
*
* @return The email SMTP host user account password.
*/
public String selectAlertReportEmailHostPswd()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.HOST.PSWD'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email subject.
*
* @return The email subject.
*/
public String selectAlertReportEmailSubject()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'EMAIL.SUBJECT'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the HTTP link prefix for all report output references.
*
* @return The HTTP link prefix
*/
public String selectAlertReportHTTP()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'URL'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] + "/AlertReports/" : "";
}
/**
* Return the HTTP link prefix for all Sentinel DTD files.
*
* @return The HTTP link prefix
*/
public String selectDtdHTTP()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'URL'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] + "/dtd/" : "";
}
/**
* Return the output directory for all generated files.
*
* @return The output directory prefix
*/
public String selectAlertReportOutputDir()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'OUTPUT.DIR'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the database name as it should appear on reports.
*
* @return The database name
*/
public String selectAlertReportDBName()
{
String select = "select opt.value from sbrext.tool_options_view_ext opt where opt.tool_name = 'SENTINEL' and opt.property = 'DB.NAME'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : "";
}
/**
* Return the email addresses for all the recipients of the statistic report.
*
* @return The list of email addresses.
*/
public String[] selectStatReportEmails()
{
String select = "select ua.electronic_mail_address "
+ "from sbr.user_accounts_view ua, sbrext.tool_options_view_ext opt "
+ "where opt.tool_name = 'SENTINEL' and "
+ "opt.property like 'ADMIN.%' and "
+ "opt.value like '%2%' and ua.ua_name = opt.ua_name "
+ "and ua.electronic_mail_address is not null "
+ "order by opt.property";
return getBasicData0(select);
}
/**
* Return the EVS URL from the tool options.
*
* @return The EVS URL.
*/
public String selectEvsUrl()
{
String select = "select value from sbrext.tool_options_view_ext where tool_name = 'EVS' and property = 'URL'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : null;
}
/**
* Return the Alert Definition name format string.
*
* @return The list of email addresses.
*/
public String selectAlertNameFormat()
{
String select = "select opt.value "
+ "from sbrext.tool_options_view_ext opt "
+ "where opt.tool_name = 'SENTINEL' and "
+ "opt.property = 'ALERT.NAME.FORMAT' ";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : null;
}
/**
* Return the reserved CS id if the reserved CSI is passed to the method.
*
* @param idseq_ The CSI id to check.
*
* @return The reserved CS id or null if the CSI is not reserved.
*/
public String selectCSfromReservedCSI(String idseq_)
{
String select = "select opt.value "
+ "from sbrext.tool_options_view_ext opt, sbr.classification_schemes_view cs, "
+ "sbr.cs_csi_view ci "
+ "where ci.csi_idseq = '" + idseq_ + "' and cs.cs_idseq = ci.cs_idseq and opt.value = cs.cs_idseq and "
+ "opt.tool_name = 'SENTINEL' and opt.property = 'RSVD.CS.CS_IDSEQ'";
String[] list = getBasicData0(select);
return (list != null) ? list[0] : null;
}
/**
* Format the integer to include comma thousand separators.
*
* @param val_ The number in string format.
* @return the number in string format with separators.
*/
private String formatInt(String val_)
{
int loop = val_.length() / 3;
int start = val_.length() % 3;
String text = val_.substring(0, start);
for (int i = 0; i < loop; ++i)
{
text = text + "," + val_.substring(start, start + 3);
start += 3;
}
return (text.charAt(0) == ',') ? text.substring(1) : text;
}
/**
* Retrieve the row counts for all the tables used by the Alert Report.
* The values may be indexed using the _ACTYPE_* variables and an index
* of _ACTYPE_LENGTH is the count of the change history table.
*
* @return The numbers for each table.
*/
public String[] reportRowCounts()
{
String[] extraTables = {"sbrext.ac_change_history_ext", "sbrext.gs_tokens", "sbrext.gs_composite" };
String[] extraNames = {"History Table", "Freestyle Token Index", "Freestyle Concatenation Index" };
int total = _DBMAP3.length + extraTables.length;
String counts[] = new String[total];
String select = "select count(*) from ";
String table;
String name;
int extraNdx = 0;
for (int ndx = 0; ndx < counts.length; ++ndx)
{
if (ndx >= _DBMAP3.length)
{
table = extraTables[extraNdx];
name = extraNames[extraNdx];
++extraNdx;
}
else if (_DBMAP3[ndx]._table == null)
{
counts[ndx] = null;
continue;
}
else
{
table = _DBMAP3[ndx]._table;
name = _DBMAP3[ndx]._val;
}
String temp = select + table;
try
{
PreparedStatement pstmt = _conn.prepareStatement(temp);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
counts[ndx] = name + AuditReport._ColSeparator + formatInt(rs.getString(1));
}
rs.close();
pstmt.close();
}
catch (SQLException ex)
{
_errorCode = DBAlertUtil.getSQLErrorCode(ex);
_errorMsg = temp + "\n" + ex.toString();
counts[ndx] = name + ": " + _errorMsg;
}
}
return counts;
}
/**
* Translate the internal column names to something the user can easily
* read.
*
* @param namespace_
* The scope of the namespace to lookup the val_.
* @param val_
* The internal column name.
* @return The translated value.
*/
public String translateColumn(String namespace_, String val_)
{
// First search global name space as most are consistent.
String rc = DBAlertUtil.binarySearchS(_DBMAP1, val_);
if (rc == val_)
{
// We didn't find it in global now look in the specific name space.
if (namespace_.compareTo("DESIGNATIONS") == 0)
rc = DBAlertUtil.binarySearchS(_DBMAP1DESIG, val_);
else if (namespace_.compareTo("REFERENCE_DOCUMENTS") == 0)
rc = DBAlertUtil.binarySearchS(_DBMAP1RD, val_);
else if (namespace_.compareTo("AC_CSI") == 0)
rc = DBAlertUtil.binarySearchS(_DBMAP1CSI, val_);
else if (namespace_.compareTo("COMPLEX_DATA_ELEMENTS") == 0)
rc = DBAlertUtil.binarySearchS(_DBMAP1COMPLEX, val_);
else
rc = DBAlertUtil.binarySearchS(_DBMAP1OTHER, val_);
return rc;
}
return rc;
}
/**
* Translate the table names for the user.
*
* @param val_
* The internal table name.
* @return The user readable name.
*/
public String translateTable(String val_)
{
if (val_ == null)
return "<null>";
return DBAlertUtil.binarySearchS(_DBMAP3, val_);
}
/**
* Look for the selection of a specific record type.
*
* @param val_ The AC type code.
* @return false if the record type is not found.
*/
public int isACTypeUsed(String val_)
{
return DBAlertUtil.binarySearch(_DBMAP3, val_);
}
/**
* Test if the string table code represents the record type of interest.
*
* @param type_ One of the DBAlert._ACTYPE* constants.
* @param tableCode_ The string type to test.
* @return true if the type and string are equivalent.
*/
public boolean isACType(int type_, String tableCode_)
{
return tableCode_.equals(_DBMAP3[type_]._key);
}
/**
* Get the used (referenced) RELEASED object classes not owned by caBIG
*
* @return the list of object classes
*/
public String[] reportUsedObjectClasses()
{
String cs1 = AuditReport._ColSeparator;
String cs2 = " || '" + cs1 + "' || ";
String select =
"SELECT 'Name" + cs1 + "Public ID" + cs1 + "Version" + cs1 + "Workflow Status" + cs1
+ "Short Name" + cs1 + "Context" + cs1 + "Created" + cs1
+ "Modified" + cs1 + "References" + cs1 + "Order" + cs1
+ "Concept" + cs1 + "Code" + cs1 + "Origin' as title, ' ' AS lname, 0 AS dorder, ' ' AS ocidseq "
+ "from dual UNION ALL "
+ "SELECT oc.long_name" + cs2 + "oc.oc_id" + cs2 + "oc.VERSION" + cs2 + "oc.asl_name" + cs2
+ "oc.preferred_name" + cs2 + "c.NAME" + cs2 + "oc.date_created" + cs2
+ "oc.date_modified" + cs2 + "ocset.cnt" + cs2 + "cc.display_order" + cs2
+ "con.long_name" + cs2 + "con.preferred_name" + cs2 + "con.origin as title, "
+ "LOWER (oc.long_name) AS lname, cc.display_order AS dorder, oc.oc_idseq AS ocidseq "
+ "FROM (SELECT ocv.oc_idseq, COUNT (*) AS cnt "
+ "FROM sbrext.object_classes_view_ext ocv, "
+ "sbr.data_element_concepts_view DEC "
+ "WHERE ocv.asl_name NOT LIKE 'RETIRED%' "
+ "AND ocv.conte_idseq NOT IN ( "
+ "SELECT VALUE "
+ "FROM sbrext.tool_options_view_ext "
+ "WHERE tool_name = 'caDSR' "
+ "AND property = 'DEFAULT_CONTEXT') "
+ "AND DEC.oc_idseq = ocv.oc_idseq "
+ "AND DEC.asl_name NOT LIKE 'RETIRED%' "
+ "GROUP BY ocv.oc_idseq) ocset, "
+ "sbrext.object_classes_view_ext oc, "
+ "sbrext.component_concepts_view_ext cc, "
+ "sbrext.concepts_view_ext con, "
+ "sbr.contexts_view c "
+ "WHERE oc.oc_idseq = ocset.oc_idseq "
+ "AND c.conte_idseq = oc.conte_idseq "
+ "AND cc.condr_idseq = oc.condr_idseq "
+ "AND con.con_idseq = cc.con_idseq "
+ "ORDER BY lname ASC, ocidseq ASC, dorder DESC";
return getBasicData0(select);
}
/**
* Pull the name and email address for all the recipients on a specific Alert Definition.
*
* @param idseq_ the database id of the Alert Definition
*/
public void selectAlertRecipients(String idseq_)
{
//TODO use this method to retrieve the name and emails for the distribution. It will
// guarantee that the pair only appears once in the list. The method signature must be
// changed to return the values.
String select = "SELECT ua.NAME, ua.electronic_mail_address "
+ "FROM sbr.user_accounts_view ua "
+ "WHERE ua.ua_name IN ( "
+ "SELECT rc.ua_name "
+ "FROM sbrext.sn_report_view_ext rep, "
+ "sbrext.sn_recipient_view_ext rc "
+ "WHERE rep.al_idseq = '"+ idseq_ + "' "
+ "AND rc.rep_idseq = rep.rep_idseq "
+ "UNION "
+ "SELECT uc.ua_name "
+ "FROM sbrext.user_contexts_view uc, "
+ "sbr.contexts_view c, "
+ "sbrext.sn_report_view_ext rep, "
+ "sbrext.sn_recipient_view_ext rc "
+ "WHERE rep.al_idseq = '"+ idseq_ + "' "
+ "AND rc.rep_idseq = rep.rep_idseq "
+ "AND c.conte_idseq = rc.conte_idseq "
+ "AND uc.NAME = c.NAME "
+ "AND uc.PRIVILEGE = 'W') "
+ "AND ua.electronic_mail_address IS NOT NULL "
+ "UNION "
+ "SELECT rc.email, rc.email "
+ "FROM sbrext.sn_report_view_ext rep, sbrext.sn_recipient_view_ext rc "
+ "WHERE rep.al_idseq = '"+ idseq_ + "' "
+ "AND rc.rep_idseq = rep.rep_idseq "
+ "AND email IS NOT NULL";
Results1 temp = getBasicData1(select, false);
}
/**
* Retrieve the database Registration Authority Identifier (RAI)
*
* @return the server value
*/
public String getDatabaseRAI()
{
String[] list = getBasicData0("select value from sbrext.tool_options_view_ext where tool_name = 'caDSR' and property = 'RAI'");
return (list != null) ? list[0] : null;
}
/**
* Convert all meaning full names back to the internal codes for the XML generation
*
* @param changes -
* array of names for changes
* @return - array of the corresponding key values
*/
@SuppressWarnings("unchecked")
public String[] getKeyNames(String[] changes)
{
// Convert to list
List<DBAlertOracleMap1> list = new ArrayList<DBAlertOracleMap1>(Arrays.asList(concat(_DBMAP1, _DBMAP1DESIG, _DBMAP1RD, _DBMAP1CSI, _DBMAP1COMPLEX,
_DBMAP1OTHER)));
// Ensure list sorted
Collections.sort(list);
// Convert it back to array as this is how the binary search is implemented
DBAlertOracleMap1[] tempMap = list.toArray(new DBAlertOracleMap1[list.size()]);
// Store the values into the new array and return the array
String[] temp = new String[changes.length];
for (int i = 0; i < changes.length; i++)
{
int rowID = DBAlertUtil.binarySearchValues(tempMap, changes[i]);
temp[i] = tempMap[rowID]._key;
}
return temp; // To change body of implemented methods use File | Settings | File Templates.
}
/**
* Concatenate all map arrays
*
* @param maps the list of maps to concatenate
* @return a single map
*/
private DBAlertOracleMap1[] concat(DBAlertOracleMap1[] ... maps)
{
int total = 0;
for (DBAlertOracleMap1[] map : maps)
{
total += map.length;
}
DBAlertOracleMap1[] concatMap = new DBAlertOracleMap1[total];
total = 0;
for (DBAlertOracleMap1[] map : maps)
{
System.arraycopy(map, 0, concatMap, total, map.length);
total += map.length;
}
return concatMap;
}
}
|
check for presence of RAI
SVN-Revision: 534
|
sentinel/src/gov/nih/nci/cadsr/sentinel/database/DBAlertOracle.java
|
check for presence of RAI
|
|
Java
|
bsd-3-clause
|
ca428eac3651d4bf5e58a608390ba928e3f52c29
| 0
|
NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror
|
/**
*
*/
package edu.northwestern.bioinformatics.studycalendar.grid;
import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.dataproviders.coppa.CoppaProviderConstants;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.domain.Site;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySecondaryIdentifier;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySite;
import edu.northwestern.bioinformatics.studycalendar.service.SiteService;
import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.service.TemplateDevelopmentService;
import edu.northwestern.bioinformatics.studycalendar.service.TemplateSkeletonCreatorImpl;
import gov.nih.nci.cabig.ccts.domain.ArmType;
import gov.nih.nci.cabig.ccts.domain.EpochType;
import gov.nih.nci.cabig.ccts.domain.IdentifierType;
import gov.nih.nci.cabig.ccts.domain.NonTreatmentEpochType;
import gov.nih.nci.cabig.ccts.domain.OrganizationAssignedIdentifierType;
import gov.nih.nci.cabig.ccts.domain.StudyOrganizationType;
import gov.nih.nci.cabig.ccts.domain.StudySiteType;
import gov.nih.nci.cabig.ccts.domain.SystemAssignedIdentifierType;
import gov.nih.nci.cabig.ccts.domain.TreatmentEpochType;
import gov.nih.nci.cabig.ctms.audit.dao.AuditHistoryRepository;
import gov.nih.nci.ccts.grid.studyconsumer.common.StudyConsumerI;
import gov.nih.nci.ccts.grid.studyconsumer.stubs.types.InvalidStudyException;
import gov.nih.nci.ccts.grid.studyconsumer.stubs.types.StudyCreationException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.oasis.wsrf.properties.GetMultipleResourcePropertiesResponse;
import org.oasis.wsrf.properties.GetMultipleResourceProperties_Element;
import org.oasis.wsrf.properties.GetResourcePropertyResponse;
import org.oasis.wsrf.properties.QueryResourcePropertiesResponse;
import org.oasis.wsrf.properties.QueryResourceProperties_Element;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;
/**
* 1. If Site does not exist DB, we will create it.
*
* @author <a href="mailto:saurabh.agrawal@semanticbits.com>Saurabh Agrawal</a>
*/
@Transactional(readOnly = false)
public class PSCStudyConsumer implements StudyConsumerI {
private static final Log logger = LogFactory.getLog(PSCStudyConsumer.class);
public static final String SERVICE_BEAN_NAME = "scheduledCalendarService";
private static final String COORDINATING_CENTER_IDENTIFIER_TYPE = "Coordinating Center Identifier";
private static final String COPPA_INDENTIFIER_TYPE = "COPPA Identifier";
private SiteDao siteDao;
private StudyService studyService;
private SiteService siteService;
private StudyDao studyDao;
private AuditHistoryRepository auditHistoryRepository;
private String studyConsumerGridServiceUrl;
private String rollbackTimeOut;
private TemplateDevelopmentService templateDevelopmentService;
public void createStudy(final gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException,
StudyCreationException {
if (studyDto == null) {
String message = "No Study message was found";
throw getInvalidStudyException(message);
}
String ccIdentifier = findCoordinatingCenterIdentifier(studyDto);
if (studyDao.getStudyIdByAssignedIdentifier(ccIdentifier) != null) {
logger.info("Already a study with the same Coordinating Center Identifier (" + ccIdentifier
+ ") exists.Returning without processing the request.");
return;
}
// <-- Start added for COPPA Identifier -->
// 1.Get the COPPA Identifier(if present in the request)
String coppaIdentifier = findCoppaIdentifier(studyDto);
boolean hasCoppaIdentifier = false;
if ((coppaIdentifier != null) && !coppaIdentifier.equals("")){
// 2.Check if COPPA Identifier already exist in DB or not
// If exist then return
if (studyDao.getStudySecondaryIdentifierByCoppaIdentifier(CoppaProviderConstants.COPPA_STUDY_IDENTIFIER_TYPE, coppaIdentifier) != null) {
logger.info("Already a study with the same Coppa Identifier (" + coppaIdentifier
+ ") exists.Returning without processing the request.");
return;
}
hasCoppaIdentifier = true;
}
// <-- End added for COPPA Identifier -->
Study study = TemplateSkeletonCreatorImpl.createBase(studyDto.getShortTitleText());
study.setAssignedIdentifier(ccIdentifier);
// 3.Add COPPA Identifier as secondary Identifier in Study
if(hasCoppaIdentifier){
StudySecondaryIdentifier studySecondaryIdentifier = new StudySecondaryIdentifier();
studySecondaryIdentifier.setStudy(study);
// set coppa type from CoppaProviderConstants.COPPA_STUDY_IDENTIFIER_TYPE
studySecondaryIdentifier.setType(CoppaProviderConstants.COPPA_STUDY_IDENTIFIER_TYPE);
// set value from the request
studySecondaryIdentifier.setValue(coppaIdentifier);
// Add coppa identifier as secondaryIndentifier in study
study.addSecondaryIdentifier(studySecondaryIdentifier);
// Set the provider as COPPA(CoppaProviderConstants.PROVIDER_TOKEN)
study.setProvider(CoppaProviderConstants.PROVIDER_TOKEN);
}
study.setGridId(studyDto.getGridId());
study.setLongTitle(studyDto.getLongTitleText());
gov.nih.nci.cabig.ccts.domain.StudyOrganizationType[] studyOrganizationTypes = studyDto.getStudyOrganization();
populateStudySite(study, studyOrganizationTypes);
// now add epochs and arms to the planned calendar of study
populateEpochsAndArms(studyDto, study);
studyService.save(study);
logger.info("Created the study :" + study.getId());
}
/**
* This method will return the COPPA identifier
*
* @param studyDto
* @return
* @throws InvalidStudyException
*/
private String findCoppaIdentifier(final gov.nih.nci.cabig.ccts.domain.Study studyDto){
String coppaIdentifier = null;
if (studyDto != null) {
for (IdentifierType identifierType : studyDto.getIdentifier()) {
if (identifierType instanceof SystemAssignedIdentifierType
&& StringUtils.equals(identifierType.getType(), COPPA_INDENTIFIER_TYPE)) {
coppaIdentifier = identifierType.getValue();
break;
}
}
}
return coppaIdentifier;
}
/**
* does nothing as we are already commiting Study message by default.
*
* @param study
* @throws RemoteException
* @throws InvalidStudyException
*/
public void commit(final gov.nih.nci.cabig.ccts.domain.Study study) throws RemoteException, InvalidStudyException {
// if (studyDto == null) {
// throw new InvalidStudyException();
// }
// logger.info("commit called for study:long titlte-" + studyDto.getLongTitleText());
// String ccIdentifier = findCoordinatingCenterIdentifier(studyDto);
//
// try {
// studyDao.commitInProgressStudy(ccIdentifier);
// }
//
// catch (Exception exp) {
// logger.error("Exception while trying to commit the study", exp);
// InvalidStudyException invalidStudyException = new InvalidStudyException();
// invalidStudyException.setFaultReason("Exception while comitting study," + exp.getMessage());
// invalidStudyException.setFaultString("Exception while comitting study," + exp.getMessage());
// throw invalidStudyException;
// }
}
public void rollback(final gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException {
if (studyDto == null) {
String message = "No Study message was found";
throw getInvalidStudyException(message);
}
logger.info("rollback called for study:long titlte-" + studyDto.getLongTitleText());
String ccIdentifier = findCoordinatingCenterIdentifier(studyDto);
Study study = studyService.getStudyByAssignedIdentifier(ccIdentifier);
if (study == null) {
String message = "Exception while rollback study..no study found with given identifier:" + ccIdentifier;
throw getInvalidStudyException(message);
}
//check if study was created by the grid service or not
boolean checkIfEntityWasCreatedByGridService = auditHistoryRepository.checkIfEntityWasCreatedByUrl(study.getClass(), study.getId(), studyConsumerGridServiceUrl);
if (!checkIfEntityWasCreatedByGridService) {
logger.info("Study was not created by the grid service url:" + studyConsumerGridServiceUrl + " so can not rollback this study:" + study.getId());
return;
}
logger.info("Study (id:" + study.getId() + ") was created by the grid service url:" + studyConsumerGridServiceUrl);
//check if this study was created one minute before or not
Calendar calendar = Calendar.getInstance();
Integer rollbackTime = 1;
try {
rollbackTime = Integer.parseInt(rollbackTimeOut);
} catch (NumberFormatException e) {
logger.error(String.format("error parsing value of rollback time out. Value of rollback time out %s must be integer.", rollbackTimeOut));
}
boolean checkIfStudyWasCreatedOneMinuteBeforeCurrentTime = auditHistoryRepository.
checkIfEntityWasCreatedMinutesBeforeSpecificDate(study.getClass(), study.getId(), calendar, rollbackTime);
try {
if (checkIfStudyWasCreatedOneMinuteBeforeCurrentTime) {
logger.info("Study was created one minute before the current time:" + calendar.getTime().toString() + " so deleting this study:" + study.getId());
templateDevelopmentService.deleteDevelopmentAmendment(study);
} else {
logger.info(String.format("Study was not created %s minute before the current time:%s so can not rollback this study:%s",
rollbackTime, calendar.getTime().toString(), study.getId()));
}
}
catch (Exception expception) {
String message = "Exception while rollback study," + expception.getMessage() + expception.getClass();
expception.printStackTrace();
throw getInvalidStudyException(message);
}
}
public GetMultipleResourcePropertiesResponse getMultipleResourceProperties(final GetMultipleResourceProperties_Element getMultipleResourceProperties_element) throws RemoteException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public GetResourcePropertyResponse getResourceProperty(final QName qName) throws RemoteException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public QueryResourcePropertiesResponse queryResourceProperties(final QueryResourceProperties_Element queryResourceProperties_element) throws RemoteException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
private void populateEpochsAndArms(final gov.nih.nci.cabig.ccts.domain.Study studyDto, final Study study) {
EpochType[] epochTypes = studyDto.getEpoch();
if (epochTypes != null) {
for (int i = 0; i < epochTypes.length; i++) {
EpochType epochType = epochTypes[i];
if (epochType instanceof NonTreatmentEpochType || ((TreatmentEpochType) epochType).getArm() == null || ((TreatmentEpochType) epochType).getArm().length == 0) {
TemplateSkeletonCreatorImpl.addEpoch(study, i, Epoch.create(epochType.getName()));
} else if (epochType instanceof TreatmentEpochType) {
TemplateSkeletonCreatorImpl.addEpoch(study, i,
createEpochForTreatmentEpochType((TreatmentEpochType) epochType));
}
}
}
}
private Epoch createEpochForTreatmentEpochType(final TreatmentEpochType treatmentEpochType) {
Epoch epoch = null;
ArmType[] armTypes = treatmentEpochType.getArm();
if (armTypes != null) {
List<String> armNames = new ArrayList<String>();
for (ArmType armType : armTypes) {
armNames.add(armType.getName());
}
epoch = Epoch.create(treatmentEpochType.getName(), armNames.toArray(new String[0]));
}
return epoch;
}
/**
* Populates study siste and returns it.
*
* @param study
* @param studyOrganizationTypes
* @throws InvalidStudyException
*/
private void populateStudySite(final Study study, final gov.nih.nci.cabig.ccts.domain.StudyOrganizationType[] studyOrganizationTypes)
throws StudyCreationException, InvalidStudyException {
List<StudySite> studySites = new ArrayList<StudySite>();
if (studyOrganizationTypes != null) {
for (StudyOrganizationType studyOrganizationType : studyOrganizationTypes) {
StudySite studySite = null;
if (studyOrganizationType instanceof StudySiteType) {
studySite = new StudySite();
studySite.setSite(fetchSite(studyOrganizationType));
studySite.setStudy(study);
studySite.setGridId(studyOrganizationType.getGridId());
}
studySites.add(studySite);
}
}
if (studySites.size() == 0 || ArrayUtils.isEmpty(studyOrganizationTypes)) {
String message = "No sites is associated to this study" + study.getLongTitle();
throw getStudyCreationException(message);
}
study.setStudySites(studySites);
}
/**
* Fetches the site from the DB or creates the site
*
* @param studyOrganizationType
* @return
*/
private Site fetchSite(final StudyOrganizationType studyOrganizationType) throws StudyCreationException {
String assignedIdentifier = studyOrganizationType.getHealthcareSite(0).getNciInstituteCode();
String siteName = studyOrganizationType.getHealthcareSite(0).getName();
Site site = siteDao.getByAssignedIdentifier(assignedIdentifier);
if (site == null) {
logger.info("No site exist in DB with assignedIdentifier: " + assignedIdentifier);
String gridIdAssignedIdentifier = studyOrganizationType.getHealthcareSite(0).getGridId();
if((gridIdAssignedIdentifier == null) || (gridIdAssignedIdentifier.equals(""))){
logger.info("Site created with assignedIdentifier: " + assignedIdentifier);
site = createSite(assignedIdentifier, siteName, false);
}else{
site = siteDao.getByAssignedIdentifier(gridIdAssignedIdentifier);
}
if (site == null) {
// create the site if its not in DB
logger.info("Site created with remote assignedIdentifier: " + gridIdAssignedIdentifier);
site = createSite(gridIdAssignedIdentifier, siteName, true);
}
}
return site;
}
/**
* Creates the site in the DB
*
* @param assignedIdentifier
* @param siteName
* @return
*/
private Site createSite(String assignedIdentifier, String siteName, boolean isRemote){
Site site = new Site();
site.setName(siteName);
site.setAssignedIdentifier(assignedIdentifier);
if(isRemote){
site.setProvider(CoppaProviderConstants.PROVIDER_TOKEN);
}
// Save it to DB
siteService.createOrUpdateSite(site);
return site;
}
/**
* This method will return the identifier specified by Coordinating center to this study.
*
* @param studyDto
* @return
* @throws InvalidStudyException
*/
private String findCoordinatingCenterIdentifier(final gov.nih.nci.cabig.ccts.domain.Study studyDto) throws InvalidStudyException {
String ccIdentifier = null;
if (studyDto.getIdentifier() != null) {
for (IdentifierType identifierType : studyDto.getIdentifier()) {
if (identifierType instanceof OrganizationAssignedIdentifierType
&& StringUtils.equals(identifierType.getType(), COORDINATING_CENTER_IDENTIFIER_TYPE)) {
ccIdentifier = identifierType.getValue();
break;
}
}
}
if (ccIdentifier == null) {
String message = "no cc identifier for study:long titlte-" + studyDto.getLongTitleText();
throw getInvalidStudyException(message);
}
return ccIdentifier;
}
private StudyCreationException getStudyCreationException(final String message) {
StudyCreationException studyCreationException = new StudyCreationException();
studyCreationException.setFaultString(message);
studyCreationException.setFaultReason(message);
logger.error(message);
return studyCreationException;
}
private InvalidStudyException getInvalidStudyException(final String message) throws InvalidStudyException {
logger.error(message);
InvalidStudyException invalidStudyException = new InvalidStudyException();
invalidStudyException.setFaultReason(message);
invalidStudyException.setFaultString(message);
throw invalidStudyException;
}
@Required
public void setStudyConsumerGridServiceUrl(String studyConsumerGridServiceUrl) {
this.studyConsumerGridServiceUrl = studyConsumerGridServiceUrl;
}
@Required
public void setSiteDao(SiteDao siteDao) {
this.siteDao = siteDao;
}
@Required
public void setStudyService(StudyService studyService) {
this.studyService = studyService;
}
@Required
public void setSiteService(SiteService siteService) {
this.siteService = siteService;
}
@Required
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
@Required
public void setAuditHistoryRepository(AuditHistoryRepository auditHistoryRepository) {
this.auditHistoryRepository = auditHistoryRepository;
}
@Required
public void setTemplateDevelopmentService(
TemplateDevelopmentService templateDevelopmentService) {
this.templateDevelopmentService = templateDevelopmentService;
}
@Required
public void setRollbackTimeOut(String rollbackTimeOut) {
this.rollbackTimeOut = rollbackTimeOut;
}
}
|
grid/study-consumer/src/java/edu/northwestern/bioinformatics/studycalendar/grid/PSCStudyConsumer.java
|
/**
*
*/
package edu.northwestern.bioinformatics.studycalendar.grid;
import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.dataproviders.coppa.CoppaProviderConstants;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.domain.Site;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySecondaryIdentifier;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySite;
import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.service.TemplateDevelopmentService;
import edu.northwestern.bioinformatics.studycalendar.service.TemplateSkeletonCreatorImpl;
import gov.nih.nci.cabig.ccts.domain.ArmType;
import gov.nih.nci.cabig.ccts.domain.EpochType;
import gov.nih.nci.cabig.ccts.domain.IdentifierType;
import gov.nih.nci.cabig.ccts.domain.NonTreatmentEpochType;
import gov.nih.nci.cabig.ccts.domain.OrganizationAssignedIdentifierType;
import gov.nih.nci.cabig.ccts.domain.StudyOrganizationType;
import gov.nih.nci.cabig.ccts.domain.StudySiteType;
import gov.nih.nci.cabig.ccts.domain.SystemAssignedIdentifierType;
import gov.nih.nci.cabig.ccts.domain.TreatmentEpochType;
import gov.nih.nci.cabig.ctms.audit.dao.AuditHistoryRepository;
import gov.nih.nci.ccts.grid.studyconsumer.common.StudyConsumerI;
import gov.nih.nci.ccts.grid.studyconsumer.stubs.types.InvalidStudyException;
import gov.nih.nci.ccts.grid.studyconsumer.stubs.types.StudyCreationException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.oasis.wsrf.properties.GetMultipleResourcePropertiesResponse;
import org.oasis.wsrf.properties.GetMultipleResourceProperties_Element;
import org.oasis.wsrf.properties.GetResourcePropertyResponse;
import org.oasis.wsrf.properties.QueryResourcePropertiesResponse;
import org.oasis.wsrf.properties.QueryResourceProperties_Element;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;
/**
* Assumptions: 1. Site should already be existing in DB..
*
* @author <a href="mailto:saurabh.agrawal@semanticbits.com>Saurabh Agrawal</a>
*/
@Transactional(readOnly = false)
public class PSCStudyConsumer implements StudyConsumerI {
private static final Log logger = LogFactory.getLog(PSCStudyConsumer.class);
public static final String SERVICE_BEAN_NAME = "scheduledCalendarService";
private static final String COORDINATING_CENTER_IDENTIFIER_TYPE = "Coordinating Center Identifier";
private static final String COPPA_INDENTIFIER_TYPE = "COPPA Identifier";
private SiteDao siteDao;
private StudyService studyService;
private StudyDao studyDao;
private AuditHistoryRepository auditHistoryRepository;
private String studyConsumerGridServiceUrl;
private String rollbackTimeOut;
private TemplateDevelopmentService templateDevelopmentService;
public void createStudy(final gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException,
StudyCreationException {
if (studyDto == null) {
String message = "No Study message was found";
throw getInvalidStudyException(message);
}
String ccIdentifier = findCoordinatingCenterIdentifier(studyDto);
if (studyDao.getStudyIdByAssignedIdentifier(ccIdentifier) != null) {
logger.info("Already a study with the same Coordinating Center Identifier (" + ccIdentifier
+ ") exists.Returning without processing the request.");
return;
}
// <-- Start added for COPPA Identifier -->
// 1.Get the COPPA Identifier(if present in the request)
String coppaIdentifier = findCoppaIdentifier(studyDto);
boolean hasCoppaIdentifier = false;
if ((coppaIdentifier != null) && !coppaIdentifier.equals("")){
// 2.Check if COPPA Identifier already exist in DB or not
// If exist then return
if (studyDao.getStudySecondaryIdentifierByCoppaIdentifier(CoppaProviderConstants.COPPA_STUDY_IDENTIFIER_TYPE, coppaIdentifier) != null) {
logger.info("Already a study with the same Coppa Identifier (" + coppaIdentifier
+ ") exists.Returning without processing the request.");
return;
}
hasCoppaIdentifier = true;
}
// <-- End added for COPPA Identifier -->
Study study = TemplateSkeletonCreatorImpl.createBase(studyDto.getShortTitleText());
study.setAssignedIdentifier(ccIdentifier);
// 3.Add COPPA Identifier as secondary Identifier in Study
if(hasCoppaIdentifier){
StudySecondaryIdentifier studySecondaryIdentifier = new StudySecondaryIdentifier();
studySecondaryIdentifier.setStudy(study);
// set coppa type from CoppaProviderConstants.COPPA_STUDY_IDENTIFIER_TYPE
studySecondaryIdentifier.setType(CoppaProviderConstants.COPPA_STUDY_IDENTIFIER_TYPE);
// set value from the request
studySecondaryIdentifier.setValue(coppaIdentifier);
// Add coppa identifier as secondaryIndentifier in study
study.addSecondaryIdentifier(studySecondaryIdentifier);
// Set the provider as COPPA(CoppaProviderConstants.PROVIDER_TOKEN)
study.setProvider(CoppaProviderConstants.PROVIDER_TOKEN);
}
study.setGridId(studyDto.getGridId());
study.setLongTitle(studyDto.getLongTitleText());
gov.nih.nci.cabig.ccts.domain.StudyOrganizationType[] studyOrganizationTypes = studyDto.getStudyOrganization();
populateStudySite(study, studyOrganizationTypes);
// now add epochs and arms to the planned calendar of study
populateEpochsAndArms(studyDto, study);
studyService.save(study);
logger.info("Created the study :" + study.getId());
}
/**
* This method will return the COPPA identifier
*
* @param studyDto
* @return
* @throws InvalidStudyException
*/
private String findCoppaIdentifier(final gov.nih.nci.cabig.ccts.domain.Study studyDto){
String coppaIdentifier = null;
if (studyDto != null) {
for (IdentifierType identifierType : studyDto.getIdentifier()) {
if (identifierType instanceof SystemAssignedIdentifierType
&& StringUtils.equals(identifierType.getType(), COPPA_INDENTIFIER_TYPE)) {
coppaIdentifier = identifierType.getValue();
break;
}
}
}
return coppaIdentifier;
}
/**
* does nothing as we are already commiting Study message by default.
*
* @param study
* @throws RemoteException
* @throws InvalidStudyException
*/
public void commit(final gov.nih.nci.cabig.ccts.domain.Study study) throws RemoteException, InvalidStudyException {
// if (studyDto == null) {
// throw new InvalidStudyException();
// }
// logger.info("commit called for study:long titlte-" + studyDto.getLongTitleText());
// String ccIdentifier = findCoordinatingCenterIdentifier(studyDto);
//
// try {
// studyDao.commitInProgressStudy(ccIdentifier);
// }
//
// catch (Exception exp) {
// logger.error("Exception while trying to commit the study", exp);
// InvalidStudyException invalidStudyException = new InvalidStudyException();
// invalidStudyException.setFaultReason("Exception while comitting study," + exp.getMessage());
// invalidStudyException.setFaultString("Exception while comitting study," + exp.getMessage());
// throw invalidStudyException;
// }
}
public void rollback(final gov.nih.nci.cabig.ccts.domain.Study studyDto) throws RemoteException, InvalidStudyException {
if (studyDto == null) {
String message = "No Study message was found";
throw getInvalidStudyException(message);
}
logger.info("rollback called for study:long titlte-" + studyDto.getLongTitleText());
String ccIdentifier = findCoordinatingCenterIdentifier(studyDto);
Study study = studyService.getStudyByAssignedIdentifier(ccIdentifier);
if (study == null) {
String message = "Exception while rollback study..no study found with given identifier:" + ccIdentifier;
throw getInvalidStudyException(message);
}
//check if study was created by the grid service or not
boolean checkIfEntityWasCreatedByGridService = auditHistoryRepository.checkIfEntityWasCreatedByUrl(study.getClass(), study.getId(), studyConsumerGridServiceUrl);
if (!checkIfEntityWasCreatedByGridService) {
logger.info("Study was not created by the grid service url:" + studyConsumerGridServiceUrl + " so can not rollback this study:" + study.getId());
return;
}
logger.info("Study (id:" + study.getId() + ") was created by the grid service url:" + studyConsumerGridServiceUrl);
//check if this study was created one minute before or not
Calendar calendar = Calendar.getInstance();
Integer rollbackTime = 1;
try {
rollbackTime = Integer.parseInt(rollbackTimeOut);
} catch (NumberFormatException e) {
logger.error(String.format("error parsing value of rollback time out. Value of rollback time out %s must be integer.", rollbackTimeOut));
}
boolean checkIfStudyWasCreatedOneMinuteBeforeCurrentTime = auditHistoryRepository.
checkIfEntityWasCreatedMinutesBeforeSpecificDate(study.getClass(), study.getId(), calendar, rollbackTime);
try {
if (checkIfStudyWasCreatedOneMinuteBeforeCurrentTime) {
logger.info("Study was created one minute before the current time:" + calendar.getTime().toString() + " so deleting this study:" + study.getId());
templateDevelopmentService.deleteDevelopmentAmendment(study);
} else {
logger.info(String.format("Study was not created %s minute before the current time:%s so can not rollback this study:%s",
rollbackTime, calendar.getTime().toString(), study.getId()));
}
}
catch (Exception expception) {
String message = "Exception while rollback study," + expception.getMessage() + expception.getClass();
expception.printStackTrace();
throw getInvalidStudyException(message);
}
}
public GetMultipleResourcePropertiesResponse getMultipleResourceProperties(final GetMultipleResourceProperties_Element getMultipleResourceProperties_element) throws RemoteException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public GetResourcePropertyResponse getResourceProperty(final QName qName) throws RemoteException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public QueryResourcePropertiesResponse queryResourceProperties(final QueryResourceProperties_Element queryResourceProperties_element) throws RemoteException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
private void populateEpochsAndArms(final gov.nih.nci.cabig.ccts.domain.Study studyDto, final Study study) {
EpochType[] epochTypes = studyDto.getEpoch();
if (epochTypes != null) {
for (int i = 0; i < epochTypes.length; i++) {
EpochType epochType = epochTypes[i];
if (epochType instanceof NonTreatmentEpochType || ((TreatmentEpochType) epochType).getArm() == null || ((TreatmentEpochType) epochType).getArm().length == 0) {
TemplateSkeletonCreatorImpl.addEpoch(study, i, Epoch.create(epochType.getName()));
} else if (epochType instanceof TreatmentEpochType) {
TemplateSkeletonCreatorImpl.addEpoch(study, i,
createEpochForTreatmentEpochType((TreatmentEpochType) epochType));
}
}
}
}
private Epoch createEpochForTreatmentEpochType(final TreatmentEpochType treatmentEpochType) {
Epoch epoch = null;
ArmType[] armTypes = treatmentEpochType.getArm();
if (armTypes != null) {
List<String> armNames = new ArrayList<String>();
for (ArmType armType : armTypes) {
armNames.add(armType.getName());
}
epoch = Epoch.create(treatmentEpochType.getName(), armNames.toArray(new String[0]));
}
return epoch;
}
/**
* Populates study siste and returns it.
*
* @param study
* @param studyOrganizationTypes
* @throws InvalidStudyException
*/
private void populateStudySite(final Study study, final gov.nih.nci.cabig.ccts.domain.StudyOrganizationType[] studyOrganizationTypes)
throws StudyCreationException, InvalidStudyException {
List<StudySite> studySites = new ArrayList<StudySite>();
if (studyOrganizationTypes != null) {
for (StudyOrganizationType studyOrganizationType : studyOrganizationTypes) {
StudySite studySite = null;
if (studyOrganizationType instanceof StudySiteType) {
studySite = new StudySite();
studySite.setSite(fetchSite(studyOrganizationType));
studySite.setStudy(study);
studySite.setGridId(studyOrganizationType.getGridId());
}
studySites.add(studySite);
}
}
if (studySites.size() == 0 || ArrayUtils.isEmpty(studyOrganizationTypes)) {
String message = "No sites is associated to this study" + study.getLongTitle();
throw getStudyCreationException(message);
}
study.setStudySites(studySites);
}
/**
* Fetches the site from the DB
*
* @param assignedIdentifier
* @return
*/
private Site fetchSite(final StudyOrganizationType studyOrganizationType) throws StudyCreationException {
String assignedIdentifier = studyOrganizationType.getHealthcareSite(0).getNciInstituteCode();
Site site = siteDao.getByAssignedIdentifier(assignedIdentifier);
if (site == null) {
assignedIdentifier = studyOrganizationType.getHealthcareSite(0).getGridId();
if((assignedIdentifier != null) && !(assignedIdentifier.equals(""))){
site = siteDao.getByAssignedIdentifier(assignedIdentifier);
}
if (site == null) {
String message = "No site exists assignedIdentifier :" + assignedIdentifier;
throw getStudyCreationException(message);
}
}
return site;
}
/**
* This method will return the identifier specified by Coordinating center to this study.
*
* @param studyDto
* @return
* @throws InvalidStudyException
*/
private String findCoordinatingCenterIdentifier(final gov.nih.nci.cabig.ccts.domain.Study studyDto) throws InvalidStudyException {
String ccIdentifier = null;
if (studyDto.getIdentifier() != null) {
for (IdentifierType identifierType : studyDto.getIdentifier()) {
if (identifierType instanceof OrganizationAssignedIdentifierType
&& StringUtils.equals(identifierType.getType(), COORDINATING_CENTER_IDENTIFIER_TYPE)) {
ccIdentifier = identifierType.getValue();
break;
}
}
}
if (ccIdentifier == null) {
String message = "no cc identifier for study:long titlte-" + studyDto.getLongTitleText();
throw getInvalidStudyException(message);
}
return ccIdentifier;
}
private StudyCreationException getStudyCreationException(final String message) {
StudyCreationException studyCreationException = new StudyCreationException();
studyCreationException.setFaultString(message);
studyCreationException.setFaultReason(message);
logger.error(message);
return studyCreationException;
}
private InvalidStudyException getInvalidStudyException(final String message) throws InvalidStudyException {
logger.error(message);
InvalidStudyException invalidStudyException = new InvalidStudyException();
invalidStudyException.setFaultReason(message);
invalidStudyException.setFaultString(message);
throw invalidStudyException;
}
@Required
public void setStudyConsumerGridServiceUrl(String studyConsumerGridServiceUrl) {
this.studyConsumerGridServiceUrl = studyConsumerGridServiceUrl;
}
@Required
public void setSiteDao(SiteDao siteDao) {
this.siteDao = siteDao;
}
@Required
public void setStudyService(StudyService studyService) {
this.studyService = studyService;
}
@Required
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
@Required
public void setAuditHistoryRepository(AuditHistoryRepository auditHistoryRepository) {
this.auditHistoryRepository = auditHistoryRepository;
}
@Required
public void setTemplateDevelopmentService(
TemplateDevelopmentService templateDevelopmentService) {
this.templateDevelopmentService = templateDevelopmentService;
}
@Required
public void setRollbackTimeOut(String rollbackTimeOut) {
this.rollbackTimeOut = rollbackTimeOut;
}
}
|
Feature #903: modified to Automatically create sites on demand in CCTS study consumer
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@4776 0d517254-b314-0410-acde-c619094fa49f
|
grid/study-consumer/src/java/edu/northwestern/bioinformatics/studycalendar/grid/PSCStudyConsumer.java
|
Feature #903: modified to Automatically create sites on demand in CCTS study consumer
|
|
Java
|
bsd-3-clause
|
b5985a4f47fc6e8bbc65caab02765cc1d0dc1ea4
| 0
|
nfi/mspsim,mspsim/mspsim,mspsim/mspsim,nfi/mspsim
|
/**
* Copyright (c) 2007, Swedish Institute of Computer Science.
* 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. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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.
*
* This file is part of MSPSim.
*
* -----------------------------------------------------------------
*
* ELF
*
* Author : Joakim Eriksson
* Created : Sun Oct 21 22:00:00 2007
*/
package se.sics.mspsim.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import se.sics.mspsim.debug.DwarfReader;
import se.sics.mspsim.debug.StabDebug;
public class ELF {
// private static final int EI_NIDENT = 16;
private static final int EI_ENCODING = 5;
private static final int[] MAGIC = new int[] {0x7f, 'E', 'L', 'F'};
public static final boolean DEBUG = false;
boolean encMSB = true;
int type;
int machine;
int version;
int entry;
int phoff;
int shoff;
int flags;
int ehsize;
int phentsize;
int phnum;
int shentsize;
int shnum;
int shstrndx;
byte[] elfData;
private int pos = 0;
private ELFSection sections[];
private ELFProgram programs[];
private ArrayList<FileInfo> files = new ArrayList<FileInfo>();
ELFSection strTable;
ELFSection symTable;
ELFSection dbgStab;
public ELFSection dbgStabStr;
ELFDebug debug;
public ELF(byte[] data) {
elfData = data;
setPos(0);
}
/* check if the file exists and is an ELF file */
public static boolean isELF(File file) {
try {
InputStream input = new BufferedInputStream(new FileInputStream(file));
for (int i = 0; i < MAGIC.length; i++) {
if (MAGIC[i] != input.read()) {
input.close();
return false;
}
}
input.close();
return true;
} catch(IOException ioe) {
// ignore and return false - this is not an elf.
return false;
}
}
private void readHeader() throws ELFException {
for (int i = 0; i < MAGIC.length; i++) {
if (elfData[i] != (byte) (MAGIC[i] & 0xff)) {
throw new ELFException("Not an elf file");
}
}
if (elfData[EI_ENCODING] == 2) {
encMSB = true;
} else if (elfData[EI_ENCODING] == 1) {
encMSB = false;
} else {
throw new ELFException("Illegal encoding: " + elfData[EI_ENCODING]);
}
setPos(getPos() + 16);
type = readElf16();
machine = readElf16();
version = readElf32();
entry = readElf32();
phoff = readElf32();
shoff = readElf32();
flags = readElf32();
ehsize = readElf16();
phentsize = readElf16();
phnum = readElf16();
shentsize = readElf16();
shnum = readElf16();
shstrndx = readElf16();
if (DEBUG) {
System.out.println("-- ELF Header --");
System.out.println("type: " + Integer.toString(type, 16));
System.out.println("machine: " + Integer.toString(machine, 16));
System.out.println("version: " + Integer.toString(version, 16));
System.out.println("entry: " + Integer.toString(entry, 16));
System.out.println("phoff: " + Integer.toString(phoff, 16));
System.out.println("shoff: " + Integer.toString(shoff, 16));
System.out.println("flags: " + Integer.toString(flags, 16));
System.out.println("ehsize: " + Integer.toString(ehsize, 16));
System.out.println("phentsize: " + Integer.toString(phentsize, 16));
System.out.println("phentnum: " + Integer.toString(phnum, 16));
System.out.println("shentsize: " + Integer.toString(shentsize, 16));
System.out.println("shentnum: " + Integer.toString(shnum, 16));
System.out.println("shstrndx: " + Integer.toString(shstrndx, 16));
}
}
private ELFSection readSectionHeader() {
ELFSection sec = new ELFSection();
sec.name = readElf32();
sec.type = readElf32();
sec.flags = readElf32();
sec.addr = readElf32();
sec.setOffset(readElf32());
sec.size = readElf32();
sec.link = readElf32();
sec.info = readElf32();
sec.addralign = readElf32();
sec.setEntrySize(readElf32());
sec.elf = this;
return sec;
}
private ELFProgram readProgramHeader() {
ELFProgram pHeader = new ELFProgram();
pHeader.type = readElf32();
pHeader.offset = readElf32();
pHeader.vaddr = readElf32();
pHeader.paddr = readElf32();
pHeader.fileSize = readElf32();
pHeader.memSize = readElf32();
pHeader.flags = readElf32();
pHeader.align = readElf32();
// 8 * 4 = 32
if (phentsize > 32) {
System.out.println("Program Header Entry SIZE differs from specs?!?!??!?!?***");
}
return pHeader;
}
public int getSectionCount() {
return shnum;
}
public ELFSection getSection(int index) {
return sections[index];
}
public int readElf32() {
int val = readElf32(getPos());
setPos(getPos() + 4);
return val;
}
public int readElf16() {
int val = readElf16(getPos());
setPos(getPos() + 2);
return val;
}
public int readElf8() {
int val = readElf16(getPos());
setPos(getPos() + 1);
return val;
}
int readElf32(int pos) {
int b = 0;
if (encMSB) {
b = (elfData[pos++] & 0xff) << 24 |
((elfData[pos++] & 0xff) << 16) |
((elfData[pos++] & 0xff) << 8) |
(elfData[pos++] & 0xff);
} else {
b = (elfData[pos++] & 0xff) |
((elfData[pos++] & 0xff) << 8) |
((elfData[pos++] & 0xff) << 16) |
((elfData[pos++] & 0xff) << 24);
}
return b;
}
int readElf16(int pos) {
int b = 0;
if (encMSB) {
b = ((elfData[pos++] & 0xff) << 8) |
(elfData[pos++] & 0xff);
} else {
b = (elfData[pos++] & 0xff) |
((elfData[pos++] & 0xff) << 8);
}
return b;
}
int readElf8(int pos) {
return elfData[pos++] & 0xff;
}
public static void printBytes(String name, byte[] data) {
System.out.print(name + " ");
for (byte element : data) {
System.out.print("" + (char) element);
}
System.out.println("");
}
private void readSections() {
setPos(shoff);
sections = new ELFSection[shnum];
for (int i = 0, n = shnum; i < n; i++) {
sections[i] = readSectionHeader();
if (sections[i].type == ELFSection.TYPE_SYMTAB) {
symTable = sections[i];
}
if (i == shstrndx) {
strTable = sections[i];
}
}
boolean readDwarf = false;
/* Find sections */
for (int i = 0, n = shnum; i < n; i++) {
String name = sections[i].getSectionName();
if (DEBUG) {
System.out.println("ELF-Section: " + name);
}
if (".stabstr".equals(name)) {
dbgStabStr = sections[i];
}
if (".stab".equals(name)) {
dbgStab = sections[i];
}
if (".debug_aranges".equals(name) ||
".debug_line".equals(name)) {
readDwarf = true;
}
}
if (readDwarf) {
DwarfReader dwarf = new DwarfReader(this);
dwarf.read();
debug = dwarf;
}
}
private void readPrograms() {
setPos(phoff);
programs = new ELFProgram[phnum];
for (int i = 0, n = phnum; i < n; i++) {
programs[i] = readProgramHeader();
if (DEBUG) {
System.out.println("-- Program header --\n" + programs[i].toString());
}
}
}
public void readAll() throws ELFException {
readHeader();
readPrograms();
readSections();
if (dbgStab != null) {
debug = new StabDebug(this, dbgStab, dbgStabStr);
}
}
public void loadPrograms(int[] memory) {
for (int i = 0, n = phnum; i < n; i++) {
// paddr or vaddr???
loadBytes(memory, programs[i].offset, programs[i].paddr,
programs[i].fileSize, programs[i].memSize);
}
}
private void loadBytes(int[] memory, int offset, int addr, int len,
int fill) {
if (DEBUG) {
System.out.println("Loading " + len + " bytes into " +
Integer.toString(addr, 16) + " fill " + fill);
}
for (int i = 0, n = len; i < n; i++) {
memory[addr++] = elfData[offset++] & 0xff;
}
if (fill > len) {
int n = fill - len;
if (n + addr > memory.length) {
n = memory.length - addr;
}
for (int i = 0; i < n; i++) {
memory[addr++] = 0;
}
}
}
public ELFDebug getDebug() {
return debug;
}
public DebugInfo getDebugInfo(int adr) {
if (debug != null) {
return debug.getDebugInfo(adr);
}
return null;
}
public String lookupFile(int address) {
if (debug != null) {
DebugInfo di = debug.getDebugInfo(address);
if (di != null) {
return di.getFile();
}
}
for (int i = 0; i < files.size(); i++) {
FileInfo fi = files.get(i);
if (address >= fi.start && address <= fi.end) {
return fi.name;
}
}
return null;
}
public MapTable getMap() {
MapTable map = new MapTable();
int sAddrHighest = -1;
boolean foundEnd = false;
ELFSection name = sections[symTable.link];
int len = symTable.size;
int count = len / symTable.getEntrySize();
int addr = symTable.getOffset();
String currentFile = null;
if (DEBUG) {
System.out.println("Number of symbols:" + count);
}
int currentAddress = 0;
for (int i = 0, n = count; i < n; i++) {
setPos(addr);
int nI = readElf32();
String sn = name.getName(nI);
int sAddr = readElf32();
int size = readElf32();
int info = readElf8();
int bind = info >> 4;
int type = info & 0xf;
if (type == ELFSection.SYMTYPE_NONE && sn != null){
if ("Letext".equals(sn)) {
if (currentFile != null) {
files.add(new FileInfo(currentFile, currentAddress, sAddr));
currentAddress = sAddr;
}
} else if (!sn.startsWith("_")) {
map.setEntry(new MapEntry(MapEntry.TYPE.variable, sAddr, 0, sn, currentFile,
false));
}
}
if (type == ELFSection.SYMTYPE_FILE) {
currentFile = sn;
}
if (DEBUG) {
System.out.println("Found symbol: " + sn + " at " +
Integer.toString(sAddr, 16) + " bind: " + bind +
" type: " + type + " size: " + size);
}
if (sAddr > 0 && sAddr < 0x100000) {
String symbolName = sn;
if (sAddr < 0x5c00 && sAddr > sAddrHighest && !sn.equals("__stack")) {
sAddrHighest = sAddr;
}
// if (bind == ELFSection.SYMBIND_LOCAL) {
// symbolName += " (" + currentFile + ')';
// }
if ("_end".equals(symbolName)) {
foundEnd = true;
map.setHeapStart(sAddr);
} else if ("__stack".equals(symbolName)){
map.setStackStart(sAddr);
}
if (type == ELFSection.SYMTYPE_FUNCTION) {
String file = lookupFile(sAddr);
if (file == null) {
file = currentFile;
}
map.setEntry(new MapEntry(MapEntry.TYPE.function, sAddr, 0, symbolName, file,
bind == ELFSection.SYMBIND_LOCAL));
} else if (type == ELFSection.SYMTYPE_OBJECT) {
String file = lookupFile(sAddr);
if (file == null) {
file = currentFile;
}
map.setEntry(new MapEntry(MapEntry.TYPE.variable, sAddr, size, symbolName, file,
bind == ELFSection.SYMBIND_LOCAL));
} else {
if (DEBUG) {
System.out.println("Skipping entry: '" + symbolName + "' @ 0x" + Integer.toString(sAddr, 16) + " (" + currentFile + ")");
}
}
}
addr += symTable.getEntrySize();
}
if (!foundEnd && sAddrHighest > 0) {
System.out.printf("Warning: Unable to parse _end symbol. I'm guessing that heap starts at 0x%05x\n", sAddrHighest);
map.setHeapStart(sAddrHighest);
}
return map;
}
public static ELF readELF(String file) throws IOException {
DataInputStream input = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream baous = new ByteArrayOutputStream();
byte[] buf = new byte[2048];
for(int read; (read = input.read(buf)) != -1; baous.write(buf, 0, read)) {
;
}
input.close();
buf = null;
byte[] data = baous.toByteArray();
if (DEBUG) {
System.out.println("Length of data: " + data.length);
}
ELF elf = new ELF(data);
elf.readAll();
return elf;
}
public static void main(String[] args) throws Exception {
ELF elf = readELF(args[0]);
if (args.length < 2) {
for (int i = 0, n = elf.shnum; i < n; i++) {
if (DEBUG) {
System.out.println("-- Section header " + i + " --\n" + elf.sections[i]);
}
if (".stab".equals(elf.sections[i].getSectionName()) ||
".stabstr".equals(elf.sections[i].getSectionName())) {
int adr = elf.sections[i].getOffset();
if (DEBUG) {
System.out.println(" == Section data ==");
}
for (int j = 0, m = 2000; j < m; j++) {
if (DEBUG) {
System.out.print((char) elf.elfData[adr++]);
if (i % 20 == 19) {
System.out.println();
}
}
}
}
System.out.println();
}
}
elf.getMap();
if (args.length > 1) {
DebugInfo dbg = elf.getDebugInfo(Integer.parseInt(args[1]));
if (dbg != null) {
System.out.println("File: " + dbg.getFile());
System.out.println("Function: " + dbg.getFunction());
System.out.println("LineNo: " + dbg.getLine());
}
}
}
public void setPos(int pos) {
this.pos = pos;
}
public int getPos() {
return pos;
}
private static class FileInfo {
public final String name;
public final int start;
public final int end;
FileInfo(String name, int start, int end) {
this.name = name;
this.start = start;
this.end = end;
}
}
} // ELF
|
se/sics/mspsim/util/ELF.java
|
/**
* Copyright (c) 2007, Swedish Institute of Computer Science.
* 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. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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.
*
* This file is part of MSPSim.
*
* -----------------------------------------------------------------
*
* ELF
*
* Author : Joakim Eriksson
* Created : Sun Oct 21 22:00:00 2007
*/
package se.sics.mspsim.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import se.sics.mspsim.debug.DwarfReader;
import se.sics.mspsim.debug.StabDebug;
public class ELF {
// private static final int EI_NIDENT = 16;
private static final int EI_ENCODING = 5;
private static final int[] MAGIC = new int[] {0x7f, 'E', 'L', 'F'};
public static final boolean DEBUG = false;
boolean encMSB = true;
int type;
int machine;
int version;
int entry;
int phoff;
int shoff;
int flags;
int ehsize;
int phentsize;
int phnum;
int shentsize;
int shnum;
int shstrndx;
byte[] elfData;
private int pos = 0;
private ELFSection sections[];
private ELFProgram programs[];
private ArrayList<FileInfo> files = new ArrayList<FileInfo>();
ELFSection strTable;
ELFSection symTable;
ELFSection dbgStab;
public ELFSection dbgStabStr;
ELFDebug debug;
public ELF(byte[] data) {
elfData = data;
setPos(0);
}
/* check if the file exists and is an ELF file */
public static boolean isELF(File file) {
try {
InputStream input = new BufferedInputStream(new FileInputStream(file));
for (int i = 0; i < MAGIC.length; i++) {
if (MAGIC[i] != input.read()) {
input.close();
return false;
}
}
input.close();
return true;
} catch(IOException ioe) {
// ignore and return false - this is not an elf.
return false;
}
}
private void readHeader() throws ELFException {
for (int i = 0; i < MAGIC.length; i++) {
if (elfData[i] != (byte) (MAGIC[i] & 0xff)) {
throw new ELFException("Not an elf file");
}
}
if (elfData[EI_ENCODING] == 2) {
encMSB = true;
} else if (elfData[EI_ENCODING] == 1) {
encMSB = false;
} else {
throw new ELFException("Illegal encoding: " + elfData[EI_ENCODING]);
}
setPos(getPos() + 16);
type = readElf16();
machine = readElf16();
version = readElf32();
entry = readElf32();
phoff = readElf32();
shoff = readElf32();
flags = readElf32();
ehsize = readElf16();
phentsize = readElf16();
phnum = readElf16();
shentsize = readElf16();
shnum = readElf16();
shstrndx = readElf16();
if (DEBUG) {
System.out.println("-- ELF Header --");
System.out.println("type: " + Integer.toString(type, 16));
System.out.println("machine: " + Integer.toString(machine, 16));
System.out.println("version: " + Integer.toString(version, 16));
System.out.println("entry: " + Integer.toString(entry, 16));
System.out.println("phoff: " + Integer.toString(phoff, 16));
System.out.println("shoff: " + Integer.toString(shoff, 16));
System.out.println("flags: " + Integer.toString(flags, 16));
System.out.println("ehsize: " + Integer.toString(ehsize, 16));
System.out.println("phentsize: " + Integer.toString(phentsize, 16));
System.out.println("phentnum: " + Integer.toString(phnum, 16));
System.out.println("shentsize: " + Integer.toString(shentsize, 16));
System.out.println("shentnum: " + Integer.toString(shnum, 16));
System.out.println("shstrndx: " + Integer.toString(shstrndx, 16));
}
}
private ELFSection readSectionHeader() {
ELFSection sec = new ELFSection();
sec.name = readElf32();
sec.type = readElf32();
sec.flags = readElf32();
sec.addr = readElf32();
sec.setOffset(readElf32());
sec.size = readElf32();
sec.link = readElf32();
sec.info = readElf32();
sec.addralign = readElf32();
sec.setEntrySize(readElf32());
sec.elf = this;
return sec;
}
private ELFProgram readProgramHeader() {
ELFProgram pHeader = new ELFProgram();
pHeader.type = readElf32();
pHeader.offset = readElf32();
pHeader.vaddr = readElf32();
pHeader.paddr = readElf32();
pHeader.fileSize = readElf32();
pHeader.memSize = readElf32();
pHeader.flags = readElf32();
pHeader.align = readElf32();
// 8 * 4 = 32
if (phentsize > 32) {
System.out.println("Program Header Entry SIZE differs from specs?!?!??!?!?***");
}
return pHeader;
}
public int getSectionCount() {
return shnum;
}
public ELFSection getSection(int index) {
return sections[index];
}
public int readElf32() {
int val = readElf32(getPos());
setPos(getPos() + 4);
return val;
}
public int readElf16() {
int val = readElf16(getPos());
setPos(getPos() + 2);
return val;
}
public int readElf8() {
int val = readElf16(getPos());
setPos(getPos() + 1);
return val;
}
int readElf32(int pos) {
int b = 0;
if (encMSB) {
b = (elfData[pos++] & 0xff) << 24 |
((elfData[pos++] & 0xff) << 16) |
((elfData[pos++] & 0xff) << 8) |
(elfData[pos++] & 0xff);
} else {
b = (elfData[pos++] & 0xff) |
((elfData[pos++] & 0xff) << 8) |
((elfData[pos++] & 0xff) << 16) |
((elfData[pos++] & 0xff) << 24);
}
return b;
}
int readElf16(int pos) {
int b = 0;
if (encMSB) {
b = ((elfData[pos++] & 0xff) << 8) |
(elfData[pos++] & 0xff);
} else {
b = (elfData[pos++] & 0xff) |
((elfData[pos++] & 0xff) << 8);
}
return b;
}
int readElf8(int pos) {
return elfData[pos++] & 0xff;
}
public static void printBytes(String name, byte[] data) {
System.out.print(name + " ");
for (byte element : data) {
System.out.print("" + (char) element);
}
System.out.println("");
}
private void readSections() {
setPos(shoff);
sections = new ELFSection[shnum];
for (int i = 0, n = shnum; i < n; i++) {
sections[i] = readSectionHeader();
if (sections[i].type == ELFSection.TYPE_SYMTAB) {
symTable = sections[i];
}
if (i == shstrndx) {
strTable = sections[i];
}
}
boolean readDwarf = false;
/* Find sections */
for (int i = 0, n = shnum; i < n; i++) {
String name = sections[i].getSectionName();
if (DEBUG) {
System.out.println("ELF-Section: " + name);
}
if (".stabstr".equals(name)) {
dbgStabStr = sections[i];
}
if (".stab".equals(name)) {
dbgStab = sections[i];
}
if (".debug_aranges".equals(name) ||
".debug_line".equals(name)) {
readDwarf = true;
}
}
if (readDwarf) {
DwarfReader dwarf = new DwarfReader(this);
dwarf.read();
debug = dwarf;
}
}
private void readPrograms() {
setPos(phoff);
programs = new ELFProgram[phnum];
for (int i = 0, n = phnum; i < n; i++) {
programs[i] = readProgramHeader();
if (DEBUG) {
System.out.println("-- Program header --\n" + programs[i].toString());
}
}
}
public void readAll() throws ELFException {
readHeader();
readPrograms();
readSections();
if (dbgStab != null) {
debug = new StabDebug(this, dbgStab, dbgStabStr);
}
}
public void loadPrograms(int[] memory) {
for (int i = 0, n = phnum; i < n; i++) {
// paddr or vaddr???
loadBytes(memory, programs[i].offset, programs[i].paddr,
programs[i].fileSize, programs[i].memSize);
}
}
private void loadBytes(int[] memory, int offset, int addr, int len,
int fill) {
if (DEBUG) {
System.out.println("Loading " + len + " bytes into " +
Integer.toString(addr, 16) + " fill " + fill);
}
for (int i = 0, n = len; i < n; i++) {
memory[addr++] = elfData[offset++] & 0xff;
}
if (fill > len) {
int n = fill - len;
if (n + addr > memory.length) {
n = memory.length - addr;
}
for (int i = 0; i < n; i++) {
memory[addr++] = 0;
}
}
}
public ELFDebug getDebug() {
return debug;
}
public DebugInfo getDebugInfo(int adr) {
if (debug != null) {
return debug.getDebugInfo(adr);
}
return null;
}
public String lookupFile(int address) {
if (debug != null) {
DebugInfo di = debug.getDebugInfo(address);
if (di != null) {
return di.getFile();
}
}
for (int i = 0; i < files.size(); i++) {
FileInfo fi = files.get(i);
if (address >= fi.start && address <= fi.end) {
return fi.name;
}
}
return null;
}
public MapTable getMap() {
MapTable map = new MapTable();
int sAddrHighest = -1;
ELFSection name = sections[symTable.link];
int len = symTable.size;
int count = len / symTable.getEntrySize();
int addr = symTable.getOffset();
String currentFile = null;
if (DEBUG) {
System.out.println("Number of symbols:" + count);
}
int currentAddress = 0;
for (int i = 0, n = count; i < n; i++) {
setPos(addr);
int nI = readElf32();
String sn = name.getName(nI);
int sAddr = readElf32();
int size = readElf32();
int info = readElf8();
int bind = info >> 4;
int type = info & 0xf;
if (type == ELFSection.SYMTYPE_NONE && sn != null){
if ("Letext".equals(sn)) {
if (currentFile != null) {
files.add(new FileInfo(currentFile, currentAddress, sAddr));
currentAddress = sAddr;
}
} else if (!sn.startsWith("_")) {
map.setEntry(new MapEntry(MapEntry.TYPE.variable, sAddr, 0, sn, currentFile,
false));
}
}
if (type == ELFSection.SYMTYPE_FILE) {
currentFile = sn;
}
if (DEBUG) {
System.out.println("Found symbol: " + sn + " at " +
Integer.toString(sAddr, 16) + " bind: " + bind +
" type: " + type + " size: " + size);
}
if (sAddr > 0 && sAddr < 0x100000) {
String symbolName = sn;
if (sAddr < 0x5c00 && sAddr > sAddrHighest) {
sAddrHighest = sAddr;
}
// if (bind == ELFSection.SYMBIND_LOCAL) {
// symbolName += " (" + currentFile + ')';
// }
if ("_end".equals(symbolName)) {
map.setHeapStart(sAddr);
} else if ("__stack".equals(symbolName)){
map.setStackStart(sAddr);
}
if (type == ELFSection.SYMTYPE_FUNCTION) {
String file = lookupFile(sAddr);
if (file == null) {
file = currentFile;
}
map.setEntry(new MapEntry(MapEntry.TYPE.function, sAddr, 0, symbolName, file,
bind == ELFSection.SYMBIND_LOCAL));
} else if (type == ELFSection.SYMTYPE_OBJECT) {
String file = lookupFile(sAddr);
if (file == null) {
file = currentFile;
}
map.setEntry(new MapEntry(MapEntry.TYPE.variable, sAddr, size, symbolName, file,
bind == ELFSection.SYMBIND_LOCAL));
} else {
if (DEBUG) {
System.out.println("Skipping entry: '" + symbolName + "' @ 0x" + Integer.toString(sAddr, 16) + " (" + currentFile + ")");
}
}
}
addr += symTable.getEntrySize();
}
if (map.getHeapStart() <= 0 && sAddrHighest > 0) {
System.err.printf("Warning: Unable to parse _end symbol. I'm guessing that heap starts at 0x%05x\n", sAddrHighest);
map.setHeapStart(sAddrHighest);
}
return map;
}
public static ELF readELF(String file) throws IOException {
DataInputStream input = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream baous = new ByteArrayOutputStream();
byte[] buf = new byte[2048];
for(int read; (read = input.read(buf)) != -1; baous.write(buf, 0, read)) {
;
}
input.close();
buf = null;
byte[] data = baous.toByteArray();
if (DEBUG) {
System.out.println("Length of data: " + data.length);
}
ELF elf = new ELF(data);
elf.readAll();
return elf;
}
public static void main(String[] args) throws Exception {
ELF elf = readELF(args[0]);
if (args.length < 2) {
for (int i = 0, n = elf.shnum; i < n; i++) {
if (DEBUG) {
System.out.println("-- Section header " + i + " --\n" + elf.sections[i]);
}
if (".stab".equals(elf.sections[i].getSectionName()) ||
".stabstr".equals(elf.sections[i].getSectionName())) {
int adr = elf.sections[i].getOffset();
if (DEBUG) {
System.out.println(" == Section data ==");
}
for (int j = 0, m = 2000; j < m; j++) {
if (DEBUG) {
System.out.print((char) elf.elfData[adr++]);
if (i % 20 == 19) {
System.out.println();
}
}
}
}
System.out.println();
}
}
elf.getMap();
if (args.length > 1) {
DebugInfo dbg = elf.getDebugInfo(Integer.parseInt(args[1]));
if (dbg != null) {
System.out.println("File: " + dbg.getFile());
System.out.println("Function: " + dbg.getFunction());
System.out.println("LineNo: " + dbg.getLine());
}
}
}
public void setPos(int pos) {
this.pos = pos;
}
public int getPos() {
return pos;
}
private static class FileInfo {
public final String name;
public final int start;
public final int end;
FileInfo(String name, int start, int end) {
this.name = name;
this.start = start;
this.end = end;
}
}
} // ELF
|
Improved handling of the stack idenfitication at end of memory that works better for mspgcc 4.7.x
|
se/sics/mspsim/util/ELF.java
|
Improved handling of the stack idenfitication at end of memory that works better for mspgcc 4.7.x
|
|
Java
|
mit
|
830b11a6327b2d4aff379eb0da5adcf96671ede2
| 0
|
mrunde/Bachelor-Thesis,mrunde/Bachelor-Thesis
|
package de.mrunde.bachelorthesis.basics;
/**
* This is the Maneuver class that converts the maneuver types of MapQuest into
* the verbal instructions.<br/>
* <br/>
* You can find the maneuver types at the MapQuest API here:<br/>
* <a href="https://open.mapquestapi.com/guidance/#maneuvertypes">https://open
* .mapquestapi.com/guidance/#maneuvertypes</a>
*
* @author Marius Runde
*/
public abstract class Maneuver {
// --- The maneuver types of MapQuest ---
// --- The maneuver types are primarily listed here to enable the user to
// include the maneuver type values manually in the application. ---
public static final int NONE = 0;
public static final int STRAIGHT = 1;
public static final int BECOMES = 2;
public static final int SLIGHT_LEFT = 3;
public static final int LEFT = 4;
public static final int SHARP_LEFT = 5;
public static final int SLIGHT_RIGHT = 6;
public static final int RIGHT = 7;
public static final int SHARP_RIGHT = 8;
public static final int STAY_LEFT = 9;
public static final int STAY_RIGHT = 10;
public static final int STAY_STRAIGHT = 11;
public static final int UTURN = 12;
public static final int UTURN_LEFT = 13;
public static final int UTURN_RIGHT = 14;
public static final int EXIT_LEFT = 15;
public static final int EXIT_RIGHT = 16;
public static final int RAMP_LEFT = 17;
public static final int RAMP_RIGHT = 18;
public static final int RAMP_STRAIGHT = 19;
public static final int MERGE_LEFT = 20;
public static final int MERGE_RIGHT = 21;
public static final int MERGE_STRAIGHT = 22;
public static final int ENTERING = 23;
public static final int DESTINATION = 24;
public static final int DESTINATION_LEFT = 25;
public static final int DESTINATION_RIGHT = 26;
public static final int ROUNDABOUT1 = 27;
public static final int ROUNDABOUT2 = 28;
public static final int ROUNDABOUT3 = 29;
public static final int ROUNDABOUT4 = 30;
public static final int ROUNDABOUT5 = 31;
public static final int ROUNDABOUT6 = 32;
public static final int ROUNDABOUT7 = 33;
public static final int ROUNDABOUT8 = 34;
public static final int TRANSIT_TAKE = 35;
public static final int TRANSIT_TRANSFER = 36;
public static final int TRANSIT_ENTER = 37;
public static final int TRANSIT_EXIT = 38;
public static final int TRANSIT_REMAIN_ON = 39;
// --- End of maneuver types of MapQuest ---
/**
* Store the verbal maneuver instructions in an array. The Strings are taken
* from the MapQuest API [1] and edited to insert them more adequately into
* the instructions.<br/>
* <br/>
* [1] <a
* href="https://open.mapquestapi.com/guidance/#maneuvertypes">https:/
* /open.mapquestapi.com/guidance/#maneuvertypes</a>
*/
private static final String[] maneuverTexts = new String[] { null, /* 0 */
"Continue straight", null, "Make a slight left turn", "Turn left",
"Make a sharp left turn", /* 5 */
"Make a slight right turn", "Turn right",
"Make a sharp right turn", "Stay left", "Stay right", /* 10 */
"Stay straight", "Make a U-turn", "Make a left U-turn",
"Make a right U-turn", "Exit left", /* 15 */
"Exit right", "Take the ramp on the left",
"Take the ramp on the right", "Take the ramp straight ahead",
"Merge left", /* 20 */
"Merge right", "Merge", "Enter state/province",
"Arrive at your destination",
"Arrive at your destination on the left", /* 25 */
"Arrive at your destination on the right",
"Enter the roundabout and take the 1st exit",
"Enter the roundabout and take the 2nd exit",
"Enter the roundabout and take the 3rd exit",
"Enter the roundabout and take the 4th exit", /* 30 */
"Enter the roundabout and take the 5th exit",
"Enter the roundabout and take the 6th exit",
"Enter the roundabout and take the 7th exit",
"Enter the roundabout and take the 8th exit",
"Take a public transit bus or rail line", /* 35 */
"Transfer to a public transit bus or rail line",
"Enter a public transit bus or rail station",
"Exit a public transit bus or rail station",
"Remain on the current bus/rail car" /* 39 */
};
/**
* Get the corresponding verbal maneuver instruction of the maneuver type
*
* @param maneuverType
* The maneuver type received from MapQuest
* @return The verbal maneuver instruction
*/
public static String getManeuverText(int maneuverType) {
return maneuverTexts[maneuverType];
}
/**
* Check if the maneuver requires a turn action
*
* @param maneuverType
* The maneuver type received from MapQuest
* @return TRUE: Turn action is required.<br/>
* FALSE: No turn action is required.
*/
public static boolean isTurnAction(int maneuverType) {
if (maneuverType == 0 || maneuverType == 2) {
return false;
} else {
return true;
}
}
/**
* Check if the maneuver is for a roundabout
*
* @param maneuverType
* The maneuver type received from MapQuest
* @return TRUE: Maneuver is for roundabout.<br/>
* FALSE: Maneuver is not for roundabout.
*/
public static boolean isRoundaboutAction(int maneuverType) {
if (maneuverType >= 27 && maneuverType <= 34) {
return true;
} else {
return false;
}
}
}
|
src/de/mrunde/bachelorthesis/basics/Maneuver.java
|
package de.mrunde.bachelorthesis.basics;
/**
* This is the Maneuver class that converts the maneuver types of MapQuest into
* the verbal instructions.<br/>
* <br/>
* You can find the maneuver types at the MapQuest API here:<br/>
* <a href="https://open.mapquestapi.com/guidance/#maneuvertypes">https://open
* .mapquestapi.com/guidance/#maneuvertypes</a>
*
* @author Marius Runde
*/
public abstract class Maneuver {
// --- The maneuver types of MapQuest ---
// --- The maneuver types are primarily listed here to enable the user to
// include the maneuver type values manually in the application. ---
public static final int NONE = 0;
public static final int STRAIGHT = 1;
public static final int BECOMES = 2;
public static final int SLIGHT_LEFT = 3;
public static final int LEFT = 4;
public static final int SHARP_LEFT = 5;
public static final int SLIGHT_RIGHT = 6;
public static final int RIGHT = 7;
public static final int SHARP_RIGHT = 8;
public static final int STAY_LEFT = 9;
public static final int STAY_RIGHT = 10;
public static final int STAY_STRAIGHT = 11;
public static final int UTURN = 12;
public static final int UTURN_LEFT = 13;
public static final int UTURN_RIGHT = 14;
public static final int EXIT_LEFT = 15;
public static final int EXIT_RIGHT = 16;
public static final int RAMP_LEFT = 17;
public static final int RAMP_RIGHT = 18;
public static final int RAMP_STRAIGHT = 19;
public static final int MERGE_LEFT = 20;
public static final int MERGE_RIGHT = 21;
public static final int MERGE_STRAIGHT = 22;
public static final int ENTERING = 23;
public static final int DESTINATION = 24;
public static final int DESTINATION_LEFT = 25;
public static final int DESTINATION_RIGHT = 26;
public static final int ROUNDABOUT1 = 27;
public static final int ROUNDABOUT2 = 28;
public static final int ROUNDABOUT3 = 29;
public static final int ROUNDABOUT4 = 30;
public static final int ROUNDABOUT5 = 31;
public static final int ROUNDABOUT6 = 32;
public static final int ROUNDABOUT7 = 33;
public static final int ROUNDABOUT8 = 34;
public static final int TRANSIT_TAKE = 35;
public static final int TRANSIT_TRANSFER = 36;
public static final int TRANSIT_ENTER = 37;
public static final int TRANSIT_EXIT = 38;
public static final int TRANSIT_REMAIN_ON = 39;
// --- End of maneuver types of MapQuest ---
/**
* Store the verbal maneuver instructions in an array. The Strings are taken
* from the MapQuest API [1] and edited to insert them more adequately into
* the instructions.<br/>
* <br/>
* [1] <a
* href="https://open.mapquestapi.com/guidance/#maneuvertypes">https:/
* /open.mapquestapi.com/guidance/#maneuvertypes</a>
*/
private static final String[] maneuverTexts = new String[] {
null, /* 0 */
"Continue straight",
null,
"Make a slight left turn",
"Turn left",
"Make a sharp left turn", /* 5 */
"Make a slight right turn",
"Turn right",
"Make a sharp right turn",
"Stay left",
"Stay right", /* 10 */
"Stay straight",
"Make a U-turn",
"Make a left U-turn",
"Make a right U-turn",
"Exit left", /* 15 */
"Exit right",
"Take the ramp on the left",
"Take the ramp on the right",
"Take the ramp straight ahead",
"Merge left", /* 20 */
"Merge right",
"Merge",
"Enter state/province",
"Arrive at your destination",
"Arrive at your destination on the left", /* 25 */
"Arrive at your destination on the right",
"Enter the roundabout and take the 1st exit",
"Enter the roundabout and take the 2nd exit",
"Enter the roundabout and take the 3rd exit",
"Enter the roundabout and take the 4th exit", /* 30 */
"Enter the roundabout and take the 5th exit",
"Enter the roundabout and take the 6th exit",
"Enter the roundabout and take the 7th exit",
"Enter the roundabout and take the 8th exit",
"Take a public transit bus or rail line", /* 35 */
"Transfer to a public transit bus or rail line",
"Enter a public transit bus or rail station",
"Exit a public transit bus or rail station",
"Remain on the current bus/rail car" /* 39 */
};
/**
* Get the corresponding verbal maneuver instruction of the maneuver type
*
* @param maneuverType
* The maneuver type received from MapQuest
* @return The verbal maneuver instruction
*/
public static String getManeuverText(int maneuverType) {
return maneuverTexts[maneuverType];
}
/**
* Check if the maneuver requires a turn action
*
* @param maneuverType
* The maneuver type received from MapQuest
* @return TRUE: Turn action is required.<br/>
* FALSE: No turn action is required.
*/
public static boolean isTurnAction(int maneuverType) {
if (maneuverType == 0 || maneuverType == 2) {
return false;
} else {
return true;
}
}
}
|
Add method to check if maneuver is used for roundabout
|
src/de/mrunde/bachelorthesis/basics/Maneuver.java
|
Add method to check if maneuver is used for roundabout
|
|
Java
|
mit
|
a3a420f1cf8e103dd9ad15258473dbd0838e9f94
| 0
|
techis/converter
|
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class Converter {
/**
* @param args
*/
static int num = 0;
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please Select a Conversion");
System.out.println("0: Select new conversion");
System.out.println("1: Decimal to Binary");
System.out.println("2: Binary to Decimal");
System.out.println("3: Decimal to Hexidecimal");
System.out.println("4: Hexidecimal to Decimal");
System.out.println("5: Hexidecimal to Binary");
System.out.println("6: Binary to Hexidecimal");
System.out.println("7: Text to Binary");
System.out.println("99: Exit");
int program = Integer.parseInt((in.nextLine()));
switch(program){
case 1: decimalToBinary(args[0]); break;
case 2: binaryToDecimal(args[0]); break;
case 3: decimalToHex(args[0]); break;
case 4: hexToDecimal(args[0]); break;
case 5: hexToBinary(args[0]); break;
case 6: binaryToHex(args[0]); break;
case 7: textToBinary(args[0]); break;
case 99: System.exit(0);
}
convert(args[0]);
}
public static void binaryToDecimal(String output){
System.out.println("You have selected Binary to Decimal. Please enter a Binary number to continue: ");
Scanner input2 = new Scanner(System.in);
String binarynum = input2.next();
String safe = binarynum.substring(0,1) + binarynum.substring(1);
int decimal = Integer.parseInt(safe,2);
input2.close();
System.out.println("Your decimal value is: " + decimal);
}
public static void decimalToBinary(String output){
System.out.println("You have selected Decimal to Binary. Please enter a decimal number to continue: ");
int decimal = Integer.parseInt((in.nextLine()));
String binaryString = Integer.toBinaryString(decimal);
System.out.println("Your binary value is: " + binaryString);
}
public static void decimalToHex(String output){
System.out.println("You have selected Decimal to Hex. Please enter a decimal number to continue: ");
Scanner input = new Scanner(System.in);
int decimal = input.nextInt();
String hexstring = Integer.toHexString(decimal);
input.close();
}
public static void hexToDecimal(String output){
System.out.println("You have selected Hex to Decimal. Please enter a hex number to continue: ");
Scanner input = new Scanner(System.in);
String hexnumber = input.next();
String safe = hexnumber.substring(0,1) + hexnumber.substring(1);
int decimal = Integer.parseInt(safe,2);
input.close();
}
public static void hexToBinary(String output){
System.out.println("You have selected Hex to Binary. Please enter a Hex number to continue: ");
Scanner input = new Scanner(System.in);
String hexnumber = input.next();
String safe = hexnumber.substring(0,1) + hexnumber.substring(1);
int decimal = Integer.parseInt(safe,2);
String binaryString = Integer.toBinaryString(decimal);
}
public static void binaryToHex(String output){
System.out.println("You have selected Binary to Hex. Please enter a Binary number to continue: ");
Scanner input2 = new Scanner(System.in);
String binarynum = input2.next();
String safe = binarynum.substring(0,1) + binarynum.substring(1);
int decimal = Integer.parseInt(safe,2);
String hexstring = Integer.toHexString(decimal);
input2.close();
}
public static void textToBinary(String output){
System.out.println("You have selected Text to Binary. Please enter a Text string to continue:");
Scanner input = new Scanner(System.in);
String text = input.nextLine();
byte[] bytes = text.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
}
System.out.println("'" + text + "' to binary: " + binary);
input.close();
}
public static void convert(String output){
System.out.println("Please Select a Conversion");
System.out.println("0: Select new conversion");
System.out.println("1: Decimal to Binary");
System.out.println("2: Binary to Decimal");
System.out.println("3: Decimal to Hexidecimal");
System.out.println("4: Hexidecimal to Decimal");
System.out.println("5: Hexidecimal to Binary");
System.out.println("6: Binary to Hexidecimal");
System.out.println("7: Text to Binary");
System.out.println("99: Exit");
int program = Integer.parseInt((in.nextLine()));
switch(program){
case 1: decimalToBinary(output); break;
case 2: binaryToDecimal(output); break;
case 3: decimalToHex(output); break;
case 4: hexToDecimal(output); break;
case 5: hexToBinary(output); break;
case 6: binaryToHex(output); break;
case 7: textToBinary(output); break;
case 99: System.exit(0);
}
convert(output);
}
}
|
Converter.java
|
//Project: Converter.java
//Author: techis
//Date: May 31, 2013
//Email: techis at gmx.com
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class Converter {
/**
* @param args
*/
static int num = 0;
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Please Select a Conversion");
System.out.println("0: Select new conversion");
System.out.println("1: Decimal to Binary");
System.out.println("2: Binary to Decimal");
System.out.println("3: Decimal to Hexidecimal");
System.out.println("4: Hexidecimal to Decimal");
System.out.println("5: Hexidecimal to Binary");
System.out.println("6: Binary to Hexidecimal");
System.out.println("7: Text to Binary");
System.out.println("99: Exit");
int program = Integer.parseInt((in.nextLine()));
switch(program){
case 1: decimalToBinary(args[0]); break;
case 2: binaryToDecimal(args[0]); break;
case 3: decimalToHex(args[0]); break;
case 4: hexToDecimal(args[0]); break;
case 5: hexToBinary(args[0]); break;
case 6: binaryToHex(args[0]); break;
case 7: textToBinary(args[0]); break;
case 99: System.exit(0);
}
convert(args[0]);
}
public static void binaryToDecimal(String output){
System.out.println("You have selected Binary to Decimal. Please enter a Binary number to continue: ");
Scanner input2 = new Scanner(System.in);
String binarynum = input2.next();
String safe = binarynum.substring(0,1) + binarynum.substring(1);
int decimal = Integer.parseInt(safe,2);
input2.close();
System.out.println("Your decimal value is: " + decimal);
}
public static void decimalToBinary(String output){
System.out.println("You have selected Decimal to Binary. Please enter a decimal number to continue: ");
int decimal = Integer.parseInt((in.nextLine()));
String binaryString = Integer.toBinaryString(decimal);
System.out.println("Your binary value is: " + binaryString);
}
public static void decimalToHex(String output){
System.out.println("You have selected Decimal to Hex. Please enter a decimal number to continue: ");
Scanner input = new Scanner(System.in);
int decimal = input.nextInt();
String hexstring = Integer.toHexString(decimal);
input.close();
}
public static void hexToDecimal(String output){
System.out.println("You have selected Hex to Decimal. Please enter a hex number to continue: ");
Scanner input = new Scanner(System.in);
String hexnumber = input.next();
String safe = hexnumber.substring(0,1) + hexnumber.substring(1);
int decimal = Integer.parseInt(safe,2);
input.close();
}
public static void hexToBinary(String output){
System.out.println("You have selected Hex to Binary. Please enter a Hex number to continue: ");
Scanner input = new Scanner(System.in);
String hexnumber = input.next();
String safe = hexnumber.substring(0,1) + hexnumber.substring(1);
int decimal = Integer.parseInt(safe,2);
String binaryString = Integer.toBinaryString(decimal);
}
public static void binaryToHex(String output){
System.out.println("You have selected Binary to Hex. Please enter a Binary number to continue: ");
Scanner input2 = new Scanner(System.in);
String binarynum = input2.next();
String safe = binarynum.substring(0,1) + binarynum.substring(1);
int decimal = Integer.parseInt(safe,2);
String hexstring = Integer.toHexString(decimal);
input2.close();
}
public static void textToBinary(String output){
System.out.println("You have selected Text to Binary. Please enter a Text string to continue:");
Scanner input = new Scanner(System.in);
String text = input.nextLine();
byte[] bytes = text.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
}
System.out.println("'" + text + "' to binary: " + binary);
input.close();
}
public static void convert(String output){
System.out.println("Please Select a Conversion");
System.out.println("0: Select new conversion");
System.out.println("1: Decimal to Binary");
System.out.println("2: Binary to Decimal");
System.out.println("3: Decimal to Hexidecimal");
System.out.println("4: Hexidecimal to Decimal");
System.out.println("5: Hexidecimal to Binary");
System.out.println("6: Binary to Hexidecimal");
System.out.println("7: Text to Binary");
System.out.println("99: Exit");
int program = Integer.parseInt((in.nextLine()));
switch(program){
case 1: decimalToBinary(output); break;
case 2: binaryToDecimal(output); break;
case 3: decimalToHex(output); break;
case 4: hexToDecimal(output); break;
case 5: hexToBinary(output); break;
case 6: binaryToHex(output); break;
case 7: textToBinary(output); break;
case 99: System.exit(0);
}
convert(output);
}
}
|
Another update
|
Converter.java
|
Another update
|
|
Java
|
mit
|
1b83ab134593807c8bb01f3f99ebd3ae724b8e7b
| 0
|
EvilMcJerkface/jessy,EvilMcJerkface/jessy,EvilMcJerkface/jessy,EvilMcJerkface/jessy,EvilMcJerkface/jessy,EvilMcJerkface/jessy
|
package fr.inria.jessy.store;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.lang.model.type.TypeVariable;
import org.junit.Test;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.EntityJoin;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.ForwardCursor;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.model.SecondaryKey;
import fr.inria.jessy.vector.CompactVector;
import fr.inria.jessy.vector.Vector;
/**
* @author Masoud Saeida Ardekani
*
* This class wraps the DPI of BerkeleyDB into a generic key-value API.
* @param <T>
*/
public class DataStore {
private Environment env;
/**
* Indicates the default store that put and get operations should be
* executed in.
*/
private String defaultStore;
/**
* Stores all EntityStores defined for this DataStore
*/
private Map<String, EntityStore> entityStores;
/**
* Store all primary indexes of all entities manage by this DataStore Each
* entity class can have only one primary key. Thus, the key of the map is
* the name of the entity class.
*/
private Map<String, PrimaryIndex<Long, ? extends JessyEntity>> primaryIndexes;
/**
* Store all secondary indexes of all entities manage by this DataStore.
* Each entity class can have multiple secondary keys. Thus, the key of the
* map is the concatenation of entity class name and secondarykey name.
*/
private Map<String, SecondaryIndex<?, ?, ? extends JessyEntity>> secondaryIndexes;
public DataStore(File envHome, boolean readOnly, String storeName)
throws Exception {
entityStores = new HashMap<String, EntityStore>();
primaryIndexes = new HashMap<String, PrimaryIndex<Long, ? extends JessyEntity>>();
secondaryIndexes = new HashMap<String, SecondaryIndex<?, ?, ? extends JessyEntity>>();
setupEnvironment(envHome, readOnly);
addStore(readOnly, storeName);
defaultStore = storeName;
}
/**
* Configure and Setup a berkeleyDB instance.
*
* @param envHome
* database home directory
* @param readOnly
* whether the database should be opened as readonly or not
*/
private void setupEnvironment(File envHome, boolean readOnly) {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setReadOnly(readOnly);
envConfig.setAllowCreate(!readOnly);
envConfig.setTransactional(false);
// TODO database should be clean manually. EFFECT THE PERFORMANCE
// SUBSTANTIALLY
// envConfig.setLocking(false); //The cleaner becomes disable here!
// Influence the performance tremendously!
envConfig.setSharedCache(true); // Does not effect the prformance much!
// TODO subject to change for optimization
envConfig.setCachePercent(90);
env = new Environment(envHome, envConfig);
}
/**
* Add a new store in BerkeleyDB. One store is automatically created when a
* datastore object is initialised.
*
* @param readonly
* true if the store is only for performing read operations.
* @param storeName
* a unique store name.
*/
public void addStore(boolean readonly, String storeName) throws Exception {
if (!entityStores.containsKey(storeName)) {
StoreConfig storeConfig = new StoreConfig();
storeConfig.setAllowCreate(true);
// Caution: Durability cannot be ensured!
// storeConfig.setDeferredWrite(true);
EntityStore store = new EntityStore(env, storeName, storeConfig);
entityStores.put(storeName, store);
} else {
throw new Exception("Store already exists");
}
}
public synchronized void close() {
if (env != null) {
try {
for(EntityStore e : entityStores.values()){
if(e!=null) e.close();
}
env.cleanLog();
env.close();
} catch (DatabaseException ex) {
ex.printStackTrace();
}
}
}
/**
* Create a primary index for an entity class that extends JessyEntity
*
* @param <E>
* the type that extends JessyEntity
* @param storeName
* the name of the store that the primary index works in. The
* primary index stores entities inside this store.
* @param entityClass
* A class that extends JessyEntity
*/
public <E extends JessyEntity> void addPrimaryIndex(String storeName,
Class<E> entityClass) throws Exception {
try {
PrimaryIndex<Long, E> pindex = entityStores.get(storeName)
.getPrimaryIndex(Long.class, entityClass);
primaryIndexes.put(entityClass.getName(), pindex);
} catch (NullPointerException ex) {
throw new NullPointerException("Store with the name " + storeName
+ " does not exists.");
}
}
public <E extends JessyEntity> void addPrimaryIndex(Class<E> entityClass)
throws Exception {
addPrimaryIndex(defaultStore, entityClass);
}
/**
* Create a secondary index for an entity class that extends JessyEntity
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @SecondaryIndex)
* @param storeName
* the name of the store that the primary index works in. The
* primary index stores entities inside this store.
* @param entityClass
* the class that extends JessyEntity
* @param secondaryKeyClass
* Class of the secondary key field (annotated with
* @SecondaryIndex)
* @param secondaryKeyName
* Name of the secondary key field (annotated with
* @SecondaryIndex)
*/
public <E extends JessyEntity, SK> void addSecondaryIndex(String storeName,
Class<E> entityClass, Class<SK> secondaryKeyClass,
String secondaryKeyName) throws Exception {
try {
PrimaryIndex<Long, ? extends JessyEntity> pindex = primaryIndexes
.get(entityClass.getName());
EntityStore store = entityStores.get(storeName);
SecondaryIndex<SK, Long, ? extends JessyEntity> sindex = store
.getSecondaryIndex(pindex, secondaryKeyClass,
secondaryKeyName);
secondaryIndexes.put(entityClass.getName() + secondaryKeyName,
sindex);
} catch (Exception ex) {
throw new Exception("StoreName or PrimaryIndex does not exists");
}
}
public <E extends JessyEntity, SK> void addSecondaryIndex(
Class<E> entityClass, Class<SK> secondaryKeyClass,
String secondaryKeyName) throws Exception {
addSecondaryIndex(defaultStore, entityClass, secondaryKeyClass,
secondaryKeyName);
}
/**
* Put the entity in the store using the primary key. Always adds a new
* entry
*
* @param <E>
* the type that extends JessyEntity
* @param entity
* entity to put inside the store
*/
public <E extends JessyEntity> void put(E entity)
throws NullPointerException {
try {
@SuppressWarnings("unchecked")
PrimaryIndex<Long, E> pindex = (PrimaryIndex<Long, E>) primaryIndexes
.get(entity.getClass().getName());
pindex.put(entity);
} catch (NullPointerException ex) {
throw new NullPointerException("PrimaryIndex cannot be found");
}
}
/**
* Get an entity object previously put inside data store. This entity object
* should be {@link Vector#isCompatible(CompactVector)} with the readSet
* vector.
* <p>
* Note: This method only returns one entity. Thus, it only works for a
* secondaryKey that is considered unique key in the application. Of course,
* they are not unique key inside BerkeleyDB because of storing different
* versions with different {@link Vector}.
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @SecondaryKey)
* @param <V>
* @param entityClass
* the class that extends JessyEntity
* @param secondaryKeyName
* Name of the secondary key field (annotated with
* @SecondaryKey)
* @param keyValue
* the value of the secondary key.
* @param readSet
* a compact vector that compactly contains versions of all
* previously read entities.
* @return
* @throws NullPointerException
*/
private <E extends JessyEntity, SK> E get(Class<E> entityClass,
String secondaryKeyName, SK keyValue, CompactVector<String> readSet)
throws NullPointerException {
try {
@SuppressWarnings("unchecked")
SecondaryIndex<SK, Long, E> sindex = (SecondaryIndex<SK, Long, E>) secondaryIndexes
.get(entityClass.getName() + secondaryKeyName);
EntityCursor<E> cur = sindex.subIndex(keyValue).entities();
E entity = cur.first();
List<E> entity2=new ArrayList<E>();
if (readSet == null) {
cur.close();
return entity;
}
while (entity != null) {
entity2.add(entity);
if (entity.getLocalVector().isCompatible(readSet)) {
cur.close();
return entity;
} else {
entity = cur.prev();
}
}
// System.out.println("==================**********************");
// for (E tmp:entity2){
// System.out.println("Local Vector_SELF Key" + tmp.getLocalVector().getSelfKey());
// System.out.println("Local Vector_SELF Value" + tmp.getLocalVector().getSelfValue());
// System.out.println("SELF KEY VALUE ON READSET" + readSet.getValue(tmp.getLocalVector().getSelfKey()));
// }
// System.out.println("==================");
cur.close();
return null;
} catch (NullPointerException ex) {
throw new NullPointerException("SecondaryIndex cannot be found");
}
}
/**
* Performs a query on several secondary keys, and returns the result set as
* a collection. All entities inside the collection should be
* {@link Vector#isCompatible(CompactVector)} with the readSet vector.
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @SecondaryKey)
* @param entityClass
* the class that extends JessyEntity
* @param keyNameToValues
* Map the name of the secondary key field (annotated with
* @SecondaryKey) to the desired value for the query.
* @param readSet
* a compact vector that compactly contains versions of all
* previously read entities.
* @return A collection of entities that the values of their keys are equal
* to {@code keyNameToValues}
* @throws NullPointerException
*/
@SuppressWarnings("unchecked")
private <E extends JessyEntity, SK> Collection<E> get(Class<E> entityClass,
List<ReadRequestKey<?>> keys, CompactVector<String> readSet)
throws NullPointerException {
try {
SecondaryIndex sindex;
PrimaryIndex<Long, E> pindex = (PrimaryIndex<Long, E>) primaryIndexes
.get(entityClass.getClass().getName());
EntityJoin<Long, E> entityJoin = new EntityJoin<Long, E>(pindex);
for (ReadRequestKey key : keys) {
sindex = secondaryIndexes.get(entityClass.getName()
+ key.getKeyName());
entityJoin.addCondition(sindex, key.getKeyValue());
}
Map<String, E> results = new HashMap<String, E>();
ForwardCursor<E> cur = entityJoin.entities();
try {
for (E entity : cur) {
// FIXME Should the readSet be updated updated upon each
// read?!
if (entity.getLocalVector().isCompatible(readSet)) {
// Always writes the most recent committed version
results.put(entity.getKey(), entity);
}
}
} finally {
cur.close();
}
return results.values();
} catch (NullPointerException ex) {
throw new NullPointerException("SecondaryIndex cannot be found");
}
}
/**
* Get the value of an entity object previously put.
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @param readRequest
* @return
* @throws NullPointerException
*/
public <E extends JessyEntity, SK> ReadReply<E> get(
ReadRequest<E> readRequest) throws NullPointerException {
if (readRequest.getKeys().size() == 1) {
ReadRequestKey readRequestKey = readRequest.getKeys().get(0);
E entity = get(readRequest.getEntityClass(),
readRequestKey.getKeyName(), readRequestKey.getKeyValue(),
readRequest.getReadSet());
return new ReadReply<E>(entity, readRequest.getReadRequestId());
} else {
Collection<E> result = get(readRequest.getEntityClass(),
readRequest.getKeys(), readRequest.getReadSet());
return new ReadReply<E>(result, readRequest.getReadRequestId());
}
}
/**
* Delete an entity with the provided secondary key from the berkeyley DB.
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @param entityClass
* the class that extends JessyEntity
* @param secondaryKeyName
* Name of the secondary key field (annotated with the value of
* the secondary key.
* @throws NullPointerException
*/
public <E extends JessyEntity, SK> boolean delete(Class<E> entityClass,
String secondaryKeyName, SK keyValue) throws NullPointerException {
try {
@SuppressWarnings("unchecked")
SecondaryIndex<SK, Long, E> sindex = (SecondaryIndex<SK, Long, E>) secondaryIndexes
.get(entityClass.getName() + secondaryKeyName);
return sindex.delete(keyValue);
} catch (NullPointerException ex) {
throw new NullPointerException("SecondaryIndex cannot be found");
}
}
/**
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @SecondaryIndex)
* @param <V>
* @param entityClass
* the class that extends JessyEntity
* @param secondaryKeyName
* @param keyValue
* @return
* @throws NullPointerException
*/
public <E extends JessyEntity, SK, V> int getEntityCounts(
Class<E> entityClass, String secondaryKeyName, SK keyValue)
throws NullPointerException {
try {
@SuppressWarnings("unchecked")
SecondaryIndex<SK, Long, E> sindex = (SecondaryIndex<SK, Long, E>) secondaryIndexes
.get(entityClass.getName() + secondaryKeyName);
EntityCursor<E> cur = sindex.subIndex(keyValue).entities();
if (cur.iterator().hasNext()) {
int result = cur.count();
cur.close();
return result;
} else {
cur.close();
return 0;
}
} catch (NullPointerException ex) {
throw new NullPointerException("SecondaryIndex cannot be found");
}
}
/**
* @return the defaultStore
*/
public String getDefaultStore() {
return defaultStore;
}
/**
* @param defaultStore
* the defaultStore to set
*/
public void setDefaultStore(String defaultStore) {
this.defaultStore = defaultStore;
}
/**
* @return the entityStores
*/
public Map<String, EntityStore> getEntityStores() {
return entityStores;
}
}
|
src/fr/inria/jessy/store/DataStore.java
|
package fr.inria.jessy.store;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.lang.model.type.TypeVariable;
import org.junit.Test;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.EntityJoin;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.ForwardCursor;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.model.SecondaryKey;
import fr.inria.jessy.vector.CompactVector;
import fr.inria.jessy.vector.Vector;
/**
* @author Masoud Saeida Ardekani
*
* This class wraps the DPI of BerkeleyDB into a generic key-value API.
* @param <T>
*/
public class DataStore {
private Environment env;
/**
* Indicates the default store that put and get operations should be
* executed in.
*/
private String defaultStore;
/**
* Stores all EntityStores defined for this DataStore
*/
private Map<String, EntityStore> entityStores;
/**
* Store all primary indexes of all entities manage by this DataStore Each
* entity class can have only one primary key. Thus, the key of the map is
* the name of the entity class.
*/
private Map<String, PrimaryIndex<Long, ? extends JessyEntity>> primaryIndexes;
/**
* Store all secondary indexes of all entities manage by this DataStore.
* Each entity class can have multiple secondary keys. Thus, the key of the
* map is the concatenation of entity class name and secondarykey name.
*/
private Map<String, SecondaryIndex<?, ?, ? extends JessyEntity>> secondaryIndexes;
public DataStore(File envHome, boolean readOnly, String storeName)
throws Exception {
entityStores = new HashMap<String, EntityStore>();
primaryIndexes = new HashMap<String, PrimaryIndex<Long, ? extends JessyEntity>>();
secondaryIndexes = new HashMap<String, SecondaryIndex<?, ?, ? extends JessyEntity>>();
setupEnvironment(envHome, readOnly);
addStore(readOnly, storeName);
defaultStore = storeName;
}
/**
* Configure and Setup a berkeleyDB instance.
*
* @param envHome
* database home directory
* @param readOnly
* whether the database should be opened as readonly or not
*/
private void setupEnvironment(File envHome, boolean readOnly) {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setReadOnly(readOnly);
envConfig.setAllowCreate(!readOnly);
envConfig.setTransactional(false);
// TODO database should be clean manually. EFFECT THE PERFORMANCE
// SUBSTANTIALLY
// envConfig.setLocking(false); //The cleaner becomes disable here!
// Influence the performance tremendously!
envConfig.setSharedCache(true); // Does not effect the prformance much!
// TODO subject to change for optimization
envConfig.setCachePercent(90);
env = new Environment(envHome, envConfig);
}
/**
* Add a new store in BerkeleyDB. One store is automatically created when a
* datastore object is initialised.
*
* @param readonly
* true if the store is only for performing read operations.
* @param storeName
* a unique store name.
*/
public void addStore(boolean readonly, String storeName) throws Exception {
if (!entityStores.containsKey(storeName)) {
StoreConfig storeConfig = new StoreConfig();
storeConfig.setAllowCreate(true);
// Caution: Durability cannot be ensured!
// storeConfig.setDeferredWrite(true);
EntityStore store = new EntityStore(env, storeName, storeConfig);
entityStores.put(storeName, store);
} else {
throw new Exception("Store already exists");
}
}
public synchronized void close() {
if (env != null) {
try {
for(EntityStore e : entityStores.values()){
if(e!=null) e.close();
}
env.cleanLog();
env.close();
} catch (DatabaseException ex) {
ex.printStackTrace();
}
}
}
/**
* Create a primary index for an entity class that extends JessyEntity
*
* @param <E>
* the type that extends JessyEntity
* @param storeName
* the name of the store that the primary index works in. The
* primary index stores entities inside this store.
* @param entityClass
* A class that extends JessyEntity
*/
public <E extends JessyEntity> void addPrimaryIndex(String storeName,
Class<E> entityClass) throws Exception {
try {
PrimaryIndex<Long, E> pindex = entityStores.get(storeName)
.getPrimaryIndex(Long.class, entityClass);
primaryIndexes.put(entityClass.getName(), pindex);
} catch (NullPointerException ex) {
throw new NullPointerException("Store with the name " + storeName
+ " does not exists.");
}
}
public <E extends JessyEntity> void addPrimaryIndex(Class<E> entityClass)
throws Exception {
addPrimaryIndex(defaultStore, entityClass);
}
/**
* Create a secondary index for an entity class that extends JessyEntity
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @SecondaryIndex)
* @param storeName
* the name of the store that the primary index works in. The
* primary index stores entities inside this store.
* @param entityClass
* the class that extends JessyEntity
* @param secondaryKeyClass
* Class of the secondary key field (annotated with
* @SecondaryIndex)
* @param secondaryKeyName
* Name of the secondary key field (annotated with
* @SecondaryIndex)
*/
public <E extends JessyEntity, SK> void addSecondaryIndex(String storeName,
Class<E> entityClass, Class<SK> secondaryKeyClass,
String secondaryKeyName) throws Exception {
try {
PrimaryIndex<Long, ? extends JessyEntity> pindex = primaryIndexes
.get(entityClass.getName());
EntityStore store = entityStores.get(storeName);
SecondaryIndex<SK, Long, ? extends JessyEntity> sindex = store
.getSecondaryIndex(pindex, secondaryKeyClass,
secondaryKeyName);
secondaryIndexes.put(entityClass.getName() + secondaryKeyName,
sindex);
} catch (Exception ex) {
throw new Exception("StoreName or PrimaryIndex does not exists");
}
}
public <E extends JessyEntity, SK> void addSecondaryIndex(
Class<E> entityClass, Class<SK> secondaryKeyClass,
String secondaryKeyName) throws Exception {
addSecondaryIndex(defaultStore, entityClass, secondaryKeyClass,
secondaryKeyName);
}
/**
* Put the entity in the store using the primary key. Always adds a new
* entry
*
* @param <E>
* the type that extends JessyEntity
* @param entity
* entity to put inside the store
*/
public <E extends JessyEntity> void put(E entity)
throws NullPointerException {
try {
@SuppressWarnings("unchecked")
PrimaryIndex<Long, E> pindex = (PrimaryIndex<Long, E>) primaryIndexes
.get(entity.getClass().getName());
pindex.put(entity);
} catch (NullPointerException ex) {
throw new NullPointerException("PrimaryIndex cannot be found");
}
}
/**
* Get an entity object previously put inside data store. This entity object
* should be {@link Vector#isCompatible(CompactVector)} with the readSet
* vector.
* <p>
* Note: This method only returns one entity. Thus, it only works for a
* secondaryKey that is considered unique key in the application. Of course,
* they are not unique key inside BerkeleyDB because of storing different
* versions with different {@link Vector}.
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @SecondaryKey)
* @param <V>
* @param entityClass
* the class that extends JessyEntity
* @param secondaryKeyName
* Name of the secondary key field (annotated with
* @SecondaryKey)
* @param keyValue
* the value of the secondary key.
* @param readSet
* a compact vector that compactly contains versions of all
* previously read entities.
* @return
* @throws NullPointerException
*/
private <E extends JessyEntity, SK> E get(Class<E> entityClass,
String secondaryKeyName, SK keyValue, CompactVector<String> readSet)
throws NullPointerException {
try {
@SuppressWarnings("unchecked")
SecondaryIndex<SK, Long, E> sindex = (SecondaryIndex<SK, Long, E>) secondaryIndexes
.get(entityClass.getName() + secondaryKeyName);
EntityCursor<E> cur = sindex.subIndex(keyValue).entities();
E entity = cur.first();
List<E> entity2=new ArrayList<E>();
if (readSet == null) {
cur.close();
return entity;
}
while (entity != null) {
entity2.add(entity);
if (entity.getLocalVector().isCompatible(readSet)) {
cur.close();
return entity;
} else {
entity = cur.prev();
}
}
System.out.println("==================**********************");
for (E tmp:entity2){
System.out.println("Local Vector_SELF Key" + tmp.getLocalVector().getSelfKey());
System.out.println("Local Vector_SELF Value" + tmp.getLocalVector().getSelfValue());
System.out.println("SELF KEY VALUE ON READSET" + readSet.getValue(tmp.getLocalVector().getSelfKey()));
}
System.out.println("==================");
cur.close();
return null;
} catch (NullPointerException ex) {
throw new NullPointerException("SecondaryIndex cannot be found");
}
}
/**
* Performs a query on several secondary keys, and returns the result set as
* a collection. All entities inside the collection should be
* {@link Vector#isCompatible(CompactVector)} with the readSet vector.
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @SecondaryKey)
* @param entityClass
* the class that extends JessyEntity
* @param keyNameToValues
* Map the name of the secondary key field (annotated with
* @SecondaryKey) to the desired value for the query.
* @param readSet
* a compact vector that compactly contains versions of all
* previously read entities.
* @return A collection of entities that the values of their keys are equal
* to {@code keyNameToValues}
* @throws NullPointerException
*/
@SuppressWarnings("unchecked")
private <E extends JessyEntity, SK> Collection<E> get(Class<E> entityClass,
List<ReadRequestKey<?>> keys, CompactVector<String> readSet)
throws NullPointerException {
try {
SecondaryIndex sindex;
PrimaryIndex<Long, E> pindex = (PrimaryIndex<Long, E>) primaryIndexes
.get(entityClass.getClass().getName());
EntityJoin<Long, E> entityJoin = new EntityJoin<Long, E>(pindex);
for (ReadRequestKey key : keys) {
sindex = secondaryIndexes.get(entityClass.getName()
+ key.getKeyName());
entityJoin.addCondition(sindex, key.getKeyValue());
}
Map<String, E> results = new HashMap<String, E>();
ForwardCursor<E> cur = entityJoin.entities();
try {
for (E entity : cur) {
// FIXME Should the readSet be updated updated upon each
// read?!
if (entity.getLocalVector().isCompatible(readSet)) {
// Always writes the most recent committed version
results.put(entity.getKey(), entity);
}
}
} finally {
cur.close();
}
return results.values();
} catch (NullPointerException ex) {
throw new NullPointerException("SecondaryIndex cannot be found");
}
}
/**
* Get the value of an entity object previously put.
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @param readRequest
* @return
* @throws NullPointerException
*/
public <E extends JessyEntity, SK> ReadReply<E> get(
ReadRequest<E> readRequest) throws NullPointerException {
if (readRequest.getKeys().size() == 1) {
ReadRequestKey readRequestKey = readRequest.getKeys().get(0);
E entity = get(readRequest.getEntityClass(),
readRequestKey.getKeyName(), readRequestKey.getKeyValue(),
readRequest.getReadSet());
return new ReadReply<E>(entity, readRequest.getReadRequestId());
} else {
Collection<E> result = get(readRequest.getEntityClass(),
readRequest.getKeys(), readRequest.getReadSet());
return new ReadReply<E>(result, readRequest.getReadRequestId());
}
}
/**
* Delete an entity with the provided secondary key from the berkeyley DB.
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @param entityClass
* the class that extends JessyEntity
* @param secondaryKeyName
* Name of the secondary key field (annotated with the value of
* the secondary key.
* @throws NullPointerException
*/
public <E extends JessyEntity, SK> boolean delete(Class<E> entityClass,
String secondaryKeyName, SK keyValue) throws NullPointerException {
try {
@SuppressWarnings("unchecked")
SecondaryIndex<SK, Long, E> sindex = (SecondaryIndex<SK, Long, E>) secondaryIndexes
.get(entityClass.getName() + secondaryKeyName);
return sindex.delete(keyValue);
} catch (NullPointerException ex) {
throw new NullPointerException("SecondaryIndex cannot be found");
}
}
/**
*
* @param <E>
* the type that extends JessyEntity
* @param <SK>
* the type of the secondary key field (annotated with
* @SecondaryIndex)
* @param <V>
* @param entityClass
* the class that extends JessyEntity
* @param secondaryKeyName
* @param keyValue
* @return
* @throws NullPointerException
*/
public <E extends JessyEntity, SK, V> int getEntityCounts(
Class<E> entityClass, String secondaryKeyName, SK keyValue)
throws NullPointerException {
try {
@SuppressWarnings("unchecked")
SecondaryIndex<SK, Long, E> sindex = (SecondaryIndex<SK, Long, E>) secondaryIndexes
.get(entityClass.getName() + secondaryKeyName);
EntityCursor<E> cur = sindex.subIndex(keyValue).entities();
if (cur.iterator().hasNext()) {
int result = cur.count();
cur.close();
return result;
} else {
cur.close();
return 0;
}
} catch (NullPointerException ex) {
throw new NullPointerException("SecondaryIndex cannot be found");
}
}
/**
* @return the defaultStore
*/
public String getDefaultStore() {
return defaultStore;
}
/**
* @param defaultStore
* the defaultStore to set
*/
public void setDefaultStore(String defaultStore) {
this.defaultStore = defaultStore;
}
/**
* @return the entityStores
*/
public Map<String, EntityStore> getEntityStores() {
return entityStores;
}
}
|
git-svn-id: svn+ssh://scm.gforge.inria.fr/svn/regal/trunk/src/jessy@1008 334080fa-30e0-4884-a663-39494f8d70c4
|
src/fr/inria/jessy/store/DataStore.java
| ||
Java
|
mit
|
5ecb4994f2db37715eb6261cd908a927e3d07327
| 0
|
bekkopen/NoCommons
|
package no.bekk.bekkopen.mail;
import no.bekk.bekkopen.mail.annotation.Postnummer;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PostnummerValidator implements ConstraintValidator<Postnummer, String> {
public void initialize(no.bekk.bekkopen.mail.annotation.Postnummer constraintAnnotation) {}
public boolean isValid(String postnummer, ConstraintValidatorContext context) {
if(postnummer == null){
return true;
}
return MailValidator.isValidPostnummer(postnummer);
}
}
|
src/main/java/no/bekk/bekkopen/mail/Postnummervalidator.java
|
package no.bekk.bekkopen.mail;
/**
* Created with IntelliJ IDEA.
* User: oyvind kvangardsnes
* Date: 07.03.13
* Time: 21.51
* To change this template use File | Settings | File Templates.
*/
public class Postnummervalidator {
}
|
La til validator for postnummer
|
src/main/java/no/bekk/bekkopen/mail/Postnummervalidator.java
|
La til validator for postnummer
|
|
Java
|
mit
|
b7f306b589d68718757028e0efc38aabac793ff6
| 0
|
johanaschan/queue-ticket-api,johanaschan/queue-ticket-api
|
package se.jaitco.queueticketapi.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import se.jaitco.queueticketapi.filter.JwtFilter;
@Configuration
public class WebConfig {
@Bean
public FilterRegistrationBean jwtFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new JwtFilter());
registrationBean.addUrlPatterns("/tickets/remove/*");
return registrationBean;
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*");
}
};
}
}
|
src/main/java/se/jaitco/queueticketapi/config/WebConfig.java
|
package se.jaitco.queueticketapi.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import se.jaitco.queueticketapi.filter.JwtFilter;
@Configuration
public class WebConfig {
@Bean
public FilterRegistrationBean jwtFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new JwtFilter());
registrationBean.addUrlPatterns("/tickets/*");
return registrationBean;
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*");
}
};
}
}
|
changed authentication uri temporary
|
src/main/java/se/jaitco/queueticketapi/config/WebConfig.java
|
changed authentication uri temporary
|
|
Java
|
mit
|
66a4487ae49ae510cb1b75f498b8983f2afc0ef5
| 0
|
auth0/Auth0.Android,auth0/Auth0.Android
|
/*
* SimpleRequest.java
*
* Copyright (c) 2015 Auth0 (http://auth0.com)
*
* 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.auth0.android.request.internal;
import android.support.annotation.NonNull;
import com.auth0.android.Auth0Exception;
import com.auth0.android.NetworkErrorException;
import com.auth0.android.RequestBodyBuildException;
import com.auth0.android.request.ErrorBuilder;
import com.auth0.android.request.ParameterizableRequest;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import java.io.Reader;
import static com.auth0.android.request.internal.ResponseUtils.closeStream;
class SimpleRequest<T, U extends Auth0Exception> extends BaseRequest<T, U> implements ParameterizableRequest<T, U>, Callback {
private final String method;
public SimpleRequest(HttpUrl url, OkHttpClient client, Gson gson, String httpMethod, TypeToken<T> typeToken, ErrorBuilder<U> errorBuilder) {
super(url, client, gson, gson.getAdapter(typeToken), errorBuilder);
this.method = httpMethod;
}
public SimpleRequest(HttpUrl url, OkHttpClient client, Gson gson, String httpMethod, Class<T> clazz, ErrorBuilder<U> errorBuilder) {
super(url, client, gson, gson.getAdapter(clazz), errorBuilder);
this.method = httpMethod;
}
public SimpleRequest(HttpUrl url, OkHttpClient client, Gson gson, String httpMethod, ErrorBuilder<U> errorBuilder) {
super(url, client, gson, gson.getAdapter(new TypeToken<T>() {
}), errorBuilder);
this.method = httpMethod;
}
@Override
public void onResponse(Response response) {
if (!response.isSuccessful()) {
postOnFailure(parseUnsuccessfulResponse(response));
return;
}
ResponseBody body = response.body();
try {
Reader charStream = body.charStream();
T payload = getAdapter().fromJson(charStream);
postOnSuccess(payload);
} catch (IOException | JsonParseException e) {
final Auth0Exception auth0Exception = new Auth0Exception("Failed to parse response to request to " + url, e);
postOnFailure(getErrorBuilder().from("Failed to parse a successful response", auth0Exception));
} finally {
closeStream(body);
}
}
@Override
protected Request doBuildRequest() throws RequestBodyBuildException {
boolean skipBody = method.equals("HEAD") || method.equals("GET");
return newBuilder()
.method(method, skipBody ? null : buildBody())
.build();
}
@NonNull
@Override
public T execute() throws Auth0Exception {
Request request = doBuildRequest();
Response response;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
throw getErrorBuilder().from("Request failed", new NetworkErrorException(e));
}
if (!response.isSuccessful()) {
throw parseUnsuccessfulResponse(response);
}
ResponseBody body = response.body();
try {
Reader charStream = body.charStream();
return getAdapter().fromJson(charStream);
} catch (IOException | JsonParseException e) {
throw new Auth0Exception("Failed to parse response to request to " + url, e);
} finally {
closeStream(body);
}
}
}
|
auth0/src/main/java/com/auth0/android/request/internal/SimpleRequest.java
|
/*
* SimpleRequest.java
*
* Copyright (c) 2015 Auth0 (http://auth0.com)
*
* 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.auth0.android.request.internal;
import android.support.annotation.NonNull;
import com.auth0.android.Auth0Exception;
import com.auth0.android.NetworkErrorException;
import com.auth0.android.RequestBodyBuildException;
import com.auth0.android.request.ErrorBuilder;
import com.auth0.android.request.ParameterizableRequest;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import java.io.Reader;
import static com.auth0.android.request.internal.ResponseUtils.closeStream;
class SimpleRequest<T, U extends Auth0Exception> extends BaseRequest<T, U> implements ParameterizableRequest<T, U>, Callback {
private final String method;
public SimpleRequest(HttpUrl url, OkHttpClient client, Gson gson, String httpMethod, TypeToken<T> typeToken, ErrorBuilder<U> errorBuilder) {
super(url, client, gson, gson.getAdapter(typeToken), errorBuilder);
this.method = httpMethod;
}
public SimpleRequest(HttpUrl url, OkHttpClient client, Gson gson, String httpMethod, Class<T> clazz, ErrorBuilder<U> errorBuilder) {
super(url, client, gson, gson.getAdapter(clazz), errorBuilder);
this.method = httpMethod;
}
public SimpleRequest(HttpUrl url, OkHttpClient client, Gson gson, String httpMethod, ErrorBuilder<U> errorBuilder) {
super(url, client, gson, gson.getAdapter(new TypeToken<T>() {
}), errorBuilder);
this.method = httpMethod;
}
@Override
public void onResponse(Response response) {
if (!response.isSuccessful()) {
postOnFailure(parseUnsuccessfulResponse(response));
return;
}
ResponseBody body = response.body();
try {
Reader charStream = body.charStream();
T payload = getAdapter().fromJson(charStream);
postOnSuccess(payload);
} catch (IOException | JsonParseException e) {
final Auth0Exception auth0Exception = new Auth0Exception("Failed to parse response to request to " + url, e);
postOnFailure(getErrorBuilder().from("Failed to parse a successful response", auth0Exception));
} finally {
closeStream(body);
}
}
@Override
protected Request doBuildRequest() throws RequestBodyBuildException {
boolean sendBody = method.equals("HEAD") || method.equals("GET");
return newBuilder()
.method(method, sendBody ? null : buildBody())
.build();
}
@NonNull
@Override
public T execute() throws Auth0Exception {
Request request = doBuildRequest();
Response response;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
throw getErrorBuilder().from("Request failed", new NetworkErrorException(e));
}
if (!response.isSuccessful()) {
throw parseUnsuccessfulResponse(response);
}
ResponseBody body = response.body();
try {
Reader charStream = body.charStream();
return getAdapter().fromJson(charStream);
} catch (IOException e) {
throw new Auth0Exception("Failed to parse response to request to " + url, e);
} finally {
closeStream(body);
}
}
}
|
catch JsonParseException when parsing sync requests
|
auth0/src/main/java/com/auth0/android/request/internal/SimpleRequest.java
|
catch JsonParseException when parsing sync requests
|
|
Java
|
epl-1.0
|
986d03e663f390ca302f04f495c19effbcc167d0
| 0
|
sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1
|
/*************************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - Initial implementation.
************************************************************************************/
package org.eclipse.birt.report.designer.internal.ui.dialogs;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.ACC;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleControlAdapter;
import org.eclipse.swt.accessibility.AccessibleControlEvent;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.accessibility.AccessibleTextAdapter;
import org.eclipse.swt.accessibility.AccessibleTextEvent;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* Dialog to choose the table/grid row/column number when create a table/grid.
*
*/
public class TableOptionDialog extends BaseDialog
{
private static final String MSG_DATA_SET = Messages.getString( "TableOptionDialog.text.DataSet" );
private static final String MSG_REMEMBER_DIMENSIONS_FOR_NEW_GRIDS = Messages.getString( "TableOptionDialog.message.RememberGrid" ); //$NON-NLS-1$
private static final String MSG_REMEMBER_DIMENSIONS_FOR_NEW_TABLES = Messages.getString( "TableOptionDialog.message.RememberTable" ); //$NON-NLS-1$
private static final String MSG_NUMBER_OF_GRID_ROWS = Messages.getString( "TableOptionDialog.text.GridRow" ); //$NON-NLS-1$
private static final String MSG_NUMBER_OF_TABLE_ROWS = Messages.getString( "TableOptionDialog.text.TableDetail" ); //$NON-NLS-1$
private static final String MSG_NUMBER_OF_COLUMNS = Messages.getString( "TableOptionDialog.text.Column" ); //$NON-NLS-1$
private static final String MSG_GRID_SIZE = Messages.getString( "TableOptionDialog.text.GridSize" ); //$NON-NLS-1$
private static final String MSG_TABLE_SIZE = Messages.getString( "TableOptionDialog.text.TableSize" ); //$NON-NLS-1$
private static final String MSG_INSERT_GRID = Messages.getString( "TableOptionDialog.title.InsertGrid" ); //$NON-NLS-1$
private static final String MSG_INSERT_TABLE = Messages.getString( "TableOptionDialog.title.InsertTable" ); //$NON-NLS-1$
private static final String NONE = Messages.getString( "BindingPage.None" );//$NON-NLS-1$
private static final int DEFAULT_TABLE_ROW_COUNT = 1;
private static final int DEFAULT_ROW_COUNT = 3;
private static final int DEFAULT_COLUMN_COUNT = 3;
/**
* Comment for <code>DEFAULT_TABLE_ROW_COUNT_KEY</code>
*/
public static final String DEFAULT_TABLE_ROW_COUNT_KEY = "Default table row count"; //$NON-NLS-1$
/**
* Comment for <code>DEFAULT_TABLE_COLUMN_COUNT_KEY</code>
*/
public static final String DEFAULT_TABLE_COLUMN_COUNT_KEY = "Default table column count"; //$NON-NLS-1$
/**
* Comment for <code>DEFAULT_GRID_ROW_COUNT_KEY</code>
*/
public static final String DEFAULT_GRID_ROW_COUNT_KEY = "Default grid row count"; //$NON-NLS-1$
/**
* Comment for <code>DEFAULT_GRID_COLUMN_COUNT_KEY</code>
*/
public static final String DEFAULT_GRID_COLUMN_COUNT_KEY = "Default grid column count"; //$NON-NLS-1$
private SimpleSpinner rowEditor;
private SimpleSpinner columnEditor;
private Button chkbox;
private int rowCount, columnCount;
private boolean insertTable = true;
private Combo dataSetCombo;
/**
* The constructor.
*
* @param parentShell
*/
public TableOptionDialog( Shell parentShell, boolean insertTable )
{
super( parentShell, insertTable ? MSG_INSERT_TABLE : MSG_INSERT_GRID );
this.insertTable = insertTable;
}
private void loadPreference( )
{
if ( insertTable )
{
columnCount = ReportPlugin.getDefault( )
.getPreferenceStore( )
.getInt( DEFAULT_TABLE_COLUMN_COUNT_KEY );
rowCount = ReportPlugin.getDefault( )
.getPreferenceStore( )
.getInt( DEFAULT_TABLE_ROW_COUNT_KEY );
}
else
{
columnCount = ReportPlugin.getDefault( )
.getPreferenceStore( )
.getInt( DEFAULT_GRID_COLUMN_COUNT_KEY );
rowCount = ReportPlugin.getDefault( )
.getPreferenceStore( )
.getInt( DEFAULT_GRID_ROW_COUNT_KEY );
}
if ( columnCount <= 0 )
{
columnCount = DEFAULT_COLUMN_COUNT;
}
if ( rowCount <= 0 )
{
rowCount = insertTable ? DEFAULT_TABLE_ROW_COUNT
: DEFAULT_ROW_COUNT;
}
}
private void savePreference( )
{
if ( insertTable )
{
ReportPlugin.getDefault( )
.getPreferenceStore( )
.setValue( DEFAULT_TABLE_COLUMN_COUNT_KEY, columnCount );
ReportPlugin.getDefault( )
.getPreferenceStore( )
.setValue( DEFAULT_TABLE_ROW_COUNT_KEY, rowCount );
}
else
{
ReportPlugin.getDefault( )
.getPreferenceStore( )
.setValue( DEFAULT_GRID_COLUMN_COUNT_KEY, columnCount );
ReportPlugin.getDefault( )
.getPreferenceStore( )
.setValue( DEFAULT_GRID_ROW_COUNT_KEY, rowCount );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea( Composite parent )
{
loadPreference( );
Composite composite = (Composite) super.createDialogArea( parent );
( (GridLayout) composite.getLayout( ) ).numColumns = 2;
new Label( composite, SWT.NONE ).setText( insertTable ? MSG_TABLE_SIZE
: MSG_GRID_SIZE );
Label sp = new Label( composite, SWT.SEPARATOR | SWT.HORIZONTAL );
sp.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Composite innerPane = new Composite( composite, SWT.NONE );
GridData gdata = new GridData( GridData.FILL_BOTH );
gdata.horizontalSpan = 2;
innerPane.setLayoutData( gdata );
GridLayout glayout = new GridLayout( 2, false );
glayout.marginWidth = 10;
innerPane.setLayout( glayout );
new Label( innerPane, SWT.NONE ).setText( MSG_NUMBER_OF_COLUMNS );
columnEditor = new SimpleSpinner( innerPane, 0 );
columnEditor.setText( String.valueOf( columnCount ) );
columnEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
new Label( innerPane, SWT.NONE ).setText( insertTable ? MSG_NUMBER_OF_TABLE_ROWS
: MSG_NUMBER_OF_GRID_ROWS );
rowEditor = new SimpleSpinner( innerPane, 0 );
rowEditor.setText( String.valueOf( rowCount ) );
rowEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
if ( insertTable )
{
new Label( innerPane, SWT.NONE ).setText( MSG_DATA_SET );
dataSetCombo = new Combo( innerPane, SWT.BORDER
| SWT.SINGLE
| SWT.READ_ONLY );
dataSetCombo.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
String[] dataSets = ChoiceSetFactory.getDataSets( );
String[] newList = new String[dataSets.length + 1];
System.arraycopy( dataSets, 0, newList, 1, dataSets.length );
newList[0] = NONE;
dataSetCombo.setItems( newList );
dataSetCombo.select( 0 );
}
else
{
Label lb = new Label( composite, SWT.NONE );
gdata = new GridData( GridData.FILL_HORIZONTAL );
gdata.horizontalSpan = 2;
lb.setLayoutData( gdata );
}
chkbox = new Button( composite, SWT.CHECK );
chkbox.setText( insertTable ? MSG_REMEMBER_DIMENSIONS_FOR_NEW_TABLES
: MSG_REMEMBER_DIMENSIONS_FOR_NEW_GRIDS );
gdata = new GridData( GridData.FILL_HORIZONTAL );
gdata.horizontalSpan = 2;
chkbox.setLayoutData( gdata );
if ( insertTable )
{
UIUtil.bindHelp( parent, IHelpContextIds.TABLE_OPTION_DIALOG_ID );
}
else
{
UIUtil.bindHelp( parent, IHelpContextIds.Grid_OPTION_DIALOG_ID );
}
return composite;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed( )
{
try
{
rowCount = Integer.parseInt( rowEditor.getText( ) );
}
catch ( NumberFormatException e )
{
rowCount = insertTable ? DEFAULT_TABLE_ROW_COUNT
: DEFAULT_ROW_COUNT;
}
try
{
columnCount = Integer.parseInt( columnEditor.getText( ) );
}
catch ( NumberFormatException e )
{
columnCount = DEFAULT_COLUMN_COUNT;
}
if ( columnCount <= 0 )
{
columnCount = DEFAULT_COLUMN_COUNT;
}
if ( rowCount <= 0 )
{
rowCount = insertTable ? DEFAULT_TABLE_ROW_COUNT
: DEFAULT_ROW_COUNT;
}
if ( insertTable )
{
setResult( new Object[]{
new Integer(rowCount),
new Integer(columnCount),
dataSetCombo.getItem( dataSetCombo.getSelectionIndex( ) )
.toString( )
} );
}
else
setResult( new int[]{
rowCount, columnCount
} );
if ( chkbox.getSelection( ) )
{
savePreference( );
}
super.okPressed( );
}
/**
* SimpleSpinner
*/
static class SimpleSpinner extends Composite
{
private static final int BUTTON_WIDTH = 16;
private Text text;
private Button up;
private Button down;
/**
* The constructor.
*
* @param parent
* @param style
*/
public SimpleSpinner( Composite parent, int style )
{
super( parent, style );
text = new Text( this, SWT.BORDER | SWT.SINGLE );
text.addVerifyListener( new VerifyListener( ) {
public void verifyText( VerifyEvent e )
{
if ( e.keyCode == 8 || e.keyCode == 127 )
{
e.doit = true;
return;
}
try
{
if ( e.text.length( ) != 0 )
{
Integer.parseInt( e.text );
}
e.doit = true;
}
catch ( Exception _ )
{
e.doit = false;
}
}
} );
text.addFocusListener( new FocusAdapter( ) {
public void focusGained( FocusEvent e )
{
text.selectAll( );
}
} );
up = new Button( this, style | SWT.ARROW | SWT.UP );
down = new Button( this, style | SWT.ARROW | SWT.DOWN );
up.addListener( SWT.Selection, new Listener( ) {
public void handleEvent( Event e )
{
up( );
}
} );
down.addListener( SWT.Selection, new Listener( ) {
public void handleEvent( Event e )
{
down( );
}
} );
addListener( SWT.Resize, new Listener( ) {
public void handleEvent( Event e )
{
resize( );
}
} );
addListener( SWT.FocusIn, new Listener( ) {
public void handleEvent( Event e )
{
focusIn( );
}
} );
initAccessible( );
}
void initAccessible( )
{
AccessibleAdapter accessibleAdapter = new AccessibleAdapter( ) {
public void getName( AccessibleEvent e )
{
getHelp( e );
}
public void getHelp( AccessibleEvent e )
{
e.result = getToolTipText( );
}
};
getAccessible( ).addAccessibleListener( accessibleAdapter );
up.getAccessible( ).addAccessibleListener( accessibleAdapter );
down.getAccessible( ).addAccessibleListener( accessibleAdapter );
getAccessible( ).addAccessibleTextListener( new AccessibleTextAdapter( ) {
public void getCaretOffset( AccessibleTextEvent e )
{
e.offset = text.getCaretPosition( );
}
} );
getAccessible( ).addAccessibleControlListener( new AccessibleControlAdapter( ) {
public void getChildAtPoint( AccessibleControlEvent e )
{
Point pt = toControl( new Point( e.x, e.y ) );
e.childID = ( getBounds( ).contains( pt ) ) ? ACC.CHILDID_SELF
: ACC.CHILDID_NONE;
}
public void getLocation( AccessibleControlEvent e )
{
Rectangle location = getBounds( );
Point pt = toDisplay( location.x, location.y );
e.x = pt.x;
e.y = pt.y;
e.width = location.width;
e.height = location.height;
}
public void getChildCount( AccessibleControlEvent e )
{
e.detail = 0;
}
public void getRole( AccessibleControlEvent e )
{
e.detail = ACC.ROLE_COMBOBOX;
}
public void getState( AccessibleControlEvent e )
{
e.detail = ACC.STATE_NORMAL;
}
} );
}
void setText( String val )
{
if ( text != null )
{
text.setText( val );
}
}
String getText( )
{
if ( text != null )
{
return text.getText( );
}
return null;
}
void up( )
{
if ( text != null )
{
try
{
int v = Integer.parseInt( text.getText( ) );
text.setText( String.valueOf( v + 1 ) );
}
catch ( NumberFormatException e )
{
text.setText( String.valueOf( 1 ) );
}
}
}
/**
* Processes down action
*/
void down( )
{
if ( text != null )
{
try
{
int v = Integer.parseInt( text.getText( ) );
if ( v < 2 )
{
v = 2;
}
text.setText( String.valueOf( v - 1 ) );
}
catch ( NumberFormatException e )
{
text.setText( String.valueOf( 1 ) );
}
}
}
void focusIn( )
{
if ( text != null )
{
text.setFocus( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.widgets.Control#computeSize(int, int, boolean)
*/
public Point computeSize( int wHint, int hHint, boolean changed )
{
return new Point( 80, 20 );
}
void resize( )
{
Point pt = computeSize( -1, -1 );
setSize( pt );
int textWidth = pt.x - BUTTON_WIDTH;
text.setBounds( 0, 0, textWidth, pt.y );
int buttonHeight = pt.y / 2;
up.setBounds( textWidth, 0, BUTTON_WIDTH, buttonHeight );
down.setBounds( textWidth,
pt.y - buttonHeight,
BUTTON_WIDTH,
buttonHeight );
}
}
}
|
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/dialogs/TableOptionDialog.java
|
/*************************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - Initial implementation.
************************************************************************************/
package org.eclipse.birt.report.designer.internal.ui.dialogs;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.accessibility.ACC;
import org.eclipse.swt.accessibility.AccessibleAdapter;
import org.eclipse.swt.accessibility.AccessibleControlAdapter;
import org.eclipse.swt.accessibility.AccessibleControlEvent;
import org.eclipse.swt.accessibility.AccessibleEvent;
import org.eclipse.swt.accessibility.AccessibleTextAdapter;
import org.eclipse.swt.accessibility.AccessibleTextEvent;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* Dialog to choose the table/grid row/column number when create a table/grid.
*
*/
public class TableOptionDialog extends BaseDialog
{
private static final String MSG_DATA_SET = Messages.getString( "TableOptionDialog.text.DataSet" );
private static final String MSG_REMEMBER_DIMENSIONS_FOR_NEW_GRIDS = Messages.getString( "TableOptionDialog.message.RememberGrid" ); //$NON-NLS-1$
private static final String MSG_REMEMBER_DIMENSIONS_FOR_NEW_TABLES = Messages.getString( "TableOptionDialog.message.RememberTable" ); //$NON-NLS-1$
private static final String MSG_NUMBER_OF_GRID_ROWS = Messages.getString( "TableOptionDialog.text.GridRow" ); //$NON-NLS-1$
private static final String MSG_NUMBER_OF_TABLE_ROWS = Messages.getString( "TableOptionDialog.text.TableDetail" ); //$NON-NLS-1$
private static final String MSG_NUMBER_OF_COLUMNS = Messages.getString( "TableOptionDialog.text.Column" ); //$NON-NLS-1$
private static final String MSG_GRID_SIZE = Messages.getString( "TableOptionDialog.text.GridSize" ); //$NON-NLS-1$
private static final String MSG_TABLE_SIZE = Messages.getString( "TableOptionDialog.text.TableSize" ); //$NON-NLS-1$
private static final String MSG_INSERT_GRID = Messages.getString( "TableOptionDialog.title.InsertGrid" ); //$NON-NLS-1$
private static final String MSG_INSERT_TABLE = Messages.getString( "TableOptionDialog.title.InsertTable" ); //$NON-NLS-1$
private static final String NONE = Messages.getString( "BindingPage.None" );//$NON-NLS-1$
private static final int DEFAULT_TABLE_ROW_COUNT = 1;
private static final int DEFAULT_ROW_COUNT = 3;
private static final int DEFAULT_COLUMN_COUNT = 3;
/**
* Comment for <code>DEFAULT_TABLE_ROW_COUNT_KEY</code>
*/
public static final String DEFAULT_TABLE_ROW_COUNT_KEY = "Default table row count"; //$NON-NLS-1$
/**
* Comment for <code>DEFAULT_TABLE_COLUMN_COUNT_KEY</code>
*/
public static final String DEFAULT_TABLE_COLUMN_COUNT_KEY = "Default table column count"; //$NON-NLS-1$
/**
* Comment for <code>DEFAULT_GRID_ROW_COUNT_KEY</code>
*/
public static final String DEFAULT_GRID_ROW_COUNT_KEY = "Default grid row count"; //$NON-NLS-1$
/**
* Comment for <code>DEFAULT_GRID_COLUMN_COUNT_KEY</code>
*/
public static final String DEFAULT_GRID_COLUMN_COUNT_KEY = "Default grid column count"; //$NON-NLS-1$
private SimpleSpinner rowEditor;
private SimpleSpinner columnEditor;
private Button chkbox;
private int rowCount, columnCount;
private boolean insertTable = true;
private Combo dataSetCombo;
/**
* The constructor.
*
* @param parentShell
*/
public TableOptionDialog( Shell parentShell, boolean insertTable )
{
super( parentShell, insertTable ? MSG_INSERT_TABLE : MSG_INSERT_GRID );
this.insertTable = insertTable;
}
private void loadPreference( )
{
if ( insertTable )
{
columnCount = ReportPlugin.getDefault( )
.getPreferenceStore( )
.getInt( DEFAULT_TABLE_COLUMN_COUNT_KEY );
rowCount = ReportPlugin.getDefault( )
.getPreferenceStore( )
.getInt( DEFAULT_TABLE_ROW_COUNT_KEY );
}
else
{
columnCount = ReportPlugin.getDefault( )
.getPreferenceStore( )
.getInt( DEFAULT_GRID_COLUMN_COUNT_KEY );
rowCount = ReportPlugin.getDefault( )
.getPreferenceStore( )
.getInt( DEFAULT_GRID_ROW_COUNT_KEY );
}
if ( columnCount <= 0 )
{
columnCount = DEFAULT_COLUMN_COUNT;
}
if ( rowCount <= 0 )
{
rowCount = insertTable ? DEFAULT_TABLE_ROW_COUNT
: DEFAULT_ROW_COUNT;
}
}
private void savePreference( )
{
if ( insertTable )
{
ReportPlugin.getDefault( )
.getPreferenceStore( )
.setValue( DEFAULT_TABLE_COLUMN_COUNT_KEY, columnCount );
ReportPlugin.getDefault( )
.getPreferenceStore( )
.setValue( DEFAULT_TABLE_ROW_COUNT_KEY, rowCount );
}
else
{
ReportPlugin.getDefault( )
.getPreferenceStore( )
.setValue( DEFAULT_GRID_COLUMN_COUNT_KEY, columnCount );
ReportPlugin.getDefault( )
.getPreferenceStore( )
.setValue( DEFAULT_GRID_ROW_COUNT_KEY, rowCount );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea( Composite parent )
{
loadPreference( );
Composite composite = (Composite) super.createDialogArea( parent );
( (GridLayout) composite.getLayout( ) ).numColumns = 2;
new Label( composite, SWT.NONE ).setText( insertTable ? MSG_TABLE_SIZE
: MSG_GRID_SIZE );
Label sp = new Label( composite, SWT.SEPARATOR | SWT.HORIZONTAL );
sp.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Composite innerPane = new Composite( composite, SWT.NONE );
GridData gdata = new GridData( GridData.FILL_BOTH );
gdata.horizontalSpan = 2;
innerPane.setLayoutData( gdata );
GridLayout glayout = new GridLayout( 2, false );
glayout.marginWidth = 10;
innerPane.setLayout( glayout );
new Label( innerPane, SWT.NONE ).setText( MSG_NUMBER_OF_COLUMNS );
columnEditor = new SimpleSpinner( innerPane, 0 );
columnEditor.setText( String.valueOf( columnCount ) );
columnEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
new Label( innerPane, SWT.NONE ).setText( insertTable ? MSG_NUMBER_OF_TABLE_ROWS
: MSG_NUMBER_OF_GRID_ROWS );
rowEditor = new SimpleSpinner( innerPane, 0 );
rowEditor.setText( String.valueOf( rowCount ) );
rowEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
if ( insertTable )
{
new Label( innerPane, SWT.NONE ).setText( MSG_DATA_SET );
dataSetCombo = new Combo( innerPane, SWT.BORDER
| SWT.SINGLE
| SWT.READ_ONLY );
dataSetCombo.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
String[] dataSets = ChoiceSetFactory.getDataSets( );
String[] newList = new String[dataSets.length + 1];
System.arraycopy( dataSets, 0, newList, 0, dataSets.length );
newList[dataSets.length] = NONE;
dataSetCombo.setItems( newList );
dataSetCombo.select( 0 );
}
else
{
Label lb = new Label( composite, SWT.NONE );
gdata = new GridData( GridData.FILL_HORIZONTAL );
gdata.horizontalSpan = 2;
lb.setLayoutData( gdata );
}
chkbox = new Button( composite, SWT.CHECK );
chkbox.setText( insertTable ? MSG_REMEMBER_DIMENSIONS_FOR_NEW_TABLES
: MSG_REMEMBER_DIMENSIONS_FOR_NEW_GRIDS );
gdata = new GridData( GridData.FILL_HORIZONTAL );
gdata.horizontalSpan = 2;
chkbox.setLayoutData( gdata );
if ( insertTable )
{
UIUtil.bindHelp( parent, IHelpContextIds.TABLE_OPTION_DIALOG_ID );
}
else
{
UIUtil.bindHelp( parent, IHelpContextIds.Grid_OPTION_DIALOG_ID );
}
return composite;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
protected void okPressed( )
{
try
{
rowCount = Integer.parseInt( rowEditor.getText( ) );
}
catch ( NumberFormatException e )
{
rowCount = insertTable ? DEFAULT_TABLE_ROW_COUNT
: DEFAULT_ROW_COUNT;
}
try
{
columnCount = Integer.parseInt( columnEditor.getText( ) );
}
catch ( NumberFormatException e )
{
columnCount = DEFAULT_COLUMN_COUNT;
}
if ( columnCount <= 0 )
{
columnCount = DEFAULT_COLUMN_COUNT;
}
if ( rowCount <= 0 )
{
rowCount = insertTable ? DEFAULT_TABLE_ROW_COUNT
: DEFAULT_ROW_COUNT;
}
if ( insertTable )
{
setResult( new Object[]{
new Integer(rowCount),
new Integer(columnCount),
dataSetCombo.getItem( dataSetCombo.getSelectionIndex( ) )
.toString( )
} );
}
else
setResult( new int[]{
rowCount, columnCount
} );
if ( chkbox.getSelection( ) )
{
savePreference( );
}
super.okPressed( );
}
/**
* SimpleSpinner
*/
static class SimpleSpinner extends Composite
{
private static final int BUTTON_WIDTH = 16;
private Text text;
private Button up;
private Button down;
/**
* The constructor.
*
* @param parent
* @param style
*/
public SimpleSpinner( Composite parent, int style )
{
super( parent, style );
text = new Text( this, SWT.BORDER | SWT.SINGLE );
text.addVerifyListener( new VerifyListener( ) {
public void verifyText( VerifyEvent e )
{
if ( e.keyCode == 8 || e.keyCode == 127 )
{
e.doit = true;
return;
}
try
{
if ( e.text.length( ) != 0 )
{
Integer.parseInt( e.text );
}
e.doit = true;
}
catch ( Exception _ )
{
e.doit = false;
}
}
} );
text.addFocusListener( new FocusAdapter( ) {
public void focusGained( FocusEvent e )
{
text.selectAll( );
}
} );
up = new Button( this, style | SWT.ARROW | SWT.UP );
down = new Button( this, style | SWT.ARROW | SWT.DOWN );
up.addListener( SWT.Selection, new Listener( ) {
public void handleEvent( Event e )
{
up( );
}
} );
down.addListener( SWT.Selection, new Listener( ) {
public void handleEvent( Event e )
{
down( );
}
} );
addListener( SWT.Resize, new Listener( ) {
public void handleEvent( Event e )
{
resize( );
}
} );
addListener( SWT.FocusIn, new Listener( ) {
public void handleEvent( Event e )
{
focusIn( );
}
} );
initAccessible( );
}
void initAccessible( )
{
AccessibleAdapter accessibleAdapter = new AccessibleAdapter( ) {
public void getName( AccessibleEvent e )
{
getHelp( e );
}
public void getHelp( AccessibleEvent e )
{
e.result = getToolTipText( );
}
};
getAccessible( ).addAccessibleListener( accessibleAdapter );
up.getAccessible( ).addAccessibleListener( accessibleAdapter );
down.getAccessible( ).addAccessibleListener( accessibleAdapter );
getAccessible( ).addAccessibleTextListener( new AccessibleTextAdapter( ) {
public void getCaretOffset( AccessibleTextEvent e )
{
e.offset = text.getCaretPosition( );
}
} );
getAccessible( ).addAccessibleControlListener( new AccessibleControlAdapter( ) {
public void getChildAtPoint( AccessibleControlEvent e )
{
Point pt = toControl( new Point( e.x, e.y ) );
e.childID = ( getBounds( ).contains( pt ) ) ? ACC.CHILDID_SELF
: ACC.CHILDID_NONE;
}
public void getLocation( AccessibleControlEvent e )
{
Rectangle location = getBounds( );
Point pt = toDisplay( location.x, location.y );
e.x = pt.x;
e.y = pt.y;
e.width = location.width;
e.height = location.height;
}
public void getChildCount( AccessibleControlEvent e )
{
e.detail = 0;
}
public void getRole( AccessibleControlEvent e )
{
e.detail = ACC.ROLE_COMBOBOX;
}
public void getState( AccessibleControlEvent e )
{
e.detail = ACC.STATE_NORMAL;
}
} );
}
void setText( String val )
{
if ( text != null )
{
text.setText( val );
}
}
String getText( )
{
if ( text != null )
{
return text.getText( );
}
return null;
}
void up( )
{
if ( text != null )
{
try
{
int v = Integer.parseInt( text.getText( ) );
text.setText( String.valueOf( v + 1 ) );
}
catch ( NumberFormatException e )
{
text.setText( String.valueOf( 1 ) );
}
}
}
/**
* Processes down action
*/
void down( )
{
if ( text != null )
{
try
{
int v = Integer.parseInt( text.getText( ) );
if ( v < 2 )
{
v = 2;
}
text.setText( String.valueOf( v - 1 ) );
}
catch ( NumberFormatException e )
{
text.setText( String.valueOf( 1 ) );
}
}
}
void focusIn( )
{
if ( text != null )
{
text.setFocus( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.widgets.Control#computeSize(int, int, boolean)
*/
public Point computeSize( int wHint, int hHint, boolean changed )
{
return new Point( 80, 20 );
}
void resize( )
{
Point pt = computeSize( -1, -1 );
setSize( pt );
int textWidth = pt.x - BUTTON_WIDTH;
text.setBounds( 0, 0, textWidth, pt.y );
int buttonHeight = pt.y / 2;
up.setBounds( textWidth, 0, BUTTON_WIDTH, buttonHeight );
down.setBounds( textWidth,
pt.y - buttonHeight,
BUTTON_WIDTH,
buttonHeight );
}
}
}
|
- Summary: Default binding of table should be None
- Bugzilla Bug (s) Resolved: 154485
- Description: Default binding of table should be None
- Tests Description: Manual test.
- Notes to Build Team:
- Notes to Developers:
- Notes to QA:
- Notes to Documentation:
- Files Added:
@addlist
- Files Edited:
@changelist
- Files Deleted:
@deletelist
|
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/dialogs/TableOptionDialog.java
|
- Summary: Default binding of table should be None
|
|
Java
|
mpl-2.0
|
5d51a2840952632eef3930ab5e3fb376d6160eab
| 0
|
WanionCane/UniDict
|
package wanion.unidict.integration;
import forestry.api.recipes.ICarpenterRecipe;
import forestry.api.recipes.ICentrifugeRecipe;
import forestry.core.recipes.ShapedRecipeCustom;
import forestry.factory.recipes.CarpenterRecipe;
import forestry.factory.recipes.CarpenterRecipeManager;
import forestry.factory.recipes.CentrifugeRecipe;
import forestry.factory.recipes.CentrifugeRecipeManager;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import wanion.lib.common.Util;
import wanion.lib.recipe.RecipeAttributes;
import wanion.lib.recipe.RecipeHelper;
import wanion.unidict.resource.UniResourceContainer;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.stream.Collectors;
final class ForestryIntegration extends AbstractIntegrationThread
{
ForestryIntegration() { super("Forestry"); }
@Override
public String call() {
try {
fixCarpenterRecipes();
fixCentrifugeRecipes();
} catch (Exception e) { logger.error(threadName + e); }
return threadName + "All these bees... they can hurt, you know?";
}
private void fixCarpenterRecipes() {
final Set<ICarpenterRecipe> carpenterRecipes = Util.getField(CarpenterRecipeManager.class, "recipes", null, Set.class);
if (carpenterRecipes == null)
return;
final List<ICarpenterRecipe> newRecipes = new ArrayList<>();
for (final Iterator<ICarpenterRecipe> carpenterRecipeIterator = carpenterRecipes.iterator(); carpenterRecipeIterator.hasNext();) {
final ICarpenterRecipe carpenterRecipe = carpenterRecipeIterator.next();
if (carpenterRecipe.getCraftingGridRecipe() instanceof ShapedRecipeCustom) {
final ShapedRecipeCustom gridRecipe = (ShapedRecipeCustom)carpenterRecipe.getCraftingGridRecipe();
newRecipes.add(new CarpenterRecipe(carpenterRecipe.getPackagingTime(),
carpenterRecipe.getFluidResource(), carpenterRecipe.getBox(), recreateRecipe(gridRecipe)));
carpenterRecipeIterator.remove();
}
}
carpenterRecipes.addAll(newRecipes);
}
private ShapedRecipeCustom recreateRecipe(final ShapedRecipeCustom recipe) {
final List<Ingredient> recipeInputs = recipe.getIngredients();
final int width = recipe.getRecipeWidth(), height = recipe.getRecipeHeight(), root = Math.max(width, height);
final Object[] newRecipeInputs = new Object[root * root];
for (int y = 0, i = 0; y < height; y++) {
for (int x = 0; x < width; x++, i++) {
final Ingredient ingredient = i < recipeInputs.size() ? recipeInputs.get(i) : null;
if (ingredient != null && ingredient.getMatchingStacks().length > 0) {
final ItemStack itemStack = ingredient.getMatchingStacks()[0];
final UniResourceContainer container = resourceHandler.getContainer(itemStack);
newRecipeInputs[y * root + x] = container != null ? container.name : itemStack;
}
}
}
final RecipeAttributes newRecipeAttributes = RecipeHelper.rawShapeToShape(newRecipeInputs);
final ShapedRecipeCustom newRecipe =
new ShapedRecipeCustom(resourceHandler.getMainItemStack(recipe.getRecipeOutput()), newRecipeAttributes.actualShape);
newRecipe.setRegistryName(recipe.getGroup());
return newRecipe;
}
private void fixCentrifugeRecipes()
{
final Set<ICentrifugeRecipe> centrifugeRecipes = Util.getField(CentrifugeRecipeManager.class, "recipes", null, Set.class);
if (centrifugeRecipes == null)
return;
final List<ICentrifugeRecipe> newRecipes = new ArrayList<>();
for (final Iterator<ICentrifugeRecipe> centrifugeRecipeIterator = centrifugeRecipes.iterator(); centrifugeRecipeIterator.hasNext();)
{
final ICentrifugeRecipe centrifugeRecipe = centrifugeRecipeIterator.next();
newRecipes.add(new CentrifugeRecipe(centrifugeRecipe.getProcessingTime(), centrifugeRecipe.getInput(), correctCentrifugeOutput(centrifugeRecipe.getAllProducts())));
centrifugeRecipeIterator.remove();
}
centrifugeRecipes.addAll(newRecipes);
}
@Nonnull
private Map<ItemStack, Float> correctCentrifugeOutput(@Nonnull final Map<ItemStack, Float> outputMap)
{
return outputMap.entrySet().stream().collect(Collectors.toMap(entry -> resourceHandler.getMainItemStack(entry.getKey()), Map.Entry::getValue));
}
}
|
src/main/java/wanion/unidict/integration/ForestryIntegration.java
|
package wanion.unidict.integration;
import forestry.api.recipes.ICarpenterRecipe;
import forestry.api.recipes.ICentrifugeRecipe;
import forestry.core.recipes.ShapedRecipeCustom;
import forestry.factory.recipes.CarpenterRecipe;
import forestry.factory.recipes.CarpenterRecipeManager;
import forestry.factory.recipes.CentrifugeRecipe;
import forestry.factory.recipes.CentrifugeRecipeManager;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import wanion.lib.common.MetaItem;
import wanion.lib.common.Util;
import wanion.unidict.resource.UniResourceContainer;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.stream.Collectors;
final class ForestryIntegration extends AbstractIntegrationThread
{
private final Set<ICarpenterRecipe> carpenterRecipes = Util.getField(CarpenterRecipeManager.class, "recipes", null, Set.class);
ForestryIntegration()
{
super("Forestry");
}
@Override
public String call()
{
try {
removeBadCarpenterOutputs(carpenterRecipes);
final UniResourceContainer ingotBronze = resourceHandler.getContainer("Bronze", "ingot");
if (ingotBronze != null)
bronzeThings(ingotBronze);
fixCentrifugeRecipes();
} catch (Exception e) { logger.error(threadName + e); }
return threadName + "All these bees... they can hurt, you know?";
}
private void removeBadCarpenterOutputs(@Nonnull final Set<ICarpenterRecipe> carpenterRecipes)
{
carpenterRecipes.removeIf(carpenterRecipe -> carpenterRecipe != null && resourceHandler.exists(MetaItem.get(carpenterRecipe.getCraftingGridRecipe().getOutput())));
}
private void bronzeThings(@Nonnull final UniResourceContainer ingotBronze)
{
Item brokenBronzePickaxe = Item.REGISTRY.getObject(new ResourceLocation("forestry", "brokenBronzePickaxe"));
if (brokenBronzePickaxe == null)
brokenBronzePickaxe = Item.REGISTRY.getObject(new ResourceLocation("forestry", "broken_bronze_pickaxe"));
Item brokenBronzeShovel = Item.REGISTRY.getObject(new ResourceLocation("forestry", "brokenBronzeShovel"));
if (brokenBronzeShovel == null)
brokenBronzeShovel = Item.REGISTRY.getObject(new ResourceLocation("forestry", "broken_bronze_shovel"));
if (brokenBronzePickaxe != null)
carpenterRecipes.add(new CarpenterRecipe(5, null, ItemStack.EMPTY, new ShapedRecipeCustom(ingotBronze.getMainEntry(2), "X ", " ", " ", 'X', new ItemStack(brokenBronzePickaxe))));
if (brokenBronzeShovel != null)
carpenterRecipes.add(new CarpenterRecipe(5, null, ItemStack.EMPTY, new ShapedRecipeCustom(ingotBronze.getMainEntry(), "X ", " ", " ", 'X', new ItemStack(brokenBronzeShovel))));
}
private void fixCentrifugeRecipes()
{
final Set<ICentrifugeRecipe> centrifugeRecipes = Util.getField(CentrifugeRecipeManager.class, "recipes", null, Set.class);
if (centrifugeRecipes == null)
return;
final List<ICentrifugeRecipe> newRecipes = new ArrayList<>();
for (final Iterator<ICentrifugeRecipe> centrifugeRecipeIterator = centrifugeRecipes.iterator(); centrifugeRecipeIterator.hasNext(); centrifugeRecipeIterator.remove())
{
final ICentrifugeRecipe centrifugeRecipe = centrifugeRecipeIterator.next();
newRecipes.add(new CentrifugeRecipe(centrifugeRecipe.getProcessingTime(), centrifugeRecipe.getInput(), correctCentrifugeOutput(centrifugeRecipe.getAllProducts())));
}
centrifugeRecipes.addAll(newRecipes);
}
@Nonnull
private Map<ItemStack, Float> correctCentrifugeOutput(@Nonnull final Map<ItemStack, Float> outputMap)
{
return outputMap.entrySet().stream().collect(Collectors.toMap(entry -> resourceHandler.getMainItemStack(entry.getKey()), Map.Entry::getValue));
}
}
|
Completely rewritten Forestry carpenter integration.
No longer removes recipes without adding them back.
|
src/main/java/wanion/unidict/integration/ForestryIntegration.java
|
Completely rewritten Forestry carpenter integration. No longer removes recipes without adding them back.
|
|
Java
|
agpl-3.0
|
0c49bab8ab742e503967f5d0ec94cab7fbd60fdb
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
03ee18ee-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
03e8adc8-2e60-11e5-9284-b827eb9e62be
|
03ee18ee-2e60-11e5-9284-b827eb9e62be
|
hello.java
|
03ee18ee-2e60-11e5-9284-b827eb9e62be
|
|
Java
|
agpl-3.0
|
ce04c161df218f2dd76a5746fc830f54da8a4bf4
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
77de4f5c-2e61-11e5-9284-b827eb9e62be
|
hello.java
|
77d8e3fa-2e61-11e5-9284-b827eb9e62be
|
77de4f5c-2e61-11e5-9284-b827eb9e62be
|
hello.java
|
77de4f5c-2e61-11e5-9284-b827eb9e62be
|
|
Java
|
lgpl-2.1
|
d47c13d182942c096cb01b71b6c95a6b10af1b60
| 0
|
lucee/Lucee,lucee/Lucee,lucee/Lucee,lucee/Lucee,jzuijlek/Lucee,jzuijlek/Lucee,jzuijlek/Lucee
|
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* 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, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.text.xml;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import lucee.commons.io.IOUtil;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.StringUtil;
import lucee.runtime.PageContext;
import lucee.runtime.config.ConfigImpl;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.exp.XMLException;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.osgi.EnvClassLoader;
import lucee.runtime.text.xml.struct.XMLMultiElementStruct;
import lucee.runtime.text.xml.struct.XMLStruct;
import lucee.runtime.text.xml.struct.XMLStructFactory;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Struct;
import org.apache.xalan.processor.TransformerFactoryImpl;
import org.ccil.cowan.tagsoup.Parser;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
*
*/
public final class XMLUtil {
public static final short UNDEFINED_NODE=-1;
public static final Collection.Key XMLCOMMENT = KeyImpl.intern("xmlcomment");
public static final Collection.Key XMLTEXT = KeyImpl.intern("xmltext");
public static final Collection.Key XMLCDATA = KeyImpl.intern("xmlcdata");
public static final Collection.Key XMLCHILDREN = KeyImpl.intern("xmlchildren");
public static final Collection.Key XMLNODES = KeyImpl.intern("xmlnodes");
public static final Collection.Key XMLNSURI = KeyImpl.intern("xmlnsuri");
public static final Collection.Key XMLNSPREFIX = KeyImpl.intern("xmlnsprefix");
public static final Collection.Key XMLROOT = KeyImpl.intern("xmlroot");
public static final Collection.Key XMLPARENT = KeyImpl.intern("xmlparent");
public static final Collection.Key XMLNAME = KeyImpl.intern("xmlname");
public static final Collection.Key XMLTYPE = KeyImpl.intern("xmltype");
public static final Collection.Key XMLVALUE = KeyImpl.intern("xmlvalue");
public static final Collection.Key XMLATTRIBUTES = KeyImpl.intern("xmlattributes");
/*
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
*/
//static DOMParser parser = new DOMParser();
private static DocumentBuilder docBuilder;
//private static DocumentBuilderFactory factory;
private static TransformerFactory transformerFactory;
public static String unescapeXMLString(String str) {
StringBuffer rtn=new StringBuffer();
int posStart=-1;
int posFinish=-1;
while((posStart=str.indexOf('&',posStart))!=-1) {
int last=posFinish+1;
posFinish=str.indexOf(';',posStart);
if(posFinish==-1)break;
rtn.append(str.substring(last,posStart));
if(posStart+1<posFinish) {
rtn.append(unescapeXMLEntity(str.substring(posStart+1,posFinish)));
}
else {
rtn.append("&;");
}
posStart=posFinish+1;
}
rtn.append(str.substring(posFinish+1));
return rtn.toString();
}
public static String unescapeXMLString2(String str) {
StringBuffer sb=new StringBuffer();
int index,last=0,indexSemi;
while((index=str.indexOf('&',last))!=-1) {
sb.append(str.substring(last,index));
indexSemi=str.indexOf(';',index+1);
if(indexSemi==-1) {
sb.append('&');
last=index+1;
}
else if(index+1==indexSemi) {
sb.append("&;");
last=index+2;
}
else {
sb.append(unescapeXMLEntity(str.substring(index+1,indexSemi)));
last=indexSemi+1;
}
}
sb.append(str.substring(last));
return sb.toString();
}
private static String unescapeXMLEntity(String str) {
if("lt".equals(str)) return "<";
if("gt".equals(str)) return ">";
if("amp".equals(str)) return "&";
if("apos".equals(str)) return "'";
if("quot".equals(str)) return "\"";
return "&"+str+";";
}
public static String escapeXMLString(String xmlStr) {
char c;
StringBuffer sb=new StringBuffer();
int len=xmlStr.length();
for(int i=0;i<len;i++) {
c=xmlStr.charAt(i);
if(c=='<') sb.append("<");
else if(c=='>') sb.append(">");
else if(c=='&') sb.append("&");
//else if(c=='\'') sb.append("&");
else if(c=='"') sb.append(""");
//else if(c>127) sb.append("&#"+((int)c)+";");
else sb.append(c);
}
return sb.toString();
}
/**
* @return returns a singelton TransformerFactory
*/
public static TransformerFactory getTransformerFactory() {
Thread.currentThread().setContextClassLoader(new EnvClassLoader((ConfigImpl)ThreadLocalPageContext.getConfig())); // TODO make this global
//if(transformerFactory==null)transformerFactory=TransformerFactory.newInstance();
if(transformerFactory==null)transformerFactory=new TransformerFactoryImpl();
return transformerFactory;
}
public static final Document parse(InputSource xml,InputSource validator, boolean isHtml)
throws SAXException, IOException {
return parse(xml, validator, new XMLEntityResolverDefaultHandler(validator), isHtml);
}
/**
* parse XML/HTML String to a XML DOM representation
* @param xml XML InputSource
* @param isHtml is a HTML or XML Object
* @return parsed Document
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
*/
public static final Document parse(InputSource xml,InputSource validator, EntityResolver entRes, boolean isHtml)
throws SAXException, IOException {
if(!isHtml) {
DocumentBuilderFactory factory = newDocumentBuilderFactory();
if(validator==null) {
XMLUtil.setAttributeEL(factory,XMLConstants.NON_VALIDATING_DTD_EXTERNAL, Boolean.FALSE);
XMLUtil.setAttributeEL(factory,XMLConstants.NON_VALIDATING_DTD_GRAMMAR, Boolean.FALSE);
}
else {
XMLUtil.setAttributeEL(factory,XMLConstants.VALIDATION_SCHEMA, Boolean.TRUE);
XMLUtil.setAttributeEL(factory,XMLConstants.VALIDATION_SCHEMA_FULL_CHECKING, Boolean.TRUE);
}
factory.setNamespaceAware(true);
factory.setValidating(validator!=null);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
if(entRes!=null)builder.setEntityResolver(entRes);
builder.setErrorHandler(new ThrowingErrorHandler(true,true,false));
return builder.parse(xml);
}
catch (ParserConfigurationException e) {
throw new SAXException(e);
}
}
XMLReader reader = new Parser();
reader.setFeature(Parser.namespacesFeature, true);
reader.setFeature(Parser.namespacePrefixesFeature, true);
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
transformer.transform(new SAXSource(reader, xml), result);
return XMLUtil.getDocument(result.getNode());
}
catch (Exception e) {
throw new SAXException(e);
}
}
private static DocumentBuilderFactory newDocumentBuilderFactory() {
return DocumentBuilderFactory.newInstance();
//return new DocumentBuilderFactoryImpl();
// we do not use DocumentBuilderFactory.newInstance(); because it is unpredictable
}
private static void setAttributeEL(DocumentBuilderFactory factory,String name, Object value) {
try{
factory.setAttribute(name, value);
}
catch(Throwable t){ExceptionUtil.rethrowIfNecessary(t);}
}
/**
* sets a node to a node (Expression Less)
* @param node
* @param key
* @param value
* @return Object set
*/
public static Object setPropertyEL(Node node, Collection.Key key, Object value) {
try {
return setProperty(node,key,value);
} catch (PageException e) {
return null;
}
}
public static Object setProperty(Node node, Collection.Key key, Object value,boolean caseSensitive, Object defaultValue) {
try {
return setProperty(node,key,value,caseSensitive);
} catch (PageException e) {
return defaultValue;
}
}
/**
* sets a node to a node
* @param node
* @param key
* @param value
* @return Object set
* @throws PageException
*/
public static Object setProperty(Node node, Collection.Key k, Object value) throws PageException {
return setProperty(node, k, value, isCaseSensitve(node));
}
public static Object setProperty(Node node, Collection.Key k, Object value,boolean caseSensitive) throws PageException {
Document doc=getDocument(node);
boolean isXMLChildren;
// Comment
if(k.equals(XMLCOMMENT)) {
removeChildren(XMLCaster.toRawNode(node),Node.COMMENT_NODE,false);
node.appendChild(XMLCaster.toRawNode(XMLCaster.toComment(doc,value)));
}
// NS URI
else if(k.equals(XMLNSURI)) {
// TODO impl
throw new ExpressionException("XML NS URI can't be set","not implemented");
}
// Prefix
else if(k.equals(XMLNSPREFIX)) {
// TODO impl
throw new ExpressionException("XML NS Prefix can't be set","not implemented");
//node.setPrefix(Caster.toString(value));
}
// Root
else if(k.equals(XMLROOT)) {
doc.appendChild(XMLCaster.toNode(doc,value,false));
}
// Parent
else if(k.equals(XMLPARENT)) {
Node parent = getParentNode(node,caseSensitive);
Key name = KeyImpl.init(parent.getNodeName());
parent = getParentNode(parent,caseSensitive);
if(parent==null)
throw new ExpressionException("there is no parent element, you are already on the root element");
return setProperty(parent, name, value, caseSensitive);
}
// Name
else if(k.equals(XMLNAME)) {
throw new XMLException("You can't assign a new value for the property [xmlname]");
}
// Type
else if(k.equals(XMLTYPE)) {
throw new XMLException("You can't change type of a xml node [xmltype]");
}
// value
else if(k.equals(XMLVALUE)) {
node.setNodeValue(Caster.toString(value));
}
// Attributes
else if(k.equals(XMLATTRIBUTES)) {
Element parent=XMLCaster.toElement(doc,node);
Attr[] attres=XMLCaster.toAttrArray(doc,value);
//print.ln("=>"+value);
for(int i=0;i<attres.length;i++) {
if(attres[i]!=null) {
parent.setAttributeNode(attres[i]);
//print.ln(attres[i].getName()+"=="+attres[i].getValue());
}
}
}
// Text
else if(k.equals(XMLTEXT)) {
removeChildCharacterData(XMLCaster.toRawNode(node),false);
node.appendChild(XMLCaster.toRawNode(XMLCaster.toText(doc,value)));
}
// CData
else if(k.equals(XMLCDATA)) {
removeChildCharacterData(XMLCaster.toRawNode(node),false);
node.appendChild(XMLCaster.toRawNode(XMLCaster.toCDATASection(doc,value)));
}
// Children
else if((isXMLChildren=k.equals(XMLCHILDREN)) || k.equals(XMLNODES)) {
Node[] nodes=XMLCaster.toNodeArray(doc,value);
removeChildren(XMLCaster.toRawNode(node),isXMLChildren?Node.ELEMENT_NODE:XMLUtil.UNDEFINED_NODE,false);
for(int i=0;i<nodes.length;i++) {
if(nodes[i]==node) throw new XMLException("can't assign a XML Node to himself");
if(nodes[i]!=null)node.appendChild(XMLCaster.toRawNode(nodes[i]));
}
}
else {
boolean isIndex=false;
Node child = XMLCaster.toNode(doc,value,false);
if(!k.getString().equalsIgnoreCase(child.getNodeName()) && !(isIndex=Decision.isInteger(k))) {
throw new XMLException("if you assign a XML Element to a XMLStruct , assignment property must have same name like XML Node Name", "Property Name is "+k.getString()+" and XML Element Name is "+child.getNodeName());
}
Node n;
// by index
if(isIndex) {
NodeList list = XMLUtil.getChildNodes(node.getParentNode(), Node.ELEMENT_NODE,true,node.getNodeName());
int len = list.getLength();
int index=Caster.toIntValue(k);
if(index>len || index<1){
String detail=len>1?
"your index is "+index+", but there are only "+len+" child elements":
"your index is "+index+", but there is only "+len+" child element";
throw new XMLException("index is out of range", detail);
}
n=list.item(index-1);
XMLUtil.replaceChild(child, n);
return value;
}
NodeList list = XMLUtil.getChildNodes(node, Node.ELEMENT_NODE);
int len = list.getLength();
// by name
for(int i=0;i<len;i++) {
n=list.item(i);
if(nameEqual(n, k.getString(), caseSensitive)) {
XMLUtil.replaceChild(child, n);
return value;
}
}
node.appendChild(XMLCaster.toRawNode(child));
}
return value;
}
public static void replaceChild(Node newChild, Node oldChild) {
Node nc = XMLCaster.toRawNode(newChild);
Node oc = XMLCaster.toRawNode(oldChild);
Node p = oc.getParentNode();
if(nc!=oc)p.replaceChild(nc, oc);
}
public static Object getProperty(Node node, Collection.Key key, Object defaultValue) {
return getProperty(node, key,isCaseSensitve(node),defaultValue);
}
/**
* returns a property from a XMl Node (Expression Less)
* @param node
* @param key
* @param caseSensitive
* @return Object matching key
*/
public static Object getProperty(Node node, Collection.Key k,boolean caseSensitive, Object defaultValue) {
try {
return getProperty(node, k,caseSensitive);
} catch (SAXException e) {
return defaultValue;
}
}
public static Object getProperty(Node node, Collection.Key key) throws SAXException {
return getProperty(node, key,isCaseSensitve(node));
}
/**
* returns a property from a XMl Node
* @param node
* @param key
* @param caseSensitive
* @return Object matching key
* @throws SAXException
*/
public static Object getProperty(Node node, Collection.Key k,boolean caseSensitive) throws SAXException {
//String lcKey=StringUtil.toLowerCase(key);
if(k.getLowerString().startsWith("xml")) {
// Comment
if(k.equals(XMLCOMMENT)) {
StringBuffer sb=new StringBuffer();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Comment) {
sb.append(((Comment)n).getData());
}
}
return sb.toString();
}
// NS URI
if(k.equals(XMLNSURI)) {
undefinedInRoot(k,node);
return param(node.getNamespaceURI(),"");
}
// Prefix
if(k.equals(XMLNSPREFIX)) {
undefinedInRoot(k,node);
return param(node.getPrefix(),"");
}
// Root
else if(k.equals(XMLROOT)) {
Element re = getRootElement(node,caseSensitive);
if(re==null) throw new SAXException("Attribute ["+k.getString()+"] not found in XML, XML is empty");
return param(re,"");
}
// Parent
else if(k.equals(XMLPARENT)) {
Node parent = getParentNode(node,caseSensitive);
if(parent==null) {
if(node.getNodeType()==Node.DOCUMENT_NODE)
throw new SAXException("Attribute ["+k.getString()+"] not found in XML, there is no parent element, you are already at the root element");
throw new SAXException("Attribute ["+k.getString()+"] not found in XML, there is no parent element");
}
return parent;
}
// Name
else if(k.equals(XMLNAME)) {
return node.getNodeName();
}
// Value
else if(k.equals(XMLVALUE)) {
return StringUtil.toStringEmptyIfNull(node.getNodeValue());
}
// Type
else if(k.equals(XMLTYPE)) {
return getTypeAsString(node,true);
}
// Attributes
else if(k.equals(XMLATTRIBUTES)) {
NamedNodeMap attr = node.getAttributes();
if(attr==null)throw undefined(k,node);
return new XMLAttributes(node,caseSensitive);
}
// Text
else if(k.equals(XMLTEXT)) {
undefinedInRoot(k,node);
if(node instanceof Text || node instanceof CDATASection)
return ((CharacterData)node).getData();
StringBuilder sb=new StringBuilder();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Text || n instanceof CDATASection) {
sb.append(((CharacterData)n).getData());
}
}
return sb.toString();
}
// CData
else if(k.equals(XMLCDATA)) {
undefinedInRoot(k,node);
StringBuffer sb=new StringBuffer();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Text || n instanceof CDATASection) {
sb.append(((CharacterData)n).getData());
}
}
return sb.toString();
}
// Children
else if(k.equals(XMLCHILDREN)) {
return new XMLNodeList(node,caseSensitive,Node.ELEMENT_NODE);
}
// Nodes
else if(k.equals(XMLNODES)) {
return new XMLNodeList(node,caseSensitive,XMLUtil.UNDEFINED_NODE);
}
}
if(node instanceof Document) {
node=((Document)node).getDocumentElement();
if(node==null) throw new SAXException("Attribute ["+k.getString()+"] not found in XML, XML is empty");
//if((!caseSensitive && node.getNodeName().equalsIgnoreCase(k.getString())) || (caseSensitive && node.getNodeName().equals(k.getString()))) {
if(nameEqual(node, k.getString(), caseSensitive)) {
return XMLStructFactory.newInstance(node,caseSensitive);
}
}
else if(node.getNodeType()==Node.ELEMENT_NODE && Decision.isInteger(k)){
int index=Caster.toIntValue(k,0);
int count=0;
Node parent = node.getParentNode();
String nodeName=node.getNodeName();
Element[] children = XMLUtil.getChildElementsAsArray(parent);
for(int i=0;i<children.length;i++){
if(XMLUtil.nameEqual(children[i],nodeName,caseSensitive)) count++;
if(count==index) return XMLCaster.toXMLStruct(children[i],caseSensitive);
}
String detail;
if(count==0)detail="there are no Elements with this name";
else if(count==1)detail="there is only 1 Element with this name";
else detail="there are only "+count+" Elements with this name";
throw new SAXException("invalid index ["+k.getString()+"] for Element with name ["+node.getNodeName()+"], "+detail);
}
else {
List<Node> children = XMLUtil.getChildNodesAsList(node,Node.ELEMENT_NODE,caseSensitive,null);
int len=children.size();
Array array=null;//new ArrayImpl();
Element el;
XMLStruct sct=null,first=null;
for(int i=0;i<len;i++) {
el=(Element) children.get(i);// XMLCaster.toXMLStruct(getChildNode(index),caseSensitive);
if(XMLUtil.nameEqual(el,k.getString(),caseSensitive)) {
sct = XMLCaster.toXMLStruct(el,caseSensitive);
if(array!=null) {
array.appendEL(sct);
}
else if(first!=null) {
array=new ArrayImpl();
array.appendEL(first);
array.appendEL(sct);
}
else {
first=sct;
}
}
}
if(array!=null) {
try {
return new XMLMultiElementStruct(array,false);
} catch (PageException e) {}
}
if(first!=null) return first;
}
throw new SAXException("Attribute ["+k.getString()+"] not found");
}
private static SAXException undefined(Key key, Node node) {
if(node.getNodeType()==Node.DOCUMENT_NODE)
return new SAXException("you cannot address ["+key+"] on the Document Object, to address ["+key+"] from the root Node use [{variable-name}.xmlRoot."+key+"]");
return new SAXException(key+" is undefined");
}
private static void undefinedInRoot(Key key, Node node) throws SAXException {
if(node.getNodeType()==Node.DOCUMENT_NODE)
throw undefined(key, node);
}
/**
* check if given name is equal to name of the element (with and without namespace)
* @param node
* @param k
* @param caseSensitive
* @return
*/
public static boolean nameEqual(Node node, String name, boolean caseSensitive) {
if(name==null) return false;
if(caseSensitive){
return name.equals(node.getNodeName()) || name.equals(node.getLocalName());
}
return name.equalsIgnoreCase(node.getNodeName()) || name.equalsIgnoreCase(node.getLocalName());
}
public static boolean isCaseSensitve(Node node) {
if(node instanceof XMLStruct) return ((XMLStruct)node).isCaseSensitive();
return true;
}
/**
* removes child from a node
* @param node
* @param key
* @param caseSensitive
* @return removed property
*/
public static Object removeProperty(Node node, Collection.Key k,boolean caseSensitive) {
boolean isXMLChildren;
//String lcKeyx=k.getLowerString();
if(k.getLowerString().startsWith("xml")) {
// Comment
if(k.equals(XMLCOMMENT)) {
StringBuffer sb=new StringBuffer();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Comment) {
sb.append(((Comment)n).getData());
node.removeChild(XMLCaster.toRawNode(n));
}
}
return sb.toString();
}
// Text
else if(k.equals(XMLTEXT)) {
if(node instanceof Text || node instanceof CDATASection)
return ((CharacterData)node).getData();
StringBuilder sb=new StringBuilder();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Text || n instanceof CDATASection) {
sb.append(((CharacterData)n).getData());
node.removeChild(XMLCaster.toRawNode(n));
}
}
return sb.toString();
}
// children
else if((isXMLChildren=k.equals(XMLCHILDREN)) || k.equals(XMLNODES)) {
NodeList list=node.getChildNodes();
Node child;
for(int i=list.getLength()-1;i>=0;i--) {
child=XMLCaster.toRawNode(list.item(i));
if(isXMLChildren && child.getNodeType()!=Node.ELEMENT_NODE) continue;
node.removeChild(child);
}
return list;
}
}
NodeList nodes = node.getChildNodes();
Array array=new ArrayImpl();
for(int i=nodes.getLength()-1;i>=0;i--) {
Object o=nodes.item(i);
if(o instanceof Element) {
Element el=(Element) o;
if(nameEqual(el, k.getString(), caseSensitive)) {
array.appendEL(XMLCaster.toXMLStruct(el,caseSensitive));
node.removeChild(XMLCaster.toRawNode(el));
}
}
}
if(array.size()>0) {
try {
return new XMLMultiElementStruct(array,false);
} catch (PageException e) {}
}
return null;
}
private static Object param(Object o1, Object o2) {
if(o1==null)return o2;
return o1;
}
/**
* return the root Element from a node
* @param node node to get root element from
* @param caseSensitive
* @return Root Element
*/
public static Element getRootElement(Node node, boolean caseSensitive) {
Document doc=XMLUtil.getDocument(node);
Element el = doc.getDocumentElement();
if(el==null) return null;
return (Element)XMLStructFactory.newInstance(el,caseSensitive);
}
public static Node getParentNode(Node node, boolean caseSensitive) {
Node parent = node.getParentNode();
if(parent==null) return null;
return XMLStructFactory.newInstance(parent,caseSensitive);
}
/**
* returns a new Empty XMl Document
* @return new Document
* @throws ParserConfigurationException
* @throws FactoryConfigurationError
*/
public static Document newDocument() throws ParserConfigurationException, FactoryConfigurationError {
if(docBuilder==null) {
docBuilder=newDocumentBuilderFactory().newDocumentBuilder();
}
return docBuilder.newDocument();
}
/**
* return the Owner Document of a Node List
* @param nodeList
* @return XML Document
* @throws XMLException
*/
public static Document getDocument(NodeList nodeList) throws XMLException {
if(nodeList instanceof Document) return (Document)nodeList;
int len=nodeList.getLength();
for(int i=0;i<len;i++) {
Node node=nodeList.item(i);
if(node!=null) return node.getOwnerDocument();
}
throw new XMLException("can't get Document from NodeList, in NoteList are no Nodes");
}
/**
* return the Owner Document of a Node
* @param node
* @return XML Document
*/
public static Document getDocument(Node node) {
if(node instanceof Document) return (Document)node;
return node.getOwnerDocument();
}
/**
* removes child elements from a specific type
* @param node node to remove elements from
* @param type Type Definition to remove (Constant value from class Node)
* @param deep remove also in sub nodes
*/
private static void removeChildren(Node node, short type, boolean deep) {
synchronized(sync(node)){
NodeList list = node.getChildNodes();
for(int i=list.getLength();i>=0;i--) {
Node n=list.item(i);
if(n ==null )continue;
if(n.getNodeType()==type || type==UNDEFINED_NODE)node.removeChild(XMLCaster.toRawNode(n));
else if(deep)removeChildren(n,type,deep);
}
}
}
/**
* remove children from type CharacterData from a node, this includes Text,Comment and CDataSection nodes
* @param node
* @param type
* @param deep
*/
private static void removeChildCharacterData(Node node, boolean deep) {
synchronized(sync(node)){
NodeList list = node.getChildNodes();
for(int i=list.getLength();i>=0;i--) {
Node n=list.item(i);
if(n ==null )continue;
if(n instanceof CharacterData)node.removeChild(XMLCaster.toRawNode(n));
else if(deep)removeChildCharacterData(n,deep);
}
}
}
/**
* return all Children of a node by a defined type as Node List
* @param node node to get children from
* @param type type of returned node
* @param filter
* @param caseSensitive
* @return all matching child node
*/
public static ArrayNodeList getChildNodes(Node node, short type) {
return getChildNodes(node, type, false, null);
}
public static int childNodesLength(Node node, short type, boolean caseSensitive, String filter) {
synchronized(sync(node)){
NodeList nodes=node.getChildNodes();
int len=nodes.getLength();
Node n;
int count=0;
for(int i=0;i<len;i++) {
try {
n=nodes.item(i);
if(n!=null && (type==UNDEFINED_NODE || n.getNodeType()==type)){
if(filter==null || (caseSensitive?filter.equals(n.getLocalName()):filter.equalsIgnoreCase(n.getLocalName())))
count++;
}
}
catch(Throwable t) {ExceptionUtil.rethrowIfNecessary(t);}
}
return count;
}
}
public static Object sync(Node node) {
Document d = getDocument(node);
if(d!=null) return d;
return node;
}
public synchronized static ArrayNodeList getChildNodes(Node node, short type, boolean caseSensitive, String filter) {
ArrayNodeList rtn=new ArrayNodeList();
NodeList nodes=node.getChildNodes();
int len=nodes.getLength();
Node n;
for(int i=0;i<len;i++) {
try {
n=nodes.item(i);
if(n!=null && (type==UNDEFINED_NODE || n.getNodeType()==type)){
if(filter==null || (caseSensitive?filter.equals(n.getLocalName()):filter.equalsIgnoreCase(n.getLocalName())))
rtn.add(n);
}
}
catch(Throwable t) {ExceptionUtil.rethrowIfNecessary(t);}
}
return rtn;
}
public static List<Node> getChildNodesAsList(Node node, short type, boolean caseSensitive, String filter) {
synchronized(sync(node)){
List<Node> rtn=new ArrayList<Node>();
NodeList nodes=node.getChildNodes();
int len=nodes.getLength();
Node n;
for(int i=0;i<len;i++) {
try {
n=nodes.item(i);
if(n!=null && (n.getNodeType()==type|| type==UNDEFINED_NODE)){
if(filter==null || (caseSensitive?filter.equals(n.getLocalName()):filter.equalsIgnoreCase(n.getLocalName())))
rtn.add(n);
}
}
catch(Throwable t) {ExceptionUtil.rethrowIfNecessary(t);}
}
return rtn;
}
}
public static Node getChildNode(Node node, short type, boolean caseSensitive, String filter, int index) {
synchronized(sync(node)){
NodeList nodes=node.getChildNodes();
int len=nodes.getLength();
Node n;
int count=0;
for(int i=0;i<len;i++) {
try {
n=nodes.item(i);
if(n!=null && (type==UNDEFINED_NODE || n.getNodeType()==type)){
if(filter==null || (caseSensitive?filter.equals(n.getLocalName()):filter.equalsIgnoreCase(n.getLocalName()))) {
if(count==index) return n;
count++;
}
}
}
catch(Throwable t) {ExceptionUtil.rethrowIfNecessary(t);}
}
return null;
}
}
/**
* return all Children of a node by a defined type as Node Array
* @param node node to get children from
* @param type type of returned node
* @param filter
* @param caseSensitive
* @return all matching child node
*/
public static Node[] getChildNodesAsArray(Node node, short type) {
ArrayNodeList nodeList=getChildNodes(node, type);
return nodeList.toArray(new Node[nodeList.getLength()]);
}
public static Node[] getChildNodesAsArray(Node node, short type, boolean caseSensitive, String filter) {
ArrayNodeList nodeList=getChildNodes(node, type,caseSensitive,filter);
return nodeList.toArray(new Node[nodeList.getLength()]);
}
/**
* return all Element Children of a node
* @param node node to get children from
* @return all matching child node
*/
public static Element[] getChildElementsAsArray(Node node) {
ArrayNodeList nodeList=getChildNodes(node,Node.ELEMENT_NODE);
return nodeList.toArray(new Element[nodeList.getLength()]);
}
/**
* transform a XML Object to a other format, with help of a XSL Stylesheet
* @param xml xml to convert
* @param xsl xsl used to convert
* @return resulting string
* @throws TransformerException
* @throws SAXException
* @throws IOException
*/
public static String transform(InputSource xml, InputSource xsl) throws TransformerException, SAXException, IOException {
return transform( parse( xml, null ,false ), xsl, null );
}
/**
* transform a XML Object to a other format, with help of a XSL Stylesheet
* @param xml xml to convert
* @param xsl xsl used to convert
* @param parameters parameters used to convert
* @return resulting string
* @throws TransformerException
* @throws SAXException
* @throws IOException
*/
public static String transform(InputSource xml, InputSource xsl, Map<String,Object> parameters) throws TransformerException, SAXException, IOException {
return transform( parse( xml, null, false ), xsl, parameters );
}
/**
* transform a XML Document to a other format, with help of a XSL Stylesheet
* @param xml xml to convert
* @param xsl xsl used to convert
* @return resulting string
* @throws TransformerException
* @throws SAXException
* @throws IOException
*/
public static String transform( Document doc, InputSource xsl ) throws TransformerException {
return transform( doc, xsl, null );
}
/**
* transform a XML Document to a other format, with help of a XSL Stylesheet
* @param xml xml to convert
* @param xsl xsl used to convert
* @param parameters parameters used to convert
* @return resulting string
* @throws TransformerException
* @throws SAXException
* @throws IOException
*/
public static String transform(Document doc, InputSource xsl, Map<String,Object> parameters) throws TransformerException {
StringWriter sw = new StringWriter();
TransformerFactory factory = XMLUtil.getTransformerFactory();
factory.setErrorListener(SimpleErrorListener.THROW_FATAL);
Transformer transformer = factory.newTransformer(new StreamSource(xsl.getCharacterStream()));
if (parameters != null) {
Iterator<Entry<String, Object>> it = parameters.entrySet().iterator();
Entry<String, Object> e;
while ( it.hasNext() ) {
e = it.next();
transformer.setParameter(e.getKey(), e.getValue());
}
}
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
}
/**
* returns the Node Type As String
* @param node
* @param cftype
* @return
*/
public static String getTypeAsString(Node node, boolean cftype) {
String suffix=cftype?"":"_NODE";
switch(node.getNodeType()) {
case Node.ATTRIBUTE_NODE: return "ATTRIBUTE"+suffix;
case Node.CDATA_SECTION_NODE: return "CDATA_SECTION"+suffix;
case Node.COMMENT_NODE: return "COMMENT"+suffix;
case Node.DOCUMENT_FRAGMENT_NODE: return "DOCUMENT_FRAGMENT"+suffix;
case Node.DOCUMENT_NODE: return "DOCUMENT"+suffix;
case Node.DOCUMENT_TYPE_NODE: return "DOCUMENT_TYPE"+suffix;
case Node.ELEMENT_NODE: return "ELEMENT"+suffix;
case Node.ENTITY_NODE: return "ENTITY"+suffix;
case Node.ENTITY_REFERENCE_NODE: return "ENTITY_REFERENCE"+suffix;
case Node.NOTATION_NODE: return "NOTATION"+suffix;
case Node.PROCESSING_INSTRUCTION_NODE: return "PROCESSING_INSTRUCTION"+suffix;
case Node.TEXT_NODE: return "TEXT"+suffix;
default: return "UNKNOW"+suffix;
}
}
public static Element getChildWithName(String name, Element el) {
synchronized(sync(el)){
Element[] children = XMLUtil.getChildElementsAsArray(el);
for(int i=0;i<children.length;i++) {
if(name.equalsIgnoreCase(children[i].getNodeName()))
return children[i];
}
}
return null;
}
public static InputSource toInputSource(Resource res, Charset cs) throws IOException {
String str = IOUtil.toString((res), cs);
return new InputSource(new StringReader(str));
}
public static InputSource toInputSource(PageContext pc, Object value) throws IOException, ExpressionException {
if(value instanceof InputSource) {
return (InputSource) value;
}
if(value instanceof String) {
return toInputSource(pc, (String)value);
}
if(value instanceof StringBuffer) {
return toInputSource(pc, value.toString());
}
if(value instanceof Resource) {
String str = IOUtil.toString(((Resource)value), (Charset)null);
return new InputSource(new StringReader(str));
}
if(value instanceof File) {
String str = IOUtil.toString(ResourceUtil.toResource(((File)value)),(Charset)null);
return new InputSource(new StringReader(str));
}
if(value instanceof InputStream) {
InputStream is = (InputStream)value;
try {
String str = IOUtil.toString(is, (Charset)null);
return new InputSource(new StringReader(str));
}
finally {
IOUtil.closeEL(is);
}
}
if(value instanceof Reader) {
Reader reader = (Reader)value;
try {
String str = IOUtil.toString(reader);
return new InputSource(new StringReader(str));
}
finally {
IOUtil.closeEL(reader);
}
}
if(value instanceof byte[]) {
return new InputSource(new ByteArrayInputStream((byte[])value));
}
throw new ExpressionException("cat cast object of type ["+Caster.toClassName(value)+"] to a Input for xml parser");
}
public static InputSource toInputSource(PageContext pc, String xml) throws IOException, ExpressionException {
return toInputSource(pc, xml,true);
}
public static InputSource toInputSource(PageContext pc, String xml, boolean canBePath) throws IOException, ExpressionException {
// xml text
xml=xml.trim();
if(!canBePath || xml.startsWith("<") || xml.length()>2000 || StringUtil.isEmpty(xml,true)) {
return new InputSource(new StringReader(xml));
}
// xml link
pc=ThreadLocalPageContext.get(pc);
Resource res = ResourceUtil.toResourceExisting(pc, xml);
return toInputSource(pc, res);
}
public static Struct validate(InputSource xml, InputSource schema, String strSchema) throws XMLException {
return new XMLValidator(schema,strSchema).validate(xml);
}
/**
* adds a child at the first place
* @param parent
* @param child
*/
public static void prependChild(Element parent, Element child) {
Node first = parent.getFirstChild();
if(first==null)parent.appendChild(child);
else {
parent.insertBefore(child, first);
}
}
public static void setFirst(Node parent, Node node) {
Node first = parent.getFirstChild();
if(first!=null) parent.insertBefore(node, first);
else parent.appendChild(node);
}
public static XMLReader createXMLReader() throws SAXException {
/*if(optionalDefaultSaxParser==null)
optionalDefaultSaxParser=DEFAULT_SAX_PARSER;
try{
return XMLReaderFactory.createXMLReader();
}
catch(Throwable t){
ExceptionUtil.rethrowIfNecessary(t);
return XMLReaderFactory.createXMLReader();
}*/
return XMLReaderFactory.createXMLReader();
}
public static Document createDocument(Resource res, boolean isHTML) throws SAXException, IOException {
InputStream is=null;
try {
return parse(toInputSource(res, null),null,isHTML);
}
finally {
IOUtil.closeEL(is);
}
}
public static Document createDocument(String xml, boolean isHTML) throws SAXException, IOException {
return parse(toInputSource(xml),null,isHTML);
}
public static Document createDocument(InputStream is, boolean isHTML) throws SAXException, IOException {
return parse(new InputSource(is),null,isHTML);
}
public static InputSource toInputSource(Object value) throws IOException {
if(value instanceof InputSource) {
return (InputSource) value;
}
if(value instanceof String) {
return toInputSource((String)value);
}
if(value instanceof StringBuffer) {
return toInputSource(value.toString());
}
if(value instanceof Resource) {
String str = IOUtil.toString(((Resource)value), (Charset)null);
return new InputSource(new StringReader(str));
}
if(value instanceof File) {
FileInputStream fis = new FileInputStream((File)value);
try {
return toInputSource(fis);
}
finally {
IOUtil.closeEL(fis);
}
}
if(value instanceof InputStream) {
InputStream is = (InputStream)value;
try {
String str = IOUtil.toString(is, (Charset)null);
return new InputSource(new StringReader(str));
}
finally {
IOUtil.closeEL(is);
}
}
if(value instanceof Reader) {
Reader reader = (Reader)value;
try {
String str = IOUtil.toString(reader);
return new InputSource(new StringReader(str));
}
finally {
IOUtil.closeEL(reader);
}
}
if(value instanceof byte[]) {
return new InputSource(new ByteArrayInputStream((byte[])value));
}
throw new IOException("cat cast object of type ["+value+"] to a Input for xml parser");
}
public static InputSource toInputSource(String xml) throws IOException {
return new InputSource(new StringReader(xml.trim()));
}
}
|
core/src/main/java/lucee/runtime/text/xml/XMLUtil.java
|
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* 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, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.text.xml;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import lucee.commons.io.IOUtil;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.StringUtil;
import lucee.runtime.PageContext;
import lucee.runtime.config.ConfigImpl;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.exp.XMLException;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.osgi.EnvClassLoader;
import lucee.runtime.text.xml.struct.XMLMultiElementStruct;
import lucee.runtime.text.xml.struct.XMLStruct;
import lucee.runtime.text.xml.struct.XMLStructFactory;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Struct;
import org.apache.xalan.processor.TransformerFactoryImpl;
import org.ccil.cowan.tagsoup.Parser;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
*
*/
public final class XMLUtil {
public static final short UNDEFINED_NODE=-1;
//public final static String DEFAULT_SAX_PARSER="org.apache.xerces.parsers.SAXParser";
public static final Collection.Key XMLCOMMENT = KeyImpl.intern("xmlcomment");
public static final Collection.Key XMLTEXT = KeyImpl.intern("xmltext");
public static final Collection.Key XMLCDATA = KeyImpl.intern("xmlcdata");
public static final Collection.Key XMLCHILDREN = KeyImpl.intern("xmlchildren");
public static final Collection.Key XMLNODES = KeyImpl.intern("xmlnodes");
public static final Collection.Key XMLNSURI = KeyImpl.intern("xmlnsuri");
public static final Collection.Key XMLNSPREFIX = KeyImpl.intern("xmlnsprefix");
public static final Collection.Key XMLROOT = KeyImpl.intern("xmlroot");
public static final Collection.Key XMLPARENT = KeyImpl.intern("xmlparent");
public static final Collection.Key XMLNAME = KeyImpl.intern("xmlname");
public static final Collection.Key XMLTYPE = KeyImpl.intern("xmltype");
public static final Collection.Key XMLVALUE = KeyImpl.intern("xmlvalue");
public static final Collection.Key XMLATTRIBUTES = KeyImpl.intern("xmlattributes");
/*
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
private static final Collection.Key = KeyImpl.getInstance();
*/
//static DOMParser parser = new DOMParser();
private static DocumentBuilder docBuilder;
//private static DocumentBuilderFactory factory;
private static TransformerFactory transformerFactory;
public static String unescapeXMLString(String str) {
StringBuffer rtn=new StringBuffer();
int posStart=-1;
int posFinish=-1;
while((posStart=str.indexOf('&',posStart))!=-1) {
int last=posFinish+1;
posFinish=str.indexOf(';',posStart);
if(posFinish==-1)break;
rtn.append(str.substring(last,posStart));
if(posStart+1<posFinish) {
rtn.append(unescapeXMLEntity(str.substring(posStart+1,posFinish)));
}
else {
rtn.append("&;");
}
posStart=posFinish+1;
}
rtn.append(str.substring(posFinish+1));
return rtn.toString();
}
public static String unescapeXMLString2(String str) {
StringBuffer sb=new StringBuffer();
int index,last=0,indexSemi;
while((index=str.indexOf('&',last))!=-1) {
sb.append(str.substring(last,index));
indexSemi=str.indexOf(';',index+1);
if(indexSemi==-1) {
sb.append('&');
last=index+1;
}
else if(index+1==indexSemi) {
sb.append("&;");
last=index+2;
}
else {
sb.append(unescapeXMLEntity(str.substring(index+1,indexSemi)));
last=indexSemi+1;
}
}
sb.append(str.substring(last));
return sb.toString();
}
private static String unescapeXMLEntity(String str) {
if("lt".equals(str)) return "<";
if("gt".equals(str)) return ">";
if("amp".equals(str)) return "&";
if("apos".equals(str)) return "'";
if("quot".equals(str)) return "\"";
return "&"+str+";";
}
public static String escapeXMLString(String xmlStr) {
char c;
StringBuffer sb=new StringBuffer();
int len=xmlStr.length();
for(int i=0;i<len;i++) {
c=xmlStr.charAt(i);
if(c=='<') sb.append("<");
else if(c=='>') sb.append(">");
else if(c=='&') sb.append("&");
//else if(c=='\'') sb.append("&");
else if(c=='"') sb.append(""");
//else if(c>127) sb.append("&#"+((int)c)+";");
else sb.append(c);
}
return sb.toString();
}
/**
* @return returns a singelton TransformerFactory
*/
public static TransformerFactory getTransformerFactory() {
Thread.currentThread().setContextClassLoader(new EnvClassLoader((ConfigImpl)ThreadLocalPageContext.getConfig())); // TODO make this global
//if(transformerFactory==null)transformerFactory=TransformerFactory.newInstance();
if(transformerFactory==null)transformerFactory=new TransformerFactoryImpl();
return transformerFactory;
}
public static final Document parse(InputSource xml,InputSource validator, boolean isHtml)
throws SAXException, IOException {
return parse(xml, validator, new XMLEntityResolverDefaultHandler(validator), isHtml);
}
/**
* parse XML/HTML String to a XML DOM representation
* @param xml XML InputSource
* @param isHtml is a HTML or XML Object
* @return parsed Document
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
*/
public static final Document parse(InputSource xml,InputSource validator, EntityResolver entRes, boolean isHtml)
throws SAXException, IOException {
if(!isHtml) {
DocumentBuilderFactory factory = newDocumentBuilderFactory();
if(validator==null) {
XMLUtil.setAttributeEL(factory,XMLConstants.NON_VALIDATING_DTD_EXTERNAL, Boolean.FALSE);
XMLUtil.setAttributeEL(factory,XMLConstants.NON_VALIDATING_DTD_GRAMMAR, Boolean.FALSE);
}
else {
XMLUtil.setAttributeEL(factory,XMLConstants.VALIDATION_SCHEMA, Boolean.TRUE);
XMLUtil.setAttributeEL(factory,XMLConstants.VALIDATION_SCHEMA_FULL_CHECKING, Boolean.TRUE);
}
factory.setNamespaceAware(true);
factory.setValidating(validator!=null);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
if(entRes!=null)builder.setEntityResolver(entRes);
builder.setErrorHandler(new ThrowingErrorHandler(true,true,false));
return builder.parse(xml);
}
catch (ParserConfigurationException e) {
throw new SAXException(e);
}
}
XMLReader reader = new Parser();
reader.setFeature(Parser.namespacesFeature, true);
reader.setFeature(Parser.namespacePrefixesFeature, true);
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
transformer.transform(new SAXSource(reader, xml), result);
return XMLUtil.getDocument(result.getNode());
}
catch (Exception e) {
throw new SAXException(e);
}
}
private static DocumentBuilderFactory newDocumentBuilderFactory() {
return DocumentBuilderFactory.newInstance();
//return new DocumentBuilderFactoryImpl();
// we do not use DocumentBuilderFactory.newInstance(); because it is unpredictable
}
private static void setAttributeEL(DocumentBuilderFactory factory,String name, Object value) {
try{
factory.setAttribute(name, value);
}
catch(Throwable t){ExceptionUtil.rethrowIfNecessary(t);}
}
/**
* sets a node to a node (Expression Less)
* @param node
* @param key
* @param value
* @return Object set
*/
public static Object setPropertyEL(Node node, Collection.Key key, Object value) {
try {
return setProperty(node,key,value);
} catch (PageException e) {
return null;
}
}
public static Object setProperty(Node node, Collection.Key key, Object value,boolean caseSensitive, Object defaultValue) {
try {
return setProperty(node,key,value,caseSensitive);
} catch (PageException e) {
return defaultValue;
}
}
/**
* sets a node to a node
* @param node
* @param key
* @param value
* @return Object set
* @throws PageException
*/
public static Object setProperty(Node node, Collection.Key k, Object value) throws PageException {
return setProperty(node, k, value, isCaseSensitve(node));
}
public static Object setProperty(Node node, Collection.Key k, Object value,boolean caseSensitive) throws PageException {
Document doc=getDocument(node);
boolean isXMLChildren;
// Comment
if(k.equals(XMLCOMMENT)) {
removeChildren(XMLCaster.toRawNode(node),Node.COMMENT_NODE,false);
node.appendChild(XMLCaster.toRawNode(XMLCaster.toComment(doc,value)));
}
// NS URI
else if(k.equals(XMLNSURI)) {
// TODO impl
throw new ExpressionException("XML NS URI can't be set","not implemented");
}
// Prefix
else if(k.equals(XMLNSPREFIX)) {
// TODO impl
throw new ExpressionException("XML NS Prefix can't be set","not implemented");
//node.setPrefix(Caster.toString(value));
}
// Root
else if(k.equals(XMLROOT)) {
doc.appendChild(XMLCaster.toNode(doc,value,false));
}
// Parent
else if(k.equals(XMLPARENT)) {
Node parent = getParentNode(node,caseSensitive);
Key name = KeyImpl.init(parent.getNodeName());
parent = getParentNode(parent,caseSensitive);
if(parent==null)
throw new ExpressionException("there is no parent element, you are already on the root element");
return setProperty(parent, name, value, caseSensitive);
}
// Name
else if(k.equals(XMLNAME)) {
throw new XMLException("You can't assign a new value for the property [xmlname]");
}
// Type
else if(k.equals(XMLTYPE)) {
throw new XMLException("You can't change type of a xml node [xmltype]");
}
// value
else if(k.equals(XMLVALUE)) {
node.setNodeValue(Caster.toString(value));
}
// Attributes
else if(k.equals(XMLATTRIBUTES)) {
Element parent=XMLCaster.toElement(doc,node);
Attr[] attres=XMLCaster.toAttrArray(doc,value);
//print.ln("=>"+value);
for(int i=0;i<attres.length;i++) {
if(attres[i]!=null) {
parent.setAttributeNode(attres[i]);
//print.ln(attres[i].getName()+"=="+attres[i].getValue());
}
}
}
// Text
else if(k.equals(XMLTEXT)) {
removeChildCharacterData(XMLCaster.toRawNode(node),false);
node.appendChild(XMLCaster.toRawNode(XMLCaster.toText(doc,value)));
}
// CData
else if(k.equals(XMLCDATA)) {
removeChildCharacterData(XMLCaster.toRawNode(node),false);
node.appendChild(XMLCaster.toRawNode(XMLCaster.toCDATASection(doc,value)));
}
// Children
else if((isXMLChildren=k.equals(XMLCHILDREN)) || k.equals(XMLNODES)) {
Node[] nodes=XMLCaster.toNodeArray(doc,value);
removeChildren(XMLCaster.toRawNode(node),isXMLChildren?Node.ELEMENT_NODE:XMLUtil.UNDEFINED_NODE,false);
for(int i=0;i<nodes.length;i++) {
if(nodes[i]==node) throw new XMLException("can't assign a XML Node to himself");
if(nodes[i]!=null)node.appendChild(XMLCaster.toRawNode(nodes[i]));
}
}
else {
boolean isIndex=false;
Node child = XMLCaster.toNode(doc,value,false);
if(!k.getString().equalsIgnoreCase(child.getNodeName()) && !(isIndex=Decision.isInteger(k))) {
throw new XMLException("if you assign a XML Element to a XMLStruct , assignment property must have same name like XML Node Name", "Property Name is "+k.getString()+" and XML Element Name is "+child.getNodeName());
}
Node n;
// by index
if(isIndex) {
NodeList list = XMLUtil.getChildNodes(node.getParentNode(), Node.ELEMENT_NODE,true,node.getNodeName());
int len = list.getLength();
int index=Caster.toIntValue(k);
if(index>len || index<1){
String detail=len>1?
"your index is "+index+", but there are only "+len+" child elements":
"your index is "+index+", but there is only "+len+" child element";
throw new XMLException("index is out of range", detail);
}
n=list.item(index-1);
XMLUtil.replaceChild(child, n);
return value;
}
NodeList list = XMLUtil.getChildNodes(node, Node.ELEMENT_NODE);
int len = list.getLength();
// by name
for(int i=0;i<len;i++) {
n=list.item(i);
if(nameEqual(n, k.getString(), caseSensitive)) {
XMLUtil.replaceChild(child, n);
return value;
}
}
node.appendChild(XMLCaster.toRawNode(child));
}
return value;
}
public static void replaceChild(Node newChild, Node oldChild) {
Node nc = XMLCaster.toRawNode(newChild);
Node oc = XMLCaster.toRawNode(oldChild);
Node p = oc.getParentNode();
if(nc!=oc)p.replaceChild(nc, oc);
}
public static Object getProperty(Node node, Collection.Key key, Object defaultValue) {
return getProperty(node, key,isCaseSensitve(node),defaultValue);
}
/**
* returns a property from a XMl Node (Expression Less)
* @param node
* @param key
* @param caseSensitive
* @return Object matching key
*/
public static Object getProperty(Node node, Collection.Key k,boolean caseSensitive, Object defaultValue) {
try {
return getProperty(node, k,caseSensitive);
} catch (SAXException e) {
return defaultValue;
}
}
public static Object getProperty(Node node, Collection.Key key) throws SAXException {
return getProperty(node, key,isCaseSensitve(node));
}
/**
* returns a property from a XMl Node
* @param node
* @param key
* @param caseSensitive
* @return Object matching key
* @throws SAXException
*/
public static Object getProperty(Node node, Collection.Key k,boolean caseSensitive) throws SAXException {
//String lcKey=StringUtil.toLowerCase(key);
if(k.getLowerString().startsWith("xml")) {
// Comment
if(k.equals(XMLCOMMENT)) {
StringBuffer sb=new StringBuffer();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Comment) {
sb.append(((Comment)n).getData());
}
}
return sb.toString();
}
// NS URI
if(k.equals(XMLNSURI)) {
undefinedInRoot(k,node);
return param(node.getNamespaceURI(),"");
}
// Prefix
if(k.equals(XMLNSPREFIX)) {
undefinedInRoot(k,node);
return param(node.getPrefix(),"");
}
// Root
else if(k.equals(XMLROOT)) {
Element re = getRootElement(node,caseSensitive);
if(re==null) throw new SAXException("Attribute ["+k.getString()+"] not found in XML, XML is empty");
return param(re,"");
}
// Parent
else if(k.equals(XMLPARENT)) {
Node parent = getParentNode(node,caseSensitive);
if(parent==null) {
if(node.getNodeType()==Node.DOCUMENT_NODE)
throw new SAXException("Attribute ["+k.getString()+"] not found in XML, there is no parent element, you are already at the root element");
throw new SAXException("Attribute ["+k.getString()+"] not found in XML, there is no parent element");
}
return parent;
}
// Name
else if(k.equals(XMLNAME)) {
return node.getNodeName();
}
// Value
else if(k.equals(XMLVALUE)) {
return StringUtil.toStringEmptyIfNull(node.getNodeValue());
}
// Type
else if(k.equals(XMLTYPE)) {
return getTypeAsString(node,true);
}
// Attributes
else if(k.equals(XMLATTRIBUTES)) {
NamedNodeMap attr = node.getAttributes();
if(attr==null)throw undefined(k,node);
return new XMLAttributes(node,caseSensitive);
}
// Text
else if(k.equals(XMLTEXT)) {
undefinedInRoot(k,node);
if(node instanceof Text || node instanceof CDATASection)
return ((CharacterData)node).getData();
StringBuilder sb=new StringBuilder();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Text || n instanceof CDATASection) {
sb.append(((CharacterData)n).getData());
}
}
return sb.toString();
}
// CData
else if(k.equals(XMLCDATA)) {
undefinedInRoot(k,node);
StringBuffer sb=new StringBuffer();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Text || n instanceof CDATASection) {
sb.append(((CharacterData)n).getData());
}
}
return sb.toString();
}
// Children
else if(k.equals(XMLCHILDREN)) {
return new XMLNodeList(node,caseSensitive,Node.ELEMENT_NODE);
}
// Nodes
else if(k.equals(XMLNODES)) {
return new XMLNodeList(node,caseSensitive,XMLUtil.UNDEFINED_NODE);
}
}
if(node instanceof Document) {
node=((Document)node).getDocumentElement();
if(node==null) throw new SAXException("Attribute ["+k.getString()+"] not found in XML, XML is empty");
//if((!caseSensitive && node.getNodeName().equalsIgnoreCase(k.getString())) || (caseSensitive && node.getNodeName().equals(k.getString()))) {
if(nameEqual(node, k.getString(), caseSensitive)) {
return XMLStructFactory.newInstance(node,caseSensitive);
}
}
else if(node.getNodeType()==Node.ELEMENT_NODE && Decision.isInteger(k)){
int index=Caster.toIntValue(k,0);
int count=0;
Node parent = node.getParentNode();
String nodeName=node.getNodeName();
Element[] children = XMLUtil.getChildElementsAsArray(parent);
for(int i=0;i<children.length;i++){
if(XMLUtil.nameEqual(children[i],nodeName,caseSensitive)) count++;
if(count==index) return XMLCaster.toXMLStruct(children[i],caseSensitive);
}
String detail;
if(count==0)detail="there are no Elements with this name";
else if(count==1)detail="there is only 1 Element with this name";
else detail="there are only "+count+" Elements with this name";
throw new SAXException("invalid index ["+k.getString()+"] for Element with name ["+node.getNodeName()+"], "+detail);
}
else {
List<Node> children = XMLUtil.getChildNodesAsList(node,Node.ELEMENT_NODE,caseSensitive,null);
int len=children.size();
Array array=null;//new ArrayImpl();
Element el;
XMLStruct sct=null,first=null;
for(int i=0;i<len;i++) {
el=(Element) children.get(i);// XMLCaster.toXMLStruct(getChildNode(index),caseSensitive);
if(XMLUtil.nameEqual(el,k.getString(),caseSensitive)) {
sct = XMLCaster.toXMLStruct(el,caseSensitive);
if(array!=null) {
array.appendEL(sct);
}
else if(first!=null) {
array=new ArrayImpl();
array.appendEL(first);
array.appendEL(sct);
}
else {
first=sct;
}
}
}
if(array!=null) {
try {
return new XMLMultiElementStruct(array,false);
} catch (PageException e) {}
}
if(first!=null) return first;
}
throw new SAXException("Attribute ["+k.getString()+"] not found");
}
private static SAXException undefined(Key key, Node node) {
if(node.getNodeType()==Node.DOCUMENT_NODE)
return new SAXException("you cannot address ["+key+"] on the Document Object, to address ["+key+"] from the root Node use [{variable-name}.xmlRoot."+key+"]");
return new SAXException(key+" is undefined");
}
private static void undefinedInRoot(Key key, Node node) throws SAXException {
if(node.getNodeType()==Node.DOCUMENT_NODE)
throw undefined(key, node);
}
/**
* check if given name is equal to name of the element (with and without namespace)
* @param node
* @param k
* @param caseSensitive
* @return
*/
public static boolean nameEqual(Node node, String name, boolean caseSensitive) {
if(name==null) return false;
if(caseSensitive){
return name.equals(node.getNodeName()) || name.equals(node.getLocalName());
}
return name.equalsIgnoreCase(node.getNodeName()) || name.equalsIgnoreCase(node.getLocalName());
}
public static boolean isCaseSensitve(Node node) {
if(node instanceof XMLStruct) return ((XMLStruct)node).isCaseSensitive();
return true;
}
/**
* removes child from a node
* @param node
* @param key
* @param caseSensitive
* @return removed property
*/
public static Object removeProperty(Node node, Collection.Key k,boolean caseSensitive) {
boolean isXMLChildren;
//String lcKeyx=k.getLowerString();
if(k.getLowerString().startsWith("xml")) {
// Comment
if(k.equals(XMLCOMMENT)) {
StringBuffer sb=new StringBuffer();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Comment) {
sb.append(((Comment)n).getData());
node.removeChild(XMLCaster.toRawNode(n));
}
}
return sb.toString();
}
// Text
else if(k.equals(XMLTEXT)) {
if(node instanceof Text || node instanceof CDATASection)
return ((CharacterData)node).getData();
StringBuilder sb=new StringBuilder();
NodeList list = node.getChildNodes();
int len=list.getLength();
for(int i=0;i<len;i++) {
Node n=list.item(i);
if(n instanceof Text || n instanceof CDATASection) {
sb.append(((CharacterData)n).getData());
node.removeChild(XMLCaster.toRawNode(n));
}
}
return sb.toString();
}
// children
else if((isXMLChildren=k.equals(XMLCHILDREN)) || k.equals(XMLNODES)) {
NodeList list=node.getChildNodes();
Node child;
for(int i=list.getLength()-1;i>=0;i--) {
child=XMLCaster.toRawNode(list.item(i));
if(isXMLChildren && child.getNodeType()!=Node.ELEMENT_NODE) continue;
node.removeChild(child);
}
return list;
}
}
NodeList nodes = node.getChildNodes();
Array array=new ArrayImpl();
for(int i=nodes.getLength()-1;i>=0;i--) {
Object o=nodes.item(i);
if(o instanceof Element) {
Element el=(Element) o;
if(nameEqual(el, k.getString(), caseSensitive)) {
array.appendEL(XMLCaster.toXMLStruct(el,caseSensitive));
node.removeChild(XMLCaster.toRawNode(el));
}
}
}
if(array.size()>0) {
try {
return new XMLMultiElementStruct(array,false);
} catch (PageException e) {}
}
return null;
}
private static Object param(Object o1, Object o2) {
if(o1==null)return o2;
return o1;
}
/**
* return the root Element from a node
* @param node node to get root element from
* @param caseSensitive
* @return Root Element
*/
public static Element getRootElement(Node node, boolean caseSensitive) {
Document doc=XMLUtil.getDocument(node);
Element el = doc.getDocumentElement();
if(el==null) return null;
return (Element)XMLStructFactory.newInstance(el,caseSensitive);
}
public static Node getParentNode(Node node, boolean caseSensitive) {
Node parent = node.getParentNode();
if(parent==null) return null;
return XMLStructFactory.newInstance(parent,caseSensitive);
}
/**
* returns a new Empty XMl Document
* @return new Document
* @throws ParserConfigurationException
* @throws FactoryConfigurationError
*/
public static Document newDocument() throws ParserConfigurationException, FactoryConfigurationError {
if(docBuilder==null) {
docBuilder=newDocumentBuilderFactory().newDocumentBuilder();
}
return docBuilder.newDocument();
}
/**
* return the Owner Document of a Node List
* @param nodeList
* @return XML Document
* @throws XMLException
*/
public static Document getDocument(NodeList nodeList) throws XMLException {
if(nodeList instanceof Document) return (Document)nodeList;
int len=nodeList.getLength();
for(int i=0;i<len;i++) {
Node node=nodeList.item(i);
if(node!=null) return node.getOwnerDocument();
}
throw new XMLException("can't get Document from NodeList, in NoteList are no Nodes");
}
/**
* return the Owner Document of a Node
* @param node
* @return XML Document
*/
public static Document getDocument(Node node) {
if(node instanceof Document) return (Document)node;
return node.getOwnerDocument();
}
/**
* removes child elements from a specific type
* @param node node to remove elements from
* @param type Type Definition to remove (Constant value from class Node)
* @param deep remove also in sub nodes
*/
private static void removeChildren(Node node, short type, boolean deep) {
synchronized(sync(node)){
NodeList list = node.getChildNodes();
for(int i=list.getLength();i>=0;i--) {
Node n=list.item(i);
if(n ==null )continue;
if(n.getNodeType()==type || type==UNDEFINED_NODE)node.removeChild(XMLCaster.toRawNode(n));
else if(deep)removeChildren(n,type,deep);
}
}
}
/**
* remove children from type CharacterData from a node, this includes Text,Comment and CDataSection nodes
* @param node
* @param type
* @param deep
*/
private static void removeChildCharacterData(Node node, boolean deep) {
synchronized(sync(node)){
NodeList list = node.getChildNodes();
for(int i=list.getLength();i>=0;i--) {
Node n=list.item(i);
if(n ==null )continue;
if(n instanceof CharacterData)node.removeChild(XMLCaster.toRawNode(n));
else if(deep)removeChildCharacterData(n,deep);
}
}
}
/**
* return all Children of a node by a defined type as Node List
* @param node node to get children from
* @param type type of returned node
* @param filter
* @param caseSensitive
* @return all matching child node
*/
public static ArrayNodeList getChildNodes(Node node, short type) {
return getChildNodes(node, type, false, null);
}
public static int childNodesLength(Node node, short type, boolean caseSensitive, String filter) {
synchronized(sync(node)){
NodeList nodes=node.getChildNodes();
int len=nodes.getLength();
Node n;
int count=0;
for(int i=0;i<len;i++) {
try {
n=nodes.item(i);
if(n!=null && (type==UNDEFINED_NODE || n.getNodeType()==type)){
if(filter==null || (caseSensitive?filter.equals(n.getLocalName()):filter.equalsIgnoreCase(n.getLocalName())))
count++;
}
}
catch(Throwable t) {ExceptionUtil.rethrowIfNecessary(t);}
}
return count;
}
}
public static Object sync(Node node) {
Document d = getDocument(node);
if(d!=null) return d;
return node;
}
public synchronized static ArrayNodeList getChildNodes(Node node, short type, boolean caseSensitive, String filter) {
ArrayNodeList rtn=new ArrayNodeList();
NodeList nodes=node.getChildNodes();
int len=nodes.getLength();
Node n;
for(int i=0;i<len;i++) {
try {
n=nodes.item(i);
if(n!=null && (type==UNDEFINED_NODE || n.getNodeType()==type)){
if(filter==null || (caseSensitive?filter.equals(n.getLocalName()):filter.equalsIgnoreCase(n.getLocalName())))
rtn.add(n);
}
}
catch(Throwable t) {ExceptionUtil.rethrowIfNecessary(t);}
}
return rtn;
}
public static List<Node> getChildNodesAsList(Node node, short type, boolean caseSensitive, String filter) {
synchronized(sync(node)){
List<Node> rtn=new ArrayList<Node>();
NodeList nodes=node.getChildNodes();
int len=nodes.getLength();
Node n;
for(int i=0;i<len;i++) {
try {
n=nodes.item(i);
if(n!=null && (n.getNodeType()==type|| type==UNDEFINED_NODE)){
if(filter==null || (caseSensitive?filter.equals(n.getLocalName()):filter.equalsIgnoreCase(n.getLocalName())))
rtn.add(n);
}
}
catch(Throwable t) {ExceptionUtil.rethrowIfNecessary(t);}
}
return rtn;
}
}
public static Node getChildNode(Node node, short type, boolean caseSensitive, String filter, int index) {
synchronized(sync(node)){
NodeList nodes=node.getChildNodes();
int len=nodes.getLength();
Node n;
int count=0;
for(int i=0;i<len;i++) {
try {
n=nodes.item(i);
if(n!=null && (type==UNDEFINED_NODE || n.getNodeType()==type)){
if(filter==null || (caseSensitive?filter.equals(n.getLocalName()):filter.equalsIgnoreCase(n.getLocalName()))) {
if(count==index) return n;
count++;
}
}
}
catch(Throwable t) {ExceptionUtil.rethrowIfNecessary(t);}
}
return null;
}
}
/**
* return all Children of a node by a defined type as Node Array
* @param node node to get children from
* @param type type of returned node
* @param filter
* @param caseSensitive
* @return all matching child node
*/
public static Node[] getChildNodesAsArray(Node node, short type) {
ArrayNodeList nodeList=getChildNodes(node, type);
return nodeList.toArray(new Node[nodeList.getLength()]);
}
public static Node[] getChildNodesAsArray(Node node, short type, boolean caseSensitive, String filter) {
ArrayNodeList nodeList=getChildNodes(node, type,caseSensitive,filter);
return nodeList.toArray(new Node[nodeList.getLength()]);
}
/**
* return all Element Children of a node
* @param node node to get children from
* @return all matching child node
*/
public static Element[] getChildElementsAsArray(Node node) {
ArrayNodeList nodeList=getChildNodes(node,Node.ELEMENT_NODE);
return nodeList.toArray(new Element[nodeList.getLength()]);
}
/**
* transform a XML Object to a other format, with help of a XSL Stylesheet
* @param xml xml to convert
* @param xsl xsl used to convert
* @return resulting string
* @throws TransformerException
* @throws SAXException
* @throws IOException
*/
public static String transform(InputSource xml, InputSource xsl) throws TransformerException, SAXException, IOException {
return transform( parse( xml, null ,false ), xsl, null );
}
/**
* transform a XML Object to a other format, with help of a XSL Stylesheet
* @param xml xml to convert
* @param xsl xsl used to convert
* @param parameters parameters used to convert
* @return resulting string
* @throws TransformerException
* @throws SAXException
* @throws IOException
*/
public static String transform(InputSource xml, InputSource xsl, Map<String,Object> parameters) throws TransformerException, SAXException, IOException {
return transform( parse( xml, null, false ), xsl, parameters );
}
/**
* transform a XML Document to a other format, with help of a XSL Stylesheet
* @param xml xml to convert
* @param xsl xsl used to convert
* @return resulting string
* @throws TransformerException
* @throws SAXException
* @throws IOException
*/
public static String transform( Document doc, InputSource xsl ) throws TransformerException {
return transform( doc, xsl, null );
}
/**
* transform a XML Document to a other format, with help of a XSL Stylesheet
* @param xml xml to convert
* @param xsl xsl used to convert
* @param parameters parameters used to convert
* @return resulting string
* @throws TransformerException
* @throws SAXException
* @throws IOException
*/
public static String transform(Document doc, InputSource xsl, Map<String,Object> parameters) throws TransformerException {
StringWriter sw = new StringWriter();
TransformerFactory factory = XMLUtil.getTransformerFactory();
factory.setErrorListener(SimpleErrorListener.THROW_FATAL);
Transformer transformer = factory.newTransformer(new StreamSource(xsl.getCharacterStream()));
if (parameters != null) {
Iterator<Entry<String, Object>> it = parameters.entrySet().iterator();
Entry<String, Object> e;
while ( it.hasNext() ) {
e = it.next();
transformer.setParameter(e.getKey(), e.getValue());
}
}
transformer.transform(new DOMSource(doc), new StreamResult(sw));
return sw.toString();
}
/**
* returns the Node Type As String
* @param node
* @param cftype
* @return
*/
public static String getTypeAsString(Node node, boolean cftype) {
String suffix=cftype?"":"_NODE";
switch(node.getNodeType()) {
case Node.ATTRIBUTE_NODE: return "ATTRIBUTE"+suffix;
case Node.CDATA_SECTION_NODE: return "CDATA_SECTION"+suffix;
case Node.COMMENT_NODE: return "COMMENT"+suffix;
case Node.DOCUMENT_FRAGMENT_NODE: return "DOCUMENT_FRAGMENT"+suffix;
case Node.DOCUMENT_NODE: return "DOCUMENT"+suffix;
case Node.DOCUMENT_TYPE_NODE: return "DOCUMENT_TYPE"+suffix;
case Node.ELEMENT_NODE: return "ELEMENT"+suffix;
case Node.ENTITY_NODE: return "ENTITY"+suffix;
case Node.ENTITY_REFERENCE_NODE: return "ENTITY_REFERENCE"+suffix;
case Node.NOTATION_NODE: return "NOTATION"+suffix;
case Node.PROCESSING_INSTRUCTION_NODE: return "PROCESSING_INSTRUCTION"+suffix;
case Node.TEXT_NODE: return "TEXT"+suffix;
default: return "UNKNOW"+suffix;
}
}
public static Element getChildWithName(String name, Element el) {
synchronized(sync(el)){
Element[] children = XMLUtil.getChildElementsAsArray(el);
for(int i=0;i<children.length;i++) {
if(name.equalsIgnoreCase(children[i].getNodeName()))
return children[i];
}
}
return null;
}
public static InputSource toInputSource(Resource res, Charset cs) throws IOException {
String str = IOUtil.toString((res), cs);
return new InputSource(new StringReader(str));
}
public static InputSource toInputSource(PageContext pc, Object value) throws IOException, ExpressionException {
if(value instanceof InputSource) {
return (InputSource) value;
}
if(value instanceof String) {
return toInputSource(pc, (String)value);
}
if(value instanceof StringBuffer) {
return toInputSource(pc, value.toString());
}
if(value instanceof Resource) {
String str = IOUtil.toString(((Resource)value), (Charset)null);
return new InputSource(new StringReader(str));
}
if(value instanceof File) {
String str = IOUtil.toString(ResourceUtil.toResource(((File)value)),(Charset)null);
return new InputSource(new StringReader(str));
}
if(value instanceof InputStream) {
InputStream is = (InputStream)value;
try {
String str = IOUtil.toString(is, (Charset)null);
return new InputSource(new StringReader(str));
}
finally {
IOUtil.closeEL(is);
}
}
if(value instanceof Reader) {
Reader reader = (Reader)value;
try {
String str = IOUtil.toString(reader);
return new InputSource(new StringReader(str));
}
finally {
IOUtil.closeEL(reader);
}
}
if(value instanceof byte[]) {
return new InputSource(new ByteArrayInputStream((byte[])value));
}
throw new ExpressionException("cat cast object of type ["+Caster.toClassName(value)+"] to a Input for xml parser");
}
public static InputSource toInputSource(PageContext pc, String xml) throws IOException, ExpressionException {
return toInputSource(pc, xml,true);
}
public static InputSource toInputSource(PageContext pc, String xml, boolean canBePath) throws IOException, ExpressionException {
// xml text
xml=xml.trim();
if(!canBePath || xml.startsWith("<") || xml.length()>2000 || StringUtil.isEmpty(xml,true)) {
return new InputSource(new StringReader(xml));
}
// xml link
pc=ThreadLocalPageContext.get(pc);
Resource res = ResourceUtil.toResourceExisting(pc, xml);
return toInputSource(pc, res);
}
public static Struct validate(InputSource xml, InputSource schema, String strSchema) throws XMLException {
return new XMLValidator(schema,strSchema).validate(xml);
}
/**
* adds a child at the first place
* @param parent
* @param child
*/
public static void prependChild(Element parent, Element child) {
Node first = parent.getFirstChild();
if(first==null)parent.appendChild(child);
else {
parent.insertBefore(child, first);
}
}
public static void setFirst(Node parent, Node node) {
Node first = parent.getFirstChild();
if(first!=null) parent.insertBefore(node, first);
else parent.appendChild(node);
}
public static XMLReader createXMLReader() throws SAXException {
/*if(optionalDefaultSaxParser==null)
optionalDefaultSaxParser=DEFAULT_SAX_PARSER;
try{
return XMLReaderFactory.createXMLReader();
}
catch(Throwable t){
ExceptionUtil.rethrowIfNecessary(t);
return XMLReaderFactory.createXMLReader();
}*/
return XMLReaderFactory.createXMLReader();
}
public static Document createDocument(Resource res, boolean isHTML) throws SAXException, IOException {
InputStream is=null;
try {
return parse(toInputSource(res, null),null,isHTML);
}
finally {
IOUtil.closeEL(is);
}
}
public static Document createDocument(String xml, boolean isHTML) throws SAXException, IOException {
return parse(toInputSource(xml),null,isHTML);
}
public static Document createDocument(InputStream is, boolean isHTML) throws SAXException, IOException {
return parse(new InputSource(is),null,isHTML);
}
public static InputSource toInputSource(Object value) throws IOException {
if(value instanceof InputSource) {
return (InputSource) value;
}
if(value instanceof String) {
return toInputSource((String)value);
}
if(value instanceof StringBuffer) {
return toInputSource(value.toString());
}
if(value instanceof Resource) {
String str = IOUtil.toString(((Resource)value), (Charset)null);
return new InputSource(new StringReader(str));
}
if(value instanceof File) {
FileInputStream fis = new FileInputStream((File)value);
try {
return toInputSource(fis);
}
finally {
IOUtil.closeEL(fis);
}
}
if(value instanceof InputStream) {
InputStream is = (InputStream)value;
try {
String str = IOUtil.toString(is, (Charset)null);
return new InputSource(new StringReader(str));
}
finally {
IOUtil.closeEL(is);
}
}
if(value instanceof Reader) {
Reader reader = (Reader)value;
try {
String str = IOUtil.toString(reader);
return new InputSource(new StringReader(str));
}
finally {
IOUtil.closeEL(reader);
}
}
if(value instanceof byte[]) {
return new InputSource(new ByteArrayInputStream((byte[])value));
}
throw new IOException("cat cast object of type ["+value+"] to a Input for xml parser");
}
public static InputSource toInputSource(String xml) throws IOException {
return new InputSource(new StringReader(xml.trim()));
}
}
|
clean up
|
core/src/main/java/lucee/runtime/text/xml/XMLUtil.java
|
clean up
|
|
Java
|
apache-2.0
|
6e6b0b8dc3ad286e29d802c88bb7a44951f9c070
| 0
|
zhuyihao/Jest,cogniteev/Jest,trajano/Jest,trajano/Jest,ldez/Jest,barrysun/Jest,cogniteev/Jest,joerivanruth/Jest,stevengonsalvez/Jest,stevengonsalvez/Jest,andrejserafim/Jest,barrysun/Jest,VlasShatokhin/Jest,andrejserafim/Jest,gvolpe/Jest,ctrimble/Jest,ldez/Jest,joerivanruth/Jest,ctrimble/Jest,zhuyihao/Jest,searchbox-io/Jest
|
package io.searchbox.client;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.client.http.JestHttpClient;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Dogukan Sonmez
*/
public class JestClientFactoryTest {
@Test
public void clientCreationWithTimeout() {
JestClientFactory factory = new JestClientFactory();
HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(
"someUri").connTimeout(150).readTimeout(300).build();
factory.setHttpClientConfig(httpClientConfig);
final RequestConfig defaultRequestConfig = factory.createRequestConfig();
assertNotNull(defaultRequestConfig);
assertEquals(150, defaultRequestConfig.getConnectionRequestTimeout());
assertEquals(300, defaultRequestConfig.getSocketTimeout());
}
@Test
public void clientCreationWithDiscovery() {
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig.Builder("http://localhost:9200").discoveryEnabled(true).build());
JestHttpClient jestClient = (JestHttpClient) factory.getObject();
assertTrue(jestClient != null);
assertNotNull(jestClient.getAsyncClient());
assertTrue(factory.createConnectionManager() instanceof BasicHttpClientConnectionManager);
assertEquals(jestClient.getServers().size(), 1);
assertTrue(jestClient.getServers().contains("http://localhost:9200"));
}
@Test
public void clientCreationWithNullClientConfig() {
JestClientFactory factory = new JestClientFactory();
JestHttpClient jestClient = (JestHttpClient) factory.getObject();
assertTrue(jestClient != null);
assertNotNull(jestClient.getAsyncClient());
assertEquals(jestClient.getServers().size(), 1);
assertTrue(jestClient.getServers().contains("http://localhost:9200"));
}
@Test
public void multiThreadedClientCreation() {
JestClientFactory factory = new JestClientFactory();
HttpRoute routeOne = new HttpRoute(new HttpHost("http://test.localhost"));
HttpRoute routeTwo = new HttpRoute(new HttpHost("http://localhost"));
HttpClientConfig httpClientConfig = new HttpClientConfig.Builder("http://localhost:9200")
.multiThreaded(true)
.maxTotalConnection(20)
.defaultMaxTotalConnectionPerRoute(10)
.maxTotalConnectionPerRoute(routeOne, 5)
.maxTotalConnectionPerRoute(routeTwo, 6)
.build();
factory.setHttpClientConfig(httpClientConfig);
JestHttpClient jestClient = (JestHttpClient) factory.getObject();
assertTrue(jestClient != null);
assertNotNull(jestClient.getAsyncClient());
final HttpClientConnectionManager connectionManager = factory.createConnectionManager();
assertTrue(connectionManager instanceof PoolingHttpClientConnectionManager);
assertEquals(10, ((PoolingHttpClientConnectionManager) connectionManager).getDefaultMaxPerRoute());
assertEquals(20, ((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal());
assertEquals(5, ((PoolingHttpClientConnectionManager) connectionManager).getMaxPerRoute(routeOne));
assertEquals(6, ((PoolingHttpClientConnectionManager) connectionManager).getMaxPerRoute(routeTwo));
assertEquals(jestClient.getServers().size(), 1);
assertTrue(jestClient.getServers().contains("http://localhost:9200"));
}
}
|
jest/src/test/java/io/searchbox/client/JestClientFactoryTest.java
|
package io.searchbox.client;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.client.http.JestHttpClient;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Dogukan Sonmez
*/
public class JestClientFactoryTest {
private JestClientFactory factory;
@Before
public void setUp() throws Exception {
factory = new JestClientFactory();
}
@Test
public void clientCreationWithTimeout() {
HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(
"someUri").connTimeout(150).readTimeout(300).build();
factory.setHttpClientConfig(httpClientConfig);
final RequestConfig defaultRequestConfig = factory.createRequestConfig();
assertNotNull(defaultRequestConfig);
assertEquals(150, defaultRequestConfig.getConnectionRequestTimeout());
assertEquals(300, defaultRequestConfig.getSocketTimeout());
}
@Test
public void clientCreationWithDiscovery() {
factory.setHttpClientConfig(new HttpClientConfig.Builder("http://localhost:9200").discoveryEnabled(true).build());
JestHttpClient jestClient = (JestHttpClient) factory.getObject();
assertTrue(jestClient != null);
assertNotNull(jestClient.getAsyncClient());
assertTrue(factory.createConnectionManager() instanceof BasicHttpClientConnectionManager);
assertEquals(jestClient.getServers().size(), 1);
assertTrue(jestClient.getServers().contains("http://localhost:9200"));
}
@Test
public void clientCreationWithNullClientConfig() {
JestHttpClient jestClient = (JestHttpClient) factory.getObject();
assertTrue(jestClient != null);
assertNotNull(jestClient.getAsyncClient());
assertEquals(jestClient.getServers().size(), 1);
assertTrue(jestClient.getServers().contains("http://localhost:9200"));
}
@Test
public void multiThreadedClientCreation() {
HttpRoute routeOne = new HttpRoute(new HttpHost("http://test.localhost"));
HttpRoute routeTwo = new HttpRoute(new HttpHost("http://localhost"));
HttpClientConfig httpClientConfig = new HttpClientConfig.Builder("http://localhost:9200")
.multiThreaded(true)
.maxTotalConnection(20)
.defaultMaxTotalConnectionPerRoute(10)
.maxTotalConnectionPerRoute(routeOne, 5)
.maxTotalConnectionPerRoute(routeTwo, 6)
.build();
factory.setHttpClientConfig(httpClientConfig);
JestHttpClient jestClient = (JestHttpClient) factory.getObject();
assertTrue(jestClient != null);
assertNotNull(jestClient.getAsyncClient());
final HttpClientConnectionManager connectionManager = factory.createConnectionManager();
assertTrue(connectionManager instanceof PoolingHttpClientConnectionManager);
assertEquals(10, ((PoolingHttpClientConnectionManager) connectionManager).getDefaultMaxPerRoute());
assertEquals(20, ((PoolingHttpClientConnectionManager) connectionManager).getMaxTotal());
assertEquals(5, ((PoolingHttpClientConnectionManager) connectionManager).getMaxPerRoute(routeOne));
assertEquals(6, ((PoolingHttpClientConnectionManager) connectionManager).getMaxPerRoute(routeTwo));
assertEquals(jestClient.getServers().size(), 1);
assertTrue(jestClient.getServers().contains("http://localhost:9200"));
}
}
|
testfix: JestClientFactoryTest
|
jest/src/test/java/io/searchbox/client/JestClientFactoryTest.java
|
testfix: JestClientFactoryTest
|
|
Java
|
apache-2.0
|
be89e0a26c744c73111872e59b9c0f5ffb88dd97
| 0
|
pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus
|
/**
* Copyright 2007-2008 University Of Southern California
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.isi.pegasus.planner.code.gridstart;
import edu.isi.pegasus.planner.catalog.site.classes.SiteStore;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.catalog.site.classes.FileServer;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.code.GridStart;
import edu.isi.pegasus.planner.code.GridStartFactory;
import edu.isi.pegasus.planner.code.POSTScript;
import edu.isi.pegasus.planner.classes.ADag;
import edu.isi.pegasus.planner.classes.Job;
import edu.isi.pegasus.planner.classes.AggregatedJob;
import edu.isi.pegasus.planner.classes.PegasusFile;
import edu.isi.pegasus.planner.classes.TransferJob;
import edu.isi.pegasus.planner.classes.PegasusBag;
import edu.isi.pegasus.planner.transfer.sls.SLSFactory;
import edu.isi.pegasus.planner.transfer.SLS;
import edu.isi.pegasus.planner.namespace.Pegasus;
import java.io.File;
import java.io.FileInputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import edu.isi.pegasus.planner.classes.PlannerOptions;
import edu.isi.pegasus.planner.cluster.JobAggregator;
import edu.isi.pegasus.planner.namespace.Condor;
/**
* This class ends up running the job directly on the grid, without wrapping
* it in any other launcher executable.
* It ends up connecting the jobs stdio and stderr to condor commands to
* ensure they are sent back to the submit host.
*
*
* @author Karan Vahi vahi@isi.edu
* @version $Revision$
*/
public class NoGridStart implements GridStart {
private PegasusBag mBag;
private ADag mDAG;
/**
* The basename of the class that is implmenting this. Could have
* been determined by reflection.
*/
public static final String CLASSNAME = "NoGridStart";
/**
* The SHORTNAME for this implementation.
*/
public static final String SHORT_NAME = "none";
/**
* The LogManager object which is used to log all the messages.
*/
protected LogManager mLogger;
/**
* The object holding all the properties pertaining to Pegasus.
*/
protected PegasusProperties mProps;
/**
* The submit directory where the submit files are being generated for
* the workflow.
*/
protected String mSubmitDir;
/**
* The argument string containing the arguments with which the exitcode
* is invoked on kickstart output.
*/
protected String mExitParserArguments;
/**
* A boolean indicating whether to generate lof files or not.
*/
protected boolean mGenerateLOF;
/**
* A boolean indicating whether to have worker node execution or not.
*/
//protected boolean mWorkerNodeExecution;
/**
* The handle to the SLS implementor
*/
protected SLS mSLS;
/**
* The options passed to the planner.
*/
protected PlannerOptions mPOptions;
/**
* Handle to the site catalog store.
*/
//protected PoolInfoProvider mSiteHandle;
protected SiteStore mSiteStore;
/**
* An instance variable to track if enabling is happening as part of a clustered job.
* See Bug 21 comments on Pegasus Bugzilla
*/
protected boolean mEnablingPartOfAggregatedJob;
/**
* Boolean indicating whether worker package staging is enabled or not.
*/
protected boolean mWorkerPackageStagingEnabled;
/**
* Initializes the GridStart implementation.
*
* @param bag the bag of objects that is used for initialization.
* @param dag the concrete dag so far.
*/
public void initialize( PegasusBag bag, ADag dag ){
mBag = bag;
mDAG = dag;
mLogger = bag.getLogger();
mSiteStore = bag.getHandleToSiteStore();
mPOptions = bag.getPlannerOptions();
mSubmitDir = mPOptions.getSubmitDirectory();
mProps = bag.getPegasusProperties();
mGenerateLOF = mProps.generateLOFFiles();
mWorkerPackageStagingEnabled = mProps.transferWorkerPackage();
// mExitParserArguments = getExitCodeArguments();
/* JIRA PM-495
mWorkerNodeExecution = mProps.executeOnWorkerNode();
if( mWorkerNodeExecution ){
//load SLS
mSLS = SLSFactory.loadInstance( bag );
}
*/
mEnablingPartOfAggregatedJob = false;
}
/**
* Enables a collection of jobs and puts them into an AggregatedJob.
* The assumption here is that all the jobs are being enabled by the same
* implementation. It enables the jobs and puts them into the AggregatedJob
* that is passed to it.
*
* @param aggJob the AggregatedJob into which the collection has to be
* integrated.
* @param jobs the collection of jobs (Job) that need to be enabled.
*
* @return the AggregatedJob containing the enabled jobs.
* @see #enable(Job,boolean)
*/
public AggregatedJob enable(AggregatedJob aggJob,Collection jobs){
//sanity check for the arguments
if( aggJob.strargs != null && aggJob.strargs.length() > 0){
//construct( aggJob, "arguments", aggJob.strargs);
// the arguments are no longer set as condor profiles
// they are now set to the corresponding profiles in
// the Condor Code Generator only.
aggJob.setArguments( aggJob.strargs );
}
//we do not want the jobs being clustered to be enabled
//for worker node execution just yet.
mEnablingPartOfAggregatedJob = true;
for (Iterator it = jobs.iterator(); it.hasNext(); ) {
Job job = (Job)it.next();
//always pass isGlobus true as always
//interested only in executable strargs
this.enable(job, true);
aggJob.add(job);
}
//set the flag back to false
mEnablingPartOfAggregatedJob = false;
return aggJob;
}
/**
* Enables a job to run on the grid. This also determines how the
* stdin,stderr and stdout of the job are to be propogated.
* To grid enable a job, the job may need to be wrapped into another
* job, that actually launches the job. It usually results in the job
* description passed being modified modified.
*
* @param job the <code>Job</code> object containing the job description
* of the job that has to be enabled on the grid.
* @param isGlobusJob is <code>true</code>, if the job generated a
* line <code>universe = globus</code>, and thus runs remotely.
* Set to <code>false</code>, if the job runs on the submit
* host in any way.
*
* @return boolean true if enabling was successful,else false.
*/
public boolean enable( AggregatedJob job,boolean isGlobusJob){
//get hold of the JobAggregator determined for this clustered job
//during clustering
JobAggregator aggregator = job.getJobAggregator();
if( aggregator == null ){
throw new RuntimeException( "Clustered job not associated with a job aggregator " + job.getID() );
}
boolean first = true;
for (Iterator it = job.constituentJobsIterator(); it.hasNext(); ) {
Job constituentJob = (Job)it.next();
//earlier was set in SeqExec JobAggregator in the enable function
constituentJob.vdsNS.construct( Pegasus.GRIDSTART_KEY,
this.getVDSKeyValue() );
if(first){
first = false;
}
else{
//we need to pass -H to kickstart
//to suppress the header creation
constituentJob.vdsNS.construct(Pegasus.GRIDSTART_ARGUMENTS_KEY,"-H");
}
//always pass isGlobus true as always
//interested only in executable strargs
//due to the fact that seqexec does not allow for setting environment
//per constitutent constituentJob, we cannot set the postscript removal option
this.enable( constituentJob, isGlobusJob );
}
//all the constitutent jobs are enabled.
//get the job aggregator to render the job
//to it's executable form
aggregator.makeAbstractAggregatedJobConcrete( job );
//set the flag back to false
//mEnablingPartOfAggregatedJob = false;
//the aggregated job itself needs to be enabled via NoGridStart
this.enable( (Job)job, isGlobusJob);
return true;
}
/**
* Enables a job to run on the grid by launching it directly. It ends
* up running the executable directly without going through any intermediate
* launcher executable. It connects the stdio, and stderr to underlying
* condor mechanisms so that they are transported back to the submit host.
*
* @param job the <code>Job</code> object containing the job description
* of the job that has to be enabled on the grid.
* @param isGlobusJob is <code>true</code>, if the job generated a
* line <code>universe = globus</code>, and thus runs remotely.
* Set to <code>false</code>, if the job runs on the submit
* host in any way.
*
* @return boolean true if enabling was successful,else false in case when
* the path to kickstart could not be determined on the site where
* the job is scheduled.
*/
public boolean enable(Job job, boolean isGlobusJob) {
//take care of relative submit directory if specified
String submitDir = mSubmitDir + mSeparator;
// String submitDir = getSubmitDirectory( mSubmitDir , job) + mSeparator;
// the arguments are no longer set as condor profiles
// they are now set to the corresponding profiles in
// the Condor Code Generator only.
job.setRemoteExecutable( handleTransferOfExecutable( job ) );
/*
//the executable path and arguments are put
//in the Condor namespace and not printed to the
//file so that they can be overriden if desired
//later through profiles and key transfer_executable
construct(job,"executable", handleTransferOfExecutable( job ) );
//sanity check for the arguments
if(job.strargs != null && job.strargs.length() > 0){
construct(job, "arguments", job.strargs);
}
*/
// handle stdin
if (job.stdIn.length() > 0) {
construct(job,"input",submitDir + job.stdIn);
if (isGlobusJob) {
//this needs to be true as you want the stdin
//to be transfered to the remote execution
//pool, as in case of the transfer script.
//it needs to be set if the stdin is already
//prepopulated at the remote side which
//it is not.
construct(job,"transfer_input","true");
}
}
if (job.stdOut.length() > 0) {
//handle stdout
construct(job,"output",job.stdOut);
if (isGlobusJob) {
construct(job,"transfer_output","false");
}
} else {
// transfer output back to submit host, if unused
construct(job,"output",submitDir + job.jobName + ".out");
if (isGlobusJob) {
construct(job,"transfer_output","true");
}
}
if (job.stdErr.length() > 0) {
//handle stderr
construct(job,"error",job.stdErr);
if (isGlobusJob) {
construct(job,"transfer_error","false");
}
} else {
// transfer error back to submit host, if unused
construct(job,"error",submitDir + job.jobName + ".err");
if (isGlobusJob) {
construct(job,"transfer_error","true");
}
}
if( mGenerateLOF ){
//but generate lof files nevertheless
//inefficient check here again. just a prototype
//we need to generate -S option only for non transfer jobs
//generate the list of filenames file for the input and output files.
if (! (job instanceof TransferJob)) {
generateListofFilenamesFile( job.getInputFiles(),
job.getID() + ".in.lof");
}
//for cleanup jobs no generation of stats for output files
if (job.getJobType() != Job.CLEANUP_JOB) {
generateListofFilenamesFile(job.getOutputFiles(),
job.getID() + ".out.lof");
}
}///end of mGenerateLOF
return true;
}
/**
* It changes the paths to the executable depending on whether we want to
* transfer the executable or not. Currently, the transfer_executable is only
* handled for staged compute jobs, where Pegasus is staging the binaries
* to the remote site.
*
* @param job the <code>Job</code> containing the job description.
*
* @return the path that needs to be set as the executable key. If
* transfer_executable is not set the path to the executable is
* returned as is.
*/
protected String handleTransferOfExecutable( Job job ) {
Condor cvar = job.condorVariables;
String path = job.executable;
if ( cvar.getBooleanValue( "transfer_executable" )) {
//explicitly check for whether the job is a staged compute job or not
// if( job.getJobType() == Job.STAGED_COMPUTE_JOB ){
if( job.userExecutablesStagedForJob() ){
//the executable is being staged to the remote site.
//all we need to do is unset transfer_executable
cvar.construct( "transfer_executable", "false" );
}
else if ( mWorkerPackageStagingEnabled &&
job.getJobType() == Job.CREATE_DIR_JOB ){
//we dont complain.
//JIRA PM-281
}
else{
mLogger.log( "Transfer of Executables in NoGridStart only works for staged computes jobs " + job.getName(),
LogManager.ERROR_MESSAGE_LEVEL );
}
}
else{
//the executable paths are correct and
//point to the executable on the remote pool
}
return path;
}
/**
* Indicates whether the enabling mechanism can set the X bit
* on the executable on the remote grid site, in addition to launching
* it on the remote grid stie
*
* @return false, as no wrapper executable is being used.
*/
public boolean canSetXBit(){
return false;
}
/**
* Returns the value of the vds profile with key as Pegasus.GRIDSTART_KEY,
* that would result in the loading of this particular implementation.
* It is usually the name of the implementing class without the
* package name.
*
* @return the value of the profile key.
* @see org.griphyn.cPlanner.namespace.Pegasus#GRIDSTART_KEY
*/
public String getVDSKeyValue(){
return this.CLASSNAME;
}
/**
* Returns a short textual description in the form of the name of the class.
*
* @return short textual description.
*/
public String shortDescribe(){
return this.SHORT_NAME;
}
/**
* Returns the SHORT_NAME for the POSTScript implementation that is used
* to be as default with this GridStart implementation.
*
* @return the identifier for the NoPOSTScript POSTScript implementation.
*
* @see POSTScript#shortDescribe()
*/
public String defaultPOSTScript(){
return NoPOSTScript.SHORT_NAME;
}
/**
* Returns the directory that is associated with the job to specify
* the directory in which the job needs to run
*
* @param job the job
*
* @return the condor key . can be initialdir or remote_initialdir
*/
private String getDirectoryKey(Job job) {
/*
String style = (String)job.vdsNS.get( Pegasus.STYLE_KEY );
//remove the remote or initial dir's for the compute jobs
String key = ( style.equalsIgnoreCase( Pegasus.GLOBUS_STYLE ) )?
"remote_initialdir" :
"initialdir";
*/
String universe = (String) job.condorVariables.get( Condor.UNIVERSE_KEY );
return ( universe.equals( Condor.STANDARD_UNIVERSE ) ||
universe.equals( Condor.LOCAL_UNIVERSE) ||
universe.equals( Condor.SCHEDULER_UNIVERSE ) )?
"initialdir" :
"remote_initialdir";
}
/**
* Returns a boolean indicating whether to remove remote directory
* information or not from the job. This is determined on the basis of the
* style key that is associated with the job.
*
* @param job the job in question.
*
* @return boolean
*/
private boolean removeDirectoryKey(Job job){
String style = job.vdsNS.containsKey(Pegasus.STYLE_KEY) ?
null :
(String)job.vdsNS.get(Pegasus.STYLE_KEY);
//is being run. Remove remote_initialdir if there
//condor style associated with the job
//Karan Nov 15,2005
return (style == null)?
false:
style.equalsIgnoreCase(Pegasus.CONDOR_STYLE);
}
/**
* Constructs a condor variable in the condor profile namespace
* associated with the job. Overrides any preexisting key values.
*
* @param job contains the job description.
* @param key the key of the profile.
* @param value the associated value.
*/
private void construct(Job job, String key, String value){
job.condorVariables.construct(key,value);
}
/**
* Returns a string containing the arguments with which the exitcode
* needs to be invoked.
*
* @return the argument string.
*/
/* private String getExitCodeArguments(){
return mProps.getPOSTScriptArguments();
}
*/
/**
* Writes out the list of filenames file for the job.
*
* @param files the list of <code>PegasusFile</code> objects contains the files
* whose stat information is required.
*
* @param basename the basename of the file that is to be created
*
* @return the full path to lof file created, else null if no file is written out.
*/
public String generateListofFilenamesFile( Set files, String basename ){
//sanity check
if ( files == null || files.isEmpty() ){
return null;
}
String result = null;
//writing the stdin file
try {
File f = new File( mSubmitDir, basename );
FileWriter input;
input = new FileWriter( f );
PegasusFile pf;
for( Iterator it = files.iterator(); it.hasNext(); ){
pf = ( PegasusFile ) it.next();
input.write( pf.getLFN() );
input.write( "\n" );
}
//close the stream
input.close();
result = f.getAbsolutePath();
} catch ( IOException e) {
mLogger.log("Unable to write the lof file " + basename, e ,
LogManager.ERROR_MESSAGE_LEVEL);
}
return result;
}
/**
* Adds contents to an output stream.
* @param src
* @param out
* @throws java.io.IOException
*/
private void addToFile( File src, OutputStream out ) throws IOException{
InputStream in = new FileInputStream(src);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
}
/**
* Returns the directory in which the job executes on the worker node.
*
* @param job
*
* @return the full path to the directory where the job executes
*/
public String getWorkerNodeDirectory( Job job ){
StringBuffer workerNodeDir = new StringBuffer();
String destDir = mSiteStore.getEnvironmentVariable( job.getSiteHandle() , "wntmp" );
destDir = ( destDir == null ) ? "/tmp" : destDir;
String relativeDir = mPOptions.getRelativeDirectory();
workerNodeDir.append( destDir ).append( File.separator ).
append( relativeDir.replaceAll( "/" , "-" ) ).
//append( File.separator ).append( job.getCompleteTCName().replaceAll( ":[:]*", "-") );
append( "-" ).append( job.getID() );
return workerNodeDir.toString();
}
public void useFullPathToGridStarts(boolean fullPath) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
src/edu/isi/pegasus/planner/code/gridstart/NoGridStart.java
|
/**
* Copyright 2007-2008 University Of Southern California
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.isi.pegasus.planner.code.gridstart;
import edu.isi.pegasus.planner.catalog.site.classes.SiteStore;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.catalog.site.classes.FileServer;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.code.GridStart;
import edu.isi.pegasus.planner.code.GridStartFactory;
import edu.isi.pegasus.planner.code.POSTScript;
import edu.isi.pegasus.planner.classes.ADag;
import edu.isi.pegasus.planner.classes.Job;
import edu.isi.pegasus.planner.classes.AggregatedJob;
import edu.isi.pegasus.planner.classes.PegasusFile;
import edu.isi.pegasus.planner.classes.TransferJob;
import edu.isi.pegasus.planner.classes.PegasusBag;
import edu.isi.pegasus.planner.transfer.sls.SLSFactory;
import edu.isi.pegasus.planner.transfer.SLS;
import edu.isi.pegasus.planner.namespace.Pegasus;
import java.io.File;
import java.io.FileInputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import edu.isi.pegasus.planner.classes.PlannerOptions;
import edu.isi.pegasus.planner.cluster.JobAggregator;
import edu.isi.pegasus.planner.namespace.Condor;
/**
* This class ends up running the job directly on the grid, without wrapping
* it in any other launcher executable.
* It ends up connecting the jobs stdio and stderr to condor commands to
* ensure they are sent back to the submit host.
*
*
* @author Karan Vahi vahi@isi.edu
* @version $Revision$
*/
public class NoGridStart implements GridStart {
private PegasusBag mBag;
private ADag mDAG;
/**
* The basename of the class that is implmenting this. Could have
* been determined by reflection.
*/
public static final String CLASSNAME = "NoGridStart";
/**
* The SHORTNAME for this implementation.
*/
public static final String SHORT_NAME = "none";
/**
* The LogManager object which is used to log all the messages.
*/
protected LogManager mLogger;
/**
* The object holding all the properties pertaining to Pegasus.
*/
protected PegasusProperties mProps;
/**
* The submit directory where the submit files are being generated for
* the workflow.
*/
protected String mSubmitDir;
/**
* The argument string containing the arguments with which the exitcode
* is invoked on kickstart output.
*/
protected String mExitParserArguments;
/**
* A boolean indicating whether to generate lof files or not.
*/
protected boolean mGenerateLOF;
/**
* A boolean indicating whether to have worker node execution or not.
*/
protected boolean mWorkerNodeExecution;
/**
* The handle to the SLS implementor
*/
protected SLS mSLS;
/**
* The options passed to the planner.
*/
protected PlannerOptions mPOptions;
/**
* Handle to the site catalog store.
*/
//protected PoolInfoProvider mSiteHandle;
protected SiteStore mSiteStore;
/**
* An instance variable to track if enabling is happening as part of a clustered job.
* See Bug 21 comments on Pegasus Bugzilla
*/
protected boolean mEnablingPartOfAggregatedJob;
/**
* Boolean indicating whether worker package staging is enabled or not.
*/
protected boolean mWorkerPackageStagingEnabled;
/**
* Initializes the GridStart implementation.
*
* @param bag the bag of objects that is used for initialization.
* @param dag the concrete dag so far.
*/
public void initialize( PegasusBag bag, ADag dag ){
mBag = bag;
mDAG = dag;
mLogger = bag.getLogger();
mSiteStore = bag.getHandleToSiteStore();
mPOptions = bag.getPlannerOptions();
mSubmitDir = mPOptions.getSubmitDirectory();
mProps = bag.getPegasusProperties();
mGenerateLOF = mProps.generateLOFFiles();
mWorkerPackageStagingEnabled = mProps.transferWorkerPackage();
// mExitParserArguments = getExitCodeArguments();
mWorkerNodeExecution = mProps.executeOnWorkerNode();
if( mWorkerNodeExecution ){
//load SLS
mSLS = SLSFactory.loadInstance( bag );
}
mEnablingPartOfAggregatedJob = false;
}
/**
* Enables a collection of jobs and puts them into an AggregatedJob.
* The assumption here is that all the jobs are being enabled by the same
* implementation. It enables the jobs and puts them into the AggregatedJob
* that is passed to it.
*
* @param aggJob the AggregatedJob into which the collection has to be
* integrated.
* @param jobs the collection of jobs (Job) that need to be enabled.
*
* @return the AggregatedJob containing the enabled jobs.
* @see #enable(Job,boolean)
*/
public AggregatedJob enable(AggregatedJob aggJob,Collection jobs){
//sanity check for the arguments
if( aggJob.strargs != null && aggJob.strargs.length() > 0){
//construct( aggJob, "arguments", aggJob.strargs);
// the arguments are no longer set as condor profiles
// they are now set to the corresponding profiles in
// the Condor Code Generator only.
aggJob.setArguments( aggJob.strargs );
}
//we do not want the jobs being clustered to be enabled
//for worker node execution just yet.
mEnablingPartOfAggregatedJob = true;
for (Iterator it = jobs.iterator(); it.hasNext(); ) {
Job job = (Job)it.next();
//always pass isGlobus true as always
//interested only in executable strargs
this.enable(job, true);
aggJob.add(job);
}
//set the flag back to false
mEnablingPartOfAggregatedJob = false;
return aggJob;
}
/**
* Enables a job to run on the grid. This also determines how the
* stdin,stderr and stdout of the job are to be propogated.
* To grid enable a job, the job may need to be wrapped into another
* job, that actually launches the job. It usually results in the job
* description passed being modified modified.
*
* @param job the <code>Job</code> object containing the job description
* of the job that has to be enabled on the grid.
* @param isGlobusJob is <code>true</code>, if the job generated a
* line <code>universe = globus</code>, and thus runs remotely.
* Set to <code>false</code>, if the job runs on the submit
* host in any way.
*
* @return boolean true if enabling was successful,else false.
*/
public boolean enable( AggregatedJob job,boolean isGlobusJob){
//get hold of the JobAggregator determined for this clustered job
//during clustering
JobAggregator aggregator = job.getJobAggregator();
if( aggregator == null ){
throw new RuntimeException( "Clustered job not associated with a job aggregator " + job.getID() );
}
boolean first = true;
for (Iterator it = job.constituentJobsIterator(); it.hasNext(); ) {
Job constituentJob = (Job)it.next();
//earlier was set in SeqExec JobAggregator in the enable function
constituentJob.vdsNS.construct( Pegasus.GRIDSTART_KEY,
this.getVDSKeyValue() );
if(first){
first = false;
}
else{
//we need to pass -H to kickstart
//to suppress the header creation
constituentJob.vdsNS.construct(Pegasus.GRIDSTART_ARGUMENTS_KEY,"-H");
}
//always pass isGlobus true as always
//interested only in executable strargs
//due to the fact that seqexec does not allow for setting environment
//per constitutent constituentJob, we cannot set the postscript removal option
this.enable( constituentJob, isGlobusJob );
}
//all the constitutent jobs are enabled.
//get the job aggregator to render the job
//to it's executable form
aggregator.makeAbstractAggregatedJobConcrete( job );
//set the flag back to false
//mEnablingPartOfAggregatedJob = false;
//the aggregated job itself needs to be enabled via NoGridStart
this.enable( (Job)job, isGlobusJob);
return true;
}
/**
* Enables a job to run on the grid by launching it directly. It ends
* up running the executable directly without going through any intermediate
* launcher executable. It connects the stdio, and stderr to underlying
* condor mechanisms so that they are transported back to the submit host.
*
* @param job the <code>Job</code> object containing the job description
* of the job that has to be enabled on the grid.
* @param isGlobusJob is <code>true</code>, if the job generated a
* line <code>universe = globus</code>, and thus runs remotely.
* Set to <code>false</code>, if the job runs on the submit
* host in any way.
*
* @return boolean true if enabling was successful,else false in case when
* the path to kickstart could not be determined on the site where
* the job is scheduled.
*/
public boolean enable(Job job, boolean isGlobusJob) {
//take care of relative submit directory if specified
String submitDir = mSubmitDir + mSeparator;
// String submitDir = getSubmitDirectory( mSubmitDir , job) + mSeparator;
// the arguments are no longer set as condor profiles
// they are now set to the corresponding profiles in
// the Condor Code Generator only.
job.setRemoteExecutable( handleTransferOfExecutable( job ) );
/*
//the executable path and arguments are put
//in the Condor namespace and not printed to the
//file so that they can be overriden if desired
//later through profiles and key transfer_executable
construct(job,"executable", handleTransferOfExecutable( job ) );
//sanity check for the arguments
if(job.strargs != null && job.strargs.length() > 0){
construct(job, "arguments", job.strargs);
}
*/
// handle stdin
if (job.stdIn.length() > 0) {
construct(job,"input",submitDir + job.stdIn);
if (isGlobusJob) {
//this needs to be true as you want the stdin
//to be transfered to the remote execution
//pool, as in case of the transfer script.
//it needs to be set if the stdin is already
//prepopulated at the remote side which
//it is not.
construct(job,"transfer_input","true");
}
}
if (job.stdOut.length() > 0) {
//handle stdout
construct(job,"output",job.stdOut);
if (isGlobusJob) {
construct(job,"transfer_output","false");
}
} else {
// transfer output back to submit host, if unused
construct(job,"output",submitDir + job.jobName + ".out");
if (isGlobusJob) {
construct(job,"transfer_output","true");
}
}
if (job.stdErr.length() > 0) {
//handle stderr
construct(job,"error",job.stdErr);
if (isGlobusJob) {
construct(job,"transfer_error","false");
}
} else {
// transfer error back to submit host, if unused
construct(job,"error",submitDir + job.jobName + ".err");
if (isGlobusJob) {
construct(job,"transfer_error","true");
}
}
//handle stuff differently for clustered jobs
//for non condor modified SLS
if( mWorkerNodeExecution ){
if( job instanceof AggregatedJob && !mSLS.doesCondorModifications()){
String key = getDirectoryKey( job );
AggregatedJob clusteredJob = (AggregatedJob) job;
Job firstJob = clusteredJob.getConstituentJob(0);
GridStartFactory factory = new GridStartFactory();
factory.initialize(mBag, mDAG);
GridStart gs = factory.loadGridStart(firstJob, "/tmp");
//always have the remote dir set to /tmp as
//we are banking on kickstart to change directory
//for us for compute jobs
//Bug fix for JIRA PM-250
//for worker node execution we dont want existing
//remote_initialdir overriden before handing over
//to SeqExec launcher.
job.condorVariables.construct( key, "/tmp" );
}
else if( !mEnablingPartOfAggregatedJob ){
if( job.getJobType() == Job.COMPUTE_JOB /*||
job.getJobType() == Job.STAGED_COMPUTE_JOB*/ ){
if( !mSLS.doesCondorModifications() &&
//do the check only if input/output files are not empty
!( job.getInputFiles().isEmpty() && job.getOutputFiles().isEmpty())){
throw new RuntimeException( "Second Level Staging with NoGridStart only works with Condor SLS" );
}
//remove the remote or initial dir's for the compute jobs
String key = getDirectoryKey( job );
String executionSiteDirectory = (String)job.condorVariables.removeKey( key );
FileServer stagingSiteFileServer = mSiteStore.lookup( job.getStagingSiteHandle() ).getHeadNodeFS().selectScratchSharedFileServer();
String stagingSiteDirectory = mSiteStore.getExternalWorkDirectory(stagingSiteFileServer, job.getStagingSiteHandle() );
String destDir = mSiteStore.getEnvironmentVariable( job.getSiteHandle() , "wntmp" );
destDir = ( destDir == null ) ? "/tmp" : destDir;
String relativeDir = mPOptions.getRelativeDirectory();
String workerNodeDir = destDir + File.separator + relativeDir.replaceAll( "/" , "-" );
//always have the remote dir set to /tmp as we are
//banking upon kickstart to change the directory for us
job.condorVariables.construct( key, "/tmp" );
//modify the job if required
if ( !mSLS.modifyJobForWorkerNodeExecution( job,
stagingSiteFileServer.getURLPrefix(),
stagingSiteDirectory,
workerNodeDir ) ){
throw new RuntimeException( "Unable to modify job " + job.getName() + " for worker node execution" );
}
}
}//end of enabling worker node execution for non clustered jobs
}//end of worker node execution
if( mGenerateLOF ){
//but generate lof files nevertheless
//inefficient check here again. just a prototype
//we need to generate -S option only for non transfer jobs
//generate the list of filenames file for the input and output files.
if (! (job instanceof TransferJob)) {
generateListofFilenamesFile( job.getInputFiles(),
job.getID() + ".in.lof");
}
//for cleanup jobs no generation of stats for output files
if (job.getJobType() != Job.CLEANUP_JOB) {
generateListofFilenamesFile(job.getOutputFiles(),
job.getID() + ".out.lof");
}
}///end of mGenerateLOF
return true;
}
/**
* It changes the paths to the executable depending on whether we want to
* transfer the executable or not. Currently, the transfer_executable is only
* handled for staged compute jobs, where Pegasus is staging the binaries
* to the remote site.
*
* @param job the <code>Job</code> containing the job description.
*
* @return the path that needs to be set as the executable key. If
* transfer_executable is not set the path to the executable is
* returned as is.
*/
protected String handleTransferOfExecutable( Job job ) {
Condor cvar = job.condorVariables;
String path = job.executable;
if ( cvar.getBooleanValue( "transfer_executable" )) {
//explicitly check for whether the job is a staged compute job or not
// if( job.getJobType() == Job.STAGED_COMPUTE_JOB ){
if( job.userExecutablesStagedForJob() ){
//the executable is being staged to the remote site.
//all we need to do is unset transfer_executable
cvar.construct( "transfer_executable", "false" );
}
else if ( mWorkerPackageStagingEnabled &&
job.getJobType() == Job.CREATE_DIR_JOB ){
//we dont complain.
//JIRA PM-281
}
else{
mLogger.log( "Transfer of Executables in NoGridStart only works for staged computes jobs " + job.getName(),
LogManager.ERROR_MESSAGE_LEVEL );
}
}
else{
//the executable paths are correct and
//point to the executable on the remote pool
}
return path;
}
/**
* Indicates whether the enabling mechanism can set the X bit
* on the executable on the remote grid site, in addition to launching
* it on the remote grid stie
*
* @return false, as no wrapper executable is being used.
*/
public boolean canSetXBit(){
return false;
}
/**
* Returns the value of the vds profile with key as Pegasus.GRIDSTART_KEY,
* that would result in the loading of this particular implementation.
* It is usually the name of the implementing class without the
* package name.
*
* @return the value of the profile key.
* @see org.griphyn.cPlanner.namespace.Pegasus#GRIDSTART_KEY
*/
public String getVDSKeyValue(){
return this.CLASSNAME;
}
/**
* Returns a short textual description in the form of the name of the class.
*
* @return short textual description.
*/
public String shortDescribe(){
return this.SHORT_NAME;
}
/**
* Returns the SHORT_NAME for the POSTScript implementation that is used
* to be as default with this GridStart implementation.
*
* @return the identifier for the NoPOSTScript POSTScript implementation.
*
* @see POSTScript#shortDescribe()
*/
public String defaultPOSTScript(){
return NoPOSTScript.SHORT_NAME;
}
/**
* Returns the directory that is associated with the job to specify
* the directory in which the job needs to run
*
* @param job the job
*
* @return the condor key . can be initialdir or remote_initialdir
*/
private String getDirectoryKey(Job job) {
/*
String style = (String)job.vdsNS.get( Pegasus.STYLE_KEY );
//remove the remote or initial dir's for the compute jobs
String key = ( style.equalsIgnoreCase( Pegasus.GLOBUS_STYLE ) )?
"remote_initialdir" :
"initialdir";
*/
String universe = (String) job.condorVariables.get( Condor.UNIVERSE_KEY );
return ( universe.equals( Condor.STANDARD_UNIVERSE ) ||
universe.equals( Condor.LOCAL_UNIVERSE) ||
universe.equals( Condor.SCHEDULER_UNIVERSE ) )?
"initialdir" :
"remote_initialdir";
}
/**
* Returns a boolean indicating whether to remove remote directory
* information or not from the job. This is determined on the basis of the
* style key that is associated with the job.
*
* @param job the job in question.
*
* @return boolean
*/
private boolean removeDirectoryKey(Job job){
String style = job.vdsNS.containsKey(Pegasus.STYLE_KEY) ?
null :
(String)job.vdsNS.get(Pegasus.STYLE_KEY);
//is being run. Remove remote_initialdir if there
//condor style associated with the job
//Karan Nov 15,2005
return (style == null)?
false:
style.equalsIgnoreCase(Pegasus.CONDOR_STYLE);
}
/**
* Constructs a condor variable in the condor profile namespace
* associated with the job. Overrides any preexisting key values.
*
* @param job contains the job description.
* @param key the key of the profile.
* @param value the associated value.
*/
private void construct(Job job, String key, String value){
job.condorVariables.construct(key,value);
}
/**
* Returns a string containing the arguments with which the exitcode
* needs to be invoked.
*
* @return the argument string.
*/
/* private String getExitCodeArguments(){
return mProps.getPOSTScriptArguments();
}
*/
/**
* Writes out the list of filenames file for the job.
*
* @param files the list of <code>PegasusFile</code> objects contains the files
* whose stat information is required.
*
* @param basename the basename of the file that is to be created
*
* @return the full path to lof file created, else null if no file is written out.
*/
public String generateListofFilenamesFile( Set files, String basename ){
//sanity check
if ( files == null || files.isEmpty() ){
return null;
}
String result = null;
//writing the stdin file
try {
File f = new File( mSubmitDir, basename );
FileWriter input;
input = new FileWriter( f );
PegasusFile pf;
for( Iterator it = files.iterator(); it.hasNext(); ){
pf = ( PegasusFile ) it.next();
input.write( pf.getLFN() );
input.write( "\n" );
}
//close the stream
input.close();
result = f.getAbsolutePath();
} catch ( IOException e) {
mLogger.log("Unable to write the lof file " + basename, e ,
LogManager.ERROR_MESSAGE_LEVEL);
}
return result;
}
/**
* Adds contents to an output stream.
* @param src
* @param out
* @throws java.io.IOException
*/
private void addToFile( File src, OutputStream out ) throws IOException{
InputStream in = new FileInputStream(src);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
}
/**
* Returns the directory in which the job executes on the worker node.
*
* @param job
*
* @return the full path to the directory where the job executes
*/
public String getWorkerNodeDirectory( Job job ){
StringBuffer workerNodeDir = new StringBuffer();
String destDir = mSiteStore.getEnvironmentVariable( job.getSiteHandle() , "wntmp" );
destDir = ( destDir == null ) ? "/tmp" : destDir;
String relativeDir = mPOptions.getRelativeDirectory();
workerNodeDir.append( destDir ).append( File.separator ).
append( relativeDir.replaceAll( "/" , "-" ) ).
//append( File.separator ).append( job.getCompleteTCName().replaceAll( ":[:]*", "-") );
append( "-" ).append( job.getID() );
return workerNodeDir.toString();
}
public void useFullPathToGridStarts(boolean fullPath) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
JIRA PM-495
NoGridStart should not do anything for worker node execution
That logic is solely now in PegasusLite impelementation of GridStart.
|
src/edu/isi/pegasus/planner/code/gridstart/NoGridStart.java
|
JIRA PM-495
|
|
Java
|
apache-2.0
|
20ee97777320992736d50750c8114081261eadf4
| 0
|
piotr-j/VisEditor,kotcrab/vis-editor,kotcrab/vis-editor,piotr-j/VisEditor,kotcrab/VisEditor
|
/*
* Copyright 2014-2016 See AUTHORS file.
*
* 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.kotcrab.vis.ui.util.adapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.UIUtils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.reflect.ClassReflection;
import com.kotcrab.vis.ui.widget.ListView;
import com.kotcrab.vis.ui.widget.ListView.ItemClickListener;
import com.kotcrab.vis.ui.widget.ListView.ListAdapterListener;
import com.kotcrab.vis.ui.widget.VisTable;
import java.util.Comparator;
/**
* Basic {@link ListAdapter} implementation using {@link CachedItemAdapter}. Supports item selection. Classes
* extending this should store provided list and provide delegates for all common methods that change array state.
* Those delegates should call {@link #itemAdded(Object)} or {@link #itemRemoved(Object)} in order to properly update
* view cache. When changes to array are too big to be handled by those two methods {@link #itemsChanged()} should be
* called. When only items fields has changed, and no new item were added or removed you should call
* {@link #itemsDataChanged()}.
* <p>
* When view does not existed in cache and must be created {@link #createView(Object)} is called. When item view exists
* in cache {@link #updateView(Actor, Object)} will be called.
* <p>
* Enabling item selection requires calling {@link #setSelectionMode(SelectionMode)} and overriding
* {@link #selectView(Actor)} and {@link #deselectView(Actor)}.
* @author Kotcrab
* @see ArrayAdapter
* @see ArrayListAdapter
* @since 1.0.0
*/
public abstract class AbstractListAdapter<ItemT, ViewT extends Actor> extends CachedItemAdapter<ItemT, ViewT>
implements ListAdapter<ItemT> {
protected ListView<ItemT> view;
protected ListAdapterListener viewListener;
private ItemClickListener<ItemT> clickListener;
private SelectionMode selectionMode = SelectionMode.DISABLED;
private ListSelection<ItemT, ViewT> selection = new ListSelection<ItemT, ViewT>(this);
private Comparator<ItemT> itemsComparator;
@Override
public void fillTable (VisTable itemsTable) {
if (itemsComparator != null) sort(itemsComparator);
for (final ItemT item : iterable()) {
final ViewT view = getView(item);
boolean listenerMissing = true;
for (EventListener listener : view.getListeners()) {
if (ClassReflection.isInstance(ListClickListener.class, listener)) {
listenerMissing = false;
break;
}
}
if (listenerMissing) {
view.setTouchable(Touchable.enabled);
view.addListener(new ListClickListener(view, item));
}
itemsTable.add(view).growX();
itemsTable.row();
}
}
@Override
public void setListView (ListView<ItemT> view, ListAdapterListener viewListener) {
if(this.view != null) throw new IllegalStateException("Adapter was already asigned to ListView");
this.view = view;
this.viewListener = viewListener;
}
@Override
public void setItemClickListener (ItemClickListener<ItemT> listener) {
clickListener = listener;
}
protected void itemAdded (ItemT item) {
viewListener.invalidateDataSet();
}
protected void itemRemoved (ItemT item) {
getViews().remove(item);
viewListener.invalidateDataSet();
}
/**
* Notifies adapter that underlying collection has changed, ie. some items were added or removed. This does not need to
* be called when only the fields of stored objects changed see {@link #itemsDataChanged()}.
*/
public void itemsChanged () {
getViews().clear();
viewListener.invalidateDataSet();
}
/**
* Notifies adapter that data of items has changed. This means that objects fields in underlying collection has changed
* and views needs updating. This must not be called if some items were removed or added from collection for that
* {@link #itemsChanged()}
*/
public void itemsDataChanged () {
viewListener.invalidateDataSet();
}
@Override
protected void updateView (ViewT view, ItemT item) {
}
public SelectionMode getSelectionMode () {
return selectionMode;
}
public void setSelectionMode (SelectionMode selectionMode) {
if (selectionMode == null) throw new IllegalArgumentException("selectionMode can't be null");
this.selectionMode = selectionMode;
}
/**
* Sets items comparator allowing to define order in which items will be displayed in list view. This will sort
* underlaying array before building views.
* @param comparator that will be used to compare items
*/
public void setItemsSorter (Comparator<ItemT> comparator) {
this.itemsComparator = comparator;
}
/** @return selected items, must not be modified */
public Array<ItemT> getSelection () {
return selection.getSelection();
}
public ListSelection<ItemT, ViewT> getSelectionManager () {
return selection;
}
protected void selectView (ViewT view) {
if (selectionMode == SelectionMode.DISABLED) return;
throw new UnsupportedOperationException("selectView must be implemented when `selectionMode` is different than SelectionMode.DISABLED");
}
protected void deselectView (ViewT view) {
if (selectionMode == SelectionMode.DISABLED) return;
throw new UnsupportedOperationException("deselectView must be implemented when `selectionMode` is different than SelectionMode.DISABLED");
}
private class ListClickListener extends ClickListener {
private ViewT view;
private ItemT item;
public ListClickListener (ViewT view, ItemT item) {
this.view = view;
this.item = item;
}
@Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
super.touchDown(event, x, y, pointer, button);
selection.touchDown(view, item);
return true;
}
@Override
public void clicked (InputEvent event, float x, float y) {
if (clickListener != null) clickListener.clicked(item);
}
}
protected abstract void sort (Comparator<ItemT> comparator);
public enum SelectionMode {
/** Selecting items is not possible. */
DISABLED,
/**
* Only one element can be selected. {@link AbstractListAdapter#selectView(Actor)} and
* {@link AbstractListAdapter#deselectView(Actor)} must be implemented.
*/
SINGLE,
/**
* Multiple elements can be selected. {@link AbstractListAdapter#selectView(Actor)} and
* {@link AbstractListAdapter#deselectView(Actor)} must be implemented.
*/
MULTIPLE
}
/**
* Manages selection of {@link AbstractListAdapter} items.
* @author Kotcrab
*/
public static class ListSelection<ItemT, ViewT extends Actor> {
private AbstractListAdapter<ItemT, ViewT> adapter;
public static final int DEFAULT_KEY = -1;
private int groupMultiSelectKey = DEFAULT_KEY; //shift by default
private int multiSelectKey = DEFAULT_KEY; //ctrl (or command on mac) by default
private Array<ItemT> selection = new Array<ItemT>();
private ListSelection (AbstractListAdapter<ItemT, ViewT> adapter) {
this.adapter = adapter;
}
public void select (ItemT item) {
select(item, adapter.getViews().get(item));
}
public void deselect (ItemT item) {
deselect(item, adapter.getViews().get(item));
}
void select (ItemT item, ViewT view) {
if (adapter.getSelectionMode() == SelectionMode.MULTIPLE && selection.size >= 1 && isGroupMultiSelectKeyPressed()) {
selectGroup(item);
}
doSelect(item, view);
}
private void doSelect (ItemT item, ViewT view) {
if (selection.contains(item, true) == false) {
adapter.selectView(view);
selection.add(item);
}
}
private void selectGroup (ItemT newItem) {
int thisSelectionIndex = adapter.indexOf(newItem);
int lastSelectionIndex = adapter.indexOf(selection.peek());
int start;
int end;
if (thisSelectionIndex > lastSelectionIndex) {
start = lastSelectionIndex;
end = thisSelectionIndex;
} else {
start = thisSelectionIndex;
end = lastSelectionIndex;
}
for (int i = start; i < end; i++) {
ItemT item = adapter.get(i);
doSelect(item, adapter.getViews().get(item));
}
}
void deselect (ItemT item, ViewT view) {
if (selection.contains(item, true) == false) return;
adapter.deselectView(view);
selection.removeValue(item, true);
}
public void deselectAll () {
Array<ItemT> items = new Array<ItemT>(selection);
for (ItemT item : items) {
deselect(item);
}
}
/** @return internal array, MUST NOT be modified directly */
public Array<ItemT> getSelection () {
return selection;
}
void touchDown (ViewT view, ItemT item) {
if (adapter.getSelectionMode() == SelectionMode.DISABLED) return;
if (isMultiSelectKeyPressed() == false && isGroupMultiSelectKeyPressed() == false) {
deselectAll();
}
if (selection.contains(item, true) == false) {
if (adapter.getSelectionMode() == SelectionMode.SINGLE) deselectAll();
select(item, view);
} else {
deselect(item, view);
}
}
public int getMultiSelectKey () {
return multiSelectKey;
}
/** @param multiSelectKey from {@link Keys} or {@link ListSelection#DEFAULT_KEY} to restore default */
public void setMultiSelectKey (int multiSelectKey) {
this.multiSelectKey = multiSelectKey;
}
public int getGroupMultiSelectKey () {
return groupMultiSelectKey;
}
/** @param groupMultiSelectKey from {@link Keys} or {@link ListSelection#DEFAULT_KEY} to restore default */
public void setGroupMultiSelectKey (int groupMultiSelectKey) {
this.groupMultiSelectKey = groupMultiSelectKey;
}
private boolean isMultiSelectKeyPressed () {
if (multiSelectKey == DEFAULT_KEY)
return UIUtils.ctrl();
else
return Gdx.input.isKeyPressed(multiSelectKey);
}
private boolean isGroupMultiSelectKeyPressed () {
if (groupMultiSelectKey == DEFAULT_KEY)
return UIUtils.shift();
else
return Gdx.input.isKeyPressed(groupMultiSelectKey);
}
}
}
|
UI/src/com/kotcrab/vis/ui/util/adapter/AbstractListAdapter.java
|
/*
* Copyright 2014-2016 See AUTHORS file.
*
* 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.kotcrab.vis.ui.util.adapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.UIUtils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.reflect.ClassReflection;
import com.kotcrab.vis.ui.widget.ListView;
import com.kotcrab.vis.ui.widget.ListView.ItemClickListener;
import com.kotcrab.vis.ui.widget.ListView.ListAdapterListener;
import com.kotcrab.vis.ui.widget.VisTable;
import java.util.Comparator;
/**
* Basic {@link ListAdapter} implementation using {@link CachedItemAdapter}. Supports item selection. Classes
* extending this should store provided list and provide delegates for all common methods that change array state.
* Those delegates should call {@link #itemAdded(Object)} or {@link #itemRemoved(Object)} in order to properly update
* view cache. When changes to array are too big to be handled by those two methods {@link #itemsChanged()} should be
* called. When only items fields has changed, and no new item were added or removed you should call
* {@link #itemsDataChanged()}.
* <p>
* When view does not existed in cache and must be created {@link #createView(Object)} is called. When item view exists
* in cache {@link #updateView(Actor, Object)} will be called.
* <p>
* Enabling item selection requires calling {@link #setSelectionMode(SelectionMode)} and overriding
* {@link #selectView(Actor)} and {@link #deselectView(Actor)}.
* @author Kotcrab
* @see ArrayAdapter
* @see ArrayListAdapter
* @since 1.0.0
*/
public abstract class AbstractListAdapter<ItemT, ViewT extends Actor> extends CachedItemAdapter<ItemT, ViewT>
implements ListAdapter<ItemT> {
protected ListView<ItemT> view;
protected ListAdapterListener viewListener;
private ItemClickListener<ItemT> clickListener;
private SelectionMode selectionMode = SelectionMode.DISABLED;
private ListSelection<ItemT, ViewT> selection = new ListSelection<ItemT, ViewT>(this);
private Comparator<ItemT> itemsComparator;
@Override
public void fillTable (VisTable itemsTable) {
if (itemsComparator != null) sort(itemsComparator);
for (final ItemT item : iterable()) {
final ViewT view = getView(item);
boolean listenerMissing = true;
for (EventListener listener : view.getListeners()) {
if (ClassReflection.isInstance(ListClickListener.class, listener)) {
listenerMissing = false;
break;
}
}
if (listenerMissing) {
view.setTouchable(Touchable.enabled);
view.addListener(new ListClickListener(view, item));
}
itemsTable.add(view).growX();
itemsTable.row();
}
}
@Override
public void setListView (ListView<ItemT> view, ListAdapterListener viewListener) {
if(view != null) throw new IllegalStateException("Adapter was already asigned to ListView");
this.view = view;
this.viewListener = viewListener;
}
@Override
public void setItemClickListener (ItemClickListener<ItemT> listener) {
clickListener = listener;
}
protected void itemAdded (ItemT item) {
viewListener.invalidateDataSet();
}
protected void itemRemoved (ItemT item) {
getViews().remove(item);
viewListener.invalidateDataSet();
}
/**
* Notifies adapter that underlying collection has changed, ie. some items were added or removed. This does not need to
* be called when only the fields of stored objects changed see {@link #itemsDataChanged()}.
*/
public void itemsChanged () {
getViews().clear();
viewListener.invalidateDataSet();
}
/**
* Notifies adapter that data of items has changed. This means that objects fields in underlying collection has changed
* and views needs updating. This must not be called if some items were removed or added from collection for that
* {@link #itemsChanged()}
*/
public void itemsDataChanged () {
viewListener.invalidateDataSet();
}
@Override
protected void updateView (ViewT view, ItemT item) {
}
public SelectionMode getSelectionMode () {
return selectionMode;
}
public void setSelectionMode (SelectionMode selectionMode) {
if (selectionMode == null) throw new IllegalArgumentException("selectionMode can't be null");
this.selectionMode = selectionMode;
}
/**
* Sets items comparator allowing to define order in which items will be displayed in list view. This will sort
* underlaying array before building views.
* @param comparator that will be used to compare items
*/
public void setItemsSorter (Comparator<ItemT> comparator) {
this.itemsComparator = comparator;
}
/** @return selected items, must not be modified */
public Array<ItemT> getSelection () {
return selection.getSelection();
}
public ListSelection<ItemT, ViewT> getSelectionManager () {
return selection;
}
protected void selectView (ViewT view) {
if (selectionMode == SelectionMode.DISABLED) return;
throw new UnsupportedOperationException("selectView must be implemented when `selectionMode` is different than SelectionMode.DISABLED");
}
protected void deselectView (ViewT view) {
if (selectionMode == SelectionMode.DISABLED) return;
throw new UnsupportedOperationException("deselectView must be implemented when `selectionMode` is different than SelectionMode.DISABLED");
}
private class ListClickListener extends ClickListener {
private ViewT view;
private ItemT item;
public ListClickListener (ViewT view, ItemT item) {
this.view = view;
this.item = item;
}
@Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
super.touchDown(event, x, y, pointer, button);
selection.touchDown(view, item);
return true;
}
@Override
public void clicked (InputEvent event, float x, float y) {
if (clickListener != null) clickListener.clicked(item);
}
}
protected abstract void sort (Comparator<ItemT> comparator);
public enum SelectionMode {
/** Selecting items is not possible. */
DISABLED,
/**
* Only one element can be selected. {@link AbstractListAdapter#selectView(Actor)} and
* {@link AbstractListAdapter#deselectView(Actor)} must be implemented.
*/
SINGLE,
/**
* Multiple elements can be selected. {@link AbstractListAdapter#selectView(Actor)} and
* {@link AbstractListAdapter#deselectView(Actor)} must be implemented.
*/
MULTIPLE
}
/**
* Manages selection of {@link AbstractListAdapter} items.
* @author Kotcrab
*/
public static class ListSelection<ItemT, ViewT extends Actor> {
private AbstractListAdapter<ItemT, ViewT> adapter;
public static final int DEFAULT_KEY = -1;
private int groupMultiSelectKey = DEFAULT_KEY; //shift by default
private int multiSelectKey = DEFAULT_KEY; //ctrl (or command on mac) by default
private Array<ItemT> selection = new Array<ItemT>();
private ListSelection (AbstractListAdapter<ItemT, ViewT> adapter) {
this.adapter = adapter;
}
public void select (ItemT item) {
select(item, adapter.getViews().get(item));
}
public void deselect (ItemT item) {
deselect(item, adapter.getViews().get(item));
}
void select (ItemT item, ViewT view) {
if (adapter.getSelectionMode() == SelectionMode.MULTIPLE && selection.size >= 1 && isGroupMultiSelectKeyPressed()) {
selectGroup(item);
}
doSelect(item, view);
}
private void doSelect (ItemT item, ViewT view) {
if (selection.contains(item, true) == false) {
adapter.selectView(view);
selection.add(item);
}
}
private void selectGroup (ItemT newItem) {
int thisSelectionIndex = adapter.indexOf(newItem);
int lastSelectionIndex = adapter.indexOf(selection.peek());
int start;
int end;
if (thisSelectionIndex > lastSelectionIndex) {
start = lastSelectionIndex;
end = thisSelectionIndex;
} else {
start = thisSelectionIndex;
end = lastSelectionIndex;
}
for (int i = start; i < end; i++) {
ItemT item = adapter.get(i);
doSelect(item, adapter.getViews().get(item));
}
}
void deselect (ItemT item, ViewT view) {
if (selection.contains(item, true) == false) return;
adapter.deselectView(view);
selection.removeValue(item, true);
}
public void deselectAll () {
Array<ItemT> items = new Array<ItemT>(selection);
for (ItemT item : items) {
deselect(item);
}
}
/** @return internal array, MUST NOT be modified directly */
public Array<ItemT> getSelection () {
return selection;
}
void touchDown (ViewT view, ItemT item) {
if (adapter.getSelectionMode() == SelectionMode.DISABLED) return;
if (isMultiSelectKeyPressed() == false && isGroupMultiSelectKeyPressed() == false) {
deselectAll();
}
if (selection.contains(item, true) == false) {
if (adapter.getSelectionMode() == SelectionMode.SINGLE) deselectAll();
select(item, view);
} else {
deselect(item, view);
}
}
public int getMultiSelectKey () {
return multiSelectKey;
}
/** @param multiSelectKey from {@link Keys} or {@link ListSelection#DEFAULT_KEY} to restore default */
public void setMultiSelectKey (int multiSelectKey) {
this.multiSelectKey = multiSelectKey;
}
public int getGroupMultiSelectKey () {
return groupMultiSelectKey;
}
/** @param groupMultiSelectKey from {@link Keys} or {@link ListSelection#DEFAULT_KEY} to restore default */
public void setGroupMultiSelectKey (int groupMultiSelectKey) {
this.groupMultiSelectKey = groupMultiSelectKey;
}
private boolean isMultiSelectKeyPressed () {
if (multiSelectKey == DEFAULT_KEY)
return UIUtils.ctrl();
else
return Gdx.input.isKeyPressed(multiSelectKey);
}
private boolean isGroupMultiSelectKeyPressed () {
if (groupMultiSelectKey == DEFAULT_KEY)
return UIUtils.shift();
else
return Gdx.input.isKeyPressed(groupMultiSelectKey);
}
}
}
|
Add forgotten this
|
UI/src/com/kotcrab/vis/ui/util/adapter/AbstractListAdapter.java
|
Add forgotten this
|
|
Java
|
apache-2.0
|
901659312ce0292bea551ac34d363470ba2c2cf6
| 0
|
pmcs/parity,paritytrading/parity,paritytrading/parity,pmcs/parity
|
package com.paritytrading.parity.fix;
import java.io.Closeable;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.List;
class Events {
private static final int TIMEOUT = 500;
public static void process(FIXAcceptor fix) throws IOException {
Selector selector = Selector.open();
final List<Session> toKeepAlive = new ArrayList<>();
final List<Session> toCleanUp = new ArrayList<>();
fix.getServerChannel().register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int numKeys = selector.select(TIMEOUT);
if (numKeys > 0) {
for (SelectionKey key : selector.selectedKeys()) {
if (key.isAcceptable()) {
final Session session = fix.accept();
if (session == null)
continue;
session.getFIX().getChannel().register(selector,
SelectionKey.OP_READ, new Receiver() {
@Override
public void close() {
toCleanUp.add(session);
}
@Override
public int receive() throws IOException {
return session.getFIX().receive();
}
});
session.getOrderEntry().getChannel().register(selector,
SelectionKey.OP_READ, new Receiver() {
@Override
public void close() {
toCleanUp.add(session);
}
@Override
public int receive() throws IOException {
return session.getOrderEntry().receive();
}
});
toKeepAlive.add(session);
} else {
Receiver receiver = (Receiver)key.attachment();
try {
if (receiver.receive() < 0)
receiver.close();
} catch (IOException e1) {
try {
receiver.close();
} catch (IOException e2) {
}
}
}
}
selector.selectedKeys().clear();
}
for (int i = 0; i < toKeepAlive.size(); i++) {
Session session = toKeepAlive.get(i);
session.getFIX().updateCurrentTimestamp();
try {
session.getOrderEntry().keepAlive();
session.getFIX().keepAlive();
} catch (IOException e) {
toCleanUp.add(session);
}
}
if (toCleanUp.isEmpty())
continue;
for (int i = 0; i < toCleanUp.size(); i++) {
try (Session session = toCleanUp.get(i)) {
toKeepAlive.remove(session);
}
}
toCleanUp.clear();
}
}
private interface Receiver extends Closeable {
int receive() throws IOException;
}
}
|
applications/fix/src/main/java/com/paritytrading/parity/fix/Events.java
|
package com.paritytrading.parity.fix;
import java.io.Closeable;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.ArrayList;
import java.util.List;
class Events {
private static final int TIMEOUT = 500;
public static void process(FIXAcceptor fix) throws IOException {
Selector selector = Selector.open();
final List<Session> toKeepAlive = new ArrayList<>();
final List<Session> toCleanUp = new ArrayList<>();
fix.getServerChannel().register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int numKeys = selector.select(TIMEOUT);
if (numKeys > 0) {
for (SelectionKey key : selector.selectedKeys()) {
if (key.isAcceptable()) {
final Session session = fix.accept();
if (session == null)
continue;
session.getFIX().getChannel().register(selector,
SelectionKey.OP_READ, new Receiver() {
@Override
public void close() {
toCleanUp.add(session);
}
@Override
public int receive() throws IOException {
return session.getFIX().receive();
}
});
session.getOrderEntry().getChannel().register(selector,
SelectionKey.OP_READ, new Receiver() {
@Override
public void close() {
toCleanUp.add(session);
}
@Override
public int receive() throws IOException {
return session.getOrderEntry().receive();
}
});
toKeepAlive.add(session);
} else {
Receiver receiver = (Receiver)key.attachment();
try {
if (receiver.receive() < 0)
receiver.close();
} catch (IOException e1) {
try {
receiver.close();
} catch (IOException e2) {
}
}
}
}
selector.selectedKeys().clear();
}
for (int i = 0; i < toKeepAlive.size(); i++) {
Session session = toKeepAlive.get(i);
session.getFIX().updateCurrentTimestamp();
try {
session.getOrderEntry().keepAlive();
session.getFIX().keepAlive();
} catch (IOException e) {
toCleanUp.add(session);
}
}
if (toCleanUp.isEmpty())
continue;
for (int i = 0; i < toCleanUp.size(); i++) {
Session session = toCleanUp.get(i);
toKeepAlive.remove(session);
try {
session.close();
} catch (IOException e) {
}
}
toCleanUp.clear();
}
}
private interface Receiver extends Closeable {
int receive() throws IOException;
}
}
|
Use try-with-resources to close resources.
|
applications/fix/src/main/java/com/paritytrading/parity/fix/Events.java
|
Use try-with-resources to close resources.
|
|
Java
|
apache-2.0
|
30b1e463b88d8c5eb5571fb95c9af38c8bd5db4a
| 0
|
zmeenosez/akosolapov
|
package ru.job4j.max;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author Aleksey Kosolapov.
* @since 15.03.17.
* @version 0.1.
*/
public class MaxTest {
/**
* Test maximum.
*/
@Test
public void whenMaximumThreeMoreOneThenThree() {
Max max1 = new Max();
int maximum = max1.max(3, 1);
int expected = 3;
assertThat(maximum, is(expected));
}
/**
* Максимум из трех чисел.
*/
@Test
public void whenMaximumThreeMoreTwoMoreOneThenThree() {
Max max1 = new Max();
int maximum = max1.max(3, 2, 1);
int expected = 3;
assertThat(maximum, is(expected));
}
}
|
chapter_001/src/test/java/ru/job4j/max/MaxTest.java
|
package ru.job4j.max;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author Aleksey Kosolapov.
* @since 15.03.17.
* @version 0.1.
*/
public class MaxTest {
/**
* Test maximum.
*/
@Test
public void whenMaximumThreeMoreOneThenThree() {
Max max1 = new Max();
int maximum = max1.max(3, 1);
int expected = 3;
assertThat(maximum, is(expected));
}
}
|
максимум из трёх чисел
|
chapter_001/src/test/java/ru/job4j/max/MaxTest.java
|
максимум из трёх чисел
|
|
Java
|
apache-2.0
|
6205e9cc1e0596fa83f9da3cc6463078fe9be48b
| 0
|
onyxbits/listmyaps,onyxbits/listmyaps
|
package de.onyxbits.listmyapps;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
public class ListTask extends
AsyncTask<Object, Object, ArrayList<SortablePackageInfo>> {
private ListView listView;
private MainActivity mainActivity;
public ListTask(MainActivity mainActivity, ListView listView) {
this.listView = listView;
this.mainActivity = mainActivity;
}
@Override
protected ArrayList<SortablePackageInfo> doInBackground(Object... params) {
SharedPreferences prefs = mainActivity.getSharedPreferences(
MainActivity.PREFSFILE, 0);
ArrayList<SortablePackageInfo> ret = new ArrayList<SortablePackageInfo>();
PackageManager pm = mainActivity.getPackageManager();
List<PackageInfo> list = pm.getInstalledPackages(0);
SortablePackageInfo spitmp[] = new SortablePackageInfo[list.size()];
Iterator<PackageInfo> it = list.iterator();
int idx = 0;
while (it.hasNext()) {
PackageInfo info = it.next();
try {
ApplicationInfo ai = pm.getApplicationInfo(info.packageName, 0);
if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != ApplicationInfo.FLAG_SYSTEM
&& (ai.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) {
CharSequence tmp = pm.getApplicationLabel(info.applicationInfo);
String inst = pm.getInstallerPackageName(info.packageName);
spitmp[idx] = new SortablePackageInfo(info.packageName, tmp, true,
inst);
idx++;
}
}
catch (NameNotFoundException exp) {
}
}
SortablePackageInfo spi[] = new SortablePackageInfo[idx];
System.arraycopy(spitmp, 0, spi, 0, idx);
Arrays.sort(spi);
for (int i = 0; i < spi.length; i++) {
spi[i].selected = prefs.getBoolean(MainActivity.SELECTED + "."
+ spi[i].packageName, false);
ret.add(spi[i]);
}
return ret;
}
@Override
protected void onPostExecute(ArrayList<SortablePackageInfo> result) {
super.onPostExecute(result);
listView
.setAdapter(new AppAdapter(mainActivity, R.layout.app_item, result));
mainActivity.apps = result;
mainActivity.setProgressBarIndeterminate(false);
mainActivity.setProgressBarVisibility(false);
}
}
|
src/de/onyxbits/listmyapps/ListTask.java
|
package de.onyxbits.listmyapps;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
public class ListTask extends
AsyncTask<Object, Object, ArrayList<SortablePackageInfo>> {
private ListView listView;
private MainActivity mainActivity;
public ListTask(MainActivity mainActivity, ListView listView) {
this.listView = listView;
this.mainActivity = mainActivity;
}
@Override
protected ArrayList<SortablePackageInfo> doInBackground(Object... params) {
SharedPreferences prefs = mainActivity.getSharedPreferences(MainActivity.PREFSFILE, 0);
ArrayList<SortablePackageInfo> ret = new ArrayList<SortablePackageInfo>();
PackageManager pm = mainActivity.getPackageManager();
List<PackageInfo> list = pm.getInstalledPackages(0);
SortablePackageInfo spitmp[] = new SortablePackageInfo[list.size()];
Iterator<PackageInfo> it = list.iterator();
int idx = 0;
while (it.hasNext()) {
PackageInfo info = it.next();
CharSequence tmp = pm.getApplicationLabel(info.applicationInfo);
if (pm.getLaunchIntentForPackage(info.packageName) != null) {
String inst = pm.getInstallerPackageName(info.packageName);
spitmp[idx] = new SortablePackageInfo(info.packageName, tmp,true,inst);
idx++;
}
}
SortablePackageInfo spi[] = new SortablePackageInfo[idx];
System.arraycopy(spitmp, 0, spi, 0, idx);
Arrays.sort(spi);
for (int i = 0; i < spi.length; i++) {
spi[i].selected=prefs.getBoolean(MainActivity.SELECTED+"."+spi[i].packageName,false);
ret.add(spi[i]);
}
return ret;
}
@Override
protected void onPostExecute(ArrayList<SortablePackageInfo> result) {
super.onPostExecute(result);
listView
.setAdapter(new AppAdapter(mainActivity, R.layout.app_item, result));
mainActivity.apps=result;
mainActivity.setProgressBarIndeterminate(false);
mainActivity.setProgressBarVisibility(false);
}
}
|
Better way to filter away system apps
|
src/de/onyxbits/listmyapps/ListTask.java
|
Better way to filter away system apps
|
|
Java
|
apache-2.0
|
fbce8c7a410ab18f0e655ee9f68c300dcaa82653
| 0
|
gayangunarathne/stratos,apache/stratos,pkdevbox/stratos,Thanu/stratos,hsbhathiya/stratos,hsbhathiya/stratos,Thanu/stratos,dinithis/stratos,pkdevbox/stratos,anuruddhal/stratos,asankasanjaya/stratos,agentmilindu/stratos,gayangunarathne/stratos,hsbhathiya/stratos,hsbhathiya/stratos,pkdevbox/stratos,lasinducharith/stratos,pubudu538/stratos,lasinducharith/stratos,apache/stratos,agentmilindu/stratos,gayangunarathne/stratos,hsbhathiya/stratos,dinithis/stratos,agentmilindu/stratos,dinithis/stratos,anuruddhal/stratos,pubudu538/stratos,pubudu538/stratos,gayangunarathne/stratos,pkdevbox/stratos,anuruddhal/stratos,ravihansa3000/stratos,hsbhathiya/stratos,pkdevbox/stratos,Thanu/stratos,lasinducharith/stratos,ravihansa3000/stratos,apache/stratos,asankasanjaya/stratos,lasinducharith/stratos,lasinducharith/stratos,gayangunarathne/stratos,asankasanjaya/stratos,agentmilindu/stratos,asankasanjaya/stratos,gayangunarathne/stratos,asankasanjaya/stratos,Thanu/stratos,pkdevbox/stratos,agentmilindu/stratos,asankasanjaya/stratos,anuruddhal/stratos,Thanu/stratos,apache/stratos,dinithis/stratos,apache/stratos,apache/stratos,hsbhathiya/stratos,ravihansa3000/stratos,dinithis/stratos,asankasanjaya/stratos,dinithis/stratos,ravihansa3000/stratos,apache/stratos,ravihansa3000/stratos,agentmilindu/stratos,lasinducharith/stratos,pubudu538/stratos,anuruddhal/stratos,agentmilindu/stratos,anuruddhal/stratos,dinithis/stratos,pubudu538/stratos,lasinducharith/stratos,ravihansa3000/stratos,pkdevbox/stratos,gayangunarathne/stratos,ravihansa3000/stratos,anuruddhal/stratos,Thanu/stratos,pubudu538/stratos,Thanu/stratos,pubudu538/stratos
|
/*
* 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.stratos.metadataservice.services;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.metadataservice.annotation.AuthorizationAction;
import org.apache.stratos.metadataservice.definition.NewProperty;
import org.apache.stratos.metadataservice.exception.RestAPIException;
import org.apache.stratos.metadataservice.registry.DataRegistryFactory;
import org.apache.stratos.metadataservice.registry.DataStore;
import org.apache.stratos.metadataservice.util.ConfUtil;
import org.wso2.carbon.registry.api.RegistryException;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.List;
@Path("/")
public class MetaDataAdmin {
@Context
UriInfo uriInfo;
private static Log log = LogFactory.getLog(MetaDataAdmin.class);
private DataStore registry;
/**
* Meta data admin configuration loading
*/
public MetaDataAdmin(){
XMLConfiguration conf = ConfUtil.getInstance(null).getConfiguration();
String DEFAULT_REG_TYPE = "carbon";
String registryType = conf.getString("metadataservice.govenanceregistrytype", DEFAULT_REG_TYPE);
registry = DataRegistryFactory.getDataStore(registryType);
}
@GET
@Path("/application/{application_id}/cluster/{cluster_id}/properties")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response getClusterProperties(@PathParam("application_id") String applicationId, @PathParam("cluster_id") String clusterId) throws RestAPIException{
List<NewProperty> properties;
NewProperty[] propertiesArr = null;
try {
properties = registry
.getPropertiesOfCluster(applicationId, clusterId);
if (properties != null) {
propertiesArr = new NewProperty[properties.size()];
propertiesArr = properties.toArray(propertiesArr);
}
} catch (RegistryException e) {
String msg = "Error occurred while getting properties ";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
Response.ResponseBuilder rb;
if (propertiesArr == null) {
rb = Response.status(Response.Status.NOT_FOUND);
} else {
rb = Response.ok().entity(propertiesArr);
}
return rb.build();
}
@GET
@Path("/application/{application_id}/cluster/{cluster_id}/property/{property_name}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response getClusterProperty(@PathParam("application_id") String applicationId, @PathParam("cluster_id") String clusterId, @PathParam("property_name") String propertyName) throws RestAPIException{
List<NewProperty> properties;
NewProperty property = null;
try {
properties = registry
.getPropertiesOfCluster(applicationId, clusterId);
if (properties == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
for (NewProperty p : properties) {
if (propertyName.equals(p.getKey())) {
property = p;
break;
}
}
} catch (RegistryException e) {
String msg = "Error occurred while getting property";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
Response.ResponseBuilder rb;
if (property == null) {
rb = Response.status(Response.Status.NOT_FOUND);
} else {
rb = Response.ok().entity(property);
}
return rb.build();
}
@POST
@Path("application/{application_id}/cluster/{cluster_id}/property")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response addPropertyToACluster(@PathParam("application_id") String applicationId, @PathParam("cluster_id") String clusterId, NewProperty property)
throws RestAPIException {
URI url = uriInfo.getAbsolutePathBuilder().path(applicationId + "/" + clusterId + "/" + property.getKey()).build();
try {
registry.addPropertyToCluster(applicationId, clusterId, property);
} catch (RegistryException e) {
String msg = "Error occurred while adding property";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
return Response.created(url).build();
}
@POST
@Path("application/{application_id}/cluster/{cluster_id}/properties")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response addPropertiesToACluster(@PathParam("application_id") String applicationId, @PathParam("cluster_id") String clusterId, NewProperty[] properties)
throws RestAPIException {
URI url = uriInfo.getAbsolutePathBuilder().path(applicationId + "/" + clusterId).build();
try {
registry.addPropertiesToCluster(applicationId, clusterId, properties);
} catch (RegistryException e) {
String msg = "Error occurred while adding properties ";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
return Response.created(url).build();
}
@DELETE
@Path("application/{application_id}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response deleteApplicationProperties(@PathParam("application_id") String applicationId)
throws RestAPIException {
try {
boolean deleted = registry.deleteApplication(applicationId);
if (!deleted) {
log.warn(String.format(
"Either no metadata is associated with given appId %s Or resources could not be deleted",
applicationId));
}
} catch (RegistryException e) {
String msg = "Resource attached with appId could not be deleted";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
return Response.ok().build();
}
}
|
components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/services/MetaDataAdmin.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.stratos.metadataservice.services;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.metadataservice.annotation.AuthorizationAction;
import org.apache.stratos.metadataservice.definition.NewProperty;
import org.apache.stratos.metadataservice.exception.RestAPIException;
import org.apache.stratos.metadataservice.registry.DataRegistryFactory;
import org.apache.stratos.metadataservice.registry.DataStore;
import org.apache.stratos.metadataservice.util.ConfUtil;
import org.wso2.carbon.registry.api.RegistryException;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.List;
@Path("/")
public class MetaDataAdmin {
@Context
UriInfo uriInfo;
private static Log log = LogFactory.getLog(MetaDataAdmin.class);
private DataStore registry;
/**
* Meta data admin configuration loading
*/
public MetaDataAdmin(){
XMLConfiguration conf = ConfUtil.getInstance(null).getConfiguration();
String DEFAULT_REG_TYPE = "carbon";
String registryType = conf.getString("metadataservice.govenanceregistrytype", DEFAULT_REG_TYPE);
registry = DataRegistryFactory.getDataStore(registryType);
}
@GET
@Path("/application/{application_id}/cluster/{cluster_id}/properties")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response getClusterProperties(@PathParam("application_id") String applicationId, @PathParam("cluster_id") String clusterId) throws RestAPIException{
List<NewProperty> properties;
NewProperty[] propertiesArr = null;
try {
properties = registry
.getPropertiesOfCluster(applicationId, clusterId);
if (properties != null) {
propertiesArr = new NewProperty[properties.size()];
propertiesArr = properties.toArray(propertiesArr);
}
} catch (RegistryException e) {
String msg = "Error occurred while getting properties ";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
Response.ResponseBuilder rb;
if (propertiesArr == null) {
rb = Response.status(Response.Status.NOT_FOUND);
} else {
rb = Response.ok().entity(propertiesArr);
}
return rb.build();
}
@GET
@Path("/application/{application_id}/cluster/{cluster_id}/property/{property_name}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response getClusterProperty(@PathParam("application_id") String applicationId, @PathParam("cluster_id") String clusterId, @PathParam("property_name") String propertyName) throws RestAPIException{
List<NewProperty> properties;
NewProperty property = null;
try {
properties = registry
.getPropertiesOfCluster(applicationId, clusterId);
if (properties == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
for (NewProperty p : properties) {
if (propertyName.equals(p.getKey())) {
property = p;
break;
}
}
} catch (RegistryException e) {
String msg = "Error occurred while adding property";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
Response.ResponseBuilder rb;
if (property == null) {
rb = Response.status(Response.Status.NOT_FOUND);
} else {
rb = Response.ok().entity(property);
}
return rb.build();
}
@POST
@Path("application/{application_id}/cluster/{cluster_id}/property")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response addPropertyToACluster(@PathParam("application_id") String applicationId, @PathParam("cluster_id") String clusterId, NewProperty property)
throws RestAPIException {
URI url = uriInfo.getAbsolutePathBuilder().path(applicationId + "/" + clusterId + "/" + property.getKey()).build();
try {
registry.addPropertyToCluster(applicationId, clusterId, property);
} catch (RegistryException e) {
String msg = "Error occurred while adding property";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
return Response.created(url).build();
}
@POST
@Path("application/{application_id}/cluster/{cluster_id}/properties")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response addPropertiesToACluster(@PathParam("application_id") String applicationId, @PathParam("cluster_id") String clusterId, NewProperty[] properties)
throws RestAPIException {
URI url = uriInfo.getAbsolutePathBuilder().path(applicationId + "/" + clusterId).build();
try {
registry.addPropertiesToCluster(applicationId, clusterId, properties);
} catch (RegistryException e) {
String msg = "Error occurred while adding properties ";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
return Response.created(url).build();
}
@DELETE
@Path("application/{application_id}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response deleteApplicationProperties(@PathParam("application_id") String applicationId)
throws RestAPIException {
try {
boolean deleted = registry.deleteApplication(applicationId);
if (!deleted) {
log.warn(String.format(
"Either no metadata is associated with given appId %s Or resources could not be deleted",
applicationId));
}
} catch (RegistryException e) {
String msg = "Resource attached with appId could not be deleted";
log.error(msg, e);
throw new RestAPIException(msg, e);
}
return Response.ok().build();
}
}
|
Update the messaging model util with apache commons isNumber util method
|
components/org.apache.stratos.metadataservice/src/main/java/org/apache/stratos/metadataservice/services/MetaDataAdmin.java
|
Update the messaging model util with apache commons isNumber util method
|
|
Java
|
apache-2.0
|
4520268303efb4571da5cf8c7679e17029d1d950
| 0
|
spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth,spring-cloud/spring-cloud-sleuth
|
/*
* Copyright 2013-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.springframework.cloud.sleuth.instrument.web;
import static org.assertj.core.api.Assertions.fail;
import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.cloud.sleuth.Sampler;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.assertions.ListOfSpans;
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import org.springframework.cloud.sleuth.trace.TestSpanContextHolder;
import org.springframework.cloud.sleuth.util.ArrayListSpanAccumulator;
import org.springframework.cloud.sleuth.util.ExceptionUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
/**
* @author Marcin Grzejszczak
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TraceFilterWebIntegrationTests.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TraceFilterWebIntegrationTests {
@Autowired Tracer tracer;
@Autowired ArrayListSpanAccumulator accumulator;
@Autowired RestTemplate restTemplate;
@Autowired Environment environment;
@Rule public OutputCapture capture = new OutputCapture();
@Before
@After
public void cleanup() {
ExceptionUtils.setFail(true);
TestSpanContextHolder.removeCurrentSpan();
this.accumulator.clear();
}
@Test
public void should_not_create_a_span_for_error_controller() {
this.restTemplate.getForObject("http://localhost:" + port() + "/", String.class);
then(this.tracer.getCurrentSpan()).isNull();
then(new ListOfSpans(this.accumulator.getSpans()))
.doesNotHaveASpanWithName("error")
.hasASpanWithTagEqualTo("http.status_code", "500");
then(ExceptionUtils.getLastException()).isNull();
then(new ListOfSpans(this.accumulator.getSpans()))
.hasASpanWithTagEqualTo(Span.SPAN_ERROR_TAG_NAME,
"Request processing failed; nested exception is java.lang.RuntimeException: Throwing exception")
.hasRpcTagsInProperOrder();// issue#714
Span span = this.accumulator.getSpans().get(0);
String hex = Span.idToHex(span.getTraceId());
String[] split = capture.toString().split("\n");
List<String> list = Arrays.stream(split).filter(s -> s.contains(
"Uncaught exception thrown"))
.filter(s -> s.contains(hex + "," + hex + ",true]"))
.collect(Collectors.toList());
then(list).isNotEmpty();
}
@Test
public void should_create_spans_for_endpoint_returning_unsuccessful_result() {
try {
new RestTemplate().getForObject("http://localhost:" + port() + "/test_bad_request", String.class);
fail("should throw exception");
} catch (HttpClientErrorException e) {
}
then(this.tracer.getCurrentSpan()).isNull();
then(ExceptionUtils.getLastException()).isNull();
then(new ListOfSpans(this.accumulator.getSpans()))
.hasServerSideSpansInProperOrder();
}
private int port() {
return this.environment.getProperty("local.server.port", Integer.class);
}
@EnableAutoConfiguration
@Configuration
public static class Config {
@Bean ExceptionThrowingController controller() {
return new ExceptionThrowingController();
}
@Bean ArrayListSpanAccumulator arrayListSpanAccumulator() {
return new ArrayListSpanAccumulator();
}
@Bean Sampler alwaysSampler() {
return new AlwaysSampler();
}
@Bean RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override public void handleError(ClientHttpResponse response)
throws IOException {
}
});
return restTemplate;
}
}
@RestController
public static class ExceptionThrowingController {
@RequestMapping("/")
public void throwException() {
throw new RuntimeException("Throwing exception");
}
@RequestMapping(path = "/test_bad_request", method = RequestMethod.GET)
public ResponseEntity<?> processFail() {
return ResponseEntity.badRequest().build();
}
}
}
|
spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterWebIntegrationTests.java
|
/*
* Copyright 2013-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.springframework.cloud.sleuth.instrument.web;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.cloud.sleuth.Sampler;
import org.springframework.cloud.sleuth.Span;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.assertions.ListOfSpans;
import org.springframework.cloud.sleuth.sampler.AlwaysSampler;
import org.springframework.cloud.sleuth.trace.TestSpanContextHolder;
import org.springframework.cloud.sleuth.util.ArrayListSpanAccumulator;
import org.springframework.cloud.sleuth.util.ExceptionUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.fail;
import static org.springframework.cloud.sleuth.assertions.SleuthAssertions.then;
/**
* @author Marcin Grzejszczak
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = TraceFilterWebIntegrationTests.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TraceFilterWebIntegrationTests {
@Autowired Tracer tracer;
@Autowired ArrayListSpanAccumulator accumulator;
@Autowired RestTemplate restTemplate;
@Autowired Environment environment;
@Rule public OutputCapture capture = new OutputCapture();
@Before
@After
public void cleanup() {
ExceptionUtils.setFail(true);
TestSpanContextHolder.removeCurrentSpan();
this.accumulator.clear();
}
@Test
public void should_not_create_a_span_for_error_controller() {
this.restTemplate.getForObject("http://localhost:" + port() + "/", String.class);
then(this.tracer.getCurrentSpan()).isNull();
then(new ListOfSpans(this.accumulator.getSpans()))
.doesNotHaveASpanWithName("error")
.hasASpanWithTagEqualTo("http.status_code", "500");
then(ExceptionUtils.getLastException()).isNull();
then(new ListOfSpans(this.accumulator.getSpans()))
.hasASpanWithTagEqualTo(Span.SPAN_ERROR_TAG_NAME,
"Request processing failed; nested exception is java.lang.RuntimeException: Throwing exception")
.hasRpcTagsInProperOrder();// issue#714
Span span = this.accumulator.getSpans().get(0);
String hex = Span.idToHex(span.getTraceId());
String[] split = capture.toString().split("\n");
List<String> list = Arrays.stream(split).filter(s -> s.contains(
"Uncaught exception thrown"))
.filter(s -> s.contains("[bootstrap," + hex + "," + hex + ",true]"))
.collect(Collectors.toList());
then(list).isNotEmpty();
}
@Test
public void should_create_spans_for_endpoint_returning_unsuccessful_result() {
try {
new RestTemplate().getForObject("http://localhost:" + port() + "/test_bad_request", String.class);
fail("should throw exception");
} catch (HttpClientErrorException e) {
}
then(this.tracer.getCurrentSpan()).isNull();
then(ExceptionUtils.getLastException()).isNull();
then(new ListOfSpans(this.accumulator.getSpans()))
.hasServerSideSpansInProperOrder();
}
private int port() {
return this.environment.getProperty("local.server.port", Integer.class);
}
@EnableAutoConfiguration
@Configuration
public static class Config {
@Bean ExceptionThrowingController controller() {
return new ExceptionThrowingController();
}
@Bean ArrayListSpanAccumulator arrayListSpanAccumulator() {
return new ArrayListSpanAccumulator();
}
@Bean Sampler alwaysSampler() {
return new AlwaysSampler();
}
@Bean RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override public void handleError(ClientHttpResponse response)
throws IOException {
}
});
return restTemplate;
}
}
@RestController
public static class ExceptionThrowingController {
@RequestMapping("/")
public void throwException() {
throw new RuntimeException("Throwing exception");
}
@RequestMapping(path = "/test_bad_request", method = RequestMethod.GET)
public ResponseEntity<?> processFail() {
return ResponseEntity.badRequest().build();
}
}
}
|
Made tests less brittle
|
spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterWebIntegrationTests.java
|
Made tests less brittle
|
|
Java
|
apache-2.0
|
ce41bce9180f60363bf86ddf5e12f19b1e534958
| 0
|
seata/seata,seata/seata,seata/seata,seata/seata,seata/seata
|
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.seata.rm.datasource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.Callable;
import io.seata.common.util.StringUtils;
import io.seata.config.ConfigurationFactory;
import io.seata.core.constants.ConfigurationKeys;
import io.seata.core.exception.TransactionException;
import io.seata.core.exception.TransactionExceptionCode;
import io.seata.core.model.BranchStatus;
import io.seata.core.model.BranchType;
import io.seata.rm.DefaultResourceManager;
import io.seata.rm.datasource.exec.LockConflictException;
import io.seata.rm.datasource.exec.LockRetryController;
import io.seata.rm.datasource.undo.SQLUndoLog;
import io.seata.rm.datasource.undo.UndoLogManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.seata.common.DefaultValues.DEFAULT_CLIENT_LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT;
import static io.seata.common.DefaultValues.DEFAULT_CLIENT_REPORT_RETRY_COUNT;
import static io.seata.common.DefaultValues.DEFAULT_CLIENT_REPORT_SUCCESS_ENABLE;
/**
* The type Connection proxy.
*
* @author sharajava
*/
public class ConnectionProxy extends AbstractConnectionProxy {
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionProxy.class);
private ConnectionContext context = new ConnectionContext();
private static final int REPORT_RETRY_COUNT = ConfigurationFactory.getInstance().getInt(
ConfigurationKeys.CLIENT_REPORT_RETRY_COUNT, DEFAULT_CLIENT_REPORT_RETRY_COUNT);
public static final boolean IS_REPORT_SUCCESS_ENABLE = ConfigurationFactory.getInstance().getBoolean(
ConfigurationKeys.CLIENT_REPORT_SUCCESS_ENABLE, DEFAULT_CLIENT_REPORT_SUCCESS_ENABLE);
private final static LockRetryPolicy LOCK_RETRY_POLICY = new LockRetryPolicy();
/**
* Instantiates a new Connection proxy.
*
* @param dataSourceProxy the data source proxy
* @param targetConnection the target connection
*/
public ConnectionProxy(DataSourceProxy dataSourceProxy, Connection targetConnection) {
super(dataSourceProxy, targetConnection);
}
/**
* Gets context.
*
* @return the context
*/
public ConnectionContext getContext() {
return context;
}
/**
* Bind.
*
* @param xid the xid
*/
public void bind(String xid) {
context.bind(xid);
}
/**
* set global lock requires flag
*
* @param isLock whether to lock
*/
public void setGlobalLockRequire(boolean isLock) {
context.setGlobalLockRequire(isLock);
}
/**
* get global lock requires flag
*/
public boolean isGlobalLockRequire() {
return context.isGlobalLockRequire();
}
/**
* Check lock.
*
* @param lockKeys the lockKeys
* @throws SQLException the sql exception
*/
public void checkLock(String lockKeys) throws SQLException {
if (StringUtils.isBlank(lockKeys)) {
return;
}
// Just check lock without requiring lock by now.
try {
boolean lockable = DefaultResourceManager.get().lockQuery(BranchType.AT,
getDataSourceProxy().getResourceId(), context.getXid(), lockKeys);
if (!lockable) {
throw new LockConflictException();
}
} catch (TransactionException e) {
recognizeLockKeyConflictException(e, lockKeys);
}
}
/**
* Lock query.
*
* @param lockKeys the lock keys
* @throws SQLException the sql exception
*/
public boolean lockQuery(String lockKeys) throws SQLException {
// Just check lock without requiring lock by now.
boolean result = false;
try {
result = DefaultResourceManager.get().lockQuery(BranchType.AT, getDataSourceProxy().getResourceId(),
context.getXid(), lockKeys);
} catch (TransactionException e) {
recognizeLockKeyConflictException(e, lockKeys);
}
return result;
}
private void recognizeLockKeyConflictException(TransactionException te) throws SQLException {
recognizeLockKeyConflictException(te, null);
}
private void recognizeLockKeyConflictException(TransactionException te, String lockKeys) throws SQLException {
if (te.getCode() == TransactionExceptionCode.LockKeyConflict) {
StringBuilder reasonBuilder = new StringBuilder("get global lock fail, xid:");
reasonBuilder.append(context.getXid());
if (StringUtils.isNotBlank(lockKeys)) {
reasonBuilder.append(", lockKeys:").append(lockKeys);
}
throw new LockConflictException(reasonBuilder.toString());
} else {
throw new SQLException(te);
}
}
/**
* append sqlUndoLog
*
* @param sqlUndoLog the sql undo log
*/
public void appendUndoLog(SQLUndoLog sqlUndoLog) {
context.appendUndoItem(sqlUndoLog);
}
/**
* append lockKey
*
* @param lockKey the lock key
*/
public void appendLockKey(String lockKey) {
context.appendLockKey(lockKey);
}
@Override
public void commit() throws SQLException {
try {
LOCK_RETRY_POLICY.execute(() -> {
doCommit();
return null;
});
} catch (SQLException e) {
if (targetConnection != null && !getAutoCommit()) {
rollback();
}
throw e;
} catch (Exception e) {
throw new SQLException(e);
}
}
private void doCommit() throws SQLException {
if (context.inGlobalTransaction()) {
processGlobalTransactionCommit();
} else if (context.isGlobalLockRequire()) {
processLocalCommitWithGlobalLocks();
} else {
targetConnection.commit();
}
}
private void processLocalCommitWithGlobalLocks() throws SQLException {
checkLock(context.buildLockKeys());
try {
targetConnection.commit();
} catch (Throwable ex) {
throw new SQLException(ex);
}
context.reset();
}
private void processGlobalTransactionCommit() throws SQLException {
try {
register();
} catch (TransactionException e) {
recognizeLockKeyConflictException(e, context.buildLockKeys());
}
try {
UndoLogManagerFactory.getUndoLogManager(this.getDbType()).flushUndoLogs(this);
targetConnection.commit();
} catch (Throwable ex) {
LOGGER.error("process connectionProxy commit error: {}", ex.getMessage(), ex);
report(false);
throw new SQLException(ex);
}
if (IS_REPORT_SUCCESS_ENABLE) {
report(true);
}
context.reset();
}
private void register() throws TransactionException {
if (!context.hasUndoLog() || context.getLockKeysBuffer().isEmpty()) {
return;
}
Long branchId = DefaultResourceManager.get().branchRegister(BranchType.AT, getDataSourceProxy().getResourceId(),
null, context.getXid(), null, context.buildLockKeys());
context.setBranchId(branchId);
}
@Override
public void rollback() throws SQLException {
targetConnection.rollback();
if (context.inGlobalTransaction() && context.isBranchRegistered()) {
report(false);
}
context.reset();
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
if ((context.inGlobalTransaction() || context.isGlobalLockRequire()) && autoCommit && !getAutoCommit()) {
// change autocommit from false to true, we should commit() first according to JDBC spec.
doCommit();
}
targetConnection.setAutoCommit(autoCommit);
}
private void report(boolean commitDone) throws SQLException {
if (context.getBranchId() == null) {
return;
}
int retry = REPORT_RETRY_COUNT;
while (retry > 0) {
try {
DefaultResourceManager.get().branchReport(BranchType.AT, context.getXid(), context.getBranchId(),
commitDone ? BranchStatus.PhaseOne_Done : BranchStatus.PhaseOne_Failed, null);
return;
} catch (Throwable ex) {
LOGGER.error("Failed to report [" + context.getBranchId() + "/" + context.getXid() + "] commit done ["
+ commitDone + "] Retry Countdown: " + retry);
retry--;
if (retry == 0) {
throw new SQLException("Failed to report branch status " + commitDone, ex);
}
}
}
}
public static class LockRetryPolicy {
protected static final boolean LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT = ConfigurationFactory
.getInstance().getBoolean(ConfigurationKeys.CLIENT_LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT, DEFAULT_CLIENT_LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT);
public <T> T execute(Callable<T> callable) throws Exception {
if (LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT) {
return callable.call();
} else {
return doRetryOnLockConflict(callable);
}
}
protected <T> T doRetryOnLockConflict(Callable<T> callable) throws Exception {
LockRetryController lockRetryController = new LockRetryController();
while (true) {
try {
return callable.call();
} catch (LockConflictException lockConflict) {
onException(lockConflict);
lockRetryController.sleep(lockConflict);
} catch (Exception e) {
onException(e);
throw e;
}
}
}
/**
* Callback on exception in doLockRetryOnConflict.
*
* @param e invocation exception
* @throws Exception error
*/
protected void onException(Exception e) throws Exception {
}
}
}
|
rm-datasource/src/main/java/io/seata/rm/datasource/ConnectionProxy.java
|
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.seata.rm.datasource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.Callable;
import io.seata.common.util.StringUtils;
import io.seata.config.ConfigurationFactory;
import io.seata.core.constants.ConfigurationKeys;
import io.seata.core.exception.TransactionException;
import io.seata.core.exception.TransactionExceptionCode;
import io.seata.core.model.BranchStatus;
import io.seata.core.model.BranchType;
import io.seata.rm.DefaultResourceManager;
import io.seata.rm.datasource.exec.LockConflictException;
import io.seata.rm.datasource.exec.LockRetryController;
import io.seata.rm.datasource.undo.SQLUndoLog;
import io.seata.rm.datasource.undo.UndoLogManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.seata.common.DefaultValues.DEFAULT_CLIENT_LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT;
import static io.seata.common.DefaultValues.DEFAULT_CLIENT_REPORT_RETRY_COUNT;
import static io.seata.common.DefaultValues.DEFAULT_CLIENT_REPORT_SUCCESS_ENABLE;
/**
* The type Connection proxy.
*
* @author sharajava
*/
public class ConnectionProxy extends AbstractConnectionProxy {
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionProxy.class);
private ConnectionContext context = new ConnectionContext();
private static final int REPORT_RETRY_COUNT = ConfigurationFactory.getInstance().getInt(
ConfigurationKeys.CLIENT_REPORT_RETRY_COUNT, DEFAULT_CLIENT_REPORT_RETRY_COUNT);
public static final boolean IS_REPORT_SUCCESS_ENABLE = ConfigurationFactory.getInstance().getBoolean(
ConfigurationKeys.CLIENT_REPORT_SUCCESS_ENABLE, DEFAULT_CLIENT_REPORT_SUCCESS_ENABLE);
private final static LockRetryPolicy LOCK_RETRY_POLICY = new LockRetryPolicy();
/**
* Instantiates a new Connection proxy.
*
* @param dataSourceProxy the data source proxy
* @param targetConnection the target connection
*/
public ConnectionProxy(DataSourceProxy dataSourceProxy, Connection targetConnection) {
super(dataSourceProxy, targetConnection);
}
/**
* Gets context.
*
* @return the context
*/
public ConnectionContext getContext() {
return context;
}
/**
* Bind.
*
* @param xid the xid
*/
public void bind(String xid) {
context.bind(xid);
}
/**
* set global lock requires flag
*
* @param isLock whether to lock
*/
public void setGlobalLockRequire(boolean isLock) {
context.setGlobalLockRequire(isLock);
}
/**
* get global lock requires flag
*/
public boolean isGlobalLockRequire() {
return context.isGlobalLockRequire();
}
/**
* Check lock.
*
* @param lockKeys the lockKeys
* @throws SQLException the sql exception
*/
public void checkLock(String lockKeys) throws SQLException {
if (StringUtils.isBlank(lockKeys)) {
return;
}
// Just check lock without requiring lock by now.
try {
boolean lockable = DefaultResourceManager.get().lockQuery(BranchType.AT,
getDataSourceProxy().getResourceId(), context.getXid(), lockKeys);
if (!lockable) {
throw new LockConflictException();
}
} catch (TransactionException e) {
recognizeLockKeyConflictException(e, lockKeys);
}
}
/**
* Lock query.
*
* @param lockKeys the lock keys
* @throws SQLException the sql exception
*/
public boolean lockQuery(String lockKeys) throws SQLException {
// Just check lock without requiring lock by now.
boolean result = false;
try {
result = DefaultResourceManager.get().lockQuery(BranchType.AT, getDataSourceProxy().getResourceId(),
context.getXid(), lockKeys);
} catch (TransactionException e) {
recognizeLockKeyConflictException(e, lockKeys);
}
return result;
}
private void recognizeLockKeyConflictException(TransactionException te) throws SQLException {
recognizeLockKeyConflictException(te, null);
}
private void recognizeLockKeyConflictException(TransactionException te, String lockKeys) throws SQLException {
if (te.getCode() == TransactionExceptionCode.LockKeyConflict) {
StringBuilder reasonBuilder = new StringBuilder("get global lock fail, xid:");
reasonBuilder.append(context.getXid());
if (StringUtils.isNotBlank(lockKeys)) {
reasonBuilder.append(", lockKeys:").append(lockKeys);
}
throw new LockConflictException(reasonBuilder.toString());
} else {
throw new SQLException(te);
}
}
/**
* append sqlUndoLog
*
* @param sqlUndoLog the sql undo log
*/
public void appendUndoLog(SQLUndoLog sqlUndoLog) {
context.appendUndoItem(sqlUndoLog);
}
/**
* append lockKey
*
* @param lockKey the lock key
*/
public void appendLockKey(String lockKey) {
context.appendLockKey(lockKey);
}
@Override
public void commit() throws SQLException {
try {
LOCK_RETRY_POLICY.execute(() -> {
doCommit();
return null;
});
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new SQLException(e);
}
}
private void doCommit() throws SQLException {
if (context.inGlobalTransaction()) {
processGlobalTransactionCommit();
} else if (context.isGlobalLockRequire()) {
processLocalCommitWithGlobalLocks();
} else {
targetConnection.commit();
}
}
private void processLocalCommitWithGlobalLocks() throws SQLException {
checkLock(context.buildLockKeys());
try {
targetConnection.commit();
} catch (Throwable ex) {
throw new SQLException(ex);
}
context.reset();
}
private void processGlobalTransactionCommit() throws SQLException {
try {
register();
} catch (TransactionException e) {
recognizeLockKeyConflictException(e, context.buildLockKeys());
}
try {
UndoLogManagerFactory.getUndoLogManager(this.getDbType()).flushUndoLogs(this);
targetConnection.commit();
} catch (Throwable ex) {
LOGGER.error("process connectionProxy commit error: {}", ex.getMessage(), ex);
report(false);
throw new SQLException(ex);
}
if (IS_REPORT_SUCCESS_ENABLE) {
report(true);
}
context.reset();
}
private void register() throws TransactionException {
if (!context.hasUndoLog() || context.getLockKeysBuffer().isEmpty()) {
return;
}
Long branchId = DefaultResourceManager.get().branchRegister(BranchType.AT, getDataSourceProxy().getResourceId(),
null, context.getXid(), null, context.buildLockKeys());
context.setBranchId(branchId);
}
@Override
public void rollback() throws SQLException {
targetConnection.rollback();
if (context.inGlobalTransaction() && context.isBranchRegistered()) {
report(false);
}
context.reset();
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
if (autoCommit && !getAutoCommit()) {
// change autocommit from false to true, we should commit() first according to JDBC spec.
doCommit();
}
targetConnection.setAutoCommit(autoCommit);
}
private void report(boolean commitDone) throws SQLException {
if (context.getBranchId() == null) {
return;
}
int retry = REPORT_RETRY_COUNT;
while (retry > 0) {
try {
DefaultResourceManager.get().branchReport(BranchType.AT, context.getXid(), context.getBranchId(),
commitDone ? BranchStatus.PhaseOne_Done : BranchStatus.PhaseOne_Failed, null);
return;
} catch (Throwable ex) {
LOGGER.error("Failed to report [" + context.getBranchId() + "/" + context.getXid() + "] commit done ["
+ commitDone + "] Retry Countdown: " + retry);
retry--;
if (retry == 0) {
throw new SQLException("Failed to report branch status " + commitDone, ex);
}
}
}
}
public static class LockRetryPolicy {
protected static final boolean LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT = ConfigurationFactory
.getInstance().getBoolean(ConfigurationKeys.CLIENT_LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT, DEFAULT_CLIENT_LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT);
public <T> T execute(Callable<T> callable) throws Exception {
if (LOCK_RETRY_POLICY_BRANCH_ROLLBACK_ON_CONFLICT) {
return callable.call();
} else {
return doRetryOnLockConflict(callable);
}
}
protected <T> T doRetryOnLockConflict(Callable<T> callable) throws Exception {
LockRetryController lockRetryController = new LockRetryController();
while (true) {
try {
return callable.call();
} catch (LockConflictException lockConflict) {
onException(lockConflict);
lockRetryController.sleep(lockConflict);
} catch (Exception e) {
onException(e);
throw e;
}
}
}
/**
* Callback on exception in doLockRetryOnConflict.
*
* @param e invocation exception
* @throws Exception error
*/
protected void onException(Exception e) throws Exception {
}
}
}
|
bugfix: fix repeated commit when autocommit is false (#3040)
|
rm-datasource/src/main/java/io/seata/rm/datasource/ConnectionProxy.java
|
bugfix: fix repeated commit when autocommit is false (#3040)
|
|
Java
|
apache-2.0
|
dc6b7a3b0de8fe39cbf9c6a9ec301f1f6b9a022e
| 0
|
chamikaramj/beam,robertwb/incubator-beam,chamikaramj/beam,apache/beam,RyanSkraba/beam,chamikaramj/beam,lukecwik/incubator-beam,apache/beam,RyanSkraba/beam,iemejia/incubator-beam,robertwb/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,robertwb/incubator-beam,RyanSkraba/beam,robertwb/incubator-beam,robertwb/incubator-beam,lukecwik/incubator-beam,chamikaramj/beam,apache/beam,chamikaramj/beam,lukecwik/incubator-beam,apache/beam,apache/beam,apache/beam,robertwb/incubator-beam,RyanSkraba/beam,lukecwik/incubator-beam,iemejia/incubator-beam,lukecwik/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,robertwb/incubator-beam,lukecwik/incubator-beam,robertwb/incubator-beam,RyanSkraba/beam,apache/beam,chamikaramj/beam,RyanSkraba/beam,RyanSkraba/beam,lukecwik/incubator-beam,lukecwik/incubator-beam,apache/beam,robertwb/incubator-beam,chamikaramj/beam,apache/beam,apache/beam,apache/beam,chamikaramj/beam,chamikaramj/beam
|
/*
* 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.beam.runners.dataflow.worker.windmill;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.SequenceInputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.apache.beam.runners.dataflow.worker.WindmillTimeUtils;
import org.apache.beam.runners.dataflow.worker.options.StreamingDataflowWorkerOptions;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.CommitStatus;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.CommitWorkRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.CommitWorkResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.ComputationGetDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetDataResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetWorkRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetWorkResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GlobalData;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GlobalDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.JobHeader;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.KeyedGetDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.KeyedGetDataResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.ReportStatsRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.ReportStatsResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingCommitRequestChunk;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingCommitResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingCommitWorkRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetDataResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetWorkRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetWorkRequestExtension;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetWorkResponseChunk;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.WorkItemCommitRequest;
import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.util.BackOff;
import org.apache.beam.sdk.util.BackOffUtils;
import org.apache.beam.sdk.util.FluentBackoff;
import org.apache.beam.sdk.util.Sleeper;
import org.apache.beam.vendor.grpc.v1p21p0.com.google.protobuf.ByteString;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.CallCredentials;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.Channel;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.Status;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.StatusRuntimeException;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.auth.MoreCallCredentials;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.inprocess.InProcessChannelBuilder;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.netty.GrpcSslContexts;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.netty.NegotiationType;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.netty.NettyChannelBuilder;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.stub.StreamObserver;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Splitter;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Verify;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.net.HostAndPort;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** gRPC client for communicating with Windmill Service. */
// Very likely real potential for bugs - https://issues.apache.org/jira/browse/BEAM-6562
// Very likely real potential for bugs - https://issues.apache.org/jira/browse/BEAM-6564
@SuppressFBWarnings({"JLM_JSR166_UTILCONCURRENT_MONITORENTER", "IS2_INCONSISTENT_SYNC"})
public class GrpcWindmillServer extends WindmillServerStub {
private static final Logger LOG = LoggerFactory.getLogger(GrpcWindmillServer.class);
// If a connection cannot be established, gRPC will fail fast so this deadline can be relatively
// high.
private static final long DEFAULT_UNARY_RPC_DEADLINE_SECONDS = 300;
private static final long DEFAULT_STREAM_RPC_DEADLINE_SECONDS = 300;
// Stream clean close seconds must be set lower than the stream deadline seconds.
private static final long DEFAULT_STREAM_CLEAN_CLOSE_SECONDS = 180;
private static final Duration MIN_BACKOFF = Duration.millis(1);
private static final Duration MAX_BACKOFF = Duration.standardSeconds(30);
// Default gRPC streams to 2MB chunks, which has shown to be a large enough chunk size to reduce
// per-chunk overhead, and small enough that we can still granularly flow-control.
private static final int COMMIT_STREAM_CHUNK_SIZE = 2 << 20;
private static final int GET_DATA_STREAM_CHUNK_SIZE = 2 << 20;
private static final AtomicLong nextId = new AtomicLong(0);
private final StreamingDataflowWorkerOptions options;
private final int streamingRpcBatchLimit;
private final List<CloudWindmillServiceV1Alpha1Grpc.CloudWindmillServiceV1Alpha1Stub> stubList =
new ArrayList<>();
private final List<CloudWindmillServiceV1Alpha1Grpc.CloudWindmillServiceV1Alpha1BlockingStub>
syncStubList = new ArrayList<>();
private WindmillApplianceGrpc.WindmillApplianceBlockingStub syncApplianceStub = null;
private long unaryDeadlineSeconds = DEFAULT_UNARY_RPC_DEADLINE_SECONDS;
private ImmutableSet<HostAndPort> endpoints;
private int logEveryNStreamFailures = 20;
private Duration maxBackoff = MAX_BACKOFF;
private final ThrottleTimer getWorkThrottleTimer = new ThrottleTimer();
private final ThrottleTimer getDataThrottleTimer = new ThrottleTimer();
private final ThrottleTimer commitWorkThrottleTimer = new ThrottleTimer();
Random rand = new Random();
private final Set<AbstractWindmillStream<?, ?>> streamRegistry =
Collections.newSetFromMap(new ConcurrentHashMap<AbstractWindmillStream<?, ?>, Boolean>());
public GrpcWindmillServer(StreamingDataflowWorkerOptions options) throws IOException {
this.options = options;
this.streamingRpcBatchLimit = options.getWindmillServiceStreamingRpcBatchLimit();
this.endpoints = ImmutableSet.of();
if (options.getWindmillServiceEndpoint() != null) {
Set<HostAndPort> endpoints = new HashSet<>();
for (String endpoint : Splitter.on(',').split(options.getWindmillServiceEndpoint())) {
endpoints.add(
HostAndPort.fromString(endpoint).withDefaultPort(options.getWindmillServicePort()));
}
initializeWindmillService(endpoints);
} else if (!streamingEngineEnabled() && options.getLocalWindmillHostport() != null) {
int portStart = options.getLocalWindmillHostport().lastIndexOf(':');
String endpoint = options.getLocalWindmillHostport().substring(0, portStart);
assert ("grpc:localhost".equals(endpoint));
int port = Integer.parseInt(options.getLocalWindmillHostport().substring(portStart + 1));
this.endpoints = ImmutableSet.<HostAndPort>of(HostAndPort.fromParts("localhost", port));
initializeLocalHost(port);
}
}
private GrpcWindmillServer(String name, boolean enableStreamingEngine) {
this.options = PipelineOptionsFactory.create().as(StreamingDataflowWorkerOptions.class);
this.streamingRpcBatchLimit = Integer.MAX_VALUE;
options.setProject("project");
options.setJobId("job");
options.setWorkerId("worker");
if (enableStreamingEngine) {
List<String> experiments = this.options.getExperiments();
if (experiments == null) {
experiments = new ArrayList<>();
}
experiments.add(GcpOptions.STREAMING_ENGINE_EXPERIMENT);
options.setExperiments(experiments);
}
this.stubList.add(CloudWindmillServiceV1Alpha1Grpc.newStub(inProcessChannel(name)));
}
private boolean streamingEngineEnabled() {
return options.isEnableStreamingEngine();
}
@Override
public synchronized void setWindmillServiceEndpoints(Set<HostAndPort> endpoints)
throws IOException {
Preconditions.checkNotNull(endpoints);
if (endpoints.equals(this.endpoints)) {
// The endpoints are equal don't recreate the stubs.
return;
}
LOG.info("Creating a new windmill stub, endpoints: {}", endpoints);
if (this.endpoints != null) {
LOG.info("Previous windmill stub endpoints: {}", this.endpoints);
}
initializeWindmillService(endpoints);
}
@Override
public synchronized boolean isReady() {
return !stubList.isEmpty();
}
private synchronized void initializeLocalHost(int port) throws IOException {
this.logEveryNStreamFailures = 1;
this.maxBackoff = Duration.millis(500);
this.unaryDeadlineSeconds = 10; // For local testing use a short deadline.
Channel channel = localhostChannel(port);
if (streamingEngineEnabled()) {
this.stubList.add(CloudWindmillServiceV1Alpha1Grpc.newStub(channel));
this.syncStubList.add(CloudWindmillServiceV1Alpha1Grpc.newBlockingStub(channel));
} else {
this.syncApplianceStub = WindmillApplianceGrpc.newBlockingStub(channel);
}
}
/**
* Create a wrapper around credentials callback that delegates to the underlying vendored {@link
* com.google.auth.RequestMetadataCallback}. Note that this class should override every method
* that is not final and not static and call the delegate directly.
*
* <p>TODO: Replace this with an auto generated proxy which calls the underlying implementation
* delegate to reduce maintenance burden.
*/
private static class VendoredRequestMetadataCallbackAdapter
implements com.google.auth.RequestMetadataCallback {
private final org.apache.beam.vendor.grpc.v1p21p0.com.google.auth.RequestMetadataCallback
callback;
private VendoredRequestMetadataCallbackAdapter(
org.apache.beam.vendor.grpc.v1p21p0.com.google.auth.RequestMetadataCallback callback) {
this.callback = callback;
}
@Override
public void onSuccess(Map<String, List<String>> metadata) {
callback.onSuccess(metadata);
}
@Override
public void onFailure(Throwable exception) {
callback.onFailure(exception);
}
}
/**
* Create a wrapper around credentials that delegates to the underlying {@link
* com.google.auth.Credentials}. Note that this class should override every method that is not
* final and not static and call the delegate directly.
*
* <p>TODO: Replace this with an auto generated proxy which calls the underlying implementation
* delegate to reduce maintenance burden.
*/
private static class VendoredCredentialsAdapter
extends org.apache.beam.vendor.grpc.v1p21p0.com.google.auth.Credentials {
private final com.google.auth.Credentials credentials;
private VendoredCredentialsAdapter(com.google.auth.Credentials credentials) {
this.credentials = credentials;
}
@Override
public String getAuthenticationType() {
return credentials.getAuthenticationType();
}
@Override
public Map<String, List<String>> getRequestMetadata() throws IOException {
return credentials.getRequestMetadata();
}
@Override
public void getRequestMetadata(
final URI uri,
Executor executor,
final org.apache.beam.vendor.grpc.v1p21p0.com.google.auth.RequestMetadataCallback
callback) {
credentials.getRequestMetadata(
uri, executor, new VendoredRequestMetadataCallbackAdapter(callback));
}
@Override
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException {
return credentials.getRequestMetadata(uri);
}
@Override
public boolean hasRequestMetadata() {
return credentials.hasRequestMetadata();
}
@Override
public boolean hasRequestMetadataOnly() {
return credentials.hasRequestMetadataOnly();
}
@Override
public void refresh() throws IOException {
credentials.refresh();
}
}
private synchronized void initializeWindmillService(Set<HostAndPort> endpoints)
throws IOException {
LOG.info("Initializing Streaming Engine GRPC client for endpoints: {}", endpoints);
this.stubList.clear();
this.syncStubList.clear();
this.endpoints = ImmutableSet.<HostAndPort>copyOf(endpoints);
for (HostAndPort endpoint : this.endpoints) {
if ("localhost".equals(endpoint.getHost())) {
initializeLocalHost(endpoint.getPort());
} else {
CallCredentials creds =
MoreCallCredentials.from(new VendoredCredentialsAdapter(options.getGcpCredential()));
this.stubList.add(
CloudWindmillServiceV1Alpha1Grpc.newStub(remoteChannel(endpoint))
.withCallCredentials(creds));
this.syncStubList.add(
CloudWindmillServiceV1Alpha1Grpc.newBlockingStub(remoteChannel(endpoint))
.withCallCredentials(creds));
}
}
}
@VisibleForTesting
static GrpcWindmillServer newTestInstance(String name, boolean enableStreamingEngine) {
return new GrpcWindmillServer(name, enableStreamingEngine);
}
private Channel inProcessChannel(String name) {
return InProcessChannelBuilder.forName(name).directExecutor().build();
}
private Channel localhostChannel(int port) {
return NettyChannelBuilder.forAddress("localhost", port)
.maxInboundMessageSize(java.lang.Integer.MAX_VALUE)
.negotiationType(NegotiationType.PLAINTEXT)
.build();
}
private Channel remoteChannel(HostAndPort endpoint) throws IOException {
return NettyChannelBuilder.forAddress(endpoint.getHost(), endpoint.getPort())
.maxInboundMessageSize(java.lang.Integer.MAX_VALUE)
.negotiationType(NegotiationType.TLS)
// Set ciphers(null) to not use GCM, which is disabled for Dataflow
// due to it being horribly slow.
.sslContext(GrpcSslContexts.forClient().ciphers(null).build())
.build();
}
private synchronized CloudWindmillServiceV1Alpha1Grpc.CloudWindmillServiceV1Alpha1Stub stub() {
if (stubList.isEmpty()) {
throw new RuntimeException("windmillServiceEndpoint has not been set");
}
if (stubList.size() == 1) {
return stubList.get(0);
}
return stubList.get(rand.nextInt(stubList.size()));
}
private synchronized CloudWindmillServiceV1Alpha1Grpc.CloudWindmillServiceV1Alpha1BlockingStub
syncStub() {
if (syncStubList.isEmpty()) {
throw new RuntimeException("windmillServiceEndpoint has not been set");
}
if (syncStubList.size() == 1) {
return syncStubList.get(0);
}
return syncStubList.get(rand.nextInt(syncStubList.size()));
}
@Override
public void appendSummaryHtml(PrintWriter writer) {
writer.write("Active Streams:<br>");
for (AbstractWindmillStream<?, ?> stream : streamRegistry) {
stream.appendSummaryHtml(writer);
writer.write("<br>");
}
}
// Configure backoff to retry calls forever, with a maximum sane retry interval.
private BackOff grpcBackoff() {
return FluentBackoff.DEFAULT
.withInitialBackoff(MIN_BACKOFF)
.withMaxBackoff(maxBackoff)
.backoff();
}
private <ResponseT> ResponseT callWithBackoff(Supplier<ResponseT> function) {
BackOff backoff = grpcBackoff();
int rpcErrors = 0;
while (true) {
try {
return function.get();
} catch (StatusRuntimeException e) {
try {
if (++rpcErrors % 20 == 0) {
LOG.warn(
"Many exceptions calling gRPC. Last exception: {} with status {}",
e,
e.getStatus());
}
if (!BackOffUtils.next(Sleeper.DEFAULT, backoff)) {
throw new WindmillServerStub.RpcException(e);
}
} catch (IOException | InterruptedException i) {
if (i instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
WindmillServerStub.RpcException rpcException = new WindmillServerStub.RpcException(e);
rpcException.addSuppressed(i);
throw rpcException;
}
}
}
}
@Override
public GetWorkResponse getWork(GetWorkRequest request) {
if (syncApplianceStub == null) {
return callWithBackoff(
() ->
syncStub()
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getWork(
request
.toBuilder()
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.setWorkerId(options.getWorkerId())
.build()));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getWork(request));
}
}
@Override
public GetDataResponse getData(GetDataRequest request) {
if (syncApplianceStub == null) {
return callWithBackoff(
() ->
syncStub()
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getData(
request
.toBuilder()
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.build()));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getData(request));
}
}
@Override
public CommitWorkResponse commitWork(CommitWorkRequest request) {
if (syncApplianceStub == null) {
return callWithBackoff(
() ->
syncStub()
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.commitWork(
request
.toBuilder()
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.build()));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.commitWork(request));
}
}
@Override
public GetWorkStream getWorkStream(GetWorkRequest request, WorkItemReceiver receiver) {
return new GrpcGetWorkStream(
GetWorkRequest.newBuilder(request)
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.setWorkerId(options.getWorkerId())
.build(),
receiver);
}
@Override
public GetDataStream getDataStream() {
return new GrpcGetDataStream();
}
@Override
public CommitWorkStream commitWorkStream() {
return new GrpcCommitWorkStream();
}
@Override
public GetConfigResponse getConfig(GetConfigRequest request) {
if (syncApplianceStub == null) {
throw new RpcException(
new UnsupportedOperationException("GetConfig not supported with windmill service."));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getConfig(request));
}
}
@Override
public ReportStatsResponse reportStats(ReportStatsRequest request) {
if (syncApplianceStub == null) {
throw new RpcException(
new UnsupportedOperationException("ReportStats not supported with windmill service."));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.reportStats(request));
}
}
@Override
public long getAndResetThrottleTime() {
return getWorkThrottleTimer.getAndResetThrottleTime()
+ getDataThrottleTimer.getAndResetThrottleTime()
+ commitWorkThrottleTimer.getAndResetThrottleTime();
}
private JobHeader makeHeader() {
return JobHeader.newBuilder()
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.setWorkerId(options.getWorkerId())
.build();
}
/** Returns a long that is unique to this process. */
private static long uniqueId() {
return nextId.incrementAndGet();
}
/**
* Base class for persistent streams connecting to Windmill.
*
* <p>This class handles the underlying gRPC StreamObservers, and automatically reconnects the
* stream if it is broken. Subclasses are responsible for retrying requests that have been lost on
* a broken stream.
*
* <p>Subclasses should override onResponse to handle responses from the server, and onNewStream
* to perform any work that must be done when a new stream is created, such as sending headers or
* retrying requests.
*
* <p>send and startStream should not be called from onResponse; use executor() instead.
*
* <p>Synchronization on this is used to synchronize the gRpc stream state and internal data
* structures. Since grpc channel operations may block, synchronization on this stream may also
* block. This is generally not a problem since streams are used in a single-threaded manner.
* However some accessors used for status page and other debugging need to take care not to
* require synchronizing on this.
*/
private abstract class AbstractWindmillStream<RequestT, ResponseT> implements WindmillStream {
private final StreamObserverFactory streamObserverFactory = StreamObserverFactory.direct();
private final Function<StreamObserver<ResponseT>, StreamObserver<RequestT>> clientFactory;
private final Executor executor = Executors.newSingleThreadExecutor();
// The following should be protected by synchronizing on this, except for
// the atomics which may be read atomically for status pages.
private StreamObserver<RequestT> requestObserver;
private final AtomicLong startTimeMs = new AtomicLong();
private final AtomicInteger errorCount = new AtomicInteger();
private final BackOff backoff = grpcBackoff();
private final AtomicLong sleepUntil = new AtomicLong();
protected final AtomicBoolean clientClosed = new AtomicBoolean();
private final CountDownLatch finishLatch = new CountDownLatch(1);
protected AbstractWindmillStream(
Function<StreamObserver<ResponseT>, StreamObserver<RequestT>> clientFactory) {
this.clientFactory = clientFactory;
}
/** Called on each response from the server */
protected abstract void onResponse(ResponseT response);
/** Called when a new underlying stream to the server has been opened. */
protected abstract void onNewStream();
/** Returns whether there are any pending requests that should be retried on a stream break. */
protected abstract boolean hasPendingRequests();
/**
* Called when the stream is throttled due to resource exhausted errors. Will be called for each
* resource exhausted error not just the first. onResponse() must stop throttling on reciept of
* the first good message.
*/
protected abstract void startThrottleTimer();
/** Send a request to the server. */
protected final synchronized void send(RequestT request) {
requestObserver.onNext(request);
}
/** Starts the underlying stream. */
protected final void startStream() {
// Add the stream to the registry after it has been fully constructed.
streamRegistry.add(this);
BackOff backoff = grpcBackoff();
while (true) {
try {
synchronized (this) {
startTimeMs.set(Instant.now().getMillis());
requestObserver = streamObserverFactory.from(clientFactory, new ResponseObserver());
onNewStream();
if (clientClosed.get()) {
close();
}
return;
}
} catch (Exception e) {
LOG.error("Failed to create new stream, retrying: ", e);
try {
long sleep = backoff.nextBackOffMillis();
sleepUntil.set(Instant.now().getMillis() + sleep);
Thread.sleep(sleep);
} catch (InterruptedException i) {
// Keep trying to create the stream.
} catch (IOException i) {
// Ignore.
}
}
}
}
protected final Executor executor() {
return executor;
}
// Care is taken that synchronization on this is unnecessary for all status page information.
// Blocking sends are made beneath this stream object's lock which could block status page
// rendering.
public final void appendSummaryHtml(PrintWriter writer) {
appendSpecificHtml(writer);
if (errorCount.get() > 0) {
writer.format(", %d errors", errorCount.get());
}
if (clientClosed.get()) {
writer.write(", client closed");
}
long sleepLeft = sleepUntil.get() - Instant.now().getMillis();
if (sleepLeft > 0) {
writer.format(", %dms backoff remaining", sleepLeft);
}
writer.format(", current stream is %dms old", Instant.now().getMillis() - startTimeMs.get());
}
// Don't require synchronization on stream, see the appendSummaryHtml comment.
protected abstract void appendSpecificHtml(PrintWriter writer);
private class ResponseObserver implements StreamObserver<ResponseT> {
@Override
public void onNext(ResponseT response) {
try {
backoff.reset();
} catch (IOException e) {
// Ignore.
}
onResponse(response);
}
@Override
public void onError(Throwable t) {
onStreamFinished(t);
}
@Override
public void onCompleted() {
onStreamFinished(null);
}
private void onStreamFinished(@Nullable Throwable t) {
synchronized (this) {
if (clientClosed.get() && !hasPendingRequests()) {
streamRegistry.remove(AbstractWindmillStream.this);
finishLatch.countDown();
return;
}
}
if (t != null) {
Status status = null;
if (t instanceof StatusRuntimeException) {
status = ((StatusRuntimeException) t).getStatus();
}
if (errorCount.incrementAndGet() % logEveryNStreamFailures == 0) {
LOG.debug(
"{} streaming Windmill RPC errors for a stream, last was: {} with status {}. " +
"This is normal during autoscaling.",
errorCount.get(),
t.toString(),
status);
}
// If the stream was stopped due to a resource exhausted error then we are throttled.
if (status != null && status.getCode() == Status.Code.RESOURCE_EXHAUSTED) {
startThrottleTimer();
}
try {
long sleep = backoff.nextBackOffMillis();
sleepUntil.set(Instant.now().getMillis() + sleep);
Thread.sleep(sleep);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IOException e) {
// Ignore.
}
}
executor.execute(AbstractWindmillStream.this::startStream);
}
}
@Override
public final synchronized void close() {
// Synchronization of close and onCompleted necessary for correct retry logic in onNewStream.
clientClosed.set(true);
requestObserver.onCompleted();
}
@Override
public final boolean awaitTermination(int time, TimeUnit unit) throws InterruptedException {
return finishLatch.await(time, unit);
}
@Override
public final void closeAfterDefaultTimeout() throws InterruptedException {
if (!finishLatch.await(DEFAULT_STREAM_CLEAN_CLOSE_SECONDS, TimeUnit.SECONDS)) {
// If the stream did not close due to error in the specified amount of time, half-close
// the stream cleanly.
close();
}
}
@Override
public final Instant startTime() {
return new Instant(startTimeMs.get());
}
}
private class GrpcGetWorkStream
extends AbstractWindmillStream<StreamingGetWorkRequest, StreamingGetWorkResponseChunk>
implements GetWorkStream {
private final GetWorkRequest request;
private final WorkItemReceiver receiver;
private final Map<Long, WorkItemBuffer> buffers = new ConcurrentHashMap<>();
private final AtomicLong inflightMessages = new AtomicLong();
private final AtomicLong inflightBytes = new AtomicLong();
private GrpcGetWorkStream(GetWorkRequest request, WorkItemReceiver receiver) {
super(
responseObserver ->
stub()
.withDeadlineAfter(DEFAULT_STREAM_RPC_DEADLINE_SECONDS, TimeUnit.SECONDS)
.getWorkStream(responseObserver));
this.request = request;
this.receiver = receiver;
startStream();
}
@Override
protected synchronized void onNewStream() {
buffers.clear();
inflightMessages.set(request.getMaxItems());
inflightBytes.set(request.getMaxBytes());
send(StreamingGetWorkRequest.newBuilder().setRequest(request).build());
}
@Override
protected boolean hasPendingRequests() {
return false;
}
@Override
public void appendSpecificHtml(PrintWriter writer) {
// Number of buffers is same as distict workers that sent work on this stream.
writer.format(
"GetWorkStream: %d buffers, %d inflight messages allowed, %d inflight bytes allowed",
buffers.size(), inflightMessages.intValue(), inflightBytes.intValue());
}
@Override
protected void onResponse(StreamingGetWorkResponseChunk chunk) {
getWorkThrottleTimer.stop();
long id = chunk.getStreamId();
WorkItemBuffer buffer = buffers.computeIfAbsent(id, (Long l) -> new WorkItemBuffer());
buffer.append(chunk);
if (chunk.getRemainingBytesForWorkItem() == 0) {
long size = buffer.bufferedSize();
buffer.runAndReset();
// Record the fact that there are now fewer outstanding messages and bytes on the stream.
long numInflight = inflightMessages.decrementAndGet();
long bytesInflight = inflightBytes.addAndGet(-size);
// If the outstanding items or bytes limit has gotten too low, top both off with a
// GetWorkExtension. The goal is to keep the limits relatively close to their maximum
// values without sending too many extension requests.
if (numInflight < request.getMaxItems() / 2 || bytesInflight < request.getMaxBytes() / 2) {
long moreItems = request.getMaxItems() - numInflight;
long moreBytes = request.getMaxBytes() - bytesInflight;
inflightMessages.getAndAdd(moreItems);
inflightBytes.getAndAdd(moreBytes);
final StreamingGetWorkRequest extension =
StreamingGetWorkRequest.newBuilder()
.setRequestExtension(
StreamingGetWorkRequestExtension.newBuilder()
.setMaxItems(moreItems)
.setMaxBytes(moreBytes))
.build();
executor()
.execute(
() -> {
try {
send(extension);
} catch (IllegalStateException e) {
// Stream was closed.
}
});
}
}
}
@Override
protected void startThrottleTimer() {
getWorkThrottleTimer.start();
}
private class WorkItemBuffer {
private String computation;
private Instant inputDataWatermark;
private Instant synchronizedProcessingTime;
private ByteString data = ByteString.EMPTY;
private long bufferedSize = 0;
private void setMetadata(Windmill.ComputationWorkItemMetadata metadata) {
this.computation = metadata.getComputationId();
this.inputDataWatermark =
WindmillTimeUtils.windmillToHarnessWatermark(metadata.getInputDataWatermark());
this.synchronizedProcessingTime =
WindmillTimeUtils.windmillToHarnessWatermark(
metadata.getDependentRealtimeInputWatermark());
}
public void append(StreamingGetWorkResponseChunk chunk) {
if (chunk.hasComputationMetadata()) {
setMetadata(chunk.getComputationMetadata());
}
this.data = data.concat(chunk.getSerializedWorkItem());
this.bufferedSize += chunk.getSerializedWorkItem().size();
}
public long bufferedSize() {
return bufferedSize;
}
public void runAndReset() {
try {
receiver.receiveWork(
computation,
inputDataWatermark,
synchronizedProcessingTime,
Windmill.WorkItem.parseFrom(data.newInput()));
} catch (IOException e) {
LOG.error("Failed to parse work item from stream: ", e);
}
data = ByteString.EMPTY;
bufferedSize = 0;
}
}
}
private class GrpcGetDataStream
extends AbstractWindmillStream<StreamingGetDataRequest, StreamingGetDataResponse>
implements GetDataStream {
private class QueuedRequest {
public QueuedRequest(String computation, KeyedGetDataRequest request) {
this.id = uniqueId();
this.globalDataRequest = null;
this.dataRequest =
ComputationGetDataRequest.newBuilder()
.setComputationId(computation)
.addRequests(request)
.build();
this.byteSize = this.dataRequest.getSerializedSize();
}
public QueuedRequest(GlobalDataRequest request) {
this.id = uniqueId();
this.globalDataRequest = request;
this.dataRequest = null;
this.byteSize = this.globalDataRequest.getSerializedSize();
}
final long id;
final long byteSize;
final GlobalDataRequest globalDataRequest;
final ComputationGetDataRequest dataRequest;
AppendableInputStream responseStream = null;
}
private class QueuedBatch {
public QueuedBatch() {}
final List<QueuedRequest> requests = new ArrayList<>();
long byteSize = 0;
boolean finalized = false;
final CountDownLatch sent = new CountDownLatch(1);
};
private final Deque<QueuedBatch> batches = new ConcurrentLinkedDeque<>();
private final Map<Long, AppendableInputStream> pending = new ConcurrentHashMap<>();
@Override
public void appendSpecificHtml(PrintWriter writer) {
writer.format(
"GetDataStream: %d pending on-wire, %d queued batches", pending.size(), batches.size());
}
GrpcGetDataStream() {
super(
responseObserver ->
stub()
.withDeadlineAfter(DEFAULT_STREAM_RPC_DEADLINE_SECONDS, TimeUnit.SECONDS)
.getDataStream(responseObserver));
startStream();
}
@Override
protected synchronized void onNewStream() {
send(StreamingGetDataRequest.newBuilder().setHeader(makeHeader()).build());
if (clientClosed.get()) {
// We rely on close only occurring after all methods on the stream have returned.
// Since the requestKeyedData and requestGlobalData methods are blocking this
// means there should be no pending requests.
Verify.verify(!hasPendingRequests());
} else {
for (AppendableInputStream responseStream : pending.values()) {
responseStream.cancel();
}
}
}
@Override
protected boolean hasPendingRequests() {
return !pending.isEmpty() || !batches.isEmpty();
}
@Override
protected void onResponse(StreamingGetDataResponse chunk) {
Preconditions.checkArgument(chunk.getRequestIdCount() == chunk.getSerializedResponseCount());
Preconditions.checkArgument(
chunk.getRemainingBytesForResponse() == 0 || chunk.getRequestIdCount() == 1);
getDataThrottleTimer.stop();
for (int i = 0; i < chunk.getRequestIdCount(); ++i) {
AppendableInputStream responseStream = pending.get(chunk.getRequestId(i));
Verify.verify(responseStream != null, "No pending response stream");
responseStream.append(chunk.getSerializedResponse(i).newInput());
if (chunk.getRemainingBytesForResponse() == 0) {
responseStream.complete();
}
}
}
@Override
protected void startThrottleTimer() {
getDataThrottleTimer.start();
}
@Override
public KeyedGetDataResponse requestKeyedData(String computation, KeyedGetDataRequest request) {
return issueRequest(new QueuedRequest(computation, request), KeyedGetDataResponse::parseFrom);
}
@Override
public GlobalData requestGlobalData(GlobalDataRequest request) {
return issueRequest(new QueuedRequest(request), GlobalData::parseFrom);
}
@Override
public void refreshActiveWork(Map<String, List<KeyedGetDataRequest>> active) {
long builderBytes = 0;
StreamingGetDataRequest.Builder builder = StreamingGetDataRequest.newBuilder();
for (Map.Entry<String, List<KeyedGetDataRequest>> entry : active.entrySet()) {
for (KeyedGetDataRequest request : entry.getValue()) {
// Calculate the bytes with some overhead for proto encoding.
long bytes = (long) entry.getKey().length() + request.getSerializedSize() + 10;
if (builderBytes > 0
&& (builderBytes + bytes > GET_DATA_STREAM_CHUNK_SIZE
|| builder.getRequestIdCount() >= streamingRpcBatchLimit)) {
send(builder.build());
builderBytes = 0;
builder.clear();
}
builderBytes += bytes;
builder.addStateRequest(
ComputationGetDataRequest.newBuilder()
.setComputationId(entry.getKey())
.addRequests(request));
}
}
if (builderBytes > 0) {
send(builder.build());
}
}
private <ResponseT> ResponseT issueRequest(QueuedRequest request, ParseFn<ResponseT> parseFn) {
while (true) {
request.responseStream = new AppendableInputStream();
try {
queueRequestAndWait(request);
return parseFn.parse(request.responseStream);
} catch (CancellationException e) {
// Retry issuing the request since the response stream was cancelled.
continue;
} catch (IOException e) {
LOG.error("Parsing GetData response failed: ", e);
continue;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
pending.remove(request.id);
}
}
}
private void queueRequestAndWait(QueuedRequest request) throws InterruptedException {
QueuedBatch batch;
boolean responsibleForSend = false;
CountDownLatch waitForSendLatch = null;
synchronized (batches) {
batch = batches.isEmpty() ? null : batches.getLast();
if (batch == null
|| batch.finalized
|| batch.requests.size() >= streamingRpcBatchLimit
|| batch.byteSize + request.byteSize > GET_DATA_STREAM_CHUNK_SIZE) {
if (batch != null) {
waitForSendLatch = batch.sent;
}
batch = new QueuedBatch();
batches.addLast(batch);
responsibleForSend = true;
}
batch.requests.add(request);
batch.byteSize += request.byteSize;
}
if (responsibleForSend) {
if (waitForSendLatch == null) {
// If there was not a previous batch wait a little while to improve
// batching.
Thread.sleep(1);
} else {
waitForSendLatch.await();
}
// Finalize the batch so that no additional requests will be added. Leave the batch in the
// queue so that a subsequent batch will wait for it's completion.
synchronized (batches) {
Verify.verify(batch == batches.peekFirst());
batch.finalized = true;
}
sendBatch(batch.requests);
synchronized (batches) {
Verify.verify(batch == batches.pollFirst());
}
// Notify all waiters with requests in this batch as well as the sender
// of the next batch (if one exists).
batch.sent.countDown();
} else {
// Wait for this batch to be sent before parsing the response.
batch.sent.await();
}
}
private void sendBatch(List<QueuedRequest> requests) {
StreamingGetDataRequest batchedRequest = flushToBatch(requests);
synchronized (this) {
// Synchronization of pending inserts is necessary with send to ensure duplicates are not
// sent on stream reconnect.
for (QueuedRequest request : requests) {
Verify.verify(pending.put(request.id, request.responseStream) == null);
}
try {
send(batchedRequest);
} catch (IllegalStateException e) {
// The stream broke before this call went through; onNewStream will retry the fetch.
}
}
}
private StreamingGetDataRequest flushToBatch(List<QueuedRequest> requests) {
// Put all global data requests first because there is only a single repeated field for
// request ids and the initial ids correspond to global data requests if they are present.
requests.sort(
(QueuedRequest r1, QueuedRequest r2) -> {
boolean r1gd = r1.globalDataRequest != null;
boolean r2gd = r2.globalDataRequest != null;
return r1gd == r2gd ? 0 : (r1gd ? -1 : 1);
});
StreamingGetDataRequest.Builder builder = StreamingGetDataRequest.newBuilder();
for (QueuedRequest request : requests) {
builder.addRequestId(request.id);
if (request.globalDataRequest == null) {
builder.addStateRequest(request.dataRequest);
} else {
builder.addGlobalDataRequest(request.globalDataRequest);
}
}
return builder.build();
}
}
private class GrpcCommitWorkStream
extends AbstractWindmillStream<StreamingCommitWorkRequest, StreamingCommitResponse>
implements CommitWorkStream {
private class PendingRequest {
private final String computation;
private final WorkItemCommitRequest request;
private final Consumer<CommitStatus> onDone;
PendingRequest(
String computation, WorkItemCommitRequest request, Consumer<CommitStatus> onDone) {
this.computation = computation;
this.request = request;
this.onDone = onDone;
}
long getBytes() {
return (long) request.getSerializedSize() + computation.length();
}
}
private final Map<Long, PendingRequest> pending = new ConcurrentHashMap<>();
private class Batcher {
long queuedBytes = 0;
Map<Long, PendingRequest> queue = new HashMap<>();
boolean canAccept(PendingRequest request) {
return queue.isEmpty()
|| (queue.size() < streamingRpcBatchLimit
&& (request.getBytes() + queuedBytes) < COMMIT_STREAM_CHUNK_SIZE);
}
void add(long id, PendingRequest request) {
assert (canAccept(request));
queuedBytes += request.getBytes();
queue.put(id, request);
}
void flush() {
flushInternal(queue);
queuedBytes = 0;
}
}
private final Batcher batcher = new Batcher();
GrpcCommitWorkStream() {
super(
responseObserver ->
stub()
.withDeadlineAfter(DEFAULT_STREAM_RPC_DEADLINE_SECONDS, TimeUnit.SECONDS)
.commitWorkStream(responseObserver));
startStream();
}
@Override
public void appendSpecificHtml(PrintWriter writer) {
writer.format("CommitWorkStream: %d pending", pending.size());
}
@Override
protected synchronized void onNewStream() {
send(StreamingCommitWorkRequest.newBuilder().setHeader(makeHeader()).build());
Batcher resendBatcher = new Batcher();
for (Map.Entry<Long, PendingRequest> entry : pending.entrySet()) {
if (!resendBatcher.canAccept(entry.getValue())) {
resendBatcher.flush();
}
resendBatcher.add(entry.getKey(), entry.getValue());
}
resendBatcher.flush();
}
@Override
protected boolean hasPendingRequests() {
return !pending.isEmpty();
}
@Override
protected void onResponse(StreamingCommitResponse response) {
commitWorkThrottleTimer.stop();
for (int i = 0; i < response.getRequestIdCount(); ++i) {
long requestId = response.getRequestId(i);
PendingRequest done = pending.remove(requestId);
if (done == null) {
LOG.error("Got unknown commit request ID: {}", requestId);
} else {
done.onDone.accept(
(i < response.getStatusCount()) ? response.getStatus(i) : CommitStatus.OK);
}
}
}
@Override
protected void startThrottleTimer() {
commitWorkThrottleTimer.start();
}
@Override
public boolean commitWorkItem(
String computation, WorkItemCommitRequest commitRequest, Consumer<CommitStatus> onDone) {
PendingRequest request = new PendingRequest(computation, commitRequest, onDone);
if (!batcher.canAccept(request)) {
return false;
}
batcher.add(uniqueId(), request);
return true;
}
@Override
public void flush() {
batcher.flush();
}
private final void flushInternal(Map<Long, PendingRequest> requests) {
if (requests.isEmpty()) {
return;
}
if (requests.size() == 1) {
Map.Entry<Long, PendingRequest> elem = requests.entrySet().iterator().next();
if (elem.getValue().request.getSerializedSize() > COMMIT_STREAM_CHUNK_SIZE) {
issueMultiChunkRequest(elem.getKey(), elem.getValue());
} else {
issueSingleRequest(elem.getKey(), elem.getValue());
}
} else {
issueBatchedRequest(requests);
}
requests.clear();
}
private void issueSingleRequest(final long id, PendingRequest pendingRequest) {
StreamingCommitWorkRequest.Builder requestBuilder = StreamingCommitWorkRequest.newBuilder();
requestBuilder
.addCommitChunkBuilder()
.setComputationId(pendingRequest.computation)
.setRequestId(id)
.setShardingKey(pendingRequest.request.getShardingKey())
.setSerializedWorkItemCommit(pendingRequest.request.toByteString());
StreamingCommitWorkRequest chunk = requestBuilder.build();
try {
synchronized (this) {
pending.put(id, pendingRequest);
send(chunk);
}
} catch (IllegalStateException e) {
// Stream was broken, request will be retried when stream is reopened.
}
}
private void issueBatchedRequest(Map<Long, PendingRequest> requests) {
StreamingCommitWorkRequest.Builder requestBuilder = StreamingCommitWorkRequest.newBuilder();
String lastComputation = null;
for (Map.Entry<Long, PendingRequest> entry : requests.entrySet()) {
PendingRequest request = entry.getValue();
StreamingCommitRequestChunk.Builder chunkBuilder = requestBuilder.addCommitChunkBuilder();
if (lastComputation == null || !lastComputation.equals(request.computation)) {
chunkBuilder.setComputationId(request.computation);
lastComputation = request.computation;
}
chunkBuilder.setRequestId(entry.getKey());
chunkBuilder.setShardingKey(request.request.getShardingKey());
chunkBuilder.setSerializedWorkItemCommit(request.request.toByteString());
}
StreamingCommitWorkRequest request = requestBuilder.build();
try {
synchronized (this) {
pending.putAll(requests);
send(request);
}
} catch (IllegalStateException e) {
// Stream was broken, request will be retried when stream is reopened.
}
}
private void issueMultiChunkRequest(final long id, PendingRequest pendingRequest) {
Preconditions.checkNotNull(pendingRequest.computation);
final ByteString serializedCommit = pendingRequest.request.toByteString();
synchronized (this) {
pending.put(id, pendingRequest);
for (int i = 0; i < serializedCommit.size(); i += COMMIT_STREAM_CHUNK_SIZE) {
int end = i + COMMIT_STREAM_CHUNK_SIZE;
ByteString chunk = serializedCommit.substring(i, Math.min(end, serializedCommit.size()));
StreamingCommitRequestChunk.Builder chunkBuilder =
StreamingCommitRequestChunk.newBuilder()
.setRequestId(id)
.setSerializedWorkItemCommit(chunk)
.setComputationId(pendingRequest.computation)
.setShardingKey(pendingRequest.request.getShardingKey());
int remaining = serializedCommit.size() - end;
if (remaining > 0) {
chunkBuilder.setRemainingBytesForWorkItem(remaining);
}
StreamingCommitWorkRequest requestChunk =
StreamingCommitWorkRequest.newBuilder().addCommitChunk(chunkBuilder).build();
try {
send(requestChunk);
} catch (IllegalStateException e) {
// Stream was broken, request will be retried when stream is reopened.
break;
}
}
}
}
}
@FunctionalInterface
private interface ParseFn<ResponseT> {
ResponseT parse(InputStream input) throws IOException;
}
/** An InputStream that can be dynamically extended with additional InputStreams. */
@SuppressWarnings("JdkObsolete")
private static class AppendableInputStream extends InputStream {
private static final InputStream POISON_PILL = ByteString.EMPTY.newInput();
private final AtomicBoolean cancelled = new AtomicBoolean(false);
private final AtomicBoolean complete = new AtomicBoolean(false);
private final BlockingDeque<InputStream> queue = new LinkedBlockingDeque<>(10);
private final InputStream stream =
new SequenceInputStream(
new Enumeration<InputStream>() {
InputStream current = ByteString.EMPTY.newInput();
@Override
public boolean hasMoreElements() {
if (current != null) {
return true;
}
try {
current = queue.take();
if (current != POISON_PILL) {
return true;
}
if (cancelled.get()) {
throw new CancellationException();
}
if (complete.get()) {
return false;
}
throw new IllegalStateException("Got poison pill but stream is not done.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CancellationException();
}
}
@Override
public InputStream nextElement() {
if (!hasMoreElements()) {
throw new NoSuchElementException();
}
InputStream next = current;
current = null;
return next;
}
});
/** Appends a new InputStream to the tail of this stream. */
public synchronized void append(InputStream chunk) {
try {
queue.put(chunk);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/** Cancels the stream. Future calls to InputStream methods will throw CancellationException. */
public synchronized void cancel() {
cancelled.set(true);
try {
// Put the poison pill at the head of the queue to cancel as quickly as possible.
queue.clear();
queue.putFirst(POISON_PILL);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/** Signals that no new InputStreams will be added to this stream. */
public synchronized void complete() {
complete.set(true);
try {
queue.put(POISON_PILL);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public int read() throws IOException {
if (cancelled.get()) {
throw new CancellationException();
}
return stream.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (cancelled.get()) {
throw new CancellationException();
}
return stream.read(b, off, len);
}
@Override
public int available() throws IOException {
if (cancelled.get()) {
throw new CancellationException();
}
return stream.available();
}
@Override
public void close() throws IOException {
stream.close();
}
}
/**
* A stopwatch used to track the amount of time spent throttled due to Resource Exhausted errors.
* Throttle time is cumulative for all three rpcs types but not for all streams. So if GetWork and
* CommitWork are both blocked for x, totalTime will be 2x. However, if 2 GetWork streams are both
* blocked for x totalTime will be x. All methods are thread safe.
*/
private static class ThrottleTimer {
// This is -1 if not currently being throttled or the time in
// milliseconds when throttling for this type started.
private long startTime = -1;
// This is the collected total throttle times since the last poll. Throttle times are
// reported as a delta so this is cleared whenever it gets reported.
private long totalTime = 0;
/**
* Starts the timer if it has not been started and does nothing if it has already been started.
*/
public synchronized void start() {
if (!throttled()) { // This timer is not started yet so start it now.
startTime = Instant.now().getMillis();
}
}
/** Stops the timer if it has been started and does nothing if it has not been started. */
public synchronized void stop() {
if (throttled()) { // This timer has been started already so stop it now.
totalTime += Instant.now().getMillis() - startTime;
startTime = -1;
}
}
/** Returns if the specified type is currently being throttled */
public synchronized boolean throttled() {
return startTime != -1;
}
/** Returns the combined total of all throttle times and resets those times to 0. */
public synchronized long getAndResetThrottleTime() {
if (throttled()) {
stop();
start();
}
long toReturn = totalTime;
totalTime = 0;
return toReturn;
}
}
}
|
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/GrpcWindmillServer.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.beam.runners.dataflow.worker.windmill;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.SequenceInputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.apache.beam.runners.dataflow.worker.WindmillTimeUtils;
import org.apache.beam.runners.dataflow.worker.options.StreamingDataflowWorkerOptions;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.CommitStatus;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.CommitWorkRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.CommitWorkResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.ComputationGetDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetConfigResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetDataResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetWorkRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GetWorkResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GlobalData;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.GlobalDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.JobHeader;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.KeyedGetDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.KeyedGetDataResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.ReportStatsRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.ReportStatsResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingCommitRequestChunk;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingCommitResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingCommitWorkRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetDataRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetDataResponse;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetWorkRequest;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetWorkRequestExtension;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.StreamingGetWorkResponseChunk;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill.WorkItemCommitRequest;
import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.util.BackOff;
import org.apache.beam.sdk.util.BackOffUtils;
import org.apache.beam.sdk.util.FluentBackoff;
import org.apache.beam.sdk.util.Sleeper;
import org.apache.beam.vendor.grpc.v1p21p0.com.google.protobuf.ByteString;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.CallCredentials;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.Channel;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.Status;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.StatusRuntimeException;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.auth.MoreCallCredentials;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.inprocess.InProcessChannelBuilder;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.netty.GrpcSslContexts;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.netty.NegotiationType;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.netty.NettyChannelBuilder;
import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.stub.StreamObserver;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Splitter;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Verify;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.net.HostAndPort;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** gRPC client for communicating with Windmill Service. */
// Very likely real potential for bugs - https://issues.apache.org/jira/browse/BEAM-6562
// Very likely real potential for bugs - https://issues.apache.org/jira/browse/BEAM-6564
@SuppressFBWarnings({"JLM_JSR166_UTILCONCURRENT_MONITORENTER", "IS2_INCONSISTENT_SYNC"})
public class GrpcWindmillServer extends WindmillServerStub {
private static final Logger LOG = LoggerFactory.getLogger(GrpcWindmillServer.class);
// If a connection cannot be established, gRPC will fail fast so this deadline can be relatively
// high.
private static final long DEFAULT_UNARY_RPC_DEADLINE_SECONDS = 300;
private static final long DEFAULT_STREAM_RPC_DEADLINE_SECONDS = 300;
// Stream clean close seconds must be set lower than the stream deadline seconds.
private static final long DEFAULT_STREAM_CLEAN_CLOSE_SECONDS = 180;
private static final Duration MIN_BACKOFF = Duration.millis(1);
private static final Duration MAX_BACKOFF = Duration.standardSeconds(30);
// Default gRPC streams to 2MB chunks, which has shown to be a large enough chunk size to reduce
// per-chunk overhead, and small enough that we can still granularly flow-control.
private static final int COMMIT_STREAM_CHUNK_SIZE = 2 << 20;
private static final int GET_DATA_STREAM_CHUNK_SIZE = 2 << 20;
private static final AtomicLong nextId = new AtomicLong(0);
private final StreamingDataflowWorkerOptions options;
private final int streamingRpcBatchLimit;
private final List<CloudWindmillServiceV1Alpha1Grpc.CloudWindmillServiceV1Alpha1Stub> stubList =
new ArrayList<>();
private final List<CloudWindmillServiceV1Alpha1Grpc.CloudWindmillServiceV1Alpha1BlockingStub>
syncStubList = new ArrayList<>();
private WindmillApplianceGrpc.WindmillApplianceBlockingStub syncApplianceStub = null;
private long unaryDeadlineSeconds = DEFAULT_UNARY_RPC_DEADLINE_SECONDS;
private ImmutableSet<HostAndPort> endpoints;
private int logEveryNStreamFailures = 20;
private Duration maxBackoff = MAX_BACKOFF;
private final ThrottleTimer getWorkThrottleTimer = new ThrottleTimer();
private final ThrottleTimer getDataThrottleTimer = new ThrottleTimer();
private final ThrottleTimer commitWorkThrottleTimer = new ThrottleTimer();
Random rand = new Random();
private final Set<AbstractWindmillStream<?, ?>> streamRegistry =
Collections.newSetFromMap(new ConcurrentHashMap<AbstractWindmillStream<?, ?>, Boolean>());
public GrpcWindmillServer(StreamingDataflowWorkerOptions options) throws IOException {
this.options = options;
this.streamingRpcBatchLimit = options.getWindmillServiceStreamingRpcBatchLimit();
this.endpoints = ImmutableSet.of();
if (options.getWindmillServiceEndpoint() != null) {
Set<HostAndPort> endpoints = new HashSet<>();
for (String endpoint : Splitter.on(',').split(options.getWindmillServiceEndpoint())) {
endpoints.add(
HostAndPort.fromString(endpoint).withDefaultPort(options.getWindmillServicePort()));
}
initializeWindmillService(endpoints);
} else if (!streamingEngineEnabled() && options.getLocalWindmillHostport() != null) {
int portStart = options.getLocalWindmillHostport().lastIndexOf(':');
String endpoint = options.getLocalWindmillHostport().substring(0, portStart);
assert ("grpc:localhost".equals(endpoint));
int port = Integer.parseInt(options.getLocalWindmillHostport().substring(portStart + 1));
this.endpoints = ImmutableSet.<HostAndPort>of(HostAndPort.fromParts("localhost", port));
initializeLocalHost(port);
}
}
private GrpcWindmillServer(String name, boolean enableStreamingEngine) {
this.options = PipelineOptionsFactory.create().as(StreamingDataflowWorkerOptions.class);
this.streamingRpcBatchLimit = Integer.MAX_VALUE;
options.setProject("project");
options.setJobId("job");
options.setWorkerId("worker");
if (enableStreamingEngine) {
List<String> experiments = this.options.getExperiments();
if (experiments == null) {
experiments = new ArrayList<>();
}
experiments.add(GcpOptions.STREAMING_ENGINE_EXPERIMENT);
options.setExperiments(experiments);
}
this.stubList.add(CloudWindmillServiceV1Alpha1Grpc.newStub(inProcessChannel(name)));
}
private boolean streamingEngineEnabled() {
return options.isEnableStreamingEngine();
}
@Override
public synchronized void setWindmillServiceEndpoints(Set<HostAndPort> endpoints)
throws IOException {
Preconditions.checkNotNull(endpoints);
if (endpoints.equals(this.endpoints)) {
// The endpoints are equal don't recreate the stubs.
return;
}
LOG.info("Creating a new windmill stub, endpoints: {}", endpoints);
if (this.endpoints != null) {
LOG.info("Previous windmill stub endpoints: {}", this.endpoints);
}
initializeWindmillService(endpoints);
}
@Override
public synchronized boolean isReady() {
return !stubList.isEmpty();
}
private synchronized void initializeLocalHost(int port) throws IOException {
this.logEveryNStreamFailures = 1;
this.maxBackoff = Duration.millis(500);
this.unaryDeadlineSeconds = 10; // For local testing use a short deadline.
Channel channel = localhostChannel(port);
if (streamingEngineEnabled()) {
this.stubList.add(CloudWindmillServiceV1Alpha1Grpc.newStub(channel));
this.syncStubList.add(CloudWindmillServiceV1Alpha1Grpc.newBlockingStub(channel));
} else {
this.syncApplianceStub = WindmillApplianceGrpc.newBlockingStub(channel);
}
}
/**
* Create a wrapper around credentials callback that delegates to the underlying vendored {@link
* com.google.auth.RequestMetadataCallback}. Note that this class should override every method
* that is not final and not static and call the delegate directly.
*
* <p>TODO: Replace this with an auto generated proxy which calls the underlying implementation
* delegate to reduce maintenance burden.
*/
private static class VendoredRequestMetadataCallbackAdapter
implements com.google.auth.RequestMetadataCallback {
private final org.apache.beam.vendor.grpc.v1p21p0.com.google.auth.RequestMetadataCallback
callback;
private VendoredRequestMetadataCallbackAdapter(
org.apache.beam.vendor.grpc.v1p21p0.com.google.auth.RequestMetadataCallback callback) {
this.callback = callback;
}
@Override
public void onSuccess(Map<String, List<String>> metadata) {
callback.onSuccess(metadata);
}
@Override
public void onFailure(Throwable exception) {
callback.onFailure(exception);
}
}
/**
* Create a wrapper around credentials that delegates to the underlying {@link
* com.google.auth.Credentials}. Note that this class should override every method that is not
* final and not static and call the delegate directly.
*
* <p>TODO: Replace this with an auto generated proxy which calls the underlying implementation
* delegate to reduce maintenance burden.
*/
private static class VendoredCredentialsAdapter
extends org.apache.beam.vendor.grpc.v1p21p0.com.google.auth.Credentials {
private final com.google.auth.Credentials credentials;
private VendoredCredentialsAdapter(com.google.auth.Credentials credentials) {
this.credentials = credentials;
}
@Override
public String getAuthenticationType() {
return credentials.getAuthenticationType();
}
@Override
public Map<String, List<String>> getRequestMetadata() throws IOException {
return credentials.getRequestMetadata();
}
@Override
public void getRequestMetadata(
final URI uri,
Executor executor,
final org.apache.beam.vendor.grpc.v1p21p0.com.google.auth.RequestMetadataCallback
callback) {
credentials.getRequestMetadata(
uri, executor, new VendoredRequestMetadataCallbackAdapter(callback));
}
@Override
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException {
return credentials.getRequestMetadata(uri);
}
@Override
public boolean hasRequestMetadata() {
return credentials.hasRequestMetadata();
}
@Override
public boolean hasRequestMetadataOnly() {
return credentials.hasRequestMetadataOnly();
}
@Override
public void refresh() throws IOException {
credentials.refresh();
}
}
private synchronized void initializeWindmillService(Set<HostAndPort> endpoints)
throws IOException {
LOG.info("Initializing Streaming Engine GRPC client for endpoints: {}", endpoints);
this.stubList.clear();
this.syncStubList.clear();
this.endpoints = ImmutableSet.<HostAndPort>copyOf(endpoints);
for (HostAndPort endpoint : this.endpoints) {
if ("localhost".equals(endpoint.getHost())) {
initializeLocalHost(endpoint.getPort());
} else {
CallCredentials creds =
MoreCallCredentials.from(new VendoredCredentialsAdapter(options.getGcpCredential()));
this.stubList.add(
CloudWindmillServiceV1Alpha1Grpc.newStub(remoteChannel(endpoint))
.withCallCredentials(creds));
this.syncStubList.add(
CloudWindmillServiceV1Alpha1Grpc.newBlockingStub(remoteChannel(endpoint))
.withCallCredentials(creds));
}
}
}
@VisibleForTesting
static GrpcWindmillServer newTestInstance(String name, boolean enableStreamingEngine) {
return new GrpcWindmillServer(name, enableStreamingEngine);
}
private Channel inProcessChannel(String name) {
return InProcessChannelBuilder.forName(name).directExecutor().build();
}
private Channel localhostChannel(int port) {
return NettyChannelBuilder.forAddress("localhost", port)
.maxInboundMessageSize(java.lang.Integer.MAX_VALUE)
.negotiationType(NegotiationType.PLAINTEXT)
.build();
}
private Channel remoteChannel(HostAndPort endpoint) throws IOException {
return NettyChannelBuilder.forAddress(endpoint.getHost(), endpoint.getPort())
.maxInboundMessageSize(java.lang.Integer.MAX_VALUE)
.negotiationType(NegotiationType.TLS)
// Set ciphers(null) to not use GCM, which is disabled for Dataflow
// due to it being horribly slow.
.sslContext(GrpcSslContexts.forClient().ciphers(null).build())
.build();
}
private synchronized CloudWindmillServiceV1Alpha1Grpc.CloudWindmillServiceV1Alpha1Stub stub() {
if (stubList.isEmpty()) {
throw new RuntimeException("windmillServiceEndpoint has not been set");
}
if (stubList.size() == 1) {
return stubList.get(0);
}
return stubList.get(rand.nextInt(stubList.size()));
}
private synchronized CloudWindmillServiceV1Alpha1Grpc.CloudWindmillServiceV1Alpha1BlockingStub
syncStub() {
if (syncStubList.isEmpty()) {
throw new RuntimeException("windmillServiceEndpoint has not been set");
}
if (syncStubList.size() == 1) {
return syncStubList.get(0);
}
return syncStubList.get(rand.nextInt(syncStubList.size()));
}
@Override
public void appendSummaryHtml(PrintWriter writer) {
writer.write("Active Streams:<br>");
for (AbstractWindmillStream<?, ?> stream : streamRegistry) {
stream.appendSummaryHtml(writer);
writer.write("<br>");
}
}
// Configure backoff to retry calls forever, with a maximum sane retry interval.
private BackOff grpcBackoff() {
return FluentBackoff.DEFAULT
.withInitialBackoff(MIN_BACKOFF)
.withMaxBackoff(maxBackoff)
.backoff();
}
private <ResponseT> ResponseT callWithBackoff(Supplier<ResponseT> function) {
BackOff backoff = grpcBackoff();
int rpcErrors = 0;
while (true) {
try {
return function.get();
} catch (StatusRuntimeException e) {
try {
if (++rpcErrors % 20 == 0) {
LOG.warn(
"Many exceptions calling gRPC. Last exception: {} with status {}",
e,
e.getStatus());
}
if (!BackOffUtils.next(Sleeper.DEFAULT, backoff)) {
throw new WindmillServerStub.RpcException(e);
}
} catch (IOException | InterruptedException i) {
if (i instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
WindmillServerStub.RpcException rpcException = new WindmillServerStub.RpcException(e);
rpcException.addSuppressed(i);
throw rpcException;
}
}
}
}
@Override
public GetWorkResponse getWork(GetWorkRequest request) {
if (syncApplianceStub == null) {
return callWithBackoff(
() ->
syncStub()
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getWork(
request
.toBuilder()
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.setWorkerId(options.getWorkerId())
.build()));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getWork(request));
}
}
@Override
public GetDataResponse getData(GetDataRequest request) {
if (syncApplianceStub == null) {
return callWithBackoff(
() ->
syncStub()
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getData(
request
.toBuilder()
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.build()));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getData(request));
}
}
@Override
public CommitWorkResponse commitWork(CommitWorkRequest request) {
if (syncApplianceStub == null) {
return callWithBackoff(
() ->
syncStub()
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.commitWork(
request
.toBuilder()
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.build()));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.commitWork(request));
}
}
@Override
public GetWorkStream getWorkStream(GetWorkRequest request, WorkItemReceiver receiver) {
return new GrpcGetWorkStream(
GetWorkRequest.newBuilder(request)
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.setWorkerId(options.getWorkerId())
.build(),
receiver);
}
@Override
public GetDataStream getDataStream() {
return new GrpcGetDataStream();
}
@Override
public CommitWorkStream commitWorkStream() {
return new GrpcCommitWorkStream();
}
@Override
public GetConfigResponse getConfig(GetConfigRequest request) {
if (syncApplianceStub == null) {
throw new RpcException(
new UnsupportedOperationException("GetConfig not supported with windmill service."));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.getConfig(request));
}
}
@Override
public ReportStatsResponse reportStats(ReportStatsRequest request) {
if (syncApplianceStub == null) {
throw new RpcException(
new UnsupportedOperationException("ReportStats not supported with windmill service."));
} else {
return callWithBackoff(
() ->
syncApplianceStub
.withDeadlineAfter(unaryDeadlineSeconds, TimeUnit.SECONDS)
.reportStats(request));
}
}
@Override
public long getAndResetThrottleTime() {
return getWorkThrottleTimer.getAndResetThrottleTime()
+ getDataThrottleTimer.getAndResetThrottleTime()
+ commitWorkThrottleTimer.getAndResetThrottleTime();
}
private JobHeader makeHeader() {
return JobHeader.newBuilder()
.setJobId(options.getJobId())
.setProjectId(options.getProject())
.setWorkerId(options.getWorkerId())
.build();
}
/** Returns a long that is unique to this process. */
private static long uniqueId() {
return nextId.incrementAndGet();
}
/**
* Base class for persistent streams connecting to Windmill.
*
* <p>This class handles the underlying gRPC StreamObservers, and automatically reconnects the
* stream if it is broken. Subclasses are responsible for retrying requests that have been lost on
* a broken stream.
*
* <p>Subclasses should override onResponse to handle responses from the server, and onNewStream
* to perform any work that must be done when a new stream is created, such as sending headers or
* retrying requests.
*
* <p>send and startStream should not be called from onResponse; use executor() instead.
*
* <p>Synchronization on this is used to synchronize the gRpc stream state and internal data
* structures. Since grpc channel operations may block, synchronization on this stream may also
* block. This is generally not a problem since streams are used in a single-threaded manner.
* However some accessors used for status page and other debugging need to take care not to
* require synchronizing on this.
*/
private abstract class AbstractWindmillStream<RequestT, ResponseT> implements WindmillStream {
private final StreamObserverFactory streamObserverFactory = StreamObserverFactory.direct();
private final Function<StreamObserver<ResponseT>, StreamObserver<RequestT>> clientFactory;
private final Executor executor = Executors.newSingleThreadExecutor();
// The following should be protected by synchronizing on this, except for
// the atomics which may be read atomically for status pages.
private StreamObserver<RequestT> requestObserver;
private final AtomicLong startTimeMs = new AtomicLong();
private final AtomicInteger errorCount = new AtomicInteger();
private final BackOff backoff = grpcBackoff();
private final AtomicLong sleepUntil = new AtomicLong();
protected final AtomicBoolean clientClosed = new AtomicBoolean();
private final CountDownLatch finishLatch = new CountDownLatch(1);
protected AbstractWindmillStream(
Function<StreamObserver<ResponseT>, StreamObserver<RequestT>> clientFactory) {
this.clientFactory = clientFactory;
}
/** Called on each response from the server */
protected abstract void onResponse(ResponseT response);
/** Called when a new underlying stream to the server has been opened. */
protected abstract void onNewStream();
/** Returns whether there are any pending requests that should be retried on a stream break. */
protected abstract boolean hasPendingRequests();
/**
* Called when the stream is throttled due to resource exhausted errors. Will be called for each
* resource exhausted error not just the first. onResponse() must stop throttling on reciept of
* the first good message.
*/
protected abstract void startThrottleTimer();
/** Send a request to the server. */
protected final synchronized void send(RequestT request) {
requestObserver.onNext(request);
}
/** Starts the underlying stream. */
protected final void startStream() {
// Add the stream to the registry after it has been fully constructed.
streamRegistry.add(this);
BackOff backoff = grpcBackoff();
while (true) {
try {
synchronized (this) {
startTimeMs.set(Instant.now().getMillis());
requestObserver = streamObserverFactory.from(clientFactory, new ResponseObserver());
onNewStream();
if (clientClosed.get()) {
close();
}
return;
}
} catch (Exception e) {
LOG.error("Failed to create new stream, retrying: ", e);
try {
long sleep = backoff.nextBackOffMillis();
sleepUntil.set(Instant.now().getMillis() + sleep);
Thread.sleep(sleep);
} catch (InterruptedException i) {
// Keep trying to create the stream.
} catch (IOException i) {
// Ignore.
}
}
}
}
protected final Executor executor() {
return executor;
}
// Care is taken that synchronization on this is unnecessary for all status page information.
// Blocking sends are made beneath this stream object's lock which could block status page
// rendering.
public final void appendSummaryHtml(PrintWriter writer) {
appendSpecificHtml(writer);
if (errorCount.get() > 0) {
writer.format(", %d errors", errorCount.get());
}
if (clientClosed.get()) {
writer.write(", client closed");
}
long sleepLeft = sleepUntil.get() - Instant.now().getMillis();
if (sleepLeft > 0) {
writer.format(", %dms backoff remaining", sleepLeft);
}
writer.format(", current stream is %dms old", Instant.now().getMillis() - startTimeMs.get());
}
// Don't require synchronization on stream, see the appendSummaryHtml comment.
protected abstract void appendSpecificHtml(PrintWriter writer);
private class ResponseObserver implements StreamObserver<ResponseT> {
@Override
public void onNext(ResponseT response) {
try {
backoff.reset();
} catch (IOException e) {
// Ignore.
}
onResponse(response);
}
@Override
public void onError(Throwable t) {
onStreamFinished(t);
}
@Override
public void onCompleted() {
onStreamFinished(null);
}
private void onStreamFinished(@Nullable Throwable t) {
synchronized (this) {
if (clientClosed.get() && !hasPendingRequests()) {
streamRegistry.remove(AbstractWindmillStream.this);
finishLatch.countDown();
return;
}
}
if (t != null) {
Status status = null;
if (t instanceof StatusRuntimeException) {
status = ((StatusRuntimeException) t).getStatus();
}
if (errorCount.incrementAndGet() % logEveryNStreamFailures == 0) {
LOG.warn(
"{} streaming Windmill RPC errors for a stream, last was: {} with status {}",
errorCount.get(),
t.toString(),
status);
}
// If the stream was stopped due to a resource exhausted error then we are throttled.
if (status != null && status.getCode() == Status.Code.RESOURCE_EXHAUSTED) {
startThrottleTimer();
}
try {
long sleep = backoff.nextBackOffMillis();
sleepUntil.set(Instant.now().getMillis() + sleep);
Thread.sleep(sleep);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (IOException e) {
// Ignore.
}
}
executor.execute(AbstractWindmillStream.this::startStream);
}
}
@Override
public final synchronized void close() {
// Synchronization of close and onCompleted necessary for correct retry logic in onNewStream.
clientClosed.set(true);
requestObserver.onCompleted();
}
@Override
public final boolean awaitTermination(int time, TimeUnit unit) throws InterruptedException {
return finishLatch.await(time, unit);
}
@Override
public final void closeAfterDefaultTimeout() throws InterruptedException {
if (!finishLatch.await(DEFAULT_STREAM_CLEAN_CLOSE_SECONDS, TimeUnit.SECONDS)) {
// If the stream did not close due to error in the specified amount of time, half-close
// the stream cleanly.
close();
}
}
@Override
public final Instant startTime() {
return new Instant(startTimeMs.get());
}
}
private class GrpcGetWorkStream
extends AbstractWindmillStream<StreamingGetWorkRequest, StreamingGetWorkResponseChunk>
implements GetWorkStream {
private final GetWorkRequest request;
private final WorkItemReceiver receiver;
private final Map<Long, WorkItemBuffer> buffers = new ConcurrentHashMap<>();
private final AtomicLong inflightMessages = new AtomicLong();
private final AtomicLong inflightBytes = new AtomicLong();
private GrpcGetWorkStream(GetWorkRequest request, WorkItemReceiver receiver) {
super(
responseObserver ->
stub()
.withDeadlineAfter(DEFAULT_STREAM_RPC_DEADLINE_SECONDS, TimeUnit.SECONDS)
.getWorkStream(responseObserver));
this.request = request;
this.receiver = receiver;
startStream();
}
@Override
protected synchronized void onNewStream() {
buffers.clear();
inflightMessages.set(request.getMaxItems());
inflightBytes.set(request.getMaxBytes());
send(StreamingGetWorkRequest.newBuilder().setRequest(request).build());
}
@Override
protected boolean hasPendingRequests() {
return false;
}
@Override
public void appendSpecificHtml(PrintWriter writer) {
// Number of buffers is same as distict workers that sent work on this stream.
writer.format(
"GetWorkStream: %d buffers, %d inflight messages allowed, %d inflight bytes allowed",
buffers.size(), inflightMessages.intValue(), inflightBytes.intValue());
}
@Override
protected void onResponse(StreamingGetWorkResponseChunk chunk) {
getWorkThrottleTimer.stop();
long id = chunk.getStreamId();
WorkItemBuffer buffer = buffers.computeIfAbsent(id, (Long l) -> new WorkItemBuffer());
buffer.append(chunk);
if (chunk.getRemainingBytesForWorkItem() == 0) {
long size = buffer.bufferedSize();
buffer.runAndReset();
// Record the fact that there are now fewer outstanding messages and bytes on the stream.
long numInflight = inflightMessages.decrementAndGet();
long bytesInflight = inflightBytes.addAndGet(-size);
// If the outstanding items or bytes limit has gotten too low, top both off with a
// GetWorkExtension. The goal is to keep the limits relatively close to their maximum
// values without sending too many extension requests.
if (numInflight < request.getMaxItems() / 2 || bytesInflight < request.getMaxBytes() / 2) {
long moreItems = request.getMaxItems() - numInflight;
long moreBytes = request.getMaxBytes() - bytesInflight;
inflightMessages.getAndAdd(moreItems);
inflightBytes.getAndAdd(moreBytes);
final StreamingGetWorkRequest extension =
StreamingGetWorkRequest.newBuilder()
.setRequestExtension(
StreamingGetWorkRequestExtension.newBuilder()
.setMaxItems(moreItems)
.setMaxBytes(moreBytes))
.build();
executor()
.execute(
() -> {
try {
send(extension);
} catch (IllegalStateException e) {
// Stream was closed.
}
});
}
}
}
@Override
protected void startThrottleTimer() {
getWorkThrottleTimer.start();
}
private class WorkItemBuffer {
private String computation;
private Instant inputDataWatermark;
private Instant synchronizedProcessingTime;
private ByteString data = ByteString.EMPTY;
private long bufferedSize = 0;
private void setMetadata(Windmill.ComputationWorkItemMetadata metadata) {
this.computation = metadata.getComputationId();
this.inputDataWatermark =
WindmillTimeUtils.windmillToHarnessWatermark(metadata.getInputDataWatermark());
this.synchronizedProcessingTime =
WindmillTimeUtils.windmillToHarnessWatermark(
metadata.getDependentRealtimeInputWatermark());
}
public void append(StreamingGetWorkResponseChunk chunk) {
if (chunk.hasComputationMetadata()) {
setMetadata(chunk.getComputationMetadata());
}
this.data = data.concat(chunk.getSerializedWorkItem());
this.bufferedSize += chunk.getSerializedWorkItem().size();
}
public long bufferedSize() {
return bufferedSize;
}
public void runAndReset() {
try {
receiver.receiveWork(
computation,
inputDataWatermark,
synchronizedProcessingTime,
Windmill.WorkItem.parseFrom(data.newInput()));
} catch (IOException e) {
LOG.error("Failed to parse work item from stream: ", e);
}
data = ByteString.EMPTY;
bufferedSize = 0;
}
}
}
private class GrpcGetDataStream
extends AbstractWindmillStream<StreamingGetDataRequest, StreamingGetDataResponse>
implements GetDataStream {
private class QueuedRequest {
public QueuedRequest(String computation, KeyedGetDataRequest request) {
this.id = uniqueId();
this.globalDataRequest = null;
this.dataRequest =
ComputationGetDataRequest.newBuilder()
.setComputationId(computation)
.addRequests(request)
.build();
this.byteSize = this.dataRequest.getSerializedSize();
}
public QueuedRequest(GlobalDataRequest request) {
this.id = uniqueId();
this.globalDataRequest = request;
this.dataRequest = null;
this.byteSize = this.globalDataRequest.getSerializedSize();
}
final long id;
final long byteSize;
final GlobalDataRequest globalDataRequest;
final ComputationGetDataRequest dataRequest;
AppendableInputStream responseStream = null;
}
private class QueuedBatch {
public QueuedBatch() {}
final List<QueuedRequest> requests = new ArrayList<>();
long byteSize = 0;
boolean finalized = false;
final CountDownLatch sent = new CountDownLatch(1);
};
private final Deque<QueuedBatch> batches = new ConcurrentLinkedDeque<>();
private final Map<Long, AppendableInputStream> pending = new ConcurrentHashMap<>();
@Override
public void appendSpecificHtml(PrintWriter writer) {
writer.format(
"GetDataStream: %d pending on-wire, %d queued batches", pending.size(), batches.size());
}
GrpcGetDataStream() {
super(
responseObserver ->
stub()
.withDeadlineAfter(DEFAULT_STREAM_RPC_DEADLINE_SECONDS, TimeUnit.SECONDS)
.getDataStream(responseObserver));
startStream();
}
@Override
protected synchronized void onNewStream() {
send(StreamingGetDataRequest.newBuilder().setHeader(makeHeader()).build());
if (clientClosed.get()) {
// We rely on close only occurring after all methods on the stream have returned.
// Since the requestKeyedData and requestGlobalData methods are blocking this
// means there should be no pending requests.
Verify.verify(!hasPendingRequests());
} else {
for (AppendableInputStream responseStream : pending.values()) {
responseStream.cancel();
}
}
}
@Override
protected boolean hasPendingRequests() {
return !pending.isEmpty() || !batches.isEmpty();
}
@Override
protected void onResponse(StreamingGetDataResponse chunk) {
Preconditions.checkArgument(chunk.getRequestIdCount() == chunk.getSerializedResponseCount());
Preconditions.checkArgument(
chunk.getRemainingBytesForResponse() == 0 || chunk.getRequestIdCount() == 1);
getDataThrottleTimer.stop();
for (int i = 0; i < chunk.getRequestIdCount(); ++i) {
AppendableInputStream responseStream = pending.get(chunk.getRequestId(i));
Verify.verify(responseStream != null, "No pending response stream");
responseStream.append(chunk.getSerializedResponse(i).newInput());
if (chunk.getRemainingBytesForResponse() == 0) {
responseStream.complete();
}
}
}
@Override
protected void startThrottleTimer() {
getDataThrottleTimer.start();
}
@Override
public KeyedGetDataResponse requestKeyedData(String computation, KeyedGetDataRequest request) {
return issueRequest(new QueuedRequest(computation, request), KeyedGetDataResponse::parseFrom);
}
@Override
public GlobalData requestGlobalData(GlobalDataRequest request) {
return issueRequest(new QueuedRequest(request), GlobalData::parseFrom);
}
@Override
public void refreshActiveWork(Map<String, List<KeyedGetDataRequest>> active) {
long builderBytes = 0;
StreamingGetDataRequest.Builder builder = StreamingGetDataRequest.newBuilder();
for (Map.Entry<String, List<KeyedGetDataRequest>> entry : active.entrySet()) {
for (KeyedGetDataRequest request : entry.getValue()) {
// Calculate the bytes with some overhead for proto encoding.
long bytes = (long) entry.getKey().length() + request.getSerializedSize() + 10;
if (builderBytes > 0
&& (builderBytes + bytes > GET_DATA_STREAM_CHUNK_SIZE
|| builder.getRequestIdCount() >= streamingRpcBatchLimit)) {
send(builder.build());
builderBytes = 0;
builder.clear();
}
builderBytes += bytes;
builder.addStateRequest(
ComputationGetDataRequest.newBuilder()
.setComputationId(entry.getKey())
.addRequests(request));
}
}
if (builderBytes > 0) {
send(builder.build());
}
}
private <ResponseT> ResponseT issueRequest(QueuedRequest request, ParseFn<ResponseT> parseFn) {
while (true) {
request.responseStream = new AppendableInputStream();
try {
queueRequestAndWait(request);
return parseFn.parse(request.responseStream);
} catch (CancellationException e) {
// Retry issuing the request since the response stream was cancelled.
continue;
} catch (IOException e) {
LOG.error("Parsing GetData response failed: ", e);
continue;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
pending.remove(request.id);
}
}
}
private void queueRequestAndWait(QueuedRequest request) throws InterruptedException {
QueuedBatch batch;
boolean responsibleForSend = false;
CountDownLatch waitForSendLatch = null;
synchronized (batches) {
batch = batches.isEmpty() ? null : batches.getLast();
if (batch == null
|| batch.finalized
|| batch.requests.size() >= streamingRpcBatchLimit
|| batch.byteSize + request.byteSize > GET_DATA_STREAM_CHUNK_SIZE) {
if (batch != null) {
waitForSendLatch = batch.sent;
}
batch = new QueuedBatch();
batches.addLast(batch);
responsibleForSend = true;
}
batch.requests.add(request);
batch.byteSize += request.byteSize;
}
if (responsibleForSend) {
if (waitForSendLatch == null) {
// If there was not a previous batch wait a little while to improve
// batching.
Thread.sleep(1);
} else {
waitForSendLatch.await();
}
// Finalize the batch so that no additional requests will be added. Leave the batch in the
// queue so that a subsequent batch will wait for it's completion.
synchronized (batches) {
Verify.verify(batch == batches.peekFirst());
batch.finalized = true;
}
sendBatch(batch.requests);
synchronized (batches) {
Verify.verify(batch == batches.pollFirst());
}
// Notify all waiters with requests in this batch as well as the sender
// of the next batch (if one exists).
batch.sent.countDown();
} else {
// Wait for this batch to be sent before parsing the response.
batch.sent.await();
}
}
private void sendBatch(List<QueuedRequest> requests) {
StreamingGetDataRequest batchedRequest = flushToBatch(requests);
synchronized (this) {
// Synchronization of pending inserts is necessary with send to ensure duplicates are not
// sent on stream reconnect.
for (QueuedRequest request : requests) {
Verify.verify(pending.put(request.id, request.responseStream) == null);
}
try {
send(batchedRequest);
} catch (IllegalStateException e) {
// The stream broke before this call went through; onNewStream will retry the fetch.
}
}
}
private StreamingGetDataRequest flushToBatch(List<QueuedRequest> requests) {
// Put all global data requests first because there is only a single repeated field for
// request ids and the initial ids correspond to global data requests if they are present.
requests.sort(
(QueuedRequest r1, QueuedRequest r2) -> {
boolean r1gd = r1.globalDataRequest != null;
boolean r2gd = r2.globalDataRequest != null;
return r1gd == r2gd ? 0 : (r1gd ? -1 : 1);
});
StreamingGetDataRequest.Builder builder = StreamingGetDataRequest.newBuilder();
for (QueuedRequest request : requests) {
builder.addRequestId(request.id);
if (request.globalDataRequest == null) {
builder.addStateRequest(request.dataRequest);
} else {
builder.addGlobalDataRequest(request.globalDataRequest);
}
}
return builder.build();
}
}
private class GrpcCommitWorkStream
extends AbstractWindmillStream<StreamingCommitWorkRequest, StreamingCommitResponse>
implements CommitWorkStream {
private class PendingRequest {
private final String computation;
private final WorkItemCommitRequest request;
private final Consumer<CommitStatus> onDone;
PendingRequest(
String computation, WorkItemCommitRequest request, Consumer<CommitStatus> onDone) {
this.computation = computation;
this.request = request;
this.onDone = onDone;
}
long getBytes() {
return (long) request.getSerializedSize() + computation.length();
}
}
private final Map<Long, PendingRequest> pending = new ConcurrentHashMap<>();
private class Batcher {
long queuedBytes = 0;
Map<Long, PendingRequest> queue = new HashMap<>();
boolean canAccept(PendingRequest request) {
return queue.isEmpty()
|| (queue.size() < streamingRpcBatchLimit
&& (request.getBytes() + queuedBytes) < COMMIT_STREAM_CHUNK_SIZE);
}
void add(long id, PendingRequest request) {
assert (canAccept(request));
queuedBytes += request.getBytes();
queue.put(id, request);
}
void flush() {
flushInternal(queue);
queuedBytes = 0;
}
}
private final Batcher batcher = new Batcher();
GrpcCommitWorkStream() {
super(
responseObserver ->
stub()
.withDeadlineAfter(DEFAULT_STREAM_RPC_DEADLINE_SECONDS, TimeUnit.SECONDS)
.commitWorkStream(responseObserver));
startStream();
}
@Override
public void appendSpecificHtml(PrintWriter writer) {
writer.format("CommitWorkStream: %d pending", pending.size());
}
@Override
protected synchronized void onNewStream() {
send(StreamingCommitWorkRequest.newBuilder().setHeader(makeHeader()).build());
Batcher resendBatcher = new Batcher();
for (Map.Entry<Long, PendingRequest> entry : pending.entrySet()) {
if (!resendBatcher.canAccept(entry.getValue())) {
resendBatcher.flush();
}
resendBatcher.add(entry.getKey(), entry.getValue());
}
resendBatcher.flush();
}
@Override
protected boolean hasPendingRequests() {
return !pending.isEmpty();
}
@Override
protected void onResponse(StreamingCommitResponse response) {
commitWorkThrottleTimer.stop();
for (int i = 0; i < response.getRequestIdCount(); ++i) {
long requestId = response.getRequestId(i);
PendingRequest done = pending.remove(requestId);
if (done == null) {
LOG.error("Got unknown commit request ID: {}", requestId);
} else {
done.onDone.accept(
(i < response.getStatusCount()) ? response.getStatus(i) : CommitStatus.OK);
}
}
}
@Override
protected void startThrottleTimer() {
commitWorkThrottleTimer.start();
}
@Override
public boolean commitWorkItem(
String computation, WorkItemCommitRequest commitRequest, Consumer<CommitStatus> onDone) {
PendingRequest request = new PendingRequest(computation, commitRequest, onDone);
if (!batcher.canAccept(request)) {
return false;
}
batcher.add(uniqueId(), request);
return true;
}
@Override
public void flush() {
batcher.flush();
}
private final void flushInternal(Map<Long, PendingRequest> requests) {
if (requests.isEmpty()) {
return;
}
if (requests.size() == 1) {
Map.Entry<Long, PendingRequest> elem = requests.entrySet().iterator().next();
if (elem.getValue().request.getSerializedSize() > COMMIT_STREAM_CHUNK_SIZE) {
issueMultiChunkRequest(elem.getKey(), elem.getValue());
} else {
issueSingleRequest(elem.getKey(), elem.getValue());
}
} else {
issueBatchedRequest(requests);
}
requests.clear();
}
private void issueSingleRequest(final long id, PendingRequest pendingRequest) {
StreamingCommitWorkRequest.Builder requestBuilder = StreamingCommitWorkRequest.newBuilder();
requestBuilder
.addCommitChunkBuilder()
.setComputationId(pendingRequest.computation)
.setRequestId(id)
.setShardingKey(pendingRequest.request.getShardingKey())
.setSerializedWorkItemCommit(pendingRequest.request.toByteString());
StreamingCommitWorkRequest chunk = requestBuilder.build();
try {
synchronized (this) {
pending.put(id, pendingRequest);
send(chunk);
}
} catch (IllegalStateException e) {
// Stream was broken, request will be retried when stream is reopened.
}
}
private void issueBatchedRequest(Map<Long, PendingRequest> requests) {
StreamingCommitWorkRequest.Builder requestBuilder = StreamingCommitWorkRequest.newBuilder();
String lastComputation = null;
for (Map.Entry<Long, PendingRequest> entry : requests.entrySet()) {
PendingRequest request = entry.getValue();
StreamingCommitRequestChunk.Builder chunkBuilder = requestBuilder.addCommitChunkBuilder();
if (lastComputation == null || !lastComputation.equals(request.computation)) {
chunkBuilder.setComputationId(request.computation);
lastComputation = request.computation;
}
chunkBuilder.setRequestId(entry.getKey());
chunkBuilder.setShardingKey(request.request.getShardingKey());
chunkBuilder.setSerializedWorkItemCommit(request.request.toByteString());
}
StreamingCommitWorkRequest request = requestBuilder.build();
try {
synchronized (this) {
pending.putAll(requests);
send(request);
}
} catch (IllegalStateException e) {
// Stream was broken, request will be retried when stream is reopened.
}
}
private void issueMultiChunkRequest(final long id, PendingRequest pendingRequest) {
Preconditions.checkNotNull(pendingRequest.computation);
final ByteString serializedCommit = pendingRequest.request.toByteString();
synchronized (this) {
pending.put(id, pendingRequest);
for (int i = 0; i < serializedCommit.size(); i += COMMIT_STREAM_CHUNK_SIZE) {
int end = i + COMMIT_STREAM_CHUNK_SIZE;
ByteString chunk = serializedCommit.substring(i, Math.min(end, serializedCommit.size()));
StreamingCommitRequestChunk.Builder chunkBuilder =
StreamingCommitRequestChunk.newBuilder()
.setRequestId(id)
.setSerializedWorkItemCommit(chunk)
.setComputationId(pendingRequest.computation)
.setShardingKey(pendingRequest.request.getShardingKey());
int remaining = serializedCommit.size() - end;
if (remaining > 0) {
chunkBuilder.setRemainingBytesForWorkItem(remaining);
}
StreamingCommitWorkRequest requestChunk =
StreamingCommitWorkRequest.newBuilder().addCommitChunk(chunkBuilder).build();
try {
send(requestChunk);
} catch (IllegalStateException e) {
// Stream was broken, request will be retried when stream is reopened.
break;
}
}
}
}
}
@FunctionalInterface
private interface ParseFn<ResponseT> {
ResponseT parse(InputStream input) throws IOException;
}
/** An InputStream that can be dynamically extended with additional InputStreams. */
@SuppressWarnings("JdkObsolete")
private static class AppendableInputStream extends InputStream {
private static final InputStream POISON_PILL = ByteString.EMPTY.newInput();
private final AtomicBoolean cancelled = new AtomicBoolean(false);
private final AtomicBoolean complete = new AtomicBoolean(false);
private final BlockingDeque<InputStream> queue = new LinkedBlockingDeque<>(10);
private final InputStream stream =
new SequenceInputStream(
new Enumeration<InputStream>() {
InputStream current = ByteString.EMPTY.newInput();
@Override
public boolean hasMoreElements() {
if (current != null) {
return true;
}
try {
current = queue.take();
if (current != POISON_PILL) {
return true;
}
if (cancelled.get()) {
throw new CancellationException();
}
if (complete.get()) {
return false;
}
throw new IllegalStateException("Got poison pill but stream is not done.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CancellationException();
}
}
@Override
public InputStream nextElement() {
if (!hasMoreElements()) {
throw new NoSuchElementException();
}
InputStream next = current;
current = null;
return next;
}
});
/** Appends a new InputStream to the tail of this stream. */
public synchronized void append(InputStream chunk) {
try {
queue.put(chunk);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/** Cancels the stream. Future calls to InputStream methods will throw CancellationException. */
public synchronized void cancel() {
cancelled.set(true);
try {
// Put the poison pill at the head of the queue to cancel as quickly as possible.
queue.clear();
queue.putFirst(POISON_PILL);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/** Signals that no new InputStreams will be added to this stream. */
public synchronized void complete() {
complete.set(true);
try {
queue.put(POISON_PILL);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public int read() throws IOException {
if (cancelled.get()) {
throw new CancellationException();
}
return stream.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (cancelled.get()) {
throw new CancellationException();
}
return stream.read(b, off, len);
}
@Override
public int available() throws IOException {
if (cancelled.get()) {
throw new CancellationException();
}
return stream.available();
}
@Override
public void close() throws IOException {
stream.close();
}
}
/**
* A stopwatch used to track the amount of time spent throttled due to Resource Exhausted errors.
* Throttle time is cumulative for all three rpcs types but not for all streams. So if GetWork and
* CommitWork are both blocked for x, totalTime will be 2x. However, if 2 GetWork streams are both
* blocked for x totalTime will be x. All methods are thread safe.
*/
private static class ThrottleTimer {
// This is -1 if not currently being throttled or the time in
// milliseconds when throttling for this type started.
private long startTime = -1;
// This is the collected total throttle times since the last poll. Throttle times are
// reported as a delta so this is cleared whenever it gets reported.
private long totalTime = 0;
/**
* Starts the timer if it has not been started and does nothing if it has already been started.
*/
public synchronized void start() {
if (!throttled()) { // This timer is not started yet so start it now.
startTime = Instant.now().getMillis();
}
}
/** Stops the timer if it has been started and does nothing if it has not been started. */
public synchronized void stop() {
if (throttled()) { // This timer has been started already so stop it now.
totalTime += Instant.now().getMillis() - startTime;
startTime = -1;
}
}
/** Returns if the specified type is currently being throttled */
public synchronized boolean throttled() {
return startTime != -1;
}
/** Returns the combined total of all throttle times and resets those times to 0. */
public synchronized long getAndResetThrottleTime() {
if (throttled()) {
stop();
start();
}
long toReturn = totalTime;
totalTime = 0;
return toReturn;
}
}
}
|
Avoid polluting Stackdriver logs with noise during autoscaling events.
Add message directing users to ignore them when appropriate.
|
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/windmill/GrpcWindmillServer.java
|
Avoid polluting Stackdriver logs with noise during autoscaling events. Add message directing users to ignore them when appropriate.
|
|
Java
|
apache-2.0
|
954517ad9bc2dde5fe9525903800b8ffdfb86edd
| 0
|
yanchenko/droidparts,b-cuts/droidparts,vovan888/droidparts,droidparts/droidparts,okankurtulus/droidparts
|
/**
* Copyright 2012 Alex Yanchenko
*
* 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.droidparts.util.io;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static org.droidparts.util.io.IOUtils.silentlyClose;
import java.io.BufferedInputStream;
import java.io.File;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.droidparts.net.http.HTTPException;
import org.droidparts.net.http.RESTClient;
import org.droidparts.util.AppUtils;
import org.droidparts.util.L;
import org.droidparts.util.ui.ViewUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
public class ImageAttacher {
private final BitmapCacher bitmapCacher;
private final ExecutorService executorService;
private final RESTClient restClient;
private final ConcurrentHashMap<ImageView, Pair<String, View>> data = new ConcurrentHashMap<ImageView, Pair<String, View>>();
private int crossFadeAnimationDuration = 400;
public ImageAttacher(Context ctx) {
this(ctx, Executors.newSingleThreadExecutor(),
new RESTClient(ctx, null));
}
public ImageAttacher(Context ctx, ExecutorService executorService,
RESTClient restClient) {
this(
new AppUtils(ctx).getExternalCacheDir() != null ? new BitmapCacher(
new File(new AppUtils(ctx).getExternalCacheDir(), "img"))
: null, executorService, restClient);
}
public ImageAttacher(BitmapCacher bitmapCacher,
ExecutorService executorService, RESTClient restClient) {
this.bitmapCacher = bitmapCacher;
this.executorService = executorService;
this.restClient = restClient;
}
public void setCrossFadeDuration(int millisec) {
this.crossFadeAnimationDuration = millisec;
}
public void attachImage(ImageView imageView, String imgUrl) {
addAndExecute(imageView, new Pair<String, View>(imgUrl, null));
}
public void attachImageCrossFaded(View placeholderView,
ImageView imageView, String imgUrl) {
placeholderView.setVisibility(VISIBLE);
imageView.setVisibility(INVISIBLE);
addAndExecute(imageView,
new Pair<String, View>(imgUrl, placeholderView));
}
private void addAndExecute(ImageView view, Pair<String, View> pair) {
data.put(view, pair);
executorService.execute(fetchAndAttachRunnable);
}
public Bitmap getCachedOrFetchAndCache(String fileUrl) {
Bitmap bm = null;
if (bitmapCacher != null) {
bm = bitmapCacher.readFromCache(fileUrl);
}
if (bm == null) {
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(
restClient.getInputStream(fileUrl).second);
bm = BitmapFactory.decodeStream(bis);
} catch (HTTPException e) {
L.e(e);
} finally {
silentlyClose(bis);
}
if (bitmapCacher != null && bm != null) {
bitmapCacher.saveToCache(fileUrl, bm);
}
}
return bm;
}
protected Bitmap processBitmapBeforeAttaching(ImageView imageView,
String url, Bitmap bm) {
return bm;
}
private final Runnable fetchAndAttachRunnable = new Runnable() {
@Override
public void run() {
for (ImageView view : data.keySet()) {
Pair<String, View> pair = data.get(view);
if (pair != null) {
String fileUrl = pair.first;
View placeholderView = pair.second;
data.remove(view);
Bitmap bm = getCachedOrFetchAndCache(fileUrl);
if (bm != null) {
bm = processBitmapBeforeAttaching(view, fileUrl, bm);
view.post(new AttachRunnable(placeholderView, view, bm));
}
}
}
}
};
private class AttachRunnable implements Runnable {
private final ImageView imageView;
private final Bitmap bitmap;
private final View placeholderView;
public AttachRunnable(View placeholderView, ImageView imageView,
Bitmap bitmap) {
this.placeholderView = placeholderView;
this.imageView = imageView;
this.bitmap = bitmap;
}
@Override
public void run() {
imageView.setImageBitmap(bitmap);
if (placeholderView != null) {
ViewUtils.crossFade(placeholderView, imageView,
crossFadeAnimationDuration);
}
}
}
//
@Deprecated
public void setImage(View view, String fileUrl) {
attachImage((ImageView) view, fileUrl);
}
@Deprecated
public void setImage(View view, String fileUrl, Drawable defaultImg) {
attachImage((ImageView) view, fileUrl);
}
}
|
extra/src/org/droidparts/util/io/ImageAttacher.java
|
/**
* Copyright 2012 Alex Yanchenko
*
* 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.droidparts.util.io;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static org.droidparts.util.io.IOUtils.silentlyClose;
import java.io.BufferedInputStream;
import java.io.File;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.droidparts.net.http.HTTPException;
import org.droidparts.net.http.RESTClient;
import org.droidparts.util.AppUtils;
import org.droidparts.util.L;
import org.droidparts.util.ui.ViewUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
public class ImageAttacher {
private final BitmapCacher bitmapCacher;
private final ExecutorService executorService;
private final RESTClient restClient;
private final Handler handler;
private final ConcurrentHashMap<ImageView, Pair<String, View>> data = new ConcurrentHashMap<ImageView, Pair<String, View>>();
private int crossFadeAnimationDuration = 400;
public ImageAttacher(Context ctx) {
this(ctx, Executors.newSingleThreadExecutor(),
new RESTClient(ctx, null));
}
public ImageAttacher(Context ctx, ExecutorService executorService,
RESTClient restClient) {
this(
new AppUtils(ctx).getExternalCacheDir() != null ? new BitmapCacher(
new File(new AppUtils(ctx).getExternalCacheDir(), "img"))
: null, executorService, restClient);
}
public ImageAttacher(BitmapCacher bitmapCacher,
ExecutorService executorService, RESTClient restClient) {
this.bitmapCacher = bitmapCacher;
this.executorService = executorService;
this.restClient = restClient;
handler = new Handler();
}
public void setCrossFadeDuration(int millisec) {
this.crossFadeAnimationDuration = millisec;
}
public void attachImage(ImageView imageView, String imgUrl) {
addAndExecute(imageView, new Pair<String, View>(imgUrl, null));
}
public void attachImageCrossFaded(View placeholderView,
ImageView imageView, String imgUrl) {
placeholderView.setVisibility(VISIBLE);
imageView.setVisibility(INVISIBLE);
addAndExecute(imageView,
new Pair<String, View>(imgUrl, placeholderView));
}
private void addAndExecute(ImageView view, Pair<String, View> pair) {
data.put(view, pair);
executorService.execute(fetchAndAttachRunnable);
}
public Bitmap getCachedOrFetchAndCache(String fileUrl) {
Bitmap bm = null;
if (bitmapCacher != null) {
bm = bitmapCacher.readFromCache(fileUrl);
}
if (bm == null) {
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(
restClient.getInputStream(fileUrl).second);
bm = BitmapFactory.decodeStream(bis);
} catch (HTTPException e) {
L.e(e);
} finally {
silentlyClose(bis);
}
if (bitmapCacher != null && bm != null) {
bitmapCacher.saveToCache(fileUrl, bm);
}
}
return bm;
}
protected Bitmap processBitmapBeforeAttaching(ImageView imageView,
String url, Bitmap bm) {
return bm;
}
private final Runnable fetchAndAttachRunnable = new Runnable() {
@Override
public void run() {
for (ImageView view : data.keySet()) {
Pair<String, View> pair = data.get(view);
if (pair != null) {
String fileUrl = pair.first;
View placeholderView = pair.second;
data.remove(view);
Bitmap bm = getCachedOrFetchAndCache(fileUrl);
if (bm != null) {
bm = processBitmapBeforeAttaching(view, fileUrl, bm);
handler.post(new AttachRunnable(placeholderView, view,
bm));
}
}
}
}
};
private class AttachRunnable implements Runnable {
private final ImageView imageView;
private final Bitmap bitmap;
private final View placeholderView;
public AttachRunnable(View placeholderView, ImageView imageView,
Bitmap bitmap) {
this.placeholderView = placeholderView;
this.imageView = imageView;
this.bitmap = bitmap;
}
@Override
public void run() {
imageView.setImageBitmap(bitmap);
if (placeholderView != null) {
ViewUtils.crossFade(placeholderView, imageView,
crossFadeAnimationDuration);
}
}
}
//
@Deprecated
public void setImage(View view, String fileUrl) {
attachImage((ImageView) view, fileUrl);
}
@Deprecated
public void setImage(View view, String fileUrl, Drawable defaultImg) {
attachImage((ImageView) view, fileUrl);
}
}
|
Handler seems to fail.
|
extra/src/org/droidparts/util/io/ImageAttacher.java
|
Handler seems to fail.
|
|
Java
|
apache-2.0
|
ba8f255ff33d279d0e9eb43f9817fd21f56aff36
| 0
|
psiinon/zaproxy,kingthorin/zaproxy,zaproxy/zaproxy,zaproxy/zaproxy,zaproxy/zaproxy,zaproxy/zaproxy,thc202/zaproxy,psiinon/zaproxy,thc202/zaproxy,kingthorin/zaproxy,kingthorin/zaproxy,kingthorin/zaproxy,thc202/zaproxy,thc202/zaproxy,psiinon/zaproxy,psiinon/zaproxy,kingthorin/zaproxy,thc202/zaproxy,psiinon/zaproxy,psiinon/zaproxy,kingthorin/zaproxy,thc202/zaproxy,thc202/zaproxy,zaproxy/zaproxy,kingthorin/zaproxy,zaproxy/zaproxy,psiinon/zaproxy,zaproxy/zaproxy
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.script;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.TreeNode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdesktop.swingx.JXTable;
import org.parosproxy.paros.CommandLine;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.extension.CommandLineArgument;
import org.parosproxy.paros.extension.CommandLineListener;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.extension.SessionChangedListener;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpSender;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.control.ExtensionFactory;
import org.zaproxy.zap.extension.script.ScriptsCache.Configuration;
import org.zaproxy.zap.utils.Stats;
public class ExtensionScript extends ExtensionAdaptor implements CommandLineListener {
public static final int EXTENSION_ORDER = 60;
public static final String NAME = "ExtensionScript";
/** @deprecated (2.7.0) Use {@link #getScriptIcon()} instead. */
@Deprecated public static final ImageIcon ICON = View.isInitialised() ? getScriptIcon() : null;
/**
* The {@code Charset} used to load/save the scripts from/to the file.
*
* <p>While the scripts can be loaded with any {@code Charset} (defaulting to this one) they are
* always saved with this {@code Charset}.
*
* @since 2.7.0
* @see #loadScript(ScriptWrapper)
* @see #loadScript(ScriptWrapper, Charset)
* @see #saveScript(ScriptWrapper)
*/
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
/**
* The script icon.
*
* <p>Lazily initialised.
*
* @see #getScriptIcon()
*/
private static ImageIcon scriptIcon;
public static final String SCRIPTS_DIR = "scripts";
public static final String TEMPLATES_DIR = SCRIPTS_DIR + File.separator + "templates";
private static final String LANG_ENGINE_SEP = " : ";
@Deprecated
protected static final String SCRIPT_CONSOLE_HOME_PAGE =
"https://github.com/zaproxy/zaproxy/wiki/ScriptConsole";
protected static final String SCRIPT_NAME_ATT = "zap.script.name";
public static final String TYPE_HTTP_SENDER = "httpsender";
public static final String TYPE_PROXY = "proxy";
public static final String TYPE_STANDALONE = "standalone";
public static final String TYPE_TARGETED = "targeted";
private ScriptEngineManager mgr = new ScriptEngineManager();
private ScriptParam scriptParam = null;
private OptionsScriptPanel optionsScriptPanel = null;
private ScriptTreeModel treeModel = null;
private List<ScriptEngineWrapper> engineWrappers = new ArrayList<>();
private Map<String, ScriptType> typeMap = new HashMap<>();
private ProxyListenerScript proxyListener = null;
private HttpSenderScriptListener httpSenderScriptListener;
private List<ScriptEventListener> listeners = new ArrayList<>();
private MultipleWriters writers = new MultipleWriters();
private ScriptUI scriptUI = null;
private CommandLineArgument[] arguments = new CommandLineArgument[1];
private static final int ARG_SCRIPT_IDX = 0;
private static final Logger logger = LogManager.getLogger(ExtensionScript.class);
/**
* Flag that indicates if the scripts/templates should be loaded when a new script type is
* registered.
*
* <p>This is to prevent loading scripts/templates of already installed scripts (ones that are
* registered during ZAP initialisation) twice, while allowing to load the scripts/templates of
* script types registered after initialisation (e.g. from installed add-ons).
*
* @since 2.4.0
* @see #registerScriptType(ScriptType)
* @see #optionsLoaded()
*/
private boolean shouldLoadScriptsOnScriptTypeRegistration;
/**
* The directories added to the extension, to automatically add and remove its scripts.
*
* @see #addScriptsFromDir(File)
* @see #removeScriptsFromDir(File)
*/
private List<File> trackedDirs = Collections.synchronizedList(new ArrayList<>());
/**
* The script output listeners added to the extension.
*
* @see #addScriptOutputListener(ScriptOutputListener)
* @see #getWriters(ScriptWrapper)
* @see #removeScriptOutputListener(ScriptOutputListener)
*/
private List<ScriptOutputListener> outputListeners = new CopyOnWriteArrayList<>();
public ExtensionScript() {
super(NAME);
this.setOrder(EXTENSION_ORDER);
ScriptEngine se = mgr.getEngineByName("ECMAScript");
if (se != null) {
this.registerScriptEngineWrapper(new JavascriptEngineWrapper(se.getFactory()));
} else {
logger.warn(
"No default JavaScript/ECMAScript engine found, some scripts might no longer work.");
}
}
@Override
public String getUIName() {
return Constant.messages.getString("script.name");
}
@Override
public void hook(ExtensionHook extensionHook) {
super.hook(extensionHook);
this.registerScriptType(
new ScriptType(
TYPE_PROXY,
"script.type.proxy",
createIcon("/resource/icon/16/script-proxy.png"),
true));
this.registerScriptType(
new ScriptType(
TYPE_STANDALONE,
"script.type.standalone",
createIcon("/resource/icon/16/script-standalone.png"),
false,
new String[] {ScriptType.CAPABILITY_APPEND}));
this.registerScriptType(
new ScriptType(
TYPE_TARGETED,
"script.type.targeted",
createIcon("/resource/icon/16/script-targeted.png"),
false));
this.registerScriptType(
new ScriptType(
TYPE_HTTP_SENDER,
"script.type.httpsender",
createIcon("/resource/icon/16/script-httpsender.png"),
true));
extensionHook.addSessionListener(new ClearScriptVarsOnSessionChange());
extensionHook.addProxyListener(this.getProxyListener());
extensionHook.addHttpSenderListener(getHttpSenderScriptListener());
extensionHook.addOptionsParamSet(getScriptParam());
extensionHook.addCommandLine(getCommandLineArguments());
if (hasView()) {
extensionHook.getHookView().addOptionPanel(getOptionsScriptPanel());
} else {
// No GUI so add stdout as a writer
this.addWriter(new PrintWriter(System.out));
}
extensionHook.addApiImplementor(new ScriptAPI(this));
}
/**
* Creates an {@code ImageIcon} with the given resource path, if in view mode.
*
* @param resourcePath the resource path of the icon, must not be {@code null}.
* @return the icon, or {@code null} if not in view mode.
*/
private ImageIcon createIcon(String resourcePath) {
if (getView() == null) {
return null;
}
return new ImageIcon(ExtensionScript.class.getResource(resourcePath));
}
private OptionsScriptPanel getOptionsScriptPanel() {
if (optionsScriptPanel == null) {
optionsScriptPanel = new OptionsScriptPanel(this);
}
return optionsScriptPanel;
}
private ProxyListenerScript getProxyListener() {
if (this.proxyListener == null) {
this.proxyListener = new ProxyListenerScript(this);
}
return this.proxyListener;
}
private HttpSenderScriptListener getHttpSenderScriptListener() {
if (this.httpSenderScriptListener == null) {
this.httpSenderScriptListener = new HttpSenderScriptListener(this);
}
return this.httpSenderScriptListener;
}
public List<String> getScriptingEngines() {
List<String> engineNames = new ArrayList<>();
List<ScriptEngineFactory> engines = mgr.getEngineFactories();
for (ScriptEngineFactory engine : engines) {
engineNames.add(engine.getLanguageName() + LANG_ENGINE_SEP + engine.getEngineName());
}
for (ScriptEngineWrapper sew : this.engineWrappers) {
if (sew.isVisible() && !engines.contains(sew.getFactory())) {
engineNames.add(sew.getLanguageName() + LANG_ENGINE_SEP + sew.getEngineName());
}
}
Collections.sort(engineNames);
return engineNames;
}
/**
* Registers a new script engine wrapper.
*
* <p>The templates of the wrapped script engine are loaded, if any.
*
* <p>The engine is set to existing scripts targeting the given engine.
*
* @param wrapper the script engine wrapper that will be added, must not be {@code null}
* @see #removeScriptEngineWrapper(ScriptEngineWrapper)
* @see ScriptWrapper#setEngine(ScriptEngineWrapper)
*/
public void registerScriptEngineWrapper(ScriptEngineWrapper wrapper) {
logger.debug(
"registerEngineWrapper "
+ wrapper.getLanguageName()
+ " : "
+ wrapper.getEngineName());
this.engineWrappers.add(wrapper);
setScriptEngineWrapper(getTreeModel().getScriptsNode(), wrapper, wrapper);
setScriptEngineWrapper(getTreeModel().getTemplatesNode(), wrapper, wrapper);
// Templates for this engine might not have been loaded
this.loadTemplates(wrapper);
synchronized (trackedDirs) {
String engineName =
wrapper.getLanguageName() + LANG_ENGINE_SEP + wrapper.getEngineName();
for (File dir : trackedDirs) {
for (ScriptType type : this.getScriptTypes()) {
addScriptsFromDir(dir, type, engineName);
}
}
}
if (scriptUI != null) {
try {
scriptUI.engineAdded(wrapper);
} catch (Exception e) {
logger.error("An error occurred while notifying ScriptUI:", e);
}
}
}
/**
* Sets the given {@code newEngineWrapper} to all children of {@code baseNode} that targets the
* given {@code engineWrapper}.
*
* @param baseNode the node whose child nodes will have the engine set, must not be {@code null}
* @param engineWrapper the script engine of the targeting scripts, must not be {@code null}
* @param newEngineWrapper the script engine that will be set to the targeting scripts
* @see ScriptWrapper#setEngine(ScriptEngineWrapper)
*/
private void setScriptEngineWrapper(
ScriptNode baseNode,
ScriptEngineWrapper engineWrapper,
ScriptEngineWrapper newEngineWrapper) {
for (@SuppressWarnings("unchecked")
Enumeration<TreeNode> e = baseNode.depthFirstEnumeration();
e.hasMoreElements(); ) {
ScriptNode node = (ScriptNode) e.nextElement();
if (node.getUserObject() != null && (node.getUserObject() instanceof ScriptWrapper)) {
ScriptWrapper scriptWrapper = (ScriptWrapper) node.getUserObject();
if (hasSameScriptEngine(scriptWrapper, engineWrapper)) {
scriptWrapper.setEngine(newEngineWrapper);
if (newEngineWrapper == null) {
if (scriptWrapper.isEnabled()) {
setEnabled(scriptWrapper, false);
scriptWrapper.setPreviouslyEnabled(true);
}
} else if (scriptWrapper.isPreviouslyEnabled()) {
setEnabled(scriptWrapper, true);
scriptWrapper.setPreviouslyEnabled(false);
}
}
}
}
}
/**
* Tells whether or not the given {@code scriptWrapper} has the given {@code engineWrapper}.
*
* <p>If the given {@code scriptWrapper} has an engine set it's checked by reference (operator
* {@code ==}), otherwise it's used the engine names.
*
* @param scriptWrapper the script wrapper that will be checked
* @param engineWrapper the engine that will be checked against the engine of the script
* @return {@code true} if the given script has the given engine, {@code false} otherwise.
* @since 2.4.0
* @see #isSameScriptEngine(String, String, String)
*/
public static boolean hasSameScriptEngine(
ScriptWrapper scriptWrapper, ScriptEngineWrapper engineWrapper) {
if (scriptWrapper.getEngine() != null) {
return scriptWrapper.getEngine() == engineWrapper;
}
return isSameScriptEngine(
scriptWrapper.getEngineName(),
engineWrapper.getEngineName(),
engineWrapper.getLanguageName());
}
/**
* Tells whether or not the given {@code name} matches the given {@code engineName} and {@code
* engineLanguage}.
*
* @param name the name that will be checked against the given {@code engineName} and {@code
* engineLanguage}.
* @param engineName the name of the script engine.
* @param engineLanguage the language of the script engine.
* @return {@code true} if the {@code name} matches the given engine's name and language, {@code
* false} otherwise.
* @since 2.4.0
* @see #hasSameScriptEngine(ScriptWrapper, ScriptEngineWrapper)
*/
public static boolean isSameScriptEngine(
String name, String engineName, String engineLanguage) {
if (name == null) {
return false;
}
// In the configs we just use the engine name, in the UI we use the language name as well
if (name.indexOf(LANG_ENGINE_SEP) > 0) {
if (name.equals(engineLanguage + LANG_ENGINE_SEP + engineName)) {
return true;
}
return false;
}
return name.equals(engineName);
}
/**
* Removes the given script engine wrapper.
*
* <p>The user's templates and scripts associated with the given engine are not removed but its
* engine is set to {@code null}. Default templates are removed.
*
* <p>The call to this method has no effect if the given type is not registered.
*
* @param wrapper the script engine wrapper that will be removed, must not be {@code null}
* @since 2.4.0
* @see #registerScriptEngineWrapper(ScriptEngineWrapper)
* @see ScriptWrapper#setEngine(ScriptEngineWrapper)
*/
public void removeScriptEngineWrapper(ScriptEngineWrapper wrapper) {
logger.debug(
"Removing script engine: "
+ wrapper.getLanguageName()
+ " : "
+ wrapper.getEngineName());
if (this.engineWrappers.remove(wrapper)) {
if (scriptUI != null) {
try {
scriptUI.engineRemoved(wrapper);
} catch (Exception e) {
logger.error("An error occurred while notifying ScriptUI:", e);
}
}
setScriptEngineWrapper(getTreeModel().getScriptsNode(), wrapper, null);
processTemplatesOfRemovedEngine(getTreeModel().getTemplatesNode(), wrapper);
}
}
private void processTemplatesOfRemovedEngine(
ScriptNode baseNode, ScriptEngineWrapper engineWrapper) {
@SuppressWarnings("unchecked")
List<TreeNode> templateNodes = Collections.list(baseNode.depthFirstEnumeration());
for (TreeNode tpNode : templateNodes) {
ScriptNode node = (ScriptNode) tpNode;
if (node.getUserObject() != null && (node.getUserObject() instanceof ScriptWrapper)) {
ScriptWrapper scriptWrapper = (ScriptWrapper) node.getUserObject();
if (hasSameScriptEngine(scriptWrapper, engineWrapper)) {
if (engineWrapper.isDefaultTemplate(scriptWrapper)) {
removeTemplate(scriptWrapper);
} else {
scriptWrapper.setEngine(null);
this.getTreeModel().nodeStructureChanged(scriptWrapper);
}
}
}
}
}
public ScriptEngineWrapper getEngineWrapper(String name) {
ScriptEngineWrapper sew = getEngineWrapperImpl(name);
if (sew == null) {
throw new InvalidParameterException("No such engine: " + name);
}
return sew;
}
/**
* Gets the script engine with the given name.
*
* @param name the name of the script engine.
* @return the engine, or {@code null} if not available.
*/
private ScriptEngineWrapper getEngineWrapperImpl(String name) {
for (ScriptEngineWrapper sew : this.engineWrappers) {
if (isSameScriptEngine(name, sew.getEngineName(), sew.getLanguageName())) {
return sew;
}
}
// Not one we know of, create a default wrapper
List<ScriptEngineFactory> engines = mgr.getEngineFactories();
ScriptEngine engine = null;
for (ScriptEngineFactory e : engines) {
if (isSameScriptEngine(name, e.getEngineName(), e.getLanguageName())) {
engine = e.getScriptEngine();
break;
}
}
if (engine != null) {
DefaultEngineWrapper dew = new DefaultEngineWrapper(engine.getFactory());
this.registerScriptEngineWrapper(dew);
return dew;
}
return null;
}
public String getEngineNameForExtension(String ext) {
ScriptEngine engine = mgr.getEngineByExtension(ext);
if (engine != null) {
return engine.getFactory().getLanguageName()
+ LANG_ENGINE_SEP
+ engine.getFactory().getEngineName();
}
for (ScriptEngineWrapper sew : this.engineWrappers) {
if (sew.getExtensions() != null) {
for (String extn : sew.getExtensions()) {
if (ext.equals(extn)) {
return sew.getLanguageName() + LANG_ENGINE_SEP + sew.getEngineName();
}
}
}
}
return null;
}
protected ScriptParam getScriptParam() {
if (this.scriptParam == null) {
this.scriptParam = new ScriptParam();
}
return this.scriptParam;
}
public ScriptTreeModel getTreeModel() {
if (this.treeModel == null) {
this.treeModel = new ScriptTreeModel();
}
return this.treeModel;
}
/**
* Registers a new type of script.
*
* <p>The script is added to the tree of scripts and its scripts/templates loaded, if any.
*
* @param type the new type of script
* @throws InvalidParameterException if a script type with same name is already registered
* @see #removeScriptType(ScriptType)
*/
public void registerScriptType(ScriptType type) {
if (typeMap.containsKey(type.getName())) {
throw new InvalidParameterException("ScriptType already registered: " + type.getName());
}
this.typeMap.put(type.getName(), type);
this.getTreeModel().addType(type);
if (shouldLoadScriptsOnScriptTypeRegistration) {
addScripts(type);
loadScriptTemplates(type);
}
synchronized (trackedDirs) {
for (File dir : trackedDirs) {
addScriptsFromDir(dir, type, null);
}
}
}
/**
* Adds the (saved) scripts of the given script type.
*
* @param type the type of the script.
* @see ScriptParam#getScripts()
*/
private void addScripts(ScriptType type) {
for (ScriptWrapper script : this.getScriptParam().getScripts()) {
if (!type.getName().equals(script.getTypeName())) {
continue;
}
try {
loadScript(script);
addScript(script, false, false);
} catch (MalformedInputException e) {
logger.warn(
"Failed to add script \""
+ script.getName()
+ "\", contains invalid character sequence (UTF-8).");
} catch (InvalidParameterException | IOException e) {
logger.error("Failed to add script: " + script.getName(), e);
}
}
}
/**
* Removes the given script type.
*
* <p>The templates and scripts associated with the given type are also removed, if any.
*
* <p>The call to this method has no effect if the given type is not registered.
*
* @param type the script type that will be removed
* @since 2.4.0
* @see #registerScriptType(ScriptType)
* @deprecated (2.9.0) Use {@link #removeScriptType(ScriptType)} instead.
*/
@Deprecated
public void removeScripType(ScriptType type) {
removeScriptType(type);
}
/**
* Removes the given script type.
*
* <p>The templates and scripts associated with the given type are also removed, if any.
*
* <p>The call to this method has no effect if the given type is not registered.
*
* @param type the script type that will be removed
* @since 2.9.0
* @see #registerScriptType(ScriptType)
*/
public void removeScriptType(ScriptType type) {
ScriptType scriptType = typeMap.remove(type.getName());
if (scriptType != null) {
getTreeModel().removeType(scriptType);
}
}
public ScriptType getScriptType(String name) {
return this.typeMap.get(name);
}
public Collection<ScriptType> getScriptTypes() {
return typeMap.values();
}
@Override
public String getAuthor() {
return Constant.ZAP_TEAM;
}
@Override
public String getDescription() {
return Constant.messages.getString("script.desc");
}
private void refreshScript(ScriptWrapper script) {
for (ScriptEventListener listener : this.listeners) {
try {
listener.refreshScript(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
private void reloadIfChangedOnDisk(ScriptWrapper script) {
if (script.hasChangedOnDisk() && !script.isChanged()) {
try {
logger.debug(
"Reloading script as its been changed on disk "
+ script.getFile().getAbsolutePath());
script.reloadScript();
} catch (IOException e) {
logger.error("Failed to reload script " + script.getFile().getAbsolutePath(), e);
}
}
}
public ScriptWrapper getScript(String name) {
ScriptWrapper script = getScriptImpl(name);
if (script != null) {
refreshScript(script);
reloadIfChangedOnDisk(script);
}
return script;
}
/**
* Gets the script with the given name.
*
* <p>Internal method that does not perform any actions on the returned script.
*
* @param name the name of the script.
* @return the script, or {@code null} if it doesn't exist.
* @see #getScript(String)
*/
private ScriptWrapper getScriptImpl(String name) {
return this.getTreeModel().getScript(name);
}
public ScriptNode addScript(ScriptWrapper script) {
return this.addScript(script, true);
}
public ScriptNode addScript(ScriptWrapper script, boolean display) {
return addScript(script, display, true);
}
private ScriptNode addScript(ScriptWrapper script, boolean display, boolean save) {
if (script == null) {
return null;
}
setEngine(script);
ScriptNode node = this.getTreeModel().addScript(script);
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptAdded(script, display);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
if (save && script.isLoadOnStart() && script.getFile() != null) {
this.getScriptParam().addScript(script);
this.getScriptParam().saveScripts();
}
return node;
}
private void logScriptEventListenerException(
ScriptEventListener listener, ScriptWrapper script, Exception e) {
String classname = listener.getClass().getCanonicalName();
String scriptName = script.getName();
logger.error(
"Error while notifying '"
+ classname
+ "' with script '"
+ scriptName
+ "', cause: "
+ e.getMessage(),
e);
}
public void saveScript(ScriptWrapper script) throws IOException {
refreshScript(script);
script.saveScript();
this.setChanged(script, false);
// The removal is required for script that use wrappers, like Zest
this.getScriptParam().removeScript(script);
this.getScriptParam().addScript(script);
this.getScriptParam().saveScripts();
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptSaved(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
public void removeScript(ScriptWrapper script) {
script.setLoadOnStart(false);
this.getScriptParam().removeScript(script);
this.getScriptParam().saveScripts();
this.getTreeModel().removeScript(script);
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptRemoved(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
public void removeTemplate(ScriptWrapper template) {
this.getTreeModel().removeTemplate(template);
for (ScriptEventListener listener : this.listeners) {
try {
listener.templateRemoved(template);
} catch (Exception e) {
logScriptEventListenerException(listener, template, e);
}
}
}
public ScriptNode addTemplate(ScriptWrapper template) {
return this.addTemplate(template, true);
}
public ScriptNode addTemplate(ScriptWrapper template, boolean display) {
if (template == null) {
return null;
}
ScriptNode node = this.getTreeModel().addTemplate(template);
for (ScriptEventListener listener : this.listeners) {
try {
listener.templateAdded(template, display);
} catch (Exception e) {
logScriptEventListenerException(listener, template, e);
}
}
return node;
}
@Override
public void postInit() {
ScriptEngineWrapper ecmaScriptEngineWrapper = null;
final List<String[]> scriptsNotAdded = new ArrayList<>(1);
for (ScriptWrapper script : this.getScriptParam().getScripts()) {
// Change scripts using Rhino (Java 7) script engine to Nashorn (Java 8+).
if (script.getEngine() == null && isRhinoScriptEngine(script.getEngineName())) {
if (ecmaScriptEngineWrapper == null) {
ecmaScriptEngineWrapper = getEcmaScriptEngineWrapper();
}
if (ecmaScriptEngineWrapper != null) {
logger.info(
"Changing ["
+ script.getName()
+ "] (ECMAScript) script engine from ["
+ script.getEngineName()
+ "] to ["
+ ecmaScriptEngineWrapper.getEngineName()
+ "].");
script.setEngine(ecmaScriptEngineWrapper);
}
}
try {
this.loadScript(script);
if (script.getType() != null) {
this.addScript(script, false, false);
} else {
logger.warn(
"Failed to add script \""
+ script.getName()
+ "\", provided script type \""
+ script.getTypeName()
+ "\" not found, available: "
+ getScriptTypesNames());
scriptsNotAdded.add(
new String[] {
script.getName(),
script.getEngineName(),
Constant.messages.getString(
"script.info.scriptsNotAdded.error.missingType",
script.getTypeName())
});
}
} catch (MalformedInputException e) {
logger.warn(
"Failed to add script \""
+ script.getName()
+ "\", contains invalid character sequence (UTF-8).");
scriptsNotAdded.add(
new String[] {
script.getName(),
script.getEngineName(),
Constant.messages.getString(
"script.info.scriptsNotAdded.error.invalidChars")
});
} catch (InvalidParameterException | IOException e) {
logger.error(e.getMessage(), e);
scriptsNotAdded.add(
new String[] {
script.getName(),
script.getEngineName(),
Constant.messages.getString("script.info.scriptsNotAdded.error.other")
});
}
}
informScriptsNotAdded(scriptsNotAdded);
this.loadTemplates();
for (File dir : this.getScriptParam().getScriptDirs()) {
// Load the scripts from subdirectories of each directory configured
int numAdded = addScriptsFromDir(dir);
logger.debug("Added " + numAdded + " scripts from dir: " + dir.getAbsolutePath());
}
shouldLoadScriptsOnScriptTypeRegistration = true;
Path defaultScriptsDir = Paths.get(Constant.getZapHome(), SCRIPTS_DIR, SCRIPTS_DIR);
for (ScriptType scriptType : typeMap.values()) {
Path scriptTypeDir = defaultScriptsDir.resolve(scriptType.getName());
if (Files.notExists(scriptTypeDir)) {
try {
Files.createDirectories(scriptTypeDir);
} catch (IOException e) {
logger.warn(
"Failed to create directory for script type: " + scriptType.getName(),
e);
}
}
}
}
private static boolean isRhinoScriptEngine(String engineName) {
return "Mozilla Rhino".equals(engineName) || "Rhino".equals(engineName);
}
private ScriptEngineWrapper getEcmaScriptEngineWrapper() {
for (ScriptEngineWrapper sew : this.engineWrappers) {
if ("ECMAScript".equals(sew.getLanguageName())) {
return sew;
}
}
return null;
}
private List<String> getScriptTypesNames() {
return getScriptTypes().stream()
.collect(ArrayList::new, (c, e) -> c.add(e.getName()), ArrayList::addAll);
}
private void informScriptsNotAdded(final List<String[]> scriptsNotAdded) {
if (!hasView() || scriptsNotAdded.isEmpty()) {
return;
}
final List<Object> optionPaneContents = new ArrayList<>(2);
optionPaneContents.add(Constant.messages.getString("script.info.scriptsNotAdded.message"));
JXTable table =
new JXTable(
new AbstractTableModel() {
private static final long serialVersionUID = -457689656746030560L;
@Override
public String getColumnName(int column) {
if (column == 0) {
return Constant.messages.getString(
"script.info.scriptsNotAdded.table.column.scriptName");
} else if (column == 1) {
return Constant.messages.getString(
"script.info.scriptsNotAdded.table.column.scriptEngine");
}
return Constant.messages.getString(
"script.info.scriptsNotAdded.table.column.errorCause");
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return scriptsNotAdded.get(rowIndex)[columnIndex];
}
@Override
public int getRowCount() {
return scriptsNotAdded.size();
}
@Override
public int getColumnCount() {
return 3;
}
});
table.setColumnControlVisible(true);
table.setVisibleRowCount(Math.min(scriptsNotAdded.size() + 1, 5));
table.packAll();
optionPaneContents.add(new JScrollPane(table));
EventQueue.invokeLater(
new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(
getView().getMainFrame(),
optionPaneContents.toArray(),
Constant.PROGRAM_NAME,
JOptionPane.INFORMATION_MESSAGE);
}
});
}
/**
* Adds the scripts from the given directory and starts tracking it.
*
* <p>The directory will be tracked to add or remove its scripts when a new script engine/type
* is added or removed.
*
* <p>The scripts are expected to be under directories of the corresponding script type, for
* example:
*
* <pre>{@code
* (dir specified)
* ├── active
* │ ├── gof_lite.js
* │ ├── TestInsecureHTTPVerbs.py
* │ └── User defined attacks.js
* ├── extender
* │ └── HTTP Message Logger.js
* ├── httpfuzzerprocessor
* │ ├── add_msgs_sites_tree.js
* │ ├── http_status_code_filter.py
* │ └── showDifferences.js
* ├── httpsender
* │ ├── add_header_request.py
* │ └── Capture and Replace Anti CSRF Token.js
* └── variant
* └── JsonStrings.js
* }</pre>
*
* where {@code active}, {@code extender}, {@code httpfuzzerprocessor}, {@code httpsender}, and
* {@code variant} are the script types.
*
* @param dir the directory from where to add the scripts.
* @return the number of scripts added.
* @since 2.4.1
* @see #removeScriptsFromDir(File)
*/
public int addScriptsFromDir(File dir) {
logger.debug("Adding scripts from dir: " + dir.getAbsolutePath());
trackedDirs.add(dir);
int addedScripts = 0;
for (ScriptType type : this.getScriptTypes()) {
addedScripts += addScriptsFromDir(dir, type, null);
}
return addedScripts;
}
/**
* Adds the scripts from the given directory of the given script type and, optionally, for the
* engine with the given name.
*
* @param dir the directory from where to add the scripts.
* @param type the script type, must not be {@code null}.
* @param targetEngineName the engine that the scripts must be of, {@code null} for all engines.
* @return the number of scripts added.
*/
private int addScriptsFromDir(File dir, ScriptType type, String targetEngineName) {
int addedScripts = 0;
File typeDir = new File(dir, type.getName());
if (typeDir.exists()) {
for (File f : typeDir.listFiles()) {
String ext = f.getName().substring(f.getName().lastIndexOf(".") + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName != null
&& (targetEngineName == null || engineName.equals(targetEngineName))) {
try {
if (f.canWrite()) {
String scriptName = this.getUniqueScriptName(f.getName(), ext);
logger.debug("Loading script " + scriptName);
ScriptWrapper sw =
new ScriptWrapper(
scriptName,
"",
this.getEngineWrapper(engineName),
type,
false,
f);
this.loadScript(sw);
this.addScript(sw, false);
} else {
// Cant write so add as a template
String scriptName = this.getUniqueTemplateName(f.getName(), ext);
logger.debug("Loading script " + scriptName);
ScriptWrapper sw =
new ScriptWrapper(
scriptName,
"",
this.getEngineWrapper(engineName),
type,
false,
f);
this.loadScript(sw);
this.addTemplate(sw, false);
}
addedScripts++;
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
} else {
logger.debug("Ignoring " + f.getName());
}
}
}
return addedScripts;
}
/**
* Removes the scripts added from the given directory and stops tracking it.
*
* <p>The number of scripts removed might be different than the number of scripts initially
* added, as a script engine or type might have been added or removed in the meantime.
*
* @param dir the directory previously added.
* @return the number of scripts removed.
* @since 2.4.1
* @see #addScriptsFromDir(File)
*/
public int removeScriptsFromDir(File dir) {
logger.debug("Removing scripts from dir: " + dir.getAbsolutePath());
trackedDirs.remove(dir);
int removedScripts = 0;
for (ScriptType type : this.getScriptTypes()) {
File locDir = new File(dir, type.getName());
if (locDir.exists()) {
// Loop through all of the known scripts and templates
// removing any from this directory
for (ScriptWrapper sw : this.getScripts(type)) {
if (isSavedInDir(sw, locDir)) {
this.removeScript(sw);
removedScripts++;
}
}
for (ScriptWrapper sw : this.getTemplates(type)) {
if (isSavedInDir(sw, locDir)) {
this.removeTemplate(sw);
removedScripts++;
}
}
}
}
return removedScripts;
}
/**
* Tells whether or not the given script is saved in the given directory.
*
* @param scriptWrapper the script to check.
* @param directory the directory where to check.
* @return {@code true} if the script is saved in the given directory, {@code false} otherwise.
*/
private static boolean isSavedInDir(ScriptWrapper scriptWrapper, File directory) {
File file = scriptWrapper.getFile();
if (file == null) {
return false;
}
return file.getParentFile().equals(directory);
}
/**
* Gets the numbers of scripts for the given directory for the currently registered script
* engines and types.
*
* @param dir the directory to check.
* @return the number of scripts.
* @since 2.4.1
*/
public int getScriptCount(File dir) {
int scripts = 0;
for (ScriptType type : this.getScriptTypes()) {
File locDir = new File(dir, type.getName());
if (locDir.exists()) {
for (File f : locDir.listFiles()) {
String ext = f.getName().substring(f.getName().lastIndexOf(".") + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName != null) {
scripts++;
}
}
}
}
return scripts;
}
/*
* Returns a unique name for the given script name
*/
private String getUniqueScriptName(String name, String ext) {
if (this.getScriptImpl(name) == null) {
// Its unique
return name;
}
// Its not unique, add a suitable index...
String stub = name.substring(0, name.length() - ext.length() - 1);
int index = 1;
do {
index++;
name = stub + "(" + index + ")." + ext;
} while (this.getScriptImpl(name) != null);
return name;
}
/*
* Returns a unique name for the given template name
*/
private String getUniqueTemplateName(String name, String ext) {
if (this.getTreeModel().getTemplate(name) == null) {
// Its unique
return name;
}
// Its not unique, add a suitable index...
String stub = name.substring(0, name.length() - ext.length() - 1);
int index = 1;
do {
index++;
name = stub + "(" + index + ")." + ext;
} while (this.getTreeModel().getTemplate(name) != null);
return name;
}
private void loadTemplates() {
this.loadTemplates(null);
}
private void loadTemplates(ScriptEngineWrapper engine) {
for (ScriptType type : this.getScriptTypes()) {
loadScriptTemplates(type, engine);
}
}
/**
* Loads script templates of the given {@code type}, for all script engines.
*
* @param type the script type whose templates will be loaded
* @since 2.4.0
* @see #loadScriptTemplates(ScriptType, ScriptEngineWrapper)
*/
private void loadScriptTemplates(ScriptType type) {
loadScriptTemplates(type, null);
}
/**
* Loads script templates of the given {@code type} for the given {@code engine}.
*
* @param type the script type whose templates will be loaded
* @param engine the script engine whose templates will be loaded for the given {@code script}
* @since 2.4.0
* @see #loadScriptTemplates(ScriptType)
*/
private void loadScriptTemplates(ScriptType type, ScriptEngineWrapper engine) {
File locDir =
new File(
Constant.getZapHome()
+ File.separator
+ TEMPLATES_DIR
+ File.separator
+ type.getName());
File stdDir =
new File(
Constant.getZapInstall()
+ File.separator
+ TEMPLATES_DIR
+ File.separator
+ type.getName());
// Load local files first, as these override any one included in the release
if (locDir.exists()) {
for (File f : locDir.listFiles()) {
loadTemplate(f, type, engine, false);
}
}
if (stdDir.exists()) {
for (File f : stdDir.listFiles()) {
// Dont log errors on duplicates - 'local' templates should take precedence
loadTemplate(f, type, engine, true);
}
}
}
private void loadTemplate(
File f, ScriptType type, ScriptEngineWrapper engine, boolean ignoreDuplicates) {
if (f.getName().indexOf(".") > 0) {
if (this.getTreeModel().getTemplate(f.getName()) == null) {
String ext = f.getName().substring(f.getName().lastIndexOf(".") + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName != null
&& (engine == null || engine.getExtensions().contains(ext))) {
try {
ScriptWrapper template =
new ScriptWrapper(
f.getName(),
"",
this.getEngineWrapper(engineName),
type,
false,
f);
this.loadScript(template);
this.addTemplate(template);
} catch (InvalidParameterException e) {
if (!ignoreDuplicates) {
logger.error(e.getMessage(), e);
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
}
/**
* Loads the script from the file, using {@link #DEFAULT_CHARSET}.
*
* <p>If the file contains invalid byte sequences (for {@code DEFAULT_CHARSET}) it will be
* loaded again using the {@link Charset#defaultCharset() (JVM) default charset}, to load
* scripts saved with older ZAP versions (which relied on default charset).
*
* @param script the ScriptWrapper to be loaded (read script from file).
* @return the {@code ScriptWrapper} with the actual script read from the file.
* @throws IOException if an error occurred while reading the script from the file.
* @throws IllegalArgumentException if the {@code script} is {@code null}.
* @see #loadScript(ScriptWrapper, Charset)
*/
public ScriptWrapper loadScript(ScriptWrapper script) throws IOException {
try {
return loadScript(script, DEFAULT_CHARSET);
} catch (MalformedInputException e) {
if (Charset.defaultCharset() == DEFAULT_CHARSET) {
// No point trying the (JVM) default charset if it's the same...
throw e;
}
if (logger.isDebugEnabled()) {
logger.debug(
"Failed to load script ["
+ script.getName()
+ "] using ["
+ DEFAULT_CHARSET
+ "], falling back to ["
+ Charset.defaultCharset()
+ "].",
e);
}
return loadScript(script, Charset.defaultCharset());
}
}
/**
* Loads the script from the file, using the given charset.
*
* @param script the ScriptWrapper to be loaded (read script from file).
* @param charset the charset to use when reading the script from the file.
* @return the {@code ScriptWrapper} with the actual script read from the file.
* @throws IOException if an error occurred while reading the script from the file.
* @throws IllegalArgumentException if the {@code script} or the {@code charset} is {@code
* null}.
* @since 2.7.0
* @see #loadScript(ScriptWrapper)
*/
public ScriptWrapper loadScript(ScriptWrapper script, Charset charset) throws IOException {
if (script == null) {
throw new IllegalArgumentException("Parameter script must not be null.");
}
if (charset == null) {
throw new IllegalArgumentException("Parameter charset must not be null.");
}
script.loadScript(charset);
if (script.getType() == null) {
// This happens when scripts are loaded from the configs as the types
// may well not have been registered at that stage
script.setType(this.getScriptType(script.getTypeName()));
}
setEngine(script);
return script;
}
/**
* Sets the engine script to the given script, if not already set.
*
* <p>Scripts loaded from the configuration file might not have the engine set when used.
*
* <p>Does nothing if the engine script is not available.
*
* @param script the script to set the engine.
*/
private void setEngine(ScriptWrapper script) {
if (script.getEngine() != null) {
return;
}
ScriptEngineWrapper sew = getEngineWrapperImpl(script.getEngineName());
if (sew == null) {
return;
}
script.setEngine(sew);
}
public List<ScriptWrapper> getScripts(String type) {
return this.getScripts(this.getScriptType(type));
}
public List<ScriptWrapper> getScripts(ScriptType type) {
List<ScriptWrapper> scripts = new ArrayList<>();
if (type == null) {
return scripts;
}
for (ScriptNode node : this.getTreeModel().getNodes(type.getName())) {
ScriptWrapper script = (ScriptWrapper) node.getUserObject();
refreshScript(script);
scripts.add((ScriptWrapper) node.getUserObject());
}
return scripts;
}
public List<ScriptWrapper> getTemplates(ScriptType type) {
List<ScriptWrapper> scripts = new ArrayList<>();
if (type == null) {
return scripts;
}
for (ScriptWrapper script : this.getTreeModel().getTemplates(type)) {
scripts.add(script);
}
return scripts;
}
/*
* This extension supports any number of writers to be registered which all get written to for
* ever script. It also supports script specific writers.
*/
private Writer getWriters(ScriptWrapper script) {
Writer delegatee = this.writers;
Writer writer = script.getWriter();
if (writer != null) {
// Use the script specific writer in addition to the std one
MultipleWriters scriptWriters = new MultipleWriters();
scriptWriters.addWriter(writer);
scriptWriters.addWriter(writers);
delegatee = scriptWriters;
}
return new ScriptWriter(script, delegatee, outputListeners);
}
/**
* Invokes the given {@code script}, synchronously, handling any {@code Exception} thrown during
* the invocation.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons. If this behaviour is not
* desired call the method {@code invokeScriptWithOutAddOnLoader} instead.
*
* @param script the script that will be invoked
* @return an {@code Invocable} for the {@code script}, or {@code null} if none.
* @throws ScriptException if the engine of the given {@code script} was not found.
* @see #invokeScriptWithOutAddOnLoader(ScriptWrapper)
* @see Invocable
*/
public Invocable invokeScript(ScriptWrapper script) throws ScriptException {
logger.debug("invokeScript " + script.getName());
preInvokeScript(script);
ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(ExtensionFactory.getAddOnLoader());
try {
return invokeScriptImpl(script);
} finally {
Thread.currentThread().setContextClassLoader(previousContextClassLoader);
}
}
/**
* Notifies the {@code ScriptEventListener}s that the given {@code script} should be refreshed,
* resets the error and output states of the given {@code script} and notifies {@code
* ScriptEventListener}s of the pre-invocation.
*
* <p>If the script does not have an engine it will be set one (if found).
*
* @param script the script that will be invoked after the call to this method
* @throws ScriptException if the engine of the given {@code script} was not found.
* @see ScriptEventListener#refreshScript(ScriptWrapper)
* @see ScriptEventListener#preInvoke(ScriptWrapper)
*/
private void preInvokeScript(ScriptWrapper script) throws ScriptException {
setEngine(script);
if (script.getEngine() == null) {
throw new ScriptException("Failed to find script engine: " + script.getEngineName());
}
refreshScript(script);
script.setLastErrorDetails("");
script.setLastException(null);
script.setLastOutput("");
for (ScriptEventListener listener : this.listeners) {
try {
listener.preInvoke(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
/**
* Invokes the given {@code script}, handling any {@code Exception} thrown during the
* invocation.
*
* <p>Script's (or default) {@code Writer} is set to the {@code ScriptContext} of the {@code
* ScriptEngine} before the invocation.
*
* @param script the script that will be invoked
* @return an {@code Invocable} for the {@code script}, or {@code null} if none.
* @see #getWriters(ScriptWrapper)
* @see Invocable
*/
private Invocable invokeScriptImpl(ScriptWrapper script) {
ScriptEngine se = script.getEngine().getEngine();
Writer writer = getWriters(script);
se.getContext().setWriter(writer);
// Set the script name as a context attribute - this is used for script level variables
se.getContext().setAttribute(SCRIPT_NAME_ATT, script.getName(), ScriptContext.ENGINE_SCOPE);
se.put("control", Control.getSingleton());
se.put("model", getModel());
se.put("view", getView());
reloadIfChangedOnDisk(script);
recordScriptCalledStats(script);
try {
se.eval(script.getContents());
} catch (Exception e) {
handleScriptException(script, writer, e);
} catch (NoClassDefFoundError | ExceptionInInitializerError e) {
if (e.getCause() instanceof Exception) {
handleScriptException(script, writer, (Exception) e.getCause());
} else {
handleUnspecifiedScriptError(script, writer, e.getMessage());
}
}
if (se instanceof Invocable) {
return (Invocable) se;
}
return null;
}
/**
* Invokes the given {@code script}, synchronously, handling any {@code Exception} thrown during
* the invocation.
*
* @param script the script that will be invoked/evaluated
* @return an {@code Invocable} for the {@code script}, or {@code null} if none.
* @throws ScriptException if the engine of the given {@code script} was not found.
* @see #invokeScript(ScriptWrapper)
* @see Invocable
*/
public Invocable invokeScriptWithOutAddOnLoader(ScriptWrapper script) throws ScriptException {
logger.debug("invokeScriptWithOutAddOnLoader " + script.getName());
preInvokeScript(script);
return invokeScriptImpl(script);
}
/**
* Handles exceptions thrown by scripts.
*
* <p>The given {@code exception} (if of type {@code ScriptException} the cause will be used
* instead) will be written to the writer(s) associated with the given {@code script}, moreover
* the script will be disabled and flagged that has an error.
*
* @param script the script that resulted in an exception, must not be {@code null}
* @param exception the exception thrown, must not be {@code null}
* @since 2.5.0
* @see #setEnabled(ScriptWrapper, boolean)
* @see #setError(ScriptWrapper, Exception)
* @see #handleFailedScriptInterface(ScriptWrapper, String)
* @see #handleScriptError(ScriptWrapper, String)
* @see ScriptException
*/
public void handleScriptException(ScriptWrapper script, Exception exception) {
handleScriptException(script, getWriters(script), exception);
}
/**
* Handles exceptions thrown by scripts.
*
* <p>The given {@code exception} (if of type {@code ScriptException} the cause will be used
* instead) will be written to the given {@code writer} and the given {@code script} will be
* disabled and flagged that has an error.
*
* @param script the script that resulted in an exception, must not be {@code null}
* @param writer the writer associated with the script, must not be {@code null}
* @param exception the exception thrown , must not be {@code null}
* @see #setError(ScriptWrapper, Exception)
* @see #setEnabled(ScriptWrapper, boolean)
* @see ScriptException
*/
private void handleScriptException(ScriptWrapper script, Writer writer, Exception exception) {
recordScriptFailedStats(script);
Exception cause = exception;
if (cause instanceof ScriptException && cause.getCause() instanceof Exception) {
// Dereference one level
cause = (Exception) cause.getCause();
}
try {
writer.append(cause.toString());
} catch (IOException ignore) {
logger.error(cause.getMessage(), cause);
}
this.setError(script, cause);
this.setEnabled(script, false);
}
/**
* Handles errors caused by scripts.
*
* <p>The given {@code error} will be written to the writer(s) associated with the given {@code
* script}, moreover the script will be disabled and flagged that has an error.
*
* @param script the script that caused the error, must not be {@code null}.
* @param error the error caused by the script, must not be {@code null}.
* @since 2.9.0
* @see #setEnabled(ScriptWrapper, boolean)
* @see #setError(ScriptWrapper, String)
* @see #handleScriptException(ScriptWrapper, Exception)
*/
public void handleScriptError(ScriptWrapper script, String error) {
recordScriptFailedStats(script);
try {
getWriters(script).append(error);
} catch (IOException ignore) {
// Nothing to do, callers should log the issue.
}
this.setError(script, error);
this.setEnabled(script, false);
}
/**
* Invokes the given {@code script}, synchronously, as a {@link TargetedScript}, handling any
* {@code Exception} thrown during the invocation.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons.
*
* @param script the script to invoke.
* @param msg the HTTP message to process.
* @since 2.2.0
* @see #getInterface(ScriptWrapper, Class)
*/
public void invokeTargetedScript(ScriptWrapper script, HttpMessage msg) {
validateScriptType(script, TYPE_TARGETED);
Writer writer = getWriters(script);
try {
// Dont need to check if enabled as it can only be invoked manually
TargetedScript s = this.getInterface(script, TargetedScript.class);
if (s != null) {
recordScriptCalledStats(script);
s.invokeWith(msg);
} else {
handleUnspecifiedScriptError(
script,
writer,
Constant.messages.getString("script.interface.targeted.error"));
}
} catch (Exception e) {
handleScriptException(script, writer, e);
}
}
/**
* Validates that the given {@code script} is of the given {@code scriptType}, throwing an
* {@code IllegalArgumentException} if not.
*
* @param script the script that will be checked, must not be {@code null}
* @param scriptType the expected type of the script, must not be {@code null}
* @throws IllegalArgumentException if the given {@code script} is not the given {@code
* scriptType}.
* @see ScriptWrapper#getTypeName()
*/
private static void validateScriptType(ScriptWrapper script, String scriptType)
throws IllegalArgumentException {
if (!scriptType.equals(script.getTypeName())) {
throw new IllegalArgumentException(
"Script "
+ script.getName()
+ " is not a '"
+ scriptType
+ "' script: "
+ script.getTypeName());
}
}
/**
* Handles a failed attempt to convert a script into an interface.
*
* <p>The given {@code errorMessage} will be written to the writer(s) associated with the given
* {@code script}, moreover it will be disabled and flagged that has an error.
*
* @param script the script that resulted in an exception, must not be {@code null}
* @param errorMessage the message that will be written to the writer(s)
* @since 2.5.0
* @see #setEnabled(ScriptWrapper, boolean)
* @see #setError(ScriptWrapper, Exception)
* @see #handleScriptException(ScriptWrapper, Exception)
*/
public void handleFailedScriptInterface(ScriptWrapper script, String errorMessage) {
handleUnspecifiedScriptError(script, getWriters(script), errorMessage);
}
/**
* Handles an unspecified error that occurred while calling or invoking a script.
*
* <p>The given {@code errorMessage} will be written to the given {@code writer} and the given
* {@code script} will be disabled and flagged that has an error.
*
* @param script the script that failed to be called/invoked, must not be {@code null}
* @param writer the writer associated with the script, must not be {@code null}
* @param errorMessage the message that will be written to the given {@code writer}
* @see #setError(ScriptWrapper, String)
* @see #setEnabled(ScriptWrapper, boolean)
*/
private void handleUnspecifiedScriptError(
ScriptWrapper script, Writer writer, String errorMessage) {
recordScriptFailedStats(script);
try {
writer.append(errorMessage);
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to append script error message because of an exception:", e);
}
logger.warn("Failed to append error message: " + errorMessage);
}
this.setError(script, errorMessage);
this.setEnabled(script, false);
}
/**
* Invokes the given {@code script}, synchronously, as a {@link ProxyScript}, handling any
* {@code Exception} thrown during the invocation.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons.
*
* @param script the script to invoke.
* @param msg the HTTP message being proxied.
* @param request {@code true} if processing the request, {@code false} otherwise.
* @return {@code true} if the request should be forward to the server, {@code false} otherwise.
* @since 2.2.0
* @see #getInterface(ScriptWrapper, Class)
*/
public boolean invokeProxyScript(ScriptWrapper script, HttpMessage msg, boolean request) {
validateScriptType(script, TYPE_PROXY);
Writer writer = getWriters(script);
try {
// Dont need to check if enabled as it can only be invoked manually
ProxyScript s = this.getInterface(script, ProxyScript.class);
if (s != null) {
recordScriptCalledStats(script);
if (request) {
return s.proxyRequest(msg);
} else {
return s.proxyResponse(msg);
}
} else {
handleUnspecifiedScriptError(
script,
writer,
Constant.messages.getString("script.interface.proxy.error"));
}
} catch (Exception e) {
handleScriptException(script, writer, e);
}
// Return true so that the request is submitted - if we returned false all proxying would
// fail on script errors
return true;
}
/**
* Invokes the given {@code script}, synchronously, as a {@link HttpSenderScript}, handling any
* {@code Exception} thrown during the invocation.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons.
*
* @param script the script to invoke.
* @param msg the HTTP message being sent/received.
* @param initiator the initiator of the request.
* @param sender the sender of the given {@code HttpMessage}.
* @param request {@code true} if processing the request, {@code false} otherwise.
* @since 2.4.1
* @see #getInterface(ScriptWrapper, Class)
*/
public void invokeSenderScript(
ScriptWrapper script,
HttpMessage msg,
int initiator,
HttpSender sender,
boolean request) {
validateScriptType(script, TYPE_HTTP_SENDER);
Writer writer = getWriters(script);
try {
HttpSenderScript senderScript = this.getInterface(script, HttpSenderScript.class);
if (senderScript != null) {
recordScriptCalledStats(script);
if (request) {
senderScript.sendingRequest(msg, initiator, new HttpSenderScriptHelper(sender));
} else {
senderScript.responseReceived(
msg, initiator, new HttpSenderScriptHelper(sender));
}
} else {
handleUnspecifiedScriptError(
script,
writer,
Constant.messages.getString("script.interface.httpsender.error"));
}
} catch (Exception e) {
handleScriptException(script, writer, e);
}
}
public void setChanged(ScriptWrapper script, boolean changed) {
script.setChanged(changed);
ScriptNode node = this.getTreeModel().getNodeForScript(script);
if (node != null) {
if (node.getNodeName().equals(script.getName())) {
// The name is the same
this.getTreeModel().nodeStructureChanged(script);
} else {
// The name has changed
node.setNodeName(script.getName());
this.getTreeModel().nodeStructureChanged(node.getParent());
}
}
notifyScriptChanged(script);
}
/**
* Notifies the {@code ScriptEventListener}s that the given {@code script} was changed.
*
* @param script the script that was changed, must not be {@code null}
* @see #listeners
* @see ScriptEventListener#scriptChanged(ScriptWrapper)
*/
private void notifyScriptChanged(ScriptWrapper script) {
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptChanged(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
public void setEnabled(ScriptWrapper script, boolean enabled) {
if (!script.getType().isEnableable()) {
return;
}
if (enabled && script.getEngine() == null) {
return;
}
script.setEnabled(enabled);
this.getTreeModel().nodeStructureChanged(script);
notifyScriptChanged(script);
}
public void setError(ScriptWrapper script, String details) {
script.setError(true);
script.setLastErrorDetails(details);
script.setLastOutput(details);
this.getTreeModel().nodeStructureChanged(script);
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptError(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
public void setError(ScriptWrapper script, Exception e) {
script.setLastException(e);
setError(script, e.getMessage());
}
public void addListener(ScriptEventListener listener) {
this.listeners.add(listener);
}
public void removeListener(ScriptEventListener listener) {
this.listeners.remove(listener);
}
/**
* Adds the given writer.
*
* <p>It will be written to each time a script writes some output.
*
* @param writer the writer to add.
* @see #removeWriter(Writer)
* @see #addScriptOutputListener(ScriptOutputListener)
*/
public void addWriter(Writer writer) {
this.writers.addWriter(writer);
}
/**
* Removes the given writer.
*
* @param writer the writer to remove.
* @see #addWriter(Writer)
*/
public void removeWriter(Writer writer) {
this.writers.removeWriter(writer);
}
/**
* Adds the given script output listener.
*
* @param listener the listener to add.
* @since 2.8.0
* @throws NullPointerException if the given listener is {@code null}.
* @see #removeScriptOutputListener(ScriptOutputListener)
*/
public void addScriptOutputListener(ScriptOutputListener listener) {
outputListeners.add(
Objects.requireNonNull(listener, "The parameter listener must not be null."));
}
/**
* Removes the given script output listener.
*
* @param listener the listener to remove.
* @since 2.8.0
* @throws NullPointerException if the given listener is {@code null}.
* @see #addScriptOutputListener(ScriptOutputListener)
*/
public void removeScriptOutputListener(ScriptOutputListener listener) {
outputListeners.remove(
Objects.requireNonNull(listener, "The parameter listener must not be null."));
}
public ScriptUI getScriptUI() {
return scriptUI;
}
public void setScriptUI(ScriptUI scriptUI) {
if (this.scriptUI != null) {
throw new InvalidParameterException(
"A script UI has already been set - only one is supported");
}
this.scriptUI = scriptUI;
}
public void removeScriptUI() {
this.scriptUI = null;
}
/**
* Creates a scripts cache.
*
* @param <T> the target interface.
* @param config the cache configuration
* @return the scripts cache.
* @since 2.10.0
*/
public <T> ScriptsCache<T> createScriptsCache(Configuration<T> config) {
return new ScriptsCache<>(this, config);
}
/**
* Gets the interface {@code class1} from the given {@code script}. Might return {@code null} if
* the {@code script} does not implement the interface.
*
* <p>First tries to get the interface directly from the {@code script} by calling the method
* {@code ScriptWrapper.getInterface(Class)}, if it returns {@code null} the interface will be
* extracted from the script after invoking it, using the method {@code
* Invocable.getInterface(Class)}.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons. If this behaviour is not
* desired call the method {@code getInterfaceWithOutAddOnLoader(} instead.
*
* @param script the script that will be invoked
* @param class1 the interface that will be obtained from the script
* @return the interface implemented by the script, or {@code null} if the {@code script} does
* not implement the interface.
* @throws ScriptException if the engine of the given {@code script} was not found.
* @throws IOException if an error occurred while obtaining the interface directly from the
* script ( {@code ScriptWrapper.getInterface(Class)})
* @see #getInterfaceWithOutAddOnLoader(ScriptWrapper, Class)
* @see ScriptWrapper#getInterface(Class)
* @see Invocable#getInterface(Class)
*/
public <T> T getInterface(ScriptWrapper script, Class<T> class1)
throws ScriptException, IOException {
ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(ExtensionFactory.getAddOnLoader());
try {
T iface = script.getInterface(class1);
if (iface != null) {
// the script wrapper has overridden the usual scripting mechanism
return iface;
}
} finally {
Thread.currentThread().setContextClassLoader(previousContextClassLoader);
}
if (script.isRunnableStandalone()) {
return null;
}
Invocable invocable = invokeScript(script);
if (invocable != null) {
return invocable.getInterface(class1);
}
return null;
}
/**
* Gets the interface {@code clazz} from the given {@code script}. Might return {@code null} if
* the {@code script} does not implement the interface.
*
* <p>First tries to get the interface directly from the {@code script} by calling the method
* {@code ScriptWrapper.getInterface(Class)}, if it returns {@code null} the interface will be
* extracted from the script after invoking it, using the method {@code
* Invocable.getInterface(Class)}.
*
* @param script the script that will be invoked
* @param clazz the interface that will be obtained from the script
* @return the interface implemented by the script, or {@code null} if the {@code script} does
* not implement the interface.
* @throws ScriptException if the engine of the given {@code script} was not found.
* @throws IOException if an error occurred while obtaining the interface directly from the
* script ( {@code ScriptWrapper.getInterface(Class)})
* @see #getInterface(ScriptWrapper, Class)
* @see ScriptWrapper#getInterface(Class)
* @see Invocable#getInterface(Class)
*/
public <T> T getInterfaceWithOutAddOnLoader(ScriptWrapper script, Class<T> clazz)
throws ScriptException, IOException {
T iface = script.getInterface(clazz);
if (iface != null) {
// the script wrapper has overridden the usual scripting mechanism
return iface;
}
return invokeScriptWithOutAddOnLoader(script).getInterface(clazz);
}
@Override
public List<String> getUnsavedResources() {
// Report all of the unsaved scripts
List<String> list = new ArrayList<>();
for (ScriptType type : this.getScriptTypes()) {
for (ScriptWrapper script : this.getScripts(type)) {
if (script.isChanged()) {
list.add(Constant.messages.getString("script.resource", script.getName()));
}
}
}
return list;
}
private void openCmdLineFile(File f) throws IOException, ScriptException {
if (!f.exists()) {
CommandLine.info(
Constant.messages.getString("script.cmdline.nofile", f.getAbsolutePath()));
return;
}
if (!f.canRead()) {
CommandLine.info(
Constant.messages.getString("script.cmdline.noread", f.getAbsolutePath()));
return;
}
int dotIndex = f.getName().lastIndexOf(".");
if (dotIndex <= 0) {
CommandLine.info(
Constant.messages.getString("script.cmdline.noext", f.getAbsolutePath()));
return;
}
String ext = f.getName().substring(dotIndex + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName == null) {
CommandLine.info(Constant.messages.getString("script.cmdline.noengine", ext));
return;
}
ScriptWrapper sw =
new ScriptWrapper(
f.getName(), "", engineName, this.getScriptType(TYPE_STANDALONE), true, f);
this.loadScript(sw);
this.addScript(sw);
if (!hasView()) {
// Only invoke if run from the command line
// if the GUI is present then its up to the user to invoke it
this.invokeScript(sw);
}
}
@Override
public void execute(CommandLineArgument[] args) {
if (args[ARG_SCRIPT_IDX].isEnabled()) {
for (String script : args[ARG_SCRIPT_IDX].getArguments()) {
try {
openCmdLineFile(new File(script));
} catch (Exception e) {
CommandLine.error(e.getMessage(), e);
}
}
}
}
private CommandLineArgument[] getCommandLineArguments() {
arguments[ARG_SCRIPT_IDX] =
new CommandLineArgument(
"-script",
1,
null,
"",
"-script <script> "
+ Constant.messages.getString("script.cmdline.help"));
return arguments;
}
@Override
public boolean handleFile(File file) {
int dotIndex = file.getName().lastIndexOf(".");
if (dotIndex <= 0) {
// No extension, cant work out which engine
return false;
}
String ext = file.getName().substring(dotIndex + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName == null) {
// No engine for this extension, we cant handle this
return false;
}
try {
openCmdLineFile(file);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return false;
}
return true;
}
@Override
public List<String> getHandledExtensions() {
// The list of all of the script extensions that can be handled from the command line
List<String> exts = new ArrayList<>();
for (ScriptEngineWrapper sew : this.engineWrappers) {
exts.addAll(sew.getExtensions());
}
return exts;
}
/** No database tables used, so all supported */
@Override
public boolean supportsDb(String type) {
return true;
}
/**
* Gets the script icon.
*
* <p>Should be called/used only when in view mode.
*
* @return the script icon, never {@code null}.
* @since 2.7.0
*/
public static ImageIcon getScriptIcon() {
if (scriptIcon == null) {
scriptIcon =
new ImageIcon(ExtensionScript.class.getResource("/resource/icon/16/059.png"));
}
return scriptIcon;
}
private static class ClearScriptVarsOnSessionChange implements SessionChangedListener {
@Override
public void sessionChanged(Session session) {}
@Override
public void sessionAboutToChange(Session session) {
ScriptVars.clear();
}
@Override
public void sessionScopeChanged(Session session) {}
@Override
public void sessionModeChanged(Mode mode) {}
}
/** A {@code Writer} that notifies {@link ScriptOutputListener}s when writing. */
private static class ScriptWriter extends Writer {
private final ScriptWrapper script;
private final Writer delegatee;
private final List<ScriptOutputListener> outputListeners;
public ScriptWriter(
ScriptWrapper script,
Writer delegatee,
List<ScriptOutputListener> outputListeners) {
this.script = Objects.requireNonNull(script);
this.delegatee = Objects.requireNonNull(delegatee);
this.outputListeners = Objects.requireNonNull(outputListeners);
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
delegatee.write(cbuf, off, len);
if (!outputListeners.isEmpty()) {
String output = new String(cbuf, off, len);
outputListeners.forEach(e -> e.output(script, output));
}
}
@Override
public void flush() throws IOException {
delegatee.flush();
}
@Override
public void close() throws IOException {
delegatee.close();
}
}
public static void recordScriptCalledStats(ScriptWrapper sw) {
if (sw != null) {
Stats.incCounter("stats.script.call." + sw.getEngineName() + "." + sw.getTypeName());
}
}
public static void recordScriptFailedStats(ScriptWrapper sw) {
if (sw != null) {
Stats.incCounter("stats.script.error." + sw.getEngineName() + "." + sw.getTypeName());
}
}
}
|
zap/src/main/java/org/zaproxy/zap/extension/script/ExtensionScript.java
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 The ZAP Development Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.script;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.tree.TreeNode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdesktop.swingx.JXTable;
import org.parosproxy.paros.CommandLine;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.extension.CommandLineArgument;
import org.parosproxy.paros.extension.CommandLineListener;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.extension.SessionChangedListener;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpSender;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.control.ExtensionFactory;
import org.zaproxy.zap.extension.script.ScriptsCache.Configuration;
import org.zaproxy.zap.utils.Stats;
public class ExtensionScript extends ExtensionAdaptor implements CommandLineListener {
public static final int EXTENSION_ORDER = 60;
public static final String NAME = "ExtensionScript";
/** @deprecated (2.7.0) Use {@link #getScriptIcon()} instead. */
@Deprecated public static final ImageIcon ICON = View.isInitialised() ? getScriptIcon() : null;
/**
* The {@code Charset} used to load/save the scripts from/to the file.
*
* <p>While the scripts can be loaded with any {@code Charset} (defaulting to this one) they are
* always saved with this {@code Charset}.
*
* @since 2.7.0
* @see #loadScript(ScriptWrapper)
* @see #loadScript(ScriptWrapper, Charset)
* @see #saveScript(ScriptWrapper)
*/
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
/**
* The script icon.
*
* <p>Lazily initialised.
*
* @see #getScriptIcon()
*/
private static ImageIcon scriptIcon;
public static final String SCRIPTS_DIR = "scripts";
public static final String TEMPLATES_DIR = SCRIPTS_DIR + File.separator + "templates";
private static final String LANG_ENGINE_SEP = " : ";
@Deprecated
protected static final String SCRIPT_CONSOLE_HOME_PAGE =
"https://github.com/zaproxy/zaproxy/wiki/ScriptConsole";
protected static final String SCRIPT_NAME_ATT = "zap.script.name";
public static final String TYPE_HTTP_SENDER = "httpsender";
public static final String TYPE_PROXY = "proxy";
public static final String TYPE_STANDALONE = "standalone";
public static final String TYPE_TARGETED = "targeted";
private ScriptEngineManager mgr = new ScriptEngineManager();
private ScriptParam scriptParam = null;
private OptionsScriptPanel optionsScriptPanel = null;
private ScriptTreeModel treeModel = null;
private List<ScriptEngineWrapper> engineWrappers = new ArrayList<>();
private Map<String, ScriptType> typeMap = new HashMap<>();
private ProxyListenerScript proxyListener = null;
private HttpSenderScriptListener httpSenderScriptListener;
private List<ScriptEventListener> listeners = new ArrayList<>();
private MultipleWriters writers = new MultipleWriters();
private ScriptUI scriptUI = null;
private CommandLineArgument[] arguments = new CommandLineArgument[1];
private static final int ARG_SCRIPT_IDX = 0;
private static final Logger logger = LogManager.getLogger(ExtensionScript.class);
/**
* Flag that indicates if the scripts/templates should be loaded when a new script type is
* registered.
*
* <p>This is to prevent loading scripts/templates of already installed scripts (ones that are
* registered during ZAP initialisation) twice, while allowing to load the scripts/templates of
* script types registered after initialisation (e.g. from installed add-ons).
*
* @since 2.4.0
* @see #registerScriptType(ScriptType)
* @see #optionsLoaded()
*/
private boolean shouldLoadScriptsOnScriptTypeRegistration;
/**
* The directories added to the extension, to automatically add and remove its scripts.
*
* @see #addScriptsFromDir(File)
* @see #removeScriptsFromDir(File)
*/
private List<File> trackedDirs = Collections.synchronizedList(new ArrayList<>());
/**
* The script output listeners added to the extension.
*
* @see #addScriptOutputListener(ScriptOutputListener)
* @see #getWriters(ScriptWrapper)
* @see #removeScriptOutputListener(ScriptOutputListener)
*/
private List<ScriptOutputListener> outputListeners = new CopyOnWriteArrayList<>();
public ExtensionScript() {
super(NAME);
this.setOrder(EXTENSION_ORDER);
ScriptEngine se = mgr.getEngineByName("ECMAScript");
if (se != null) {
this.registerScriptEngineWrapper(new JavascriptEngineWrapper(se.getFactory()));
} else {
logger.warn(
"No default JavaScript/ECMAScript engine found, some scripts might no longer work.");
}
}
@Override
public String getUIName() {
return Constant.messages.getString("script.name");
}
@Override
public void hook(ExtensionHook extensionHook) {
super.hook(extensionHook);
this.registerScriptType(
new ScriptType(
TYPE_PROXY,
"script.type.proxy",
createIcon("/resource/icon/16/script-proxy.png"),
true));
this.registerScriptType(
new ScriptType(
TYPE_STANDALONE,
"script.type.standalone",
createIcon("/resource/icon/16/script-standalone.png"),
false,
new String[] {ScriptType.CAPABILITY_APPEND}));
this.registerScriptType(
new ScriptType(
TYPE_TARGETED,
"script.type.targeted",
createIcon("/resource/icon/16/script-targeted.png"),
false));
this.registerScriptType(
new ScriptType(
TYPE_HTTP_SENDER,
"script.type.httpsender",
createIcon("/resource/icon/16/script-httpsender.png"),
true));
extensionHook.addSessionListener(new ClearScriptVarsOnSessionChange());
extensionHook.addProxyListener(this.getProxyListener());
extensionHook.addHttpSenderListener(getHttpSenderScriptListener());
extensionHook.addOptionsParamSet(getScriptParam());
extensionHook.addCommandLine(getCommandLineArguments());
if (hasView()) {
extensionHook.getHookView().addOptionPanel(getOptionsScriptPanel());
} else {
// No GUI so add stdout as a writer
this.addWriter(new PrintWriter(System.out));
}
extensionHook.addApiImplementor(new ScriptAPI(this));
}
/**
* Creates an {@code ImageIcon} with the given resource path, if in view mode.
*
* @param resourcePath the resource path of the icon, must not be {@code null}.
* @return the icon, or {@code null} if not in view mode.
*/
private ImageIcon createIcon(String resourcePath) {
if (getView() == null) {
return null;
}
return new ImageIcon(ExtensionScript.class.getResource(resourcePath));
}
private OptionsScriptPanel getOptionsScriptPanel() {
if (optionsScriptPanel == null) {
optionsScriptPanel = new OptionsScriptPanel(this);
}
return optionsScriptPanel;
}
private ProxyListenerScript getProxyListener() {
if (this.proxyListener == null) {
this.proxyListener = new ProxyListenerScript(this);
}
return this.proxyListener;
}
private HttpSenderScriptListener getHttpSenderScriptListener() {
if (this.httpSenderScriptListener == null) {
this.httpSenderScriptListener = new HttpSenderScriptListener(this);
}
return this.httpSenderScriptListener;
}
public List<String> getScriptingEngines() {
List<String> engineNames = new ArrayList<>();
List<ScriptEngineFactory> engines = mgr.getEngineFactories();
for (ScriptEngineFactory engine : engines) {
engineNames.add(engine.getLanguageName() + LANG_ENGINE_SEP + engine.getEngineName());
}
for (ScriptEngineWrapper sew : this.engineWrappers) {
if (sew.isVisible() && !engines.contains(sew.getFactory())) {
engineNames.add(sew.getLanguageName() + LANG_ENGINE_SEP + sew.getEngineName());
}
}
Collections.sort(engineNames);
return engineNames;
}
/**
* Registers a new script engine wrapper.
*
* <p>The templates of the wrapped script engine are loaded, if any.
*
* <p>The engine is set to existing scripts targeting the given engine.
*
* @param wrapper the script engine wrapper that will be added, must not be {@code null}
* @see #removeScriptEngineWrapper(ScriptEngineWrapper)
* @see ScriptWrapper#setEngine(ScriptEngineWrapper)
*/
public void registerScriptEngineWrapper(ScriptEngineWrapper wrapper) {
logger.debug(
"registerEngineWrapper "
+ wrapper.getLanguageName()
+ " : "
+ wrapper.getEngineName());
this.engineWrappers.add(wrapper);
setScriptEngineWrapper(getTreeModel().getScriptsNode(), wrapper, wrapper);
setScriptEngineWrapper(getTreeModel().getTemplatesNode(), wrapper, wrapper);
// Templates for this engine might not have been loaded
this.loadTemplates(wrapper);
synchronized (trackedDirs) {
String engineName =
wrapper.getLanguageName() + LANG_ENGINE_SEP + wrapper.getEngineName();
for (File dir : trackedDirs) {
for (ScriptType type : this.getScriptTypes()) {
addScriptsFromDir(dir, type, engineName);
}
}
}
if (scriptUI != null) {
try {
scriptUI.engineAdded(wrapper);
} catch (Exception e) {
logger.error("An error occurred while notifying ScriptUI:", e);
}
}
}
/**
* Sets the given {@code newEngineWrapper} to all children of {@code baseNode} that targets the
* given {@code engineWrapper}.
*
* @param baseNode the node whose child nodes will have the engine set, must not be {@code null}
* @param engineWrapper the script engine of the targeting scripts, must not be {@code null}
* @param newEngineWrapper the script engine that will be set to the targeting scripts
* @see ScriptWrapper#setEngine(ScriptEngineWrapper)
*/
private void setScriptEngineWrapper(
ScriptNode baseNode,
ScriptEngineWrapper engineWrapper,
ScriptEngineWrapper newEngineWrapper) {
for (@SuppressWarnings("unchecked")
Enumeration<TreeNode> e = baseNode.depthFirstEnumeration();
e.hasMoreElements(); ) {
ScriptNode node = (ScriptNode) e.nextElement();
if (node.getUserObject() != null && (node.getUserObject() instanceof ScriptWrapper)) {
ScriptWrapper scriptWrapper = (ScriptWrapper) node.getUserObject();
if (hasSameScriptEngine(scriptWrapper, engineWrapper)) {
scriptWrapper.setEngine(newEngineWrapper);
if (newEngineWrapper == null) {
if (scriptWrapper.isEnabled()) {
setEnabled(scriptWrapper, false);
scriptWrapper.setPreviouslyEnabled(true);
}
} else if (scriptWrapper.isPreviouslyEnabled()) {
setEnabled(scriptWrapper, true);
scriptWrapper.setPreviouslyEnabled(false);
}
}
}
}
}
/**
* Tells whether or not the given {@code scriptWrapper} has the given {@code engineWrapper}.
*
* <p>If the given {@code scriptWrapper} has an engine set it's checked by reference (operator
* {@code ==}), otherwise it's used the engine names.
*
* @param scriptWrapper the script wrapper that will be checked
* @param engineWrapper the engine that will be checked against the engine of the script
* @return {@code true} if the given script has the given engine, {@code false} otherwise.
* @since 2.4.0
* @see #isSameScriptEngine(String, String, String)
*/
public static boolean hasSameScriptEngine(
ScriptWrapper scriptWrapper, ScriptEngineWrapper engineWrapper) {
if (scriptWrapper.getEngine() != null) {
return scriptWrapper.getEngine() == engineWrapper;
}
return isSameScriptEngine(
scriptWrapper.getEngineName(),
engineWrapper.getEngineName(),
engineWrapper.getLanguageName());
}
/**
* Tells whether or not the given {@code name} matches the given {@code engineName} and {@code
* engineLanguage}.
*
* @param name the name that will be checked against the given {@code engineName} and {@code
* engineLanguage}.
* @param engineName the name of the script engine.
* @param engineLanguage the language of the script engine.
* @return {@code true} if the {@code name} matches the given engine's name and language, {@code
* false} otherwise.
* @since 2.4.0
* @see #hasSameScriptEngine(ScriptWrapper, ScriptEngineWrapper)
*/
public static boolean isSameScriptEngine(
String name, String engineName, String engineLanguage) {
if (name == null) {
return false;
}
// In the configs we just use the engine name, in the UI we use the language name as well
if (name.indexOf(LANG_ENGINE_SEP) > 0) {
if (name.equals(engineLanguage + LANG_ENGINE_SEP + engineName)) {
return true;
}
return false;
}
return name.equals(engineName);
}
/**
* Removes the given script engine wrapper.
*
* <p>The user's templates and scripts associated with the given engine are not removed but its
* engine is set to {@code null}. Default templates are removed.
*
* <p>The call to this method has no effect if the given type is not registered.
*
* @param wrapper the script engine wrapper that will be removed, must not be {@code null}
* @since 2.4.0
* @see #registerScriptEngineWrapper(ScriptEngineWrapper)
* @see ScriptWrapper#setEngine(ScriptEngineWrapper)
*/
public void removeScriptEngineWrapper(ScriptEngineWrapper wrapper) {
logger.debug(
"Removing script engine: "
+ wrapper.getLanguageName()
+ " : "
+ wrapper.getEngineName());
if (this.engineWrappers.remove(wrapper)) {
if (scriptUI != null) {
try {
scriptUI.engineRemoved(wrapper);
} catch (Exception e) {
logger.error("An error occurred while notifying ScriptUI:", e);
}
}
setScriptEngineWrapper(getTreeModel().getScriptsNode(), wrapper, null);
processTemplatesOfRemovedEngine(getTreeModel().getTemplatesNode(), wrapper);
}
}
private void processTemplatesOfRemovedEngine(
ScriptNode baseNode, ScriptEngineWrapper engineWrapper) {
@SuppressWarnings("unchecked")
List<TreeNode> templateNodes = Collections.list(baseNode.depthFirstEnumeration());
for (TreeNode tpNode : templateNodes) {
ScriptNode node = (ScriptNode) tpNode;
if (node.getUserObject() != null && (node.getUserObject() instanceof ScriptWrapper)) {
ScriptWrapper scriptWrapper = (ScriptWrapper) node.getUserObject();
if (hasSameScriptEngine(scriptWrapper, engineWrapper)) {
if (engineWrapper.isDefaultTemplate(scriptWrapper)) {
removeTemplate(scriptWrapper);
} else {
scriptWrapper.setEngine(null);
this.getTreeModel().nodeStructureChanged(scriptWrapper);
}
}
}
}
}
public ScriptEngineWrapper getEngineWrapper(String name) {
ScriptEngineWrapper sew = getEngineWrapperImpl(name);
if (sew == null) {
throw new InvalidParameterException("No such engine: " + name);
}
return sew;
}
/**
* Gets the script engine with the given name.
*
* @param name the name of the script engine.
* @return the engine, or {@code null} if not available.
*/
private ScriptEngineWrapper getEngineWrapperImpl(String name) {
for (ScriptEngineWrapper sew : this.engineWrappers) {
if (isSameScriptEngine(name, sew.getEngineName(), sew.getLanguageName())) {
return sew;
}
}
// Not one we know of, create a default wrapper
List<ScriptEngineFactory> engines = mgr.getEngineFactories();
ScriptEngine engine = null;
for (ScriptEngineFactory e : engines) {
if (isSameScriptEngine(name, e.getEngineName(), e.getLanguageName())) {
engine = e.getScriptEngine();
break;
}
}
if (engine != null) {
DefaultEngineWrapper dew = new DefaultEngineWrapper(engine.getFactory());
this.registerScriptEngineWrapper(dew);
return dew;
}
return null;
}
public String getEngineNameForExtension(String ext) {
ScriptEngine engine = mgr.getEngineByExtension(ext);
if (engine != null) {
return engine.getFactory().getLanguageName()
+ LANG_ENGINE_SEP
+ engine.getFactory().getEngineName();
}
for (ScriptEngineWrapper sew : this.engineWrappers) {
if (sew.getExtensions() != null) {
for (String extn : sew.getExtensions()) {
if (ext.equals(extn)) {
return sew.getLanguageName() + LANG_ENGINE_SEP + sew.getEngineName();
}
}
}
}
return null;
}
protected ScriptParam getScriptParam() {
if (this.scriptParam == null) {
this.scriptParam = new ScriptParam();
}
return this.scriptParam;
}
public ScriptTreeModel getTreeModel() {
if (this.treeModel == null) {
this.treeModel = new ScriptTreeModel();
}
return this.treeModel;
}
/**
* Registers a new type of script.
*
* <p>The script is added to the tree of scripts and its scripts/templates loaded, if any.
*
* @param type the new type of script
* @throws InvalidParameterException if a script type with same name is already registered
* @see #removeScriptType(ScriptType)
*/
public void registerScriptType(ScriptType type) {
if (typeMap.containsKey(type.getName())) {
throw new InvalidParameterException("ScriptType already registered: " + type.getName());
}
this.typeMap.put(type.getName(), type);
this.getTreeModel().addType(type);
if (shouldLoadScriptsOnScriptTypeRegistration) {
addScripts(type);
loadScriptTemplates(type);
}
synchronized (trackedDirs) {
for (File dir : trackedDirs) {
addScriptsFromDir(dir, type, null);
}
}
}
/**
* Adds the (saved) scripts of the given script type.
*
* @param type the type of the script.
* @see ScriptParam#getScripts()
*/
private void addScripts(ScriptType type) {
for (ScriptWrapper script : this.getScriptParam().getScripts()) {
if (!type.getName().equals(script.getTypeName())) {
continue;
}
try {
loadScript(script);
addScript(script, false, false);
} catch (MalformedInputException e) {
logger.warn(
"Failed to add script \""
+ script.getName()
+ "\", contains invalid character sequence (UTF-8).");
} catch (InvalidParameterException | IOException e) {
logger.error("Failed to add script: " + script.getName(), e);
}
}
}
/**
* Removes the given script type.
*
* <p>The templates and scripts associated with the given type are also removed, if any.
*
* <p>The call to this method has no effect if the given type is not registered.
*
* @param type the script type that will be removed
* @since 2.4.0
* @see #registerScriptType(ScriptType)
* @deprecated (2.9.0) Use {@link #removeScriptType(ScriptType)} instead.
*/
@Deprecated
public void removeScripType(ScriptType type) {
removeScriptType(type);
}
/**
* Removes the given script type.
*
* <p>The templates and scripts associated with the given type are also removed, if any.
*
* <p>The call to this method has no effect if the given type is not registered.
*
* @param type the script type that will be removed
* @since 2.9.0
* @see #registerScriptType(ScriptType)
*/
public void removeScriptType(ScriptType type) {
ScriptType scriptType = typeMap.remove(type.getName());
if (scriptType != null) {
getTreeModel().removeType(scriptType);
}
}
public ScriptType getScriptType(String name) {
return this.typeMap.get(name);
}
public Collection<ScriptType> getScriptTypes() {
return typeMap.values();
}
@Override
public String getAuthor() {
return Constant.ZAP_TEAM;
}
@Override
public String getDescription() {
return Constant.messages.getString("script.desc");
}
private void refreshScript(ScriptWrapper script) {
for (ScriptEventListener listener : this.listeners) {
try {
listener.refreshScript(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
private void reloadIfChangedOnDisk(ScriptWrapper script) {
if (script.hasChangedOnDisk() && !script.isChanged()) {
try {
logger.debug(
"Reloading script as its been changed on disk "
+ script.getFile().getAbsolutePath());
script.reloadScript();
} catch (IOException e) {
logger.error("Failed to reload script " + script.getFile().getAbsolutePath(), e);
}
}
}
public ScriptWrapper getScript(String name) {
ScriptWrapper script = getScriptImpl(name);
if (script != null) {
refreshScript(script);
reloadIfChangedOnDisk(script);
}
return script;
}
/**
* Gets the script with the given name.
*
* <p>Internal method that does not perform any actions on the returned script.
*
* @param name the name of the script.
* @return the script, or {@code null} if it doesn't exist.
* @see #getScript(String)
*/
private ScriptWrapper getScriptImpl(String name) {
return this.getTreeModel().getScript(name);
}
public ScriptNode addScript(ScriptWrapper script) {
return this.addScript(script, true);
}
public ScriptNode addScript(ScriptWrapper script, boolean display) {
return addScript(script, display, true);
}
private ScriptNode addScript(ScriptWrapper script, boolean display, boolean save) {
if (script == null) {
return null;
}
setEngine(script);
ScriptNode node = this.getTreeModel().addScript(script);
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptAdded(script, display);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
if (save && script.isLoadOnStart() && script.getFile() != null) {
this.getScriptParam().addScript(script);
this.getScriptParam().saveScripts();
}
return node;
}
private void logScriptEventListenerException(
ScriptEventListener listener, ScriptWrapper script, Exception e) {
String classname = listener.getClass().getCanonicalName();
String scriptName = script.getName();
logger.error(
"Error while notifying '"
+ classname
+ "' with script '"
+ scriptName
+ "', cause: "
+ e.getMessage(),
e);
}
public void saveScript(ScriptWrapper script) throws IOException {
refreshScript(script);
script.saveScript();
this.setChanged(script, false);
// The removal is required for script that use wrappers, like Zest
this.getScriptParam().removeScript(script);
this.getScriptParam().addScript(script);
this.getScriptParam().saveScripts();
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptSaved(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
public void removeScript(ScriptWrapper script) {
script.setLoadOnStart(false);
this.getScriptParam().removeScript(script);
this.getScriptParam().saveScripts();
this.getTreeModel().removeScript(script);
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptRemoved(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
public void removeTemplate(ScriptWrapper template) {
this.getTreeModel().removeTemplate(template);
for (ScriptEventListener listener : this.listeners) {
try {
listener.templateRemoved(template);
} catch (Exception e) {
logScriptEventListenerException(listener, template, e);
}
}
}
public ScriptNode addTemplate(ScriptWrapper template) {
return this.addTemplate(template, true);
}
public ScriptNode addTemplate(ScriptWrapper template, boolean display) {
if (template == null) {
return null;
}
ScriptNode node = this.getTreeModel().addTemplate(template);
for (ScriptEventListener listener : this.listeners) {
try {
listener.templateAdded(template, display);
} catch (Exception e) {
logScriptEventListenerException(listener, template, e);
}
}
return node;
}
@Override
public void postInit() {
ScriptEngineWrapper ecmaScriptEngineWrapper = null;
final List<String[]> scriptsNotAdded = new ArrayList<>(1);
for (ScriptWrapper script : this.getScriptParam().getScripts()) {
// Change scripts using Rhino (Java 7) script engine to Nashorn (Java 8+).
if (script.getEngine() == null && isRhinoScriptEngine(script.getEngineName())) {
if (ecmaScriptEngineWrapper == null) {
ecmaScriptEngineWrapper = getEcmaScriptEngineWrapper();
}
if (ecmaScriptEngineWrapper != null) {
logger.info(
"Changing ["
+ script.getName()
+ "] (ECMAScript) script engine from ["
+ script.getEngineName()
+ "] to ["
+ ecmaScriptEngineWrapper.getEngineName()
+ "].");
script.setEngine(ecmaScriptEngineWrapper);
}
}
try {
this.loadScript(script);
if (script.getType() != null) {
this.addScript(script, false, false);
} else {
logger.warn(
"Failed to add script \""
+ script.getName()
+ "\", provided script type \""
+ script.getTypeName()
+ "\" not found, available: "
+ getScriptTypesNames());
scriptsNotAdded.add(
new String[] {
script.getName(),
script.getEngineName(),
Constant.messages.getString(
"script.info.scriptsNotAdded.error.missingType",
script.getTypeName())
});
}
} catch (MalformedInputException e) {
logger.warn(
"Failed to add script \""
+ script.getName()
+ "\", contains invalid character sequence (UTF-8).");
scriptsNotAdded.add(
new String[] {
script.getName(),
script.getEngineName(),
Constant.messages.getString(
"script.info.scriptsNotAdded.error.invalidChars")
});
} catch (InvalidParameterException | IOException e) {
logger.error(e.getMessage(), e);
scriptsNotAdded.add(
new String[] {
script.getName(),
script.getEngineName(),
Constant.messages.getString("script.info.scriptsNotAdded.error.other")
});
}
}
informScriptsNotAdded(scriptsNotAdded);
this.loadTemplates();
for (File dir : this.getScriptParam().getScriptDirs()) {
// Load the scripts from subdirectories of each directory configured
int numAdded = addScriptsFromDir(dir);
logger.debug("Added " + numAdded + " scripts from dir: " + dir.getAbsolutePath());
}
shouldLoadScriptsOnScriptTypeRegistration = true;
Path defaultScriptsDir = Paths.get(Constant.getZapHome(), SCRIPTS_DIR, SCRIPTS_DIR);
for (ScriptType scriptType : typeMap.values()) {
Path scriptTypeDir = defaultScriptsDir.resolve(scriptType.getName());
if (Files.notExists(scriptTypeDir)) {
try {
Files.createDirectories(scriptTypeDir);
} catch (IOException e) {
logger.warn(
"Failed to create directory for script type: " + scriptType.getName(),
e);
}
}
}
}
private static boolean isRhinoScriptEngine(String engineName) {
return "Mozilla Rhino".equals(engineName) || "Rhino".equals(engineName);
}
private ScriptEngineWrapper getEcmaScriptEngineWrapper() {
for (ScriptEngineWrapper sew : this.engineWrappers) {
if ("ECMAScript".equals(sew.getLanguageName())) {
return sew;
}
}
return null;
}
private List<String> getScriptTypesNames() {
return getScriptTypes().stream()
.collect(ArrayList::new, (c, e) -> c.add(e.getName()), ArrayList::addAll);
}
private void informScriptsNotAdded(final List<String[]> scriptsNotAdded) {
if (!hasView() || scriptsNotAdded.isEmpty()) {
return;
}
final List<Object> optionPaneContents = new ArrayList<>(2);
optionPaneContents.add(Constant.messages.getString("script.info.scriptsNotAdded.message"));
JXTable table =
new JXTable(
new AbstractTableModel() {
private static final long serialVersionUID = -457689656746030560L;
@Override
public String getColumnName(int column) {
if (column == 0) {
return Constant.messages.getString(
"script.info.scriptsNotAdded.table.column.scriptName");
} else if (column == 1) {
return Constant.messages.getString(
"script.info.scriptsNotAdded.table.column.scriptEngine");
}
return Constant.messages.getString(
"script.info.scriptsNotAdded.table.column.errorCause");
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return scriptsNotAdded.get(rowIndex)[columnIndex];
}
@Override
public int getRowCount() {
return scriptsNotAdded.size();
}
@Override
public int getColumnCount() {
return 3;
}
});
table.setColumnControlVisible(true);
table.setVisibleRowCount(Math.min(scriptsNotAdded.size() + 1, 5));
table.packAll();
optionPaneContents.add(new JScrollPane(table));
EventQueue.invokeLater(
new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(
getView().getMainFrame(),
optionPaneContents.toArray(),
Constant.PROGRAM_NAME,
JOptionPane.INFORMATION_MESSAGE);
}
});
}
/**
* Adds the scripts from the given directory and starts tracking it.
*
* <p>The directory will be tracked to add or remove its scripts when a new script engine/type
* is added or removed.
*
* <p>The scripts are expected to be under directories of the corresponding script type, for
* example:
*
* <pre>{@code
* (dir specified)
* ├── active
* │ ├── gof_lite.js
* │ ├── TestInsecureHTTPVerbs.py
* │ └── User defined attacks.js
* ├── extender
* │ └── HTTP Message Logger.js
* ├── httpfuzzerprocessor
* │ ├── add_msgs_sites_tree.js
* │ ├── http_status_code_filter.py
* │ └── showDifferences.js
* ├── httpsender
* │ ├── add_header_request.py
* │ └── Capture and Replace Anti CSRF Token.js
* └── variant
* └── JsonStrings.js
* }</pre>
*
* where {@code active}, {@code extender}, {@code httpfuzzerprocessor}, {@code httpsender}, and
* {@code variant} are the script types.
*
* @param dir the directory from where to add the scripts.
* @return the number of scripts added.
* @since 2.4.1
* @see #removeScriptsFromDir(File)
*/
public int addScriptsFromDir(File dir) {
logger.debug("Adding scripts from dir: " + dir.getAbsolutePath());
trackedDirs.add(dir);
int addedScripts = 0;
for (ScriptType type : this.getScriptTypes()) {
addedScripts += addScriptsFromDir(dir, type, null);
}
return addedScripts;
}
/**
* Adds the scripts from the given directory of the given script type and, optionally, for the
* engine with the given name.
*
* @param dir the directory from where to add the scripts.
* @param type the script type, must not be {@code null}.
* @param targetEngineName the engine that the scripts must be of, {@code null} for all engines.
* @return the number of scripts added.
*/
private int addScriptsFromDir(File dir, ScriptType type, String targetEngineName) {
int addedScripts = 0;
File typeDir = new File(dir, type.getName());
if (typeDir.exists()) {
for (File f : typeDir.listFiles()) {
String ext = f.getName().substring(f.getName().lastIndexOf(".") + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName != null
&& (targetEngineName == null || engineName.equals(targetEngineName))) {
try {
if (f.canWrite()) {
String scriptName = this.getUniqueScriptName(f.getName(), ext);
logger.debug("Loading script " + scriptName);
ScriptWrapper sw =
new ScriptWrapper(
scriptName,
"",
this.getEngineWrapper(engineName),
type,
false,
f);
this.loadScript(sw);
this.addScript(sw, false);
} else {
// Cant write so add as a template
String scriptName = this.getUniqueTemplateName(f.getName(), ext);
logger.debug("Loading script " + scriptName);
ScriptWrapper sw =
new ScriptWrapper(
scriptName,
"",
this.getEngineWrapper(engineName),
type,
false,
f);
this.loadScript(sw);
this.addTemplate(sw, false);
}
addedScripts++;
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
} else {
logger.debug("Ignoring " + f.getName());
}
}
}
return addedScripts;
}
/**
* Removes the scripts added from the given directory and stops tracking it.
*
* <p>The number of scripts removed might be different than the number of scripts initially
* added, as a script engine or type might have been added or removed in the meantime.
*
* @param dir the directory previously added.
* @return the number of scripts removed.
* @since 2.4.1
* @see #addScriptsFromDir(File)
*/
public int removeScriptsFromDir(File dir) {
logger.debug("Removing scripts from dir: " + dir.getAbsolutePath());
trackedDirs.remove(dir);
int removedScripts = 0;
for (ScriptType type : this.getScriptTypes()) {
File locDir = new File(dir, type.getName());
if (locDir.exists()) {
// Loop through all of the known scripts and templates
// removing any from this directory
for (ScriptWrapper sw : this.getScripts(type)) {
if (isSavedInDir(sw, locDir)) {
this.removeScript(sw);
removedScripts++;
}
}
for (ScriptWrapper sw : this.getTemplates(type)) {
if (isSavedInDir(sw, locDir)) {
this.removeTemplate(sw);
removedScripts++;
}
}
}
}
return removedScripts;
}
/**
* Tells whether or not the given script is saved in the given directory.
*
* @param scriptWrapper the script to check.
* @param directory the directory where to check.
* @return {@code true} if the script is saved in the given directory, {@code false} otherwise.
*/
private static boolean isSavedInDir(ScriptWrapper scriptWrapper, File directory) {
File file = scriptWrapper.getFile();
if (file == null) {
return false;
}
return file.getParentFile().equals(directory);
}
/**
* Gets the numbers of scripts for the given directory for the currently registered script
* engines and types.
*
* @param dir the directory to check.
* @return the number of scripts.
* @since 2.4.1
*/
public int getScriptCount(File dir) {
int scripts = 0;
for (ScriptType type : this.getScriptTypes()) {
File locDir = new File(dir, type.getName());
if (locDir.exists()) {
for (File f : locDir.listFiles()) {
String ext = f.getName().substring(f.getName().lastIndexOf(".") + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName != null) {
scripts++;
}
}
}
}
return scripts;
}
/*
* Returns a unique name for the given script name
*/
private String getUniqueScriptName(String name, String ext) {
if (this.getScriptImpl(name) == null) {
// Its unique
return name;
}
// Its not unique, add a suitable index...
String stub = name.substring(0, name.length() - ext.length() - 1);
int index = 1;
do {
index++;
name = stub + "(" + index + ")." + ext;
} while (this.getScriptImpl(name) != null);
return name;
}
/*
* Returns a unique name for the given template name
*/
private String getUniqueTemplateName(String name, String ext) {
if (this.getTreeModel().getTemplate(name) == null) {
// Its unique
return name;
}
// Its not unique, add a suitable index...
String stub = name.substring(0, name.length() - ext.length() - 1);
int index = 1;
do {
index++;
name = stub + "(" + index + ")." + ext;
} while (this.getTreeModel().getTemplate(name) != null);
return name;
}
private void loadTemplates() {
this.loadTemplates(null);
}
private void loadTemplates(ScriptEngineWrapper engine) {
for (ScriptType type : this.getScriptTypes()) {
loadScriptTemplates(type, engine);
}
}
/**
* Loads script templates of the given {@code type}, for all script engines.
*
* @param type the script type whose templates will be loaded
* @since 2.4.0
* @see #loadScriptTemplates(ScriptType, ScriptEngineWrapper)
*/
private void loadScriptTemplates(ScriptType type) {
loadScriptTemplates(type, null);
}
/**
* Loads script templates of the given {@code type} for the given {@code engine}.
*
* @param type the script type whose templates will be loaded
* @param engine the script engine whose templates will be loaded for the given {@code script}
* @since 2.4.0
* @see #loadScriptTemplates(ScriptType)
*/
private void loadScriptTemplates(ScriptType type, ScriptEngineWrapper engine) {
File locDir =
new File(
Constant.getZapHome()
+ File.separator
+ TEMPLATES_DIR
+ File.separator
+ type.getName());
File stdDir =
new File(
Constant.getZapInstall()
+ File.separator
+ TEMPLATES_DIR
+ File.separator
+ type.getName());
// Load local files first, as these override any one included in the release
if (locDir.exists()) {
for (File f : locDir.listFiles()) {
loadTemplate(f, type, engine, false);
}
}
if (stdDir.exists()) {
for (File f : stdDir.listFiles()) {
// Dont log errors on duplicates - 'local' templates should take precedence
loadTemplate(f, type, engine, true);
}
}
}
private void loadTemplate(
File f, ScriptType type, ScriptEngineWrapper engine, boolean ignoreDuplicates) {
if (f.getName().indexOf(".") > 0) {
if (this.getTreeModel().getTemplate(f.getName()) == null) {
String ext = f.getName().substring(f.getName().lastIndexOf(".") + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName != null
&& (engine == null || engine.getExtensions().contains(ext))) {
try {
ScriptWrapper template =
new ScriptWrapper(
f.getName(),
"",
this.getEngineWrapper(engineName),
type,
false,
f);
this.loadScript(template);
this.addTemplate(template);
} catch (InvalidParameterException e) {
if (!ignoreDuplicates) {
logger.error(e.getMessage(), e);
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
}
/**
* Loads the script from the file, using {@link #DEFAULT_CHARSET}.
*
* <p>If the file contains invalid byte sequences (for {@code DEFAULT_CHARSET}) it will be
* loaded again using the {@link Charset#defaultCharset() (JVM) default charset}, to load
* scripts saved with older ZAP versions (which relied on default charset).
*
* @param script the ScriptWrapper to be loaded (read script from file).
* @return the {@code ScriptWrapper} with the actual script read from the file.
* @throws IOException if an error occurred while reading the script from the file.
* @throws IllegalArgumentException if the {@code script} is {@code null}.
* @see #loadScript(ScriptWrapper, Charset)
*/
public ScriptWrapper loadScript(ScriptWrapper script) throws IOException {
try {
return loadScript(script, DEFAULT_CHARSET);
} catch (MalformedInputException e) {
if (Charset.defaultCharset() == DEFAULT_CHARSET) {
// No point trying the (JVM) default charset if it's the same...
throw e;
}
if (logger.isDebugEnabled()) {
logger.debug(
"Failed to load script ["
+ script.getName()
+ "] using ["
+ DEFAULT_CHARSET
+ "], falling back to ["
+ Charset.defaultCharset()
+ "].",
e);
}
return loadScript(script, Charset.defaultCharset());
}
}
/**
* Loads the script from the file, using the given charset.
*
* @param script the ScriptWrapper to be loaded (read script from file).
* @param charset the charset to use when reading the script from the file.
* @return the {@code ScriptWrapper} with the actual script read from the file.
* @throws IOException if an error occurred while reading the script from the file.
* @throws IllegalArgumentException if the {@code script} or the {@code charset} is {@code
* null}.
* @since 2.7.0
* @see #loadScript(ScriptWrapper)
*/
public ScriptWrapper loadScript(ScriptWrapper script, Charset charset) throws IOException {
if (script == null) {
throw new IllegalArgumentException("Parameter script must not be null.");
}
if (charset == null) {
throw new IllegalArgumentException("Parameter charset must not be null.");
}
script.loadScript(charset);
if (script.getType() == null) {
// This happens when scripts are loaded from the configs as the types
// may well not have been registered at that stage
script.setType(this.getScriptType(script.getTypeName()));
}
setEngine(script);
return script;
}
/**
* Sets the engine script to the given script, if not already set.
*
* <p>Scripts loaded from the configuration file might not have the engine set when used.
*
* <p>Does nothing if the engine script is not available.
*
* @param script the script to set the engine.
*/
private void setEngine(ScriptWrapper script) {
if (script.getEngine() != null) {
return;
}
ScriptEngineWrapper sew = getEngineWrapperImpl(script.getEngineName());
if (sew == null) {
return;
}
script.setEngine(sew);
}
public List<ScriptWrapper> getScripts(String type) {
return this.getScripts(this.getScriptType(type));
}
public List<ScriptWrapper> getScripts(ScriptType type) {
List<ScriptWrapper> scripts = new ArrayList<>();
if (type == null) {
return scripts;
}
for (ScriptNode node : this.getTreeModel().getNodes(type.getName())) {
ScriptWrapper script = (ScriptWrapper) node.getUserObject();
refreshScript(script);
scripts.add((ScriptWrapper) node.getUserObject());
}
return scripts;
}
public List<ScriptWrapper> getTemplates(ScriptType type) {
List<ScriptWrapper> scripts = new ArrayList<>();
if (type == null) {
return scripts;
}
for (ScriptWrapper script : this.getTreeModel().getTemplates(type)) {
scripts.add(script);
}
return scripts;
}
/*
* This extension supports any number of writers to be registered which all get written to for
* ever script. It also supports script specific writers.
*/
private Writer getWriters(ScriptWrapper script) {
Writer delegatee = this.writers;
Writer writer = script.getWriter();
if (writer != null) {
// Use the script specific writer in addition to the std one
MultipleWriters scriptWriters = new MultipleWriters();
scriptWriters.addWriter(writer);
scriptWriters.addWriter(writers);
delegatee = scriptWriters;
}
return new ScriptWriter(script, delegatee, outputListeners);
}
/**
* Invokes the given {@code script}, synchronously, handling any {@code Exception} thrown during
* the invocation.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons. If this behaviour is not
* desired call the method {@code invokeScriptWithOutAddOnLoader} instead.
*
* @param script the script that will be invoked
* @return an {@code Invocable} for the {@code script}, or {@code null} if none.
* @throws ScriptException if the engine of the given {@code script} was not found.
* @see #invokeScriptWithOutAddOnLoader(ScriptWrapper)
* @see Invocable
*/
public Invocable invokeScript(ScriptWrapper script) throws ScriptException {
logger.debug("invokeScript " + script.getName());
preInvokeScript(script);
ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(ExtensionFactory.getAddOnLoader());
try {
return invokeScriptImpl(script);
} finally {
Thread.currentThread().setContextClassLoader(previousContextClassLoader);
}
}
/**
* Notifies the {@code ScriptEventListener}s that the given {@code script} should be refreshed,
* resets the error and output states of the given {@code script} and notifies {@code
* ScriptEventListener}s of the pre-invocation.
*
* <p>If the script does not have an engine it will be set one (if found).
*
* @param script the script that will be invoked after the call to this method
* @throws ScriptException if the engine of the given {@code script} was not found.
* @see ScriptEventListener#refreshScript(ScriptWrapper)
* @see ScriptEventListener#preInvoke(ScriptWrapper)
*/
private void preInvokeScript(ScriptWrapper script) throws ScriptException {
setEngine(script);
if (script.getEngine() == null) {
throw new ScriptException("Failed to find script engine: " + script.getEngineName());
}
refreshScript(script);
script.setLastErrorDetails("");
script.setLastException(null);
script.setLastOutput("");
for (ScriptEventListener listener : this.listeners) {
try {
listener.preInvoke(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
/**
* Invokes the given {@code script}, handling any {@code Exception} thrown during the
* invocation.
*
* <p>Script's (or default) {@code Writer} is set to the {@code ScriptContext} of the {@code
* ScriptEngine} before the invocation.
*
* @param script the script that will be invoked
* @return an {@code Invocable} for the {@code script}, or {@code null} if none.
* @see #getWriters(ScriptWrapper)
* @see Invocable
*/
private Invocable invokeScriptImpl(ScriptWrapper script) {
ScriptEngine se = script.getEngine().getEngine();
Writer writer = getWriters(script);
se.getContext().setWriter(writer);
// Set the script name as a context attribute - this is used for script level variables
se.getContext().setAttribute(SCRIPT_NAME_ATT, script.getName(), ScriptContext.ENGINE_SCOPE);
reloadIfChangedOnDisk(script);
recordScriptCalledStats(script);
try {
se.eval(script.getContents());
} catch (Exception e) {
handleScriptException(script, writer, e);
} catch (NoClassDefFoundError | ExceptionInInitializerError e) {
if (e.getCause() instanceof Exception) {
handleScriptException(script, writer, (Exception) e.getCause());
} else {
handleUnspecifiedScriptError(script, writer, e.getMessage());
}
}
if (se instanceof Invocable) {
return (Invocable) se;
}
return null;
}
/**
* Invokes the given {@code script}, synchronously, handling any {@code Exception} thrown during
* the invocation.
*
* @param script the script that will be invoked/evaluated
* @return an {@code Invocable} for the {@code script}, or {@code null} if none.
* @throws ScriptException if the engine of the given {@code script} was not found.
* @see #invokeScript(ScriptWrapper)
* @see Invocable
*/
public Invocable invokeScriptWithOutAddOnLoader(ScriptWrapper script) throws ScriptException {
logger.debug("invokeScriptWithOutAddOnLoader " + script.getName());
preInvokeScript(script);
return invokeScriptImpl(script);
}
/**
* Handles exceptions thrown by scripts.
*
* <p>The given {@code exception} (if of type {@code ScriptException} the cause will be used
* instead) will be written to the writer(s) associated with the given {@code script}, moreover
* the script will be disabled and flagged that has an error.
*
* @param script the script that resulted in an exception, must not be {@code null}
* @param exception the exception thrown, must not be {@code null}
* @since 2.5.0
* @see #setEnabled(ScriptWrapper, boolean)
* @see #setError(ScriptWrapper, Exception)
* @see #handleFailedScriptInterface(ScriptWrapper, String)
* @see #handleScriptError(ScriptWrapper, String)
* @see ScriptException
*/
public void handleScriptException(ScriptWrapper script, Exception exception) {
handleScriptException(script, getWriters(script), exception);
}
/**
* Handles exceptions thrown by scripts.
*
* <p>The given {@code exception} (if of type {@code ScriptException} the cause will be used
* instead) will be written to the given {@code writer} and the given {@code script} will be
* disabled and flagged that has an error.
*
* @param script the script that resulted in an exception, must not be {@code null}
* @param writer the writer associated with the script, must not be {@code null}
* @param exception the exception thrown , must not be {@code null}
* @see #setError(ScriptWrapper, Exception)
* @see #setEnabled(ScriptWrapper, boolean)
* @see ScriptException
*/
private void handleScriptException(ScriptWrapper script, Writer writer, Exception exception) {
recordScriptFailedStats(script);
Exception cause = exception;
if (cause instanceof ScriptException && cause.getCause() instanceof Exception) {
// Dereference one level
cause = (Exception) cause.getCause();
}
try {
writer.append(cause.toString());
} catch (IOException ignore) {
logger.error(cause.getMessage(), cause);
}
this.setError(script, cause);
this.setEnabled(script, false);
}
/**
* Handles errors caused by scripts.
*
* <p>The given {@code error} will be written to the writer(s) associated with the given {@code
* script}, moreover the script will be disabled and flagged that has an error.
*
* @param script the script that caused the error, must not be {@code null}.
* @param error the error caused by the script, must not be {@code null}.
* @since 2.9.0
* @see #setEnabled(ScriptWrapper, boolean)
* @see #setError(ScriptWrapper, String)
* @see #handleScriptException(ScriptWrapper, Exception)
*/
public void handleScriptError(ScriptWrapper script, String error) {
recordScriptFailedStats(script);
try {
getWriters(script).append(error);
} catch (IOException ignore) {
// Nothing to do, callers should log the issue.
}
this.setError(script, error);
this.setEnabled(script, false);
}
/**
* Invokes the given {@code script}, synchronously, as a {@link TargetedScript}, handling any
* {@code Exception} thrown during the invocation.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons.
*
* @param script the script to invoke.
* @param msg the HTTP message to process.
* @since 2.2.0
* @see #getInterface(ScriptWrapper, Class)
*/
public void invokeTargetedScript(ScriptWrapper script, HttpMessage msg) {
validateScriptType(script, TYPE_TARGETED);
Writer writer = getWriters(script);
try {
// Dont need to check if enabled as it can only be invoked manually
TargetedScript s = this.getInterface(script, TargetedScript.class);
if (s != null) {
recordScriptCalledStats(script);
s.invokeWith(msg);
} else {
handleUnspecifiedScriptError(
script,
writer,
Constant.messages.getString("script.interface.targeted.error"));
}
} catch (Exception e) {
handleScriptException(script, writer, e);
}
}
/**
* Validates that the given {@code script} is of the given {@code scriptType}, throwing an
* {@code IllegalArgumentException} if not.
*
* @param script the script that will be checked, must not be {@code null}
* @param scriptType the expected type of the script, must not be {@code null}
* @throws IllegalArgumentException if the given {@code script} is not the given {@code
* scriptType}.
* @see ScriptWrapper#getTypeName()
*/
private static void validateScriptType(ScriptWrapper script, String scriptType)
throws IllegalArgumentException {
if (!scriptType.equals(script.getTypeName())) {
throw new IllegalArgumentException(
"Script "
+ script.getName()
+ " is not a '"
+ scriptType
+ "' script: "
+ script.getTypeName());
}
}
/**
* Handles a failed attempt to convert a script into an interface.
*
* <p>The given {@code errorMessage} will be written to the writer(s) associated with the given
* {@code script}, moreover it will be disabled and flagged that has an error.
*
* @param script the script that resulted in an exception, must not be {@code null}
* @param errorMessage the message that will be written to the writer(s)
* @since 2.5.0
* @see #setEnabled(ScriptWrapper, boolean)
* @see #setError(ScriptWrapper, Exception)
* @see #handleScriptException(ScriptWrapper, Exception)
*/
public void handleFailedScriptInterface(ScriptWrapper script, String errorMessage) {
handleUnspecifiedScriptError(script, getWriters(script), errorMessage);
}
/**
* Handles an unspecified error that occurred while calling or invoking a script.
*
* <p>The given {@code errorMessage} will be written to the given {@code writer} and the given
* {@code script} will be disabled and flagged that has an error.
*
* @param script the script that failed to be called/invoked, must not be {@code null}
* @param writer the writer associated with the script, must not be {@code null}
* @param errorMessage the message that will be written to the given {@code writer}
* @see #setError(ScriptWrapper, String)
* @see #setEnabled(ScriptWrapper, boolean)
*/
private void handleUnspecifiedScriptError(
ScriptWrapper script, Writer writer, String errorMessage) {
recordScriptFailedStats(script);
try {
writer.append(errorMessage);
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to append script error message because of an exception:", e);
}
logger.warn("Failed to append error message: " + errorMessage);
}
this.setError(script, errorMessage);
this.setEnabled(script, false);
}
/**
* Invokes the given {@code script}, synchronously, as a {@link ProxyScript}, handling any
* {@code Exception} thrown during the invocation.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons.
*
* @param script the script to invoke.
* @param msg the HTTP message being proxied.
* @param request {@code true} if processing the request, {@code false} otherwise.
* @return {@code true} if the request should be forward to the server, {@code false} otherwise.
* @since 2.2.0
* @see #getInterface(ScriptWrapper, Class)
*/
public boolean invokeProxyScript(ScriptWrapper script, HttpMessage msg, boolean request) {
validateScriptType(script, TYPE_PROXY);
Writer writer = getWriters(script);
try {
// Dont need to check if enabled as it can only be invoked manually
ProxyScript s = this.getInterface(script, ProxyScript.class);
if (s != null) {
recordScriptCalledStats(script);
if (request) {
return s.proxyRequest(msg);
} else {
return s.proxyResponse(msg);
}
} else {
handleUnspecifiedScriptError(
script,
writer,
Constant.messages.getString("script.interface.proxy.error"));
}
} catch (Exception e) {
handleScriptException(script, writer, e);
}
// Return true so that the request is submitted - if we returned false all proxying would
// fail on script errors
return true;
}
/**
* Invokes the given {@code script}, synchronously, as a {@link HttpSenderScript}, handling any
* {@code Exception} thrown during the invocation.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons.
*
* @param script the script to invoke.
* @param msg the HTTP message being sent/received.
* @param initiator the initiator of the request.
* @param sender the sender of the given {@code HttpMessage}.
* @param request {@code true} if processing the request, {@code false} otherwise.
* @since 2.4.1
* @see #getInterface(ScriptWrapper, Class)
*/
public void invokeSenderScript(
ScriptWrapper script,
HttpMessage msg,
int initiator,
HttpSender sender,
boolean request) {
validateScriptType(script, TYPE_HTTP_SENDER);
Writer writer = getWriters(script);
try {
HttpSenderScript senderScript = this.getInterface(script, HttpSenderScript.class);
if (senderScript != null) {
recordScriptCalledStats(script);
if (request) {
senderScript.sendingRequest(msg, initiator, new HttpSenderScriptHelper(sender));
} else {
senderScript.responseReceived(
msg, initiator, new HttpSenderScriptHelper(sender));
}
} else {
handleUnspecifiedScriptError(
script,
writer,
Constant.messages.getString("script.interface.httpsender.error"));
}
} catch (Exception e) {
handleScriptException(script, writer, e);
}
}
public void setChanged(ScriptWrapper script, boolean changed) {
script.setChanged(changed);
ScriptNode node = this.getTreeModel().getNodeForScript(script);
if (node != null) {
if (node.getNodeName().equals(script.getName())) {
// The name is the same
this.getTreeModel().nodeStructureChanged(script);
} else {
// The name has changed
node.setNodeName(script.getName());
this.getTreeModel().nodeStructureChanged(node.getParent());
}
}
notifyScriptChanged(script);
}
/**
* Notifies the {@code ScriptEventListener}s that the given {@code script} was changed.
*
* @param script the script that was changed, must not be {@code null}
* @see #listeners
* @see ScriptEventListener#scriptChanged(ScriptWrapper)
*/
private void notifyScriptChanged(ScriptWrapper script) {
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptChanged(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
public void setEnabled(ScriptWrapper script, boolean enabled) {
if (!script.getType().isEnableable()) {
return;
}
if (enabled && script.getEngine() == null) {
return;
}
script.setEnabled(enabled);
this.getTreeModel().nodeStructureChanged(script);
notifyScriptChanged(script);
}
public void setError(ScriptWrapper script, String details) {
script.setError(true);
script.setLastErrorDetails(details);
script.setLastOutput(details);
this.getTreeModel().nodeStructureChanged(script);
for (ScriptEventListener listener : this.listeners) {
try {
listener.scriptError(script);
} catch (Exception e) {
logScriptEventListenerException(listener, script, e);
}
}
}
public void setError(ScriptWrapper script, Exception e) {
script.setLastException(e);
setError(script, e.getMessage());
}
public void addListener(ScriptEventListener listener) {
this.listeners.add(listener);
}
public void removeListener(ScriptEventListener listener) {
this.listeners.remove(listener);
}
/**
* Adds the given writer.
*
* <p>It will be written to each time a script writes some output.
*
* @param writer the writer to add.
* @see #removeWriter(Writer)
* @see #addScriptOutputListener(ScriptOutputListener)
*/
public void addWriter(Writer writer) {
this.writers.addWriter(writer);
}
/**
* Removes the given writer.
*
* @param writer the writer to remove.
* @see #addWriter(Writer)
*/
public void removeWriter(Writer writer) {
this.writers.removeWriter(writer);
}
/**
* Adds the given script output listener.
*
* @param listener the listener to add.
* @since 2.8.0
* @throws NullPointerException if the given listener is {@code null}.
* @see #removeScriptOutputListener(ScriptOutputListener)
*/
public void addScriptOutputListener(ScriptOutputListener listener) {
outputListeners.add(
Objects.requireNonNull(listener, "The parameter listener must not be null."));
}
/**
* Removes the given script output listener.
*
* @param listener the listener to remove.
* @since 2.8.0
* @throws NullPointerException if the given listener is {@code null}.
* @see #addScriptOutputListener(ScriptOutputListener)
*/
public void removeScriptOutputListener(ScriptOutputListener listener) {
outputListeners.remove(
Objects.requireNonNull(listener, "The parameter listener must not be null."));
}
public ScriptUI getScriptUI() {
return scriptUI;
}
public void setScriptUI(ScriptUI scriptUI) {
if (this.scriptUI != null) {
throw new InvalidParameterException(
"A script UI has already been set - only one is supported");
}
this.scriptUI = scriptUI;
}
public void removeScriptUI() {
this.scriptUI = null;
}
/**
* Creates a scripts cache.
*
* @param <T> the target interface.
* @param config the cache configuration
* @return the scripts cache.
* @since 2.10.0
*/
public <T> ScriptsCache<T> createScriptsCache(Configuration<T> config) {
return new ScriptsCache<>(this, config);
}
/**
* Gets the interface {@code class1} from the given {@code script}. Might return {@code null} if
* the {@code script} does not implement the interface.
*
* <p>First tries to get the interface directly from the {@code script} by calling the method
* {@code ScriptWrapper.getInterface(Class)}, if it returns {@code null} the interface will be
* extracted from the script after invoking it, using the method {@code
* Invocable.getInterface(Class)}.
*
* <p>The context class loader of caller thread is replaced with the class loader {@code
* AddOnLoader} to allow the script to access classes of add-ons. If this behaviour is not
* desired call the method {@code getInterfaceWithOutAddOnLoader(} instead.
*
* @param script the script that will be invoked
* @param class1 the interface that will be obtained from the script
* @return the interface implemented by the script, or {@code null} if the {@code script} does
* not implement the interface.
* @throws ScriptException if the engine of the given {@code script} was not found.
* @throws IOException if an error occurred while obtaining the interface directly from the
* script ( {@code ScriptWrapper.getInterface(Class)})
* @see #getInterfaceWithOutAddOnLoader(ScriptWrapper, Class)
* @see ScriptWrapper#getInterface(Class)
* @see Invocable#getInterface(Class)
*/
public <T> T getInterface(ScriptWrapper script, Class<T> class1)
throws ScriptException, IOException {
ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(ExtensionFactory.getAddOnLoader());
try {
T iface = script.getInterface(class1);
if (iface != null) {
// the script wrapper has overridden the usual scripting mechanism
return iface;
}
} finally {
Thread.currentThread().setContextClassLoader(previousContextClassLoader);
}
if (script.isRunnableStandalone()) {
return null;
}
Invocable invocable = invokeScript(script);
if (invocable != null) {
return invocable.getInterface(class1);
}
return null;
}
/**
* Gets the interface {@code clazz} from the given {@code script}. Might return {@code null} if
* the {@code script} does not implement the interface.
*
* <p>First tries to get the interface directly from the {@code script} by calling the method
* {@code ScriptWrapper.getInterface(Class)}, if it returns {@code null} the interface will be
* extracted from the script after invoking it, using the method {@code
* Invocable.getInterface(Class)}.
*
* @param script the script that will be invoked
* @param clazz the interface that will be obtained from the script
* @return the interface implemented by the script, or {@code null} if the {@code script} does
* not implement the interface.
* @throws ScriptException if the engine of the given {@code script} was not found.
* @throws IOException if an error occurred while obtaining the interface directly from the
* script ( {@code ScriptWrapper.getInterface(Class)})
* @see #getInterface(ScriptWrapper, Class)
* @see ScriptWrapper#getInterface(Class)
* @see Invocable#getInterface(Class)
*/
public <T> T getInterfaceWithOutAddOnLoader(ScriptWrapper script, Class<T> clazz)
throws ScriptException, IOException {
T iface = script.getInterface(clazz);
if (iface != null) {
// the script wrapper has overridden the usual scripting mechanism
return iface;
}
return invokeScriptWithOutAddOnLoader(script).getInterface(clazz);
}
@Override
public List<String> getUnsavedResources() {
// Report all of the unsaved scripts
List<String> list = new ArrayList<>();
for (ScriptType type : this.getScriptTypes()) {
for (ScriptWrapper script : this.getScripts(type)) {
if (script.isChanged()) {
list.add(Constant.messages.getString("script.resource", script.getName()));
}
}
}
return list;
}
private void openCmdLineFile(File f) throws IOException, ScriptException {
if (!f.exists()) {
CommandLine.info(
Constant.messages.getString("script.cmdline.nofile", f.getAbsolutePath()));
return;
}
if (!f.canRead()) {
CommandLine.info(
Constant.messages.getString("script.cmdline.noread", f.getAbsolutePath()));
return;
}
int dotIndex = f.getName().lastIndexOf(".");
if (dotIndex <= 0) {
CommandLine.info(
Constant.messages.getString("script.cmdline.noext", f.getAbsolutePath()));
return;
}
String ext = f.getName().substring(dotIndex + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName == null) {
CommandLine.info(Constant.messages.getString("script.cmdline.noengine", ext));
return;
}
ScriptWrapper sw =
new ScriptWrapper(
f.getName(), "", engineName, this.getScriptType(TYPE_STANDALONE), true, f);
this.loadScript(sw);
this.addScript(sw);
if (!hasView()) {
// Only invoke if run from the command line
// if the GUI is present then its up to the user to invoke it
this.invokeScript(sw);
}
}
@Override
public void execute(CommandLineArgument[] args) {
if (args[ARG_SCRIPT_IDX].isEnabled()) {
for (String script : args[ARG_SCRIPT_IDX].getArguments()) {
try {
openCmdLineFile(new File(script));
} catch (Exception e) {
CommandLine.error(e.getMessage(), e);
}
}
}
}
private CommandLineArgument[] getCommandLineArguments() {
arguments[ARG_SCRIPT_IDX] =
new CommandLineArgument(
"-script",
1,
null,
"",
"-script <script> "
+ Constant.messages.getString("script.cmdline.help"));
return arguments;
}
@Override
public boolean handleFile(File file) {
int dotIndex = file.getName().lastIndexOf(".");
if (dotIndex <= 0) {
// No extension, cant work out which engine
return false;
}
String ext = file.getName().substring(dotIndex + 1);
String engineName = this.getEngineNameForExtension(ext);
if (engineName == null) {
// No engine for this extension, we cant handle this
return false;
}
try {
openCmdLineFile(file);
} catch (Exception e) {
logger.error(e.getMessage(), e);
return false;
}
return true;
}
@Override
public List<String> getHandledExtensions() {
// The list of all of the script extensions that can be handled from the command line
List<String> exts = new ArrayList<>();
for (ScriptEngineWrapper sew : this.engineWrappers) {
exts.addAll(sew.getExtensions());
}
return exts;
}
/** No database tables used, so all supported */
@Override
public boolean supportsDb(String type) {
return true;
}
/**
* Gets the script icon.
*
* <p>Should be called/used only when in view mode.
*
* @return the script icon, never {@code null}.
* @since 2.7.0
*/
public static ImageIcon getScriptIcon() {
if (scriptIcon == null) {
scriptIcon =
new ImageIcon(ExtensionScript.class.getResource("/resource/icon/16/059.png"));
}
return scriptIcon;
}
private static class ClearScriptVarsOnSessionChange implements SessionChangedListener {
@Override
public void sessionChanged(Session session) {}
@Override
public void sessionAboutToChange(Session session) {
ScriptVars.clear();
}
@Override
public void sessionScopeChanged(Session session) {}
@Override
public void sessionModeChanged(Mode mode) {}
}
/** A {@code Writer} that notifies {@link ScriptOutputListener}s when writing. */
private static class ScriptWriter extends Writer {
private final ScriptWrapper script;
private final Writer delegatee;
private final List<ScriptOutputListener> outputListeners;
public ScriptWriter(
ScriptWrapper script,
Writer delegatee,
List<ScriptOutputListener> outputListeners) {
this.script = Objects.requireNonNull(script);
this.delegatee = Objects.requireNonNull(delegatee);
this.outputListeners = Objects.requireNonNull(outputListeners);
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
delegatee.write(cbuf, off, len);
if (!outputListeners.isEmpty()) {
String output = new String(cbuf, off, len);
outputListeners.forEach(e -> e.output(script, output));
}
}
@Override
public void flush() throws IOException {
delegatee.flush();
}
@Override
public void close() throws IOException {
delegatee.close();
}
}
public static void recordScriptCalledStats(ScriptWrapper sw) {
if (sw != null) {
Stats.incCounter("stats.script.call." + sw.getEngineName() + "." + sw.getTypeName());
}
}
public static void recordScriptFailedStats(ScriptWrapper sw) {
if (sw != null) {
Stats.incCounter("stats.script.error." + sw.getEngineName() + "." + sw.getTypeName());
}
}
}
|
Pass Control, Model, View singletons to scripts
Signed-off-by: ricekot <64b2b6d12bfe4baae7dad3d018f8cbf6b0e7a044@ricekot.com>
|
zap/src/main/java/org/zaproxy/zap/extension/script/ExtensionScript.java
|
Pass Control, Model, View singletons to scripts
|
|
Java
|
apache-2.0
|
b854ae1697dfc84eb0f5a5e67c703864e731f7a2
| 0
|
nhl/bootique-jetty,nhl/bootique-jetty
|
package io.bootique.jetty.server;
import io.bootique.annotation.BQConfig;
import io.bootique.annotation.BQConfigProperty;
import io.bootique.jetty.JettyModuleExtender;
import io.bootique.jetty.MappedFilter;
import io.bootique.jetty.MappedListener;
import io.bootique.jetty.MappedServlet;
import io.bootique.jetty.connector.ConnectorFactory;
import io.bootique.jetty.connector.HttpConnectorFactory;
import io.bootique.resource.FolderResourceFactory;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
@BQConfig("Configures embedded Jetty server, including servlet spec objects, web server root location, connectors, " +
"thread pool parameters, etc.")
public class ServerFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerFactory.class);
protected List<ConnectorFactory> connectors;
protected String context;
protected int idleThreadTimeout;
protected Map<String, FilterFactory> filters;
protected int maxThreads;
protected int minThreads;
protected int maxQueuedRequests;
protected Map<String, ServletFactory> servlets;
protected boolean sessions;
private Map<String, String> params;
private FolderResourceFactory staticResourceBase;
private boolean compression;
private boolean compactPath;
// defined as "int" in Jetty, so we should not exceed max int
private int maxFormContentSize;
private int maxFormKeys;
/**
* Maintains a mapping between erroneous response's Status Code and the page (URL) which will be used to handle it further.
*/
private Map<Integer, String> errorPages;
public ServerFactory() {
this.context = "/";
this.minThreads = 4;
this.maxThreads = 1024;
this.maxQueuedRequests = 1024;
this.idleThreadTimeout = 60000;
this.sessions = true;
this.compression = true;
this.compactPath = false;
}
public Server createServer(Set<MappedServlet> servlets, Set<MappedFilter> filters, Set<MappedListener> listeners) {
ThreadPool threadPool = createThreadPool();
Server server = new Server(threadPool);
server.setStopAtShutdown(true);
server.setStopTimeout(1000L);
server.setHandler(createHandler(servlets, filters, listeners));
if (maxFormContentSize > 0) {
server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", maxFormContentSize);
}
if (maxFormKeys > 0) {
server.setAttribute("org.eclipse.jetty.server.Request.maxFormKeys", maxFormKeys);
}
createRequestLog(server);
Collection<ConnectorFactory> connectorFactories = connectorFactories(server);
Collection<ConnectorDescriptor> connectorDescriptors = new ArrayList<>(2);
if (connectorFactories.isEmpty()) {
LOGGER.warn("Jetty starts with no connectors configured. Is that expected?");
} else {
connectorFactories.forEach(cf -> {
NetworkConnector connector = cf.createConnector(server);
server.addConnector(connector);
connectorDescriptors.add(new ConnectorDescriptor(connector));
});
}
server.addLifeCycleListener(new ServerLifecycleLogger(connectorDescriptors, context));
return server;
}
protected Handler createHandler(Set<MappedServlet> servlets,
Set<MappedFilter> filters,
Set<MappedListener> listeners) {
int options = 0;
if (sessions) {
options |= ServletContextHandler.SESSIONS;
}
ServletContextHandler handler = new ServletContextHandler(options);
handler.setContextPath(context);
handler.setCompactPath(compactPath);
if (params != null) {
params.forEach((k, v) -> handler.setInitParameter(k, v));
}
if (staticResourceBase != null) {
handler.setResourceBase(staticResourceBase.getUrl().toExternalForm());
}
if (compression) {
handler.setGzipHandler(createGzipHandler());
}
if (errorPages != null) {
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorPages.forEach((statusCode, location) -> errorHandler.addErrorPage(statusCode, location));
handler.setErrorHandler(errorHandler);
}
installListeners(handler, listeners);
installServlets(handler, servlets);
installFilters(handler, filters);
return handler;
}
protected GzipHandler createGzipHandler() {
GzipHandler gzipHandler = new GzipHandler();
gzipHandler.setCheckGzExists(false);
return gzipHandler;
}
protected void installServlets(ServletContextHandler handler, Set<MappedServlet> servlets) {
servlets.forEach(mappedServlet -> getServletFactory(mappedServlet.getName()).createAndAddJettyServlet(handler,
mappedServlet));
}
protected ServletFactory getServletFactory(String name) {
ServletFactory factory = null;
if (servlets != null && name != null) {
factory = servlets.get(name);
}
return factory != null ? factory : new ServletFactory();
}
protected void installFilters(ServletContextHandler handler, Set<MappedFilter> filters) {
sortedFilters(filters).forEach(mappedFilter -> getFilterFactory(mappedFilter.getName())
.createAndAddJettyFilter(handler, mappedFilter));
}
protected FilterFactory getFilterFactory(String name) {
FilterFactory factory = null;
if (filters != null && name != null) {
factory = filters.get(name);
}
return factory != null ? factory : new FilterFactory();
}
protected void installListeners(ServletContextHandler handler, Set<MappedListener> listeners) {
if (listeners.isEmpty()) {
return;
}
Optional<SessionHandler> sessionHandler = sessions
? Optional.of(handler.getSessionHandler()) : Optional.empty();
sortedListeners(listeners).forEach(listener -> {
LOGGER.info("Adding listener {}", listener.getListener().getClass().getName());
// context handler and session handler would do their own listener filtering
// passing every listener down to them without trying to second guess
handler.addEventListener(listener.getListener());
sessionHandler.ifPresent(sh -> sh.addEventListener(listener.getListener()));
});
}
private List<MappedFilter> sortedFilters(Set<MappedFilter> unsorted) {
List<MappedFilter> sorted = new ArrayList<>(unsorted);
Collections.sort(sorted, Comparator.comparing(MappedFilter::getOrder));
return sorted;
}
private List<MappedListener> sortedListeners(Set<MappedListener> unsorted) {
List<MappedListener> sorted = new ArrayList<>(unsorted);
Collections.sort(sorted, Comparator.comparing(MappedListener::getOrder));
return sorted;
}
protected Collection<ConnectorFactory> connectorFactories(Server server) {
Collection<ConnectorFactory> connectorFactories = new ArrayList<>();
if (this.connectors != null) {
connectorFactories.addAll(this.connectors);
}
// add default connector if none are configured
if (connectorFactories.isEmpty()) {
connectorFactories.add(new HttpConnectorFactory());
}
return connectorFactories;
}
protected QueuedThreadPool createThreadPool() {
BlockingQueue<Runnable> queue = new BlockingArrayQueue<>(minThreads, maxThreads, maxQueuedRequests);
QueuedThreadPool threadPool = createThreadPool(queue);
threadPool.setName("bootique-http");
return threadPool;
}
protected QueuedThreadPool createThreadPool(BlockingQueue<Runnable> queue) {
return new QueuedThreadPool(maxThreads, minThreads, idleThreadTimeout, queue);
}
protected void createRequestLog(Server server) {
Logger logger = LoggerFactory.getLogger(RequestLogger.class);
if (logger.isInfoEnabled()) {
server.setRequestLog(new RequestLogger());
}
}
/**
* @return a List of server connectors, each listening on its own unique port.
* @since 0.18
*/
public List<ConnectorFactory> getConnectors() {
return connectors;
}
/**
* Sets a list of connector factories for this server. Each connectors would listen on its own unique port.
*
* @param connectors a list of preconfigured connector factories.
* @since 0.18
*/
@BQConfigProperty("A list of objects specifying properties of the server network connectors.")
public void setConnectors(List<ConnectorFactory> connectors) {
this.connectors = connectors;
}
@BQConfigProperty("A map of servlet configurations by servlet name. ")
public void setServlets(Map<String, ServletFactory> servlets) {
this.servlets = servlets;
}
@BQConfigProperty("A map of servlet Filter configurations by filter name.")
public void setFilters(Map<String, FilterFactory> filters) {
this.filters = filters;
}
/**
* @return web application context path.
* @since 0.15
*/
public String getContext() {
return context;
}
@BQConfigProperty("Web application context path. Default is '/'.")
public void setContext(String context) {
this.context = context;
}
/**
* @return a period in milliseconds specifying how long it takes until an
* idle thread is terminated.
* @since 0.15
*/
public int getIdleThreadTimeout() {
return idleThreadTimeout;
}
@BQConfigProperty("A period in milliseconds specifying how long until an idle thread is terminated. ")
public void setIdleThreadTimeout(int idleThreadTimeout) {
this.idleThreadTimeout = idleThreadTimeout;
}
/**
* @return a maximum number of requests to queue if the thread pool is busy.
* @since 0.15
*/
public int getMaxQueuedRequests() {
return maxQueuedRequests;
}
@BQConfigProperty("Maximum number of requests to queue if the thread pool is busy. If this number is exceeded, " +
"the server will start dropping requests.")
public void setMaxQueuedRequests(int maxQueuedRequests) {
this.maxQueuedRequests = maxQueuedRequests;
}
/**
* @return a maximum number of request processing threads in the pool.
* @since 0.15
*/
public int getMaxThreads() {
return maxThreads;
}
@BQConfigProperty("Maximum number of request processing threads in the pool.")
public void setMaxThreads(int maxConnectorThreads) {
this.maxThreads = maxConnectorThreads;
}
/**
* @return an initial number of request processing threads in the pool.
* @since 0.15
*/
public int getMinThreads() {
return minThreads;
}
@BQConfigProperty("Minimal number of request processing threads in the pool.")
public void setMinThreads(int minThreads) {
this.minThreads = minThreads;
}
/**
* @return a map of arbitrary key/value parameters that are used as "init"
* parameters of the ServletContext.
* @since 0.15
*/
public Map<String, String> getParams() {
return params != null ? Collections.unmodifiableMap(params) : Collections.emptyMap();
}
/**
* @param params a map of context init parameters.
* @since 0.13
*/
@BQConfigProperty("A map of application-specific key/value parameters that are used as \"init\" parameters of the " +
"ServletContext.")
public void setParams(Map<String, String> params) {
this.params = params;
}
/**
* @return a boolean specifying whether servlet sessions should be supported
* by Jetty.
* @since 0.15
*/
public boolean isSessions() {
return sessions;
}
@BQConfigProperty("A boolean specifying whether servlet sessions should be supported by Jetty. The default is 'true'")
public void setSessions(boolean sessions) {
this.sessions = sessions;
}
/**
* @return a base location for resources of the Jetty context.
* @since 0.15
*/
public FolderResourceFactory getStaticResourceBase() {
return staticResourceBase;
}
/**
* Sets a base location for resources of the Jetty context. Used by static
* resource servlets, including the "default" servlet. The value can be a
* file path or a URL, as well as a special URL starting with "classpath:".
* <p>
* It can be optionally overridden by DefaultServlet configuration.
* <p>
* For security reasons this has to be set explicitly. There's no default.
*
* @param staticResourceBase A base location for resources of the Jetty context, that can
* be a file path or a URL, as well as a special URL starting
* with "classpath:".
* @see JettyModuleExtender#useDefaultServlet()
* @see JettyModuleExtender#addStaticServlet(String, String...)
* @see <a href=
* "http://download.eclipse.org/jetty/9.3.7.v20160115/apidocs/org/eclipse/jetty/servlet/DefaultServlet.html">
* DefaultServlet</a>.
* @since 0.13
*/
@BQConfigProperty("Defines a base location for resources of the Jetty context. It can be a filesystem path, a URL " +
"or a special \"classpath:\" URL (giving the ability to bundle resources in the app, not unlike a JavaEE " +
".war file). This setting only makes sense when some form of \"default\" servlet is in use, that will be " +
"responsible for serving static resources. See JettyModule.contributeStaticServlet(..) or " +
"JettyModule.contributeDefaultServlet(..). ")
public void setStaticResourceBase(FolderResourceFactory staticResourceBase) {
this.staticResourceBase = staticResourceBase;
}
/**
* @return whether content compression is supported.
* @since 0.15
*/
public boolean isCompression() {
return compression;
}
/**
* Sets whether compression whether gzip compression should be supported.
* When true, responses will be compressed if a client requests it via
* "Accept-Encoding:" header. Default is true.
*
* @param compression whether gzip compression should be supported.
* @since 0.15
*/
@BQConfigProperty("A boolean specifying whether gzip compression should be supported. When enabled " +
"responses will be compressed if a client indicates it supports compression via " +
"\"Accept-Encoding: gzip\" header. Default value is 'true'.")
public void setCompression(boolean compression) {
this.compression = compression;
}
/**
* Compact URLs with multiple '/'s with a single '/'.
*
* @param compactPath Compact URLs with multiple '/'s with a single '/'. Default value is 'false'
* @since 0.26
*/
@BQConfigProperty("Replaces multiple '/'s with a single '/' in URL. Default value is 'false'.")
public void setCompactPath(boolean compactPath) { this.compactPath = compactPath; }
/**
* Sets the maximum size of submitted forms in bytes. Default is 200000 (~195K).
*
* @param maxFormContentSize maximum size of submitted forms in bytes. Default is 200000 (~195K)
* @since 0.22
*/
@BQConfigProperty("Maximum size of submitted forms in bytes. Default is 200000 (~195K).")
public void setMaxFormContentSize(int maxFormContentSize) {
this.maxFormContentSize = maxFormContentSize;
}
/**
* Sets the maximum number of form fields. Default is 1000.
*
* @param maxFormKeys maximum number of form fields. Default is 1000.
* @since 0.22
*/
@BQConfigProperty("Maximum number of form fields. Default is 1000.")
public void setMaxFormKeys(int maxFormKeys) {
this.maxFormKeys = maxFormKeys;
}
/**
* @return a potentially null map of error pages configuration.
* @since 0.24
*/
public Map<Integer, String> getErrorPages() {
return errorPages;
}
/**
* Sets mappings between HTTP status codes and corresponding pages which will be returned to the user instead.
*
* @param errorPages map where keys are HTTP status codes and values are page URLs which will be used to handle them
* @since 0.24
*/
@BQConfigProperty("A map specifying a mapping between HTTP status codes and pages (URLs) which will be used as their handlers. If no mapping is specified then standard error handler is used.")
public void setErrorPages(Map<Integer, String> errorPages) {
this.errorPages = errorPages;
}
}
|
bootique-jetty/src/main/java/io/bootique/jetty/server/ServerFactory.java
|
package io.bootique.jetty.server;
import io.bootique.annotation.BQConfig;
import io.bootique.annotation.BQConfigProperty;
import io.bootique.jetty.JettyModuleExtender;
import io.bootique.jetty.MappedFilter;
import io.bootique.jetty.MappedListener;
import io.bootique.jetty.MappedServlet;
import io.bootique.jetty.connector.ConnectorFactory;
import io.bootique.jetty.connector.HttpConnectorFactory;
import io.bootique.resource.FolderResourceFactory;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
@BQConfig("Configures embedded Jetty server, including servlet spec objects, web server root location, connectors, " +
"thread pool parameters, etc.")
public class ServerFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerFactory.class);
protected List<ConnectorFactory> connectors;
protected String context;
protected int idleThreadTimeout;
protected Map<String, FilterFactory> filters;
protected int maxThreads;
protected int minThreads;
protected int maxQueuedRequests;
protected Map<String, ServletFactory> servlets;
protected boolean sessions;
private Map<String, String> params;
private FolderResourceFactory staticResourceBase;
private boolean compression;
// defined as "int" in Jetty, so we should not exceed max int
private int maxFormContentSize;
private int maxFormKeys;
/**
* Maintains a mapping between erroneous response's Status Code and the page (URL) which will be used to handle it further.
*/
private Map<Integer, String> errorPages;
public ServerFactory() {
this.context = "/";
this.minThreads = 4;
this.maxThreads = 1024;
this.maxQueuedRequests = 1024;
this.idleThreadTimeout = 60000;
this.sessions = true;
this.compression = true;
}
public Server createServer(Set<MappedServlet> servlets, Set<MappedFilter> filters, Set<MappedListener> listeners) {
ThreadPool threadPool = createThreadPool();
Server server = new Server(threadPool);
server.setStopAtShutdown(true);
server.setStopTimeout(1000L);
server.setHandler(createHandler(servlets, filters, listeners));
if (maxFormContentSize > 0) {
server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", maxFormContentSize);
}
if (maxFormKeys > 0) {
server.setAttribute("org.eclipse.jetty.server.Request.maxFormKeys", maxFormKeys);
}
createRequestLog(server);
Collection<ConnectorFactory> connectorFactories = connectorFactories(server);
Collection<ConnectorDescriptor> connectorDescriptors = new ArrayList<>(2);
if (connectorFactories.isEmpty()) {
LOGGER.warn("Jetty starts with no connectors configured. Is that expected?");
} else {
connectorFactories.forEach(cf -> {
NetworkConnector connector = cf.createConnector(server);
server.addConnector(connector);
connectorDescriptors.add(new ConnectorDescriptor(connector));
});
}
server.addLifeCycleListener(new ServerLifecycleLogger(connectorDescriptors, context));
return server;
}
protected Handler createHandler(Set<MappedServlet> servlets,
Set<MappedFilter> filters,
Set<MappedListener> listeners) {
int options = 0;
if (sessions) {
options |= ServletContextHandler.SESSIONS;
}
ServletContextHandler handler = new ServletContextHandler(options);
handler.setContextPath(context);
if (params != null) {
params.forEach((k, v) -> handler.setInitParameter(k, v));
}
if (staticResourceBase != null) {
handler.setResourceBase(staticResourceBase.getUrl().toExternalForm());
}
if (compression) {
handler.setGzipHandler(createGzipHandler());
}
if (errorPages != null) {
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorPages.forEach((statusCode, location) -> errorHandler.addErrorPage(statusCode, location));
handler.setErrorHandler(errorHandler);
}
installListeners(handler, listeners);
installServlets(handler, servlets);
installFilters(handler, filters);
return handler;
}
protected GzipHandler createGzipHandler() {
GzipHandler gzipHandler = new GzipHandler();
gzipHandler.setCheckGzExists(false);
return gzipHandler;
}
protected void installServlets(ServletContextHandler handler, Set<MappedServlet> servlets) {
servlets.forEach(mappedServlet -> getServletFactory(mappedServlet.getName()).createAndAddJettyServlet(handler,
mappedServlet));
}
protected ServletFactory getServletFactory(String name) {
ServletFactory factory = null;
if (servlets != null && name != null) {
factory = servlets.get(name);
}
return factory != null ? factory : new ServletFactory();
}
protected void installFilters(ServletContextHandler handler, Set<MappedFilter> filters) {
sortedFilters(filters).forEach(mappedFilter -> getFilterFactory(mappedFilter.getName())
.createAndAddJettyFilter(handler, mappedFilter));
}
protected FilterFactory getFilterFactory(String name) {
FilterFactory factory = null;
if (filters != null && name != null) {
factory = filters.get(name);
}
return factory != null ? factory : new FilterFactory();
}
protected void installListeners(ServletContextHandler handler, Set<MappedListener> listeners) {
if (listeners.isEmpty()) {
return;
}
Optional<SessionHandler> sessionHandler = sessions
? Optional.of(handler.getSessionHandler()) : Optional.empty();
sortedListeners(listeners).forEach(listener -> {
LOGGER.info("Adding listener {}", listener.getListener().getClass().getName());
// context handler and session handler would do their own listener filtering
// passing every listener down to them without trying to second guess
handler.addEventListener(listener.getListener());
sessionHandler.ifPresent(sh -> sh.addEventListener(listener.getListener()));
});
}
private List<MappedFilter> sortedFilters(Set<MappedFilter> unsorted) {
List<MappedFilter> sorted = new ArrayList<>(unsorted);
Collections.sort(sorted, Comparator.comparing(MappedFilter::getOrder));
return sorted;
}
private List<MappedListener> sortedListeners(Set<MappedListener> unsorted) {
List<MappedListener> sorted = new ArrayList<>(unsorted);
Collections.sort(sorted, Comparator.comparing(MappedListener::getOrder));
return sorted;
}
protected Collection<ConnectorFactory> connectorFactories(Server server) {
Collection<ConnectorFactory> connectorFactories = new ArrayList<>();
if (this.connectors != null) {
connectorFactories.addAll(this.connectors);
}
// add default connector if none are configured
if (connectorFactories.isEmpty()) {
connectorFactories.add(new HttpConnectorFactory());
}
return connectorFactories;
}
protected QueuedThreadPool createThreadPool() {
BlockingQueue<Runnable> queue = new BlockingArrayQueue<>(minThreads, maxThreads, maxQueuedRequests);
QueuedThreadPool threadPool = createThreadPool(queue);
threadPool.setName("bootique-http");
return threadPool;
}
protected QueuedThreadPool createThreadPool(BlockingQueue<Runnable> queue) {
return new QueuedThreadPool(maxThreads, minThreads, idleThreadTimeout, queue);
}
protected void createRequestLog(Server server) {
Logger logger = LoggerFactory.getLogger(RequestLogger.class);
if (logger.isInfoEnabled()) {
server.setRequestLog(new RequestLogger());
}
}
/**
* @return a List of server connectors, each listening on its own unique port.
* @since 0.18
*/
public List<ConnectorFactory> getConnectors() {
return connectors;
}
/**
* Sets a list of connector factories for this server. Each connectors would listen on its own unique port.
*
* @param connectors a list of preconfigured connector factories.
* @since 0.18
*/
@BQConfigProperty("A list of objects specifying properties of the server network connectors.")
public void setConnectors(List<ConnectorFactory> connectors) {
this.connectors = connectors;
}
@BQConfigProperty("A map of servlet configurations by servlet name. ")
public void setServlets(Map<String, ServletFactory> servlets) {
this.servlets = servlets;
}
@BQConfigProperty("A map of servlet Filter configurations by filter name.")
public void setFilters(Map<String, FilterFactory> filters) {
this.filters = filters;
}
/**
* @return web application context path.
* @since 0.15
*/
public String getContext() {
return context;
}
@BQConfigProperty("Web application context path. Default is '/'.")
public void setContext(String context) {
this.context = context;
}
/**
* @return a period in milliseconds specifying how long it takes until an
* idle thread is terminated.
* @since 0.15
*/
public int getIdleThreadTimeout() {
return idleThreadTimeout;
}
@BQConfigProperty("A period in milliseconds specifying how long until an idle thread is terminated. ")
public void setIdleThreadTimeout(int idleThreadTimeout) {
this.idleThreadTimeout = idleThreadTimeout;
}
/**
* @return a maximum number of requests to queue if the thread pool is busy.
* @since 0.15
*/
public int getMaxQueuedRequests() {
return maxQueuedRequests;
}
@BQConfigProperty("Maximum number of requests to queue if the thread pool is busy. If this number is exceeded, " +
"the server will start dropping requests.")
public void setMaxQueuedRequests(int maxQueuedRequests) {
this.maxQueuedRequests = maxQueuedRequests;
}
/**
* @return a maximum number of request processing threads in the pool.
* @since 0.15
*/
public int getMaxThreads() {
return maxThreads;
}
@BQConfigProperty("Maximum number of request processing threads in the pool.")
public void setMaxThreads(int maxConnectorThreads) {
this.maxThreads = maxConnectorThreads;
}
/**
* @return an initial number of request processing threads in the pool.
* @since 0.15
*/
public int getMinThreads() {
return minThreads;
}
@BQConfigProperty("Minimal number of request processing threads in the pool.")
public void setMinThreads(int minThreads) {
this.minThreads = minThreads;
}
/**
* @return a map of arbitrary key/value parameters that are used as "init"
* parameters of the ServletContext.
* @since 0.15
*/
public Map<String, String> getParams() {
return params != null ? Collections.unmodifiableMap(params) : Collections.emptyMap();
}
/**
* @param params a map of context init parameters.
* @since 0.13
*/
@BQConfigProperty("A map of application-specific key/value parameters that are used as \"init\" parameters of the " +
"ServletContext.")
public void setParams(Map<String, String> params) {
this.params = params;
}
/**
* @return a boolean specifying whether servlet sessions should be supported
* by Jetty.
* @since 0.15
*/
public boolean isSessions() {
return sessions;
}
@BQConfigProperty("A boolean specifying whether servlet sessions should be supported by Jetty. The default is 'true'")
public void setSessions(boolean sessions) {
this.sessions = sessions;
}
/**
* @return a base location for resources of the Jetty context.
* @since 0.15
*/
public FolderResourceFactory getStaticResourceBase() {
return staticResourceBase;
}
/**
* Sets a base location for resources of the Jetty context. Used by static
* resource servlets, including the "default" servlet. The value can be a
* file path or a URL, as well as a special URL starting with "classpath:".
* <p>
* It can be optionally overridden by DefaultServlet configuration.
* <p>
* For security reasons this has to be set explicitly. There's no default.
*
* @param staticResourceBase A base location for resources of the Jetty context, that can
* be a file path or a URL, as well as a special URL starting
* with "classpath:".
* @see JettyModuleExtender#useDefaultServlet()
* @see JettyModuleExtender#addStaticServlet(String, String...)
* @see <a href=
* "http://download.eclipse.org/jetty/9.3.7.v20160115/apidocs/org/eclipse/jetty/servlet/DefaultServlet.html">
* DefaultServlet</a>.
* @since 0.13
*/
@BQConfigProperty("Defines a base location for resources of the Jetty context. It can be a filesystem path, a URL " +
"or a special \"classpath:\" URL (giving the ability to bundle resources in the app, not unlike a JavaEE " +
".war file). This setting only makes sense when some form of \"default\" servlet is in use, that will be " +
"responsible for serving static resources. See JettyModule.contributeStaticServlet(..) or " +
"JettyModule.contributeDefaultServlet(..). ")
public void setStaticResourceBase(FolderResourceFactory staticResourceBase) {
this.staticResourceBase = staticResourceBase;
}
/**
* @return whether content compression is supported.
* @since 0.15
*/
public boolean isCompression() {
return compression;
}
/**
* Sets whether compression whether gzip compression should be supported.
* When true, responses will be compressed if a client requests it via
* "Accept-Encoding:" header. Default is true.
*
* @param compression whether gzip compression should be supported.
* @since 0.15
*/
@BQConfigProperty("A boolean specifying whether gzip compression should be supported. When enabled " +
"responses will be compressed if a client indicates it supports compression via " +
"\"Accept-Encoding: gzip\" header. Default value is 'true'.")
public void setCompression(boolean compression) {
this.compression = compression;
}
/**
* Sets the maximum size of submitted forms in bytes. Default is 200000 (~195K).
*
* @param maxFormContentSize maximum size of submitted forms in bytes. Default is 200000 (~195K)
* @since 0.22
*/
@BQConfigProperty("Maximum size of submitted forms in bytes. Default is 200000 (~195K).")
public void setMaxFormContentSize(int maxFormContentSize) {
this.maxFormContentSize = maxFormContentSize;
}
/**
* Sets the maximum number of form fields. Default is 1000.
*
* @param maxFormKeys maximum number of form fields. Default is 1000.
* @since 0.22
*/
@BQConfigProperty("Maximum number of form fields. Default is 1000.")
public void setMaxFormKeys(int maxFormKeys) {
this.maxFormKeys = maxFormKeys;
}
/**
* @return a potentially null map of error pages configuration.
* @since 0.24
*/
public Map<Integer, String> getErrorPages() {
return errorPages;
}
/**
* Sets mappings between HTTP status codes and corresponding pages which will be returned to the user instead.
*
* @param errorPages map where keys are HTTP status codes and values are page URLs which will be used to handle them
* @since 0.24
*/
@BQConfigProperty("A map specifying a mapping between HTTP status codes and pages (URLs) which will be used as their handlers. If no mapping is specified then standard error handler is used.")
public void setErrorPages(Map<Integer, String> errorPages) {
this.errorPages = errorPages;
}
}
|
Add a @BQConfigProperty for 'compactPath' in ContextHandler
|
bootique-jetty/src/main/java/io/bootique/jetty/server/ServerFactory.java
|
Add a @BQConfigProperty for 'compactPath' in ContextHandler
|
|
Java
|
apache-2.0
|
00e860fd8f63ba28f9c8156a8e31ed2ec48dd6ba
| 0
|
ajiang-open/jpaquery
|
package com.jpaquery.testcase.querytest;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jpaquery.core.Querys;
import com.jpaquery.core.facade.JpaQuery;
import com.jpaquery.testcase.schema.Student;
import com.jpaquery.testcase.schema.Teacher;
public class QueryTest {
Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void test1() {
JpaQuery jpaQuery = Querys.newJpaQuery();
Student modelStudent = jpaQuery.from(Student.class);
jpaQuery.select(modelStudent.getClazz());
Teacher modelTeacher = jpaQuery.join(modelStudent.getTeachers()).left();
jpaQuery.on(modelTeacher).get(modelTeacher.getClazzs().get(100).getName()).equal("aaa");
jpaQuery.where(modelStudent.getName()).equal("张三");
logger.info(jpaQuery.toQueryContent().toString());
}
}
|
src/test/java/com/jpaquery/testcase/querytest/QueryTest.java
|
package com.jpaquery.testcase.querytest;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jpaquery.core.Querys;
import com.jpaquery.core.facade.JpaQuery;
import com.jpaquery.testcase.schema.Student;
import com.jpaquery.testcase.schema.Teacher;
public class QueryTest {
Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void test1() {
JpaQuery jpaQuery = Querys.newJpaQuery();
Student modelStudent = jpaQuery.from(Student.class);
jpaQuery.select(modelStudent.getClazz());
Teacher modelTeacher = jpaQuery.join(modelStudent.getTeachers()).left();
jpaQuery.on(modelTeacher).get(modelTeacher.getClazzs().get(0).getName()).equal("aaa");
jpaQuery.where(modelStudent.getName()).equal("张三");
logger.info(jpaQuery.toQueryContent().toString());
}
}
|
提交区域查询样例
|
src/test/java/com/jpaquery/testcase/querytest/QueryTest.java
|
提交区域查询样例
|
|
Java
|
apache-2.0
|
f7b155c574224a7f338097c41a565fab1b1045ab
| 0
|
hjwylde/whiley-compiler,Whiley/WhileyCompiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler
|
package wycs.testing.tests;
import org.junit.Ignore;
import org.junit.Test;
import wycs.testing.TestHarness;
public class ValidTests extends TestHarness {
public ValidTests() {
super("tests/valid");
}
@Test public void Test_Arith_1() { verifyPassTest("test_arith_01"); }
@Test public void Test_Arith_2() { verifyPassTest("test_arith_02"); }
@Test public void Test_Arith_3() { verifyPassTest("test_arith_03"); }
@Test public void Test_Arith_4() { verifyPassTest("test_arith_04"); }
@Test public void Test_Arith_5() { verifyPassTest("test_arith_05"); }
@Test public void Test_Arith_6() { verifyPassTest("test_arith_06"); }
@Test public void Test_Arith_7() { verifyPassTest("test_arith_07"); }
@Test public void Test_Arith_8() { verifyPassTest("test_arith_08"); }
@Test public void Test_Arith_9() { verifyPassTest("test_arith_09"); }
@Test public void Test_Arith_10() { verifyPassTest("test_arith_10"); }
@Test public void Test_Arith_11() { verifyPassTest("test_arith_11"); }
@Ignore("Known Issue") @Test public void Test_Arith_12() { verifyPassTest("test_arith_12"); }
@Test public void Test_Arith_13() { verifyPassTest("test_arith_13"); }
@Test public void Test_Arith_14() { verifyPassTest("test_arith_14"); }
@Ignore("Known Issue") @Test public void Test_Arith_15() { verifyPassTest("test_arith_15"); }
@Test public void Test_Arith_16() { verifyPassTest("test_arith_16"); }
@Test public void Test_Arith_17() { verifyPassTest("test_arith_17"); }
@Ignore("Known Issue") @Test public void Test_Arith_18() { verifyPassTest("test_arith_18"); }
@Ignore("Known Issue") @Test public void Test_Arith_19() { verifyPassTest("test_arith_19"); }
@Test public void Test_Arith_20() { verifyPassTest("test_arith_20"); }
@Test public void Test_Arith_21() { verifyPassTest("test_arith_21"); }
@Test public void Test_Arith_22() { verifyPassTest("test_arith_22"); }
@Test public void Test_Arith_23() { verifyPassTest("test_arith_23"); }
@Test public void Test_Arith_24() { verifyPassTest("test_arith_24"); }
@Test public void Test_Arith_25() { verifyPassTest("test_arith_25"); }
@Test public void Test_Arith_26() { verifyPassTest("test_arith_26"); }
@Test public void Test_Arith_27() { verifyPassTest("test_arith_27"); }
@Ignore("Known Issue") @Test public void Test_Arith_28() { verifyPassTest("test_arith_28"); }
@Test public void Test_Arith_29() { verifyPassTest("test_arith_29"); }
@Ignore("Known Issue") @Test public void Test_Arith_30() { verifyPassTest("test_arith_30"); }
@Ignore("Known Issue") @Test public void Test_Arith_31() { verifyPassTest("test_arith_31"); }
@Test public void Test_Arith_32() { verifyPassTest("test_arith_32"); }
@Test public void Test_Arith_33() { verifyPassTest("test_arith_33"); }
@Test public void Test_Macro_1() { verifyPassTest("test_macro_01"); }
@Test public void Test_Macro_2() { verifyPassTest("test_macro_02"); }
@Test public void Test_Bool_1() { verifyPassTest("test_bool_01"); }
@Test public void Test_Fun_1() { verifyPassTest("test_fun_01"); }
@Test public void Test_Fun_2() { verifyPassTest("test_fun_02"); }
@Test public void Test_Set_1() { verifyPassTest("test_set_01"); }
@Test public void Test_Set_2() { verifyPassTest("test_set_02"); }
@Ignore("#290") @Test public void Test_Set_3() { verifyPassTest("test_set_03"); }
@Test public void Test_Set_4() { verifyPassTest("test_set_04"); }
@Ignore("#304") @Test public void Test_Set_5() { verifyPassTest("test_set_05"); }
@Test public void Test_Set_6() { verifyPassTest("test_set_06"); }
@Ignore("#304") @Test public void Test_Set_7() { verifyPassTest("test_set_07"); }
@Test public void Test_Set_8() { verifyPassTest("test_set_08"); }
@Ignore("Known Issue") @Test public void Test_Set_9() { verifyPassTest("test_set_09"); }
@Test public void Test_Set_10() { verifyPassTest("test_set_10"); }
@Ignore("#302")
@Test public void Test_Set_11() { verifyPassTest("test_set_11"); }
@Ignore("#303") @Test public void Test_Set_12() { verifyPassTest("test_set_12"); }
@Test public void Test_Set_13() { verifyPassTest("test_set_13"); }
@Test public void Test_Set_14() { verifyPassTest("test_set_14"); }
@Test public void Test_Set_15() { verifyPassTest("test_set_15"); }
@Ignore("#304") @Test public void Test_Set_16() { verifyPassTest("test_set_16"); }
@Test public void Test_Set_17() { verifyPassTest("test_set_17"); }
@Test public void Test_Set_18() { verifyPassTest("test_set_18"); }
@Test public void Test_Set_19() { verifyPassTest("test_set_19"); }
@Ignore("#303") @Test public void Test_Set_20() { verifyPassTest("test_set_20"); }
@Ignore("#304") @Test public void Test_Set_21() { verifyPassTest("test_set_21"); }
@Ignore("#304") @Test public void Test_Set_22() { verifyPassTest("test_set_22"); }
@Test public void Test_Set_23() { verifyPassTest("test_set_23"); }
@Test public void Test_Set_24() { verifyPassTest("test_set_24"); }
@Test public void Test_Set_25() { verifyPassTest("test_set_25"); }
@Ignore("Known Issue") @Test public void Test_List_1() { verifyPassTest("test_list_01"); }
@Ignore("Known Issue") @Test public void Test_List_2() { verifyPassTest("test_list_02"); }
@Test public void Test_List_4() { verifyPassTest("test_list_04"); }
@Test public void Test_List_5() { verifyPassTest("test_list_05"); }
@Ignore("#231,#303")
@Test public void Test_List_6() { verifyPassTest("test_list_06"); }
@Test public void Test_List_7() { verifyPassTest("test_list_07"); }
@Test public void Test_List_8() { verifyPassTest("test_list_08"); }
@Ignore("#231") @Test public void Test_List_9() { verifyPassTest("test_list_09"); }
@Ignore("#231") @Test public void Test_List_10() { verifyPassTest("test_list_10"); }
@Test public void Test_List_11() { verifyPassTest("test_list_11"); }
@Test public void Test_List_12() { verifyPassTest("test_list_12"); }
@Test public void Test_List_13() { verifyPassTest("test_list_13"); }
@Test public void Test_List_14() { verifyPassTest("test_list_14"); }
//@Ignore("#378")
@Test public void Test_List_15() { verifyPassTest("test_list_15"); }
@Test public void Test_Tuple_1() { verifyPassTest("test_tuple_01"); }
@Test public void Test_Valid_100() { verifyPassTest("test_100"); }
@Ignore("Known Issue") @Test public void Test_Valid_101() { verifyPassTest("test_101"); }
@Test public void Test_Valid_102() { verifyPassTest("test_102"); }
@Ignore("Known Issue") @Test public void Test_Valid_103() { verifyPassTest("test_103"); }
@Ignore("MaxSteps") @Test public void Test_Valid_104() { verifyPassTest("test_104"); }
@Ignore("Known Issue") @Test public void Test_Valid_105() { verifyPassTest("test_105"); }
@Ignore("MaxSteps") @Test public void Test_Valid_106() { verifyPassTest("test_106"); }
@Ignore("MaxSteps") @Test public void Test_Valid_107() { verifyPassTest("test_107"); }
@Test public void Test_Valid_108() { verifyPassTest("test_108"); }
@Ignore("MaxSteps") @Test public void Test_Valid_109() { verifyPassTest("test_109"); }
@Ignore("MaxSteps") @Test public void Test_Valid_110() { verifyPassTest("test_110"); }
@Ignore("MaxSteps") @Test public void Test_Valid_111() { verifyPassTest("test_111"); }
@Ignore("MaxSteps") @Test public void Test_Valid_112() { verifyPassTest("test_112"); }
@Ignore("Known Issue") @Test public void Test_Valid_113() { verifyPassTest("test_113"); }
@Test public void Test_Valid_114() { verifyPassTest("test_114"); }
@Ignore("Internal Failure") @Test public void Test_Valid_115() { verifyPassTest("test_115"); }
@Ignore("MaxSteps") @Test public void Test_Valid_116() { verifyPassTest("test_116"); }
@Ignore("Known Issue") @Test public void Test_Valid_117() { verifyPassTest("test_117"); }
@Ignore("Known Issue") @Test public void Test_Valid_118() { verifyPassTest("test_118"); }
@Ignore("Known Issue") @Test public void Test_Valid_119() { verifyPassTest("test_119"); }
@Ignore("Known Issue") @Test public void Test_Valid_120() { verifyPassTest("test_120"); }
@Ignore("Known Issue") @Test public void Test_Valid_121() { verifyPassTest("test_121"); }
}
|
modules/wycs/src/wycs/testing/tests/ValidTests.java
|
package wycs.testing.tests;
import org.junit.Ignore;
import org.junit.Test;
import wycs.testing.TestHarness;
public class ValidTests extends TestHarness {
public ValidTests() {
super("tests/valid");
}
@Test public void Test_Arith_1() { verifyPassTest("test_arith_01"); }
@Test public void Test_Arith_2() { verifyPassTest("test_arith_02"); }
@Test public void Test_Arith_3() { verifyPassTest("test_arith_03"); }
@Test public void Test_Arith_4() { verifyPassTest("test_arith_04"); }
@Test public void Test_Arith_5() { verifyPassTest("test_arith_05"); }
@Test public void Test_Arith_6() { verifyPassTest("test_arith_06"); }
@Test public void Test_Arith_7() { verifyPassTest("test_arith_07"); }
@Test public void Test_Arith_8() { verifyPassTest("test_arith_08"); }
@Test public void Test_Arith_9() { verifyPassTest("test_arith_09"); }
@Test public void Test_Arith_10() { verifyPassTest("test_arith_10"); }
@Test public void Test_Arith_11() { verifyPassTest("test_arith_11"); }
@Ignore("Known Issue") @Test public void Test_Arith_12() { verifyPassTest("test_arith_12"); }
@Test public void Test_Arith_13() { verifyPassTest("test_arith_13"); }
@Test public void Test_Arith_14() { verifyPassTest("test_arith_14"); }
@Ignore("Known Issue") @Test public void Test_Arith_15() { verifyPassTest("test_arith_15"); }
@Test public void Test_Arith_16() { verifyPassTest("test_arith_16"); }
@Test public void Test_Arith_17() { verifyPassTest("test_arith_17"); }
@Ignore("Known Issue") @Test public void Test_Arith_18() { verifyPassTest("test_arith_18"); }
@Ignore("Known Issue") @Test public void Test_Arith_19() { verifyPassTest("test_arith_19"); }
@Test public void Test_Arith_20() { verifyPassTest("test_arith_20"); }
@Test public void Test_Arith_21() { verifyPassTest("test_arith_21"); }
@Test public void Test_Arith_22() { verifyPassTest("test_arith_22"); }
@Test public void Test_Arith_23() { verifyPassTest("test_arith_23"); }
@Test public void Test_Arith_24() { verifyPassTest("test_arith_24"); }
@Test public void Test_Arith_25() { verifyPassTest("test_arith_25"); }
@Test public void Test_Arith_26() { verifyPassTest("test_arith_26"); }
@Test public void Test_Arith_27() { verifyPassTest("test_arith_27"); }
@Ignore("Known Issue") @Test public void Test_Arith_28() { verifyPassTest("test_arith_28"); }
@Test public void Test_Arith_29() { verifyPassTest("test_arith_29"); }
@Ignore("Known Issue") @Test public void Test_Arith_30() { verifyPassTest("test_arith_30"); }
@Ignore("Known Issue") @Test public void Test_Arith_31() { verifyPassTest("test_arith_31"); }
@Test public void Test_Arith_32() { verifyPassTest("test_arith_32"); }
@Test public void Test_Arith_33() { verifyPassTest("test_arith_33"); }
@Test public void Test_Macro_1() { verifyPassTest("test_macro_01"); }
@Test public void Test_Macro_2() { verifyPassTest("test_macro_02"); }
@Test public void Test_Bool_1() { verifyPassTest("test_bool_01"); }
@Test public void Test_Fun_1() { verifyPassTest("test_fun_01"); }
@Test public void Test_Fun_2() { verifyPassTest("test_fun_02"); }
@Test public void Test_Set_1() { verifyPassTest("test_set_01"); }
@Test public void Test_Set_2() { verifyPassTest("test_set_02"); }
@Ignore("#290") @Test public void Test_Set_3() { verifyPassTest("test_set_03"); }
@Test public void Test_Set_4() { verifyPassTest("test_set_04"); }
@Ignore("#304") @Test public void Test_Set_5() { verifyPassTest("test_set_05"); }
@Test public void Test_Set_6() { verifyPassTest("test_set_06"); }
@Ignore("#304") @Test public void Test_Set_7() { verifyPassTest("test_set_07"); }
@Test public void Test_Set_8() { verifyPassTest("test_set_08"); }
@Ignore("Known Issue") @Test public void Test_Set_9() { verifyPassTest("test_set_09"); }
@Test public void Test_Set_10() { verifyPassTest("test_set_10"); }
@Ignore("#302")
@Test public void Test_Set_11() { verifyPassTest("test_set_11"); }
@Ignore("#303") @Test public void Test_Set_12() { verifyPassTest("test_set_12"); }
@Test public void Test_Set_13() { verifyPassTest("test_set_13"); }
@Test public void Test_Set_14() { verifyPassTest("test_set_14"); }
@Test public void Test_Set_15() { verifyPassTest("test_set_15"); }
@Ignore("#304") @Test public void Test_Set_16() { verifyPassTest("test_set_16"); }
@Test public void Test_Set_17() { verifyPassTest("test_set_17"); }
@Test public void Test_Set_18() { verifyPassTest("test_set_18"); }
@Test public void Test_Set_19() { verifyPassTest("test_set_19"); }
@Ignore("#303") @Test public void Test_Set_20() { verifyPassTest("test_set_20"); }
@Ignore("#304") @Test public void Test_Set_21() { verifyPassTest("test_set_21"); }
@Ignore("#304") @Test public void Test_Set_22() { verifyPassTest("test_set_22"); }
@Test public void Test_Set_23() { verifyPassTest("test_set_23"); }
@Test public void Test_Set_24() { verifyPassTest("test_set_24"); }
@Test public void Test_Set_25() { verifyPassTest("test_set_25"); }
@Ignore("Known Issue") @Test public void Test_List_1() { verifyPassTest("test_list_01"); }
@Ignore("Known Issue") @Test public void Test_List_2() { verifyPassTest("test_list_02"); }
@Test public void Test_List_4() { verifyPassTest("test_list_04"); }
@Test public void Test_List_5() { verifyPassTest("test_list_05"); }
@Ignore("#231,#303")
@Test public void Test_List_6() { verifyPassTest("test_list_06"); }
@Test public void Test_List_7() { verifyPassTest("test_list_07"); }
@Test public void Test_List_8() { verifyPassTest("test_list_08"); }
@Ignore("#231") @Test public void Test_List_9() { verifyPassTest("test_list_09"); }
@Ignore("#231") @Test public void Test_List_10() { verifyPassTest("test_list_10"); }
@Test public void Test_List_11() { verifyPassTest("test_list_11"); }
@Test public void Test_List_12() { verifyPassTest("test_list_12"); }
@Test public void Test_List_13() { verifyPassTest("test_list_13"); }
@Test public void Test_List_14() { verifyPassTest("test_list_14"); }
//@Ignore("#378")
@Test public void Test_List_15() { verifyPassTest("test_list_15"); }
@Test public void Test_Tuple_1() { verifyPassTest("test_tuple_01"); }
@Test public void Test_Valid_100() { verifyPassTest("test_100"); }
@Ignore("MaxSteps") @Test public void Test_Valid_101() { verifyPassTest("test_101"); }
@Test public void Test_Valid_102() { verifyPassTest("test_102"); }
@Ignore("Known Issue") @Test public void Test_Valid_103() { verifyPassTest("test_103"); }
@Ignore("MaxSteps") @Test public void Test_Valid_104() { verifyPassTest("test_104"); }
@Ignore("Known Issue") @Test public void Test_Valid_105() { verifyPassTest("test_105"); }
@Ignore("MaxSteps") @Test public void Test_Valid_106() { verifyPassTest("test_106"); }
@Ignore("MaxSteps") @Test public void Test_Valid_107() { verifyPassTest("test_107"); }
@Test public void Test_Valid_108() { verifyPassTest("test_108"); }
@Ignore("MaxSteps") @Test public void Test_Valid_109() { verifyPassTest("test_109"); }
@Ignore("MaxSteps") @Test public void Test_Valid_110() { verifyPassTest("test_110"); }
@Ignore("MaxSteps") @Test public void Test_Valid_111() { verifyPassTest("test_111"); }
@Ignore("MaxSteps") @Test public void Test_Valid_112() { verifyPassTest("test_112"); }
@Ignore("Known Issue") @Test public void Test_Valid_113() { verifyPassTest("test_113"); }
@Test public void Test_Valid_114() { verifyPassTest("test_114"); }
@Ignore("Internal Failure") @Test public void Test_Valid_115() { verifyPassTest("test_115"); }
@Ignore("MaxSteps") @Test public void Test_Valid_116() { verifyPassTest("test_116"); }
@Ignore("Known Issue") @Test public void Test_Valid_117() { verifyPassTest("test_117"); }
@Ignore("Known Issue") @Test public void Test_Valid_118() { verifyPassTest("test_118"); }
@Ignore("Known Issue") @Test public void Test_Valid_119() { verifyPassTest("test_119"); }
@Ignore("Known Issue") @Test public void Test_Valid_120() { verifyPassTest("test_120"); }
@Ignore("Known Issue") @Test public void Test_Valid_121() { verifyPassTest("test_121"); }
}
|
WyCS: looking through test cases wondering about reasons why they fail
|
modules/wycs/src/wycs/testing/tests/ValidTests.java
|
WyCS: looking through test cases wondering about reasons why they fail
|
|
Java
|
apache-2.0
|
8a0c1cfcc62d1fd8e58b28bfc0c669208e911fc6
| 0
|
abhinavmishra14/soap-demo
|
/*
* Created By: Abhinav Kumar Mishra
* Copyright © 2016. Abhinav Kumar Mishra.
* 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.github.abhinavmishra14.pojo;
import java.io.Serializable;
/**
* The Class UserModel.
*/
public class UserModel implements Serializable{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -3529671170359212999L;
/** The user name. */
private String userName;
/** The password. */
private String password;
/**
* Gets the user name.
*
* @return the user name
*/
public String getUserName() {
return userName;
}
/**
* Sets the user name.
*
* @param userName the user name
*/
public void setUserName(final String userName) {
this.userName = userName;
}
/**
* Gets the password.
*
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Sets the password.
*
* @param password the password
*/
public void setPassword(final String password) {
this.password = password;
}
}
|
src/main/java/com/github/abhinavmishra14/pojo/UserModel.java
|
/*
* Created By: Abhinav Kumar Mishra
* Copyright © 2016. Abhinav Kumar Mishra.
* 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.github.abhinavmishra14.pojo;
/**
* The Class UserModel.
*/
public class UserModel {
/** The user name. */
private String userName;
/** The password. */
private String password;
/**
* Gets the user name.
*
* @return the user name
*/
public String getUserName() {
return userName;
}
/**
* Sets the user name.
*
* @param userName the user name
*/
public void setUserName(final String userName) {
this.userName = userName;
}
/**
* Gets the password.
*
* @return the password
*/
public String getPassword() {
return password;
}
/**
* Sets the password.
*
* @param password the password
*/
public void setPassword(final String password) {
this.password = password;
}
}
|
Added serial version id.
|
src/main/java/com/github/abhinavmishra14/pojo/UserModel.java
|
Added serial version id.
|
|
Java
|
apache-2.0
|
65054e57d1d80ca4e1616232e2f373718f5573ec
| 0
|
jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics
|
/*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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
*
* Author:
* Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
*
*/
package org.jenetics.util;
import static org.jenetics.util.object.hashCodeOf;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class implements a linear congruental PRNG with additional bit-shift
* transition. The base recursion
* <p><div align="center">
* <img
* alt="r_{i+1} = (a\cdot r_i + b) \mod 2^{64}"
* src="doc-files/lcg-recursion.gif"
* />
* </p></div>
* is followed by a non-linear transformation
* <p><div align="center">
* <img
* alt="\begin{eqnarray*}
* t &=& r_i \\
* t &=& t \oplus (t >> 17) \\
* t &=& t \oplus (t << 31) \\
* t &=& t \oplus (t >> 8)
* \end{eqnarray*}"
* src="doc-files/lcg-non-linear.gif"
* />
* </p></div>
* which destroys the lattice structure introduced by the recursion. The period of
* this PRNG is 2<sup>64</sup>, {@code iff} <i>b</i> is odd and <i>a</i>
* {@code mod} 4 = 1.
* <p/>
*
* <p><b>
* The <i>main</i> class of this PRNG is not thread safe. To create an thread
* safe instances of this PRNG, use the {@link LCG64ShiftRandom.ThreadSafe} or
* {@link LCG64ShiftRandom.ThreadLocal} class.
* </b></p>
*
* <em>
* This is an re-implementation of the
* <a href="https://github.com/rabauke/trng4/blob/master/src/lcg64_shift.hpp">
* trng::lcg64_shift</a> PRNG class of the
* <a href="http://numbercrunch.de/trng/">TRNG</a> library created by Heiko
* Bauke.</em>
*
* @see <a href="http://numbercrunch.de/trng/">TRNG</a>
* @see RandomRegistry
*
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
* @since 1.1
* @version 1.1 — <em>$Date: 2012-12-07 $</em>
*/
public class LCG64ShiftRandom extends Random64 {
private static final long serialVersionUID = 1L;
/**
* Parameter class for the {@code LCG64ShiftRandom} generator, for the
* parameters <i>a</i> and <i>b</i> of the LC recursion
* <i>r<sub>i+1</sub> = a · r<sub>i</sub> + b</i> mod <i>2<sup>64</sup></i>.
*
* @see LCG64ShiftRandom#DEFAULT
* @see LCG64ShiftRandom#LECUYER1
* @see LCG64ShiftRandom#LECUYER2
* @see LCG64ShiftRandom#LECUYER3
*/
public static final class Param implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The parameter <i>a</i> of the LC recursion.
*/
public final long a;
/**
* The parameter <i>b</i> of the LC recursion.
*/
public final long b;
/**
* Create a new parameter object.
*
* @param a the parameter <i>a</i> of the LC recursion.
* @param b the parameter <i>b</i> of the LC recursion.
*/
public Param(final long a, final long b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
return 31*(int)(a^(a >>> 32)) + 31*(int)(b^(b >>> 32));
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Param)) {
return false;
}
final Param param = (Param)obj;
return a == param.a && b == param.b;
}
@Override
public String toString() {
return String.format("%s[a=%d, b=%d]", getClass().getName(), a, b);
}
}
/**
* This class represents a <i>thread local</i> implementation of the
* {@code LCG64ShiftRandom} PRNG.
*
* It's recommended to initialize the {@code RandomRegistry} the following
* way:
*
* [code]
* // Register the PRGN with the default parameters.
* RandomRegistry.setRandom(new LCG64ShiftRandom.ThreadLocal());
*
* // Register the PRNG with the {@code LECUYER3} parameters.
* RandomRegistry.setRandom(new LCG64ShiftRandom.ThreadLocal(
* LCG64ShiftRandom.LECUYER3
* ));
* [/code]
*
* Be aware, that calls of the {@code setSeed(long)} method will throw an
* {@code UnsupportedOperationException} for <i>thread local</i> instances.
* [code]
* RandomRegistry.setRandom(new LCG64ShiftRandom.ThreadLocal());
*
* // Will throw 'UnsupportedOperationException'.
* RandomRegistry.getRandom().setSeed(1234);
* [/code]
*/
public static class ThreadLocal extends java.lang.ThreadLocal<LCG64ShiftRandom> {
private static final long STEP_BASE = 1L << 57;
private final long _seed = math.random.seed();
private final AtomicInteger _thread = new AtomicInteger(0);
private final Param _param;
/**
* Create a new <i>thread local</i> instance of the
* {@code LCG64ShiftRandom} PRGN with the {@code DEFAULT} parameters.
*/
public ThreadLocal() {
this(DEFAULT);
}
/**
* Create a new <i>thread local</i> instance of the
* {@code LCG64ShiftRandom} PRGN with the given parameters.
*
* @param param the LC parameters.
* @throws NullPointerException if the given parameters are null.
*/
public ThreadLocal(final Param param) {
_param = object.nonNull(param, "PRNG param must not be null.");
}
/**
* Create a new PRNG using <i>block splitting</i> for guaranteeing well
* distributed PRN for every thread.
*
* <p align="left">
* <strong>Tina’s Random Number Generator Library</strong>
* <br/>
* <em>Chapter 2. Pseudo-random numbers for parallel Monte Carlo
* simulations, Page 7</em>
* <br/>
* <small>Heiko Bauke</small>
* <br/>
* [<a href="http://numbercrunch.de/trng/trng.pdf">
* http://numbercrunch.de/trng/trng.pdf
* </a>].
* <p/>
*/
@Override
protected LCG64ShiftRandom initialValue() {
final LCG64ShiftRandom random = new TLLCG64ShiftRandom(_seed, _param);
random.jump((_thread.getAndIncrement()%64)*STEP_BASE);
return random;
}
}
private static final class TLLCG64ShiftRandom extends LCG64ShiftRandom {
private static final long serialVersionUID = 1L;
private final Boolean _sentry = Boolean.TRUE;
private TLLCG64ShiftRandom(final long seed, final Param param) {
super(seed, param);
}
@Override
public void setSeed(final long seed) {
if (_sentry != null) {
throw new UnsupportedOperationException(
"The 'setSeed(long)' method is not supported " +
"for thread local instances."
);
}
}
}
/**
* This is a <i>thread safe</i> variation of the this PRGN.
*/
public static class ThreadSafe extends LCG64ShiftRandom {
private static final long serialVersionUID = 1L;
/**
* Create a new PRNG instance with {@link #DEFAULT} parameter and seed
* {@link System#nanoTime()}.
*/
public ThreadSafe() {
}
/**
* Create a new PRNG instance with {@link #DEFAULT} parameter and the
* given seed.
*
* @param seed the seed of the PRNG
*/
public ThreadSafe(final long seed) {
super(seed);
}
/**
* Create a new PRNG instance with the given parameter and a seed of
* {@link System#nanoTime()}.
*
* @param param the PRNG parameter.
* @throws NullPointerException if the given {@code param} is null.
*/
public ThreadSafe(final Param param) {
super(param);
}
/**
* Create a new PRNG instance with the given parameter and seed.
*
* @param seed the seed of the PRNG.
* @param param the parameter of the PRNG.
* @throws NullPointerException if the given {@code param} is null.
*/
public ThreadSafe(final long seed, final Param param) {
super(seed, param);
}
@Override
public synchronized void setSeed(final long seed) {
super.setSeed(seed);
}
@Override
public synchronized long nextLong() {
return super.nextLong();
}
}
/**
* The default PRNG parameters: a = 18,145,460,002,477,866,997; b = 1
*/
public static final Param DEFAULT = new Param(0xFBD19FBBC5C07FF5L, 1L);
/**
* LEcuyer 1 parameters: a = 2,862,933,555,777,941,757; b = 1
*/
public static final Param LECUYER1 = new Param(0x27BB2EE687B0B0FDL, 1L);
/**
* LEcuyer 2 parameters: a = 3,202,034,522,624,059,733; b = 1
*/
public static final Param LECUYER2 = new Param(0x2C6FE96EE78B6955L, 1L);
/**
* LEcuyer 3 parameters: a = 3,935,559,000,370,003,845; b = 1
*/
public static final Param LECUYER3 = new Param(0x369DEA0F31A53F85L, 1L);
private final Param _param;
private final long _seed;
private long _a = 0;
private long _b = 0;
private long _r = 0;
/**
* Create a new PRNG instance with {@link #DEFAULT} parameter and seed
* {@link System#nanoTime()}.
*/
public LCG64ShiftRandom() {
this(math.random.seed());
}
/**
* Create a new PRNG instance with {@link #DEFAULT} parameter and the given
* seed.
*
* @param seed the seed of the PRNG
*/
public LCG64ShiftRandom(final long seed) {
this(seed, DEFAULT);
}
/**
* Create a new PRNG instance with the given parameter and a seed of
* {@link System#nanoTime()}.
*
* @param param the PRNG parameter.
* @throws NullPointerException if the given {@code param} is null.
*/
public LCG64ShiftRandom(final Param param) {
this(math.random.seed(), param);
}
/**
* Create a new PRNG instance with the given parameter and seed.
*
* @param seed the seed of the PRNG.
* @param param the parameter of the PRNG.
* @throws NullPointerException if the given {@code param} is null.
*/
public LCG64ShiftRandom(final long seed, final Param param) {
_param = object.nonNull(param, "PRNG param must not be null.");
_seed = seed;
_r = seed;
_a = param.a;
_b = param.b;
}
/**
* Resets the PRNG back to the creation state.
*/
public void reset() {
_r = _seed;
_a = _param.a;
_b = _param.b;
}
@Override
public void setSeed(final long seed) {
_r = seed;
}
@Override
public long nextLong() {
step();
long t = _r;
t ^= t >>> 17;
t ^= t << 31;
t ^= t >>> 8;
return t;
}
private void step() {
_r = _a*_r + _b;
}
/**
* Changes the internal state of the PRNG in a way that future calls to
* {@link #nextLong()} will generated the s<sup>th</sup> sub-stream of
* p<sup>th</sup> sub-streams. <i>s</i> must be within the range of
* {@code [0, n)}. This method is mainly used for <i>parallelization</i>
* via <i>leapfrogging</i>.
*
* @param p the overall number of sub-streams
* @param s the s<sup>th</sup> sub-stream
* @throws IllegalArgumentException if {@code p < 1 || s >= p}.
*/
public void split(final int p, final int s) {
if (p < 1) {
throw new IllegalArgumentException(String.format(
"p must be >= 1 but was %d.", p
));
}
if (s >= p) {
throw new IllegalArgumentException(String.format(
"s must be < %d but was %d.", p, s
));
}
if (p > 1) {
jump(s + 1);
_b *= f(p, _a);
_a = pow(_a, p);
backward();
}
}
/**
* Changes the internal state of the PRNG in such a way that the engine
* <i>jumps</i> 2<sup>s</sup> steps ahead.
*
* @param s the 2<sup>s</sup> steps to jump ahead.
* @throws IllegalArgumentException if {@code s < 0}.
*/
public void jump2(final int s) {
if (s < 0) {
throw new IllegalArgumentException(String.format(
"s must be positive but was %d.", s
));
}
if (s >= Long.SIZE) {
throw new IllegalArgumentException(String.format(
"The 'jump2' size must be smaller than %d but was %d.",
Long.SIZE, s
));
}
_r = _r*pow(_a, 1L << s) + f(1L << s, _a)*_b;
}
/**
* Changes the internal state of the PRNG in such a way that the engine
* <i>jumps</i> s steps ahead.
*
* @param step the steps to jump ahead.
* @throws IllegalArgumentException if {@code s < 0}.
*/
public void jump(final long step) {
if (step < 0) {
throw new IllegalArgumentException(String.format(
"step must be positive but was %d", step
));
}
if (step < 16) {
for (int i = 0; i < step; ++i) {
step();
}
} else {
long s = step;
int i = 0;
while (s > 0) {
if (s%2 == 1) {
jump2(i);
}
++i;
s >>= 1;
}
}
}
private void backward() {
for (int i = 0; i < Long.SIZE; ++i) {
jump2(i);
}
}
@Override
public String toString() {
return String.format(
"%s[a=%d, b=%d, r=%d",
getClass().getName(), _a, _b, _r
);
}
@Override
public int hashCode() {
return hashCodeOf(getClass())
.and(_a).and(_b).and(_r)
.and(_seed).and(_param).value();
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof LCG64ShiftRandom)) {
return false;
}
final LCG64ShiftRandom random = (LCG64ShiftRandom)obj;
return _a == random._a &&
_b == random._b &&
_r == random._r &&
_seed == random._seed &&
_param.equals(random._param);
}
/**
* Compute prod(1+a^(2^i), i=0..l-1).
*/
private static long g(final int l, final long a) {
long p = a;
long res = 1;
for (int i = 0; i < l; ++i) {
res *= 1 + p;
p *= p;
}
return res;
}
/**
* Compute sum(a^i, i=0..s-1).
*/
private static long f(final long s, final long a) {
long y = 0;
if (s != 0) {
long e = log2Floor(s);
long p = a;
for (int l = 0; l <= e; ++l) {
if (((1L << l) & s) != 0) {
y = g(l, a) + p*y;
}
p *= p;
}
}
return y;
}
private static long pow(final long b, final long e) {
long base = b;
long exp = e;
long result = 1;
while (exp != 0) {
if ((exp & 1) != 0) {
result *= base;
}
base *= base;
exp >>>= 1;
}
return result;
}
private static long log2Floor(final long s) {
long x = s;
long y = 0;
while (x != 0) {
x >>>= 1;
++y;
}
return y - 1;
}
}
|
org.jenetics/src/main/java/org/jenetics/util/LCG64ShiftRandom.java
|
/*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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
*
* Author:
* Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
*
*/
package org.jenetics.util;
import static org.jenetics.util.object.hashCodeOf;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class implements a linear congruental PRNG with additional bit-shift
* transition. The base recursion
* <p><div align="center">
* <img
* alt="r_{i+1} = (a\cdot r_i + b) \mod 2^{64}"
* src="doc-files/lcg-recursion.gif"
* />
* </p></div>
* is followed by a non-linear transformation
* <p><div align="center">
* <img
* alt="\begin{eqnarray*}
* t &=& r_i \\
* t &=& t \oplus (t >> 17) \\
* t &=& t \oplus (t << 31) \\
* t &=& t \oplus (t >> 8)
* \end{eqnarray*}"
* src="doc-files/lcg-non-linear.gif"
* />
* </p></div>
* which destroys the lattice structure introduced by the recursion. The period of
* this PRNG is 2<sup>64</sup>, {@code iff} <i>b</i> is odd and <i>a</i>
* {@code mod} 4 = 1.
* <p/>
*
* <p><b>
* The <i>main</i> class of this PRNG is not thread safe. To create an thread
* safe instances of this PRNG, use the {@link LCG64ShiftRandom.ThreadSafe} or
* {@link LCG64ShiftRandom.ThreadLocal} class.
* </b></p>
*
* <em>
* This is an re-implementation of the
* <a href="https://github.com/rabauke/trng4/blob/master/src/lcg64_shift.hpp">
* trng::lcg64_shift</a> PRNG class of the
* <a href="http://numbercrunch.de/trng/">TRNG</a> library created by Heiko
* Bauke.</em>
*
* @see <a href="http://numbercrunch.de/trng/">TRNG</a>
* @see RandomRegistry
*
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
* @since 1.1
* @version 1.1 — <em>$Date: 2012-12-06 $</em>
*/
public class LCG64ShiftRandom extends Random64 {
private static final long serialVersionUID = 1L;
/**
* Parameter class for the {@code LCG64ShiftRandom} generator, for the
* parameters <i>a</i> and <i>b</i> of the LC recursion
* <i>r<sub>i+1</sub> = a · r<sub>i</sub> + b</i> mod <i>2<sup>64</sup></i>.
*/
public static final class Param implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The parameter <i>a</i> of the LC recursion.
*/
public final long a;
/**
* The parameter <i>b</i> of the LC recursion.
*/
public final long b;
/**
* Create a new parameter object.
*
* @param a the parameter <i>a</i> of the LC recursion.
* @param b the parameter <i>b</i> of the LC recursion.
*/
public Param(final long a, final long b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
return 31*(int)(a^(a >>> 32)) + 31*(int)(b^(b >>> 32));
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Param)) {
return false;
}
final Param param = (Param)obj;
return a == param.a && b == param.b;
}
@Override
public String toString() {
return String.format("%s[a=%d, b=%d]", getClass().getName(), a, b);
}
}
/**
* This class represents a <i>thread local</i> implementation of the
* {@code LCG64ShiftRandom} PRNG.
*
* It's recommended to initialize the {@code RandomRegistry} the following
* way:
*
* [code]
* // Register the PRGN with the default parameters.
* RandomRegistry.setRandom(new LCG64ShiftRandom.ThreadLocal());
*
* // Register the PRNG with the {@code LECUYER3} parameters.
* RandomRegistry.setRandom(new LCG64ShiftRandom.ThreadLocal(
* LCG64ShiftRandom.LECUYER3
* ));
* [/code]
*
* Be aware, that calls of the {@code setSeed(long)} method will throw an
* {@code UnsupportedOperationException} for <i>thread local</i> instances.
* [code]
* RandomRegistry.setRandom(new LCG64ShiftRandom.ThreadLocal());
*
* // Will throw 'UnsupportedOperationException'.
* RandomRegistry.getRandom().setSeed(1234);
* [/code]
*/
public static class ThreadLocal extends java.lang.ThreadLocal<LCG64ShiftRandom> {
private static final long STEP_BASE = 1L << 57;
private final long _seed = math.random.seed();
private final AtomicInteger _thread = new AtomicInteger(0);
private final Param _param;
/**
* Create a new <i>thread local</i> instance of the
* {@code LCG64ShiftRandom} PRGN with the {@code DEFAULT} parameters.
*/
public ThreadLocal() {
this(DEFAULT);
}
/**
* Create a new <i>thread local</i> instance of the
* {@code LCG64ShiftRandom} PRGN with the given parameters.
*
* @param param the LC parameters.
* @throws NullPointerException if the given parameters are null.
*/
public ThreadLocal(final Param param) {
_param = object.nonNull(param, "PRNG param must not be null.");
}
/**
* Create a new PRNG using <i>block splitting</i> for guaranteeing well
* distributed PRN for every thread.
*
* <p align="left">
* <strong>Tina’s Random Number Generator Library</strong>
* <br/>
* <em>Chapter 2. Pseudo-random numbers for parallel Monte Carlo
* simulations, Page 7</em>
* <br/>
* <small>Heiko Bauke</small>
* <br/>
* [<a href="http://numbercrunch.de/trng/trng.pdf">
* http://numbercrunch.de/trng/trng.pdf
* </a>].
* <p/>
*/
@Override
protected LCG64ShiftRandom initialValue() {
final LCG64ShiftRandom random = new TLLCG64ShiftRandom(_seed, _param);
random.jump((_thread.getAndIncrement()%64)*STEP_BASE);
return random;
}
}
private static final class TLLCG64ShiftRandom extends LCG64ShiftRandom {
private static final long serialVersionUID = 1L;
private final Boolean _sentry = Boolean.TRUE;
private TLLCG64ShiftRandom(final long seed, final Param param) {
super(seed, param);
}
@Override
public void setSeed(final long seed) {
if (_sentry != null) {
throw new UnsupportedOperationException(
"The 'setSeed(long)' method is not supported " +
"for thread local instances."
);
}
}
}
/**
* This is a <i>thread safe</i> variation of the this PRGN.
*/
public static class ThreadSafe extends LCG64ShiftRandom {
private static final long serialVersionUID = 1L;
/**
* Create a new PRNG instance with {@link #DEFAULT} parameter and seed
* {@link System#nanoTime()}.
*/
public ThreadSafe() {
}
/**
* Create a new PRNG instance with {@link #DEFAULT} parameter and the
* given seed.
*
* @param seed the seed of the PRNG
*/
public ThreadSafe(final long seed) {
super(seed);
}
/**
* Create a new PRNG instance with the given parameter and a seed of
* {@link System#nanoTime()}.
*
* @param param the PRNG parameter.
* @throws NullPointerException if the given {@code param} is null.
*/
public ThreadSafe(final Param param) {
super(param);
}
/**
* Create a new PRNG instance with the given parameter and seed.
*
* @param seed the seed of the PRNG.
* @param param the parameter of the PRNG.
* @throws NullPointerException if the given {@code param} is null.
*/
public ThreadSafe(final long seed, final Param param) {
super(seed, param);
}
@Override
public synchronized void setSeed(final long seed) {
super.setSeed(seed);
}
@Override
public synchronized long nextLong() {
return super.nextLong();
}
}
/**
* The default PRNG parameters: a = 18,145,460,002,477,866,997; b = 1
*/
public static final Param DEFAULT = new Param(0xFBD19FBBC5C07FF5L, 1L);
/**
* LEcuyer 1 parameters: a = 2,862,933,555,777,941,757; b = 1
*/
public static final Param LECUYER1 = new Param(0x27BB2EE687B0B0FDL, 1L);
/**
* LEcuyer 2 parameters: a = 3,202,034,522,624,059,733; b = 1
*/
public static final Param LECUYER2 = new Param(0x2C6FE96EE78B6955L, 1L);
/**
* LEcuyer 3 parameters: a = 3,935,559,000,370,003,845; b = 1
*/
public static final Param LECUYER3 = new Param(0x369DEA0F31A53F85L, 1L);
private final Param _param;
private final long _seed;
private long _a = 0;
private long _b = 0;
private long _r = 0;
/**
* Create a new PRNG instance with {@link #DEFAULT} parameter and seed
* {@link System#nanoTime()}.
*/
public LCG64ShiftRandom() {
this(math.random.seed());
}
/**
* Create a new PRNG instance with {@link #DEFAULT} parameter and the given
* seed.
*
* @param seed the seed of the PRNG
*/
public LCG64ShiftRandom(final long seed) {
this(seed, DEFAULT);
}
/**
* Create a new PRNG instance with the given parameter and a seed of
* {@link System#nanoTime()}.
*
* @param param the PRNG parameter.
* @throws NullPointerException if the given {@code param} is null.
*/
public LCG64ShiftRandom(final Param param) {
this(math.random.seed(), param);
}
/**
* Create a new PRNG instance with the given parameter and seed.
*
* @param seed the seed of the PRNG.
* @param param the parameter of the PRNG.
* @throws NullPointerException if the given {@code param} is null.
*/
public LCG64ShiftRandom(final long seed, final Param param) {
_param = object.nonNull(param, "PRNG param must not be null.");
_seed = seed;
_r = seed;
_a = param.a;
_b = param.b;
}
/**
* Resets the PRNG back to the creation state.
*/
public void reset() {
_r = _seed;
_a = _param.a;
_b = _param.b;
}
@Override
public void setSeed(final long seed) {
_r = seed;
}
@Override
public long nextLong() {
step();
long t = _r;
t ^= t >>> 17;
t ^= t << 31;
t ^= t >>> 8;
return t;
}
private void step() {
_r = _a*_r + _b;
}
/**
* Changes the internal state of the PRNG in a way that future calls to
* {@link #nextLong()} will generated the s<sup>th</sup> sub-stream of
* p<sup>th</sup> sub-streams. <i>s</i> must be within the range of
* {@code [0, n)}. This method is mainly used for <i>parallelization</i>
* via <i>leapfrogging</i>.
*
* @param p the overall number of sub-streams
* @param s the s<sup>th</sup> sub-stream
* @throws IllegalArgumentException if {@code p < 1 || s >= p}.
*/
public void split(final int p, final int s) {
if (p < 1) {
throw new IllegalArgumentException(String.format(
"p must be >= 1 but was %d.", p
));
}
if (s >= p) {
throw new IllegalArgumentException(String.format(
"s must be < %d but was %d.", p, s
));
}
if (p > 1) {
jump(s + 1);
_b *= f(p, _a);
_a = pow(_a, p);
backward();
}
}
/**
* Changes the internal state of the PRNG in such a way that the engine
* <i>jumps</i> 2<sup>s</sup> steps ahead.
*
* @param s the 2<sup>s</sup> steps to jump ahead.
* @throws IllegalArgumentException if {@code s < 0}.
*/
public void jump2(final int s) {
if (s < 0) {
throw new IllegalArgumentException(String.format(
"s must be positive but was %d.", s
));
}
if (s >= Long.SIZE) {
throw new IllegalArgumentException(String.format(
"The 'jump2' size must be smaller than %d but was %d.",
Long.SIZE, s
));
}
_r = _r*pow(_a, 1L << s) + f(1L << s, _a)*_b;
}
/**
* Changes the internal state of the PRNG in such a way that the engine
* <i>jumps</i> s steps ahead.
*
* @param step the steps to jump ahead.
* @throws IllegalArgumentException if {@code s < 0}.
*/
public void jump(final long step) {
if (step < 0) {
throw new IllegalArgumentException(String.format(
"step must be positive but was %d", step
));
}
if (step < 16) {
for (int i = 0; i < step; ++i) {
step();
}
} else {
long s = step;
int i = 0;
while (s > 0) {
if (s%2 == 1) {
jump2(i);
}
++i;
s >>= 1;
}
}
}
private void backward() {
for (int i = 0; i < Long.SIZE; ++i) {
jump2(i);
}
}
@Override
public String toString() {
return String.format(
"%s[a=%d, b=%d, r=%d",
getClass().getName(), _a, _b, _r
);
}
@Override
public int hashCode() {
return hashCodeOf(getClass())
.and(_a).and(_b).and(_r)
.and(_seed).and(_param).value();
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof LCG64ShiftRandom)) {
return false;
}
final LCG64ShiftRandom random = (LCG64ShiftRandom)obj;
return _a == random._a &&
_b == random._b &&
_r == random._r &&
_seed == random._seed &&
_param.equals(random._param);
}
/**
* Compute prod(1+a^(2^i), i=0..l-1).
*/
private static long g(final int l, final long a) {
long p = a;
long res = 1;
for (int i = 0; i < l; ++i) {
res *= 1 + p;
p *= p;
}
return res;
}
/**
* Compute sum(a^i, i=0..s-1).
*/
private static long f(final long s, final long a) {
long y = 0;
if (s != 0) {
long e = log2Floor(s);
long p = a;
for (int l = 0; l <= e; ++l) {
if (((1L << l) & s) != 0) {
y = g(l, a) + p*y;
}
p *= p;
}
}
return y;
}
private static long pow(final long b, final long e) {
long base = b;
long exp = e;
long result = 1;
while (exp != 0) {
if ((exp & 1) != 0) {
result *= base;
}
base *= base;
exp >>>= 1;
}
return result;
}
private static long log2Floor(final long s) {
long x = s;
long y = 0;
while (x != 0) {
x >>>= 1;
++y;
}
return y - 1;
}
}
|
Update javadoc.
|
org.jenetics/src/main/java/org/jenetics/util/LCG64ShiftRandom.java
|
Update javadoc.
|
|
Java
|
apache-2.0
|
3992dcbe183f2edae1a79dae263ceff183742d25
| 0
|
takawitter/trie4j,takawitter/trie4j
|
/*
* Copyright 2014 Takao Nakaguchi
*
* 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.trie4j.bv;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
public class BytesConstantTimeSelect0SuccinctBitVector
implements Externalizable, SuccinctBitVector{
public BytesConstantTimeSelect0SuccinctBitVector(){
this(16);
}
public BytesConstantTimeSelect0SuccinctBitVector(int initialCapacity){
this.bytes = new byte[initialCapacity / 8 + 1];
int blockSize = CACHE_WIDTH;
int size = initialCapacity / blockSize + 1;
countCache0 = new int[size];
bvD = new LongsRank1OnlySuccinctBitVector();
bvR = new LongsRank1OnlySuccinctBitVector();
arS = new int[]{0};
arSSize = 1;
}
public BytesConstantTimeSelect0SuccinctBitVector(byte[] bytes, int bitsSize){
this.bytes = Arrays.copyOf(bytes, bytesSize(bitsSize));
this.size = bitsSize;
int cacheSize = countCache0Size(bitsSize);
countCache0 = new int[cacheSize + 1];
// cache, indexCache(0のCACHE_WIDTH個毎に位置を記憶), node1/2/3pos(0)
int n = bytes.length;
for(int i = 0; i < n; i++){
// 8bit毎に処理を行う
int b = bytes[i] & 0xff;
byte[] zeroPosInB = BITPOS0[b];
int rest = bitsSize - i * 8;
if(rest < 8){
// 残りより後の0の位置は扱わない
int nz = zeroPosInB.length;
for(int j = 0; j < nz; j++){
if(zeroPosInB[j] >= rest){
zeroPosInB = Arrays.copyOf(zeroPosInB, j);
break;
}
}
}
int zeroCount = zeroPosInB.length;
if(size0 < 3 && zeroCount > 0){
if(size0 == 0){
node1pos = zeroPosInB[0] + 8 * i;
if(zeroPosInB.length > 1) node2pos = zeroPosInB[1] + 8 * i;
if(zeroPosInB.length > 2) node3pos = zeroPosInB[2] + 8 * i;
} else if(size0 == 1){
node2pos = zeroPosInB[0] + 8 * i;
if(zeroPosInB.length > 1) node3pos = zeroPosInB[1] + 8 * i;
} else{
node3pos = zeroPosInB[0] + 8 * i;
}
}
size0 += zeroCount;
if((i + 1) % (CACHE_WIDTH / 8) == 0){
countCache0[i / (CACHE_WIDTH / 8)] = size0;
}
if(rest < 8) break;
}
countCache0[(size - 1) / CACHE_WIDTH] = size0;
}
public BytesConstantTimeSelect0SuccinctBitVector(
byte[] bytes, int size, int size0,
int node1pos, int node2pos, int node3pos,
int[] countCache0) {
this.bytes = bytes;
this.size = size;
this.size0 = size0;
this.node1pos = node1pos;
this.node2pos = node2pos;
this.node3pos = node3pos;
this.countCache0 = countCache0;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
int n = Math.min(size, 32);
for(int i = 0; i < n; i++){
b.append((bytes[(i / 8)] & (0x80 >> (i % 8))) != 0 ? "1" : "0");
}
return b.toString();
}
public byte[] getBytes(){
return bytes;
}
public int[] getCountCache0(){
return countCache0;
}
@Override
public boolean get(int pos) {
return isOne(pos);
}
public boolean isZero(int pos){
return (bytes[pos / 8] & BITS[pos % 8]) == 0;
}
public boolean isOne(int pos){
return (bytes[pos / 8] & BITS[pos % 8]) != 0;
}
public int size(){
return this.size;
}
public int getSize0() {
return size0;
}
public int getNode1pos() {
return node1pos;
}
public int getNode2pos() {
return node2pos;
}
public int getNode3pos() {
return node3pos;
}
public SuccinctBitVector getBvD() {
return bvD;
}
public SuccinctBitVector getBvR() {
return bvR;
}
public int[] getArS() {
return arS;
}
public int getArSSize() {
return arSSize;
}
public void trimToSize(){
bytes = Arrays.copyOf(bytes, bytesSize(size));
countCache0 = Arrays.copyOf(countCache0, countCache0Size(size));
bvD.trimToSize();
bvR.trimToSize();
arS = Arrays.copyOf(arS, arSSize);
}
public void append1(){
int blockIndex = size / 8;
int indexInBlock = size % 8;
int cacheBlockIndex = size / CACHE_WIDTH;
if(blockIndex >= bytes.length){
extend();
}
if(size % CACHE_WIDTH == 0 && cacheBlockIndex > 0){
countCache0[cacheBlockIndex] = countCache0[cacheBlockIndex - 1];
}
bytes[blockIndex] |= BITS[indexInBlock];
if(indexInBlock == 0){
// first bit in block
prevBsC = currentBsC;
currentBsC = false;
arS[arSSize - 1]++;
}
size++;
if(size % 8 == 0){
first0bitInBlock = true;
}
}
public void append0(){
int blockIndex = size / 8;
int indexInBlock = size % 8;
int cacheBlockIndex = size / CACHE_WIDTH;
int indexInCacheBlock = size % CACHE_WIDTH;
if(blockIndex >= bytes.length){
extend();
}
if(indexInCacheBlock== 0 && cacheBlockIndex > 0){
countCache0[cacheBlockIndex] = countCache0[cacheBlockIndex - 1];
}
size0++;
switch(size0){
case 1:
node1pos = size;
break;
case 2:
node2pos = size;
break;
case 3:
node3pos = size;
break;
}
countCache0[cacheBlockIndex]++;
// D, C, Rを構築
// Dはbytesの0bitに対応。8bitブロック内で最初に現れるものに1、連続する場合は0。
// Cはbytesの8bitブロックに対応。0を含むものに1、含まないものに0。
// RはCの1bitに対応。最初に現れるものに1、続いて現れるものに0。0は無視。
if(first0bitInBlock){
bvD.append1();
first0bitInBlock = false;
} else{
bvD.append0();
}
if(indexInBlock == 0){
//first bit
if(bvR.size() == 0 || !currentBsC){
bvR.append1();
addArS();
} else{
bvR.append0();
}
prevBsC = currentBsC;
currentBsC = true;
} else if(!currentBsC){
// turn from 0 to 1
if(bvR.size() == 0 || !prevBsC){
bvR.append1();
} else{
bvR.append0();
}
arS[arSSize - 1]--;
if(!prevBsC){
addArS();
}
currentBsC = true;
}
size++;
if(size % 8 == 0){
first0bitInBlock = true;
}
}
public void append(boolean bit){
if(bit) append1();
else append0();
}
public int rank1(int pos){
int ret = 0;
int cn = pos / CACHE_WIDTH;
if(cn > 0){
ret = cn * CACHE_WIDTH - countCache0[cn - 1];
}
int n = pos / 8;
for(int i = (cn * (CACHE_WIDTH / 8)); i < n; i++){
ret += BITCOUNTS1[bytes[i] & 0xff];
}
ret += BITCOUNTS1[bytes[n] & MASKS[pos % 8]];
return ret;
}
public int rank0(int pos){
int ret = 0;
int cn = pos / CACHE_WIDTH;
if(cn > 0){
ret = countCache0[cn - 1];
}
int n = pos / 8;
for(int i = (cn * (CACHE_WIDTH / 8)); i < n; i++){
ret += BITCOUNTS0[bytes[i] & 0xff];
}
ret += BITCOUNTS0[bytes[n] & MASKS[pos % 8]] - 7 + (pos % 8);
return ret;
}
public int rank(int pos, boolean b){
if(b) return rank1(pos);
else return rank0(pos);
}
public int select0(int count){
if(count > size) return -1;
if(count <= 3){
if(count == 1) return node1pos;
else if(count == 2) return node2pos;
else if(count == 3) return node3pos;
else return -1;
}
int c = count - 1;
int ci = bvD.rank1(c) - 1;
int u = ci + arS[bvR.rank1(ci) - 1];
int ui = u * 8;
int r = u == 0 ? 0 : rank0(ui - 1);
return ui + BITPOS0[bytes[u] & 0xff][c - r];
}
public int select1(int count){
for(int i = 0; i < bytes.length; i++){
if(i * 8 >= size) return -1;
int c = BITCOUNTS1[bytes[i] & 0xff];
if(count <= c){
int v = bytes[i] & 0xff;
for(int j = 0; j < 8; j++){
if(i * 8 + j >= size) return -1;
if((v & 0x80) != 0){
count--;
if(count == 0){
return i * 8 + j;
}
}
v <<= 1;
}
}
count -= c;
}
return -1;
}
public int select(int count, boolean b){
if(b) return select1(count);
else return select0(count);
}
public int next0(int pos){
if(pos >= size) return -1;
if(pos <= node3pos){
if(pos <= node1pos) return node1pos;
else if(pos <= node2pos) return node2pos;
else return node3pos;
}
int i = pos / 8;
int s = pos % 8;
if(s != 0){
for(byte b : BITPOS0[bytes[i] & 0xff]){
if(s <= b) return i * 8 + b;
}
i++;
}
int n = size / 8 + 1;
for(; i < n; i++){
byte[] poss = BITPOS0[bytes[i] & 0xff];
if(poss.length > 0){
return poss[0] + i * 8;
}
}
return -1;
}
@Override
public void readExternal(ObjectInput in)
throws ClassNotFoundException, IOException{
size = in.readInt();
size0 = in.readInt();
node1pos = in.readInt();
node2pos = in.readInt();
node3pos = in.readInt();
int vectorSize = in.readInt();
bytes = new byte[vectorSize];
in.readFully(bytes, 0, vectorSize);
countCache0 = (int[])in.readObject();
bvD = (SuccinctBitVector)in.readObject();
first0bitInBlock = in.readBoolean();
bvR = (SuccinctBitVector)in.readObject();
arS = (int[])in.readObject();
arSSize = in.readInt();
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(size);
out.writeInt(size0);
out.writeInt(node1pos);
out.writeInt(node2pos);
out.writeInt(node3pos);
trimToSize();
out.writeInt(bytes.length);
out.write(bytes);
out.writeObject(countCache0);
out.writeObject(bvD);
out.writeBoolean(first0bitInBlock);
out.writeObject(bvR);
out.writeObject(arS);
out.writeInt(arSSize);
}
private void extend(){
int vectorSize = (int)(bytes.length * 1.2) + 1;
bytes = Arrays.copyOf(bytes, vectorSize);
int blockSize = CACHE_WIDTH / 8;
int size = vectorSize / blockSize + (((vectorSize % blockSize) != 0) ? 1 : 0);
countCache0 = Arrays.copyOf(countCache0, size);
}
private void addArS(){
if(arSSize == arS.length){
arS = Arrays.copyOf(arS, (int)(arSSize * 1.2) + 1);
}
if(arSSize > 0){
arS[arSSize] = arS[arSSize - 1];
}
arSSize++;
}
private static int bytesSize(int bitSize){
return (bitSize - 1) / BITS_IN_BYTE + 1;
}
private static int countCache0Size(int bitSize){
return (bitSize - 1) / CACHE_WIDTH + 1;
}
private static final int BITS_IN_BYTE = 8;
private static final int CACHE_WIDTH = 64;
private byte[] bytes;
private int size;
private int size0;
private int node1pos = -1;
private int node2pos = -1;
private int node3pos = -1;
private int[] countCache0;
private SuccinctBitVector bvD;
private boolean first0bitInBlock = true;
private boolean prevBsC;
private boolean currentBsC;
private SuccinctBitVector bvR;
private int[] arS;
private int arSSize;
private static final int[] MASKS = {
0x80, 0xc0, 0xe0, 0xf0
, 0xf8, 0xfc, 0xfe, 0xff
};
private static final byte[] BITS = {
(byte)0x80, (byte)0x40, (byte)0x20, (byte)0x10
, (byte)0x08, (byte)0x04, (byte)0x02, (byte)0x01
};
private static final byte[] BITCOUNTS1 = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
private static final byte[] BITCOUNTS0 = {
8, 7, 7, 6, 7, 6, 6, 5, 7, 6, 6, 5, 6, 5, 5, 4,
7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3,
7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1,
7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1,
5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1,
4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0,
};
public static void main(String[] args) throws Exception{
System.out.println("\tprivate static final byte[][] BITPOS0 = {");
for(int i = 0; i < 256; i++){
int count = 0;
System.out.print("\t\t{");
for(int b = 0x80; b > 0; b >>= 1){
if((i & b) == 0){
System.out.print(count);
System.out.print(", ");
}
count++;
}
System.out.println("}, // " + String.format("%d(%1$x)", i));
}
System.out.println("\t};");
}
private static final byte[][] BITPOS0 = {
{0, 1, 2, 3, 4, 5, 6, 7, }, // 0(0)
{0, 1, 2, 3, 4, 5, 6, }, // 1(1)
{0, 1, 2, 3, 4, 5, 7, }, // 2(2)
{0, 1, 2, 3, 4, 5, }, // 3(3)
{0, 1, 2, 3, 4, 6, 7, }, // 4(4)
{0, 1, 2, 3, 4, 6, }, // 5(5)
{0, 1, 2, 3, 4, 7, }, // 6(6)
{0, 1, 2, 3, 4, }, // 7(7)
{0, 1, 2, 3, 5, 6, 7, }, // 8(8)
{0, 1, 2, 3, 5, 6, }, // 9(9)
{0, 1, 2, 3, 5, 7, }, // 10(a)
{0, 1, 2, 3, 5, }, // 11(b)
{0, 1, 2, 3, 6, 7, }, // 12(c)
{0, 1, 2, 3, 6, }, // 13(d)
{0, 1, 2, 3, 7, }, // 14(e)
{0, 1, 2, 3, }, // 15(f)
{0, 1, 2, 4, 5, 6, 7, }, // 16(10)
{0, 1, 2, 4, 5, 6, }, // 17(11)
{0, 1, 2, 4, 5, 7, }, // 18(12)
{0, 1, 2, 4, 5, }, // 19(13)
{0, 1, 2, 4, 6, 7, }, // 20(14)
{0, 1, 2, 4, 6, }, // 21(15)
{0, 1, 2, 4, 7, }, // 22(16)
{0, 1, 2, 4, }, // 23(17)
{0, 1, 2, 5, 6, 7, }, // 24(18)
{0, 1, 2, 5, 6, }, // 25(19)
{0, 1, 2, 5, 7, }, // 26(1a)
{0, 1, 2, 5, }, // 27(1b)
{0, 1, 2, 6, 7, }, // 28(1c)
{0, 1, 2, 6, }, // 29(1d)
{0, 1, 2, 7, }, // 30(1e)
{0, 1, 2, }, // 31(1f)
{0, 1, 3, 4, 5, 6, 7, }, // 32(20)
{0, 1, 3, 4, 5, 6, }, // 33(21)
{0, 1, 3, 4, 5, 7, }, // 34(22)
{0, 1, 3, 4, 5, }, // 35(23)
{0, 1, 3, 4, 6, 7, }, // 36(24)
{0, 1, 3, 4, 6, }, // 37(25)
{0, 1, 3, 4, 7, }, // 38(26)
{0, 1, 3, 4, }, // 39(27)
{0, 1, 3, 5, 6, 7, }, // 40(28)
{0, 1, 3, 5, 6, }, // 41(29)
{0, 1, 3, 5, 7, }, // 42(2a)
{0, 1, 3, 5, }, // 43(2b)
{0, 1, 3, 6, 7, }, // 44(2c)
{0, 1, 3, 6, }, // 45(2d)
{0, 1, 3, 7, }, // 46(2e)
{0, 1, 3, }, // 47(2f)
{0, 1, 4, 5, 6, 7, }, // 48(30)
{0, 1, 4, 5, 6, }, // 49(31)
{0, 1, 4, 5, 7, }, // 50(32)
{0, 1, 4, 5, }, // 51(33)
{0, 1, 4, 6, 7, }, // 52(34)
{0, 1, 4, 6, }, // 53(35)
{0, 1, 4, 7, }, // 54(36)
{0, 1, 4, }, // 55(37)
{0, 1, 5, 6, 7, }, // 56(38)
{0, 1, 5, 6, }, // 57(39)
{0, 1, 5, 7, }, // 58(3a)
{0, 1, 5, }, // 59(3b)
{0, 1, 6, 7, }, // 60(3c)
{0, 1, 6, }, // 61(3d)
{0, 1, 7, }, // 62(3e)
{0, 1, }, // 63(3f)
{0, 2, 3, 4, 5, 6, 7, }, // 64(40)
{0, 2, 3, 4, 5, 6, }, // 65(41)
{0, 2, 3, 4, 5, 7, }, // 66(42)
{0, 2, 3, 4, 5, }, // 67(43)
{0, 2, 3, 4, 6, 7, }, // 68(44)
{0, 2, 3, 4, 6, }, // 69(45)
{0, 2, 3, 4, 7, }, // 70(46)
{0, 2, 3, 4, }, // 71(47)
{0, 2, 3, 5, 6, 7, }, // 72(48)
{0, 2, 3, 5, 6, }, // 73(49)
{0, 2, 3, 5, 7, }, // 74(4a)
{0, 2, 3, 5, }, // 75(4b)
{0, 2, 3, 6, 7, }, // 76(4c)
{0, 2, 3, 6, }, // 77(4d)
{0, 2, 3, 7, }, // 78(4e)
{0, 2, 3, }, // 79(4f)
{0, 2, 4, 5, 6, 7, }, // 80(50)
{0, 2, 4, 5, 6, }, // 81(51)
{0, 2, 4, 5, 7, }, // 82(52)
{0, 2, 4, 5, }, // 83(53)
{0, 2, 4, 6, 7, }, // 84(54)
{0, 2, 4, 6, }, // 85(55)
{0, 2, 4, 7, }, // 86(56)
{0, 2, 4, }, // 87(57)
{0, 2, 5, 6, 7, }, // 88(58)
{0, 2, 5, 6, }, // 89(59)
{0, 2, 5, 7, }, // 90(5a)
{0, 2, 5, }, // 91(5b)
{0, 2, 6, 7, }, // 92(5c)
{0, 2, 6, }, // 93(5d)
{0, 2, 7, }, // 94(5e)
{0, 2, }, // 95(5f)
{0, 3, 4, 5, 6, 7, }, // 96(60)
{0, 3, 4, 5, 6, }, // 97(61)
{0, 3, 4, 5, 7, }, // 98(62)
{0, 3, 4, 5, }, // 99(63)
{0, 3, 4, 6, 7, }, // 100(64)
{0, 3, 4, 6, }, // 101(65)
{0, 3, 4, 7, }, // 102(66)
{0, 3, 4, }, // 103(67)
{0, 3, 5, 6, 7, }, // 104(68)
{0, 3, 5, 6, }, // 105(69)
{0, 3, 5, 7, }, // 106(6a)
{0, 3, 5, }, // 107(6b)
{0, 3, 6, 7, }, // 108(6c)
{0, 3, 6, }, // 109(6d)
{0, 3, 7, }, // 110(6e)
{0, 3, }, // 111(6f)
{0, 4, 5, 6, 7, }, // 112(70)
{0, 4, 5, 6, }, // 113(71)
{0, 4, 5, 7, }, // 114(72)
{0, 4, 5, }, // 115(73)
{0, 4, 6, 7, }, // 116(74)
{0, 4, 6, }, // 117(75)
{0, 4, 7, }, // 118(76)
{0, 4, }, // 119(77)
{0, 5, 6, 7, }, // 120(78)
{0, 5, 6, }, // 121(79)
{0, 5, 7, }, // 122(7a)
{0, 5, }, // 123(7b)
{0, 6, 7, }, // 124(7c)
{0, 6, }, // 125(7d)
{0, 7, }, // 126(7e)
{0, }, // 127(7f)
{1, 2, 3, 4, 5, 6, 7, }, // 128(80)
{1, 2, 3, 4, 5, 6, }, // 129(81)
{1, 2, 3, 4, 5, 7, }, // 130(82)
{1, 2, 3, 4, 5, }, // 131(83)
{1, 2, 3, 4, 6, 7, }, // 132(84)
{1, 2, 3, 4, 6, }, // 133(85)
{1, 2, 3, 4, 7, }, // 134(86)
{1, 2, 3, 4, }, // 135(87)
{1, 2, 3, 5, 6, 7, }, // 136(88)
{1, 2, 3, 5, 6, }, // 137(89)
{1, 2, 3, 5, 7, }, // 138(8a)
{1, 2, 3, 5, }, // 139(8b)
{1, 2, 3, 6, 7, }, // 140(8c)
{1, 2, 3, 6, }, // 141(8d)
{1, 2, 3, 7, }, // 142(8e)
{1, 2, 3, }, // 143(8f)
{1, 2, 4, 5, 6, 7, }, // 144(90)
{1, 2, 4, 5, 6, }, // 145(91)
{1, 2, 4, 5, 7, }, // 146(92)
{1, 2, 4, 5, }, // 147(93)
{1, 2, 4, 6, 7, }, // 148(94)
{1, 2, 4, 6, }, // 149(95)
{1, 2, 4, 7, }, // 150(96)
{1, 2, 4, }, // 151(97)
{1, 2, 5, 6, 7, }, // 152(98)
{1, 2, 5, 6, }, // 153(99)
{1, 2, 5, 7, }, // 154(9a)
{1, 2, 5, }, // 155(9b)
{1, 2, 6, 7, }, // 156(9c)
{1, 2, 6, }, // 157(9d)
{1, 2, 7, }, // 158(9e)
{1, 2, }, // 159(9f)
{1, 3, 4, 5, 6, 7, }, // 160(a0)
{1, 3, 4, 5, 6, }, // 161(a1)
{1, 3, 4, 5, 7, }, // 162(a2)
{1, 3, 4, 5, }, // 163(a3)
{1, 3, 4, 6, 7, }, // 164(a4)
{1, 3, 4, 6, }, // 165(a5)
{1, 3, 4, 7, }, // 166(a6)
{1, 3, 4, }, // 167(a7)
{1, 3, 5, 6, 7, }, // 168(a8)
{1, 3, 5, 6, }, // 169(a9)
{1, 3, 5, 7, }, // 170(aa)
{1, 3, 5, }, // 171(ab)
{1, 3, 6, 7, }, // 172(ac)
{1, 3, 6, }, // 173(ad)
{1, 3, 7, }, // 174(ae)
{1, 3, }, // 175(af)
{1, 4, 5, 6, 7, }, // 176(b0)
{1, 4, 5, 6, }, // 177(b1)
{1, 4, 5, 7, }, // 178(b2)
{1, 4, 5, }, // 179(b3)
{1, 4, 6, 7, }, // 180(b4)
{1, 4, 6, }, // 181(b5)
{1, 4, 7, }, // 182(b6)
{1, 4, }, // 183(b7)
{1, 5, 6, 7, }, // 184(b8)
{1, 5, 6, }, // 185(b9)
{1, 5, 7, }, // 186(ba)
{1, 5, }, // 187(bb)
{1, 6, 7, }, // 188(bc)
{1, 6, }, // 189(bd)
{1, 7, }, // 190(be)
{1, }, // 191(bf)
{2, 3, 4, 5, 6, 7, }, // 192(c0)
{2, 3, 4, 5, 6, }, // 193(c1)
{2, 3, 4, 5, 7, }, // 194(c2)
{2, 3, 4, 5, }, // 195(c3)
{2, 3, 4, 6, 7, }, // 196(c4)
{2, 3, 4, 6, }, // 197(c5)
{2, 3, 4, 7, }, // 198(c6)
{2, 3, 4, }, // 199(c7)
{2, 3, 5, 6, 7, }, // 200(c8)
{2, 3, 5, 6, }, // 201(c9)
{2, 3, 5, 7, }, // 202(ca)
{2, 3, 5, }, // 203(cb)
{2, 3, 6, 7, }, // 204(cc)
{2, 3, 6, }, // 205(cd)
{2, 3, 7, }, // 206(ce)
{2, 3, }, // 207(cf)
{2, 4, 5, 6, 7, }, // 208(d0)
{2, 4, 5, 6, }, // 209(d1)
{2, 4, 5, 7, }, // 210(d2)
{2, 4, 5, }, // 211(d3)
{2, 4, 6, 7, }, // 212(d4)
{2, 4, 6, }, // 213(d5)
{2, 4, 7, }, // 214(d6)
{2, 4, }, // 215(d7)
{2, 5, 6, 7, }, // 216(d8)
{2, 5, 6, }, // 217(d9)
{2, 5, 7, }, // 218(da)
{2, 5, }, // 219(db)
{2, 6, 7, }, // 220(dc)
{2, 6, }, // 221(dd)
{2, 7, }, // 222(de)
{2, }, // 223(df)
{3, 4, 5, 6, 7, }, // 224(e0)
{3, 4, 5, 6, }, // 225(e1)
{3, 4, 5, 7, }, // 226(e2)
{3, 4, 5, }, // 227(e3)
{3, 4, 6, 7, }, // 228(e4)
{3, 4, 6, }, // 229(e5)
{3, 4, 7, }, // 230(e6)
{3, 4, }, // 231(e7)
{3, 5, 6, 7, }, // 232(e8)
{3, 5, 6, }, // 233(e9)
{3, 5, 7, }, // 234(ea)
{3, 5, }, // 235(eb)
{3, 6, 7, }, // 236(ec)
{3, 6, }, // 237(ed)
{3, 7, }, // 238(ee)
{3, }, // 239(ef)
{4, 5, 6, 7, }, // 240(f0)
{4, 5, 6, }, // 241(f1)
{4, 5, 7, }, // 242(f2)
{4, 5, }, // 243(f3)
{4, 6, 7, }, // 244(f4)
{4, 6, }, // 245(f5)
{4, 7, }, // 246(f6)
{4, }, // 247(f7)
{5, 6, 7, }, // 248(f8)
{5, 6, }, // 249(f9)
{5, 7, }, // 250(fa)
{5, }, // 251(fb)
{6, 7, }, // 252(fc)
{6, }, // 253(fd)
{7, }, // 254(fe)
{}, // 255(ff)
};
private static final long serialVersionUID = -7658605229245494623L;
}
|
trie4j/src/org/trie4j/bv/BytesConstantTimeSelect0SuccinctBitVector.java
|
/*
* Copyright 2014 Takao Nakaguchi
*
* 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.trie4j.bv;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
public class BytesConstantTimeSelect0SuccinctBitVector
implements Externalizable, SuccinctBitVector{
public BytesConstantTimeSelect0SuccinctBitVector(){
this(16);
}
public BytesConstantTimeSelect0SuccinctBitVector(int initialCapacity){
this.bytes = new byte[initialCapacity / 8 + 1];
int blockSize = CACHE_WIDTH;
int size = initialCapacity / blockSize + 1;
countCache0 = new int[size];
bvD = new LongsRank1OnlySuccinctBitVector();
bvR = new LongsRank1OnlySuccinctBitVector();
arS = new int[]{0};
arSSize = 1;
}
public BytesConstantTimeSelect0SuccinctBitVector(byte[] bytes, int bitsSize){
this.bytes = Arrays.copyOf(bytes, containerBytesCount(bitsSize));
this.size = bitsSize;
int cacheSize = bitsSize / CACHE_WIDTH + 1;
countCache0 = new int[cacheSize + 1];
// cache, indexCache(0のCACHE_WIDTH個毎に位置を記憶), node1/2/3pos(0)
int n = bytes.length;
for(int i = 0; i < n; i++){
// 8bit毎に処理を行う
int b = bytes[i] & 0xff;
byte[] zeroPosInB = BITPOS0[b];
int rest = bitsSize - i * 8;
if(rest < 8){
// 残りより後の0の位置は扱わない
int nz = zeroPosInB.length;
for(int j = 0; j < nz; j++){
if(zeroPosInB[j] >= rest){
zeroPosInB = Arrays.copyOf(zeroPosInB, j);
break;
}
}
}
int zeroCount = zeroPosInB.length;
if(size0 < 3 && zeroCount > 0){
if(size0 == 0){
node1pos = zeroPosInB[0] + 8 * i;
if(zeroPosInB.length > 1) node2pos = zeroPosInB[1] + 8 * i;
if(zeroPosInB.length > 2) node3pos = zeroPosInB[2] + 8 * i;
} else if(size0 == 1){
node2pos = zeroPosInB[0] + 8 * i;
if(zeroPosInB.length > 1) node3pos = zeroPosInB[1] + 8 * i;
} else{
node3pos = zeroPosInB[0] + 8 * i;
}
}
size0 += zeroCount;
if((i + 1) % (CACHE_WIDTH / 8) == 0){
countCache0[i / (CACHE_WIDTH / 8)] = size0;
}
if(rest < 8) break;
}
countCache0[(size - 1) / CACHE_WIDTH] = size0;
}
public BytesConstantTimeSelect0SuccinctBitVector(
byte[] bytes, int size, int size0,
int node1pos, int node2pos, int node3pos,
int[] countCache0) {
this.bytes = bytes;
this.size = size;
this.size0 = size0;
this.node1pos = node1pos;
this.node2pos = node2pos;
this.node3pos = node3pos;
this.countCache0 = countCache0;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
int n = Math.min(size, 32);
for(int i = 0; i < n; i++){
b.append((bytes[(i / 8)] & (0x80 >> (i % 8))) != 0 ? "1" : "0");
}
return b.toString();
}
public byte[] getBytes(){
return bytes;
}
public int[] getCountCache0(){
return countCache0;
}
@Override
public boolean get(int pos) {
return isOne(pos);
}
public boolean isZero(int pos){
return (bytes[pos / 8] & BITS[pos % 8]) == 0;
}
public boolean isOne(int pos){
return (bytes[pos / 8] & BITS[pos % 8]) != 0;
}
public int size(){
return this.size;
}
public int getSize0() {
return size0;
}
public int getNode1pos() {
return node1pos;
}
public int getNode2pos() {
return node2pos;
}
public int getNode3pos() {
return node3pos;
}
public SuccinctBitVector getBvD() {
return bvD;
}
public SuccinctBitVector getBvR() {
return bvR;
}
public int[] getArS() {
return arS;
}
public int getArSSize() {
return arSSize;
}
public void trimToSize(){
int vectorSize = size / 8 + 1;
bytes = Arrays.copyOf(bytes, Math.min(bytes.length, vectorSize));
int blockSize = CACHE_WIDTH / 8;
int size = vectorSize / blockSize + (((vectorSize % blockSize) != 0) ? 1 : 0);
int countCacheSize0 = size;
countCache0 = Arrays.copyOf(countCache0, Math.min(countCache0.length, countCacheSize0));
bvD.trimToSize();
bvR.trimToSize();
arS = Arrays.copyOf(arS, arSSize);
}
public void append1(){
int blockIndex = size / 8;
int indexInBlock = size % 8;
int cacheBlockIndex = size / CACHE_WIDTH;
if(blockIndex >= bytes.length){
extend();
}
if(size % CACHE_WIDTH == 0 && cacheBlockIndex > 0){
countCache0[cacheBlockIndex] = countCache0[cacheBlockIndex - 1];
}
bytes[blockIndex] |= BITS[indexInBlock];
if(indexInBlock == 0){
// first bit in block
prevBsC = currentBsC;
currentBsC = false;
arS[arSSize - 1]++;
}
size++;
if(size % 8 == 0){
first0bitInBlock = true;
}
}
public void append0(){
int blockIndex = size / 8;
int indexInBlock = size % 8;
int cacheBlockIndex = size / CACHE_WIDTH;
int indexInCacheBlock = size % CACHE_WIDTH;
if(blockIndex >= bytes.length){
extend();
}
if(indexInCacheBlock== 0 && cacheBlockIndex > 0){
countCache0[cacheBlockIndex] = countCache0[cacheBlockIndex - 1];
}
size0++;
switch(size0){
case 1:
node1pos = size;
break;
case 2:
node2pos = size;
break;
case 3:
node3pos = size;
break;
}
countCache0[cacheBlockIndex]++;
// D, C, Rを構築
// Dはbytesの0bitに対応。8bitブロック内で最初に現れるものに1、連続する場合は0。
// Cはbytesの8bitブロックに対応。0を含むものに1、含まないものに0。
// RはCの1bitに対応。最初に現れるものに1、続いて現れるものに0。0は無視。
if(first0bitInBlock){
bvD.append1();
first0bitInBlock = false;
} else{
bvD.append0();
}
if(indexInBlock == 0){
//first bit
if(bvR.size() == 0 || !currentBsC){
bvR.append1();
addArS();
} else{
bvR.append0();
}
prevBsC = currentBsC;
currentBsC = true;
} else if(!currentBsC){
// turn from 0 to 1
if(bvR.size() == 0 || !prevBsC){
bvR.append1();
} else{
bvR.append0();
}
arS[arSSize - 1]--;
if(!prevBsC){
addArS();
}
currentBsC = true;
}
size++;
if(size % 8 == 0){
first0bitInBlock = true;
}
}
public void append(boolean bit){
if(bit) append1();
else append0();
}
public int rank1(int pos){
int ret = 0;
int cn = pos / CACHE_WIDTH;
if(cn > 0){
ret = cn * CACHE_WIDTH - countCache0[cn - 1];
}
int n = pos / 8;
for(int i = (cn * (CACHE_WIDTH / 8)); i < n; i++){
ret += BITCOUNTS1[bytes[i] & 0xff];
}
ret += BITCOUNTS1[bytes[n] & MASKS[pos % 8]];
return ret;
}
public int rank0(int pos){
int ret = 0;
int cn = pos / CACHE_WIDTH;
if(cn > 0){
ret = countCache0[cn - 1];
}
int n = pos / 8;
for(int i = (cn * (CACHE_WIDTH / 8)); i < n; i++){
ret += BITCOUNTS0[bytes[i] & 0xff];
}
ret += BITCOUNTS0[bytes[n] & MASKS[pos % 8]] - 7 + (pos % 8);
return ret;
}
public int rank(int pos, boolean b){
if(b) return rank1(pos);
else return rank0(pos);
}
public int select0(int count){
if(count > size) return -1;
if(count <= 3){
if(count == 1) return node1pos;
else if(count == 2) return node2pos;
else if(count == 3) return node3pos;
else return -1;
}
int c = count - 1;
int ci = bvD.rank1(c) - 1;
int u = ci + arS[bvR.rank1(ci) - 1];
int ui = u * 8;
int r = u == 0 ? 0 : rank0(ui - 1);
return ui + BITPOS0[bytes[u] & 0xff][c - r];
}
public int select1(int count){
for(int i = 0; i < bytes.length; i++){
if(i * 8 >= size) return -1;
int c = BITCOUNTS1[bytes[i] & 0xff];
if(count <= c){
int v = bytes[i] & 0xff;
for(int j = 0; j < 8; j++){
if(i * 8 + j >= size) return -1;
if((v & 0x80) != 0){
count--;
if(count == 0){
return i * 8 + j;
}
}
v <<= 1;
}
}
count -= c;
}
return -1;
}
public int select(int count, boolean b){
if(b) return select1(count);
else return select0(count);
}
public int next0(int pos){
if(pos >= size) return -1;
if(pos <= node3pos){
if(pos <= node1pos) return node1pos;
else if(pos <= node2pos) return node2pos;
else return node3pos;
}
int i = pos / 8;
int s = pos % 8;
if(s != 0){
for(byte b : BITPOS0[bytes[i] & 0xff]){
if(s <= b) return i * 8 + b;
}
i++;
}
int n = size / 8 + 1;
for(; i < n; i++){
byte[] poss = BITPOS0[bytes[i] & 0xff];
if(poss.length > 0){
return poss[0] + i * 8;
}
}
return -1;
}
@Override
public void readExternal(ObjectInput in)
throws ClassNotFoundException, IOException{
size = in.readInt();
size0 = in.readInt();
node1pos = in.readInt();
node2pos = in.readInt();
node3pos = in.readInt();
int vectorSize = in.readInt();
bytes = new byte[vectorSize];
in.readFully(bytes, 0, vectorSize);
countCache0 = (int[])in.readObject();
bvD = (SuccinctBitVector)in.readObject();
first0bitInBlock = in.readBoolean();
bvR = (SuccinctBitVector)in.readObject();
arS = (int[])in.readObject();
arSSize = in.readInt();
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(size);
out.writeInt(size0);
out.writeInt(node1pos);
out.writeInt(node2pos);
out.writeInt(node3pos);
trimToSize();
out.writeInt(bytes.length);
out.write(bytes);
out.writeObject(countCache0);
out.writeObject(bvD);
out.writeBoolean(first0bitInBlock);
out.writeObject(bvR);
out.writeObject(arS);
out.writeInt(arSSize);
}
private void extend(){
int vectorSize = (int)(bytes.length * 1.2) + 1;
bytes = Arrays.copyOf(bytes, vectorSize);
int blockSize = CACHE_WIDTH / 8;
int size = vectorSize / blockSize + (((vectorSize % blockSize) != 0) ? 1 : 0);
countCache0 = Arrays.copyOf(countCache0, size);
}
private void addArS(){
if(arSSize == arS.length){
arS = Arrays.copyOf(arS, (int)(arSSize * 1.2) + 1);
}
if(arSSize > 0){
arS[arSSize] = arS[arSSize - 1];
}
arSSize++;
}
private static int containerBytesCount(int size){
return size / 8 + ((size % 8) != 0 ? 1 : 0);
}
private static final int CACHE_WIDTH = 64;
private byte[] bytes;
private int size;
private int size0;
private int node1pos = -1;
private int node2pos = -1;
private int node3pos = -1;
private int[] countCache0;
private SuccinctBitVector bvD;
private boolean first0bitInBlock = true;
private boolean prevBsC;
private boolean currentBsC;
private SuccinctBitVector bvR;
private int[] arS;
private int arSSize;
private static final int[] MASKS = {
0x80, 0xc0, 0xe0, 0xf0
, 0xf8, 0xfc, 0xfe, 0xff
};
private static final byte[] BITS = {
(byte)0x80, (byte)0x40, (byte)0x20, (byte)0x10
, (byte)0x08, (byte)0x04, (byte)0x02, (byte)0x01
};
private static final byte[] BITCOUNTS1 = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
private static final byte[] BITCOUNTS0 = {
8, 7, 7, 6, 7, 6, 6, 5, 7, 6, 6, 5, 6, 5, 5, 4,
7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3,
7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1,
7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1,
6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2,
5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1,
5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1,
4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0,
};
public static void main(String[] args) throws Exception{
System.out.println("\tprivate static final byte[][] BITPOS0 = {");
for(int i = 0; i < 256; i++){
int count = 0;
System.out.print("\t\t{");
for(int b = 0x80; b > 0; b >>= 1){
if((i & b) == 0){
System.out.print(count);
System.out.print(", ");
}
count++;
}
System.out.println("}, // " + String.format("%d(%1$x)", i));
}
System.out.println("\t};");
}
private static final byte[][] BITPOS0 = {
{0, 1, 2, 3, 4, 5, 6, 7, }, // 0(0)
{0, 1, 2, 3, 4, 5, 6, }, // 1(1)
{0, 1, 2, 3, 4, 5, 7, }, // 2(2)
{0, 1, 2, 3, 4, 5, }, // 3(3)
{0, 1, 2, 3, 4, 6, 7, }, // 4(4)
{0, 1, 2, 3, 4, 6, }, // 5(5)
{0, 1, 2, 3, 4, 7, }, // 6(6)
{0, 1, 2, 3, 4, }, // 7(7)
{0, 1, 2, 3, 5, 6, 7, }, // 8(8)
{0, 1, 2, 3, 5, 6, }, // 9(9)
{0, 1, 2, 3, 5, 7, }, // 10(a)
{0, 1, 2, 3, 5, }, // 11(b)
{0, 1, 2, 3, 6, 7, }, // 12(c)
{0, 1, 2, 3, 6, }, // 13(d)
{0, 1, 2, 3, 7, }, // 14(e)
{0, 1, 2, 3, }, // 15(f)
{0, 1, 2, 4, 5, 6, 7, }, // 16(10)
{0, 1, 2, 4, 5, 6, }, // 17(11)
{0, 1, 2, 4, 5, 7, }, // 18(12)
{0, 1, 2, 4, 5, }, // 19(13)
{0, 1, 2, 4, 6, 7, }, // 20(14)
{0, 1, 2, 4, 6, }, // 21(15)
{0, 1, 2, 4, 7, }, // 22(16)
{0, 1, 2, 4, }, // 23(17)
{0, 1, 2, 5, 6, 7, }, // 24(18)
{0, 1, 2, 5, 6, }, // 25(19)
{0, 1, 2, 5, 7, }, // 26(1a)
{0, 1, 2, 5, }, // 27(1b)
{0, 1, 2, 6, 7, }, // 28(1c)
{0, 1, 2, 6, }, // 29(1d)
{0, 1, 2, 7, }, // 30(1e)
{0, 1, 2, }, // 31(1f)
{0, 1, 3, 4, 5, 6, 7, }, // 32(20)
{0, 1, 3, 4, 5, 6, }, // 33(21)
{0, 1, 3, 4, 5, 7, }, // 34(22)
{0, 1, 3, 4, 5, }, // 35(23)
{0, 1, 3, 4, 6, 7, }, // 36(24)
{0, 1, 3, 4, 6, }, // 37(25)
{0, 1, 3, 4, 7, }, // 38(26)
{0, 1, 3, 4, }, // 39(27)
{0, 1, 3, 5, 6, 7, }, // 40(28)
{0, 1, 3, 5, 6, }, // 41(29)
{0, 1, 3, 5, 7, }, // 42(2a)
{0, 1, 3, 5, }, // 43(2b)
{0, 1, 3, 6, 7, }, // 44(2c)
{0, 1, 3, 6, }, // 45(2d)
{0, 1, 3, 7, }, // 46(2e)
{0, 1, 3, }, // 47(2f)
{0, 1, 4, 5, 6, 7, }, // 48(30)
{0, 1, 4, 5, 6, }, // 49(31)
{0, 1, 4, 5, 7, }, // 50(32)
{0, 1, 4, 5, }, // 51(33)
{0, 1, 4, 6, 7, }, // 52(34)
{0, 1, 4, 6, }, // 53(35)
{0, 1, 4, 7, }, // 54(36)
{0, 1, 4, }, // 55(37)
{0, 1, 5, 6, 7, }, // 56(38)
{0, 1, 5, 6, }, // 57(39)
{0, 1, 5, 7, }, // 58(3a)
{0, 1, 5, }, // 59(3b)
{0, 1, 6, 7, }, // 60(3c)
{0, 1, 6, }, // 61(3d)
{0, 1, 7, }, // 62(3e)
{0, 1, }, // 63(3f)
{0, 2, 3, 4, 5, 6, 7, }, // 64(40)
{0, 2, 3, 4, 5, 6, }, // 65(41)
{0, 2, 3, 4, 5, 7, }, // 66(42)
{0, 2, 3, 4, 5, }, // 67(43)
{0, 2, 3, 4, 6, 7, }, // 68(44)
{0, 2, 3, 4, 6, }, // 69(45)
{0, 2, 3, 4, 7, }, // 70(46)
{0, 2, 3, 4, }, // 71(47)
{0, 2, 3, 5, 6, 7, }, // 72(48)
{0, 2, 3, 5, 6, }, // 73(49)
{0, 2, 3, 5, 7, }, // 74(4a)
{0, 2, 3, 5, }, // 75(4b)
{0, 2, 3, 6, 7, }, // 76(4c)
{0, 2, 3, 6, }, // 77(4d)
{0, 2, 3, 7, }, // 78(4e)
{0, 2, 3, }, // 79(4f)
{0, 2, 4, 5, 6, 7, }, // 80(50)
{0, 2, 4, 5, 6, }, // 81(51)
{0, 2, 4, 5, 7, }, // 82(52)
{0, 2, 4, 5, }, // 83(53)
{0, 2, 4, 6, 7, }, // 84(54)
{0, 2, 4, 6, }, // 85(55)
{0, 2, 4, 7, }, // 86(56)
{0, 2, 4, }, // 87(57)
{0, 2, 5, 6, 7, }, // 88(58)
{0, 2, 5, 6, }, // 89(59)
{0, 2, 5, 7, }, // 90(5a)
{0, 2, 5, }, // 91(5b)
{0, 2, 6, 7, }, // 92(5c)
{0, 2, 6, }, // 93(5d)
{0, 2, 7, }, // 94(5e)
{0, 2, }, // 95(5f)
{0, 3, 4, 5, 6, 7, }, // 96(60)
{0, 3, 4, 5, 6, }, // 97(61)
{0, 3, 4, 5, 7, }, // 98(62)
{0, 3, 4, 5, }, // 99(63)
{0, 3, 4, 6, 7, }, // 100(64)
{0, 3, 4, 6, }, // 101(65)
{0, 3, 4, 7, }, // 102(66)
{0, 3, 4, }, // 103(67)
{0, 3, 5, 6, 7, }, // 104(68)
{0, 3, 5, 6, }, // 105(69)
{0, 3, 5, 7, }, // 106(6a)
{0, 3, 5, }, // 107(6b)
{0, 3, 6, 7, }, // 108(6c)
{0, 3, 6, }, // 109(6d)
{0, 3, 7, }, // 110(6e)
{0, 3, }, // 111(6f)
{0, 4, 5, 6, 7, }, // 112(70)
{0, 4, 5, 6, }, // 113(71)
{0, 4, 5, 7, }, // 114(72)
{0, 4, 5, }, // 115(73)
{0, 4, 6, 7, }, // 116(74)
{0, 4, 6, }, // 117(75)
{0, 4, 7, }, // 118(76)
{0, 4, }, // 119(77)
{0, 5, 6, 7, }, // 120(78)
{0, 5, 6, }, // 121(79)
{0, 5, 7, }, // 122(7a)
{0, 5, }, // 123(7b)
{0, 6, 7, }, // 124(7c)
{0, 6, }, // 125(7d)
{0, 7, }, // 126(7e)
{0, }, // 127(7f)
{1, 2, 3, 4, 5, 6, 7, }, // 128(80)
{1, 2, 3, 4, 5, 6, }, // 129(81)
{1, 2, 3, 4, 5, 7, }, // 130(82)
{1, 2, 3, 4, 5, }, // 131(83)
{1, 2, 3, 4, 6, 7, }, // 132(84)
{1, 2, 3, 4, 6, }, // 133(85)
{1, 2, 3, 4, 7, }, // 134(86)
{1, 2, 3, 4, }, // 135(87)
{1, 2, 3, 5, 6, 7, }, // 136(88)
{1, 2, 3, 5, 6, }, // 137(89)
{1, 2, 3, 5, 7, }, // 138(8a)
{1, 2, 3, 5, }, // 139(8b)
{1, 2, 3, 6, 7, }, // 140(8c)
{1, 2, 3, 6, }, // 141(8d)
{1, 2, 3, 7, }, // 142(8e)
{1, 2, 3, }, // 143(8f)
{1, 2, 4, 5, 6, 7, }, // 144(90)
{1, 2, 4, 5, 6, }, // 145(91)
{1, 2, 4, 5, 7, }, // 146(92)
{1, 2, 4, 5, }, // 147(93)
{1, 2, 4, 6, 7, }, // 148(94)
{1, 2, 4, 6, }, // 149(95)
{1, 2, 4, 7, }, // 150(96)
{1, 2, 4, }, // 151(97)
{1, 2, 5, 6, 7, }, // 152(98)
{1, 2, 5, 6, }, // 153(99)
{1, 2, 5, 7, }, // 154(9a)
{1, 2, 5, }, // 155(9b)
{1, 2, 6, 7, }, // 156(9c)
{1, 2, 6, }, // 157(9d)
{1, 2, 7, }, // 158(9e)
{1, 2, }, // 159(9f)
{1, 3, 4, 5, 6, 7, }, // 160(a0)
{1, 3, 4, 5, 6, }, // 161(a1)
{1, 3, 4, 5, 7, }, // 162(a2)
{1, 3, 4, 5, }, // 163(a3)
{1, 3, 4, 6, 7, }, // 164(a4)
{1, 3, 4, 6, }, // 165(a5)
{1, 3, 4, 7, }, // 166(a6)
{1, 3, 4, }, // 167(a7)
{1, 3, 5, 6, 7, }, // 168(a8)
{1, 3, 5, 6, }, // 169(a9)
{1, 3, 5, 7, }, // 170(aa)
{1, 3, 5, }, // 171(ab)
{1, 3, 6, 7, }, // 172(ac)
{1, 3, 6, }, // 173(ad)
{1, 3, 7, }, // 174(ae)
{1, 3, }, // 175(af)
{1, 4, 5, 6, 7, }, // 176(b0)
{1, 4, 5, 6, }, // 177(b1)
{1, 4, 5, 7, }, // 178(b2)
{1, 4, 5, }, // 179(b3)
{1, 4, 6, 7, }, // 180(b4)
{1, 4, 6, }, // 181(b5)
{1, 4, 7, }, // 182(b6)
{1, 4, }, // 183(b7)
{1, 5, 6, 7, }, // 184(b8)
{1, 5, 6, }, // 185(b9)
{1, 5, 7, }, // 186(ba)
{1, 5, }, // 187(bb)
{1, 6, 7, }, // 188(bc)
{1, 6, }, // 189(bd)
{1, 7, }, // 190(be)
{1, }, // 191(bf)
{2, 3, 4, 5, 6, 7, }, // 192(c0)
{2, 3, 4, 5, 6, }, // 193(c1)
{2, 3, 4, 5, 7, }, // 194(c2)
{2, 3, 4, 5, }, // 195(c3)
{2, 3, 4, 6, 7, }, // 196(c4)
{2, 3, 4, 6, }, // 197(c5)
{2, 3, 4, 7, }, // 198(c6)
{2, 3, 4, }, // 199(c7)
{2, 3, 5, 6, 7, }, // 200(c8)
{2, 3, 5, 6, }, // 201(c9)
{2, 3, 5, 7, }, // 202(ca)
{2, 3, 5, }, // 203(cb)
{2, 3, 6, 7, }, // 204(cc)
{2, 3, 6, }, // 205(cd)
{2, 3, 7, }, // 206(ce)
{2, 3, }, // 207(cf)
{2, 4, 5, 6, 7, }, // 208(d0)
{2, 4, 5, 6, }, // 209(d1)
{2, 4, 5, 7, }, // 210(d2)
{2, 4, 5, }, // 211(d3)
{2, 4, 6, 7, }, // 212(d4)
{2, 4, 6, }, // 213(d5)
{2, 4, 7, }, // 214(d6)
{2, 4, }, // 215(d7)
{2, 5, 6, 7, }, // 216(d8)
{2, 5, 6, }, // 217(d9)
{2, 5, 7, }, // 218(da)
{2, 5, }, // 219(db)
{2, 6, 7, }, // 220(dc)
{2, 6, }, // 221(dd)
{2, 7, }, // 222(de)
{2, }, // 223(df)
{3, 4, 5, 6, 7, }, // 224(e0)
{3, 4, 5, 6, }, // 225(e1)
{3, 4, 5, 7, }, // 226(e2)
{3, 4, 5, }, // 227(e3)
{3, 4, 6, 7, }, // 228(e4)
{3, 4, 6, }, // 229(e5)
{3, 4, 7, }, // 230(e6)
{3, 4, }, // 231(e7)
{3, 5, 6, 7, }, // 232(e8)
{3, 5, 6, }, // 233(e9)
{3, 5, 7, }, // 234(ea)
{3, 5, }, // 235(eb)
{3, 6, 7, }, // 236(ec)
{3, 6, }, // 237(ed)
{3, 7, }, // 238(ee)
{3, }, // 239(ef)
{4, 5, 6, 7, }, // 240(f0)
{4, 5, 6, }, // 241(f1)
{4, 5, 7, }, // 242(f2)
{4, 5, }, // 243(f3)
{4, 6, 7, }, // 244(f4)
{4, 6, }, // 245(f5)
{4, 7, }, // 246(f6)
{4, }, // 247(f7)
{5, 6, 7, }, // 248(f8)
{5, 6, }, // 249(f9)
{5, 7, }, // 250(fa)
{5, }, // 251(fb)
{6, 7, }, // 252(fc)
{6, }, // 253(fd)
{7, }, // 254(fe)
{}, // 255(ff)
};
private static final long serialVersionUID = -7658605229245494623L;
}
|
improve calcuration of block size.
|
trie4j/src/org/trie4j/bv/BytesConstantTimeSelect0SuccinctBitVector.java
|
improve calcuration of block size.
|
|
Java
|
apache-2.0
|
f856bea4dd13ca3045d179369ce964006489285e
| 0
|
AliaksandrShuhayeu/pentaho-kettle,hudak/pentaho-kettle,stepanovdg/pentaho-kettle,pentaho/pentaho-kettle,tkafalas/pentaho-kettle,rmansoor/pentaho-kettle,matthewtckr/pentaho-kettle,mkambol/pentaho-kettle,rmansoor/pentaho-kettle,DFieldFL/pentaho-kettle,emartin-pentaho/pentaho-kettle,pminutillo/pentaho-kettle,SergeyTravin/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,pedrofvteixeira/pentaho-kettle,e-cuellar/pentaho-kettle,bmorrise/pentaho-kettle,pentaho/pentaho-kettle,Advent51/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,skofra0/pentaho-kettle,matthewtckr/pentaho-kettle,emartin-pentaho/pentaho-kettle,pavel-sakun/pentaho-kettle,bmorrise/pentaho-kettle,SergeyTravin/pentaho-kettle,hudak/pentaho-kettle,lgrill-pentaho/pentaho-kettle,roboguy/pentaho-kettle,ddiroma/pentaho-kettle,wseyler/pentaho-kettle,ccaspanello/pentaho-kettle,skofra0/pentaho-kettle,ddiroma/pentaho-kettle,tkafalas/pentaho-kettle,ViswesvarSekar/pentaho-kettle,nicoben/pentaho-kettle,hudak/pentaho-kettle,pedrofvteixeira/pentaho-kettle,SergeyTravin/pentaho-kettle,mbatchelor/pentaho-kettle,roboguy/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,mbatchelor/pentaho-kettle,aminmkhan/pentaho-kettle,graimundo/pentaho-kettle,mkambol/pentaho-kettle,ViswesvarSekar/pentaho-kettle,pavel-sakun/pentaho-kettle,Advent51/pentaho-kettle,skofra0/pentaho-kettle,mdamour1976/pentaho-kettle,marcoslarsen/pentaho-kettle,dkincade/pentaho-kettle,alina-ipatina/pentaho-kettle,rmansoor/pentaho-kettle,ViswesvarSekar/pentaho-kettle,pavel-sakun/pentaho-kettle,aminmkhan/pentaho-kettle,matthewtckr/pentaho-kettle,pavel-sakun/pentaho-kettle,mbatchelor/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,graimundo/pentaho-kettle,cjsonger/pentaho-kettle,denisprotopopov/pentaho-kettle,skofra0/pentaho-kettle,aminmkhan/pentaho-kettle,lgrill-pentaho/pentaho-kettle,stepanovdg/pentaho-kettle,DFieldFL/pentaho-kettle,nicoben/pentaho-kettle,Advent51/pentaho-kettle,marcoslarsen/pentaho-kettle,cjsonger/pentaho-kettle,stepanovdg/pentaho-kettle,pedrofvteixeira/pentaho-kettle,tkafalas/pentaho-kettle,zlcnju/kettle,HiromuHota/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,pentaho/pentaho-kettle,roboguy/pentaho-kettle,HiromuHota/pentaho-kettle,flbrino/pentaho-kettle,kurtwalker/pentaho-kettle,tmcsantos/pentaho-kettle,alina-ipatina/pentaho-kettle,pentaho/pentaho-kettle,zlcnju/kettle,tmcsantos/pentaho-kettle,zlcnju/kettle,kurtwalker/pentaho-kettle,DFieldFL/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,marcoslarsen/pentaho-kettle,dkincade/pentaho-kettle,marcoslarsen/pentaho-kettle,emartin-pentaho/pentaho-kettle,Advent51/pentaho-kettle,HiromuHota/pentaho-kettle,flbrino/pentaho-kettle,tkafalas/pentaho-kettle,wseyler/pentaho-kettle,lgrill-pentaho/pentaho-kettle,alina-ipatina/pentaho-kettle,mdamour1976/pentaho-kettle,graimundo/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,nicoben/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,e-cuellar/pentaho-kettle,SergeyTravin/pentaho-kettle,rmansoor/pentaho-kettle,aminmkhan/pentaho-kettle,ccaspanello/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,DFieldFL/pentaho-kettle,denisprotopopov/pentaho-kettle,tmcsantos/pentaho-kettle,ddiroma/pentaho-kettle,mdamour1976/pentaho-kettle,mbatchelor/pentaho-kettle,bmorrise/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,flbrino/pentaho-kettle,pedrofvteixeira/pentaho-kettle,pminutillo/pentaho-kettle,matthewtckr/pentaho-kettle,bmorrise/pentaho-kettle,mkambol/pentaho-kettle,lgrill-pentaho/pentaho-kettle,stepanovdg/pentaho-kettle,pminutillo/pentaho-kettle,zlcnju/kettle,kurtwalker/pentaho-kettle,cjsonger/pentaho-kettle,emartin-pentaho/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,hudak/pentaho-kettle,denisprotopopov/pentaho-kettle,ccaspanello/pentaho-kettle,cjsonger/pentaho-kettle,nicoben/pentaho-kettle,mdamour1976/pentaho-kettle,dkincade/pentaho-kettle,wseyler/pentaho-kettle,dkincade/pentaho-kettle,HiromuHota/pentaho-kettle,ccaspanello/pentaho-kettle,flbrino/pentaho-kettle,ddiroma/pentaho-kettle,wseyler/pentaho-kettle,alina-ipatina/pentaho-kettle,e-cuellar/pentaho-kettle,roboguy/pentaho-kettle,denisprotopopov/pentaho-kettle,tmcsantos/pentaho-kettle,mkambol/pentaho-kettle,e-cuellar/pentaho-kettle,graimundo/pentaho-kettle,pminutillo/pentaho-kettle,ViswesvarSekar/pentaho-kettle,kurtwalker/pentaho-kettle
|
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.memgroupby;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.memgroupby.MemoryGroupByMeta;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class MemoryGroupByDialog extends BaseStepDialog implements StepDialogInterface {
private static Class<?> PKG = MemoryGroupByMeta.class; // for i18n purposes, needed by Translator2!!
private Label wlGroup;
private TableView wGroup;
private FormData fdlGroup, fdGroup;
private Label wlAgg;
private TableView wAgg;
private FormData fdlAgg, fdAgg;
private Label wlAlwaysAddResult;
private Button wAlwaysAddResult;
private FormData fdlAlwaysAddResult, fdAlwaysAddResult;
private Button wGet, wGetAgg;
private FormData fdGet, fdGetAgg;
private Listener lsGet, lsGetAgg;
private MemoryGroupByMeta input;
private ColumnInfo[] ciKey;
private ColumnInfo[] ciReturn;
private Map<String, Integer> inputFields;
public MemoryGroupByDialog( Shell parent, Object in, TransMeta transMeta, String sname ) {
super( parent, (BaseStepMeta) in, transMeta, sname );
input = (MemoryGroupByMeta) in;
inputFields = new HashMap<String, Integer>();
}
@Override
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN );
props.setLook( shell );
setShellImage( shell, input );
ModifyListener lsMod = new ModifyListener() {
@Override
public void modifyText( ModifyEvent e ) {
input.setChanged();
}
};
SelectionListener lsSel = new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent arg0 ) {
input.setChanged();
}
};
backupChanged = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.Shell.Title" ) );
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname = new Label( shell, SWT.RIGHT );
wlStepname.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.Stepname.Label" ) );
props.setLook( wlStepname );
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment( 0, 0 );
fdlStepname.right = new FormAttachment( middle, -margin );
fdlStepname.top = new FormAttachment( 0, margin );
wlStepname.setLayoutData( fdlStepname );
wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wStepname.setText( stepname );
props.setLook( wStepname );
wStepname.addModifyListener( lsMod );
fdStepname = new FormData();
fdStepname.left = new FormAttachment( middle, 0 );
fdStepname.top = new FormAttachment( 0, margin );
fdStepname.right = new FormAttachment( 100, 0 );
wStepname.setLayoutData( fdStepname );
// Always pass a result rows as output
//
wlAlwaysAddResult = new Label( shell, SWT.RIGHT );
wlAlwaysAddResult.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.AlwaysAddResult.Label" ) );
wlAlwaysAddResult
.setToolTipText( BaseMessages.getString( PKG, "MemoryGroupByDialog.AlwaysAddResult.ToolTip" ) );
props.setLook( wlAlwaysAddResult );
fdlAlwaysAddResult = new FormData();
fdlAlwaysAddResult.left = new FormAttachment( 0, 0 );
fdlAlwaysAddResult.top = new FormAttachment( wStepname, margin );
fdlAlwaysAddResult.right = new FormAttachment( middle, -margin );
wlAlwaysAddResult.setLayoutData( fdlAlwaysAddResult );
wAlwaysAddResult = new Button( shell, SWT.CHECK );
wAlwaysAddResult.setToolTipText( BaseMessages.getString( PKG, "MemoryGroupByDialog.AlwaysAddResult.ToolTip" ) );
props.setLook( wAlwaysAddResult );
fdAlwaysAddResult = new FormData();
fdAlwaysAddResult.left = new FormAttachment( middle, 0 );
fdAlwaysAddResult.top = new FormAttachment( wStepname, margin );
fdAlwaysAddResult.right = new FormAttachment( 100, 0 );
wAlwaysAddResult.setLayoutData( fdAlwaysAddResult );
wAlwaysAddResult.addSelectionListener( lsSel );
wlGroup = new Label( shell, SWT.NONE );
wlGroup.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.Group.Label" ) );
props.setLook( wlGroup );
fdlGroup = new FormData();
fdlGroup.left = new FormAttachment( 0, 0 );
fdlGroup.top = new FormAttachment( wAlwaysAddResult, margin );
wlGroup.setLayoutData( fdlGroup );
int nrKeyCols = 1;
int nrKeyRows = ( input.getGroupField() != null ? input.getGroupField().length : 1 );
ciKey = new ColumnInfo[nrKeyCols];
ciKey[0] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.GroupField" ),
ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false );
wGroup =
new TableView(
transMeta, shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL, ciKey,
nrKeyRows, lsMod, props );
wGet = new Button( shell, SWT.PUSH );
wGet.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.GetFields.Button" ) );
fdGet = new FormData();
fdGet.top = new FormAttachment( wlGroup, margin );
fdGet.right = new FormAttachment( 100, 0 );
wGet.setLayoutData( fdGet );
fdGroup = new FormData();
fdGroup.left = new FormAttachment( 0, 0 );
fdGroup.top = new FormAttachment( wlGroup, margin );
fdGroup.right = new FormAttachment( wGet, -margin );
fdGroup.bottom = new FormAttachment( 45, 0 );
wGroup.setLayoutData( fdGroup );
// THE Aggregate fields
wlAgg = new Label( shell, SWT.NONE );
wlAgg.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.Aggregates.Label" ) );
props.setLook( wlAgg );
fdlAgg = new FormData();
fdlAgg.left = new FormAttachment( 0, 0 );
fdlAgg.top = new FormAttachment( wGroup, margin );
wlAgg.setLayoutData( fdlAgg );
int UpInsCols = 4;
int UpInsRows = ( input.getAggregateField() != null ? input.getAggregateField().length : 1 );
ciReturn = new ColumnInfo[UpInsCols];
ciReturn[0] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Name" ), ColumnInfo.COLUMN_TYPE_TEXT,
false );
ciReturn[1] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Subject" ),
ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false );
ciReturn[2] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Type" ), ColumnInfo.COLUMN_TYPE_CCOMBO,
MemoryGroupByMeta.typeGroupLongDesc );
ciReturn[3] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Value" ), ColumnInfo.COLUMN_TYPE_TEXT,
false );
ciReturn[3].setToolTip( BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Value.Tooltip" ) );
ciReturn[3].setUsingVariables( true );
wAgg =
new TableView(
transMeta, shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL, ciReturn,
UpInsRows, lsMod, props );
wGetAgg = new Button( shell, SWT.PUSH );
wGetAgg.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.GetLookupFields.Button" ) );
fdGetAgg = new FormData();
fdGetAgg.top = new FormAttachment( wlAgg, margin );
fdGetAgg.right = new FormAttachment( 100, 0 );
wGetAgg.setLayoutData( fdGetAgg );
//
// Search the fields in the background
final Runnable runnable = new Runnable() {
@Override
public void run() {
StepMeta stepMeta = transMeta.findStep( stepname );
if ( stepMeta != null ) {
try {
RowMetaInterface row = transMeta.getPrevStepFields( stepMeta );
// Remember these fields...
for ( int i = 0; i < row.size(); i++ ) {
inputFields.put( row.getValueMeta( i ).getName(), Integer.valueOf( i ) );
}
setComboBoxes();
} catch ( KettleException e ) {
logError( BaseMessages.getString( PKG, "System.Dialog.GetFieldsFailed.Message" ) );
}
}
}
};
new Thread( runnable ).start();
// THE BUTTONS
wOK = new Button( shell, SWT.PUSH );
wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
setButtonPositions( new Button[] { wOK, wCancel }, margin, null );
fdAgg = new FormData();
fdAgg.left = new FormAttachment( 0, 0 );
fdAgg.top = new FormAttachment( wlAgg, margin );
fdAgg.right = new FormAttachment( wGetAgg, -margin );
fdAgg.bottom = new FormAttachment( wOK, -margin );
wAgg.setLayoutData( fdAgg );
// Add listeners
lsOK = new Listener() {
@Override
public void handleEvent( Event e ) {
ok();
}
};
lsGet = new Listener() {
@Override
public void handleEvent( Event e ) {
get();
}
};
lsGetAgg = new Listener() {
@Override
public void handleEvent( Event e ) {
getAgg();
}
};
lsCancel = new Listener() {
@Override
public void handleEvent( Event e ) {
cancel();
}
};
wOK.addListener( SWT.Selection, lsOK );
wGet.addListener( SWT.Selection, lsGet );
wGetAgg.addListener( SWT.Selection, lsGetAgg );
wCancel.addListener( SWT.Selection, lsCancel );
lsDef = new SelectionAdapter() {
@Override
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
@Override
public void shellClosed( ShellEvent e ) {
cancel();
}
} );
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged( backupChanged );
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return stepname;
}
protected void setComboBoxes() {
// Something was changed in the row.
//
final Map<String, Integer> fields = new HashMap<String, Integer>();
// Add the currentMeta fields...
fields.putAll( inputFields );
Set<String> keySet = fields.keySet();
List<String> entries = new ArrayList<String>( keySet );
String[] fieldNames = entries.toArray( new String[entries.size()] );
Const.sortStrings( fieldNames );
ciKey[0].setComboValues( fieldNames );
ciReturn[1].setComboValues( fieldNames );
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
logDebug( BaseMessages.getString( PKG, "MemoryGroupByDialog.Log.GettingKeyInfo" ) );
wAlwaysAddResult.setSelection( input.isAlwaysGivingBackOneRow() );
if ( input.getGroupField() != null ) {
for ( int i = 0; i < input.getGroupField().length; i++ ) {
TableItem item = wGroup.table.getItem( i );
if ( input.getGroupField()[i] != null ) {
item.setText( 1, input.getGroupField()[i] );
}
}
}
if ( input.getAggregateField() != null ) {
for ( int i = 0; i < input.getAggregateField().length; i++ ) {
TableItem item = wAgg.table.getItem( i );
if ( input.getAggregateField()[i] != null ) {
item.setText( 1, input.getAggregateField()[i] );
}
if ( input.getSubjectField()[i] != null ) {
item.setText( 2, input.getSubjectField()[i] );
}
item.setText( 3, Const.NVL( MemoryGroupByMeta.getTypeDescLong( input.getAggregateType()[i] ), "" ) );
if ( input.getValueField()[i] != null ) {
item.setText( 4, input.getValueField()[i] );
}
}
}
wGroup.setRowNums();
wGroup.optWidth( true );
wAgg.setRowNums();
wAgg.optWidth( true );
wStepname.selectAll();
wStepname.setFocus();
}
private void cancel() {
stepname = null;
input.setChanged( backupChanged );
dispose();
}
private void ok() {
if ( Const.isEmpty( wStepname.getText() ) ) {
return;
}
int sizegroup = wGroup.nrNonEmpty();
int nrfields = wAgg.nrNonEmpty();
input.setAlwaysGivingBackOneRow( wAlwaysAddResult.getSelection() );
input.allocate( sizegroup, nrfields );
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < sizegroup; i++ ) {
TableItem item = wGroup.getNonEmpty( i );
input.getGroupField()[i] = item.getText( 1 );
}
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < nrfields; i++ ) {
TableItem item = wAgg.getNonEmpty( i );
input.getAggregateField()[i] = item.getText( 1 );
input.getSubjectField()[i] = item.getText( 2 );
input.getAggregateType()[i] = MemoryGroupByMeta.getType( item.getText( 3 ) );
input.getValueField()[i] = item.getText( 4 );
}
stepname = wStepname.getText();
dispose();
}
private void get() {
try {
RowMetaInterface r = transMeta.getPrevStepFields( stepname );
if ( r != null && !r.isEmpty() ) {
BaseStepDialog.getFieldsFromPrevious( r, wGroup, 1, new int[] { 1 }, new int[] {}, -1, -1, null );
}
} catch ( KettleException ke ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "MemoryGroupByDialog.FailedToGetFields.DialogTitle" ), BaseMessages
.getString( PKG, "MemoryGroupByDialog.FailedToGetFields.DialogMessage" ), ke );
}
}
private void getAgg() {
try {
RowMetaInterface r = transMeta.getPrevStepFields( stepname );
if ( r != null && !r.isEmpty() ) {
BaseStepDialog.getFieldsFromPrevious( r, wAgg, 1, new int[] { 1, 2 }, new int[] {}, -1, -1, null );
}
} catch ( KettleException ke ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "MemoryGroupByDialog.FailedToGetFields.DialogTitle" ), BaseMessages
.getString( PKG, "MemoryGroupByDialog.FailedToGetFields.DialogMessage" ), ke );
}
}
}
|
ui/src/org/pentaho/di/ui/trans/steps/memgroupby/MemoryGroupByDialog.java
|
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.memgroupby;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.memgroupby.MemoryGroupByMeta;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class MemoryGroupByDialog extends BaseStepDialog implements StepDialogInterface {
private static Class<?> PKG = MemoryGroupByMeta.class; // for i18n purposes, needed by Translator2!!
private Label wlGroup;
private TableView wGroup;
private FormData fdlGroup, fdGroup;
private Label wlAgg;
private TableView wAgg;
private FormData fdlAgg, fdAgg;
private Label wlAlwaysAddResult;
private Button wAlwaysAddResult;
private FormData fdlAlwaysAddResult, fdAlwaysAddResult;
private Button wGet, wGetAgg;
private FormData fdGet, fdGetAgg;
private Listener lsGet, lsGetAgg;
private MemoryGroupByMeta input;
private ColumnInfo[] ciKey;
private ColumnInfo[] ciReturn;
private Map<String, Integer> inputFields;
public MemoryGroupByDialog( Shell parent, Object in, TransMeta transMeta, String sname ) {
super( parent, (BaseStepMeta) in, transMeta, sname );
input = (MemoryGroupByMeta) in;
inputFields = new HashMap<String, Integer>();
}
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN );
props.setLook( shell );
setShellImage( shell, input );
ModifyListener lsMod = new ModifyListener() {
public void modifyText( ModifyEvent e ) {
input.setChanged();
}
};
backupChanged = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.Shell.Title" ) );
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname = new Label( shell, SWT.RIGHT );
wlStepname.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.Stepname.Label" ) );
props.setLook( wlStepname );
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment( 0, 0 );
fdlStepname.right = new FormAttachment( middle, -margin );
fdlStepname.top = new FormAttachment( 0, margin );
wlStepname.setLayoutData( fdlStepname );
wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wStepname.setText( stepname );
props.setLook( wStepname );
wStepname.addModifyListener( lsMod );
fdStepname = new FormData();
fdStepname.left = new FormAttachment( middle, 0 );
fdStepname.top = new FormAttachment( 0, margin );
fdStepname.right = new FormAttachment( 100, 0 );
wStepname.setLayoutData( fdStepname );
// Always pass a result rows as output
//
wlAlwaysAddResult = new Label( shell, SWT.RIGHT );
wlAlwaysAddResult.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.AlwaysAddResult.Label" ) );
wlAlwaysAddResult
.setToolTipText( BaseMessages.getString( PKG, "MemoryGroupByDialog.AlwaysAddResult.ToolTip" ) );
props.setLook( wlAlwaysAddResult );
fdlAlwaysAddResult = new FormData();
fdlAlwaysAddResult.left = new FormAttachment( 0, 0 );
fdlAlwaysAddResult.top = new FormAttachment( wStepname, margin );
fdlAlwaysAddResult.right = new FormAttachment( middle, -margin );
wlAlwaysAddResult.setLayoutData( fdlAlwaysAddResult );
wAlwaysAddResult = new Button( shell, SWT.CHECK );
wAlwaysAddResult.setToolTipText( BaseMessages.getString( PKG, "MemoryGroupByDialog.AlwaysAddResult.ToolTip" ) );
props.setLook( wAlwaysAddResult );
fdAlwaysAddResult = new FormData();
fdAlwaysAddResult.left = new FormAttachment( middle, 0 );
fdAlwaysAddResult.top = new FormAttachment( wStepname, margin );
fdAlwaysAddResult.right = new FormAttachment( 100, 0 );
wAlwaysAddResult.setLayoutData( fdAlwaysAddResult );
wlGroup = new Label( shell, SWT.NONE );
wlGroup.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.Group.Label" ) );
props.setLook( wlGroup );
fdlGroup = new FormData();
fdlGroup.left = new FormAttachment( 0, 0 );
fdlGroup.top = new FormAttachment( wAlwaysAddResult, margin );
wlGroup.setLayoutData( fdlGroup );
int nrKeyCols = 1;
int nrKeyRows = ( input.getGroupField() != null ? input.getGroupField().length : 1 );
ciKey = new ColumnInfo[nrKeyCols];
ciKey[0] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.GroupField" ),
ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false );
wGroup =
new TableView(
transMeta, shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL, ciKey,
nrKeyRows, lsMod, props );
wGet = new Button( shell, SWT.PUSH );
wGet.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.GetFields.Button" ) );
fdGet = new FormData();
fdGet.top = new FormAttachment( wlGroup, margin );
fdGet.right = new FormAttachment( 100, 0 );
wGet.setLayoutData( fdGet );
fdGroup = new FormData();
fdGroup.left = new FormAttachment( 0, 0 );
fdGroup.top = new FormAttachment( wlGroup, margin );
fdGroup.right = new FormAttachment( wGet, -margin );
fdGroup.bottom = new FormAttachment( 45, 0 );
wGroup.setLayoutData( fdGroup );
// THE Aggregate fields
wlAgg = new Label( shell, SWT.NONE );
wlAgg.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.Aggregates.Label" ) );
props.setLook( wlAgg );
fdlAgg = new FormData();
fdlAgg.left = new FormAttachment( 0, 0 );
fdlAgg.top = new FormAttachment( wGroup, margin );
wlAgg.setLayoutData( fdlAgg );
int UpInsCols = 4;
int UpInsRows = ( input.getAggregateField() != null ? input.getAggregateField().length : 1 );
ciReturn = new ColumnInfo[UpInsCols];
ciReturn[0] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Name" ), ColumnInfo.COLUMN_TYPE_TEXT,
false );
ciReturn[1] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Subject" ),
ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false );
ciReturn[2] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Type" ), ColumnInfo.COLUMN_TYPE_CCOMBO,
MemoryGroupByMeta.typeGroupLongDesc );
ciReturn[3] =
new ColumnInfo(
BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Value" ), ColumnInfo.COLUMN_TYPE_TEXT,
false );
ciReturn[3].setToolTip( BaseMessages.getString( PKG, "MemoryGroupByDialog.ColumnInfo.Value.Tooltip" ) );
ciReturn[3].setUsingVariables( true );
wAgg =
new TableView(
transMeta, shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL, ciReturn,
UpInsRows, lsMod, props );
wGetAgg = new Button( shell, SWT.PUSH );
wGetAgg.setText( BaseMessages.getString( PKG, "MemoryGroupByDialog.GetLookupFields.Button" ) );
fdGetAgg = new FormData();
fdGetAgg.top = new FormAttachment( wlAgg, margin );
fdGetAgg.right = new FormAttachment( 100, 0 );
wGetAgg.setLayoutData( fdGetAgg );
//
// Search the fields in the background
final Runnable runnable = new Runnable() {
public void run() {
StepMeta stepMeta = transMeta.findStep( stepname );
if ( stepMeta != null ) {
try {
RowMetaInterface row = transMeta.getPrevStepFields( stepMeta );
// Remember these fields...
for ( int i = 0; i < row.size(); i++ ) {
inputFields.put( row.getValueMeta( i ).getName(), Integer.valueOf( i ) );
}
setComboBoxes();
} catch ( KettleException e ) {
logError( BaseMessages.getString( PKG, "System.Dialog.GetFieldsFailed.Message" ) );
}
}
}
};
new Thread( runnable ).start();
// THE BUTTONS
wOK = new Button( shell, SWT.PUSH );
wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
setButtonPositions( new Button[] { wOK, wCancel }, margin, null );
fdAgg = new FormData();
fdAgg.left = new FormAttachment( 0, 0 );
fdAgg.top = new FormAttachment( wlAgg, margin );
fdAgg.right = new FormAttachment( wGetAgg, -margin );
fdAgg.bottom = new FormAttachment( wOK, -margin );
wAgg.setLayoutData( fdAgg );
// Add listeners
lsOK = new Listener() {
public void handleEvent( Event e ) {
ok();
}
};
lsGet = new Listener() {
public void handleEvent( Event e ) {
get();
}
};
lsGetAgg = new Listener() {
public void handleEvent( Event e ) {
getAgg();
}
};
lsCancel = new Listener() {
public void handleEvent( Event e ) {
cancel();
}
};
wOK.addListener( SWT.Selection, lsOK );
wGet.addListener( SWT.Selection, lsGet );
wGetAgg.addListener( SWT.Selection, lsGetAgg );
wCancel.addListener( SWT.Selection, lsCancel );
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
public void shellClosed( ShellEvent e ) {
cancel();
}
} );
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged( backupChanged );
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return stepname;
}
protected void setComboBoxes() {
// Something was changed in the row.
//
final Map<String, Integer> fields = new HashMap<String, Integer>();
// Add the currentMeta fields...
fields.putAll( inputFields );
Set<String> keySet = fields.keySet();
List<String> entries = new ArrayList<String>( keySet );
String[] fieldNames = entries.toArray( new String[entries.size()] );
Const.sortStrings( fieldNames );
ciKey[0].setComboValues( fieldNames );
ciReturn[1].setComboValues( fieldNames );
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
logDebug( BaseMessages.getString( PKG, "MemoryGroupByDialog.Log.GettingKeyInfo" ) );
wAlwaysAddResult.setSelection( input.isAlwaysGivingBackOneRow() );
if ( input.getGroupField() != null ) {
for ( int i = 0; i < input.getGroupField().length; i++ ) {
TableItem item = wGroup.table.getItem( i );
if ( input.getGroupField()[i] != null ) {
item.setText( 1, input.getGroupField()[i] );
}
}
}
if ( input.getAggregateField() != null ) {
for ( int i = 0; i < input.getAggregateField().length; i++ ) {
TableItem item = wAgg.table.getItem( i );
if ( input.getAggregateField()[i] != null ) {
item.setText( 1, input.getAggregateField()[i] );
}
if ( input.getSubjectField()[i] != null ) {
item.setText( 2, input.getSubjectField()[i] );
}
item.setText( 3, Const.NVL( MemoryGroupByMeta.getTypeDescLong( input.getAggregateType()[i] ), "" ) );
if ( input.getValueField()[i] != null ) {
item.setText( 4, input.getValueField()[i] );
}
}
}
wGroup.setRowNums();
wGroup.optWidth( true );
wAgg.setRowNums();
wAgg.optWidth( true );
wStepname.selectAll();
wStepname.setFocus();
}
private void cancel() {
stepname = null;
input.setChanged( backupChanged );
dispose();
}
private void ok() {
if ( Const.isEmpty( wStepname.getText() ) ) {
return;
}
int sizegroup = wGroup.nrNonEmpty();
int nrfields = wAgg.nrNonEmpty();
input.setAlwaysGivingBackOneRow( wAlwaysAddResult.getSelection() );
input.allocate( sizegroup, nrfields );
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < sizegroup; i++ ) {
TableItem item = wGroup.getNonEmpty( i );
input.getGroupField()[i] = item.getText( 1 );
}
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < nrfields; i++ ) {
TableItem item = wAgg.getNonEmpty( i );
input.getAggregateField()[i] = item.getText( 1 );
input.getSubjectField()[i] = item.getText( 2 );
input.getAggregateType()[i] = MemoryGroupByMeta.getType( item.getText( 3 ) );
input.getValueField()[i] = item.getText( 4 );
}
stepname = wStepname.getText();
dispose();
}
private void get() {
try {
RowMetaInterface r = transMeta.getPrevStepFields( stepname );
if ( r != null && !r.isEmpty() ) {
BaseStepDialog.getFieldsFromPrevious( r, wGroup, 1, new int[] { 1 }, new int[] {}, -1, -1, null );
}
} catch ( KettleException ke ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "MemoryGroupByDialog.FailedToGetFields.DialogTitle" ), BaseMessages
.getString( PKG, "MemoryGroupByDialog.FailedToGetFields.DialogMessage" ), ke );
}
}
private void getAgg() {
try {
RowMetaInterface r = transMeta.getPrevStepFields( stepname );
if ( r != null && !r.isEmpty() ) {
BaseStepDialog.getFieldsFromPrevious( r, wAgg, 1, new int[] { 1, 2 }, new int[] {}, -1, -1, null );
}
} catch ( KettleException ke ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "MemoryGroupByDialog.FailedToGetFields.DialogTitle" ), BaseMessages
.getString( PKG, "MemoryGroupByDialog.FailedToGetFields.DialogMessage" ), ke );
}
}
}
|
[PDI-15464] Memory Group By setChanged
|
ui/src/org/pentaho/di/ui/trans/steps/memgroupby/MemoryGroupByDialog.java
|
[PDI-15464] Memory Group By setChanged
|
|
Java
|
apache-2.0
|
27f53b562275f891e32bc6910a0afa0cdb9af550
| 0
|
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
|
package com.planet_ink.coffee_mud.Abilities.Common;
import com.planet_ink.coffee_mud.Abilities.StdAbility;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.MOB.Attrib;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.io.IOException;
import java.util.*;
/*
Copyright 2017-2017 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Studying extends CommonSkill
{
@Override
public String ID()
{
return "Studying";
}
private final static String localizedName = CMLib.lang().L("Studying");
@Override
public String name()
{
return localizedName;
}
protected static enum perLevelLimits
{
COMMON(1,6,1, ACODE_COMMON_SKILL, ACODE_LANGUAGE),
SKILL(1,6,2,ACODE_SKILL, ACODE_THIEF_SKILL),
SONG(1,6,3,ACODE_SONG, -1),
SPELL(1,6,4,ACODE_SPELL, -1),
CHANT(1,6,5,ACODE_CHANT, -1),
PRAYER(1,6,6,ACODE_PRAYER, -1)
;
private int type1 = -1;
private int type2 = -1;
private int num = 1;
private int perLevels = 1;
private int aboveLevel = 1;
private perLevelLimits(int num, int perLevels, int aboveLevel, int type1, int type2)
{
this.num=num;
this.perLevels=perLevels;
this.aboveLevel=aboveLevel;
this.type1=type1;
this.type2=type2;
}
public boolean doesRuleApplyTo(final Ability A)
{
return (A!=null)
&& (((A.classificationCode()&Ability.ALL_ACODES)==type1)
||((A.classificationCode()&Ability.ALL_ACODES)==type2));
}
public int numAllowed(final int classLevel)
{
if(classLevel < aboveLevel)
return 0;
return num + (num * (int)Math.round(Math.floor((classLevel-aboveLevel) / perLevels)));
}
}
protected perLevelLimits getSupportedSkillType()
{
return null;
}
@Override
public boolean isAutoInvoked()
{
return true;
}
@Override
public boolean canBeUninvoked()
{
return !isAnAutoEffect;
}
/*
* TODO:
When the command is initiated, it looks like a reverse TEACH. It will provide the teaching character
with a y/n dialogue option if they want to train the scholar, and it will tell them about how long to
train the scholar. .
We could also make this 6 different abilities Common Skill Studying, Skills
Studying, Songs Studying, Chants Studying, Spells Studying, and Prayers Studying if you would prefer
granting each ability at the lowest level above (1,2,3,4,5,6).
*/
protected Ability teachingA = null;
protected volatile boolean distributed = false;
protected boolean successfullyTaught = false;
protected List<Ability> skillList = new LinkedList<Ability>();
@Override
public void setMiscText(final String newMiscText)
{
super.setMiscText(newMiscText);
distributed = false;
}
@Override
public String displayText()
{
if(this.isNowAnAutoEffect())
return L("(Scholarly)"); // prevents it from being uninvokeable through autoaffects
final MOB invoker=this.invoker;
final Ability teachingA = this.teachingA;
final Physical affected = this.affected;
if((invoker != null)
&&(teachingA != null)
&&(affected instanceof MOB))
return L("You are teaching @x1 @x2.",invoker.name((MOB)affected),teachingA.name());
return L("You are teaching someone something somehow!");
}
@Override
protected int canAffectCode()
{
return CAN_MOBS;
}
@Override
protected int canTargetCode()
{
return CAN_MOBS;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_OK_OTHERS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_COMMON_SKILL;
}
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if((msg.source() == affected)
&&(!canBeUninvoked())
&&(msg.tool() instanceof Ability))
{
final MOB mob=msg.source();
if(msg.tool().ID().equals("Spell_Scribe")
||msg.tool().ID().equals("Spell_EnchantWand")
||msg.tool().ID().equals("Spell_MagicItem")
||msg.tool().ID().equals("Spell_StoreSpell")
||msg.tool().ID().equals("Spell_WardArea"))
{
final Ability A=mob.fetchAbility(msg.tool().text());
if((A!=null)&&(!A.isSavable()))
forget(mob,A.ID());
}
final Ability A=mob.fetchAbility(msg.tool().ID());
if((A!=null)&&(!A.isSavable())
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL))
forget(mob,A.ID());
}
}
protected boolean forget(final MOB mob, final String abilityID)
{
if(mob == null)
return false;
final Studying studA=(Studying)mob.fetchAbility(ID());
final Studying effA=(Studying)mob.fetchEffect(ID());
if((studA != null) && (effA != null))
{
final List<String> strList = CMParms.parseSemicolons(studA.text(), true);
for(int i=0;i<strList.size();i++)
{
if(strList.get(i).startsWith(abilityID+","))
{
strList.remove(i);
break;
}
}
final String text=CMParms.combineWith(strList,';');
for(final Ability A : effA.skillList)
{
if(A.ID().equalsIgnoreCase(abilityID))
{
mob.delAbility(A);
effA.setMiscText(text);
studA.setMiscText(text);
}
}
return true;
}
return false;
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!canBeUninvoked())
{
if((msg.source()==affected)
&&(msg.tool() instanceof Ability)
&&(skillList.contains(msg.tool())))
{
msg.source().tell(L("You don't know how to do that."));
return false;
}
else
if((msg.target()==affected)
&&(msg.targetMinor()==CMMsg.TYP_TEACH)
&&(msg.tool() instanceof Ability))
forget((MOB)msg.target(),msg.tool().ID());
}
return super.okMessage(myHost,msg);
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking, tickID))
return false;
if(!canBeUninvoked())
{
final MOB mob=(MOB)affected;
if((!distributed)
&&(affected instanceof MOB)
&&(isNowAnAutoEffect()))
{
boolean doWorkOn = false;
synchronized(skillList)
{
if(!distributed)
{
distributed=true;
doWorkOn=true;
}
}
if(doWorkOn)
{
if(skillList.size() > 0)
{
for(Ability a : skillList)
{
final Ability A=mob.fetchAbility(a.ID());
if((A!=null)&&(!A.isSavable()))
{
mob.delAbility(A);
final Ability fA=mob.fetchEffect(A.ID());
fA.unInvoke();
mob.delEffect(fA);
}
}
skillList.clear();
}
for(final String as : CMParms.parseSemicolons(text(), false))
{
final List<String> idProf = CMParms.parseCommas(as, true);
if(idProf.size()>1)
{
final Ability A=CMClass.getAbility(idProf.get(0));
if(A!=null)
{
A.setSavable(false);
A.setProficiency(CMath.s_int(idProf.get(1)));
mob.addAbility(A);
skillList.add(A);
}
}
}
}
}
}
else
if((affected instanceof MOB)&&(tickID==Tickable.TICKID_MOB))
{
final MOB mob=(MOB)affected;
final MOB invoker=this.invoker();
if((invoker == null)
||(invoker == mob)
||(invoker.location()!=mob.location())
||(invoker.isInCombat())
||(invoker.location()!=activityRoom)
||(!CMLib.flags().isAliveAwakeMobileUnbound(invoker,true)))
{
aborted=true;
unInvoke();
return false;
}
}
return true;
}
@Override
public void unInvoke()
{
if( canBeUninvoked()
&& (!super.unInvoked)
&& (affected instanceof MOB)
&& (!aborted))
{
final MOB mob=(MOB)affected;
final MOB invoker=this.invoker;
final Ability teachingA=this.teachingA;
if((mob!=null)
&&(invoker !=null)
&&(teachingA != null)
&&(mob.location()!=null)
&&(invoker.location()==mob.location()))
{
if(this.successfullyTaught)
{
final Ability A=invoker.fetchAbility(ID());
final Ability fA=invoker.fetchEffect(ID());
final Ability mTeachingA=mob.fetchAbility(teachingA.ID());
if((A==null)||(fA==null)||(mTeachingA==null)||(!A.isSavable())||(!fA.isNowAnAutoEffect()))
aborted=true;
else
{
final StringBuilder str=new StringBuilder(A.text());
if(str.length()>0)
str.append(';');
final int prof = mTeachingA.proficiency() + (5 * super.expertise(mob, mTeachingA, ExpertiseLibrary.Flag.LEVEL));
str.append(mTeachingA.ID()).append(',').append(prof);
fA.setMiscText(str.toString()); // and this should do it.
A.setMiscText(str.toString()); // and this should be savable
}
}
else
mob.location().show(mob,invoker,getActivityMessageType(),L("<S-NAME> fail(s) to teach <T-NAME> @x1.",teachingA.name()));
// let super announce it
}
}
this.teachingA=null;
super.unInvoke();
}
@Override
public boolean invoke(final MOB mob, List<String> commands, Physical givenTarget, final boolean auto, final int asLevel)
{
if(commands.size()==0)
{
mob.tell(L("You've been taught: "));
final List<List<String>> taughts = CMParms.parseDoubleDelimited(text(), ';', ',');
StringBuilder str=new StringBuilder("");
for(final List<String> l : taughts)
{
if(l.size()>1)
{
final Ability A=mob.fetchAbility(l.get(0));
final Ability eA=mob.fetchEffect(l.get(0));
final int prof=CMath.s_int(l.get(1));
if((A!=null)&&(!A.isSavable()))
{
A.setProficiency(prof);
if(eA!=null)
{
eA.unInvoke();
mob.delEffect(eA);
}
if(str.length()>0)
str.append(", ");
str.append(CMStrings.padRight(L(Ability.ACODE_DESCS[A.abilityCode()&Ability.ALL_ACODES]), 12)+": "+A.Name()+"\n\r");
}
}
}
mob.tell(str.toString());
}
if(commands.get(0).equalsIgnoreCase("FORGET") && (commands.size()>1))
{
commands.remove(0);
final Ability A=CMClass.findAbility(CMParms.combine(commands));
if(A!=null)
{
if(forget(mob,A.ID()))
mob.tell(L("You have forgotten @x1.",A.name()));
else
mob.tell(L("You haven't studied @x1.",A.name()));
}
}
if(commands.size()<2)
{
mob.tell(L("Have who teach you what?"));
return false;
}
List<String> name = new XVector<String>(commands.remove(0));
final MOB target=super.getTarget(mob, name, givenTarget);
if(target==null)
return false;
if(target == mob)
{
mob.tell(L("You can't teach yourself."));
return false;
}
if((target.isAttributeSet(MOB.Attrib.NOTEACH))
&&((!target.isMonster())||(!target.willFollowOrdersOf(mob))))
{
mob.tell(L("@x1 is not accepting students right now.",target.name(mob)));
return false;
}
final String skillName = CMParms.combine(commands);
final Ability A=CMClass.findAbility(skillName, mob);
if(A==null)
{
mob.tell(L("@x1 doesn't know '@x2'.",target.name(mob),skillName));
return false;
}
final int lowestQualifyingLevel = CMLib.ableMapper().lowestQualifyingLevel(A.ID());
final int classLevel = CMLib.ableMapper().qualifyingClassLevel(mob, this);
if((classLevel >=0)
&&(!auto)
&&(classLevel < lowestQualifyingLevel))
{
mob.tell(L("You aren't qualified to be taught @x1.",A.Name()));
return false;
}
final int teacherClassLevel = CMLib.ableMapper().qualifyingClassLevel(target, this);
if((teacherClassLevel <0)
&&(!auto))
{
mob.tell(L("@x1 isn't qualified to teach @x2.",target.name(mob),A.Name()));
return false;
}
perLevelLimits limitObj = null;
for(perLevelLimits l : perLevelLimits.values())
{
if(l.doesRuleApplyTo(A))
limitObj = l;
}
if(limitObj == null)
{
mob.tell(L("You can not study that sort of skill."));
return false;
}
if((getSupportedSkillType()!=null) && (getSupportedSkillType()!=limitObj))
{
mob.tell(L("You can not study that sort of skill with this one."));
return false;
}
int numAllowed = limitObj.numAllowed(classLevel);
int numHas = 0;
final List<List<String>> taughts = CMParms.parseDoubleDelimited(text(), ';', ',');
for(final List<String> l : taughts)
{
if(l.size()>0)
{
final Ability A1=CMClass.getAbility(l.get(0));
if(limitObj.doesRuleApplyTo(A1))
numHas++;
}
}
if(numHas >= numAllowed)
{
mob.tell(L("You may not study any more @x1 at this time.",CMLib.english().makePlural(Ability.ACODE_DESCS[A.abilityCode()&Ability.ALL_ACODES])));
return false;
}
if(!super.invoke(mob, commands, givenTarget, auto, asLevel))
return false;
final double quickPct = getXTIMELevel(mob) * 0.05;
final int teachTicks = (int)(((teacherClassLevel * 60000L)
- (10000L * (classLevel-teacherClassLevel))
- (15000L * super.getXLEVELLevel(mob))) / CMProps.getTickMillis());
final int duration=teachTicks-(int)Math.round(CMath.mul(teachTicks, quickPct));
final long minutes = (duration * CMProps.getTickMillis() / 60000L);
final long seconds = (duration * CMProps.getTickMillis() / 1000L);
/*
Training time should be (Skill's qualifying level by the teaching character in minutes
minus 10 seconds per level the teacher has over that, minus 15 seconds per expertise the scholar has, with
a minimum of 1 minute)
*/
successfullyTaught = super.proficiencyCheck(mob, 0, auto);
{
final Session sess = target.session();
final Ability thisOne=this;
final Runnable R=new Runnable()
{
final MOB M = mob;
final MOB tM = target;
final Ability tA = A;
final Ability oA = thisOne;
@Override
public void run()
{
verb=L("teaching @x1 about @x2",M.name(tM),tA.name());
displayText=L("You are @x1",verb);
String str=L("<T-NAME> start(s) teaching <S-NAME> about @x1.",tA.Name());
final CMMsg msg=CMClass.getMsg(mob,target,oA,CMMsg.MSG_NOISYMOVEMENT|(auto?CMMsg.MASK_ALWAYS:0),str);
final Room R=mob.location();
if(R!=null)
{
if(R.okMessage(mob,msg))
{
R.send(mob, msg);
//final Studying sA = (Studying)
beneficialAffect(mob,mob,asLevel,duration);
}
}
}
};
if(target.isMonster() || (sess==null))
R.run();
else
{
sess.prompt(new InputCallback(InputCallback.Type.CONFIRM,"N",0)
{
@Override
public void showPrompt()
{
String timeStr;
if(minutes<2)
timeStr = CMLib.lang().L("@x1 seconds",""+seconds);
else
timeStr = CMLib.lang().L("@x1 minutes",""+minutes);
sess.promptPrint(L("\n\r@x1 wants you to try to teach @x2 about @x3. It will take around @x4. Is that OK (y/N)? ",
mob.name(target), target.charStats().himher(), A.name(), timeStr));
}
@Override
public void timedOut()
{
}
@Override
public void callBack()
{
if (this.input.equals("Y"))
{
try
{
R.run();
}
catch (Exception e)
{
}
}
}
});
}
}
return true;
}
}
|
com/planet_ink/coffee_mud/Abilities/Common/Studying.java
|
package com.planet_ink.coffee_mud.Abilities.Common;
import com.planet_ink.coffee_mud.Abilities.StdAbility;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.MOB.Attrib;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.io.IOException;
import java.util.*;
/*
Copyright 2017-2017 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Studying extends CommonSkill
{
@Override
public String ID()
{
return "Studying";
}
private final static String localizedName = CMLib.lang().L("Studying");
@Override
public String name()
{
return localizedName;
}
protected static enum perLevelLimits
{
COMMON(1,6,1, ACODE_COMMON_SKILL, ACODE_LANGUAGE),
SKILL(1,6,2,ACODE_SKILL, ACODE_THIEF_SKILL),
SONG(1,6,3,ACODE_SONG, -1),
SPELL(1,6,4,ACODE_SPELL, -1),
CHANT(1,6,5,ACODE_CHANT, -1),
PRAYER(1,6,6,ACODE_PRAYER, -1)
;
private int type1 = -1;
private int type2 = -1;
private int num = 1;
private int perLevels = 1;
private int aboveLevel = 1;
private perLevelLimits(int num, int perLevels, int aboveLevel, int type1, int type2)
{
this.num=num;
this.perLevels=perLevels;
this.aboveLevel=aboveLevel;
this.type1=type1;
this.type2=type2;
}
public boolean doesRuleApplyTo(final Ability A)
{
return (A!=null)
&& (((A.classificationCode()&Ability.ALL_ACODES)==type1)
||((A.classificationCode()&Ability.ALL_ACODES)==type2));
}
public int numAllowed(final int classLevel)
{
if(classLevel < aboveLevel)
return 0;
return num + (num * (int)Math.round(Math.floor((classLevel-aboveLevel) / perLevels)));
}
}
protected perLevelLimits getSupportedSkillType()
{
return null;
}
@Override
public boolean isAutoInvoked()
{
return true;
}
@Override
public boolean canBeUninvoked()
{
return !isAnAutoEffect;
}
/*
* TODO:
When the command is initiated, it looks like a reverse TEACH. It will provide the teaching character
with a y/n dialogue option if they want to train the scholar, and it will tell them about how long to
train the scholar. .
We could also make this 6 different abilities Common Skill Studying, Skills
Studying, Songs Studying, Chants Studying, Spells Studying, and Prayers Studying if you would prefer
granting each ability at the lowest level above (1,2,3,4,5,6).
*/
protected Ability teachingA = null;
protected volatile boolean distributed = false;
protected boolean successfullyTaught = false;
protected List<Ability> skillList = new LinkedList<Ability>();
@Override
public void setMiscText(final String newMiscText)
{
super.setMiscText(newMiscText);
distributed = false;
}
@Override
public String displayText()
{
if(this.isNowAnAutoEffect())
return L("(Scholarly)"); // prevents it from being uninvokeable through autoaffects
final MOB invoker=this.invoker;
final Ability teachingA = this.teachingA;
final Physical affected = this.affected;
if((invoker != null)
&&(teachingA != null)
&&(affected instanceof MOB))
return L("You are teaching @x1 @x2.",invoker.name((MOB)affected),teachingA.name());
return L("You are teaching someone something somehow!");
}
@Override
protected int canAffectCode()
{
return CAN_MOBS;
}
@Override
protected int canTargetCode()
{
return CAN_MOBS;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_OK_OTHERS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_COMMON_SKILL;
}
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if((msg.source() == affected)
&&(!canBeUninvoked())
&&(msg.tool() instanceof Ability))
{
final MOB mob=msg.source();
if(msg.tool().ID().equals("Spell_Scribe")
||msg.tool().ID().equals("Spell_EnchantWand")
||msg.tool().ID().equals("Spell_MagicItem")
||msg.tool().ID().equals("Spell_StoreSpell")
||msg.tool().ID().equals("Spell_WardArea"))
{
final Ability A=mob.fetchAbility(msg.tool().text());
if((A!=null)&&(!A.isSavable()))
forget(mob,A.ID());
}
final Ability A=mob.fetchAbility(msg.tool().ID());
if((A!=null)&&(!A.isSavable())
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL))
forget(mob,A.ID());
}
}
protected boolean forget(final MOB mob, final String abilityID)
{
if(mob == null)
return false;
final Studying studA=(Studying)mob.fetchAbility(ID());
final Studying effA=(Studying)mob.fetchEffect(ID());
if((studA != null) && (effA != null))
{
final List<String> strList = CMParms.parseSemicolons(studA.text(), true);
for(int i=0;i<strList.size();i++)
{
if(strList.get(i).startsWith(abilityID+","))
{
strList.remove(i);
break;
}
}
final String text=CMParms.combineWith(strList,';');
for(final Ability A : effA.skillList)
{
if(A.ID().equalsIgnoreCase(abilityID))
{
mob.delAbility(A);
effA.setMiscText(text);
studA.setMiscText(text);
}
}
return true;
}
return false;
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!canBeUninvoked())
{
if((msg.source()==affected)
&&(msg.tool() instanceof Ability)
&&(skillList.contains(msg.tool())))
{
msg.source().tell(L("You don't know how to do that."));
return false;
}
else
if((msg.target()==affected)
&&(msg.targetMinor()==CMMsg.TYP_TEACH)
&&(msg.tool() instanceof Ability))
forget((MOB)msg.target(),msg.tool().ID());
}
return super.okMessage(myHost,msg);
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking, tickID))
return false;
if(!canBeUninvoked())
{
final MOB mob=(MOB)affected;
if((!distributed)
&&(affected instanceof MOB)
&&(isNowAnAutoEffect()))
{
boolean doWorkOn = false;
synchronized(skillList)
{
if(!distributed)
{
distributed=true;
doWorkOn=true;
}
}
if(doWorkOn)
{
if(skillList.size() > 0)
{
for(Ability a : skillList)
{
final Ability A=mob.fetchAbility(a.ID());
if((A!=null)&&(!A.isSavable()))
{
mob.delAbility(A);
final Ability fA=mob.fetchEffect(A.ID());
fA.unInvoke();
mob.delEffect(fA);
}
}
skillList.clear();
}
for(final String as : CMParms.parseSemicolons(text(), false))
{
final List<String> idProf = CMParms.parseCommas(as, true);
if(idProf.size()>1)
{
final Ability A=CMClass.getAbility(idProf.get(0));
if(A!=null)
{
A.setSavable(false);
A.setProficiency(CMath.s_int(idProf.get(1)));
mob.addAbility(A);
skillList.add(A);
}
}
}
}
}
}
else
if((affected instanceof MOB)&&(tickID==Tickable.TICKID_MOB))
{
final MOB mob=(MOB)affected;
final MOB invoker=this.invoker();
if((invoker == null)
||(invoker == mob)
||(invoker.location()!=mob.location())
||(invoker.isInCombat())
||(invoker.location()!=activityRoom)
||(!CMLib.flags().isAliveAwakeMobileUnbound(invoker,true)))
{
aborted=true;
unInvoke();
return false;
}
}
return true;
}
@Override
public void unInvoke()
{
if( canBeUninvoked()
&& (!super.unInvoked)
&& (affected instanceof MOB)
&& (!aborted))
{
final MOB mob=(MOB)affected;
final MOB invoker=this.invoker;
final Ability teachingA=this.teachingA;
if((mob!=null)
&&(invoker !=null)
&&(teachingA != null)
&&(mob.location()!=null)
&&(invoker.location()==mob.location()))
{
if(this.successfullyTaught)
{
final Ability A=invoker.fetchAbility(ID());
final Ability fA=invoker.fetchEffect(ID());
final Ability mTeachingA=mob.fetchAbility(teachingA.ID());
if((A==null)||(fA==null)||(mTeachingA==null)||(!A.isSavable())||(!fA.isNowAnAutoEffect()))
aborted=true;
else
{
final StringBuilder str=new StringBuilder(A.text());
if(str.length()>0)
str.append(';');
final int prof = mTeachingA.proficiency() + (5 * super.expertise(mob, mTeachingA, ExpertiseLibrary.Flag.LEVEL));
str.append(mTeachingA.ID()).append(',').append(prof);
fA.setMiscText(str.toString()); // and this should do it.
A.setMiscText(str.toString()); // and this should be savable
}
}
else
mob.location().show(mob,invoker,getActivityMessageType(),L("<S-NAME> fail(s) to teach <T-NAME> @x1.",teachingA.name()));
// let super announce it
}
}
this.teachingA=null;
super.unInvoke();
}
@Override
public boolean invoke(final MOB mob, List<String> commands, Physical givenTarget, final boolean auto, final int asLevel)
{
if(commands.size()==0)
{
mob.tell(L("You've been taught: "));
final List<List<String>> taughts = CMParms.parseDoubleDelimited(text(), ';', ',');
StringBuilder str=new StringBuilder("");
for(final List<String> l : taughts)
{
if(l.size()>1)
{
final Ability A=mob.fetchAbility(l.get(0));
final Ability eA=mob.fetchEffect(l.get(0));
final int prof=CMath.s_int(l.get(1));
if((A!=null)&&(!A.isSavable()))
{
A.setProficiency(prof);
if(eA!=null)
{
eA.unInvoke();
mob.delEffect(eA);
}
if(str.length()>0)
str.append(", ");
str.append(CMStrings.padRight(L(Ability.ACODE_DESCS[A.abilityCode()&Ability.ALL_ACODES]), 12)+": "+A.Name()+"\n\r");
}
}
}
mob.tell(str.toString());
}
if(commands.get(0).equalsIgnoreCase("FORGET") && (commands.size()>1))
{
commands.remove(0);
final Ability A=CMClass.findAbility(CMParms.combine(commands));
if(A!=null)
{
if(forget(mob,A.ID()))
mob.tell(L("You have forgotten @x1.",A.name()));
else
mob.tell(L("You haven't studied @x1.",A.name()));
}
}
if(commands.size()<2)
{
mob.tell(L("Have who teach you what?"));
return false;
}
List<String> name = new XVector<String>(commands.remove(0));
final MOB target=super.getTarget(mob, name, givenTarget);
if(target==null)
return false;
if(target == mob)
{
mob.tell(L("You can't teach yourself."));
return false;
}
if((target.isAttributeSet(MOB.Attrib.NOTEACH))
&&((!target.isMonster())||(!target.willFollowOrdersOf(mob))))
{
mob.tell(L("@x1 is not accepting students right now.",target.name(mob)));
return false;
}
final String skillName = CMParms.combine(commands);
final Ability A=CMClass.findAbility(skillName, mob);
if(A==null)
{
mob.tell(L("@x1 doesn't know '@x2'.",target.name(mob),skillName));
return false;
}
final int lowestQualifyingLevel = CMLib.ableMapper().lowestQualifyingLevel(A.ID());
final int classLevel = CMLib.ableMapper().qualifyingClassLevel(mob, this);
if((classLevel >=0)
&&(!auto)
&&(classLevel < lowestQualifyingLevel))
{
mob.tell(L("You aren't qualified to be taught @x1.",A.Name()));
return false;
}
final int teacherClassLevel = CMLib.ableMapper().qualifyingClassLevel(target, this);
if((teacherClassLevel <0)
&&(!auto))
{
mob.tell(L("@x1 isn't qualified to teach @x2.",target.name(mob),A.Name()));
return false;
}
perLevelLimits limitObj = null;
for(perLevelLimits l : perLevelLimits.values())
{
if(l.doesRuleApplyTo(A))
limitObj = l;
}
if(limitObj == null)
{
mob.tell(L("You can not study that sort of skill."));
return false;
}
if((getSupportedSkillType()!=null) && (getSupportedSkillType()!=limitObj))
{
mob.tell(L("You can not study that sort of skill with this one."));
return false;
}
int numAllowed = limitObj.numAllowed(classLevel);
int numHas = 0;
final List<List<String>> taughts = CMParms.parseDoubleDelimited(text(), ';', ',');
for(final List<String> l : taughts)
{
if(l.size()>0)
{
final Ability A1=CMClass.getAbility(l.get(0));
if(limitObj.doesRuleApplyTo(A1))
numHas++;
}
}
if(numHas >= numAllowed)
{
mob.tell(L("You may not study any more @x1 at this time.",CMLib.english().makePlural(Ability.ACODE_DESCS[A.abilityCode()&Ability.ALL_ACODES])));
return false;
}
if(!super.invoke(mob, commands, givenTarget, auto, asLevel))
return false;
final double quickPct = getXTIMELevel(mob) * 0.05;
final int teachTicks = (int)(((teacherClassLevel * 60000L)
- (10000L * (classLevel-teacherClassLevel))
- (15000L * super.getXLEVELLevel(mob))) / CMProps.getTickMillis());
final int duration=teachTicks-(int)Math.round(CMath.mul(teachTicks, quickPct));
final long minutes = (duration * CMProps.getTickMillis() / 60000L);
final long seconds = (duration * CMProps.getTickMillis() / 1000L);
/*
Training time should be (Skills qualifying level by the teaching character in minutes
minus 10 seconds per level the teacher has over that, minus 15 seconds per expertise the scholar has, with
a minimum of 1 minute)
*/
successfullyTaught = super.proficiencyCheck(mob, 0, auto);
{
final Session sess = target.session();
final Ability thisOne=this;
final Runnable R=new Runnable()
{
final MOB M = mob;
final MOB tM = target;
final Ability tA = A;
final Ability oA = thisOne;
@Override
public void run()
{
verb=L("teaching @x1 about @x2",M.name(tM),tA.name());
displayText=L("You are @x1",verb);
String str=L("<T-NAME> start(s) teaching <S-NAME> about @x1.",tA.Name());
final CMMsg msg=CMClass.getMsg(mob,target,oA,CMMsg.MSG_NOISYMOVEMENT|(auto?CMMsg.MASK_ALWAYS:0),str);
final Room R=mob.location();
if(R!=null)
{
if(R.okMessage(mob,msg))
{
R.send(mob, msg);
//final Studying sA = (Studying)
beneficialAffect(mob,mob,asLevel,duration);
}
}
}
};
if(target.isMonster() || (sess==null))
R.run();
else
{
sess.prompt(new InputCallback(InputCallback.Type.CONFIRM,"N",0)
{
@Override
public void showPrompt()
{
String timeStr;
if(minutes<2)
timeStr = CMLib.lang().L("@x1 seconds",""+seconds);
else
timeStr = CMLib.lang().L("@x1 minutes",""+minutes);
sess.promptPrint(L("\n\r@x1 wants you to try to teach @x2 about @x3. It will take around @x4. Is that OK (y/N)? ",
mob.name(target), target.charStats().himher(), A.name(), timeStr));
}
@Override
public void timedOut()
{
}
@Override
public void callBack()
{
if (this.input.equals("Y"))
{
try
{
R.run();
}
catch (Exception e)
{
}
}
}
});
}
}
return true;
}
}
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@14996 0d6f1817-ed0e-0410-87c9-987e46238f29
|
com/planet_ink/coffee_mud/Abilities/Common/Studying.java
| ||
Java
|
apache-2.0
|
d6a4f6c9ac36fc9bb39ab614791e697ae8e3cc39
| 0
|
kryptnostic/kodex
|
package com.kryptnostic.storage.v2.http;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Path;
import com.kryptnostic.storage.v2.models.ObjectMetadataNode;
import com.kryptnostic.v2.constants.Names;
/**
*
* @author Matthew Tamayo-Rios <matthew@kryptnostic.com>
*
*/
public interface ObjectListingApi {
String CONTROLLER = "/objects";
String TYPE = "type";
String PAGE = Names.PAGE_FIELD;
String PAGE_SIZE = Names.SIZE_FIELD;
String ID = Names.ID_FIELD;
String LATEST_PATH = "/latest";
String USER_ID_PATH = "/{" + ID + "}";
String TYPE_ID_PATH = "/{" + TYPE + "}";
String PAGE_SIZE_PATH = "/{" + PAGE_SIZE + "}";
String PAGE_PATH = "/{" + PAGE + "}";
@GET( CONTROLLER + USER_ID_PATH )
Set<UUID> getObjectIds( @Path( ID ) UUID userId );
@GET( CONTROLLER + USER_ID_PATH + PAGE_SIZE_PATH )
Set<UUID> getLatestUnfinishedPageOfObjectIds(
@Path( ID ) UUID userId,
@Path( PAGE_SIZE ) Integer pageSize );
@GET( CONTROLLER + USER_ID_PATH + TYPE_ID_PATH + PAGE_SIZE_PATH )
Set<UUID> getLatestUnfinishedPageOfObjectIdsByType(
@Path( ID ) UUID userId,
@Path( TYPE ) UUID typeId,
@Path( PAGE_SIZE ) Integer pageSize );
/**
* Retrieves all objects owned by a given a user. This is a slow call / uncached call.
*
* @param userId The userId for which to return the list of paged objects.
* @return The UUID of all objects owned by the user.
*/
@GET( CONTROLLER + USER_ID_PATH )
Set<UUID> getAllObjectIds( @Path( ID ) UUID userId );
@GET( CONTROLLER + USER_ID_PATH + PAGE_SIZE_PATH + PAGE_PATH )
Set<UUID> getAllObjectIdsPaged(
@Path( ID ) UUID userId,
@Path( PAGE ) Integer offset,
@Path( PAGE_SIZE ) Integer pageSize );
@GET( CONTROLLER + USER_ID_PATH + TYPE_ID_PATH )
Set<UUID> getObjectIdsByType( @Path( ID ) UUID userId, @Path( TYPE ) UUID type );
@GET( CONTROLLER + USER_ID_PATH + TYPE_ID_PATH + PAGE_SIZE_PATH + PAGE_PATH )
Set<UUID> getObjectIdsByTypePaged(
@Path( ID ) UUID userId,
@Path( TYPE ) UUID typeId,
@Path( PAGE ) Integer offset,
@Path( PAGE_SIZE ) Integer pageSize );
@POST( CONTROLLER )
Map<UUID, ObjectMetadataNode> getObjectMetadataTrees( @Body Set<UUID> objectIds );
}
|
src/main/java/com/kryptnostic/storage/v2/http/ObjectListingApi.java
|
package com.kryptnostic.storage.v2.http;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Path;
import com.kryptnostic.storage.v2.models.ObjectMetadataNode;
import com.kryptnostic.v2.constants.Names;
/**
*
* @author Matthew Tamayo-Rios <matthew@kryptnostic.com>
*
*/
public interface ObjectListingApi {
String CONTROLLER = "/objects";
String TYPE = "type";
String PAGE = Names.PAGE_FIELD;
String PAGE_SIZE = Names.SIZE_FIELD;
String ID = Names.ID_FIELD;
String LATEST_PATH = "/latest";
String USER_ID_PATH = "/{" + ID + "}";
String TYPE_ID_PATH = "/{" + TYPE + "}";
String PAGE_SIZE_PATH = "/{" + PAGE_SIZE + "}";
String PAGE_PATH = "/{" + PAGE + "}";
@GET( CONTROLLER + USER_ID_PATH )
Set<UUID> getObjectIds();
@GET( CONTROLLER + USER_ID_PATH + PAGE_SIZE_PATH )
Set<UUID> getLatestUnfinishedPageOfObjectIds(
@Path( ID ) UUID userId,
@Path( PAGE_SIZE ) Integer pageSize );
@GET( CONTROLLER + USER_ID_PATH + TYPE_ID_PATH + PAGE_SIZE_PATH )
Set<UUID> getLatestUnfinishedPageOfObjectIdsByType(
@Path( ID ) UUID userId,
@Path( TYPE ) UUID typeId,
@Path( PAGE_SIZE ) Integer pageSize );
/**
* Retrieves all objects owned by a given a user. This is a slow call / uncached call.
*
* @param userId The userId for which to return the list of paged objects.
* @return The UUID of all objects owned by the user.
*/
@GET( CONTROLLER + USER_ID_PATH )
Set<UUID> getAllObjectIds( @Path( ID ) UUID userId );
@GET( CONTROLLER + USER_ID_PATH + PAGE_SIZE_PATH + PAGE_PATH )
Set<UUID> getAllObjectIdsPaged(
@Path( ID ) UUID userId,
@Path( PAGE ) Integer offset,
@Path( PAGE_SIZE ) Integer pageSize );
@GET( CONTROLLER + USER_ID_PATH + TYPE_ID_PATH )
Set<UUID> getObjectIdsByType( @Path( ID ) UUID userId, @Path( TYPE ) UUID type );
@GET( CONTROLLER + USER_ID_PATH + TYPE_ID_PATH + PAGE_SIZE_PATH + PAGE_PATH )
Set<UUID> getObjectIdsByTypePaged(
@Path( ID ) UUID userId,
@Path( TYPE ) UUID typeId,
@Path( PAGE ) Integer offset,
@Path( PAGE_SIZE ) Integer pageSize );
@POST( CONTROLLER )
Map<UUID, ObjectMetadataNode> getObjectMetadataTrees( @Body Set<UUID> objectIds );
}
|
add parameter for getOBjectIds
|
src/main/java/com/kryptnostic/storage/v2/http/ObjectListingApi.java
|
add parameter for getOBjectIds
|
|
Java
|
apache-2.0
|
cd3ff6a783760bdc875ec14db00cd00a15c7b64c
| 0
|
sepetnit/j-heuristic-search-framework,sepetnit/j-heuristic-search-framework
|
package org.cs4j.core.mains;
import org.cs4j.core.SearchDomain;
import org.cs4j.core.domains.*;
import java.io.*;
/**
* Created by sepetnit on 11/10/2015.
*
*/
public class DomainsCreation {
/*******************************************************************************************************************
* Private static methods : Domains creation
******************************************************************************************************************/
public static SearchDomain createGridPathFindingInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/gridpathfinding/generated/maze512-1-6.map/" + instance));
//InputStream is = new FileInputStream(new File("input/gridpathfinding/generated/den400d.map/" + instance));
return new GridPathFinding(is);
}
public static SearchDomain createGridPathFindingInstanceFromAutomaticallyGeneratedWithTDH(
String instance, int pivotsCount) throws IOException {
String mapFileName = "input/gridpathfinding/generated/brc202d.map";
//String mapFileName = "input/gridpathfinding/generated/maze512-1-6.map";
//String pivotsFileName = "input/gridpathfinding/raw/maps/" + new File(mapFileName).getName() + ".pivots.pdb";
//String pivotsFileName = "input/gridpathfinding/raw/mazes/maze1/_maze512-1-6-80.map.pivots.pdb";
String pivotsFileName = "input/gridpathfinding/raw/maps/brc202d.map.pivots.pdb";
InputStream is = new FileInputStream(new File(mapFileName + "/" + instance));
GridPathFinding problem = new GridPathFinding(is);
//problem.setAdditionalParameter("heuristic", "dh-furthest");
//problem.setAdditionalParameter("heuristic", "dh-md-average-md-if-dh-is-0");
//problem.setAdditionalParameter("heuristic", "dh-random-pivot");
problem.setAdditionalParameter("heuristic", "dh-random-pivots");
problem.setAdditionalParameter("random-pivots-count", 9 + "");
//problem.setAdditionalParameter("heuristic", "random-dh-md");
problem.setAdditionalParameter("pivots-distances-db-file", pivotsFileName);
problem.setAdditionalParameter("pivots-count", pivotsCount + "");
return problem;
}
public static SearchDomain createGridPathFindingInstanceFromAutomaticallyGeneratedWithTDH(SearchDomain previous,
String instance,
int pivotsCount)
throws IOException {
String mapFileName = "input/gridpathfinding/generated/brc202d.map";
//String mapFileName = "input/gridpathfinding/generated/maze512-1-6.map";
InputStream is = new FileInputStream(new File(mapFileName, instance));
GridPathFinding problem = new GridPathFinding((GridPathFinding)previous, is);
// Change the number of pivots
problem.setAdditionalParameter("pivots-count", pivotsCount + "");
return problem;
}
// The k is for GAP-k heuristic setting
public static SearchDomain createPancakesInstanceFromAutomaticallyGenerated(int size, String instance, int k) throws FileNotFoundException {
Pancakes toReturn = null;
String filename = "input/pancakes/generated-" + size + "/" + instance;
try {
InputStream is = new FileInputStream(new File(filename));
toReturn = new Pancakes(is);
toReturn.setAdditionalParameter("GAP-k", k + "");
} catch (FileNotFoundException e) {
System.out.println("[WARNING] File " + filename + " not found");
}
return toReturn;
}
public static SearchDomain createPancakesInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
String filename = "input/pancakes/generated-10/" + instance;
try {
InputStream is = new FileInputStream(new File(filename));
return new Pancakes(is);
} catch (FileNotFoundException e) {
System.out.println("[WARNING] File " + filename + " not found");
return null;
}
}
public static SearchDomain createVacuumRobotInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/vacuumrobot/generated-10-dirt/" + instance));
return new VacuumRobot(is);
}
public static SearchDomain create15PuzzleInstanceFromKorfInstancesPDB555(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/fifteenpuzzle/korf100-real/" + instance));
FifteenPuzzle puzzle = new FifteenPuzzle(is);
String PDBsDirs[] = new String[]{"C:\\users\\user\\", "H:\\", "C:\\"};
puzzle.setAdditionalParameter("heuristic", "pdb-555");
boolean pdbFilesOK = false;
for (String PDBsDir : PDBsDirs) {
try {
puzzle.setAdditionalParameter(
"pdb-555-files",
PDBsDir + "PDBs\\15-puzzle\\dis_1_2_3_4_5,"+
PDBsDir + "PDBs\\15-puzzle\\dis_6_7_8_9_10,"+
PDBsDir + "PDBs\\15-puzzle\\dis_11_12_13_14_15");
pdbFilesOK = true;
break;
} catch (IllegalArgumentException e) { }
}
assert pdbFilesOK;
puzzle.setAdditionalParameter("use-reflection", true + "");
return puzzle;
}
public static SearchDomain create15PuzzleInstanceFromKorfInstancesPDB78(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/fifteenpuzzle/korf100-real/" + instance));
FifteenPuzzle puzzle = new FifteenPuzzle(is);
String PDBsDirs[] = new String[]{"C:\\users\\user\\", "H:\\", "C:\\"};
puzzle.setAdditionalParameter("heuristic", "pdb-78");
boolean pdbFilesOK = false;
for (String PDBsDir : PDBsDirs) {
try {
puzzle.setAdditionalParameter(
"pdb-78-files",
PDBsDir + "PDBs\\15-puzzle\\dis_1_2_3_4_5_6_7," +
PDBsDir + "PDBs\\15-puzzle\\dis_8_9_10_11_12_13_14_15");
pdbFilesOK = true;
break;
} catch (IllegalArgumentException e) { }
}
assert pdbFilesOK;
puzzle.setAdditionalParameter("use-reflection", true + "");
return puzzle;
}
public static SearchDomain create15PuzzleInstanceFromKorfInstances(SearchDomain previous, String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/fifteenpuzzle/korf100-real/" + instance));
return new FifteenPuzzle((FifteenPuzzle)previous, is);
}
public static SearchDomain createDockyardRobotInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/dockyardrobot/generated-max-edge-2-out-of-place-30/" + instance));
return new DockyardRobot(is);
}
}
|
src/main/java/org/cs4j/core/mains/DomainsCreation.java
|
package org.cs4j.core.mains;
import org.cs4j.core.SearchDomain;
import org.cs4j.core.domains.*;
import java.io.*;
/**
* Created by sepetnit on 11/10/2015.
*
*/
public class DomainsCreation {
/*******************************************************************************************************************
* Private static methods : Domains creation
******************************************************************************************************************/
public static SearchDomain createGridPathFindingInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/gridpathfinding/generated/maze512-1-6.map/" + instance));
//InputStream is = new FileInputStream(new File("input/gridpathfinding/generated/den400d.map/" + instance));
return new GridPathFinding(is);
}
public static SearchDomain createGridPathFindingInstanceFromAutomaticallyGeneratedWithTDH(
String instance, int pivotsCount) throws IOException {
String mapFileName = "input/gridpathfinding/generated/brc202d.map";
//String mapFileName = "input/gridpathfinding/generated/maze512-1-6.map";
//String pivotsFileName = "input/gridpathfinding/raw/maps/" + new File(mapFileName).getName() + ".pivots.pdb";
//String pivotsFileName = "input/gridpathfinding/raw/mazes/maze1/_maze512-1-6-80.map.pivots.pdb";
String pivotsFileName = "input/gridpathfinding/raw/maps/brc202d.map.pivots.pdb";
InputStream is = new FileInputStream(new File(mapFileName + "/" + instance));
GridPathFinding problem = new GridPathFinding(is);
//problem.setAdditionalParameter("heuristic", "dh-furthest");
//problem.setAdditionalParameter("heuristic", "dh-md-average-md-if-dh-is-0");
problem.setAdditionalParameter("heuristic", "dh-random-pivot");
//problem.setAdditionalParameter("heuristic", "random-dh-md");
problem.setAdditionalParameter("pivots-distances-db-file", pivotsFileName);
problem.setAdditionalParameter("pivots-count", pivotsCount + "");
return problem;
}
public static SearchDomain createGridPathFindingInstanceFromAutomaticallyGeneratedWithTDH(SearchDomain previous,
String instance,
int pivotsCount)
throws IOException {
String mapFileName = "input/gridpathfinding/generated/brc202d.map";
//String mapFileName = "input/gridpathfinding/generated/maze512-1-6.map";
InputStream is = new FileInputStream(new File(mapFileName, instance));
GridPathFinding problem = new GridPathFinding((GridPathFinding)previous, is);
// Change the number of pivots
problem.setAdditionalParameter("pivots-count", pivotsCount + "");
return problem;
}
// The k is for GAP-k heuristic setting
public static SearchDomain createPancakesInstanceFromAutomaticallyGenerated(int size, String instance, int k) throws FileNotFoundException {
Pancakes toReturn = null;
String filename = "input/pancakes/generated-" + size + "/" + instance;
try {
InputStream is = new FileInputStream(new File(filename));
toReturn = new Pancakes(is);
toReturn.setAdditionalParameter("GAP-k", k + "");
} catch (FileNotFoundException e) {
System.out.println("[WARNING] File " + filename + " not found");
}
return toReturn;
}
public static SearchDomain createPancakesInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
String filename = "input/pancakes/generated-10/" + instance;
try {
InputStream is = new FileInputStream(new File(filename));
return new Pancakes(is);
} catch (FileNotFoundException e) {
System.out.println("[WARNING] File " + filename + " not found");
return null;
}
}
public static SearchDomain createVacuumRobotInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/vacuumrobot/generated-10-dirt/" + instance));
return new VacuumRobot(is);
}
public static SearchDomain create15PuzzleInstanceFromKorfInstancesPDB555(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/fifteenpuzzle/korf100-real/" + instance));
FifteenPuzzle puzzle = new FifteenPuzzle(is);
String PDBsDirs[] = new String[]{"C:\\users\\user\\", "H:\\", "C:\\"};
puzzle.setAdditionalParameter("heuristic", "pdb-555");
boolean pdbFilesOK = false;
for (String PDBsDir : PDBsDirs) {
try {
puzzle.setAdditionalParameter(
"pdb-555-files",
PDBsDir + "PDBs\\15-puzzle\\dis_1_2_3_4_5,"+
PDBsDir + "PDBs\\15-puzzle\\dis_6_7_8_9_10,"+
PDBsDir + "PDBs\\15-puzzle\\dis_11_12_13_14_15");
pdbFilesOK = true;
break;
} catch (IllegalArgumentException e) { }
}
assert pdbFilesOK;
puzzle.setAdditionalParameter("use-reflection", true + "");
return puzzle;
}
public static SearchDomain create15PuzzleInstanceFromKorfInstancesPDB78(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/fifteenpuzzle/korf100-real/" + instance));
FifteenPuzzle puzzle = new FifteenPuzzle(is);
String PDBsDirs[] = new String[]{"C:\\users\\user\\", "H:\\", "C:\\"};
puzzle.setAdditionalParameter("heuristic", "pdb-78");
boolean pdbFilesOK = false;
for (String PDBsDir : PDBsDirs) {
try {
puzzle.setAdditionalParameter(
"pdb-78-files",
PDBsDir + "PDBs\\15-puzzle\\dis_1_2_3_4_5_6_7," +
PDBsDir + "PDBs\\15-puzzle\\dis_8_9_10_11_12_13_14_15");
pdbFilesOK = true;
break;
} catch (IllegalArgumentException e) { }
}
assert pdbFilesOK;
puzzle.setAdditionalParameter("use-reflection", true + "");
return puzzle;
}
public static SearchDomain create15PuzzleInstanceFromKorfInstances(SearchDomain previous, String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/fifteenpuzzle/korf100-real/" + instance));
return new FifteenPuzzle((FifteenPuzzle)previous, is);
}
public static SearchDomain createDockyardRobotInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/dockyardrobot/generated-max-edge-2-out-of-place-30/" + instance));
return new DockyardRobot(is);
}
}
|
Added option for random pivots ...
|
src/main/java/org/cs4j/core/mains/DomainsCreation.java
|
Added option for random pivots ...
|
|
Java
|
apache-2.0
|
c4debf4cacd53b874008d48c0d96483a862397ec
| 0
|
yukim/cassandra,bcoverston/apache-hosted-cassandra,bdeggleston/cassandra,yanbit/cassandra,yangzhe1991/cassandra,krummas/cassandra,guanxi55nba/key-value-store,jasobrown/cassandra,scylladb/scylla-tools-java,codefollower/Cassandra-Research,exoscale/cassandra,jbellis/cassandra,lalithsuresh/cassandra-c3,shookari/cassandra,tongjixianing/projects,matthewtt/cassandra_read,Jollyplum/cassandra,michaelsembwever/cassandra,szhou1234/cassandra,scylladb/scylla-tools-java,guanxi55nba/db-improvement,kgreav/cassandra,krummas/cassandra,jeffjirsa/cassandra,bcoverston/apache-hosted-cassandra,Stratio/cassandra,carlyeks/cassandra,RyanMagnusson/cassandra,nutbunnies/cassandra,RyanMagnusson/cassandra,yanbit/cassandra,adejanovski/cassandra,tjake/cassandra,bdeggleston/cassandra,jeffjirsa/cassandra,asias/cassandra,clohfink/cassandra,michaelmior/cassandra,ptnapoleon/cassandra,beobal/cassandra,belliottsmith/cassandra,boneill42/cassandra,adelapena/cassandra,Jaumo/cassandra,apache/cassandra,nakomis/cassandra,DavidHerzogTU-Berlin/cassandra,darach/cassandra,vaibhi9/cassandra,AtwooTM/cassandra,stef1927/cassandra,instaclustr/cassandra,knifewine/cassandra,mashuai/Cassandra-Research,AtwooTM/cassandra,adelapena/cassandra,blambov/cassandra,helena/cassandra,DavidHerzogTU-Berlin/cassandra,weideng1/cassandra,macintoshio/cassandra,Stratio/stratio-cassandra,aboudreault/cassandra,pthomaid/cassandra,bdeggleston/cassandra,belliottsmith/cassandra,thelastpickle/cassandra,pcmanus/cassandra,josh-mckenzie/cassandra,jsanda/cassandra,newrelic-forks/cassandra,bmel/cassandra,tjake/cassandra,sluk3r/cassandra,Instagram/cassandra,kangkot/stratio-cassandra,knifewine/cassandra,nvoron23/cassandra,whitepages/cassandra,tommystendahl/cassandra,leomrocha/cassandra,driftx/cassandra,phact/cassandra,blerer/cassandra,miguel0afd/cassandra-cqlMod,weipinghe/cassandra,helena/cassandra,pcmanus/cassandra,ptnapoleon/cassandra,kgreav/cassandra,leomrocha/cassandra,nlalevee/cassandra,qinjin/mdtc-cassandra,joesiewert/cassandra,likaiwalkman/cassandra,szhou1234/cassandra,mike-tr-adamson/cassandra,heiko-braun/cassandra,beobal/cassandra,matthewtt/cassandra_read,dkua/cassandra,aarushi12002/cassandra,xiongzheng/Cassandra-Research,adejanovski/cassandra,chbatey/cassandra-1,mkjellman/cassandra,michaelmior/cassandra,chbatey/cassandra-1,dprguiuc/Cassandra-Wasef,xiongzheng/Cassandra-Research,mshuler/cassandra,dongjiaqiang/cassandra,jrwest/cassandra,mkjellman/cassandra,sluk3r/cassandra,pauloricardomg/cassandra,matthewtt/cassandra_read,ben-manes/cassandra,chaordic/cassandra,pcn/cassandra-1,clohfink/cassandra,beobal/cassandra,jrwest/cassandra,EnigmaCurry/cassandra,mike-tr-adamson/cassandra,ben-manes/cassandra,thobbs/cassandra,kangkot/stratio-cassandra,jasobrown/cassandra,jrwest/cassandra,jeffjirsa/cassandra,aboudreault/cassandra,qinjin/mdtc-cassandra,yhnishi/cassandra,ifesdjeen/cassandra,ejankan/cassandra,ptuckey/cassandra,AtwooTM/cassandra,apache/cassandra,jeromatron/cassandra,sivikt/cassandra,lalithsuresh/cassandra-c3,tongjixianing/projects,hengxin/cassandra,sharvanath/cassandra,dkua/cassandra,LatencyUtils/cassandra-stress2,vramaswamy456/cassandra,pkdevbox/cassandra,snazy/cassandra,WorksApplications/cassandra,strapdata/cassandra,swps/cassandra,carlyeks/cassandra,yhnishi/cassandra,darach/cassandra,chaordic/cassandra,spodkowinski/cassandra,yangzhe1991/cassandra,ibmsoe/cassandra,whitepages/cassandra,juiceblender/cassandra,wreda/cassandra,snazy/cassandra,mariusae/cassandra,iamaleksey/cassandra,mheffner/cassandra-1,iburmistrov/Cassandra,yhnishi/cassandra,iamaleksey/cassandra,thelastpickle/cassandra,blerer/cassandra,spodkowinski/cassandra,yonglehou/cassandra,mt0803/cassandra,ben-manes/cassandra,jeromatron/cassandra,clohfink/cassandra,DICL/cassandra,gdusbabek/cassandra,ifesdjeen/cassandra,jasonwee/cassandra,exoscale/cassandra,asias/cassandra,rackerlabs/cloudmetrics-cassandra,mklew/mmp,stef1927/cassandra,belliottsmith/cassandra,EnigmaCurry/cassandra,a-buck/cassandra,sbtourist/cassandra,rdio/cassandra,bdeggleston/cassandra,pallavi510/cassandra,scylladb/scylla-tools-java,pofallon/cassandra,miguel0afd/cassandra-cqlMod,juiceblender/cassandra,mshuler/cassandra,szhou1234/cassandra,iburmistrov/Cassandra,fengshao0907/cassandra-1,macintoshio/cassandra,mshuler/cassandra,pcmanus/cassandra,tommystendahl/cassandra,aweisberg/cassandra,swps/cassandra,modempachev4/kassandra,ejankan/cassandra,Stratio/stratio-cassandra,fengshao0907/cassandra-1,ollie314/cassandra,GabrielNicolasAvellaneda/cassandra,blerer/cassandra,jkni/cassandra,pauloricardomg/cassandra,mkjellman/cassandra,segfault/apache_cassandra,Bj0rnen/cassandra,DavidHerzogTU-Berlin/cassandraToRun,hengxin/cassandra,mklew/mmp,thelastpickle/cassandra,strapdata/cassandra,hhorii/cassandra,aboudreault/cassandra,bpupadhyaya/cassandra,mt0803/cassandra,mariusae/cassandra,pofallon/cassandra,rmarchei/cassandra,instaclustr/cassandra,adejanovski/cassandra,aureagle/cassandra,mklew/mmp,adelapena/cassandra,jasonstack/cassandra,vramaswamy456/cassandra,mkjellman/cassandra,mt0803/cassandra,mheffner/cassandra-1,stuhood/cassandra-old,DICL/cassandra,wreda/cassandra,sayanh/ViewMaintenanceCassandra,cooldoger/cassandra,Instagram/cassandra,regispl/cassandra,sbtourist/cassandra,qinjin/mdtc-cassandra,christian-esken/cassandra,jbellis/cassandra,spodkowinski/cassandra,shookari/cassandra,pcn/cassandra-1,ollie314/cassandra,mike-tr-adamson/cassandra,shawnkumar/cstargraph,christian-esken/cassandra,guard163/cassandra,weideng1/cassandra,iburmistrov/Cassandra,Stratio/cassandra,sayanh/ViewMaintenanceCassandra,WorksApplications/cassandra,belliottsmith/cassandra,HidemotoNakada/cassandra-udf,MasahikoSawada/cassandra,guanxi55nba/db-improvement,apache/cassandra,nitsanw/cassandra,pauloricardomg/cassandra,modempachev4/kassandra,ejankan/cassandra,michaelsembwever/cassandra,iamaleksey/cassandra,pofallon/cassandra,regispl/cassandra,regispl/cassandra,vaibhi9/cassandra,pallavi510/cassandra,blambov/cassandra,Imran-C/cassandra,yonglehou/cassandra,scylladb/scylla-tools-java,aureagle/cassandra,mheffner/cassandra-1,mariusae/cassandra,jbellis/cassandra,GabrielNicolasAvellaneda/cassandra,wreda/cassandra,sedulam/CASSANDRA-12201,mgmuscari/cassandra-cdh4,beobal/cassandra,juiceblender/cassandra,rmarchei/cassandra,LatencyUtils/cassandra-stress2,stef1927/cassandra,fengshao0907/Cassandra-Research,chbatey/cassandra-1,dprguiuc/Cassandra-Wasef,sedulam/CASSANDRA-12201,tommystendahl/cassandra,dkua/cassandra,Jaumo/cassandra,juiceblender/cassandra,aarushi12002/cassandra,nakomis/cassandra,ptuckey/cassandra,gdusbabek/cassandra,guard163/cassandra,Instagram/cassandra,sbtourist/cassandra,jeromatron/cassandra,MasahikoSawada/cassandra,phact/cassandra,Imran-C/cassandra,josh-mckenzie/cassandra,shawnkumar/cstargraph,caidongyun/cassandra,joesiewert/cassandra,vramaswamy456/cassandra,mariusae/cassandra,sayanh/ViewMaintenanceSupport,HidemotoNakada/cassandra-udf,mashuai/Cassandra-Research,instaclustr/cassandra,pcn/cassandra-1,exoscale/cassandra,mike-tr-adamson/cassandra,Jollyplum/cassandra,kangkot/stratio-cassandra,hengxin/cassandra,tjake/cassandra,fengshao0907/Cassandra-Research,taigetco/cassandra_read,boneill42/cassandra,aweisberg/cassandra,driftx/cassandra,ibmsoe/cassandra,codefollower/Cassandra-Research,thobbs/cassandra,shawnkumar/cstargraph,snazy/cassandra,jasonstack/cassandra,Bj0rnen/cassandra,sayanh/ViewMaintenanceSupport,rdio/cassandra,sharvanath/cassandra,caidongyun/cassandra,nvoron23/cassandra,DICL/cassandra,mashuai/Cassandra-Research,LatencyUtils/cassandra-stress2,ibmsoe/cassandra,taigetco/cassandra_read,krummas/cassandra,codefollower/Cassandra-Research,driftx/cassandra,iamaleksey/cassandra,WorksApplications/cassandra,lalithsuresh/cassandra-c3,kgreav/cassandra,christian-esken/cassandra,weipinghe/cassandra,pthomaid/cassandra,project-zerus/cassandra,mgmuscari/cassandra-cdh4,shookari/cassandra,bcoverston/cassandra,joesiewert/cassandra,emolsson/cassandra,knifewine/cassandra,Jollyplum/cassandra,Stratio/stratio-cassandra,macintoshio/cassandra,pbailis/cassandra-pbs,jasonstack/cassandra,Stratio/stratio-cassandra,snazy/cassandra,WorksApplications/cassandra,likaiwalkman/cassandra,mambocab/cassandra,vaibhi9/cassandra,dongjiaqiang/cassandra,rdio/cassandra,weideng1/cassandra,yangzhe1991/cassandra,GabrielNicolasAvellaneda/cassandra,Stratio/stratio-cassandra,stuhood/cassandra-old,sluk3r/cassandra,blambov/cassandra,cooldoger/cassandra,jkni/cassandra,strapdata/cassandra,ifesdjeen/cassandra,leomrocha/cassandra,segfault/apache_cassandra,michaelsembwever/cassandra,tommystendahl/cassandra,JeremiahDJordan/cassandra,whitepages/cassandra,jasonwee/cassandra,boneill42/cassandra,yukim/cassandra,Bj0rnen/cassandra,clohfink/cassandra,scaledata/cassandra,fengshao0907/cassandra-1,rackerlabs/cloudmetrics-cassandra,ifesdjeen/cassandra,blambov/cassandra,kangkot/stratio-cassandra,pkdevbox/cassandra,bcoverston/apache-hosted-cassandra,nvoron23/cassandra,EnigmaCurry/cassandra,likaiwalkman/cassandra,josh-mckenzie/cassandra,mariusae/cassandra,sivikt/cassandra,pkdevbox/cassandra,caidongyun/cassandra,DavidHerzogTU-Berlin/cassandraToRun,nitsanw/cassandra,DikangGu/cassandra,asias/cassandra,bcoverston/cassandra,rackerlabs/cloudmetrics-cassandra,yonglehou/cassandra,jkni/cassandra,rmarchei/cassandra,nutbunnies/cassandra,guanxi55nba/key-value-store,JeremiahDJordan/cassandra,fengshao0907/Cassandra-Research,bmel/cassandra,DikangGu/cassandra,newrelic-forks/cassandra,kangkot/stratio-cassandra,yukim/cassandra,guanxi55nba/db-improvement,sriki77/cassandra,miguel0afd/cassandra-cqlMod,pbailis/cassandra-pbs,JeremiahDJordan/cassandra,mshuler/cassandra,pbailis/cassandra-pbs,josh-mckenzie/cassandra,RyanMagnusson/cassandra,michaelsembwever/cassandra,DavidHerzogTU-Berlin/cassandraToRun,dprguiuc/Cassandra-Wasef,swps/cassandra,MasahikoSawada/cassandra,pallavi510/cassandra,emolsson/cassandra,rogerchina/cassandra,nlalevee/cassandra,aureagle/cassandra,Imran-C/cassandra,jsanda/cassandra,segfault/apache_cassandra,Stratio/cassandra,dongjiaqiang/cassandra,bpupadhyaya/cassandra,ollie314/cassandra,rogerchina/cassandra,darach/cassandra,aweisberg/cassandra,project-zerus/cassandra,ptnapoleon/cassandra,nakomis/cassandra,sivikt/cassandra,strapdata/cassandra,jasonwee/cassandra,ptuckey/cassandra,mambocab/cassandra,carlyeks/cassandra,weipinghe/cassandra,nlalevee/cassandra,bpupadhyaya/cassandra,bcoverston/cassandra,aweisberg/cassandra,project-zerus/cassandra,HidemotoNakada/cassandra-udf,driftx/cassandra,newrelic-forks/cassandra,tjake/cassandra,emolsson/cassandra,yanbit/cassandra,kgreav/cassandra,a-buck/cassandra,gdusbabek/cassandra,michaelmior/cassandra,yukim/cassandra,pauloricardomg/cassandra,pthomaid/cassandra,sriki77/cassandra,szhou1234/cassandra,sayanh/ViewMaintenanceCassandra,nitsanw/cassandra,spodkowinski/cassandra,hhorii/cassandra,sharvanath/cassandra,jasobrown/cassandra,guanxi55nba/key-value-store,heiko-braun/cassandra,krummas/cassandra,thelastpickle/cassandra,scaledata/cassandra,a-buck/cassandra,apache/cassandra,instaclustr/cassandra,helena/cassandra,guard163/cassandra,mgmuscari/cassandra-cdh4,rogerchina/cassandra,bcoverston/cassandra,jasobrown/cassandra,taigetco/cassandra_read,cooldoger/cassandra,thobbs/cassandra,DikangGu/cassandra,jeffjirsa/cassandra,phact/cassandra,Jaumo/cassandra,adelapena/cassandra,mambocab/cassandra,scaledata/cassandra,hhorii/cassandra,heiko-braun/cassandra,xiongzheng/Cassandra-Research,blerer/cassandra,Instagram/cassandra,stuhood/cassandra-old,sriki77/cassandra,jrwest/cassandra,DavidHerzogTU-Berlin/cassandra,modempachev4/kassandra,jsanda/cassandra,chaordic/cassandra,aarushi12002/cassandra,stef1927/cassandra,tongjixianing/projects,bmel/cassandra,cooldoger/cassandra,nutbunnies/cassandra,sedulam/CASSANDRA-12201,stuhood/cassandra-old
|
package org.apache.cassandra.tools;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import org.apache.cassandra.config.ConfigurationException;
import java.io.IOException;
public class SchemaTool
{
public static void main(String[] args)
throws NumberFormatException, IOException, InterruptedException, ConfigurationException
{
if (args.length < 3)
usage();
if (args.length != 3 && "import".equals(args[2]))
usage();
if (args.length != 4 && "export".equals(args[2]))
usage();
System.out.println("# Note: This tool is deprecated and will be removed in future releases.");
String host = args[0];
int port = 0;
try
{
port = Integer.parseInt(args[1]);
}
catch (NumberFormatException e)
{
System.err.println("Port must be a number.");
System.exit(1);
}
if ("import".equals(args[2]))
new NodeProbe(host, port).loadSchemaFromYAML();
else if ("export".equals(args[2]))
new NodeProbe(host, port).exportSchemaToYAML(args[3]);
else
usage();
}
private static void usage()
{
System.err.printf("java %s <host> <port> import|export to_file%n", SchemaTool.class.getName());
System.exit(1);
}
}
|
src/java/org/apache/cassandra/tools/SchemaTool.java
|
package org.apache.cassandra.tools;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import org.apache.cassandra.config.ConfigurationException;
import java.io.IOException;
public class SchemaTool
{
public static void main(String[] args)
throws NumberFormatException, IOException, InterruptedException, ConfigurationException
{
if (args.length != 3 && "import".equals(args[2]))
usage();
if (args.length != 4 && "export".equals(args[2]))
usage();
System.out.println("# Note: This tool is deprecated and will be removed in future releases.");
String host = args[0];
int port = 0;
try
{
port = Integer.parseInt(args[1]);
}
catch (NumberFormatException e)
{
System.err.println("Port must be a number.");
System.exit(1);
}
if ("import".equals(args[2]))
new NodeProbe(host, port).loadSchemaFromYAML();
else if ("export".equals(args[2]))
new NodeProbe(host, port).exportSchemaToYAML(args[3]);
else
usage();
}
private static void usage()
{
System.err.printf("java %s <host> <port> import|export to_file%n", SchemaTool.class.getName());
System.exit(1);
}
}
|
add additional usage check to SchemaTool
git-svn-id: af0234e1aff5c580ad966c5a1be7e5402979d927@985351 13f79535-47bb-0310-9956-ffa450edef68
|
src/java/org/apache/cassandra/tools/SchemaTool.java
|
add additional usage check to SchemaTool
|
|
Java
|
apache-2.0
|
23afdb8b0af9b2b7e4830bb54989612e1faecff4
| 0
|
ya7lelkom/swift-k,swift-lang/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,swift-lang/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,swift-lang/swift-k,ya7lelkom/swift-k,swift-lang/swift-k,swift-lang/swift-k
|
/*
* Created on Jun 8, 2006
*/
package org.griphyn.vdl.karajan;
import java.util.Iterator;
import java.util.LinkedList;
import org.globus.cog.karajan.stack.VariableNotFoundException;
import org.globus.cog.karajan.workflow.events.Event;
import org.globus.cog.karajan.workflow.events.EventBus;
import org.globus.cog.karajan.workflow.events.EventListener;
import org.globus.cog.karajan.workflow.events.EventTargetPair;
import org.globus.cog.karajan.workflow.futures.Future;
import org.globus.cog.karajan.workflow.futures.FutureEvaluationException;
import org.griphyn.vdl.mapping.DSHandle;
import org.griphyn.vdl.mapping.DSHandleListener;
public class DSHandleFutureWrapper implements Future, DSHandleListener {
private DSHandle handle;
private LinkedList listeners;
public DSHandleFutureWrapper(DSHandle handle) {
this.handle = handle;
handle.addListener(this);
}
public synchronized void close() {
handle.closeShallow();
}
public synchronized boolean isClosed() {
return handle.isClosed();
}
public synchronized Object getValue() throws VariableNotFoundException {
Object value = handle.getValue();
if (value instanceof RuntimeException) {
throw (RuntimeException) value;
}
else {
return value;
}
}
public synchronized void addModificationAction(EventListener target, Event event) {
/**
* So, the strategy is the following: getValue() or something else
* throws a future exception; then some entity catches that and calls
* this method. There is no way to ensure that the future was not closed
* in the mean time. What has to be done is that this method should
* check if the future was closed or modified at the time of the call of
* this method and call notifyListeners().
*/
if (listeners == null) {
listeners = new LinkedList();
}
listeners.add(new EventTargetPair(event, target));
WaitingThreadsMonitor.addThread(event.getStack());
if (handle.isClosed()) {
notifyListeners();
}
}
private synchronized void notifyListeners() {
if (listeners == null) {
return;
}
while (!listeners.isEmpty()) {
EventTargetPair etp = (EventTargetPair) listeners.removeFirst();
WaitingThreadsMonitor.removeThread(etp.getEvent().getStack());
EventBus.post(etp.getTarget(), etp.getEvent());
}
listeners = null;
}
public int listenerCount() {
if (listeners == null) {
return 0;
}
else {
return listeners.size();
}
}
public EventTargetPair[] getListenerEvents() {
if (listeners != null) {
return (EventTargetPair[]) listeners.toArray(new EventTargetPair[0]);
}
else {
return null;
}
}
public String toString() {
return "F/" + handle;
}
public void fail(FutureEvaluationException e) {
handle.setValue(e);
handle.closeShallow();
}
public void handleClosed(DSHandle handle) {
notifyListeners();
}
}
|
src/org/griphyn/vdl/karajan/DSHandleFutureWrapper.java
|
/*
* Created on Jun 8, 2006
*/
package org.griphyn.vdl.karajan;
import java.util.Iterator;
import java.util.LinkedList;
import org.globus.cog.karajan.stack.VariableNotFoundException;
import org.globus.cog.karajan.workflow.events.Event;
import org.globus.cog.karajan.workflow.events.EventBus;
import org.globus.cog.karajan.workflow.events.EventListener;
import org.globus.cog.karajan.workflow.events.EventTargetPair;
import org.globus.cog.karajan.workflow.futures.Future;
import org.globus.cog.karajan.workflow.futures.FutureEvaluationException;
import org.griphyn.vdl.mapping.DSHandle;
import org.griphyn.vdl.mapping.DSHandleListener;
public class DSHandleFutureWrapper implements Future, Mergeable, DSHandleListener {
private DSHandle handle;
private LinkedList listeners;
public DSHandleFutureWrapper(DSHandle handle) {
this.handle = handle;
handle.addListener(this);
}
public synchronized void close() {
handle.closeShallow();
}
public synchronized boolean isClosed() {
return handle.isClosed();
}
public synchronized Object getValue() throws VariableNotFoundException {
Object value = handle.getValue();
if (value instanceof RuntimeException) {
throw (RuntimeException) value;
}
else {
return value;
}
}
public synchronized void addModificationAction(EventListener target, Event event) {
/**
* So, the strategy is the following: getValue() or something else
* throws a future exception; then some entity catches that and calls
* this method. There is no way to ensure that the future was not closed
* in the mean time. What has to be done is that this method should
* check if the future was closed or modified at the time of the call of
* this method and call notifyListeners().
*/
if (listeners == null) {
listeners = new LinkedList();
}
listeners.add(new EventTargetPair(event, target));
WaitingThreadsMonitor.addThread(event.getStack());
if (handle.isClosed()) {
notifyListeners();
}
}
private synchronized void notifyListeners() {
if (listeners == null) {
return;
}
while (!listeners.isEmpty()) {
EventTargetPair etp = (EventTargetPair) listeners.removeFirst();
WaitingThreadsMonitor.removeThread(etp.getEvent().getStack());
EventBus.post(etp.getTarget(), etp.getEvent());
}
listeners = null;
}
public void mergeListeners(Future f) {
Iterator i = listeners.iterator();
while (i.hasNext()) {
EventTargetPair etp = (EventTargetPair) i.next();
f.addModificationAction(etp.getTarget(), etp.getEvent());
i.remove();
}
listeners = null;
}
public int listenerCount() {
if (listeners == null) {
return 0;
}
else {
return listeners.size();
}
}
public EventTargetPair[] getListenerEvents() {
if (listeners != null) {
return (EventTargetPair[]) listeners.toArray(new EventTargetPair[0]);
}
else {
return null;
}
}
public String toString() {
return "F/" + handle;
}
public void fail(FutureEvaluationException e) {
handle.setValue(e);
handle.closeShallow();
}
public void handleClosed(DSHandle handle) {
notifyListeners();
}
}
|
as far as I can tell, this never gets used
git-svn-id: 6ee47c8665bf46900d9baa0afb711c5b4a0eafac@2403 e2bb083e-7f23-0410-b3a8-8253ac9ef6d8
|
src/org/griphyn/vdl/karajan/DSHandleFutureWrapper.java
|
as far as I can tell, this never gets used
|
|
Java
|
apache-2.0
|
5bedb47a0c483cb3ac69dc719e4dd42c28b05956
| 0
|
vjuranek/JGroups,ibrahimshbat/JGroups,vjuranek/JGroups,slaskawi/JGroups,rpelisse/JGroups,vjuranek/JGroups,slaskawi/JGroups,TarantulaTechnology/JGroups,dimbleby/JGroups,rvansa/JGroups,deepnarsay/JGroups,pferraro/JGroups,rhusar/JGroups,dimbleby/JGroups,kedzie/JGroups,Sanne/JGroups,ligzy/JGroups,deepnarsay/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,Sanne/JGroups,kedzie/JGroups,danberindei/JGroups,rvansa/JGroups,TarantulaTechnology/JGroups,rpelisse/JGroups,pruivo/JGroups,deepnarsay/JGroups,pferraro/JGroups,slaskawi/JGroups,ibrahimshbat/JGroups,ligzy/JGroups,belaban/JGroups,tristantarrant/JGroups,kedzie/JGroups,TarantulaTechnology/JGroups,pruivo/JGroups,belaban/JGroups,pruivo/JGroups,rpelisse/JGroups,rhusar/JGroups,danberindei/JGroups,danberindei/JGroups,rhusar/JGroups,pferraro/JGroups,ibrahimshbat/JGroups,tristantarrant/JGroups,belaban/JGroups,ligzy/JGroups,dimbleby/JGroups
|
package org.jgroups.tests;
import org.jgroups.*;
import org.jgroups.protocols.TP;
import org.jgroups.util.Util;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.*;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Tests the TLS
* @author Bela Ban
* @version $Id: ConcurrentStackTest.java,v 1.13 2009/06/04 07:35:54 vlada Exp $
*/
@Test(groups=Global.STACK_DEPENDENT,sequential=true)
public class ConcurrentStackTest extends ChannelTestBase {
JChannel ch1, ch2, ch3;
final static int NUM=25, EXPECTED=NUM * 3;
final static long SLEEPTIME=100;
CyclicBarrier barrier;
@BeforeMethod
void setUp() throws Exception {
barrier=new CyclicBarrier(4);
ch1=createChannel(true,3);
ch2=createChannel(ch1);
ch3=createChannel(ch1);
}
@AfterMethod
protected void tearDown() throws Exception {
Util.close(ch3, ch2, ch1);
barrier.reset();
}
@Test
public void testSequentialDelivery() throws Exception {
doIt(false);
}
@Test
public void testConcurrentDelivery() throws Exception {
doIt(true);
}
private void doIt(boolean concurrent) throws Exception {
long start, stop, diff;
setConcurrent(ch1, concurrent);
setConcurrent(ch2, concurrent);
setConcurrent(ch3, concurrent);
MyReceiver r1=new MyReceiver("R1"), r2=new MyReceiver("R2"), r3=new MyReceiver("R3");
ch1.setReceiver(r1); ch2.setReceiver(r2); ch3.setReceiver(r3);
ch1.connect("ConcurrentStackTest");
ch2.connect("ConcurrentStackTest");
ch3.connect("ConcurrentStackTest");
View v=ch3.getView();
assert v.size() == 3 : "view is " + v;
new Thread(new Sender(ch1)) {}.start();
new Thread(new Sender(ch2)) {}.start();
new Thread(new Sender(ch3)) {}.start();
barrier.await(); // start senders
start=System.currentTimeMillis();
Exception ex=null;
try {
barrier.await((long)(EXPECTED * SLEEPTIME * 1.5), TimeUnit.MILLISECONDS); // wait for all receivers
}
catch(java.util.concurrent.TimeoutException e) {
ex=e;
}
stop=System.currentTimeMillis();
diff=stop - start;
System.out.println("Total time: " + diff + " ms\n");
checkFIFO(r1);
checkFIFO(r2);
checkFIFO(r3);
/*
* TODO Vladimir Feb 15th 2007
* Re-enable once acceptable bounds are known for all stacks
* checkTime(diff, threadless);
*
* */
if(ex != null)
throw ex;
}
private void checkFIFO(MyReceiver r) {
List<Pair<Address,Integer>> msgs=r.getMessages();
Map<Address,List<Integer>> map=new HashMap<Address,List<Integer>>();
for(Pair<Address,Integer> p: msgs) {
Address sender=p.key;
List<Integer> list=map.get(sender);
if(list == null) {
list=new LinkedList<Integer>();
map.put(sender, list);
}
list.add(p.val);
}
boolean fifo=true;
List<Address> incorrect_receivers=new LinkedList<Address>();
System.out.println("Checking FIFO for " + r.getName() + ":");
for(Address addr: map.keySet()) {
List<Integer> list=map.get(addr);
print(addr, list);
if(!verifyFIFO(list)) {
fifo=false;
incorrect_receivers.add(addr);
}
}
System.out.print("\n");
if(!fifo)
assert false : "The following receivers didn't receive all messages in FIFO order: " + incorrect_receivers;
}
private static boolean verifyFIFO(List<Integer> list) {
List<Integer> list2=new LinkedList<Integer>(list);
Collections.sort(list2);
return list.equals(list2);
}
private static void print(Address addr, List<Integer> list) {
StringBuilder sb=new StringBuilder();
sb.append(addr).append(": ");
for(Integer i: list)
sb.append(i).append(" ");
System.out.println(sb);
}
private static void setConcurrent(JChannel ch1, boolean concurrent) {
TP transport=ch1.getProtocolStack().getTransport();
transport.setUseConcurrentStack(concurrent);
ThreadPoolExecutor default_pool=(ThreadPoolExecutor)transport.getDefaultThreadPool();
if(default_pool != null) {
default_pool.setCorePoolSize(1);
default_pool.setMaximumPoolSize(100);
}
transport.setThreadPoolQueueEnabled(false);
}
private class Sender implements Runnable {
Channel ch;
Address local_addr;
public Sender(Channel ch) {
this.ch=ch;
local_addr=ch.getAddress();
}
public void run() {
Message msg;
try {
barrier.await();
}
catch(Throwable t) {
return;
}
for(int i=1; i <= NUM; i++) {
msg=new Message(null, null, new Integer(i));
try {
ch.send(msg);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
private class Pair<K,V> {
K key;
V val;
public Pair(K key, V val) {
this.key=key;
this.val=val;
}
public String toString() {
return key + "::" + val;
}
}
private class MyReceiver extends ReceiverAdapter {
String name;
final List<Pair<Address,Integer>> msgs=new LinkedList<Pair<Address,Integer>>();
AtomicInteger count=new AtomicInteger(0);
public MyReceiver(String name) {
this.name=name;
}
public void receive(Message msg) {
Util.sleep(SLEEPTIME);
Pair<Address,Integer> pair=new Pair<Address,Integer>(msg.getSrc(), (Integer)msg.getObject());
synchronized(msgs) {
msgs.add(pair);
}
if(count.incrementAndGet() >= EXPECTED) {
try {
barrier.await();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public List<Pair<Address,Integer>> getMessages() {return msgs;}
public String getName() {
return name;
}
}
}
|
tests/junit/org/jgroups/tests/ConcurrentStackTest.java
|
package org.jgroups.tests;
import org.jgroups.*;
import org.jgroups.protocols.TP;
import org.jgroups.util.Util;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.*;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Tests the TLS
* @author Bela Ban
* @version $Id: ConcurrentStackTest.java,v 1.12 2009/04/09 09:11:16 belaban Exp $
*/
@Test(groups=Global.STACK_DEPENDENT,sequential=true)
public class ConcurrentStackTest extends ChannelTestBase {
JChannel ch1, ch2, ch3;
final static int NUM=25, EXPECTED=NUM * 3;
final static long SLEEPTIME=100;
CyclicBarrier barrier;
@BeforeMethod
void setUp() throws Exception {
barrier=new CyclicBarrier(4);
ch1=createChannel(true,3);
ch2=createChannel(ch1);
ch3=createChannel(ch1);
}
@AfterMethod
protected void tearDown() throws Exception {
Util.close(ch3, ch2, ch1);
barrier.reset();
}
@Test
public void testSequentialDelivery() throws Exception {
doIt(false);
}
@Test
public void testConcurrentDelivery() throws Exception {
doIt(true);
}
private void doIt(boolean concurrent) throws Exception {
long start, stop, diff;
setConcurrent(ch1, concurrent);
setConcurrent(ch2, concurrent);
setConcurrent(ch3, concurrent);
MyReceiver r1=new MyReceiver("R1"), r2=new MyReceiver("R2"), r3=new MyReceiver("R3");
ch1.setReceiver(r1); ch2.setReceiver(r2); ch3.setReceiver(r3);
ch1.connect("ConcurrentStackTest");
ch2.connect("ConcurrentStackTest");
ch3.connect("ConcurrentStackTest");
View v=ch3.getView();
assert v.size() == 3 : "view is " + v;
new Thread(new Sender(ch1)) {}.start();
new Thread(new Sender(ch2)) {}.start();
new Thread(new Sender(ch3)) {}.start();
barrier.await(); // start senders
start=System.currentTimeMillis();
Exception ex=null;
try {
barrier.await((long)(EXPECTED * SLEEPTIME * 1.3), TimeUnit.MILLISECONDS); // wait for all receivers
}
catch(java.util.concurrent.TimeoutException e) {
ex=e;
}
stop=System.currentTimeMillis();
diff=stop - start;
System.out.println("Total time: " + diff + " ms\n");
checkFIFO(r1);
checkFIFO(r2);
checkFIFO(r3);
/*
* TODO Vladimir Feb 15th 2007
* Re-enable once acceptable bounds are known for all stacks
* checkTime(diff, threadless);
*
* */
if(ex != null)
throw ex;
}
private void checkFIFO(MyReceiver r) {
List<Pair<Address,Integer>> msgs=r.getMessages();
Map<Address,List<Integer>> map=new HashMap<Address,List<Integer>>();
for(Pair<Address,Integer> p: msgs) {
Address sender=p.key;
List<Integer> list=map.get(sender);
if(list == null) {
list=new LinkedList<Integer>();
map.put(sender, list);
}
list.add(p.val);
}
boolean fifo=true;
List<Address> incorrect_receivers=new LinkedList<Address>();
System.out.println("Checking FIFO for " + r.getName() + ":");
for(Address addr: map.keySet()) {
List<Integer> list=map.get(addr);
print(addr, list);
if(!verifyFIFO(list)) {
fifo=false;
incorrect_receivers.add(addr);
}
}
System.out.print("\n");
if(!fifo)
assert false : "The following receivers didn't receive all messages in FIFO order: " + incorrect_receivers;
}
private static boolean verifyFIFO(List<Integer> list) {
List<Integer> list2=new LinkedList<Integer>(list);
Collections.sort(list2);
return list.equals(list2);
}
private static void print(Address addr, List<Integer> list) {
StringBuilder sb=new StringBuilder();
sb.append(addr).append(": ");
for(Integer i: list)
sb.append(i).append(" ");
System.out.println(sb);
}
private static void setConcurrent(JChannel ch1, boolean concurrent) {
TP transport=ch1.getProtocolStack().getTransport();
transport.setUseConcurrentStack(concurrent);
ThreadPoolExecutor default_pool=(ThreadPoolExecutor)transport.getDefaultThreadPool();
if(default_pool != null) {
default_pool.setCorePoolSize(1);
default_pool.setMaximumPoolSize(100);
}
transport.setThreadPoolQueueEnabled(false);
}
private class Sender implements Runnable {
Channel ch;
Address local_addr;
public Sender(Channel ch) {
this.ch=ch;
local_addr=ch.getAddress();
}
public void run() {
Message msg;
try {
barrier.await();
}
catch(Throwable t) {
return;
}
for(int i=1; i <= NUM; i++) {
msg=new Message(null, null, new Integer(i));
try {
ch.send(msg);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
private class Pair<K,V> {
K key;
V val;
public Pair(K key, V val) {
this.key=key;
this.val=val;
}
public String toString() {
return key + "::" + val;
}
}
private class MyReceiver extends ReceiverAdapter {
String name;
final List<Pair<Address,Integer>> msgs=new LinkedList<Pair<Address,Integer>>();
AtomicInteger count=new AtomicInteger(0);
public MyReceiver(String name) {
this.name=name;
}
public void receive(Message msg) {
Util.sleep(SLEEPTIME);
Pair<Address,Integer> pair=new Pair<Address,Integer>(msg.getSrc(), (Integer)msg.getObject());
synchronized(msgs) {
msgs.add(pair);
}
if(count.incrementAndGet() >= EXPECTED) {
try {
barrier.await();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public List<Pair<Address,Integer>> getMessages() {return msgs;}
public String getName() {
return name;
}
}
}
|
increase barrier wait time slightly
|
tests/junit/org/jgroups/tests/ConcurrentStackTest.java
|
increase barrier wait time slightly
|
|
Java
|
apache-2.0
|
b4073cd21954c632884b284967bbe1fd781cc109
| 0
|
lrkwz/generator-jhipster,rkohel/generator-jhipster,atomfrede/generator-jhipster,siliconharborlabs/generator-jhipster,cbornet/generator-jhipster,nkolosnjaji/generator-jhipster,dalbelap/generator-jhipster,Tcharl/generator-jhipster,siliconharborlabs/generator-jhipster,xetys/generator-jhipster,rkohel/generator-jhipster,siliconharborlabs/generator-jhipster,sendilkumarn/generator-jhipster,atomfrede/generator-jhipster,dalbelap/generator-jhipster,eosimosu/generator-jhipster,ctamisier/generator-jhipster,deepu105/generator-jhipster,yongli82/generator-jhipster,pascalgrimaud/generator-jhipster,duderoot/generator-jhipster,ziogiugno/generator-jhipster,pascalgrimaud/generator-jhipster,gzsombor/generator-jhipster,hdurix/generator-jhipster,baskeboler/generator-jhipster,gzsombor/generator-jhipster,wmarques/generator-jhipster,sendilkumarn/generator-jhipster,hdurix/generator-jhipster,deepu105/generator-jhipster,wmarques/generator-jhipster,ruddell/generator-jhipster,sendilkumarn/generator-jhipster,wmarques/generator-jhipster,cbornet/generator-jhipster,robertmilowski/generator-jhipster,erikkemperman/generator-jhipster,vivekmore/generator-jhipster,maniacneron/generator-jhipster,lrkwz/generator-jhipster,nkolosnjaji/generator-jhipster,baskeboler/generator-jhipster,maniacneron/generator-jhipster,eosimosu/generator-jhipster,ziogiugno/generator-jhipster,PierreBesson/generator-jhipster,stevehouel/generator-jhipster,sendilkumarn/generator-jhipster,deepu105/generator-jhipster,liseri/generator-jhipster,ruddell/generator-jhipster,pascalgrimaud/generator-jhipster,gzsombor/generator-jhipster,rkohel/generator-jhipster,cbornet/generator-jhipster,liseri/generator-jhipster,sohibegit/generator-jhipster,cbornet/generator-jhipster,ramzimaalej/generator-jhipster,gzsombor/generator-jhipster,ruddell/generator-jhipster,dalbelap/generator-jhipster,baskeboler/generator-jhipster,baskeboler/generator-jhipster,danielpetisme/generator-jhipster,jkutner/generator-jhipster,pascalgrimaud/generator-jhipster,robertmilowski/generator-jhipster,siliconharborlabs/generator-jhipster,ctamisier/generator-jhipster,dimeros/generator-jhipster,PierreBesson/generator-jhipster,ruddell/generator-jhipster,duderoot/generator-jhipster,stevehouel/generator-jhipster,danielpetisme/generator-jhipster,mraible/generator-jhipster,mosoft521/generator-jhipster,mosoft521/generator-jhipster,lrkwz/generator-jhipster,liseri/generator-jhipster,Tcharl/generator-jhipster,gmarziou/generator-jhipster,maniacneron/generator-jhipster,sendilkumarn/generator-jhipster,hdurix/generator-jhipster,nkolosnjaji/generator-jhipster,eosimosu/generator-jhipster,stevehouel/generator-jhipster,danielpetisme/generator-jhipster,vivekmore/generator-jhipster,robertmilowski/generator-jhipster,robertmilowski/generator-jhipster,JulienMrgrd/generator-jhipster,eosimosu/generator-jhipster,mraible/generator-jhipster,liseri/generator-jhipster,dimeros/generator-jhipster,nkolosnjaji/generator-jhipster,ziogiugno/generator-jhipster,jkutner/generator-jhipster,sohibegit/generator-jhipster,atomfrede/generator-jhipster,ctamisier/generator-jhipster,PierreBesson/generator-jhipster,jhipster/generator-jhipster,duderoot/generator-jhipster,mosoft521/generator-jhipster,mraible/generator-jhipster,hdurix/generator-jhipster,PierreBesson/generator-jhipster,wmarques/generator-jhipster,rifatdover/generator-jhipster,xetys/generator-jhipster,gmarziou/generator-jhipster,dimeros/generator-jhipster,jhipster/generator-jhipster,deepu105/generator-jhipster,dimeros/generator-jhipster,robertmilowski/generator-jhipster,jkutner/generator-jhipster,gzsombor/generator-jhipster,rkohel/generator-jhipster,jkutner/generator-jhipster,duderoot/generator-jhipster,ramzimaalej/generator-jhipster,JulienMrgrd/generator-jhipster,lrkwz/generator-jhipster,ziogiugno/generator-jhipster,JulienMrgrd/generator-jhipster,dalbelap/generator-jhipster,ctamisier/generator-jhipster,eosimosu/generator-jhipster,erikkemperman/generator-jhipster,ruddell/generator-jhipster,jkutner/generator-jhipster,mraible/generator-jhipster,erikkemperman/generator-jhipster,yongli82/generator-jhipster,rifatdover/generator-jhipster,mraible/generator-jhipster,liseri/generator-jhipster,gmarziou/generator-jhipster,PierreBesson/generator-jhipster,xetys/generator-jhipster,stevehouel/generator-jhipster,dynamicguy/generator-jhipster,ramzimaalej/generator-jhipster,baskeboler/generator-jhipster,ziogiugno/generator-jhipster,dimeros/generator-jhipster,maniacneron/generator-jhipster,erikkemperman/generator-jhipster,deepu105/generator-jhipster,jhipster/generator-jhipster,pascalgrimaud/generator-jhipster,lrkwz/generator-jhipster,gmarziou/generator-jhipster,xetys/generator-jhipster,cbornet/generator-jhipster,atomfrede/generator-jhipster,siliconharborlabs/generator-jhipster,rifatdover/generator-jhipster,dynamicguy/generator-jhipster,jhipster/generator-jhipster,stevehouel/generator-jhipster,sohibegit/generator-jhipster,sohibegit/generator-jhipster,hdurix/generator-jhipster,vivekmore/generator-jhipster,erikkemperman/generator-jhipster,Tcharl/generator-jhipster,rkohel/generator-jhipster,wmarques/generator-jhipster,yongli82/generator-jhipster,ctamisier/generator-jhipster,danielpetisme/generator-jhipster,nkolosnjaji/generator-jhipster,mosoft521/generator-jhipster,yongli82/generator-jhipster,dalbelap/generator-jhipster,jhipster/generator-jhipster,JulienMrgrd/generator-jhipster,atomfrede/generator-jhipster,Tcharl/generator-jhipster,dynamicguy/generator-jhipster,vivekmore/generator-jhipster,Tcharl/generator-jhipster,dynamicguy/generator-jhipster,gmarziou/generator-jhipster,mosoft521/generator-jhipster,yongli82/generator-jhipster,sohibegit/generator-jhipster,JulienMrgrd/generator-jhipster,duderoot/generator-jhipster,vivekmore/generator-jhipster,danielpetisme/generator-jhipster,maniacneron/generator-jhipster
|
package <%=packageName%>.service;
import <%=packageName%>.config.audit.AuditEventConverter;
import <%=packageName%>.domain.PersistentAuditEvent;
import <%=packageName%>.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
/**
* Service for managing audit event.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Inject
private AuditEventConverter auditEventConverter;
public List<AuditEvent> findAll() {
return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
}
public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) {
final List<PersistentAuditEvent> persistentAuditEvents =
persistenceAuditEventRepository.findByDates(fromDate, toDate);
return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
}
}
|
app/templates/src/main/java/package/service/_AuditEventService.java
|
package <%=packageName%>.service;
import <%=packageName%>.config.audit.AuditEventConverter;
import <%=packageName%>.domain.PersistentAuditEvent;
import <%=packageName%>.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
/**
* Service for managing audit event.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Inject
private AuditEventConverter auditEventConverter;
public List<AuditEvent> findAll() {
return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
}
public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) {
final List<PersistentAuditEvent> persistentAuditEvents =
persistenceAuditEventRepository.findByAuditEventDateBetween(fromDate, toDate);
return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
}
}
|
Call the new findByDates method
|
app/templates/src/main/java/package/service/_AuditEventService.java
|
Call the new findByDates method
|
|
Java
|
bsd-2-clause
|
135c3ee12d39c691f599daebdb879d1b0f967973
| 0
|
imagej/imagej-legacy,imagej/imagej-legacy,imagej/imagej-legacy,imagej/imagej-legacy
|
/*-
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2018 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.legacy.plugin;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.imagej.legacy.IJ1Helper;
import org.fife.ui.autocomplete.BasicCompletion;
import org.fife.ui.autocomplete.Completion;
import org.fife.ui.autocomplete.DefaultCompletionProvider;
import org.fife.ui.autocomplete.SortByRelevanceComparator;
import org.fife.ui.rtextarea.RTextArea;
import org.fife.ui.rtextarea.ToolTipSupplier;
import org.scijava.module.ModuleInfo;
import org.scijava.module.ModuleService;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
/**
* Creates the list of auto-completion suggestions from functions.html
* documentation.
*
* @author Robert Haase
*/
class MacroAutoCompletionProvider extends DefaultCompletionProvider implements
ToolTipSupplier
{
private ModuleService moduleService;
private MacroExtensionAutoCompletionService macroExtensionAutoCompletionService;
private static MacroAutoCompletionProvider instance = null;
private boolean sorted = false;
private final int maximumSearchResults = 100;
private MacroAutoCompletionProvider() {
parseFunctionsHtmlDoc("/doc/ij1macro/functions.html");
parseFunctionsHtmlDoc("/doc/ij1macro/functions_extd.html");
}
public static synchronized MacroAutoCompletionProvider getInstance() {
if (instance == null) {
instance = new MacroAutoCompletionProvider();
}
return instance;
}
private boolean parseFunctionsHtmlDoc(final String filename) {
InputStream resourceAsStream;
sorted = false;
try {
if (filename.startsWith("http")) {
final URL url = new URL(filename);
resourceAsStream = url.openStream();
}
else {
resourceAsStream = getClass().getResourceAsStream(filename);
}
if (resourceAsStream == null) return false;
final BufferedReader br = //
new BufferedReader(new InputStreamReader(resourceAsStream));
String name = "";
String headline = "";
String description = "";
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
line = line.replace("<a name=\"", "<a name=").replace("\"></a>",
"></a>");
if (line.contains("<a name=")) {
if (checkCompletion(headline, name, description)) {
addCompletion(makeListEntry(this, headline, name, description));
}
name = htmlToText(line.split("<a name=")[1].split("></a>")[0]);
description = "";
headline = "";
}
else {
if (headline.length() == 0) {
headline = htmlToText(line);
}
else {
description = description + line + "\n";
}
}
}
if (checkCompletion(headline, name, description)) {
addCompletion(makeListEntry(this, headline, name, description));
}
}
catch (final javax.net.ssl.SSLHandshakeException e)
{
return false;
}
catch (final UnknownHostException e) {
return false;
}
catch (final IOException e) {
e.printStackTrace();
return false;
}
return true;
}
void addModuleCompletions(ModuleService moduleService) {
if (this.moduleService == moduleService) {
return;
}
sorted = false;
this.moduleService = moduleService;
for (ModuleInfo info : moduleService.getModules()) {
if(info.getMenuPath().getLeaf() != null) {
String name = info.getMenuPath().getLeaf().getName().trim();
String headline = "run(\"" + name +"\")";
String description = "<b>" + headline + "</b><p>" +
"<a href=\"https://imagej.net/Special:Search/" + name.replace(" ", "%20") + "\">Search imagej wiki for help</a>";
addCompletion(makeListEntry(this, headline, null, description));
}
}
}
public void addMacroExtensionAutoCompletions(MacroExtensionAutoCompletionService macroExtensionAutoCompletionService) {
if (this.macroExtensionAutoCompletionService != null) {
return;
}
sorted = false;
this.macroExtensionAutoCompletionService = macroExtensionAutoCompletionService;
List<BasicCompletion> completions = macroExtensionAutoCompletionService.getCompletions(this);
for (BasicCompletion completion : completions) {
addCompletion(completion);
}
}
public void sort() {
if (!sorted) {
Collections.sort(completions, new SortByRelevanceComparator());
sorted = true;
}
}
private boolean checkCompletion(final String headline, final String name, final String description) {
return headline.length() > 0 && //
name.length() > 1 && //
!name.trim().startsWith("<") && //
!name.trim().startsWith("-") && //
name.compareTo("Top") != 0 && //
name.compareTo("IJ") != 0 && //
name.compareTo("Stack") != 0 && //
name.compareTo("Array") != 0 && //
name.compareTo("file") != 0 && //
name.compareTo("Fit") != 0 && //
name.compareTo("List") != 0 && //
name.compareTo("Overlay") != 0 && //
name.compareTo("Plot") != 0 && //
name.compareTo("Roi") != 0 && //
name.compareTo("String") != 0 && //
name.compareTo("Table") != 0 && //
name.compareTo("Ext") != 0 && //
name.compareTo("ext") != 0 && //
name.compareTo("alphabar") != 0 && //
name.compareTo("ext") != 0;
}
private String htmlToText(final String text) {
return text //
.replace(""", "\"") //
.replace("&", "&") //
.replace("<b>", "") //
.replace("</b>", "") //
.replace("<i>", "") //
.replace("</i>", "") //
.replace("<br>", "\n");
}
private BasicCompletion makeListEntry(
final MacroAutoCompletionProvider provider, String headline,
final String name, String description)
{
if (!headline.startsWith("run(\"")) {
final String link = //
"https://imagej.net/developer/macro/functions.html#" + name;
description = //
"<a href=\"" + link + "\">" + headline + "</a><br>" + description;
}
if (headline.trim().endsWith("-")) {
headline = headline.trim();
headline = headline.substring(0, headline.length() - 2);
}
return new BasicCompletion(provider, headline, null, description);
}
/**
* Returns the tool tip to display for a mouse event.
* <p>
* For this method to be called, the <tt>RSyntaxTextArea</tt> must be
* registered with the <tt>javax.swing.ToolTipManager</tt> like so:
* </p>
*
* <pre>
* ToolTipManager.sharedInstance().registerComponent(textArea);
* </pre>
*
* @param textArea The text area.
* @param e The mouse event.
* @return The tool tip text, or <code>null</code> if none.
*/
@Override
public String getToolTipText(final RTextArea textArea, final MouseEvent e) {
String tip = null;
final List<Completion> completions = //
getCompletionsAt(textArea, e.getPoint());
if (completions != null && completions.size() > 0) {
// Only ever 1 match for us in C...
final Completion c = completions.get(0);
tip = c.getToolTipText();
}
return tip;
}
protected boolean isValidChar(char ch) {
return Character.isLetterOrDigit(ch) || ch == '_' || ch == '.' || ch == '"';
}
/**
* Returns a list of <tt>Completion</tt>s in this provider with the
* specified input text.
*
* @param inputText The input text to search for.
* @return A list of {@link Completion}s, or <code>null</code> if there
* are no matching <tt>Completion</tt>s.
*/
@SuppressWarnings("unchecked")
@Override
public List<Completion> getCompletionByInputText(String inputText) {
inputText = inputText.toLowerCase();
ArrayList<Completion> result = new ArrayList<Completion>();
int count = 0;
int secondaryCount = 0;
for (Completion completion : completions) {
String text = completion.getInputText().toLowerCase();
if (text.contains(inputText)) {
if (text.startsWith(inputText)) {
result.add(count, completion);
count++;
} else {
result.add(completion);
secondaryCount++;
}
}
if (secondaryCount + count > maximumSearchResults) {
break; // if too many results are found, exit to not annoy the user
}
}
return result;
}
private void appendMacroSpecificCompletions(String input, List<Completion> result, JTextComponent comp) {
List<Completion> completions = new ArrayList<Completion>();
String lcaseinput = input.toLowerCase();
String text = null;
try {
text = comp.getDocument().getText(0, comp.getDocument().getLength());
} catch (BadLocationException e) {
e.printStackTrace();
return;
}
text = text + "\n" + IJ1Helper.getAdditionalMacroFunctions();
int linecount = 0;
String[] textArray = text.split("\n");
for (String line : textArray){
String trimmedline = line.trim();
String lcaseline = trimmedline.toLowerCase();
if (lcaseline.startsWith("function ")) {
String command = trimmedline.substring(8).trim().replace("{", "");
String lcasecommand = command.toLowerCase();
if (lcasecommand.contains(lcaseinput)) {
String description = findDescription(textArray, linecount, "User defined function " + command + "\n as specified in line " + (linecount + 1));
completions.add(new BasicCompletion(this, command, null, description));
}
}
if (lcaseline.contains("=")) {
String command = trimmedline.substring(0, lcaseline.indexOf("=")).trim();
String lcasecommand = command.toLowerCase();
if (lcasecommand.contains(lcaseinput) && command.matches("[_a-zA-Z]+")) {
String description = "User defined variable " + command + "\n as specified in line " + (linecount + 1);
completions.add(new BasicCompletion(this, command, null, description));
}
}
linecount++;
}
Collections.sort(completions, new SortByRelevanceComparator());
result.addAll(0, completions);
}
private String findDescription(String[] textArray, int linecount, String defaultDescription) {
String resultDescription = "";
int l = linecount - 1;
while (l > 0) {
String lineBefore = textArray[l].trim();
System.out.println("Scanning B " + lineBefore);
if (lineBefore.startsWith("//")) {
resultDescription = lineBefore.substring(2) + "\n" + resultDescription;
} else {
break;
}
l--;
}
l = linecount + 1;
while (l < textArray.length - 1) {
String lineAfter = textArray[l].trim();
System.out.println("Scanning A " + lineAfter);
if (lineAfter.startsWith("//")) {
resultDescription = resultDescription + "\n" + lineAfter.substring(2);
} else {
break;
}
l++;
}
if (resultDescription.length() > 0) {
resultDescription = resultDescription + "<br><br>";
}
resultDescription = resultDescription + defaultDescription;
return resultDescription;
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
protected List<Completion> getCompletionsImpl(JTextComponent comp) {
List<Completion> retVal = new ArrayList<Completion>();
String text = getAlreadyEnteredText(comp);
if (text != null) {
retVal = getCompletionByInputText(text);
appendMacroSpecificCompletions(text, retVal, comp);
}
return retVal;
}
@Override
public List<Completion> getCompletions(JTextComponent comp) {
List<Completion> completions = this.getCompletionsImpl(comp);
return completions;
}
}
|
src/main/java/net/imagej/legacy/plugin/MacroAutoCompletionProvider.java
|
/*-
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2018 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.legacy.plugin;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.imagej.legacy.IJ1Helper;
import org.fife.ui.autocomplete.BasicCompletion;
import org.fife.ui.autocomplete.Completion;
import org.fife.ui.autocomplete.DefaultCompletionProvider;
import org.fife.ui.autocomplete.SortByRelevanceComparator;
import org.fife.ui.rtextarea.RTextArea;
import org.fife.ui.rtextarea.ToolTipSupplier;
import org.scijava.module.ModuleInfo;
import org.scijava.module.ModuleService;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
/**
* Creates the list of auto-completion suggestions from functions.html
* documentation.
*
* @author Robert Haase
*/
class MacroAutoCompletionProvider extends DefaultCompletionProvider implements
ToolTipSupplier
{
private ModuleService moduleService;
private MacroExtensionAutoCompletionService macroExtensionAutoCompletionService;
private static MacroAutoCompletionProvider instance = null;
private boolean sorted = false;
private final int maximumSearchResults = 100;
private MacroAutoCompletionProvider() {
parseFunctionsHtmlDoc("/doc/ij1macro/functions.html");
parseFunctionsHtmlDoc("/doc/ij1macro/functions_extd.html");
}
public static synchronized MacroAutoCompletionProvider getInstance() {
if (instance == null) {
instance = new MacroAutoCompletionProvider();
}
return instance;
}
private boolean parseFunctionsHtmlDoc(final String filename) {
InputStream resourceAsStream;
sorted = false;
try {
if (filename.startsWith("http")) {
final URL url = new URL(filename);
resourceAsStream = url.openStream();
}
else {
resourceAsStream = getClass().getResourceAsStream(filename);
}
if (resourceAsStream == null) return false;
final BufferedReader br = //
new BufferedReader(new InputStreamReader(resourceAsStream));
String name = "";
String headline = "";
String description = "";
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
line = line.replace("<a name=\"", "<a name=").replace("\"></a>",
"></a>");
if (line.contains("<a name=")) {
if (checkCompletion(headline, name, description)) {
addCompletion(makeListEntry(this, headline, name, description));
}
name = htmlToText(line.split("<a name=")[1].split("></a>")[0]);
description = "";
headline = "";
}
else {
if (headline.length() == 0) {
headline = htmlToText(line);
}
else {
description = description + line + "\n";
}
}
}
if (checkCompletion(headline, name, description)) {
addCompletion(makeListEntry(this, headline, name, description));
}
}
catch (final javax.net.ssl.SSLHandshakeException e)
{
return false;
}
catch (final UnknownHostException e) {
return false;
}
catch (final IOException e) {
e.printStackTrace();
return false;
}
return true;
}
void addModuleCompletions(ModuleService moduleService) {
if (this.moduleService == moduleService) {
return;
}
sorted = false;
this.moduleService = moduleService;
for (ModuleInfo info : moduleService.getModules()) {
if(info.getMenuPath().getLeaf() != null) {
String name = info.getMenuPath().getLeaf().getName().trim();
String headline = "run(\"" + name +"\")";
String description = "<b>" + headline + "</b><p>" +
"<a href=\"https://imagej.net/Special:Search/" + name.replace(" ", "%20") + "\">Search imagej wiki for help</a>";
addCompletion(makeListEntry(this, headline, null, description));
}
}
}
public void addMacroExtensionAutoCompletions(MacroExtensionAutoCompletionService macroExtensionAutoCompletionService) {
if (this.macroExtensionAutoCompletionService != null) {
return;
}
sorted = false;
this.macroExtensionAutoCompletionService = macroExtensionAutoCompletionService;
List<BasicCompletion> completions = macroExtensionAutoCompletionService.getCompletions(this);
for (BasicCompletion completion : completions) {
addCompletion(completion);
}
}
public void sort() {
if (!sorted) {
Collections.sort(completions, new SortByRelevanceComparator());
sorted = true;
}
}
private boolean checkCompletion(final String headline, final String name, final String description) {
return headline.length() > 0 && //
name.length() > 1 && //
!name.trim().startsWith("<") && //
!name.trim().startsWith("-") && //
name.compareTo("Top") != 0 && //
name.compareTo("IJ") != 0 && //
name.compareTo("Stack") != 0 && //
name.compareTo("Array") != 0 && //
name.compareTo("file") != 0 && //
name.compareTo("Fit") != 0 && //
name.compareTo("List") != 0 && //
name.compareTo("Overlay") != 0 && //
name.compareTo("Plot") != 0 && //
name.compareTo("Roi") != 0 && //
name.compareTo("String") != 0 && //
name.compareTo("Table") != 0 && //
name.compareTo("Ext") != 0 && //
name.compareTo("ext") != 0 && //
name.compareTo("alphabar") != 0 && //
name.compareTo("ext") != 0;
}
private String htmlToText(final String text) {
return text //
.replace(""", "\"") //
.replace("&", "&") //
.replace("<b>", "") //
.replace("</b>", "") //
.replace("<i>", "") //
.replace("</i>", "") //
.replace("<br>", "");
}
private BasicCompletion makeListEntry(
final MacroAutoCompletionProvider provider, String headline,
final String name, String description)
{
if (!headline.startsWith("run(\"")) {
final String link = //
"https://imagej.net/developer/macro/functions.html#" + name;
description = //
"<a href=\"" + link + "\">" + headline + "</a><br>" + description;
}
if (headline.trim().endsWith("-")) {
headline = headline.trim();
headline = headline.substring(0, headline.length() - 2);
}
return new BasicCompletion(provider, headline, null, description);
}
/**
* Returns the tool tip to display for a mouse event.
* <p>
* For this method to be called, the <tt>RSyntaxTextArea</tt> must be
* registered with the <tt>javax.swing.ToolTipManager</tt> like so:
* </p>
*
* <pre>
* ToolTipManager.sharedInstance().registerComponent(textArea);
* </pre>
*
* @param textArea The text area.
* @param e The mouse event.
* @return The tool tip text, or <code>null</code> if none.
*/
@Override
public String getToolTipText(final RTextArea textArea, final MouseEvent e) {
String tip = null;
final List<Completion> completions = //
getCompletionsAt(textArea, e.getPoint());
if (completions != null && completions.size() > 0) {
// Only ever 1 match for us in C...
final Completion c = completions.get(0);
tip = c.getToolTipText();
}
return tip;
}
protected boolean isValidChar(char ch) {
return Character.isLetterOrDigit(ch) || ch == '_' || ch == '.' || ch == '"';
}
/**
* Returns a list of <tt>Completion</tt>s in this provider with the
* specified input text.
*
* @param inputText The input text to search for.
* @return A list of {@link Completion}s, or <code>null</code> if there
* are no matching <tt>Completion</tt>s.
*/
@SuppressWarnings("unchecked")
@Override
public List<Completion> getCompletionByInputText(String inputText) {
inputText = inputText.toLowerCase();
ArrayList<Completion> result = new ArrayList<Completion>();
int count = 0;
int secondaryCount = 0;
for (Completion completion : completions) {
String text = completion.getInputText().toLowerCase();
if (text.contains(inputText)) {
if (text.startsWith(inputText)) {
result.add(count, completion);
count++;
} else {
result.add(completion);
secondaryCount++;
}
}
if (secondaryCount + count > maximumSearchResults) {
break; // if too many results are found, exit to not annoy the user
}
}
return result;
}
private void appendMacroSpecificCompletions(String input, List<Completion> result, JTextComponent comp) {
List<Completion> completions = new ArrayList<Completion>();
String lcaseinput = input.toLowerCase();
String text = null;
try {
text = comp.getDocument().getText(0, comp.getDocument().getLength());
} catch (BadLocationException e) {
e.printStackTrace();
return;
}
text = text + "\n" + IJ1Helper.getAdditionalMacroFunctions();
int linecount = 0;
String[] textArray = text.split("\n");
for (String line : textArray){
String trimmedline = line.trim();
String lcaseline = trimmedline.toLowerCase();
if (lcaseline.startsWith("function ")) {
String command = trimmedline.substring(8).trim().replace("{", "");
String lcasecommand = command.toLowerCase();
if (lcasecommand.contains(lcaseinput)) {
String description = findDescription(textArray, linecount, "User defined function " + command + "\n as specified in line " + (linecount + 1));
completions.add(new BasicCompletion(this, command, null, description));
}
}
if (lcaseline.contains("=")) {
String command = trimmedline.substring(0, lcaseline.indexOf("=")).trim();
String lcasecommand = command.toLowerCase();
if (lcasecommand.contains(lcaseinput) && command.matches("[_a-zA-Z]+")) {
String description = "User defined variable " + command + "\n as specified in line " + (linecount + 1);
completions.add(new BasicCompletion(this, command, null, description));
}
}
linecount++;
}
Collections.sort(completions, new SortByRelevanceComparator());
result.addAll(0, completions);
}
private String findDescription(String[] textArray, int linecount, String defaultDescription) {
String resultDescription = "";
int l = linecount - 1;
while (l > 0) {
String lineBefore = textArray[l].trim();
System.out.println("Scanning B " + lineBefore);
if (lineBefore.startsWith("//")) {
resultDescription = lineBefore.substring(2) + "\n" + resultDescription;
} else {
break;
}
l--;
}
l = linecount + 1;
while (l < textArray.length - 1) {
String lineAfter = textArray[l].trim();
System.out.println("Scanning A " + lineAfter);
if (lineAfter.startsWith("//")) {
resultDescription = resultDescription + "\n" + lineAfter.substring(2);
} else {
break;
}
l++;
}
if (resultDescription.length() > 0) {
resultDescription = resultDescription + "<br><br>";
}
resultDescription = resultDescription + defaultDescription;
return resultDescription;
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
protected List<Completion> getCompletionsImpl(JTextComponent comp) {
List<Completion> retVal = new ArrayList<Completion>();
String text = getAlreadyEnteredText(comp);
if (text != null) {
retVal = getCompletionByInputText(text);
appendMacroSpecificCompletions(text, retVal, comp);
}
return retVal;
}
@Override
public List<Completion> getCompletions(JTextComponent comp) {
List<Completion> completions = this.getCompletionsImpl(comp);
return completions;
}
}
|
allow multi-line auto-completions (e.g. code snippets)
|
src/main/java/net/imagej/legacy/plugin/MacroAutoCompletionProvider.java
|
allow multi-line auto-completions (e.g. code snippets)
|
|
Java
|
lgpl-2.1
|
1a3b54738e9caec31e783b9e0c94b11afd9d8be3
| 0
|
animesh-kumar/topcoder
|
git/topcoder/SRM649-2015-02-10/src/CartInSupermarketEasy.java
|
import java.util.ArrayList;
/**
* This code is not complete and doesn't work. Please don't use it.
*
* @author animesh-kumar
*
*/
public class CartInSupermarketEasy {
public int calc(int n, int k) {
// First check if k > 0
int time = 0;
ArrayList<Integer> carts = new ArrayList<Integer>();
ArrayList<Integer> cartsDup = new ArrayList<Integer>();
cartsDup.add(n);
if (k > 0) {
// Split the cart
for (int i = 0; i < k; i++) {
// Check each element in the arraylist and divide it
boolean divided = false;
for (Integer cart : cartsDup) {
if (cart > 1) {
divided = true;
int half = cart / 2;
if (cart % 2 == 0) {
carts.add(half);
carts.add(half);
} else {
carts.add(half);
carts.add(half + 1);
}
} else {
break;
}
}
if (divided) {
time++;
cartsDup.removeAll(cartsDup);
cartsDup.addAll(carts);
carts.removeAll(carts);
}
}
int i = 0;
carts.addAll(cartsDup);
int size = carts.size();
// Once you have finished division reduce
while (size > 0) {
for (int j = 0; j < size; j++) {
int cart = carts.remove(i);
cart--;
if (cart > 0) {
carts.add(cart);
}
}
size = carts.size();
time++;
}
System.out.println(time);
return time;
}
System.out.println(time);
return n;
}
public static void main(String[] args) {
CartInSupermarketEasy c = new CartInSupermarketEasy();
int n = 15;
int k = 4;
c.calc(n, k);
}
}
|
Delete CartInSupermarketEasy.java
|
git/topcoder/SRM649-2015-02-10/src/CartInSupermarketEasy.java
|
Delete CartInSupermarketEasy.java
|
||
Java
|
isc
|
2a36b5f0db796b5d31908d50d34af8d2f0e63883
| 0
|
yamill/react-native-orientation,yamill/react-native-orientation,yamill/react-native-orientation
|
package com.github.yamill.orientation;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import com.facebook.common.logging.FLog;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class OrientationModule extends ReactContextBaseJavaModule {
final private Activity mActivity;
final private ReactApplicationContext mReactContext;
private static final int ORIENTATION_0 = 0;
private static final int ORIENTATION_90 = 3;
private static final int ORIENTATION_270 = 1;
public OrientationModule(ReactApplicationContext reactContext, final Activity activity) {
super(reactContext);
mActivity = activity;
mReactContext = reactContext;
final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Configuration newConfig = intent.getParcelableExtra("newConfig");
Log.d("receiver", String.valueOf(newConfig.orientation));
String orientationValue = newConfig.orientation == 1 ? "PORTRAIT" : "LANDSCAPE";
WritableMap params = Arguments.createMap();
params.putString("orientation", orientationValue);
mReactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("orientationDidChange", params);
//Specific Orientation
Display display = ((WindowManager)
mReactContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenOrientation = display.getRotation();
String specifOrientationValue = getSpecificOrientationString(screenOrientation);
WritableMap params2 = Arguments.createMap();
params2.putString("specificOrientation", specifOrientationValue);
mReactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("specificOrientationDidChange", params2);
}
};
activity.registerReceiver(receiver, new IntentFilter("onConfigurationChanged"));
LifecycleEventListener listener = new LifecycleEventListener() {
@Override
public void onHostResume() {
activity.registerReceiver(receiver, new IntentFilter("onConfigurationChanged"));
}
@Override
public void onHostPause() {
try
{
activity.unregisterReceiver(receiver);
}
catch (java.lang.IllegalArgumentException e) {
FLog.e(ReactConstants.TAG, "receiver already unregistered", e);
}
}
@Override
public void onHostDestroy() {
try
{
activity.unregisterReceiver(receiver);
}
catch (java.lang.IllegalArgumentException e) {
FLog.e(ReactConstants.TAG, "receiver already unregistered", e);
}
}
};
reactContext.addLifecycleEventListener(listener);
}
@Override
public String getName() {
return "Orientation";
}
@ReactMethod
public void getOrientation(Callback callback) {
final int orientationInt = getReactApplicationContext().getResources().getConfiguration().orientation;
String orientation = this.getOrientationString(orientationInt);
if (orientation == "null") {
callback.invoke(orientationInt, null);
} else {
callback.invoke(null, orientation);
}
}
@ReactMethod
public void getSpecificOrientation(Callback callback) {
Display display = ((WindowManager)
mReactContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenOrientation = display.getRotation();
String specifOrientationValue = getSpecificOrientationString(screenOrientation);
if (specifOrientationValue == "null") {
callback.invoke(screenOrientation, null);
} else {
callback.invoke(null, specifOrientationValue);
}
}
@ReactMethod
public void lockToPortrait() {
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
@ReactMethod
public void lockToLandscape() {
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
@ReactMethod
public void unlockAllOrientations() {
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
@Override
public @Nullable Map<String, Object> getConstants() {
HashMap<String, Object> constants = new HashMap<String, Object>();
int orientationInt = getReactApplicationContext().getResources().getConfiguration().orientation;
String orientation = this.getOrientationString(orientationInt);
if (orientation == "null") {
constants.put("initialOrientation", null);
} else {
constants.put("initialOrientation", orientation);
}
return constants;
}
private String getOrientationString(int orientation) {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
return "LANDSCAPE";
} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
return "PORTRAIT";
} else if (orientation == Configuration.ORIENTATION_UNDEFINED) {
return "UNKNOWN";
} else {
return "null";
}
}
private String getSpecificOrientationString(int screenOrientation) {
String specifOrientationValue = "UNKNOWN";
switch (screenOrientation)
{
default:
case ORIENTATION_0: // Portrait
specifOrientationValue = "PORTRAIT";
break;
case ORIENTATION_90: // Landscape right
specifOrientationValue = "LANDSCAPE-RIGHT";
break;
case ORIENTATION_270: // Landscape left
specifOrientationValue = "LANDSCAPE-LEFT";
break;
}
return specifOrientationValue;
}
}
|
android/src/main/java/com/github/yamill/orientation/OrientationModule.java
|
package com.github.yamill.orientation;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import com.facebook.common.logging.FLog;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class OrientationModule extends ReactContextBaseJavaModule {
final private Activity mActivity;
public OrientationModule(ReactApplicationContext reactContext, final Activity activity) {
super(reactContext);
mActivity = activity;
final ReactApplicationContext ctx = reactContext;
final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Configuration newConfig = intent.getParcelableExtra("newConfig");
Log.d("receiver", String.valueOf(newConfig.orientation));
String orientationValue = newConfig.orientation == 1 ? "PORTRAIT" : "LANDSCAPE";
WritableMap params = Arguments.createMap();
params.putString("orientation", orientationValue);
ctx
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("orientationDidChange", params);
}
};
activity.registerReceiver(receiver, new IntentFilter("onConfigurationChanged"));
LifecycleEventListener listener = new LifecycleEventListener() {
@Override
public void onHostResume() {
activity.registerReceiver(receiver, new IntentFilter("onConfigurationChanged"));
}
@Override
public void onHostPause() {
try
{
activity.unregisterReceiver(receiver);
}
catch (java.lang.IllegalArgumentException e) {
FLog.e(ReactConstants.TAG, "receiver already unregistered", e);
}
}
@Override
public void onHostDestroy() {
try
{
activity.unregisterReceiver(receiver);
}
catch (java.lang.IllegalArgumentException e) {
FLog.e(ReactConstants.TAG, "receiver already unregistered", e);
}
}
};
reactContext.addLifecycleEventListener(listener);
}
@Override
public String getName() {
return "Orientation";
}
@ReactMethod
public void getOrientation(Callback callback) {
final int orientationInt = getReactApplicationContext().getResources().getConfiguration().orientation;
String orientation = this.getOrientationString(orientationInt);
if (orientation == "null") {
callback.invoke(orientationInt, null);
} else {
callback.invoke(null, orientation);
}
}
@ReactMethod
public void lockToPortrait() {
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
@ReactMethod
public void lockToLandscape() {
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
@ReactMethod
public void unlockAllOrientations() {
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
@Override
public @Nullable Map<String, Object> getConstants() {
HashMap<String, Object> constants = new HashMap<String, Object>();
int orientationInt = getReactApplicationContext().getResources().getConfiguration().orientation;
String orientation = this.getOrientationString(orientationInt);
if (orientation == "null") {
constants.put("initialOrientation", null);
} else {
constants.put("initialOrientation", orientation);
}
return constants;
}
private String getOrientationString(int orientation) {
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
return "LANDSCAPE";
} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
return "PORTRAIT";
} else if (orientation == Configuration.ORIENTATION_UNDEFINED) {
return "UNKNOWN";
} else {
return "null";
}
}
}
|
Android - Specific Orientation Functionality
|
android/src/main/java/com/github/yamill/orientation/OrientationModule.java
|
Android - Specific Orientation Functionality
|
|
Java
|
mit
|
e16cca952eb523a4aad0caff9fbead5668924b18
| 0
|
shunjikonishi/flectSoap
|
package jp.co.flect.soap;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import jp.co.flect.soap.annotation.SoapField;
import jp.co.flect.xmlschema.ComplexType;
import jp.co.flect.xmlschema.TypeDef;
import jp.co.flect.xmlschema.ElementDef;
import jp.co.flect.xmlschema.SimpleType;
import jp.co.flect.xmlschema.ComplexType;
import jp.co.flect.util.ExtendedMap;
public class TypedObjectConverter {
private ComplexType type;
private Class clazz;
private Map<String, Field> fieldMap = new HashMap<String, Field>();
private Map<String, MethodInfo> methodMap = new HashMap<String, MethodInfo>();
public <T extends TypedObject> TypedObjectConverter(ComplexType type, Class<T> clazz) {
this.type = type;
this.clazz = clazz;
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
String fieldName = f.getName();
SoapField api = f.getAnnotation(SoapField.class);
if (api != null) {
String apiName = api.value();
if (apiName == null || apiName.length() == 0) {
apiName = fieldName;
}
f.setAccessible(true);
this.fieldMap.put(apiName, f);
}
}
Method[] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
String fieldName = m.getName();
SoapField api = m.getAnnotation(SoapField.class);
if (api != null) {
String apiName = api.value();
if (apiName == null || apiName.length() == 0) {
apiName = fieldName;
}
MethodInfo info = this.methodMap.get(apiName);
if (info == null) {
info = new MethodInfo();
this.methodMap.put(apiName, info);
}
info.set(m);
m.setAccessible(true);
}
}
}
public String getTargetName() { return this.type.getName();}
public ComplexType getTargetType() { return this.type;}
public Class getTargetClass() { return this.clazz;}
public ExtendedMap toMap(TypedObject obj) {
if (obj.getClass() != this.clazz) {
throw new IllegalArgumentException(obj.getClass().getName());
}
ExtendedMap map = new ExtendedMap();
for (Map.Entry<String, Field> entry : this.fieldMap.entrySet()) {
String name = entry.getKey();
Field f = entry.getValue();
ElementDef el = type.getModel(type.getNamespace(), name);
if (el == null) {
throw new IllegalArgumentException("Unknown fieldName: " + getTargetName() + "." + name);
}
try {
Object value = f.get(obj);
if (value != null) {
putValue(map, name, value, el);
}
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
for (Map.Entry<String, MethodInfo> entry : this.methodMap.entrySet()) {
String name = entry.getKey();
MethodInfo info = entry.getValue();
if (info.getter == null) {
continue;
}
Method m = info.getter;
ElementDef el = type.getModel(type.getNamespace(), name);
if (el == null) {
throw new IllegalArgumentException("Unknown fieldName: " + getTargetName() + "." + name);
}
try {
Object value = m.invoke(obj);
if (value != null) {
putValue(map, name, value, el);
}
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
return map;
}
public TypedObject toObject(XMLStreamReader reader) throws XMLStreamException {
try {
TypedObject ret = (TypedObject)this.clazz.newInstance();
boolean hasValue = false;
boolean endValue = false;
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamReader.START_ELEMENT:
hasValue = true;
String nsuri = reader.getNamespaceURI();
String name = reader.getLocalName();
ElementDef el = type.getModel(nsuri, name);
if (el == null) {
throw new IllegalStateException("Unknown element: " + nsuri + ", " + name);
}
TypeDef elType = el.getType();
if (elType.isSimpleType()) {
Object value = parseSimple((SimpleType)elType, reader);
if (value != null) {
setValue(ret, name, value);
}
} else {
throw new IllegalStateException("Complex type is not implemented.: " + nsuri + ", " + name);
}
break;
case XMLStreamReader.CHARACTERS:
case XMLStreamReader.CDATA:
if (!reader.isWhiteSpace()) {
throw new IllegalStateException();
}
break;
case XMLStreamReader.END_ELEMENT:
endValue = true;
break;
case XMLStreamReader.START_DOCUMENT:
case XMLStreamReader.END_DOCUMENT:
case XMLStreamReader.ATTRIBUTE:
case XMLStreamReader.NAMESPACE:
case XMLStreamReader.SPACE:
case XMLStreamReader.COMMENT:
case XMLStreamReader.PROCESSING_INSTRUCTION:
case XMLStreamReader.ENTITY_REFERENCE:
case XMLStreamReader.DTD:
throw new IllegalStateException();
}
if (endValue) {
break;
}
}
return hasValue ? ret : null;
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
private Object parseSimple(SimpleType type, XMLStreamReader reader) throws XMLStreamException {
StringBuilder buf = new StringBuilder();
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamReader.CHARACTERS:
case XMLStreamReader.CDATA:
buf.append(reader.getText());
break;
case XMLStreamReader.END_ELEMENT:
return buf.length() > 0 ? type.parse(buf.toString()) : null;
case XMLStreamReader.START_DOCUMENT:
case XMLStreamReader.END_DOCUMENT:
case XMLStreamReader.START_ELEMENT:
case XMLStreamReader.ATTRIBUTE:
case XMLStreamReader.NAMESPACE:
case XMLStreamReader.SPACE:
case XMLStreamReader.COMMENT:
case XMLStreamReader.PROCESSING_INSTRUCTION:
case XMLStreamReader.ENTITY_REFERENCE:
case XMLStreamReader.DTD:
throw new IllegalStateException();
}
}
throw new IllegalStateException();
}
private void putValue(ExtendedMap map, String name, Object value, ElementDef el) {
//ToDo complexType
SimpleType type = (SimpleType)el.getType();
map.put(name, type.format(value));
}
private void setValue(TypedObject obj, String name, Object value) {
try {
Field f = fieldMap.get(name);
if (f != null) {
value = convertType(f.getType(), value);
f.set(obj, value);
return;
}
MethodInfo info = methodMap.get(name);
if (info != null && info.setter != null) {
Method m = info.setter;
value = convertType(m.getParameterTypes()[0], value);
m.invoke(obj, value);
}
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
private Object convertType(Class c, Object value) {
if (c == String.class) return value.toString();
if (value instanceof Number) {
Number n = (Number)value;
if (c == Integer.class) return n.intValue();
if (c == Long.class) return n.longValue();
if (c == Double.class) return n.doubleValue();
if (c == Float.class) return n.floatValue();
if (c == Byte.class) return n.byteValue();
if (c == Short.class) return n.shortValue();
if (c == BigDecimal.class) return new BigDecimal(n.toString());
if (c == BigInteger.class) return new BigInteger(n.toString());
}
if (c.isEnum()) {
String str = value.toString();
try {
Method m = c.getDeclaredMethod("values");
Object[] enums = (Object[])m.invoke(null);
for (Object o : enums) {
if (str.equals(o.toString())) {
return o;
}
}
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
return value;
}
private static class MethodInfo {
public Method getter;
public Method setter;
public void set(Method m) {
if (isGetter(m)) {
this.getter = m;
} else if (isSetter(m)) {
this.setter = m;
} else {
throw new IllegalStateException("Invalid method: " + m.getName());
}
}
private boolean isGetter(Method m) {
Class rt = m.getReturnType();
if (rt == null || rt == Void.TYPE) {
return false;
}
Class[] params = m.getParameterTypes();
return params == null || params.length == 0;
}
private boolean isSetter(Method m) {
Class[] params = m.getParameterTypes();
return params != null || params.length == 1;
}
}
}
|
src/main/java/jp/co/flect/soap/TypedObjectConverter.java
|
package jp.co.flect.soap;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import jp.co.flect.soap.annotation.SoapField;
import jp.co.flect.xmlschema.ComplexType;
import jp.co.flect.xmlschema.TypeDef;
import jp.co.flect.xmlschema.ElementDef;
import jp.co.flect.xmlschema.SimpleType;
import jp.co.flect.xmlschema.ComplexType;
import jp.co.flect.util.ExtendedMap;
public class TypedObjectConverter {
private ComplexType type;
private Class clazz;
private Map<String, Field> fieldMap = new HashMap<String, Field>();
private Map<String, MethodInfo> methodMap = new HashMap<String, MethodInfo>();
public <T extends TypedObject> TypedObjectConverter(ComplexType type, Class<T> clazz) {
this.type = type;
this.clazz = clazz;
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
String fieldName = f.getName();
SoapField api = f.getAnnotation(SoapField.class);
if (api != null) {
String apiName = api.value();
if (apiName == null || apiName.length() == 0) {
apiName = fieldName;
}
f.setAccessible(true);
this.fieldMap.put(apiName, f);
}
}
Method[] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
String fieldName = m.getName();
SoapField api = m.getAnnotation(SoapField.class);
if (api != null) {
String apiName = api.value();
if (apiName == null || apiName.length() == 0) {
apiName = fieldName;
}
MethodInfo info = this.methodMap.get(apiName);
if (info == null) {
info = new MethodInfo();
this.methodMap.put(apiName, info);
}
info.set(m);
m.setAccessible(true);
}
}
}
public String getTargetName() { return this.type.getName();}
public ComplexType getTargetType() { return this.type;}
public Class getTargetClass() { return this.clazz;}
public ExtendedMap toMap(TypedObject obj) {
if (obj.getClass() != this.clazz) {
throw new IllegalArgumentException(obj.getClass().getName());
}
ExtendedMap map = new ExtendedMap();
for (Map.Entry<String, Field> entry : this.fieldMap.entrySet()) {
String name = entry.getKey();
Field f = entry.getValue();
ElementDef el = type.getModel(type.getNamespace(), name);
if (el == null) {
throw new IllegalArgumentException("Unknown fieldName: " + getTargetName() + "." + name);
}
try {
Object value = f.get(obj);
if (value != null) {
putValue(map, name, value, el);
}
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
for (Map.Entry<String, MethodInfo> entry : this.methodMap.entrySet()) {
String name = entry.getKey();
MethodInfo info = entry.getValue();
if (info.getter == null) {
continue;
}
Method m = info.getter;
ElementDef el = type.getModel(type.getNamespace(), name);
if (el == null) {
throw new IllegalArgumentException("Unknown fieldName: " + getTargetName() + "." + name);
}
try {
Object value = m.invoke(obj);
if (value != null) {
putValue(map, name, value, el);
}
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
return map;
}
public TypedObject toObject(XMLStreamReader reader) throws XMLStreamException {
try {
TypedObject ret = (TypedObject)this.clazz.newInstance();
boolean hasValue = false;
boolean endValue = false;
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamReader.START_ELEMENT:
hasValue = true;
String nsuri = reader.getNamespaceURI();
String name = reader.getLocalName();
ElementDef el = type.getModel(nsuri, name);
if (el == null) {
throw new IllegalStateException("Unknown element: " + nsuri + ", " + name);
}
TypeDef elType = el.getType();
if (elType.isSimpleType()) {
Object value = parseSimple((SimpleType)elType, reader);
if (value != null) {
setValue(ret, name, value);
}
} else {
throw new IllegalStateException("Complex type is not implemented.: " + nsuri + ", " + name);
}
break;
case XMLStreamReader.CHARACTERS:
case XMLStreamReader.CDATA:
if (!reader.isWhiteSpace()) {
throw new IllegalStateException();
}
break;
case XMLStreamReader.END_ELEMENT:
endValue = true;
break;
case XMLStreamReader.START_DOCUMENT:
case XMLStreamReader.END_DOCUMENT:
case XMLStreamReader.ATTRIBUTE:
case XMLStreamReader.NAMESPACE:
case XMLStreamReader.SPACE:
case XMLStreamReader.COMMENT:
case XMLStreamReader.PROCESSING_INSTRUCTION:
case XMLStreamReader.ENTITY_REFERENCE:
case XMLStreamReader.DTD:
throw new IllegalStateException();
}
if (endValue) {
break;
}
}
return hasValue ? ret : null;
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
private Object parseSimple(SimpleType type, XMLStreamReader reader) throws XMLStreamException {
StringBuilder buf = new StringBuilder();
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamReader.CHARACTERS:
case XMLStreamReader.CDATA:
buf.append(reader.getText());
break;
case XMLStreamReader.END_ELEMENT:
return buf.length() > 0 ? type.parse(buf.toString()) : null;
case XMLStreamReader.START_DOCUMENT:
case XMLStreamReader.END_DOCUMENT:
case XMLStreamReader.START_ELEMENT:
case XMLStreamReader.ATTRIBUTE:
case XMLStreamReader.NAMESPACE:
case XMLStreamReader.SPACE:
case XMLStreamReader.COMMENT:
case XMLStreamReader.PROCESSING_INSTRUCTION:
case XMLStreamReader.ENTITY_REFERENCE:
case XMLStreamReader.DTD:
throw new IllegalStateException();
}
}
throw new IllegalStateException();
}
private void putValue(ExtendedMap map, String name, Object value, ElementDef el) {
//ToDo complexType
SimpleType type = (SimpleType)el.getType();
map.put(name, type.format(value));
}
private void setValue(TypedObject obj, String name, Object value) {
try {
Field f = fieldMap.get(name);
if (f != null) {
value = convertType(f.getType(), value);
f.set(obj, value);
return;
}
MethodInfo info = methodMap.get(name);
if (info != null && info.setter != null) {
Method m = info.setter;
value = convertType(m.getParameterTypes()[0], value);
m.invoke(obj, value);
}
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
private Object convertType(Class c, Object value) {
if (c == String.class) return value.toString();
if (value instanceof Number) {
Number n = (Number)value;
if (c == Integer.class) return n.intValue();
if (c == Long.class) return n.longValue();
if (c == Double.class) return n.doubleValue();
if (c == Float.class) return n.floatValue();
if (c == Byte.class) return n.byteValue();
if (c == Short.class) return n.shortValue();
if (c == BigDecimal.class) return new BigDecimal(n.toString());
if (c == BigInteger.class) return new BigInteger(n.toString());
}
return value;
}
private static class MethodInfo {
public Method getter;
public Method setter;
public void set(Method m) {
if (isGetter(m)) {
this.getter = m;
} else if (isSetter(m)) {
this.setter = m;
} else {
throw new IllegalStateException("Invalid method: " + m.getName());
}
}
private boolean isGetter(Method m) {
Class rt = m.getReturnType();
if (rt == null || rt == Void.TYPE) {
return false;
}
Class[] params = m.getParameterTypes();
return params == null || params.length == 0;
}
private boolean isSetter(Method m) {
Class[] params = m.getParameterTypes();
return params != null || params.length == 1;
}
}
}
|
Support enum in TypedObjectConverter
|
src/main/java/jp/co/flect/soap/TypedObjectConverter.java
|
Support enum in TypedObjectConverter
|
|
Java
|
mit
|
3893c0a85eb4182536ada8f31832a5433f89668d
| 0
|
CS2103JAN2017-W14-B4/main,CS2103JAN2017-W14-B4/main
|
package seedu.ezdo.logic.commands;
import java.util.ArrayList;
import seedu.ezdo.commons.core.Messages;
import seedu.ezdo.commons.core.UnmodifiableObservableList;
import seedu.ezdo.logic.commands.exceptions.CommandException;
import seedu.ezdo.model.todo.ReadOnlyTask;
import seedu.ezdo.model.todo.Task;
import seedu.ezdo.model.todo.UniqueTaskList.TaskNotFoundException;
/**
* Marks a task as identified using its last displayed index from ezDo as done
*/
public class DoneCommand extends Command {
public static final String COMMAND_WORD = "done";
public static final String SHORT_COMMAND_WORD = "d";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Marks the task identified by the index number used in the last task listing as done\n"
+ "Parameters: INDEX (must be a positive integer)\n"
+ "Example: " + COMMAND_WORD + " 1";
public static final String MESSAGE_DONE_TASK_SUCCESS = "Done task: %1$s";
public static final String MESSAGE_DONE_LISTED = "Done tasks listed";
private final ArrayList<Integer> targetIndexes;
private final ArrayList<Task> tasksToDone;
private final boolean requestToViewDoneOnly;
public DoneCommand(ArrayList<Integer> indexes) {
this.targetIndexes = new ArrayList<Integer>(indexes);
this.requestToViewDoneOnly = false;
this.tasksToDone = new ArrayList<Task>();
}
public DoneCommand() {
this.targetIndexes = null;
this.requestToViewDoneOnly = true;
this.tasksToDone = null;
}
@Override
public CommandResult execute() throws CommandException {
UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList();
if (requestToViewDoneOnly) {
model.updateFilteredDoneList();
return new CommandResult(MESSAGE_DONE_LISTED);
}
if (lastShownList.size() < targetIndex) {
throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
Task taskToDone = (Task) lastShownList.get(targetIndex - 1);
if (taskToDone.getDone()) {
throw new CommandException(Messages.MESSAGE_WRONG_LIST);
}
try {
model.doneTask(taskToDone);
} catch (TaskNotFoundException tnfe) {
assert false : "The target task cannot be missing";
}
return new CommandResult(String.format(MESSAGE_DONE_TASK_SUCCESS, taskToDone));
}
}
|
src/main/java/seedu/ezdo/logic/commands/DoneCommand.java
|
package seedu.ezdo.logic.commands;
import seedu.ezdo.commons.core.Messages;
import seedu.ezdo.commons.core.UnmodifiableObservableList;
import seedu.ezdo.logic.commands.exceptions.CommandException;
import seedu.ezdo.model.todo.ReadOnlyTask;
import seedu.ezdo.model.todo.Task;
import seedu.ezdo.model.todo.UniqueTaskList.TaskNotFoundException;
/**
* Marks a task as identified using its last displayed index from ezDo as done
*/
public class DoneCommand extends Command {
public static final String COMMAND_WORD = "done";
public static final String SHORT_COMMAND_WORD = "d";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Marks the task identified by the index number used in the last task listing as done\n"
+ "Parameters: INDEX (must be a positive integer)\n"
+ "Example: " + COMMAND_WORD + " 1";
public static final String MESSAGE_DONE_TASK_SUCCESS = "Done task: %1$s";
public static final String MESSAGE_DONE_LISTED = "Done tasks listed";
public final int targetIndex;
public final boolean requestToViewDoneOnly;
public DoneCommand(int targetIndex) {
this.targetIndex = targetIndex;
this.requestToViewDoneOnly = false;
}
public DoneCommand() {
this.targetIndex = 0;
this.requestToViewDoneOnly = true;
}
@Override
public CommandResult execute() throws CommandException {
UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList();
if (requestToViewDoneOnly) {
model.updateFilteredDoneList();
return new CommandResult(MESSAGE_DONE_LISTED);
}
if (lastShownList.size() < targetIndex) {
throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
Task taskToDone = (Task) lastShownList.get(targetIndex - 1);
if (taskToDone.getDone()) {
throw new CommandException(Messages.MESSAGE_WRONG_LIST);
}
try {
model.doneTask(taskToDone);
} catch (TaskNotFoundException tnfe) {
assert false : "The target task cannot be missing";
}
return new CommandResult(String.format(MESSAGE_DONE_TASK_SUCCESS, taskToDone));
}
}
|
Update DoneCommand constructors and fields
|
src/main/java/seedu/ezdo/logic/commands/DoneCommand.java
|
Update DoneCommand constructors and fields
|
|
Java
|
mit
|
d469a06d2ae056faf379a98646542d4290b5b0ac
| 0
|
NikitaKozlov/Pury
|
package com.nikitakozlov.pury.profile;
import org.junit.Test;
import static java.lang.Thread.sleep;
import static org.junit.Assert.*;
public class StopWatchTest {
private static long ONE_HUNDERD_MILLIS = 100L;
@Test
public void getExecTimeInMillis_ReturnsTimeBiggerThenTimeBetweenStartAndStop() throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
sleep(ONE_HUNDERD_MILLIS);
stopWatch.stop();
assertTrue(ONE_HUNDERD_MILLIS * 1000000 <= stopWatch.getExecTime());
}
@Test
public void getStartTimeInMillis_ReturnsTimeBiggerThenCurrentTimeBeforeStart() throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long currentTime = System.nanoTime();
assertTrue(currentTime >= stopWatch.getStartTime());
}
@Test
public void isStopped_ReturnsTrue_AfterStop() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
stopWatch.stop();
assertTrue(stopWatch.isStopped());
}
@Test
public void isStopped_CantStart_AfterStop() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long firstStartTime = stopWatch.getStartTime();
stopWatch.stop();
stopWatch.start();
assertEquals(firstStartTime, stopWatch.getStartTime());
}
@Test
public void isStopped_CantStopTwice() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
stopWatch.stop();
long firstStopTime = stopWatch.getExecTime();
stopWatch.stop();
assertEquals(firstStopTime, stopWatch.getExecTime());
}
}
|
pury/src/test/java/com/nikitakozlov/pury/profile/StopWatchTest.java
|
package com.nikitakozlov.pury.profile;
import org.junit.Test;
import static java.lang.Thread.sleep;
import static org.junit.Assert.*;
public class StopWatchTest {
private static long ONE_HUNDERD_MILLIS = 100L;
@Test
public void getExecTimeInMillis_ReturnsTimeBiggerThenTimeBetweenStartAndStop() throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
sleep(ONE_HUNDERD_MILLIS);
stopWatch.stop();
assertTrue(ONE_HUNDERD_MILLIS <= stopWatch.getExecTime());
}
@Test
public void getStartTimeInMillis_ReturnsTimeBiggerThenCurrentTimeBeforeStart() throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long currentTime = System.nanoTime();
assertTrue(currentTime >= stopWatch.getStartTime());
}
}
|
Added more tests for `StopWatch`
|
pury/src/test/java/com/nikitakozlov/pury/profile/StopWatchTest.java
|
Added more tests for `StopWatch`
|
|
Java
|
mit
|
9048f7c7f71a23c2a9f26ad72dbb4d2b68b847bd
| 0
|
sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor
|
package com.sleekbyte.tailor.common;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
/**
* Represent a config object.
*/
public final class YamlConfiguration {
private static final String[] DEFAULT_INCLUDE = new String[] {"**.swift"};
private static final String[] DEFAULT_EXCLUDE = new String[] {"**.{svn,git,lproj,xcassets,framework,xcodeproj}"};
private Optional<String> fileLocation = Optional.empty();
private Set<String> include = new HashSet<>(Arrays.asList(DEFAULT_INCLUDE));
private Set<String> exclude = new HashSet<>(Arrays.asList(DEFAULT_EXCLUDE));
private Set<String> only = new HashSet<>();
private Set<String> except = new HashSet<>();
private String format = "";
private boolean debug = false;
private String color = "";
private int purge = 0;
private boolean purgeSet = false;
public String getFormat() {
return format;
}
public Optional<String> getFileLocation() {
return fileLocation;
}
public Set<String> getInclude() {
return include;
}
public Set<String> getExclude() {
return exclude;
}
public Set<String> getOnly() {
return only;
}
public Set<String> getExcept() {
return except;
}
public boolean isDebug() {
return debug;
}
public String getColor() {
return color;
}
public int getPurge() {
return purge;
}
public void setFileLocation(String fileLocation) {
this.fileLocation = Optional.ofNullable(fileLocation);
}
public void setInclude(Set<String> include) {
this.include = include;
}
public void setExclude(Set<String> exclude) {
this.exclude = exclude;
}
public void setOnly(Set<String> only) {
this.only = only;
}
public void setExcept(Set<String> except) {
this.except = except;
}
public void setFormat(String format) {
this.format = format;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public void setColor(String color) {
this.color = color;
}
public void setPurge(int purge) {
this.purge = purge;
purgeSet = true;
}
public boolean isPurgeSet() {
return purgeSet;
}
}
|
src/main/java/com/sleekbyte/tailor/common/YamlConfiguration.java
|
package com.sleekbyte.tailor.common;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
/**
* Represent a config object.
*/
public final class YamlConfiguration {
private static final String[] DEFAULT_INCLUDE = new String[] {"**.swift"};
private static final String[] DEFAULT_EXCLUDE = new String[] {"**.{svn,git,lproj,xcassets,framework,xcodeproj}"};
private Optional<String> fileLocation = Optional.empty();
private Set<String> include = new HashSet<>(Arrays.asList(DEFAULT_INCLUDE));
private Set<String> exclude = new HashSet<>(Arrays.asList(DEFAULT_EXCLUDE));
private Set<String> only = new HashSet<>();
private Set<String> except = new HashSet<>();
private String format = "";
private boolean debug = false;
private String color = "";
private int purge = -1;
private boolean purgeSet = false;
public String getFormat() {
return format;
}
public Optional<String> getFileLocation() {
return fileLocation;
}
public Set<String> getInclude() {
return include;
}
public Set<String> getExclude() {
return exclude;
}
public Set<String> getOnly() {
return only;
}
public Set<String> getExcept() {
return except;
}
public boolean isDebug() {
return debug;
}
public String getColor() {
return color;
}
public int getPurge() {
return purge;
}
public void setFileLocation(String fileLocation) {
this.fileLocation = Optional.ofNullable(fileLocation);
}
public void setInclude(Set<String> include) {
this.include = include;
}
public void setExclude(Set<String> exclude) {
this.exclude = exclude;
}
public void setOnly(Set<String> only) {
this.only = only;
}
public void setExcept(Set<String> except) {
this.except = except;
}
public void setFormat(String format) {
this.format = format;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public void setColor(String color) {
this.color = color;
}
public void setPurge(int purge) {
this.purge = purge;
purgeSet = true;
}
public boolean isPurgeSet() {
return purgeSet;
}
}
|
Change purge default to zero
|
src/main/java/com/sleekbyte/tailor/common/YamlConfiguration.java
|
Change purge default to zero
|
|
Java
|
mit
|
8906dd3426fba88b4de08c6cf7710fcfc6d6506a
| 0
|
borysn/tictactoe
|
package tictactoe.game.engine;
public class TicTacToeMove implements Move {
private int x;
private int y;
public TicTacToeMove(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
int result = 1;
result = 31 * result + this.x;
result = 31 * result + this.y;
return 31 * result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o != null && o instanceof TicTacToeMove) {
TicTacToeMove move = (TicTacToeMove) o;
return this.x == move.getX() && this.y == move.getY();
}
return false;
}
@Override
public int getX() {
return this.x;
}
@Override
public int getY() {
return this.y;
}
}
|
src/main/java/tictactoe/game/engine/TicTacToeMove.java
|
package tictactoe.game.engine;
public class TicTacToeMove implements Move {
private int x;
private int y;
public TicTacToeMove(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return this.x - this.y;
}
@Override
public boolean equals(Object o) {
if (o instanceof TicTacToeMove) {
TicTacToeMove move = (TicTacToeMove) o;
return this.x == move.getX() && this.y == move.getY();
}
return false;
}
@Override
public int getX() {
return this.x;
}
@Override
public int getY() {
return this.y;
}
}
|
improved equals and hashCode impl
|
src/main/java/tictactoe/game/engine/TicTacToeMove.java
|
improved equals and hashCode impl
|
|
Java
|
mit
|
ba2994378b245ddf54fd8ad7471834882ae63bd0
| 0
|
jameskbride/grocery-reminder
|
package com.groceryreminder.injection;
import java.util.ArrayList;
import java.util.List;
import dagger.ObjectGraph;
public class TestReminderApplication extends ReminderApplication {
private TestReminderModule testReminderModule;
private TestAndroidModule testAndroidModule;
@Override
public void onCreate() {
List<Object> modules = getModules();
graph = ObjectGraph.create(modules.toArray());
}
@Override
protected List<Object> getModules() {
List<Object> modules = new ArrayList<Object>();
modules.add(getTestReminderModule());
modules.add(getTestAndroidModule());
return modules;
}
public TestReminderModule getTestReminderModule() {
if (testReminderModule == null) {
this.testReminderModule = new TestReminderModule();
}
return testReminderModule;
}
public TestAndroidModule getTestAndroidModule() {
if (testAndroidModule == null) {
testAndroidModule = new TestAndroidModule();
}
return testAndroidModule;
}
}
|
app/src/test/java/com/groceryreminder/injection/TestReminderApplication.java
|
package com.groceryreminder.injection;
import java.util.ArrayList;
import java.util.List;
import dagger.ObjectGraph;
public class TestReminderApplication extends ReminderApplication {
private TestReminderModule testReminderModule;
private TestAndroidModule testAndroidModule;
private AndroidModule androidModule;
@Override
public void onCreate() {
List<Object> modules = getModules();
graph = ObjectGraph.create(modules.toArray());
}
public TestReminderApplication() {
this.testReminderModule = new TestReminderModule();
}
@Override
protected List<Object> getModules() {
List<Object> modules = new ArrayList<Object>();
modules.add(getTestReminderModule());
modules.add(TestAndroidModule.class);
return modules;
}
public TestReminderModule getTestReminderModule() {
if (testReminderModule == null) {
this.testReminderModule = new TestReminderModule();
}
return testReminderModule;
}
public TestAndroidModule getTestAndroidModule() {
if (testAndroidModule == null) {
testAndroidModule = new TestAndroidModule();
}
return testAndroidModule;
}
}
|
Refactoring.
|
app/src/test/java/com/groceryreminder/injection/TestReminderApplication.java
|
Refactoring.
|
|
Java
|
agpl-3.0
|
681b74b28d75a5f902815c98f52f81c87c5aa29d
| 0
|
aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms
|
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2002-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 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 Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.TreeMap;
import org.apache.commons.codec.binary.Base64;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ValidationException;
import org.opennms.core.utils.ConfigFileConstants;
import org.opennms.core.utils.IPLike;
import org.opennms.core.utils.InetAddressComparator;
import org.opennms.core.utils.InetAddressUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.opennms.core.xml.CastorUtils;
import org.opennms.netmgt.config.wmi.Definition;
import org.opennms.netmgt.config.wmi.Range;
import org.opennms.netmgt.config.wmi.WmiAgentConfig;
import org.opennms.netmgt.config.wmi.WmiConfig;
import org.springframework.core.io.FileSystemResource;
/**
* This class is the main repository for WMI configuration information used by
* the capabilities daemon. When this class is loaded it reads the WMI
* configuration into memory, and uses the configuration to find the
* {@link org.opennms.protocols.wmi.WmiAgentConfig WmiAgentConfig} objects for specific
* addresses. If an address cannot be located in the configuration then a
* default peer instance is returned to the caller.
*
* <strong>Note: </strong>Users of this class should make sure the
* <em>init()</em> is called before calling any other method to ensure the
* config is loaded before accessing other convenience methods.
*
* @author <a href="mailto:david@opennms.org">David Hustace </a>
* @author <a href="mailto:weave@oculan.com">Weave </a>
* @author <a href="mailto:gturner@newedgenetworks.com">Gerald Turner </a>
* @author <a href="mailto:matt.raykowski@gmail.com">Matt Raykowski</a>
*/
public class WmiPeerFactory {
private static final Logger LOG = LoggerFactory.getLogger(WmiPeerFactory.class);
/**
* The singleton instance of this factory
*/
private static WmiPeerFactory m_singleton = null;
/**
* The config class loaded from the config file
*/
private static WmiConfig m_config;
/**
* This member is set to true if the configuration file has been loaded.
*/
private static boolean m_loaded = false;
/**
* Private constructor
*
* @exception java.io.IOException
* Thrown if the specified config file cannot be read
* @exception org.exolab.castor.xml.MarshalException
* Thrown if the file does not conform to the schema.
* @exception org.exolab.castor.xml.ValidationException
* Thrown if the contents do not match the required schema.
*
* @param configFile the path to the config file to load in.
*/
private WmiPeerFactory(String configFile) throws IOException, MarshalException, ValidationException {
m_config = CastorUtils.unmarshal(WmiConfig.class, new FileSystemResource(configFile));
}
/**
* <p>Constructor for WmiPeerFactory.</p>
*
* @param stream a {@link java.io.InputStream} object.
* @throws org.exolab.castor.xml.MarshalException if any.
* @throws org.exolab.castor.xml.ValidationException if any.
*/
public WmiPeerFactory(InputStream stream) throws MarshalException, ValidationException {
m_config = CastorUtils.unmarshal(WmiConfig.class, stream);
}
/**
* Load the config from the default config file and create the singleton
* instance of this factory.
*
* @exception java.io.IOException
* Thrown if the specified config file cannot be read
* @exception org.exolab.castor.xml.MarshalException
* Thrown if the file does not conform to the schema.
* @exception org.exolab.castor.xml.ValidationException
* Thrown if the contents do not match the required schema.
* @throws java.io.IOException if any.
* @throws org.exolab.castor.xml.MarshalException if any.
* @throws org.exolab.castor.xml.ValidationException if any.
*/
public static synchronized void init() throws IOException, MarshalException, ValidationException {
if (m_loaded) {
// init already called - return
// to reload, reload() will need to be called
return;
}
File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.WMI_CONFIG_FILE_NAME);
LOG.debug("init: config file path: {}", cfgFile.getPath());
m_singleton = new WmiPeerFactory(cfgFile.getPath());
m_loaded = true;
}
/**
* Reload the config from the default config file
*
* @exception java.io.IOException
* Thrown if the specified config file cannot be read/loaded
* @exception org.exolab.castor.xml.MarshalException
* Thrown if the file does not conform to the schema.
* @exception org.exolab.castor.xml.ValidationException
* Thrown if the contents do not match the required schema.
* @throws java.io.IOException if any.
* @throws org.exolab.castor.xml.MarshalException if any.
* @throws org.exolab.castor.xml.ValidationException if any.
*/
public static synchronized void reload() throws IOException, MarshalException, ValidationException {
m_singleton = null;
m_loaded = false;
init();
}
/**
* Package-private access. Should only be used for unit testing.
*/
WmiConfig getConfig() {
return m_config;
}
/**
* Saves the current settings to disk
*
* @throws java.lang.Exception if saving settings to disk fails.
*/
public static synchronized void saveCurrent() throws Exception {
optimize();
// Marshal to a string first, then write the string to the file. This
// way the original config
// isn't lost if the XML from the marshal is hosed.
StringWriter stringWriter = new StringWriter();
Marshaller.marshal(m_config, stringWriter);
if (stringWriter.toString() != null) {
Writer fileWriter = new OutputStreamWriter(new FileOutputStream(ConfigFileConstants.getFile(ConfigFileConstants.WMI_CONFIG_FILE_NAME)), "UTF-8");
fileWriter.write(stringWriter.toString());
fileWriter.flush();
fileWriter.close();
}
reload();
}
/**
* Combine specific and range elements so that WMIPeerFactory has to spend
* less time iterating all these elements.
* TODO This really should be pulled up into PeerFactory somehow, but I'm not sure how (given that "Definition" is different for both
* SNMP and WMI. Maybe some sort of visitor methodology would work. The basic logic should be fine as it's all IP address manipulation
*
* @throws UnknownHostException
*/
static void optimize() throws UnknownHostException {
// First pass: Remove empty definition elements
for (Iterator<Definition> definitionsIterator = m_config.getDefinitionCollection().iterator();
definitionsIterator.hasNext();) {
Definition definition = definitionsIterator.next();
if (definition.getSpecificCount() == 0 && definition.getRangeCount() == 0) {
LOG.debug("optimize: Removing empty definition element");
definitionsIterator.remove();
}
}
// Second pass: Replace single IP range elements with specific elements
for (Definition definition : m_config.getDefinitionCollection()) {
synchronized(definition) {
for (Iterator<Range> rangesIterator = definition.getRangeCollection().iterator(); rangesIterator.hasNext();) {
Range range = rangesIterator.next();
if (range.getBegin().equals(range.getEnd())) {
definition.addSpecific(range.getBegin());
rangesIterator.remove();
}
}
}
}
// Third pass: Sort specific and range elements for improved XML
// readability and then combine them into fewer elements where possible
for (Iterator<Definition> defIterator = m_config.getDefinitionCollection().iterator(); defIterator.hasNext(); ) {
Definition definition = defIterator.next();
// Sort specifics
final TreeMap<InetAddress,String> specificsMap = new TreeMap<InetAddress,String>(new InetAddressComparator());
for (String specific : definition.getSpecificCollection()) {
specificsMap.put(InetAddressUtils.getInetAddress(specific), specific.trim());
}
// Sort ranges
final TreeMap<InetAddress,Range> rangesMap = new TreeMap<InetAddress,Range>(new InetAddressComparator());
for (Range range : definition.getRangeCollection()) {
rangesMap.put(InetAddressUtils.getInetAddress(range.getBegin()), range);
}
// Combine consecutive specifics into ranges
InetAddress priorSpecific = null;
Range addedRange = null;
for (final InetAddress specific : specificsMap.keySet()) {
if (priorSpecific == null) {
priorSpecific = specific;
continue;
}
if (BigInteger.ONE.equals(InetAddressUtils.difference(specific, priorSpecific)) &&
InetAddressUtils.inSameScope(specific, priorSpecific)) {
if (addedRange == null) {
addedRange = new Range();
addedRange.setBegin(InetAddressUtils.toIpAddrString(priorSpecific));
rangesMap.put(priorSpecific, addedRange);
specificsMap.remove(priorSpecific);
}
addedRange.setEnd(InetAddressUtils.toIpAddrString(specific));
specificsMap.remove(specific);
}
else {
addedRange = null;
}
priorSpecific = specific;
}
// Move specifics to ranges
for (final InetAddress specific : new ArrayList<InetAddress>(specificsMap.keySet())) {
for (final InetAddress begin : new ArrayList<InetAddress>(rangesMap.keySet())) {
if (!InetAddressUtils.inSameScope(begin, specific)) {
continue;
}
if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE).compareTo(InetAddressUtils.toInteger(specific)) > 0) {
continue;
}
Range range = rangesMap.get(begin);
final InetAddress end = InetAddressUtils.getInetAddress(range.getEnd());
if (InetAddressUtils.toInteger(end).add(BigInteger.ONE).compareTo(InetAddressUtils.toInteger(specific)) < 0) {
continue;
}
if (
InetAddressUtils.toInteger(specific).compareTo(InetAddressUtils.toInteger(begin)) >= 0 &&
InetAddressUtils.toInteger(specific).compareTo(InetAddressUtils.toInteger(end)) <= 0
) {
specificsMap.remove(specific);
break;
}
if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE).equals(InetAddressUtils.toInteger(specific))) {
rangesMap.remove(begin);
rangesMap.put(specific, range);
range.setBegin(InetAddressUtils.toIpAddrString(specific));
specificsMap.remove(specific);
break;
}
if (InetAddressUtils.toInteger(end).add(BigInteger.ONE).equals(InetAddressUtils.toInteger(specific))) {
range.setEnd(InetAddressUtils.toIpAddrString(specific));
specificsMap.remove(specific);
break;
}
}
}
// Combine consecutive ranges
Range priorRange = null;
InetAddress priorBegin = null;
InetAddress priorEnd = null;
for (final Iterator<InetAddress> rangesIterator = rangesMap.keySet().iterator(); rangesIterator.hasNext();) {
final InetAddress beginAddress = rangesIterator.next();
final Range range = rangesMap.get(beginAddress);
final InetAddress endAddress = InetAddressUtils.getInetAddress(range.getEnd());
if (priorRange != null) {
if (InetAddressUtils.inSameScope(beginAddress, priorEnd) && InetAddressUtils.difference(beginAddress, priorEnd).compareTo(BigInteger.ONE) <= 0) {
priorBegin = new InetAddressComparator().compare(priorBegin, beginAddress) < 0 ? priorBegin : beginAddress;
priorRange.setBegin(InetAddressUtils.toIpAddrString(priorBegin));
priorEnd = new InetAddressComparator().compare(priorEnd, endAddress) > 0 ? priorEnd : endAddress;
priorRange.setEnd(InetAddressUtils.toIpAddrString(priorEnd));
rangesIterator.remove();
continue;
}
}
priorRange = range;
priorBegin = beginAddress;
priorEnd = endAddress;
}
// Update changes made to sorted maps
definition.setSpecific(specificsMap.values().toArray(new String[0]));
definition.setRange(rangesMap.values().toArray(new Range[0]));
}
}
/**
* Return the singleton instance of this factory.
*
* @return The current factory instance.
* @throws java.lang.IllegalStateException
* Thrown if the factory has not yet been initialized.
*/
public static synchronized WmiPeerFactory getInstance() {
if (!m_loaded)
throw new IllegalStateException("The WmiPeerFactory has not been initialized");
return m_singleton;
}
/**
* <p>setInstance</p>
*
* @param singleton a {@link org.opennms.netmgt.config.WmiPeerFactory} object.
*/
public static synchronized void setInstance(WmiPeerFactory singleton) {
m_singleton = singleton;
m_loaded = true;
}
/**
* <p>getAgentConfig</p>
*
* @param agentInetAddress a {@link java.net.InetAddress} object.
* @return a {@link org.opennms.protocols.wmi.WmiAgentConfig} object.
*/
public synchronized WmiAgentConfig getAgentConfig(InetAddress agentInetAddress) {
if (m_config == null) {
return new WmiAgentConfig(agentInetAddress);
}
WmiAgentConfig agentConfig = new WmiAgentConfig(agentInetAddress);
//Now set the defaults from the m_config
setWmiAgentConfig(agentConfig, new Definition());
// Attempt to locate the node
//
Enumeration<Definition> edef = m_config.enumerateDefinition();
DEFLOOP: while (edef.hasMoreElements()) {
Definition def = edef.nextElement();
// check the specifics first
for (String saddr : def.getSpecificCollection()) {
InetAddress addr = InetAddressUtils.addr(saddr);
if (addr.equals(agentConfig.getAddress())) {
setWmiAgentConfig(agentConfig, def);
break DEFLOOP;
}
}
// check the ranges
for (Range rng : def.getRangeCollection()) {
if (InetAddressUtils.isInetAddressInRange(InetAddressUtils.str(agentConfig.getAddress()), rng.getBegin(), rng.getEnd())) {
setWmiAgentConfig(agentConfig, def );
break DEFLOOP;
}
}
// check the matching IP expressions
//
for (String ipMatch : def.getIpMatchCollection()) {
if (IPLike.matches(InetAddressUtils.str(agentInetAddress), ipMatch)) {
setWmiAgentConfig(agentConfig, def);
break DEFLOOP;
}
}
} // end DEFLOOP
if (agentConfig == null) {
Definition def = new Definition();
setWmiAgentConfig(agentConfig, def);
}
return agentConfig;
}
private void setWmiAgentConfig(WmiAgentConfig agentConfig, Definition def) {
setCommonAttributes(agentConfig, def);
agentConfig.setPassword(determinePassword(def));
}
/**
* This is a helper method to set all the common attributes in the agentConfig.
*
* @param agentConfig
* @param def
*/
private void setCommonAttributes(WmiAgentConfig agentConfig, Definition def) {
agentConfig.setRetries(determineRetries(def));
agentConfig.setTimeout((int)determineTimeout(def));
agentConfig.setUsername(determineUsername(def));
agentConfig.setPassword(determinePassword(def));
agentConfig.setDomain(determineDomain(def));
}
/**
* Helper method to search the wmi-config for the appropriate username
* @param def
* @return a string containing the username. will return the default if none is set.
*/
private String determineUsername(Definition def) {
return (def.getUsername() == null ? (m_config.getUsername() == null ? WmiAgentConfig.DEFAULT_USERNAME :m_config.getUsername()) : def.getUsername());
}
/**
* Helper method to search the wmi-config for the appropriate domain/workgroup.
* @param def
* @return a string containing the domain. will return the default if none is set.
*/
private String determineDomain(Definition def) {
return (def.getDomain() == null ? (m_config.getDomain() == null ? WmiAgentConfig.DEFAULT_DOMAIN :m_config.getDomain()) : def.getDomain());
}
/**
* Helper method to search the wmi-config for the appropriate password
* @param def
* @return a string containing the password. will return the default if none is set.
*/
private String determinePassword(Definition def) {
String literalPass = (def.getPassword() == null ? (m_config.getPassword() == null ? WmiAgentConfig.DEFAULT_PASSWORD :m_config.getPassword()) : def.getPassword());
if (literalPass.endsWith("===")) {
return new String(Base64.decodeBase64(literalPass));
}
return literalPass;
}
/**
* Helper method to search the wmi-config
* @param def
* @return a long containing the timeout, WmiAgentConfig.DEFAULT_TIMEOUT if not specified.
*/
private long determineTimeout(Definition def) {
long timeout = WmiAgentConfig.DEFAULT_TIMEOUT;
return (long)(def.getTimeout() == 0 ? (m_config.getTimeout() == 0 ? timeout : m_config.getTimeout()) : def.getTimeout());
}
private int determineRetries(Definition def) {
int retries = WmiAgentConfig.DEFAULT_RETRIES;
return (def.getRetry() == 0 ? (m_config.getRetry() == 0 ? retries : m_config.getRetry()) : def.getRetry());
}
/**
* <p>getWmiConfig</p>
*
* @return a {@link org.opennms.netmgt.config.wmi.WmiConfig} object.
*/
public static WmiConfig getWmiConfig() {
return m_config;
}
/**
* <p>setWmiConfig</p>
*
* @param m_config a {@link org.opennms.netmgt.config.wmi.WmiConfig} object.
*/
public static synchronized void setWmiConfig(WmiConfig m_config) {
WmiPeerFactory.m_config = m_config;
}
}
|
opennms-config/src/main/java/org/opennms/netmgt/config/WmiPeerFactory.java
|
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2002-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 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 Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.TreeMap;
import org.apache.commons.codec.binary.Base64;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ValidationException;
import org.opennms.core.utils.ConfigFileConstants;
import org.opennms.core.utils.IPLike;
import org.opennms.core.utils.InetAddressComparator;
import org.opennms.core.utils.InetAddressUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.opennms.core.xml.CastorUtils;
import org.opennms.netmgt.config.wmi.Definition;
import org.opennms.netmgt.config.wmi.Range;
import org.opennms.netmgt.config.wmi.WmiAgentConfig;
import org.opennms.netmgt.config.wmi.WmiConfig;
import org.springframework.core.io.FileSystemResource;
/**
* This class is the main repository for WMI configuration information used by
* the capabilities daemon. When this class is loaded it reads the WMI
* configuration into memory, and uses the configuration to find the
* {@link org.opennms.protocols.wmi.WmiAgentConfig WmiAgentConfig} objects for specific
* addresses. If an address cannot be located in the configuration then a
* default peer instance is returned to the caller.
*
* <strong>Note: </strong>Users of this class should make sure the
* <em>init()</em> is called before calling any other method to ensure the
* config is loaded before accessing other convenience methods.
*
* @author <a href="mailto:david@opennms.org">David Hustace </a>
* @author <a href="mailto:weave@oculan.com">Weave </a>
* @author <a href="mailto:gturner@newedgenetworks.com">Gerald Turner </a>
* @author <a href="mailto:matt.raykowski@gmail.com">Matt Raykowski</a>
*/
public class WmiPeerFactory {
private static final Logger LOG = LoggerFactory.getLogger(WmiPeerFactory.class);
/**
* The singleton instance of this factory
*/
private static WmiPeerFactory m_singleton = null;
/**
* The config class loaded from the config file
*/
private static WmiConfig m_config;
/**
* This member is set to true if the configuration file has been loaded.
*/
private static boolean m_loaded = false;
/**
* Private constructor
*
* @exception java.io.IOException
* Thrown if the specified config file cannot be read
* @exception org.exolab.castor.xml.MarshalException
* Thrown if the file does not conform to the schema.
* @exception org.exolab.castor.xml.ValidationException
* Thrown if the contents do not match the required schema.
*
* @param configFile the path to the config file to load in.
*/
private WmiPeerFactory(String configFile) throws IOException, MarshalException, ValidationException {
m_config = CastorUtils.unmarshal(WmiConfig.class, new FileSystemResource(configFile));
}
/**
* <p>Constructor for WmiPeerFactory.</p>
*
* @param stream a {@link java.io.InputStream} object.
* @throws org.exolab.castor.xml.MarshalException if any.
* @throws org.exolab.castor.xml.ValidationException if any.
*/
public WmiPeerFactory(InputStream stream) throws MarshalException, ValidationException {
m_config = CastorUtils.unmarshal(WmiConfig.class, stream);
}
/**
* Load the config from the default config file and create the singleton
* instance of this factory.
*
* @exception java.io.IOException
* Thrown if the specified config file cannot be read
* @exception org.exolab.castor.xml.MarshalException
* Thrown if the file does not conform to the schema.
* @exception org.exolab.castor.xml.ValidationException
* Thrown if the contents do not match the required schema.
* @throws java.io.IOException if any.
* @throws org.exolab.castor.xml.MarshalException if any.
* @throws org.exolab.castor.xml.ValidationException if any.
*/
public static synchronized void init() throws IOException, MarshalException, ValidationException {
if (m_loaded) {
// init already called - return
// to reload, reload() will need to be called
return;
}
File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.WMI_CONFIG_FILE_NAME);
LOG.debug("init: config file path: {}", cfgFile.getPath());
m_singleton = new WmiPeerFactory(cfgFile.getPath());
m_loaded = true;
}
/**
* Reload the config from the default config file
*
* @exception java.io.IOException
* Thrown if the specified config file cannot be read/loaded
* @exception org.exolab.castor.xml.MarshalException
* Thrown if the file does not conform to the schema.
* @exception org.exolab.castor.xml.ValidationException
* Thrown if the contents do not match the required schema.
* @throws java.io.IOException if any.
* @throws org.exolab.castor.xml.MarshalException if any.
* @throws org.exolab.castor.xml.ValidationException if any.
*/
public static synchronized void reload() throws IOException, MarshalException, ValidationException {
m_singleton = null;
m_loaded = false;
init();
}
/**
* Package-private access. Should only be used for unit testing.
*/
WmiConfig getConfig() {
return m_config;
}
/**
* Saves the current settings to disk
*
* @throws java.lang.Exception if saving settings to disk fails.
*/
public static synchronized void saveCurrent() throws Exception {
optimize();
// Marshal to a string first, then write the string to the file. This
// way the original config
// isn't lost if the XML from the marshal is hosed.
StringWriter stringWriter = new StringWriter();
Marshaller.marshal(m_config, stringWriter);
if (stringWriter.toString() != null) {
Writer fileWriter = new OutputStreamWriter(new FileOutputStream(ConfigFileConstants.getFile(ConfigFileConstants.WMI_CONFIG_FILE_NAME)), "UTF-8");
fileWriter.write(stringWriter.toString());
fileWriter.flush();
fileWriter.close();
}
reload();
}
/**
* Combine specific and range elements so that WMIPeerFactory has to spend
* less time iterating all these elements.
* TODO This really should be pulled up into PeerFactory somehow, but I'm not sure how (given that "Definition" is different for both
* SNMP and WMI. Maybe some sort of visitor methodology would work. The basic logic should be fine as it's all IP address manipulation
*
* @throws UnknownHostException
*/
static void optimize() throws UnknownHostException {
// First pass: Remove empty definition elements
for (Iterator<Definition> definitionsIterator = m_config.getDefinitionCollection().iterator();
definitionsIterator.hasNext();) {
Definition definition = definitionsIterator.next();
if (definition.getSpecificCount() == 0 && definition.getRangeCount() == 0) {
LOG.debug("optimize: Removing empty definition element");
definitionsIterator.remove();
}
}
// Second pass: Replace single IP range elements with specific elements
for (Definition definition : m_config.getDefinitionCollection()) {
synchronized(definition) {
for (Iterator<Range> rangesIterator = definition.getRangeCollection().iterator(); rangesIterator.hasNext();) {
Range range = rangesIterator.next();
if (range.getBegin().equals(range.getEnd())) {
definition.addSpecific(range.getBegin());
rangesIterator.remove();
}
}
}
}
// Third pass: Sort specific and range elements for improved XML
// readability and then combine them into fewer elements where possible
for (Iterator<Definition> defIterator = m_config.getDefinitionCollection().iterator(); defIterator.hasNext(); ) {
Definition definition = defIterator.next();
// Sort specifics
final TreeMap<InetAddress,String> specificsMap = new TreeMap<InetAddress,String>(new InetAddressComparator());
for (String specific : definition.getSpecificCollection()) {
specificsMap.put(InetAddressUtils.getInetAddress(specific), specific.trim());
}
// Sort ranges
final TreeMap<InetAddress,Range> rangesMap = new TreeMap<InetAddress,Range>(new InetAddressComparator());
for (Range range : definition.getRangeCollection()) {
rangesMap.put(InetAddressUtils.getInetAddress(range.getBegin()), range);
}
// Combine consecutive specifics into ranges
InetAddress priorSpecific = null;
Range addedRange = null;
for (final InetAddress specific : specificsMap.keySet()) {
if (priorSpecific == null) {
priorSpecific = specific;
continue;
}
if (BigInteger.ONE.equals(InetAddressUtils.difference(specific, priorSpecific)) &&
InetAddressUtils.inSameScope(specific, priorSpecific)) {
if (addedRange == null) {
addedRange = new Range();
addedRange.setBegin(InetAddressUtils.toIpAddrString(priorSpecific));
rangesMap.put(priorSpecific, addedRange);
specificsMap.remove(priorSpecific);
}
addedRange.setEnd(InetAddressUtils.toIpAddrString(specific));
specificsMap.remove(specific);
}
else {
addedRange = null;
}
priorSpecific = specific;
}
// Move specifics to ranges
for (final InetAddress specific : new ArrayList<InetAddress>(specificsMap.keySet())) {
for (final InetAddress begin : new ArrayList<InetAddress>(rangesMap.keySet())) {
if (!InetAddressUtils.inSameScope(begin, specific)) {
continue;
}
if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE).compareTo(InetAddressUtils.toInteger(specific)) > 0) {
continue;
}
Range range = rangesMap.get(begin);
final InetAddress end = InetAddressUtils.getInetAddress(range.getEnd());
if (InetAddressUtils.toInteger(end).add(BigInteger.ONE).compareTo(InetAddressUtils.toInteger(specific)) < 0) {
continue;
}
if (
InetAddressUtils.toInteger(specific).compareTo(InetAddressUtils.toInteger(begin)) >= 0 &&
InetAddressUtils.toInteger(specific).compareTo(InetAddressUtils.toInteger(end)) <= 0
) {
specificsMap.remove(specific);
break;
}
if (InetAddressUtils.toInteger(begin).subtract(BigInteger.ONE).equals(InetAddressUtils.toInteger(specific))) {
rangesMap.remove(begin);
rangesMap.put(specific, range);
range.setBegin(InetAddressUtils.toIpAddrString(specific));
specificsMap.remove(specific);
break;
}
if (InetAddressUtils.toInteger(end).add(BigInteger.ONE).equals(InetAddressUtils.toInteger(specific))) {
range.setEnd(InetAddressUtils.toIpAddrString(specific));
specificsMap.remove(specific);
break;
}
}
}
// Combine consecutive ranges
Range priorRange = null;
InetAddress priorBegin = null;
InetAddress priorEnd = null;
for (final Iterator<InetAddress> rangesIterator = rangesMap.keySet().iterator(); rangesIterator.hasNext();) {
final InetAddress beginAddress = rangesIterator.next();
final Range range = rangesMap.get(beginAddress);
final InetAddress endAddress = InetAddressUtils.getInetAddress(range.getEnd());
if (priorRange != null) {
if (InetAddressUtils.inSameScope(beginAddress, priorEnd) && InetAddressUtils.difference(beginAddress, priorEnd).compareTo(BigInteger.ONE) <= 0) {
priorBegin = new InetAddressComparator().compare(priorBegin, beginAddress) < 0 ? priorBegin : beginAddress;
priorRange.setBegin(InetAddressUtils.toIpAddrString(priorBegin));
priorEnd = new InetAddressComparator().compare(priorEnd, endAddress) > 0 ? priorEnd : endAddress;
priorRange.setEnd(InetAddressUtils.toIpAddrString(priorEnd));
rangesIterator.remove();
continue;
}
}
priorRange = range;
priorBegin = beginAddress;
priorEnd = endAddress;
}
// Update changes made to sorted maps
definition.setSpecific(specificsMap.values().toArray(new String[0]));
definition.setRange(rangesMap.values().toArray(new Range[0]));
}
}
/**
* Return the singleton instance of this factory.
*
* @return The current factory instance.
* @throws java.lang.IllegalStateException
* Thrown if the factory has not yet been initialized.
*/
public static synchronized WmiPeerFactory getInstance() {
if (!m_loaded)
throw new IllegalStateException("The WmiPeerFactory has not been initialized");
return m_singleton;
}
/**
* <p>setInstance</p>
*
* @param singleton a {@link org.opennms.netmgt.config.WmiPeerFactory} object.
*/
public static synchronized void setInstance(WmiPeerFactory singleton) {
m_singleton = singleton;
m_loaded = true;
}
/**
* <p>getAgentConfig</p>
*
* @param agentInetAddress a {@link java.net.InetAddress} object.
* @return a {@link org.opennms.protocols.wmi.WmiAgentConfig} object.
*/
public synchronized WmiAgentConfig getAgentConfig(InetAddress agentInetAddress) {
if (m_config == null) {
return new WmiAgentConfig(agentInetAddress);
}
WmiAgentConfig agentConfig = new WmiAgentConfig(agentInetAddress);
//Now set the defaults from the m_config
setWmiAgentConfig(agentConfig, new Definition());
// Attempt to locate the node
//
Enumeration<Definition> edef = m_config.enumerateDefinition();
DEFLOOP: while (edef.hasMoreElements()) {
Definition def = edef.nextElement();
// check the specifics first
for (String saddr : def.getSpecificCollection()) {
InetAddress addr = InetAddressUtils.addr(saddr);
if (addr.equals(agentConfig.getAddress())) {
setWmiAgentConfig(agentConfig, def);
break DEFLOOP;
}
}
// check the ranges
for (Range rng : def.getRangeCollection()) {
if (InetAddressUtils.isInetAddressInRange(InetAddressUtils.str(agentConfig.getAddress()), rng.getBegin(), rng.getEnd())) {
setWmiAgentConfig(agentConfig, def );
break DEFLOOP;
}
}
// check the matching IP expressions
//
for (String ipMatch : def.getIpMatchCollection()) {
if (IPLike.matches(InetAddressUtils.str(agentInetAddress), ipMatch)) {
setWmiAgentConfig(agentConfig, def);
break DEFLOOP;
}
}
} // end DEFLOOP
if (agentConfig == null) {
Definition def = new Definition();
setWmiAgentConfig(agentConfig, def);
}
return agentConfig;
}
private void setWmiAgentConfig(WmiAgentConfig agentConfig, Definition def) {
setCommonAttributes(agentConfig, def);
agentConfig.setPassword(determinePassword(def));
}
/**
* This is a helper method to set all the common attributes in the agentConfig.
*
* @param agentConfig
* @param def
*/
private void setCommonAttributes(WmiAgentConfig agentConfig, Definition def) {
agentConfig.setRetries(determineRetries(def));
agentConfig.setTimeout((int)determineTimeout(def));
agentConfig.setUsername(determineUsername(def));
agentConfig.setPassword(determinePassword(def));
agentConfig.setDomain(determineDomain(def));
}
/**
* Helper method to search the wmi-config for the appropriate username
* @param def
* @return a string containing the username. will return the default if none is set.
*/
private String determineUsername(Definition def) {
return (def.getPassword() == null ? (m_config.getUsername() == null ? WmiAgentConfig.DEFAULT_USERNAME :m_config.getUsername()) : def.getUsername());
}
/**
* Helper method to search the wmi-config for the appropriate domain/workgroup.
* @param def
* @return a string containing the domain. will return the default if none is set.
*/
private String determineDomain(Definition def) {
return (def.getDomain() == null ? (m_config.getDomain() == null ? WmiAgentConfig.DEFAULT_DOMAIN :m_config.getDomain()) : def.getDomain());
}
/**
* Helper method to search the wmi-config for the appropriate password
* @param def
* @return a string containing the password. will return the default if none is set.
*/
private String determinePassword(Definition def) {
String literalPass = (def.getPassword() == null ? (m_config.getPassword() == null ? WmiAgentConfig.DEFAULT_PASSWORD :m_config.getPassword()) : def.getPassword());
if (literalPass.endsWith("===")) {
return new String(Base64.decodeBase64(literalPass));
}
return literalPass;
}
/**
* Helper method to search the wmi-config
* @param def
* @return a long containing the timeout, WmiAgentConfig.DEFAULT_TIMEOUT if not specified.
*/
private long determineTimeout(Definition def) {
long timeout = WmiAgentConfig.DEFAULT_TIMEOUT;
return (long)(def.getTimeout() == 0 ? (m_config.getTimeout() == 0 ? timeout : m_config.getTimeout()) : def.getTimeout());
}
private int determineRetries(Definition def) {
int retries = WmiAgentConfig.DEFAULT_RETRIES;
return (def.getRetry() == 0 ? (m_config.getRetry() == 0 ? retries : m_config.getRetry()) : def.getRetry());
}
/**
* <p>getWmiConfig</p>
*
* @return a {@link org.opennms.netmgt.config.wmi.WmiConfig} object.
*/
public static WmiConfig getWmiConfig() {
return m_config;
}
/**
* <p>setWmiConfig</p>
*
* @param m_config a {@link org.opennms.netmgt.config.wmi.WmiConfig} object.
*/
public static synchronized void setWmiConfig(WmiConfig m_config) {
WmiPeerFactory.m_config = m_config;
}
}
|
[bamboo] Automated branch merge (from foundation:470ac164ca80544ec8318b6ec23ff467bad9e41e)
|
opennms-config/src/main/java/org/opennms/netmgt/config/WmiPeerFactory.java
|
[bamboo] Automated branch merge (from foundation:470ac164ca80544ec8318b6ec23ff467bad9e41e)
|
|
Java
|
agpl-3.0
|
b37099a2795295a916c39b4a46d38ce37c89801a
| 0
|
yonh/rubysonar,yonh/rubysonar,yonh/rubysonar
|
package org.yinwang.rubysonar.types;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.yinwang.rubysonar.State;
public class ModuleType extends Type {
@NotNull
public String name;
@Nullable
public String qname;
public ModuleType(@NotNull String name, @Nullable String file, @NotNull State parent) {
this.name = name;
this.file = file; // null for builtin modules
if (parent.path.isEmpty()) {
qname = name;
} else {
qname = parent.path + "/" + name;
}
setTable(new State(parent, State.StateType.MODULE));
table.setPath(qname);
table.setType(this);
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return "ModuleType".hashCode();
}
@Override
public boolean equals(Object other) {
if (other instanceof ModuleType) {
ModuleType co = (ModuleType) other;
if (file != null) {
return file.equals(co.file);
}
}
return this == other;
}
@Override
protected String printType(CyclicTypeRecorder ctr) {
return name;
}
}
|
src/main/java/org/yinwang/rubysonar/types/ModuleType.java
|
package org.yinwang.rubysonar.types;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.yinwang.rubysonar.State;
import org.yinwang.rubysonar._;
public class ModuleType extends Type {
@NotNull
public String name;
@Nullable
public String qname;
public ModuleType(@NotNull String name, @Nullable String file, @NotNull State parent) {
this.name = name;
this.file = file; // null for builtin modules
if (file != null) {
// This will return null iff specified file is not prefixed by
// any path in the module search path -- i.e., the caller asked
// the analyzer to load a file not in the search path.
qname = _.moduleQname(file);
}
if (qname == null) {
qname = name;
}
setTable(new State(parent, State.StateType.MODULE));
table.setPath(qname);
table.setType(this);
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return "ModuleType".hashCode();
}
@Override
public boolean equals(Object other) {
if (other instanceof ModuleType) {
ModuleType co = (ModuleType) other;
if (file != null) {
return file.equals(co.file);
}
}
return this == other;
}
@Override
protected String printType(CyclicTypeRecorder ctr) {
return name;
}
}
|
use ruby's global name space as qname/path
|
src/main/java/org/yinwang/rubysonar/types/ModuleType.java
|
use ruby's global name space as qname/path
|
|
Java
|
lgpl-2.1
|
f57a5fc92a31e7964eef7d13a98ab88d9245d3ca
| 0
|
concord-consortium/otrunk,concord-consortium/otrunk
|
/*
* Copyright (C) 2004 The Concord Consortium, Inc.,
* 10 Concord Crossing, Concord, MA 01742
*
* Web Site: http://www.concord.org
* Email: info@concord.org
*
* 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
*
* END LICENSE */
/*
* Created on Aug 19, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package org.concord.otrunk.view.document;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.html.HTML;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.view.OTFrame;
import org.concord.framework.otrunk.view.OTJComponentView;
import org.concord.framework.otrunk.view.OTView;
import org.concord.framework.otrunk.view.OTViewEntryAware;
import org.concord.framework.otrunk.view.OTViewEntry;
import org.concord.framework.otrunk.view.OTXHTMLView;
import org.concord.otrunk.OTrunkUtil;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author scott
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Generation - Code and Comments
*/
public class OTDocumentView extends AbstractOTDocumentView implements
ChangeListener, HyperlinkListener, OTXHTMLView, OTViewEntryAware {
public static boolean addedCustomLayout = false;
JTabbedPane tabbedPane = null;
protected JComponent previewComponent = null;
protected JEditorPane editorPane = null;
DocumentBuilderFactory xmlDocumentFactory = null;
DocumentBuilder xmlDocumentBuilder = null;
protected JTextArea parsedTextArea = null;
protected OTDocumentViewConfig viewEntry;
protected OTObject otObject;
public final static String XHTML_PREFIX_START =
// "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>\n"
+ "\n" + "<head>\n" + "<title>default</title>\n"
+ "<style type=\"text/css\">\n";
public final static String XHTML_PREFIX_END = "</style>" + "</head>\n"
+ "<body>\n";
public final static String XHTML_SUFFIX = "</body>\n" + "</html>";
protected void setup(OTObject doc) {
// Don't call super.setup() to avoid listening to the ot object
// inneccesarily
pfObject = (OTDocument) doc;
}
public JComponent getComponent(OTObject otObject, boolean editable) {
this.otObject = otObject;
setup(otObject);
initTextAreaModel();
if (tabbedPane != null) {
tabbedPane.removeChangeListener(this);
}
// need to use the PfCDEditorKit
updateFormatedView();
setReloadOnViewEntryChange(true);
if (!editable) {
return previewComponent;
}
// JScrollPane renderedScrollPane = new JScrollPane(previewComponent);
// renderedScrollPane.getViewport().setViewPosition(new Point(0,0));
if (System.getProperty("otrunk.view.debug", "").equals("true")) {
tabbedPane = new JTabbedPane();
// need to add a listener so we can update the view pane
tabbedPane.add("View", previewComponent);
textArea = new JTextArea(textAreaModel);
JScrollPane scrollPane = new JScrollPane(textArea);
tabbedPane.add("Edit", scrollPane);
parsedTextArea.setEnabled(false);
scrollPane = new JScrollPane(parsedTextArea);
tabbedPane.add("Parsed", scrollPane);
tabbedPane.addChangeListener(this);
return tabbedPane;
} else {
return previewComponent;
}
}
public String updateFormatedView() {
if (pfObject == null)
return null;
// System.out.println(this+" updateFormatedView");
String markupLanguage = pfObject.getMarkupLanguage();
if (markupLanguage == null) {
markupLanguage = System.getProperty("org.concord.portfolio.markup",
null);
}
String bodyText = pfObject.getDocumentText();
bodyText = substituteIncludables(bodyText);
// default to html viewer for now
// FIXME the handling of the plain markup is to test the new view entry
// code
// it isn't quite valid because plain text might have html chars in it
// so it will get parsed incorrectly.
if (markupLanguage == null
|| markupLanguage.equals(OTDocument.MARKUP_PFHTML)
|| markupLanguage.equals(OTDocument.MARKUP_PLAIN)) {
if (editorPane == null) {
editorPane = new JEditorPane();
OTHTMLFactory kitViewFactory = new OTHTMLFactory(this);
OTDocumentEditorKit editorKit = new OTDocumentEditorKit(
kitViewFactory);
editorPane.setEditorKit(editorKit);
editorPane.setEditable(false);
editorPane.addHyperlinkListener(this);
}
bodyText = htmlizeText(bodyText);
if (viewEntry instanceof OTDocumentViewConfig) {
String css = "";
if (viewEntry.getCss() != null && viewEntry.getCss().length() > 0){
css = css + viewEntry.getCss();
}
if (viewEntry.getCssBlocks() != null && viewEntry.getCssBlocks().getVector().size() > 0){
Vector cssBlocks = viewEntry.getCssBlocks().getVector();
for (int i = 0; i < cssBlocks.size(); i++) {
OTCssText cssText = (OTCssText) cssBlocks.get(i);
css = css + " " + cssText.getCssText();
}
}
String XHTML_PREFIX = XHTML_PREFIX_START + css
+ XHTML_PREFIX_END;
bodyText = XHTML_PREFIX + bodyText + XHTML_SUFFIX;
}
// when this text is set it will recreate all the
// OTDocumentObjectViews, so we need to clear and
// close all the old panels first
removeAllSubViews();
editorPane.setText(bodyText);
previewComponent = editorPane;
// we used to set thie caret pos so the view would
// scroll to the top, but now we disable scrolling
// during the load, and that seems to work better
// there is no flicker that way.
// editorPane.setCaretPosition(0);
} else {
System.err.println("xhtml markup not supported");
}
if (parsedTextArea == null) {
parsedTextArea = new JTextArea();
}
parsedTextArea.setText(bodyText);
return bodyText;
}
/**
* This method gets the object with idStr and tries to get the view entry
* with the viewIdStr. If the viewIdStr is not null then it gets the view
* for that view entry and the current view mode, and determines if it is a
* {@link OTXHTMLView}. If it is then it gets the html text of that view.
* If the viewIdStr is null then asks the viewFactory for a view of this
* object which implements the OTXHTMLView interface. If such a view exists
* then that is used to get the text.
*
* The text returned is intended for use by the Matcher.appendReplacement
* method. So $0 means to just leave the text as is. Because of this any
* text needs to be escaped, specifically $ and \ needs to be escaped.
* {@link OTrunkUtil#escapeReplacement(String)}
*
* So far this is only used by the substitueIncludables method
*
* @see OTrunkUtil#escapeReplacement(String)
* @see #substituteIncludables(String)
*
*/
public String getIncludableReplacement(String idStr, String viewIdStr,
String modeStr) {
// lookup the object at this id
OTObject referencedObject = getReferencedObject(idStr);
if (referencedObject == null) {
return "$0";
}
OTViewEntry viewEntry = null;
if (viewIdStr != null) {
OTObject viewEntryTmp = getReferencedObject(viewIdStr);
if (viewEntryTmp instanceof OTViewEntry) {
viewEntry = (OTViewEntry) viewEntryTmp;
} else {
System.err.println("viewid reference to a non viewEntry object");
System.err.println(" doc: " + pfObject.getGlobalId());
System.err.println(" refid: " + idStr);
System.err.println(" viewid: " + viewIdStr);
}
}
OTView view = null;
String viewMode = getViewMode();
if (modeStr != null) {
if (modeStr.length() == 0) {
viewMode = null;
} else {
viewMode = modeStr;
}
}
if (viewEntry != null) {
view = getViewFactory().getView(referencedObject, viewEntry,
viewMode);
} else {
view = getViewFactory().getView(referencedObject,
OTXHTMLView.class, viewMode);
// if there isnt' a xhtml view and there is a view mode, then see if
// that viewMode of the jcomponent view is an xhtmlview.
// this logic is really contorted. The mixing of viewmodes and
// renderings needs to be well defined.
if (view == null && getViewMode() != null) {
view = getViewFactory().getView(referencedObject,
OTJComponentView.class, viewMode);
}
}
if (view instanceof OTXHTMLView) {
OTXHTMLView xhtmlView = (OTXHTMLView) view;
try {
String replacement = xhtmlView.getXHTMLText(referencedObject);
if (replacement == null) {
// this is an empty embedded object
System.err.println("empty embedd obj: " + idStr);
return "";
}
return OTrunkUtil.escapeReplacement(replacement);
} catch (Exception e) {
System.err
.println("Failed to generate xhtml version of embedded object");
e.printStackTrace();
}
}
return "$0";
}
public String substituteIncludables(String inText) {
if (inText == null) {
return null;
}
Pattern p = Pattern.compile("<object refid=\"([^\"]*)\"[^>]*>");
Pattern pViewId = Pattern.compile("viewid=\"([^\"]*)\"");
Pattern pMode = Pattern.compile("mode=\"([^\"]*)\"");
Matcher m = p.matcher(inText);
StringBuffer parsed = new StringBuffer();
while (m.find()) {
String id = m.group(1);
String element = m.group(0);
Matcher mViewId = pViewId.matcher(element);
String viewIdStr = null;
if (mViewId.find()) {
viewIdStr = mViewId.group(1);
}
Matcher mMode = pMode.matcher(element);
String modeStr = null;
if (mMode.find()) {
modeStr = mMode.group(1);
}
String replacement = getIncludableReplacement(id, viewIdStr,
modeStr);
try {
m.appendReplacement(parsed, replacement);
} catch (IllegalArgumentException e) {
System.err.println("bad replacement: " + replacement);
e.printStackTrace();
}
}
m.appendTail(parsed);
return parsed.toString();
}
public String htmlizeText(String inText) {
if (inText == null) {
return null;
}
inText = inText.replaceAll("<p[ ]*/>", "<p></p>");
return inText.replaceAll("<([^>]*)/>", "<$1>");
/*
* Pattern p = Pattern.compile("<([^>]*)/>"); Matcher m =
* p.matcher(inText); StringBuffer parsed = new StringBuffer();
* while(m.find()) { String tagBody = m.group(1);
* // We need 6 backslashes because // first the java compiler strips
* off half of them so the sting // becomes: \\\$ // then the replacer
* uses the backslash as a quote, and the $ // character is used to
* reference groups of characters, so it // must be escaped. So the 1st
* two are turned into one, and the // 3rd one escapes the $. So the end
* result is: // \$ // We need this \$ because the replacement below is
* going to // parse the $ otherwise tagBody = tagBody.replaceAll("\\$",
* "\\\\\\$"); try { m.appendReplacement(parsed, "<$1>" + tagBody +
* ">"); } catch (IllegalArgumentException e) { System.err.println("bad
* tag: " + tagBody); e.printStackTrace(); } } m.appendTail(parsed);
* return parsed.toString();
*/
}
// FIXME: Does this do anything anymore? Nothing seems to call it. -SF
public Document parseString(String text, String systemId) {
try {
if (xmlDocumentFactory == null) {
xmlDocumentFactory = DocumentBuilderFactory.newInstance();
xmlDocumentFactory.setValidating(true);
xmlDocumentBuilder = xmlDocumentFactory.newDocumentBuilder();
// TODO Fix this
xmlDocumentBuilder.setErrorHandler(new DefaultHandler());
}
StringReader stringReader = new StringReader(text);
InputSource inputSource = new InputSource(stringReader);
inputSource.setSystemId(systemId);
return xmlDocumentBuilder.parse(inputSource);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* (non-Javadoc)
*
* @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
*/
public void stateChanged(ChangeEvent event) {
// System.out.println(this+" -- TABS stateChanged");
updateFormatedView();
}
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
String linkTarget = e.getDescription();
if (linkTarget.startsWith("http")
|| linkTarget.startsWith("file")) {
try {
// FIXME this should be changed to be a service
// so external links can work in both a jnlp
// env and a regular application env
Class serviceManager = Class
.forName("javax.jnlp.ServiceManager");
Method lookupMethod = serviceManager.getMethod(
"lookup", new Class[] { String.class });
Object basicService = lookupMethod.invoke(null,
new Object[] { "javax.jnlp.BasicService" });
Method showDocument = basicService.getClass()
.getMethod("showDocument",
new Class[] { URL.class });
showDocument.invoke(basicService,
new Object[] { new URL(linkTarget) });
return;
} catch (Exception exp) {
System.err.println("Can't open external link.");
exp.printStackTrace();
}
}
OTObject linkObj = getReferencedObject(linkTarget);
if (linkObj == null) {
System.err.println("Invalid link: " + e.getDescription());
return;
}
Element aElement = e.getSourceElement();
AttributeSet attribs = aElement.getAttributes();
// this is a hack because i don't really know what is going on
// here
AttributeSet tagAttribs = (AttributeSet) attribs
.getAttribute(HTML.Tag.A);
String target = (String) tagAttribs
.getAttribute(HTML.Attribute.TARGET);
String viewEntryId = (String) tagAttribs.getAttribute("viewid");
String modeStr = (String) tagAttribs.getAttribute("mode");
if (target == null) {
getViewContainer().setCurrentObject(linkObj);
} else {
// they want to use a frame
OTFrame targetFrame = null;
// get the frame object
// modify setCurrentObject to take a frame object
// then at the top level view container deal with this
// object
targetFrame = (OTFrame) getReferencedObject(target);
OTViewEntry viewEntry = null;
if (viewEntryId != null) {
viewEntry = (OTViewEntry) getReferencedObject(viewEntryId);
}
if (targetFrame == null) {
System.err.println("Invalid link target attrib: "
+ target);
return;
}
if (modeStr != null && modeStr.length() == 0) {
modeStr = null;
} else if (modeStr == null) {
modeStr = getViewMode();
}
getFrameManager().putObjectInFrame(linkObj, viewEntry,
targetFrame, modeStr);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
public String getXHTMLText(OTObject otObject) {
if (otObject == null) {
throw new IllegalArgumentException("otObject can't be null");
}
pfObject = (OTDocument) otObject;
// return updateFormatedView().replace(viewEntry.getCss(), "");
String bodyText = pfObject.getDocumentText();
bodyText = substituteIncludables(bodyText);
return bodyText;
}
/*
* (non-Javadoc)
*
* @see org.concord.framework.otrunk.view.OTViewConfigAware#setViewConfig(org.concord.framework.otrunk.OTObject)
*/
public void setViewEntry(OTViewEntry viewEntry) {
super.setViewEntry(viewEntry);
if (viewEntry instanceof OTDocumentViewConfig) {
this.viewEntry = (OTDocumentViewConfig) viewEntry;
setViewMode(this.viewEntry.getMode());
}
}
}
|
src/java/org/concord/otrunk/view/document/OTDocumentView.java
|
/*
* Copyright (C) 2004 The Concord Consortium, Inc.,
* 10 Concord Crossing, Concord, MA 01742
*
* Web Site: http://www.concord.org
* Email: info@concord.org
*
* 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
*
* END LICENSE */
/*
* Created on Aug 19, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package org.concord.otrunk.view.document;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.html.HTML;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.view.OTFrame;
import org.concord.framework.otrunk.view.OTJComponentView;
import org.concord.framework.otrunk.view.OTView;
import org.concord.framework.otrunk.view.OTViewEntryAware;
import org.concord.framework.otrunk.view.OTViewEntry;
import org.concord.framework.otrunk.view.OTXHTMLView;
import org.concord.otrunk.OTrunkUtil;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author scott
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Generation - Code and Comments
*/
public class OTDocumentView extends AbstractOTDocumentView implements
ChangeListener, HyperlinkListener, OTXHTMLView, OTViewEntryAware {
public static boolean addedCustomLayout = false;
JTabbedPane tabbedPane = null;
protected JComponent previewComponent = null;
protected JEditorPane editorPane = null;
DocumentBuilderFactory xmlDocumentFactory = null;
DocumentBuilder xmlDocumentBuilder = null;
protected JTextArea parsedTextArea = null;
protected OTDocumentViewConfig viewEntry;
protected OTObject otObject;
public final static String XHTML_PREFIX_START =
// "<?xml version='1.0' encoding='UTF-8'?>\n" +
"<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>\n"
+ "\n" + "<head>\n" + "<title>default</title>\n"
+ "<style type=\"text/css\">\n";
public final static String XHTML_PREFIX_END = "</style>" + "</head>\n"
+ "<body>\n";
public final static String XHTML_SUFFIX = "</body>\n" + "</html>";
protected void setup(OTObject doc) {
// Don't call super.setup() to avoid listening to the ot object
// inneccesarily
pfObject = (OTDocument) doc;
}
public JComponent getComponent(OTObject otObject, boolean editable) {
System.out.println("getting component");
this.otObject = otObject;
setup(otObject);
initTextAreaModel();
if (tabbedPane != null) {
tabbedPane.removeChangeListener(this);
}
// need to use the PfCDEditorKit
updateFormatedView();
setReloadOnViewEntryChange(true);
if (!editable) {
return previewComponent;
}
// JScrollPane renderedScrollPane = new JScrollPane(previewComponent);
// renderedScrollPane.getViewport().setViewPosition(new Point(0,0));
if (System.getProperty("otrunk.view.debug", "").equals("true")) {
tabbedPane = new JTabbedPane();
// need to add a listener so we can update the view pane
tabbedPane.add("View", previewComponent);
textArea = new JTextArea(textAreaModel);
JScrollPane scrollPane = new JScrollPane(textArea);
tabbedPane.add("Edit", scrollPane);
parsedTextArea.setEnabled(false);
scrollPane = new JScrollPane(parsedTextArea);
tabbedPane.add("Parsed", scrollPane);
tabbedPane.addChangeListener(this);
return tabbedPane;
} else {
return previewComponent;
}
}
public String updateFormatedView() {
if (pfObject == null)
return null;
// System.out.println(this+" updateFormatedView");
String markupLanguage = pfObject.getMarkupLanguage();
if (markupLanguage == null) {
markupLanguage = System.getProperty("org.concord.portfolio.markup",
null);
}
String bodyText = pfObject.getDocumentText();
bodyText = substituteIncludables(bodyText);
// default to html viewer for now
// FIXME the handling of the plain markup is to test the new view entry
// code
// it isn't quite valid because plain text might have html chars in it
// so it will get parsed incorrectly.
if (markupLanguage == null
|| markupLanguage.equals(OTDocument.MARKUP_PFHTML)
|| markupLanguage.equals(OTDocument.MARKUP_PLAIN)) {
if (editorPane == null) {
editorPane = new JEditorPane();
OTHTMLFactory kitViewFactory = new OTHTMLFactory(this);
OTDocumentEditorKit editorKit = new OTDocumentEditorKit(
kitViewFactory);
editorPane.setEditorKit(editorKit);
editorPane.setEditable(false);
editorPane.addHyperlinkListener(this);
}
bodyText = htmlizeText(bodyText);
if (viewEntry instanceof OTDocumentViewConfig) {
String css = "";
if (viewEntry.getCss() != null && viewEntry.getCss().length() > 0){
css = css + viewEntry.getCss();
}
if (viewEntry.getCssBlocks() != null && viewEntry.getCssBlocks().getVector().size() > 0){
Vector cssBlocks = viewEntry.getCssBlocks().getVector();
for (int i = 0; i < cssBlocks.size(); i++) {
OTCssText cssText = (OTCssText) cssBlocks.get(i);
css = css + " " + cssText.getCssText();
}
}
String XHTML_PREFIX = XHTML_PREFIX_START + css
+ XHTML_PREFIX_END;
bodyText = XHTML_PREFIX + bodyText + XHTML_SUFFIX;
}
// when this text is set it will recreate all the
// OTDocumentObjectViews, so we need to clear and
// close all the old panels first
removeAllSubViews();
editorPane.setText(bodyText);
previewComponent = editorPane;
// we used to set thie caret pos so the view would
// scroll to the top, but now we disable scrolling
// during the load, and that seems to work better
// there is no flicker that way.
// editorPane.setCaretPosition(0);
} else {
System.err.println("xhtml markup not supported");
}
if (parsedTextArea == null) {
parsedTextArea = new JTextArea();
}
parsedTextArea.setText(bodyText);
return bodyText;
}
/**
* This method gets the object with idStr and tries to get the view entry
* with the viewIdStr. If the viewIdStr is not null then it gets the view
* for that view entry and the current view mode, and determines if it is a
* {@link OTXHTMLView}. If it is then it gets the html text of that view.
* If the viewIdStr is null then asks the viewFactory for a view of this
* object which implements the OTXHTMLView interface. If such a view exists
* then that is used to get the text.
*
* The text returned is intended for use by the Matcher.appendReplacement
* method. So $0 means to just leave the text as is. Because of this any
* text needs to be escaped, specifically $ and \ needs to be escaped.
* {@link OTrunkUtil#escapeReplacement(String)}
*
* So far this is only used by the substitueIncludables method
*
* @see OTrunkUtil#escapeReplacement(String)
* @see #substituteIncludables(String)
*
*/
public String getIncludableReplacement(String idStr, String viewIdStr,
String modeStr) {
// lookup the object at this id
OTObject referencedObject = getReferencedObject(idStr);
if (referencedObject == null) {
return "$0";
}
OTViewEntry viewEntry = null;
if (viewIdStr != null) {
OTObject viewEntryTmp = getReferencedObject(viewIdStr);
if (viewEntryTmp instanceof OTViewEntry) {
viewEntry = (OTViewEntry) viewEntryTmp;
} else {
System.err.println("viewid reference to a non viewEntry object");
System.err.println(" doc: " + pfObject.getGlobalId());
System.err.println(" refid: " + idStr);
System.err.println(" viewid: " + viewIdStr);
}
}
OTView view = null;
String viewMode = getViewMode();
if (modeStr != null) {
if (modeStr.length() == 0) {
viewMode = null;
} else {
viewMode = modeStr;
}
}
if (viewEntry != null) {
view = getViewFactory().getView(referencedObject, viewEntry,
viewMode);
} else {
view = getViewFactory().getView(referencedObject,
OTXHTMLView.class, viewMode);
// if there isnt' a xhtml view and there is a view mode, then see if
// that viewMode of the jcomponent view is an xhtmlview.
// this logic is really contorted. The mixing of viewmodes and
// renderings needs to be well defined.
if (view == null && getViewMode() != null) {
view = getViewFactory().getView(referencedObject,
OTJComponentView.class, viewMode);
}
}
if (view instanceof OTXHTMLView) {
OTXHTMLView xhtmlView = (OTXHTMLView) view;
try {
String replacement = xhtmlView.getXHTMLText(referencedObject);
if (replacement == null) {
// this is an empty embedded object
System.err.println("empty embedd obj: " + idStr);
return "";
}
return OTrunkUtil.escapeReplacement(replacement);
} catch (Exception e) {
System.err
.println("Failed to generate xhtml version of embedded object");
e.printStackTrace();
}
}
return "$0";
}
public String substituteIncludables(String inText) {
if (inText == null) {
return null;
}
Pattern p = Pattern.compile("<object refid=\"([^\"]*)\"[^>]*>");
Pattern pViewId = Pattern.compile("viewid=\"([^\"]*)\"");
Pattern pMode = Pattern.compile("mode=\"([^\"]*)\"");
Matcher m = p.matcher(inText);
StringBuffer parsed = new StringBuffer();
while (m.find()) {
String id = m.group(1);
String element = m.group(0);
Matcher mViewId = pViewId.matcher(element);
String viewIdStr = null;
if (mViewId.find()) {
viewIdStr = mViewId.group(1);
}
Matcher mMode = pMode.matcher(element);
String modeStr = null;
if (mMode.find()) {
modeStr = mMode.group(1);
}
String replacement = getIncludableReplacement(id, viewIdStr,
modeStr);
try {
m.appendReplacement(parsed, replacement);
} catch (IllegalArgumentException e) {
System.err.println("bad replacement: " + replacement);
e.printStackTrace();
}
}
m.appendTail(parsed);
return parsed.toString();
}
public String htmlizeText(String inText) {
if (inText == null) {
return null;
}
inText = inText.replaceAll("<p[ ]*/>", "<p></p>");
return inText.replaceAll("<([^>]*)/>", "<$1>");
/*
* Pattern p = Pattern.compile("<([^>]*)/>"); Matcher m =
* p.matcher(inText); StringBuffer parsed = new StringBuffer();
* while(m.find()) { String tagBody = m.group(1);
* // We need 6 backslashes because // first the java compiler strips
* off half of them so the sting // becomes: \\\$ // then the replacer
* uses the backslash as a quote, and the $ // character is used to
* reference groups of characters, so it // must be escaped. So the 1st
* two are turned into one, and the // 3rd one escapes the $. So the end
* result is: // \$ // We need this \$ because the replacement below is
* going to // parse the $ otherwise tagBody = tagBody.replaceAll("\\$",
* "\\\\\\$"); try { m.appendReplacement(parsed, "<$1>" + tagBody +
* ">"); } catch (IllegalArgumentException e) { System.err.println("bad
* tag: " + tagBody); e.printStackTrace(); } } m.appendTail(parsed);
* return parsed.toString();
*/
}
// FIXME: Does this do anything anymore? Nothing seems to call it. -SF
public Document parseString(String text, String systemId) {
try {
if (xmlDocumentFactory == null) {
xmlDocumentFactory = DocumentBuilderFactory.newInstance();
xmlDocumentFactory.setValidating(true);
xmlDocumentBuilder = xmlDocumentFactory.newDocumentBuilder();
// TODO Fix this
xmlDocumentBuilder.setErrorHandler(new DefaultHandler());
}
StringReader stringReader = new StringReader(text);
InputSource inputSource = new InputSource(stringReader);
inputSource.setSystemId(systemId);
return xmlDocumentBuilder.parse(inputSource);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* (non-Javadoc)
*
* @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
*/
public void stateChanged(ChangeEvent event) {
// System.out.println(this+" -- TABS stateChanged");
updateFormatedView();
}
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
String linkTarget = e.getDescription();
if (linkTarget.startsWith("http")
|| linkTarget.startsWith("file")) {
try {
// FIXME this should be changed to be a service
// so external links can work in both a jnlp
// env and a regular application env
Class serviceManager = Class
.forName("javax.jnlp.ServiceManager");
Method lookupMethod = serviceManager.getMethod(
"lookup", new Class[] { String.class });
Object basicService = lookupMethod.invoke(null,
new Object[] { "javax.jnlp.BasicService" });
Method showDocument = basicService.getClass()
.getMethod("showDocument",
new Class[] { URL.class });
showDocument.invoke(basicService,
new Object[] { new URL(linkTarget) });
return;
} catch (Exception exp) {
System.err.println("Can't open external link.");
exp.printStackTrace();
}
}
OTObject linkObj = getReferencedObject(linkTarget);
if (linkObj == null) {
System.err.println("Invalid link: " + e.getDescription());
return;
}
Element aElement = e.getSourceElement();
AttributeSet attribs = aElement.getAttributes();
// this is a hack because i don't really know what is going on
// here
AttributeSet tagAttribs = (AttributeSet) attribs
.getAttribute(HTML.Tag.A);
String target = (String) tagAttribs
.getAttribute(HTML.Attribute.TARGET);
String viewEntryId = (String) tagAttribs.getAttribute("viewid");
String modeStr = (String) tagAttribs.getAttribute("mode");
if (target == null) {
getViewContainer().setCurrentObject(linkObj);
} else {
// they want to use a frame
OTFrame targetFrame = null;
// get the frame object
// modify setCurrentObject to take a frame object
// then at the top level view container deal with this
// object
targetFrame = (OTFrame) getReferencedObject(target);
OTViewEntry viewEntry = null;
if (viewEntryId != null) {
viewEntry = (OTViewEntry) getReferencedObject(viewEntryId);
}
if (targetFrame == null) {
System.err.println("Invalid link target attrib: "
+ target);
return;
}
if (modeStr != null && modeStr.length() == 0) {
modeStr = null;
} else if (modeStr == null) {
modeStr = getViewMode();
}
getFrameManager().putObjectInFrame(linkObj, viewEntry,
targetFrame, modeStr);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
public String getXHTMLText(OTObject otObject) {
if (otObject == null) {
throw new IllegalArgumentException("otObject can't be null");
}
pfObject = (OTDocument) otObject;
// return updateFormatedView().replace(viewEntry.getCss(), "");
String bodyText = pfObject.getDocumentText();
bodyText = substituteIncludables(bodyText);
return bodyText;
}
/*
* (non-Javadoc)
*
* @see org.concord.framework.otrunk.view.OTViewConfigAware#setViewConfig(org.concord.framework.otrunk.OTObject)
*/
public void setViewEntry(OTViewEntry viewEntry) {
super.setViewEntry(viewEntry);
if (viewEntry instanceof OTDocumentViewConfig) {
this.viewEntry = (OTDocumentViewConfig) viewEntry;
setViewMode(this.viewEntry.getMode());
}
}
}
|
rm sysout
git-svn-id: 8ebed0c25533aaea68ca43268d4d516467f97e6a@8136 6e01202a-0783-4428-890a-84243c50cc2b
|
src/java/org/concord/otrunk/view/document/OTDocumentView.java
|
rm sysout
|
|
Java
|
lgpl-2.1
|
c76c35c395153c344d4e3e4f05d86a649ca45b04
| 0
|
Darkhax-Minecraft/Dark-Utilities
|
package net.darkhax.darkutils.items;
import java.util.List;
import baubles.api.BaubleType;
import baubles.api.IBauble;
import net.darkhax.darkutils.DarkUtils;
import net.darkhax.darkutils.addons.baubles.BaublesAddon;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@Optional.Interface(iface = "baubles.api.IBauble", modid = "Baubles")
public class ItemRingEnchanted extends Item implements IBauble {
public static String[] varients = new String[] { "knockback", "fire", "fortune", "loot", "lure", "luck", "efficiency" };
public static Enchantment[] enchants = new Enchantment[] { Enchantment.knockback, Enchantment.fireAspect, Enchantment.fortune, Enchantment.looting, Enchantment.lure, Enchantment.luckOfTheSea, Enchantment.efficiency };
public ItemRingEnchanted() {
this.setUnlocalizedName("darkutils.ring");
this.setCreativeTab(DarkUtils.tab);
this.setMaxStackSize(1);
this.setHasSubtypes(true);
}
@Override
public EnumRarity getRarity (ItemStack itemstack) {
return EnumRarity.RARE;
}
@Override
public int getMetadata (int damage) {
return damage;
}
@Override
public String getUnlocalizedName (ItemStack stack) {
int meta = stack.getMetadata();
if (!((meta >= 0) && (meta < varients.length)))
return super.getUnlocalizedName() + "." + varients[0];
return super.getUnlocalizedName() + "." + varients[meta];
}
@Override
public ItemStack onItemRightClick (ItemStack stack, World world, EntityPlayer player) {
if (!world.isRemote && !BaublesAddon.equipBauble(player, stack, 1))
BaublesAddon.equipBauble(player, stack, 2);
return stack;
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems (Item itemIn, CreativeTabs tab, List<ItemStack> subItems) {
for (int meta = 0; meta < varients.length; meta++)
subItems.add(new ItemStack(this, 1, meta));
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation (ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced) {
final int meta = stack.getMetadata();
if (meta > -1 && meta < varients.length)
tooltip.add(EnumChatFormatting.GOLD + enchants[meta].getTranslatedName(1));
}
@Override
@Optional.Method(modid = "Baubles")
public boolean canEquip (ItemStack stack, EntityLivingBase entity) {
return true;
}
@Override
@Optional.Method(modid = "Baubles")
public boolean canUnequip (ItemStack stack, EntityLivingBase entity) {
return true;
}
@Override
@Optional.Method(modid = "Baubles")
public BaubleType getBaubleType (ItemStack stack) {
return BaubleType.RING;
}
@Override
@Optional.Method(modid = "Baubles")
public void onEquipped (ItemStack stack, EntityLivingBase entity) {
}
@Override
@Optional.Method(modid = "Baubles")
public void onUnequipped (ItemStack stack, EntityLivingBase entity) {
}
@Override
@Optional.Method(modid = "Baubles")
public void onWornTick (ItemStack stack, EntityLivingBase entity) {
}
}
|
src/main/java/net/darkhax/darkutils/items/ItemRingEnchanted.java
|
package net.darkhax.darkutils.items;
import java.util.List;
import baubles.api.BaubleType;
import baubles.api.IBauble;
import net.darkhax.darkutils.DarkUtils;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@Optional.Interface(iface = "baubles.api.IBauble", modid = "Baubles")
public class ItemRingEnchanted extends Item implements IBauble {
public static String[] varients = new String[] { "knockback", "fire", "fortune", "loot", "lure", "luck", "efficiency" };
public static Enchantment[] enchants = new Enchantment[] { Enchantment.knockback, Enchantment.fireAspect, Enchantment.fortune, Enchantment.looting, Enchantment.lure, Enchantment.luckOfTheSea, Enchantment.efficiency };
public ItemRingEnchanted() {
this.setUnlocalizedName("darkutils.ring");
this.setCreativeTab(DarkUtils.tab);
this.setMaxStackSize(1);
this.setHasSubtypes(true);
}
@Override
public EnumRarity getRarity (ItemStack itemstack) {
return EnumRarity.RARE;
}
@Override
public int getMetadata (int damage) {
return damage;
}
@Override
public String getUnlocalizedName (ItemStack stack) {
int meta = stack.getMetadata();
if (!((meta >= 0) && (meta < varients.length)))
return super.getUnlocalizedName() + "." + varients[0];
return super.getUnlocalizedName() + "." + varients[meta];
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems (Item itemIn, CreativeTabs tab, List<ItemStack> subItems) {
for (int meta = 0; meta < varients.length; meta++)
subItems.add(new ItemStack(this, 1, meta));
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation (ItemStack stack, EntityPlayer playerIn, List<String> tooltip, boolean advanced) {
final int meta = stack.getMetadata();
if (meta > -1 && meta < varients.length)
tooltip.add(EnumChatFormatting.GOLD + enchants[meta].getTranslatedName(1));
}
@Override
@Optional.Method(modid = "Baubles")
public boolean canEquip (ItemStack stack, EntityLivingBase entity) {
return true;
}
@Override
@Optional.Method(modid = "Baubles")
public boolean canUnequip (ItemStack stack, EntityLivingBase entity) {
return true;
}
@Override
@Optional.Method(modid = "Baubles")
public BaubleType getBaubleType (ItemStack stack) {
return BaubleType.RING;
}
@Override
@Optional.Method(modid = "Baubles")
public void onEquipped (ItemStack stack, EntityLivingBase entity) {
}
@Override
@Optional.Method(modid = "Baubles")
public void onUnequipped (ItemStack stack, EntityLivingBase entity) {
}
@Override
@Optional.Method(modid = "Baubles")
public void onWornTick (ItemStack stack, EntityLivingBase entity) {
}
}
|
Enchanted rings can be equipped by right clicking on them.
|
src/main/java/net/darkhax/darkutils/items/ItemRingEnchanted.java
|
Enchanted rings can be equipped by right clicking on them.
|
|
Java
|
unlicense
|
526cacc4026187013219ae4b971514e80ac3b616
| 0
|
verfade/examples
|
package be.kifaru.examples;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.apache.commons.io.FileUtils.writeStringToFile;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
/**
* @author Devid Verfaillie
* @since 2016-08-07
*/
public class JUnitTemporaryFolderAndFile {
/**
* The TemporaryFolder Rule allows creation of files and folders that should be deleted when the test method
* finishes (whether it passes or fails).
*/
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
File fileInTempFolder = tempFolder.newFile("sample.txt");
// File subFolderInTempFolder = tempFolder.newFolder("subfolder");
String expectedLine = "testing JUnit's TemporaryFolder Rule";
writeStringToFile(fileInTempFolder, expectedLine, UTF_8, true);
System.out.println("fileInTempFolder = " + fileInTempFolder.getAbsolutePath());
String fileAsString = readFileToString(fileInTempFolder, UTF_8);
assertThat(fileAsString, is(equalTo(expectedLine)));
}
}
|
examples/src/test/java/be/kifaru/examples/JUnitTemporaryFolderAndFile.java
|
package be.kifaru.examples;
import java.io.File;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.apache.commons.io.FileUtils.writeStringToFile;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
/**
* @author Devid Verfaillie (jd60988)
* @since 2016-08-07
*/
public class JUnitTemporaryFolderAndFile {
/**
* The TemporaryFolder Rule allows creation of files and folders that should be deleted when the test method
* finishes (whether it passes or fails).
*/
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
File fileInTempFolder = tempFolder.newFile("sample.txt");
// File subFolderInTempFolder = tempFolder.newFolder("subfolder");
String expectedLine = "testing JUnit's TemporaryFolder Rule";
writeStringToFile(fileInTempFolder, expectedLine, UTF_8, true);
System.out.println("fileInTempFolder = " + fileInTempFolder.getAbsolutePath());
String fileAsString = readFileToString(fileInTempFolder, UTF_8);
assertThat(fileAsString, is(equalTo(expectedLine)));
}
}
|
Improve @author.
|
examples/src/test/java/be/kifaru/examples/JUnitTemporaryFolderAndFile.java
|
Improve @author.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.