repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
rhauch/modeshape | web/modeshape-web-explorer/src/main/java/org/modeshape/web/client/NodePanel.java | 16932 | /*
* ModeShape (http://www.modeshape.org)
*
* 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.modeshape.web.client;
import java.util.Collection;
import org.modeshape.web.shared.JcrAccessControlList;
import org.modeshape.web.shared.JcrPolicy;
import org.modeshape.web.shared.JcrProperty;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridEditEvent;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.fields.events.ChangeEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangeHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.CellSavedEvent;
import com.smartgwt.client.widgets.grid.events.CellSavedHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
/**
* @author kulikov
*/
public class NodePanel extends Tab {
private GeneralNodeInformationPanel generalInfo = new GeneralNodeInformationPanel();
private PropertiesPanel properties;
private AccessControlPanel accessControl;
protected JcrTreeNode node;
protected String path;
protected Console console;
public NodePanel( Console console ) {
super();
this.console = console;
setIcon("icons/view_table.png");
setTitle("Node Properties");
properties = new PropertiesPanel();
accessControl = new AccessControlPanel();
VLayout vLayout = new VLayout();
vLayout.addMember(new Strut(15));
vLayout.addMember(generalInfo);
vLayout.addMember(new Strut(15));
SectionStack stack = new SectionStack();
stack.setWidth100();
stack.setHeight100();
stack.setVisibilityMode(VisibilityMode.MULTIPLE);
SectionStackSection psection = new SectionStackSection("Properties");
psection.setExpanded(true);
psection.addItem(properties);
stack.addSection(psection);
SectionStackSection acl = new SectionStackSection("Access Control");
acl.addItem(accessControl);
acl.setExpanded(true);
stack.addSection(acl);
vLayout.addMember(stack);
setPane(vLayout);
}
public String principal() {
return this.accessControl.principal();
}
/**
* Displays given node.
*
* @param node the node to display.
*/
public void display( JcrTreeNode node ) {
this.node = node;
path = node.getPath();
generalInfo.setNode(node);
properties.setData(node.getProperties());
accessControl.display(node.getAccessList(), null);
console.jcrURL.setPath(path);
console.htmlHistory.newItem(console.jcrURL.toString(), true);
}
public void setProperties( Collection<JcrProperty> props ) {
properties.setData(props);
}
public void setCanEditProperties( boolean flag ) {
this.properties.setCanEdit(flag);
}
public void refreshProperties() {
properties.refresh();
}
public void display( JcrAccessControlList acl ) {
accessControl.display(acl, null);
}
public void display( JcrAccessControlList acl,
String principal ) {
accessControl.display(acl, principal);
}
private class PropertiesPanel extends VLayout {
private ListGrid grid = new ListGrid();
private ListGridField valueField;
// private PropertiesToolBar toolBar = new PropertiesToolBar();
public PropertiesPanel() {
super();
this.setBackgroundColor("#d3d3d3");
grid.setWidth(500);
grid.setHeight(224);
grid.setAlternateRecordStyles(true);
grid.setShowAllRecords(true);
grid.setCanEdit(true);
grid.setEditEvent(ListGridEditEvent.CLICK);
grid.setEditByCell(true);
ListGridField iconField = new ListGridField("icon", " ");
iconField.setCanEdit(false);
iconField.setShowHover(true);
iconField.setWidth(20);
iconField.setType(ListGridFieldType.IMAGE);
iconField.setImageURLPrefix("icons/bullet_");
iconField.setImageURLSuffix(".png");
iconField.setTitle(" ");
iconField.setAlign(Alignment.CENTER);
ListGridField nameField = new ListGridField("name", "Name");
nameField.setCanEdit(false);
nameField.setShowHover(true);
nameField.setIcon("icons/folder_modernist_add.png");
ListGridField typeField = new ListGridField("type", "Type");
typeField.setCanEdit(false);
typeField.setShowHover(true);
typeField.setWidth(100);
typeField.setIcon("icons/tag.png");
ListGridField isProtectedField = new ListGridField("isProtected", "Protected");
isProtectedField.setCanEdit(false);
isProtectedField.setShowHover(true);
isProtectedField.setIcon("icons/document_letter_locked.png");
isProtectedField.setWidth(100);
isProtectedField.setType(ListGridFieldType.IMAGE);
isProtectedField.setImageURLPrefix("icons/");
isProtectedField.setImageURLSuffix(".png");
isProtectedField.setAlign(Alignment.CENTER);
ListGridField isMultipleField = new ListGridField("isMultiple", "Multiple");
isMultipleField.setCanEdit(false);
isMultipleField.setShowHover(true);
isMultipleField.setIcon("icons/documents.png");
isMultipleField.setWidth(100);
isMultipleField.setType(ListGridFieldType.IMAGE);
isMultipleField.setImageURLPrefix("icons/");
isMultipleField.setImageURLSuffix(".png");
isMultipleField.setAlign(Alignment.CENTER);
valueField = new ListGridField("value", "Value");
valueField.setShowHover(true);
valueField.setIcon("icons/tag_edit.png");
grid.setFields(iconField, nameField, typeField, isProtectedField, isMultipleField, valueField);
grid.setCanResizeFields(true);
grid.setWidth100();
grid.setHeight100();
grid.addCellSavedHandler(new CellSavedHandler() {
@Override
public void onCellSaved( CellSavedEvent event ) {
String name = event.getRecord().getAttribute("name");
String value = (String)event.getNewValue();
console.jcrService.setProperty(path, name, value, new AsyncCallback<Object>() {
@Override
public void onFailure( Throwable caught ) {
SC.say(caught.getMessage());
display(node);
}
@Override
public void onSuccess( Object result ) {
display(node);
}
});
}
});
// ListGridRecord listGridRecord = new ListGridRecord();
// grid.setData(new ListGridRecord[]{listGridRecord});
// grid.addCellSavedHandler(new PropertiesCellSavedHandler(Explorer.this));
// grid.addCellClickHandler(new PropertiesCellClickHandler());
// grid.setContextMenu(createPropertyRightClickMenu());
addMember(new PropsToolbar(console));
addMember(grid);
}
public void setData( Collection<JcrProperty> props ) {
ListGridRecord[] data = new ListGridRecord[props.size()];
int i = 0;
for (JcrProperty p : props) {
ListGridRecord record = new ListGridRecord();
valueField.setType(ListGridFieldType.SEQUENCE);
record.setAttribute("icon", "blue");
record.setAttribute("name", p.getName());
record.setAttribute("type", p.getType());
record.setAttribute("isProtected", Boolean.toString(p.isProtected()));
record.setAttribute("isMultiple", Boolean.toString(p.isMultiValue()));
record.setAttribute("value", p.getValue());
data[i++] = record;
}
grid.setData(data);
grid.draw();
}
public void setCanEdit( boolean flag ) {
this.grid.setCanEdit(flag);
}
public void refresh() {
// grid.setData(propertiesListGridRecords);
}
}
private class AccessControlPanel extends VLayout {
private HLayout principalPanel = new HLayout();
private ComboBoxItem principalCombo = new ComboBoxItem();
private ListGrid grid = new ListGrid();
protected JcrAccessControlList acl;
public AccessControlPanel() {
super();
setHeight(250);
DynamicForm form = new DynamicForm();
principalPanel.addMember(form);
principalPanel.setHeight(30);
principalPanel.addMember(new AclToolbar(console));
principalPanel.setBackgroundColor("#d3d3d3");
principalCombo.setTitle("Principal");
principalCombo.addChangeHandler(new ChangeHandler() {
@Override
public void onChange( ChangeEvent event ) {
String principal = (String)event.getValue();
displayPermissions(principal);
}
});
form.setItems(principalCombo);
grid.setAlternateRecordStyles(true);
grid.setShowAllRecords(true);
grid.setCanEdit(true);
grid.setEditEvent(ListGridEditEvent.CLICK);
grid.setEditByCell(true);
ListGridField iconField = new ListGridField("icon", " ");
iconField.setCanEdit(false);
iconField.setShowHover(true);
iconField.setWidth(20);
iconField.setType(ListGridFieldType.IMAGE);
iconField.setImageURLPrefix("icons/bullet_");
iconField.setImageURLSuffix(".png");
iconField.setTitle(" ");
iconField.setAlign(Alignment.CENTER);
ListGridField signField = new ListGridField("sign", " ");
signField.setCanEdit(false);
signField.setShowHover(true);
signField.setWidth(30);
signField.setType(ListGridFieldType.IMAGE);
signField.setImageURLPrefix("icons/");
signField.setImageURLSuffix(".png");
signField.setTitle(" ");
signField.setAlign(Alignment.CENTER);
ListGridField nameField = new ListGridField("permission", "Permission");
nameField.setCanEdit(false);
nameField.setShowHover(true);
nameField.setIcon("icons/sprocket.png");
ListGridField statusField = new ListGridField("status", "Status");
statusField.setCanEdit(false);
statusField.setShowHover(true);
statusField.setIcon("icons/shield.png");
grid.setFields(iconField, nameField, signField, statusField);
grid.setCanResizeFields(true);
grid.setWidth100();
grid.setHeight100();
grid.addCellClickHandler(new CellClickHandler() {
@Override
public void onCellClick( CellClickEvent event ) {
Record record = event.getRecord();
String action = record.getAttribute("permission");
String status = record.getAttribute("status");
if (status.equals("Allow")) {
record.setAttribute("status", "Deny");
acl.modify(principal(), action, "Deny");
} else {
record.setAttribute("status", "Allow");
acl.modify(principal(), action, "Allow");
}
displayPermissions();
}
});
addMember(principalPanel);
addMember(grid);
}
public String principal() {
return principalCombo.getValueAsString();
}
public void display( JcrAccessControlList acl,
String principal ) {
this.acl = acl;
Collection<JcrPolicy> entries = acl.entries();
String[] principals = new String[entries.size()];
int i = 0;
for (JcrPolicy entry : entries) {
principals[i++] = entry.getPrincipal();
}
principalCombo.setValueMap(principals);
if (principal != null) {
principalCombo.setValue(principal);
} else {
principalCombo.setValue(principals[0]);
}
displayPermissions();
}
/**
* Displays permissions for the current node and current principal
*/
protected void displayPermissions() {
String principal = (String)principalCombo.getValue();
grid.setData(acl.test(principal));
grid.show();
}
protected void displayPermissions( String principal ) {
grid.setData(acl.test(principal));
grid.show();
}
}
private class GeneralNodeInformationPanel extends VLayout {
private RecordPane currentNodeName = new RecordPane("Current Node");
private RecordPane primaryType = new RecordPane("Primary Type");
private RecordPane versions = new RecordPane("Number of Versions");
private RecordPane mixins = new RecordPane("Mixin types");
public GeneralNodeInformationPanel() {
super();
setWidth100();
addMember(currentNodeName);
addMember(primaryType);
addMember(versions);
addMember(mixins);
}
/**
* Displays general properties of the given node.
*
* @param node the node to be displayed.
*/
public void setNode( JcrTreeNode node ) {
currentNodeName.setValue(node.getName());
primaryType.setValue(node.getPrimaryType());
versions.setValue("Versions here");
mixins.setValue(combine(node.getMixins()));
}
/**
* Combines list of text items into single line.
*
* @param text the lines
* @return the combined text
*/
private String combine( String[] text ) {
if (text == null) {
return "";
}
if (text.length == 1) {
return text[0];
}
String s = text[0];
for (int i = 1; i < text.length; i++) {
s += "," + text[i];
}
return s;
}
}
private class RecordPane extends HLayout {
private Label valueLabel;
public RecordPane( String title ) {
Label titleLabel = new Label();
titleLabel.setContents(title + ":");
titleLabel.setWidth(200);
valueLabel = new Label();
valueLabel.setContents("N/A");
addMember(titleLabel);
addMember(valueLabel);
}
public void setValue( String value ) {
valueLabel.setContents(value);
}
}
private class Strut extends HLayout {
public Strut( int size ) {
super();
setHeight(size);
}
}
}
| apache-2.0 |
lpn520/sjdbc | sjdbc/src/sjdbc-config-spring/com/dangdang/ddframe/rdb/sharding/spring/namespace/constants/ShardingJdbcDataSourceBeanDefinitionParserTag.java | 2278 | /*
* Copyright 1999-2015 dangdang.com.
* <p>
* 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.spring.namespace.constants;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* 数据源解析标签.
*
* @author caohao
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ShardingJdbcDataSourceBeanDefinitionParserTag {
public static final String SHARDING_RULE_CONFIG_TAG = "sharding-rule";
public static final String PROPS_TAG = "props";
public static final String DATA_SOURCES_TAG = "data-sources";
public static final String DEFAULT_DATA_SOURCE_TAG = "default-data-source";
public static final String TABLE_RULES_TAG = "table-rules";
public static final String TABLE_RULE_TAG = "table-rule";
public static final String BINDING_TABLE_RULES_TAG = "binding-table-rules";
public static final String BINDING_TABLE_RULE_TAG = "binding-table-rule";
public static final String LOGIC_TABLE_ATTRIBUTE = "logic-table";
public static final String LOGIC_TABLES_ATTRIBUTE = "logic-tables";
public static final String DYNAMIC_TABLE_ATTRIBUTE = "dynamic";
public static final String ACTUAL_TABLES_ATTRIBUTE = "actual-tables";
public static final String DATA_SOURCE_NAMES_ATTRIBUTE = "data-source-names";
public static final String DATABASE_STRATEGY_ATTRIBUTE = "database-strategy";
public static final String TABLE_STRATEGY_ATTRIBUTE = "table-strategy";
public static final String DEFAULT_DATABASE_STRATEGY_ATTRIBUTE = "default-database-strategy";
public static final String DEFAULT_TABLE_STRATEGY_ATTRIBUTE = "default-table-strategy";
}
| apache-2.0 |
roman-sd/java-a-to-z | chapter_005/src/test/java/ru/sdroman/pro/generic/SimpleArrayTest.java | 2396 | package ru.sdroman.pro.generic;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test SimpleArray class.
* @author sdroman
* @since 04.17
*/
public class SimpleArrayTest {
/**
* SimpleArray instance.
*/
private SimpleArray<Integer> array;
/**
* SetUp.
*/
@Before
public void setUp() {
array = new SimpleArray<>();
}
/**
* Test add method.
*/
@Test
public void whenAddCallThenAddsElement() {
final int value = 5;
array.add(value);
assertThat(array.get(0), is(value));
}
/**
* Test grow method in add.
*/
@Test
public void whenAddCallThenArrayGrows() {
final int size = 5;
final int value = 6;
final int newSize = size * 3 / 2 + 1;
for (int i = 0; i < size; i++) {
array.add(i);
}
array.add(value);
assertThat(array.getElements().length, is(newSize));
}
/**
* Test remove method.
*/
@Test
public void whenRemoveCallThenRemovesElement() {
final int size = 5;
final Integer[] expected = new Integer[]{1, 2, 3, 4, null};
for (int i = 0; i < size; i++) {
array.add(i);
}
array.remove(0);
assertThat(array.getElements(), is(expected));
}
/**
* Test get method.
*/
@Test
public void whenGetCallThenReturnsElement() {
final int size = 5;
final int index = 3;
final Integer expected = 3;
for (int i = 0; i < size; i++) {
array.add(i);
}
assertThat(array.get(index), is(expected));
}
/**
* Test exception.
*/
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void whenGetCallThenThrowsException() {
final int size = 5;
final int index = 5;
for (int i = 0; i < size; i++) {
array.add(i);
}
array.get(index);
}
/**
* Test update.
*/
@Test
public void whenUpdateCallThenSetElementToNewValue() {
final int size = 5;
final Integer newValue = 10;
for (int i = 0; i < size; i++) {
array.add(i);
}
array.update(0, newValue);
assertThat(array.get(0), is(newValue));
}
}
| apache-2.0 |
seasarorg/s2dao | s2-dao/src/test/java/org/seasar/dao/dbms/Employee.java | 4172 | /*
* Copyright 2004-2011 the Seasar Foundation and the Others.
*
* 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.seasar.dao.dbms;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = 3099497274013211707L;
public static final String TABLE = "EMP";
public static final int department_RELNO = 0;
public static final int department2_RELNO = 1;
private long empno;
private String ename;
private String job;
private Short mgr;
private java.util.Date hiredate;
private Float sal;
private Float comm;
private short deptno;
private byte[] password;
private String dummy;
private Department department;
private Department department2;
public Employee() {
}
public Employee(long empno) {
this.empno = empno;
}
public long getEmpno() {
return this.empno;
}
public void setEmpno(long empno) {
this.empno = empno;
}
public java.lang.String getEname() {
return this.ename;
}
public void setEname(java.lang.String ename) {
this.ename = ename;
}
public java.lang.String getJob() {
return this.job;
}
public void setJob(java.lang.String job) {
this.job = job;
}
public Short getMgr() {
return this.mgr;
}
public void setMgr(Short mgr) {
this.mgr = mgr;
}
public java.util.Date getHiredate() {
return this.hiredate;
}
public void setHiredate(java.util.Date hiredate) {
this.hiredate = hiredate;
}
public Float getSal() {
return this.sal;
}
public void setSal(Float sal) {
this.sal = sal;
}
public Float getComm() {
return this.comm;
}
public void setComm(Float comm) {
this.comm = comm;
}
public short getDeptno() {
return this.deptno;
}
public void setDeptno(short deptno) {
this.deptno = deptno;
}
public byte[] getPassword() {
return this.password;
}
public void setPassword(byte[] password) {
this.password = password;
}
public String getDummy() {
return this.dummy;
}
public void setDummy(String dummy) {
this.dummy = dummy;
}
public Department getDepartment() {
return this.department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Department getDepartment2() {
return this.department2;
}
public void setDepartment2(Department department2) {
this.department2 = department2;
}
public boolean equals(Object other) {
if (!(other instanceof Employee))
return false;
Employee castOther = (Employee) other;
return this.getEmpno() == castOther.getEmpno();
}
public int hashCode() {
return (int) this.getEmpno();
}
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(empno).append(", ");
buf.append(ename).append(", ");
buf.append(job).append(", ");
buf.append(mgr).append(", ");
buf.append(hiredate).append(", ");
buf.append(sal).append(", ");
buf.append(comm).append(", ");
buf.append(deptno).append(" {");
buf.append(department).append("}");
return buf.toString();
}
}
| apache-2.0 |
jmarranz/relproxy_examples | relproxy_ex_gwt/src/com/innowhere/relproxyexgwt/server/GreetingServiceImpl.java | 5568 | package com.innowhere.relproxyexgwt.server;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.innowhere.relproxy.RelProxyOnReloadListener;
import com.innowhere.relproxy.jproxy.JProxy;
import com.innowhere.relproxy.jproxy.JProxyCompilerListener;
import com.innowhere.relproxy.jproxy.JProxyConfig;
import com.innowhere.relproxy.jproxy.JProxyDiagnosticsListener;
import com.innowhere.relproxy.jproxy.JProxyInputSourceFileExcludedListener;
import com.innowhere.relproxyexgwt.client.GreetingService;
/**
* The server-side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
protected GreetingServiceDelegate delegate;
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext context = config.getServletContext();
String inputPath = context.getRealPath("/") + "/../src/";
if (!new File(inputPath).exists())
{
System.out.println("RelProxy is disabled, detected production mode ");
return;
}
JProxyInputSourceFileExcludedListener excludedListener = new JProxyInputSourceFileExcludedListener()
{
@Override
public boolean isExcluded(File file, File rootFolder) {
String absPath = file.getAbsolutePath();
if (file.isDirectory())
{
return absPath.endsWith(File.separatorChar + "client") ||
absPath.endsWith(File.separatorChar + "shared");
}
else
{
return absPath.endsWith(GreetingServiceDelegate.class.getSimpleName() + ".java") ||
absPath.endsWith(GreetingServiceImpl.class.getSimpleName() + ".java");
}
}
};
String classFolder = null; // Optional: context.getRealPath("/") + "/WEB-INF/classes";
Iterable<String> compilationOptions = Arrays.asList(new String[]{"-source","1.6","-target","1.6"});
long scanPeriod = 200;
RelProxyOnReloadListener proxyListener = new RelProxyOnReloadListener() {
public void onReload(Object objOld, Object objNew, Object proxy, Method method, Object[] args) {
System.out.println("Reloaded " + objNew + " Calling method: " + method);
}
};
JProxyCompilerListener compilerListener = new JProxyCompilerListener(){
@Override
public void beforeCompile(File file)
{
System.out.println("Before compile: " + file);
}
@Override
public void afterCompile(File file)
{
System.out.println("After compile: " + file);
}
};
JProxyDiagnosticsListener diagnosticsListener = new JProxyDiagnosticsListener()
{
public void onDiagnostics(DiagnosticCollector<javax.tools.JavaFileObject> diagnostics)
{
List<Diagnostic<? extends JavaFileObject>> diagList = diagnostics.getDiagnostics();
int i = 1;
for (Diagnostic<? extends JavaFileObject> diagnostic : diagList)
{
System.err.println("Diagnostic " + i);
System.err.println(" code: " + diagnostic.getCode());
System.err.println(" kind: " + diagnostic.getKind());
System.err.println(" line number: " + diagnostic.getLineNumber());
System.err.println(" column number: " + diagnostic.getColumnNumber());
System.err.println(" start position: " + diagnostic.getStartPosition());
System.err.println(" position: " + diagnostic.getPosition());
System.err.println(" end position: " + diagnostic.getEndPosition());
System.err.println(" source: " + diagnostic.getSource());
System.err.println(" message: " + diagnostic.getMessage(null));
i++;
}
}
};
JProxyConfig jpConfig = JProxy.createJProxyConfig();
jpConfig.setEnabled(true)
.setRelProxyOnReloadListener(proxyListener)
.setInputPath(inputPath)
.setJProxyInputSourceFileExcludedListener(excludedListener)
.setScanPeriod(scanPeriod)
.setClassFolder(classFolder)
.setCompilationOptions(compilationOptions)
.setJProxyCompilerListener(compilerListener)
.setJProxyDiagnosticsListener(diagnosticsListener);
JProxy.init(jpConfig);
this.delegate = JProxy.create(new GreetingServiceDelegateImpl(this), GreetingServiceDelegate.class);
} // init
public String greetServer(String input) throws IllegalArgumentException
{
try
{
return delegate.greetServer(input);
}
catch(IllegalArgumentException ex)
{
ex.printStackTrace();
throw ex;
}
catch(Exception ex)
{
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public HttpServletRequest getThreadLocalRequestPublic()
{
return getThreadLocalRequest();
}
}
| apache-2.0 |
moyun/copycat | server/src/main/java/io/atomix/copycat/server/storage/cleaner/Cleaner.java | 6220 | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.copycat.server.storage.cleaner;
import io.atomix.copycat.server.storage.Segment;
import io.atomix.copycat.server.storage.SegmentManager;
import io.atomix.catalyst.util.Assert;
import io.atomix.catalyst.util.concurrent.ThreadContext;
import io.atomix.catalyst.util.concurrent.ThreadPoolContext;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Log cleaner.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
public class Cleaner implements AutoCloseable {
private static final double CLEAN_THRESHOLD = 0.5;
private final SegmentManager manager;
private final EntryTree tree = new EntryTree();
private final ScheduledExecutorService executor;
private CompletableFuture<Void> cleanFuture;
/**
* @throws NullPointerException if {@code manager} or {@code executor} are null
*/
public Cleaner(SegmentManager manager, ScheduledExecutorService executor) {
this.manager = Assert.notNull(manager, "manager");
this.executor = Assert.notNull(executor, "executor");
}
/**
* Returns the cleaner index.
*
* @return The cleaner index.
*/
public long index() {
return manager.compactIndex();
}
/**
* Returns the log cleaner entry tree.
*
* @return The log cleaner entry tree.
*/
public EntryTree tree() {
return tree;
}
/**
* Cleans the log.
*
* @return A completable future to be completed once the log has been cleaned.
*/
public CompletableFuture<Void> clean() {
if (cleanFuture != null)
return cleanFuture;
cleanFuture = new CompletableFuture<>();
cleanSegments(ThreadContext.currentContext());
return cleanFuture.whenComplete((result, error) -> cleanFuture = null);
}
/**
* Cleans all cleanable segments.
*/
private void cleanSegments(ThreadContext context) {
AtomicInteger counter = new AtomicInteger();
List<List<Segment>> cleanSegments = getCleanSegments();
if (!cleanSegments.isEmpty()) {
for (List<Segment> segments : cleanSegments) {
EntryCleaner cleaner = new EntryCleaner(manager, tree, new ThreadPoolContext(executor, manager.serializer()));
executor.execute(() -> cleaner.clean(segments).whenComplete((result, error) -> {
if (counter.incrementAndGet() == cleanSegments.size()) {
if (context != null) {
context.execute(() -> cleanFuture.complete(null));
} else {
cleanFuture.complete(null);
}
}
}));
}
} else {
cleanFuture.complete(null);
}
}
/**
* Returns a list of segment sets to clean.
*
* @return A list of segment sets to clean in the order in which they should be cleaned.
*/
private List<List<Segment>> getCleanSegments() {
List<List<Segment>> clean = new ArrayList<>();
List<Segment> segments = null;
Segment previousSegment = null;
for (Segment segment : getCleanableSegments()) {
if (segments == null) {
segments = new ArrayList<>();
segments.add(segment);
}
// If the previous segment is not an instance of the same version as this segment then reset the segments list.
// Similarly, if the previous segment doesn't directly end with the index prior to the first index in this segment then
// reset the segments list. We can only combine segments that are direct neighbors of one another.
else if (previousSegment != null && (previousSegment.descriptor().version() != segment.descriptor().version() || previousSegment.lastIndex() != segment.firstIndex() - 1)) {
clean.add(segments);
segments = new ArrayList<>();
segments.add(segment);
}
// If the total count of entries in all segments is less then the total slots in any individual segment, combine the segments.
else if (segments.stream().mapToLong(Segment::count).sum() + segment.count() < segments.stream().mapToLong(Segment::length).max().getAsLong()) {
segments.add(segment);
}
// If there's not enough room to combine segments, reset the segments list.
else {
clean.add(segments);
segments = new ArrayList<>();
segments.add(segment);
}
previousSegment = segment;
}
// Ensure all cleanable segments have been added to the clean segments list.
if (segments != null) {
clean.add(segments);
}
return clean;
}
/**
* Returns a list of compactable segments.
*
* @return A list of compactable segments.
*/
private Iterable<Segment> getCleanableSegments() {
List<Segment> segments = new ArrayList<>();
for (Segment segment : manager.segments()) {
// Only allow compaction of segments that are full.
if (segment.lastIndex() <= index() && segment.isFull()) {
// Calculate the percentage of entries that have been marked for cleaning in the segment.
double cleanPercentage = (segment.length() - segment.deleteCount()) / (double) segment.length();
// If the percentage of entries marked for cleaning times the segment version meets the cleaning threshold,
// add the segment to the segments list for cleaning.
if (cleanPercentage * segment.descriptor().version() >= CLEAN_THRESHOLD) {
segments.add(segment);
}
}
}
return segments;
}
/**
* Closes the log cleaner.
*/
@Override
public void close() {
executor.shutdown();
}
}
| apache-2.0 |
pmgexpo17/Topic-Thunder | jmsSudokuModel/src/main/java/org/pmg/jms/sudoku/genresolvar/GameResponderB1.java | 4064 | /**
* Copyright (c) 2016 Peter A McGill
*
* 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.pmg.jms.sudoku.genresolvar;
import com.google.inject.Inject;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import org.pmg.jms.genclient.ClientResponder;
import org.pmg.jms.genconnect.OpenWire;
import org.pmg.jms.genconnect.SessionProvider;
import org.pmg.jms.sudoku.genmodel.ClientState;
/**
*
* @author peter
*/
public class GameResponderB1 extends ClientResponder {
private static final int MESSAGE_LIFESPAN = 3000; // milliseconds (3 seconds)
private static final int HIGH_PRIORITY = 9;
private final ReductorBean bean;
private final ClientState state;
@Inject
public GameResponderB1(@OpenWire SessionProvider sessionPrvdr,
ClientState state,
ReductorBean bean) {
super(sessionPrvdr);
this.state = state;
this.bean = bean;
LOG.debug("[{}] state bean : {}",className, state.toString());
LOG.debug("[{}] reductor bean : {}",className, bean.toString());
}
protected ReductorBean getReductorBean() {
return bean;
}
public void putControlAction(String action) {
try {
MapMessage mapMessage = getSession().createMapMessage();
mapMessage.setStringProperty("peer",bean.sessionId);
mapMessage.setString("action",action);
mapMessage.setString("peerId",bean.peerId);
send("resolve-reduce",mapMessage,DeliveryMode.NON_PERSISTENT,
HIGH_PRIORITY,MESSAGE_LIFESPAN);
} catch (JMSException ex) {
LOG.error("[{}] message send failure",className,ex);
}
}
public void putMonitorAction(String action) {
try {
MapMessage mapMessage = getSession().createMapMessage();
mapMessage.setStringProperty("peer","monitor");
mapMessage.setString("action",action);
mapMessage.setString("peerId",bean.peerId);
send("resolve-reduce",mapMessage,DeliveryMode.NON_PERSISTENT,
HIGH_PRIORITY,MESSAGE_LIFESPAN);
} catch (JMSException ex) {
LOG.error("[{}] message send failure",className,ex);
}
}
public void putSolveMap() {
bean.fillSolveMap();
for( String peerId: bean.solvant.keySet() )
putSolveMap(peerId);
}
private void putSolveMap(String toPeerId) {
try {
String action = bean.peerId.equals(toPeerId) ? "monitor" : "resolve";
MapMessage mapMessage = getSession().createMapMessage();
mapMessage.setStringProperty("peer",toPeerId);
mapMessage.setString("gameId",bean.gameId);
mapMessage.setString("peerId",bean.peerId);
mapMessage.setInt("trialId",bean.trialId);
mapMessage.setString("action",action);
mapMessage.setString("solved", bean.getSolvent(toPeerId));
send("resolve-reduce",mapMessage,DeliveryMode.NON_PERSISTENT,
Message.DEFAULT_PRIORITY,MESSAGE_LIFESPAN);
} catch (JMSException ex) {
LOG.error("[{}] message send failure",className,ex);
}
}
}
| apache-2.0 |
saulbein/web3j | core/src/main/java/org/web3j/abi/datatypes/generated/Fixed8x136.java | 580 | package org.web3j.abi.datatypes.generated;
import java.math.BigInteger;
import org.web3j.abi.datatypes.Fixed;
/**
* <p>Auto generated code.<br>
* <strong>Do not modifiy!</strong><br>
* Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.</p>
*/
public class Fixed8x136 extends Fixed {
public static final Fixed8x136 DEFAULT = new Fixed8x136(BigInteger.ZERO);
public Fixed8x136(BigInteger value) {
super(8, 136, value);
}
public Fixed8x136(int mBitSize, int nBitSize, BigInteger m, BigInteger n) {
super(8, 136, m, n);
}
}
| apache-2.0 |
Yunying/SimCity | src/transportation/Interfaces/Passenger.java | 803 | package transportation.Interfaces;
import interfaces.Building;
import transportation.BusAgent;
import transportation.BusStop;
public interface Passenger {
public void addBusStop(Stop bs);
public void setActive();
public void msgAnimation();
public void msgTransportationStopped();
public void msgGoToBuilding(Building start, Building end, boolean c);
public void msgPleaseComeAboard();
public void msgHereIsBus(Bus bus);
public void msgYouHaveToWait();
public void msgAtStop(Stop bs, Stop bs2);
public boolean isAsked();
public void setAsked(boolean a);
public Building getStartBuilding();
public Building getEndBuilding();
public Stop getStartStop();
public Stop getEndStop();
public String getPassengerName();
public void msgWeAreGoing(Stop next);
}
| apache-2.0 |
flordan/COMPSs-Mobile | code/runtime/commons/src/main/java/es/bsc/mobile/types/JobExecution.java | 19215 | /*
* Copyright 2008-2016 Barcelona Supercomputing Center (www.bsc.es)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package es.bsc.mobile.types;
import es.bsc.mobile.annotations.Parameter;
import es.bsc.mobile.data.DataManager;
import es.bsc.mobile.data.access.DaAccess;
import es.bsc.mobile.data.access.RAccess;
import es.bsc.mobile.data.access.RWAccess;
import es.bsc.mobile.data.access.WAccess;
import es.bsc.mobile.exceptions.UnexpectedDirectionException;
import java.util.LinkedList;
public abstract class JobExecution implements Comparable<JobExecution> {
private static final String UNEXPECTED_DIRECTION = "Unexpected direction ";
private static final String FOR_PARAM = " for parameter ";
private static final String FOR_TARGET = " for target object";
private static final String FULL_STOP = ".";
private static final int BYTE_SIZE = 1;
private static final int SHORT_SIZE = 2;
private static final int CHAR_SIZE = 2;
private static final int INT_SIZE = 4;
private static final int FLOAT_SIZE = 4;
private static final int LONG_SIZE = 8;
private static final int DOUBLE_SIZE = 8;
private static final int BOOL_SIZE = 1;
public static final int TARGET_PARAM_IDX = -1;
public static final int RESULT_PARAM_IDX = -2;
private final Job job;
public JobExecution(Job job) {
this.job = job;
}
public final Job getJob() {
return job;
}
public final void checkParameterExistence(int paramId) {
DaAccess dataAccess;
JobParameter jp = job.getParams()[paramId];
switch (jp.getType()) {
case OBJECT:
JobParameter.ObjectJobParameter ojp = (JobParameter.ObjectJobParameter) jp;
dataAccess = ojp.getDataAccess();
break;
case FILE:
JobParameter.FileJobParameter fjp = (JobParameter.FileJobParameter) jp;
dataAccess = fjp.getDataAccess();
break;
default:
paramExists(jp);
return;
}
String data;
switch (jp.getDirection()) {
case IN:
data = ((RAccess) dataAccess).getReadDataInstance();
break;
case INOUT:
data = ((RWAccess) dataAccess).getReadDataInstance();
break;
default:
// case OUT
paramExists(jp);
return;
}
requestParamDataExistence(data, paramId, new ParameterExistence(jp, paramId));
}
public final void checkTargetExistence() throws UnexpectedDirectionException {
JobParameter.ObjectJobParameter target = job.getTarget();
if (target != null) {
String data;
DaAccess dataAccess = target.getDataAccess();
switch (target.getDirection()) {
case IN:
data = ((RAccess) dataAccess).getReadDataInstance();
break;
case INOUT:
data = ((RWAccess) dataAccess).getReadDataInstance();
break;
default:
// case OUT
throw new UnexpectedDirectionException("Unexpected direction " + target.getDirection() + " for target object ");
}
requestParamDataExistence(data, TARGET_PARAM_IDX, new ParameterExistence(target, TARGET_PARAM_IDX));
} else {
paramExists(target);
}
}
protected abstract void requestParamDataExistence(String dataId, int paramId, DataManager.DataExistenceListener listener);
public abstract LinkedList<Implementation> getCompatibleImplementations();
private class ParameterExistence implements DataManager.DataExistenceListener {
private final JobParameter jp;
private final int paramId;
public ParameterExistence(JobParameter jp, int paramId) {
this.jp = jp;
this.paramId = paramId;
}
@Override
public void paused() {
}
@Override
public void exists() {
paramExists(jp);
}
@Override
public void exists(Class<?> type, Object value) {
if (paramId == TARGET_PARAM_IDX) {
job.forwardTargetValue(value);
} else {
job.forwardParamValue(paramId, type, value);
}
paramExists(jp);
}
}
private void paramExists(JobParameter jp) {
paramDataExists(jp);
if (job.createdParam()) {
allParamDataExists();
}
}
public abstract void paramDataExists(JobParameter jp);
public abstract void allParamDataExists();
public void obtainJobParameter(int paramId) throws UnexpectedDirectionException {
JobParameter jp = job.getParams()[paramId];
String daIdin;
String daIdout = null;
switch (jp.getType()) {
case BOOLEAN:
job.setParamSizeIn(paramId, BOOL_SIZE);
job.setParamValue(paramId, boolean.class, ((JobParameter.BooleanJobParameter) jp).getValue(), true);
break;
case CHAR:
job.setParamSizeIn(paramId, CHAR_SIZE);
job.setParamValue(paramId, char.class, ((JobParameter.CharJobParameter) jp).getValue(), true);
break;
case STRING:
String stringValue = ((JobParameter.StringJobParameter) jp).getValue();
job.setParamSizeIn(paramId, stringValue.length());
job.setParamValue(paramId, String.class, stringValue, true);
break;
case BYTE:
job.setParamSizeIn(paramId, BYTE_SIZE);
job.setParamValue(paramId, byte.class, ((JobParameter.ByteJobParameter) jp).getValue(), true);
break;
case SHORT:
job.setParamSizeIn(paramId, SHORT_SIZE);
job.setParamValue(paramId, short.class, ((JobParameter.ShortJobParameter) jp).getValue(), true);
break;
case INT:
job.setParamSizeIn(paramId, INT_SIZE);
job.setParamValue(paramId, int.class, ((JobParameter.IntegerJobParameter) jp).getValue(), true);
break;
case LONG:
job.setParamSizeIn(paramId, LONG_SIZE);
job.setParamValue(paramId, long.class, ((JobParameter.LongJobParameter) jp).getValue(), true);
break;
case FLOAT:
job.setParamSizeIn(paramId, FLOAT_SIZE);
job.setParamValue(paramId, float.class, ((JobParameter.FloatJobParameter) jp).getValue(), true);
break;
case DOUBLE:
job.setParamSizeIn(paramId, DOUBLE_SIZE);
job.setParamValue(paramId, double.class, ((JobParameter.DoubleJobParameter) jp).getValue(), true);
break;
case FILE:
switch (jp.getDirection()) {
case IN:
daIdin = ((RAccess) ((JobParameter.FileJobParameter) jp).getDataAccess()).getReadDataInstance();
daIdout = daIdin;
break;
case INOUT:
daIdin = ((RWAccess) ((JobParameter.FileJobParameter) jp).getDataAccess()).getReadDataInstance();
daIdout = ((RWAccess) ((JobParameter.FileJobParameter) jp).getDataAccess()).getWrittenDataInstance();
break;
case OUT:
daIdin = ((WAccess) ((JobParameter.FileJobParameter) jp).getDataAccess()).getWrittenDataInstance();
daIdout = daIdin;
job.setParamSizeIn(paramId, 0);
job.setParamValue(paramId, String.class, daIdin, true);
return;
default:
daIdin = "";
daIdout = "";
throw new UnexpectedDirectionException(UNEXPECTED_DIRECTION + jp.getDirection() + FOR_PARAM + paramId);
}
if (job.isParamValueSet(paramId)) {
if (job.setParamValue(paramId, job.getParamTypes()[paramId], job.getParamValues()[paramId], true)) {
job.endsTransfers();
allDataPresent();
}
obtainDataSize(daIdin, paramId, new LoadParamData(paramId));
} else {
obtainDataAsFile(daIdin, daIdout, paramId, new LoadParamData(paramId));
}
break;
case OBJECT:
switch (jp.getDirection()) {
case IN:
daIdin = ((RAccess) ((JobParameter.ObjectJobParameter) jp).getDataAccess()).getReadDataInstance();
daIdout = daIdin;
break;
case INOUT:
daIdin = ((RWAccess) ((JobParameter.ObjectJobParameter) jp).getDataAccess()).getReadDataInstance();
daIdout = ((RWAccess) ((JobParameter.ObjectJobParameter) jp).getDataAccess()).getWrittenDataInstance();
break;
case OUT:
daIdin = ((WAccess) ((JobParameter.ObjectJobParameter) jp).getDataAccess()).getWrittenDataInstance();
daIdout = daIdin;
job.setParamSizeIn(paramId, 0);
job.setParamValue(paramId, null, null, true);
break;
default:
daIdin = "";
daIdout = "";
throw new UnexpectedDirectionException(UNEXPECTED_DIRECTION + jp.getDirection() + FOR_PARAM + paramId + FULL_STOP);
}
if (job.isParamValueSet(paramId)) {
if (job.setParamValue(paramId, job.getParamTypes()[paramId], job.getParamValues()[paramId], true)) {
job.endsTransfers();
allDataPresent();
}
obtainDataSize(daIdin, paramId, new LoadParamData(paramId));
} else {
obtainDataAsObject(daIdin, daIdout, paramId, new LoadParamData(paramId));
}
break;
default:
}
}
public void obtainTargetObject() throws UnexpectedDirectionException {
if (job.isTargetValueSet()) {
Object value = job.getTargetValue();
if (job.setTargetValue(value, true)) {
job.endsTransfers();
allDataPresent();
}
}
JobParameter.ObjectJobParameter targetParam = job.getTarget();
if (targetParam != null) {
String daIdin;
String daIdout;
switch (targetParam.getDirection()) {
case IN:
daIdin = ((RAccess) targetParam.getDataAccess()).getReadDataInstance();
daIdout = daIdin;
break;
case INOUT:
daIdin = ((RWAccess) targetParam.getDataAccess()).getReadDataInstance();
daIdout = ((RWAccess) targetParam.getDataAccess()).getWrittenDataInstance();
break;
default:
throw new UnexpectedDirectionException(UNEXPECTED_DIRECTION + targetParam.getDirection() + FOR_TARGET + FULL_STOP);
}
obtainDataAsObject(daIdin, daIdout, TARGET_PARAM_IDX, new LoadParamData(TARGET_PARAM_IDX));
} else {
job.setTargetSizeIn(0);
if (job.setTargetValue(null, true)) {
job.endsTransfers();
allDataPresent();
}
}
}
protected abstract void obtainDataSize(String dataId, int paramId, LoadParamData listener);
protected abstract void obtainDataAsObject(String dataId, String dataRenaming, int paramId, LoadParamData listener);
protected abstract void obtainDataAsFile(String dataId, String dataRenaming, int paramId, LoadParamData listener);
public class LoadParamData implements DataManager.DataOperationListener {
private final int paramId;
private boolean toCount = true;
public LoadParamData(int paramId) {
this.paramId = paramId;
}
@Override
public void paused() {
}
@Override
public void setSize(long value) {
int missingParams;
if (paramId == TARGET_PARAM_IDX) {
missingParams = job.setTargetSizeIn(value);
} else {
missingParams = job.setParamSizeIn(paramId, value);
}
if (missingParams == 0) {
completed();
}
}
public void skipLoadValue() {
if (paramId == TARGET_PARAM_IDX) {
if (job.setTargetValue(null, toCount)) {
allDataPresent();
}
} else if (job.setParamValue(paramId, null, null, toCount)) {
allDataPresent();
}
}
@Override
public void setValue(Class<?> type, Object value) {
if (paramId == TARGET_PARAM_IDX) {
if (job.setTargetValue(value, toCount)) {
job.endsTransfers();
allDataPresent();
}
} else if (job.setParamValue(paramId, type, value, toCount)) {
job.endsTransfers();
allDataPresent();
}
toCount = false;
}
@Override
public String toString() {
switch (paramId) {
case TARGET_PARAM_IDX:
return "input version of the target object for job " + job.getTaskId();
default:
return "input version of the parameter " + paramId + " for job " + job.getTaskId();
}
}
}
public abstract void allDataPresent();
public abstract void prepareJobParameter(int paramId);
public abstract void prepareTargetObject();
public abstract void prepareResult();
public abstract void allDataReady();
public abstract void executeOn(Object id, Implementation impl);
public abstract void failedExecution();
public abstract void finishedExecution();
public void storeJobParameter(int paramId) {
JobParameter jp = job.getParams()[paramId];
DaAccess dataAccess;
switch (jp.getType()) {
case OBJECT:
JobParameter.ObjectJobParameter ojp = (JobParameter.ObjectJobParameter) jp;
dataAccess = ojp.getDataAccess();
break;
case FILE:
JobParameter.FileJobParameter fjp = (JobParameter.FileJobParameter) jp;
dataAccess = fjp.getDataAccess();
break;
default:
job.setParamSizeOut(paramId, 0);
return;
}
String data;
switch (jp.getDirection()) {
case IN:
job.setParamSizeOut(paramId, 0);
return;
case INOUT:
data = ((RWAccess) dataAccess).getWrittenDataInstance();
break;
default:
// case OUT
data = ((WAccess) dataAccess).getWrittenDataInstance();
break;
}
if (jp.getType() == Parameter.Type.OBJECT) {
storeObject(data, job.getParamValues()[paramId], new StoreDataListener(paramId));
} else {
storeFile(data, (String) job.getParamValues()[paramId], new StoreDataListener(paramId));
}
}
public void storeTarget() {
if (job.getTarget() != null) {
if (job.getTarget().getDirection() == Parameter.Direction.INOUT) {
String data = ((RWAccess) job.getTarget().getDataAccess()).getWrittenDataInstance();
storeObject(data, job.getTargetValue(), new StoreDataListener(TARGET_PARAM_IDX));
}
} else {
int missingSizes = job.setTargetSizeOut(0);
if (missingSizes == 0) {
completed();
}
}
}
public void storeResult() {
if (job.getResult() != null) {
String data = ((WAccess) job.getResult().getDataAccess()).getWrittenDataInstance();
storeObject(data, job.getResultValue(), new StoreDataListener(RESULT_PARAM_IDX));
} else {
int missingSizes = job.setResultSize(0);
if (missingSizes == 0) {
completed();
}
}
}
protected abstract void storeObject(String dataId, Object value, DataManager.DataOperationListener listener);
protected abstract void storeFile(String dataId, String location, DataManager.DataOperationListener listener);
private class StoreDataListener implements DataManager.DataOperationListener {
private final int param;
public StoreDataListener(int param) {
this.param = param;
}
@Override
public void paused() {
}
@Override
public void setSize(long value) {
int missingSizes;
switch (param) {
case RESULT_PARAM_IDX:
missingSizes = job.setResultSize(value);
break;
case TARGET_PARAM_IDX:
missingSizes = job.setTargetSizeOut(value);
break;
default:
missingSizes = job.setParamSizeOut(param, value);
}
if (missingSizes == 0) {
completed();
}
}
@Override
public void setValue(Class<?> type, Object value) {
}
@Override
public String toString() {
switch (param) {
case RESULT_PARAM_IDX:
return "result object for job " + job.getId();
case TARGET_PARAM_IDX:
return "output version of the target object for job " + job.getId();
default:
return "output version of the parameter " + param + " for job " + job.getId();
}
}
}
public abstract void completed();
@Override
public int compareTo(JobExecution o) {
return Integer.compare(this.job.getTaskId(), o.job.getTaskId());
}
}
| apache-2.0 |
wmixlabs/sped | src/main/java/br/com/wmixvideo/sped/enums/SFIndicadorOperacao.java | 379 | package br.com.wmixvideo.sped.enums;
public enum SFIndicadorOperacao {
AQUISICAO("0"),
PRESTACAO("1");
private final String codigo;
SFIndicadorOperacao(final String codigo) {
this.codigo = codigo;
}
public String getCodigo() {
return this.codigo;
}
@Override
public String toString() {
return this.codigo;
}
} | apache-2.0 |
phax/ph-commons | ph-xml/src/test/java/com/helger/xml/supplementary/test/MainFindInvalidXMLChars.java | 8331 | /*
* Copyright (C) 2014-2022 Philip Helger (www.helger.com)
* philip[at]helger[dot]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.helger.xml.supplementary.test;
import java.util.List;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.helger.commons.collection.impl.CommonsArrayList;
import com.helger.commons.collection.impl.ICommonsList;
import com.helger.commons.io.stream.NonBlockingStringWriter;
import com.helger.xml.EXMLVersion;
import com.helger.xml.XMLFactory;
import com.helger.xml.serialize.read.DOMReader;
import com.helger.xml.transform.XMLTransformerFactory;
public final class MainFindInvalidXMLChars
{
private static final Logger LOGGER = LoggerFactory.getLogger (MainFindInvalidXMLChars.class);
private MainFindInvalidXMLChars ()
{}
private static String _getFormatted (final List <Integer> x)
{
if (x.isEmpty ())
return "false";
final int nRadix = 16;
if (x.size () == 1)
return "c == 0x" + Integer.toString (x.get (0).intValue (), nRadix);
final StringBuilder ret = new StringBuilder ();
int nIndex = 0;
int nFirst = -1;
int nLast = -1;
do
{
final int nValue = x.get (nIndex).intValue ();
if (nFirst < 0)
{
// First item
nFirst = nLast = nValue;
}
else
if (nValue == nLast + 1)
{
nLast = nValue;
}
else
{
if (ret.length () > 0)
ret.append (" || ");
if (nFirst == nLast)
ret.append ("(c == 0x" + Integer.toString (nFirst, nRadix) + ")");
else
ret.append ("(c >= 0x" + Integer.toString (nFirst, nRadix) + " && c <= 0x" + Integer.toString (nLast, nRadix) + ")");
nFirst = nLast = nValue;
}
++nIndex;
} while (nIndex < x.size ());
if (nLast > nFirst)
{
if (ret.length () > 0)
ret.append (" || ");
ret.append ("(c >= 0x" + Integer.toString (nFirst, nRadix) + " && c <= 0x" + Integer.toString (nLast, nRadix) + ")");
}
return ret.toString ();
}
public static void main (final String [] args)
{
final EXMLVersion eXMLVersion = EXMLVersion.XML_10;
final int nMax = Character.MAX_VALUE + 1;
final ICommonsList <Integer> aForbiddenE1 = new CommonsArrayList <> ();
for (int i = 0; i < nMax; ++i)
{
final Document aDoc = XMLFactory.newDocument (eXMLVersion);
try
{
aDoc.appendChild (aDoc.createElement (Character.toString ((char) i)));
final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
XMLTransformerFactory.newTransformer ().transform (new DOMSource (aDoc), new StreamResult (aSW));
DOMReader.readXMLDOM (aSW.getAsString ());
}
catch (final Exception ex)
{
aForbiddenE1.add (Integer.valueOf (i));
}
}
final ICommonsList <Integer> aForbiddenE2 = new CommonsArrayList <> ();
for (int i = 0; i < nMax; ++i)
{
final Document aDoc = XMLFactory.newDocument (eXMLVersion);
try
{
aDoc.appendChild (aDoc.createElement ("a" + Character.toString ((char) i)));
final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
XMLTransformerFactory.newTransformer ().transform (new DOMSource (aDoc), new StreamResult (aSW));
DOMReader.readXMLDOM (aSW.getAsString ());
}
catch (final Exception ex)
{
aForbiddenE2.add (Integer.valueOf (i));
}
}
final ICommonsList <Integer> aForbiddenAN1 = new CommonsArrayList <> ();
for (int i = 0; i < nMax; ++i)
{
final Document aDoc = XMLFactory.newDocument (eXMLVersion);
try
{
final Element aElement = (Element) aDoc.appendChild (aDoc.createElement ("abc"));
aElement.setAttribute (Character.toString ((char) i), "xyz");
final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
XMLTransformerFactory.newTransformer ().transform (new DOMSource (aDoc), new StreamResult (aSW));
DOMReader.readXMLDOM (aSW.getAsString ());
}
catch (final Exception ex)
{
aForbiddenAN1.add (Integer.valueOf (i));
}
}
final ICommonsList <Integer> aForbiddenAN2 = new CommonsArrayList <> ();
for (int i = 0; i < nMax; ++i)
{
final Document aDoc = XMLFactory.newDocument (eXMLVersion);
try
{
final Element aElement = (Element) aDoc.appendChild (aDoc.createElement ("abc"));
aElement.setAttribute ("a" + Character.toString ((char) i), "xyz");
final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
XMLTransformerFactory.newTransformer ().transform (new DOMSource (aDoc), new StreamResult (aSW));
DOMReader.readXMLDOM (aSW.getAsString ());
}
catch (final Exception ex)
{
aForbiddenAN2.add (Integer.valueOf (i));
}
}
final ICommonsList <Integer> aForbiddenAV = new CommonsArrayList <> ();
for (int i = 0; i < nMax; ++i)
{
final Document aDoc = XMLFactory.newDocument (eXMLVersion);
try
{
final Element aElement = (Element) aDoc.appendChild (aDoc.createElement ("abc"));
aElement.setAttribute ("a", Character.toString ((char) i));
final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
XMLTransformerFactory.newTransformer ().transform (new DOMSource (aDoc), new StreamResult (aSW));
DOMReader.readXMLDOM (aSW.getAsString ());
}
catch (final Exception ex)
{
aForbiddenAV.add (Integer.valueOf (i));
}
}
final ICommonsList <Integer> aForbiddenTV = new CommonsArrayList <> ();
for (int i = 0; i < nMax; ++i)
{
final Document aDoc = XMLFactory.newDocument (eXMLVersion);
try
{
final Element aElement = (Element) aDoc.appendChild (aDoc.createElement ("abc"));
aElement.appendChild (aDoc.createTextNode (Character.toString ((char) i)));
final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
XMLTransformerFactory.newTransformer ().transform (new DOMSource (aDoc), new StreamResult (aSW));
DOMReader.readXMLDOM (aSW.getAsString ());
}
catch (final Exception ex)
{
aForbiddenTV.add (Integer.valueOf (i));
}
}
final ICommonsList <Integer> aForbiddenCV = new CommonsArrayList <> ();
for (int i = 0; i < nMax; ++i)
{
final Document aDoc = XMLFactory.newDocument (eXMLVersion);
try
{
final Element aElement = (Element) aDoc.appendChild (aDoc.createElement ("abc"));
aElement.appendChild (aDoc.createCDATASection (Character.toString ((char) i)));
final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
XMLTransformerFactory.newTransformer ().transform (new DOMSource (aDoc), new StreamResult (aSW));
DOMReader.readXMLDOM (aSW.getAsString ());
}
catch (final Exception ex)
{
aForbiddenCV.add (Integer.valueOf (i));
}
}
LOGGER.info ("Forbidden Element Name Start: " + _getFormatted (aForbiddenE1));
LOGGER.info ("Forbidden Element Name InBetween: " + _getFormatted (aForbiddenE2));
LOGGER.info ("Forbidden Attribute Name Start: " + _getFormatted (aForbiddenAN1));
LOGGER.info ("Forbidden Attribute Name InBetween: " + _getFormatted (aForbiddenAN2));
LOGGER.info ("Forbidden Attribute Value: " + _getFormatted (aForbiddenAV));
LOGGER.info ("Forbidden Text Value: " + _getFormatted (aForbiddenTV));
LOGGER.info ("Forbidden CDATA Value: " + _getFormatted (aForbiddenCV));
}
}
| apache-2.0 |
shijiameng/OpenVirteX | src/main/java/org/openflow/protocol/statistics/OFVendorStatistics.java | 3655 | /*******************************************************************************
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/**
* Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior
* University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package org.openflow.protocol.statistics;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.openflow.vendor.enslab.statistics.OFEnslabStatistics;
/**
* The base class for vendor implemented statistics
*
* @author David Erickson (daviderickson@cs.stanford.edu)
*/
public class OFVendorStatistics implements OFStatistics {
protected int vendor;
protected byte[] body;
// non-message fields
protected int length = 0;
// SJM NIaaS
public void setVendor(final int vendor) {
this.vendor = vendor;
}
public void setVendorBody(final int dataType, OFEnslabStatistics body) {
ChannelBuffer buffer = ChannelBuffers.buffer(8 + body.getLength());
buffer.writeInt(dataType);
buffer.writeInt(0);
body.writeTo(buffer);
this.body = buffer.array();
}
public byte[] getVendorBody() {
return this.body;
}
// SJM NIaaS END
@Override
public void readFrom(final ChannelBuffer data) {
this.vendor = data.readInt();
if (this.body == null) {
this.body = new byte[this.length - 4];
}
data.readBytes(this.body);
}
@Override
public void writeTo(final ChannelBuffer data) {
data.writeInt(this.vendor);
if (this.body != null) {
data.writeBytes(this.body);
}
}
@Override
public int hashCode() {
final int prime = 457;
int result = 1;
result = prime * result + this.vendor;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof OFVendorStatistics)) {
return false;
}
final OFVendorStatistics other = (OFVendorStatistics) obj;
if (this.vendor != other.vendor) {
return false;
}
return true;
}
@Override
public int getLength() {
return this.length;
}
public void setLength(final int length) {
this.length = length;
}
}
| apache-2.0 |
opensingular/singular-core | lib/commons/src/main/java/org/opensingular/lib/commons/io/TempFileInputStream.java | 1650 | /*
* Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.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.opensingular.lib.commons.io;
import org.opensingular.lib.commons.util.Loggable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Keeps a reference of a temp file and delete it as soon as the stream
* is closed.
*/
public class TempFileInputStream extends FileInputStream implements Loggable{
private File tempFile;
public TempFileInputStream(File file) throws FileNotFoundException {
super(file);
this.tempFile = file;
}
@Override
public void close() throws IOException {
super.close();
if (tempFile != null) {
String name = tempFile.getName();
boolean deletedWithSuccess = tempFile.delete();
if (!deletedWithSuccess) {
getLogger().warn("Não foi possivel deletar o arquivo {} corretamente", name);
} else {
tempFile = null;
}
}
}
} | apache-2.0 |
sbower/kuali-rice-1 | impl/src/main/java/org/kuali/rice/kew/routelog/web/RouteLogForm.java | 5841 | /*
* Copyright 2006-2011 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kew.routelog.web;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.kew.actionrequest.ActionRequestValue;
import org.kuali.rice.kns.web.struts.form.KualiForm;
import org.kuali.rice.krad.util.UrlFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* The Struts ActionForm used with {@link RouteLogAction} to display the routelog.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class RouteLogForm extends KualiForm {
private static final long serialVersionUID = -3997667167734868281L;
private String methodToCall = "";
private String documentId;
private List rootRequests = new ArrayList();
private int pendingActionRequestCount;
private List<ActionRequestValue> futureRootRequests = new ArrayList<ActionRequestValue>();
private int futureActionRequestCount;
private boolean showFuture;
private String showFutureError;
private boolean removeHeader;
private boolean lookFuture;
private boolean showNotes;
private String docId;
private String returnUrlLocation = null;
private boolean showCloseButton = false;
private String newRouteLogActionMessage;
private boolean enableLogAction = false;
public boolean isShowCloseButton() {
return showCloseButton;
}
public void setShowCloseButton(boolean showCloseButton) {
this.showCloseButton = showCloseButton;
}
public String getReturnUrlLocation() {
return returnUrlLocation;
}
public void setReturnUrlLocation(String returnUrlLocation) {
this.returnUrlLocation = returnUrlLocation;
}
public String getDocId() {
return docId;
}
public void setDocId(String docId) {
this.docId = docId;
}
public boolean isShowFutureHasError() {
return !org.apache.commons.lang.StringUtils.isEmpty(getShowFutureError());
}
public String getShowFutureError() {
return showFutureError;
}
public void setShowFutureError(String showFutureError) {
this.showFutureError = showFutureError;
}
public boolean isShowFuture() {
return showFuture;
}
public void setShowFuture(boolean showReportURL) {
this.showFuture = showReportURL;
}
public String getMethodToCall() {
return methodToCall;
}
public void setMethodToCall(String methodToCall) {
this.methodToCall = methodToCall;
}
public String getDocumentId() {
return documentId;
}
public void setDocumentId(String documentId) {
this.documentId = documentId;
}
public int getPendingActionRequestCount() {
return pendingActionRequestCount;
}
public void setPendingActionRequestCount(int pendingActionRequestCount) {
this.pendingActionRequestCount = pendingActionRequestCount;
}
public List getRootRequests() {
return rootRequests;
}
public void setRootRequests(List rootRequests) {
this.rootRequests = rootRequests;
}
public int getFutureActionRequestCount() {
return futureActionRequestCount;
}
public void setFutureActionRequestCount(int futureActionRequestCount) {
this.futureActionRequestCount = futureActionRequestCount;
}
public List getFutureRootRequests() {
return futureRootRequests;
}
public void setFutureRootRequests(List futureRootRequests) {
this.futureRootRequests = futureRootRequests;
}
public boolean isRemoveHeader() {
return removeHeader;
}
public void setRemoveHeader(boolean removeBar) {
this.removeHeader = removeBar;
}
public boolean isLookFuture() {
return lookFuture;
}
public void setLookFuture(boolean showFutureLink) {
this.lookFuture = showFutureLink;
}
public boolean isShowNotes() {
return showNotes;
}
public void setShowNotes(boolean showNotes) {
this.showNotes = showNotes;
}
public String getNewRouteLogActionMessage() {
return this.newRouteLogActionMessage;
}
public void setNewRouteLogActionMessage(String newRouteLogActionMessage) {
this.newRouteLogActionMessage = newRouteLogActionMessage;
}
public boolean isEnableLogAction() {
return this.enableLogAction;
}
public void setEnableLogAction(boolean enableLogAction) {
this.enableLogAction = enableLogAction;
}
public String getHeaderMenuBar() {
Properties parameters = new Properties();
parameters.put("showFuture", isShowFuture());
parameters.put("showNotes", isShowNotes());
if (getDocumentId() != null) {
parameters.put("documentId", getDocumentId());
}
if (getDocId() != null) {
parameters.put("docId", getDocId());
}
if (getReturnUrlLocation() != null) {
parameters.put("backUrl", getReturnUrlLocation());
}
String url = UrlFactory.parameterizeUrl("RouteLog.do", parameters);
String krBaseUrl = ConfigContext.getCurrentContextConfig().getKRBaseURL();
url = "<div class=\"lookupcreatenew\" title=\"Refresh\"><a href=\"" + url + "\"><img src=\""+krBaseUrl+"/images/tinybutton-refresh.gif\" alt=\"refresh\"></a></div>";
return url;
}
}
| apache-2.0 |
fmrsabino/library | src/bftsmart/statemanagement/strategy/durability/StateSender.java | 1549 | /**
Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bftsmart.statemanagement.strategy.durability;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import bftsmart.statemanagement.ApplicationState;
public class StateSender implements Runnable {
private final Socket socket;
private ApplicationState state;
public StateSender(Socket socket) {
this.socket = socket;
}
public void setState(ApplicationState state) {
this.state = state;
}
@Override
public void run() {
try {
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
System.out.print("--- Sending state in different socket");
oos.writeObject(state);
System.out.print("--- Sent state in different socket");
oos.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| apache-2.0 |
sduskis/cloud-bigtable-client | bigtable-client-core-parent/bigtable-hbase-integration-tests-common/src/test/java/com/google/cloud/bigtable/hbase/AbstractTestCreateTable.java | 12618 | /*
* Copyright 2018 Google LLC 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.google.cloud.bigtable.hbase;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.TableExistsException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public abstract class AbstractTestCreateTable extends AbstractTest {
/**
* This variable ensures that
*
* <pre>testTableNames()</pre>
*
* only runs once even if there are many subclasses of AbstractTestCreateTable. HBase 2 will
* likely have 3+ subclasses, but
*
* <pre>testTableNames()</pre>
*
* should still run only once.
*
* <pre>testTableNames()</pre>
*
* is more about a test of Cloud Bigtable than any specific client implementation.
*/
private static final AtomicInteger testTableNames_Counter = new AtomicInteger();
@Rule public ExpectedException thrown = ExpectedException.none();
@Test
public void testCreate() throws Exception {
TableName tableName = sharedTestEnv.newTestTableName();
createTable(tableName);
Assert.assertTrue(tableExists(tableName));
deleteTable(tableName);
Assert.assertFalse(tableExists(tableName));
}
/** Requirement 1.8 - Table names must match [_a-zA-Z0-9][-_.a-zA-Z0-9]* */
@Test(timeout = 1000l * 60 * 4)
public void testTableNames() throws Exception {
String shouldTest = System.getProperty("bigtable.test.create.table", "true");
if (!"true".equals(shouldTest) || testTableNames_Counter.incrementAndGet() > 1) {
return;
}
String[] badNames = {
"-x", ".x", "a!", "a@", "a#", "a$", "a%", "a^", "a&", "a*", "a(", "a+", "a=", "a~", "a`",
"a{", "a[", "a|", "a\\", "a/", "a<", "a,", "a?"
};
for (String badName : badNames) {
assertBadTableName(badName);
}
for (int i = 0; i < 20; i++) {
String randomString = RandomStringUtils.random(10, false, false);
if (isBadTableName(randomString)) {
assertBadTableName("a" + randomString);
}
}
// more than one subclass can run at the same time. Ensure that this method is serial.
String[] goodNames = {
"a",
"1",
"_", // Really? Yuck.
"_x",
"a-._5x",
"_a-._5x",
// TODO(sduskis): Join the last 2 strings once the Bigtable backend supports table names
// longer than 50 characters.
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghi",
"jklmnopqrstuvwxyz1234567890_-."
};
final TableName[] tableNames = getConnection().getAdmin().listTableNames();
List<ListenableFuture<Void>> futures = new ArrayList<>();
ListeningExecutorService es = MoreExecutors.listeningDecorator(sharedTestEnv.getExecutor());
for (final String goodName : goodNames) {
futures.add(
es.submit(
new Callable<Void>() {
@Override
public Void call() throws Exception {
createTable(goodName, tableNames);
return null;
}
}));
}
try {
Futures.allAsList(futures).get(3, TimeUnit.MINUTES);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void createTable(String goodName, TableName[] tableNames) throws Exception {
logger.info("Try create table for: %s", goodName);
TableName tableName = TableName.valueOf(goodName);
try {
if (contains(tableNames, tableName)) {
logger.warn("Not creating the table since it exists: %s", tableName);
} else {
logger.info("Do create table for: %s", goodName);
createTable(tableName);
}
} finally {
deleteTable(tableName);
}
}
private boolean contains(TableName[] tableNames, TableName tableNameTocheck) {
for (TableName tableName : tableNames) {
if (tableName.equals(tableNameTocheck)) {
return true;
}
}
return false;
}
private void assertBadTableName(String tableName) {
try {
createTable(TableName.valueOf(tableName));
Assert.fail("Should fail as table name: '" + tableName + "'");
} catch (Exception ex) {
// TODO verify - added RuntimeException check as RandomStringUtils seems to be generating a
// string server side doesn't like
}
}
private static boolean isBadTableName(String tableName) {
byte[] tableChars = tableName.getBytes();
for (byte codePoint : tableChars) {
if (!Character.isAlphabetic(codePoint)) {
return true;
}
}
return false;
}
@Test
public void testSplitKeys() throws Exception {
byte[][] splits =
new byte[][] {
Bytes.toBytes("AAA"), Bytes.toBytes("BBB"), Bytes.toBytes("CCC"),
};
TableName tableName = sharedTestEnv.newTestTableName();
try {
createTable(tableName, splits);
List<HRegionLocation> regions = null;
try (RegionLocator locator = getConnection().getRegionLocator(tableName)) {
regions = locator.getAllRegionLocations();
}
// The number of regions should be the number of splits + 1.
Assert.assertEquals(splits.length + 1, regions.size());
assertSplitsAndRegionsMatch(splits, regions);
} finally {
deleteTable(tableName);
}
}
/**
* Ensures that the requested splits and the actual list of {@link HRegionLocation} are the same.
*/
public static void assertSplitsAndRegionsMatch(byte[][] splits, List<HRegionLocation> regions) {
for (int i = 0; i < regions.size(); i++) {
HRegionLocation region = regions.get(i);
String start_key = Bytes.toString(region.getRegionInfo().getStartKey());
String end_key = Bytes.toString(region.getRegionInfo().getEndKey());
// Check start & end keys vs what was requested.
if (i == 0) {
// First split: the end key must be the first element of splits.
Assert.assertEquals(Bytes.toString(splits[0]), end_key);
} else if (i == regions.size() - 1) {
// Last split: the start key must be the last element of splits.
Assert.assertEquals(Bytes.toString(splits[splits.length - 1]), start_key);
} else {
// For all others: start_key = splits[i-i], end_key = splits[i].
Assert.assertEquals(Bytes.toString(splits[i - 1]), start_key);
Assert.assertEquals(Bytes.toString(splits[i]), end_key);
}
}
}
@Test
public void testEvenSplitKeysFailures() throws Exception {
TableName tableName = sharedTestEnv.newTestTableName();
byte[] startKey = Bytes.toBytes("AAA");
byte[] endKey = Bytes.toBytes("ZZZ");
try {
createTable(tableName, startKey, endKey, 2);
Assert.fail();
} catch (IllegalArgumentException e) {
}
try {
createTable(tableName, endKey, startKey, 5);
Assert.fail();
} catch (IllegalArgumentException e) {
}
}
@Test
public void testThreeRegionSplit() throws Exception {
TableName tableName = sharedTestEnv.newTestTableName();
byte[] startKey = Bytes.toBytes("AAA");
byte[] endKey = Bytes.toBytes("ZZZ");
try {
createTable(tableName, startKey, endKey, 3);
List<HRegionLocation> regions = null;
try (RegionLocator locator = getConnection().getRegionLocator(tableName)) {
regions = locator.getAllRegionLocations();
}
Assert.assertEquals(3, regions.size());
for (int i = 0; i < regions.size(); i++) {
HRegionLocation region = regions.get(i);
String start_key = Bytes.toString(region.getRegionInfo().getStartKey());
String end_key = Bytes.toString(region.getRegionInfo().getEndKey());
// Check start & end keys vs what was requested.
if (i == 0) {
Assert.assertEquals(Bytes.toString(startKey), end_key);
} else if (i == 1) {
Assert.assertEquals(Bytes.toString(startKey), start_key);
Assert.assertEquals(Bytes.toString(endKey), end_key);
} else {
Assert.assertEquals(Bytes.toString(endKey), start_key);
}
}
} finally {
deleteTable(tableName);
}
}
@Test
public void testFiveRegionSplit() throws Exception {
TableName tableName = sharedTestEnv.newTestTableName();
byte[] startKey = Bytes.toBytes("AAA");
byte[] endKey = Bytes.toBytes("ZZZ");
byte[][] splitKeys = Bytes.split(startKey, endKey, 2);
try {
createTable(tableName, startKey, endKey, 5);
List<HRegionLocation> regions = null;
try (RegionLocator locator = getConnection().getRegionLocator(tableName)) {
regions = locator.getAllRegionLocations();
}
// The number of regions should be the number of splits + 1.
Assert.assertEquals(5, regions.size());
for (int i = 0; i < regions.size(); i++) {
HRegionLocation region = regions.get(i);
String start_key = Bytes.toString(region.getRegionInfo().getStartKey());
String end_key = Bytes.toString(region.getRegionInfo().getEndKey());
// Check start & end keys vs what was requested.
if (i == 0) {
// First split: the end key must be the first element of splits.
Assert.assertEquals(Bytes.toString(startKey), end_key);
} else if (i == regions.size() - 1) {
// Last split: the start key must be the last element of splits.
Assert.assertEquals(Bytes.toString(endKey), start_key);
} else {
// For all others: start_key = splits[i-i], end_key = splits[i].
Assert.assertEquals(Bytes.toString(splitKeys[i - 1]), start_key);
Assert.assertEquals(Bytes.toString(splitKeys[i]), end_key);
}
}
} finally {
deleteTable(tableName);
}
}
@Test
public void testAlreadyExists() throws Exception {
thrown.expect(TableExistsException.class);
createTable(sharedTestEnv.getDefaultTableName());
}
protected void deleteTable(TableName tableName) {
try {
if (isTableEnabled(tableName)) {
disableTable(tableName);
}
adminDeleteTable(tableName);
} catch (Throwable t) {
// logger the error and ignore it.
logger.warn("Error cleaning up the table", t);
}
}
@Test
public void testGetRegionLocation() throws Exception {
TableName tableName = sharedTestEnv.newTestTableName();
createTable(tableName);
List<HRegionLocation> regions = getRegions(tableName);
Assert.assertEquals(1, regions.size());
}
@Test
public void testAsyncGetRegions() throws Exception {
TableName tableName = sharedTestEnv.newTestTableName();
createTable(tableName);
Assert.assertEquals(true, asyncGetRegions(tableName));
}
protected abstract void createTable(TableName name) throws Exception;
protected abstract void createTable(TableName name, byte[] start, byte[] end, int splitCount)
throws Exception;
protected abstract void createTable(TableName name, byte[][] ranges) throws Exception;
protected abstract List<HRegionLocation> getRegions(TableName tableName) throws Exception;
protected abstract boolean isTableEnabled(TableName tableName) throws Exception;
protected abstract void disableTable(final TableName tableName) throws Exception;
protected abstract boolean asyncGetRegions(TableName tableName) throws Exception;
protected abstract void adminDeleteTable(final TableName tableName) throws Exception;
protected abstract boolean tableExists(final TableName tableName) throws Exception;
}
| apache-2.0 |
canoo/dolphin-platform | platform/dolphin-platform-remoting-common/src/test/java/com/canoo/dolphin/impl/DolphinUtilsTest.java | 4991 | /*
* Copyright 2015-2018 Canoo Engineering AG.
*
* 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.canoo.dolphin.impl;
import com.canoo.dp.impl.remoting.collections.ObservableArrayList;
import com.canoo.dp.impl.remoting.DolphinUtils;
import com.canoo.dp.impl.remoting.MockedProperty;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.lang.annotation.RetentionPolicy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.Locale;
import java.util.UUID;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
public class DolphinUtilsTest {
@Test
public void testIsAllowedForUnmanaged() {
//Basics
assertTrue(DolphinUtils.isAllowedForUnmanaged(Double.class));
assertTrue(DolphinUtils.isAllowedForUnmanaged(Double.TYPE));
assertTrue(DolphinUtils.isAllowedForUnmanaged(Long.class));
assertTrue(DolphinUtils.isAllowedForUnmanaged(Long.TYPE));
assertTrue(DolphinUtils.isAllowedForUnmanaged(Float.class));
assertTrue(DolphinUtils.isAllowedForUnmanaged(Float.TYPE));
assertTrue(DolphinUtils.isAllowedForUnmanaged(Integer.class));
assertTrue(DolphinUtils.isAllowedForUnmanaged(Integer.TYPE));
assertTrue(DolphinUtils.isAllowedForUnmanaged(Boolean.class));
assertTrue(DolphinUtils.isAllowedForUnmanaged(Boolean.TYPE));
assertTrue(DolphinUtils.isAllowedForUnmanaged(String.class));
//Enum
assertTrue(DolphinUtils.isAllowedForUnmanaged(RetentionPolicy.class));
//Property
assertTrue(DolphinUtils.isAllowedForUnmanaged(MockedProperty.class));
//Other
assertFalse(DolphinUtils.isAllowedForUnmanaged(Date.class));
assertFalse(DolphinUtils.isAllowedForUnmanaged(LocalDateTime.class));
assertFalse(DolphinUtils.isAllowedForUnmanaged(Locale.class));
try {
DolphinUtils.isAllowedForUnmanaged(null);
Assert.fail("Null check not working");
} catch (Exception e) {
}
}
@Test
public void testIsEnumType() throws Exception {
assertTrue(DolphinUtils.isEnumType(DataType.class));
try {
DolphinUtils.isEnumType(null);
Assert.fail("Null check not working");
} catch (Exception e) {
}
}
@Test
public void testIsProperty() throws Exception {
assertTrue(DolphinUtils.isProperty(MockedProperty.class));
try {
DolphinUtils.isProperty((Class<?>) null);
Assert.fail("Null check not working");
} catch (Exception e) {
}
}
@Test
public void testBasicType() throws Exception {
assertTrue(DolphinUtils.isBasicType(String.class));
assertTrue(DolphinUtils.isBasicType(Number.class));
assertTrue(DolphinUtils.isBasicType(Long.class));
assertTrue(DolphinUtils.isBasicType(Integer.class));
assertTrue(DolphinUtils.isBasicType(Double.class));
assertTrue(DolphinUtils.isBasicType(Boolean.class));
assertTrue(DolphinUtils.isBasicType(Byte.class));
assertTrue(DolphinUtils.isBasicType(Short.class));
assertTrue(DolphinUtils.isBasicType(BigDecimal.class));
assertTrue(DolphinUtils.isBasicType(BigInteger.class));
assertTrue(DolphinUtils.isBasicType(Long.TYPE));
assertTrue(DolphinUtils.isBasicType(Integer.TYPE));
assertTrue(DolphinUtils.isBasicType(Double.TYPE));
assertTrue(DolphinUtils.isBasicType(Boolean.TYPE));
assertTrue(DolphinUtils.isBasicType(Byte.TYPE));
assertTrue(DolphinUtils.isBasicType(Short.TYPE));
assertFalse(DolphinUtils.isBasicType(DolphinUtilsTest.class));
assertFalse(DolphinUtils.isBasicType(DataType.class));
assertFalse(DolphinUtils.isBasicType(UUID.class));
try {
DolphinUtils.isBasicType(null);
Assert.fail("Null check not working");
} catch (Exception e) {
}
}
@Test
public void testIsObservableList() {
assertTrue(DolphinUtils.isObservableList(ObservableArrayList.class));
assertFalse(DolphinUtils.isObservableList(LinkedList.class));
try {
DolphinUtils.isObservableList(null);
Assert.fail("Null check not working");
} catch (Exception e) {
}
}
}
| apache-2.0 |
mayonghui2112/helloWorld | sourceCode/testMaven/effective-java-3e-source-code-master/src/main/java/effectivejava/chapter6/item38/ExtendedOperation.java | 1707 | package effectivejava.chapter6.item38;
import java.util.*;
// Emulated extensible enum (Pages 176-9)
public enum ExtendedOperation implements Operation {
EXP("^") {
public double apply(double x, double y) {
return Math.pow(x, y);
}
},
REMAINDER("%") {
public double apply(double x, double y) {
return x % y;
}
};
private final String symbol;
ExtendedOperation(String symbol) {
this.symbol = symbol;
}
@Override public String toString() {
return symbol;
}
// // Using an enum class object to represent a collection of extended enums (page 178)
// public static void main(String[] args) {
// double x = Double.parseDouble(args[0]);
// double y = Double.parseDouble(args[1]);
// test(ExtendedOperation.class, x, y);
// }
// private static <T extends Enum<T> & Operation> void test(
// Class<T> opEnumType, double x, double y) {
// for (Operation op : opEnumType.getEnumConstants())
// System.out.printf("%f %s %f = %f%n",
// x, op, y, op.apply(x, y));
// }
// Using a collection instance to represent a collection of extended enums (page 178)
public static void main(String[] args) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
test(Arrays.asList(ExtendedOperation.values()), x, y);
}
private static void test(Collection<? extends Operation> opSet,
double x, double y) {
for (Operation op : opSet)
System.out.printf("%f %s %f = %f%n",
x, op, y, op.apply(x, y));
}
}
| apache-2.0 |
NiteshKant/RxJava | src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java | 37651 | /**
* Copyright (c) 2016-present, RxJava 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 io.reactivex.internal.operators.observable;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import io.reactivex.*;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.functions.*;
import io.reactivex.internal.disposables.*;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.internal.fuseable.HasUpstreamObservableSource;
import io.reactivex.internal.util.*;
import io.reactivex.observables.ConnectableObservable;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Timed;
public final class ObservableReplay<T> extends ConnectableObservable<T> implements HasUpstreamObservableSource<T>, ResettableConnectable {
/** The source observable. */
final ObservableSource<T> source;
/** Holds the current subscriber that is, will be or just was subscribed to the source observable. */
final AtomicReference<ReplayObserver<T>> current;
/** A factory that creates the appropriate buffer for the ReplayObserver. */
final BufferSupplier<T> bufferFactory;
final ObservableSource<T> onSubscribe;
interface BufferSupplier<T> {
ReplayBuffer<T> call();
}
@SuppressWarnings("rawtypes")
static final BufferSupplier DEFAULT_UNBOUNDED_FACTORY = new UnBoundedFactory();
/**
* Given a connectable observable factory, it multicasts over the generated
* ConnectableObservable via a selector function.
* @param <U> the value type of the ConnectableObservable
* @param <R> the result value type
* @param connectableFactory the factory that returns a ConnectableObservable for each individual subscriber
* @param selector the function that receives an Observable and should return another Observable that will be subscribed to
* @return the new Observable instance
*/
public static <U, R> Observable<R> multicastSelector(
final Callable<? extends ConnectableObservable<U>> connectableFactory,
final Function<? super Observable<U>, ? extends ObservableSource<R>> selector) {
return RxJavaPlugins.onAssembly(new MulticastReplay<R, U>(connectableFactory, selector));
}
/**
* Child Observers will observe the events of the ConnectableObservable on the
* specified scheduler.
* @param <T> the value type
* @param co the connectable observable instance
* @param scheduler the target scheduler
* @return the new ConnectableObservable instance
*/
public static <T> ConnectableObservable<T> observeOn(final ConnectableObservable<T> co, final Scheduler scheduler) {
final Observable<T> observable = co.observeOn(scheduler);
return RxJavaPlugins.onAssembly(new Replay<T>(co, observable));
}
/**
* Creates a replaying ConnectableObservable with an unbounded buffer.
* @param <T> the value type
* @param source the source observable
* @return the new ConnectableObservable instance
*/
@SuppressWarnings("unchecked")
public static <T> ConnectableObservable<T> createFrom(ObservableSource<? extends T> source) {
return create(source, DEFAULT_UNBOUNDED_FACTORY);
}
/**
* Creates a replaying ConnectableObservable with a size bound buffer.
* @param <T> the value type
* @param source the source ObservableSource to use
* @param bufferSize the maximum number of elements to hold
* @return the new ConnectableObservable instance
*/
public static <T> ConnectableObservable<T> create(ObservableSource<T> source,
final int bufferSize) {
if (bufferSize == Integer.MAX_VALUE) {
return createFrom(source);
}
return create(source, new ReplayBufferSupplier<T>(bufferSize));
}
/**
* Creates a replaying ConnectableObservable with a time bound buffer.
* @param <T> the value type
* @param source the source ObservableSource to use
* @param maxAge the maximum age of entries
* @param unit the unit of measure of the age amount
* @param scheduler the target scheduler providing the current time
* @return the new ConnectableObservable instance
*/
public static <T> ConnectableObservable<T> create(ObservableSource<T> source,
long maxAge, TimeUnit unit, Scheduler scheduler) {
return create(source, maxAge, unit, scheduler, Integer.MAX_VALUE);
}
/**
* Creates a replaying ConnectableObservable with a size and time bound buffer.
* @param <T> the value type
* @param source the source ObservableSource to use
* @param maxAge the maximum age of entries
* @param unit the unit of measure of the age amount
* @param scheduler the target scheduler providing the current time
* @param bufferSize the maximum number of elements to hold
* @return the new ConnectableObservable instance
*/
public static <T> ConnectableObservable<T> create(ObservableSource<T> source,
final long maxAge, final TimeUnit unit, final Scheduler scheduler, final int bufferSize) {
return create(source, new ScheduledReplaySupplier<T>(bufferSize, maxAge, unit, scheduler));
}
/**
* Creates a OperatorReplay instance to replay values of the given source observable.
* @param source the source observable
* @param bufferFactory the factory to instantiate the appropriate buffer when the observable becomes active
* @return the connectable observable
*/
static <T> ConnectableObservable<T> create(ObservableSource<T> source,
final BufferSupplier<T> bufferFactory) {
// the current connection to source needs to be shared between the operator and its onSubscribe call
final AtomicReference<ReplayObserver<T>> curr = new AtomicReference<ReplayObserver<T>>();
ObservableSource<T> onSubscribe = new ReplaySource<T>(curr, bufferFactory);
return RxJavaPlugins.onAssembly(new ObservableReplay<T>(onSubscribe, source, curr, bufferFactory));
}
private ObservableReplay(ObservableSource<T> onSubscribe, ObservableSource<T> source,
final AtomicReference<ReplayObserver<T>> current,
final BufferSupplier<T> bufferFactory) {
this.onSubscribe = onSubscribe;
this.source = source;
this.current = current;
this.bufferFactory = bufferFactory;
}
@Override
public ObservableSource<T> source() {
return source;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void resetIf(Disposable connectionObject) {
current.compareAndSet((ReplayObserver)connectionObject, null);
}
@Override
protected void subscribeActual(Observer<? super T> observer) {
onSubscribe.subscribe(observer);
}
@Override
public void connect(Consumer<? super Disposable> connection) {
boolean doConnect;
ReplayObserver<T> ps;
// we loop because concurrent connect/disconnect and termination may change the state
for (;;) {
// retrieve the current subscriber-to-source instance
ps = current.get();
// if there is none yet or the current has been disposed
if (ps == null || ps.isDisposed()) {
// create a new subscriber-to-source
ReplayBuffer<T> buf = bufferFactory.call();
ReplayObserver<T> u = new ReplayObserver<T>(buf);
// try setting it as the current subscriber-to-source
if (!current.compareAndSet(ps, u)) {
// did not work, perhaps a new subscriber arrived
// and created a new subscriber-to-source as well, retry
continue;
}
ps = u;
}
// if connect() was called concurrently, only one of them should actually
// connect to the source
doConnect = !ps.shouldConnect.get() && ps.shouldConnect.compareAndSet(false, true);
break; // NOPMD
}
/*
* Notify the callback that we have a (new) connection which it can dispose
* but since ps is unique to a connection, multiple calls to connect() will return the
* same Disposable and even if there was a connect-disconnect-connect pair, the older
* references won't disconnect the newer connection.
* Synchronous source consumers have the opportunity to disconnect via dispose() on the
* Disposable as subscribe() may never return in its own.
*
* Note however, that asynchronously disconnecting a running source might leave
* child observers without any terminal event; ReplaySubject does not have this
* issue because the dispose() call was always triggered by the child observers
* themselves.
*/
try {
connection.accept(ps);
} catch (Throwable ex) {
if (doConnect) {
ps.shouldConnect.compareAndSet(true, false);
}
Exceptions.throwIfFatal(ex);
throw ExceptionHelper.wrapOrThrow(ex);
}
if (doConnect) {
source.subscribe(ps);
}
}
@SuppressWarnings("rawtypes")
static final class ReplayObserver<T>
extends AtomicReference<Disposable>
implements Observer<T>, Disposable {
private static final long serialVersionUID = -533785617179540163L;
/** Holds notifications from upstream. */
final ReplayBuffer<T> buffer;
/** Indicates this Observer received a terminal event. */
boolean done;
/** Indicates an empty array of inner observers. */
static final InnerDisposable[] EMPTY = new InnerDisposable[0];
/** Indicates a terminated ReplayObserver. */
static final InnerDisposable[] TERMINATED = new InnerDisposable[0];
/** Tracks the subscribed observers. */
final AtomicReference<InnerDisposable[]> observers;
/**
* Atomically changed from false to true by connect to make sure the
* connection is only performed by one thread.
*/
final AtomicBoolean shouldConnect;
ReplayObserver(ReplayBuffer<T> buffer) {
this.buffer = buffer;
this.observers = new AtomicReference<InnerDisposable[]>(EMPTY);
this.shouldConnect = new AtomicBoolean();
}
@Override
public boolean isDisposed() {
return observers.get() == TERMINATED;
}
@Override
public void dispose() {
observers.set(TERMINATED);
// unlike OperatorPublish, we can't null out the terminated so
// late observers can still get replay
// current.compareAndSet(ReplayObserver.this, null);
// we don't care if it fails because it means the current has
// been replaced in the meantime
DisposableHelper.dispose(this);
}
/**
* Atomically try adding a new InnerDisposable to this Observer or return false if this
* Observer was terminated.
* @param producer the producer to add
* @return true if succeeded, false otherwise
*/
boolean add(InnerDisposable<T> producer) {
// the state can change so we do a CAS loop to achieve atomicity
for (;;) {
// get the current producer array
InnerDisposable[] c = observers.get();
// if this subscriber-to-source reached a terminal state by receiving
// an onError or onComplete, just refuse to add the new producer
if (c == TERMINATED) {
return false;
}
// we perform a copy-on-write logic
int len = c.length;
InnerDisposable[] u = new InnerDisposable[len + 1];
System.arraycopy(c, 0, u, 0, len);
u[len] = producer;
// try setting the observers array
if (observers.compareAndSet(c, u)) {
return true;
}
// if failed, some other operation succeeded (another add, remove or termination)
// so retry
}
}
/**
* Atomically removes the given InnerDisposable from the observers array.
* @param producer the producer to remove
*/
void remove(InnerDisposable<T> producer) {
// the state can change so we do a CAS loop to achieve atomicity
for (;;) {
// let's read the current observers array
InnerDisposable[] c = observers.get();
int len = c.length;
// if it is either empty or terminated, there is nothing to remove so we quit
if (len == 0) {
return;
}
// let's find the supplied producer in the array
// although this is O(n), we don't expect too many child observers in general
int j = -1;
for (int i = 0; i < len; i++) {
if (c[i].equals(producer)) {
j = i;
break;
}
}
// we didn't find it so just quit
if (j < 0) {
return;
}
// we do copy-on-write logic here
InnerDisposable[] u;
// we don't create a new empty array if producer was the single inhabitant
// but rather reuse an empty array
if (len == 1) {
u = EMPTY;
} else {
// otherwise, create a new array one less in size
u = new InnerDisposable[len - 1];
// copy elements being before the given producer
System.arraycopy(c, 0, u, 0, j);
// copy elements being after the given producer
System.arraycopy(c, j + 1, u, j, len - j - 1);
}
// try setting this new array as
if (observers.compareAndSet(c, u)) {
return;
}
// if we failed, it means something else happened
// (a concurrent add/remove or termination), we need to retry
}
}
@Override
public void onSubscribe(Disposable p) {
if (DisposableHelper.setOnce(this, p)) {
replay();
}
}
@Override
public void onNext(T t) {
if (!done) {
buffer.next(t);
replay();
}
}
@Override
public void onError(Throwable e) {
// The observer front is accessed serially as required by spec so
// no need to CAS in the terminal value
if (!done) {
done = true;
buffer.error(e);
replayFinal();
} else {
RxJavaPlugins.onError(e);
}
}
@Override
public void onComplete() {
// The observer front is accessed serially as required by spec so
// no need to CAS in the terminal value
if (!done) {
done = true;
buffer.complete();
replayFinal();
}
}
/**
* Tries to replay the buffer contents to all known observers.
*/
void replay() {
@SuppressWarnings("unchecked")
InnerDisposable<T>[] a = observers.get();
for (InnerDisposable<T> rp : a) {
buffer.replay(rp);
}
}
/**
* Tries to replay the buffer contents to all known observers.
*/
void replayFinal() {
@SuppressWarnings("unchecked")
InnerDisposable<T>[] a = observers.getAndSet(TERMINATED);
for (InnerDisposable<T> rp : a) {
buffer.replay(rp);
}
}
}
/**
* A Disposable that manages the disposed state of a
* child Observer in thread-safe manner.
* @param <T> the value type
*/
static final class InnerDisposable<T>
extends AtomicInteger
implements Disposable {
private static final long serialVersionUID = 2728361546769921047L;
/**
* The parent subscriber-to-source used to allow removing the child in case of
* child dispose() call.
*/
final ReplayObserver<T> parent;
/** The actual child subscriber. */
final Observer<? super T> child;
/**
* Holds an object that represents the current location in the buffer.
* Guarded by the emitter loop.
*/
Object index;
volatile boolean cancelled;
InnerDisposable(ReplayObserver<T> parent, Observer<? super T> child) {
this.parent = parent;
this.child = child;
}
@Override
public boolean isDisposed() {
return cancelled;
}
@Override
public void dispose() {
if (!cancelled) {
cancelled = true;
// remove this from the parent
parent.remove(this);
// make sure the last known node is not retained
index = null;
}
}
/**
* Convenience method to auto-cast the index object.
* @return the index Object or null
*/
@SuppressWarnings("unchecked")
<U> U index() {
return (U)index;
}
}
/**
* The interface for interacting with various buffering logic.
*
* @param <T> the value type
*/
interface ReplayBuffer<T> {
/**
* Adds a regular value to the buffer.
* @param value the value to be stored in the buffer
*/
void next(T value);
/**
* Adds a terminal exception to the buffer.
* @param e the error to be stored in the buffer
*/
void error(Throwable e);
/**
* Adds a completion event to the buffer.
*/
void complete();
/**
* Tries to replay the buffered values to the
* subscriber inside the output if there
* is new value and requests available at the
* same time.
* @param output the receiver of the buffered events
*/
void replay(InnerDisposable<T> output);
}
/**
* Holds an unbounded list of events.
*
* @param <T> the value type
*/
static final class UnboundedReplayBuffer<T> extends ArrayList<Object> implements ReplayBuffer<T> {
private static final long serialVersionUID = 7063189396499112664L;
/** The total number of events in the buffer. */
volatile int size;
UnboundedReplayBuffer(int capacityHint) {
super(capacityHint);
}
@Override
public void next(T value) {
add(NotificationLite.next(value));
size++;
}
@Override
public void error(Throwable e) {
add(NotificationLite.error(e));
size++;
}
@Override
public void complete() {
add(NotificationLite.complete());
size++;
}
@Override
public void replay(InnerDisposable<T> output) {
if (output.getAndIncrement() != 0) {
return;
}
final Observer<? super T> child = output.child;
int missed = 1;
for (;;) {
if (output.isDisposed()) {
return;
}
int sourceIndex = size;
Integer destinationIndexObject = output.index();
int destinationIndex = destinationIndexObject != null ? destinationIndexObject : 0;
while (destinationIndex < sourceIndex) {
Object o = get(destinationIndex);
if (NotificationLite.accept(o, child)) {
return;
}
if (output.isDisposed()) {
return;
}
destinationIndex++;
}
output.index = destinationIndex;
missed = output.addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
}
/**
* Represents a node in a bounded replay buffer's linked list.
*/
static final class Node extends AtomicReference<Node> {
private static final long serialVersionUID = 245354315435971818L;
final Object value;
Node(Object value) {
this.value = value;
}
}
/**
* Base class for bounded buffering with options to specify an
* enter and leave transforms and custom truncation behavior.
*
* @param <T> the value type
*/
abstract static class BoundedReplayBuffer<T> extends AtomicReference<Node> implements ReplayBuffer<T> {
private static final long serialVersionUID = 2346567790059478686L;
Node tail;
int size;
BoundedReplayBuffer() {
Node n = new Node(null);
tail = n;
set(n);
}
/**
* Add a new node to the linked list.
* @param n the Node instance to add as last
*/
final void addLast(Node n) {
tail.set(n);
tail = n;
size++;
}
/**
* Remove the first node from the linked list.
*/
final void removeFirst() {
Node head = get();
Node next = head.get();
size--;
// can't just move the head because it would retain the very first value
// can't null out the head's value because of late replayers would see null
setFirst(next);
}
final void trimHead() {
Node head = get();
if (head.value != null) {
Node n = new Node(null);
n.lazySet(head.get());
set(n);
}
}
/* test */ final void removeSome(int n) {
Node head = get();
while (n > 0) {
head = head.get();
n--;
size--;
}
setFirst(head);
}
/**
* Arranges the given node is the new head from now on.
* @param n the Node instance to set as first
*/
final void setFirst(Node n) {
set(n);
}
@Override
public final void next(T value) {
Object o = enterTransform(NotificationLite.next(value));
Node n = new Node(o);
addLast(n);
truncate();
}
@Override
public final void error(Throwable e) {
Object o = enterTransform(NotificationLite.error(e));
Node n = new Node(o);
addLast(n);
truncateFinal();
}
@Override
public final void complete() {
Object o = enterTransform(NotificationLite.complete());
Node n = new Node(o);
addLast(n);
truncateFinal();
}
@Override
public final void replay(InnerDisposable<T> output) {
if (output.getAndIncrement() != 0) {
return;
}
int missed = 1;
for (;;) {
Node node = output.index();
if (node == null) {
node = getHead();
output.index = node;
}
for (;;) {
if (output.isDisposed()) {
output.index = null;
return;
}
Node v = node.get();
if (v != null) {
Object o = leaveTransform(v.value);
if (NotificationLite.accept(o, output.child)) {
output.index = null;
return;
}
node = v;
} else {
break;
}
}
output.index = node;
missed = output.addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
/**
* Override this to wrap the NotificationLite object into a
* container to be used later by truncate.
* @param value the value to transform into the internal representation
* @return the transformed value
*/
Object enterTransform(Object value) {
return value;
}
/**
* Override this to unwrap the transformed value into a
* NotificationLite object.
* @param value the value in the internal representation to transform
* @return the transformed value
*/
Object leaveTransform(Object value) {
return value;
}
/**
* Override this method to truncate a non-terminated buffer
* based on its current properties.
*/
abstract void truncate();
/**
* Override this method to truncate a terminated buffer
* based on its properties (i.e., truncate but the very last node).
*/
void truncateFinal() {
trimHead();
}
/* test */ final void collect(Collection<? super T> output) {
Node n = getHead();
for (;;) {
Node next = n.get();
if (next != null) {
Object o = next.value;
Object v = leaveTransform(o);
if (NotificationLite.isComplete(v) || NotificationLite.isError(v)) {
break;
}
output.add(NotificationLite.<T>getValue(v));
n = next;
} else {
break;
}
}
}
/* test */ boolean hasError() {
return tail.value != null && NotificationLite.isError(leaveTransform(tail.value));
}
/* test */ boolean hasCompleted() {
return tail.value != null && NotificationLite.isComplete(leaveTransform(tail.value));
}
Node getHead() {
return get();
}
}
/**
* A bounded replay buffer implementation with size limit only.
*
* @param <T> the value type
*/
static final class SizeBoundReplayBuffer<T> extends BoundedReplayBuffer<T> {
private static final long serialVersionUID = -5898283885385201806L;
final int limit;
SizeBoundReplayBuffer(int limit) {
this.limit = limit;
}
@Override
void truncate() {
// overflow can be at most one element
if (size > limit) {
removeFirst();
}
}
// no need for final truncation because values are truncated one by one
}
/**
* Size and time bound replay buffer.
*
* @param <T> the buffered value type
*/
static final class SizeAndTimeBoundReplayBuffer<T> extends BoundedReplayBuffer<T> {
private static final long serialVersionUID = 3457957419649567404L;
final Scheduler scheduler;
final long maxAge;
final TimeUnit unit;
final int limit;
SizeAndTimeBoundReplayBuffer(int limit, long maxAge, TimeUnit unit, Scheduler scheduler) {
this.scheduler = scheduler;
this.limit = limit;
this.maxAge = maxAge;
this.unit = unit;
}
@Override
Object enterTransform(Object value) {
return new Timed<Object>(value, scheduler.now(unit), unit);
}
@Override
Object leaveTransform(Object value) {
return ((Timed<?>)value).value();
}
@Override
void truncate() {
long timeLimit = scheduler.now(unit) - maxAge;
Node prev = get();
Node next = prev.get();
int e = 0;
for (;;) {
if (next != null) {
if (size > limit) {
e++;
size--;
prev = next;
next = next.get();
} else {
Timed<?> v = (Timed<?>)next.value;
if (v.time() <= timeLimit) {
e++;
size--;
prev = next;
next = next.get();
} else {
break;
}
}
} else {
break;
}
}
if (e != 0) {
setFirst(prev);
}
}
@Override
void truncateFinal() {
long timeLimit = scheduler.now(unit) - maxAge;
Node prev = get();
Node next = prev.get();
int e = 0;
for (;;) {
if (next != null && size > 1) {
Timed<?> v = (Timed<?>)next.value;
if (v.time() <= timeLimit) {
e++;
size--;
prev = next;
next = next.get();
} else {
break;
}
} else {
break;
}
}
if (e != 0) {
setFirst(prev);
}
}
@Override
Node getHead() {
long timeLimit = scheduler.now(unit) - maxAge;
Node prev = get();
Node next = prev.get();
for (;;) {
if (next == null) {
break;
}
Timed<?> v = (Timed<?>)next.value;
if (NotificationLite.isComplete(v.value()) || NotificationLite.isError(v.value())) {
break;
}
if (v.time() <= timeLimit) {
prev = next;
next = next.get();
} else {
break;
}
}
return prev;
}
}
static final class UnBoundedFactory implements BufferSupplier<Object> {
@Override
public ReplayBuffer<Object> call() {
return new UnboundedReplayBuffer<Object>(16);
}
}
static final class DisposeConsumer<R> implements Consumer<Disposable> {
private final ObserverResourceWrapper<R> srw;
DisposeConsumer(ObserverResourceWrapper<R> srw) {
this.srw = srw;
}
@Override
public void accept(Disposable r) {
srw.setResource(r);
}
}
static final class ReplayBufferSupplier<T> implements BufferSupplier<T> {
private final int bufferSize;
ReplayBufferSupplier(int bufferSize) {
this.bufferSize = bufferSize;
}
@Override
public ReplayBuffer<T> call() {
return new SizeBoundReplayBuffer<T>(bufferSize);
}
}
static final class ScheduledReplaySupplier<T> implements BufferSupplier<T> {
private final int bufferSize;
private final long maxAge;
private final TimeUnit unit;
private final Scheduler scheduler;
ScheduledReplaySupplier(int bufferSize, long maxAge, TimeUnit unit, Scheduler scheduler) {
this.bufferSize = bufferSize;
this.maxAge = maxAge;
this.unit = unit;
this.scheduler = scheduler;
}
@Override
public ReplayBuffer<T> call() {
return new SizeAndTimeBoundReplayBuffer<T>(bufferSize, maxAge, unit, scheduler);
}
}
static final class ReplaySource<T> implements ObservableSource<T> {
private final AtomicReference<ReplayObserver<T>> curr;
private final BufferSupplier<T> bufferFactory;
ReplaySource(AtomicReference<ReplayObserver<T>> curr, BufferSupplier<T> bufferFactory) {
this.curr = curr;
this.bufferFactory = bufferFactory;
}
@Override
public void subscribe(Observer<? super T> child) {
// concurrent connection/disconnection may change the state,
// we loop to be atomic while the child subscribes
for (;;) {
// get the current subscriber-to-source
ReplayObserver<T> r = curr.get();
// if there isn't one
if (r == null) {
// create a new subscriber to source
ReplayBuffer<T> buf = bufferFactory.call();
ReplayObserver<T> u = new ReplayObserver<T>(buf);
// let's try setting it as the current subscriber-to-source
if (!curr.compareAndSet(null, u)) {
// didn't work, maybe someone else did it or the current subscriber
// to source has just finished
continue;
}
// we won, let's use it going onwards
r = u;
}
// create the backpressure-managing producer for this child
InnerDisposable<T> inner = new InnerDisposable<T>(r, child);
// the producer has been registered with the current subscriber-to-source so
// at least it will receive the next terminal event
// setting the producer will trigger the first request to be considered by
// the subscriber-to-source.
child.onSubscribe(inner);
// we try to add it to the array of observers
// if it fails, no worries because we will still have its buffer
// so it is going to replay it for us
r.add(inner);
if (inner.isDisposed()) {
r.remove(inner);
return;
}
// replay the contents of the buffer
r.buffer.replay(inner);
break; // NOPMD
}
}
}
static final class MulticastReplay<R, U> extends Observable<R> {
private final Callable<? extends ConnectableObservable<U>> connectableFactory;
private final Function<? super Observable<U>, ? extends ObservableSource<R>> selector;
MulticastReplay(Callable<? extends ConnectableObservable<U>> connectableFactory, Function<? super Observable<U>, ? extends ObservableSource<R>> selector) {
this.connectableFactory = connectableFactory;
this.selector = selector;
}
@Override
protected void subscribeActual(Observer<? super R> child) {
ConnectableObservable<U> co;
ObservableSource<R> observable;
try {
co = ObjectHelper.requireNonNull(connectableFactory.call(), "The connectableFactory returned a null ConnectableObservable");
observable = ObjectHelper.requireNonNull(selector.apply(co), "The selector returned a null ObservableSource");
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
EmptyDisposable.error(e, child);
return;
}
final ObserverResourceWrapper<R> srw = new ObserverResourceWrapper<R>(child);
observable.subscribe(srw);
co.connect(new DisposeConsumer<R>(srw));
}
}
static final class Replay<T> extends ConnectableObservable<T> {
private final ConnectableObservable<T> co;
private final Observable<T> observable;
Replay(ConnectableObservable<T> co, Observable<T> observable) {
this.co = co;
this.observable = observable;
}
@Override
public void connect(Consumer<? super Disposable> connection) {
co.connect(connection);
}
@Override
protected void subscribeActual(Observer<? super T> observer) {
observable.subscribe(observer);
}
}
}
| apache-2.0 |
eswdd/disco | disco-test/disco-normal-code-tests/src/test/java/uk/co/exemel/disco/tests/updatedcomponenttests/responsetypes/soap/SOAPMapResponseSimpleMapDuplicateKeyTest.java | 3430 | /*
* Copyright 2013, The Sporting Exchange Limited
* Copyright 2014, Simon Matić Langford
*
* 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.
*/
// Originally from UpdatedComponentTests/ResponseTypes/SOAP/SOAP_MapResponse_SimpleMap_DuplicateKey.xls;
package uk.co.exemel.disco.tests.updatedcomponenttests.responsetypes.soap;
import uk.co.exemel.testing.utils.disco.misc.XMLHelpers;
import uk.co.exemel.testing.utils.disco.assertions.AssertionUtils;
import uk.co.exemel.testing.utils.disco.beans.HttpCallBean;
import uk.co.exemel.testing.utils.disco.beans.HttpResponseBean;
import uk.co.exemel.testing.utils.disco.enums.DiscoMessageProtocolResponseTypeEnum;
import uk.co.exemel.testing.utils.disco.manager.DiscoManager;
import uk.co.exemel.testing.utils.disco.manager.RequestLogRequirement;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import java.sql.Timestamp;
/**
* Test that when SOAP request operation is performed against Disco, passing in a Map with a duplicate key, it is correctly processed and the correct response map is returned.
*/
public class SOAPMapResponseSimpleMapDuplicateKeyTest {
@Test
public void doTest() throws Exception {
XMLHelpers xMLHelpers1 = new XMLHelpers();
Document createAsDocument1 = xMLHelpers1.getXMLObjectFromString("<TestSimpleMapGetRequest><inputMap><entry key=\"aaa\"><String>First Value for aaa</String></entry><entry key=\"aaa\"><String>Second Value for aaa</String></entry><entry key=\"bbb\"><String>Value for bbb</String></entry><entry key=\"ccc\"><String>Value for ccc</String></entry></inputMap></TestSimpleMapGetRequest>");
DiscoManager discoManager2 = DiscoManager.getInstance();
HttpCallBean getNewHttpCallBean2 = discoManager2.getNewHttpCallBean("87.248.113.14");
discoManager2 = discoManager2;
getNewHttpCallBean2.setServiceName("Baseline", "discoBaseline");
getNewHttpCallBean2.setVersion("v2");
getNewHttpCallBean2.setPostObjectForRequestType(createAsDocument1, "SOAP");
Timestamp getTimeAsTimeStamp7 = new Timestamp(System.currentTimeMillis());
discoManager2.makeSoapDiscoHTTPCalls(getNewHttpCallBean2);
XMLHelpers xMLHelpers4 = new XMLHelpers();
Document createAsDocument9 = xMLHelpers4.getXMLObjectFromString("<response><entry key=\"aaa\"><String>Second Value for aaa</String></entry><entry key=\"ccc\"><String>Value for ccc</String></entry><entry key=\"bbb\"><String>Value for bbb</String></entry></response>");
HttpResponseBean response5 = getNewHttpCallBean2.getResponseObjectsByEnum(DiscoMessageProtocolResponseTypeEnum.SOAP);
AssertionUtils.multiAssertEquals(createAsDocument9, response5.getResponseObject());
// generalHelpers.pauseTest(2000L);
discoManager2.verifyRequestLogEntriesAfterDate(getTimeAsTimeStamp7, new RequestLogRequirement("2.8", "testSimpleMapGet") );
}
}
| apache-2.0 |
1032262055/coolweather | app/src/main/java/android/coolweather/com/coolweather/db/Province.java | 853 | package android.coolweather.com.coolweather.db;
import org.litepal.crud.DataSupport;
/**
* Created by asus on 2017/6/6.
*
*/
public class Province extends DataSupport {
private int id;
private String provinceName;//记录省的名字
private int provinceCode;//记录省的代号
public String getProvinceName() {
return provinceName;
}
public int getId() {
return id;
}
public int getProvinceCode() {
return provinceCode;
}
public void setId(int id) {
this.id = id;
}
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
public void setProvinceCode(int provinceCode) {
this.provinceCode = provinceCode;
}
@Override
public synchronized boolean save() {
return super.save();
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-elasticbeanstalk/src/main/java/com/amazonaws/services/elasticbeanstalk/model/UpdateApplicationResourceLifecycleRequest.java | 5611 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.elasticbeanstalk.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/UpdateApplicationResourceLifecycle"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateApplicationResourceLifecycleRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the application.
* </p>
*/
private String applicationName;
/**
* <p>
* The lifecycle configuration.
* </p>
*/
private ApplicationResourceLifecycleConfig resourceLifecycleConfig;
/**
* <p>
* The name of the application.
* </p>
*
* @param applicationName
* The name of the application.
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
/**
* <p>
* The name of the application.
* </p>
*
* @return The name of the application.
*/
public String getApplicationName() {
return this.applicationName;
}
/**
* <p>
* The name of the application.
* </p>
*
* @param applicationName
* The name of the application.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateApplicationResourceLifecycleRequest withApplicationName(String applicationName) {
setApplicationName(applicationName);
return this;
}
/**
* <p>
* The lifecycle configuration.
* </p>
*
* @param resourceLifecycleConfig
* The lifecycle configuration.
*/
public void setResourceLifecycleConfig(ApplicationResourceLifecycleConfig resourceLifecycleConfig) {
this.resourceLifecycleConfig = resourceLifecycleConfig;
}
/**
* <p>
* The lifecycle configuration.
* </p>
*
* @return The lifecycle configuration.
*/
public ApplicationResourceLifecycleConfig getResourceLifecycleConfig() {
return this.resourceLifecycleConfig;
}
/**
* <p>
* The lifecycle configuration.
* </p>
*
* @param resourceLifecycleConfig
* The lifecycle configuration.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateApplicationResourceLifecycleRequest withResourceLifecycleConfig(ApplicationResourceLifecycleConfig resourceLifecycleConfig) {
setResourceLifecycleConfig(resourceLifecycleConfig);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getApplicationName() != null)
sb.append("ApplicationName: ").append(getApplicationName()).append(",");
if (getResourceLifecycleConfig() != null)
sb.append("ResourceLifecycleConfig: ").append(getResourceLifecycleConfig());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateApplicationResourceLifecycleRequest == false)
return false;
UpdateApplicationResourceLifecycleRequest other = (UpdateApplicationResourceLifecycleRequest) obj;
if (other.getApplicationName() == null ^ this.getApplicationName() == null)
return false;
if (other.getApplicationName() != null && other.getApplicationName().equals(this.getApplicationName()) == false)
return false;
if (other.getResourceLifecycleConfig() == null ^ this.getResourceLifecycleConfig() == null)
return false;
if (other.getResourceLifecycleConfig() != null && other.getResourceLifecycleConfig().equals(this.getResourceLifecycleConfig()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getApplicationName() == null) ? 0 : getApplicationName().hashCode());
hashCode = prime * hashCode + ((getResourceLifecycleConfig() == null) ? 0 : getResourceLifecycleConfig().hashCode());
return hashCode;
}
@Override
public UpdateApplicationResourceLifecycleRequest clone() {
return (UpdateApplicationResourceLifecycleRequest) super.clone();
}
}
| apache-2.0 |
espiegelberg/spring-data-neo4j | spring-data-neo4j/src/test/java/org/springframework/data/neo4j/repository/ContactRepository.java | 182 | package org.springframework.data.neo4j.repository;
/**
* Created by markangrish on 24/03/2017.
*/
public interface ContactRepository extends Neo4jRepository<Contact, String> {
}
| apache-2.0 |
wangruiling/samples | spring/src/main/java/org/wrl/spring/aop/service/impl/HelloworldService.java | 380 | package org.wrl.spring.aop.service.impl;
import org.wrl.spring.aop.service.IHelloWorldService;
/**
* Created with IntelliJ IDEA.
* 定义目标接口实现
* @author: wangrl
* @Date: 2015-11-11 15:47
*/
public class HelloworldService implements IHelloWorldService {
@Override
public void sayHello() {
System.out.println("============Hello World!");
}
}
| apache-2.0 |
Null01/AlgorithmsCompetitiveProgramming | competitive-programming/src/geometry/Circle.java | 336 | package geometry;
public class Circle {
public double h, k, r;
public Circle(double h, double k, double r) {
this.r = r;
this.h = h;
this.k = k;
}
public Circle(Point p, double r) {
this.r = r;
this.h = p.x;
this.k = p.y;
}
public boolean contains(Point p) {
return (new Point(h, k).distance(p) <= this.r);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-kms/src/main/java/com/amazonaws/services/kms/model/transform/ImportKeyMaterialRequestMarshaller.java | 3424 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.kms.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.kms.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* ImportKeyMaterialRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ImportKeyMaterialRequestMarshaller {
private static final MarshallingInfo<String> KEYID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("KeyId").build();
private static final MarshallingInfo<java.nio.ByteBuffer> IMPORTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.BYTE_BUFFER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ImportToken").build();
private static final MarshallingInfo<java.nio.ByteBuffer> ENCRYPTEDKEYMATERIAL_BINDING = MarshallingInfo.builder(MarshallingType.BYTE_BUFFER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EncryptedKeyMaterial").build();
private static final MarshallingInfo<java.util.Date> VALIDTO_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ValidTo").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<String> EXPIRATIONMODEL_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ExpirationModel").build();
private static final ImportKeyMaterialRequestMarshaller instance = new ImportKeyMaterialRequestMarshaller();
public static ImportKeyMaterialRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(ImportKeyMaterialRequest importKeyMaterialRequest, ProtocolMarshaller protocolMarshaller) {
if (importKeyMaterialRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(importKeyMaterialRequest.getKeyId(), KEYID_BINDING);
protocolMarshaller.marshall(importKeyMaterialRequest.getImportToken(), IMPORTTOKEN_BINDING);
protocolMarshaller.marshall(importKeyMaterialRequest.getEncryptedKeyMaterial(), ENCRYPTEDKEYMATERIAL_BINDING);
protocolMarshaller.marshall(importKeyMaterialRequest.getValidTo(), VALIDTO_BINDING);
protocolMarshaller.marshall(importKeyMaterialRequest.getExpirationModel(), EXPIRATIONMODEL_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
quanla/quan-util-core | src/main/java/qj/tool/graph/Node.java | 159 | package qj.tool.graph;
import java.util.Collection;
public class Node <V> {
V val;
Collection<Link<V>> links;
public Node(V val) {
this.val = val;
}
}
| apache-2.0 |
wxb2939/rwxlicai | mzb-phone-app-android/MzbCustomerApp/src/main/java/com/xem/mzbcustomerapp/net/NetCallBack.java | 1803 | package com.xem.mzbcustomerapp.net;
import android.util.Log;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.xem.mzbcustomerapp.view.IProcessDialog;
/**
* Created by xuebing on 15/10/22.
*/
public abstract class NetCallBack extends AsyncHttpResponseHandler {
IProcessDialog showProcess;
public NetCallBack()
{
}
public NetCallBack(IProcessDialog processDialog)
{
showProcess = processDialog;
}
@Override
public void onStart() {
Log.i("info", "请求开始,弹出进度框");
showProcessDialog();
super.onStart();
}
@Override
public void onSuccess(String s) {
Log.i("info", "请求成功,隐藏进度框" + s);
closeProcessDialog();
onMzbSuccess(s);
super.onSuccess(s);
}
@Override
public void onFailure(Throwable throwable, String s) {
Log.i("info", "错误信息:" + s);
closeProcessDialog();
onMzbFailues(throwable);
super.onFailure(throwable);
}
@Override
public void onFailure(Throwable throwable) {
Log.i("info", "网络请求失败,隐藏进度框");
closeProcessDialog();
onMzbFailues(throwable);
super.onFailure(throwable);
}
@Override
public void onFinish() {
Log.i("info", "结束");
super.onFinish();
}
public abstract void onMzbSuccess(String result);
public abstract void onMzbFailues(Throwable arg0);
private void showProcessDialog()
{
if (showProcess != null)
{
showProcess.showProcessDialog();
}
}
private void closeProcessDialog()
{
if (showProcess != null)
{
showProcess.closeProcessDialog();
}
}
}
| apache-2.0 |
llv22/baidu_push_sdk_java | src/main/java/com/baidu/cloud/core/filter/RangeRestrictFilter.java | 403 | package com.baidu.cloud.core.filter;
import java.lang.reflect.Field;
import java.util.Map;
public class RangeRestrictFilter implements IFieldFilter {
@Override
public void validate(Field field, Object obj) {
// TODO Auto-generated method stub
}
@Override
public void mapping(Field field, Object obj, Map<String, String> map) {
// TODO Auto-generated method stub
}
}
| apache-2.0 |
oriley-me/homage | homage-core/src/main/java/me/oriley/homage/utils/ResourceUtils.java | 2204 | /*
* Copyright (C) 2016 Kane O'Riley
*
* 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 me.oriley.homage.utils;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import java.lang.reflect.Field;
import static java.util.Locale.US;
@SuppressWarnings("WeakerAccess")
public final class ResourceUtils {
@SuppressWarnings("unused")
public enum ResourceType {
ANIM, ANIMATOR, BOOL, COLOR, DIMEN, DRAWABLE, ID, INTEGER, LAYOUT, MENU, MIPMAP, RAW, STRING, STYLE, STYLEABLE
}
private static final String TAG = ResourceUtils.class.getSimpleName();
private static final int INVALID = -1;
private ResourceUtils() {
throw new IllegalAccessError("no instances");
}
public static int getResourceId(@NonNull Context context, @NonNull String name, @NonNull ResourceType type) {
String typeName = type.name().toLowerCase(US);
try {
Class resourceClass = Class.forName(context.getPackageName() + ".R$" + typeName);
return getResourceId(name, resourceClass);
} catch (Exception e) {
Log.e(TAG, "Exception reading field " + name + " for type " + typeName, e);
return INVALID;
}
}
public static int getResourceId(@NonNull String name, @NonNull Class<?> resourceClass) {
try {
Field field = resourceClass.getDeclaredField(name);
field.setAccessible(true);
return field.getInt(field);
} catch (Exception e) {
Log.e(TAG, "Exception reading field " + name + " for class " + resourceClass.getName(), e);
return INVALID;
}
}
}
| apache-2.0 |
datazuul/ion-cms-maven | backoffice/src/main/java/org/nextime/ion/backoffice/tree/TreeControlNode.java | 9851 | package org.nextime.ion.backoffice.tree;
import java.io.Serializable;
import java.util.ArrayList;
/**
* <p>
* An individual node of a tree control represented by an instance of <code>TreeControl</code>, and rendered by an
* instance of <code>TreeControlTag</code>.</p>
*
* @author Jazmin Jonson
* @author Craig R. McClanahan
* @version $Revision: 1.1 $ $Date: 2003/04/23 18:55:01 $
*/
public class TreeControlNode implements Serializable {
// ----------------------------------------------------------- Constructors
/**
* Construct a new TreeControlNode with the specified parameters.
*
* @param name Internal name of this node (must be unique within the entire tree)
* @param icon Pathname of the image file for the icon to be displayed when this node is visible, relative to the
* image directory for our images
* @param label The label that will be displayed to the user if this node is visible
* @param action The hyperlink to be selected if the user selects this node, or <code>null</code> if this node's
* label should not be a hyperlink
* @param target The window target in which the <code>action</code> hyperlink's results will be displayed, or
* <code>null</code> for the current window
* @param expanded Should this node be expanded?
*/
public TreeControlNode(
String name,
String icon,
String label,
String action,
String target,
boolean expanded) {
super();
this.name = name;
this.icon = icon;
this.label = label;
this.action = action;
this.target = target;
this.expanded = expanded;
}
// ----------------------------------------------------- Instance Variables
/**
* The set of child <code>TreeControlNodes</code> for this node, in the order that they should be displayed.
*/
protected ArrayList children = new ArrayList();
// ------------------------------------------------------------- Properties
/**
* The hyperlink to which control will be directed if this node is selected by the user.
*/
protected String action = null;
public String getAction() {
return (this.action);
}
/**
* Is this node currently expanded?
*/
protected boolean expanded = false;
public boolean isExpanded() {
return (this.expanded);
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
/**
* The pathname to the icon file displayed when this node is visible, relative to the image directory for our
* images.
*/
protected String icon = null;
public String getIcon() {
return (this.icon);
}
/**
* The label that will be displayed when this node is visible.
*/
protected String label = null;
public String getLabel() {
return (this.label);
}
/**
* Is this the last node in the set of children for our parent node?
*/
protected boolean last = false;
public boolean isLast() {
return (this.last);
}
void setLast(boolean last) {
this.last = last;
}
/**
* Is this a "leaf" node (i.e. one with no children)?
*/
public boolean isLeaf() {
synchronized (children) {
return (children.size() < 1);
}
}
public void up() {
TreeControlNode parent = getParent();
ArrayList brothers = parent.children;
int myIndex = brothers.indexOf(this);
if (myIndex < brothers.size() - 1) {
TreeControlNode nextOne
= (TreeControlNode) brothers.get(myIndex + 1);
brothers.set(myIndex, nextOne);
brothers.set(myIndex + 1, this);
}
rebuildLast(brothers);
}
protected void rebuildLast(ArrayList nodes) {
for (int i = 1; i <= nodes.size(); i++) {
TreeControlNode node = (TreeControlNode) nodes.get(i - 1);
if (i == nodes.size()) {
node.setLast(true);
} else {
node.setLast(false);
}
}
}
public void rebuildLast() {
ArrayList brothers = parent.children;
rebuildLast(brothers);
}
public void rebuildLastChildren() {
ArrayList brothers = children;
rebuildLast(brothers);
}
public void down() {
TreeControlNode parent = getParent();
ArrayList brothers = parent.children;
int myIndex = brothers.indexOf(this);
if (myIndex > 0) {
TreeControlNode nextOne
= (TreeControlNode) brothers.get(myIndex - 1);
brothers.set(myIndex, nextOne);
brothers.set(myIndex - 1, this);
}
rebuildLast(brothers);
}
/**
* The unique (within the entire tree) name of this node.
*/
protected String name = null;
public String getName() {
return (this.name);
}
/**
* The parent node of this node, or <code>null</code> if this is the root node.
*/
protected TreeControlNode parent = null;
public TreeControlNode getParent() {
return (this.parent);
}
void setParent(TreeControlNode parent) {
this.parent = parent;
if (parent == null) {
width = 1;
} else {
width = parent.getWidth() + 1;
}
}
/**
* Is this node currently selected?
*/
protected boolean selected = false;
public boolean isSelected() {
return (this.selected);
}
public void setSelected(boolean selected) {
this.selected = selected;
}
/**
* The window target for the hyperlink identified by the <code>action</code> property, if this node is selected by
* the user.
*/
protected String target = null;
public String getTarget() {
return (this.target);
}
/**
* The <code>TreeControl</code> instance representing the entire tree.
*/
protected TreeControl tree = null;
public TreeControl getTree() {
return (this.tree);
}
void setTree(TreeControl tree) {
this.tree = tree;
}
/**
* The display width necessary to display this item (if it is visible). If this item is not visible, the calculated
* width will be that of our most immediately visible parent.
*/
protected int width = 0;
public int getWidth() {
return (this.width);
}
// --------------------------------------------------------- Public Methods
/**
* Add a new child node to the end of the list.
*
* @param child The new child node
*
* @exception IllegalArgumentException if the name of the new child node is not unique
*/
public void addChild(TreeControlNode child)
throws IllegalArgumentException {
tree.addNode(child);
child.setParent(this);
synchronized (children) {
int n = children.size();
if (n > 0) {
TreeControlNode node = (TreeControlNode) children.get(n - 1);
node.setLast(false);
}
child.setLast(true);
children.add(child);
}
}
/**
* Add a new child node at the specified position in the child list.
*
* @param offset Zero-relative offset at which the new node should be inserted
* @param child The new child node
*
* @exception IllegalArgumentException if the name of the new child node is not unique
*/
public void addChild(int offset, TreeControlNode child)
throws IllegalArgumentException {
tree.addNode(child);
child.setParent(this);
synchronized (children) {
children.add(offset, child);
}
}
/**
* Return the set of child nodes for this node.
*/
public TreeControlNode[] findChildren() {
synchronized (children) {
TreeControlNode results[] = new TreeControlNode[children.size()];
return ((TreeControlNode[]) children.toArray(results));
}
}
/**
* Remove this node from the tree.
*/
public void remove() {
if (tree != null) {
tree.removeNode(this);
}
}
/**
* Remove the child node (and all children of that child) at the specified position in the child list.
*
* @param offset Zero-relative offset at which the existing node should be removed
*/
public void removeChild(int offset) {
synchronized (children) {
TreeControlNode child = (TreeControlNode) children.get(offset);
tree.removeNode(child);
child.setParent(null);
children.remove(offset);
}
}
// -------------------------------------------------------- Package Methods
/**
* Remove the specified child node. It is assumed that all of the children of this child node have already been
* removed.
*
* @param child Child node to be removed
*/
void removeChild(TreeControlNode child) {
if (child == null) {
return;
}
synchronized (children) {
int n = children.size();
for (int i = 0; i < n; i++) {
if (child == (TreeControlNode) children.get(i)) {
children.remove(i);
return;
}
}
}
}
/**
* Sets the label.
*
* @param label The label to set
*/
public void setLabel(String label) {
this.label = label;
}
/**
* Sets the icon.
*
* @param icon The icon to set
*/
public void setIcon(String icon) {
this.icon = icon;
}
}
| apache-2.0 |
acoburn/trellis-spi | src/main/java/org/trellisldp/spi/RDFUtils.java | 6899 | /*
* 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.trellisldp.spi;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableMap;
import static java.util.stream.Stream.concat;
import static java.util.stream.Stream.of;
import static org.trellisldp.vocabulary.RDF.type;
import static org.trellisldp.vocabulary.Trellis.PreferAudit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.stream.Stream;
import org.apache.commons.rdf.api.BlankNode;
import org.apache.commons.rdf.api.IRI;
import org.apache.commons.rdf.api.Quad;
import org.apache.commons.rdf.api.RDF;
import org.apache.commons.rdf.api.RDFTerm;
import org.trellisldp.vocabulary.AS;
import org.trellisldp.vocabulary.LDP;
import org.trellisldp.vocabulary.PROV;
import org.trellisldp.vocabulary.XSD;
/**
* The RDFUtils class provides a set of convenience methods related to
* generating and processing RDF objects.
*
* @author acoburn
* @deprecated Please use the org.trellisldp.api package instead
*/
@Deprecated
public final class RDFUtils {
private static RDF rdf = ServiceLoader.load(RDF.class).iterator().next();
/**
* The internal trellis prefix
*/
public static final String TRELLIS_PREFIX = "trellis:";
/**
* The internal blank node prefix
*/
public static final String TRELLIS_BNODE_PREFIX = "trellis:bnode/";
/**
* A mapping of LDP types to their supertype
*/
public static final Map<IRI, IRI> superClassOf;
static {
final Map<IRI, IRI> data = new HashMap<>();
data.put(LDP.NonRDFSource, LDP.Resource);
data.put(LDP.RDFSource, LDP.Resource);
data.put(LDP.Container, LDP.RDFSource);
data.put(LDP.BasicContainer, LDP.Container);
data.put(LDP.DirectContainer, LDP.Container);
data.put(LDP.IndirectContainer, LDP.Container);
superClassOf = unmodifiableMap(data);
}
/**
* Get the Commons RDF instance in use
* @return the RDF instance
*/
public static RDF getInstance() {
return rdf;
}
/**
* Create audit-related creation data
* @param subject the subject
* @param session the session
* @return the quads
*/
public static List<Quad> auditCreation(final IRI subject, final Session session) {
return auditData(subject, session, asList(PROV.Activity, AS.Create));
}
/**
* Create audit-related deletion data
* @param subject the subject
* @param session the session
* @return the quads
*/
public static List<Quad> auditDeletion(final IRI subject, final Session session) {
return auditData(subject, session, asList(PROV.Activity, AS.Delete));
}
/**
* Create audit-related update data
* @param subject the subject
* @param session the session
* @return the quads
*/
public static List<Quad> auditUpdate(final IRI subject, final Session session) {
return auditData(subject, session, asList(PROV.Activity, AS.Update));
}
private static List<Quad> auditData(final IRI subject, final Session session, final List<IRI> types) {
final List<Quad> data = new ArrayList<>();
final BlankNode bnode = rdf.createBlankNode();
data.add(rdf.createQuad(PreferAudit, subject, PROV.wasGeneratedBy, bnode));
types.forEach(t -> data.add(rdf.createQuad(PreferAudit, bnode, type, t)));
data.add(rdf.createQuad(PreferAudit, bnode, PROV.wasAssociatedWith, session.getAgent()));
data.add(rdf.createQuad(PreferAudit, bnode, PROV.startedAtTime,
rdf.createLiteral(session.getCreated().toString(), XSD.dateTime)));
session.getDelegatedBy().ifPresent(delegate ->
data.add(rdf.createQuad(PreferAudit, bnode, PROV.actedOnBehalfOf, delegate)));
return data;
}
/**
* Get all of the LDP resource (super) types for the given LDP interaction model
* @param interactionModel the interaction model
* @return a stream of types
*/
public static Stream<IRI> ldpResourceTypes(final IRI interactionModel) {
return of(interactionModel).filter(type -> RDFUtils.superClassOf.containsKey(type) || LDP.Resource.equals(type))
.flatMap(type -> concat(ldpResourceTypes(RDFUtils.superClassOf.get(type)), of(type)));
}
/**
* Convert an internal term to an external term
* @param <T> the RDF term type
* @param term the RDF term
* @param baseUrl the base URL
* @return a converted RDF term
*/
@SuppressWarnings("unchecked")
public static <T extends RDFTerm> T toExternalTerm(final T term, final String baseUrl) {
if (term instanceof IRI) {
final String iri = ((IRI) term).getIRIString();
if (iri.startsWith(TRELLIS_PREFIX)) {
return (T) rdf.createIRI(baseUrl + iri.substring(TRELLIS_PREFIX.length()));
}
}
return term;
}
/**
* Convert an external term to an internal term
* @param <T> the RDF term type
* @param term the RDF term
* @param baseUrl the base URL
* @return a converted RDF term
*/
@SuppressWarnings("unchecked")
public static <T extends RDFTerm> T toInternalTerm(final T term, final String baseUrl) {
if (term instanceof IRI) {
final String iri = ((IRI) term).getIRIString();
if (iri.startsWith(baseUrl)) {
return (T) rdf.createIRI(TRELLIS_PREFIX + iri.substring(baseUrl.length()));
}
}
return term;
}
/**
* Clean the identifier
* @param identifier the identifier
* @return the cleaned identifier
*/
public static String cleanIdentifier(final String identifier) {
final String id = identifier.split("#")[0].split("\\?")[0];
if (id.endsWith("/")) {
return id.substring(0, id.length() - 1);
}
return id;
}
/**
* Clean the identifier
* @param identifier the identifier
* @return the cleaned identifier
*/
public static IRI cleanIdentifier(final IRI identifier) {
return rdf.createIRI(cleanIdentifier(identifier.getIRIString()));
}
private RDFUtils() {
// prevent instantiation
}
}
| apache-2.0 |
dremio/dremio-oss | services/base-rpc/src/main/java/com/dremio/exec/rpc/ConnectionFailedException.java | 1209 | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.exec.rpc;
import com.dremio.exec.rpc.RpcConnectionHandler.FailureType;
/**
* Exception thrown when server connection is closed or not available.
*/
public class ConnectionFailedException extends RpcException {
public ConnectionFailedException(RpcException ex) {
super(ex.getLocalizedMessage(), ex.getStatus(), ex.getErrorId(), ex);
}
public static RpcException mapException(RpcException ex, FailureType failureType) {
if (failureType == RpcConnectionHandler.FailureType.CONNECTION) {
return new ConnectionFailedException(ex);
}
return ex;
}
}
| apache-2.0 |
devacfr/multicast-event | multicastevent-core/src/main/java/org/cfr/multicastevent/core/DefaultChannelAdapter.java | 2024 | /**
* Copyright 2014 devacfr<christophefriederich@mac.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.cfr.multicastevent.core;
import java.util.Collection;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.cfr.multicastevent.core.spi.IChannel;
import org.cfr.multicastevent.core.spi.IMember;
/**
*
* @author devacfr<christophefriederich@mac.com>
* @since 1.0
*/
@Singleton
public class DefaultChannelAdapter extends AbstractChannelAdapter {
private IInboundEndpoint inboundEndpoint;
@Inject
public DefaultChannelAdapter(@Nonnull final IChannel channel, @Named("clusterName") String clusterName) {
super(channel, clusterName);
}
public void setInboundEndpoint(@Nullable IInboundEndpoint inboundEndpoint) {
this.inboundEndpoint = inboundEndpoint;
}
@Nullable
public IInboundEndpoint getInboundEndpoint() {
return inboundEndpoint;
}
@Override
public void membersChanged(Collection<IMember> member) {
//noop
}
@Override
public void memberJoined(@Nullable IMember member) {
//noop
}
@Override
public void memberLeft(@Nullable IMember member) {
//noop
}
@Override
public void receiveEvent(MulticastEvent event) {
if (this.inboundEndpoint == null) {
return;
}
this.inboundEndpoint.receive(event);
};
}
| apache-2.0 |
Duct-and-rice/KrswtkhrWiki4Android | app/src/main/java/org/wikipedia/feed/random/RandomClient.java | 320 | package org.wikipedia.feed.random;
import org.wikipedia.Site;
import org.wikipedia.feed.DummyClient;
public class RandomClient extends DummyClient<RandomCard> {
public RandomClient() {
super();
}
@Override
public RandomCard getNewCard(Site site) {
return new RandomCard(site);
}
}
| apache-2.0 |
tkowalcz/presentations | rxjava/src/main/java/pl/tkowalcz/examples/basic/BasicsCompleted.java | 2955 | package pl.tkowalcz.examples.basic;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import pl.tkowalcz.twitter.Tweet;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
import java.io.IOException;
public class BasicsCompleted {
public static final Splitter SPLITTER = Splitter.on(' ').trimResults().omitEmptyStrings();
public static void main(String[] args) throws IOException {
String tweet1 = "{\"created_at\": \"Fri Oct 10 11:26:33 +0000 2014\", \"text\": \"Charging by induction is like proof by induction. It takes ages and you're never quite sure if it worked.\", \"user\": { \"screen_name\": \"tastapod\", \"location\": \"Agilia\" }}";
String tweet2 = "{\"created_at\": \"Fri Oct 10 11:26:33 +0000 2014\", \"text\": \"TIL the movie Inception was based on node.js callbacks\", \"user\": { \"screen_name\": \"HackerNewsOnion\", \"location\": \"HackerNews\" }}";
String tweet3 = "{\"created_at\": \"Fri Oct 10 12:26:33 +0000 2014\", \"text\": \"Shark Facts: Statistically, you are a more likely to be killed by a statistician than by a shark\", \"user\": { \"screen_name\": \"TheTechShark\"}}";
String tweet4 = "{\"delete\":{\"status\":{\"id\":48223552775705600}}}";
String tweet5 = "{\"created_at\": \"Fri Oct 10 08:26:33 +0000 2014\", \"text\": \"Keep calm and don't block threads\", \"user\": { \"screen_name\": \"tkowalcz\", \"location\": \"DevoxxPL\"}}";
// Will deserialize tweets from json
Gson gson = new GsonBuilder().create();
Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
System.out.println("Thread.currentThread() = " + Thread.currentThread());
ImmutableList<String> tweets = ImmutableList.of(tweet1, tweet2, tweet3, tweet4, tweet5);
for (String tweet : tweets) {
if (subscriber.isUnsubscribed()) {
break;
}
subscriber.onNext(tweet);
}
subscriber.onCompleted();
}
})
.observeOn(Schedulers.computation())
// We are only interested in new tweets so lets filter out others
.filter(s -> s.contains("created_at"))
// Deserialize from JSON
.map(s -> gson.fromJson(s, Tweet.class))
// Pass only tweets that are 'valid' - contain nonempty text, location and author
.filter(Tweet::isValidTweet)
// Lets roll
.subscribe(tweet -> {
System.out.println("Thread.currentThread() = " + Thread.currentThread());
}, System.out::println);
}
}
| apache-2.0 |
ind9/gocd-s3-artifacts | publish/src/main/java/com/indix/gocd/s3publish/SourceDestination.java | 310 | package com.indix.gocd.s3publish;
public class SourceDestination {
public String source;
public String destination;
public SourceDestination() {
}
public SourceDestination(String source, String destination) {
this.source = source;
this.destination = destination;
}
}
| apache-2.0 |
OpenVnmrJ/OpenVnmrJ | src/vnmrj/src/vnmr/bo/VColorMapPanel.java | 6499 | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
package vnmr.bo;
import java.awt.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.geom.*;
import java.awt.event.*;
import java.awt.image.*;
import java.beans.*;
import vnmr.ui.*;
import vnmr.util.*;
import vnmr.templates.*;
public class VColorMapPanel extends JPanel implements VObjIF, VObjDef {
private VColorLookupPanel lookupTable;
private VColorScale vsEditor;
private VColorMapSelector mapSelector;
private SessionShare sshare;
private ButtonIF vif;
private String typeName;
private JTabbedPane tabPan;
private int colorNum = 0;
private JSplitPane split;
private JPanel colorPanel;
private VColorImageSelector imgSelectPanel;
public VColorMapPanel(SessionShare sshare, ButtonIF vif, String typ) {
this.colorNum = 0;
buildGUi();
}
public VColorMapPanel()
{
this(null, null, "colormap");
}
private void buildGUi() {
sshare = Util.getSessionShare();
vif = (ButtonIF) Util.getActiveView();
typeName = "colormap";
setLayout(new BorderLayout());
colorPanel = new JPanel();
colorPanel.setLayout(new BorderLayout());
split = new JSplitPane(JSplitPane.VERTICAL_SPLIT,false);
split.setDividerSize(6);
colorNum = 64;
lookupTable = new VColorLookupPanel(true);
colorPanel.add(lookupTable, BorderLayout.NORTH);
lookupTable.setColorNumber(colorNum);
tabPan = new JTabbedPane();
vsEditor = new VColorScale();
mapSelector = new VColorMapSelector();
tabPan.add("Maps", mapSelector);
tabPan.add("Scale", vsEditor);
colorPanel.add(tabPan, BorderLayout.CENTER);
split.setTopComponent(colorPanel);
imgSelectPanel = new VColorImageSelector();
split.setBottomComponent(imgSelectPanel);
add(split, BorderLayout.CENTER);
mapSelector.setLookupPanel(lookupTable);
imgSelectPanel.setLookupPanel(lookupTable);
imgSelectPanel.setMapSelector(mapSelector);
split.setResizeWeight(0.82);
ImageColorMapEditor.addColormapList(this);
Util.setColormapPanel(this);
}
public void setColorNumber(int n) {
int num = 0;
int[] vlist = VColorMapFile.SIZE_VALUE_LIST;
for (int i = 0; i < vlist.length; i++) {
if (n == vlist[i]) {
num = vlist[i];
break;
}
}
if (num == 0)
num = vlist[0];
if (num == colorNum)
return;
colorNum = num;
lookupTable.setColorNumber(num);
}
public void setDebugMode(boolean b) {
lookupTable.setDebugMode(b);
mapSelector.setDebugMode(b);
}
public void saveColormap(String path) {
}
private void setLoadMode(boolean b) {
lookupTable.setLoadMode(b);
}
public void loadDefaultColormap(String name) {
setColorNumber(64);
lookupTable.loadColormap(name, name);
}
public void loadColormap(String name, String path) {
if (path != null)
path = FileUtil.openPath(path);
setLoadMode(true);
if (path == null) {
if (name != null) {
if (name.equals(VColorMapFile.DEFAULT_NAME))
loadDefaultColormap(name);
}
setLoadMode(false);
return;
}
int num = 0;
BufferedReader ins = null;
String line;
try {
ins = new BufferedReader(new FileReader(path));
while ((line = ins.readLine()) != null) {
if (line.startsWith("#"))
continue;
StringTokenizer tok = new StringTokenizer(line, " \t\r\n");
if (tok.hasMoreTokens()) {
String data = tok.nextToken();
if (data.equals(VColorMapFile.SIZE_NAME)) {
if (tok.hasMoreTokens()) {
data = tok.nextToken();
num = Integer.parseInt(data);
break;
}
}
}
}
} catch (Exception e) {
setLoadMode(false);
num = 0;
}
finally {
try {
if (ins != null)
ins.close();
}
catch (Exception e2) {}
}
if (num > 2) {
setColorNumber(num);
lookupTable.loadColormap(name, path);
}
setLoadMode(false);
}
public void loadColormap(String name) {
if (name == null)
return;
String path = VColorMapFile.getMapFilePath(name);
if (path == null)
return;
loadColormap(name, path);
}
public void setColorInfo(int id, int order, int mapId,
int transparency, String imgName) {
imgSelectPanel.addImageInfo(id, order,mapId,transparency, imgName);
}
public void selectColorInfo(int id) {
imgSelectPanel.selectImageInfo(id);
}
// VObjIF interface
public void setAttribute(int t, String s) {
}
public String getAttribute(int t) {
return null;
}
public void setEditStatus(boolean s) { }
public void setEditMode(boolean s) {}
public void addDefChoice(String s) { }
public void addDefValue(String s) { }
public void setDefLabel(String s) { }
public void setDefColor(String s) { }
public void setDefLoc(int x, int y) { }
public void refresh() { }
public void changeFont() { }
public void updateValue() { }
public void setValue(ParamIF p) { }
public void setShowValue(ParamIF p) { }
public void changeFocus(boolean s) { }
public ButtonIF getVnmrIF() {
return null;
}
public void setVnmrIF(ButtonIF vif) { }
public void destroy() { }
public void setModalMode(boolean s) { }
public void sendVnmrCmd() { }
public void setSizeRatio(double w, double h) { }
public Point getDefLoc() {
return new Point(0, 0);
}
}
| apache-2.0 |
mdgeek/hspc-connectathon | cwfdemo-ui-parent/cwfdemo-ui-messagebox/src/main/java/org/hspconsortium/cwfdemo/ui/messagebox/MessageListener.java | 3757 | /*
* #%L
* Message Viewer Plugin
* %%
* Copyright (C) 2014 - 2016 Healthcare Services Platform Consortium
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.hspconsortium.cwfdemo.ui.messagebox;
import org.hspconsortium.cwfdemo.ui.messagebox.MainController.Action;
import org.socraticgrid.hl7.services.uc.exceptions.BadBodyException;
import org.socraticgrid.hl7.services.uc.exceptions.FeatureNotSupportedException;
import org.socraticgrid.hl7.services.uc.exceptions.InvalidContentException;
import org.socraticgrid.hl7.services.uc.exceptions.InvalidMessageException;
import org.socraticgrid.hl7.services.uc.exceptions.MissingBodyTypeException;
import org.socraticgrid.hl7.services.uc.exceptions.ProcessingException;
import org.socraticgrid.hl7.services.uc.exceptions.ServiceAdapterFaultException;
import org.socraticgrid.hl7.services.uc.exceptions.UndeliverableMessageException;
import org.socraticgrid.hl7.services.uc.interfaces.UCSClientIntf;
import org.socraticgrid.hl7.services.uc.model.Conversation;
import org.socraticgrid.hl7.services.uc.model.DeliveryAddress;
import org.socraticgrid.hl7.services.uc.model.Message;
import org.socraticgrid.hl7.services.uc.model.MessageModel;
public class MessageListener implements UCSClientIntf {
private final MainController controller;
public MessageListener(MainController controller) {
this.controller = controller;
}
@Override
public boolean callReady(Conversation conversation, String callHandle, String serverId) {
// TODO Auto-generated method stub
return false;
}
@Override
public <T extends Message> boolean handleException(MessageModel<T> messageModel, DeliveryAddress sender,
DeliveryAddress receiver, ProcessingException exp, String serverId) {
// TODO Auto-generated method stub
return false;
}
@Override
public <T extends Message> boolean handleNotification(MessageModel<T> messageModel, String serverId) {
controller.invokeAction(Action.ADD, messageModel.getMessageType());
return true;
}
@Override
public <T extends Message> MessageModel<T> handleResponse(MessageModel<T> messageModel,
String serverId) throws InvalidMessageException,
InvalidContentException,
MissingBodyTypeException, BadBodyException,
ServiceAdapterFaultException,
UndeliverableMessageException,
FeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends Message> boolean receiveMessage(MessageModel<T> messageModel, String serverId) {
controller.invokeAction(Action.ADD, messageModel.getMessageType());
return true;
}
}
| apache-2.0 |
equella/Equella | autotest/Interface/Plugins/com.tle.web.api.search.interfaces/src/com/tle/web/api/search/interfaces/SearchResource.java | 5753 | package com.tle.web.api.search.interfaces;
import com.tle.common.interfaces.CsvList;
import com.tle.web.api.interfaces.beans.SearchBean;
import com.tle.web.api.item.interfaces.ItemResource;
import com.tle.web.api.item.interfaces.beans.ItemBean;
import com.tle.web.api.search.interfaces.beans.FacetSearchBean;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
@Path("search")
@Api(value = "/search", description = "search")
@Produces(MediaType.APPLICATION_JSON)
public interface SearchResource {
/**
* @param q The text query
* @param start The index of the first record to return. The first available record is at 0
* @param length The number of results to return
* @param collections A comma separated list of collection UUIDs (optional). If omitted, all
* collections will be searched.
* @param order One of: "relevance", "modified", "name", "rating"
* @param reverse Reverse the order of the results.
* @param where A complex where query.
* @param info A comma separated list of field groups to return.
* @param showall If true then includes draft items in the search results.
* @return JSON format
*/
@GET
@Path("/")
@ApiOperation(
value = "Search for items",
notes = "Search for items that the current user can discover")
@ApiResponses({
@ApiResponse(
code = 200,
message = "{\n \"start\":0,\n \"length\":0,\n \"available\":0,\n \"results\":[]\n}",
response = SearchBean.class)
})
//
// @formatter:off
public SearchBean<ItemBean> searchItems(
@Context UriInfo uriInfo,
@ApiParam(value = "Query string", required = false) @QueryParam("q") String q,
@ApiParam(
value = "The first record of the search results to return",
required = false,
defaultValue = "0")
@QueryParam("start")
int start,
@ApiParam(
value = "The number of results to return",
required = false,
defaultValue = "10",
allowableValues = "range[0,50]")
@QueryParam("length")
@DefaultValue("10")
int length,
@ApiParam(value = "List of collections", required = false) @QueryParam("collections")
CsvList collections,
@ApiParam(
value = "The order of the search results",
allowableValues = ",relevance,modified,name,rating",
required = false)
@QueryParam("order")
String order,
@ApiParam(
value = "Reverse the order of the search results",
allowableValues = ",true,false",
defaultValue = "false",
required = false)
@QueryParam("reverse")
String reverse,
@ApiParam(
value =
"The where-clause in the same format as the old SOAP one. See http://code.pearson.com/equella/soap-api/searchitems-soapservice50",
required = false)
@QueryParam("where")
String where,
@ApiParam(
value = "How much information to return for the results",
required = false,
allowableValues = ItemResource.ALL_ALLOWABLE_INFOS,
allowMultiple = true)
@QueryParam("info")
CsvList info,
@ApiParam(
value = "If true then includes items that are not live",
allowableValues = ",true,false",
defaultValue = "false",
required = false)
@QueryParam("showall")
String showall);
// @formatter:on
@GET
@Path("/facet")
@ApiOperation(value = "Perform a facet search")
// @formatter:off
public FacetSearchBean searchFacets(
@ApiParam(value = "Comma seperated list of schema nodes to facet over", required = true)
@QueryParam("nodes")
CsvList nodes,
@ApiParam(
value =
"The level at which to nest the facet search, the selected node must be flagged as nested in the schema definition",
required = false)
@QueryParam("nest")
String nestLevel,
@ApiParam(value = "Query string", required = false) @QueryParam("q") String q,
@ApiParam(
value =
"The number of term combinations to search for, a higher number will return more results and more accurate counts, but will take longer",
required = false,
defaultValue = "10",
allowableValues = "range[0,200]")
@QueryParam("breadth")
@DefaultValue("10")
int breadth,
@ApiParam(value = "List of collections", required = false) @QueryParam("collections")
CsvList collections,
@ApiParam(
value =
"The where-clause in the same format as the old SOAP one. See http://code.pearson.com/equella/soap-api/searchitems-soapservice50",
required = false)
@QueryParam("where")
String where,
@ApiParam(
value = "If true then includes items that are not live",
allowableValues = "true,false",
defaultValue = "false",
required = false)
@QueryParam("showall")
String showall);
// @formatter:on
}
| apache-2.0 |
jphp-compiler/jphp | jphp-core/src/org/develnext/jphp/core/tokenizer/token/expr/value/FromExprToken.java | 233 | package org.develnext.jphp.core.tokenizer.token.expr.value;
import org.develnext.jphp.core.tokenizer.TokenMeta;
public class FromExprToken extends NameToken {
public FromExprToken(TokenMeta meta) {
super(meta);
}
}
| apache-2.0 |
OpenVnmrJ/OpenVnmrJ | src/vnmrj/src/vnmr/util/ParamInfoPanel.java | 111871 | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
package vnmr.util;
import static vnmr.bo.EasyJTable.ACTION_SCROLL_TO_BOTTOM;
import static vnmr.bo.EasyJTable.REASON_ANY;
import static vnmr.bo.EasyJTable.REASON_INITIAL_VIEW;
import static vnmr.bo.EasyJTable.STATE_ANY;
import static vnmr.bo.EasyJTable.STATE_BOTTOM_SHOWS;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.filechooser.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.util.*;
import java.beans.*;
import java.io.File;
import vnmr.bo.*;
import vnmr.ui.*;
import vnmr.ui.shuf.*;
import vnmr.templates.*;
public class ParamInfoPanel extends ModelessDialog
implements VObjDef, ActionListener, PropertyChangeListener, Types
{
private static final long serialVersionUID = 1L;
private String itemName="";
private String panelEditorGeometryFile="PanelEditorGeometry";
private String panelEditorPersistenceFile="PanelEditor";
private boolean initialized=false;
private ArrayList<VObjIF> edits=new ArrayList<VObjIF>();
private ParamPanel editPanel;
private VObjIF editVobj=null;
private JLabel lbs[];
private VUndoableText txts[];
private JPanel pans[];
private JLabel vlbs[];
private JComponent vwidgs[];
private JPanel vpans[];
private boolean vwidgIsSet[];
private JPanel panel=null;
private JPanel headerPan=null;
private JPanel prefPan=null;
private JPanel ctlPan=null;
private JPanel attrPan=null;
private JScrollPane attrScroll=null;
private JPanel editablePan=null;
private VUndoableText snapSize=null;
private VUndoableText locX=null;
private VUndoableText locY=null;
private VUndoableText locW=null;
private VUndoableText locH=null;
private JLabel typeOfItem=null;
private JLabel itemSource=null;
private JLabel itemLabel=null;
private JLabel InLabel=null;
private VUndoableText itemEntry;
private JComboBox saveDirectory;
private boolean changed_page = false;
private JComboBox typeList;
private JButton saveButton=null;
private JButton reloadButton=null;
private JButton clearButton=null;
private JButton revertButton=null;
private JRadioButton editableOn;
private JRadioButton editableOff;
private RadioGroup tabgrp=null;
private JCheckBox autoscroll=null;
private JRadioButton autosaveButton;
private JRadioButton warnsaveButton;
private JRadioButton usersaveButton;
private JCheckBox edit_tools=null;
private JCheckBox edit_panels=null;
private JCheckBox edit_status=null;
private JCheckBox edit_actions=null;
private String panelName = null;
private String panelType = "generic";
private String fileName = null;
private StyleChooser textStyle=null;
private int attrWidth=26;
private final int ILABEL = 0; // label
private final int VAR = 1; // VNMR variables
private final int IVAL = 2; // value for this item
private final int SHOWX = 3; // show condition
private final int CMD_1 = 4; // cmd for entry, choice, button,radio, check
private final int CMD_2 = 5; // cmd for reset check or toggle
private final int CHOICE = 6; // choice labels
private final int CHVALS = 7; // choice values
private final int DIGITS = 8; // number of digits
private final int STATVARS = 9; // status variables
private final int numItems = 10;
private int selectedType = ParamInfo.PARAMLAYOUT;
private final int SAVE_IN_LAYOUT = 0;
private final int AUTO_SAVE = 2;
private final int WARN_SAVE = 1;
private final int USER_SAVE = 0;
private SaveWarnDialog warnDialog=null;
private int save_policy=USER_SAVE;
private boolean isNewType = true;
private int lastSaveIndex = 0;
private boolean inAddMode=true;
private int textLen = 20;
private int windowWidth = 720;
private int scrollH = 30;
private int etcH = 130; // the panelHeight - scrollH
private int sbW = 0;
private boolean inSetMode = false;
private SessionShare sshare;
private AppIF appIf;
private Font font = DisplayOptions.getFont("Dialog", Font.PLAIN, 12);
private AttributeChangeListener attributeChangeListener;
private String openpath=null;
private String savepath=null;
private ItemEditor editor=null;
private SimpleH2Layout xLayout = new SimpleH2Layout(SimpleH2Layout.LEFT,
4, 0, true, true);
private SimpleH2Layout tLayout = new SimpleH2Layout(SimpleH2Layout.LEFT,
4, 0, false, true);
/** Constructor. */
public ParamInfoPanel(String strhelpfile) {
super(null);
DisplayOptions.addChangeListener(this);
m_strHelpFile = strhelpfile;
Container contentPane = getContentPane();
attributeChangeListener = new AttributeChangeListener();
setTitle(Util.getLabel("peTitle"));
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenDim = tk.getScreenSize();
if (screenDim.width > 1000)
setLocation(400, 30);
else
setLocation(300, 30);
lbs = new JLabel[numItems];
txts = new VUndoableText[numItems];
pans = new JPanel[numItems];
vlbs = new JLabel[100];
vwidgs = new JComponent[100];
vpans = new JPanel[100];
vwidgIsSet = new boolean[100];
pans[ILABEL] = new JPanel();
pans[ILABEL].setLayout(xLayout);
lbs[ILABEL] = new JLabel(Util.getLabel(VObjDef.LABEL));
txts[ILABEL] = new VUndoableText(" ", textLen);
pans[ILABEL].add(lbs[ILABEL]);
pans[ILABEL].add(txts[ILABEL]);
pans[CHOICE] = new JPanel();
pans[CHOICE].setLayout(xLayout);
lbs[CHOICE] = new JLabel(Util.getLabel(VObjDef.SETCHOICE));
txts[CHOICE] = new VUndoableText(" ", textLen);
pans[CHOICE].add(lbs[CHOICE]);
pans[CHOICE].add(txts[CHOICE]);
pans[CHVALS] = new JPanel();
pans[CHVALS].setLayout(xLayout);
lbs[CHVALS] = new JLabel(Util.getLabel(VObjDef.SETCHVAL));
txts[CHVALS] = new VUndoableText("", textLen);
pans[CHVALS].add(lbs[CHVALS]);
pans[CHVALS].add(txts[CHVALS]);
pans[VAR] = new JPanel();
pans[VAR].setLayout(xLayout);
lbs[VAR] = new JLabel(Util.getLabel(VObjDef.VARIABLE));
txts[VAR] = new VUndoableText("", textLen);
pans[VAR].add(lbs[VAR]);
pans[VAR].add(txts[VAR]);
pans[CMD_1] = new JPanel();
pans[CMD_1].setLayout(xLayout);
lbs[CMD_1] = new JLabel(Util.getLabel(VObjDef.CMD));
txts[CMD_1] = new VUndoableText("", textLen);
pans[CMD_1].add(lbs[CMD_1]);
pans[CMD_1].add(txts[CMD_1]);
pans[CMD_2] = new JPanel();
pans[CMD_2].setLayout(xLayout);
lbs[CMD_2] = new JLabel(Util.getLabel(VObjDef.CMD2));
txts[CMD_2] = new VUndoableText("", textLen);
pans[CMD_2].add(lbs[CMD_2]);
pans[CMD_2].add(txts[CMD_2]);
pans[IVAL] = new JPanel();
pans[IVAL].setLayout(xLayout);
lbs[IVAL] = new JLabel(Util.getLabel(VObjDef.SETVAL));
txts[IVAL] = new VUndoableText("", textLen);
pans[IVAL].add(lbs[IVAL]);
pans[IVAL].add(txts[IVAL]);
pans[SHOWX] = new JPanel();
pans[SHOWX].setLayout(xLayout);
lbs[SHOWX] = new JLabel(Util.getLabel(VObjDef.SHOW));
txts[SHOWX] = new VUndoableText("", textLen);
pans[SHOWX].add(lbs[SHOWX]);
pans[SHOWX].add(txts[SHOWX]);
pans[DIGITS] = new JPanel();
pans[DIGITS].setLayout(xLayout);
lbs[DIGITS] = new JLabel(Util.getLabel(VObjDef.STATPAR));
txts[DIGITS] = new VUndoableText("", textLen);
pans[DIGITS].add(lbs[DIGITS]);
pans[DIGITS].add(txts[DIGITS]);
pans[STATVARS] = new JPanel();
pans[STATVARS].setLayout(xLayout);
lbs[STATVARS] = new JLabel(Util.getLabel(VObjDef.NUMDIGIT));
txts[STATVARS] = new VUndoableText("", textLen);
pans[STATVARS].add(lbs[STATVARS]);
pans[STATVARS].add(txts[STATVARS]);
JPanel typePan = new JPanel();
JLabel lb=new JLabel(Util.getLabel("peFile")+": ");
lb.setPreferredSize(new Dimension(48, 25));
typePan.add(lb);
itemSource = new JLabel("");
typePan.add(itemSource);
typePan.setLayout(new SimpleH2Layout(SimpleH2Layout.LEFT, 5, 0,true));
itemSource.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
itemSource.setPreferredSize(new Dimension(windowWidth-250, 25));
JPanel editPan = new JPanel();
editPan.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
editPan.setLayout(new SimpleH2Layout(SimpleH2Layout.LEFT, 5, 0, false));
editPan.add(new JLabel("Edit:"));
edit_panels=new JCheckBox("Panels");
edit_panels.setActionCommand("editcheck");
edit_panels.addActionListener(this);
editPan.add(edit_panels);
edit_actions=new JCheckBox("Actions");
edit_actions.setActionCommand("editcheck");
edit_actions.addActionListener(this);
editPan.add(edit_actions);
edit_tools=new JCheckBox("Tools");
edit_tools.setActionCommand("editcheck");
edit_tools.addActionListener(this);
editPan.add(edit_tools);
edit_status=new JCheckBox("Status");
edit_status.setActionCommand("editcheck");
edit_status.addActionListener(this);
editPan.add(edit_status);
typePan.add(editPan);
JPanel fontPan = new JPanel();
fontPan.setLayout(new SimpleH2Layout(SimpleH2Layout.LEFT, 5, 0, false));
lb = new JLabel(Util.getLabel("peType")+": ");
lb.setPreferredSize(new Dimension(48, 25));
fontPan.add(lb);
typeOfItem = new JLabel("");
fontPan.add(typeOfItem);
lb = new JLabel(Util.getLabel("peStyle")+": ");
fontPan.add(lb);
typeOfItem.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
typeOfItem.setPreferredSize(new Dimension(100, 25));
textStyle=new StyleChooser("style");
textStyle.setOpaque(true);
textStyle.setEditable(false);
fontPan.add(textStyle);
addButton(Util.getLabel("peEditStyles"), fontPan, this, "editStyles");
addButton(Util.getLabel("peEditItems"), fontPan, this, "editItems");
addButton("Browser...", fontPan, this, "openBrowser");
if(!FillDBManager.locatorOff())
addButton("Locator...", fontPan, this, "openLocator");
headerPan=new JPanel();
headerPan.setLayout(new AttrLayout());
headerPan.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
headerPan.add(fontPan);
headerPan.add(typePan);
editablePan = new JPanel();
editablePan.setLayout(tLayout);
lb = new JLabel(Util.getLabel(VObjDef.EDITABLE));
ButtonGroup editGroup = new ButtonGroup();
editableOn = new JRadioButton(Util.getLabel("mlTrue"));
editableOff = new JRadioButton(Util.getLabel("mlFalse"));
editGroup.add(editableOn);
editGroup.add(editableOff);
editablePan.add(lb);
editablePan.add(editableOn);
editablePan.add(editableOff);
editableOff.setSelected(true);
editablePan.setVisible(false);
attrPan=new JPanel();
attrPan.setBorder(new BevelBorder(BevelBorder.LOWERED));
attrPan.setLayout(new AttrLayout());
attrPan.add(pans[ILABEL]);
attrPan.add(pans[VAR]);
attrPan.add(pans[IVAL]);
attrPan.add(pans[SHOWX]);
attrPan.add(pans[CMD_1]);
attrPan.add(pans[CMD_2]);
attrPan.add(pans[CHOICE]);
attrPan.add(pans[CHVALS]);
attrPan.add(pans[DIGITS]);
attrPan.add(pans[STATVARS]);
int wht=(numItems+3)*attrWidth;
attrPan.setPreferredSize(new Dimension(windowWidth-8,wht));
attrScroll = new JScrollPane(attrPan);
attrScroll.setPreferredSize(new Dimension(windowWidth-2,wht));
prefPan = new JPanel();
prefPan.setLayout(new SimpleH2Layout(SimpleH2Layout.LEFT, 10, 0, false));
prefPan.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
prefPan.setPreferredSize(new Dimension(400, 30));
JPanel snapPan = new JPanel();
snapPan.setLayout(new SimpleH2Layout(SimpleH2Layout.LEFT, 5, 0, false));
lb = new JLabel(Util.getLabel("Grid"));
snapSize = new VUndoableText("5", 4);
snapPan.add(lb);
snapPan.add(snapSize);
prefPan.add(snapPan);
JPanel locPan = new JPanel();
locPan.setLayout(new SimpleH2Layout(SimpleH2Layout.LEFT, 5, 0, false));
lb = new JLabel("X ");
locPan.add(lb);
locX = new VUndoableText("", 4);
locPan.add(locX);
lb = new JLabel("Y ");
locPan.add(lb);
locY = new VUndoableText("", 4);
locPan.add(locY);
lb = new JLabel("W ");
locPan.add(lb);
locW = new VUndoableText("", 4);
locPan.add(locW);
lb = new JLabel("H ");
locPan.add(lb);
locH = new VUndoableText("", 4);
locPan.add(locH);
prefPan.add(locPan);
autoscroll=new JCheckBox("Scroll");
autoscroll.setActionCommand("autoscroll");
autoscroll.addActionListener(this);
autoscroll.setToolTipText("Automatically scroll panels when moving components");
prefPan.add(autoscroll);
JPanel savePan = new JPanel();
savePan.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
savePan.setLayout(new SimpleH2Layout(SimpleH2Layout.LEFT, 5, 0, false));
savePan.add(new JLabel("Save:"));
autosaveButton=new JRadioButton("Auto");
autosaveButton.setActionCommand("autosave");
autosaveButton.addActionListener(this);
autosaveButton.setToolTipText("Automatically save edited panels and pages");
savePan.add(autosaveButton);
warnsaveButton=new JRadioButton("Warn");
warnsaveButton.setActionCommand("warnsave");
warnsaveButton.addActionListener(this);
warnsaveButton.setToolTipText("Issue a warning when switching panels with unsaved edits");
savePan.add(warnsaveButton);
usersaveButton=new JRadioButton("Manual");
usersaveButton.setActionCommand("usersave");
usersaveButton.addActionListener(this);
usersaveButton.setToolTipText("User is responsible for saving items manually");
savePan.add(usersaveButton);
ButtonGroup saveButtons=new ButtonGroup();
saveButtons.add(autosaveButton);
saveButtons.add(warnsaveButton);
saveButtons.add(usersaveButton);
prefPan.add(savePan);
ctlPan = new JPanel();
reloadButton=addButton(Util.getLabel("blLoad"), ctlPan, this, "LoadItem");
saveButton=addButton(Util.getLabel("blSave"), ctlPan, this, "saveItem");
revertButton=addButton(Util.getLabel("Revert"), ctlPan, this, "revertItem");
revertButton.setToolTipText("Remove local item - revert to system default");
itemLabel=new JLabel(Util.getLabel("peType"));
itemLabel.setFont(DisplayOptions.getFont("Dialog", Font.BOLD, 14));
ctlPan.add(itemLabel);
itemEntry=new VUndoableText(itemName,12);
itemEntry.setActionCommand("itemName");
itemEntry.addActionListener(this);
itemEntry.setPreferredSize(new Dimension(300, 25));
ctlPan.add(itemEntry);
InLabel=new JLabel(Util.getLabel("peDir"));
InLabel.setFont(DisplayOptions.getFont("Dialog", Font.BOLD, 14));
ctlPan.add(InLabel);
saveDirectory=new JComboBox();
saveDirectory.setActionCommand("setSaveDirectory");
saveDirectory.setEditable(true);
saveDirectory.setPreferredSize(new Dimension(150, 25));
ctlPan.add(saveDirectory);
lb = new JLabel(Util.getLabel("peType"));
lb.setFont(DisplayOptions.getFont("Dialog", Font.BOLD, 14));
ctlPan.add(lb);
typeList=new JComboBox();
typeList.setActionCommand("setItemType");
typeList.setEditable(true);
typeList.setModel(new DefaultComboBoxModel());
typeList.setPreferredSize(new Dimension(130, 25));
ctlPan.add(typeList);
clearButton=addButton(Util.getLabel("blClear"), ctlPan, this, "ClearItem");
ctlPan.setLayout(new SimpleH2Layout(SimpleH2Layout.LEFT, 4, 0, false));
ctlPan.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
ctlPan.setPreferredSize(new Dimension(windowWidth-2, 35));
panel=new JPanel();
panel.setLayout(new PanelLayout());
panel.add(headerPan);
panel.add(attrScroll);
panel.add(prefPan);
panel.add(ctlPan);
contentPane.add(panel,BorderLayout.CENTER);
initPanel();
initAction();
getEditItems();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
savePrefAttr();
saveObj();
saveGeometry();
writePersistence();
setVisible(false);
if(editor !=null){
editor.saveContent();
editor.setVisible(false);
}
if(warnDialog !=null){
warnDialog.setVisible(false);
}
ParamInfo.setEditMode(false);
}
public void windowDeactivated(WindowEvent e) {
savePrefAttr();
}
});
/*
setResizable(false);
*/
historyButton.setEnabled(false);
undoButton.setEnabled(false);
historyButton.setActionCommand("edit");
historyButton.setEnabled(false);
historyButton.addActionListener(this);
undoButton.setActionCommand("undo");
undoButton.addActionListener(this);
closeButton.setActionCommand("Close");
closeButton.addActionListener(this);
abandonButton.setActionCommand("Cancel");
abandonButton.addActionListener(this);
helpButton.setActionCommand("help");
helpButton.addActionListener(this);
revertButton.addActionListener(this);
revertButton.setActionCommand("revertItem");
setAbandonEnabled(true);
setCloseEnabled(true);
setBgColor();
pack();
typeList.addActionListener(this);
saveDirectory.addActionListener(this);
addGeometryListener();
}
private static void setDebug(String s){
if(DebugOutput.isSetFor("ParamInfoPanel"))
Messages.postDebug("ParamInfoPanel : "+s);
}
public ModelessDialog getEditor(){
return editor;
}
public void addGeometryListener(){
addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent ce) {
saveGeometry();
}
});
}
public void writePersistence() {
if(openpath!=null)
FileUtil.writeValueToPersistence(panelEditorPersistenceFile, // File
"openpath", // Key
openpath); // Value
if(savepath!=null)
FileUtil.writeValueToPersistence(panelEditorPersistenceFile, // File
"savepath", // Key
savepath); // Value
String estr=Integer.toString(ParamInfo.getEditItems());
FileUtil.writeValueToPersistence(panelEditorPersistenceFile, // File
"edit_types", // Key
estr); // Value
}
public void readPersistence() {
openpath=FileUtil.readStringFromPersistence(panelEditorPersistenceFile,"openpath");
savepath=FileUtil.readStringFromPersistence(panelEditorPersistenceFile,"savepath");
String estr=FileUtil.readStringFromPersistence(panelEditorPersistenceFile,"edit_types");
if(estr!=null){
int i=Integer.parseInt(estr);
ParamInfo.setEditItems(i);
getEditItems();
}
}
public void saveGeometry(){
FileUtil.writeGeometryToPersistence(panelEditorGeometryFile, this);
}
public void restoreGeometry(){
if(initialized)
return;
FileUtil.setGeometryFromPersistence(panelEditorGeometryFile, this);
initialized=true;
}
private void setBgColor(){
textStyle.setBackground(null);
}
public void setVisible(boolean b){
if(b){
if(!initialized){
restoreGeometry();
readPersistence();
}
}
super.setVisible(b);
}
/** PropertyChangeListener interface */
public void propertyChange(PropertyChangeEvent evt){
super.propertyChange(evt);
}
public void setChangedPage(boolean b){
if(b != changed_page){
changed_page=b;
updateItemButtons();
}
}
/** get edit object's location and size. */
public void getObjectGeometry() {
JComponent comp=(JComponent)editVobj;
if(comp==null){
locX.setText("");
locY.setText("");
locH.setText("");
locW.setText("");
return;
}
if(!comp.isShowing())
return;
Point pt = comp.getLocation();
Point pt2;
Container pp = comp.getParent();
while (pp != null) {
if (pp instanceof ParamPanel)
break;
pt2 = pp.getLocation();
pt.x += pt2.x;
pt.y += pt2.y;
pp = pp.getParent();
}
locX.setText(Integer.toString(pt.x));
locY.setText(Integer.toString(pt.y));
Dimension d=comp.getPreferredSize();
locW.setText(Integer.toString(d.width));
locH.setText(Integer.toString(d.height));
}
/** set edit object's location and size. */
public void setObjectGeometry()
{
JComponent comp=(JComponent)editVobj;
if(comp ==null || !comp.isShowing())
return;
String s;
Dimension d = comp.getSize();
int x = 0;
int y = 0;
try {
s = locX.getText().trim();
x = Integer.parseInt(s);
s = locY.getText().trim();
y = Integer.parseInt(s);
s = locH.getText().trim();
d.height=Integer.parseInt(s);
s = locW.getText().trim();
d.width=Integer.parseInt(s);
}
catch (NumberFormatException e) { }
comp.setPreferredSize(d);
Point p0 = editPanel.getLocationOnScreen();
Point p2 = new Point(x+p0.x,y+p0.y);
comp.setLocation(p2);
ParamEditUtil.relocateObj(editVobj);
}
private void abandon(){
// Remove the last appended statement and restore to the
// previous position
sshare = Util.getSessionShare();
ControlPanel ctl = Util.getControlPanel();
if(ctl!=null){
editPanel=ctl.getParamPanel().getParamLayout();
if (editPanel != null)
editPanel.restore();
ActionBar action=(ActionBar)ctl.getActionPanel();
if(action !=null)
action.restore();
}
saveGeometry();
writePersistence();
this.setVisible(false);
if(editor!=null)
editor.setVisible(false);
if(warnDialog!=null)
warnDialog.setVisible(false);
ParamEditUtil.setEditPanel((ParamPanel) null);
// if (ctl != null)
// ctl.setEditMode(false);
ParamInfo.setEditMode(false);
appIf = Util.getAppIF();
if (sshare != null ) {
LocatorHistoryList lhl = sshare.getLocatorHistoryList();
if(lhl!=null)
lhl.setLocatorHistoryToPrev();
}
if (appIf != null)
appIf.repaint();
}
/** ActionListener interface. */
public void actionPerformed(ActionEvent evt)
{
ControlPanel ctl;
String cmd = evt.getActionCommand();
if (cmd.equals("setSaveDirectory")){
if(!inAddMode){
int index=saveDirectory.getSelectedIndex();
if(index<0) // new name
updateSaveDirMenu();
lastSaveIndex=saveDirectory.getSelectedIndex();
setChangedPage(true);
}
return;
}
else if (cmd.equals("setItemType")){
if(!inAddMode){
panelType=(String)typeList.getSelectedItem();
}
return;
}
else if (cmd.equals("itemName")) {
itemName=itemEntry.getText().trim();
updateItemButtons();
return;
}
else if (cmd.equals("revertItem")) {
revertItem();
}
else if (cmd.equals("editcheck")) {
setEditItems();
return;
}
else if (cmd.equals("saveItem")) {
switch(selectedType){
case ParamInfo.PARAMLAYOUT:
saveLayout();
break;
case ParamInfo.TOOLPANEL:
saveToolPanel();
break;
case ParamInfo.PAGE:
savePage();
break;
case ParamInfo.ACTION:
saveAction();
break;
case ParamInfo.ITEM:
saveItem();
break;
case ParamInfo.PARAMPANEL:
saveParamPanel();
break;
}
return;
}
else if (cmd.equals("LoadItem")) {
switch(selectedType){
case ParamInfo.PARAMLAYOUT:
loadItem();
break;
case ParamInfo.PAGE:
loadItem();
break;
case ParamInfo.ACTION:
loadItem();
break;
case ParamInfo.ITEM:
loadItem();
break;
case ParamInfo.PARAMPANEL:
case ParamInfo.TOOLPANEL:
reloadPanel();
break;
}
}
else if (cmd.equals("autoscroll")) {
boolean b=autoscroll.isSelected();
ParamEditUtil.setAutoScroll(b);
}
else if(cmd.equals("autosave")){
autosaveButton.setSelected(true);
save_policy=AUTO_SAVE;
}
else if(cmd.equals("warnsave")){
warnsaveButton.setSelected(true);
save_policy=WARN_SAVE;
}
else if(cmd.equals("usersave")){
usersaveButton.setSelected(true);
save_policy=USER_SAVE;
}
else if (cmd.equals("ClearItem")) {
switch(selectedType){
case ParamInfo.PARAMLAYOUT:
if (editPanel != null){
setItemEdited(editPanel);
editPanel.clearAll();
}
break;
case ParamInfo.PAGE:
if (editVobj != null) {
JComponent jobj = (JComponent)editVobj;
if(jobj.getComponentCount()==0){
editVobj.destroy();
editPanel.removeTab(editVobj);
setItemEdited(editPanel);
}
else{
jobj.removeAll();
ParamEditUtil.setEditObj(editVobj);
}
}
break;
case ParamInfo.ITEM:
if (editVobj != null) {
JComponent cobj = (JComponent)editVobj;
JComponent pobj = (JComponent)cobj.getParent();
setItemEdited(editVobj);
editVobj.destroy();
pobj.remove(cobj);
ParamEditUtil.setEditObj((VObjIF)pobj);
pobj.repaint();
}
break;
}
updateItemButtons();
return;
}
else if (cmd.equals("Close")) {
// Remove the last appended statement and restore to the
// previous position
sshare = Util.getSessionShare();
saveObj();
saveGeometry();
writePersistence();
this.setVisible(false);
if(editor !=null){
editor.saveContent();
editor.setVisible(false);
}
ParamEditUtil.setEditPanel((ParamPanel) null);
//ctl = Util.getControlPanel();
// if (ctl != null)
// ctl.setEditMode(false);
ParamInfo.setEditMode(false);
if (sshare != null ) {
LocatorHistoryList lhl = sshare.getLocatorHistoryList();
if(lhl != null)
lhl.setLocatorHistoryToPrev();
}
appIf = Util.getAppIF();
if (appIf != null)
appIf.repaint();
return;
}
else if(cmd.equals("Cancel")) {
abandon();
return;
}
else if (cmd.equals("editStyles")) {
// open the DisplayOptions dialog
Util.showDisplayOptions();
return;
}
else if (cmd.equals("openLocator")) {
Util.getDefaultExp().sendToVnmr("vnmrjcmd('toolpanel','Locator','open')");
return;
}
else if (cmd.equals("openBrowser")) {
Util.getDefaultExp().sendToVnmr("vnmrjcmd('LOC browserPanel')");
return;
}
else if (cmd.equals("editItems")) {
if(editor==null){
editor=new ItemEditor("Item Editor");
}
else if(editor.isVisible())
editor.setVisible(false);
else
editor.setVisible(true);
return;
}
else if (cmd.equals("help"))
displayHelp();
}
private void getEditItems(){
int current_edits=ParamInfo.getEditItems();
edit_panels.setSelected(((current_edits & ParamInfo.PARAMPANELS)>0));
edit_actions.setSelected(((current_edits & ParamInfo.ACTIONBAR)>0));
edit_tools.setSelected(((current_edits & ParamInfo.TOOLPANELS)>0));
edit_status.setSelected(((current_edits & ParamInfo.STATUSBAR)>0));
}
private void setEditItems() {
int current_edits=0;
if(edit_panels.isSelected())
current_edits+=ParamInfo.PARAMPANELS;
if(edit_actions.isSelected())
current_edits+=ParamInfo.ACTIONBAR;
if(edit_tools.isSelected())
current_edits+=ParamInfo.TOOLPANELS;
if(edit_status.isSelected())
current_edits+=ParamInfo.STATUSBAR;
ParamInfo.setEditItems(current_edits);
}
/** set the panel to be edited */
public void setEditPanel(ParamPanel obj,boolean clrvobj) {
if(editPanel !=null && edits.size()>0){
checkEdits();
}
editPanel = obj;
if(clrvobj)
editVobj = null;
fileName=editPanel.getPanelFile();
panelName = editPanel.getPanelName();
String title=Util.getLabel("peEdit")+" "+ panelName;
if (obj == null){
setTitle(title);
return;
}
if (isLayoutPanel(obj) ){
typeList.removeAllItems();
ShufDBManager dbManager = ShufDBManager.getdbManager();
ArrayList list = dbManager.attrList.getAttrValueList(
PTYPE, Shuf.DB_PANELSNCOMPONENTS);
typeList.setModel(new DefaultComboBoxModel(new Vector(list)));
typeList.setMaximumRowCount(list.size());
panelType = editPanel.getPanelType();
typeList.setSelectedItem(panelType);
setTitle(title+" "+Util.getLabel("peFor")+" "+editPanel.getLayoutName());
}
else {
setTitle(title);
}
obj.setSnap(true);
ParamEditUtil.setSnap(true);
String d = (String) snapSize.getText();
d.trim();
if (d.length() < 1) {
d = "5";
snapSize.setText(d);
}
if (d.length() > 0) {
ParamEditUtil.setSnapGap(d);
obj.setSnapGap(d);
}
obj.setGrid(true);
Color c=Util.getGridColor();
obj.setGridColor(c);
makeSaveDirMenu();
setDebug("setEditPanel : "+fileName);
}
ParamPanel getParamPanel(VObjIF obj){
Component comp = (Component)obj;
while (comp != null) {
if (comp instanceof ParamPanel) {
return (ParamPanel)comp;
}
comp = comp.getParent();
}
return null;
}
ParamLayout getParamLayout(VObjIF obj){
Component comp = (Component)obj;
while (comp != null) {
if (comp instanceof ParamLayout) {
return (ParamLayout)comp;
}
comp = comp.getParent();
}
return null;
}
VGroup getPage(VObjIF obj){
ParamLayout panel=getParamLayout(obj);
if(panel==null)
return null;
Component comp = (Component)obj;
while (comp != null && comp != panel) {
if (ParamPanel.isTabGroup(comp)) {
return (VGroup)comp;
}
comp = comp.getParent();
}
return null;
}
ActionBar getAction(VObjIF obj){
Component comp = (Component)obj;
while (comp != null) {
if(comp instanceof ActionBar)
return (ActionBar)comp;
comp = comp.getParent();
}
return null;
}
void checkEdits(){
if(DebugOutput.isSetFor("ParamInfoSave"))
saveDebug();
switch(save_policy){
case AUTO_SAVE:
autoSave();
break;
case WARN_SAVE:
warnSave();
break;
case USER_SAVE:
break;
}
}
void autoSave() {
for (int i = 0; i < edits.size(); i++) {
VObjIF obj = edits.get(i);
if (obj instanceof ActionBar)
saveAction();
else if (obj == editPanel)
saveLayout();
else{
String name=defaultItemName(obj);
saveObj();
savePage(obj,name);
}
}
edits.clear();
}
void warnSave() {
if(warnDialog==null){
warnDialog=new SaveWarnDialog("");
Point p=getLocation();
Dimension d=getSize();
p.x+=d.width;
warnDialog.setLocation(p);
}
//warnDialog.setTitle("Unsaved Components of <"+editPanel.getPanelName()+">");
warnDialog.setTitle("Unsaved Components");
warnDialog.showEdits();
}
void saveDebug(){
for(int i=0;i<edits.size();i++){
VObjIF obj=edits.get(i);
if(editPanel instanceof ActionBar)
Messages.postDebug("Save Needed: Action panel "+editPanel.getPanelName());
else
if(editPanel instanceof ParamLayout){
if(obj==editPanel)
Messages.postDebug("Save Needed: Panel "+editPanel.getPanelName());
else
Messages.postDebug("Save Needed: "+ editPanel.getPanelName()+" Page "+obj.getAttribute(LABEL));
}
}
}
void addEditItem(VObjIF obj){
if(!edits.contains(obj)){
if(obj instanceof ParamPanel)
System.out.println("Adding panel:"+((ParamPanel)obj).getPanelName());
else
System.out.println("Adding page:"+obj.getAttribute(LABEL));
edits.add(obj);
if(save_policy==WARN_SAVE)
warnSave();
}
}
void rmvEditItem(VObjIF obj){
if(!edits.contains(obj)){
//setDebug("Removing edit item:"+obj.getAttribute(LABEL));
edits.remove(obj);
}
}
public void setItemEdited(VObjIF vobj){
if(vobj==null)
return;
VObjIF edit=null;
switch(selectedType){
case ParamInfo.PAGE:
addEditItem(vobj);
break;
case ParamInfo.PARAMLAYOUT:
addEditItem(vobj);
break;
case ParamInfo.ITEM:
edit=getPage(vobj);
if(edit!=null){
addEditItem(edit);
break;
} // note: intentional fall-through
case ParamInfo.ACTION:
edit=getAction(vobj);
if(edit!=null)
addEditItem(edit);
break;
}
}
/** Set the active edit object. */
public void setEditElement(VObjIF vobj) {
boolean newobj=false;
if(vobj != editVobj){
if(editVobj != null)
saveObj();
itemName=defaultItemName(vobj);
newobj=true;
tabgrp=null;
}
editVobj = vobj;
if(!newobj){
return;
}
itemEntry.setText(itemName);
inSetMode = true;
getObjectGeometry();
int oldType=selectedType;
if (vobj == null) {
editPanel=null;
}
else{
typeOfItem.setText(vobj.getAttribute(TYPE));
String data = vobj.getAttribute(FONT_STYLE);
textStyle.setStyleObject(vobj);
if(data != null && textStyle.isType(data))
textStyle.setType(data);
else
textStyle.setDefaultType();
if(vobj instanceof ParamPanel)
selectedType=((ParamPanel)vobj).getType();
else if(isActionPanel(vobj))
selectedType=ParamInfo.ACTION;
else if(isTabPage(vobj))
selectedType=ParamInfo.PAGE;
else
selectedType=ParamInfo.ITEM;
String spath=getSourcePath(itemName);
if(spath==null)
itemSource.setText("");
else
itemSource.setText(spath);
if (vobj instanceof VEditIF)
showVariableFields((VEditIF)vobj);
else
showDefaultFields(vobj);
}
isNewType=(oldType==selectedType)?false:true;
updateItemButtons();
revertButton.setEnabled(userFileExists());
adjustAttrPanelSize();
inSetMode = false;
setDebug("setEditElement : "+itemName);
}
//================ private methods ==================================
private void postInfo(String s){
if(DebugOutput.isSetFor("pedit"))
Messages.postInfo(s);
setDebug(s);
}
private boolean hasReference(VObjIF obj){
if(obj==null)
return false;
if(itemName==null || itemName.length()==0)
return false;
String fname=itemName;
String ext=FileUtil.fileExt(fname);
if(ext !=null && ext.contains(".xml"))
FileUtil.setOpenAll(false);
else
FileUtil.setOpenAll(true);
fname=fname.replaceFirst(".xml","");
if(editPanel !=null && isTabPage(obj)){
if(FileUtil.findReference(editPanel.getLayoutName(),fname+".xml")){
FileUtil.setOpenAll(true);
return true;
}
}
FileUtil.setOpenAll(true);
return FileUtil.fileExists("PANELITEMS/"+itemName+".xml");
}
private String getSavePath(String fname){
String base=FileUtil.usrdir();
String spath=null;
switch(selectedType){
case ParamInfo.ITEM:
spath=FileUtil.fullPath(base,"PANELITEMS/"+fname+".xml");
break;
case ParamInfo.PARAMPANEL:
spath=FileUtil.fullPath(base,"INTERFACE/"+fname+".xml");
break;
case ParamInfo.TOOLPANEL:
spath=FileUtil.fullPath(base,"TOOLPANELS/"+fname+".xml");
break;
default:
if (editPanel != null) {
String path=editPanel.getLayoutName();
if(path!=null)
spath=FileUtil.getLayoutPath(path,fname+".xml");
}
break;
}
return spath;
}
private String getSourcePath(String name){
String spath=null;
String fname=name;
if(fname==null)
return null;
String ext=FileUtil.fileExt(fname);
if(ext!=null && ext.contains(".xml"))
FileUtil.setOpenAll(false);
else
FileUtil.setOpenAll(true);
fname=fname.replaceFirst(".xml","");
if(name!=null && name.length()>0) {
switch(selectedType){
case ParamInfo.ITEM:
spath=FileUtil.openPath("PANELITEMS/"+fname+".xml");
break;
case ParamInfo.PARAMPANEL:
spath=FileUtil.openPath("INTERFACE/"+fname+".xml");
break;
default:
if (editPanel != null) {
String path=editPanel.getLayoutName();
if(path!=null)
spath=FileUtil.getLayoutPath(path,fname+".xml");
}
break;
}
}
FileUtil.setOpenAll(true);
return spath;
}
private String defaultItemName(VObjIF obj){
String name="";
if(obj==null){
return "";
}
if(obj instanceof ParamPanel){
name=((ParamPanel)obj).getPanelFile();
if(name !=null)
name=name.replace(".xml","");
}
else if(isActionPanel(obj)){
ActionBar action=getAction(obj);
name=action.getPanelFile();
name=name.replace(".xml","");
}
else if((obj instanceof VGroup) || (obj instanceof VTabbedPane)){
name=obj.getAttribute(REFERENCE);
if(name==null || name.length()==0){
name=obj.getAttribute(LABEL);
JComponent p=(JComponent)obj;
if(name==null || name.length()==0){
int nLength = p.getComponentCount();
for (int i = 0; i < nLength; i++) {
Component comp = p.getComponent(i);
if (comp instanceof VTab) {
name=((VObjIF)comp).getAttribute(LABEL);
if(name!=null && name.length()>0)
break;
}
}
}
// if main group has no label try children ..
if(name==null || name.length()==0){
int nLength = p.getComponentCount();
for (int i = 0; i < nLength; i++) {
Component comp = p.getComponent(i);
if (comp instanceof VLabel || comp instanceof VGroup) {
name=((VObjIF)comp).getAttribute(LABEL);
if(name!=null && name.length()>0)
break;
}
}
}
}
}
if(name!=null && name.length()>=0){
String s="";
StringTokenizer tok=new StringTokenizer(name);
while(tok.hasMoreTokens())
s+=tok.nextToken();
name=s.trim();
}
String spath=getSourcePath(name);
if(spath !=null){
name=FileUtil.pathName(spath);
name=name.replace(".xml","");
}
return name;
}
private void showVariableFields(VEditIF vobj) {
int i;
// Remove existing fields
attrPan.removeAll();
// Put in the fields for this object
Object attrs[][] = vobj.getAttributes();
if(attrs==null)
return;
int nats = attrs.length;
for (i = 0; i < nats; i++) {
vwidgIsSet[i] = true;
int attrCode = ((Integer) attrs[i][0]).intValue();
if (vpans[i] == null)
vpans[i] = new JPanel();
else
vpans[i].removeAll();
vlbs[i] = new JLabel(((String) attrs[i][1]).trim());
vpans[i].add(vlbs[i]);
String data = vobj.getAttribute(attrCode);
String type = "edit";
String enabled = "true";
if (attrs[i].length > 2) {
String str = (String) attrs[i][2];
if (str.equals("true") || str.equals("false"))
enabled = str;
else
type = str;
}
if (type.equals("edit")) {
vpans[i].setLayout(xLayout);
VUndoableText jtxt = new VUndoableText("", textLen);
vwidgs[i] = jtxt;
if (data != null)
jtxt.setText(data);
if (enabled.equals("true")) {
jtxt.setActionCommand(String.valueOf(attrCode));
jtxt.setEditable(true);
} else {
jtxt.setEditable(false);
}
jtxt.addActionListener(attributeChangeListener);
} else if (type.equals("menu") || type.equals("style")
|| type.equals("color")) {
// Use menu to take attribute value
JComboBox jcombo;
vpans[i].setLayout(tLayout);
if (type.equals("menu"))
jcombo = new JComboBox((Object[]) attrs[i][3]);
else {
jcombo = new StyleChooser(type);
if (type.equals("color") && data == null)
data = "transparent";
}
jcombo.setOpaque(true);
jcombo.setEditable(false);
jcombo.setBackground(null);
vwidgs[i] = jcombo;
vwidgIsSet[i] = false;
jcombo.setActionCommand(String.valueOf(attrCode));
jcombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
comboAction(evt);
}
});
if (data != null) {
int n = jcombo.getItemCount();
for (int j = 0; j < n; j++) {
String str = ((String) jcombo.getItemAt(j));
if (data.equalsIgnoreCase(str)) {
jcombo.setSelectedIndex(j);
vwidgIsSet[i] = true;
break;
}
}
}
} else if (type.equals("radio")) {
// Use button group to take attribute value
vpans[i].setLayout(tLayout);
String[] names = (String[]) attrs[i][3];
int n = names.length;
RadioGroup rgroup = new RadioGroup(attrCode);
vwidgs[i] = rgroup;
for (int j = 0; j < n; j++) {
rgroup.add(names[j]);
}
if (vobj instanceof VGroup) {
if (attrCode == TAB)
tabgrp = rgroup;
}
if (data != null) {
rgroup.setSelectedItem(data);
}
}
vpans[i].add(vwidgs[i]);
attrPan.add(vpans[i]);
}
//setBgColor(getComponents(), Util.getBgColor());
}
private void showDefaultFields(VObjIF vobj) {
int i;
// Remove existing fields
attrPan.removeAll();
// Put in the correct fields;
// make inactive
i = ILABEL;
if (vobj != null && vobj instanceof VText) {
editablePan.setVisible(true);
pans[ILABEL].setVisible(false);
attrPan.add(editablePan);
i = 1;
String ed = vobj.getAttribute(EDITABLE);
if (ed != null && ed.equals("yes"))
editableOn.setSelected(true);
else
editableOff.setSelected(true);
} else {
editablePan.setVisible(false);
pans[ILABEL].setVisible(true);
}
while (i < numItems) {
if (i == CMD_2) {
if (vobj != null && !(vobj instanceof VEntry))
attrPan.add(pans[i]);
} else if (i == DIGITS) {
if (vobj != null && vobj instanceof VEntry)
attrPan.add(pans[i]);
} else
attrPan.add(pans[i]);
txts[i].setText("");
txts[i].setEnabled(false);
lbs[i].setEnabled(false);
i++;
}
if (vobj == null)
return;
txts[VAR].setEnabled(true);
lbs[VAR].setEnabled(true);
String data = vobj.getAttribute(VARIABLE);
if (data != null)
txts[VAR].setText(data);
txts[SHOWX].setEnabled(true);
lbs[SHOWX].setEnabled(true);
data = vobj.getAttribute(SHOW);
if (data != null)
txts[SHOWX].setText(data);
if ((vobj instanceof VLabel) || (vobj instanceof VButton) ||
(vobj instanceof VRadio) || (vobj instanceof VToggle) ||
(vobj instanceof VCheck) || (vobj instanceof VTab) ||
(vobj instanceof VMenu)) {
txts[ILABEL].setEnabled(true);
lbs[ILABEL].setEnabled(true);
data = vobj.getAttribute(LABEL);
if (data != null)
txts[ILABEL].setText(data);
}
if (vobj instanceof VMenu) {
txts[CHOICE].setEnabled(true);
lbs[CHOICE].setEnabled(true);
txts[CHVALS].setEnabled(true);
lbs[CHVALS].setEnabled(true);
data = vobj.getAttribute(SETCHOICE);
if (data != null)
txts[CHOICE].setText(data);
data = vobj.getAttribute(SETCHVAL);
if (data != null)
txts[CHVALS].setText(data);
}
if (vobj instanceof VScroll) {
txts[CHVALS].setEnabled(true);
lbs[CHVALS].setEnabled(true);
data = vobj.getAttribute(SETCHVAL);
if (data != null)
txts[CHVALS].setText(data);
}
if ((vobj instanceof VLabel) || (vobj instanceof VTab)) {
return;
}
if (!(vobj instanceof VButton)) {
txts[IVAL].setEnabled(true);
lbs[IVAL].setEnabled(true);
data = vobj.getAttribute(SETVAL);
if (data != null)
txts[IVAL].setText(data);
}
txts[CMD_1].setEnabled(true);
lbs[CMD_1].setEnabled(true);
data = vobj.getAttribute(CMD);
if (data != null)
txts[CMD_1].setText(data);
if ((vobj instanceof VCheck) || (vobj instanceof VToggle)
|| (vobj instanceof VRadio)) {
txts[CMD_2].setEnabled(true);
lbs[CMD_2].setEnabled(true);
data = vobj.getAttribute(CMD2);
if (data != null)
txts[CMD_2].setText(data);
}
if (vobj instanceof VEntry) {
txts[DIGITS].setEnabled(true);
lbs[DIGITS].setEnabled(true);
data = vobj.getAttribute(NUMDIGIT);
if (data != null)
txts[DIGITS].setText(data);
}
//setBgColor(getComponents(), Util.getBgColor());
}
private void saveObj() {
if (editVobj instanceof VEditIF) {
VEditIF vobj = (VEditIF) editVobj;
Object attrs[][] = vobj.getAttributes();
if(attrs!=null){
int nSize = attrs.length;
for (int i = 0; i < nSize; i++) {
String str = null;
int attrval = ((Integer) attrs[i][0]).intValue();
if (vwidgs[i] instanceof JTextField) {
str = ((JTextField) vwidgs[i]).getText();
} else if (vwidgs[i] instanceof JComboBox) {
str = (String) ((JComboBox) vwidgs[i]).getSelectedItem();
} else if (vwidgs[i] instanceof RadioGroup) {
str = (String) ((RadioGroup) vwidgs[i]).getSelectedItem();
} else if (vwidgs[i] instanceof VColorChooser) {
str = ((VColorChooser) vwidgs[i]).getAttribute(KEYVAL);
}
if (vwidgIsSet[i]) {
if (str != null && str.length() > 0)
vobj.setAttribute(attrval, str);
else
vobj.setAttribute(attrval, null);
}
}
}
} else {
if (txts[ILABEL].isEnabled()) {
setObjAttr(LABEL, ILABEL);
}
if (txts[CHOICE].isEnabled()) {
setObjAttr(SETCHOICE, CHOICE);
}
if (txts[CHVALS].isEnabled()) {
setObjAttr(SETCHVAL, CHVALS);
}
if (txts[VAR].isEnabled()) {
setObjAttr(VARIABLE, VAR);
}
if (txts[CMD_1].isEnabled()) {
setObjAttr(CMD, CMD_1);
}
if (txts[CMD_2].isEnabled()) {
setObjAttr(CMD2, CMD_2);
}
if (txts[IVAL].isEnabled()) {
setObjAttr(SETVAL, IVAL);
}
if (txts[SHOWX].isEnabled()) {
setObjAttr(SHOW, SHOWX);
}
if (txts[DIGITS].isEnabled()) {
setObjAttr(NUMDIGIT, DIGITS);
}
}
ParamEditUtil.clearDummyObj();
}
private void updateSaveDirMenu(){
if (editPanel == null)
return;
String edit=(String)saveDirectory.getSelectedItem(); // edit box
if(lastSaveIndex==SAVE_IN_LAYOUT)
editPanel.setLayoutName(edit);
else
editPanel.setDefaultName(edit);
if(editPanel.getLayoutName()!=null)
setTitle("Edit "+ panelName+" panel for "+editPanel.getLayoutName());
//else
// setTitle("Edit "+ panelName);
if(editVobj==editPanel){
showVariableFields(editPanel); // update default edit field
}
makeSaveDirMenu();
}
private void updateLocator(String file, String path) {
if(FillDBManager.locatorOff())
return;
String usr = System.getProperty("user.name");
AddToLocatorViaThread addThread = new AddToLocatorViaThread(
Shuf.DB_PANELSNCOMPONENTS, file, path, usr, true);
addThread.setPriority(Thread.MIN_PRIORITY);
addThread.setName("AddToLocatorViaThread");
addThread.start();
}
/** save a parameter panel. */
private void saveLayout(VObjIF obj){
ParamLayout layout=getParamLayout(obj);
if (layout == null)
return;
String name=layout.getPanelFile();
LayoutBuilder.clrShufflerString();
LayoutBuilder.setShufflerString(ETYPE,"panels");
LayoutBuilder.setShufflerString(PTYPE,panelType);
LayoutBuilder.setShufflerString(NAME,panelName);
String dir= null;
if(lastSaveIndex==SAVE_IN_LAYOUT)
dir=layout.getSaveDir();
else
dir=layout.getDefaultDir();
if(dir==null){
Messages.postError("error saving panel "+name);
return;
}
dir+="/"+name;
LayoutBuilder.writeToFile(layout, dir, true);
updateLocator(name, dir);
postInfo("Saving Folder : "+name);
}
/** save a parameter panel. */
private void saveLayout(){
saveObj();
saveLayout(editPanel);
rmvEditItem(editPanel);
}
/** save action panel. */
private void saveAction(VObjIF obj){
ActionBar action=getAction(obj);
if(action == null){
Messages.postError("error saving Action panel for "+fileName);
return;
}
String name=action.getPanelFile();
String dir= null;
if(lastSaveIndex==SAVE_IN_LAYOUT)
dir=action.getSaveDir();
else
dir=action.getDefaultDir();
if(dir==null){
Messages.postError("error saving "+name);
return;
}
dir+="/"+name;
LayoutBuilder.writeToFile(action, dir, true);
postInfo("Saving Action : "+name);
}
/** save action panel. */
private void saveAction(){
if(editPanel == null || editVobj == null)
return;
saveObj();
saveAction(editPanel);
rmvEditItem(editPanel);
}
/** save a page. */
private void restorePage(VObjIF obj){
ParamLayout layout=getParamLayout(obj);
if (layout == null)
return;
String pagename=defaultItemName(obj);
String file=pagename;
file+=".xml";
String path=FileUtil.getLayoutPath(layout.getLayoutName(), file);
if(path==null){
Messages.postError("error restoring page "+file);
return;
}
layout.reloadObject(obj, path, true,false);
}
/** save a page. */
private void savePage(VObjIF obj, String pagename){
ParamLayout layout=getParamLayout(obj);
if (layout == null)
return;
LayoutBuilder.clrShufflerString();
LayoutBuilder.setShufflerString(ETYPE,"pages");
LayoutBuilder.setShufflerString(PTYPE,panelType);
String file=pagename;
LayoutBuilder.setShufflerString(NAME,file);
file+=".xml";
String dir= null;
if(lastSaveIndex==SAVE_IN_LAYOUT)
dir=editPanel.getSaveDir();
else
dir=editPanel.getDefaultDir();
if(dir==null){
Messages.postError("error saving page "+file);
return;
}
String path=dir+"/"+file;
obj.setAttribute(REFERENCE,FileUtil.fileName(pagename));
obj.setAttribute(USEREF,"no");
LayoutBuilder.writeToFile((JComponent)obj, path, false);
obj.setAttribute(USEREF,"yes");
updateLocator(file, path);
ParamEditUtil.setChangedPage(false);
changed_page=false;
String name=layout.getPanelFile();
if(name != null && lastSaveIndex==SAVE_IN_LAYOUT){ // changed_panel
LayoutBuilder.clrShufflerString();
LayoutBuilder.setShufflerString(ETYPE,"panels");
LayoutBuilder.setShufflerString(PTYPE,panelType);
LayoutBuilder.setShufflerString(NAME,panelName);
String fname=name;
String ext=FileUtil.fileExt(itemName);
if(ext !=null)
fname=FileUtil.fileName(name)+ext+".xml";
path=dir+"/"+fname;
postInfo("Saving Folder : "+fname);
LayoutBuilder.writeToFile(layout, path, true);
}
postInfo("Saving Page : "+file);
}
/** save selected page. */
private void savePage(){
if(editPanel == null || editVobj == null)
return;
saveObj();
itemName=itemEntry.getText().trim();
savePage(editVobj,itemName);
updateItemButtons();
rmvEditItem(editVobj);
}
/** save an item. */
private void saveItem(){
if(editPanel == null || editVobj == null)
return;
saveObj();
LayoutBuilder.clrShufflerString();
if((editVobj instanceof VGroup) || (editVobj instanceof VTabbedPane))
LayoutBuilder.setShufflerString(ETYPE,"groups");
else
LayoutBuilder.setShufflerString(ETYPE,"elements");
LayoutBuilder.setShufflerString(PTYPE,panelType);
itemName=itemEntry.getText().trim();
String file=itemName;
LayoutBuilder.setShufflerString(NAME,file);
file+=".xml";
String dir=FileUtil.savePath("PANELITEMS");
String path=dir+"/"+file;
postInfo("Saving Item : "+file);
editVobj.setAttribute(REFERENCE,FileUtil.fileName(itemName));
editVobj.setAttribute(USEREF,"no");
LayoutBuilder.writeToFile((JComponent)editVobj, path, false);
updateItemButtons();
updateLocator(file, path);
}
/** save a ParamPanel. */
private void saveParamPanel(){
if(editPanel == null || editVobj == null)
return;
saveObj();
itemName=itemEntry.getText().trim();
String file=itemName;
file+=".xml";
String dir=FileUtil.savePath("INTERFACE");
String path=dir+"/"+file;
postInfo("Saving Panel : "+file);
editVobj.setAttribute(REFERENCE,FileUtil.fileName(itemName));
editVobj.setAttribute(USEREF,"no");
LayoutBuilder.writeToFile((JComponent)editVobj, path, false);
updateItemButtons();
}
/** save a tool panel. */
private void saveToolPanel(){
if (editPanel == null)
return;
String dir= getSavePath(itemName);
if(dir==null){
Messages.postError("error saving panel "+dir);
return;
}
LayoutBuilder.writeToFile(editPanel, dir, true);
}
private void setDefaultItemName(){
itemName=defaultItemName(editVobj);
itemEntry.setText(itemName);
updateItemButtons();
}
private boolean isTabGroup(VObjIF obj){
if(obj !=null && obj instanceof VGroup){
String label=obj.getAttribute(LABEL);
if(label !=null && label.length()>0)
return true;
}
return false;
}
private boolean isTabPage(VObjIF obj){
if(obj !=null && obj instanceof VGroup){
if(((VGroup)obj).isTabGroup())
return true;
}
return false;
}
private boolean isActionPanel(VObjIF obj){
if(obj instanceof ActionBar)
return true;
if(obj !=null && obj instanceof VGroup){
Container p=((VGroup)obj).getParent();
if(p !=null && p instanceof ActionBar)
return true;
}
return false;
}
private boolean isParamLayout(VObjIF obj){
if(obj instanceof ParamLayout)
return true;
if(obj !=null && obj instanceof VGroup){
Container p=((VGroup)obj).getParent();
if(p !=null && p instanceof ParamLayout)
return true;
}
return false;
}
private boolean isLayoutPanel(VObjIF obj){
if(isActionPanel(obj) || isParamLayout(obj))
return true;
return false;
}
private void reloadPanel(){
if(editVobj==null || editPanel==null)
return;
if(itemName==null || itemName.length()==0)
return;
// String name=itemEntry.getText().trim();
// String ext=FileUtil.fileExt(name);
// if(ext!=null && ext.contains(".xml"))
// FileUtil.setOpenAll(false);
// name=name.replaceFirst(".xml","");
// String fname=name+".xml";
// String msgName=name;
String path=getSelectedPath();
//String path=FileUtil.openPath("INTERFACE/"+fname);
VObjIF vobj=null;
if(path!=null){
postInfo("Reloading : "+path);
vobj=editPanel.reloadContent(path);
}
if(path==null || vobj==null){
Messages.postError("could not load "+path);
}
setEditElement(vobj);
editVobj=vobj;
FileUtil.setOpenAll(true);
}
private void loadItem(){
if(editVobj==null || editPanel==null)
return;
if(itemName==null || itemName.length()==0)
return;
String path=null;
String name=itemEntry.getText().trim();
String ext=FileUtil.fileExt(name);
if(ext!=null && ext.contains(".xml"))
FileUtil.setOpenAll(false);
name=name.replaceFirst(".xml","");
String fname=name+".xml";
String msgName=name;
boolean tabpage=isTabPage(editVobj);
boolean actionpanel=isActionPanel(editVobj);
if(tabpage||(editVobj==editPanel)||actionpanel)
path=FileUtil.getLayoutPath(editPanel.getLayoutName(),fname);
if(path==null)
path=FileUtil.openPath("PANELITEMS/"+fname);
if(path!=null){
postInfo("Reloading : "+path);
if(editVobj==editPanel){
editPanel.restore();
}
else{
boolean expand_page=false;
if(tabpage ){
String oldref=editVobj.getAttribute(REFERENCE);
if(!name.equals(oldref))
expand_page=true;
}
VObjIF vobj=editPanel.reloadObject(editVobj,path,expand_page,true);
if(vobj!=editVobj)
setEditElement(vobj);
editVobj=vobj;
if(vobj !=null){
if(tabpage){
vobj.setAttribute(USEREF,"yes");
setChangedPage(false);
}
else
vobj.setAttribute(USEREF,"no");
}
}
}
else{
Messages.postError("could not load "+msgName);
}
itemEntry.setText(name);
FileUtil.setOpenAll(true);
}
private String getSelectedPath(){
String spath=null;
switch(selectedType){
case ParamInfo.PARAMLAYOUT:
case ParamInfo.ACTION:
case ParamInfo.PAGE:
case ParamInfo.TOOLPANEL:
spath=getSourcePath(itemName);
break;
case ParamInfo.PARAMPANEL:
spath=FileUtil.openPath("INTERFACE/"+itemName+".xml");
break;
case ParamInfo.ITEM:
spath=FileUtil.openPath("PANELITEMS/"+itemName+".xml");
break;
}
//if(spath!=null)
return spath;
//return getSavePath(itemName);
}
private void revertItem(){
String spath=getSelectedPath();
if(spath==null || !spath.contains(FileUtil.usrdir()))
return;
File file=new File(spath);
file.delete();
switch(selectedType){
case ParamInfo.PARAMPANEL:
case ParamInfo.TOOLPANEL:
reloadPanel();
break;
}
updateItemButtons();
}
private boolean userFileExists(){
String spath=getSelectedPath();
if(spath==null)
return false;
return spath.contains(FileUtil.usrdir());
}
private void updateItemButtons(){
String itemStr="";
String spath=null;
switch(selectedType){
case ParamInfo.PARAMLAYOUT:
clearButton.setEnabled(true);
saveButton.setEnabled(true);
spath=getSourcePath(itemName);
if(spath!=null&&FileUtil.pathName(spath).equals(fileName))
reloadButton.setEnabled(true);
else
reloadButton.setEnabled(false);
itemStr=Util.getLabel("peFolder");
break;
case ParamInfo.TOOLPANEL:
clearButton.setEnabled(true);
saveButton.setEnabled(true);
spath=getSourcePath(itemName);
if(spath!=null&&FileUtil.pathName(spath).equals(fileName))
reloadButton.setEnabled(true);
else
reloadButton.setEnabled(false);
if(spath==null)
spath=getSavePath(itemName);
itemStr=Util.getLabel("ToolPanel");
break;
case ParamInfo.ACTION:
clearButton.setEnabled(true);
saveButton.setEnabled(true);
spath=getSourcePath(itemName);
if(spath!=null&&FileUtil.pathName(spath).equals(fileName))
reloadButton.setEnabled(true);
else
reloadButton.setEnabled(false);
itemStr=Util.getLabel("Action");
break;
case ParamInfo.PAGE:
spath=getSourcePath(itemName);
itemStr=Util.getLabel("pePage");
if(editVobj==null)
clearButton.setEnabled(false);
else
clearButton.setEnabled(true);
if(tabgrp != null){
if(isTabGroup(editVobj))
tabgrp.setEnabled(true);
else
tabgrp.setEnabled(false);
}
boolean b=(editVobj!=null && itemName!=null && itemName.length()>0);
reloadButton.setEnabled(hasReference(editVobj));
saveButton.setEnabled(b);
break;
case ParamInfo.PARAMPANEL:
clearButton.setEnabled(true);
saveButton.setEnabled(true);
spath=getSourcePath(itemName);
reloadButton.setEnabled(true);
break;
}
itemLabel.setText(itemStr);
//spath=getSourcePath(itemName);
if(spath==null)
itemSource.setText("");
else
itemSource.setText(spath);
if(isNewType)
updateSaveDir();
revertButton.setEnabled(userFileExists());
getEditItems();
}
private void makeSaveDirMenu(){
if (editPanel == null)
return;
inAddMode=true;
saveDirectory.removeAllItems();
saveDirectory.addItem(editPanel.getLayoutName());
saveDirectory.addItem(editPanel.getDefaultName());
saveDirectory.setSelectedIndex(lastSaveIndex);
inAddMode=false;
}
private void updateSaveDir(){
inAddMode=true;
switch(selectedType){
case ParamInfo.PARAMLAYOUT:
case ParamInfo.PAGE:
case ParamInfo.ACTION:
InLabel.setVisible(true);
saveDirectory.setSelectedIndex(lastSaveIndex);
saveDirectory.setVisible(true);
break;
case ParamInfo.PARAMPANEL:
case ParamInfo.ITEM:
case ParamInfo.TOOLPANEL:
saveDirectory.setVisible(false);
InLabel.setVisible(false);
break;
}
inAddMode=false;
}
private void savePrefAttr() {
sshare = Util.getSessionShare();
if (sshare != null) {
sshare.userInfo().put("snap", "on");
sshare.userInfo().put("snapSize", snapSize.getText());
if(ParamEditUtil.getAutoScroll())
sshare.userInfo().put("autoscroll", "true");
else
sshare.userInfo().put("autoscroll", "false");
sshare.userInfo().put("savepolicy",Integer.toString(save_policy));
}
}
private void initPanel() {
sshare = Util.getSessionShare();
if (sshare != null) {
String data = (String) sshare.userInfo().get("snap");
data = (String) sshare.userInfo().get("snapSize");
if (data == null)
data = "5";
try {
Integer.parseInt(data);
}
catch (NumberFormatException e) {
data = "5";
}
snapSize.setText(data);
data=(String) sshare.userInfo().get("autoscroll");
if(data !=null && data.equals("true"))
ParamEditUtil.setAutoScroll(true);
else
ParamEditUtil.setAutoScroll(false);
autoscroll.setSelected(ParamEditUtil.getAutoScroll());
data = (String) sshare.userInfo().get("savepolicy");
if(data!=null)
save_policy=Integer.parseInt(data);
switch(save_policy){
case USER_SAVE: usersaveButton.setSelected(true); break;
case WARN_SAVE: warnsaveButton.setSelected(true); break;
case AUTO_SAVE: autosaveButton.setSelected(true); break;
}
}
}
private void adjustAttrPanelSize() {
Dimension dim;
int h = 0;
int w = 0;
int k;
int n = attrPan.getComponentCount();
for ( k = 0; k < n; k++) {
Component m = attrPan.getComponent(k);
dim = m.getPreferredSize();
h += dim.height+2;
}
w = windowWidth - 8;
if (h > scrollH)
w = w - sbW;
attrPan.setPreferredSize(new Dimension(w, h));
attrPan.repaint();
}
private JButton addButton(String label, Container p, Object obj, String cmd)
{
JButton but = new JButton(label);
but.setActionCommand(cmd);
but.addActionListener((ActionListener) obj);
but.setFont(font);
p.add(but);
return but;
}
private void setObjAttr(int attr, int id) {
if (editVobj == null)
return;
String data = txts[id].getText().trim();
if (data == null || data.length() < 1)
editVobj.setAttribute(attr, null);
else
editVobj.setAttribute(attr, data);
}
private void comboAction(ActionEvent e) {
if (editVobj != null) {
String cmd = e.getActionCommand();
JComboBox combo = (JComboBox)e.getSource();
String sel = (String)combo.getSelectedItem();
try {
int attr = Integer.parseInt(cmd);
editVobj.setAttribute(attr, sel);
} catch (NumberFormatException exception) {
Messages.postError("ParamInfoPanel.comboAction");
}
//setItemEdited(editVobj);
}
}
private void initAction() {
txts[CHOICE].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(SETCHOICE, CHOICE);
}
});
txts[CHVALS].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(SETCHVAL, CHVALS);
}
});
txts[VAR].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(VARIABLE, VAR);
}
});
txts[CMD_1].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(CMD, CMD_1);
}
});
txts[CMD_2].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(CMD2, CMD_2);
}
});
txts[IVAL].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(SETVAL, IVAL);
}
});
txts[SHOWX].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(SHOW, SHOWX);
}
});
txts[ILABEL].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(LABEL, ILABEL);
}
});
txts[DIGITS].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(NUMDIGIT, DIGITS);
}
});
txts[STATVARS].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setObjAttr(STATPAR, STATVARS);
}
});
snapSize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String s = snapSize.getText().trim();
if (s.length() < 1)
s = "0";
int k = 1;
try {
k = Integer.parseInt(s);
}
catch (NumberFormatException e) {
k = 0;
}
if (k < 1) {
snapSize.setText("5");
k = 5;
}
if (editPanel != null)
editPanel.setSnapGap(k);
ParamEditUtil.setSnapGap(k);
if(editor !=null)
editor.setSnapGrid(k);
}
});
locX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (editVobj == null)
return;
saveObj();
setObjectGeometry();
}
});
locY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (editVobj == null)
return;
saveObj();
setObjectGeometry();
}
});
locW.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (editVobj == null)
return;
saveObj();
setObjectGeometry();
}
});
locH.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (editVobj == null)
return;
saveObj();
setObjectGeometry();
}
});
editableOn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (editVobj != null)
editVobj.setAttribute(EDITABLE, "yes");
}
});
editableOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (editVobj != null)
editVobj.setAttribute(EDITABLE, "no");
}
});
}
//================ private classes ==================================
private class SaveWarnDialog extends ModelessDialog
implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton saveButton=new JButton("Save");
private JButton restoreButton=new JButton("Restore");
private JPanel panel=null;
protected TableCellRenderer m_messageCellRenderer;
private JScrollPane scrollPane = null;
EasyJTable m_table=null;
public SaveWarnDialog(String title){
super(title);
setVisible(false);
panel=new JPanel();
panel.setLayout(new BorderLayout());
panel.setPreferredSize(new Dimension(200,200));
m_table = new EasyJTable(new DefaultTableModel(0, 1));
scrollPane = new JScrollPane(m_table);
m_messageCellRenderer = new MessageCellRenderer();
m_table.setDefaultRenderer(m_table.getColumnClass(0),
m_messageCellRenderer);
m_table.setDefaultEditor(m_table.getColumnClass(0), null);
m_table.setTableHeader(null);
m_table.setShowGrid(false);
m_table.setRowMargin(0);
int[] policy =
{REASON_INITIAL_VIEW | STATE_ANY | ACTION_SCROLL_TO_BOTTOM,
REASON_ANY | STATE_BOTTOM_SHOWS | ACTION_SCROLL_TO_BOTTOM};
m_table.setScrollPolicy(policy);
panel.add(scrollPane,BorderLayout.CENTER);
add(panel);
saveButton.setEnabled(true);
saveButton.setActionCommand("Save");
saveButton.addActionListener(this);
buttonPane.add(saveButton, 1);
restoreButton.setEnabled(true);
restoreButton.addActionListener(this);
restoreButton.setActionCommand("Revert");
buttonPane.add(restoreButton, 2);
closeButton.setActionCommand("Close");
closeButton.addActionListener(this);
setCloseEnabled(true);
setUndoEnabled(false);
setAbandonEnabled(false);
historyButton.setEnabled(false);
pack();
}
public void setList(ArrayList<VObjIF> list){
DefaultTableModel tableModel = (DefaultTableModel)m_table.getModel();
tableModel.setRowCount(0);
int nLength = list.size();
for (int i = 0; i < nLength; i++)
{
VObjIF[] obj = {(VObjIF)list.get(i)};
m_table.addRow(obj, false);
}
// m_table.positionScroll(REASON_INITIAL_VIEW);
if (nLength > 1)
m_table.scrollToRowLater(nLength - 1);
}
@Override
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
if (cmd.equals("Close")) {
this.setVisible(false);
}
if (cmd.equals("Revert")) {
saveObj();
ArrayList<VObjIF> objs=new ArrayList<VObjIF>();
for (int i = 0; i < edits.size(); i++) {
VObjIF obj = edits.get(i);
if(m_table.isRowSelected(i))
objs.add(obj);
}
for (int i = 0; i < objs.size(); i++) {
VObjIF obj = objs.get(i);
if (obj instanceof ParamPanel)
((ParamPanel)obj).restore();
else{
VObjIF p=getParamLayout(obj);
if(p !=null)
restorePage(obj);
}
edits.remove(obj);
}
showEdits();
if(edits.size()==0)
setVisible(false);
}
if (cmd.equals("Save")) {
saveObj();
ArrayList<VObjIF> objs=new ArrayList<VObjIF>();
for (int i = 0; i < edits.size(); i++) {
VObjIF obj = edits.get(i);
if(m_table.isRowSelected(i))
objs.add(obj);
}
for (int i = 0; i < objs.size(); i++) {
VObjIF obj = objs.get(i);
if (obj instanceof ActionBar)
saveAction(obj);
else if (obj instanceof ParamLayout)
saveLayout(obj);
else{
String name=defaultItemName(obj);
savePage(obj,name);
}
edits.remove(obj);
}
showEdits();
if(edits.size()==0)
setVisible(false);
}
}
public void updateButtons(){
if(edits.size()>0){
saveButton.setEnabled(true);
undoButton.setEnabled(true);
}
else{
saveButton.setEnabled(false);
undoButton.setEnabled(false);
}
}
public void showEdits(){
setList(edits);
m_table.selectAll();
updateButtons();
if(edits.size()>0)
setVisible(true);
//else
// setVisible(false);
}
class MessageCellRenderer extends JTextField
implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public MessageCellRenderer() {
setOpaque(true);
setPreferredSize(new Dimension(100,20));
}
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean cellHasFocus, int row, int column)
{
setOpaque(true);
setBorder(BorderFactory.createEtchedBorder());
String panelname="";
String msg;
VObjIF obj = (VObjIF)value;
if (obj instanceof ActionBar){
panelname=((ActionBar)obj).getPanelName();
msg = panelname +" Action Panel\n";
}
else if (obj instanceof ParamLayout) {
panelname=((ParamLayout)obj).getPanelName();
msg=panelname +" Page List\n";
}
else{
ParamLayout p=getParamLayout(obj);
if(p!=null)
panelname=((ParamLayout)p).getPanelName();
msg=panelname +" Page <"+obj.getAttribute(LABEL)+">\n";
}
if(isSelected)
selectAll();
// setTabSize(2);
setText(msg);
String var ="Info";
Color c=DisplayOptions.getColor(var);
Color bg = DisplayOptions.getColor(var + "Bkg");
Color curbg = bg;
Color curfg;
if (bg == null) {
bg=Util.getBgColor();
}
if (c == null) {
c = Util.getContrastingColor(bg);
}
setForeground(c);
curfg = c;
setBackground(bg);
curbg = bg;
Font f=DisplayOptions.getFont(var,var,var);
setFont(f);
if (isSelected) {
Color[] fgbg = Util.getSelectFgBg(curfg, curbg);
setForeground(fgbg[0]);
setBackground(fgbg[1]);
}
int width = m_table.getColumnModel().getColumn(column).getWidth();
setSize(width, 1000);
int height = m_table.getRowHeight(row);
double rowheight = getPreferredSize().getHeight();
if (height != rowheight)
m_table.setRowHeight(row, (int)rowheight);
return this;
}
} // class MessageCellRenderer
}
private class ItemEditor extends ModelessDialog
implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
ParamPanel layout = null;
private JScrollPane scrollPane;
private String itemEditorGeometryFile = "ItemEditorGeometry";
private String itemEditorContentFile="ItemEditorContent";
private JToggleButton testButton=new JToggleButton("Test");
private JButton openButton=new JButton("Open..");
private JButton saveButton=new JButton("Save..");
private String mTitle;
public ItemEditor(String title) {
super(title);
setVisible(false);
mTitle=title;
historyButton.setEnabled(false);
undoButton.setEnabled(false);
testButton.setEnabled(true);
testButton.setSelected(false);
testButton.setActionCommand("test");
testButton.addActionListener(this);
buttonPane.add(testButton, 1);
saveButton.setEnabled(true);
saveButton.setActionCommand("save");
saveButton.addActionListener(this);
buttonPane.add(saveButton, 2);
openButton.setActionCommand("open");
openButton.addActionListener(this);
buttonPane.add(openButton, 3);
closeButton.setActionCommand("Close");
closeButton.addActionListener(this);
abandonButton.setActionCommand("Abandon");
abandonButton.addActionListener(this);
helpButton.setActionCommand("help");
helpButton.addActionListener(this);
layout = new ParamPanel();//(Util.getSessionShare(), getExpIF());
//layout.setUseMenu(false);
layout.setPanelName("Items");
Dimension dim=new Dimension(400,300);
layout.setPreferredSize(dim);
layout.setSnapGap(ParamEditUtil.getSnapGap());
layout.setGridColor(Util.getGridColor());
//setEditMode(true);
scrollPane = new JScrollPane(layout,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(scrollPane);
setCloseEnabled(true);
setAbandonEnabled(true);
pack();
restoreGeometry();
Component comp=restoreContent();
setEditMode(true);
layout.adjustSize();
setContentVisible();
if(comp !=null)
comp.setVisible(true);
addGeometryListener();
setVisible(true);
}
public void setSnapGrid(int k) {
layout.setSnapGap(k);
}
private void setContentVisible() {
// setEditMode should set all top level groups visible but for some reason doesn't
int k = layout.getComponentCount();
for (int i = 0; i < k; i++) {
Component comp = layout.getComponent(i);
comp.setVisible(true);
}
}
public void saveContent() {
String filepath = FileUtil.savePath("USER/PERSISTENCE/"+itemEditorContentFile);
if(filepath !=null){
File tmpFile=new File(filepath);
String f = tmpFile.getAbsolutePath();
layout.setAttribute(USEREF,"false");
ParamEditUtil.clearDummyObj(); // remove selection outline objects
LayoutBuilder.writeToFile(layout, f,true);
}
}
public Component restoreContent(){
String filepath = FileUtil.openPath("USER/PERSISTENCE/"+itemEditorContentFile);
if(filepath==null)
return null;
try{
Component comp=LayoutBuilder.build(layout, getExpIF(), filepath, true);
return comp;
}
catch(Exception be) {
Messages.writeStackTrace(be);
return null;
}
}
public void setEditMode(boolean s) {
layout.setEditMode(s);
layout.setEditModeToAll(s);
}
@Override
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
if (cmd.equals("Close")) {
this.setVisible(false);
}
if (cmd.equals("Abandon")) {
abandon();
}
if (cmd.equals("save")) {
save();
}
if (cmd.equals("open")) {
open();
}
if (cmd.equals("test")) {
test();
}
}
private void test() {
if(testButton.isSelected())
layout.setEditModeToAll(false);
else
layout.setEditModeToAll(true);
layout.validate();
layout.repaint();
}
private void save() {
JFrame frame= new JFrame();
frame.setTitle("Save Items");
JFileChooser fc= new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
fc.addChoosableFileFilter(new XMLFilter());
if(savepath!=null)
fc.setSelectedFile(new File(savepath));
int returnVal= fc.showSaveDialog(frame);
if(returnVal==JFileChooser.APPROVE_OPTION){
File file= fc.getSelectedFile();
savepath=file.getPath();
if(openpath==null)
openpath=savepath;
layout.setAttribute(USEREF,"false");
ParamEditUtil.clearDummyObj(); // removes selection outline objects
LayoutBuilder.writeToFile(layout, savepath,true);
setTitle(mTitle+"-"+file.getName());
}
}
private void open() {
JFrame frame= new JFrame();
frame.setTitle("Open Items");
JFileChooser fc= new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
fc.addChoosableFileFilter(new XMLFilter());
if(openpath!=null)
fc.setSelectedFile(new File(openpath));
int returnVal= fc.showOpenDialog(frame);
if(returnVal==JFileChooser.APPROVE_OPTION){
File file= fc.getSelectedFile();
openpath=file.getPath();
if(savepath==null)
savepath=openpath;
try{
setTitle(mTitle+"-"+file.getName());
layout.removeAll();
LayoutBuilder.build(layout, getExpIF(), openpath, true);
layout.setEditModeToAll(true);
setContentVisible();
layout.adjustSize();
layout.validate();
layout.repaint();
}
catch(Exception be) {
Messages.writeStackTrace(be);
}
}
}
private void abandon() {
layout.removeAll();
restoreContent();
layout.setEditModeToAll(true);
setContentVisible();
this.setVisible(false);
}
private ButtonIF getExpIF() {
return Util.getViewArea().getDefaultExp();
}
public void addGeometryListener() {
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
changedSize();
}
public void componentMoved(ComponentEvent ce) {
saveGeometry();
}
});
}
public void changedSize() {
layout.adjustSize();
FileUtil.writeGeometryToPersistence(itemEditorGeometryFile, this);
}
public void saveGeometry() {
FileUtil.writeGeometryToPersistence(itemEditorGeometryFile, this);
}
public void restoreGeometry() {
FileUtil.setGeometryFromPersistence(itemEditorGeometryFile, this);
}
public class XMLFilter extends FileFilter {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension != null) {
if (extension.equals("xml")){
return true;
} else {
return false;
}
}
return false;
}
public String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
}
public String getDescription() {
return "XML Files";
}
}
}
private class RadioGroup extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
ButtonGroup group=null;
private boolean first=true;
int attr;
RadioGroup(int a){
group=new ButtonGroup();
attr=a;
setLayout(new SimpleH2Layout(SimpleH2Layout.LEFT, 4, 2, false));
}
public void add(String s){
JRadioButton button=new JRadioButton(s);
if(first)
button.setSelected(true);
group.add(button);
super.add(button);
button.setOpaque(false);
button.setBackground(null);
button.setActionCommand(s);
button.addActionListener(this);
button.setRequestFocusEnabled(false);
first=false;
}
public void setSelectedItem(String s){
Enumeration elist=group.getElements();
JRadioButton selected=null;
while(elist.hasMoreElements()){
JRadioButton button=(JRadioButton)elist.nextElement();
if(s.equals(button.getActionCommand()))
selected=button;
button.setSelected(false);
}
if(selected !=null)
selected.setSelected(true);
else
Messages.postError("illegal attribute choice "+s);
}
public String getSelectedItem(){
String s="";
if(group.getSelection()!=null)
s= group.getSelection().getActionCommand();
return s;
}
public void actionPerformed(ActionEvent evt) {
if (editVobj != null) {
String str=getSelectedItem();
if(attr==TAB){
VObjIF obj=editVobj;
if(str.equals("yes"))
ParamEditUtil.unParent();
editVobj.setAttribute(USEREF,str);
editVobj.setAttribute(TAB,str);
editVobj=null; // force setEditElement to reload object
setEditElement(obj);
}
ParamEditUtil.setChangedPage(true);
editVobj.setAttribute(attr, str);
}
}
public void setEnabled(boolean enabled){
Component[] comps = getComponents();
int nSize = comps.length;
for(int j=0;j<nSize;j++){
comps[j].setEnabled(enabled);
}
super.setEnabled(enabled);
}
} // class RadioGroup
private class AttributeChangeListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
VObjIF vobj = editVobj;
if(vobj == null)
vobj = editPanel;
if(vobj == null)
return;
if(vobj==editVobj)
ParamEditUtil.setChangedPage(true);
String cmd = e.getActionCommand();
JTextField obj = (JTextField) e.getSource();
try {
int attr = Integer.parseInt(cmd);
vobj.setAttribute(attr, obj.getText());
if(vobj instanceof ParamPanel){
makeSaveDirMenu();
}
else if((vobj instanceof VGroup) && (attr == LABEL || attr == TAB)) {
setDefaultItemName();
String ref = vobj.getAttribute(REFERENCE);
if(ref == null || ref.length() == 0)
vobj.setAttribute(REFERENCE, itemName);
}
if (vobj instanceof VGroup && attr == COUNT)
{
((VGroup)vobj).showPanel();
}
setItemEdited(editVobj);
} catch(NumberFormatException exception) {
Messages.postError("ParamInfoPanel number format exception");
}
}
} //class AttributeChangeListener
private class AttrLayout implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {}
public void removeLayoutComponent(Component comp) {}
public Dimension preferredLayoutSize(Container target) {
Dimension dim;
int w = 0;
int h = 0;
int k;
int n = target.getComponentCount();
for ( k = 0; k < n; k++) {
Component m = target.getComponent(k);
dim = m.getPreferredSize();
if (dim.width > w)
w = dim.width;
h += dim.height+2;
}
return new Dimension(w, h);
}
public Dimension minimumLayoutSize(Container target) {
return new Dimension(0, 0); // unused
}
public void layoutContainer(Container target) {
synchronized (target.getTreeLock()) {
Dimension dim;
int n = target.getComponentCount();
int w = 0;
int h = 4;
int k;
for ( k = 0; k < n; k++) {
Component m = target.getComponent(k);
if(m instanceof Container)
m=((Container)m).getComponent(0);
dim = m.getPreferredSize();
if (dim.width > w)
w = dim.width;
}
SimpleH2Layout.setFirstWidth(w);
Dimension dim0 = target.getSize();
for (k = 0; k < n; k++) {
Component obj = target.getComponent(k);
if (obj.isVisible()) {
dim = obj.getPreferredSize();
obj.setBounds(2, h, dim0.width-6, dim.height);
h += dim.height;
}
}
}
}
} // class AttrLayout
private class PanelLayout implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {}
public void removeLayoutComponent(Component comp) {}
public Dimension preferredLayoutSize(Container target) {
Dimension dim;
int w = 0;
int h = 0;
int k;
int n = target.getComponentCount();
for (k = 0; k < n; k++) {
Component m = target.getComponent(k);
dim = m.getPreferredSize();
if (dim.width > w)
w = dim.width;
h += dim.height + 2;
}
return new Dimension(w, h);
}
public Dimension minimumLayoutSize(Container target) {
return new Dimension(0, 0); // unused
}
public void layoutContainer(Container target) {
synchronized (target.getTreeLock()) {
Dimension dim;
int n = target.getComponentCount();
int h = 0;
int hs = 0;
int k;
for (k = 0; k < n; k++) {
Component m = target.getComponent(k);
dim = m.getPreferredSize();
if (m != attrScroll)
hs += dim.height;
}
if (hs > 500) // something wrong
hs = etcH;
else
etcH = hs;
Dimension dim0 = target.getSize();
windowWidth = dim0.width;
hs = dim0.height - hs - 4;
if (hs < 20)
hs = 20;
scrollH = hs;
if (sbW == 0) {
JScrollBar jb = attrScroll.getVerticalScrollBar();
if (jb != null) {
dim = jb.getPreferredSize();
sbW = dim.width;
} else
sbW = 20;
}
/*
* if (editVobj != null) adjustAttrPanelSize();
*/
for (k = 0; k < n; k++) {
Component obj = target.getComponent(k);
if (obj.isVisible()) {
dim = obj.getPreferredSize();
if (obj == attrScroll) {
obj.setBounds(2, h, dim0.width - 4, hs);
h += hs;
} else {
if (dim.height > 500) {
if (obj == headerPan)
dim.height = 100;
else if (obj == prefPan)
dim.height = 40;
else if (obj == ctlPan)
dim.height = 40;
}
obj.setBounds(2, h, dim0.width - 4, dim.height);
h += dim.height;
}
}
}
}
}
} // class PanelLayout
private class StyleChooser extends JComboBox implements ActionListener {
private static final long serialVersionUID = 1L;
private String sel = null;
Hashtable types = new Hashtable();
private VObjIF sobj = null;
private boolean color_only = false;
private boolean style_only = false;
Color orgBg;
boolean inAddMode = true;
public StyleChooser(String type) {
inAddMode = true;
orgBg = getBackground();
setOpaque(true);
if (type.equals("color"))
setColorOnly(true);
else if (type.equals("style"))
setStyleOnly(true);
ArrayList list;
if(style_only)
list=DisplayOptions.getTypes(DisplayOptions.FONT);
else
list= DisplayOptions.getSymbols();
int nLength = list.size();
for (int i = 0; i < nLength; i++) {
String s = (String) list.get(i);
addItem(s);
types.put(s, s);
}
if (color_only) {
addItem("transparent");
types.put("transparent", "transparent");
}
addActionListener(this);
setRenderer(new StyleMenuRenderer());
setPreferredSize(new Dimension(150, 22));
//setOpaque(false);
inAddMode = false;
}
public void actionPerformed(ActionEvent evt) {
if (inAddMode)
return;
sel = (String) getSelectedItem();
StyleData style = new StyleData(sel);
setFont(style.font);
//setBackground(style.bg);
setForeground(style.fg);
if (!inSetMode && sobj != null)
setStyle(sobj);
repaint();
}
public void setColorOnly(boolean c) {
color_only = c;
}
public void setStyleOnly(boolean c) {
style_only = c;
}
public void setStyleObject(VObjIF v) {
sobj = v;
}
public String getType() {
return (String) getSelectedItem();
}
public void setType(String s) {
setSelectedItem(s);
}
public void setDefaultType() {
if (getItemCount() < 1)
return;
setSelectedIndex(0);
}
public boolean isType(String s) {
return types.containsKey(s);
}
public void setStyle(VObjIF obj) {
if (obj == null)
return;
sel = (String) getSelectedItem();
obj.setAttribute(FONT_STYLE, sel);
obj.setAttribute(FGCOLOR, sel);
obj.changeFont();
}
public void setColor(VObjIF obj) {
if (obj == null)
return;
sel = (String) getSelectedItem();
obj.setAttribute(FGCOLOR, sel);
}
class StyleData {
public Color fg;
public Color bg;
public Font font;
public StyleData(String sel) {
if (color_only) {
font = DisplayOptions.getFont(null, null);
bg = DisplayOptions.getColor(sel);
if (intensity(bg) <= 1)
fg = Color.white;
else
fg = Color.black;
} else {
font = DisplayOptions.getFont(sel, sel);
fg = DisplayOptions.getColor(sel);
bg = orgBg;
if (contrast(fg, bg) < 0.3) {
bg = DisplayOptions.getColor(sel);
if (intensity(bg) <= 1)
fg = Color.white;
else
fg = Color.black;
}
}
}
double intensity(Color c) {
if (c == null) {
return Double.NaN;
}
float f[] = new float[3];
c.getColorComponents(f);
double r = f[0];
double g = f[1];
double b = f[2];
double mag = (r * r + g * g + b * b);
return mag;
}
double contrast(Color c1, Color c2) {
if (c1 == null || c2 == null) {
return Double.NaN;
}
float f1[] = new float[3];
float f2[] = new float[3];
c1.getColorComponents(f1);
c2.getColorComponents(f2);
double r = f1[0] - f2[0];
double g = f1[1] - f2[1];
double b = f1[2] - f2[2];
double mag = (r * r + g * g + b * b);
return mag;
}
}
// cell renderer for menu items
class StyleMenuRenderer extends JLabel implements ListCellRenderer {
private static final long serialVersionUID = 1L;
public StyleMenuRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
if (value == null) {
setText(" ");
return this;
}
String sel = value.toString();
StyleData style = new StyleData(sel);
setText(sel);
setFont(style.font);
setBackground(style.bg);
setForeground(style.fg);
return this;
}
} // class StyleMenuRenderer
} // class StyleChooser
}
| apache-2.0 |
empt-ak/meditor | editor-backend/src/main/java/cz/muni/fi/editor/security/JwtAuthRequest.java | 850 | /*
* Copyright © 2016 - 2017 Dominik Szalai (emptulik@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 cz.muni.fi.editor.security;
import lombok.Data;
/**
* @author Dominik Szalai - emptulik at gmail.com on 6/30/17.
*/
@Data
public class JwtAuthRequest {
private String username;
private String password;
}
| apache-2.0 |
frincon/openeos | modules/org.openeos.utils/src/main/java/org/openeos/utils/GenericExtender.java | 3085 | /**
* Copyright 2014 Fernando Rincon Martin <frm.rincon@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 org.openeos.utils;
import java.util.HashSet;
import java.util.Set;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.util.tracker.BundleTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GenericExtender<T> {
private static final Logger LOG = LoggerFactory.getLogger(GenericExtender.class);
private ExtenderHandler<T> extenderHandler;
private BundleContext bundleContext;
private BundleFilter<T> bundleFilter;
private int stateMask;
private BundleTracker<Bundle> bundleTracker;
private Set<Bundle> bundleRegistered = new HashSet<Bundle>();
//Compatibility with extender handler header based implementation
@SuppressWarnings("unchecked")
public GenericExtender(ExtenderHeaderHandler extenderHandler, BundleContext bundleContext) {
this((ExtenderHandler<T>) extenderHandler, bundleContext, Bundle.ACTIVE,
(BundleFilter<T>) new HeaderBundleFilter(extenderHandler.getHeaderName()));
}
public GenericExtender(ExtenderHandler<T> extenderHandler, BundleContext bundleContext, int stateMask,
BundleFilter<T> bundleFilter) {
this.extenderHandler = extenderHandler;
this.bundleContext = bundleContext;
this.stateMask = stateMask;
this.bundleFilter = bundleFilter;
}
public void init() {
LOG.debug("Starting Generic extender width handler of class: " + extenderHandler.getClass());
bundleTracker = new BundleTracker<Bundle>(bundleContext, stateMask, null) {
@Override
public Bundle addingBundle(Bundle bundle, BundleEvent event) {
T object = bundleFilter.filterBundle(bundle);
if (object != null) {
LOG.debug("Found bundle whith object required\n\tBundle: " + bundle.getSymbolicName() + "\n\t\t"
+ object.getClass().getName() + ": " + object.toString());
extenderHandler.onBundleArrival(bundle, object);
bundleRegistered.add(bundle);
}
return bundle;
}
@Override
public void removedBundle(Bundle bundle, BundleEvent event, Bundle object) {
if (bundleRegistered.contains(bundle)) {
LOG.debug("Removing bundle previously extended\n\tBundle: " + bundle.getSymbolicName());
extenderHandler.onBundleDeparture(bundle);
bundleRegistered.remove(bundle);
}
}
};
extenderHandler.starting();
bundleTracker.open();
}
public void destroy() {
bundleTracker.close();
bundleTracker = null;
extenderHandler.stopping();
}
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/InvalidInstanceInformationFilterValueException.java | 1322 | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.simplesystemsmanagement.model;
import javax.annotation.Generated;
/**
* <p>
* The specified filter value is not valid.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidInstanceInformationFilterValueException extends com.amazonaws.services.simplesystemsmanagement.model.AWSSimpleSystemsManagementException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new InvalidInstanceInformationFilterValueException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public InvalidInstanceInformationFilterValueException(String message) {
super(message);
}
}
| apache-2.0 |
bq/lib-token | src/main/java/com/bq/corbel/lib/token/provider/SessionProvider.java | 4828 | package com.bq.corbel.lib.token.provider;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.CookieParam;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.ext.Provider;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory;
import org.glassfish.jersey.server.internal.inject.AbstractValueFactoryProvider;
import org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider;
import org.glassfish.jersey.server.internal.inject.ParamInjectionResolver;
import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bq.corbel.lib.token.exception.TokenVerificationException;
import com.bq.corbel.lib.token.parser.TokenParser;
import com.bq.corbel.lib.token.reader.TokenReader;
import com.google.common.base.Optional;
public class SessionProvider {
private static final Logger LOG = LoggerFactory.getLogger(SessionProvider.class);
private static TokenParser tokenParser;
public SessionProvider(TokenParser tokenParser) {
this.tokenParser = tokenParser;
}
public org.glassfish.hk2.utilities.Binder getBinder() {
return new Binder();
}
public static class Binder extends AbstractBinder {
@Override
protected void configure() {
bind(SessionFactoryProvider.class).to(ValueFactoryProvider.class).in(Singleton.class);
bind(SessionInjectionResolver.class).to(new TypeLiteral<InjectionResolver<CookieParam>>() {}).in(Singleton.class);
}
}
public static final class SessionInjectionResolver extends ParamInjectionResolver<CookieParam> {
public SessionInjectionResolver() {
super(SessionFactoryProvider.class);
}
}
@Provider public static class SessionFactoryProvider extends AbstractValueFactoryProvider {
@Inject
protected SessionFactoryProvider(MultivaluedParameterExtractorProvider mpep, ServiceLocator locator) {
super(mpep, locator, Parameter.Source.COOKIE);
}
@Override
protected AbstractContainerRequestValueFactory<?> createValueFactory(Parameter parameter) {
String parameterName = parameter.getSourceName();
if (parameterName == null || parameterName.length() == 0) {
// Invalid cookie parameter name
return null;
}
if (isOptionalSession(parameter.getType())) {
return new OptionalSessionInjectable(parameterName);
}
if (TokenReader.class.isAssignableFrom(parameter.getRawType())) {
return new SessionInjectable(parameterName);
}
return null;
}
private class OptionalSessionInjectable extends AbstractContainerRequestValueFactory<Optional<TokenReader>> {
private final SessionInjectable sessionInjectable;
public OptionalSessionInjectable(String cookieKey) {
sessionInjectable = new SessionInjectable(cookieKey);
}
@Override
public Optional<TokenReader> provide() {
return Optional.fromNullable(sessionInjectable.provide());
}
}
private class SessionInjectable extends AbstractContainerRequestValueFactory<TokenReader> {
private final String cookieKey;
public SessionInjectable(String cookieKey) {
this.cookieKey = cookieKey;
}
@Override
public TokenReader provide() {
Cookie cookie = getContainerRequest().getCookies().get(cookieKey);
if (cookie != null) {
try {
return tokenParser.parseAndVerify(cookie.getValue());
} catch (TokenVerificationException e) {
LOG.warn("Received invalid session cookie {}", cookie);
}
}
return null;
}
}
private boolean isOptionalSession(Type parameterType) {
if (parameterType instanceof ParameterizedType) {
ParameterizedType generic = (ParameterizedType) parameterType;
if (generic.getRawType().equals(Optional.class)) {
return generic.getActualTypeArguments()[0].equals(TokenReader.class);
}
}
return false;
}
}
}
| apache-2.0 |
mosaic-cloud/mosaic-java-platform | tools-threading/src/main/java/eu/mosaic_cloud/tools/threading/core/ThreadingSecurityManager.java | 780 | /*
* #%L
* mosaic-tools-threading
* %%
* Copyright (C) 2010 - 2013 Institute e-Austria Timisoara (Romania)
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package eu.mosaic_cloud.tools.threading.core;
public interface ThreadingSecurityManager
{}
| apache-2.0 |
tripodsan/jackrabbit-filevault | vault-core/src/main/java/org/apache/jackrabbit/vault/packaging/VersionRange.java | 6803 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.vault.packaging;
/**
* Implements a version range
* @since 2.0
*/
public class VersionRange {
/**
* Infinite (covers all) range.
*/
public static final VersionRange INFINITE = new VersionRange(null, true, null, true);
/**
* lower bound
*/
private final Version low;
/**
* specifies if lower bound is inclusive
*/
private final boolean lowIncl;
/**
* upper bound
*/
private final Version high;
/**
* specifies if upper bound is inclusive
*/
private final boolean highIncl;
/**
* internal string representation
*/
private final String str;
/**
* Creates a new version range.
* @param low lower bound or {@code null}
* @param lowIncl specifies if lower bound is inclusive
* @param high upper bound or {@code null}
* @param highIncl specifies if upper bound is inclusive
* @throws IllegalArgumentException if bounds are not valid
*/
public VersionRange(Version low, boolean lowIncl, Version high, boolean highIncl) {
if (low == Version.EMPTY) {
low = null;
}
if (high == Version.EMPTY) {
high = null;
}
// check if range is valid
if (low != null && high != null) {
int comp = low.compareTo(high);
if (comp > 0) {
throw new IllegalArgumentException("lower bound must be less or equal to upper bound.");
} else if (comp == 0) {
if (!lowIncl || !highIncl) {
throw new IllegalArgumentException("invalid empty range. upper and lower bound must be inclusive.");
}
}
}
this.low = low;
this.lowIncl = lowIncl;
this.high = high;
this.highIncl = highIncl;
StringBuilder b = new StringBuilder();
if (low == null && high == null) {
// infinite range, empty string
} else if (high == null) {
// no high bound,
if (lowIncl) {
// special case, just use version
b.append(low);
} else {
b.append('(');
b.append(low);
b.append(",)");
}
} else if (low == null) {
b.append("[,");
b.append(high);
b.append(highIncl ? ']' : ')');
} else {
b.append(lowIncl ? '[' : '(');
b.append(low);
b.append(',');
b.append(high);
b.append(highIncl ? ']' : ')');
}
this.str = b.toString();
}
/**
* Creates a new version range that exactly includes the given version.
* @param v the version.
*/
public VersionRange(Version v) {
this(v, true, v, true);
}
/**
* Returns the lower bound
* @return the lower bound or {@code null}
*/
public Version getLow() {
return low;
}
/**
* Returns {@code true} if the lower bound is inclusive
* @return {@code true} if the lower bound is inclusive
*/
public boolean isLowInclusive() {
return lowIncl;
}
/**
* Returns the upper bound
* @return the upper bound or {@code null}
*/
public Version getHigh() {
return high;
}
/**
* Returns {@code true} if the upper bound is inclusive
* @return {@code true} if the upper bound is inclusive
*/
public boolean isHighInclusive() {
return highIncl;
}
@Override
public int hashCode() {
return str.hashCode();
}
@Override
public boolean equals(Object obj) {
return this == obj ||
obj instanceof VersionRange && str.equals(obj.toString());
}
@Override
public String toString() {
return str;
}
/**
* Checks if the given version is in this range.
* @param v the version to check
* @return {@code true} if the given version is in this range.
*/
public boolean isInRange(Version v) {
if (low != null) {
int comp = v.compareTo(low);
if (comp < 0 || comp == 0 && !lowIncl) {
return false;
}
}
if (high != null) {
int comp = v.compareTo(high);
if (comp > 0 || comp == 0 && !highIncl) {
return false;
}
}
return true;
}
/**
* Creates a range from a string
* @param str string
* @return the version range
*/
public static VersionRange fromString(String str) {
int idx = str.indexOf(',');
if (idx >= 0) {
boolean linc = false;
int lm = str.indexOf('(');
if (lm < 0) {
lm = str.indexOf('[');
if (lm < 0) {
throw new IllegalArgumentException("Range must start with '[' or '('");
}
linc = true;
}
boolean hinc = false;
int hm = str.indexOf(')');
if (hm < 0) {
hm = str.indexOf(']');
if (hm < 0) {
throw new IllegalArgumentException("Range must end with ']' or ')'");
}
hinc = true;
}
String low = str.substring(lm + 1, idx).trim();
String high = str.substring(idx+1, hm).trim();
Version vLow = low.length() == 0 ? null : Version.create(low);
Version vHigh = high.length() == 0 ? null : Version.create(high);
return new VersionRange(vLow, linc, vHigh, hinc);
} else if (str.length() == 0) {
// infinite range
return new VersionRange(null, false, null, false);
} else {
// simple range where given version is minimum
return new VersionRange(Version.create(str), true, null, false);
}
}
} | apache-2.0 |
McLeodMoores/starling | projects/analytics/src/test/java/com/opengamma/analytics/financial/credit/obligor/SectorDelegateTest.java | 2450 | /**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.credit.obligor;
import static org.testng.AssertJUnit.assertEquals;
import org.testng.annotations.Test;
import com.opengamma.util.test.TestGroup;
/**
* Tests the delegation of the sector enum to a sector object.
*/
@Test(groups = TestGroup.UNIT)
@SuppressWarnings("deprecation")
public class SectorDelegateTest {
/**
* Tests the sector conversion.
*/
@Test
public void test() {
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.BASICMATERIALS.name()), Sector.BASICMATERIALS.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.CONSUMERGOODS.name()), Sector.CONSUMERGOODS.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.CONSUMERSERVICES.name()), Sector.CONSUMERSERVICES.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.ENERGY.name()), Sector.ENERGY.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.FINANCIALS.name()), Sector.FINANCIALS.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.GOVERNMENT.name()), Sector.GOVERNMENT.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.HEALTHCARE.name()), Sector.HEALTHCARE.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.INDUSTRIALS.name()), Sector.INDUSTRIALS.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.TECHNOLOGY.name()), Sector.TECHNOLOGY.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.TELECOMMUNICATIONSERVICES.name()), Sector.TELECOMMUNICATIONSERVICES.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.UTILITIES.name()), Sector.UTILITIES.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.MUNICIPAL.name()), Sector.MUNICIPAL.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.GOVERNMENT.name()), Sector.GOVERNMENT.toSector());
assertEquals(com.opengamma.analytics.financial.legalentity.Sector.of(Sector.NONE.name()), Sector.NONE.toSector());
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-elasticsearch/src/main/java/com/amazonaws/services/elasticsearch/model/DeleteElasticsearchDomainRequest.java | 3947 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.elasticsearch.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Container for the parameters to the <code><a>DeleteElasticsearchDomain</a></code> operation. Specifies the name of
* the Elasticsearch domain that you want to delete.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteElasticsearchDomainRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the Elasticsearch domain that you want to permanently delete.
* </p>
*/
private String domainName;
/**
* <p>
* The name of the Elasticsearch domain that you want to permanently delete.
* </p>
*
* @param domainName
* The name of the Elasticsearch domain that you want to permanently delete.
*/
public void setDomainName(String domainName) {
this.domainName = domainName;
}
/**
* <p>
* The name of the Elasticsearch domain that you want to permanently delete.
* </p>
*
* @return The name of the Elasticsearch domain that you want to permanently delete.
*/
public String getDomainName() {
return this.domainName;
}
/**
* <p>
* The name of the Elasticsearch domain that you want to permanently delete.
* </p>
*
* @param domainName
* The name of the Elasticsearch domain that you want to permanently delete.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeleteElasticsearchDomainRequest withDomainName(String domainName) {
setDomainName(domainName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getDomainName() != null)
sb.append("DomainName: ").append(getDomainName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteElasticsearchDomainRequest == false)
return false;
DeleteElasticsearchDomainRequest other = (DeleteElasticsearchDomainRequest) obj;
if (other.getDomainName() == null ^ this.getDomainName() == null)
return false;
if (other.getDomainName() != null && other.getDomainName().equals(this.getDomainName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getDomainName() == null) ? 0 : getDomainName().hashCode());
return hashCode;
}
@Override
public DeleteElasticsearchDomainRequest clone() {
return (DeleteElasticsearchDomainRequest) super.clone();
}
}
| apache-2.0 |
ljishen/leetcode-sol | ReverseVowelsOfAString.java | 1032 | // Question: https://leetcode.com/problems/reverse-vowels-of-a-string/
public class ReverseVowelsOfAString {
public String reverseVowels(String s) {
if (s == null) {
return null;
}
Set<Character> vowels = new HashSet<>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
vowels.add('A');
vowels.add('E');
vowels.add('I');
vowels.add('O');
vowels.add('U');
char[] cs = s.toCharArray();
int start = 0;
int end = s.length() - 1;
while (start < end) {
while (start < end && !vowels.contains(cs[start])) {
start++;
}
while (start < end && !vowels.contains(cs[end])) {
end--;
}
char tmp = cs[start];
cs[start] = cs[end];
cs[end] = tmp;
start++;
end--;
}
return new String(cs);
}
}
| apache-2.0 |
lynx-r/social-rushashki-net | src/main/java/net/rushashki/social/shashki64/client/view/ProfileView.java | 192 | package net.rushashki.social.shashki64.client.view;
/**
* Created with IntelliJ IDEA.
* User: alekspo
* Date: 06.12.14
* Time: 9:16
*/
public interface ProfileView extends BasicView {
}
| apache-2.0 |
datanucleus/tests | jpa/general/src/java/org/datanucleus/samples/annotations/versioned/VersionedSub.java | 1059 | /**********************************************************************
Copyright (c) 2018 Andy Jefferson and others. 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.
Contributors:
...
**********************************************************************/
package org.datanucleus.samples.annotations.versioned;
import javax.persistence.MappedSuperclass;
/**
* Abstract sub class of a versioned hierarchy.
*/
@MappedSuperclass
public abstract class VersionedSub extends VersionedBase
{
public VersionedSub(long id)
{
super(id);
}
}
| apache-2.0 |
caskdata/cdap | cdap-app-fabric/src/main/java/co/cask/cdap/internal/app/runtime/distributed/MapReduceTwillRunnable.java | 1112 | /*
* Copyright © 2014-2016 Cask Data, 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 co.cask.cdap.internal.app.runtime.distributed;
import co.cask.cdap.internal.app.runtime.batch.MapReduceProgramRunner;
/**
* Wraps {@link MapReduceProgramRunner} to be run via Twill
*/
final class MapReduceTwillRunnable extends AbstractProgramTwillRunnable<MapReduceProgramRunner> {
MapReduceTwillRunnable(String name) {
super(name);
}
@Override
protected boolean propagateServiceError() {
// Don't propagate MR failure as failure. Quick fix for CDAP-749.
return false;
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/ListStringCreativeTemplateVariable.java | 3303 |
package com.google.api.ads.dfp.jaxws.v201511;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Represents a list variable defined in a creative template. This is similar to
* {@link StringCreativeTemplateVariable}, except that there are possible choices to
* choose from.
*
* <p>Use {@link StringCreativeTemplateVariableValue} to specify the value
* for this variable when creating a {@link TemplateCreative} from a {@link CreativeTemplate}.
*
*
* <p>Java class for ListStringCreativeTemplateVariable complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ListStringCreativeTemplateVariable">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v201511}StringCreativeTemplateVariable">
* <sequence>
* <element name="choices" type="{https://www.google.com/apis/ads/publisher/v201511}ListStringCreativeTemplateVariable.VariableChoice" maxOccurs="unbounded" minOccurs="0"/>
* <element name="allowOtherChoice" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ListStringCreativeTemplateVariable", propOrder = {
"choices",
"allowOtherChoice"
})
public class ListStringCreativeTemplateVariable
extends StringCreativeTemplateVariable
{
protected List<ListStringCreativeTemplateVariableVariableChoice> choices;
protected Boolean allowOtherChoice;
/**
* Gets the value of the choices property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the choices property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getChoices().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ListStringCreativeTemplateVariableVariableChoice }
*
*
*/
public List<ListStringCreativeTemplateVariableVariableChoice> getChoices() {
if (choices == null) {
choices = new ArrayList<ListStringCreativeTemplateVariableVariableChoice>();
}
return this.choices;
}
/**
* Gets the value of the allowOtherChoice property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isAllowOtherChoice() {
return allowOtherChoice;
}
/**
* Sets the value of the allowOtherChoice property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setAllowOtherChoice(Boolean value) {
this.allowOtherChoice = value;
}
}
| apache-2.0 |
gawkermedia/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201602/Browser.java | 2140 |
package com.google.api.ads.dfp.jaxws.v201602;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Represents an internet browser.
*
*
* <p>Java class for Browser complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Browser">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v201602}Technology">
* <sequence>
* <element name="majorVersion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="minorVersion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Browser", propOrder = {
"majorVersion",
"minorVersion"
})
public class Browser
extends Technology
{
protected String majorVersion;
protected String minorVersion;
/**
* Gets the value of the majorVersion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMajorVersion() {
return majorVersion;
}
/**
* Sets the value of the majorVersion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMajorVersion(String value) {
this.majorVersion = value;
}
/**
* Gets the value of the minorVersion property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMinorVersion() {
return minorVersion;
}
/**
* Sets the value of the minorVersion property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMinorVersion(String value) {
this.minorVersion = value;
}
}
| apache-2.0 |
plamenbbn/XDATA | graph-matching/src/main/java/com/bbn/algebra/hadoop/reducers/SquareMatrixBlockTraceMultReducer.java | 1532 | package com.bbn.algebra.hadoop.reducers;
import java.io.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Reducer;
import com.bbn.fileformats.*;
public class SquareMatrixBlockTraceMultReducer extends Reducer<Text,MatrixBlock,NullWritable,DoubleWritable> {
MatrixBlock left;
MatrixBlock right;
DoubleWritable outVal;
protected void setup(Context context) {
Configuration conf = context.getConfiguration();
int sRL = conf.getInt("SRL",0);
int sCL = conf.getInt("SCL",0);
int sRR = conf.getInt("SRR",0);
int sCR = conf.getInt("SCR",0);
left = new MatrixBlock(sRL,sCL);
right = new MatrixBlock(sRR,sCR);
outVal = new DoubleWritable();
}
public void reduce(Text key, Iterable<MatrixBlock> values, Context context) throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
String lName = conf.get("LEFTNAME");
String rName = conf.get ("RIGHTNAME");
String resName = conf.get("RESNAME");
boolean lTrans = conf.getBoolean("LTRANS", false);
boolean rTrans = conf.getBoolean("RTRANS", false);
double scalar = conf.getFloat("SCALAR", 1);
for (MatrixBlock val : values) {
if (val.name.equals(lName)) {
left.set(val);
}
else if (val.name.equals(rName)) {
right.set(val);
}
}
outVal.set(left.SquareTraceMult(right, scalar, lTrans,rTrans));
context.write(NullWritable.get(), outVal);
}
} | apache-2.0 |
StarMade/SMEditClassic | JoFileLibrary/src/jo/sm/ent/data/ControlSubElement.java | 572 | package jo.sm.ent.data;
import java.util.ArrayList;
import java.util.List;
import jo.vecmath.Point3i;
public class ControlSubElement
{
private short mVal;
private List<Point3i> mVals;
public ControlSubElement()
{
mVals = new ArrayList<Point3i>();
}
public short getVal()
{
return mVal;
}
public void setVal(short val)
{
mVal = val;
}
public List<Point3i> getVals()
{
return mVals;
}
public void setVals(List<Point3i> vals)
{
mVals = vals;
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Features/Base/src/main/java/ghidra/app/util/RefRepeatComment.java | 1894 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.util;
import java.util.Arrays;
import ghidra.program.model.address.Address;
public class RefRepeatComment {
private Address address;
private String[] commentLines;
RefRepeatComment(Address address, String[] commentLines) {
this.address = address;
this.commentLines = commentLines;
}
public Address getAddress() {
return address;
}
public String[] getCommentLines() {
return commentLines;
}
public int getCommentLineCount() {
return commentLines.length;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + Arrays.hashCode(commentLines);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
RefRepeatComment other = (RefRepeatComment) obj;
if (address == null) {
if (other.address != null) {
return false;
}
}
else if (!address.equals(other.address)) {
return false;
}
if (!Arrays.equals(commentLines, other.commentLines)) {
return false;
}
return true;
}
@Override
public String toString() {
return Arrays.toString(commentLines);
}
}
| apache-2.0 |
wxb2939/rwxlicai | mzb-phone-app-android/app/src/main/java/com/xem/mzbphoneapp/view/MzbFramLayout.java | 523 | package com.xem.mzbphoneapp.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.FrameLayout;
/**
* Created by xuebing on 15/12/14.
*/
public class MzbFramLayout extends FrameLayout {
private Button button;
public MzbFramLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return true;
}
}
| apache-2.0 |
smaring/pentaho-data-profiling | model/core/src/main/java/org/pentaho/profiling/model/StreamingProfileImpl.java | 8378 | /*******************************************************************************
*
* Pentaho Data Profiling
*
* Copyright (C) 2002-2017 by Hitachi Vantara : 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.profiling.model;
import org.pentaho.profiling.api.IllegalTransactionException;
import org.pentaho.profiling.api.MutableProfileField;
import org.pentaho.profiling.api.MutableProfileStatus;
import org.pentaho.profiling.api.ProfileFieldProperty;
import org.pentaho.profiling.api.ProfileState;
import org.pentaho.profiling.api.ProfileStatusManager;
import org.pentaho.profiling.api.ProfileStatusMessage;
import org.pentaho.profiling.api.ProfileStatusWriteOperation;
import org.pentaho.profiling.api.StreamingProfile;
import org.pentaho.profiling.api.action.ProfileActionException;
import org.pentaho.profiling.api.commit.CommitAction;
import org.pentaho.profiling.api.commit.CommitStrategy;
import org.pentaho.profiling.api.commit.strategies.LinearTimeCommitStrategy;
import org.pentaho.profiling.api.mapper.HasStatusMessages;
import org.pentaho.profiling.api.metrics.MetricContributor;
import org.pentaho.profiling.api.metrics.MetricContributors;
import org.pentaho.profiling.api.metrics.MetricContributorsFactory;
import org.pentaho.profiling.api.metrics.ProfileFieldProperties;
import org.pentaho.profiling.api.metrics.field.DataSourceFieldValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by bryan on 3/23/15.
*/
public class StreamingProfileImpl implements StreamingProfile {
private static final Logger LOGGER = LoggerFactory.getLogger( StreamingProfileImpl.class );
private final AtomicBoolean isRunning = new AtomicBoolean( false );
private final ProfileStatusManager profileStatusManager;
private final List<MetricContributor> metricContributorList;
private ExecutorService executorService;
private CommitStrategy commitStrategy;
private HasStatusMessages hasStatusMessages;
private MutableProfileStatus transaction;
private final CommitAction commitAction = new CommitAction() {
@Override public void perform() {
commit();
}
};
public StreamingProfileImpl( ProfileStatusManager profileStatusManager,
MetricContributorsFactory metricContributorsFactory,
MetricContributors metricContributors ) {
this.profileStatusManager = profileStatusManager;
this.metricContributorList = metricContributorsFactory.construct( metricContributors );
setCommitStrategy( new LinearTimeCommitStrategy( 1000 ) );
profileStatusManager.write( new ProfileStatusWriteOperation<Void>() {
@Override public Void write( MutableProfileStatus profileStatus ) {
List<ProfileFieldProperty> intrinsicProperties = Arrays.asList( ProfileFieldProperties.LOGICAL_NAME,
ProfileFieldProperties.PHYSICAL_NAME, ProfileFieldProperties.FIELD_TYPE,
ProfileFieldProperties.COUNT_FIELD );
List<ProfileFieldProperty> profileFieldProperties = new ArrayList<ProfileFieldProperty>( intrinsicProperties );
for ( MetricContributor metricContributor : metricContributorList ) {
for ( ProfileFieldProperty profileFieldProperty : metricContributor.getProfileFieldProperties() ) {
profileFieldProperties.add( profileFieldProperty );
}
}
profileStatus.setProfileFieldProperties( profileFieldProperties );
profileStatus.setTotalEntities( 0L );
return null;
}
} );
}
@Override public void setCommitStrategy( CommitStrategy commitStrategy ) {
this.commitStrategy = commitStrategy;
this.commitStrategy.init( commitAction, executorService );
}
@Override public synchronized <T> T perform( ProfileStatusWriteOperation<T> profileStatusWriteOperation ) {
boolean startTransaction = transaction != null;
if ( startTransaction ) {
try {
profileStatusManager.commit( transaction );
try {
return profileStatusManager.write( profileStatusWriteOperation );
} finally {
if ( startTransaction ) {
transaction = profileStatusManager.startTransaction();
}
}
} catch ( IllegalTransactionException e ) {
e.printStackTrace();
}
}
return null;
}
@Override public synchronized void processRecord( final List<DataSourceFieldValue> dataSourceFieldValues )
throws ProfileActionException {
if ( isRunning.get() ) {
Long totalEntities = transaction.getTotalEntities() + 1;
transaction.setTotalEntities( totalEntities );
for ( DataSourceFieldValue dataSourceFieldValue : dataSourceFieldValues ) {
MutableProfileField field = transaction
.getOrCreateField( dataSourceFieldValue.getPhysicalName(), dataSourceFieldValue.getLogicalName() );
field.getOrCreateValueTypeMetrics( dataSourceFieldValue.getFieldTypeName() ).incrementCount();
}
for ( MetricContributor metricContributor : metricContributorList ) {
metricContributor.processFields( transaction, dataSourceFieldValues );
}
commitStrategy.eventProcessed();
} else {
throw new ProfileActionException( null, null );
}
}
@Override public void setHasStatusMessages( HasStatusMessages hasStatusMessages ) {
this.hasStatusMessages = hasStatusMessages;
}
private void doRefresh() throws IllegalTransactionException {
if ( transaction != null ) {
HasStatusMessages hasStatusMessages = StreamingProfileImpl.this.hasStatusMessages;
if ( hasStatusMessages != null ) {
transaction.setStatusMessages( hasStatusMessages.getStatusMessages() );
}
for ( MetricContributor metricContributor : metricContributorList ) {
try {
metricContributor.setDerived( transaction );
} catch ( Exception e ) {
LOGGER.error( e.getMessage(), e );
}
}
profileStatusManager.commit( transaction );
if ( isRunning() ) {
transaction = profileStatusManager.startTransaction();
} else {
transaction = null;
}
}
}
@Override public String getId() {
return profileStatusManager.getId();
}
@Override public String getName() {
return profileStatusManager.getName();
}
@Override public synchronized void start( ExecutorService executorService ) {
this.executorService = executorService;
setCommitStrategy( this.commitStrategy );
try {
transaction = profileStatusManager.startTransaction();
} catch ( IllegalTransactionException e ) {
LOGGER.error( "Unable to create transaction", e );
}
isRunning.set( true );
}
@Override public synchronized void commit() {
try {
doRefresh();
} catch ( IllegalTransactionException e ) {
LOGGER.error( "Unable to commit", e );
}
}
@Override public synchronized void stop() {
if ( !isRunning.getAndSet( false ) ) {
return;
}
try {
doRefresh();
} catch ( IllegalTransactionException e ) {
LOGGER.error( e.getMessage(), e );
}
profileStatusManager.write( new ProfileStatusWriteOperation<Void>() {
@Override public Void write( MutableProfileStatus profileStatus ) {
profileStatus.setProfileState( ProfileState.STOPPED );
profileStatus.setStatusMessages( new ArrayList<ProfileStatusMessage>() );
return null;
}
} );
}
@Override public boolean isRunning() {
return isRunning.get();
}
}
| apache-2.0 |
akjava/GWT-Hangouts | src/com/akjava/gwt/lib/hangouts/client/av/effects/OnLoad.java | 988 | package com.akjava.gwt.lib.hangouts.client.av.effects;
import com.akjava.gwt.lib.hangouts.client.av.effects.listeners.ResourceLoadResultListener;
import com.akjava.gwt.lib.hangouts.client.layout.listeners.DisplayedParticipantChangedListener;
import com.google.gwt.core.client.JavaScriptObject;
public class OnLoad extends JavaScriptObject{
protected OnLoad(){}
public final native void add(ResourceLoadResultListener listener)/*-{
this.add(listener.@com.akjava.gwt.lib.hangouts.client.av.effects.listeners.ResourceLoadResultListener::onResourceLoadResult(Lcom/akjava/gwt/lib/hangouts/client/av/effects/events/ResourceLoadResult;));
}-*/;
public final native void remove(DisplayedParticipantChangedListener listener)/*-{
this.remove(listener.@com.akjava.gwt.lib.hangouts.client.av.effects.listeners.ResourceLoadResultListener::onResourceLoadResult(Lcom/akjava/gwt/lib/hangouts/client/av/effects/events/ResourceLoadResult;));
}-*/;
}
| apache-2.0 |
cboehme/metafacture-core | metafacture-xml/src/test/java/org/metafacture/xml/SimpleXmlEncoderTest.java | 4834 | /*
* Copyright 2013, 2014 Deutsche Nationalbibliothek
*
* 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.metafacture.xml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.metafacture.framework.helpers.DefaultObjectReceiver;
/**
* Tests for class {@link SimpleXmlEncoder}.
*
* @author Markus Geipel
* @author Christoph Böhme
*
*/
public final class SimpleXmlEncoderTest {
private static final String TAG = "tag";
private static final String VALUE = "value";
private SimpleXmlEncoder simpleXmlEncoder;
private StringBuilder resultCollector;
@Before
public void initSystemUnderTest() {
simpleXmlEncoder = new SimpleXmlEncoder();
simpleXmlEncoder.setReceiver(
new DefaultObjectReceiver<String>() {
@Override
public void process(final String obj) {
resultCollector.append(obj);
}
});
resultCollector = new StringBuilder();
}
@Test
public void issue249_shouldNotEmitClosingRootTagOnCloseStreamIfNoOutputWasGenerated() {
simpleXmlEncoder.closeStream();
assertTrue(getResultXml().isEmpty());
}
@Test
public void shouldNotEmitClosingRootTagOnResetStreamIfNoOutputWasGenerated() {
simpleXmlEncoder.resetStream();
assertTrue(getResultXml().isEmpty());
}
@Test
public void shouldOnlyEscapeXmlReservedCharacters() {
final StringBuilder builder = new StringBuilder();
SimpleXmlEncoder.writeEscaped(builder , "&<>'\" üäö");
assertEquals("&<>'" üäö", builder.toString());
}
@Test
public void shouldWrapEachRecordInRootTagIfSeparateRootsIsTrue() {
simpleXmlEncoder.setSeparateRoots(true);
emitTwoRecords();
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><tag>value</tag></record></records><?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><tag>value</tag></record></records>",
getResultXml());
}
@Test
public void shouldWrapAllRecordsInOneRootTagtIfSeparateRootsIsFalse() {
simpleXmlEncoder.setSeparateRoots(false);
emitTwoRecords();
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><tag>value</tag></record><record><tag>value</tag></record></records>",
getResultXml());
}
@Test
public void shouldAddNamespaceToRootElement() {
final Map<String, String> namespaces = new HashMap<String, String>();
namespaces.put("ns", "http://example.org/ns");
simpleXmlEncoder.setNamespaces(namespaces);
emitEmptyRecord();
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records xmlns:ns=\"http://example.org/ns\"><record /></records>",
getResultXml());
}
@Test
public void shouldAddNamespaceWithEmptyKeyAsDefaultNamespace() {
final Map<String, String> namespaces = new HashMap<String, String>();
namespaces.put("", "http://example.org/ns");
simpleXmlEncoder.setNamespaces(namespaces);
emitEmptyRecord();
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records xmlns=\"http://example.org/ns\"><record /></records>",
getResultXml());
}
@Test
public void shouldNotEmitRootTagIfWriteRootTagIsFalse() {
simpleXmlEncoder.setWriteRootTag(false);
emitEmptyRecord();
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><record />",
getResultXml());
}
@Test
public void shouldAddNamespacesToRecordTagIfWriteRootTagIsFalse() {
final Map<String, String> namespaces = new HashMap<String, String>();
namespaces.put("ns", "http://example.org/ns");
simpleXmlEncoder.setNamespaces(namespaces);
simpleXmlEncoder.setWriteRootTag(false);
emitEmptyRecord();
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><record xmlns:ns=\"http://example.org/ns\" />",
getResultXml());
}
private void emitTwoRecords() {
simpleXmlEncoder.startRecord("X");
simpleXmlEncoder.literal(TAG, VALUE);
simpleXmlEncoder.endRecord();
simpleXmlEncoder.startRecord("Y");
simpleXmlEncoder.literal(TAG, VALUE);
simpleXmlEncoder.endRecord();
simpleXmlEncoder.closeStream();
}
private void emitEmptyRecord() {
simpleXmlEncoder.startRecord("");
simpleXmlEncoder.endRecord();
simpleXmlEncoder.closeStream();
}
private String getResultXml() {
return resultCollector.toString().replaceAll("[\\n\\t]", "");
}
}
| apache-2.0 |
EcoleKeine/pentaho-kettle | ui/src/org/pentaho/di/ui/spoon/Spoon.java | 337775 | //CHECKSTYLE:FileLength:OFF
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2015 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.spoon;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;
import org.apache.commons.vfs.FileObject;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.window.DefaultToolTip;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.ImageTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TreeAdapter;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.DeviceData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.printing.Printer;
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.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Sash;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.pentaho.di.base.AbstractMeta;
import org.pentaho.di.cluster.ClusterSchema;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.AddUndoPositionInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.DBCache;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.JndiUtil;
import org.pentaho.di.core.KettleClientEnvironment;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.LastUsedFile;
import org.pentaho.di.core.NotePadMeta;
import org.pentaho.di.core.ObjectUsageCount;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.SourceToTargetMapping;
import org.pentaho.di.core.changed.ChangedFlagInterface;
import org.pentaho.di.core.changed.PDIObserver;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleAuthException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleMissingPluginsException;
import org.pentaho.di.core.exception.KettleRowException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.extension.ExtensionPointHandler;
import org.pentaho.di.core.extension.KettleExtensionPoint;
import org.pentaho.di.core.gui.GUIFactory;
import org.pentaho.di.core.gui.OverwritePrompter;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.core.gui.SpoonFactory;
import org.pentaho.di.core.gui.SpoonInterface;
import org.pentaho.di.core.gui.UndoInterface;
import org.pentaho.di.core.lifecycle.LifeEventHandler;
import org.pentaho.di.core.lifecycle.LifeEventInfo;
import org.pentaho.di.core.lifecycle.LifecycleException;
import org.pentaho.di.core.lifecycle.LifecycleSupport;
import org.pentaho.di.core.logging.DefaultLogLevel;
import org.pentaho.di.core.logging.FileLoggingEventListener;
import org.pentaho.di.core.logging.KettleLogStore;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.core.logging.LoggingObjectType;
import org.pentaho.di.core.logging.SimpleLoggingObject;
import org.pentaho.di.core.parameters.NamedParams;
import org.pentaho.di.core.plugins.JobEntryPluginType;
import org.pentaho.di.core.plugins.LifecyclePluginType;
import org.pentaho.di.core.plugins.PartitionerPluginType;
import org.pentaho.di.core.plugins.PluginFolder;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.PluginTypeInterface;
import org.pentaho.di.core.plugins.PluginTypeListener;
import org.pentaho.di.core.plugins.RepositoryPluginType;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.core.reflection.StringSearchResult;
import org.pentaho.di.core.row.RowBuffer;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.undo.TransAction;
import org.pentaho.di.core.util.StringUtil;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.imp.ImportRules;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobExecutionConfiguration;
import org.pentaho.di.job.JobHopMeta;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.job.JobEntryJob;
import org.pentaho.di.job.entries.trans.JobEntryTrans;
import org.pentaho.di.job.entry.JobEntryCopy;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.laf.BasePropertyHandler;
import org.pentaho.di.metastore.MetaStoreConst;
import org.pentaho.di.pan.CommandLineOption;
import org.pentaho.di.partition.PartitionSchema;
import org.pentaho.di.pkg.JarfileGenerator;
import org.pentaho.di.repository.KettleRepositoryLostException;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.RepositoriesMeta;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryCapabilities;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.repository.RepositoryElementInterface;
import org.pentaho.di.repository.RepositoryMeta;
import org.pentaho.di.repository.RepositoryObjectType;
import org.pentaho.di.repository.RepositoryOperation;
import org.pentaho.di.repository.RepositorySecurityManager;
import org.pentaho.di.repository.RepositorySecurityProvider;
import org.pentaho.di.resource.ResourceExportInterface;
import org.pentaho.di.resource.ResourceUtil;
import org.pentaho.di.resource.TopLevelResource;
import org.pentaho.di.shared.SharedObjectInterface;
import org.pentaho.di.shared.SharedObjects;
import org.pentaho.di.trans.DatabaseImpact;
import org.pentaho.di.trans.HasDatabasesInterface;
import org.pentaho.di.trans.HasSlaveServersInterface;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransExecutionConfiguration;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.RowDistributionInterface;
import org.pentaho.di.trans.step.RowDistributionPluginType;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepErrorMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.step.StepPartitioningMeta;
import org.pentaho.di.trans.steps.selectvalues.SelectValuesMeta;
import org.pentaho.di.ui.cluster.dialog.ClusterSchemaDialog;
import org.pentaho.di.ui.cluster.dialog.SlaveServerDialog;
import org.pentaho.di.ui.core.ConstUI;
import org.pentaho.di.ui.core.PrintSpool;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.auth.AuthProviderDialog;
import org.pentaho.di.ui.core.database.wizard.CreateDatabaseWizard;
import org.pentaho.di.ui.core.dialog.AboutDialog;
import org.pentaho.di.ui.core.dialog.CheckResultDialog;
import org.pentaho.di.ui.core.dialog.EnterMappingDialog;
import org.pentaho.di.ui.core.dialog.EnterOptionsDialog;
import org.pentaho.di.ui.core.dialog.EnterSearchDialog;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.EnterStringsDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.KettlePropertiesFileDialog;
import org.pentaho.di.ui.core.dialog.PopupOverwritePrompter;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.dialog.ShowBrowserDialog;
import org.pentaho.di.ui.core.dialog.ShowMessageDialog;
import org.pentaho.di.ui.core.dialog.Splash;
import org.pentaho.di.ui.core.dialog.SubjectDataBrowserDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.OsHelper;
import org.pentaho.di.ui.core.widget.TreeMemory;
import org.pentaho.di.ui.imp.ImportRulesDialog;
import org.pentaho.di.ui.job.dialog.JobDialogPluginType;
import org.pentaho.di.ui.job.dialog.JobLoadProgressDialog;
import org.pentaho.di.ui.partition.dialog.PartitionSchemaDialog;
import org.pentaho.di.ui.repository.ILoginCallback;
import org.pentaho.di.ui.repository.RepositoriesDialog;
import org.pentaho.di.ui.repository.RepositorySecurityUI;
import org.pentaho.di.ui.repository.dialog.RepositoryDialogInterface;
import org.pentaho.di.ui.repository.dialog.RepositoryExportProgressDialog;
import org.pentaho.di.ui.repository.dialog.RepositoryImportProgressDialog;
import org.pentaho.di.ui.repository.dialog.RepositoryRevisionBrowserDialogInterface;
import org.pentaho.di.ui.repository.dialog.SelectDirectoryDialog;
import org.pentaho.di.ui.repository.dialog.SelectObjectDialog;
import org.pentaho.di.ui.repository.repositoryexplorer.RepositoryExplorer;
import org.pentaho.di.ui.repository.repositoryexplorer.RepositoryExplorerCallback;
import org.pentaho.di.ui.repository.repositoryexplorer.UISupportRegistery;
import org.pentaho.di.ui.repository.repositoryexplorer.model.UIRepositoryContent;
import org.pentaho.di.ui.repository.repositoryexplorer.uisupport.BaseRepositoryExplorerUISupport;
import org.pentaho.di.ui.repository.repositoryexplorer.uisupport.ManageUserUISupport;
import org.pentaho.di.ui.spoon.SpoonLifecycleListener.SpoonLifeCycleEvent;
import org.pentaho.di.ui.spoon.TabMapEntry.ObjectType;
import org.pentaho.di.ui.spoon.delegates.SpoonDelegates;
import org.pentaho.di.ui.spoon.dialog.AnalyseImpactProgressDialog;
import org.pentaho.di.ui.spoon.dialog.CapabilityManagerDialog;
import org.pentaho.di.ui.spoon.dialog.CheckTransProgressDialog;
import org.pentaho.di.ui.spoon.dialog.LogSettingsDialog;
import org.pentaho.di.ui.spoon.dialog.MetaStoreExplorerDialog;
import org.pentaho.di.ui.spoon.dialog.SaveProgressDialog;
import org.pentaho.di.ui.spoon.job.JobGraph;
import org.pentaho.di.ui.spoon.partition.PartitionMethodSelector;
import org.pentaho.di.ui.spoon.partition.PartitionSettings;
import org.pentaho.di.ui.spoon.partition.processor.MethodProcessor;
import org.pentaho.di.ui.spoon.partition.processor.MethodProcessorFactory;
import org.pentaho.di.ui.spoon.trans.TransGraph;
import org.pentaho.di.ui.spoon.wizards.CopyTableWizardPage1;
import org.pentaho.di.ui.spoon.wizards.CopyTableWizardPage2;
import org.pentaho.di.ui.trans.dialog.TransDialogPluginType;
import org.pentaho.di.ui.trans.dialog.TransHopDialog;
import org.pentaho.di.ui.trans.dialog.TransLoadProgressDialog;
import org.pentaho.di.ui.util.HelpUtils;
import org.pentaho.di.ui.util.ThreadGuiResources;
import org.pentaho.di.ui.xul.KettleXulLoader;
import org.pentaho.di.version.BuildVersion;
import org.pentaho.metastore.api.IMetaStore;
import org.pentaho.metastore.api.exceptions.MetaStoreException;
import org.pentaho.metastore.stores.delegate.DelegatingMetaStore;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulEventSource;
import org.pentaho.ui.xul.binding.BindingFactory;
import org.pentaho.ui.xul.binding.DefaultBindingFactory;
import org.pentaho.ui.xul.components.WaitBoxRunnable;
import org.pentaho.ui.xul.components.XulMenuitem;
import org.pentaho.ui.xul.components.XulMenuseparator;
import org.pentaho.ui.xul.components.XulToolbarbutton;
import org.pentaho.ui.xul.components.XulWaitBox;
import org.pentaho.ui.xul.containers.XulMenupopup;
import org.pentaho.ui.xul.containers.XulToolbar;
import org.pentaho.ui.xul.impl.XulEventHandler;
import org.pentaho.ui.xul.jface.tags.ApplicationWindowLocal;
import org.pentaho.ui.xul.jface.tags.JfaceMenuitem;
import org.pentaho.ui.xul.jface.tags.JfaceMenupopup;
import org.pentaho.ui.xul.swt.tags.SwtDeck;
import org.pentaho.vfs.ui.VfsFileChooserDialog;
import org.pentaho.xul.swt.tab.TabItem;
import org.pentaho.xul.swt.tab.TabListener;
import org.pentaho.xul.swt.tab.TabSet;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import com.google.common.annotations.VisibleForTesting;
/**
* This class handles the main window of the Spoon graphical transformation editor.
*
* @author Matt
* @since 16-may-2003, i18n at 07-Feb-2006, redesign 01-Dec-2006
*/
public class Spoon extends ApplicationWindow implements AddUndoPositionInterface, TabListener, SpoonInterface,
OverwritePrompter, PDIObserver, LifeEventHandler, XulEventSource, XulEventHandler, PartitionSchemasProvider {
private static Class<?> PKG = Spoon.class;
public static final LoggingObjectInterface loggingObject = new SimpleLoggingObject( "Spoon", LoggingObjectType.SPOON,
null );
public static final String STRING_TRANSFORMATIONS = BaseMessages.getString( PKG, "Spoon.STRING_TRANSFORMATIONS" );
public static final String STRING_JOBS = BaseMessages.getString( PKG, "Spoon.STRING_JOBS" );
public static final String STRING_BUILDING_BLOCKS = BaseMessages.getString( PKG, "Spoon.STRING_BUILDING_BLOCKS" );
public static final String STRING_ELEMENTS = BaseMessages.getString( PKG, "Spoon.STRING_ELEMENTS" );
public static final String STRING_CONNECTIONS = BaseMessages.getString( PKG, "Spoon.STRING_CONNECTIONS" );
public static final String STRING_STEPS = BaseMessages.getString( PKG, "Spoon.STRING_STEPS" );
public static final String STRING_JOB_ENTRIES = BaseMessages.getString( PKG, "Spoon.STRING_JOB_ENTRIES" );
public static final String STRING_HOPS = BaseMessages.getString( PKG, "Spoon.STRING_HOPS" );
public static final String STRING_PARTITIONS = BaseMessages.getString( PKG, "Spoon.STRING_PARTITIONS" );
public static final String STRING_SLAVES = BaseMessages.getString( PKG, "Spoon.STRING_SLAVES" );
public static final String STRING_CLUSTERS = BaseMessages.getString( PKG, "Spoon.STRING_CLUSTERS" );
public static final String STRING_TRANS_BASE = BaseMessages.getString( PKG, "Spoon.STRING_BASE" );
public static final String STRING_HISTORY = BaseMessages.getString( PKG, "Spoon.STRING_HISTORY" );
public static final String STRING_TRANS_NO_NAME = BaseMessages.getString( PKG, "Spoon.STRING_TRANS_NO_NAME" );
public static final String STRING_JOB_NO_NAME = BaseMessages.getString( PKG, "Spoon.STRING_JOB_NO_NAME" );
public static final String STRING_TRANSFORMATION = BaseMessages.getString( PKG, "Spoon.STRING_TRANSFORMATION" );
public static final String STRING_JOB = BaseMessages.getString( PKG, "Spoon.STRING_JOB" );
private static final String SYNC_TRANS = "sync_trans_name_to_file_name";
public static final String APP_NAME = BaseMessages.getString( PKG, "Spoon.Application.Name" );
private static final String STRING_SPOON_MAIN_TREE = BaseMessages.getString( PKG, "Spoon.MainTree.Label" );
private static final String STRING_SPOON_CORE_OBJECTS_TREE = BaseMessages
.getString( PKG, "Spoon.CoreObjectsTree.Label" );
public static final String XML_TAG_TRANSFORMATION_STEPS = "transformation-steps";
public static final String XML_TAG_JOB_JOB_ENTRIES = "job-jobentries";
private static final String XML_TAG_STEPS = "steps";
public static final int MESSAGE_DIALOG_WITH_TOGGLE_YES_BUTTON_ID = 256;
public static final int MESSAGE_DIALOG_WITH_TOGGLE_NO_BUTTON_ID = 257;
public static final int MESSAGE_DIALOG_WITH_TOGGLE_CUSTOM_DISTRIBUTION_BUTTON_ID = 258;
private static Spoon staticSpoon;
private static LogChannelInterface log;
private Display display;
private Shell shell;
private static Splash splash;
private static FileLoggingEventListener fileLoggingEventListener;
private boolean destroy;
private SashForm sashform;
public TabSet tabfolder;
// THE HANDLERS
public SpoonDelegates delegates = new SpoonDelegates( this );
public RowMetaAndData variables = new RowMetaAndData( new RowMeta() );
/**
* These are the arguments that were given at Spoon launch time...
*/
private String[] arguments;
private boolean stopped;
private Cursor cursor_hourglass, cursor_hand;
public PropsUI props;
public Repository rep;
// private RepositorySecurityManager securityManager;
public RepositoryCapabilities capabilities;
// Save the last directory saved to for new files
// TODO: Save the last saved position to the defaultSaveLocation
private RepositoryDirectoryInterface defaultSaveLocation = null;
// Associate the defaultSaveLocation with a given repository; We should clear this out on a repo change
private Repository defaultSaveLocationRepository = null;
private CTabItem view, design;
private Label selectionLabel;
public Text selectionFilter;
private org.eclipse.swt.widgets.Menu fileMenus;
private static final String APP_TITLE = APP_NAME;
private static final String STRING_WELCOME_TAB_NAME = BaseMessages.getString( PKG, "Spoon.Title.STRING_WELCOME" );
private static final String STRING_DOCUMENT_TAB_NAME = BaseMessages.getString( PKG, "Spoon.Documentation" );
// "docs/English/welcome/index.html";
private static final String FILE_WELCOME_PAGE = Const
.safeAppendDirectory( BasePropertyHandler.getProperty( "documentationDirBase", "docs/" ),
BaseMessages.getString( PKG, "Spoon.Title.STRING_DOCUMENT_WELCOME" ) );
// "docs/English/InformationMap.html";
private static final String FILE_DOCUMENT_MAP = Const
.safeAppendDirectory( BasePropertyHandler.getProperty( "documentationDirBase", "docs/" ),
BaseMessages.getString( PKG, "Spoon.Title.STRING_DOCUMENT_MAP" ) );
private static final String UNDO_MENU_ITEM = "edit-undo";
private static final String REDO_MENU_ITEM = "edit-redo";
// "Undo : not available \tCTRL-Z"
private static final String UNDO_UNAVAILABLE = BaseMessages.getString( PKG, "Spoon.Menu.Undo.NotAvailable" );
// "Redo : not available \tCTRL-Y"
private static final String REDO_UNAVAILABLE = BaseMessages.getString( PKG, "Spoon.Menu.Redo.NotAvailable" );
public static final String REFRESH_SELECTION_EXTENSION = "REFRESH_SELECTION_EXTENSION";
public static final String EDIT_SELECTION_EXTENSION = "EDIT_SELECTION_EXTENSION";
private Composite tabComp;
private Tree selectionTree;
private Tree coreObjectsTree;
private TransExecutionConfiguration transExecutionConfiguration;
private TransExecutionConfiguration transPreviewExecutionConfiguration;
private TransExecutionConfiguration transDebugExecutionConfiguration;
private JobExecutionConfiguration jobExecutionConfiguration;
// private Menu spoonMenu; // Connections,
private int coreObjectsState = STATE_CORE_OBJECTS_NONE;
protected Map<String, FileListener> fileExtensionMap = new HashMap<String, FileListener>();
private List<Object[]> menuListeners = new ArrayList<Object[]>();
// loads the lifecycle listeners
private LifecycleSupport lifecycleSupport = new LifecycleSupport();
private Composite mainComposite;
private boolean viewSelected;
private boolean designSelected;
private Composite variableComposite;
private Map<String, String> coreStepToolTipMap;
private Map<String, String> coreJobToolTipMap;
private DefaultToolTip toolTip;
public Map<String, SharedObjects> sharedObjectsFileMap;
/**
* We can use this to set a default filter path in the open and save dialogs
*/
public String lastDirOpened;
private List<FileListener> fileListeners = new ArrayList<FileListener>();
private XulDomContainer mainSpoonContainer;
// Menu controllers to modify the main spoon menu
private List<ISpoonMenuController> menuControllers = new ArrayList<ISpoonMenuController>();
private XulToolbar mainToolbar;
private SwtDeck deck;
public static final String XUL_FILE_MAIN = "ui/spoon.xul";
private Map<String, XulComponent> menuMap = new HashMap<String, XulComponent>();
private RepositoriesDialog loginDialog;
private VfsFileChooserDialog vfsFileChooserDialog;
// the id of the perspective to start in, if any
protected String startupPerspective = null;
private CommandLineOption[] commandLineOptions;
public DelegatingMetaStore metaStore;
/**
* This is the main procedure for Spoon.
*
* @param a
* Arguments are available in the "Get System Info" step.
*/
public static void main( String[] a ) throws KettleException {
ExecutorService executor = Executors.newCachedThreadPool();
Future<KettleException> pluginRegistryFuture = executor.submit( new Callable<KettleException>() {
@Override
public KettleException call() throws Exception {
registerUIPluginObjectTypes();
try {
KettleEnvironment.init();
} catch ( KettleException e ) {
return e;
}
KettleClientEnvironment.getInstance().setClient( KettleClientEnvironment.ClientType.SPOON );
return null;
}
} );
try {
OsHelper.setAppName();
// Bootstrap Kettle
//
Display display;
if ( System.getProperties().containsKey( "SLEAK" ) ) {
DeviceData data = new DeviceData();
data.tracking = true;
display = new Display( data );
Sleak sleak = new Sleak();
Shell sleakShell = new Shell( display );
sleakShell.setText( "S-Leak" );
org.eclipse.swt.graphics.Point size = sleakShell.getSize();
sleakShell.setSize( size.x / 2, size.y / 2 );
sleak.create( sleakShell );
sleakShell.open();
} else {
display = new Display();
}
// Note: this needs to be done before the look and feel is set
OsHelper.initOsHandlers( display );
UIManager.setLookAndFeel( new MetalLookAndFeel() );
// The core plugin types don't know about UI classes. Add them in now
// before the PluginRegistry is inited.
splash = new Splash( display );
List<String> args = new ArrayList<String>( Arrays.asList( a ) );
CommandLineOption[] commandLineOptions = getCommandLineArgs( args );
KettleException registryException = pluginRegistryFuture.get();
if ( registryException != null ) {
throw registryException;
}
PropsUI.init( display, Props.TYPE_PROPERTIES_SPOON );
KettleLogStore
.init( PropsUI.getInstance().getMaxNrLinesInLog(), PropsUI.getInstance().getMaxLogLineTimeoutMinutes() );
initLogging( commandLineOptions );
// remember...
staticSpoon = new Spoon();
staticSpoon.commandLineOptions = commandLineOptions;
// pull the startup perspective id from the command line options and hand it to Spoon
String pId;
StringBuffer perspectiveIdBuff = Spoon.getCommandLineOption( commandLineOptions, "perspective" ).getArgument();
pId = perspectiveIdBuff.toString();
if ( !Const.isEmpty( pId ) ) {
Spoon.staticSpoon.startupPerspective = pId;
}
SpoonFactory.setSpoonInstance( staticSpoon );
staticSpoon.setDestroy( true );
GUIFactory.setThreadDialogs( new ThreadGuiResources() );
staticSpoon.setArguments( args.toArray( new String[ args.size() ] ) );
staticSpoon.start();
} catch ( Throwable t ) {
// avoid calls to Messages i18n method getString() in this block
// We do this to (hopefully) also catch Out of Memory Exceptions
//
t.printStackTrace();
if ( staticSpoon != null ) {
log.logError( "Fatal error : " + Const.NVL( t.toString(), Const.NVL( t.getMessage(), "Unknown error" ) ) );
log.logError( Const.getStackTracker( t ) );
}
}
// Kill all remaining things in this VM!
System.exit( 0 );
}
private static void initLogging( CommandLineOption[] options ) throws KettleException {
StringBuffer optionLogFile = getCommandLineOption( options, "logfile" ).getArgument();
StringBuffer optionLogLevel = getCommandLineOption( options, "level" ).getArgument();
// Set default Locale:
Locale.setDefault( Const.DEFAULT_LOCALE );
if ( !Const.isEmpty( optionLogFile ) ) {
fileLoggingEventListener = new FileLoggingEventListener( optionLogFile.toString(), true );
if ( log.isBasic() ) {
String filename = fileLoggingEventListener.getFilename();
log.logBasic( BaseMessages.getString( PKG, "Spoon.Log.LoggingToFile" ) + filename );
}
KettleLogStore.getAppender().addLoggingEventListener( fileLoggingEventListener );
} else {
fileLoggingEventListener = null;
}
if ( !Const.isEmpty( optionLogLevel ) ) {
log.setLogLevel( LogLevel.getLogLevelForCode( optionLogLevel.toString() ) );
if ( log.isBasic() ) {
// "Logging is at level : "
log.logBasic( BaseMessages.getString( PKG, "Spoon.Log.LoggingAtLevel" ) + log.getLogLevel().getDescription() );
}
}
}
public Spoon() {
this( null );
}
public Spoon( Repository rep ) {
super( null );
this.addMenuBar();
log = new LogChannel( APP_NAME );
SpoonFactory.setSpoonInstance( this );
// Load at least one local Pentaho metastore and add it to the delegating metastore
//
metaStore = new DelegatingMetaStore();
try {
IMetaStore localMetaStore = MetaStoreConst.openLocalPentahoMetaStore();
metaStore.addMetaStore( localMetaStore );
metaStore.setActiveMetaStoreName( localMetaStore.getName() );
if ( rep != null ) {
metaStore.addMetaStore( 0, rep.getMetaStore() );
metaStore.setActiveMetaStoreName( rep.getMetaStore().getName() );
}
} catch ( MetaStoreException e ) {
new ErrorDialog( shell, "Error opening Pentaho Metastore", "Unable to open local Pentaho Metastore", e );
}
setRepository( rep );
props = PropsUI.getInstance();
sharedObjectsFileMap = new Hashtable<String, SharedObjects>();
Thread uiThread = Thread.currentThread();
display = Display.findDisplay( uiThread );
staticSpoon = this;
try {
JndiUtil.initJNDI();
} catch ( Exception e ) {
new ErrorDialog( shell, "Unable to init simple JNDI", "Unable to init simple JNDI", e );
}
}
/**
* The core plugin types don't know about UI classes. This method adds those in before initialization.
*
* TODO: create a SpoonLifecycle listener that can notify interested parties of a pre-initialization state so this can
* happen in those listeners.
*/
private static void registerUIPluginObjectTypes() {
RepositoryPluginType.getInstance()
.addObjectType( RepositoryRevisionBrowserDialogInterface.class, "version-browser-classname" );
RepositoryPluginType.getInstance().addObjectType( RepositoryDialogInterface.class, "dialog-classname" );
PluginRegistry.addPluginType( SpoonPluginType.getInstance() );
SpoonPluginType.getInstance().getPluginFolders().add( new PluginFolder( "plugins/repositories", false, true ) );
LifecyclePluginType.getInstance().getPluginFolders().add( new PluginFolder( "plugins/spoon", false, true ) );
LifecyclePluginType.getInstance().getPluginFolders().add( new PluginFolder( "plugins/repositories", false, true ) );
PluginRegistry.addPluginType( JobDialogPluginType.getInstance() );
PluginRegistry.addPluginType( TransDialogPluginType.getInstance() );
}
public void init( TransMeta ti ) {
FormLayout layout = new FormLayout();
layout.marginWidth = 0;
layout.marginHeight = 0;
shell.setLayout( layout );
addFileListener( new TransFileListener() );
addFileListener( new JobFileListener() );
// INIT Data structure
if ( ti != null ) {
delegates.trans.addTransformation( ti );
}
// Load settings in the props
loadSettings();
transExecutionConfiguration = new TransExecutionConfiguration();
transExecutionConfiguration.setGatheringMetrics( true );
transPreviewExecutionConfiguration = new TransExecutionConfiguration();
transPreviewExecutionConfiguration.setGatheringMetrics( true );
transDebugExecutionConfiguration = new TransExecutionConfiguration();
transDebugExecutionConfiguration.setGatheringMetrics( true );
jobExecutionConfiguration = new JobExecutionConfiguration();
// Clean out every time we start, auto-loading etc, is not a good idea
// If they are needed that often, set them in the kettle.properties file
//
variables = new RowMetaAndData( new RowMeta() );
// props.setLook(shell);
Image[] images = { GUIResource.getInstance().getImageSpoonHigh(), GUIResource.getInstance().getImageSpoon() };
shell.setImages( images );
// shell.setImage(GUIResource.getInstance().getImageSpoon());
cursor_hourglass = new Cursor( display, SWT.CURSOR_WAIT );
cursor_hand = new Cursor( display, SWT.CURSOR_HAND );
Composite sashComposite = null;
MainSpoonPerspective mainPerspective = null;
try {
KettleXulLoader xulLoader = new KettleXulLoader();
xulLoader.setIconsSize( 16, 16 );
xulLoader.setOuterContext( shell );
xulLoader.setSettingsManager( XulSpoonSettingsManager.getInstance() );
ApplicationWindowLocal.setApplicationWindow( this );
mainSpoonContainer = xulLoader.loadXul( XUL_FILE_MAIN, new XulSpoonResourceBundle() );
BindingFactory bf = new DefaultBindingFactory();
bf.setDocument( mainSpoonContainer.getDocumentRoot() );
mainSpoonContainer.addEventHandler( this );
/* menuBar = (XulMenubar) */
mainSpoonContainer.getDocumentRoot().getElementById( "spoon-menubar" );
mainToolbar = (XulToolbar) mainSpoonContainer.getDocumentRoot().getElementById( "main-toolbar" );
props.setLook( (Control) mainToolbar.getManagedObject(), Props.WIDGET_STYLE_TOOLBAR );
/* canvas = (XulVbox) */
mainSpoonContainer.getDocumentRoot().getElementById( "trans-job-canvas" );
deck = (SwtDeck) mainSpoonContainer.getDocumentRoot().getElementById( "canvas-deck" );
final Composite tempSashComposite = new Composite( shell, SWT.None );
sashComposite = tempSashComposite;
mainPerspective = new MainSpoonPerspective( tempSashComposite, tabfolder );
if ( startupPerspective == null ) {
startupPerspective = mainPerspective.getId();
}
SpoonPerspectiveManager.getInstance().setStartupPerspective( startupPerspective );
SpoonPerspectiveManager.getInstance().addPerspective( mainPerspective );
SpoonPluginManager.getInstance().applyPluginsForContainer( "spoon", mainSpoonContainer );
SpoonPerspectiveManager.getInstance().setDeck( deck );
SpoonPerspectiveManager.getInstance().setXulDoc( mainSpoonContainer );
SpoonPerspectiveManager.getInstance().initialize();
} catch ( Exception e ) {
LogChannel.GENERAL.logError( "Error initializing transformation", e );
}
// addBar();
// Set the shell size, based upon previous time...
WindowProperty windowProperty = props.getScreen( APP_TITLE );
if ( windowProperty != null ) {
windowProperty.setShell( shell );
} else {
shell.pack();
shell.setMaximized( true ); // Default = maximized!
}
layout = new FormLayout();
layout.marginWidth = 0;
layout.marginHeight = 0;
GridData data = new GridData();
data.grabExcessHorizontalSpace = true;
data.grabExcessVerticalSpace = true;
data.verticalAlignment = SWT.FILL;
data.horizontalAlignment = SWT.FILL;
sashComposite.setLayoutData( data );
sashComposite.setLayout( layout );
sashform = new SashForm( sashComposite, SWT.HORIZONTAL );
FormData fdSash = new FormData();
fdSash.left = new FormAttachment( 0, 0 );
// fdSash.top = new FormAttachment((org.eclipse.swt.widgets.ToolBar)
// toolbar.getNativeObject(), 0);
fdSash.top = new FormAttachment( 0, 0 );
fdSash.bottom = new FormAttachment( 100, 0 );
fdSash.right = new FormAttachment( 100, 0 );
sashform.setLayoutData( fdSash );
createPopupMenus();
addTree();
addTabs();
mainPerspective.setTabset( this.tabfolder );
( (Composite) deck.getManagedObject() ).layout( true, true );
SpoonPluginManager.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.STARTUP );
// Add a browser widget
if ( props.showWelcomePageOnStartup() ) {
showWelcomePage();
}
// Allow data to be copied or moved to the drop target
int operations = DND.DROP_COPY | DND.DROP_DEFAULT;
DropTarget target = new DropTarget( shell, operations );
// Receive data in File format
final FileTransfer fileTransfer = FileTransfer.getInstance();
Transfer[] types = new Transfer[] { fileTransfer };
target.setTransfer( types );
target.addDropListener( new DropTargetListener() {
public void dragEnter( DropTargetEvent event ) {
if ( event.detail == DND.DROP_DEFAULT ) {
if ( ( event.operations & DND.DROP_COPY ) != 0 ) {
event.detail = DND.DROP_COPY;
} else {
event.detail = DND.DROP_NONE;
}
}
}
public void dragOver( DropTargetEvent event ) {
event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL;
}
public void dragOperationChanged( DropTargetEvent event ) {
if ( event.detail == DND.DROP_DEFAULT ) {
if ( ( event.operations & DND.DROP_COPY ) != 0 ) {
event.detail = DND.DROP_COPY;
} else {
event.detail = DND.DROP_NONE;
}
}
}
public void dragLeave( DropTargetEvent event ) {
}
public void dropAccept( DropTargetEvent event ) {
}
public void drop( DropTargetEvent event ) {
if ( fileTransfer.isSupportedType( event.currentDataType ) ) {
String[] files = (String[]) event.data;
for ( String file : files ) {
openFile( file, false );
}
}
}
} );
// listen for steps being added or removed
PluginRegistry.getInstance().addPluginListener( StepPluginType.class, new PluginTypeListener() {
@Override
public void pluginAdded( Object serviceObject ) {
previousShowTrans = false; // hack to get the tree to reload
Display.getDefault().asyncExec( new Runnable() {
@Override
public void run() {
refreshCoreObjects();
}
} );
}
@Override
public void pluginRemoved( Object serviceObject ) {
previousShowTrans = false; // hack to get the tree to reload
Display.getDefault().asyncExec( new Runnable() {
@Override
public void run() {
refreshCoreObjects();
}
} );
}
@Override
public void pluginChanged( Object serviceObject ) {
}
} );
}
public XulDomContainer getMainSpoonContainer() {
return mainSpoonContainer;
}
public void loadPerspective( String id ) {
List<SpoonPerspective> perspectives = SpoonPerspectiveManager.getInstance().getPerspectives();
for ( int pos = 0; pos < perspectives.size(); pos++ ) {
SpoonPerspective perspective = perspectives.get( pos );
if ( perspective.getId().equals( id ) ) {
loadPerspective( pos );
return;
}
}
}
public void loadPerspective( int pos ) {
try {
SpoonPerspectiveManager.getInstance().activatePerspective(
SpoonPerspectiveManager.getInstance().getPerspectives().get( pos ).getClass() );
} catch ( KettleException e ) {
log.logError( "Error loading perspective", e );
}
}
public static Spoon getInstance() {
return staticSpoon;
}
public VfsFileChooserDialog getVfsFileChooserDialog( FileObject rootFile, FileObject initialFile ) {
if ( vfsFileChooserDialog == null ) {
vfsFileChooserDialog = new VfsFileChooserDialog( shell, KettleVFS.getInstance().getFileSystemManager(), rootFile,
initialFile );
}
vfsFileChooserDialog.setRootFile( rootFile );
vfsFileChooserDialog.setInitialFile( initialFile );
return vfsFileChooserDialog;
}
public boolean closeFile() {
boolean closed = true;
EngineMetaInterface meta = getActiveMeta();
if ( meta != null ) {
String beforeCloseId = null;
String afterCloseId = null;
if( meta instanceof TransMeta ) {
beforeCloseId = KettleExtensionPoint.TransBeforeClose.id;
afterCloseId = KettleExtensionPoint.TransAfterClose.id;
}
else if( meta instanceof JobMeta ) {
beforeCloseId = KettleExtensionPoint.JobBeforeClose.id;
afterCloseId = KettleExtensionPoint.JobAfterClose.id;
}
if( beforeCloseId != null ) {
try {
ExtensionPointHandler.callExtensionPoint( log, beforeCloseId, meta );
} catch ( KettleException e ) {
// fails gracefully but perhaps should return false?
}
}
// If a transformation or job is the current active tab, close it
closed = tabCloseSelected();
if( closed && ( afterCloseId != null ) ) {
try {
ExtensionPointHandler.callExtensionPoint( log, afterCloseId, meta );
} catch ( KettleException e ) {
// fails gracefully but perhaps should return false?
}
}
}
return closed;
}
public boolean closeAllFiles() {
int numTabs = delegates.tabs.getTabs().size();
for ( int i = numTabs - 1; i >= 0; i-- ) {
tabfolder.setSelected( i );
if ( !closeFile() ) {
return false; // A single cancel aborts the rest of the operation
}
}
return true;
}
/**
* Prompt user to close all open Jobs & Transformations if they have execute permissions.
* If they don't have execute permission then warn user if they really want to disconnect
* from repository. If yes, close all tabs.
*
* @return If user agrees with closing of tabs then return true so we can disconnect from the repo.
*/
public boolean closeAllJobsAndTransformations() {
// Check to see if there are any open jobs/trans. If there are not any then we don't need to close anything.
// Keep in mind that the 'Welcome' tab can be active.
final List<TransMeta> transList = delegates.trans.getTransformationList();
final List<JobMeta> jobList = delegates.jobs.getJobList();
if ( ( transList.size() == 0 ) && ( jobList.size() == 0 ) ) {
return true;
}
boolean createPerms = !RepositorySecurityUI
.verifyOperations( shell, rep, false, RepositoryOperation.MODIFY_TRANSFORMATION,
RepositoryOperation.MODIFY_JOB );
boolean executePerms = !RepositorySecurityUI
.verifyOperations( shell, rep, false, RepositoryOperation.EXECUTE_TRANSFORMATION,
RepositoryOperation.EXECUTE_JOB );
boolean readPerms = !RepositorySecurityUI
.verifyOperations( shell, rep, false, RepositoryOperation.READ_TRANSFORMATION, RepositoryOperation.READ_JOB );
// Check to see if display of warning dialog has been disabled
String warningTitle = BaseMessages.getString( PKG, "Spoon.Dialog.WarnToCloseAllForce.Disconnect.Title" );
String warningText = BaseMessages.getString( PKG, "Spoon.Dialog.WarnToCloseAllForce.Disconnect.Message" );
int buttons = SWT.OK;
if ( readPerms && createPerms && executePerms ) {
warningTitle = BaseMessages.getString( PKG, "Spoon.Dialog.WarnToCloseAllOption.Disconnect.Title" );
warningText = BaseMessages.getString( PKG, "Spoon.Dialog.WarnToCloseAllOption.Disconnect.Message" );
buttons = SWT.YES | SWT.NO;
}
MessageBox mb = new MessageBox( Spoon.getInstance().getShell(), buttons | SWT.ICON_WARNING );
mb.setMessage( warningText );
mb.setText( warningTitle );
final int isCloseAllFiles = mb.open();
if ( ( isCloseAllFiles == SWT.YES ) || ( isCloseAllFiles == SWT.OK ) ) {
// Yes - User specified that they want to close all.
return Spoon.getInstance().closeAllFiles();
} else if ( ( isCloseAllFiles == SWT.NO ) && ( executePerms ) ) {
// No - don't close tabs only if user has execute permissions.
// Return true so we can disconnect from repo
return true;
} else {
// Cancel - don't close tabs and don't disconnect from repo
return false;
}
}
public void closeSpoonBrowser() {
TabMapEntry browserTab = delegates.tabs.findTabMapEntry( STRING_WELCOME_TAB_NAME, ObjectType.BROWSER );
if ( browserTab != null ) {
delegates.tabs.removeTab( browserTab );
}
}
/**
* Search the transformation meta-data.
*
*/
public void searchMetaData() {
TransMeta[] transMetas = getLoadedTransformations();
JobMeta[] jobMetas = getLoadedJobs();
if ( ( transMetas == null || transMetas.length == 0 ) && ( jobMetas == null || jobMetas.length == 0 ) ) {
return;
}
EnterSearchDialog esd = new EnterSearchDialog( shell );
if ( !esd.open() ) {
return;
}
List<Object[]> rows = new ArrayList<Object[]>();
for ( TransMeta transMeta : transMetas ) {
String filter = esd.getFilterString();
if ( filter != null ) {
filter = filter.toUpperCase();
}
List<StringSearchResult> stringList =
transMeta.getStringList( esd.isSearchingSteps(), esd.isSearchingDatabases(), esd.isSearchingNotes() );
for ( StringSearchResult result : stringList ) {
boolean add = Const.isEmpty( filter );
if ( filter != null && result.getString().toUpperCase().contains( filter ) ) {
add = true;
}
if ( filter != null && result.getFieldName().toUpperCase().contains( filter ) ) {
add = true;
}
if ( filter != null && result.getParentObject().toString().toUpperCase().contains( filter ) ) {
add = true;
}
if ( filter != null && result.getGrandParentObject().toString().toUpperCase().contains( filter ) ) {
add = true;
}
if ( add ) {
rows.add( result.toRow() );
}
}
}
for ( JobMeta jobMeta : jobMetas ) {
String filter = esd.getFilterString();
if ( filter != null ) {
filter = filter.toUpperCase();
}
List<StringSearchResult> stringList =
jobMeta.getStringList( esd.isSearchingSteps(), esd.isSearchingDatabases(), esd.isSearchingNotes() );
for ( StringSearchResult result : stringList ) {
boolean add = Const.isEmpty( filter );
if ( filter != null && result.getString().toUpperCase().contains( filter ) ) {
add = true;
}
if ( filter != null && result.getFieldName().toUpperCase().contains( filter ) ) {
add = true;
}
if ( filter != null && result.getParentObject().toString().toUpperCase().contains( filter ) ) {
add = true;
}
if ( filter != null && result.getGrandParentObject().toString().toUpperCase().contains( filter ) ) {
add = true;
}
if ( add ) {
rows.add( result.toRow() );
}
}
}
if ( rows.size() != 0 ) {
PreviewRowsDialog prd =
new PreviewRowsDialog( shell, Variables.getADefaultVariableSpace(), SWT.NONE, BaseMessages.getString(
PKG, "Spoon.StringSearchResult.Subtitle" ), StringSearchResult.getResultRowMeta(), rows );
String title = BaseMessages.getString( PKG, "Spoon.StringSearchResult.Title" );
String message = BaseMessages.getString( PKG, "Spoon.StringSearchResult.Message" );
prd.setTitleMessage( title, message );
prd.open();
} else {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.NothingFound.Message" ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.NothingFound.Title" ) ); // Sorry!
mb.open();
}
}
public void showArguments() {
RowMetaAndData allArgs = new RowMetaAndData();
for ( int ii = 0; ii < arguments.length; ++ii ) {
allArgs.addValue( new ValueMeta(
Props.STRING_ARGUMENT_NAME_PREFIX + ( 1 + ii ), ValueMetaInterface.TYPE_STRING ), arguments[ii] );
}
// Now ask the use for more info on these!
EnterStringsDialog esd = new EnterStringsDialog( shell, SWT.NONE, allArgs );
esd.setTitle( BaseMessages.getString( PKG, "Spoon.Dialog.ShowArguments.Title" ) );
esd.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.ShowArguments.Message" ) );
esd.setReadOnly( true );
esd.setShellImage( GUIResource.getInstance().getImageLogoSmall() );
esd.open();
}
private void fillVariables( RowMetaAndData vars ) {
TransMeta[] transMetas = getLoadedTransformations();
JobMeta[] jobMetas = getLoadedJobs();
if ( ( transMetas == null || transMetas.length == 0 ) && ( jobMetas == null || jobMetas.length == 0 ) ) {
return;
}
Properties sp = new Properties();
sp.putAll( System.getProperties() );
VariableSpace space = Variables.getADefaultVariableSpace();
String[] keys = space.listVariables();
for ( String key : keys ) {
sp.put( key, space.getVariable( key ) );
}
for ( TransMeta transMeta : transMetas ) {
List<String> list = transMeta.getUsedVariables();
for ( String varName : list ) {
String varValue = sp.getProperty( varName, "" );
if ( vars.getRowMeta().indexOfValue( varName ) < 0 && !varName.startsWith( Const.INTERNAL_VARIABLE_PREFIX ) ) {
vars.addValue( new ValueMeta( varName, ValueMetaInterface.TYPE_STRING ), varValue );
}
}
}
for ( JobMeta jobMeta : jobMetas ) {
List<String> list = jobMeta.getUsedVariables();
for ( String varName : list ) {
String varValue = sp.getProperty( varName, "" );
if ( vars.getRowMeta().indexOfValue( varName ) < 0 && !varName.startsWith( Const.INTERNAL_VARIABLE_PREFIX ) ) {
vars.addValue( new ValueMeta( varName, ValueMetaInterface.TYPE_STRING ), varValue );
}
}
}
}
public void setVariables() {
fillVariables( variables );
// Now ask the use for more info on these!
EnterStringsDialog esd = new EnterStringsDialog( shell, SWT.NONE, variables );
esd.setTitle( BaseMessages.getString( PKG, "Spoon.Dialog.SetVariables.Title" ) );
esd.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.SetVariables.Message" ) );
esd.setReadOnly( false );
esd.setShellImage( GUIResource.getInstance().getImageVariable() );
if ( esd.open() != null ) {
applyVariables();
}
}
public void applyVariables() {
for ( int i = 0; i < variables.size(); i++ ) {
try {
String name = variables.getValueMeta( i ).getName();
String value = variables.getString( i, "" );
applyVariableToAllLoadedObjects( name, value );
} catch ( KettleValueException e ) {
// Just eat the exception. getString() should never give an
// exception.
log.logDebug( "Unexpected exception occurred : " + e.getMessage() );
}
}
}
public void applyVariableToAllLoadedObjects( String name, String value ) {
// We want to insert the variables into all loaded jobs and
// transformations
//
for ( TransMeta transMeta : getLoadedTransformations() ) {
transMeta.setVariable( name, Const.NVL( value, "" ) );
}
for ( JobMeta jobMeta : getLoadedJobs() ) {
jobMeta.setVariable( name, Const.NVL( value, "" ) );
}
// Not only that, we also want to set the variables in the
// execution configurations...
//
transExecutionConfiguration.getVariables().put( name, value );
jobExecutionConfiguration.getVariables().put( name, value );
transDebugExecutionConfiguration.getVariables().put( name, value );
}
public void showVariables() {
fillVariables( variables );
// Now ask the use for more info on these!
EnterStringsDialog esd = new EnterStringsDialog( shell, SWT.NONE, variables );
esd.setTitle( BaseMessages.getString( PKG, "Spoon.Dialog.ShowVariables.Title" ) );
esd.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.ShowVariables.Message" ) );
esd.setReadOnly( true );
esd.setShellImage( GUIResource.getInstance().getImageVariable() );
esd.open();
}
public void openSpoon() {
shell = getShell();
shell.setText( APP_TITLE );
mainComposite.setRedraw( true );
mainComposite.setVisible( false );
mainComposite.setVisible( true );
mainComposite.redraw();
// Perhaps the transformation contains elements at startup?
refreshTree(); // Do a complete refresh then...
setShellText();
}
public boolean readAndDispatch() {
return display.readAndDispatch();
}
/**
* @return check whether or not the application was stopped.
*/
public boolean isStopped() {
return stopped;
}
/**
* @param stopped
* True to stop this application.
*/
public void setStopped( boolean stopped ) {
this.stopped = stopped;
}
/**
* @param destroy
* Whether or not to destroy the display.
*/
public void setDestroy( boolean destroy ) {
this.destroy = destroy;
}
/**
* @return Returns whether or not we should destroy the display.
*/
public boolean doDestroy() {
return destroy;
}
/**
* @param arguments
* The arguments to set.
*/
public void setArguments( String[] arguments ) {
this.arguments = arguments;
}
/**
* @return Returns the arguments.
*/
public String[] getArguments() {
return arguments;
}
public synchronized void dispose() {
setStopped( true );
cursor_hand.dispose();
cursor_hourglass.dispose();
if ( destroy && ( display != null ) && !display.isDisposed() ) {
try {
display.dispose();
} catch ( SWTException e ) {
// dispose errors
}
}
}
public boolean isDisposed() {
return display.isDisposed();
}
public void sleep() {
display.sleep();
}
public void undoAction() {
undoAction( getActiveUndoInterface() );
}
public void redoAction() {
redoAction( getActiveUndoInterface() );
}
/**
* It's called copySteps, but the job entries also arrive at this location
*/
public void copySteps() {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
copySelected( transMeta, transMeta.getSelectedSteps(), transMeta.getSelectedNotes() );
}
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
copyJobentries();
}
}
public void copyJobentries() {
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
if ( RepositorySecurityUI.verifyOperations( shell, rep,
RepositoryOperation.MODIFY_JOB, RepositoryOperation.EXECUTE_JOB ) ) {
return;
}
delegates.jobs.copyJobEntries( jobMeta, jobMeta.getSelectedEntries() );
}
}
public void copy() {
TransMeta transMeta = getActiveTransformation();
JobMeta jobMeta = getActiveJob();
boolean transActive = transMeta != null;
boolean jobActive = jobMeta != null;
if ( transActive ) {
if ( transMeta.getSelectedSteps().size() > 0 ) {
copySteps();
} else {
copyTransformation();
}
} else if ( jobActive ) {
if ( jobMeta.getSelectedEntries().size() > 0 ) {
copyJobentries();
} else {
copyJob();
}
}
}
public void copyFile() {
TransMeta transMeta = getActiveTransformation();
JobMeta jobMeta = getActiveJob();
boolean transActive = transMeta != null;
boolean jobActive = jobMeta != null;
if ( transActive ) {
copyTransformation();
} else if ( jobActive ) {
copyJob();
}
}
public void cut() {
TransMeta transMeta = getActiveTransformation();
JobMeta jobMeta = getActiveJob();
boolean transActive = transMeta != null;
boolean jobActive = jobMeta != null;
if ( transActive ) {
List<StepMeta> stepMetas = transMeta.getSelectedSteps();
if ( stepMetas != null && stepMetas.size() > 0 ) {
copySteps();
delSteps( transMeta, stepMetas.toArray( new StepMeta[stepMetas.size()] ) );
}
} else if ( jobActive ) {
List<JobEntryCopy> jobEntryCopies = jobMeta.getSelectedEntries();
if ( jobEntryCopies != null && jobEntryCopies.size() > 0 ) {
copyJobentries();
deleteJobEntryCopies( jobMeta, jobEntryCopies.toArray( new JobEntryCopy[jobEntryCopies.size()] ) );
}
}
}
public void removeMenuItem( String itemid, boolean removeTrailingSeparators ) {
XulMenuitem item = (XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById( itemid );
if ( item != null ) {
XulComponent menu = item.getParent();
item.getParent().removeChild( item );
if ( removeTrailingSeparators ) {
List<XulComponent> children = menu.getChildNodes();
if ( children.size() > 0 ) {
XulComponent lastMenuItem = children.get( children.size() - 1 );
if ( lastMenuItem instanceof XulMenuseparator ) {
menu.removeChild( lastMenuItem );
// above call should work, but doesn't for some reason, removing separator by force
// the menu separators seem to not be modeled as individual objects in XUL
try {
Menu swtm = (Menu) menu.getManagedObject();
swtm.getItems()[swtm.getItemCount() - 1].dispose();
} catch ( Throwable t ) {
LogChannel.GENERAL.logError( "Error removing XUL menu item", t );
}
}
}
}
} else {
log.logError( "Could not find menu item with id " + itemid + " to remove from Spoon menu" );
}
}
public void createPopupMenus() {
try {
menuMap.put( "trans-class", mainSpoonContainer.getDocumentRoot().getElementById( "trans-class" ) );
menuMap.put( "trans-class-new", mainSpoonContainer.getDocumentRoot().getElementById( "trans-class-new" ) );
menuMap.put( "job-class", mainSpoonContainer.getDocumentRoot().getElementById( "job-class" ) );
menuMap.put( "trans-hop-class", mainSpoonContainer.getDocumentRoot().getElementById( "trans-hop-class" ) );
menuMap.put( "database-class", mainSpoonContainer.getDocumentRoot().getElementById( "database-class" ) );
menuMap.put( "partition-schema-class", mainSpoonContainer.getDocumentRoot().getElementById(
"partition-schema-class" ) );
menuMap.put( "cluster-schema-class", mainSpoonContainer.getDocumentRoot().getElementById(
"cluster-schema-class" ) );
menuMap.put( "slave-cluster-class", mainSpoonContainer.getDocumentRoot().getElementById(
"slave-cluster-class" ) );
menuMap.put( "trans-inst", mainSpoonContainer.getDocumentRoot().getElementById( "trans-inst" ) );
menuMap.put( "job-inst", mainSpoonContainer.getDocumentRoot().getElementById( "job-inst" ) );
menuMap.put( "step-plugin", mainSpoonContainer.getDocumentRoot().getElementById( "step-plugin" ) );
menuMap.put( "database-inst", mainSpoonContainer.getDocumentRoot().getElementById( "database-inst" ) );
menuMap.put( "named-conf-inst", mainSpoonContainer.getDocumentRoot().getElementById( "named-conf-inst" ) );
menuMap.put( "step-inst", mainSpoonContainer.getDocumentRoot().getElementById( "step-inst" ) );
menuMap.put( "job-entry-copy-inst", mainSpoonContainer.getDocumentRoot().getElementById(
"job-entry-copy-inst" ) );
menuMap.put( "trans-hop-inst", mainSpoonContainer.getDocumentRoot().getElementById( "trans-hop-inst" ) );
menuMap.put( "partition-schema-inst", mainSpoonContainer.getDocumentRoot().getElementById(
"partition-schema-inst" ) );
menuMap.put( "cluster-schema-inst", mainSpoonContainer.getDocumentRoot().getElementById(
"cluster-schema-inst" ) );
menuMap
.put( "slave-server-inst", mainSpoonContainer.getDocumentRoot().getElementById( "slave-server-inst" ) );
} catch ( Throwable t ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Exception.ErrorReadingXULFile.Title" ), BaseMessages
.getString( PKG, "Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_MAIN ), new Exception( t ) );
}
addMenuLast();
}
public void executeTransformation() {
executeTransformation(
getActiveTransformation(), true, false, false, false, false, transExecutionConfiguration.getReplayDate(),
false, transExecutionConfiguration.getLogLevel() );
}
public void previewTransformation() {
executeTransformation(
getActiveTransformation(), true, false, false, true, false, transDebugExecutionConfiguration
.getReplayDate(), true, transDebugExecutionConfiguration.getLogLevel() );
}
public void debugTransformation() {
executeTransformation(
getActiveTransformation(), true, false, false, false, true, transPreviewExecutionConfiguration
.getReplayDate(), true, transPreviewExecutionConfiguration.getLogLevel() );
}
public void checkTrans() {
checkTrans( getActiveTransformation() );
}
public void analyseImpact() {
analyseImpact( getActiveTransformation() );
}
public void showLastImpactAnalyses() {
showLastImpactAnalyses( getActiveTransformation() );
}
public void showLastTransPreview() {
TransGraph transGraph = getActiveTransGraph();
if ( transGraph != null ) {
transGraph.showLastPreviewResults();
}
}
public void showExecutionResults() {
TransGraph transGraph = getActiveTransGraph();
if ( transGraph != null ) {
transGraph.showExecutionResults();
enableMenus();
} else {
JobGraph jobGraph = getActiveJobGraph();
if ( jobGraph != null ) {
jobGraph.showExecutionResults();
enableMenus();
}
}
}
public boolean isExecutionResultsPaneVisible() {
TransGraph transGraph = getActiveTransGraph();
return ( transGraph != null ) && ( transGraph.isExecutionResultsPaneVisible() );
}
public void copyTransformation() {
copyTransformation( getActiveTransformation() );
}
public void copyTransformationImage() {
copyTransformationImage( getActiveTransformation() );
}
public boolean editTransformationProperties() {
return TransGraph.editProperties( getActiveTransformation(), this, rep, true );
}
public boolean editProperties() {
if ( getActiveTransformation() != null ) {
return editTransformationProperties();
} else if ( getActiveJob() != null ) {
return editJobProperties( "job-settings" );
}
// no properties were edited, so no cancel was clicked
return true;
}
public void executeJob() {
executeJob( getActiveJob(), true, false, null, false, null, 0 );
}
public void copyJob() {
copyJob( getActiveJob() );
}
public void showWelcomePage() {
try {
LocationListener listener = new LocationListener() {
public void changing( LocationEvent event ) {
if ( event.location.endsWith( ".pdf" ) ) {
Program.launch( event.location );
event.doit = false;
} else if ( event.location.contains( "samples/transformations" )
|| event.location.contains( "samples/jobs" ) || event.location.contains( "samples/mapping" ) ) {
try {
FileObject fileObject = KettleVFS.getFileObject( event.location );
if ( fileObject.exists() ) {
if ( event.location.endsWith( ".ktr" ) || event.location.endsWith( ".kjb" ) ) {
openFile( event.location, false );
} else {
lastDirOpened = KettleVFS.getFilename( fileObject );
openFile( true );
}
event.doit = false;
}
} catch ( Exception e ) {
log.logError( "Error handling samples location: " + event.location, e );
}
}
}
public void changed( LocationEvent event ) {
// System.out.println("Changed to: " + event.location);
}
};
// see if we are in webstart mode
String webstartRoot = System.getProperty( "spoon.webstartroot" );
if ( webstartRoot != null ) {
URL url = new URL( webstartRoot + '/' + FILE_WELCOME_PAGE );
addSpoonBrowser( STRING_WELCOME_TAB_NAME, url.toString(), listener ); // ./docs/English/tips/index.htm
} else {
// see if we can find the welcome file on the file system
File file = new File( FILE_WELCOME_PAGE );
if ( file.exists() ) {
// ./docs/English/tips/index.htm
addSpoonBrowser( STRING_WELCOME_TAB_NAME, file.toURI().toURL().toString(), listener );
}
}
} catch ( MalformedURLException e1 ) {
log.logError( Const.getStackTracker( e1 ) );
}
}
public void showDocumentMap() {
try {
LocationListener listener = new LocationListener() {
public void changing( LocationEvent event ) {
if ( event.location.endsWith( ".pdf" ) ) {
Program.launch( event.location );
event.doit = false;
}
}
public void changed( LocationEvent event ) {
System.out.println( "Changed to: " + event.location );
}
};
// see if we are in webstart mode
String webstartRoot = System.getProperty( "spoon.webstartroot" );
if ( webstartRoot != null ) {
URL url = new URL( webstartRoot + '/' + FILE_DOCUMENT_MAP );
addSpoonBrowser( STRING_DOCUMENT_TAB_NAME, url.toString(), listener ); // ./docs/English/tips/index.htm
} else {
// see if we can find the welcome file on the file system
File file = new File( FILE_DOCUMENT_MAP );
if ( file.exists() ) {
// ./docs/English/tips/index.htm
addSpoonBrowser( STRING_DOCUMENT_TAB_NAME, file.toURI().toURL().toString(), listener );
}
}
} catch ( MalformedURLException e1 ) {
log.logError( Const.getStackTracker( e1 ) );
}
}
public void addMenuLast() {
org.pentaho.ui.xul.dom.Document doc = mainSpoonContainer.getDocumentRoot();
JfaceMenupopup recentFilesPopup = (JfaceMenupopup) doc.getElementById( "file-open-recent-popup" );
recentFilesPopup.removeChildren();
// Previously loaded files...
List<LastUsedFile> lastUsedFiles = props.getLastUsedFiles();
for ( int i = 0; i < lastUsedFiles.size(); i++ ) {
final LastUsedFile lastUsedFile = lastUsedFiles.get( i );
char chr = (char) ( '1' + i );
String accessKey = "ctrl-" + chr;
String accessText = "CTRL-" + chr;
String text = lastUsedFile.toString();
String id = "last-file-" + i;
if ( i > 8 ) {
accessKey = null;
accessText = null;
}
final String lastFileId = Integer.toString( i );
Action action = new Action( "open-last-file-" + ( i + 1 ), Action.AS_DROP_DOWN_MENU ) {
public void run() {
lastFileSelect( lastFileId );
}
};
// shorten the filename if necessary
int targetLength = 40;
if ( text.length() > targetLength ) {
int lastSep = text.replace( '\\', '/' ).lastIndexOf( '/' );
if ( lastSep != -1 ) {
String fileName = "..." + text.substring( lastSep );
if ( fileName.length() < targetLength ) {
// add the start of the file path
int leadSize = targetLength - fileName.length();
text = text.substring( 0, leadSize ) + fileName;
} else {
text = fileName;
}
}
}
JfaceMenuitem miFileLast = new JfaceMenuitem( null, recentFilesPopup, mainSpoonContainer, text, 0, action );
miFileLast.setLabel( text );
miFileLast.setId( id );
if ( accessText != null && accessKey != null ) {
miFileLast.setAcceltext( accessText );
miFileLast.setAccesskey( accessKey );
}
if ( lastUsedFile.isTransformation() ) {
miFileLast.setImage( GUIResource.getInstance().getImageTransGraph() );
} else if ( lastUsedFile.isJob() ) {
miFileLast.setImage( GUIResource.getInstance().getImageJobGraph() );
}
miFileLast.setCommand( "spoon.lastFileSelect('" + i + "')" );
}
}
public void lastFileSelect( String id ) {
int idx = Integer.parseInt( id );
List<LastUsedFile> lastUsedFiles = props.getLastUsedFiles();
final LastUsedFile lastUsedFile = lastUsedFiles.get( idx );
// If the file comes from a repository and it's not the same as
// the one we're connected to, ask for a username/password!
//
if ( lastUsedFile.isSourceRepository()
&& ( rep == null || !rep.getName().equalsIgnoreCase( lastUsedFile.getRepositoryName() ) ) ) {
// Ask for a username password to get the required repository access
//
loginDialog = new RepositoriesDialog( shell, lastUsedFile.getRepositoryName(), new ILoginCallback() {
public void onSuccess( Repository repository ) {
// Close the previous connection...
if ( rep != null ) {
rep.disconnect();
SpoonPluginManager
.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.REPOSITORY_DISCONNECTED );
}
setRepository( repository );
try {
loadLastUsedFile( lastUsedFile, rep == null ? null : rep.getName() );
addMenuLast();
} catch ( KettleException ke ) {
// "Error loading transformation", "I was unable to load this
// transformation from the
// XML file because of an error"
new ErrorDialog( loginDialog.getShell(),
BaseMessages.getString( PKG, "Spoon.Dialog.LoadTransformationError.Title" ),
BaseMessages.getString( PKG, "Spoon.Dialog.LoadTransformationError.Message" ), ke );
}
}
public void onError( Throwable t ) {
onLoginError( t );
}
public void onCancel() {
}
} );
loginDialog.show();
} else if ( !lastUsedFile.isSourceRepository() ) {
// This file must have been on the file system.
openFile( lastUsedFile.getFilename(), false );
} else {
// read from a repository...
//
try {
loadLastUsedFile( lastUsedFile, rep == null ? null : rep.getName() );
addMenuLast();
} catch ( KettleException ke ) {
// "Error loading transformation", "I was unable to load this
// transformation from the
// XML file because of an error"
new ErrorDialog( loginDialog.getShell(),
BaseMessages.getString( PKG, "Spoon.Dialog.LoadTransformationError.Title" ),
BaseMessages.getString( PKG, "Spoon.Dialog.LoadTransformationError.Message" ), ke );
}
}
}
private void addTree() {
mainComposite = new Composite( sashform, SWT.BORDER );
mainComposite.setLayout( new FormLayout() );
props.setLook( mainComposite, Props.WIDGET_STYLE_TOOLBAR );
CTabFolder tabFolder = new CTabFolder( mainComposite, SWT.HORIZONTAL );
props.setLook( tabFolder, Props.WIDGET_STYLE_TAB );
FormData fdTab = new FormData();
fdTab.left = new FormAttachment( 0, 0 );
fdTab.top = new FormAttachment( mainComposite, 0 );
fdTab.right = new FormAttachment( 100, 0 );
fdTab.height = 0;
tabFolder.setLayoutData( fdTab );
view = new CTabItem( tabFolder, SWT.NONE );
view.setControl( new Composite( tabFolder, SWT.NONE ) );
view.setText( STRING_SPOON_MAIN_TREE );
view.setImage( GUIResource.getInstance().getImageExploreSolutionSmall() );
design = new CTabItem( tabFolder, SWT.NONE );
design.setText( STRING_SPOON_CORE_OBJECTS_TREE );
design.setControl( new Composite( tabFolder, SWT.NONE ) );
design.setImage( GUIResource.getInstance().getImageEditSmall() );
Label sep3 = new Label( mainComposite, SWT.SEPARATOR | SWT.HORIZONTAL );
sep3.setBackground( GUIResource.getInstance().getColorWhite() );
FormData fdSep3 = new FormData();
fdSep3.left = new FormAttachment( 0, 0 );
fdSep3.right = new FormAttachment( 100, 0 );
fdSep3.top = new FormAttachment( tabFolder, 0 );
sep3.setLayoutData( fdSep3 );
selectionLabel = new Label( mainComposite, SWT.HORIZONTAL );
FormData fdsLabel = new FormData();
fdsLabel.left = new FormAttachment( 3, 0 );
if ( Const.isLinux() ) {
fdsLabel.top = new FormAttachment( sep3, 10 );
} else {
fdsLabel.top = new FormAttachment( sep3, 8 );
}
selectionLabel.setLayoutData( fdsLabel );
ToolBar treeTb = new ToolBar( mainComposite, SWT.HORIZONTAL | SWT.FLAT );
props.setLook( treeTb, Props.WIDGET_STYLE_TOOLBAR );
/*
This contains a map with all the unnamed transformation (just a filename)
*/
ToolItem expandAll = new ToolItem( treeTb, SWT.PUSH );
expandAll.setImage( GUIResource.getInstance().getImageExpandAll() );
ToolItem collapseAll = new ToolItem( treeTb, SWT.PUSH );
collapseAll.setImage( GUIResource.getInstance().getImageCollapseAll() );
FormData fdTreeToolbar = new FormData();
if ( Const.isLinux() ) {
fdTreeToolbar.top = new FormAttachment( sep3, 3 );
} else {
fdTreeToolbar.top = new FormAttachment( sep3, 5 );
}
fdTreeToolbar.right = new FormAttachment( 95, 5 );
treeTb.setLayoutData( fdTreeToolbar );
selectionFilter =
new Text( mainComposite, SWT.SINGLE
| SWT.BORDER | SWT.LEFT | SWT.SEARCH | SWT.ICON_SEARCH | SWT.ICON_CANCEL );
selectionFilter.setToolTipText( BaseMessages.getString( PKG, "Spoon.SelectionFilter.Tooltip" ) );
FormData fdSelectionFilter = new FormData();
int offset = -( GUIResource.getInstance().getImageExpandAll().getBounds().height + 5 );
if ( Const.isLinux() ) {
if ( !Const.isKDE() ) {
offset = -( GUIResource.getInstance().getImageExpandAll().getBounds().height + 12 );
}
}
fdSelectionFilter.top = new FormAttachment( treeTb, offset );
fdSelectionFilter.right = new FormAttachment( 95, -55 );
fdSelectionFilter.left = new FormAttachment( selectionLabel, 10 );
selectionFilter.setLayoutData( fdSelectionFilter );
selectionFilter.addModifyListener( new ModifyListener() {
public void modifyText( ModifyEvent arg0 ) {
if ( coreObjectsTree != null && !coreObjectsTree.isDisposed() ) {
previousShowTrans = false;
previousShowJob = false;
refreshCoreObjects();
if ( !Const.isEmpty( selectionFilter.getText() ) ) {
tidyBranches( coreObjectsTree.getItems(), true ); // expand all
} else { // no filter: collapse all
tidyBranches( coreObjectsTree.getItems(), false );
}
}
if ( selectionTree != null && !selectionTree.isDisposed() ) {
refreshTree();
if ( !Const.isEmpty( selectionFilter.getText() ) ) {
tidyBranches( selectionTree.getItems(), true ); // expand all
} else { // no filter: collapse all
tidyBranches( selectionTree.getItems(), false );
}
selectionFilter.setFocus();
}
}
} );
expandAll.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent event ) {
if ( designSelected ) {
tidyBranches( coreObjectsTree.getItems(), true );
}
if ( viewSelected ) {
tidyBranches( selectionTree.getItems(), true );
}
}
} );
collapseAll.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent event ) {
if ( designSelected ) {
tidyBranches( coreObjectsTree.getItems(), false );
}
if ( viewSelected ) {
tidyBranches( selectionTree.getItems(), false );
}
}
} );
tabFolder.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent arg0 ) {
if ( arg0.item == view ) {
setViewMode();
} else {
setDesignMode();
}
}
} );
Label sep4 = new Label( mainComposite, SWT.SEPARATOR | SWT.HORIZONTAL );
sep4.setBackground( GUIResource.getInstance().getColorWhite() );
FormData fdSep4 = new FormData();
fdSep4.left = new FormAttachment( 0, 0 );
fdSep4.right = new FormAttachment( 100, 0 );
fdSep4.top = new FormAttachment( treeTb, 5 );
sep4.setLayoutData( fdSep4 );
variableComposite = new Composite( mainComposite, SWT.NONE );
variableComposite.setLayout( new FillLayout() );
FormData fdVariableComposite = new FormData();
fdVariableComposite.left = new FormAttachment( 0, 0 );
fdVariableComposite.right = new FormAttachment( 100, 0 );
fdVariableComposite.top = new FormAttachment( sep4, 0 );
fdVariableComposite.bottom = new FormAttachment( 100, 0 );
variableComposite.setLayoutData( fdVariableComposite );
disposeVariableComposite( true, false, false, false );
coreStepToolTipMap = new Hashtable<String, String>();
coreJobToolTipMap = new Hashtable<String, String>();
addDefaultKeyListeners( tabFolder );
addDefaultKeyListeners( mainComposite );
}
public void addDefaultKeyListeners( Control control ) {
control.addKeyListener( new KeyAdapter() {
@Override
public void keyPressed( KeyEvent e ) {
// CTRL-W or CTRL-F4 : close tab
//
if ( ( e.keyCode == 'w' && ( e.stateMask & SWT.CONTROL ) != 0 )
|| ( e.keyCode == SWT.F4 && ( e.stateMask & SWT.CONTROL ) != 0 ) ) {
closeFile();
}
// CTRL-F5 : metastore explorer
//
if ( e.keyCode == SWT.F5 && ( e.stateMask & SWT.CONTROL ) != 0 ) {
new MetaStoreExplorerDialog( shell, metaStore ).open();
}
}
} );
}
public boolean setViewMode() {
if ( viewSelected ) {
return true;
}
selectionFilter.setText( "" ); // reset filter when switched to view
disposeVariableComposite( true, false, false, false );
refreshTree();
return false;
}
public boolean setDesignMode() {
if ( designSelected ) {
return true;
}
selectionFilter.setText( "" ); // reset filter when switched to design
disposeVariableComposite( false, false, true, false );
refreshCoreObjects();
return false;
}
private void tidyBranches( TreeItem[] items, boolean expand ) {
for ( TreeItem item : items ) {
item.setExpanded( expand );
tidyBranches( item.getItems(), expand );
}
}
public void disposeVariableComposite( boolean tree, boolean shared, boolean core, boolean history ) {
viewSelected = tree;
view.getParent().setSelection( viewSelected ? view : design );
designSelected = core;
// historySelected = history;
// sharedSelected = shared;
for ( Control control : variableComposite.getChildren() ) {
// PDI-1247 - these menus are coded for reuse, so make sure
// they don't get disposed of here (alert: dirty design)
if ( control instanceof Tree ) {
( control ).setMenu( null );
}
control.dispose();
}
previousShowTrans = false;
previousShowJob = false;
// stepHistoryChanged=true;
selectionLabel.setText( tree ? BaseMessages.getString( PKG, "Spoon.Explorer" ) : BaseMessages.getString(
PKG, "Spoon.Steps" ) );
}
public void addCoreObjectsTree() {
// Now create a new expand bar inside that item
// We're going to put the core object in there
//
coreObjectsTree = new Tree( variableComposite, SWT.V_SCROLL | SWT.SINGLE );
props.setLook( coreObjectsTree );
coreObjectsTree.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent event ) {
// expand the selected tree item, collapse the rest
//
if ( props.getAutoCollapseCoreObjectsTree() ) {
TreeItem[] selection = coreObjectsTree.getSelection();
if ( selection.length == 1 ) {
// expand if clicked on the the top level entry only...
//
TreeItem top = selection[0];
while ( top.getParentItem() != null ) {
top = top.getParentItem();
}
if ( top == selection[0] ) {
boolean expanded = top.getExpanded();
for ( TreeItem item : coreObjectsTree.getItems() ) {
item.setExpanded( false );
}
top.setExpanded( !expanded );
}
}
}
}
} );
coreObjectsTree.addTreeListener( new TreeAdapter() {
public void treeExpanded( TreeEvent treeEvent ) {
if ( props.getAutoCollapseCoreObjectsTree() ) {
TreeItem treeItem = (TreeItem) treeEvent.item;
/*
* Trick for WSWT on Windows systems: a SelectionEvent is called after the TreeEvent if setSelection() is not
* used here. Otherwise the first item in the list is selected as default and collapsed again but wrong, see
* PDI-1480
*/
coreObjectsTree.setSelection( treeItem );
// expand the selected tree item, collapse the rest
//
for ( TreeItem item : coreObjectsTree.getItems() ) {
if ( item != treeItem ) {
item.setExpanded( false );
} else {
treeItem.setExpanded( true );
}
}
}
}
} );
coreObjectsTree.addMouseMoveListener( new MouseMoveListener() {
public void mouseMove( MouseEvent move ) {
// don't show tooltips in the tree if the option is not set
if ( !getProperties().showToolTips() ) {
return;
}
toolTip.hide();
TreeItem item = searchMouseOverTreeItem( coreObjectsTree.getItems(), move.x, move.y );
if ( item != null ) {
String name = item.getText();
String tip = coreStepToolTipMap.get( name );
if ( tip != null ) {
PluginInterface plugin = PluginRegistry.getInstance().findPluginWithName( StepPluginType.class, name );
if ( plugin != null ) {
Image image =
GUIResource.getInstance().getImagesSteps().get( plugin.getIds()[0] ).getAsBitmapForSize( display,
ConstUI.ICON_SIZE, ConstUI.ICON_SIZE );
if ( image == null ) {
toolTip.hide();
}
toolTip.setImage( image );
toolTip.setText( name + Const.CR + Const.CR + tip );
toolTip.setBackgroundColor( GUIResource.getInstance().getColor( 255, 254, 225 ) );
toolTip.setForegroundColor( GUIResource.getInstance().getColor( 0, 0, 0 ) );
toolTip.show( new org.eclipse.swt.graphics.Point( move.x + 10, move.y + 10 ) );
}
}
tip = coreJobToolTipMap.get( name );
if ( tip != null ) {
PluginInterface plugin =
PluginRegistry.getInstance().findPluginWithName( JobEntryPluginType.class, name );
if ( plugin != null ) {
Image image =
GUIResource.getInstance().getImagesJobentries().get( plugin.getIds()[0] ).getAsBitmapForSize(
display, ConstUI.ICON_SIZE, ConstUI.ICON_SIZE );
toolTip.setImage( image );
toolTip.setText( name + Const.CR + Const.CR + tip );
toolTip.setBackgroundColor( GUIResource.getInstance().getColor( 255, 254, 225 ) );
toolTip.setForegroundColor( GUIResource.getInstance().getColor( 0, 0, 0 ) );
toolTip.show( new org.eclipse.swt.graphics.Point( move.x + 10, move.y + 10 ) );
}
}
}
}
} );
addDragSourceToTree( coreObjectsTree );
addDefaultKeyListeners( coreObjectsTree );
coreObjectsTree.addMouseListener( new MouseAdapter() {
@Override
public void mouseDoubleClick( MouseEvent event ) {
boolean shift = ( event.stateMask & SWT.SHIFT ) != 0;
doubleClickedInTree( coreObjectsTree, shift );
}
} );
toolTip = new DefaultToolTip( variableComposite, ToolTip.RECREATE, true );
toolTip.setRespectMonitorBounds( true );
toolTip.setRespectDisplayBounds( true );
toolTip.setPopupDelay( 350 );
toolTip.setHideDelay( 5000 );
toolTip.setShift( new org.eclipse.swt.graphics.Point( ConstUI.TOOLTIP_OFFSET, ConstUI.TOOLTIP_OFFSET ) );
}
protected TreeItem searchMouseOverTreeItem( TreeItem[] treeItems, int x, int y ) {
for ( TreeItem treeItem : treeItems ) {
if ( treeItem.getBounds().contains( x, y ) ) {
return treeItem;
}
if ( treeItem.getItemCount() > 0 ) {
treeItem = searchMouseOverTreeItem( treeItem.getItems(), x, y );
if ( treeItem != null ) {
return treeItem;
}
}
}
return null;
}
private boolean previousShowTrans;
private boolean previousShowJob;
public boolean showTrans;
public boolean showJob;
public void refreshCoreObjects() {
if ( shell.isDisposed() ) {
return;
}
if ( !designSelected ) {
return;
}
if ( coreObjectsTree == null || coreObjectsTree.isDisposed() ) {
addCoreObjectsTree();
}
showTrans = getActiveTransformation() != null;
showJob = getActiveJob() != null;
if ( showTrans == previousShowTrans && showJob == previousShowJob ) {
return;
}
// First remove all the entries that where present...
//
TreeItem[] expandItems = coreObjectsTree.getItems();
for ( TreeItem item : expandItems ) {
item.dispose();
}
if ( showTrans ) {
selectionLabel.setText( BaseMessages.getString( PKG, "Spoon.Steps" ) );
// Fill the base components...
//
// ////////////////////////////////////////////////////////////////////////////////////////////////
// TRANSFORMATIONS
// ////////////////////////////////////////////////////////////////////////////////////////////////
PluginRegistry registry = PluginRegistry.getInstance();
final List<PluginInterface> baseSteps = registry.getPlugins( StepPluginType.class );
final List<String> baseCategories = registry.getCategories( StepPluginType.class );
for ( String baseCategory : baseCategories ) {
TreeItem item = new TreeItem( coreObjectsTree, SWT.NONE );
item.setText( baseCategory );
item.setImage( GUIResource.getInstance().getImageFolder() );
List<PluginInterface> sortedCat = new ArrayList<PluginInterface>();
for ( PluginInterface baseStep : baseSteps ) {
if ( baseStep.getCategory().equalsIgnoreCase( baseCategory ) ) {
sortedCat.add( baseStep );
}
}
Collections.sort( sortedCat, new Comparator<PluginInterface>() {
public int compare( PluginInterface p1, PluginInterface p2 ) {
return p1.getName().compareTo( p2.getName() );
}
} );
for ( PluginInterface p : sortedCat ) {
final Image stepImage =
GUIResource.getInstance().getImagesStepsSmall().get( p.getIds()[ 0 ] );
String pluginName = p.getName();
String pluginDescription = p.getDescription();
if ( !filterMatch( pluginName ) && !filterMatch( pluginDescription ) ) {
continue;
}
createTreeItem( item, pluginName, stepImage );
coreStepToolTipMap.put( pluginName, pluginDescription );
}
}
// Add History Items...
TreeItem item = new TreeItem( coreObjectsTree, SWT.NONE );
item.setText( BaseMessages.getString( PKG, "Spoon.History" ) );
item.setImage( GUIResource.getInstance().getImageFolder() );
List<ObjectUsageCount> pluginHistory = props.getPluginHistory();
// The top 10 at most, the rest is not interesting anyway
//
for ( int i = 0; i < pluginHistory.size() && i < 10; i++ ) {
ObjectUsageCount usage = pluginHistory.get( i );
PluginInterface stepPlugin =
PluginRegistry.getInstance().findPluginWithId( StepPluginType.class, usage.getObjectName() );
if ( stepPlugin != null ) {
final Image stepImage =
GUIResource.getInstance().getImagesSteps().get( stepPlugin.getIds()[0] ).getAsBitmapForSize( display, ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE );
String pluginName = Const.NVL( stepPlugin.getName(), "" );
String pluginDescription = Const.NVL( stepPlugin.getDescription(), "" );
if ( !filterMatch( pluginName ) && !filterMatch( pluginDescription ) ) {
continue;
}
TreeItem stepItem = createTreeItem( item, pluginName, stepImage );
stepItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event event ) {
System.out.println( "Tree item Listener fired" );
}
} );
coreStepToolTipMap.put( stepPlugin.getDescription(), pluginDescription + " (" + usage.getNrUses() + ")" );
}
}
}
if ( showJob ) {
// Fill the base components...
//
// ////////////////////////////////////////////////////////////////////////////////////////////////
// JOBS
// ////////////////////////////////////////////////////////////////////////////////////////////////
selectionLabel.setText( BaseMessages.getString( PKG, "Spoon.Entries" ) );
PluginRegistry registry = PluginRegistry.getInstance();
List<PluginInterface> baseJobEntries = registry.getPlugins( JobEntryPluginType.class );
List<String> baseCategories = registry.getCategories( JobEntryPluginType.class );
TreeItem generalItem = null;
for ( String baseCategory : baseCategories ) {
TreeItem item = new TreeItem( coreObjectsTree, SWT.NONE );
item.setText( baseCategory );
item.setImage( GUIResource.getInstance().getImageFolder() );
if ( baseCategory.equalsIgnoreCase( JobEntryPluginType.GENERAL_CATEGORY ) ) {
generalItem = item;
}
for ( int j = 0; j < baseJobEntries.size(); j++ ) {
if ( !baseJobEntries.get( j ).getIds()[ 0 ].equals( "SPECIAL" ) ) {
if ( baseJobEntries.get( j ).getCategory().equalsIgnoreCase( baseCategory ) ) {
final Image jobEntryImage =
GUIResource.getInstance().getImagesJobentriesSmall().get( baseJobEntries.get( j ).getIds()[0] );
String pluginName = Const.NVL( baseJobEntries.get( j ).getName(), "" );
String pluginDescription = Const.NVL( baseJobEntries.get( j ).getDescription(), "" );
if ( !filterMatch( pluginName ) && !filterMatch( pluginDescription ) ) {
continue;
}
TreeItem stepItem = createTreeItem( item, pluginName, jobEntryImage );
stepItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event arg0 ) {
System.out.println( "Tree item Listener fired" );
}
} );
// if (isPlugin)
// stepItem.setFont(GUIResource.getInstance().getFontBold());
coreJobToolTipMap.put( pluginName, pluginDescription );
}
}
}
}
// First add a few "Special entries: Start, Dummy, OK, ERROR
// We add these to the top of the base category, we don't care about
// the sort order here.
//
JobEntryCopy startEntry = JobMeta.createStartEntry();
JobEntryCopy dummyEntry = JobMeta.createDummyEntry();
String[] specialText = new String[] { startEntry.getName(), dummyEntry.getName(), };
String[] specialTooltip = new String[] { startEntry.getDescription(), dummyEntry.getDescription(), };
Image[] specialImage =
new Image[] {
GUIResource.getInstance().getImageStartMedium(), GUIResource.getInstance().getImageDummyMedium() };
for ( int i = 0; i < specialText.length; i++ ) {
TreeItem specialItem = new TreeItem( generalItem, SWT.NONE, i );
specialItem.setImage( specialImage[i] );
specialItem.setText( specialText[i] );
specialItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event arg0 ) {
System.out.println( "Tree item Listener fired" );
}
} );
coreJobToolTipMap.put( specialText[i], specialTooltip[i] );
}
}
variableComposite.layout( true, true );
previousShowTrans = showTrans;
previousShowJob = showJob;
}
protected void shareObject( SharedObjectInterface sharedObject ) {
sharedObject.setShared( true );
EngineMetaInterface meta = getActiveMeta();
try {
if ( meta != null ) {
SharedObjects sharedObjects = null;
if ( meta instanceof TransMeta ) {
sharedObjects = ( (TransMeta) meta ).getSharedObjects();
}
if ( meta instanceof JobMeta ) {
sharedObjects = ( (JobMeta) meta ).getSharedObjects();
}
if ( sharedObjects != null ) {
sharedObjects.storeObject( sharedObject );
sharedObjects.saveToFile();
}
}
} catch ( Exception e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorWritingSharedObjects.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorWritingSharedObjects.Message" ), e );
}
refreshTree();
}
protected void unShareObject( SharedObjectInterface sharedObject ) {
MessageBox mb = new MessageBox( shell, SWT.YES | SWT.NO | SWT.ICON_WARNING );
// "Are you sure you want to stop sharing?"
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.StopSharing.Message" ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.StopSharing.Title" ) ); // Warning!
int answer = mb.open();
if ( answer == SWT.YES ) {
sharedObject.setShared( false );
EngineMetaInterface meta = getActiveMeta();
try {
if ( meta != null ) {
SharedObjects sharedObjects = null;
if ( meta instanceof TransMeta ) {
sharedObjects = ( (TransMeta) meta ).getSharedObjects();
}
if ( meta instanceof JobMeta ) {
sharedObjects = ( (JobMeta) meta ).getSharedObjects();
}
if ( sharedObjects != null ) {
sharedObjects.removeObject( sharedObject );
sharedObjects.saveToFile();
}
}
} catch ( Exception e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorWritingSharedObjects.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorWritingSharedObjects.Message" ), e );
}
refreshTree();
}
}
/**
* @return The object that is selected in the tree or null if we couldn't figure it out. (titles etc. == null)
*/
public TreeSelection[] getTreeObjects( final Tree tree ) {
return delegates.tree.getTreeObjects( tree, selectionTree, coreObjectsTree );
}
private void addDragSourceToTree( final Tree tree ) {
delegates.tree.addDragSourceToTree( tree, selectionTree, coreObjectsTree );
}
public void hideToolTips() {
if ( toolTip != null ) {
toolTip.hide();
}
}
/**
* If you click in the tree, you might want to show the corresponding window.
*/
public void showSelection() {
TreeSelection[] objects = getTreeObjects( selectionTree );
if ( objects.length != 1 ) {
return; // not yet supported, we can do this later when the OSX bug
// goes away
}
TreeSelection object = objects[0];
final Object selection = object.getSelection();
final Object parent = object.getParent();
TransMeta transMeta = null;
if ( selection instanceof TransMeta ) {
transMeta = (TransMeta) selection;
}
if ( parent instanceof TransMeta ) {
transMeta = (TransMeta) parent;
}
if ( transMeta != null ) {
TabMapEntry entry = delegates.tabs.findTabMapEntry( transMeta );
if ( entry != null ) {
int current = tabfolder.getSelectedIndex();
int desired = tabfolder.indexOf( entry.getTabItem() );
if ( current != desired ) {
tabfolder.setSelected( desired );
}
transMeta.setInternalKettleVariables();
if ( getCoreObjectsState() != STATE_CORE_OBJECTS_SPOON ) {
// Switch the core objects in the lower left corner to the
// spoon trans types
refreshCoreObjects();
}
}
}
JobMeta jobMeta = null;
if ( selection instanceof JobMeta ) {
jobMeta = (JobMeta) selection;
}
if ( parent instanceof JobMeta ) {
jobMeta = (JobMeta) parent;
}
if ( jobMeta != null ) {
TabMapEntry entry = delegates.tabs.findTabMapEntry( transMeta );
if ( entry != null ) {
int current = tabfolder.getSelectedIndex();
int desired = tabfolder.indexOf( entry.getTabItem() );
if ( current != desired ) {
tabfolder.setSelected( desired );
}
jobMeta.setInternalKettleVariables();
if ( getCoreObjectsState() != STATE_CORE_OBJECTS_CHEF ) {
// Switch the core objects in the lower left corner to the
// spoon job types
//
refreshCoreObjects();
}
}
}
}
private Object selectionObjectParent = null;
private Object selectionObject = null;
public void newHop() {
newHop( (TransMeta) selectionObjectParent );
}
public void sortHops() {
( (TransMeta) selectionObjectParent ).sortHops();
refreshTree();
}
public void newDatabasePartitioningSchema() {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
newPartitioningSchema( transMeta );
}
}
public void newClusteringSchema() {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
newClusteringSchema( transMeta );
}
}
public void newSlaveServer() {
newSlaveServer( (HasSlaveServersInterface) selectionObjectParent );
}
public void editTransformationPropertiesPopup() {
TransGraph.editProperties( (TransMeta) selectionObject, this, rep, true );
}
public void addTransLog() {
TransGraph activeTransGraph = getActiveTransGraph();
if ( activeTransGraph != null ) {
activeTransGraph.transLogDelegate.addTransLog();
activeTransGraph.transGridDelegate.addTransGrid();
}
}
public void addTransHistory() {
TransGraph activeTransGraph = getActiveTransGraph();
if ( activeTransGraph != null ) {
activeTransGraph.transHistoryDelegate.addTransHistory();
}
}
public boolean editJobProperties( String id ) {
if ( "job-settings".equals( id ) ) {
return JobGraph.editProperties( getActiveJob(), this, rep, true );
} else if ( "job-inst-settings".equals( id ) ) {
return JobGraph.editProperties( (JobMeta) selectionObject, this, rep, true );
}
return false;
}
public void editJobPropertiesPopup() {
JobGraph.editProperties( (JobMeta) selectionObject, this, rep, true );
}
public void addJobLog() {
JobGraph activeJobGraph = getActiveJobGraph();
if ( activeJobGraph != null ) {
activeJobGraph.jobLogDelegate.addJobLog();
activeJobGraph.jobGridDelegate.addJobGrid();
}
}
public void addJobHistory() {
addJobHistory( (JobMeta) selectionObject, true );
}
public void newStep() {
newStep( getActiveTransformation() );
}
public void editConnection() {
if ( RepositorySecurityUI.verifyOperations( shell, rep, RepositoryOperation.MODIFY_DATABASE ) ) {
return;
}
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
delegates.db.editConnection( databaseMeta );
}
public void dupeConnection() {
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
final HasDatabasesInterface hasDatabasesInterface = (HasDatabasesInterface) selectionObjectParent;
delegates.db.dupeConnection( hasDatabasesInterface, databaseMeta );
}
public void clipConnection() {
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
delegates.db.clipConnection( databaseMeta );
}
public void delConnection() {
if ( RepositorySecurityUI.verifyOperations( shell, rep, RepositoryOperation.DELETE_DATABASE ) ) {
return;
}
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
MessageBox mb = new MessageBox( shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION );
mb.setMessage( BaseMessages.getString(
PKG, "Spoon.ExploreDB.DeleteConnectionAsk.Message", databaseMeta.getName() ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.ExploreDB.DeleteConnectionAsk.Title" ) );
int response = mb.open();
if ( response != SWT.YES ) {
return;
}
final HasDatabasesInterface hasDatabasesInterface = (HasDatabasesInterface) selectionObjectParent;
delegates.db.delConnection( hasDatabasesInterface, databaseMeta );
}
public void sqlConnection() {
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
delegates.db.sqlConnection( databaseMeta );
}
public void clearDBCache( String id ) {
if ( "database-class-clear-cache".equals( id ) ) {
delegates.db.clearDBCache( null );
}
if ( "database-inst-clear-cache".equals( id ) ) {
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
delegates.db.clearDBCache( databaseMeta );
}
}
public void exploreDatabase() {
if ( RepositorySecurityUI.verifyOperations( shell, rep, RepositoryOperation.EXPLORE_DATABASE ) ) {
return;
}
// Show a minimal window to allow you to quickly select the database
// connection to explore
//
List<DatabaseMeta> databases = new ArrayList<DatabaseMeta>();
// First load the connections from the loaded file
//
HasDatabasesInterface databasesInterface = getActiveHasDatabasesInterface();
if ( databasesInterface != null ) {
databases.addAll( databasesInterface.getDatabases() );
}
// Overwrite the information with the connections from the repository
//
if ( rep != null ) {
try {
List<DatabaseMeta> list = rep.readDatabases();
for ( DatabaseMeta databaseMeta : list ) {
int index = databases.indexOf( databaseMeta );
if ( index < 0 ) {
databases.add( databaseMeta );
} else {
databases.set( index, databaseMeta );
}
}
} catch ( KettleException e ) {
log.logError( "Unexpected repository error", e.getMessage() );
}
}
if ( databases.size() == 0 ) {
return;
}
// OK, get a list of all the database names...
//
String[] databaseNames = new String[databases.size()];
for ( int i = 0; i < databases.size(); i++ ) {
databaseNames[i] = databases.get( i ).getName();
}
// show the shell...
//
EnterSelectionDialog dialog = new EnterSelectionDialog( shell, databaseNames,
BaseMessages.getString( PKG, "Spoon.ExploreDB.SelectDB.Title" ),
BaseMessages.getString( PKG, "Spoon.ExploreDB.SelectDB.Message" ) );
String name = dialog.open();
if ( name != null ) {
selectionObject = DatabaseMeta.findDatabase( databases, name );
exploreDB();
}
}
public void exploreDB() {
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
delegates.db.exploreDB( databaseMeta, true );
}
public void editStep() {
final TransMeta transMeta = (TransMeta) selectionObjectParent;
final StepMeta stepMeta = (StepMeta) selectionObject;
delegates.steps.editStep( transMeta, stepMeta );
}
public void dupeStep() {
final TransMeta transMeta = (TransMeta) selectionObjectParent;
final StepMeta stepMeta = (StepMeta) selectionObject;
delegates.steps.dupeStep( transMeta, stepMeta );
}
public void delStep() {
final TransMeta transMeta = (TransMeta) selectionObjectParent;
final StepMeta stepMeta = (StepMeta) selectionObject;
delegates.steps.delStep( transMeta, stepMeta );
}
public void helpStep() {
final StepMeta stepMeta = (StepMeta) selectionObject;
PluginInterface stepPlugin =
PluginRegistry.getInstance().findPluginWithId( StepPluginType.class, stepMeta.getStepID() );
HelpUtils.openHelpDialog( shell, stepPlugin );
}
public void shareObject( String id ) {
if ( "database-inst-share".equals( id ) ) {
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
if ( databaseMeta.isShared() ) {
unShareObject( databaseMeta );
} else {
shareObject( databaseMeta );
}
}
if ( "step-inst-share".equals( id ) ) {
final StepMeta stepMeta = (StepMeta) selectionObject;
shareObject( stepMeta );
}
if ( "partition-schema-inst-share".equals( id ) ) {
final PartitionSchema partitionSchema = (PartitionSchema) selectionObject;
shareObject( partitionSchema );
}
if ( "cluster-schema-inst-share".equals( id ) ) {
final ClusterSchema clusterSchema = (ClusterSchema) selectionObject;
shareObject( clusterSchema );
}
if ( "slave-server-inst-share".equals( id ) ) {
final SlaveServer slaveServer = (SlaveServer) selectionObject;
shareObject( slaveServer );
}
}
public void editJobEntry() {
final JobMeta jobMeta = (JobMeta) selectionObjectParent;
final JobEntryCopy jobEntry = (JobEntryCopy) selectionObject;
editJobEntry( jobMeta, jobEntry );
}
public void dupeJobEntry() {
final JobMeta jobMeta = (JobMeta) selectionObjectParent;
final JobEntryCopy jobEntry = (JobEntryCopy) selectionObject;
delegates.jobs.dupeJobEntry( jobMeta, jobEntry );
}
public void deleteJobEntryCopies() {
final JobMeta jobMeta = (JobMeta) selectionObjectParent;
final JobEntryCopy jobEntry = (JobEntryCopy) selectionObject;
deleteJobEntryCopies( jobMeta, jobEntry );
}
public void helpJobEntry() {
final JobEntryCopy jobEntry = (JobEntryCopy) selectionObject;
String jobName = jobEntry.getName();
PluginInterface jobEntryPlugin =
PluginRegistry.getInstance().findPluginWithName( JobEntryPluginType.class, jobName );
HelpUtils.openHelpDialog( shell, jobEntryPlugin );
}
public void editHop() {
final TransMeta transMeta = (TransMeta) selectionObjectParent;
final TransHopMeta transHopMeta = (TransHopMeta) selectionObject;
editHop( transMeta, transHopMeta );
}
public void delHop() {
final TransMeta transMeta = (TransMeta) selectionObjectParent;
final TransHopMeta transHopMeta = (TransHopMeta) selectionObject;
delHop( transMeta, transHopMeta );
}
public void editPartitionSchema() {
final TransMeta transMeta = (TransMeta) selectionObjectParent;
final PartitionSchema partitionSchema = (PartitionSchema) selectionObject;
editPartitionSchema( transMeta, partitionSchema );
}
public void delPartitionSchema() {
final TransMeta transMeta = (TransMeta) selectionObjectParent;
final PartitionSchema partitionSchema = (PartitionSchema) selectionObject;
delPartitionSchema( transMeta, partitionSchema );
}
public void editClusterSchema() {
final TransMeta transMeta = (TransMeta) selectionObjectParent;
final ClusterSchema clusterSchema = (ClusterSchema) selectionObject;
editClusterSchema( transMeta, clusterSchema );
}
public void delClusterSchema() {
final TransMeta transMeta = (TransMeta) selectionObjectParent;
final ClusterSchema clusterSchema = (ClusterSchema) selectionObject;
delClusterSchema( transMeta, clusterSchema );
}
public void monitorClusterSchema() throws KettleException {
final ClusterSchema clusterSchema = (ClusterSchema) selectionObject;
monitorClusterSchema( clusterSchema );
}
public void editSlaveServer() {
final SlaveServer slaveServer = (SlaveServer) selectionObject;
editSlaveServer( slaveServer );
}
public void delSlaveServer() {
final HasSlaveServersInterface hasSlaveServersInterface = (HasSlaveServersInterface) selectionObjectParent;
final SlaveServer slaveServer = (SlaveServer) selectionObject;
delSlaveServer( hasSlaveServersInterface, slaveServer );
}
public void addSpoonSlave() {
final SlaveServer slaveServer = (SlaveServer) selectionObject;
addSpoonSlave( slaveServer );
}
private synchronized void setMenu( Tree tree ) {
TreeSelection[] objects = getTreeObjects( tree );
if ( objects.length != 1 ) {
return; // not yet supported, we can do this later when the OSX bug
// goes away
}
TreeSelection object = objects[0];
selectionObject = object.getSelection();
Object selection = selectionObject;
selectionObjectParent = object.getParent();
// Not clicked on a real object: returns a class
XulMenupopup spoonMenu = null;
if ( selection instanceof Class<?> ) {
if ( selection.equals( TransMeta.class ) ) {
// New
spoonMenu = (XulMenupopup) menuMap.get( "trans-class" );
} else if ( selection.equals( JobMeta.class ) ) {
// New
spoonMenu = (XulMenupopup) menuMap.get( "job-class" );
} else if ( selection.equals( TransHopMeta.class ) ) {
// New
spoonMenu = (XulMenupopup) menuMap.get( "trans-hop-class" );
} else if ( selection.equals( DatabaseMeta.class ) ) {
spoonMenu = (XulMenupopup) menuMap.get( "database-class" );
} else if ( selection.equals( PartitionSchema.class ) ) {
// New
spoonMenu = (XulMenupopup) menuMap.get( "partition-schema-class" );
} else if ( selection.equals( ClusterSchema.class ) ) {
spoonMenu = (XulMenupopup) menuMap.get( "cluster-schema-class" );
} else if ( selection.equals( SlaveServer.class ) ) {
spoonMenu = (XulMenupopup) menuMap.get( "slave-cluster-class" );
} else {
spoonMenu = null;
}
} else {
if ( selection instanceof TransMeta ) {
spoonMenu = (XulMenupopup) menuMap.get( "trans-inst" );
} else if ( selection instanceof JobMeta ) {
spoonMenu = (XulMenupopup) menuMap.get( "job-inst" );
} else if ( selection instanceof PluginInterface ) {
spoonMenu = (XulMenupopup) menuMap.get( "step-plugin" );
} else if ( selection instanceof DatabaseMeta ) {
spoonMenu = (XulMenupopup) menuMap.get( "database-inst" );
// disable for now if the connection is an SAP ERP type of database...
//
XulMenuitem item =
(XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById( "database-inst-explore" );
if ( item != null ) {
final DatabaseMeta databaseMeta = (DatabaseMeta) selection;
item.setDisabled( !databaseMeta.isExplorable() );
}
item = (XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById( "database-inst-clear-cache" );
if ( item != null ) {
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
item.setLabel( BaseMessages.getString( PKG, "Spoon.Menu.Popup.CONNECTIONS.ClearDBCache" )
+ databaseMeta.getName() ); // Clear
}
item = (XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById( "database-inst-share" );
if ( item != null ) {
final DatabaseMeta databaseMeta = (DatabaseMeta) selection;
if ( databaseMeta.isShared() ) {
item.setLabel( BaseMessages.getString( PKG, "Spoon.Menu.Popup.CONNECTIONS.UnShare" ) );
} else {
item.setLabel( BaseMessages.getString( PKG, "Spoon.Menu.Popup.CONNECTIONS.Share" ) );
}
}
} else if ( selection instanceof StepMeta ) {
spoonMenu = (XulMenupopup) menuMap.get( "step-inst" );
} else if ( selection instanceof JobEntryCopy ) {
spoonMenu = (XulMenupopup) menuMap.get( "job-entry-copy-inst" );
} else if ( selection instanceof TransHopMeta ) {
spoonMenu = (XulMenupopup) menuMap.get( "trans-hop-inst" );
} else if ( selection instanceof PartitionSchema ) {
spoonMenu = (XulMenupopup) menuMap.get( "partition-schema-inst" );
} else if ( selection instanceof ClusterSchema ) {
spoonMenu = (XulMenupopup) menuMap.get( "cluster-schema-inst" );
} else if ( selection instanceof SlaveServer ) {
spoonMenu = (XulMenupopup) menuMap.get( "slave-server-inst" );
}
}
if ( spoonMenu != null ) {
ConstUI.displayMenu( spoonMenu, tree );
} else {
tree.setMenu( null );
}
createPopUpMenuExtension();
}
/**
* Reaction to double click
*
*/
private void doubleClickedInTree( Tree tree ) {
doubleClickedInTree( tree, false );
}
/**
* Reaction to double click
*
*/
private void doubleClickedInTree( Tree tree, boolean shift ) {
TreeSelection[] objects = getTreeObjects( tree );
if ( objects.length != 1 ) {
return; // not yet supported, we can do this later when the OSX bug
// goes away
}
TreeSelection object = objects[0];
final Object selection = object.getSelection();
final Object parent = object.getParent();
if ( selection instanceof Class<?> ) {
if ( selection.equals( TransMeta.class ) ) {
newTransFile();
}
if ( selection.equals( JobMeta.class ) ) {
newJobFile();
}
if ( selection.equals( TransHopMeta.class ) ) {
newHop( (TransMeta) parent );
}
if ( selection.equals( DatabaseMeta.class ) ) {
delegates.db.newConnection();
}
if ( selection.equals( PartitionSchema.class ) ) {
newPartitioningSchema( (TransMeta) parent );
}
if ( selection.equals( ClusterSchema.class ) ) {
newClusteringSchema( (TransMeta) parent );
}
if ( selection.equals( SlaveServer.class ) ) {
newSlaveServer( (HasSlaveServersInterface) parent );
}
} else {
if ( selection instanceof TransMeta ) {
TransGraph.editProperties( (TransMeta) selection, this, rep, true );
}
if ( selection instanceof JobMeta ) {
JobGraph.editProperties( (JobMeta) selection, this, rep, true );
}
if ( selection instanceof PluginInterface ) {
PluginInterface plugin = (PluginInterface) selection;
if ( plugin.getPluginType().equals( StepPluginType.class ) ) {
TransGraph transGraph = getActiveTransGraph();
if ( transGraph != null ) {
transGraph.addStepToChain( plugin, shift );
}
}
if ( plugin.getPluginType().equals( JobEntryPluginType.class ) ) {
JobGraph jobGraph = getActiveJobGraph();
if ( jobGraph != null ) {
jobGraph.addJobEntryToChain( object.getItemText(), shift );
}
}
// newStep( getActiveTransformation() );
}
if ( selection instanceof DatabaseMeta ) {
delegates.db.editConnection( (DatabaseMeta) selection );
}
if ( selection instanceof StepMeta ) {
delegates.steps.editStep( (TransMeta) parent, (StepMeta) selection );
}
if ( selection instanceof JobEntryCopy ) {
editJobEntry( (JobMeta) parent, (JobEntryCopy) selection );
}
if ( selection instanceof TransHopMeta ) {
editHop( (TransMeta) parent, (TransHopMeta) selection );
}
if ( selection instanceof PartitionSchema ) {
editPartitionSchema( (TransMeta) parent, (PartitionSchema) selection );
}
if ( selection instanceof ClusterSchema ) {
editClusterSchema( (TransMeta) parent, (ClusterSchema) selection );
}
if ( selection instanceof SlaveServer ) {
editSlaveServer( (SlaveServer) selection );
}
editSelectionTreeExtension( selection );
}
}
protected void monitorClusterSchema( ClusterSchema clusterSchema ) throws KettleException {
for ( int i = 0; i < clusterSchema.getSlaveServers().size(); i++ ) {
SlaveServer slaveServer = clusterSchema.getSlaveServers().get( i );
addSpoonSlave( slaveServer );
}
}
protected void editSlaveServer( SlaveServer slaveServer ) {
// slaveServer.getVariable("MASTER_HOST")
SlaveServerDialog dialog = new SlaveServerDialog( shell, slaveServer );
if ( dialog.open() ) {
refreshTree();
refreshGraph();
}
}
private void addTabs() {
if ( tabComp != null ) {
tabComp.dispose();
}
tabComp = new Composite( sashform, SWT.BORDER );
props.setLook( tabComp );
tabComp.setLayout( new FillLayout() );
tabfolder = new TabSet( tabComp );
tabfolder.setChangedFont( GUIResource.getInstance().getFontBold() );
final CTabFolder cTabFolder = tabfolder.getSwtTabset();
props.setLook( cTabFolder, Props.WIDGET_STYLE_TAB );
cTabFolder.addMenuDetectListener( new MenuDetectListener() {
@Override
public void menuDetected( MenuDetectEvent event ) {
org.eclipse.swt.graphics.Point real = new org.eclipse.swt.graphics.Point( event.x, event.y );
org.eclipse.swt.graphics.Point point = display.map( null, cTabFolder, real );
final CTabItem item = cTabFolder.getItem( point );
if ( item != null ) {
Menu menu = new Menu( cTabFolder );
MenuItem closeItem = new MenuItem( menu, SWT.NONE );
closeItem.setText( BaseMessages.getString( PKG, "Spoon.Tab.Close" ) );
closeItem.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent event ) {
int index = tabfolder.getSwtTabset().indexOf( item );
if ( index >= 0 ) {
TabMapEntry entry = delegates.tabs.getTabs().get( index );
tabClose( entry.getTabItem() );
}
}
} );
MenuItem closeAllItems = new MenuItem( menu, SWT.NONE );
closeAllItems.setText( BaseMessages.getString( PKG, "Spoon.Tab.CloseAll" ) );
closeAllItems.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent event ) {
for ( TabMapEntry entry : delegates.tabs.getTabs() ) {
tabClose( entry.getTabItem() );
}
}
} );
MenuItem closeOtherItems = new MenuItem( menu, SWT.NONE );
closeOtherItems.setText( BaseMessages.getString( PKG, "Spoon.Tab.CloseOthers" ) );
closeOtherItems.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent event ) {
int index = tabfolder.getSwtTabset().indexOf( item );
if ( index >= 0 ) {
TabMapEntry entry = delegates.tabs.getTabs().get( index );
for ( TabMapEntry closeEntry : delegates.tabs.getTabs() ) {
if ( !closeEntry.equals( entry ) ) {
tabClose( closeEntry.getTabItem() );
}
}
}
}
} );
menu.setLocation( real );
menu.setVisible( true );
}
}
} );
int[] weights = props.getSashWeights();
sashform.setWeights( weights );
sashform.setVisible( true );
// Set a minimum width on the sash so that the view and design buttons
// on the left panel are always visible.
//
Control[] comps = sashform.getChildren();
for ( Control comp : comps ) {
if ( comp instanceof Sash ) {
int limit = 10;
final int SASH_LIMIT = Const.isOSX() ? 150 : limit;
final Sash sash = (Sash) comp;
sash.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent event ) {
Rectangle rect = sash.getParent().getClientArea();
event.x = Math.min( Math.max( event.x, SASH_LIMIT ), rect.width - SASH_LIMIT );
if ( event.detail != SWT.DRAG ) {
sash.setBounds( event.x, event.y, event.width, event.height );
sashform.layout();
}
}
} );
}
}
tabfolder.addListener( this ); // methods: tabDeselected, tabClose,
// tabSelected
}
public void tabDeselected( TabItem item ) {
}
public boolean tabCloseSelected() {
// this gets called on by the file-close menu item
String activePerspectiveId = SpoonPerspectiveManager.getInstance().getActivePerspective().getId();
boolean etlPerspective = activePerspectiveId.equals( MainSpoonPerspective.ID );
if ( etlPerspective ) {
return tabClose( tabfolder.getSelected() );
}
// hack to make the plugins see file-close commands
// this should be resolved properly when resolving PDI-6054
// maybe by extending the SpoonPerspectiveInterface to register event handlers from Spoon?
try {
SpoonPerspective activePerspective = SpoonPerspectiveManager.getInstance().getActivePerspective();
Class<? extends SpoonPerspective> cls = activePerspective.getClass();
Method m = cls.getMethod( "onFileClose" );
return (Boolean) m.invoke( activePerspective );
} catch ( Exception e ) {
// ignore any errors resulting from the hack
// e.printStackTrace();
}
return false;
}
public boolean tabClose( TabItem item ) {
try {
return delegates.tabs.tabClose( item );
} catch ( Exception e ) {
new ErrorDialog( shell, "Error", "Unexpected error closing tab!", e );
return false;
}
}
public TabSet getTabSet() {
return tabfolder;
}
public void tabSelected( TabItem item ) {
delegates.tabs.tabSelected( item );
enableMenus();
}
public String getRepositoryName() {
if ( rep == null ) {
return null;
}
return rep.getName();
}
public void pasteXML( TransMeta transMeta, String clipcontent, Point loc ) {
if ( RepositorySecurityUI.verifyOperations( shell, rep,
RepositoryOperation.MODIFY_TRANSFORMATION, RepositoryOperation.EXECUTE_TRANSFORMATION ) ) {
return;
}
try {
Document doc = XMLHandler.loadXMLString( clipcontent );
Node transNode = XMLHandler.getSubNode( doc, Spoon.XML_TAG_TRANSFORMATION_STEPS );
// De-select all, re-select pasted steps...
transMeta.unselectAll();
Node stepsNode = XMLHandler.getSubNode( transNode, "steps" );
int nr = XMLHandler.countNodes( stepsNode, "step" );
if ( getLog().isDebug() ) {
// "I found "+nr+" steps to paste on location: "
getLog().logDebug( BaseMessages.getString( PKG, "Spoon.Log.FoundSteps", "" + nr ) + loc );
}
StepMeta[] steps = new StepMeta[nr];
ArrayList<String> stepOldNames = new ArrayList<String>( nr );
// Point min = new Point(loc.x, loc.y);
Point min = new Point( 99999999, 99999999 );
// Load the steps...
for ( int i = 0; i < nr; i++ ) {
Node stepNode = XMLHandler.getSubNodeByNr( stepsNode, "step", i );
steps[i] = new StepMeta( stepNode, transMeta.getDatabases(), metaStore );
if ( loc != null ) {
Point p = steps[i].getLocation();
if ( min.x > p.x ) {
min.x = p.x;
}
if ( min.y > p.y ) {
min.y = p.y;
}
}
}
// Load the hops...
Node hopsNode = XMLHandler.getSubNode( transNode, "order" );
nr = XMLHandler.countNodes( hopsNode, "hop" );
if ( getLog().isDebug() ) {
// "I found "+nr+" hops to paste."
getLog().logDebug( BaseMessages.getString( PKG, "Spoon.Log.FoundHops", "" + nr ) );
}
TransHopMeta[] hops = new TransHopMeta[nr];
for ( int i = 0; i < nr; i++ ) {
Node hopNode = XMLHandler.getSubNodeByNr( hopsNode, "hop", i );
hops[i] = new TransHopMeta( hopNode, Arrays.asList( steps ) );
}
// This is the offset:
Point offset = new Point( loc.x - min.x, loc.y - min.y );
// Undo/redo object positions...
int[] position = new int[steps.length];
for ( int i = 0; i < steps.length; i++ ) {
Point p = steps[i].getLocation();
String name = steps[i].getName();
steps[i].setLocation( p.x + offset.x, p.y + offset.y );
steps[i].setDraw( true );
// Check the name, find alternative...
stepOldNames.add( name );
steps[i].setName( transMeta.getAlternativeStepname( name ) );
transMeta.addStep( steps[i] );
position[i] = transMeta.indexOfStep( steps[i] );
steps[i].setSelected( true );
}
// Add the hops too...
for ( TransHopMeta hop : hops ) {
transMeta.addTransHop( hop );
}
// Load the notes...
Node notesNode = XMLHandler.getSubNode( transNode, "notepads" );
nr = XMLHandler.countNodes( notesNode, "notepad" );
if ( getLog().isDebug() ) {
// "I found "+nr+" notepads to paste."
getLog().logDebug( BaseMessages.getString( PKG, "Spoon.Log.FoundNotepads", "" + nr ) );
}
NotePadMeta[] notes = new NotePadMeta[nr];
for ( int i = 0; i < notes.length; i++ ) {
Node noteNode = XMLHandler.getSubNodeByNr( notesNode, "notepad", i );
notes[i] = new NotePadMeta( noteNode );
Point p = notes[i].getLocation();
notes[i].setLocation( p.x + offset.x, p.y + offset.y );
transMeta.addNote( notes[i] );
notes[i].setSelected( true );
}
// Set the source and target steps ...
for ( StepMeta step : steps ) {
StepMetaInterface smi = step.getStepMetaInterface();
smi.searchInfoAndTargetSteps( transMeta.getSteps() );
}
// Set the error handling hops
Node errorHandlingNode = XMLHandler.getSubNode( transNode, TransMeta.XML_TAG_STEP_ERROR_HANDLING );
int nrErrorHandlers = XMLHandler.countNodes( errorHandlingNode, StepErrorMeta.XML_TAG );
for ( int i = 0; i < nrErrorHandlers; i++ ) {
Node stepErrorMetaNode = XMLHandler.getSubNodeByNr( errorHandlingNode, StepErrorMeta.XML_TAG, i );
StepErrorMeta stepErrorMeta =
new StepErrorMeta( transMeta.getParentVariableSpace(), stepErrorMetaNode, transMeta.getSteps() );
// Handle pasting multiple times, need to update source and target step names
int srcStepPos = stepOldNames.indexOf( stepErrorMeta.getSourceStep().getName() );
int tgtStepPos = stepOldNames.indexOf( stepErrorMeta.getTargetStep().getName() );
StepMeta sourceStep = transMeta.findStep( steps[srcStepPos].getName() );
if ( sourceStep != null ) {
sourceStep.setStepErrorMeta( stepErrorMeta );
}
sourceStep.setStepErrorMeta( null );
if ( tgtStepPos >= 0 ) {
sourceStep.setStepErrorMeta( stepErrorMeta );
StepMeta targetStep = transMeta.findStep( steps[tgtStepPos].getName() );
stepErrorMeta.setSourceStep( sourceStep );
stepErrorMeta.setTargetStep( targetStep );
}
}
// Save undo information too...
addUndoNew( transMeta, steps, position, false );
int[] hopPos = new int[hops.length];
for ( int i = 0; i < hops.length; i++ ) {
hopPos[i] = transMeta.indexOfTransHop( hops[i] );
}
addUndoNew( transMeta, hops, hopPos, true );
int[] notePos = new int[notes.length];
for ( int i = 0; i < notes.length; i++ ) {
notePos[i] = transMeta.indexOfNote( notes[i] );
}
addUndoNew( transMeta, notes, notePos, true );
if ( transMeta.haveStepsChanged() ) {
refreshTree();
refreshGraph();
}
} catch ( KettleException e ) {
// "Error pasting steps...",
// "I was unable to paste steps to this transformation"
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Dialog.UnablePasteSteps.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.UnablePasteSteps.Message" ), e );
}
}
public void copySelected( TransMeta transMeta, List<StepMeta> steps, List<NotePadMeta> notes ) {
if ( steps == null || steps.size() == 0 ) {
return;
}
if ( RepositorySecurityUI.verifyOperations( shell, rep,
RepositoryOperation.MODIFY_TRANSFORMATION, RepositoryOperation.EXECUTE_TRANSFORMATION ) ) {
return;
}
StringBuilder xml = new StringBuilder( 5000 ).append( XMLHandler.getXMLHeader() );
try {
xml.append( XMLHandler.openTag( Spoon.XML_TAG_TRANSFORMATION_STEPS ) ).append( Const.CR );
xml.append( XMLHandler.openTag( Spoon.XML_TAG_STEPS ) ).append( Const.CR );
for ( StepMeta step : steps ) {
xml.append( step.getXML() );
}
xml.append( XMLHandler.closeTag( Spoon.XML_TAG_STEPS ) ).append( Const.CR );
// Also check for the hops in between the selected steps...
xml.append( XMLHandler.openTag( TransMeta.XML_TAG_ORDER ) ).append( Const.CR );
for ( StepMeta step1 : steps ) {
for ( StepMeta step2 : steps ) {
if ( step1 != step2 ) {
TransHopMeta hop = transMeta.findTransHop( step1, step2, true );
if ( hop != null ) {
// Ok, we found one...
xml.append( hop.getXML() ).append( Const.CR );
}
}
}
}
xml.append( XMLHandler.closeTag( TransMeta.XML_TAG_ORDER ) ).append( Const.CR );
xml.append( XMLHandler.openTag( TransMeta.XML_TAG_NOTEPADS ) ).append( Const.CR );
if ( notes != null ) {
for ( NotePadMeta note : notes ) {
xml.append( note.getXML() );
}
}
xml.append( XMLHandler.closeTag( TransMeta.XML_TAG_NOTEPADS ) ).append( Const.CR );
xml.append( XMLHandler.openTag( TransMeta.XML_TAG_STEP_ERROR_HANDLING ) ).append( Const.CR );
for ( StepMeta step : steps ) {
if ( step.getStepErrorMeta() != null ) {
xml.append( step.getStepErrorMeta().getXML() ).append( Const.CR );
}
}
xml.append( XMLHandler.closeTag( TransMeta.XML_TAG_STEP_ERROR_HANDLING ) ).append( Const.CR );
xml.append( XMLHandler.closeTag( Spoon.XML_TAG_TRANSFORMATION_STEPS ) ).append( Const.CR );
toClipboard( xml.toString() );
} catch ( Exception ex ) {
new ErrorDialog( getShell(), "Error", "Error encoding to XML", ex );
}
}
public void editHop( TransMeta transMeta, TransHopMeta transHopMeta ) {
// Backup situation BEFORE edit:
String name = transHopMeta.toString();
TransHopMeta before = (TransHopMeta) transHopMeta.clone();
TransHopDialog hd = new TransHopDialog( shell, SWT.NONE, transHopMeta, transMeta );
if ( hd.open() != null ) {
// Backup situation for redo/undo:
TransHopMeta after = (TransHopMeta) transHopMeta.clone();
addUndoChange( transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta
.indexOfTransHop( transHopMeta ) } );
String newName = transHopMeta.toString();
if ( !name.equalsIgnoreCase( newName ) ) {
refreshTree();
refreshGraph(); // color, nr of copies...
}
}
setShellText();
}
public void delHop( TransMeta transMeta, TransHopMeta transHopMeta ) {
int index = transMeta.indexOfTransHop( transHopMeta );
addUndoDelete( transMeta, new Object[] { (TransHopMeta) transHopMeta.clone() }, new int[] { index } );
transMeta.removeTransHop( index );
// If this is an error handling hop, disable it
//
if ( transHopMeta.getFromStep().isDoingErrorHandling() ) {
StepErrorMeta stepErrorMeta = transHopMeta.getFromStep().getStepErrorMeta();
// We can only disable error handling if the target of the hop is the same as the target of the error handling.
//
if ( stepErrorMeta.getTargetStep() != null
&& stepErrorMeta.getTargetStep().equals( transHopMeta.getToStep() ) ) {
StepMeta stepMeta = transHopMeta.getFromStep();
// Only if the target step is where the error handling is going to...
//
StepMeta before = (StepMeta) stepMeta.clone();
stepErrorMeta.setEnabled( false );
index = transMeta.indexOfStep( stepMeta );
addUndoChange( transMeta, new Object[] { before }, new Object[] { stepMeta }, new int[] { index } );
}
}
refreshTree();
refreshGraph();
}
public void newHop( TransMeta transMeta, StepMeta fr, StepMeta to ) {
TransHopMeta hi = new TransHopMeta( fr, to );
TransHopDialog hd = new TransHopDialog( shell, SWT.NONE, hi, transMeta );
if ( hd.open() != null ) {
newHop( transMeta, hi );
}
}
public void newHop( TransMeta transMeta, TransHopMeta transHopMeta ) {
if ( checkIfHopAlreadyExists( transMeta, transHopMeta ) ) {
transMeta.addTransHop( transHopMeta );
int idx = transMeta.indexOfTransHop( transHopMeta );
if ( !performNewTransHopChecks( transMeta, transHopMeta ) ) {
// Some error occurred: loops, existing hop, etc.
// Remove it again...
//
transMeta.removeTransHop( idx );
} else {
addUndoNew( transMeta, new TransHopMeta[] { transHopMeta }, new int[] { transMeta
.indexOfTransHop( transHopMeta ) } );
}
// Just to make sure
transHopMeta.getFromStep().drawStep();
transHopMeta.getToStep().drawStep();
refreshTree();
refreshGraph();
}
}
/**
* @param transMeta transformation's meta
* @param newHop hop to be checked
* @return true when the hop was added, false if there was an error
*/
public boolean checkIfHopAlreadyExists( TransMeta transMeta, TransHopMeta newHop ) {
boolean ok = true;
if ( transMeta.findTransHop( newHop.getFromStep(), newHop.getToStep() ) != null ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.HopExists.Message" ) ); // "This hop already exists!"
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.HopExists.Title" ) ); // Error!
mb.open();
ok = false;
}
return ok;
}
/**
* @param transMeta transformation's meta
* @param newHop hop to be checked
* @return true when the hop was added, false if there was an error
*/
public boolean performNewTransHopChecks( TransMeta transMeta, TransHopMeta newHop ) {
boolean ok = true;
if ( transMeta.hasLoop( newHop.getFromStep() ) || transMeta.hasLoop( newHop.getToStep() ) ) {
MessageBox mb = new MessageBox( shell, SWT.YES | SWT.ICON_WARNING );
mb.setMessage( BaseMessages.getString( PKG, "TransGraph.Dialog.HopCausesLoop.Message" ) );
mb.setText( BaseMessages.getString( PKG, "TransGraph.Dialog.HopCausesLoop.Title" ) );
mb.open();
ok = false;
}
if ( ok ) { // only do the following checks, e.g. checkRowMixingStatically
// when not looping, otherwise we get a loop with
// StackOverflow there ;-)
try {
if ( !newHop.getToStep().getStepMetaInterface().excludeFromRowLayoutVerification() ) {
transMeta.checkRowMixingStatically( newHop.getToStep(), null );
}
} catch ( KettleRowException re ) {
// Show warning about mixing rows with conflicting layouts...
new ErrorDialog(
shell, BaseMessages.getString( PKG, "TransGraph.Dialog.HopCausesRowMixing.Title" ), BaseMessages
.getString( PKG, "TransGraph.Dialog.HopCausesRowMixing.Message" ), re );
}
verifyCopyDistribute( transMeta, newHop.getFromStep() );
}
return ok;
}
public void verifyCopyDistribute( TransMeta transMeta, StepMeta fr ) {
List<StepMeta> nextSteps = transMeta.findNextSteps( fr );
int nrNextSteps = nextSteps.size();
// don't show it for 3 or more hops, by then you should have had the
// message
if ( nrNextSteps == 2 ) {
boolean distributes = fr.getStepMetaInterface().excludeFromCopyDistributeVerification();
boolean customDistribution = false;
if ( props.showCopyOrDistributeWarning()
&& !fr.getStepMetaInterface().excludeFromCopyDistributeVerification() ) {
MessageDialogWithToggle md =
new MessageDialogWithToggle(
shell, BaseMessages.getString( PKG, "System.Warning" ), null, BaseMessages.getString(
PKG, "Spoon.Dialog.CopyOrDistribute.Message", fr.getName(), Integer.toString( nrNextSteps ) ),
MessageDialog.WARNING, getRowDistributionLabels(), 0, BaseMessages.getString(
PKG, "Spoon.Message.Warning.NotShowWarning" ), !props.showCopyOrDistributeWarning() );
MessageDialogWithToggle.setDefaultImage( GUIResource.getInstance().getImageSpoon() );
int idx = md.open();
props.setShowCopyOrDistributeWarning( !md.getToggleState() );
props.saveProps();
distributes = idx == Spoon.MESSAGE_DIALOG_WITH_TOGGLE_YES_BUTTON_ID;
customDistribution = idx == Spoon.MESSAGE_DIALOG_WITH_TOGGLE_CUSTOM_DISTRIBUTION_BUTTON_ID;
}
if ( distributes ) {
fr.setDistributes( true );
fr.setRowDistribution( null );
} else if ( customDistribution ) {
RowDistributionInterface rowDistribution = getActiveTransGraph().askUserForCustomDistributionMethod();
fr.setDistributes( true );
fr.setRowDistribution( rowDistribution );
} else {
fr.setDistributes( false );
fr.setDistributes( false );
}
refreshTree();
refreshGraph();
}
}
private String[] getRowDistributionLabels() {
ArrayList<String> labels = new ArrayList<String>();
labels.add( BaseMessages.getString( PKG, "Spoon.Dialog.CopyOrDistribute.Distribute" ) );
labels.add( BaseMessages.getString( PKG, "Spoon.Dialog.CopyOrDistribute.Copy" ) );
if ( PluginRegistry.getInstance().getPlugins( RowDistributionPluginType.class ).size() > 0 ) {
labels.add( BaseMessages.getString( PKG, "Spoon.Dialog.CopyOrDistribute.CustomRowDistribution" ) );
}
return labels.toArray( new String[labels.size()] );
}
public void newHop( TransMeta transMeta ) {
newHop( transMeta, null, null );
}
public void openRepository() {
// Check to tabs are dirty and warn user that they must save tabs prior to connecting. Don't connect!
if ( Spoon.getInstance().isTabsChanged() ) {
MessageBox mb = new MessageBox( Spoon.getInstance().getShell(), SWT.OK );
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.WarnToSaveAllPriorToConnect.Message" ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.WarnToCloseAllForce.Disconnect.Title" ) );
mb.open();
// Don't connect, user will need to save all their dirty tabs.
return;
}
loginDialog = new RepositoriesDialog( shell, null, new ILoginCallback() {
public void onSuccess( Repository repository ) {
// Close previous repository...
if ( rep != null ) {
rep.disconnect();
SpoonPluginManager.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.REPOSITORY_DISCONNECTED );
}
setRepository( repository );
loadSessionInformation( repository, true );
refreshTree();
setShellText();
SpoonPluginManager.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.REPOSITORY_CONNECTED );
}
public void onError( Throwable t ) {
closeRepository();
onLoginError( t );
}
public void onCancel() {
}
} );
loginDialog.show();
}
private void loadSessionInformation( Repository repository, boolean saveOldDatabases ) {
JobMeta[] jobMetas = getLoadedJobs();
for ( JobMeta jobMeta : jobMetas ) {
for ( int i = 0; i < jobMeta.nrDatabases(); i++ ) {
jobMeta.getDatabase( i ).setObjectId( null );
}
// Set for the existing job the ID at -1!
jobMeta.setObjectId( null );
// Keep track of the old databases for now.
List<DatabaseMeta> oldDatabases = jobMeta.getDatabases();
// In order to re-match the databases on name (not content), we
// need to load the databases from the new repository.
// NOTE: for purposes such as DEVELOP - TEST - PRODUCTION
// cycles.
// first clear the list of databases and slave servers
jobMeta.setDatabases( new ArrayList<DatabaseMeta>() );
jobMeta.setSlaveServers( new ArrayList<SlaveServer>() );
// Read them from the new repository.
try {
SharedObjects sharedObjects =
repository != null ? repository.readJobMetaSharedObjects( jobMeta ) : jobMeta.readSharedObjects();
sharedObjectsFileMap.put( sharedObjects.getFilename(), sharedObjects );
} catch ( KettleException e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Message", makeTabName( jobMeta, true ) ),
e
);
}
// Then we need to re-match the databases at save time...
for ( DatabaseMeta oldDatabase : oldDatabases ) {
DatabaseMeta newDatabase = DatabaseMeta.findDatabase( jobMeta.getDatabases(), oldDatabase.getName() );
// If it exists, change the settings...
if ( newDatabase != null ) {
//
// A database connection with the same name exists in
// the new repository.
// Change the old connections to reflect the settings in
// the new repository
//
oldDatabase.setDatabaseInterface( newDatabase.getDatabaseInterface() );
} else {
if ( saveOldDatabases ) {
//
// The old database is not present in the new
// repository: simply add it to the list.
// When the job gets saved, it will be added
// to the repository.
//
jobMeta.addDatabase( oldDatabase );
}
}
}
if ( repository != null ) {
try {
// For the existing job, change the directory too:
// Try to find the same directory in the new repository...
RepositoryDirectoryInterface rdi =
repository.findDirectory( jobMeta.getRepositoryDirectory().getPath() );
if ( rdi != null ) {
jobMeta.setRepositoryDirectory( rdi );
} else {
// the root is the default!
jobMeta.setRepositoryDirectory( repository.loadRepositoryDirectoryTree() );
}
} catch ( KettleException ke ) {
rep = null;
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorConnectingRepository.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorConnectingRepository.Message", Const.CR ), ke
);
}
}
}
TransMeta[] transMetas = getLoadedTransformations();
for ( TransMeta transMeta : transMetas ) {
for ( int i = 0; i < transMeta.nrDatabases(); i++ ) {
transMeta.getDatabase( i ).setObjectId( null );
}
// Set for the existing transformation the ID at -1!
transMeta.setObjectId( null );
// Keep track of the old databases for now.
List<DatabaseMeta> oldDatabases = transMeta.getDatabases();
// In order to re-match the databases on name (not content), we
// need to load the databases from the new repository.
// NOTE: for purposes such as DEVELOP - TEST - PRODUCTION
// cycles.
// first clear the list of databases, partition schemas, slave
// servers, clusters
transMeta.setDatabases( new ArrayList<DatabaseMeta>() );
transMeta.setPartitionSchemas( new ArrayList<PartitionSchema>() );
transMeta.setSlaveServers( new ArrayList<SlaveServer>() );
transMeta.setClusterSchemas( new ArrayList<ClusterSchema>() );
// Read them from the new repository.
try {
SharedObjects sharedObjects =
repository != null ? repository.readTransSharedObjects( transMeta ) : transMeta.readSharedObjects();
sharedObjectsFileMap.put( sharedObjects.getFilename(), sharedObjects );
} catch ( KettleException e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Title" ),
BaseMessages.getString( PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Message", makeTabName(
transMeta, true ) ), e
);
}
// Then we need to re-match the databases at save time...
for ( DatabaseMeta oldDatabase : oldDatabases ) {
DatabaseMeta newDatabase = DatabaseMeta.findDatabase( transMeta.getDatabases(), oldDatabase.getName() );
// If it exists, change the settings...
if ( newDatabase != null ) {
//
// A database connection with the same name exists in
// the new repository.
// Change the old connections to reflect the settings in
// the new repository
//
oldDatabase.setDatabaseInterface( newDatabase.getDatabaseInterface() );
} else {
if ( saveOldDatabases ) {
//
// The old database is not present in the new
// repository: simply add it to the list.
// When the transformation gets saved, it will be added
// to the repository.
//
transMeta.addDatabase( oldDatabase );
}
}
}
if ( repository != null ) {
try {
// For the existing transformation, change the directory too:
// Try to find the same directory in the new repository...
RepositoryDirectoryInterface rdi =
repository.findDirectory( transMeta.getRepositoryDirectory().getPath() );
if ( rdi != null ) {
transMeta.setRepositoryDirectory( rdi );
} else {
// the root is the default!
transMeta.setRepositoryDirectory( repository.loadRepositoryDirectoryTree() );
}
} catch ( KettleException ke ) {
rep = null;
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorConnectingRepository.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorConnectingRepository.Message", Const.CR ), ke
);
}
}
}
}
public void clearSharedObjectCache() throws KettleException {
if ( rep != null ) {
rep.clearSharedObjectCache();
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
rep.readTransSharedObjects( transMeta );
}
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
rep.readJobMetaSharedObjects( jobMeta );
}
}
}
public void exploreRepository() {
if ( rep != null ) {
final RepositoryExplorerCallback cb = new RepositoryExplorerCallback() {
@Override
public boolean open( UIRepositoryContent element, String revision ) throws Exception {
String objName = element.getName();
if ( objName != null ) {
RepositoryObjectType objectType = element.getRepositoryElementType();
RepositoryDirectory repDir = element.getRepositoryDirectory();
if ( element.getObjectId() != null ) { // new way
loadObjectFromRepository( element.getObjectId(), objectType, revision );
} else { // old way
loadObjectFromRepository( objName, objectType, repDir, revision );
}
}
return false; // do not close explorer
}
@Override
public boolean error( String message ) throws Exception {
closeRepository();
return true;
}
};
try {
final XulWaitBox box = (XulWaitBox) this.mainSpoonContainer.getDocumentRoot().createElement( "waitbox" );
box.setIndeterminate( true );
box.setCanCancel( false );
box.setTitle( BaseMessages.getString(
RepositoryDialogInterface.class, "RepositoryExplorerDialog.Connection.Wait.Title" ) );
box.setMessage( BaseMessages.getString(
RepositoryDialogInterface.class, "RepositoryExplorerDialog.Explorer.Wait.Message" ) );
box.setDialogParent( shell );
box.setRunnable( new WaitBoxRunnable( box ) {
@Override
public void run() {
shell.getDisplay().syncExec( new Runnable() {
public void run() {
RepositoryExplorer explorer;
try {
try {
explorer =
new RepositoryExplorer( shell, rep, cb, Variables.getADefaultVariableSpace() );
} catch ( final KettleRepositoryLostException krle ) {
shell.getDisplay().asyncExec( new Runnable() {
public void run() {
new ErrorDialog(
getShell(),
BaseMessages.getString( PKG, "Spoon.Error" ),
krle.getPrefaceMessage(),
krle );
}
} );
closeRepository();
return;
} finally {
box.stop();
}
if ( explorer.isInitialized() ) {
explorer.show();
} else {
return;
}
explorer.dispose();
} catch ( final Throwable e ) {
shell.getDisplay().asyncExec( new Runnable() {
public void run() {
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Error" ), e.getMessage(), e );
}
} );
}
}
} );
}
@Override
public void cancel() {
}
} );
box.start();
} catch ( Throwable e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Error" ), e.getMessage(), e );
}
}
}
private void loadObjectFromRepository(
ObjectId objectId, RepositoryObjectType objectType, String revision ) throws Exception {
// Try to open the selected transformation.
if ( objectType.equals( RepositoryObjectType.TRANSFORMATION ) ) {
try {
TransLoadProgressDialog progressDialog = new TransLoadProgressDialog( shell, rep, objectId, revision );
TransMeta transMeta = progressDialog.open();
transMeta.clearChanged();
if ( transMeta != null ) {
if ( log.isDetailed() ) {
log.logDetailed( BaseMessages.getString(
PKG, "Spoon.Log.LoadToTransformation", transMeta.getName(), transMeta
.getRepositoryDirectory().getName() ) );
}
props.addLastFile( LastUsedFile.FILE_TYPE_TRANSFORMATION, transMeta.getName(), transMeta
.getRepositoryDirectory().getPath(), true, rep.getName() );
addMenuLast();
addTransGraph( transMeta );
}
refreshTree();
refreshGraph();
} catch ( Exception e ) {
if ( KettleRepositoryLostException.lookupStackStrace( e ) == null ) {
new ErrorDialog( ( (Spoon) SpoonFactory.getInstance() ).getShell(), BaseMessages.getString(
Spoon.class, "Spoon.Dialog.ErrorOpeningById.Message", objectId ), e.getMessage(), e );
} else {
throw e;
}
}
} else if ( objectType.equals( RepositoryObjectType.JOB ) ) {
try {
JobLoadProgressDialog progressDialog = new JobLoadProgressDialog( shell, rep, objectId, revision );
JobMeta jobMeta = progressDialog.open();
jobMeta.clearChanged();
if ( jobMeta != null ) {
props.addLastFile( LastUsedFile.FILE_TYPE_JOB, jobMeta.getName(), jobMeta
.getRepositoryDirectory().getPath(), true, rep.getName() );
saveSettings();
addMenuLast();
addJobGraph( jobMeta );
}
refreshTree();
refreshGraph();
} catch ( Exception e ) {
if ( KettleRepositoryLostException.lookupStackStrace( e ) == null ) {
new ErrorDialog( ( (Spoon) SpoonFactory.getInstance() ).getShell(), BaseMessages.getString(
Spoon.class, "Spoon.Dialog.ErrorOpeningById.Message", objectId ), e.getMessage(), e );
} else {
throw e;
}
}
}
}
public void loadObjectFromRepository( String objName, RepositoryObjectType objectType,
RepositoryDirectoryInterface repDir, String versionLabel ) throws Exception {
// Try to open the selected transformation.
if ( objectType.equals( RepositoryObjectType.TRANSFORMATION ) ) {
try {
TransLoadProgressDialog progressDialog =
new TransLoadProgressDialog( shell, rep, objName, repDir, versionLabel );
TransMeta transMeta = progressDialog.open();
transMeta.clearChanged();
if ( transMeta != null ) {
if ( log.isDetailed() ) {
log.logDetailed( BaseMessages.getString( PKG, "Spoon.Log.LoadToTransformation", objName, repDir
.getName() ) );
}
props
.addLastFile( LastUsedFile.FILE_TYPE_TRANSFORMATION, objName, repDir.getPath(), true, rep.getName() );
addMenuLast();
addTransGraph( transMeta );
}
refreshTree();
refreshGraph();
} catch ( Exception e ) {
if ( KettleRepositoryLostException.lookupStackStrace( e ) == null ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.ErrorOpening.Message" )
+ objName + Const.CR + e.getMessage() ); // "Error opening : "
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.ErrorOpening.Title" ) );
mb.open();
} else {
throw e;
}
}
} else if ( objectType.equals( RepositoryObjectType.JOB ) ) {
// Try to open the selected job.
try {
JobLoadProgressDialog progressDialog =
new JobLoadProgressDialog( shell, rep, objName, repDir, versionLabel );
JobMeta jobMeta = progressDialog.open();
jobMeta.clearChanged();
if ( jobMeta != null ) {
props.addLastFile( LastUsedFile.FILE_TYPE_JOB, objName, repDir.getPath(), true, rep.getName() );
saveSettings();
addMenuLast();
addJobGraph( jobMeta );
}
refreshTree();
refreshGraph();
} catch ( Exception e ) {
if ( KettleRepositoryLostException.lookupStackStrace( e ) == null ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.ErrorOpening.Message" )
+ objName + Const.CR + e.getMessage() ); // "Error opening : "
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.ErrorOpening.Title" ) );
mb.open();
} else {
throw e;
}
}
}
}
public void closeRepository() {
if ( rep != null ) {
// Prompt and close all tabs as user disconnected from the repo
boolean shouldDisconnect = Spoon.getInstance().closeAllJobsAndTransformations();
if ( shouldDisconnect ) {
loadSessionInformation( null, false );
rep.disconnect();
if ( metaStore.getMetaStoreList().size() > 1 ) {
try {
metaStore.getMetaStoreList().remove( 0 );
metaStore.setActiveMetaStoreName( metaStore.getMetaStoreList().get( 0 ).getName() );
} catch ( MetaStoreException e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.ErrorRemovingMetaStore.Title" ),
BaseMessages.getString( PKG, "Spoon.ErrorRemovingMetaStore.Message" ), e );
}
}
setRepository( null );
setShellText();
SpoonPluginManager.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.REPOSITORY_DISCONNECTED );
enableMenus();
}
}
}
public void openFile() {
openFile( false );
}
public void importFile() {
openFile( true );
}
public void openFile( boolean importfile ) {
try {
SpoonPerspective activePerspective = SpoonPerspectiveManager.getInstance().getActivePerspective();
// In case the perspective wants to handle open/save itself, let it...
//
if ( !importfile ) {
if ( activePerspective instanceof SpoonPerspectiveOpenSaveInterface ) {
( (SpoonPerspectiveOpenSaveInterface) activePerspective ).open();
return;
}
}
String activePerspectiveId = activePerspective.getId();
boolean etlPerspective = activePerspectiveId.equals( MainSpoonPerspective.ID );
if ( rep == null || importfile || !etlPerspective ) { // Load from XML
FileDialog dialog = new FileDialog( shell, SWT.OPEN );
LinkedHashSet<String> extensions = new LinkedHashSet<String>();
LinkedHashSet<String> extensionNames = new LinkedHashSet<String>();
StringBuilder allExtensions = new StringBuilder();
for ( FileListener l : fileListeners ) {
for ( String ext : l.getSupportedExtensions() ) {
extensions.add( "*." + ext );
allExtensions.append( "*." ).append( ext ).append( ";" );
}
Collections.addAll( extensionNames, l.getFileTypeDisplayNames( Locale.getDefault() ) );
}
extensions.add( "*" );
extensionNames.add( BaseMessages.getString( PKG, "Spoon.Dialog.OpenFile.AllFiles" ) );
String[] exts = new String[extensions.size() + 1];
exts[0] = allExtensions.toString();
System.arraycopy( extensions.toArray( new String[extensions.size()] ), 0, exts, 1, extensions.size() );
String[] extNames = new String[extensionNames.size() + 1];
extNames[0] = BaseMessages.getString( PKG, "Spoon.Dialog.OpenFile.AllTypes" );
System.arraycopy( extensionNames.toArray( new String[extensionNames.size()] ), 0, extNames, 1, extensionNames
.size() );
dialog.setFilterExtensions( exts );
setFilterPath( dialog );
String filename = dialog.open();
if ( filename != null ) {
if ( importfile ) {
if ( activePerspective instanceof SpoonPerspectiveOpenSaveInterface ) {
( (SpoonPerspectiveOpenSaveInterface) activePerspective ).importFile( filename );
return;
}
}
lastDirOpened = dialog.getFilterPath();
openFile( filename, importfile );
}
} else {
SelectObjectDialog sod = new SelectObjectDialog( shell, rep );
if ( sod.open() != null ) {
RepositoryObjectType type = sod.getObjectType();
String name = sod.getObjectName();
RepositoryDirectoryInterface repDir = sod.getDirectory();
ObjectId objId = sod.getObjectId();
// Load a transformation
if ( RepositoryObjectType.TRANSFORMATION.equals( type ) ) {
TransLoadProgressDialog tlpd = null;
// prioritize loading file by id
if( objId != null && !Const.isEmpty( objId.getId() ) ) {
tlpd = new TransLoadProgressDialog( shell, rep, objId, null ); // Load by id
} else {
tlpd = new TransLoadProgressDialog( shell, rep, name, repDir, null ); // Load by name/path
}
// the
// last
// version
TransMeta transMeta = tlpd.open();
sharedObjectsFileMap.put( transMeta.getSharedObjects().getFilename(), transMeta.getSharedObjects() );
setTransMetaVariables( transMeta );
if ( transMeta != null ) {
if ( log.isDetailed() ) {
log.logDetailed( BaseMessages.getString( PKG, "Spoon.Log.LoadToTransformation", name, repDir
.getName() ) );
}
props.addLastFile( LastUsedFile.FILE_TYPE_TRANSFORMATION, name, repDir.getPath(), true, rep.getName() );
addMenuLast();
transMeta.clearChanged();
// transMeta.setFilename(name); // Don't do it, it's a bad idea!
addTransGraph( transMeta );
}
refreshGraph();
refreshTree();
} else if ( RepositoryObjectType.JOB.equals( type ) ) {
// Load a job
JobLoadProgressDialog jlpd = null;
// prioritize loading file by id
if( objId != null && !Const.isEmpty( objId.getId() ) ) {
jlpd = new JobLoadProgressDialog( shell, rep, objId, null ); // Loads
} else {
jlpd = new JobLoadProgressDialog( shell, rep, name, repDir, null ); // Loads
}
// the last version
JobMeta jobMeta = jlpd.open();
sharedObjectsFileMap.put( jobMeta.getSharedObjects().getFilename(), jobMeta.getSharedObjects() );
setJobMetaVariables( jobMeta );
if ( jobMeta != null ) {
props.addLastFile( LastUsedFile.FILE_TYPE_JOB, name, repDir.getPath(), true, rep.getName() );
saveSettings();
addMenuLast();
addJobGraph( jobMeta );
}
refreshGraph();
refreshTree();
}
}
}
} catch ( KettleRepositoryLostException krle ) {
new ErrorDialog(
getShell(),
BaseMessages.getString( PKG, "Spoon.Error" ),
krle.getPrefaceMessage(),
krle );
this.closeRepository();
}
}
private void setFilterPath( FileDialog dialog ) {
if ( !Const.isEmpty( lastDirOpened ) ) {
if ( new File( lastDirOpened ).exists() ) {
dialog.setFilterPath( lastDirOpened );
}
}
}
private String lastFileOpened = null;
public String getLastFileOpened() {
if ( lastFileOpened == null ) {
lastFileOpened = System.getProperty( "org.pentaho.di.defaultVFSPath", "" );
}
return lastFileOpened;
}
public void setLastFileOpened( String inLastFileOpened ) {
lastFileOpened = inLastFileOpened;
}
public void displayCmdLine() {
String cmdFile = getCmdLine();
if ( Const.isEmpty( cmdFile ) ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage( BaseMessages.getString( PKG, "ExportCmdLine.JobOrTransformationMissing.Message" ) );
mb.setText( BaseMessages.getString( PKG, "ExportCmdLine.JobOrTransformationMissing.Title" ) );
mb.open();
} else {
ShowBrowserDialog sbd =
new ShowBrowserDialog( shell, BaseMessages.getString( PKG, "ExportCmdLine.CommandLine.Title" ), cmdFile );
sbd.open();
}
}
public void createCmdLineFile() {
String cmdFile = getCmdLine();
if ( Const.isEmpty( cmdFile ) ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage( BaseMessages.getString( PKG, "ExportCmdLine.JobOrTransformationMissing.Message" ) );
mb.setText( BaseMessages.getString( PKG, "ExportCmdLine.JobOrTransformationMissing.Title" ) );
mb.open();
} else {
boolean export = true;
FileDialog dialog = new FileDialog( shell, SWT.SAVE );
dialog.setFilterExtensions( new String[] { "*.bat", ".sh", "*.*" } );
dialog.setFilterNames( new String[] {
BaseMessages.getString( PKG, "ExportCmdLine.BatFiles" ),
BaseMessages.getString( PKG, "ExportCmdLineShFiles" ),
BaseMessages.getString( PKG, "ExportCmdLine.AllFiles" ) } );
String filename = dialog.open();
if ( filename != null ) {
// See if the file already exists...
int id = SWT.YES;
try {
FileObject f = KettleVFS.getFileObject( filename );
if ( f.exists() ) {
MessageBox mb = new MessageBox( shell, SWT.NO | SWT.YES | SWT.ICON_WARNING );
mb.setMessage( BaseMessages.getString( PKG, "ExportCmdLineShFiles.FileExistsReplace", filename ) );
mb.setText( BaseMessages.getString( PKG, "ExportCmdLineShFiles.ConfirmOverwrite" ) );
id = mb.open();
}
} catch ( Exception e ) {
// Ignore errors
}
if ( id == SWT.NO ) {
export = false;
}
if ( export ) {
java.io.FileWriter out = null;
try {
out = new java.io.FileWriter( filename );
out.write( cmdFile );
out.flush();
} catch ( Exception e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "ExportCmdLineShFiles.ErrorWritingFile.Title" ), BaseMessages
.getString( PKG, "ExportCmdLineShFiles.ErrorWritingFile.Message", filename ), e );
} finally {
if ( out != null ) {
try {
out.close();
} catch ( Exception e ) {
// Ignore errors
}
}
}
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage( BaseMessages.getString( PKG, "ExportCmdLineShFiles.CmdExported.Message", filename ) );
mb.setText( BaseMessages.getString( PKG, "ExportCmdLineShFiles.CmdExported.Title" ) );
mb.open();
}
}
}
}
private String getCmdLine() {
TransMeta transMeta = getActiveTransformation();
JobMeta jobMeta = getActiveJob();
String cmdFile = "";
if ( rep != null && ( jobMeta != null || transMeta != null ) ) {
if ( jobMeta != null ) {
if ( jobMeta.getName() != null ) {
if ( Const.isWindows() ) {
cmdFile =
"kitchen "
+ "/rep:\"" + rep.getName() + "\"" + " /user:\""
+ ( rep.getUserInfo() != null ? rep.getUserInfo().getLogin() : "" ) + "\"" + " /pass:\""
+ Encr.encryptPasswordIfNotUsingVariables( rep.getUserInfo().getPassword() ) + "\""
+ " /job:\"" + jobMeta.getName() + '"' + " /dir:\""
+ jobMeta.getRepositoryDirectory().getPath() + "\"" + " /level:Basic";
} else {
cmdFile =
"sh kitchen.sh "
+ "-rep='"
+ rep.getName()
+ "'"
+ " -user='"
+ ( rep.getUserInfo() != null ? rep.getUserInfo().getLogin() : "" )
+ "'"
+ " -pass='"
+ Encr.encryptPasswordIfNotUsingVariables( rep.getUserInfo() != null ? rep
.getUserInfo().getPassword() : "" ) + "'" + " -job='" + jobMeta.getName() + "'"
+ " -dir='" + jobMeta.getRepositoryDirectory().getPath() + "'" + " -level=Basic";
}
}
} else {
if ( transMeta.getName() != null ) {
if ( Const.isWindows() ) {
cmdFile =
"pan "
+ "/rep:\""
+ rep.getName()
+ "\""
+ " /user:\""
+ ( rep.getUserInfo() != null ? rep.getUserInfo().getLogin() : "" )
+ "\""
+ " /pass:\""
+ Encr.encryptPasswordIfNotUsingVariables( rep.getUserInfo() != null ? rep
.getUserInfo().getPassword() : "" ) + "\"" + " /trans:\"" + transMeta.getName() + "\""
+ " /dir:\"" + transMeta.getRepositoryDirectory().getPath() + "\"" + " /level:Basic";
} else {
cmdFile =
"sh pan.sh "
+ "-rep='"
+ rep.getName()
+ "'"
+ " -user='"
+ ( rep.getUserInfo() != null ? rep.getUserInfo().getLogin() : "" )
+ "'"
+ " -pass='"
+ Encr.encryptPasswordIfNotUsingVariables( rep.getUserInfo() != null ? rep
.getUserInfo().getPassword() : "" ) + "'" + " -trans='" + transMeta.getName() + "'"
+ " -dir='" + transMeta.getRepositoryDirectory().getPath() + "'" + " -level=Basic";
}
}
}
} else if ( rep == null && ( jobMeta != null || transMeta != null ) ) {
if ( jobMeta != null ) {
if ( jobMeta.getFilename() != null ) {
if ( Const.isWindows() ) {
cmdFile = "kitchen " + "/file:\"" + jobMeta.getFilename() + "\"" + " /level:Basic";
} else {
cmdFile = "sh kitchen.sh " + "-file='" + jobMeta.getFilename() + "'" + " -level=Basic";
}
}
} else {
if ( transMeta.getFilename() != null ) {
if ( Const.isWindows() ) {
cmdFile = "pan " + "/file:\"" + transMeta.getFilename() + "\"" + " /level:Basic";
} else {
cmdFile = "sh pan.sh " + "-file:'" + transMeta.getFilename() + "'" + " -level=Basic";
}
}
}
}
return cmdFile;
}
// private String lastVfsUsername="";
// private String lastVfsPassword="";
public void openFileVFSFile() {
FileObject initialFile;
FileObject rootFile;
try {
initialFile = KettleVFS.getFileObject( getLastFileOpened() );
rootFile = initialFile.getFileSystem().getRoot();
} catch ( Exception e ) {
String message = Const.getStackTracker( e );
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Error" ), message, e );
return;
}
FileObject selectedFile =
getVfsFileChooserDialog( rootFile, initialFile ).open(
shell, null, Const.STRING_TRANS_AND_JOB_FILTER_EXT, Const.getTransformationAndJobFilterNames(),
VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE );
if ( selectedFile != null ) {
setLastFileOpened( selectedFile.getName().getFriendlyURI() );
openFile( selectedFile.getName().getFriendlyURI(), false );
}
}
public void addFileListener( FileListener listener ) {
this.fileListeners.add( listener );
for ( String s : listener.getSupportedExtensions() ) {
if ( !fileExtensionMap.containsKey( s ) ) {
fileExtensionMap.put( s, listener );
}
}
}
public void openFile( String filename, boolean importfile ) {
try {
// Open the XML and see what's in there.
// We expect a single <transformation> or <job> root at this time...
boolean loaded = false;
FileListener listener = null;
Node root = null;
// match by extension first
int idx = filename.lastIndexOf( '.' );
if ( idx != -1 ) {
for ( FileListener li : fileListeners ) {
if ( li.accepts( filename ) ) {
listener = li;
break;
}
}
}
// Attempt to find a root XML node name. Fails gracefully for non-XML file
// types.
try {
Document document = XMLHandler.loadXMLFile( filename );
root = document.getDocumentElement();
} catch ( KettleXMLException e ) {
if ( log.isDetailed() ) {
log.logDetailed( BaseMessages.getString( PKG, "Spoon.File.Xml.Parse.Error" ) );
}
}
// otherwise try by looking at the root node if we were able to parse file
// as XML
if ( listener == null && root != null ) {
for ( FileListener li : fileListeners ) {
if ( li.acceptsXml( root.getNodeName() ) ) {
listener = li;
break;
}
}
}
// You got to have a file name!
//
if ( !Const.isEmpty( filename ) ) {
if ( listener != null ) {
loaded = listener.open( root, filename, importfile );
}
if ( !loaded ) {
// Give error back
hideSplash();
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "Spoon.UnknownFileType.Message", filename ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.UnknownFileType.Title" ) );
mb.open();
} else {
applyVariables(); // set variables in the newly loaded
// transformation(s) and job(s).
}
}
} catch ( KettleMissingPluginsException e ) {
// There are missing plugins, let's try to handle them in the marketplace...
//
if ( marketPluginIsAvailable() ) {
handleMissingPluginsExceptionWithMarketplace( e );
}
}
}
/**
* Check to see if the market plugin is available.
*
* @return true if the market plugin is installed and ready, false if it is not.
*/
private boolean marketPluginIsAvailable() {
PluginInterface marketPlugin = findMarketPlugin();
return marketPlugin != null;
}
private PluginInterface findMarketPlugin() {
return PluginRegistry.getInstance().findPluginWithId( SpoonPluginType.class, "market" );
}
/**
* Shows a dialog listing the missing plugins, asking if you want to go into the marketplace
*
* @param missingPluginsException
* The missing plugins exception
*/
public void handleMissingPluginsExceptionWithMarketplace( KettleMissingPluginsException missingPluginsException ) {
try {
hideSplash();
MessageBox box = new MessageBox( shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO );
box.setText( BaseMessages.getString( PKG, "Spoon.MissingPluginsFoundDialog.Title" ) );
box.setMessage( BaseMessages.getString(
PKG, "Spoon.MissingPluginsFoundDialog.Message", Const.CR, missingPluginsException.getPluginsMessage() ) );
int answer = box.open();
if ( ( answer & SWT.YES ) != 0 ) {
String controllerClassName = "org.pentaho.di.ui.spoon.dialog.MarketplaceController";
PluginInterface marketPlugin = findMarketPlugin();
ClassLoader classLoader = PluginRegistry.getInstance().getClassLoader( marketPlugin );
Class<?> controllerClass = classLoader.loadClass( controllerClassName );
Method method = controllerClass.getMethod( "showMarketPlaceDialog" );
method.invoke( null );
}
} catch ( Exception ex ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.ErrorShowingMarketplaceDialog.Title" ), BaseMessages
.getString( PKG, "Spoon.ErrorShowingMarketplaceDialog.Message" ), ex );
}
}
public PropsUI getProperties() {
return props;
}
/*
* public void newFileDropDown() { newFileDropDown(toolbar); }
*/
public void newFileDropDown() {
// Drop down a list below the "New" icon (new.png)
// First problem: where is that icon?
XulToolbarbutton button = (XulToolbarbutton) this.mainToolbar.getElementById( "file-new" );
Object object = button.getManagedObject();
if ( object instanceof ToolItem ) {
// OK, let's determine the location of this widget...
//
ToolItem item = (ToolItem) object;
Rectangle bounds = item.getBounds();
org.eclipse.swt.graphics.Point p =
item.getParent().toDisplay( new org.eclipse.swt.graphics.Point( bounds.x, bounds.y ) );
fileMenus.setLocation( p.x, p.y + bounds.height );
fileMenus.setVisible( true );
}
}
public void newTransFile() {
TransMeta transMeta = new TransMeta();
transMeta.addObserver( this );
// Set the variables that were previously defined in this session on the
// transformation metadata too.
//
setTransMetaVariables( transMeta );
// Pass repository information
//
transMeta.setRepository( rep );
transMeta.setMetaStore( metaStore );
try {
SharedObjects sharedObjects =
rep != null ? rep.readTransSharedObjects( transMeta ) : transMeta.readSharedObjects();
sharedObjectsFileMap.put( sharedObjects.getFilename(), sharedObjects );
transMeta.importFromMetaStore();
transMeta.clearChanged();
} catch ( Exception e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Exception.ErrorReadingSharedObjects.Title" ), BaseMessages
.getString( PKG, "Spoon.Exception.ErrorReadingSharedObjects.Message" ), e );
}
// Set the location of the new transMeta to that of the default location or the last saved location
transMeta.setRepositoryDirectory( getDefaultSaveLocation( transMeta ) );
int nr = 1;
transMeta.setName( STRING_TRANSFORMATION + " " + nr );
// See if a transformation with the same name isn't already loaded...
//
while ( findTransformation( delegates.tabs.makeTabName( transMeta, false ) ) != null ) {
nr++;
transMeta.setName( STRING_TRANSFORMATION + " " + nr ); // rename
}
addTransGraph( transMeta );
applyVariables();
// switch to design mode...
//
if ( setDesignMode() ) {
// No refresh done yet, do so
refreshTree();
}
loadPerspective( MainSpoonPerspective.ID );
}
public void newJobFile() {
try {
JobMeta jobMeta = new JobMeta();
jobMeta.addObserver( this );
// Set the variables that were previously defined in this session on
// the transformation metadata too.
//
setJobMetaVariables( jobMeta );
// Pass repository information
//
jobMeta.setRepository( rep );
jobMeta.setMetaStore( metaStore );
try {
SharedObjects sharedObjects =
rep != null ? rep.readJobMetaSharedObjects( jobMeta ) : jobMeta.readSharedObjects();
sharedObjectsFileMap.put( sharedObjects.getFilename(), sharedObjects );
jobMeta.importFromMetaStore();
} catch ( Exception e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Message", delegates.tabs.makeTabName(
jobMeta, true ) ), e );
}
// Set the location of the new jobMeta to that of the default location or the last saved location
jobMeta.setRepositoryDirectory( getDefaultSaveLocation( jobMeta ) );
int nr = 1;
jobMeta.setName( STRING_JOB + " " + nr );
// See if a transformation with the same name isn't already
// loaded...
while ( findJob( delegates.tabs.makeTabName( jobMeta, false ) ) != null ) {
nr++;
jobMeta.setName( STRING_JOB + " " + nr ); // rename
}
jobMeta.clearChanged();
addJobGraph( jobMeta );
applyVariables();
// switch to design mode...
//
if ( setDesignMode() ) {
// No refresh done yet, do so
refreshTree();
}
loadPerspective( MainSpoonPerspective.ID );
} catch ( Exception e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Exception.ErrorCreatingNewJob.Title" ), BaseMessages
.getString( PKG, "Spoon.Exception.ErrorCreatingNewJob.Message" ), e );
}
}
/**
* Set previously defined variables (set variables dialog) on the specified transformation
*
* @param transMeta transformation's meta
*/
public void setTransMetaVariables( TransMeta transMeta ) {
for ( int i = 0; i < variables.size(); i++ ) {
try {
String name = variables.getValueMeta( i ).getName();
String value = variables.getString( i, "" );
transMeta.setVariable( name, Const.NVL( value, "" ) );
} catch ( Exception e ) {
// Ignore the exception, it should never happen on a getString()
// anyway.
}
}
// Also set the parameters
//
setParametersAsVariablesInUI( transMeta, transMeta );
}
/**
* Set previously defined variables (set variables dialog) on the specified job
*
* @param jobMeta job's meta
*/
public void setJobMetaVariables( JobMeta jobMeta ) {
for ( int i = 0; i < variables.size(); i++ ) {
try {
String name = variables.getValueMeta( i ).getName();
String value = variables.getString( i, "" );
jobMeta.setVariable( name, Const.NVL( value, "" ) );
} catch ( Exception e ) {
// Ignore the exception, it should never happen on a getString()
// anyway.
}
}
// Also set the parameters
//
setParametersAsVariablesInUI( jobMeta, jobMeta );
}
public void loadRepositoryObjects( TransMeta transMeta ) {
// Load common database info from active repository...
if ( rep != null ) {
try {
SharedObjects sharedObjects = rep.readTransSharedObjects( transMeta );
sharedObjectsFileMap.put( sharedObjects.getFilename(), sharedObjects );
} catch ( Exception e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Error.UnableToLoadSharedObjects.Title" ), BaseMessages
.getString( PKG, "Spoon.Error.UnableToLoadSharedObjects.Message" ), e );
}
}
}
public boolean quitFile( boolean canCancel ) throws KettleException {
if ( log.isDetailed() ) {
log.logDetailed( BaseMessages.getString( PKG, "Spoon.Log.QuitApplication" ) ); // "Quit application."
}
boolean exit = true;
saveSettings();
if ( props.showExitWarning() && canCancel ) {
// Display message: are you sure you want to exit?
//
MessageDialogWithToggle md =
new MessageDialogWithToggle( shell,
BaseMessages.getString( PKG, "System.Warning" ), // "Warning!"
null,
BaseMessages.getString( PKG, "Spoon.Message.Warning.PromptExit" ),
MessageDialog.WARNING, new String[] {
// "Yes",
BaseMessages.getString( PKG, "Spoon.Message.Warning.Yes" ),
// "No"
BaseMessages.getString( PKG, "Spoon.Message.Warning.No" )
}, 1,
// "Please, don't show this warning anymore."
BaseMessages.getString( PKG, "Spoon.Message.Warning.NotShowWarning" ),
!props.showExitWarning() );
MessageDialogWithToggle.setDefaultImage( GUIResource.getInstance().getImageSpoon() );
int idx = md.open();
props.setExitWarningShown( !md.getToggleState() );
props.saveProps();
if ( ( idx & 0xFF ) == 1 ) {
return false; // No selected: don't exit!
}
}
// Check all tabs to see if we can close them...
//
List<TabMapEntry> list = delegates.tabs.getTabs();
for ( TabMapEntry mapEntry : list ) {
TabItemInterface itemInterface = mapEntry.getObject();
if ( !itemInterface.canBeClosed() ) {
// Show the tab
tabfolder.setSelected( mapEntry.getTabItem() );
// Unsaved work that needs to changes to be applied?
//
int reply = itemInterface.showChangedWarning();
if ( reply == SWT.YES ) {
exit = itemInterface.applyChanges();
} else {
if ( reply == SWT.CANCEL ) {
return false;
} else { // SWT.NO
exit = true;
}
}
}
}
if ( exit || !canCancel ) {
// we have asked about it all and we're still here. Now close
// all the tabs, stop the running transformations
for ( TabMapEntry mapEntry : list ) {
if ( !mapEntry.getObject().canBeClosed() ) {
// Unsaved transformation?
//
if ( mapEntry.getObject() instanceof TransGraph ) {
TransMeta transMeta = (TransMeta) mapEntry.getObject().getManagedObject();
if ( transMeta.hasChanged() ) {
delegates.tabs.removeTab( mapEntry );
}
}
// A running transformation?
//
if ( mapEntry.getObject() instanceof TransGraph ) {
TransGraph transGraph = (TransGraph) mapEntry.getObject();
if ( transGraph.isRunning() ) {
transGraph.stop();
delegates.tabs.removeTab( mapEntry );
}
}
}
}
}
// and now we call the listeners
try {
lifecycleSupport.onExit( this );
} catch ( LifecycleException e ) {
MessageBox box = new MessageBox( shell, SWT.ICON_ERROR | SWT.OK );
box.setMessage( e.getMessage() );
box.open();
}
if ( exit ) {
close();
}
return exit;
}
public boolean saveFile() {
try {
EngineMetaInterface meta = getActiveMeta();
if ( meta != null ) {
return saveToFile( meta );
}
} catch ( Exception e ) {
KettleRepositoryLostException krle = KettleRepositoryLostException.lookupStackStrace( e );
if ( krle != null ) {
new ErrorDialog(
shell,
BaseMessages.getString( PKG, "Spoon.File.Save.Fail.Title" ),
krle.getPrefaceMessage(),
krle );
closeRepository();
} else {
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.File.Save.Fail.Title" ), BaseMessages.getString(
PKG, "Spoon.File.Save.Fail.Message" ), e );
}
}
return false;
}
public boolean saveToFile( EngineMetaInterface meta ) throws KettleException {
if ( meta == null ) {
return false;
}
boolean saved = false;
if ( meta instanceof TransMeta ) {
( (TransMeta) meta ).setRepository( rep );
( (TransMeta) meta ).setMetaStore( metaStore );
}
if ( meta instanceof JobMeta ) {
( (JobMeta) meta ).setRepository( rep );
( (JobMeta) meta ).setMetaStore( metaStore );
}
if ( log.isDetailed() ) {
// "Save to file or repository...
log.logDetailed( BaseMessages.getString( PKG, "Spoon.Log.SaveToFileOrRepository" ) );
}
SpoonPerspective activePerspective = SpoonPerspectiveManager.getInstance().getActivePerspective();
// In case the perspective wants to handle open/save itself, let it...
//
if ( activePerspective instanceof SpoonPerspectiveOpenSaveInterface ) {
return ( (SpoonPerspectiveOpenSaveInterface) activePerspective ).save( meta );
}
String activePerspectiveId = activePerspective.getId();
boolean etlPerspective = activePerspectiveId.equals( MainSpoonPerspective.ID );
if ( rep != null && etlPerspective ) {
saved = saveToRepository( meta );
} else {
if ( meta.getFilename() != null ) {
saved = save( meta, meta.getFilename(), false );
} else {
if ( meta.canSave() ) {
saved = saveFileAs( meta );
}
}
}
meta.saveSharedObjects(); // throws Exception in case anything goes wrong
try {
if ( props.useDBCache() && meta instanceof TransMeta ) {
( (TransMeta) meta ).getDbCache().saveCache();
}
} catch ( KettleException e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorSavingDatabaseCache.Title" ),
// "An error occurred saving the database cache to disk"
BaseMessages.getString( PKG, "Spoon.Dialog.ErrorSavingDatabaseCache.Message" ), e );
}
delegates.tabs.renameTabs(); // filename or name of transformation might
// have changed.
refreshTree();
// Update menu status for the newly saved object
enableMenus();
return saved;
}
public boolean saveToRepository( EngineMetaInterface meta ) throws KettleException {
return saveToRepository( meta, meta.getObjectId() == null );
}
public boolean saveToRepository( EngineMetaInterface meta, boolean ask_name ) throws KettleException {
// Verify repository security first...
//
if ( meta.getFileType().equals( LastUsedFile.FILE_TYPE_TRANSFORMATION ) ) {
if ( RepositorySecurityUI.verifyOperations( shell, rep, RepositoryOperation.MODIFY_TRANSFORMATION ) ) {
return false;
}
}
if ( meta.getFileType().equals( LastUsedFile.FILE_TYPE_JOB ) ) {
if ( RepositorySecurityUI.verifyOperations( shell, rep, RepositoryOperation.MODIFY_JOB ) ) {
return false;
}
}
if ( log.isDetailed() ) {
// "Save to repository..."
//
log.logDetailed( BaseMessages.getString( PKG, "Spoon.Log.SaveToRepository" ) );
}
if ( rep != null ) {
boolean answer = true;
boolean ask = ask_name;
// If the repository directory is root then get the default save directory
if ( meta.getRepositoryDirectory() == null || meta.getRepositoryDirectory().isRoot() ) {
meta.setRepositoryDirectory( rep.getDefaultSaveDirectory( meta ) );
}
while ( answer && ( ask || Const.isEmpty( meta.getName() ) ) ) {
if ( !ask ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_WARNING );
// "Please give this transformation a name before saving it in the database."
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.PromptTransformationName.Message" ) );
// "Transformation has no name."
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.PromptTransformationName.Title" ) );
mb.open();
}
ask = false;
if ( meta instanceof TransMeta ) {
answer = TransGraph.editProperties( (TransMeta) meta, this, rep, false );
}
if ( meta instanceof JobMeta ) {
answer = JobGraph.editProperties( (JobMeta) meta, this, rep, false );
}
}
if ( answer && !Const.isEmpty( meta.getName() ) ) {
int response = SWT.YES;
ObjectId existingId = null;
if ( meta instanceof TransMeta ) {
existingId = rep.getTransformationID( meta.getName(), meta.getRepositoryDirectory() );
}
if ( meta instanceof JobMeta ) {
existingId = rep.getJobId( meta.getName(), meta.getRepositoryDirectory() );
}
// If there is no object id (import from XML) and there is an existing object.
//
// or...
//
// If the transformation/job has an object id and it's different from the one in the repository.
//
if ( ( meta.getObjectId() == null && existingId != null )
|| existingId != null && !meta.getObjectId().equals( existingId ) ) {
// In case we support revisions, we can simply overwrite
// without a problem so we simply don't ask.
// However, if we import from a file we should ask.
//
if ( !rep.getRepositoryMeta().getRepositoryCapabilities().supportsRevisions()
|| meta.getObjectId() == null ) {
MessageBox mb = new MessageBox( shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION );
// There already is a transformation called ... in the repository.
// Do you want to overwrite the transformation?
//
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.PromptOverwriteTransformation.Message", meta
.getName(), Const.CR ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.PromptOverwriteTransformation.Title" ) );
response = mb.open();
}
}
boolean saved = false;
if ( response == SWT.YES ) {
if ( meta.getObjectId() == null ) {
meta.setObjectId( existingId );
}
try {
shell.setCursor( cursor_hourglass );
// Keep info on who & when this transformation was
// created and or modified...
if ( meta.getCreatedDate() == null ) {
meta.setCreatedDate( new Date() );
if ( capabilities.supportsUsers() ) {
meta.setCreatedUser( rep.getUserInfo().getLogin() );
}
}
// Keep info on who & when this transformation was
// changed...
meta.setModifiedDate( new Date() );
if ( capabilities.supportsUsers() ) {
meta.setModifiedUser( rep.getUserInfo().getLogin() );
}
boolean versioningEnabled = true;
boolean versionCommentsEnabled = true;
String fullPath = meta.getRepositoryDirectory() + "/" + meta.getName() + meta.getRepositoryElementType().getExtension();
RepositorySecurityProvider repositorySecurityProvider =
rep != null && rep.getSecurityProvider() != null ? rep.getSecurityProvider() : null;
if ( repositorySecurityProvider != null ) {
versioningEnabled = repositorySecurityProvider.isVersioningEnabled( fullPath );
versionCommentsEnabled = repositorySecurityProvider.allowsVersionComments( fullPath );
}
// Finally before saving, ask for a version comment (if
// applicable)
//
String versionComment = null;
boolean versionOk;
if ( !versioningEnabled || !versionCommentsEnabled ) {
versionOk = true;
versionComment = "";
} else {
versionOk = false;
}
while ( !versionOk ) {
versionComment = RepositorySecurityUI.getVersionComment( shell, rep, meta.getName(), fullPath, false );
// if the version comment is null, the user hit cancel, exit.
if ( rep != null && rep.getSecurityProvider() != null
&& rep.getSecurityProvider().allowsVersionComments( fullPath ) && versionComment == null ) {
return false;
}
if ( Const.isEmpty( versionComment ) && rep.getSecurityProvider().isVersioningEnabled( fullPath )
&& rep.getSecurityProvider().isVersionCommentMandatory() ) {
if ( !RepositorySecurityUI.showVersionCommentMandatoryDialog( shell ) ) {
return false; // no, I don't want to enter a
// version comment and yes,
// it's mandatory.
}
} else {
versionOk = true;
}
}
if ( versionOk ) {
SaveProgressDialog spd = new SaveProgressDialog( shell, rep, meta, versionComment );
if ( spd.open() ) {
saved = true;
if ( !props.getSaveConfirmation() ) {
MessageDialogWithToggle md =
new MessageDialogWithToggle(
shell, BaseMessages.getString( PKG, "Spoon.Message.Warning.SaveOK" ), null, BaseMessages
.getString( PKG, "Spoon.Message.Warning.TransformationWasStored" ),
MessageDialog.QUESTION, new String[] {
BaseMessages.getString( PKG, "Spoon.Message.Warning.OK" ) },
0,
BaseMessages.getString( PKG, "Spoon.Message.Warning.NotShowThisMessage" ),
props.getSaveConfirmation() );
MessageDialogWithToggle.setDefaultImage( GUIResource.getInstance().getImageSpoon() );
md.open();
props.setSaveConfirmation( md.getToggleState() );
}
// Handle last opened files...
props.addLastFile(
meta.getFileType(), meta.getName(), meta.getRepositoryDirectory().getPath(), true,
getRepositoryName() );
saveSettings();
addMenuLast();
setShellText();
}
}
} finally {
shell.setCursor( null );
}
}
return saved;
}
} else {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
// "There is no repository connection available."
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.NoRepositoryConnection.Message" ) );
// "No repository available."
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.NoRepositoryConnection.Title" ) );
mb.open();
}
return false;
}
public boolean saveJobRepository( JobMeta jobMeta ) throws KettleException {
return saveToRepository( jobMeta, false );
}
public boolean saveJobRepository( JobMeta jobMeta, boolean ask_name ) throws KettleException {
return saveToRepository( jobMeta, ask_name );
}
public boolean saveFileAs() throws KettleException {
try {
EngineMetaInterface meta = getActiveMeta();
if ( meta != null ) {
if ( meta.canSave() ) {
return saveFileAs( meta );
}
}
} catch ( Exception e ) {
KettleRepositoryLostException krle = KettleRepositoryLostException.lookupStackStrace( e );
if ( krle != null ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "Spoon.File.Save.Fail.Title" ),
krle.getPrefaceMessage(),
krle );
closeRepository();
} else {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "Spoon.File.Save.Fail.Title" ),
BaseMessages.getString( PKG, "Spoon.File.Save.Fail.Message" ), e );
}
}
return false;
}
public boolean saveFileAs( EngineMetaInterface meta ) throws KettleException {
boolean saved;
if ( log.isBasic() ) {
log.logBasic( BaseMessages.getString( PKG, "Spoon.Log.SaveAs" ) ); // "Save as..."
}
String activePerspectiveId = SpoonPerspectiveManager.getInstance().getActivePerspective().getId();
boolean etlPerspective = activePerspectiveId.equals( MainSpoonPerspective.ID );
if ( rep != null && etlPerspective ) {
meta.setObjectId( null );
saved = saveToRepository( meta, true );
} else {
saved = saveXMLFile( meta, false );
}
delegates.tabs.renameTabs(); // filename or name of transformation might
// have changed.
refreshTree();
if ( saved && ( meta instanceof TransMeta || meta instanceof JobMeta ) ) {
TabMapEntry tabEntry = delegates.tabs.findTabMapEntry( meta );
TabItem tabItem = tabEntry.getTabItem();
if ( meta.getFileType().equals( LastUsedFile.FILE_TYPE_TRANSFORMATION ) ) {
tabItem.setImage( GUIResource.getInstance().getImageTransGraph() );
} else if ( meta.getFileType().equals( LastUsedFile.FILE_TYPE_JOB ) ) {
tabItem.setImage( GUIResource.getInstance().getImageJobGraph() );
}
}
// Update menu status for the newly saved object
enableMenus();
return saved;
}
public boolean exportXMLFile() {
return saveXMLFile( true );
}
/**
* Export this job or transformation including all depending resources to a single zip file.
*/
public void exportAllXMLFile() {
ResourceExportInterface resourceExportInterface = getActiveTransformation();
if ( resourceExportInterface == null ) {
resourceExportInterface = getActiveJob();
}
if ( resourceExportInterface == null ) {
return; // nothing to do here, prevent an NPE
}
// ((VariableSpace)resourceExportInterface).getVariable("Internal.Transformation.Filename.Directory");
// Ask the user for a zip file to export to:
//
try {
String zipFilename = null;
while ( Const.isEmpty( zipFilename ) ) {
FileDialog dialog = new FileDialog( shell, SWT.SAVE );
dialog.setText( BaseMessages.getString( PKG, "Spoon.ExportResourceSelectZipFile" ) );
dialog.setFilterExtensions( new String[] { "*.zip;*.ZIP", "*" } );
dialog.setFilterNames( new String[] {
BaseMessages.getString( PKG, "System.FileType.ZIPFiles" ),
BaseMessages.getString( PKG, "System.FileType.AllFiles" ), } );
setFilterPath( dialog );
if ( dialog.open() != null ) {
lastDirOpened = dialog.getFilterPath();
zipFilename = dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName();
FileObject zipFileObject = KettleVFS.getFileObject( zipFilename );
if ( zipFileObject.exists() ) {
MessageBox box = new MessageBox( shell, SWT.YES | SWT.NO | SWT.CANCEL );
box
.setMessage( BaseMessages
.getString( PKG, "Spoon.ExportResourceZipFileExists.Message", zipFilename ) );
box.setText( BaseMessages.getString( PKG, "Spoon.ExportResourceZipFileExists.Title" ) );
int answer = box.open();
if ( answer == SWT.CANCEL ) {
return;
}
if ( answer == SWT.NO ) {
zipFilename = null;
}
}
} else {
return;
}
}
// Export the resources linked to the currently loaded file...
//
TopLevelResource topLevelResource =
ResourceUtil.serializeResourceExportInterface(
zipFilename, resourceExportInterface, (VariableSpace) resourceExportInterface, rep, metaStore );
String message =
ResourceUtil.getExplanation( zipFilename, topLevelResource.getResourceName(), resourceExportInterface );
/*
* // Add the ZIP file as a repository to the repository list... // RepositoriesMeta repositoriesMeta = new
* RepositoriesMeta(); repositoriesMeta.readData();
*
* KettleFileRepositoryMeta fileRepositoryMeta = new KettleFileRepositoryMeta(
* KettleFileRepositoryMeta.REPOSITORY_TYPE_ID, "Export " + baseFileName, "Export to file : " + zipFilename,
* "zip://" + zipFilename + "!"); fileRepositoryMeta.setReadOnly(true); // A ZIP file is read-only int nr = 2;
* String baseName = fileRepositoryMeta.getName(); while
* (repositoriesMeta.findRepository(fileRepositoryMeta.getName()) != null) { fileRepositoryMeta.setName(baseName +
* " " + nr); nr++; }
*
* repositoriesMeta.addRepository(fileRepositoryMeta); repositoriesMeta.writeData();
*/
// Show some information concerning all this work...
EnterTextDialog enterTextDialog =
new EnterTextDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ResourceSerialized" ), BaseMessages.getString(
PKG, "Spoon.Dialog.ResourceSerializedSuccesfully" ), message );
enterTextDialog.setReadOnly();
enterTextDialog.open();
} catch ( Exception e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Error" ), BaseMessages.getString(
PKG, "Spoon.ErrorExportingFile" ), e );
}
}
/**
* Export this job or transformation including all depending resources to a single ZIP file containing a file
* repository.
*/
public void exportAllFileRepository() {
ResourceExportInterface resourceExportInterface = getActiveTransformation();
if ( resourceExportInterface == null ) {
resourceExportInterface = getActiveJob();
}
if ( resourceExportInterface == null ) {
return; // nothing to do here, prevent an NPE
}
// Ask the user for a zip file to export to:
//
try {
String zipFilename = null;
while ( Const.isEmpty( zipFilename ) ) {
FileDialog dialog = new FileDialog( shell, SWT.SAVE );
dialog.setText( BaseMessages.getString( PKG, "Spoon.ExportResourceSelectZipFile" ) );
dialog.setFilterExtensions( new String[] { "*.zip;*.ZIP", "*" } );
dialog.setFilterNames( new String[] {
BaseMessages.getString( PKG, "System.FileType.ZIPFiles" ),
BaseMessages.getString( PKG, "System.FileType.AllFiles" ), } );
setFilterPath( dialog );
if ( dialog.open() != null ) {
lastDirOpened = dialog.getFilterPath();
zipFilename = dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName();
FileObject zipFileObject = KettleVFS.getFileObject( zipFilename );
if ( zipFileObject.exists() ) {
MessageBox box = new MessageBox( shell, SWT.YES | SWT.NO | SWT.CANCEL );
box
.setMessage( BaseMessages
.getString( PKG, "Spoon.ExportResourceZipFileExists.Message", zipFilename ) );
box.setText( BaseMessages.getString( PKG, "Spoon.ExportResourceZipFileExists.Title" ) );
int answer = box.open();
if ( answer == SWT.CANCEL ) {
return;
}
if ( answer == SWT.NO ) {
zipFilename = null;
}
}
} else {
return;
}
}
// Export the resources linked to the currently loaded file...
//
TopLevelResource topLevelResource =
ResourceUtil.serializeResourceExportInterface(
zipFilename, resourceExportInterface, (VariableSpace) resourceExportInterface, rep, metaStore );
String message =
ResourceUtil.getExplanation( zipFilename, topLevelResource.getResourceName(), resourceExportInterface );
/*
* // Add the ZIP file as a repository to the repository list... // RepositoriesMeta repositoriesMeta = new
* RepositoriesMeta(); repositoriesMeta.readData();
*
* KettleFileRepositoryMeta fileRepositoryMeta = new KettleFileRepositoryMeta(
* KettleFileRepositoryMeta.REPOSITORY_TYPE_ID, "Export " + baseFileName, "Export to file : " + zipFilename,
* "zip://" + zipFilename + "!"); fileRepositoryMeta.setReadOnly(true); // A ZIP file is read-only int nr = 2;
* String baseName = fileRepositoryMeta.getName(); while
* (repositoriesMeta.findRepository(fileRepositoryMeta.getName()) != null) { fileRepositoryMeta.setName(baseName +
* " " + nr); nr++; }
*
* repositoriesMeta.addRepository(fileRepositoryMeta); repositoriesMeta.writeData();
*/
// Show some information concerning all this work...
//
EnterTextDialog enterTextDialog =
new EnterTextDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ResourceSerialized" ), BaseMessages.getString(
PKG, "Spoon.Dialog.ResourceSerializedSuccesfully" ), message );
enterTextDialog.setReadOnly();
enterTextDialog.open();
} catch ( Exception e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Error" ), BaseMessages.getString(
PKG, "Spoon.ErrorExportingFile" ), e );
}
}
public void exportRepositoryAll() {
exportRepositoryDirectory( null );
}
/**
* @param directoryToExport
* set to null to export the complete repository
* @return false if we want to stop processing. true if we need to continue.
*/
public boolean exportRepositoryDirectory( RepositoryDirectory directoryToExport ) {
FileDialog dialog = this.getExportFileDialog();
if ( dialog.open() == null ) {
return false;
}
String filename = dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName();
log.logBasic( BaseMessages.getString( PKG, "Spoon.Log.Exporting" ), BaseMessages.getString(
PKG, "Spoon.Log.ExportObjectsToFile", filename ) );
// check if file is exists
MessageBox box = RepositoryExportProgressDialog.checkIsFileIsAcceptable( shell, log, filename );
int answer = ( box == null ) ? SWT.OK : box.open();
if ( answer != SWT.OK ) {
// seems user don't want to overwrite file...
return false;
}
//ok, let's show one more modal dialog, users like modal dialogs.
//They feel that their opinion are important to us.
box =
new MessageBox( shell, SWT.ICON_QUESTION
| SWT.APPLICATION_MODAL | SWT.SHEET | SWT.YES | SWT.NO | SWT.CANCEL );
box.setText( BaseMessages.getString( PKG, "Spoon.QuestionApplyImportRulesToExport.Title" ) );
box.setMessage( BaseMessages.getString( PKG, "Spoon.QuestionApplyImportRulesToExport.Message" ) );
answer = box.open();
if ( answer == SWT.CANCEL ) {
return false;
}
// Get the import rules
//
ImportRules importRules = new ImportRules();
if ( answer == SWT.YES ) {
ImportRulesDialog importRulesDialog = new ImportRulesDialog( shell, importRules );
if ( !importRulesDialog.open() ) {
return false;
}
}
RepositoryExportProgressDialog repd =
new RepositoryExportProgressDialog( shell, rep, directoryToExport, filename, importRules );
repd.open();
return true;
}
/**
* local method to be able to use Spoon localization messages.
* @return
*/
public FileDialog getExportFileDialog() {
FileDialog dialog = new FileDialog( shell, SWT.SAVE | SWT.SINGLE );
dialog.setText( BaseMessages.getString( PKG, "Spoon.SelectAnXMLFileToExportTo.Message" ) );
return dialog;
}
public void importDirectoryToRepository() {
FileDialog dialog = new FileDialog( shell, SWT.OPEN | SWT.MULTI );
dialog.setText( BaseMessages.getString( PKG, "Spoon.SelectAnXMLFileToImportFrom.Message" ) );
if ( dialog.open() == null ) {
return;
}
// Ask for a set of import rules
//
MessageBox box =
new MessageBox( shell, SWT.ICON_QUESTION
| SWT.APPLICATION_MODAL | SWT.SHEET | SWT.YES | SWT.NO | SWT.CANCEL );
box.setText( BaseMessages.getString( PKG, "Spoon.QuestionApplyImportRules.Title" ) );
box.setMessage( BaseMessages.getString( PKG, "Spoon.QuestionApplyImportRules.Message" ) );
int answer = box.open();
if ( answer == SWT.CANCEL ) {
return;
}
// Get the import rules
//
ImportRules importRules = new ImportRules();
if ( answer == SWT.YES ) {
ImportRulesDialog importRulesDialog = new ImportRulesDialog( shell, importRules );
if ( !importRulesDialog.open() ) {
return;
}
}
// Ask for a destination in the repository...
//
SelectDirectoryDialog sdd = new SelectDirectoryDialog( shell, SWT.NONE, rep );
RepositoryDirectoryInterface baseDirectory = sdd.open();
if ( baseDirectory == null ) {
return;
}
// Finally before importing, ask for a version comment (if applicable)
//
String fullPath = baseDirectory.getPath() + "/foo.ktr";
String versionComment = null;
boolean versionOk = false;
while ( !versionOk ) {
versionComment =
RepositorySecurityUI.getVersionComment( shell, rep, "Import of files into ["
+ baseDirectory.getPath() + "]", fullPath, true );
// if the version comment is null, the user hit cancel, exit.
if ( versionComment == null ) {
return;
}
if ( Const.isEmpty( versionComment ) && rep.getSecurityProvider().isVersionCommentMandatory( ) ) {
if ( !RepositorySecurityUI.showVersionCommentMandatoryDialog( shell ) ) {
versionOk = true;
}
} else {
versionOk = true;
}
}
String[] filenames = dialog.getFileNames();
if ( filenames.length > 0 ) {
RepositoryImportProgressDialog ripd =
new RepositoryImportProgressDialog(
shell, SWT.NONE, rep, dialog.getFilterPath(), filenames, baseDirectory, versionComment, importRules );
ripd.open();
refreshTree();
}
}
public boolean saveXMLFile( boolean export ) {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
return saveXMLFile( transMeta, export );
}
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
return saveXMLFile( jobMeta, export );
}
return false;
}
public boolean saveXMLFile( EngineMetaInterface meta, boolean export ) {
if ( log.isBasic() ) {
log.logBasic( "Save file as..." );
}
boolean saved = false;
String beforeFilename = meta.getFilename();
String beforeName = meta.getName();
FileDialog dialog = new FileDialog( shell, SWT.SAVE );
String[] extensions = meta.getFilterExtensions();
dialog.setFilterExtensions( extensions );
dialog.setFilterNames( meta.getFilterNames() );
setFilterPath( dialog );
String filename = dialog.open();
if ( filename != null ) {
lastDirOpened = dialog.getFilterPath();
// Is the filename ending on .ktr, .xml?
boolean ending = false;
for ( int i = 0; i < extensions.length - 1; i++ ) {
String[] parts = extensions[i].split( ";" );
for ( String part : parts ) {
if ( filename.toLowerCase().endsWith( part.substring( 1 ).toLowerCase() ) ) {
ending = true;
}
}
}
if ( filename.endsWith( meta.getDefaultExtension() ) ) {
ending = true;
}
if ( !ending ) {
if ( !meta.getDefaultExtension().startsWith( "." ) && !filename.endsWith( "." ) ) {
filename += ".";
}
filename += meta.getDefaultExtension();
}
// See if the file already exists...
int id = SWT.YES;
try {
FileObject f = KettleVFS.getFileObject( filename );
if ( f.exists() ) {
MessageBox mb = new MessageBox( shell, SWT.NO | SWT.YES | SWT.ICON_WARNING );
// "This file already exists. Do you want to overwrite it?"
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.PromptOverwriteFile.Message" ) );
// "This file already exists!"
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.PromptOverwriteFile.Title" ) );
id = mb.open();
}
} catch ( Exception e ) {
// TODO do we want to show an error dialog here? My first guess
// is not, but we might.
}
if ( id == SWT.YES ) {
if ( !export && !Const.isEmpty( beforeFilename ) && !beforeFilename.equals( filename ) ) {
meta.setName( Const.createName( filename ) );
meta.setFilename( filename );
// If the user hits cancel here, don't save anything
//
if ( !editProperties() ) {
// Revert the changes!
//
meta.setFilename( beforeFilename );
meta.setName( beforeName );
return saved;
}
}
saved = save( meta, filename, export );
if ( !saved ) {
meta.setFilename( beforeFilename );
meta.setName( beforeName );
}
}
}
return saved;
}
public boolean saveXMLFileToVfs() {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
return saveXMLFileToVfs( transMeta );
}
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
return saveXMLFileToVfs( jobMeta );
}
return false;
}
public boolean saveXMLFileToVfs( EngineMetaInterface meta ) {
if ( log.isBasic() ) {
log.logBasic( "Save file as..." );
}
FileObject rootFile;
FileObject initialFile;
try {
initialFile = KettleVFS.getFileObject( getLastFileOpened() );
rootFile = KettleVFS.getFileObject( getLastFileOpened() ).getFileSystem().getRoot();
} catch ( Exception e ) {
MessageBox messageDialog = new MessageBox( shell, SWT.ICON_ERROR | SWT.OK );
messageDialog.setText( "Error" );
messageDialog.setMessage( e.getMessage() );
messageDialog.open();
return false;
}
String filename = null;
FileObject selectedFile =
getVfsFileChooserDialog( rootFile, initialFile ).open(
shell, "Untitled", Const.STRING_TRANS_AND_JOB_FILTER_EXT, Const.getTransformationAndJobFilterNames(),
VfsFileChooserDialog.VFS_DIALOG_SAVEAS );
if ( selectedFile != null ) {
filename = selectedFile.getName().getFriendlyURI();
}
String[] extensions = meta.getFilterExtensions();
if ( filename != null ) {
// Is the filename ending on .ktr, .xml?
boolean ending = false;
for ( int i = 0; i < extensions.length - 1; i++ ) {
if ( filename.endsWith( extensions[i].substring( 1 ) ) ) {
ending = true;
}
}
if ( filename.endsWith( meta.getDefaultExtension() ) ) {
ending = true;
}
if ( !ending ) {
filename += '.' + meta.getDefaultExtension();
}
// See if the file already exists...
int id = SWT.YES;
try {
FileObject f = KettleVFS.getFileObject( filename );
if ( f.exists() ) {
MessageBox mb = new MessageBox( shell, SWT.NO | SWT.YES | SWT.ICON_WARNING );
// "This file already exists. Do you want to overwrite it?"
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.PromptOverwriteFile.Message" ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.PromptOverwriteFile.Title" ) );
id = mb.open();
}
} catch ( Exception e ) {
// TODO do we want to show an error dialog here? My first guess
// is not, but we might.
}
if ( id == SWT.YES ) {
save( meta, filename, false );
}
}
return false;
}
public boolean save( EngineMetaInterface meta, String filename, boolean export ) {
boolean saved = false;
// the only file types that are subject to ascii-only rule are those that are not trans and not job
boolean isNotTransOrJob =
!LastUsedFile.FILE_TYPE_TRANSFORMATION.equals( meta.getFileType() )
&& !LastUsedFile.FILE_TYPE_JOB.equals( meta.getFileType() );
if ( isNotTransOrJob ) {
Pattern pattern = Pattern.compile( "\\p{ASCII}+" );
Matcher matcher = pattern.matcher( filename );
if ( !matcher.matches() ) {
/*
* Temporary fix for AGILEBI-405 Don't allow saving of files that contain special characters until AGILEBI-394
* is resolved. AGILEBI-394 Naming an analyzer report with spanish accents gives error when publishing.
*/
MessageBox box = new MessageBox( staticSpoon.shell, SWT.ICON_ERROR | SWT.OK );
box.setMessage( "Special characters are not allowed in the filename. Please use ASCII characters only" );
box.setText( BaseMessages.getString( PKG, "Spoon.Dialog.ErrorSavingConnection.Title" ) );
box.open();
return false;
}
}
FileListener listener = null;
// match by extension first
int idx = filename.lastIndexOf( '.' );
if ( idx != -1 ) {
String extension = filename.substring( idx + 1 );
listener = fileExtensionMap.get( extension );
}
if ( listener == null ) {
String xt = meta.getDefaultExtension();
listener = fileExtensionMap.get( xt );
}
if ( listener != null ) {
String sync = BasePropertyHandler.getProperty( SYNC_TRANS );
if ( Boolean.parseBoolean( sync ) ) {
listener.syncMetaName( meta, Const.createName( filename ) );
delegates.tabs.renameTabs();
}
saved = listener.save( meta, filename, export );
}
return saved;
}
public boolean saveMeta( EngineMetaInterface meta, String filename ) {
meta.setFilename( filename );
if ( Const.isEmpty( meta.getName() )
|| delegates.jobs.isDefaultJobName( meta.getName() )
|| delegates.trans.isDefaultTransformationName( meta.getName() ) ) {
meta.nameFromFilename();
}
boolean saved = false;
try {
String xml = XMLHandler.getXMLHeader() + meta.getXML();
DataOutputStream dos = new DataOutputStream( KettleVFS.getOutputStream( filename, false ) );
dos.write( xml.getBytes( Const.XML_ENCODING ) );
dos.close();
saved = true;
// Handle last opened files...
props.addLastFile( meta.getFileType(), filename, null, false, null );
saveSettings();
addMenuLast();
if ( log.isDebug() ) {
log.logDebug( BaseMessages.getString( PKG, "Spoon.Log.FileWritten" ) + " [" + filename + "]" ); // "File
}
// written
// to
meta.setFilename( filename );
meta.clearChanged();
setShellText();
} catch ( Exception e ) {
if ( log.isDebug() ) {
// "Error opening file for writing! --> "
log.logDebug( BaseMessages.getString( PKG, "Spoon.Log.ErrorOpeningFileForWriting" ) + e.toString() );
}
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorSavingFile.Title" ),
BaseMessages.getString( PKG, "Spoon.Dialog.ErrorSavingFile.Message" )
+ Const.CR + e.toString(), e );
}
return saved;
}
public void helpAbout() {
try {
AboutDialog aboutDialog = new AboutDialog( getShell() );
aboutDialog.open();
} catch ( KettleException e ) {
log.logError( "Error opening about dialog", e );
}
}
/**
* Show a plugin browser
*/
public void showPluginInfo() {
try {
// First we collect information concerning all the plugin types...
//
Map<String, RowMetaInterface> metaMap = new HashMap<String, RowMetaInterface>();
Map<String, List<Object[]>> dataMap = new HashMap<String, List<Object[]>>();
PluginRegistry registry = PluginRegistry.getInstance();
List<Class<? extends PluginTypeInterface>> pluginTypeClasses = registry.getPluginTypes();
for ( Class<? extends PluginTypeInterface> pluginTypeClass : pluginTypeClasses ) {
PluginTypeInterface pluginTypeInterface = registry.getPluginType( pluginTypeClass );
String subject = pluginTypeInterface.getName();
RowBuffer pluginInformation = registry.getPluginInformation( pluginTypeClass );
metaMap.put( subject, pluginInformation.getRowMeta() );
dataMap.put( subject, pluginInformation.getBuffer() );
}
// Now push it all to a subject data browser...
//
SubjectDataBrowserDialog dialog =
new SubjectDataBrowserDialog( shell, metaMap, dataMap, "Plugin browser", "Plugin type" );
dialog.open();
} catch ( Exception e ) {
new ErrorDialog( shell, "Error", "Error listing plugins", e );
}
}
public void editUnselectAll() {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
transMeta.unselectAll();
getActiveTransGraph().redraw();
}
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
jobMeta.unselectAll();
getActiveJobGraph().redraw();
}
}
public void editSelectAll() {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
transMeta.selectAll();
getActiveTransGraph().redraw();
}
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
jobMeta.selectAll();
getActiveJobGraph().redraw();
}
}
public void editOptions() {
EnterOptionsDialog eod = new EnterOptionsDialog( shell );
if ( eod.open() != null ) {
props.saveProps();
loadSettings();
changeLooks();
MessageBox mb = new MessageBox( shell, SWT.ICON_INFORMATION );
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.PleaseRestartApplication.Message" ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.PleaseRestartApplication.Title" ) );
mb.open();
}
}
public void editCapabilities() {
CapabilityManagerDialog capabilityManagerDialog = new CapabilityManagerDialog( this.shell );
capabilityManagerDialog.open();
}
public void editKettlePropertiesFile() {
KettlePropertiesFileDialog dialog = new KettlePropertiesFileDialog( shell, SWT.NONE );
Map<String, String> newProperties = dialog.open();
if ( newProperties != null ) {
for ( String name : newProperties.keySet() ) {
String value = newProperties.get( name );
applyVariableToAllLoadedObjects( name, value );
// Also set as a JVM property
//
System.setProperty( name, value );
}
}
}
/**
* Matches if the filter is non-empty
*
* @param string string to match
* @return true in case string matches filter
*/
@VisibleForTesting boolean filterMatch( String string ) {
if ( Const.isEmpty( string ) ) {
return true;
}
String filter = selectionFilter.getText();
if ( Const.isEmpty( filter ) ) {
return true;
}
try {
if ( string.matches( filter ) ) {
return true;
}
} catch ( Exception e ) {
log.logError( "Not a valid pattern [" + filter + "] : " + e.getMessage() );
}
return string.toUpperCase().contains( filter.toUpperCase() );
}
private void createSelectionTree() {
// //////////////////////////////////////////////////////////////////////////////////////////////////
//
// Now set up the transformation/job tree
//
selectionTree = new Tree( variableComposite, SWT.SINGLE );
props.setLook( selectionTree );
selectionTree.setLayout( new FillLayout() );
addDefaultKeyListeners( selectionTree );
/*
* ExpandItem treeItem = new ExpandItem(mainExpandBar, SWT.NONE); treeItem.setControl(selectionTree);
* treeItem.setHeight(shell.getBounds().height); setHeaderImage(treeItem,
* GUIResource.getInstance().getImageLogoSmall(), STRING_SPOON_MAIN_TREE, 0, true);
*/
// Add a tree memory as well...
TreeMemory.addTreeListener( selectionTree, STRING_SPOON_MAIN_TREE );
selectionTree.addMenuDetectListener( new MenuDetectListener() {
public void menuDetected( MenuDetectEvent e ) {
setMenu( selectionTree );
}
} );
selectionTree.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent e ) {
showSelection();
}
public void widgetDefaultSelected( SelectionEvent e ) {
doubleClickedInTree( selectionTree );
}
} );
// Set a listener on the tree
addDragSourceToTree( selectionTree );
}
/**
* Refresh the object selection tree (on the left of the screen)
*/
public void refreshTree() {
if ( shell.isDisposed() || !viewSelected ) {
return;
}
if ( selectionTree == null || selectionTree.isDisposed() ) {
createSelectionTree();
}
GUIResource guiResource = GUIResource.getInstance();
TransMeta activeTransMeta = getActiveTransformation();
JobMeta activeJobMeta = getActiveJob();
boolean showAll = activeTransMeta == null && activeJobMeta == null;
// get a list of transformations from the transformation map
//
/*
* List<TransMeta> transformations = delegates.trans.getTransformationList(); Collections.sort(transformations);
* TransMeta[] transMetas = transformations.toArray(new TransMeta[transformations.size()]);
*
* // get a list of jobs from the job map List<JobMeta> jobs = delegates.jobs.getJobList(); Collections.sort(jobs);
* JobMeta[] jobMetas = jobs.toArray(new JobMeta[jobs.size()]);
*/
// Refresh the content of the tree for those transformations
//
// First remove the old ones.
selectionTree.removeAll();
// Now add the data back
//
if ( !props.isOnlyActiveFileShownInTree() || showAll || activeTransMeta != null ) {
TreeItem tiTrans = new TreeItem( selectionTree, SWT.NONE );
tiTrans.setText( STRING_TRANSFORMATIONS );
tiTrans.setImage( GUIResource.getInstance().getImageFolder() );
// Set expanded if this is the only transformation shown.
if ( props.isOnlyActiveFileShownInTree() ) {
TreeMemory.getInstance().storeExpanded( STRING_SPOON_MAIN_TREE, tiTrans, true );
}
for ( TabMapEntry entry : delegates.tabs.getTabs() ) {
Object managedObject = entry.getObject().getManagedObject();
if ( managedObject instanceof TransMeta ) {
TransMeta transMeta = (TransMeta) managedObject;
if ( !props.isOnlyActiveFileShownInTree()
|| showAll || ( activeTransMeta != null && activeTransMeta.equals( transMeta ) ) ) {
// Add a tree item with the name of transformation
//
String name = delegates.tabs.makeTabName( transMeta, entry.isShowingLocation() );
if ( Const.isEmpty( name ) ) {
name = STRING_TRANS_NO_NAME;
}
TreeItem tiTransName = createTreeItem( tiTrans, name, guiResource.getImageTransTree() );
// Set expanded if this is the only transformation
// shown.
if ( props.isOnlyActiveFileShownInTree() ) {
TreeMemory.getInstance().storeExpanded( STRING_SPOON_MAIN_TREE, tiTransName, true );
}
refreshDbConnectionsSubtree( tiTransName, transMeta, guiResource );
refreshStepsSubtree( tiTransName, transMeta, guiResource );
refreshHopsSubtree( tiTransName, transMeta, guiResource );
refreshPartitionsSubtree( tiTransName, transMeta, guiResource );
refreshSlavesSubtree( tiTransName, transMeta, guiResource );
refreshClustersSubtree( tiTransName, transMeta, guiResource );
refreshSelectionTreeExtension( tiTransName, transMeta, guiResource );
}
}
}
}
if ( !props.isOnlyActiveFileShownInTree() || showAll || activeJobMeta != null ) {
TreeItem tiJobs = new TreeItem( selectionTree, SWT.NONE );
tiJobs.setText( STRING_JOBS );
tiJobs.setImage( GUIResource.getInstance().getImageFolder() );
// Set expanded if this is the only job shown.
if ( props.isOnlyActiveFileShownInTree() ) {
tiJobs.setExpanded( true );
TreeMemory.getInstance().storeExpanded( STRING_SPOON_MAIN_TREE, tiJobs, true );
}
// Now add the jobs
//
for ( TabMapEntry entry : delegates.tabs.getTabs() ) {
Object managedObject = entry.getObject().getManagedObject();
if ( managedObject instanceof JobMeta ) {
JobMeta jobMeta = (JobMeta) managedObject;
if ( !props.isOnlyActiveFileShownInTree()
|| showAll || ( activeJobMeta != null && activeJobMeta.equals( jobMeta ) ) ) {
// Add a tree item with the name of job
//
String name = delegates.tabs.makeTabName( jobMeta, entry.isShowingLocation() );
if ( Const.isEmpty( name ) ) {
name = STRING_JOB_NO_NAME;
}
if ( !filterMatch( name ) ) {
continue;
}
TreeItem tiJobName = createTreeItem( tiJobs, name, guiResource.getImageJobTree() );
// Set expanded if this is the only job shown.
if ( props.isOnlyActiveFileShownInTree() ) {
TreeMemory.getInstance().storeExpanded( STRING_SPOON_MAIN_TREE, tiJobName, true );
}
refreshDbConnectionsSubtree( tiJobName, jobMeta, guiResource );
refreshJobEntriesSubtree( tiJobName, jobMeta, guiResource );
refreshSelectionTreeExtension( tiJobName, jobMeta, guiResource );
refreshSlavesSubtree( tiJobName, jobMeta, guiResource );
}
}
}
}
// Set the expanded state of the complete tree.
TreeMemory.setExpandedFromMemory( selectionTree, STRING_SPOON_MAIN_TREE );
// refreshCoreObjectsHistory();
selectionTree.setFocus();
selectionTree.layout();
variableComposite.layout( true, true );
setShellText();
}
@VisibleForTesting TreeItem createTreeItem( TreeItem parent, String text, Image image ) {
TreeItem item = new TreeItem( parent, SWT.NONE );
item.setText( text );
item.setImage( image );
return item;
}
@VisibleForTesting void refreshDbConnectionsSubtree( TreeItem tiRootName, AbstractMeta meta,
GUIResource guiResource ) {
TreeItem tiDbTitle = createTreeItem( tiRootName, STRING_CONNECTIONS, guiResource.getImageFolder() );
DatabasesCollector collector = new DatabasesCollector( meta, rep );
try {
collector.collectDatabases();
} catch ( KettleException e ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "Spoon.ErrorDialog.Title" ),
BaseMessages.getString( PKG, "Spoon.ErrorDialog.ErrorFetchingFromRepo.DbConnections" ),
e
);
return;
}
for ( String dbName : collector.getDatabaseNames() ) {
if ( !filterMatch( dbName ) ) {
continue;
}
DatabaseMeta databaseMeta = collector.getMetaFor( dbName );
TreeItem tiDb = createTreeItem( tiDbTitle, databaseMeta.getDisplayName(), guiResource.getImageConnectionTree() );
if ( databaseMeta.isShared() ) {
tiDb.setFont( guiResource.getFontBold() );
}
}
}
private void refreshStepsSubtree( TreeItem tiRootName, TransMeta meta, GUIResource guiResource ) {
TreeItem tiStepTitle = createTreeItem( tiRootName, STRING_STEPS, guiResource.getImageFolder() );
// Put the steps below it.
for ( int i = 0; i < meta.nrSteps(); i++ ) {
StepMeta stepMeta = meta.getStep( i );
PluginInterface stepPlugin =
PluginRegistry.getInstance().findPluginWithId( StepPluginType.class, stepMeta.getStepID() );
if ( !filterMatch( stepMeta.getName() ) ) {
continue;
}
Image stepIcon = guiResource.getImagesStepsSmall().get( stepPlugin.getIds()[ 0 ] );
if ( stepIcon == null ) {
stepIcon = guiResource.getImageFolder();
}
TreeItem tiStep = createTreeItem( tiStepTitle, stepMeta.getName(), stepIcon );
if ( stepMeta.isShared() ) {
tiStep.setFont( guiResource.getFontBold() );
}
if ( !stepMeta.isDrawn() ) {
tiStep.setForeground( guiResource.getColorDarkGray() );
}
}
}
@VisibleForTesting void refreshHopsSubtree( TreeItem tiTransName, TransMeta transMeta, GUIResource guiResource ) {
TreeItem tiHopTitle = createTreeItem( tiTransName, STRING_HOPS, guiResource.getImageFolder() );
// Put the steps below it.
for ( int i = 0; i < transMeta.nrTransHops(); i++ ) {
TransHopMeta hopMeta = transMeta.getTransHop( i );
if ( !filterMatch( hopMeta.toString() ) ) {
continue;
}
Image icon = hopMeta.isEnabled() ? guiResource.getImageHopTree() : guiResource.getImageDisabledHopTree();
createTreeItem( tiHopTitle, hopMeta.toString(), icon );
}
}
@Override public List<String> getPartitionSchemasNames( TransMeta transMeta ) throws KettleException {
return Arrays.asList( pickupPartitionSchemaNames( transMeta ) );
}
private String[] pickupPartitionSchemaNames( TransMeta transMeta ) throws KettleException {
return ( rep == null ) ? transMeta.getPartitionSchemasNames() : rep.getPartitionSchemaNames( false );
}
@Override public List<PartitionSchema> getPartitionSchemas( TransMeta transMeta ) throws KettleException {
return pickupPartitionSchemas( transMeta );
}
private List<PartitionSchema> pickupPartitionSchemas( TransMeta transMeta ) throws KettleException {
if ( rep != null ) {
ObjectId[] ids = rep.getPartitionSchemaIDs( false );
List<PartitionSchema> result = new ArrayList<PartitionSchema>( ids.length );
for ( ObjectId id : ids ) {
PartitionSchema schema = rep.loadPartitionSchema( id, null );
result.add( schema );
}
return result;
}
return transMeta.getPartitionSchemas();
}
@VisibleForTesting void refreshPartitionsSubtree( TreeItem tiTransName, TransMeta transMeta, GUIResource guiResource ) {
TreeItem tiPartitionTitle = createTreeItem( tiTransName, STRING_PARTITIONS, guiResource.getImageFolder() );
List<PartitionSchema> partitionSchemas;
try {
partitionSchemas = pickupPartitionSchemas( transMeta );
} catch ( KettleException e ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "Spoon.ErrorDialog.Title" ),
BaseMessages.getString( PKG, "Spoon.ErrorDialog.ErrorFetchingFromRepo.PartitioningSchemas" ),
e
);
return;
}
// Put the steps below it.
for ( PartitionSchema partitionSchema : partitionSchemas ) {
if ( !filterMatch( partitionSchema.getName() ) ) {
continue;
}
TreeItem tiPartition =
createTreeItem( tiPartitionTitle, partitionSchema.getName(), guiResource.getImageFolderConnectionsMedium() );
if ( partitionSchema.isShared() ) {
tiPartition.setFont( guiResource.getFontBold() );
}
}
}
private List<SlaveServer> pickupSlaveServers( AbstractMeta transMeta ) throws KettleException {
return ( rep == null ) ? transMeta.getSlaveServers() : rep.getSlaveServers();
}
@VisibleForTesting void refreshSelectionTreeExtension( TreeItem tiRootName, AbstractMeta meta, GUIResource guiResource ) {
try {
ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.SpoonViewTreeExtension.id,
new SelectionTreeExtension( tiRootName, meta, guiResource, REFRESH_SELECTION_EXTENSION ) );
} catch ( Exception e ) {
log.logError( "Error handling menu right click on job entry through extension point", e );
}
}
@VisibleForTesting void editSelectionTreeExtension( Object selection ) {
try {
ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.SpoonViewTreeExtension.id,
new SelectionTreeExtension( selection, EDIT_SELECTION_EXTENSION ) );
} catch ( Exception e ) {
log.logError( "Error handling menu right click on job entry through extension point", e );
}
}
@VisibleForTesting void createPopUpMenuExtension() {
try {
ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.SpoonPopupMenuExtension.id, selectionTree );
} catch ( Exception e ) {
log.logError( "Error handling menu right click on job entry through extension point", e );
}
}
@VisibleForTesting void refreshSlavesSubtree( TreeItem tiRootName, AbstractMeta meta, GUIResource guiResource ) {
TreeItem tiSlaveTitle = createTreeItem( tiRootName, STRING_SLAVES, guiResource.getImageFolder() );
List<SlaveServer> servers;
try {
servers = pickupSlaveServers( meta );
} catch ( KettleException e ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "Spoon.ErrorDialog.Title" ),
BaseMessages.getString( PKG, "Spoon.ErrorDialog.ErrorFetchingFromRepo.SlaveServers" ),
e
);
return;
}
String[] slaveNames = SlaveServer.getSlaveServerNames( servers );
Arrays.sort( slaveNames, String.CASE_INSENSITIVE_ORDER );
for ( String slaveName : slaveNames ) {
if ( !filterMatch( slaveName ) ) {
continue;
}
SlaveServer slaveServer = SlaveServer.findSlaveServer( servers, slaveName );
TreeItem tiSlave = createTreeItem( tiSlaveTitle, slaveServer.getName(), guiResource.getImageSlaveMedium() );
if ( slaveServer.isShared() ) {
tiSlave.setFont( guiResource.getFontBold() );
}
}
}
@VisibleForTesting void refreshClustersSubtree( TreeItem tiTransName, TransMeta transMeta, GUIResource guiResource ) {
TreeItem tiClusterTitle = createTreeItem( tiTransName, STRING_CLUSTERS, guiResource.getImageFolder() );
// Put the steps below it.
for ( ClusterSchema clusterSchema : transMeta.getClusterSchemas() ) {
if ( !filterMatch( clusterSchema.getName() ) ) {
continue;
}
TreeItem tiCluster = createTreeItem( tiClusterTitle, clusterSchema.toString(), guiResource.getImageClusterMedium() );
if ( clusterSchema.isShared() ) {
tiCluster.setFont( guiResource.getFontBold() );
}
}
}
private void refreshJobEntriesSubtree( TreeItem tiJobName, JobMeta jobMeta, GUIResource guiResource ) {
TreeItem tiJobEntriesTitle = createTreeItem( tiJobName, STRING_JOB_ENTRIES, guiResource.getImageFolder() );
for ( int i = 0; i < jobMeta.nrJobEntries(); i++ ) {
JobEntryCopy jobEntry = jobMeta.getJobEntry( i );
if ( !filterMatch( jobEntry.getName() ) && !filterMatch( jobEntry.getDescription() ) ) {
continue;
}
TreeItem tiJobEntry = ConstUI.findTreeItem( tiJobEntriesTitle, jobEntry.getName() );
if ( tiJobEntry != null ) {
continue; // only show it once
}
// if (jobEntry.isShared())
// tiStep.setFont(guiResource.getFontBold()); TODO:
// allow job entries to be shared as well...
Image icon;
if ( jobEntry.isStart() ) {
icon = GUIResource.getInstance().getImageStartMedium();
} else if ( jobEntry.isDummy() ) {
icon = GUIResource.getInstance().getImageDummyMedium();
} else {
String key = jobEntry.getEntry().getPluginId();
icon = GUIResource.getInstance().getImagesJobentriesSmall().get( key );
}
createTreeItem( tiJobEntriesTitle, jobEntry.getName(), icon );
}
}
public String getActiveTabText() {
if ( tabfolder.getSelected() == null ) {
return null;
}
return tabfolder.getSelected().getText();
}
public void refreshGraph() {
if ( shell.isDisposed() ) {
return;
}
TabItem tabItem = tabfolder.getSelected();
if ( tabItem == null ) {
return;
}
TabMapEntry tabMapEntry = delegates.tabs.getTab( tabItem );
if ( tabMapEntry != null ) {
if ( tabMapEntry.getObject() instanceof TransGraph ) {
TransGraph transGraph = (TransGraph) tabMapEntry.getObject();
transGraph.redraw();
}
if ( tabMapEntry.getObject() instanceof JobGraph ) {
JobGraph jobGraph = (JobGraph) tabMapEntry.getObject();
jobGraph.redraw();
}
}
setShellText();
}
public StepMeta newStep( TransMeta transMeta ) {
return newStep( transMeta, true, true );
}
public StepMeta newStep( TransMeta transMeta, boolean openit, boolean rename ) {
if ( transMeta == null ) {
return null;
}
TreeItem[] ti = selectionTree.getSelection();
StepMeta inf = null;
if ( ti.length == 1 ) {
String stepType = ti[0].getText();
if ( log.isDebug() ) {
log.logDebug( BaseMessages.getString( PKG, "Spoon.Log.NewStep" ) + stepType ); // "New step: "
}
inf = newStep( transMeta, stepType, stepType, openit, rename );
}
return inf;
}
/**
* Allocate new step, optionally open and rename it.
*
* @param name
* Name of the new step
* @param description
* Description of the type of step
* @param openit
* Open the dialog for this step?
* @param rename
* Rename this step?
*
* @return The newly created StepMeta object.
*
*/
public StepMeta newStep( TransMeta transMeta, String name, String description, boolean openit, boolean rename ) {
StepMeta inf = null;
// See if we need to rename the step to avoid doubles!
if ( rename && transMeta.findStep( name ) != null ) {
int i = 2;
String newName = name + " " + i;
while ( transMeta.findStep( newName ) != null ) {
i++;
newName = name + " " + i;
}
name = newName;
}
PluginRegistry registry = PluginRegistry.getInstance();
PluginInterface stepPlugin = null;
try {
stepPlugin = registry.findPluginWithName( StepPluginType.class, description );
if ( stepPlugin != null ) {
StepMetaInterface info = (StepMetaInterface) registry.loadClass( stepPlugin );
info.setDefault();
if ( openit ) {
StepDialogInterface dialog = this.getStepEntryDialog( info, transMeta, name );
if ( dialog != null ) {
name = dialog.open();
}
}
inf = new StepMeta( stepPlugin.getIds()[0], name, info );
if ( name != null ) {
// OK pressed in the dialog: we have a step-name
String newName = name;
StepMeta stepMeta = transMeta.findStep( newName );
int nr = 2;
while ( stepMeta != null ) {
newName = name + " " + nr;
stepMeta = transMeta.findStep( newName );
nr++;
}
if ( nr > 2 ) {
inf.setName( newName );
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
// "This stepName already exists. Spoon changed the stepName to ["+newName+"]"
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.ChangeStepname.Message", newName ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.ChangeStepname.Title" ) );
mb.open();
}
inf.setLocation( 20, 20 ); // default location at (20,20)
transMeta.addStep( inf );
addUndoNew( transMeta, new StepMeta[] { inf }, new int[] { transMeta.indexOfStep( inf ) } );
// Also store it in the pluginHistory list...
props.increasePluginHistory( stepPlugin.getIds()[0] );
// stepHistoryChanged = true;
refreshTree();
} else {
return null; // Cancel pressed in dialog.
}
setShellText();
}
} catch ( KettleException e ) {
String filename = stepPlugin.getErrorHelpFile();
if ( stepPlugin != null && !Const.isEmpty( filename ) ) {
// OK, in stead of a normal error message, we give back the
// content of the error help file... (HTML)
FileInputStream fis = null;
try {
StringBuilder content = new StringBuilder();
fis = new FileInputStream( new File( filename ) );
int ch = fis.read();
while ( ch >= 0 ) {
content.append( (char) ch );
ch = fis.read();
}
ShowBrowserDialog sbd =
new ShowBrowserDialog(
// "Error help text"
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorHelpText.Title" ), content.toString() );
sbd.open();
} catch ( Exception ex ) {
new ErrorDialog( shell,
// "Error showing help text"
BaseMessages.getString( PKG, "Spoon.Dialog.ErrorShowingHelpText.Title" ), BaseMessages.getString(
PKG, "Spoon.Dialog.ErrorShowingHelpText.Message" ), ex );
} finally {
if ( fis != null ) {
try {
fis.close();
} catch ( Exception ex ) {
log.logError( "Error closing plugin help file", ex );
}
}
}
} else {
new ErrorDialog( shell,
// "Error creating step"
// "I was unable to create a new step"
BaseMessages.getString( PKG, "Spoon.Dialog.UnableCreateNewStep.Title" ), BaseMessages.getString(
PKG, "Spoon.Dialog.UnableCreateNewStep.Message" ), e );
}
return null;
} catch ( Throwable e ) {
if ( !shell.isDisposed() ) {
new ErrorDialog( shell,
// "Error creating step"
BaseMessages.getString( PKG, "Spoon.Dialog.ErrorCreatingStep.Title" ), BaseMessages.getString(
PKG, "Spoon.Dialog.UnableCreateNewStep.Message" ), e );
}
return null;
}
return inf;
}
public void setShellText() {
if ( shell.isDisposed() ) {
return;
}
String filename = null;
String name = null;
String version = null;
ChangedFlagInterface changed = null;
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
changed = transMeta;
filename = transMeta.getFilename();
name = transMeta.getName();
version = transMeta.getObjectRevision() == null ? null : transMeta.getObjectRevision().getName();
}
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
changed = jobMeta;
filename = jobMeta.getFilename();
name = jobMeta.getName();
version = jobMeta.getObjectRevision() == null ? null : jobMeta.getObjectRevision().getName();
}
String text = "";
if ( rep != null ) {
text += APP_TITLE + " - [" + getRepositoryName() + "] ";
} else {
text += APP_TITLE + " - ";
}
if ( Const.isEmpty( name ) ) {
if ( !Const.isEmpty( filename ) ) {
text += filename;
} else {
String tab = getActiveTabText();
if ( !Const.isEmpty( tab ) ) {
text += tab;
} else {
text += BaseMessages.getString( PKG, "Spoon.Various.NoName" ); // "[no name]"
}
}
} else {
text += name;
}
if ( !Const.isEmpty( version ) ) {
text += " v" + version;
}
if ( changed != null && changed.hasChanged() ) {
text += " " + BaseMessages.getString( PKG, "Spoon.Various.Changed" );
}
shell.setText( text );
markTabsChanged();
}
public void enableMenus() {
boolean disableTransMenu = getActiveTransformation() == null;
boolean disableJobMenu = getActiveJob() == null;
boolean disableMetaMenu = getActiveMeta() == null;
boolean isRepositoryRunning = rep != null;
boolean disablePreviewButton = true;
String activePerspectiveId = null;
SpoonPerspectiveManager manager = SpoonPerspectiveManager.getInstance();
if ( manager != null && manager.getActivePerspective() != null ) {
activePerspectiveId = manager.getActivePerspective().getId();
}
boolean etlPerspective = false;
if ( activePerspectiveId != null && activePerspectiveId.length() > 0 ) {
etlPerspective = activePerspectiveId.equals( MainSpoonPerspective.ID );
}
TransGraph transGraph = getActiveTransGraph();
if ( transGraph != null ) {
disablePreviewButton = !( transGraph.isRunning() && !transGraph.isHalting() );
}
boolean disableSave = true;
TabItemInterface currentTab = getActiveTabitem();
if ( currentTab != null && currentTab.canHandleSave() ) {
disableSave = !currentTab.hasContentChanged();
}
EngineMetaInterface meta = getActiveMeta();
if ( meta != null ) {
disableSave = !meta.canSave();
}
org.pentaho.ui.xul.dom.Document doc;
if ( mainSpoonContainer != null ) {
doc = mainSpoonContainer.getDocumentRoot();
if ( doc != null ) {
if ( etlPerspective ) {
doc.getElementById( "file" ).setVisible( etlPerspective );
doc.getElementById( "edit" ).setVisible( etlPerspective );
doc.getElementById( "view" ).setVisible( etlPerspective );
doc.getElementById( "action" ).setVisible( etlPerspective );
doc.getElementById( "tools" ).setVisible( etlPerspective );
doc.getElementById( "help" ).setVisible( etlPerspective );
doc.getElementById( "help-welcome" ).setVisible( etlPerspective );
doc.getElementById( "help-plugins" ).setVisible( true );
}
// Only enable certain menu-items if we need to.
disableMenuItem( doc, "file-new-database", disableTransMenu && disableJobMenu || !isRepositoryRunning );
disableMenuItem( doc, "file-save", disableTransMenu && disableJobMenu && disableMetaMenu || disableSave );
disableMenuItem( doc, "toolbar-file-save", disableTransMenu
&& disableJobMenu && disableMetaMenu || disableSave );
disableMenuItem( doc, "file-save-as", disableTransMenu && disableJobMenu && disableMetaMenu || disableSave );
disableMenuItem( doc, "toolbar-file-save-as", disableTransMenu
&& disableJobMenu && disableMetaMenu || disableSave );
disableMenuItem( doc, "file-save-as-vfs", disableTransMenu && disableJobMenu && disableMetaMenu );
disableMenuItem( doc, "file-close", disableTransMenu && disableJobMenu && disableMetaMenu );
disableMenuItem( doc, "file-print", disableTransMenu && disableJobMenu );
disableMenuItem( doc, "file-export-to-xml", disableTransMenu && disableJobMenu );
disableMenuItem( doc, "file-export-all-to-xml", disableTransMenu && disableJobMenu );
// Disable the undo and redo menus if there is no active transformation
// or active job
// DO NOT ENABLE them otherwise ... leave that to the undo/redo settings
//
disableMenuItem( doc, UNDO_MENU_ITEM, disableTransMenu && disableJobMenu );
disableMenuItem( doc, REDO_MENU_ITEM, disableTransMenu && disableJobMenu );
disableMenuItem( doc, "edit-clear-selection", disableTransMenu && disableJobMenu );
disableMenuItem( doc, "edit-select-all", disableTransMenu && disableJobMenu );
updateSettingsMenu( doc, disableTransMenu, disableJobMenu );
disableMenuItem( doc, "edit-settings", disableTransMenu && disableJobMenu && disableMetaMenu );
// View Menu
( (XulMenuitem) doc.getElementById( "view-results" ) ).setSelected( isExecutionResultsPaneVisible() );
disableMenuItem( doc, "view-results", transGraph == null && disableJobMenu );
disableMenuItem( doc, "view-zoom-in", disableTransMenu && disableJobMenu );
disableMenuItem( doc, "view-zoom-out", disableTransMenu && disableJobMenu );
disableMenuItem( doc, "view-zoom-100pct", disableTransMenu && disableJobMenu );
// Transformations
disableMenuItem( doc, "process-run", disableTransMenu && disablePreviewButton && disableJobMenu );
disableMenuItem( doc, "trans-replay", disableTransMenu && disablePreviewButton );
disableMenuItem( doc, "trans-preview", disableTransMenu && disablePreviewButton );
disableMenuItem( doc, "trans-debug", disableTransMenu && disablePreviewButton );
disableMenuItem( doc, "trans-verify", disableTransMenu );
disableMenuItem( doc, "trans-impact", disableTransMenu );
disableMenuItem( doc, "trans-get-sql", disableTransMenu );
disableMenuItem( doc, "trans-last-impact", disableTransMenu );
// Tools
disableMenuItem( doc, "repository-connect", isRepositoryRunning );
disableMenuItem( doc, "repository-disconnect", !isRepositoryRunning );
disableMenuItem( doc, "repository-explore", !isRepositoryRunning );
disableMenuItem( doc, "repository-clear-shared-object-cache", !isRepositoryRunning );
disableMenuItem( doc, "toolbar-expore-repository", !isRepositoryRunning );
disableMenuItem( doc, "repository-export-all", !isRepositoryRunning );
disableMenuItem( doc, "repository-import-directory", !isRepositoryRunning );
disableMenuItem( doc, "trans-last-preview", !isRepositoryRunning || disableTransMenu );
// Wizard
disableMenuItem( doc, "wizard-connection", disableTransMenu && disableJobMenu );
disableMenuItem( doc, "wizard-copy-table", disableTransMenu && disableJobMenu );
disableMenuItem( doc, "wizard-copy-tables", isRepositoryRunning && disableTransMenu && disableJobMenu );
disableMenuItem( doc, "database-inst-dependancy", !isRepositoryRunning );
SpoonPluginManager.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.MENUS_REFRESHED );
MenuManager menuManager = getMenuBarManager();
menuManager.updateAll( true );
// What steps & plugins to show?
refreshCoreObjects();
fireMenuControlers();
}
}
}
/**
* @param doc
* @param disableJobMenu
* @param disableTransMenu
*/
private void updateSettingsMenu( org.pentaho.ui.xul.dom.Document doc, boolean disableTransMenu,
boolean disableJobMenu ) {
XulMenuitem settingsItem = (XulMenuitem) doc.getElementById( "edit-settings" );
if ( settingsItem != null ) {
if ( disableTransMenu && !disableJobMenu ) {
settingsItem.setAcceltext( "CTRL-J" );
settingsItem.setAccesskey( "ctrl-j" );
} else if ( !disableTransMenu && disableJobMenu ) {
settingsItem.setAcceltext( "CTRL-T" );
settingsItem.setAccesskey( "ctrl-t" );
} else {
settingsItem.setAcceltext( "" );
settingsItem.setAccesskey( "" );
}
}
}
public void addSpoonMenuController( ISpoonMenuController menuController ) {
if ( menuControllers != null ) {
menuControllers.add( menuController );
}
}
public boolean removeSpoonMenuController( ISpoonMenuController menuController ) {
if ( menuControllers != null ) {
return menuControllers.remove( menuController );
}
return false;
}
public ISpoonMenuController removeSpoonMenuController( String menuControllerName ) {
ISpoonMenuController result = null;
if ( menuControllers != null ) {
for ( ISpoonMenuController menuController : menuControllers ) {
if ( menuController.getName().equals( menuControllerName ) ) {
result = menuController;
menuControllers.remove( result );
break;
}
}
}
return result;
}
private void disableMenuItem( org.pentaho.ui.xul.dom.Document doc, String itemId, boolean disable ) {
XulComponent menuItem = doc.getElementById( itemId );
if ( menuItem != null ) {
menuItem.setDisabled( disable );
} else {
log.logError( "Non-Fatal error : Menu Item with id = " + itemId + " does not exist! Check 'menubar.xul'" );
}
}
private void markTabsChanged() {
for ( TabMapEntry entry : delegates.tabs.getTabs() ) {
if ( entry.getTabItem().isDisposed() ) {
continue;
}
boolean changed = entry.getObject().hasContentChanged();
if( changed ) {
// Call extension point to alert plugins that a transformation or job has changed
Object tabObject = entry.getObject().getManagedObject();
String changedId = null;
if( tabObject instanceof TransMeta ) {
changedId = KettleExtensionPoint.TransChanged.id;
}
else if( tabObject instanceof JobMeta ) {
changedId = KettleExtensionPoint.JobChanged.id;
}
if( changedId != null ) {
try {
ExtensionPointHandler.callExtensionPoint( log, changedId, tabObject );
} catch ( KettleException e ) {
// fails gracefully
}
}
}
entry.getTabItem().setChanged( changed );
}
}
/**
* Check to see if any jobs or transformations are dirty
* @return true if any of the open jobs or trans are marked dirty
*/
public boolean isTabsChanged() {
for ( TabMapEntry entry : delegates.tabs.getTabs() ) {
if ( entry.getTabItem().isDisposed() ) {
continue;
}
if ( entry.getObject().hasContentChanged() ) {
return true;
}
}
return false;
}
public void printFile() {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
printTransFile( transMeta );
}
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
printJobFile( jobMeta );
}
}
private void printTransFile( TransMeta transMeta ) {
TransGraph transGraph = getActiveTransGraph();
if ( transGraph == null ) {
return;
}
PrintSpool ps = new PrintSpool();
Printer printer = ps.getPrinter( shell );
// Create an image of the screen
Point max = transMeta.getMaximum();
Image img = transGraph.getTransformationImage( printer, max.x, max.y, 1.0f );
ps.printImage( shell, img );
img.dispose();
ps.dispose();
}
private void printJobFile( JobMeta jobMeta ) {
JobGraph jobGraph = getActiveJobGraph();
if ( jobGraph == null ) {
return;
}
PrintSpool ps = new PrintSpool();
Printer printer = ps.getPrinter( shell );
// Create an image of the screen
Point max = jobMeta.getMaximum();
Image img = jobGraph.getJobImage( printer, max.x, max.y, 1.0f );
ps.printImage( shell, img );
img.dispose();
ps.dispose();
}
public TransGraph getActiveTransGraph() {
if ( tabfolder != null ) {
if ( tabfolder.getSelected() == null ) {
return null;
}
} else {
return null;
}
if ( delegates != null && delegates.tabs != null ) {
TabMapEntry mapEntry = delegates.tabs.getTab( tabfolder.getSelected() );
if ( mapEntry != null ) {
if ( mapEntry.getObject() instanceof TransGraph ) {
return (TransGraph) mapEntry.getObject();
}
}
}
return null;
}
public JobGraph getActiveJobGraph() {
if ( delegates != null && delegates.tabs != null && tabfolder != null ) {
TabMapEntry mapEntry = delegates.tabs.getTab( tabfolder.getSelected() );
if ( mapEntry != null && mapEntry.getObject() instanceof JobGraph ) {
return (JobGraph) mapEntry.getObject();
}
}
return null;
}
public EngineMetaInterface getActiveMeta() {
SpoonPerspectiveManager manager = SpoonPerspectiveManager.getInstance();
if ( manager != null && manager.getActivePerspective() != null ) {
return manager.getActivePerspective().getActiveMeta();
}
return null;
}
public TabItemInterface getActiveTabitem() {
if ( tabfolder == null ) {
return null;
}
TabItem tabItem = tabfolder.getSelected();
if ( tabItem == null ) {
return null;
}
if ( delegates != null && delegates.tabs != null ) {
TabMapEntry mapEntry = delegates.tabs.getTab( tabItem );
if ( mapEntry != null ) {
return mapEntry.getObject();
} else {
return null;
}
}
return null;
}
/**
* @return The active TransMeta object by looking at the selected TransGraph, TransLog, TransHist If nothing valueable
* is selected, we return null
*/
public TransMeta getActiveTransformation() {
EngineMetaInterface meta = getActiveMeta();
if ( meta instanceof TransMeta ) {
return (TransMeta) meta;
}
return null;
}
/**
* @return The active JobMeta object by looking at the selected JobGraph, JobLog, JobHist If nothing valueable is
* selected, we return null
*/
public JobMeta getActiveJob() {
EngineMetaInterface meta = getActiveMeta();
if ( meta instanceof JobMeta ) {
return (JobMeta) meta;
}
return null;
}
public UndoInterface getActiveUndoInterface() {
return (UndoInterface) this.getActiveMeta();
}
public TransMeta findTransformation( String tabItemText ) {
if ( delegates != null && delegates.trans != null ) {
return delegates.trans.getTransformation( tabItemText );
} else {
return null;
}
}
public JobMeta findJob( String tabItemText ) {
if ( delegates != null && delegates.jobs != null ) {
return delegates.jobs.getJob( tabItemText );
} else {
return null;
}
}
public TransMeta[] getLoadedTransformations() {
if ( delegates != null && delegates.trans != null ) {
List<TransMeta> list = delegates.trans.getTransformationList();
return list.toArray( new TransMeta[list.size()] );
} else {
return null;
}
}
public JobMeta[] getLoadedJobs() {
if ( delegates != null && delegates.jobs != null ) {
List<JobMeta> list = delegates.jobs.getJobList();
return list.toArray( new JobMeta[list.size()] );
} else {
return null;
}
}
public void saveSettings() {
if ( shell.isDisposed() ) {
// we cannot save the settings, it's too late
return;
}
WindowProperty windowProperty = new WindowProperty( shell );
windowProperty.setName( APP_TITLE );
props.setScreen( windowProperty );
props.setLogLevel( DefaultLogLevel.getLogLevel().getCode() );
props.setSashWeights( sashform.getWeights() );
// Also save the open files...
// Go over the list of tabs, then add the info to the list
// of open tab files in PropsUI
//
props.getOpenTabFiles().clear();
for ( TabMapEntry entry : delegates.tabs.getTabs() ) {
String fileType = null;
String filename = null;
String directory = null;
int openType = 0;
if ( entry.getObjectType() == ObjectType.TRANSFORMATION_GRAPH ) {
fileType = LastUsedFile.FILE_TYPE_TRANSFORMATION;
TransMeta transMeta = (TransMeta) entry.getObject().getManagedObject();
filename = rep != null ? transMeta.getName() : transMeta.getFilename();
directory = transMeta.getRepositoryDirectory().toString();
openType = LastUsedFile.OPENED_ITEM_TYPE_MASK_GRAPH;
} else if ( entry.getObjectType() == ObjectType.JOB_GRAPH ) {
fileType = LastUsedFile.FILE_TYPE_JOB;
JobMeta jobMeta = (JobMeta) entry.getObject().getManagedObject();
filename = rep != null ? jobMeta.getName() : jobMeta.getFilename();
directory = jobMeta.getRepositoryDirectory().toString();
openType = LastUsedFile.OPENED_ITEM_TYPE_MASK_GRAPH;
}
if ( fileType != null ) {
props.addOpenTabFile(
fileType, filename, directory, rep != null, rep != null ? rep.getName() : null, openType );
}
}
props.saveProps();
}
public void loadSettings() {
LogLevel logLevel = LogLevel.getLogLevelForCode( props.getLogLevel() );
DefaultLogLevel.setLogLevel( logLevel );
log.setLogLevel( logLevel );
KettleLogStore.getAppender().setMaxNrLines( props.getMaxNrLinesInLog() );
// transMeta.setMaxUndo(props.getMaxUndo());
DBCache.getInstance().setActive( props.useDBCache() );
}
public void changeLooks() {
if ( !selectionTree.isDisposed() ) {
props.setLook( selectionTree );
}
props.setLook( tabfolder.getSwtTabset(), Props.WIDGET_STYLE_TAB );
refreshTree();
refreshGraph();
}
public void undoAction( UndoInterface undoInterface ) {
if ( undoInterface == null ) {
return;
}
TransAction ta = undoInterface.previousUndo();
if ( ta == null ) {
return;
}
setUndoMenu( undoInterface ); // something changed: change the menu
if ( undoInterface instanceof TransMeta ) {
delegates.trans.undoTransformationAction( (TransMeta) undoInterface, ta );
if ( ta.getType() == TransAction.TYPE_ACTION_DELETE_STEP ) {
setUndoMenu( undoInterface ); // something changed: change the menu
ta = undoInterface.viewPreviousUndo();
if ( ta != null && ta.getType() == TransAction.TYPE_ACTION_DELETE_HOP ) {
ta = undoInterface.previousUndo();
delegates.trans.undoTransformationAction( (TransMeta) undoInterface, ta );
}
}
}
if ( undoInterface instanceof JobMeta ) {
delegates.jobs.undoJobAction( (JobMeta) undoInterface, ta );
if ( ta.getType() == TransAction.TYPE_ACTION_DELETE_JOB_ENTRY ) {
setUndoMenu( undoInterface ); // something changed: change the menu
ta = undoInterface.viewPreviousUndo();
if ( ta != null && ta.getType() == TransAction.TYPE_ACTION_DELETE_JOB_HOP ) {
ta = undoInterface.previousUndo();
delegates.jobs.undoJobAction( (JobMeta) undoInterface, ta );
}
}
}
// Put what we undo in focus
if ( undoInterface instanceof TransMeta ) {
TransGraph transGraph = delegates.trans.findTransGraphOfTransformation( (TransMeta) undoInterface );
transGraph.forceFocus();
}
if ( undoInterface instanceof JobMeta ) {
JobGraph jobGraph = delegates.jobs.findJobGraphOfJob( (JobMeta) undoInterface );
jobGraph.forceFocus();
}
}
public void redoAction( UndoInterface undoInterface ) {
if ( undoInterface == null ) {
return;
}
TransAction ta = undoInterface.nextUndo();
if ( ta == null ) {
return;
}
setUndoMenu( undoInterface ); // something changed: change the menu
if ( undoInterface instanceof TransMeta ) {
delegates.trans.redoTransformationAction( (TransMeta) undoInterface, ta );
if ( ta.getType() == TransAction.TYPE_ACTION_DELETE_HOP ) {
setUndoMenu( undoInterface ); // something changed: change the menu
ta = undoInterface.viewNextUndo();
if ( ta != null && ta.getType() == TransAction.TYPE_ACTION_DELETE_STEP) {
ta = undoInterface.nextUndo();
delegates.trans.redoTransformationAction( (TransMeta) undoInterface, ta );
}
}
}
if ( undoInterface instanceof JobMeta ) {
delegates.jobs.redoJobAction( (JobMeta) undoInterface, ta );
if ( ta.getType() == TransAction.TYPE_ACTION_DELETE_JOB_HOP ) {
setUndoMenu( undoInterface ); // something changed: change the menu
ta = undoInterface.viewNextUndo();
if ( ta != null && ta.getType() == TransAction.TYPE_ACTION_DELETE_JOB_ENTRY) {
ta = undoInterface.nextUndo();
delegates.jobs.redoJobAction( (JobMeta) undoInterface, ta );
}
}
}
// Put what we redo in focus
if ( undoInterface instanceof TransMeta ) {
TransGraph transGraph = delegates.trans.findTransGraphOfTransformation( (TransMeta) undoInterface );
transGraph.forceFocus();
}
if ( undoInterface instanceof JobMeta ) {
JobGraph jobGraph = delegates.jobs.findJobGraphOfJob( (JobMeta) undoInterface );
jobGraph.forceFocus();
}
}
/**
* Sets the text and enabled settings for the undo and redo menu items
*
* @param undoInterface
* the object which holds the undo/redo information
*/
public void setUndoMenu( UndoInterface undoInterface ) {
if ( shell.isDisposed() ) {
return;
}
TransAction prev = undoInterface != null ? undoInterface.viewThisUndo() : null;
TransAction next = undoInterface != null ? undoInterface.viewNextUndo() : null;
// Set the menubar text and enabled flags
XulMenuitem item = (XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById( UNDO_MENU_ITEM );
item.setLabel( prev == null ? UNDO_UNAVAILABLE : BaseMessages.getString(
PKG, "Spoon.Menu.Undo.Available", prev.toString() ) );
item.setDisabled( prev == null );
item = (XulMenuitem) mainSpoonContainer.getDocumentRoot().getElementById( REDO_MENU_ITEM );
item.setLabel( next == null ? REDO_UNAVAILABLE : BaseMessages.getString(
PKG, "Spoon.Menu.Redo.Available", next.toString() ) );
item.setDisabled( next == null );
}
public void addUndoNew( UndoInterface undoInterface, Object[] obj, int[] position ) {
addUndoNew( undoInterface, obj, position, false );
}
public void addUndoNew( UndoInterface undoInterface, Object[] obj, int[] position, boolean nextAlso ) {
undoInterface.addUndo( obj, null, position, null, null, TransMeta.TYPE_UNDO_NEW, nextAlso );
setUndoMenu( undoInterface );
}
// Undo delete object
public void addUndoDelete( UndoInterface undoInterface, Object[] obj, int[] position ) {
addUndoDelete( undoInterface, obj, position, false );
}
// Undo delete object
public void addUndoDelete( UndoInterface undoInterface, Object[] obj, int[] position, boolean nextAlso ) {
undoInterface.addUndo( obj, null, position, null, null, TransMeta.TYPE_UNDO_DELETE, nextAlso );
setUndoMenu( undoInterface );
}
// Change of step, connection, hop or note...
public void addUndoPosition( UndoInterface undoInterface, Object[] obj, int[] pos, Point[] prev, Point[] curr ) {
// It's better to store the indexes of the objects, not the objects
// itself!
undoInterface.addUndo( obj, null, pos, prev, curr, JobMeta.TYPE_UNDO_POSITION, false );
setUndoMenu( undoInterface );
}
// Change of step, connection, hop or note...
public void addUndoChange( UndoInterface undoInterface, Object[] from, Object[] to, int[] pos ) {
addUndoChange( undoInterface, from, to, pos, false );
}
// Change of step, connection, hop or note...
public void addUndoChange( UndoInterface undoInterface, Object[] from, Object[] to, int[] pos, boolean nextAlso ) {
undoInterface.addUndo( from, to, pos, null, null, JobMeta.TYPE_UNDO_CHANGE, nextAlso );
setUndoMenu( undoInterface );
}
/**
* Checks *all* the steps in the transformation, puts the result in remarks list
*/
public void checkTrans( TransMeta transMeta ) {
checkTrans( transMeta, false );
}
/**
* Check the steps in a transformation
*
* @param only_selected
* True: Check only the selected steps...
*/
public void checkTrans( TransMeta transMeta, boolean only_selected ) {
if ( transMeta == null ) {
return;
}
TransGraph transGraph = delegates.trans.findTransGraphOfTransformation( transMeta );
if ( transGraph == null ) {
return;
}
CheckTransProgressDialog ctpd =
new CheckTransProgressDialog( shell, transMeta, transGraph.getRemarks(), only_selected );
ctpd.open(); // manages the remarks arraylist...
showLastTransCheck();
}
/**
* Show the remarks of the last transformation check that was run.
*
* @see #checkTrans()
*/
public void showLastTransCheck() {
TransMeta transMeta = getActiveTransformation();
if ( transMeta == null ) {
return;
}
TransGraph transGraph = delegates.trans.findTransGraphOfTransformation( transMeta );
if ( transGraph == null ) {
return;
}
CheckResultDialog crd = new CheckResultDialog( transMeta, shell, SWT.NONE, transGraph.getRemarks() );
String stepName = crd.open();
if ( stepName != null ) {
// Go to the indicated step!
StepMeta stepMeta = transMeta.findStep( stepName );
if ( stepMeta != null ) {
delegates.steps.editStep( transMeta, stepMeta );
}
}
}
public void analyseImpact( TransMeta transMeta ) {
if ( transMeta == null ) {
return;
}
TransGraph transGraph = delegates.trans.findTransGraphOfTransformation( transMeta );
if ( transGraph == null ) {
return;
}
AnalyseImpactProgressDialog aipd = new AnalyseImpactProgressDialog( shell, transMeta, transGraph.getImpact() );
transGraph.setImpactFinished( aipd.open() );
if ( transGraph.isImpactFinished() ) {
showLastImpactAnalyses( transMeta );
}
}
public void showLastImpactAnalyses( TransMeta transMeta ) {
if ( transMeta == null ) {
return;
}
TransGraph transGraph = delegates.trans.findTransGraphOfTransformation( transMeta );
if ( transGraph == null ) {
return;
}
List<Object[]> rows = new ArrayList<Object[]>();
RowMetaInterface rowMeta = null;
for ( int i = 0; i < transGraph.getImpact().size(); i++ ) {
DatabaseImpact ii = transGraph.getImpact().get( i );
RowMetaAndData row = ii.getRow();
rowMeta = row.getRowMeta();
rows.add( row.getData() );
}
if ( rows.size() > 0 ) {
// Display all the rows...
PreviewRowsDialog prd =
new PreviewRowsDialog( shell, Variables.getADefaultVariableSpace(), SWT.NONE, "-", rowMeta, rows );
prd.setTitleMessage(
// "Impact analyses"
// "Result of analyses:"
BaseMessages.getString( PKG, "Spoon.Dialog.ImpactAnalyses.Title" ), BaseMessages.getString(
PKG, "Spoon.Dialog.ImpactAnalyses.Message" ) );
prd.open();
} else {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
if ( transGraph.isImpactFinished() ) {
// "As far as I can tell, this transformation has no impact on any database."
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.TransformationNoImpactOnDatabase.Message" ) );
} else {
// "Please run the impact analyses first on this transformation."
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Dialog.RunImpactAnalysesFirst.Message" ) );
}
mb.setText( BaseMessages.getString( PKG, "Spoon.Dialog.ImpactAnalyses.Title" ) ); // Impact
mb.open();
}
}
public void toClipboard( String clipText ) {
try {
GUIResource.getInstance().toClipboard( clipText );
} catch ( Throwable e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ExceptionCopyToClipboard.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ExceptionCopyToClipboard.Message" ), e );
}
}
public String fromClipboard() {
try {
return GUIResource.getInstance().fromClipboard();
} catch ( Throwable e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ExceptionPasteFromClipboard.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ExceptionPasteFromClipboard.Message" ), e );
return null;
}
}
/**
* Paste transformation from the clipboard...
*
*/
public void pasteTransformation() {
if ( RepositorySecurityUI.verifyOperations( shell, rep,
RepositoryOperation.MODIFY_TRANSFORMATION, RepositoryOperation.EXECUTE_TRANSFORMATION ) ) {
return;
}
if ( log.isDetailed() ) {
// "Paste transformation from the clipboard!"
log.logDetailed( BaseMessages.getString( PKG, "Spoon.Log.PasteTransformationFromClipboard" ) );
}
String xml = fromClipboard();
try {
Document doc = XMLHandler.loadXMLString( xml );
TransMeta transMeta = new TransMeta( XMLHandler.getSubNode( doc, TransMeta.XML_TAG ), rep );
setTransMetaVariables( transMeta );
addTransGraph( transMeta ); // create a new tab
sharedObjectsFileMap.put( transMeta.getSharedObjects().getFilename(), transMeta.getSharedObjects() );
refreshGraph();
refreshTree();
} catch ( KettleException e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorPastingTransformation.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorPastingTransformation.Message" ), e );
}
}
/**
* Paste job from the clipboard...
*
*/
public void pasteJob() {
if ( RepositorySecurityUI.verifyOperations( shell, rep,
RepositoryOperation.MODIFY_JOB, RepositoryOperation.EXECUTE_JOB ) ) {
return;
}
String xml = fromClipboard();
try {
Document doc = XMLHandler.loadXMLString( xml );
JobMeta jobMeta = new JobMeta( XMLHandler.getSubNode( doc, JobMeta.XML_TAG ), rep, this );
addJobGraph( jobMeta ); // create a new tab
refreshGraph();
refreshTree();
} catch ( KettleException e ) {
new ErrorDialog( shell,
// Error pasting transformation
// "An error occurred pasting a transformation from the clipboard"
BaseMessages.getString( PKG, "Spoon.Dialog.ErrorPastingJob.Title" ), BaseMessages.getString(
PKG, "Spoon.Dialog.ErrorPastingJob.Message" ), e );
}
}
public void copyTransformation( TransMeta transMeta ) {
if ( transMeta == null ) {
return;
}
try {
if ( RepositorySecurityUI.verifyOperations(
shell, rep, RepositoryOperation.MODIFY_TRANSFORMATION, RepositoryOperation.EXECUTE_TRANSFORMATION ) ) {
return;
}
toClipboard( XMLHandler.getXMLHeader() + transMeta.getXML() );
} catch ( Exception ex ) {
new ErrorDialog( getShell(), "Error", "Error encoding to XML", ex );
}
}
public void copyJob( JobMeta jobMeta ) {
if ( jobMeta == null ) {
return;
}
if ( RepositorySecurityUI.verifyOperations(
shell, rep, RepositoryOperation.MODIFY_JOB, RepositoryOperation.EXECUTE_JOB ) ) {
return;
}
toClipboard( XMLHandler.getXMLHeader() + jobMeta.getXML() );
}
public void copyTransformationImage( TransMeta transMeta ) {
TransGraph transGraph = delegates.trans.findTransGraphOfTransformation( transMeta );
if ( transGraph == null ) {
return;
}
Clipboard clipboard = GUIResource.getInstance().getNewClipboard();
Point area = transMeta.getMaximum();
Image image = transGraph.getTransformationImage( Display.getCurrent(), area.x, area.y, 1.0f );
clipboard.setContents(
new Object[] { image.getImageData() }, new Transfer[] { ImageTransfer.getInstance() } );
}
/**
* @return Either a TransMeta or JobMeta object
*/
public HasDatabasesInterface getActiveHasDatabasesInterface() {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
return transMeta;
}
return getActiveJob();
}
/**
* Shows a wizard that creates a new database connection...
*
*/
public void createDatabaseWizard() {
HasDatabasesInterface hasDatabasesInterface = getActiveHasDatabasesInterface();
if ( hasDatabasesInterface == null ) {
return; // nowhere to put the new database
}
CreateDatabaseWizard cdw = new CreateDatabaseWizard();
DatabaseMeta newDBInfo = cdw.createAndRunDatabaseWizard( shell, props, hasDatabasesInterface.getDatabases() );
if ( newDBInfo != null ) { // finished
hasDatabasesInterface.addDatabase( newDBInfo );
refreshTree();
refreshGraph();
}
}
public List<DatabaseMeta> getActiveDatabases() {
Map<String, DatabaseMeta> map = new Hashtable<String, DatabaseMeta>();
HasDatabasesInterface hasDatabasesInterface = getActiveHasDatabasesInterface();
if ( hasDatabasesInterface != null ) {
for ( int i = 0; i < hasDatabasesInterface.nrDatabases(); i++ ) {
map.put( hasDatabasesInterface.getDatabase( i ).getName(), hasDatabasesInterface.getDatabase( i ) );
}
}
if ( rep != null ) {
try {
List<DatabaseMeta> repDBs = rep.readDatabases();
for ( DatabaseMeta databaseMeta : repDBs ) {
map.put( databaseMeta.getName(), databaseMeta );
}
} catch ( Exception e ) {
log.logError( "Unexpected error reading databases from the repository: " + e.toString() );
log.logError( Const.getStackTracker( e ) );
}
}
List<DatabaseMeta> databases = new ArrayList<DatabaseMeta>();
databases.addAll( map.values() );
return databases;
}
/**
* Create a transformation that extracts tables & data from a database.
* <p>
* <p>
*
* 0) Select the database to rip
* <p>
* 1) Select the table in the database to copy
* <p>
* 2) Select the database to dump to
* <p>
* 3) Select the repository directory in which it will end up
* <p>
* 4) Select a name for the new transformation
* <p>
* 6) Create 1 transformation for the selected table
* <p>
*/
public void copyTableWizard() {
List<DatabaseMeta> databases = getActiveDatabases();
if ( databases.size() == 0 ) {
return; // Nothing to do here
}
final CopyTableWizardPage1 page1 = new CopyTableWizardPage1( "1", databases );
page1.createControl( shell );
final CopyTableWizardPage2 page2 = new CopyTableWizardPage2( "2" );
page2.createControl( shell );
Wizard wizard = new Wizard() {
public boolean performFinish() {
return delegates.db.copyTable( page1.getSourceDatabase(), page1.getTargetDatabase(), page2.getSelection() );
}
/**
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish() {
return page2.canFinish();
}
};
wizard.addPage( page1 );
wizard.addPage( page2 );
WizardDialog wd = new WizardDialog( shell, wizard );
WizardDialog.setDefaultImage( GUIResource.getInstance().getImageWizard() );
wd.setMinimumPageSize( 700, 400 );
wd.updateSize();
wd.open();
}
public String toString() {
return APP_NAME;
}
public void selectRep( CommandLineOption[] options ) {
RepositoryMeta repositoryMeta;
StringBuffer optionRepname = getCommandLineOption( options, "rep" ).getArgument();
StringBuffer optionFilename = getCommandLineOption( options, "file" ).getArgument();
StringBuffer optionUsername = getCommandLineOption( options, "user" ).getArgument();
StringBuffer optionPassword = getCommandLineOption( options, "pass" ).getArgument();
if ( Const.isEmpty( optionRepname )
&& Const.isEmpty( optionFilename ) && props.showRepositoriesDialogAtStartup() ) {
if ( log.isBasic() ) {
// "Asking for repository"
log.logBasic( BaseMessages.getString( PKG, "Spoon.Log.AskingForRepository" ) );
}
loginDialog = new RepositoriesDialog( shell, null, new ILoginCallback() {
public void onSuccess( Repository repository ) {
setRepository( repository );
SpoonPluginManager.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.REPOSITORY_CONNECTED );
}
public void onError( Throwable t ) {
onLoginError( t );
}
public void onCancel() {
// do nothing
}
} );
hideSplash();
loginDialog.show();
showSplash();
} else if ( !Const.isEmpty( optionRepname ) && Const.isEmpty( optionFilename ) ) {
RepositoriesMeta repsInfo = new RepositoriesMeta();
try {
repsInfo.readData();
repositoryMeta = repsInfo.findRepository( optionRepname.toString() );
if ( repositoryMeta != null && !Const.isEmpty( optionUsername ) && !Const.isEmpty( optionPassword ) ) {
// Define and connect to the repository...
Repository repo =
PluginRegistry
.getInstance().loadClass( RepositoryPluginType.class, repositoryMeta, Repository.class );
repo.init( repositoryMeta );
repo.connect( optionUsername != null ? optionUsername.toString() : null, optionPassword != null
? optionPassword.toString() : null );
setRepository( repo );
} else {
if ( !Const.isEmpty( optionUsername ) && !Const.isEmpty( optionPassword ) ) {
String msg = BaseMessages.getString( PKG, "Spoon.Log.NoRepositoriesDefined" );
log.logError( msg ); // "No repositories defined on this system."
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Error.Repository.NotFound", optionRepname
.toString() ) );
mb.setText( BaseMessages.getString( PKG, "Spoon.Error.Repository.NotFound.Title" ) );
mb.open();
}
loginDialog = new RepositoriesDialog( shell, null, new ILoginCallback() {
public void onSuccess( Repository repository ) {
setRepository( repository );
SpoonPluginManager.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.REPOSITORY_CONNECTED );
}
public void onError( Throwable t ) {
onLoginError( t );
}
public void onCancel() {
// TODO Auto-generated method stub
}
} );
hideSplash();
loginDialog.show();
showSplash();
}
} catch ( Exception e ) {
hideSplash();
// Eat the exception but log it...
log.logError( "Error reading repositories xml file", e );
}
}
}
public void handleStartOptions( CommandLineOption[] options ) {
// note that at this point the rep object is populated by previous calls
StringBuffer optionRepname = getCommandLineOption( options, "rep" ).getArgument();
StringBuffer optionFilename = getCommandLineOption( options, "file" ).getArgument();
StringBuffer optionDirname = getCommandLineOption( options, "dir" ).getArgument();
StringBuffer optionTransname = getCommandLineOption( options, "trans" ).getArgument();
StringBuffer optionJobname = getCommandLineOption( options, "job" ).getArgument();
// StringBuffer optionUsername = getCommandLineOption(options,
// "user").getArgument();
// StringBuffer optionPassword = getCommandLineOption(options,
// "pass").getArgument();
try {
// Read kettle transformation specified on command-line?
if ( !Const.isEmpty( optionRepname ) || !Const.isEmpty( optionFilename ) ) {
if ( !Const.isEmpty( optionRepname ) ) {
if ( rep != null ) {
if ( Const.isEmpty( optionDirname ) ) {
optionDirname = new StringBuffer( RepositoryDirectory.DIRECTORY_SEPARATOR );
}
// Options /file, /job and /trans are mutually
// exclusive
int t =
( Const.isEmpty( optionFilename ) ? 0 : 1 )
+ ( Const.isEmpty( optionJobname ) ? 0 : 1 ) + ( Const.isEmpty( optionTransname ) ? 0 : 1 );
if ( t > 1 ) {
// "More then one mutually exclusive options /file, /job and /trans are specified."
log.logError( BaseMessages.getString( PKG, "Spoon.Log.MutuallyExcusive" ) );
} else if ( t == 1 ) {
if ( !Const.isEmpty( optionFilename ) ) {
openFile( optionFilename.toString(), false );
} else {
// OK, if we have a specified job or
// transformation, try to load it...
// If not, keep the repository logged
// in.
RepositoryDirectoryInterface rdi = rep.findDirectory( optionDirname.toString() );
if ( rdi == null ) {
log.logError( BaseMessages.getString( PKG, "Spoon.Log.UnableFindDirectory", optionDirname
.toString() ) ); // "Can't find directory ["+dirname+"] in the repository."
} else {
if ( !Const.isEmpty( optionTransname ) ) {
TransMeta transMeta =
rep.loadTransformation( optionTransname.toString(), rdi, null, true, null ); // reads
// last
// version
transMeta.clearChanged();
transMeta.setInternalKettleVariables();
addTransGraph( transMeta );
} else {
// Try to load a specified job
// if any
JobMeta jobMeta = rep.loadJob( optionJobname.toString(), rdi, null, null ); // reads
// last
// version
jobMeta.clearChanged();
jobMeta.setInternalKettleVariables();
addJobGraph( jobMeta );
}
}
}
}
} else {
// "No repositories defined on this system."
log.logError( BaseMessages.getString( PKG, "Spoon.Log.NoRepositoriesDefined" ) );
}
} else if ( !Const.isEmpty( optionFilename ) ) {
openFile( optionFilename.toString(), false );
}
}
} catch ( KettleException ke ) {
hideSplash();
log.logError( BaseMessages.getString( PKG, "Spoon.Log.ErrorOccurred" ) + Const.CR + ke.getMessage() );
log.logError( Const.getStackTracker( ke ) );
// do not just eat the exception
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Log.ErrorOccurred" ), BaseMessages.getString(
PKG, "Spoon.Log.ErrorOccurred" )
+ Const.CR + ke.getMessage(), ke );
rep = null;
}
}
private void loadLastUsedFiles() {
if ( props.openLastFile() ) {
if ( log.isDetailed() ) {
// "Trying to open the last file used."
log.logDetailed( BaseMessages.getString( PKG, "Spoon.Log.TryingOpenLastUsedFile" ) );
}
List<LastUsedFile> lastUsedFiles = props.getOpenTabFiles();
for ( LastUsedFile lastUsedFile : lastUsedFiles ) {
try {
if ( !lastUsedFile.isSourceRepository()
|| lastUsedFile.isSourceRepository() && rep != null
&& rep.getName().equals( lastUsedFile.getRepositoryName() ) ) {
loadLastUsedFile( lastUsedFile, rep == null ? null : rep.getName(), false );
}
} catch ( Exception e ) {
hideSplash();
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.LoadLastUsedFile.Exception.Title" ), BaseMessages
.getString( PKG, "Spoon.LoadLastUsedFile.Exception.Message", lastUsedFile.toString() ), e );
}
}
}
}
public void start( CommandLineOption[] options ) throws KettleException {
// Show the repository connection dialog
//
selectRep( options );
// Read the start option parameters
//
handleStartOptions( options );
// Load the last loaded files
//
loadLastUsedFiles();
// Enable menus based on whether user was able to login or not
//
enableMenus();
// enable perspective switching
SpoonPerspectiveManager.getInstance().setForcePerspective( false );
if ( splash != null ) {
splash.dispose();
splash = null;
}
// If we are a MILESTONE or RELEASE_CANDIDATE
if ( !ValueMeta.convertStringToBoolean( System.getProperty( "KETTLE_HIDE_DEVELOPMENT_VERSION_WARNING", "N" ) )
&& Const.RELEASE.equals( Const.ReleaseType.MILESTONE ) ) {
// display the same warning message
MessageBox dialog = new MessageBox( shell, SWT.ICON_WARNING );
dialog.setText( BaseMessages.getString( PKG, "Spoon.Warning.DevelopmentRelease.Title" ) );
dialog.setMessage( BaseMessages.getString(
PKG, "Spoon.Warning.DevelopmentRelease.Message", Const.CR, BuildVersion.getInstance().getVersion() ) );
dialog.open();
}
}
private void waitForDispose() {
boolean retryAfterError; // Enable the user to retry and
// continue after fatal error
do {
retryAfterError = false; // reset to false after error otherwise
// it will loop forever after
// closing Spoon
try {
while ( getShell() != null && !getShell().isDisposed() ) {
if ( !readAndDispatch() ) {
sleep();
}
}
} catch ( Throwable e ) {
// "An unexpected error occurred in Spoon: probable cause: please close all windows before stopping Spoon! "
log.logError( BaseMessages.getString( PKG, "Spoon.Log.UnexpectedErrorOccurred" )
+ Const.CR + e.getMessage() );
log.logError( Const.getStackTracker( e ) );
try {
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Log.UnexpectedErrorOccurred" ), BaseMessages
.getString( PKG, "Spoon.Log.UnexpectedErrorOccurred" )
+ Const.CR + e.getMessage(), e );
// Retry dialog
MessageBox mb = new MessageBox( shell, SWT.ICON_QUESTION | SWT.NO | SWT.YES );
mb.setText( BaseMessages.getString( PKG, "Spoon.Log.UnexpectedErrorRetry.Titel" ) );
mb.setMessage( BaseMessages.getString( PKG, "Spoon.Log.UnexpectedErrorRetry.Message" ) );
if ( mb.open() == SWT.YES ) {
retryAfterError = true;
}
} catch ( Throwable e1 ) {
// When the opening of a dialog crashed, we can not do
// anything more here
}
}
} while ( retryAfterError );
if ( !display.isDisposed() ) {
display.update();
}
dispose();
if ( log.isBasic() ) {
log.logBasic( APP_NAME + " " + BaseMessages.getString( PKG, "Spoon.Log.AppHasEnded" ) ); // " has ended."
}
// Close the logfile
if ( fileLoggingEventListener != null ) {
try {
fileLoggingEventListener.close();
} catch ( Exception e ) {
LogChannel.GENERAL.logError( "Error closing logging file", e );
}
KettleLogStore.getAppender().removeLoggingEventListener( fileLoggingEventListener );
}
}
// public Splash splash;
// public CommandLineOption options[];
public static CommandLineOption getCommandLineOption( CommandLineOption[] options, String opt ) {
for ( CommandLineOption option : options ) {
if ( option.getOption().equals( opt ) ) {
return option;
}
}
return null;
}
public static CommandLineOption[] getCommandLineArgs( List<String> args ) {
CommandLineOption[] clOptions =
new CommandLineOption[] {
new CommandLineOption( "rep", "Repository name", new StringBuffer() ),
new CommandLineOption( "user", "Repository username", new StringBuffer() ),
new CommandLineOption( "pass", "Repository password", new StringBuffer() ),
new CommandLineOption( "job", "The name of the job to launch", new StringBuffer() ),
new CommandLineOption( "trans", "The name of the transformation to launch", new StringBuffer() ),
new CommandLineOption( "dir", "The directory (don't forget the leading /)", new StringBuffer() ),
new CommandLineOption( "file", "The filename (Transformation in XML) to launch", new StringBuffer() ),
new CommandLineOption(
"level", "The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)",
new StringBuffer() ),
new CommandLineOption( "logfile", "The logging file to write to", new StringBuffer() ),
new CommandLineOption(
"log", "The logging file to write to (deprecated)", new StringBuffer(), false, true ),
new CommandLineOption( "perspective", "The perspective to start in", new StringBuffer(), false, true ) };
// start with the default logger until we find out otherwise
//
log = new LogChannel( APP_NAME );
// Parse the options...
if ( !CommandLineOption.parseArguments( args, clOptions, log ) ) {
log.logError( "Command line option not understood" );
System.exit( 8 );
}
String kettleRepname = Const.getEnvironmentVariable( "KETTLE_REPOSITORY", null );
String kettleUsername = Const.getEnvironmentVariable( "KETTLE_USER", null );
String kettlePassword = Const.getEnvironmentVariable( "KETTLE_PASSWORD", null );
if ( !Const.isEmpty( kettleRepname ) ) {
clOptions[0].setArgument( new StringBuffer( kettleRepname ) );
}
if ( !Const.isEmpty( kettleUsername ) ) {
clOptions[1].setArgument( new StringBuffer( kettleUsername ) );
}
if ( !Const.isEmpty( kettlePassword ) ) {
clOptions[2].setArgument( new StringBuffer( kettlePassword ) );
}
return clOptions;
}
private void loadLastUsedFile( LastUsedFile lastUsedFile, String repositoryName ) throws KettleException {
loadLastUsedFile( lastUsedFile, repositoryName, true );
}
private void loadLastUsedFile(
LastUsedFile lastUsedFile, String repositoryName, boolean trackIt ) throws KettleException {
boolean useRepository = repositoryName != null;
// Perhaps we need to connect to the repository?
//
if ( lastUsedFile.isSourceRepository() ) {
if ( !Const.isEmpty( lastUsedFile.getRepositoryName() ) ) {
if ( useRepository && !lastUsedFile.getRepositoryName().equalsIgnoreCase( repositoryName ) ) {
// We just asked...
useRepository = false;
}
}
}
if ( useRepository && lastUsedFile.isSourceRepository() ) {
if ( rep != null ) { // load from this repository...
if ( rep.getName().equalsIgnoreCase( lastUsedFile.getRepositoryName() ) ) {
RepositoryDirectoryInterface rdi = rep.findDirectory( lastUsedFile.getDirectory() );
if ( rdi != null ) {
// Are we loading a transformation or a job?
if ( lastUsedFile.isTransformation() ) {
if ( log.isDetailed() ) {
// "Auto loading transformation ["+lastfiles[0]+"] from repository directory ["+lastdirs[0]+"]"
log.logDetailed( BaseMessages.getString( PKG, "Spoon.Log.AutoLoadingTransformation", lastUsedFile
.getFilename(), lastUsedFile.getDirectory() ) );
}
TransLoadProgressDialog tlpd =
new TransLoadProgressDialog( shell, rep, lastUsedFile.getFilename(), rdi, null );
TransMeta transMeta = tlpd.open();
if ( transMeta != null ) {
if ( trackIt ) {
props.addLastFile( LastUsedFile.FILE_TYPE_TRANSFORMATION, lastUsedFile.getFilename(), rdi
.getPath(), true, rep.getName() );
}
// transMeta.setFilename(lastUsedFile.getFilename());
transMeta.clearChanged();
addTransGraph( transMeta );
refreshTree();
}
} else if ( lastUsedFile.isJob() ) {
JobLoadProgressDialog progressDialog =
new JobLoadProgressDialog( shell, rep, lastUsedFile.getFilename(), rdi, null );
JobMeta jobMeta = progressDialog.open();
if ( jobMeta != null ) {
if ( trackIt ) {
props.addLastFile(
LastUsedFile.FILE_TYPE_JOB, lastUsedFile.getFilename(), rdi.getPath(), true, rep
.getName() );
}
jobMeta.clearChanged();
addJobGraph( jobMeta );
}
}
refreshTree();
}
}
}
}
if ( !lastUsedFile.isSourceRepository() && !Const.isEmpty( lastUsedFile.getFilename() ) ) {
if ( lastUsedFile.isTransformation() ) {
openFile( lastUsedFile.getFilename(), false );
}
if ( lastUsedFile.isJob() ) {
openFile( lastUsedFile.getFilename(), false );
}
refreshTree();
}
}
/**
* Create a new SelectValues step in between this step and the previous. If the previous fields are not there, no
* mapping can be made, same with the required fields.
*
* @param stepMeta
* The target step to map against.
*/
// retry of required fields acquisition
public void generateFieldMapping( TransMeta transMeta, StepMeta stepMeta ) {
try {
if ( stepMeta != null ) {
StepMetaInterface smi = stepMeta.getStepMetaInterface();
RowMetaInterface targetFields = smi.getRequiredFields( transMeta );
RowMetaInterface sourceFields = transMeta.getPrevStepFields( stepMeta );
// Build the mapping: let the user decide!!
String[] source = sourceFields.getFieldNames();
for ( int i = 0; i < source.length; i++ ) {
ValueMetaInterface v = sourceFields.getValueMeta( i );
source[i] += EnterMappingDialog.STRING_ORIGIN_SEPARATOR + v.getOrigin() + ")";
}
String[] target = targetFields.getFieldNames();
EnterMappingDialog dialog = new EnterMappingDialog( shell, source, target );
List<SourceToTargetMapping> mappings = dialog.open();
if ( mappings != null ) {
// OK, so we now know which field maps where.
// This allows us to generate the mapping using a
// SelectValues Step...
SelectValuesMeta svm = new SelectValuesMeta();
svm.allocate( mappings.size(), 0, 0 );
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < mappings.size(); i++ ) {
SourceToTargetMapping mapping = mappings.get( i );
svm.getSelectName()[i] = sourceFields.getValueMeta( mapping.getSourcePosition() ).getName();
svm.getSelectRename()[i] = target[mapping.getTargetPosition()];
svm.getSelectLength()[i] = -1;
svm.getSelectPrecision()[i] = -1;
}
// a new comment. Sincerely yours CO ;)
// Now that we have the meta-data, create a new step info object
String stepName = stepMeta.getName() + " Mapping";
stepName = transMeta.getAlternativeStepname( stepName ); // if
// it's already there, rename it.
StepMeta newStep = new StepMeta( "SelectValues", stepName, svm );
newStep.setLocation( stepMeta.getLocation().x + 20, stepMeta.getLocation().y + 20 );
newStep.setDraw( true );
transMeta.addStep( newStep );
addUndoNew( transMeta, new StepMeta[] { newStep }, new int[] { transMeta.indexOfStep( newStep ) } );
// Redraw stuff...
refreshTree();
refreshGraph();
}
} else {
throw new KettleException( "There is no target to do a field mapping against!" );
}
} catch ( KettleException e ) {
new ErrorDialog(
shell, "Error creating mapping",
"There was an error when Kettle tried to generate a field mapping against the target step", e );
}
}
public boolean isDefinedSchemaExist( String[] schemaNames ) {
// Before we start, check if there are any partition schemas defined...
if ( ( schemaNames == null ) || ( schemaNames.length == 0 ) ) {
MessageBox box = new MessageBox( shell, SWT.ICON_ERROR | SWT.OK );
box.setText( "Create a partition schema" );
box.setMessage( "You first need to create one or more partition schemas in "
+ "the transformation settings dialog before you can select one!" );
box.open();
return false;
}
return true;
}
public void editPartitioning( TransMeta transMeta, StepMeta stepMeta ) {
String[] schemaNames;
try {
schemaNames = pickupPartitionSchemaNames( transMeta );
} catch ( KettleException e ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "Spoon.ErrorDialog.Title" ),
BaseMessages.getString( PKG, "Spoon.ErrorDialog.ErrorFetchingFromRepo.PartitioningSchemas" ),
e
);
return;
}
try {
/*Check if Partition schema has already defined*/
if ( isDefinedSchemaExist( schemaNames ) ) {
/*Prepare settings for Method selection*/
PluginRegistry registry = PluginRegistry.getInstance();
List<PluginInterface> plugins = registry.getPlugins( PartitionerPluginType.class );
int exactSize = StepPartitioningMeta.methodDescriptions.length + plugins.size();
PartitionSettings settings = new PartitionSettings( exactSize, transMeta, stepMeta, this );
settings.fillOptionsAndCodesByPlugins( plugins );
/*Method selection*/
PartitionMethodSelector methodSelector = new PartitionMethodSelector();
String partitionMethodDescription =
methodSelector.askForPartitionMethod( shell, settings );
if ( !StringUtil.isEmpty( partitionMethodDescription ) ) {
String method = settings.getMethodByMethodDescription( partitionMethodDescription );
int methodType = StepPartitioningMeta.getMethodType( method );
settings.updateMethodType( methodType );
settings.updateMethod( method );
/*Schema selection*/
MethodProcessor methodProcessor = MethodProcessorFactory.create( methodType );
methodProcessor.schemaSelection( settings, shell, delegates );
}
addUndoChange( settings.getTransMeta(), new StepMeta[] { settings.getBefore() },
new StepMeta[] { settings.getAfter() }, new int[] { settings.getTransMeta()
.indexOfStep( settings.getStepMeta() ) }
);
refreshGraph();
}
} catch ( Exception e ) {
new ErrorDialog(
shell, "Error",
"There was an unexpected error while editing the partitioning method specifics:", e );
}
}
/**
* Select a clustering schema for this step.
*
* @param stepMeta
* The step to set the clustering schema for.
*/
public void editClustering( TransMeta transMeta, StepMeta stepMeta ) {
editClustering( transMeta, Collections.singletonList( stepMeta ) );
}
private String[] pickupClusterSchemas( TransMeta transMeta ) throws KettleException {
return ( rep == null ) ? transMeta.getClusterSchemaNames() : rep.getClusterNames( false );
}
/**
* Select a clustering schema for this step.
*
* @param stepMetas The steps (at least one!) to set the clustering schema for.
*/
public void editClustering( TransMeta transMeta, List<StepMeta> stepMetas ) {
String[] clusterSchemaNames;
try {
clusterSchemaNames = pickupClusterSchemas( transMeta );
} catch ( KettleException e ) {
new ErrorDialog( shell,
BaseMessages.getString( PKG, "Spoon.ErrorDialog.Title" ),
BaseMessages.getString( PKG, "Spoon.ErrorDialog.ErrorFetchingFromRepo.ClusterSchemas" ),
e
);
return;
}
StepMeta stepMeta = stepMetas.get( 0 );
int idx = -1;
if ( stepMeta.getClusterSchema() != null ) {
idx = transMeta.getClusterSchemas().indexOf( stepMeta.getClusterSchema() );
}
EnterSelectionDialog dialog = new EnterSelectionDialog(
shell,
clusterSchemaNames,
BaseMessages.getString( PKG, "Spoon.Dialog.SelectClusteringSchema.Title" ),
BaseMessages.getString( PKG, "Spoon.Dialog.SelectClusteringSchema.Message" )
);
String schemaName = dialog.open( idx );
if ( schemaName == null ) {
for ( StepMeta step : stepMetas ) {
step.setClusterSchema( null );
}
} else {
ClusterSchema clusterSchema = transMeta.findClusterSchema( schemaName );
for ( StepMeta step : stepMetas ) {
step.setClusterSchema( clusterSchema );
}
}
transMeta.setChanged();
refreshTree();
refreshGraph();
}
public void createKettleArchive( TransMeta transMeta ) {
if ( transMeta == null ) {
return;
}
JarfileGenerator.generateJarFile( transMeta );
}
/**
* This creates a new partitioning schema, edits it and adds it to the transformation metadata if its name is not a
* duplicate of any of existing
*/
public void newPartitioningSchema( TransMeta transMeta ) {
delegates.partitions.newPartitioningSchema( transMeta );
}
private void editPartitionSchema( TransMeta transMeta, PartitionSchema partitionSchema ) {
PartitionSchemaDialog dialog =
new PartitionSchemaDialog( shell, partitionSchema, transMeta.getDatabases(), transMeta );
if ( dialog.open() ) {
refreshTree();
}
}
private void delPartitionSchema( TransMeta transMeta, PartitionSchema partitionSchema ) {
try {
if ( rep != null && partitionSchema.getObjectId() != null ) {
// remove the partition schema from the repository too...
rep.deletePartitionSchema( partitionSchema.getObjectId() );
}
int idx = transMeta.getPartitionSchemas().indexOf( partitionSchema );
transMeta.getPartitionSchemas().remove( idx );
refreshTree();
} catch ( KettleException e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorDeletingClusterSchema.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorDeletingClusterSchema.Message" ), e );
}
}
/**
* This creates a new clustering schema, edits it and adds it to the transformation metadata if its name is not a
* duplicate of any of existing
*/
public void newClusteringSchema( TransMeta transMeta ) {
delegates.clusters.newClusteringSchema( transMeta );
}
private void editClusterSchema( TransMeta transMeta, ClusterSchema clusterSchema ) {
ClusterSchemaDialog dialog = new ClusterSchemaDialog( shell, clusterSchema, transMeta.getSlaveServers() );
if ( dialog.open() ) {
refreshTree();
}
}
private void delClusterSchema( TransMeta transMeta, ClusterSchema clusterSchema ) {
try {
if ( rep != null && clusterSchema.getObjectId() != null ) {
// remove the partition schema from the repository too...
rep.deleteClusterSchema( clusterSchema.getObjectId() );
}
int idx = transMeta.getClusterSchemas().indexOf( clusterSchema );
transMeta.getClusterSchemas().remove( idx );
refreshTree();
} catch ( KettleException e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorDeletingPartitionSchema.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorDeletingPartitionSchema.Message" ), e );
}
}
/**
* This creates a slave server, edits it and adds it to the transformation metadata
*
*/
public void newSlaveServer( HasSlaveServersInterface hasSlaveServersInterface ) {
delegates.slaves.newSlaveServer( hasSlaveServersInterface );
}
public void delSlaveServer( HasSlaveServersInterface hasSlaveServersInterface, SlaveServer slaveServer ) {
try {
delegates.slaves.delSlaveServer( hasSlaveServersInterface, slaveServer );
} catch ( KettleException e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorDeletingSlave.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorDeletingSlave.Message" ), e );
}
}
/**
* Sends transformation to slave server
*
* @param executionConfiguration
*/
public void sendTransformationXMLToSlaveServer( TransMeta transMeta,
TransExecutionConfiguration executionConfiguration ) {
try {
Trans.sendToSlaveServer( transMeta, executionConfiguration, rep, metaStore );
} catch ( Exception e ) {
new ErrorDialog( shell, "Error", "Error sending transformation to server", e );
}
}
public void runFile() {
executeFile( true, false, false, false, false, null, false );
}
public void replayTransformation() {
TransExecutionConfiguration tc = this.getTransExecutionConfiguration();
executeFile(
tc.isExecutingLocally(), tc.isExecutingRemotely(), tc.isExecutingClustered(), false, false, new Date(),
false );
}
public void previewFile() {
executeFile( true, false, false, true, false, null, true );
}
public void debugFile() {
executeFile( true, false, false, false, true, null, true );
}
public void executeFile( boolean local, boolean remote, boolean cluster, boolean preview, boolean debug,
Date replayDate, boolean safe ) {
TransMeta transMeta = getActiveTransformation();
if ( transMeta != null ) {
executeTransformation(
transMeta, local, remote, cluster, preview, debug, replayDate, safe, transExecutionConfiguration
.getLogLevel() );
}
JobMeta jobMeta = getActiveJob();
if ( jobMeta != null ) {
executeJob( jobMeta, local, remote, replayDate, safe, null, 0 );
}
}
public void executeTransformation( final TransMeta transMeta, final boolean local, final boolean remote,
final boolean cluster, final boolean preview, final boolean debug, final Date replayDate,
final boolean safe, final LogLevel logLevel ) {
if ( RepositorySecurityUI.verifyOperations( shell, rep, RepositoryOperation.EXECUTE_TRANSFORMATION ) ) {
return;
}
Thread thread = new Thread() {
public void run() {
getDisplay().asyncExec( new Runnable() {
public void run() {
try {
delegates.trans.executeTransformation(
transMeta, local, remote, cluster, preview, debug, replayDate, safe, logLevel );
} catch ( Exception e ) {
new ErrorDialog(
shell, "Execute transformation", "There was an error during transformation execution", e );
}
}
} );
}
};
thread.start();
}
public void executeJob( JobMeta jobMeta, boolean local, boolean remote, Date replayDate, boolean safe,
String startCopyName, int startCopyNr ) {
if ( RepositorySecurityUI.verifyOperations( shell, rep, RepositoryOperation.EXECUTE_JOB ) ) {
return;
}
try {
delegates.jobs.executeJob( jobMeta, local, remote, replayDate, safe, startCopyName, startCopyNr );
} catch ( Exception e ) {
new ErrorDialog( shell, "Execute job", "There was an error during job execution", e );
}
}
public void addSpoonSlave( SlaveServer slaveServer ) {
delegates.slaves.addSpoonSlave( slaveServer );
}
public void addJobHistory( JobMeta jobMeta, boolean select ) {
JobGraph activeJobGraph = getActiveJobGraph();
if ( activeJobGraph != null ) {
activeJobGraph.jobHistoryDelegate.addJobHistory();
}
// delegates.jobs.addJobHistory(jobMeta, select);
}
public void paste() {
String clipContent = fromClipboard();
if ( clipContent != null ) {
// Load the XML
//
try {
Document document = XMLHandler.loadXMLString( clipContent );
boolean transformation = XMLHandler.getSubNode( document, TransMeta.XML_TAG ) != null;
boolean job = XMLHandler.getSubNode( document, JobMeta.XML_TAG ) != null;
boolean steps = XMLHandler.getSubNode( document, Spoon.XML_TAG_TRANSFORMATION_STEPS ) != null;
boolean jobEntries = XMLHandler.getSubNode( document, Spoon.XML_TAG_JOB_JOB_ENTRIES ) != null;
if ( transformation ) {
pasteTransformation();
} else if ( job ) {
pasteJob();
} else if ( steps ) {
TransGraph transGraph = getActiveTransGraph();
if ( transGraph != null && transGraph.getLastMove() != null ) {
pasteXML( transGraph.getManagedObject(), clipContent, transGraph.getLastMove() );
}
} else if ( jobEntries ) {
JobGraph jobGraph = getActiveJobGraph();
if ( jobGraph != null && jobGraph.getLastMove() != null ) {
pasteXML( jobGraph.getManagedObject(), clipContent, jobGraph.getLastMove() );
}
}
} catch ( KettleXMLException e ) {
log.logError( "Unable to paste", e );
}
}
}
public JobEntryCopy newJobEntry( JobMeta jobMeta, String typeDesc, boolean openit ) {
return delegates.jobs.newJobEntry( jobMeta, typeDesc, openit );
}
public JobEntryDialogInterface getJobEntryDialog( JobEntryInterface jei, JobMeta jobMeta ) {
return delegates.jobs.getJobEntryDialog( jei, jobMeta );
}
public StepDialogInterface getStepEntryDialog( StepMetaInterface stepMeta, TransMeta transMeta, String stepName ) {
try {
return delegates.steps.getStepDialog( stepMeta, transMeta, stepName );
} catch ( Throwable t ) {
log.logError( "Could not create dialog for " + stepMeta.getDialogClassName(), t );
}
return null;
}
public void editJobEntry( JobMeta jobMeta, JobEntryCopy je ) {
delegates.jobs.editJobEntry( jobMeta, je );
}
public void deleteJobEntryCopies( JobMeta jobMeta, JobEntryCopy[] jobEntry ) {
delegates.jobs.deleteJobEntryCopies( jobMeta, jobEntry );
}
public void deleteJobEntryCopies( JobMeta jobMeta, JobEntryCopy jobEntry ) {
delegates.jobs.deleteJobEntryCopies( jobMeta, jobEntry );
}
public void pasteXML( JobMeta jobMeta, String clipContent, Point loc ) {
if ( RepositorySecurityUI.verifyOperations( shell, rep,
RepositoryOperation.MODIFY_JOB, RepositoryOperation.EXECUTE_JOB ) ) {
return;
}
delegates.jobs.pasteXML( jobMeta, clipContent, loc );
}
public void newJobHop( JobMeta jobMeta, JobEntryCopy fr, JobEntryCopy to ) {
delegates.jobs.newJobHop( jobMeta, fr, to );
}
/**
* Create a job that extracts tables & data from a database.
* <p>
* <p>
*
* 0) Select the database to rip
* <p>
* 1) Select the tables in the database to rip
* <p>
* 2) Select the database to dump to
* <p>
* 3) Select the repository directory in which it will end up
* <p>
* 4) Select a name for the new job
* <p>
* 5) Create an empty job with the selected name.
* <p>
* 6) Create 1 transformation for every selected table
* <p>
* 7) add every created transformation to the job & evaluate
* <p>
*
*/
public void ripDBWizard() {
delegates.jobs.ripDBWizard();
}
public JobMeta ripDB( final List<DatabaseMeta> databases, final String jobName,
final RepositoryDirectory repdir, final String directory, final DatabaseMeta sourceDbInfo,
final DatabaseMeta targetDbInfo, final String[] tables ) {
return delegates.jobs.ripDB( databases, jobName, repdir, directory, sourceDbInfo, targetDbInfo, tables );
}
/**
* Set the core object state.
*
* @param state state to set
*/
public void setCoreObjectsState( int state ) {
coreObjectsState = state;
}
/**
* Get the core object state.
*
* @return state.
*/
public int getCoreObjectsState() {
return coreObjectsState;
}
public LogChannelInterface getLog() {
return log;
}
public Repository getRepository() {
return rep;
}
public void setRepository( Repository rep ) {
this.rep = rep;
try {
// Keep one metastore here...
//
if ( metaStore.getMetaStoreList().size() > 1 ) {
metaStore.getMetaStoreList().remove( 0 );
metaStore.setActiveMetaStoreName( metaStore.getMetaStoreList().get( 0 ).getName() );
}
if ( rep != null ) {
this.capabilities = rep.getRepositoryMeta().getRepositoryCapabilities();
// add a wrapper metastore to the delegation
//
IMetaStore repositoryMetaStore = rep.getMetaStore();
if ( repositoryMetaStore != null ) {
metaStore.addMetaStore( 0, repositoryMetaStore ); // first priority for explicitly connected repositories.
metaStore.setActiveMetaStoreName( repositoryMetaStore.getName() );
log.logBasic( "Connected to metastore : "
+ repositoryMetaStore.getName() + ", added to delegating metastore" );
} else {
log.logBasic( "No metastore found in the repository : "
+ rep.getName() + ", connected? " + rep.isConnected() );
}
}
} catch ( MetaStoreException e ) {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "Spoon.Dialog.ErrorAddingRepositoryMetaStore.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Message" ), e );
}
// Registering the UI Support classes
UISupportRegistery.getInstance().registerUISupport(
RepositorySecurityProvider.class, BaseRepositoryExplorerUISupport.class );
UISupportRegistery
.getInstance().registerUISupport( RepositorySecurityManager.class, ManageUserUISupport.class );
if ( rep != null ) {
SpoonPluginManager.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.REPOSITORY_CHANGED );
}
delegates.update( this );
enableMenus();
}
public void addMenuListener( String id, Object listener, String methodName ) {
menuListeners.add( new Object[] { id, listener, methodName } );
}
public void addTransGraph( TransMeta transMeta ) {
delegates.trans.addTransGraph( transMeta );
}
public void addJobGraph( JobMeta jobMeta ) {
delegates.jobs.addJobGraph( jobMeta );
}
public boolean addSpoonBrowser( String name, String urlString, LocationListener locationListener ) {
return delegates.tabs.addSpoonBrowser( name, urlString, locationListener );
}
public boolean addSpoonBrowser( String name, String urlString ) {
return delegates.tabs.addSpoonBrowser( name, urlString, null );
}
public TransExecutionConfiguration getTransExecutionConfiguration() {
return transExecutionConfiguration;
}
public void editStepErrorHandling( TransMeta transMeta, StepMeta stepMeta ) {
delegates.steps.editStepErrorHandling( transMeta, stepMeta );
}
public String editStep( TransMeta transMeta, StepMeta stepMeta ) {
return delegates.steps.editStep( transMeta, stepMeta );
}
public void dupeStep( TransMeta transMeta, StepMeta stepMeta ) {
delegates.steps.dupeStep( transMeta, stepMeta );
}
public void delSteps( TransMeta transformation, StepMeta[] steps ) {
delegates.steps.delSteps( transformation, steps );
}
public void delStep( TransMeta transMeta, StepMeta stepMeta ) {
delegates.steps.delStep( transMeta, stepMeta );
}
public String makeTabName( EngineMetaInterface transMeta, boolean showingLocation ) {
return delegates.tabs.makeTabName( transMeta, showingLocation );
}
public void newConnection() {
delegates.db.newConnection();
}
public void getSQL() {
delegates.db.getSQL();
}
public boolean overwritePrompt( String message, String rememberText, String rememberPropertyName ) {
return new PopupOverwritePrompter( shell, props ).overwritePrompt( message, rememberText, rememberPropertyName );
}
public Object[] messageDialogWithToggle( String dialogTitle, Object image, String message, int dialogImageType,
String[] buttonLabels, int defaultIndex, String toggleMessage, boolean toggleState ) {
return GUIResource.getInstance().messageDialogWithToggle(
shell, dialogTitle, (Image) image, message, dialogImageType, buttonLabels, defaultIndex, toggleMessage,
toggleState );
}
public boolean messageBox( final String message, final String text, final boolean allowCancel, final int type ) {
final StringBuffer answer = new StringBuffer( "N" );
display.syncExec( new Runnable() {
@Override
public void run() {
int flags = SWT.OK;
if ( allowCancel ) {
flags |= SWT.CANCEL;
}
switch ( type ) {
case Const.INFO:
flags |= SWT.ICON_INFORMATION;
break;
case Const.ERROR:
flags |= SWT.ICON_ERROR;
break;
case Const.WARNING:
flags |= SWT.ICON_WARNING;
break;
default:
break;
}
MessageBox mb = new MessageBox( shell, flags );
// Set the Body Message
mb.setMessage( message );
// Set the title Message
mb.setText( text );
if ( mb.open() == SWT.OK ) {
answer.setCharAt( 0, 'Y' );
}
}
} );
return "Y".equalsIgnoreCase( answer.toString() );
}
/**
* @return the previewExecutionConfiguration
*/
public TransExecutionConfiguration getTransPreviewExecutionConfiguration() {
return transPreviewExecutionConfiguration;
}
/**
* @param previewExecutionConfiguration
* the previewExecutionConfiguration to set
*/
public void setTransPreviewExecutionConfiguration( TransExecutionConfiguration previewExecutionConfiguration ) {
this.transPreviewExecutionConfiguration = previewExecutionConfiguration;
}
/**
* @return the debugExecutionConfiguration
*/
public TransExecutionConfiguration getTransDebugExecutionConfiguration() {
return transDebugExecutionConfiguration;
}
/**
* @param debugExecutionConfiguration
* the debugExecutionConfiguration to set
*/
public void setTransDebugExecutionConfiguration( TransExecutionConfiguration debugExecutionConfiguration ) {
this.transDebugExecutionConfiguration = debugExecutionConfiguration;
}
/**
* @param executionConfiguration
* the executionConfiguration to set
*/
public void setTransExecutionConfiguration( TransExecutionConfiguration executionConfiguration ) {
this.transExecutionConfiguration = executionConfiguration;
}
/**
* @return the jobExecutionConfiguration
*/
public JobExecutionConfiguration getJobExecutionConfiguration() {
return jobExecutionConfiguration;
}
/**
* @param jobExecutionConfiguration
* the jobExecutionConfiguration to set
*/
public void setJobExecutionConfiguration( JobExecutionConfiguration jobExecutionConfiguration ) {
this.jobExecutionConfiguration = jobExecutionConfiguration;
}
/*
* public XulToolbar getToolbar() { return toolbar; }
*/
public void update( ChangedFlagInterface o, Object arg ) {
try {
Method m = getClass().getMethod( arg.toString() );
if ( m != null ) {
m.invoke( this );
}
} catch ( Exception e ) {
// ignore... let the other notifiers try to do something
System.out.println( "Unable to update: " + e.getLocalizedMessage() );
}
}
public void consume( final LifeEventInfo info ) {
// if (PropsUI.getInstance().isListenerDisabled(info.getName()))
// return;
if ( info.hasHint( LifeEventInfo.Hint.DISPLAY_BROWSER ) ) {
display.asyncExec( new Runnable() {
public void run() {
delegates.tabs.addSpoonBrowser( info.getName(), info.getMessage(), false, null );
}
} );
} else {
MessageBox box =
new MessageBox( shell, ( info.getState() != LifeEventInfo.State.SUCCESS
? SWT.ICON_ERROR : SWT.ICON_INFORMATION )
| SWT.OK );
box.setText( info.getName() );
box.setMessage( info.getMessage() );
box.open();
}
}
public void setLog() {
LogSettingsDialog lsd = new LogSettingsDialog( shell, SWT.NONE, props );
lsd.open();
log.setLogLevel( DefaultLogLevel.getLogLevel() );
}
/**
* @return the display
*/
public Display getDisplay() {
return display;
}
public void zoomIn() {
TransGraph transGraph = getActiveTransGraph();
if ( transGraph != null ) {
transGraph.zoomIn();
}
JobGraph jobGraph = getActiveJobGraph();
if ( jobGraph != null ) {
jobGraph.zoomIn();
}
}
public void zoomOut() {
TransGraph transGraph = getActiveTransGraph();
if ( transGraph != null ) {
transGraph.zoomOut();
}
JobGraph jobGraph = getActiveJobGraph();
if ( jobGraph != null ) {
jobGraph.zoomOut();
}
}
public void zoom100Percent() {
TransGraph transGraph = getActiveTransGraph();
if ( transGraph != null ) {
transGraph.zoom100Percent();
}
JobGraph jobGraph = getActiveJobGraph();
if ( jobGraph != null ) {
jobGraph.zoom100Percent();
}
}
public void setParametersAsVariablesInUI( NamedParams namedParameters, VariableSpace space ) {
for ( String param : namedParameters.listParameters() ) {
try {
space.setVariable( param, Const.NVL( namedParameters.getParameterValue( param ), Const.NVL(
namedParameters.getParameterDefault( param ), Const.NVL( space.getVariable( param ), "" ) ) ) );
} catch ( Exception e ) {
// ignore this
}
}
}
public void browseVersionHistory() {
if ( rep == null ) {
return;
}
TransGraph transGraph = getActiveTransGraph();
if ( transGraph != null ) {
transGraph.browseVersionHistory();
}
JobGraph jobGraph = getActiveJobGraph();
if ( jobGraph != null ) {
jobGraph.browseVersionHistory();
}
}
public Trans findActiveTrans( Job job, JobEntryCopy jobEntryCopy ) {
JobEntryTrans jobEntryTrans = job.getActiveJobEntryTransformations().get( jobEntryCopy );
if ( jobEntryTrans == null ) {
return null;
}
return jobEntryTrans.getTrans();
}
public Job findActiveJob( Job job, JobEntryCopy jobEntryCopy ) {
JobEntryJob jobEntryJob = job.getActiveJobEntryJobs().get( jobEntryCopy );
if ( jobEntryJob == null ) {
return null;
}
return jobEntryJob.getJob();
}
public Object getSelectionObject() {
return selectionObject;
}
public RepositoryDirectoryInterface getDefaultSaveLocation( RepositoryElementInterface repositoryElement ) {
try {
if ( getRepository() != defaultSaveLocationRepository ) {
// The repository has changed, reset the defaultSaveLocation
defaultSaveLocation = null;
defaultSaveLocationRepository = null;
}
if ( defaultSaveLocation == null ) {
if ( getRepository() != null ) {
defaultSaveLocation = getRepository().getDefaultSaveDirectory( repositoryElement );
defaultSaveLocationRepository = getRepository();
} else {
defaultSaveLocation = new RepositoryDirectory();
}
}
} catch ( Exception e ) {
throw new RuntimeException( e );
}
return defaultSaveLocation;
}
/* ========================= XulEventSource Methods ========================== */
protected PropertyChangeSupport changeSupport = new PropertyChangeSupport( this );
public void addPropertyChangeListener( PropertyChangeListener listener ) {
changeSupport.addPropertyChangeListener( listener );
}
public void addPropertyChangeListener( String propertyName, PropertyChangeListener listener ) {
changeSupport.addPropertyChangeListener( propertyName, listener );
}
public void removePropertyChangeListener( PropertyChangeListener listener ) {
changeSupport.removePropertyChangeListener( listener );
}
protected void firePropertyChange( String attr, Object previousVal, Object newVal ) {
if ( previousVal == null && newVal == null ) {
return;
}
changeSupport.firePropertyChange( attr, previousVal, newVal );
}
/*
* ========================= End XulEventSource Methods ==========================
*/
/*
* ========================= Start XulEventHandler Methods ==========================
*/
public Object getData() {
return null;
}
public String getName() {
return "spoon";
}
public XulDomContainer getXulDomContainer() {
return getMainSpoonContainer();
}
public void setData( Object arg0 ) {
}
public void setName( String arg0 ) {
}
public void setXulDomContainer( XulDomContainer arg0 ) {
}
public RepositorySecurityManager getSecurityManager() {
return rep.getSecurityManager();
}
public void displayDbDependancies() {
TreeItem[] selection = selectionTree.getSelection();
if ( selection == null || selection.length != 1 ) {
return;
}
// Clear all dependencies for select connection
TreeItem parent = selection[0];
if ( parent != null ) {
int nrChilds = parent.getItemCount();
if ( nrChilds > 0 ) {
for ( int i = 0; i < nrChilds; i++ ) {
parent.getItem( i ).dispose();
}
}
}
if ( rep == null ) {
return;
}
try {
final DatabaseMeta databaseMeta = (DatabaseMeta) selectionObject;
String[] jobList = rep.getJobsUsingDatabase( databaseMeta.getObjectId() );
String[] transList = rep.getTransformationsUsingDatabase( databaseMeta.getObjectId() );
if ( jobList.length == 0 && transList.length == 0 ) {
MessageBox box = new MessageBox( shell, SWT.ICON_INFORMATION | SWT.OK );
box.setText( "Connection dependencies" );
box.setMessage( "This connection is not used by a job nor a transformation." );
box.open();
} else {
for ( String aJobList : jobList ) {
if ( aJobList != null ) {
createTreeItem( parent, aJobList, GUIResource.getInstance().getImageJobGraph() );
}
}
for ( String aTransList : transList ) {
if ( aTransList != null ) {
createTreeItem( parent, aTransList, GUIResource.getInstance().getImageTransGraph() );
}
}
parent.setExpanded( true );
}
} catch ( Exception e ) {
new ErrorDialog( shell, "Error", "Error getting dependencies! :", e );
}
}
public void fireMenuControlers() {
if ( !Display.getDefault().getThread().equals( Thread.currentThread() ) ) {
display.syncExec( new Runnable() {
public void run() {
fireMenuControlers();
}
} );
return;
}
org.pentaho.ui.xul.dom.Document doc;
if ( mainSpoonContainer != null ) {
doc = mainSpoonContainer.getDocumentRoot();
for ( ISpoonMenuController menuController : menuControllers ) {
menuController.updateMenu( doc );
}
}
}
public void hideSplash() {
if ( splash != null ) {
splash.hide();
}
}
private void showSplash() {
if ( splash != null ) {
splash.show();
}
}
/**
* Hides or shows the main toolbar
*
* @param visible
*/
public void setMainToolbarVisible( boolean visible ) {
mainToolbar.setVisible( visible );
}
public void setMenuBarVisible( boolean visible ) {
mainSpoonContainer.getDocumentRoot().getElementById( "edit" ).setVisible( visible );
mainSpoonContainer.getDocumentRoot().getElementById( "file" ).setVisible( visible );
mainSpoonContainer.getDocumentRoot().getElementById( "view" ).setVisible( visible );
mainSpoonContainer.getDocumentRoot().getElementById( "action" ).setVisible( visible );
mainSpoonContainer.getDocumentRoot().getElementById( "tools" ).setVisible( visible );
mainSpoonContainer.getDocumentRoot().getElementById( "help" ).setVisible( visible );
MenuManager menuManager = getMenuBarManager();
menuManager.getMenu().setVisible( visible );
menuManager.updateAll( true );
}
@Override
protected Control createContents( Composite parent ) {
shell = getShell();
init( null );
openSpoon();
// listeners
//
try {
lifecycleSupport.onStart( this );
} catch ( LifecycleException e ) {
// if severe, we have to quit
MessageBox box = new MessageBox( shell, ( e.isSevere() ? SWT.ICON_ERROR : SWT.ICON_WARNING ) | SWT.OK );
box.setMessage( e.getMessage() );
box.open();
}
try {
start( commandLineOptions );
} catch ( KettleException e ) {
MessageBox box = new MessageBox( shell, SWT.ICON_ERROR | SWT.OK );
box.setMessage( e.getMessage() );
box.open();
}
getMenuBarManager().updateAll( true );
return parent;
}
public void start() {
// We store the UI thread for the getDisplay() method
setBlockOnOpen( false );
try {
open();
waitForDispose();
// runEventLoop2(getShell());
} catch ( Throwable e ) {
LogChannel.GENERAL.logError( "Error starting Spoon shell", e );
}
System.out.println( "stopping" );
}
public String getStartupPerspective() {
return startupPerspective;
}
public DelegatingMetaStore getMetaStore() {
return metaStore;
}
public void setMetaStore( DelegatingMetaStore metaStore ) {
this.metaStore = metaStore;
}
private void onLoginError( Throwable t ) {
if ( t instanceof KettleAuthException ) {
ShowMessageDialog dialog =
new ShowMessageDialog( loginDialog.getShell(), SWT.OK | SWT.ICON_ERROR, BaseMessages.getString(
PKG, "Spoon.Dialog.LoginFailed.Title" ), t.getLocalizedMessage() );
dialog.open();
} else {
new ErrorDialog(
loginDialog.getShell(), BaseMessages.getString( PKG, "Spoon.Dialog.LoginFailed.Title" ), BaseMessages
.getString( PKG, "Spoon.Dialog.LoginFailed.Message", t ), t );
}
}
@Override
protected void handleShellCloseEvent() {
try {
if ( quitFile( true ) ) {
SpoonPluginManager.getInstance().notifyLifecycleListeners( SpoonLifeCycleEvent.SHUTDOWN );
super.handleShellCloseEvent();
}
} catch ( Exception e ) {
LogChannel.GENERAL.logError( "Error closing Spoon", e );
}
}
public void showAuthenticationOptions() {
AuthProviderDialog authProviderDialog = new AuthProviderDialog( shell );
authProviderDialog.show();
}
}
| apache-2.0 |
alibaba/canal | instance/manager/src/main/java/com/alibaba/otter/canal/instance/manager/model/CanalParameter.java | 32811 | package com.alibaba.otter.canal.instance.manager.model;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.alibaba.otter.canal.common.utils.CanalToStringStyle;
/**
* canal运行相关参数
*
* @author jianghang 2012-7-4 下午02:52:52
* @version 1.0.0
*/
public class CanalParameter implements Serializable {
private static final long serialVersionUID = -5893459662315430900L;
private Long canalId;
// 相关参数
private RunMode runMode = RunMode.EMBEDDED; // 运行模式:嵌入式/服务式
private ClusterMode clusterMode = ClusterMode.STANDALONE; // 集群模式:单机/冷备/热备份
private Long zkClusterId; // zk集群id,为管理方便
private List<String> zkClusters; // zk集群地址
private String dataDir = "../conf"; // 默认本地文件数据的目录默认是conf
// meta相关参数
private MetaMode metaMode = MetaMode.MEMORY; // meta机制
private Integer metaFileFlushPeriod = 1000; // meta刷新间隔
// storage存储
private Integer transactionSize = 1024; // 支持处理的transaction事务大小
private StorageMode storageMode = StorageMode.MEMORY; // 存储机制
private BatchMode storageBatchMode = BatchMode.MEMSIZE; // 基于大小返回结果
private Integer memoryStorageBufferSize = 16 * 1024; // 内存存储的buffer大小
private Integer memoryStorageBufferMemUnit = 1024; // 内存存储的buffer内存占用单位,默认为1kb
private Boolean memoryStorageRawEntry = Boolean.TRUE; // 内存存储的对象是否启用raw的ByteString模式
private String fileStorageDirectory; // 文件存储的目录位置
private Integer fileStorageStoreCount; // 每个文件store存储的记录数
private Integer fileStorageRollverCount; // store文件的个数
private Integer fileStoragePercentThresold; // 整个store存储占disk硬盘的百分比,超过百分比及时条数还未满也不写入
private StorageScavengeMode storageScavengeMode = StorageScavengeMode.ON_ACK;
private String scavengeSchdule; // 调度规则
// replcation相关参数
private SourcingType sourcingType = SourcingType.MYSQL; // 数据来源类型
private String localBinlogDirectory; // 本地localBinlog目录
private HAMode haMode = HAMode.HEARTBEAT; // ha机制
// 网络链接参数
private Integer port = 11111; // 服务端口,独立运行时需要配置
private Integer defaultConnectionTimeoutInSeconds = 30; // sotimeout
private Integer receiveBufferSize = 64 * 1024;
private Integer sendBufferSize = 64 * 1024;
// 编码信息
private Byte connectionCharsetNumber = (byte) 33;
private String connectionCharset = "UTF-8";
// 数据库信息
private List<InetSocketAddress> dbAddresses; // 数据库链接信息
private List<List<DataSourcing>> groupDbAddresses; // 数据库链接信息,包含多组信息
private String dbUsername; // 数据库用户
private String dbPassword; // 数据库密码
// binlog链接信息
private IndexMode indexMode;
private List<String> positions; // 数据库positions信息
private String defaultDatabaseName; // 默认链接的数据库schmea
private Long slaveId; // 链接到mysql的slaveId
private Integer fallbackIntervalInSeconds = 60; // 数据库发生切换查找时回退的时间
// 心跳检查信息
private Boolean detectingEnable = true; // 是否开启心跳语句
private Boolean heartbeatHaEnable = false; // 是否开启基于心跳检查的ha功能
private String detectingSQL; // 心跳sql
private Integer detectingIntervalInSeconds = 3; // 检测频率
private Integer detectingTimeoutThresholdInSeconds = 30; // 心跳超时时间
private Integer detectingRetryTimes = 3; // 心跳检查重试次数
// tddl/diamond 配置信息
private String app;
private String group;
// media配置信息
private String mediaGroup;
// metaq 存储配置信息
private String metaqStoreUri;
// ddl同步支持,隔离dml/ddl
private Boolean ddlIsolation = Boolean.FALSE; // 是否将ddl单条返回
private Boolean filterTableError = Boolean.FALSE; // 是否忽略表解析异常
private String blackFilter = null; // 匹配黑名单,忽略解析
private Boolean tsdbEnable = Boolean.FALSE; // 是否开启tableMetaTSDB
private String tsdbJdbcUrl;
private String tsdbJdbcUserName;
private String tsdbJdbcPassword;
private Integer tsdbSnapshotInterval = 24;
private Integer tsdbSnapshotExpire = 360;
private String rdsAccesskey;
private String rdsSecretkey;
private String rdsInstanceId;
private Boolean gtidEnable = Boolean.FALSE; // 是否开启gtid
// ================================== 兼容字段处理
private InetSocketAddress masterAddress; // 主库信息
private String masterUsername; // 帐号
private String masterPassword; // 密码
private InetSocketAddress standbyAddress; // 备库信息
private String standbyUsername; // 帐号
private String standbyPassword;
private String masterLogfileName = null; // master起始位置
private Long masterLogfileOffest = null;
private Long masterTimestamp = null;
private String standbyLogfileName = null; // standby起始位置
private Long standbyLogfileOffest = null;
private Long standbyTimestamp = null;
private Boolean parallel = Boolean.FALSE;
//自定义alarmHandler类全路径
private String alarmHandlerClass = null;
//自定义alarmHandler插件文件夹路径
private String alarmHandlerPluginDir = null;
public static enum RunMode {
/** 嵌入式 */
EMBEDDED,
/** 服务式 */
SERVICE;
public boolean isEmbedded() {
return this.equals(RunMode.EMBEDDED);
}
public boolean isService() {
return this.equals(RunMode.SERVICE);
}
}
public static enum ClusterMode {
/** 嵌入式 */
STANDALONE,
/** 冷备 */
STANDBY,
/** 热备 */
ACTIVE;
public boolean isStandalone() {
return this.equals(ClusterMode.STANDALONE);
}
public boolean isStandby() {
return this.equals(ClusterMode.STANDBY);
}
public boolean isActive() {
return this.equals(ClusterMode.ACTIVE);
}
}
public static enum HAMode {
/** 心跳检测 */
HEARTBEAT,
/** otter media */
MEDIA;
public boolean isHeartBeat() {
return this.equals(HAMode.HEARTBEAT);
}
public boolean isMedia() {
return this.equals(HAMode.MEDIA);
}
}
public static enum StorageMode {
/** 内存存储模式 */
MEMORY,
/** 文件存储模式 */
FILE,
/** 混合模式,内存+文件 */
MIXED;
public boolean isMemory() {
return this.equals(StorageMode.MEMORY);
}
public boolean isFile() {
return this.equals(StorageMode.FILE);
}
public boolean isMixed() {
return this.equals(StorageMode.MIXED);
}
}
public static enum StorageScavengeMode {
/** 在存储满的时候触发 */
ON_FULL,
/** 在每次有ack请求时触发 */
ON_ACK,
/** 定时触发,需要外部控制 */
ON_SCHEDULE,
/** 不做任何操作,由外部进行清理 */
NO_OP;
public boolean isOnFull() {
return this.equals(StorageScavengeMode.ON_FULL);
}
public boolean isOnAck() {
return this.equals(StorageScavengeMode.ON_ACK);
}
public boolean isOnSchedule() {
return this.equals(StorageScavengeMode.ON_SCHEDULE);
}
public boolean isNoop() {
return this.equals(StorageScavengeMode.NO_OP);
}
}
public static enum SourcingType {
/** mysql DB */
MYSQL,
/** localBinLog */
LOCALBINLOG,
/** oracle DB */
ORACLE,
/** 多库合并模式 */
GROUP;
public boolean isMysql() {
return this.equals(SourcingType.MYSQL);
}
public boolean isLocalBinlog() {
return this.equals(SourcingType.LOCALBINLOG);
}
public boolean isOracle() {
return this.equals(SourcingType.ORACLE);
}
public boolean isGroup() {
return this.equals(SourcingType.GROUP);
}
}
public static enum MetaMode {
/** 内存存储模式 */
MEMORY,
/** 文件存储模式 */
ZOOKEEPER,
/** 混合模式,内存+文件 */
MIXED,
/** 本地文件存储模式 */
LOCAL_FILE;
public boolean isMemory() {
return this.equals(MetaMode.MEMORY);
}
public boolean isZookeeper() {
return this.equals(MetaMode.ZOOKEEPER);
}
public boolean isMixed() {
return this.equals(MetaMode.MIXED);
}
public boolean isLocalFile() {
return this.equals(MetaMode.LOCAL_FILE);
}
}
public static enum IndexMode {
/** 内存存储模式 */
MEMORY,
/** 文件存储模式 */
ZOOKEEPER,
/** 混合模式,内存+文件 */
MIXED,
/** 基于meta信息 */
META,
/** 基于内存+meta的failback实现 */
MEMORY_META_FAILBACK;
public boolean isMemory() {
return this.equals(IndexMode.MEMORY);
}
public boolean isZookeeper() {
return this.equals(IndexMode.ZOOKEEPER);
}
public boolean isMixed() {
return this.equals(IndexMode.MIXED);
}
public boolean isMeta() {
return this.equals(IndexMode.META);
}
public boolean isMemoryMetaFailback() {
return this.equals(IndexMode.MEMORY_META_FAILBACK);
}
}
public static enum BatchMode {
/** 对象数量 */
ITEMSIZE,
/** 内存大小 */
MEMSIZE;
public boolean isItemSize() {
return this == BatchMode.ITEMSIZE;
}
public boolean isMemSize() {
return this == BatchMode.MEMSIZE;
}
}
/**
* 数据来源描述
*
* @author jianghang 2012-12-26 上午11:05:20
* @version 4.1.5
*/
public static class DataSourcing implements Serializable {
private static final long serialVersionUID = -1770648468678085234L;
private SourcingType type;
private InetSocketAddress dbAddress;
public DataSourcing(){
}
public DataSourcing(SourcingType type, InetSocketAddress dbAddress){
this.type = type;
this.dbAddress = dbAddress;
}
public SourcingType getType() {
return type;
}
public void setType(SourcingType type) {
this.type = type;
}
public InetSocketAddress getDbAddress() {
return dbAddress;
}
public void setDbAddress(InetSocketAddress dbAddress) {
this.dbAddress = dbAddress;
}
}
public Long getCanalId() {
return canalId;
}
public void setCanalId(Long canalId) {
this.canalId = canalId;
}
public RunMode getRunMode() {
return runMode;
}
public void setRunMode(RunMode runMode) {
this.runMode = runMode;
}
public ClusterMode getClusterMode() {
return clusterMode;
}
public void setClusterMode(ClusterMode clusterMode) {
this.clusterMode = clusterMode;
}
public List<String> getZkClusters() {
return zkClusters;
}
public void setZkClusters(List<String> zkClusters) {
this.zkClusters = zkClusters;
}
public MetaMode getMetaMode() {
return metaMode;
}
public void setMetaMode(MetaMode metaMode) {
this.metaMode = metaMode;
}
public StorageMode getStorageMode() {
return storageMode;
}
public String getDataDir() {
return dataDir;
}
public void setDataDir(String dataDir) {
this.dataDir = dataDir;
}
public Integer getMetaFileFlushPeriod() {
return metaFileFlushPeriod;
}
public void setMetaFileFlushPeriod(Integer metaFileFlushPeriod) {
this.metaFileFlushPeriod = metaFileFlushPeriod;
}
public void setStorageMode(StorageMode storageMode) {
this.storageMode = storageMode;
}
public Integer getMemoryStorageBufferSize() {
return memoryStorageBufferSize;
}
public void setMemoryStorageBufferSize(Integer memoryStorageBufferSize) {
this.memoryStorageBufferSize = memoryStorageBufferSize;
}
public String getFileStorageDirectory() {
return fileStorageDirectory;
}
public void setFileStorageDirectory(String fileStorageDirectory) {
this.fileStorageDirectory = fileStorageDirectory;
}
public Integer getFileStorageStoreCount() {
return fileStorageStoreCount;
}
public void setFileStorageStoreCount(Integer fileStorageStoreCount) {
this.fileStorageStoreCount = fileStorageStoreCount;
}
public Integer getFileStorageRollverCount() {
return fileStorageRollverCount;
}
public void setFileStorageRollverCount(Integer fileStorageRollverCount) {
this.fileStorageRollverCount = fileStorageRollverCount;
}
public Integer getFileStoragePercentThresold() {
return fileStoragePercentThresold;
}
public void setFileStoragePercentThresold(Integer fileStoragePercentThresold) {
this.fileStoragePercentThresold = fileStoragePercentThresold;
}
public SourcingType getSourcingType() {
return sourcingType;
}
public void setSourcingType(SourcingType sourcingType) {
this.sourcingType = sourcingType;
}
public String getLocalBinlogDirectory() {
return localBinlogDirectory;
}
public void setLocalBinlogDirectory(String localBinlogDirectory) {
this.localBinlogDirectory = localBinlogDirectory;
}
public HAMode getHaMode() {
return haMode;
}
public void setHaMode(HAMode haMode) {
this.haMode = haMode;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public Integer getDefaultConnectionTimeoutInSeconds() {
return defaultConnectionTimeoutInSeconds;
}
public void setDefaultConnectionTimeoutInSeconds(Integer defaultConnectionTimeoutInSeconds) {
this.defaultConnectionTimeoutInSeconds = defaultConnectionTimeoutInSeconds;
}
public Integer getReceiveBufferSize() {
return receiveBufferSize;
}
public void setReceiveBufferSize(Integer receiveBufferSize) {
this.receiveBufferSize = receiveBufferSize;
}
public Integer getSendBufferSize() {
return sendBufferSize;
}
public void setSendBufferSize(Integer sendBufferSize) {
this.sendBufferSize = sendBufferSize;
}
public Byte getConnectionCharsetNumber() {
return connectionCharsetNumber;
}
public void setConnectionCharsetNumber(Byte connectionCharsetNumber) {
this.connectionCharsetNumber = connectionCharsetNumber;
}
public String getConnectionCharset() {
return connectionCharset;
}
public void setConnectionCharset(String connectionCharset) {
this.connectionCharset = connectionCharset;
}
public IndexMode getIndexMode() {
return indexMode;
}
public void setIndexMode(IndexMode indexMode) {
this.indexMode = indexMode;
}
public String getDefaultDatabaseName() {
return defaultDatabaseName;
}
public void setDefaultDatabaseName(String defaultDatabaseName) {
this.defaultDatabaseName = defaultDatabaseName;
}
public Long getSlaveId() {
return slaveId;
}
public void setSlaveId(Long slaveId) {
this.slaveId = slaveId;
}
public Boolean getDetectingEnable() {
return detectingEnable;
}
public void setDetectingEnable(Boolean detectingEnable) {
this.detectingEnable = detectingEnable;
}
public String getDetectingSQL() {
return detectingSQL;
}
public void setDetectingSQL(String detectingSQL) {
this.detectingSQL = detectingSQL;
}
public Integer getDetectingIntervalInSeconds() {
return detectingIntervalInSeconds;
}
public void setDetectingIntervalInSeconds(Integer detectingIntervalInSeconds) {
this.detectingIntervalInSeconds = detectingIntervalInSeconds;
}
public Integer getDetectingTimeoutThresholdInSeconds() {
return detectingTimeoutThresholdInSeconds;
}
public void setDetectingTimeoutThresholdInSeconds(Integer detectingTimeoutThresholdInSeconds) {
this.detectingTimeoutThresholdInSeconds = detectingTimeoutThresholdInSeconds;
}
public Integer getDetectingRetryTimes() {
return detectingRetryTimes;
}
public void setDetectingRetryTimes(Integer detectingRetryTimes) {
this.detectingRetryTimes = detectingRetryTimes;
}
public StorageScavengeMode getStorageScavengeMode() {
return storageScavengeMode;
}
public void setStorageScavengeMode(StorageScavengeMode storageScavengeMode) {
this.storageScavengeMode = storageScavengeMode;
}
public String getScavengeSchdule() {
return scavengeSchdule;
}
public void setScavengeSchdule(String scavengeSchdule) {
this.scavengeSchdule = scavengeSchdule;
}
public String getApp() {
return app;
}
public String getGroup() {
return group;
}
public void setApp(String app) {
this.app = app;
}
public void setGroup(String group) {
this.group = group;
}
public String getMetaqStoreUri() {
return metaqStoreUri;
}
public void setMetaqStoreUri(String metaqStoreUri) {
this.metaqStoreUri = metaqStoreUri;
}
public Integer getTransactionSize() {
return transactionSize != null ? transactionSize : 1024;
}
public void setTransactionSize(Integer transactionSize) {
this.transactionSize = transactionSize;
}
public List<InetSocketAddress> getDbAddresses() {
if (dbAddresses == null) {
dbAddresses = new ArrayList<>();
if (masterAddress != null) {
dbAddresses.add(masterAddress);
}
if (standbyAddress != null) {
dbAddresses.add(standbyAddress);
}
}
return dbAddresses;
}
public List<List<DataSourcing>> getGroupDbAddresses() {
if (groupDbAddresses == null) {
groupDbAddresses = new ArrayList<>();
if (dbAddresses != null) {
for (InetSocketAddress address : dbAddresses) {
List<DataSourcing> groupAddresses = new ArrayList<>();
groupAddresses.add(new DataSourcing(sourcingType, address));
groupDbAddresses.add(groupAddresses);
}
} else {
if (masterAddress != null) {
List<DataSourcing> groupAddresses = new ArrayList<>();
groupAddresses.add(new DataSourcing(sourcingType, masterAddress));
groupDbAddresses.add(groupAddresses);
}
if (standbyAddress != null) {
List<DataSourcing> groupAddresses = new ArrayList<>();
groupAddresses.add(new DataSourcing(sourcingType, standbyAddress));
groupDbAddresses.add(groupAddresses);
}
}
}
return groupDbAddresses;
}
public void setGroupDbAddresses(List<List<DataSourcing>> groupDbAddresses) {
this.groupDbAddresses = groupDbAddresses;
}
public void setDbAddresses(List<InetSocketAddress> dbAddresses) {
this.dbAddresses = dbAddresses;
}
public String getDbUsername() {
if (dbUsername == null) {
dbUsername = (masterUsername != null ? masterUsername : standbyUsername);
}
return dbUsername;
}
public void setDbUsername(String dbUsername) {
this.dbUsername = dbUsername;
}
public String getDbPassword() {
if (dbPassword == null) {
dbPassword = (masterPassword != null ? masterPassword : standbyPassword);
}
return dbPassword;
}
public void setDbPassword(String dbPassword) {
this.dbPassword = dbPassword;
}
public List<String> getPositions() {
if (positions == null) {
positions = new ArrayList<>();
String masterPosition = buildPosition(masterLogfileName, masterLogfileOffest, masterTimestamp);
if (masterPosition != null) {
positions.add(masterPosition);
}
String standbyPosition = buildPosition(standbyLogfileName, standbyLogfileOffest, standbyTimestamp);
if (standbyPosition != null) {
positions.add(standbyPosition);
}
}
return positions;
}
public void setPositions(List<String> positions) {
this.positions = positions;
}
// ===========================兼容字段
private String buildPosition(String journalName, Long position, Long timestamp) {
StringBuilder masterBuilder = new StringBuilder();
if (StringUtils.isNotEmpty(journalName) || position != null || timestamp != null) {
masterBuilder.append('{');
if (StringUtils.isNotEmpty(journalName)) {
masterBuilder.append("\"journalName\":\"").append(journalName).append("\"");
}
if (position != null) {
if (masterBuilder.length() > 1) {
masterBuilder.append(",");
}
masterBuilder.append("\"position\":").append(position);
}
if (timestamp != null) {
if (masterBuilder.length() > 1) {
masterBuilder.append(",");
}
masterBuilder.append("\"timestamp\":").append(timestamp);
}
masterBuilder.append('}');
return masterBuilder.toString();
} else {
return null;
}
}
public void setMasterUsername(String masterUsername) {
this.masterUsername = masterUsername;
}
public void setMasterPassword(String masterPassword) {
this.masterPassword = masterPassword;
}
public void setStandbyAddress(InetSocketAddress standbyAddress) {
this.standbyAddress = standbyAddress;
}
public void setStandbyUsername(String standbyUsername) {
this.standbyUsername = standbyUsername;
}
public void setStandbyPassword(String standbyPassword) {
this.standbyPassword = standbyPassword;
}
public void setMasterLogfileName(String masterLogfileName) {
this.masterLogfileName = masterLogfileName;
}
public void setMasterLogfileOffest(Long masterLogfileOffest) {
this.masterLogfileOffest = masterLogfileOffest;
}
public void setMasterTimestamp(Long masterTimestamp) {
this.masterTimestamp = masterTimestamp;
}
public void setStandbyLogfileName(String standbyLogfileName) {
this.standbyLogfileName = standbyLogfileName;
}
public void setStandbyLogfileOffest(Long standbyLogfileOffest) {
this.standbyLogfileOffest = standbyLogfileOffest;
}
public void setStandbyTimestamp(Long standbyTimestamp) {
this.standbyTimestamp = standbyTimestamp;
}
public void setMasterAddress(InetSocketAddress masterAddress) {
this.masterAddress = masterAddress;
}
public Integer getFallbackIntervalInSeconds() {
return fallbackIntervalInSeconds == null ? 60 : fallbackIntervalInSeconds;
}
public void setFallbackIntervalInSeconds(Integer fallbackIntervalInSeconds) {
this.fallbackIntervalInSeconds = fallbackIntervalInSeconds;
}
public Boolean getHeartbeatHaEnable() {
return heartbeatHaEnable == null ? false : heartbeatHaEnable;
}
public void setHeartbeatHaEnable(Boolean heartbeatHaEnable) {
this.heartbeatHaEnable = heartbeatHaEnable;
}
public BatchMode getStorageBatchMode() {
return storageBatchMode == null ? BatchMode.MEMSIZE : storageBatchMode;
}
public void setStorageBatchMode(BatchMode storageBatchMode) {
this.storageBatchMode = storageBatchMode;
}
public Integer getMemoryStorageBufferMemUnit() {
return memoryStorageBufferMemUnit == null ? 1024 : memoryStorageBufferMemUnit;
}
public void setMemoryStorageBufferMemUnit(Integer memoryStorageBufferMemUnit) {
this.memoryStorageBufferMemUnit = memoryStorageBufferMemUnit;
}
public String getMediaGroup() {
return mediaGroup;
}
public void setMediaGroup(String mediaGroup) {
this.mediaGroup = mediaGroup;
}
public Long getZkClusterId() {
return zkClusterId;
}
public void setZkClusterId(Long zkClusterId) {
this.zkClusterId = zkClusterId;
}
public Boolean getDdlIsolation() {
return ddlIsolation == null ? false : ddlIsolation;
}
public void setDdlIsolation(Boolean ddlIsolation) {
this.ddlIsolation = ddlIsolation;
}
public Boolean getFilterTableError() {
return filterTableError == null ? false : filterTableError;
}
public void setFilterTableError(Boolean filterTableError) {
this.filterTableError = filterTableError;
}
public String getBlackFilter() {
return blackFilter;
}
public void setBlackFilter(String blackFilter) {
this.blackFilter = blackFilter;
}
public Boolean getTsdbEnable() {
return tsdbEnable;
}
public void setTsdbEnable(Boolean tsdbEnable) {
this.tsdbEnable = tsdbEnable;
}
public String getTsdbJdbcUrl() {
return tsdbJdbcUrl;
}
public void setTsdbJdbcUrl(String tsdbJdbcUrl) {
this.tsdbJdbcUrl = tsdbJdbcUrl;
}
public String getTsdbJdbcUserName() {
return tsdbJdbcUserName;
}
public void setTsdbJdbcUserName(String tsdbJdbcUserName) {
this.tsdbJdbcUserName = tsdbJdbcUserName;
}
public String getTsdbJdbcPassword() {
return tsdbJdbcPassword;
}
public void setTsdbJdbcPassword(String tsdbJdbcPassword) {
this.tsdbJdbcPassword = tsdbJdbcPassword;
}
public String getRdsAccesskey() {
return rdsAccesskey;
}
public void setRdsAccesskey(String rdsAccesskey) {
this.rdsAccesskey = rdsAccesskey;
}
public String getRdsSecretkey() {
return rdsSecretkey;
}
public void setRdsSecretkey(String rdsSecretkey) {
this.rdsSecretkey = rdsSecretkey;
}
public String getRdsInstanceId() {
return rdsInstanceId;
}
public void setRdsInstanceId(String rdsInstanceId) {
this.rdsInstanceId = rdsInstanceId;
}
public Boolean getGtidEnable() {
return gtidEnable;
}
public void setGtidEnable(Boolean gtidEnable) {
this.gtidEnable = gtidEnable;
}
public Boolean getMemoryStorageRawEntry() {
return memoryStorageRawEntry;
}
public void setMemoryStorageRawEntry(Boolean memoryStorageRawEntry) {
this.memoryStorageRawEntry = memoryStorageRawEntry;
}
public Integer getTsdbSnapshotInterval() {
return tsdbSnapshotInterval;
}
public void setTsdbSnapshotInterval(Integer tsdbSnapshotInterval) {
this.tsdbSnapshotInterval = tsdbSnapshotInterval;
}
public Integer getTsdbSnapshotExpire() {
return tsdbSnapshotExpire;
}
public void setTsdbSnapshotExpire(Integer tsdbSnapshotExpire) {
this.tsdbSnapshotExpire = tsdbSnapshotExpire;
}
public Boolean getParallel() {
return parallel;
}
public void setParallel(Boolean parallel) {
this.parallel = parallel;
}
public String getAlarmHandlerClass() {
return alarmHandlerClass;
}
public void setAlarmHandlerClass(String alarmHandlerClass) {
this.alarmHandlerClass = alarmHandlerClass;
}
public String getAlarmHandlerPluginDir() {
return alarmHandlerPluginDir;
}
public void setAlarmHandlerPluginDir(String alarmHandlerPluginDir) {
this.alarmHandlerPluginDir = alarmHandlerPluginDir;
}
public String toString() {
return ToStringBuilder.reflectionToString(this, CanalToStringStyle.DEFAULT_STYLE);
}
}
| apache-2.0 |
smanvi-pivotal/geode | geode-core/src/test/java/org/apache/geode/internal/cache/ConcurrentRollingAndRegionOperationsJUnitTest.java | 30164 | /*
* 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.geode.internal.cache;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.EntryNotFoundException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.Scope;
import org.apache.geode.internal.cache.entries.DiskEntry;
import org.apache.geode.test.dunit.ThreadUtils;
import org.apache.geode.test.junit.categories.IntegrationTest;
/**
* This JUnit test tests concurrent rolling and normal region operations put,get,clear,destroy in
* both sync and async mode
*
* A region operation is done on the same key that is about to be rolled or has just been rolled and
* the region operation is verified to have been correctly executed.
*/
@Category(IntegrationTest.class)
public class ConcurrentRollingAndRegionOperationsJUnitTest extends DiskRegionTestingBase {
protected volatile boolean hasBeenNotified;
protected int rollingCount = 0;
protected boolean encounteredFailure = false;
@Override
protected final void preSetUp() throws Exception {
this.hasBeenNotified = false;
}
void putBeforeRoll(final Region region) {
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void beforeGoingToCompact() {
region.put("Key", "Value2");
}
public void afterHavingCompacted() {
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
if (!hasBeenNotified) {
try {
region.wait(10000);
assertTrue(hasBeenNotified);
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
}
try {
assertEquals("Value2", getValueOnDisk(region));
} catch (EntryNotFoundException e) {
logWriter.error("Exception occurred", e);
throw new AssertionError("Entry not found although was supposed to be there", e);
}
}
void getBeforeRoll(final Region region) {
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void beforeGoingToCompact() {
region.get("Key");
}
public void afterHavingCompacted() {
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
if (!hasBeenNotified) {
try {
region.wait(10000);
assertTrue(hasBeenNotified);
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
}
try {
assertEquals("Value1", getValueOnDisk(region));
assertEquals("Value1", getValueInHTree(region));
} catch (EntryNotFoundException e) {
logWriter.error("Exception occurred", e);
throw new AssertionError("Entry not found although was supposed to be there", e);
}
}
void delBeforeRoll(final Region region) {
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void beforeGoingToCompact() {
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
if (!hasBeenNotified) {
try {
region.wait(10000);
assertTrue(hasBeenNotified);
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
}
try {
region.destroy("Key");
} catch (Exception e) {
logWriter.error("Exception occurred", e);
throw new AssertionError("failed while trying to destroy due to ", e);
}
boolean entryNotFound = false;
try {
getValueOnDisk(region);
} catch (EntryNotFoundException e) {
entryNotFound = true;
}
if (!entryNotFound) {
fail("EntryNotFoundException was expected but did not get it");
}
entryNotFound = false;
Object obj = ((LocalRegion) region).basicGetEntry("Key");
if (obj == null) {
entryNotFound = true;
}
if (!entryNotFound) {
fail("EntryNotFoundException was expected but did not get it");
}
}
void clearBeforeRoll(final Region region) {
this.hasBeenNotified = false;
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void beforeGoingToCompact() {
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
if (!hasBeenNotified) {
try {
region.wait(10000);
assertTrue(hasBeenNotified);
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
}
region.clear();
boolean entryNotFound = false;
try {
getValueOnDisk(region);
} catch (EntryNotFoundException e) {
entryNotFound = true;
}
if (!entryNotFound) {
fail("EntryNotFoundException was expected but did not get it");
}
entryNotFound = false;
Object obj = ((LocalRegion) region).basicGetEntry("Key");
if (obj == null) {
entryNotFound = true;
}
if (!entryNotFound) {
fail("EntryNotFoundException was expected but did not get it");
}
}
void putAfterRoll(final Region region) {
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void beforeGoingToCompact() {
region.put("Key", "Value1");
}
public void afterHavingCompacted() {
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
}
});
region.put("makeNonEmpty", "needSomethingSoIt can be compacted");
switchOplog(region);
synchronized (region) {
if (!hasBeenNotified) {
try {
region.wait(10000);
assertTrue(hasBeenNotified);
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
}
region.put("Key", "Value2");
try {
assertEquals("Value2", getValueOnDisk(region));
} catch (EntryNotFoundException e) {
logWriter.error("Exception occurred", e);
throw new AssertionError("Entry not found although was supposed to be there", e);
}
}
void getAfterRoll(final Region region) {
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void afterHavingCompacted() {
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
if (!hasBeenNotified) {
try {
region.wait(10000);
assertTrue(hasBeenNotified);
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
}
region.get("Key");
try {
assertEquals("Value1", getValueOnDisk(region));
assertEquals("Value1", getValueInHTree(region));
} catch (EntryNotFoundException e) {
logWriter.error("Exception occurred", e);
throw new AssertionError("Entry not found although was supposed to be there", e);
}
}
void delAfterRoll(final Region region) {
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void afterHavingCompacted() {
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
if (!hasBeenNotified) {
try {
region.wait(10000);
assertTrue(hasBeenNotified);
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
}
try {
region.destroy("Key");
} catch (Exception e1) {
logWriter.error("Exception occurred", e1);
throw new AssertionError("encounter exception when not expected ", e1);
}
boolean entryNotFound = false;
try {
getValueOnDisk(region);
} catch (EntryNotFoundException e) {
entryNotFound = true;
}
if (!entryNotFound) {
fail("EntryNotFoundException was expected but did not get it");
}
entryNotFound = false;
Object obj = ((LocalRegion) region).basicGetEntry("Key");
if (obj == null) {
entryNotFound = true;
}
if (!entryNotFound) {
fail("EntryNotFoundException was expected but did not get it");
}
}
void clearAfterRoll(final Region region) {
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void afterHavingCompacted() {
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
if (!hasBeenNotified) {
try {
region.wait(10000);
assertTrue(hasBeenNotified);
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
}
region.clear();
boolean entryNotFound = false;
try {
getValueOnDisk(region);
} catch (EntryNotFoundException e) {
entryNotFound = true;
}
if (!entryNotFound) {
fail("EntryNotFoundException was expected but did not get it");
}
entryNotFound = false;
Object obj = ((LocalRegion) region).basicGetEntry("Key");
if (obj == null) {
entryNotFound = true;
}
if (!entryNotFound) {
fail("EntryNotFoundException was expected but did not get it");
}
}
private void switchOplog(Region region) {
((LocalRegion) region).getDiskRegion().forceFlush();
region.forceRolling();
}
Object getValueOnDisk(Region region) throws EntryNotFoundException {
((LocalRegion) region).getDiskRegion().forceFlush();
return ((LocalRegion) region).getValueOnDisk("Key");
}
Object getValueInHTree(Region region) {
RegionEntry re = ((LocalRegion) region).basicGetEntry("Key");
return ((LocalRegion) region).getDiskRegion().getNoBuffer(((DiskEntry) re).getDiskId());
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testSyncPutBeforeRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
putBeforeRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testAsyncPutBeforeRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskRegionProperties);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
putBeforeRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testSyncPutAfterRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
putAfterRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testAsyncPutAfterRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskRegionProperties);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
putAfterRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testSyncGetBeforeRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
getBeforeRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testAsyncGetBeforeRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskRegionProperties);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
getBeforeRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testSyncGetAfterRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
getAfterRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testAsyncGetAfterRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskRegionProperties);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
getAfterRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testSyncClearBeforeRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
clearBeforeRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testAsyncClearBeforeRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskRegionProperties);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
clearBeforeRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testSyncClearAfterRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
clearAfterRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testAsyncClearAfterRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskRegionProperties);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
clearAfterRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testSyncDelBeforeRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
delBeforeRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testAsyncDelBeforeRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskRegionProperties);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
delBeforeRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testSyncDelAfterRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
delAfterRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testAsyncDelAfterRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskRegionProperties);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
delAfterRoll(region);
region.destroyRegion();
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testCloseBeforeRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
closeBeforeRoll(region);
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testCloseAfterRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
closeAfterRoll(region);
// Asif :Recreate the region so it gets destroyed in tear down
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
}
@Ignore("TODO:DARREL_DISABLE: test is disabled")
@Test
public void testconcurrentPutAndRoll() {
DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
diskRegionProperties.setDiskDirs(dirs);
diskRegionProperties.setRolling(true);
diskRegionProperties.setCompactionThreshold(100);
region =
DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskRegionProperties, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
concurrentPutAndRoll(region);
region.destroyRegion();
}
private void concurrentPutAndRoll(final Region region) {
hasBeenNotified = false;
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
long startTime, endTime, totalTime = 0;
boolean localHasBeenNotified = false;
public void beforeGoingToCompact() {
final Object obj = new Object();
Thread thread1 = new Thread() {
public void run() {
RegionEntry re = ((LocalRegion) region).basicGetEntry("Key");
synchronized (re) {
synchronized (obj) {
obj.notify();
localHasBeenNotified = true;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
testFailed = true;
failureCause = "Exception occurred when it was not supposed to occur, Exception is "
+ e + "in concurrentPutAndRoll";
throw new AssertionError("exception not expected here", e);
}
}
}
};
thread1.start();
synchronized (obj) {
try {
if (!localHasBeenNotified) {
obj.wait(10000);
assertTrue(localHasBeenNotified);
}
} catch (InterruptedException e) {
testFailed = true;
failureCause = "Exception occurred when it was not supposed to occur, Exception is " + e
+ "in concurrentPutAndRoll";
throw new AssertionError("exception not expected here", e);
}
}
startTime = System.currentTimeMillis();
}
public void afterHavingCompacted() {
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
setTotalTime(totalTime);
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
try {
if (!hasBeenNotified) {
region.wait(10000);
assertTrue(hasBeenNotified);
}
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
if (this.totalTime < 2000) {
fail(" It should have taken more than 2000 millisecs but it took " + totalTime);
}
assertFalse(failureCause, testFailed);
}
/**
* Check if the roller thread cant skip rolling the entry & if a get is done on that entry , it is
* possible for the get operation to get the Oplog which is not yet destroyed but by the time a
* basicGet is done,the oplog gets destroyed & the get operation sees the file length zero or it
* may encounter null pointer exception while retrieving the oplog.
*/
@Test
public void testConcurrentRollingAndGet() {
final int MAX_OPLOG_SIZE = 1000 * 2;
DiskRegionProperties diskProps = new DiskRegionProperties();
diskProps.setMaxOplogSize(MAX_OPLOG_SIZE);
diskProps.setPersistBackup(true);
diskProps.setRolling(true);
diskProps.setCompactionThreshold(100);
diskProps.setSynchronous(true);
diskProps.setOverflow(false);
final int TOTAL_SWITCHING = 200;
final int TOTAL_KEYS = 20;
final List threads = new ArrayList();
final byte[] val = new byte[100];
region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, diskProps, Scope.LOCAL);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
CacheObserver old = CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void beforeGoingToCompact() {
for (int k = 0; k < TOTAL_KEYS; ++k) {
final int num = k;
Thread th = new Thread(new Runnable() {
public void run() {
byte[] val_on_disk = null;
try {
val_on_disk = (byte[]) ((LocalRegion) region).getValueOnDisk("key" + (num + 1));
assertTrue(
"byte array was not of right size as its size was " + val_on_disk.length,
val_on_disk.length == 100);
} catch (Exception e) {
encounteredFailure = true;
logWriter.error("Test encountered exception ", e);
throw new AssertionError(
" Test failed as could not obtain value from disk.Exception = ", e);
}
}
});
threads.add(th);
}
for (int j = 0; j < TOTAL_KEYS; ++j) {
((Thread) threads.get(rollingCount++)).start();
}
}
});
for (int i = 0; i < TOTAL_SWITCHING; ++i) {
for (int j = 0; j < TOTAL_KEYS; ++j) {
region.put("key" + (j + 1), val);
}
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = true;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
logWriter.error("Main thread encountered exception ", e);
throw new AssertionError(" Test failed as main thread encountered exception = ", e);
}
}
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
for (int i = 0; i < threads.size(); ++i) {
Thread th = (Thread) threads.get(i);
if (th != null) {
ThreadUtils.join(th, 30 * 1000);
}
}
assertTrue(
"The test will fail as atleast one thread doing get operation encounetred exception",
!encounteredFailure);
CacheObserverHolder.setInstance(old);
closeDown();
}
private volatile long totalTime = 0;
protected void setTotalTime(long time) {
this.totalTime = time;
}
void closeAfterRoll(final Region region) {
hasBeenNotified = false;
final Close th = new Close(region);
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void afterHavingCompacted() {
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
try {
th.start();
Thread.sleep(3000);
} catch (Exception e) {
logWriter.error("Exception occurred", e);
throw new AssertionError("Exception occurred when it was not supposed to occur", e);
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
try {
if (!hasBeenNotified) {
region.wait(10000);
assertTrue(hasBeenNotified);
}
} catch (InterruptedException e) {
throw new AssertionError("exception not expected here", e);
}
}
try {
th.join(5000);
} catch (InterruptedException ignore) {
throw new AssertionError("exception not expected here", ignore);
}
assertFalse(th.isAlive());
assertFalse(failureCause, testFailed);
}
void closeBeforeRoll(final Region region) {
hasBeenNotified = false;
final Close th = new Close(region);
CacheObserverHolder.setInstance(new CacheObserverAdapter() {
public void beforeGoingToCompact() {
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER = false;
try {
th.start();
Thread.sleep(3000);
} catch (Exception e) {
logWriter.error("Exception occurred", e);
throw new AssertionError("Exception occurred when it was not supposed to occur", e);
}
}
});
region.put("Key", "Value1");
switchOplog(region);
synchronized (region) {
try {
if (!hasBeenNotified) {
region.wait(10000);
assertTrue(hasBeenNotified);
}
} catch (InterruptedException e) {
fail("exception not expected here");
}
}
try {
th.join(5000);
} catch (InterruptedException ignore) {
throw new AssertionError("exception not expected here", ignore);
}
assertFalse(th.isAlive());
assertFalse(failureCause, testFailed);
}
class Close extends Thread {
private Region region;
Close(Region region) {
this.region = region;
}
public void run() {
try {
region.close();
synchronized (region) {
region.notify();
hasBeenNotified = true;
}
} catch (Exception e) {
logWriter.error("Exception occurred", e);
testFailed = true;
failureCause = "Exception occurred when it was not supposed to occur, due to " + e;
throw new AssertionError("Exception occurred when it was not supposed to occur, due to ",
e);
}
}
}
}
| apache-2.0 |
Loveswift/ssm-crud | src/main/java/com/xjc/bean/Employee.java | 1834 | package com.xjc.bean;
import javax.validation.constraints.Pattern;
public class Employee {
private Integer empId;
@Pattern(regexp="(^[a-zA-Z0-9_-]{3,16}$)|(^[\\u2E80-\\u9FFF]{2,5})",message="姓名格式为2-5位字符或3-16位数字和字母组合")
private String empName;
private String gender;
@Pattern(regexp="^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$",message="邮箱格式错误")
private String email;
private Integer dId;
private Department department;
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public Employee(Integer empId, String empName, String gender, String email, Integer dId) {
super();
this.empId = empId;
this.empName = empName;
this.gender = gender;
this.email = email;
this.dId = dId;
}
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName == null ? null : empName.trim();
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender == null ? null : gender.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public Integer getdId() {
return dId;
}
public void setdId(Integer dId) {
this.dId = dId;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
} | apache-2.0 |
LetyM/nihonGO | JavaApplication1/src/Paneles/ITraduccion.java | 421 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Paneles;
import Paneles.Palabra;
/**
*
* @author Secretaria
*/
public interface ITraduccion {
public void add(Palabra palabra);
public Palabra getTraducc(int i);
public int getNumPalabras();
}
| apache-2.0 |
dotta/async-http-client | client/src/test/java/org/asynchttpclient/ComplexClientTest.java | 2003 | /*
* Copyright 2010 Ning, Inc.
*
* Ning 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.asynchttpclient;
import static org.asynchttpclient.Dsl.*;
import static org.testng.Assert.assertEquals;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.Test;
public class ComplexClientTest extends AbstractBasicTest {
@Test(groups = "standalone")
public void multipleRequestsTest() throws Exception {
try (AsyncHttpClient c = asyncHttpClient()) {
String body = "hello there";
// once
Response response = c.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);
assertEquals(response.getResponseBody(), body);
// twice
response = c.preparePost(getTargetUrl()).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);
assertEquals(response.getResponseBody(), body);
}
}
@Test(groups = "standalone")
public void urlWithoutSlashTest() throws Exception {
try (AsyncHttpClient c = asyncHttpClient()) {
String body = "hello there";
Response response = c.preparePost(String.format("http://127.0.0.1:%d/foo/test", port1)).setBody(body).setHeader("Content-Type", "text/html").execute().get(TIMEOUT, TimeUnit.SECONDS);
assertEquals(response.getResponseBody(), body);
}
}
}
| apache-2.0 |
SacredScriptureFoundation/sacredscripture | api/src/main/java/org/sacredscripture/platform/bible/canon/BookTypeGroupLocalization.java | 1746 | /*
* Copyright (c) 2013, 2015 Sacred Scripture Foundation.
* "All scripture is given by inspiration of God, and is profitable for
* doctrine, for reproof, for correction, for instruction in righteousness:
* That the man of God may be perfect, throughly furnished unto all good
* works." (2 Tim 3:16-17)
*
* 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.sacredscripture.platform.bible.canon;
import org.sacredscripturefoundation.commons.Named;
import org.sacredscripturefoundation.commons.entity.Entity;
import org.sacredscripturefoundation.commons.locale.LocaleProvider;
import java.util.Locale;
/**
* @author Paul Benedict
* @since Sacred Scripture Platform 1.0
*/
public interface BookTypeGroupLocalization extends Entity<Long>, Named, LocaleProvider {
/**
* Retrieves the owning group of this localization.
*
* @return the group
*/
BookTypeGroup getBookTypeGroup();
void setBookTypeGroup(BookTypeGroup bookTypeGroup);
/**
* Stores the new locale for this localization.
*
* @param locale the locale
* @see #getLocale()
*/
void setLocale(Locale locale);
void setName(String name);
}
| apache-2.0 |
sohutv/cachecloud | cachecloud-web/src/main/java/com/sohu/cache/task/tasks/MachineSyncTask.java | 17134 | package com.sohu.cache.task.tasks;
import com.sohu.cache.entity.MachineInfo;
import com.sohu.cache.entity.MachineRelation;
import com.sohu.cache.exception.SSHException;
import com.sohu.cache.ssh.SSHTemplate.Result;
import com.sohu.cache.task.BaseTask;
import com.sohu.cache.task.constant.TaskConstants;
import com.sohu.cache.task.constant.TaskStepFlowEnum.TaskFlowStatusEnum;
import com.sohu.cache.util.ConstUtils;
import com.sohu.cache.web.enums.MachineTaskEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;
/**
* Created by chenshi on 2019/5/24.
*/
@Component("MachineSyncTask")
@Scope(SCOPE_PROTOTYPE)
public class MachineSyncTask extends BaseTask {
/**
* 源宿主机ip
*/
private String sourceIp;
/**
* 目标宿主机ip
*/
private String targetIp;
/**
* 容器ip
*/
private String containerIp;
/**
* k8s 持久化/配置/日志 目录
*/
private static String baseConfDir = "/data/redis/conf/";
private static String baseDataDir = "/data/redis/data/";
private static String baseLogDir = "/data/redis/logs/";
private static String backupDir = "/data/redis/bak/";
/**
* 同步/校验数据 超时时间
*/
private static int SYNC_DATA_TIMEOUT = 30 * 60 * 1000;
private static int MD5_CHECK_TIMEOUT = 20 * 1000;
private static int BACKUP_DATA_TIMEOUT = 30 * 1000;
@Override
public List<String> getTaskSteps() {
List<String> taskStepList = new ArrayList<String>();
//1. 参数初始化
taskStepList.add(TaskConstants.INIT_METHOD_KEY);
//2. 检查源主机同步环境
taskStepList.add("checkSourceMachineEnv");
//3. 检查目标主机连通性及目录检查
taskStepList.add("checkTargetMachineEnv");
//4. scp同步数据 source->target host machine
taskStepList.add("startSyncData");
//5. 校验目的文件是否一致
taskStepList.add("checkDirMd5");
//6. 备份历史数据
taskStepList.add("backupSourceData");
//7. 同步完成
taskStepList.add("syncOver");
return taskStepList;
}
@Override
public TaskFlowStatusEnum init() {
super.init();
// 1.源宿主机
sourceIp = MapUtils.getString(paramMap, TaskConstants.SOURCE_HOST_KEY);
if (StringUtils.isEmpty(sourceIp)) {
logger.error(marker, "task {} source machine ip {} is empty", taskId, sourceIp);
return TaskFlowStatusEnum.ABORT;
}
// 2.目标宿主机
targetIp = MapUtils.getString(paramMap, TaskConstants.TARGET_HOST_KEY);
if (StringUtils.isEmpty(targetIp)) {
logger.error(marker, "task {} target machine ip {} is empty", taskId, targetIp);
return TaskFlowStatusEnum.ABORT;
}
// 3.容器ip
containerIp = MapUtils.getString(paramMap, TaskConstants.CONTAINER_IP);
if (!StringUtils.isEmpty(containerIp)) {
MachineInfo machineInfo = machineDao.getMachineInfoByIp(containerIp);
if (machineInfo == null) {
logger.error(marker, "task {} container ip {} is not exist", taskId, containerIp);
return TaskFlowStatusEnum.ABORT;
}
} else {
logger.error(marker, "task {} container ip {} is empty", taskId, containerIp);
return TaskFlowStatusEnum.ABORT;
}
return TaskFlowStatusEnum.SUCCESS;
}
/**
* 2.源主机:
* 2.1.机器连通性
* 2.2.sshpass安装
* 2.3.源数据目录是否存在
*/
public TaskFlowStatusEnum checkSourceMachineEnv() {
// 1.连通性 + sshpass
String sshpass_command = "sshpass -V | head -1 ";
// 源数据目录
String checkDir_command = "ls -l " + baseConfDir.concat(containerIp) + " | wc -l && ls -l " + baseDataDir.concat(containerIp) + " | wc -l && ls -l " + baseLogDir.concat(containerIp) + " | wc -l";
try {
Result checkResult = sshService.executeWithResult(sourceIp, sshpass_command);
if (checkResult.isSuccess() && checkResult.getResult().indexOf("sshpass") > -1) {
logger.info(marker, "sourceMachine ip :{} check sshpass env result:{}", sourceIp, checkResult.getResult());
} else {
logger.error(marker, "sourceMachine ip :{} check sshpass env error message:{}", sourceIp, checkResult.getResult());
return TaskFlowStatusEnum.ABORT;
}
Result checkDirResult = sshService.executeWithResult(sourceIp, checkDir_command);
if (checkDirResult.isSuccess()) {
logger.info(marker, "sourceMachine ip :{} check dir env command:{} , result:{}", sourceIp, checkDir_command, checkDirResult.getResult());
if (checkDirResult.getResult() != null && checkDirResult.getResult().indexOf("0 0 0") > -1) {
logger.error(marker, "sourceMachine ip :{} check dir not exist result:{}", sourceIp, checkDirResult.getResult());
return TaskFlowStatusEnum.ABORT;
}
} else {
logger.error(marker, "sourceMachine ip :{} check dir env error message:{}", sourceIp, checkDirResult.getResult());
return TaskFlowStatusEnum.ABORT;
}
} catch (SSHException e) {
logger.error(marker, "sourceMachine ip :{} check env error message:{}", sourceIp, e.getMessage());
e.printStackTrace();
return TaskFlowStatusEnum.ABORT;
}
return TaskFlowStatusEnum.SUCCESS;
}
/**
* 3.目标主机检查:
* 3.1. 机器连通性
* 3.2. cachecloud用户是否存在
* 3.3. 检测容器上是否有redis进程
* 3.4. 同步目录存在且无redis进程 删除数据目录
*/
public TaskFlowStatusEnum checkTargetMachineEnv() {
String checkUser_command = "cat /etc/passwd | grep cachecloud ";
String checkRedis_command = "ps -ef | grep redis | grep -v \"grep redis\" | wc -l ";
String delDir_command = "rm -rf " + baseConfDir.concat(containerIp) + " " + baseDataDir.concat(containerIp) + " " + baseLogDir.concat(containerIp);
try {
// 1.检查用户是否存在
Result checkResult = sshService.executeWithResult(targetIp, checkUser_command);
if (checkResult.isSuccess() && checkResult.getResult().indexOf("cachecloud") > -1) {
logger.info(marker, "targetMachine ip :{} check user:{} , result:{}", targetIp, checkUser_command, checkResult.getResult());
} else {
logger.error(marker, "targetMachine ip :{} check user:{} , error message:{}", targetIp, checkUser_command, checkResult.getResult());
return TaskFlowStatusEnum.ABORT;
}
// 2.检测容器是否还有redis进程
Result checkRedisResult = sshService.executeWithResult(containerIp, checkRedis_command);
if (checkRedisResult.isSuccess() && checkRedisResult.getResult().equals("0")) {
logger.info(marker, "container ip :{} check redis:{} size:{} is not exist ", containerIp, checkRedis_command, checkRedisResult.getResult());
} else {
logger.error(marker, "container ip :{} check redis:{} size:{} , message:{}", containerIp, checkRedis_command, checkRedisResult.getResult());
return TaskFlowStatusEnum.ABORT;
}
// 3.清除目标主机的目录数据(防止冲突)
Result delResult = sshService.executeWithResult(targetIp, delDir_command);
if (delResult.isSuccess()) {
logger.info(marker, "targetMachine ip :{} , del success command:{} ", targetIp, delDir_command, delResult.getResult());
} else {
logger.error(marker, "targetMachine ip :{} , del command:{}, error message:{}", targetIp, delDir_command, delResult.getResult());
return TaskFlowStatusEnum.ABORT;
}
} catch (SSHException e) {
logger.error(marker, "sourceMachine ip :{} check env error message:{}", sourceIp, e.getMessage(),e);
return TaskFlowStatusEnum.ABORT;
}
return TaskFlowStatusEnum.SUCCESS;
}
/**
* 4.持久化数据、配置目录同步任务
*/
public TaskFlowStatusEnum startSyncData() {
/*String sync_command = " sshpass -p " + ConstUtils.PASSWORD + " scp -oStrictHostKeyChecking=no -r " + baseConfDir.concat(containerIp) + " " + ConstUtils.USERNAME + "@" + targetIp + ":" + baseConfDir +
" && sshpass -p " + ConstUtils.PASSWORD + " scp -oStrictHostKeyChecking=no -r " + baseDataDir.concat(containerIp) + " " + ConstUtils.USERNAME + "@" + targetIp + ":" + baseDataDir +
" && sshpass -p " + ConstUtils.PASSWORD + " scp -oStrictHostKeyChecking=no -r " + baseLogDir.concat(containerIp) + " " + ConstUtils.USERNAME + "@" + targetIp + ":" + baseLogDir;
*/
String sync_command = " scp -i "+ConstUtils.DEFAULT_PUBLIC_KEY_PEM+" -oStrictHostKeyChecking=no -r " + baseConfDir.concat(containerIp) + " " + ConstUtils.USERNAME + "@" + targetIp + ":" + baseConfDir +
" && scp -i "+ConstUtils.DEFAULT_PUBLIC_KEY_PEM+" -oStrictHostKeyChecking=no -r " + baseDataDir.concat(containerIp) + " " + ConstUtils.USERNAME + "@" + targetIp + ":" + baseDataDir +
" && scp -i "+ConstUtils.DEFAULT_PUBLIC_KEY_PEM+" -oStrictHostKeyChecking=no -r " + baseLogDir.concat(containerIp) + " " + ConstUtils.USERNAME + "@" + targetIp + ":" + baseLogDir;
logger.info(marker, "source ip :{} ,execute command :{}", sourceIp, sync_command);
Result syncResult = null;
try {
long start = System.currentTimeMillis();
syncResult = sshService.executeWithResult(sourceIp, sync_command, SYNC_DATA_TIMEOUT);
if (syncResult.isSuccess() || syncResult.getResult().indexOf("Permission denied") == -1) {
logger.info(marker, "sync data result:{} costTime:{} s", syncResult.getResult(), (System.currentTimeMillis() - start) / 1000);
} else {
logger.error(marker, "sync data error message:{}", syncResult.getResult());
return TaskFlowStatusEnum.ABORT;
}
} catch (SSHException e) {
logger.error(marker, "sync data error message:{} {}", syncResult,e.getMessage(),e);
return TaskFlowStatusEnum.ABORT;
}
return TaskFlowStatusEnum.SUCCESS;
}
/**
* 5.同步数据目录文件md5校验
*/
public TaskFlowStatusEnum checkDirMd5() {
String sourceShell = "find " + baseConfDir.concat(containerIp) + " " + baseDataDir.concat(containerIp) + " " + baseLogDir.concat(containerIp) + " -type f -exec md5sum {} \\; | sort -k 2";
String targetShell = "find " + baseConfDir.concat(containerIp) + " " + baseDataDir.concat(containerIp) + " " + baseLogDir.concat(containerIp) + " -type f -exec md5sum {} \\; | sort -k 2";
//1.源宿主机和目标宿主机 目录文件列表的md5值
Result sourceMd5Result;
Result targetMd5Result;
try {
sourceMd5Result = sshService.executeWithResult(sourceIp, sourceShell, MD5_CHECK_TIMEOUT);
if(sourceMd5Result == null){
logger.error(marker, " source ip:{} validate md5 result is null", sourceIp);
return TaskFlowStatusEnum.ABORT;
}
if (sourceMd5Result.isSuccess()) {
logger.info(marker, "source ip:{} validate md5 result: ", sourceIp);
for (String sourceMd5 : sourceMd5Result.getResult().split("\n")) {
logger.info(marker, "source file md5 {} : ", sourceMd5);
}
} else {
logger.error(marker, " source ip:{} validate md5 error:{}", sourceIp, sourceMd5Result.getExcetion());
return TaskFlowStatusEnum.ABORT;
}
} catch (SSHException e) {
logger.error(marker, " source ip:{} validate md5 error:{}", sourceIp, e.getMessage());
return TaskFlowStatusEnum.ABORT;
}
try {
targetMd5Result = sshService.executeWithResult(targetIp, targetShell, MD5_CHECK_TIMEOUT);
if(targetMd5Result == null){
logger.error(marker, " target ip:{} validate md5 result is null", targetIp);
return TaskFlowStatusEnum.ABORT;
}
if (targetMd5Result.isSuccess()) {
logger.info(marker, "target ip:{} validate md5 result:{} ", targetIp, targetMd5Result.getResult());
for (String targetMd5 : targetMd5Result.getResult().split("\n")) {
logger.info(marker, "target file md5 {} : ", targetMd5);
}
} else {
logger.error(marker, " target ip:{} validate md5 error:{}", targetIp, targetMd5Result.getResult());
return TaskFlowStatusEnum.ABORT;
}
} catch (SSHException e) {
logger.error(marker, " target ip:{} validate md5 error:{}", sourceIp, e.getMessage());
return TaskFlowStatusEnum.ABORT;
}
// 2.print md5 compare result
if (sourceMd5Result != null && targetMd5Result != null && targetMd5Result.getResult().equals(sourceMd5Result.getResult())) {
logger.info(marker, "===== compare source ip:{} & target ip:{} is equal =====", sourceIp, targetIp);
} else {
logger.error(marker, "===== compare source ip:{} & target ip:{} is diffrent =====", sourceIp, targetIp);
return TaskFlowStatusEnum.ABORT;
}
return TaskFlowStatusEnum.SUCCESS;
}
public TaskFlowStatusEnum backupSourceData() {
// 1. backup data : /data/redis/bak/${ip}_${time}/...
SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmm");
String timeFormat = time.format(new Date());
// 2. backup command
String backup_command = " mkdir -p " + backupDir.concat(containerIp + "_" + timeFormat) + " && " +
" mv " + baseConfDir.concat(containerIp) + " " + backupDir.concat(containerIp + "_" + timeFormat).concat("/conf") + " && " +
" mv " + baseDataDir.concat(containerIp) + " " + backupDir.concat(containerIp + "_" + timeFormat).concat("/data") + " && " +
" mv " + baseLogDir.concat(containerIp) + " " + backupDir.concat(containerIp + "_" + timeFormat).concat("/logs");
Result backupResult;
try {
backupResult = sshService.executeWithResult(sourceIp, backup_command, BACKUP_DATA_TIMEOUT);
if (backupResult.isSuccess()) {
logger.info(marker, "source ip:{} backup date success ,result:{} ", sourceIp, backupResult.getResult());
} else {
logger.error(marker, " source ip:{} backup date error:{}", sourceIp, backupResult.getResult());
return TaskFlowStatusEnum.ABORT;
}
} catch (SSHException e) {
logger.error(marker, " source ip:{} backup date error:{}", sourceIp, e.getMessage());
return TaskFlowStatusEnum.ABORT;
}
return TaskFlowStatusEnum.SUCCESS;
}
/**
* 7.更新机器同步状态
*/
public TaskFlowStatusEnum syncOver() {
// update machine SYNC status
try {
List<MachineRelation> relationList = machineRelationDao.getUnSyncRelationList(containerIp, sourceIp);
if (!CollectionUtils.isEmpty(relationList)) {
for (MachineRelation machineRelation : relationList) {
machineRelationDao.updateMachineSyncStatus(machineRelation.getId(), MachineTaskEnum.SYNCED.getValue());
logger.info(marker, "update machine realtion id:{}, ip:{},realIp:{} sync status success !", machineRelation.getId(), sourceIp, containerIp);
}
}
} catch (Exception e) {
logger.error(marker, "update machine relation ", sourceIp, targetIp);
return TaskFlowStatusEnum.ABORT;
}
return TaskFlowStatusEnum.SUCCESS;
}
/**
* 执行一个ls命令,确认ssh以及不是只读盘
*
* @return
*/
protected boolean checkMachineIsConnect(String ip) {
try {
Result result = sshService.executeWithResult(ip, "ls / | wc -l");
if (result.isSuccess()) {
return true;
}
} catch (Exception e) {
logger.error(marker, e.getMessage());
}
return false;
}
}
| apache-2.0 |
Albero/Albero | model/src/main/java/nl/trivento/albero/model/builders/AbstractBuilder.java | 1732 | /* Copyright 2011-2012 Profict Holding
*
* 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 nl.trivento.albero.model.builders;
import nl.trivento.albero.utilities.Logger;
/**
* Simplifies implementing the {@link Builder builder interface}.
*
* @param <B> the type of the object that is being built by the builder
* @param <I> the type of the buildable object
*/
abstract class AbstractBuilder<B, I extends Buildable> implements Builder<B> {
/** The object that is being built. */
protected final I buildableObject;
/** The logger to use. */
protected final Logger logger;
/**
* Creates an abstract builder.
*
* @param buildableObject the buildable object to use
*/
protected AbstractBuilder(I buildableObject) {
this.buildableObject = buildableObject;
logger = Logger.get(getClass());
}
public B build() throws BuilderException {
buildableObject.checkValues();
try {
// we have to cast here because we're not allowed to say AbstractBuilder<B, I extends Buildable & B>
@SuppressWarnings("unchecked")
B builtObject = (B) buildableObject;
return builtObject;
} catch (ClassCastException exception) {
throw new BuilderException(exception, "can't cast buildable object");
}
}
}
| apache-2.0 |
m-salcedo/itunes-store | app/src/main/java/com/grability/msalcedo/itunesstore_test/model/Link.java | 942 |
package com.grability.msalcedo.itunesstore_test.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by Mariangela Salcedo (msalcedo047@gmail.com) on 08/10/16.
* Copyright (c) 2016 m-salcedo. All rights reserved.
*/
public class Link {
@SerializedName("attributes")
@Expose
private Attributes attributes;
/**
* No args constructor for use in serialization
*
*/
public Link() {
}
/**
*
* @param attributes
*/
public Link(Attributes attributes) {
this.attributes = attributes;
}
/**
*
* @return
* The attributes
*/
public Attributes getAttributes() {
return attributes;
}
/**
*
* @param attributes
* The attributes
*/
public void setAttributes(Attributes attributes) {
this.attributes = attributes;
}
}
| apache-2.0 |
Ariah-Group/Finance | af_webapp/src/main/java/org/kuali/kfs/module/purap/businessobject/options/DateRequiredReasonValuesFinder.java | 1988 | /*
* Copyright 2006 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.purap.businessobject.options;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.kuali.kfs.module.purap.businessobject.DeliveryRequiredDateReason;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.krad.keyvalues.KeyValuesBase;
import org.kuali.rice.krad.service.KeyValuesService;
/**
* Value Finder for Date Required Reasons.
*/
public class DateRequiredReasonValuesFinder extends KeyValuesBase {
/**
* Returns code/description pairs of all Date Required Reasons.
*
* @see org.kuali.rice.kns.lookup.keyvalues.KeyValuesFinder#getKeyValues()
*/
public List getKeyValues() {
KeyValuesService boService = SpringContext.getBean(KeyValuesService.class);
Collection codes = boService.findAll(DeliveryRequiredDateReason.class);
List labels = new ArrayList();
labels.add(new ConcreteKeyValue("", ""));
for (Iterator iter = codes.iterator(); iter.hasNext();) {
DeliveryRequiredDateReason reason = (DeliveryRequiredDateReason) iter.next();
labels.add(new ConcreteKeyValue(reason.getDeliveryRequiredDateReasonCode(), reason.getDeliveryRequiredDateReasonDescription()));
}
return labels;
}
}
| apache-2.0 |
nince-wyj/jahhan | cache/cache-redis-sentinel/src/main/java/net/jahhan/lock/impl/GlobalReentrantLock.java | 4154 | package net.jahhan.lock.impl;
import lombok.Data;
import net.jahhan.cache.Redis;
import net.jahhan.cache.RedisFactory;
import net.jahhan.common.extension.constant.JahhanErrorCode;
import net.jahhan.common.extension.exception.JahhanException;
import net.jahhan.common.extension.utils.LogUtil;
import net.jahhan.globalTransaction.LockParamHolder;
import net.jahhan.globalTransaction.LockStatus;
import net.jahhan.globalTransaction.LockThreadStatus;
import net.jahhan.lock.DistributedLock;
import net.jahhan.lock.communication.LockWaitingThreadHolder;
import net.jahhan.variable.BaseThreadVariable;
@Data
public class GlobalReentrantLock implements DistributedLock {
private Redis redis;
private long level = 0;
private String lockName;
private int ttl = 0;
public GlobalReentrantLock(String redisType, String lockName, int ttl) {
this.redis = RedisFactory.getRedis(redisType, null);
this.lockName = lockName;
this.ttl = ttl;
}
@Override
public void lock() {
String chainId = ((BaseThreadVariable) BaseThreadVariable.getThreadVariable("base")).getChainId();
level = redis.queueGetGlobalReentrantLock(lockName, chainId, level, ttl);
if (level > 0) {
LogUtil.lockInfo("get globalLock:" + lockName + ",lock chain:" + chainId + ",level:" + level);
return;
}
if (level < 0) {
JahhanException.throwException(JahhanErrorCode.LOCK_ERROE, "锁层级错误");
}
LockParamHolder.newChainLock(chainId);
int count = 0;
while (count < 1000) {
LockWaitingThreadHolder.registWaitingThread(lockName, chainId, ttl * 1000);
LockThreadStatus chainLockStatus = LockParamHolder.getChainLockStatus(chainId);
switch (chainLockStatus) {
case WEAKUP: {
if (weakup()) {
return;
}
break;
}
case COMPETE: {
if (compete()) {
return;
}
break;
}
case REQUEUE: {
if (tryLock()) {
chainLockStatus = LockThreadStatus.BLOCK;
return;
}
break;
}
default:
break;
}
count++;
}
JahhanException.throwException(JahhanErrorCode.LOCK_ERROE, "锁超重试");
}
@Override
public boolean tryLock() {
String chainId = ((BaseThreadVariable) BaseThreadVariable.getThreadVariable("base")).getChainId();
level = redis.queueGetGlobalReentrantLock(lockName, chainId, level, ttl);
if (level > 0) {
LogUtil.lockInfo("get globalLock:" + lockName + ",lock chain:" + chainId + ",level:" + level);
return true;
}
return false;
}
@Override
public void unlock() {
String chainId = ((BaseThreadVariable) BaseThreadVariable.getThreadVariable("base")).getChainId();
level = redis.unLockGlobalReentrantLock(lockName, chainId, level);
LockParamHolder.removeChainLock(chainId);
LogUtil.lockInfo("release globalLock:" + lockName + ",lock chain:" + chainId + ",level:" + level);
if (level < 0) {
LogUtil.lockInfo("releaseError globalLock:" + lockName + ",lock chain:" + chainId + ",level:" + level);
JahhanException.throwException(JahhanErrorCode.LOCK_ERROE, "锁错误:" + lockName);
}
}
private boolean weakup() {
String chainId = ((BaseThreadVariable) BaseThreadVariable.getThreadVariable("base")).getChainId();
LockStatus chainLock = LockParamHolder.getChainLock(chainId);
level = redis.callGetGlobalReentrantLock(lockName, chainId, ttl);
chainLock.setStatus(LockThreadStatus.BLOCK);
if (level > 0) {
LogUtil.lockInfo("get globalLock:" + lockName + ",lock chain:" + chainId + ",level:" + level);
return true;
}
return false;
}
private boolean compete() {
String chainId = ((BaseThreadVariable) BaseThreadVariable.getThreadVariable("base")).getChainId();
LockStatus chainLock = LockParamHolder.getChainLock(chainId);
level = redis.competeGetGlobalReentrantLock(lockName, chainId, chainLock.getKey(), ttl);
chainLock.setStatus(LockThreadStatus.BLOCK);
if (level > 0) {
LogUtil.lockInfo("get globalLock:" + lockName + ",lock chain:" + chainId + ",level:" + level);
return true;
}
return false;
}
@Override
public void close() throws Exception {
unlock();
}
}
| apache-2.0 |
MonALISA-CIT/fdt | src/org/apache/commons/cli/Options.java | 9823 | /*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/Options.java,v 1.5 2002/06/06 22:32:37 bayard Exp $
* $Revision: 1.5 $
* $Date: 2002/06/06 22:32:37 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.cli;
import java.util.*;
/**
* <p>Main entry-point into the library.</p>
* <p>
* <p>Options represents a collection of {@link Option} objects, which
* describe the possible options for a command-line.<p>
* <p>
* <p>It may flexibly parse long and short options, with or without
* values. Additionally, it may parse only a portion of a commandline,
* allowing for flexible multi-stage parsing.<p>
*
* @author bob mcwhirter (bob @ werken.com)
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @version $Revision: 1.5 $
* @see org.apache.commons.cli.CommandLine
*/
public class Options {
/**
* a map of the options with the character key
*/
private Map shortOpts = new HashMap();
/**
* a map of the options with the long key
*/
private Map longOpts = new HashMap();
/**
* a map of the required options
*/
private List requiredOpts = new ArrayList();
/**
* a map of the option groups
*/
private Map optionGroups = new HashMap();
/**
* <p>Construct a new Options descriptor</p>
*/
public Options() {
}
/**
* <p>Add the specified option group.</p>
*
* @param group the OptionGroup that is to be added
* @return the resulting Options instance
*/
public Options addOptionGroup(OptionGroup group) {
Iterator options = group.getOptions().iterator();
if (group.isRequired()) {
requiredOpts.add(group);
}
while (options.hasNext()) {
Option option = (Option) options.next();
// an Option cannot be required if it is in an
// OptionGroup, either the group is required or
// nothing is required
option.setRequired(false);
addOption(option);
optionGroups.put(option.getOpt(), group);
}
return this;
}
/**
* <p>Add an option that only contains a short-name</p>
* <p>It may be specified as requiring an argument.</p>
*
* @param opt Short single-character name of the option.
* @param hasArg flag signally if an argument is required after this option
* @param description Self-documenting description
* @return the resulting Options instance
*/
public Options addOption(String opt, boolean hasArg, String description) {
addOption(opt, null, hasArg, description);
return this;
}
/**
* <p>Add an option that contains a short-name and a long-name</p>
* <p>It may be specified as requiring an argument.</p>
*
* @param opt Short single-character name of the option.
* @param longOpt Long multi-character name of the option.
* @param hasArg flag signally if an argument is required after this option
* @param description Self-documenting description
* @return the resulting Options instance
*/
public Options addOption(String opt, String longOpt, boolean hasArg, String description) {
addOption(new Option(opt, longOpt, hasArg, description));
return this;
}
/**
* <p>Adds an option instance</p>
*
* @param opt the option that is to be added
* @return the resulting Options instance
*/
public Options addOption(Option opt) {
String shortOpt = "-" + opt.getOpt();
// add it to the long option list
if (opt.hasLongOpt()) {
longOpts.put("--" + opt.getLongOpt(), opt);
}
// if the option is required add it to the required list
if (opt.isRequired()) {
requiredOpts.add(shortOpt);
}
shortOpts.put(shortOpt, opt);
return this;
}
/**
* <p>Retrieve a read-only list of options in this set</p>
*
* @return read-only Collection of {@link Option} objects in this descriptor
*/
public Collection getOptions() {
List opts = new ArrayList(shortOpts.values());
// now look through the long opts to see if there are any Long-opt
// only options
Iterator iter = longOpts.values().iterator();
while (iter.hasNext()) {
Object item = iter.next();
if (!opts.contains(item)) {
opts.add(item);
}
}
return Collections.unmodifiableCollection(opts);
}
/**
* <p>Returns the Options for use by the HelpFormatter.</p>
*
* @return the List of Options
*/
List helpOptions() {
return new ArrayList(shortOpts.values());
}
/**
* <p>Returns the required options as a
* <code>java.util.Collection</code>.</p>
*
* @return Collection of required options
*/
public List getRequiredOptions() {
return requiredOpts;
}
/**
* <p>Retrieve the named {@link Option}</p>
*
* @param opt short or long name of the {@link Option}
* @return the option represented by opt
*/
public Option getOption(String opt) {
Option option = null;
// short option
if (opt.length() == 1) {
option = (Option) shortOpts.get("-" + opt);
}
// long option
else if (opt.startsWith("--")) {
option = (Option) longOpts.get(opt);
}
// a just-in-case
else {
option = (Option) shortOpts.get(opt);
}
return (option == null) ? null : (Option) option.clone();
}
/**
* <p>Returns whether the named {@link Option} is a member
* of this {@link Options}</p>
*
* @param opt short or long name of the {@link Option}
* @return true if the named {@link Option} is a member
* of this {@link Options}
*/
public boolean hasOption(String opt) {
// short option
if (opt.length() == 1) {
return shortOpts.containsKey("-" + opt);
}
// long option
else if (opt.startsWith("--")) {
return longOpts.containsKey(opt);
}
// a just-in-case
else {
return shortOpts.containsKey(opt);
}
}
/**
* <p>Returns the OptionGroup the <code>opt</code>
* belongs to.</p>
*
* @param opt the option whose OptionGroup is being queried.
* @return the OptionGroup if <code>opt</code> is part
* of an OptionGroup, otherwise return null
*/
public OptionGroup getOptionGroup(Option opt) {
return (OptionGroup) optionGroups.get(opt.getOpt());
}
/**
* <p>Dump state, suitable for debugging.</p>
*
* @return Stringified form of this object
*/
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("[ Options: [ short ");
buf.append(shortOpts.toString());
buf.append(" ] [ long ");
buf.append(longOpts);
buf.append(" ]");
return buf.toString();
}
}
| apache-2.0 |
pgorla/usergrid | mongo-emulator/src/main/java/org/usergrid/mongo/protocol/OpMsg.java | 1877 | /*******************************************************************************
* Copyright 2012 Apigee Corporation
*
* 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.usergrid.mongo.protocol;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.jboss.netty.buffer.ChannelBuffer;
public class OpMsg extends Message {
String message;
public OpMsg() {
opCode = OP_MSG;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public void decode(ChannelBuffer buffer) throws IOException {
super.decode(buffer);
message = readCString(buffer);
}
@Override
public ChannelBuffer encode(ChannelBuffer buffer) {
int l = 16; // 4 ints * 4 bytes
ByteBuffer messageBytes = getCString(message);
l += messageBytes.capacity();
messageLength = l;
buffer = super.encode(buffer);
buffer.writeBytes(messageBytes);
return buffer;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "OpMsg [message=" + message + ", messageLength=" + messageLength
+ ", requestID=" + requestID + ", responseTo=" + responseTo
+ ", opCode=" + opCode + "]";
}
}
| apache-2.0 |
alexcreasy/pnc | spi/src/main/java/org/jboss/pnc/spi/repositorymanager/RepositoryManager.java | 4755 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.spi.repositorymanager;
import java.util.Map;
import org.jboss.pnc.model.BuildRecord;
import org.jboss.pnc.enums.RepositoryType;
import org.jboss.pnc.spi.repositorymanager.model.RepositorySession;
import org.jboss.pnc.spi.repositorymanager.model.RunningRepositoryDeletion;
import org.jboss.pnc.spi.repositorymanager.model.RunningRepositoryPromotion;
/**
* Created by <a href="mailto:matejonnet@gmail.com">Matej Lazar</a> on 2014-11-23.
*/
public interface RepositoryManager {
/**
* Create a new repository session tuned to the parameters of that build collection and the build that will use this
* repository session.
*
* @param buildExecution The build execution currently running
* @param accessToken The access token to use
* @param serviceAccountToken The access token for service account to use for repo creation, promotion and cleanup
* @param repositoryType the created repositories' type (npm, maven, etc.)
* @param genericParameters Generic parameters specified in the BuildConfiguration
* @return The new repository session
* @throws RepositoryManagerException If there is a problem creating the repository
*/
RepositorySession createBuildRepository(
BuildExecution buildExecution,
String accessToken,
String serviceAccountToken,
RepositoryType repositoryType,
Map<String, String> genericParameters) throws RepositoryManagerException;
/**
* Collects processed repository manager result for a previously finished build for any repair work needed. This
* reads the tracking report and collects the downloads and uploads the same way as they are collected at the end of
* a successful build.
*
* @param buildContentId string identifier of the build
* @param tempBuild flag if this is a temporary build
* @return repository manager result
* @throws RepositoryManagerException in case of an error when collecting the build artifacts and dependencies
*/
RepositoryManagerResult collectRepoManagerResult(Integer id) throws RepositoryManagerException;
/**
* Add the repository containing output associated with the specified {@link BuildRecord} to the membership of the
* repository group with the given ID. Note that the operation won't start until monitoring starts for the returned
* {@link RunningRepositoryPromotion} instance.
*
* @param buildRecord The build output to promote
* @param pakageType package type key used by repository manager
* @param toGroup The ID of the repository group where the build output should be promoted
* @param accessToken The access token to use
* @return An object representing the running promotion process, with callbacks for result and error.
*
* @throws RepositoryManagerException If there is a problem promoting the build
*/
RunningRepositoryPromotion promoteBuild(
BuildRecord buildRecord,
String pakageType,
String toGroup,
String accessToken) throws RepositoryManagerException;
/**
* Used to purge the artifacts that were output from a given build (including the specific hosted repository which
* was used for that build). Note that the operation won't start until monitoring starts for the returned
* {@link RunningRepositoryDeletion} instance.
*
* @param buildRecord The build whose artifacts/repositories should be removed
* @param pakageType package type key used by repository manager
* @param accessToken The access token to use
* @return An object representing the running deletion, with callbacks for result and error.
*
* @throws RepositoryManagerException If there is a problem deleting the build
*/
RunningRepositoryDeletion deleteBuild(BuildRecord buildRecord, String pakageType, String accessToken)
throws RepositoryManagerException;
boolean canManage(RepositoryType managerType);
}
| apache-2.0 |
detnavillus/modular-informatic-designs | search-core/src/main/java/com/modinfodesigns/search/IQueryRenderer.java | 123 | package com.modinfodesigns.search;
public interface IQueryRenderer
{
public String renderQuery( IQuery query );
}
| apache-2.0 |
NotFound403/WePay | src/main/java/cn/felord/wepay/ali/sdk/api/domain/AlipayEcoMycarMaintainBizorderCreateModel.java | 10236 | package cn.felord.wepay.ali.sdk.api.domain;
import java.util.List;
import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiListField;
/**
* 创建保养洗车订单接口
*
* @author auto create
* @version $Id: $Id
*/
public class AlipayEcoMycarMaintainBizorderCreateModel extends AlipayObject {
private static final long serialVersionUID = 5165646828679537573L;
/**
* 预约确认时间yyyy-MM-dd HH:mm:ss。门店确认预约时间。门店确认后,预约流程生效,用户可到店服务。
*/
@ApiField("appoint_affirm_time")
private String appointAffirmTime;
/**
* 预约结束时间yyyy-MM-dd HH:mm:ss。用户选择的预约结束时间,用于判断用户是否在预约时间到店服务。
*/
@ApiField("appoint_end_time")
private String appointEndTime;
/**
* 预约开始时间yyyy-MM-dd HH:mm:ss,用户选择的预约开始时间,用于判断用户是否在预约时间到店服务。
*/
@ApiField("appoint_start_time")
private String appointStartTime;
/**
* 预约状态(0-待确认预约 1-确认预约)。有预约流程的订单,门店确认前为待确认预约,门店确认后为 确认预约。
*/
@ApiField("appoint_status")
private Long appointStatus;
/**
* 到店时间yyyy-MM-dd HH:mm:ss。 用户到店时间,用于判断用户是否在预约时间到店服务。
*/
@ApiField("arrive_time")
private String arriveTime;
/**
* ISV订单状态文案。由ISV上传自己订单的状态,用于订单数据的匹配和对账。
*/
@ApiField("biz_status_txt")
private String bizStatusTxt;
/**
* 订单类型,1:洗车,2:保养,4:4s店
*/
@ApiField("biz_type")
private Long bizType;
/**
* 车主平台我的爱车ID。可通过接口查询爱车详情。 请查看alipay.eco.mycar.dataservice.maintainvehicle.share接口。
*/
@ApiField("car_id")
private String carId;
/**
* 服务项列表
*/
@ApiListField("order_server_list")
@ApiField("maintain_biz_order")
private List<MaintainBizOrder> orderServerList;
/**
* 车主平台业务订单状态
1-未支付;
4-已关闭;
6-支付完成;
7-已出库;
8-已收货;
11-服务开始;
55-服务完成/已核销;
56-订单完成;
*/
@ApiField("order_status")
private Long orderStatus;
/**
* 原始金额,服务原价累计后金额。金额单位(元),保留两位小数。
原始金额 = 服务原始价格 * 数量 + 商品售卖价格 * 数量
*/
@ApiField("original_cost")
private String originalCost;
/**
* ISV业务订单号,ISV上传订单场景,由业务方保证唯一
*/
@ApiField("out_order_no")
private String outOrderNo;
/**
* 外部门店编号,订单创建时对应的门店的外部编号,要保证编码在车主平台已经创建对应的门店数据,即有与之唯一匹配的车主平台shop_id
*/
@ApiField("out_shop_id")
private String outShopId;
/**
* 支付时间yyyy-MM-dd HH:mm:ss
*/
@ApiField("pay_time")
private String payTime;
/**
* 交易金额。下单时实际支付金额。金额单位(元),保留两位小数。
交易金额 = 服务售卖价格 * 数量 + 商品售卖价格 * 数量
*/
@ApiField("real_cost")
private String realCost;
/**
* 车主平台门店编号
*/
@ApiField("shop_id")
private Long shopId;
/**
* 支付宝用户ID
*/
@ApiField("user_id")
private String userId;
/**
* <p>Getter for the field <code>appointAffirmTime</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getAppointAffirmTime() {
return this.appointAffirmTime;
}
/**
* <p>Setter for the field <code>appointAffirmTime</code>.</p>
*
* @param appointAffirmTime a {@link java.lang.String} object.
*/
public void setAppointAffirmTime(String appointAffirmTime) {
this.appointAffirmTime = appointAffirmTime;
}
/**
* <p>Getter for the field <code>appointEndTime</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getAppointEndTime() {
return this.appointEndTime;
}
/**
* <p>Setter for the field <code>appointEndTime</code>.</p>
*
* @param appointEndTime a {@link java.lang.String} object.
*/
public void setAppointEndTime(String appointEndTime) {
this.appointEndTime = appointEndTime;
}
/**
* <p>Getter for the field <code>appointStartTime</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getAppointStartTime() {
return this.appointStartTime;
}
/**
* <p>Setter for the field <code>appointStartTime</code>.</p>
*
* @param appointStartTime a {@link java.lang.String} object.
*/
public void setAppointStartTime(String appointStartTime) {
this.appointStartTime = appointStartTime;
}
/**
* <p>Getter for the field <code>appointStatus</code>.</p>
*
* @return a {@link java.lang.Long} object.
*/
public Long getAppointStatus() {
return this.appointStatus;
}
/**
* <p>Setter for the field <code>appointStatus</code>.</p>
*
* @param appointStatus a {@link java.lang.Long} object.
*/
public void setAppointStatus(Long appointStatus) {
this.appointStatus = appointStatus;
}
/**
* <p>Getter for the field <code>arriveTime</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getArriveTime() {
return this.arriveTime;
}
/**
* <p>Setter for the field <code>arriveTime</code>.</p>
*
* @param arriveTime a {@link java.lang.String} object.
*/
public void setArriveTime(String arriveTime) {
this.arriveTime = arriveTime;
}
/**
* <p>Getter for the field <code>bizStatusTxt</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getBizStatusTxt() {
return this.bizStatusTxt;
}
/**
* <p>Setter for the field <code>bizStatusTxt</code>.</p>
*
* @param bizStatusTxt a {@link java.lang.String} object.
*/
public void setBizStatusTxt(String bizStatusTxt) {
this.bizStatusTxt = bizStatusTxt;
}
/**
* <p>Getter for the field <code>bizType</code>.</p>
*
* @return a {@link java.lang.Long} object.
*/
public Long getBizType() {
return this.bizType;
}
/**
* <p>Setter for the field <code>bizType</code>.</p>
*
* @param bizType a {@link java.lang.Long} object.
*/
public void setBizType(Long bizType) {
this.bizType = bizType;
}
/**
* <p>Getter for the field <code>carId</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getCarId() {
return this.carId;
}
/**
* <p>Setter for the field <code>carId</code>.</p>
*
* @param carId a {@link java.lang.String} object.
*/
public void setCarId(String carId) {
this.carId = carId;
}
/**
* <p>Getter for the field <code>orderServerList</code>.</p>
*
* @return a {@link java.util.List} object.
*/
public List<MaintainBizOrder> getOrderServerList() {
return this.orderServerList;
}
/**
* <p>Setter for the field <code>orderServerList</code>.</p>
*
* @param orderServerList a {@link java.util.List} object.
*/
public void setOrderServerList(List<MaintainBizOrder> orderServerList) {
this.orderServerList = orderServerList;
}
/**
* <p>Getter for the field <code>orderStatus</code>.</p>
*
* @return a {@link java.lang.Long} object.
*/
public Long getOrderStatus() {
return this.orderStatus;
}
/**
* <p>Setter for the field <code>orderStatus</code>.</p>
*
* @param orderStatus a {@link java.lang.Long} object.
*/
public void setOrderStatus(Long orderStatus) {
this.orderStatus = orderStatus;
}
/**
* <p>Getter for the field <code>originalCost</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getOriginalCost() {
return this.originalCost;
}
/**
* <p>Setter for the field <code>originalCost</code>.</p>
*
* @param originalCost a {@link java.lang.String} object.
*/
public void setOriginalCost(String originalCost) {
this.originalCost = originalCost;
}
/**
* <p>Getter for the field <code>outOrderNo</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getOutOrderNo() {
return this.outOrderNo;
}
/**
* <p>Setter for the field <code>outOrderNo</code>.</p>
*
* @param outOrderNo a {@link java.lang.String} object.
*/
public void setOutOrderNo(String outOrderNo) {
this.outOrderNo = outOrderNo;
}
/**
* <p>Getter for the field <code>outShopId</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getOutShopId() {
return this.outShopId;
}
/**
* <p>Setter for the field <code>outShopId</code>.</p>
*
* @param outShopId a {@link java.lang.String} object.
*/
public void setOutShopId(String outShopId) {
this.outShopId = outShopId;
}
/**
* <p>Getter for the field <code>payTime</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getPayTime() {
return this.payTime;
}
/**
* <p>Setter for the field <code>payTime</code>.</p>
*
* @param payTime a {@link java.lang.String} object.
*/
public void setPayTime(String payTime) {
this.payTime = payTime;
}
/**
* <p>Getter for the field <code>realCost</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getRealCost() {
return this.realCost;
}
/**
* <p>Setter for the field <code>realCost</code>.</p>
*
* @param realCost a {@link java.lang.String} object.
*/
public void setRealCost(String realCost) {
this.realCost = realCost;
}
/**
* <p>Getter for the field <code>shopId</code>.</p>
*
* @return a {@link java.lang.Long} object.
*/
public Long getShopId() {
return this.shopId;
}
/**
* <p>Setter for the field <code>shopId</code>.</p>
*
* @param shopId a {@link java.lang.Long} object.
*/
public void setShopId(Long shopId) {
this.shopId = shopId;
}
/**
* <p>Getter for the field <code>userId</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getUserId() {
return this.userId;
}
/**
* <p>Setter for the field <code>userId</code>.</p>
*
* @param userId a {@link java.lang.String} object.
*/
public void setUserId(String userId) {
this.userId = userId;
}
}
| apache-2.0 |
LayneMobile/Stash | samples/hockeyloader/src/main/java/stash/samples/hockeyloader/activity/MainActivity.java | 3205 | /*
* Copyright 2016 Layne Mobile, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package stash.samples.hockeyloader.activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import rxsubscriptions.components.support.RxsAppCompatActivity;
import stash.samples.hockeyloader.R;
import stash.samples.hockeyloader.fragment.AuthFragment;
import stash.samples.hockeyloader.fragment.HockeyFragment;
import stash.samples.hockeyloader.fragment.MyAppsFragment;
import stash.samples.hockeyloader.network.model.Auth;
public class MainActivity extends RxsAppCompatActivity
implements AuthFragment.AuthDelegate, HockeyFragment.HockeyFragmentListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null && Auth.getCurrentUser() == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.container, new AuthFragment())
.commit();
} else if (Auth.getCurrentUser() == null) {
getFragmentManager()
.beginTransaction()
.replace(R.id.container, new AuthFragment())
.commit();
} else if (savedInstanceState == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.container, new MyAppsFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the source bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle source bar item clicks here. The source bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onAuthenticated(Auth auth) {
getFragmentManager()
.beginTransaction()
.replace(R.id.container, new MyAppsFragment())
.commit();
}
@Override
public void push(HockeyFragment fragment) {
getFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit();
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/transform/RecognizeCelebritiesRequestMarshaller.java | 2068 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.rekognition.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.rekognition.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* RecognizeCelebritiesRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RecognizeCelebritiesRequestMarshaller {
private static final MarshallingInfo<StructuredPojo> IMAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Image").build();
private static final RecognizeCelebritiesRequestMarshaller instance = new RecognizeCelebritiesRequestMarshaller();
public static RecognizeCelebritiesRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(RecognizeCelebritiesRequest recognizeCelebritiesRequest, ProtocolMarshaller protocolMarshaller) {
if (recognizeCelebritiesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(recognizeCelebritiesRequest.getImage(), IMAGE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
tailanx/test | src/com/yidejia/app/mall/log/LogService.java | 3609 | package com.yidejia.app.mall.log;
import com.opens.asyncokhttpclient.AsyncHttpResponse;
import com.opens.asyncokhttpclient.AsyncOkHttpClient;
import com.opens.asyncokhttpclient.RequestParams;
import com.yidejia.app.mall.ctrl.IpAddress;
import com.yidejia.app.mall.jni.JNICallBack;
import com.yidejia.app.mall.net.user.Login;
import com.yidejia.app.mall.util.Consts;
import com.yidejia.app.mall.util.DesUtils;
import com.yidejia.app.mall.util.HttpClientUtil;
import com.yidejia.app.mall.util.IHttpResp;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
public class LogService extends Service {
private SharedPreferences sp;
private Consts consts;
// private LoginTask task;
private IpAddress ipAddress;
// private Login login;
private String baseName;
private String basepasswrod;
// private AsyncOkHttpClient client;
// private RequestParams params;
private String hosturl;
// private String contentType;
private Boolean isCheck;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
consts = new Consts();
sp = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
ipAddress = new IpAddress();
// params = new RequestParams();
hosturl = new JNICallBack().HTTPURL;
// contentType = "application/x-www-form-urlencoded;charset=UTF-8";
// client = new AsyncOkHttpClient();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
baseName = sp.getString("DESMI", null);
//
String basePwd = sp.getString("DESPWD", null);
String keyName = baseName + consts.getMiStr();
basepasswrod = DesUtils.decode(keyName, basePwd);
isCheck = sp.getBoolean("CHECK", false);
if (null == basePwd || null == basepasswrod || !isCheck) {
stopSelf();
} else {
String url = new JNICallBack().getHttp4Login(baseName,
basepasswrod, ipAddress.getIpAddress());
// params.put(url);
loginService(url);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
stopSelf();
}
private void loginService(String url) {
HttpClientUtil httpClientUtil = new HttpClientUtil();
httpClientUtil.getHttpResp(hosturl, url, new IHttpResp(){
@Override
public void onFinish() {
super.onFinish();
stopSelf();
}
@Override
public void onSuccess(String content) {
super.onSuccess(content);
if (null != content && !"".equals(content)) {
Login login = new Login();
login.parseLogin(content);
stopSelf();
} else {
stopSelf();
}
}
@Override
public void onError() {
super.onError();
stopSelf();
}
});
/*client.post(hosturl, contentType, params, new AsyncHttpResponse() {
@Override
public void onStart() {
super.onStart();
}
@Override
public void onFinish() {
super.onFinish();
stopSelf();
}
@Override
public void onSuccess(int statusCode, String content) {
super.onSuccess(statusCode, content);
if (null != content && !"".equals(content)) {
Login login = new Login();
login.parseLogin(content);
stopSelf();
} else {
stopSelf();
}
}
@Override
public void onError(Throwable error, String content) {
super.onError(error, content);
stopSelf();
}
});*/
}
}
| apache-2.0 |
featherfly/conversion | src/main/java/cn/featherfly/conversion/core/bp/FloatWrapperBeanPropertyFormatConvertor.java | 483 |
package cn.featherfly.conversion.core.bp;
import cn.featherfly.conversion.core.format.FloatWrapperFormatConvertor;
/**
* <p>
* 带格式支持的数字转换器,在属性字段上使用@NumberFormat来指定格式.
* </p>
*
* @author 钟冀
*/
public class FloatWrapperBeanPropertyFormatConvertor extends BeanPropertyFormatConvertor<Float> {
/**
*/
public FloatWrapperBeanPropertyFormatConvertor() {
super(new FloatWrapperFormatConvertor());
}
}
| apache-2.0 |
caratarse/caratarse-auth | caratarse-auth-cas-support/src/main/java/org/caratarse/auth/cas/support/CaratarseAuthClientAuthenticationHandler.java | 4128 | /**
* Copyright (C) 2015 Caratarse Auth Team <lucio.benfante@gmail.com>
*
* This file is part of Caratarse Auth support for CAS.
*
* 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.caratarse.auth.cas.support;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.caratarse.auth.client.ApiResponse;
import org.caratarse.auth.client.CaratarseAuthClient;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.handler.BadPasswordAuthenticationException;
import org.jasig.cas.authentication.handler.BlockedCredentialsAuthenticationException;
import org.jasig.cas.authentication.handler.UnknownUsernameAuthenticationException;
import org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.springframework.beans.factory.InitializingBean;
/**
* An authentication handler that uses the Caratarse-auth services.
*
* @author Lucio Benfante <lucio@benfante.com>
*/
public class CaratarseAuthClientAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler implements InitializingBean {
private CaratarseAuthClient caratarseAuthClient;
private boolean withSalt = true;
protected final boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials) throws AuthenticationException {
final String transformedUsername = getPrincipalNameTransformer().transform(credentials.getUsername());
final String encryptedPassword = getPasswordEncoder().encode(
credentials.getPassword() + (isWithSalt()?"{" + transformedUsername + "}":""));
ApiResponse response;
JsonNode userTree;
try {
response = caratarseAuthClient.getUserByUsername(transformedUsername);
if ("404".equals(response.getCode())) {
throw new UnknownUsernameAuthenticationException();
}
ObjectMapper m = new ObjectMapper();
JsonNode rootTree = m.readTree(response.getContent());
userTree = rootTree.get("_embedded").get("users").get(0);
if (userTree == null) {
throw new UnknownUsernameAuthenticationException();
}
} catch (Exception ex) {
throw new AuthenticationException("Authentication failed for user "+transformedUsername, ex) {};
}
if (!userIsEnabled(userTree)) {
throw new BlockedCredentialsAuthenticationException();
}
if (!passwordMatches(userTree, encryptedPassword)) {
throw new BadPasswordAuthenticationException();
}
// update last login
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
}
public CaratarseAuthClient getCaratarseAuthClient() {
return caratarseAuthClient;
}
public void setCaratarseAuthClient(CaratarseAuthClient caratarseAuthClient) {
this.caratarseAuthClient = caratarseAuthClient;
}
public boolean isWithSalt() {
return withSalt;
}
public void setWithSalt(boolean withSalt) {
this.withSalt = withSalt;
}
private boolean userIsEnabled(JsonNode userTree) {
return userTree.get("disabled") == null;
}
private boolean passwordMatches(JsonNode userTree, String encryptedPassword) {
return encryptedPassword.equals(userTree.get("password").asText());
}
} | apache-2.0 |
VardanMatevosyan/Vardan-Git-Repository | CollectionsLite/bank/src/test/java/ru/matevosyan/package-info.java | 137 | /**
* Created for testing Bank class.
* Created on 28.04.2017.
* @author Matevosyan Vardan
* @version 1.0
*/
package ru.matevosyan; | apache-2.0 |
yuzhiping/jeeplus | jeeplus-blog/src/main/java/com/jeeplus/blog/common/freemarker/directive/article/ArticleTimeLineNavigateDirective.java | 1616 | package com.jeeplus.blog.common.freemarker.directive.article;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.jeeplus.blog.service.BlogArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
/**
*
* <pre>
* 类名称:文章时间轴 导航
* 类描述:
* 创建人:陈国祥 (kingschan)
* 创建时间:2016-2-20 下午3:20:55
* 修改人:Administrator
* 修改时间:2016-2-20 下午3:20:55
* 修改备注:
* @version V1.0
* </pre>
*/
@Component("ArticleTimeLineNavigate")
public class ArticleTimeLineNavigateDirective implements TemplateDirectiveModel {
@Autowired
private BlogArticleService articleService;
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] tm, TemplateDirectiveBody body)
throws TemplateException, IOException {
String websiteid=params.get("website_id").toString();
try {
List<Map<String, Object>> lis = articleService.getArticleTimeNavigate(websiteid);
env.setVariable("article_timeline_nav", ObjectWrapper.DEFAULT_WRAPPER.wrap(lis));
body.render(env.getOut());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
StarMade/SMEditClassic | JoFileMods/src/jo/sm/plugins/planet/gen/UndulatingParametersBeanInfo.java | 2217 | package jo.sm.plugins.planet.gen;
import java.awt.Image;
import java.beans.BeanDescriptor;
import java.beans.BeanInfo;
import java.beans.EventSetDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import jo.sm.ui.act.plugin.BlockPropertyDescriptor;
public class UndulatingParametersBeanInfo implements BeanInfo
{
private BeanInfo mRootBeanInfo;
public UndulatingParametersBeanInfo() throws IntrospectionException
{
super();
mRootBeanInfo = Introspector.getBeanInfo(UndulatingParameters.class, Introspector.IGNORE_IMMEDIATE_BEANINFO);
}
@Override
public PropertyDescriptor[] getPropertyDescriptors()
{
PropertyDescriptor[] props = mRootBeanInfo.getPropertyDescriptors();
for (int i = 0; i < props.length; i++)
{
if (props[i].getName().equalsIgnoreCase("fillWith"))
try
{
props[i] = new BlockPropertyDescriptor(props[i].getName(),
props[i].getReadMethod(), props[i].getWriteMethod());
}
catch (IntrospectionException e)
{
e.printStackTrace();
}
}
return props;
}
@Override
public BeanInfo[] getAdditionalBeanInfo()
{
return mRootBeanInfo.getAdditionalBeanInfo();
}
@Override
public BeanDescriptor getBeanDescriptor()
{
return mRootBeanInfo.getBeanDescriptor();
}
@Override
public int getDefaultEventIndex()
{
return mRootBeanInfo.getDefaultEventIndex();
}
@Override
public int getDefaultPropertyIndex()
{
return mRootBeanInfo.getDefaultPropertyIndex();
}
@Override
public EventSetDescriptor[] getEventSetDescriptors()
{
return mRootBeanInfo.getEventSetDescriptors();
}
@Override
public Image getIcon(int flags)
{
return mRootBeanInfo.getIcon(flags);
}
@Override
public MethodDescriptor[] getMethodDescriptors()
{
return mRootBeanInfo.getMethodDescriptors();
}
}
| apache-2.0 |
hhu94/Synapse-Repository-Services | lib/lib-audit/src/test/java/org/sagebionetworks/audit/ObjectCSVDAOTest.java | 3879 | package org.sagebionetworks.audit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.sagebionetworks.audit.dao.ObjectCSVDAO;
import org.sagebionetworks.csv.utils.ExampleObject;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3ObjectSummary;
public class ObjectCSVDAOTest {
private AmazonS3Client mockS3Client;
private int stackInstanceNumber;
private String bucketName;
private Class<ExampleObject> objectClass;
private String[] headers;
private ObjectCSVDAO<ExampleObject> dao;
@Before
public void setUp() {
mockS3Client = Mockito.mock(AmazonS3Client.class);
stackInstanceNumber = 1;
bucketName = "object.csv.dao.test";
objectClass = ExampleObject.class;
headers = new String[]{"aString", "aLong", "aBoolean", "aDouble", "anInteger", "aFloat", "someEnum"};
dao = new ObjectCSVDAO<ExampleObject>(mockS3Client, stackInstanceNumber, bucketName, objectClass, headers);
}
/**
* Test write and read methods
* @throws Exception
*/
@Test
public void testRoundTrip() throws Exception{
Long timestamp = System.currentTimeMillis();
boolean rolling = false;
// Build up some sample data
List<ExampleObject> data = ExampleObject.buildExampleObjectList(12);
// call under test.
String key = dao.write(data, timestamp, rolling);
// capture results
ArgumentCaptor<String> bucketCapture = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> keyCapture = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<InputStream> inCapture = ArgumentCaptor.forClass(InputStream.class);
ArgumentCaptor<ObjectMetadata> metaCapture = ArgumentCaptor.forClass(ObjectMetadata.class);
verify(mockS3Client).putObject(bucketCapture.capture(), keyCapture.capture(), inCapture.capture(), metaCapture.capture());
assertEquals(bucketName, bucketCapture.getValue());
assertEquals(key, keyCapture.getValue());
// Can we read the results?
List<ExampleObject> results = dao.readFromStream(inCapture.getValue());
assertEquals(data, results);
assertEquals("attachment; filename="+key+";", metaCapture.getValue().getContentDisposition());
assertEquals("application/x-gzip", metaCapture.getValue().getContentType());
assertEquals("gzip", metaCapture.getValue().getContentEncoding());
assertTrue(metaCapture.getValue().getContentLength() > 1);
}
@Test
public void testListBatchKeys() throws Exception {
ObjectListing one = new ObjectListing();
S3ObjectSummary sum = new S3ObjectSummary();
sum.setKey("one");
one.getObjectSummaries().add(sum);
sum = new S3ObjectSummary();
sum.setKey("two");
one.getObjectSummaries().add(sum);
one.setNextMarker("nextMarker");
ObjectListing two = new ObjectListing();
sum = new S3ObjectSummary();
sum.setKey("three");
two.getObjectSummaries().add(sum);
sum = new S3ObjectSummary();
sum.setKey("four");
two.getObjectSummaries().add(sum);
two.setMarker(null);
when(mockS3Client.listObjects(any(ListObjectsRequest.class))).thenReturn(one, two);
// Now iterate over all key and ensure all keys are found
Set<String> foundKeys = dao.listAllKeys();
// the two set should be equal
assertEquals(4, foundKeys.size());
assertTrue(foundKeys.contains("one"));
assertTrue(foundKeys.contains("two"));
assertTrue(foundKeys.contains("three"));
assertTrue(foundKeys.contains("four"));
}
}
| apache-2.0 |
BartoszJarocki/boilerpipe-android | src/main/java/mf/org/apache/xerces/impl/xpath/regex/Op.java | 8775 | /*
* 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 mf.org.apache.xerces.impl.xpath.regex;
import java.util.Vector;
/**
* @xerces.internal
*
* @version $Id: Op.java 572108 2007-09-02 18:48:31Z mrglavas $
*/
class Op {
static final int DOT = 0;
static final int CHAR = 1; // Single character
static final int RANGE = 3; // [a-zA-Z]
static final int NRANGE = 4; // [^a-zA-Z]
static final int ANCHOR = 5; // ^ $ ...
static final int STRING = 6; // literal String
static final int CLOSURE = 7; // X*
static final int NONGREEDYCLOSURE = 8; // X*?
static final int QUESTION = 9; // X?
static final int NONGREEDYQUESTION = 10; // X??
static final int UNION = 11; // X|Y
static final int CAPTURE = 15; // ( and )
static final int BACKREFERENCE = 16; // \1 \2 ...
static final int LOOKAHEAD = 20; // (?=...)
static final int NEGATIVELOOKAHEAD = 21; // (?!...)
static final int LOOKBEHIND = 22; // (?<=...)
static final int NEGATIVELOOKBEHIND = 23; // (?<!...)
static final int INDEPENDENT = 24; // (?>...)
static final int MODIFIER = 25; // (?ims-ims:...)
static final int CONDITION = 26; // (?(..)yes|no)
static int nofinstances = 0;
static final boolean COUNT = false;
static Op createDot() {
if (Op.COUNT) Op.nofinstances ++;
return new Op(Op.DOT);
}
static CharOp createChar(int data) {
if (Op.COUNT) Op.nofinstances ++;
return new CharOp(Op.CHAR, data);
}
static CharOp createAnchor(int data) {
if (Op.COUNT) Op.nofinstances ++;
return new CharOp(Op.ANCHOR, data);
}
static CharOp createCapture(int number, Op next) {
if (Op.COUNT) Op.nofinstances ++;
CharOp op = new CharOp(Op.CAPTURE, number);
op.next = next;
return op;
}
static UnionOp createUnion(int size) {
if (Op.COUNT) Op.nofinstances ++;
//System.err.println("Creates UnionOp");
return new UnionOp(Op.UNION, size);
}
static ChildOp createClosure(int id) {
if (Op.COUNT) Op.nofinstances ++;
return new ModifierOp(Op.CLOSURE, id, -1);
}
static ChildOp createNonGreedyClosure() {
if (Op.COUNT) Op.nofinstances ++;
return new ChildOp(Op.NONGREEDYCLOSURE);
}
static ChildOp createQuestion(boolean nongreedy) {
if (Op.COUNT) Op.nofinstances ++;
return new ChildOp(nongreedy ? Op.NONGREEDYQUESTION : Op.QUESTION);
}
static RangeOp createRange(Token tok) {
if (Op.COUNT) Op.nofinstances ++;
return new RangeOp(Op.RANGE, tok);
}
static ChildOp createLook(int type, Op next, Op branch) {
if (Op.COUNT) Op.nofinstances ++;
ChildOp op = new ChildOp(type);
op.setChild(branch);
op.next = next;
return op;
}
static CharOp createBackReference(int refno) {
if (Op.COUNT) Op.nofinstances ++;
return new CharOp(Op.BACKREFERENCE, refno);
}
static StringOp createString(String literal) {
if (Op.COUNT) Op.nofinstances ++;
return new StringOp(Op.STRING, literal);
}
static ChildOp createIndependent(Op next, Op branch) {
if (Op.COUNT) Op.nofinstances ++;
ChildOp op = new ChildOp(Op.INDEPENDENT);
op.setChild(branch);
op.next = next;
return op;
}
static ModifierOp createModifier(Op next, Op branch, int add, int mask) {
if (Op.COUNT) Op.nofinstances ++;
ModifierOp op = new ModifierOp(Op.MODIFIER, add, mask);
op.setChild(branch);
op.next = next;
return op;
}
static ConditionOp createCondition(Op next, int ref, Op conditionflow, Op yesflow, Op noflow) {
if (Op.COUNT) Op.nofinstances ++;
ConditionOp op = new ConditionOp(Op.CONDITION, ref, conditionflow, yesflow, noflow);
op.next = next;
return op;
}
final int type;
Op next = null;
protected Op(int type) {
this.type = type;
}
int size() { // for UNION
return 0;
}
Op elementAt(int index) { // for UNIoN
throw new RuntimeException("Internal Error: type="+this.type);
}
Op getChild() { // for CLOSURE, QUESTION
throw new RuntimeException("Internal Error: type="+this.type);
}
// ModifierOp
int getData() { // CharOp for CHAR, BACKREFERENCE, CAPTURE, ANCHOR,
throw new RuntimeException("Internal Error: type="+this.type);
}
int getData2() { // ModifierOp
throw new RuntimeException("Internal Error: type="+this.type);
}
RangeToken getToken() { // RANGE, NRANGE
throw new RuntimeException("Internal Error: type="+this.type);
}
String getString() { // STRING
throw new RuntimeException("Internal Error: type="+this.type);
}
// ================================================================
static class CharOp extends Op {
final int charData;
CharOp(int type, int data) {
super(type);
this.charData = data;
}
int getData() {
return this.charData;
}
}
// ================================================================
static class UnionOp extends Op {
final Vector branches;
UnionOp(int type, int size) {
super(type);
this.branches = new Vector(size);
}
void addElement(Op op) {
this.branches.addElement(op);
}
int size() {
return this.branches.size();
}
Op elementAt(int index) {
return (Op)this.branches.elementAt(index);
}
}
// ================================================================
static class ChildOp extends Op {
Op child;
ChildOp(int type) {
super(type);
}
void setChild(Op child) {
this.child = child;
}
Op getChild() {
return this.child;
}
}
// ================================================================
static class ModifierOp extends ChildOp {
final int v1;
final int v2;
ModifierOp(int type, int v1, int v2) {
super(type);
this.v1 = v1;
this.v2 = v2;
}
int getData() {
return this.v1;
}
int getData2() {
return this.v2;
}
}
// ================================================================
static class RangeOp extends Op {
final Token tok;
RangeOp(int type, Token tok) {
super(type);
this.tok = tok;
}
RangeToken getToken() {
return (RangeToken)this.tok;
}
}
// ================================================================
static class StringOp extends Op {
final String string;
StringOp(int type, String literal) {
super(type);
this.string = literal;
}
String getString() {
return this.string;
}
}
// ================================================================
static class ConditionOp extends Op {
final int refNumber;
final Op condition;
final Op yes;
final Op no;
ConditionOp(int type, int refno, Op conditionflow, Op yesflow, Op noflow) {
super(type);
this.refNumber = refno;
this.condition = conditionflow;
this.yes = yesflow;
this.no = noflow;
}
}
}
| apache-2.0 |
iisquare/analysis-ik-online | elasticsearch7.x/src/main/java/com/iisquare/elasticsearch/wltea/core/CharacterUtil.java | 4215 | /**
* IK 中文分词 版本 5.0
* IK Analyzer release 5.0
* <p>
* 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.
* <p>
* 源代码由林良益(linliangyi2005@gmail.com)提供
* 版权声明 2012,乌龙茶工作室
* provided by Linliangyi and copyright 2012 by Oolong studio
* <p>
* 字符集识别工具类
*/
package com.iisquare.elasticsearch.wltea.core;
/**
*
* 字符集识别工具类
*/
class CharacterUtil {
public static final int CHAR_USELESS = 0;
public static final int CHAR_ARABIC = 0X00000001;
public static final int CHAR_ENGLISH = 0X00000002;
public static final int CHAR_CHINESE = 0X00000004;
public static final int CHAR_OTHER_CJK = 0X00000008;
/**
* 识别字符类型
*
* @param input
* none
* @return int CharacterUtil定义的字符类型常量
*/
static int identifyCharType(char input, boolean useArabic,
boolean useEnglish) {
if (' ' == input)
return CHAR_USELESS;
if (useArabic && input >= '0' && input <= '9')
return CHAR_ARABIC;
if (useEnglish
&& ((input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z')))
return CHAR_ENGLISH;
Character.UnicodeBlock ub = Character.UnicodeBlock.of(input);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A) {
// 目前已知的中文字符UTF-8集合
return CHAR_CHINESE;
}
return CHAR_OTHER_CJK;
/*
* if(input >= '0' && input <= '9'){ return CHAR_ARABIC;
*
* }else if((input >= 'a' && input <= 'z') || (input >= 'A' && input <=
* 'Z')){ return CHAR_ENGLISH;
*
* }else { Character.UnicodeBlock ub = Character.UnicodeBlock.of(input);
*
* if(ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub ==
* Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub ==
* Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A){
* //目前已知的中文字符UTF-8集合 return CHAR_CHINESE;
*
* }else if(ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
* //全角数字字符和日韩字符 //韩文字符集 || ub ==
* Character.UnicodeBlock.HANGUL_SYLLABLES || ub ==
* Character.UnicodeBlock.HANGUL_JAMO || ub ==
* Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO //日文字符集 || ub ==
* Character.UnicodeBlock.HIRAGANA //平假名 || ub ==
* Character.UnicodeBlock.KATAKANA //片假名 || ub ==
* Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS){ return
* CHAR_OTHER_CJK;
*
* } } //其他的不做处理的字符 return CHAR_USELESS;
*/
}
/**
* 进行字符规格化(全角转半角,大写转小写处理)
*
* @param input
* none
* @return char none
*/
static char regularize(char input) {
if (input == 12288) {
input = (char) 32;
} else if (input > 65280 && input < 65375) {
input = (char) (input - 65248);
} else if (input >= 'A' && input <= 'Z') {
input += 32;
}
return input;
}
}
| apache-2.0 |
Benjamin-Dobell/Apktool | brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/StringBlock.java | 12044 | /**
* Copyright (C) 2017 Ryszard Wiśniewski <brut.alll@gmail.com>
* Copyright (C) 2017 Connor Tumbleson <connor.tumbleson@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 brut.androlib.res.decoder;
import brut.androlib.res.xml.ResXmlEncoders;
import brut.util.ExtDataInput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.*;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Ryszard Wiśniewski <brut.alll@gmail.com>
* @author Dmitry Skiba
*
* Block of strings, used in binary xml and arsc.
*
* TODO: - implement get()
*
*/
public class StringBlock {
/**
* Reads whole (including chunk type) string block from stream. Stream must
* be at the chunk type.
*/
public static StringBlock read(ExtDataInput reader) throws IOException {
reader.skipCheckChunkTypeInt(CHUNK_STRINGPOOL_TYPE, CHUNK_NULL_TYPE);
int chunkSize = reader.readInt();
// ResStringPool_header
int stringCount = reader.readInt();
int styleCount = reader.readInt();
int flags = reader.readInt();
int stringsOffset = reader.readInt();
int stylesOffset = reader.readInt();
StringBlock block = new StringBlock();
block.m_isUTF8 = (flags & UTF8_FLAG) != 0;
block.m_stringOffsets = reader.readIntArray(stringCount);
block.m_stringOwns = new int[stringCount];
Arrays.fill(block.m_stringOwns, -1);
if (styleCount != 0) {
block.m_styleOffsets = reader.readIntArray(styleCount);
}
int size = ((stylesOffset == 0) ? chunkSize : stylesOffset) - stringsOffset;
block.m_strings = new byte[size];
reader.readFully(block.m_strings);
if (stylesOffset != 0) {
size = (chunkSize - stylesOffset);
block.m_styles = reader.readIntArray(size / 4);
// read remaining bytes
int remaining = size % 4;
if (remaining >= 1) {
while (remaining-- > 0) {
reader.readByte();
}
}
}
return block;
}
/**
* Returns number of strings in block.
*/
public int getCount() {
return m_stringOffsets != null ? m_stringOffsets.length : 0;
}
/**
* Returns raw string (without any styling information) at specified index.
*/
public String getString(int index) {
if (index < 0 || m_stringOffsets == null || index >= m_stringOffsets.length) {
return null;
}
int offset = m_stringOffsets[index];
int length;
if (m_isUTF8) {
int[] val = getUtf8(m_strings, offset);
offset = val[0];
length = val[1];
} else {
int[] val = getUtf16(m_strings, offset);
offset += val[0];
length = val[1];
}
return decodeString(offset, length);
}
/**
* Not yet implemented.
*
* Returns string with style information (if any).
*/
public CharSequence get(int index) {
return getString(index);
}
/**
* Returns string with style tags (html-like).
*/
public String getHTML(int index) {
String raw = getString(index);
if (raw == null) {
return raw;
}
int[] style = getStyle(index);
if (style == null) {
return ResXmlEncoders.escapeXmlChars(raw);
}
// If the returned style is further in string, than string length. Lets skip it.
if (style[1] > raw.length()) {
return ResXmlEncoders.escapeXmlChars(raw);
}
StringBuilder html = new StringBuilder(raw.length() + 32);
int[] opened = new int[style.length / 3];
boolean[] unclosed = new boolean[style.length / 3];
int offset = 0, depth = 0;
while (true) {
int i = -1, j;
for (j = 0; j != style.length; j += 3) {
if (style[j + 1] == -1) {
continue;
}
if (i == -1 || style[i + 1] > style[j + 1]) {
i = j;
}
}
int start = ((i != -1) ? style[i + 1] : raw.length());
for (j = depth - 1; j >= 0; j--) {
int last = opened[j];
int end = style[last + 2];
if (end >= start) {
if (style[last + 1] == -1 && end != -1) {
unclosed[j] = true;
}
break;
}
if (offset <= end) {
html.append(ResXmlEncoders.escapeXmlChars(raw.substring(offset, end + 1)));
offset = end + 1;
}
outputStyleTag(getString(style[last]), html, true);
}
depth = j + 1;
if (offset < start) {
html.append(ResXmlEncoders.escapeXmlChars(raw.substring(offset, start)));
if (j >= 0 && unclosed.length >= j && unclosed[j]) {
if (unclosed.length > (j + 1) && unclosed[j + 1] || unclosed.length == 1) {
outputStyleTag(getString(style[opened[j]]), html, true);
}
}
offset = start;
}
if (i == -1) {
break;
}
outputStyleTag(getString(style[i]), html, false);
style[i + 1] = -1;
opened[depth++] = i;
}
return html.toString();
}
private void outputStyleTag(String tag, StringBuilder builder, boolean close) {
builder.append('<');
if (close) {
builder.append('/');
}
int pos = tag.indexOf(';');
if (pos == -1) {
builder.append(tag);
} else {
builder.append(tag.substring(0, pos));
if (!close) {
boolean loop = true;
while (loop) {
int pos2 = tag.indexOf('=', pos + 1);
// malformed style information will cause crash. so
// prematurely end style tags, if recreation
// cannot be created.
if (pos2 != -1) {
builder.append(' ').append(tag.substring(pos + 1, pos2)).append("=\"");
pos = tag.indexOf(';', pos2 + 1);
String val;
if (pos != -1) {
val = tag.substring(pos2 + 1, pos);
} else {
loop = false;
val = tag.substring(pos2 + 1);
}
builder.append(ResXmlEncoders.escapeXmlChars(val)).append('"');
} else {
loop = false;
}
}
}
}
builder.append('>');
}
/**
* Finds index of the string. Returns -1 if the string was not found.
*/
public int find(String string) {
if (string == null) {
return -1;
}
for (int i = 0; i != m_stringOffsets.length; ++i) {
int offset = m_stringOffsets[i];
int length = getShort(m_strings, offset);
if (length != string.length()) {
continue;
}
int j = 0;
for (; j != length; ++j) {
offset += 2;
if (string.charAt(j) != getShort(m_strings, offset)) {
break;
}
}
if (j == length) {
return i;
}
}
return -1;
}
private StringBlock() {
}
/**
* Returns style information - array of int triplets, where in each triplet:
* * first int is index of tag name ('b','i', etc.) * second int is tag
* start index in string * third int is tag end index in string
*/
private int[] getStyle(int index) {
if (m_styleOffsets == null || m_styles == null|| index >= m_styleOffsets.length) {
return null;
}
int offset = m_styleOffsets[index] / 4;
int style[];
{
int count = 0;
for (int i = offset; i < m_styles.length; ++i) {
if (m_styles[i] == -1) {
break;
}
count += 1;
}
if (count == 0 || (count % 3) != 0) {
return null;
}
style = new int[count];
}
for (int i = offset, j = 0; i < m_styles.length;) {
if (m_styles[i] == -1) {
break;
}
style[j++] = m_styles[i++];
}
return style;
}
private String decodeString(int offset, int length) {
try {
return (m_isUTF8 ? UTF8_DECODER : UTF16LE_DECODER).decode(
ByteBuffer.wrap(m_strings, offset, length)).toString();
} catch (CharacterCodingException ex) {
LOGGER.log(Level.WARNING, null, ex);
return null;
}
}
private static final int getShort(byte[] array, int offset) {
return (array[offset + 1] & 0xff) << 8 | array[offset] & 0xff;
}
private static final int getShort(int[] array, int offset) {
int value = array[offset / 4];
if ((offset % 4) / 2 == 0) {
return (value & 0xFFFF);
} else {
return (value >>> 16);
}
}
private static final int[] getUtf8(byte[] array, int offset) {
int val = array[offset];
int length;
// We skip the utf16 length of the string
if ((val & 0x80) != 0) {
offset += 2;
} else {
offset += 1;
}
// And we read only the utf-8 encoded length of the string
val = array[offset];
offset += 1;
if ((val & 0x80) != 0) {
int low = (array[offset] & 0xFF);
length = ((val & 0x7F) << 8) + low;
offset += 1;
} else {
length = val;
}
return new int[] { offset, length};
}
private static final int[] getUtf16(byte[] array, int offset) {
int val = ((array[offset + 1] & 0xFF) << 8 | array[offset] & 0xFF);
if ((val & 0x8000) != 0) {
int high = (array[offset + 3] & 0xFF) << 8;
int low = (array[offset + 2] & 0xFF);
int len_value = ((val & 0x7FFF) << 16) + (high + low);
return new int[] {4, len_value * 2};
}
return new int[] {2, val * 2};
}
private int[] m_stringOffsets;
private byte[] m_strings;
private int[] m_styleOffsets;
private int[] m_styles;
private boolean m_isUTF8;
private int[] m_stringOwns;
private final CharsetDecoder UTF16LE_DECODER = Charset.forName("UTF-16LE").newDecoder();
private final CharsetDecoder UTF8_DECODER = Charset.forName("UTF-8").newDecoder();
private static final Logger LOGGER = Logger.getLogger(StringBlock.class.getName());
// ResChunk_header = header.type (0x0001) + header.headerSize (0x001C)
private static final int CHUNK_STRINGPOOL_TYPE = 0x001C0001;
private static final int CHUNK_NULL_TYPE = 0x00000000;
private static final int UTF8_FLAG = 0x00000100;
}
| apache-2.0 |
googleapis/java-talent | proto-google-cloud-talent-v4/src/main/java/com/google/cloud/talent/v4/DeviceInfoOrBuilder.java | 1969 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/talent/v4/common.proto
package com.google.cloud.talent.v4;
public interface DeviceInfoOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.talent.v4.DeviceInfo)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Type of the device.
* </pre>
*
* <code>.google.cloud.talent.v4.DeviceInfo.DeviceType device_type = 1;</code>
*
* @return The enum numeric value on the wire for deviceType.
*/
int getDeviceTypeValue();
/**
*
*
* <pre>
* Type of the device.
* </pre>
*
* <code>.google.cloud.talent.v4.DeviceInfo.DeviceType device_type = 1;</code>
*
* @return The deviceType.
*/
com.google.cloud.talent.v4.DeviceInfo.DeviceType getDeviceType();
/**
*
*
* <pre>
* A device-specific ID. The ID must be a unique identifier that
* distinguishes the device from other devices.
* </pre>
*
* <code>string id = 2;</code>
*
* @return The id.
*/
java.lang.String getId();
/**
*
*
* <pre>
* A device-specific ID. The ID must be a unique identifier that
* distinguishes the device from other devices.
* </pre>
*
* <code>string id = 2;</code>
*
* @return The bytes for id.
*/
com.google.protobuf.ByteString getIdBytes();
}
| apache-2.0 |
alorchenkov/spring-data-openjpa-example | ws-simulator-core/src/main/java/com/cpwr/gdo/simulator/web/security/secure/SecurePage.java | 367 | package com.cpwr.gdo.simulator.web.security.secure;
import com.cpwr.gdo.simulator.web.page.BorderPage;
/**
* Provides a Spring Security (ACEGI) path protected secure page class.
*/
public class SecurePage extends BorderPage {
private static final long serialVersionUID = 1L;
@Override
public String getHelpPageLink() {
return null;
}
}
| apache-2.0 |
obidea/semantika | src/main/java/com/obidea/semantika/database/datatype/AbstractBooleanType.java | 951 | /*
* Copyright (c) 2013-2015 Josef Hardi <josef.hardi@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.obidea.semantika.database.datatype;
public abstract class AbstractBooleanType extends AbstractSqlType<Boolean>
{
protected AbstractBooleanType(String name)
{
super(name);
}
@Override
public Boolean getValue(String lexicalForm)
{
return Boolean.parseBoolean(lexicalForm);
}
}
| apache-2.0 |
mgiaccone/restelio | restelio-sample/restelio-sample-core/src/main/java/restelio/sample/core/SampleFactory.java | 742 | /*
* Copyright 2014 Matteo Giaccone and 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 restelio.sample.core;
import restelio.annotation.RestelioFactory;
@RestelioFactory
public class SampleFactory {
}
| apache-2.0 |
mhurne/aws-sdk-java | aws-java-sdk-machinelearning/src/main/java/com/amazonaws/services/machinelearning/model/transform/UpdateDataSourceRequestMarshaller.java | 3256 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.machinelearning.model.transform;
import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.machinelearning.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* UpdateDataSourceRequest Marshaller
*/
public class UpdateDataSourceRequestMarshaller implements
Marshaller<Request<UpdateDataSourceRequest>, UpdateDataSourceRequest> {
public Request<UpdateDataSourceRequest> marshall(
UpdateDataSourceRequest updateDataSourceRequest) {
if (updateDataSourceRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<UpdateDataSourceRequest> request = new DefaultRequest<UpdateDataSourceRequest>(
updateDataSourceRequest, "AmazonMachineLearning");
request.addHeader("X-Amz-Target", "AmazonML_20141212.UpdateDataSource");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
final StructuredJsonGenerator jsonGenerator = SdkJsonProtocolFactory
.createWriter(false, "1.1");
jsonGenerator.writeStartObject();
if (updateDataSourceRequest.getDataSourceId() != null) {
jsonGenerator.writeFieldName("DataSourceId").writeValue(
updateDataSourceRequest.getDataSourceId());
}
if (updateDataSourceRequest.getDataSourceName() != null) {
jsonGenerator.writeFieldName("DataSourceName").writeValue(
updateDataSourceRequest.getDataSourceName());
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length",
Integer.toString(content.length));
request.addHeader("Content-Type", jsonGenerator.getContentType());
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
| apache-2.0 |
CoepPortal/PortalApp | app/src/main/java/com/aceshub/portal/student/today/TodayListItem.java | 597 | package com.aceshub.portal.student.today;
public class TodayListItem {
private String subjectCode;
private String subjectName;
private Integer attendPerc;
public Integer getAttendPerc() {
return attendPerc;
}
public String getSubjectCode() {
return subjectCode;
}
public TodayListItem(String subjectCode, String subjectName, Integer attendPerc) {
this.subjectCode = subjectCode;
this.subjectName = subjectName;
this.attendPerc=attendPerc;
}
public String getSubjectName() {
return subjectName;
}
}
| apache-2.0 |
NessComputing/migratory | migratory-core/src/main/java/com/nesscomputing/migratory/MigratoryDBIConfig.java | 1400 | /**
* 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.migratory;
import org.skife.config.Config;
import org.skife.config.Default;
import org.skife.config.DefaultNull;
public abstract class MigratoryDBIConfig
{
@Config("${_migratory}driver")
@DefaultNull
public String getDBDriverClass()
{
return null;
}
@Config("${_migratory}url")
@DefaultNull
public String getDBUrl()
{
return null;
}
@Config("${_migratory}user")
@DefaultNull
public String getDBUser()
{
return null;
}
@Config("${_migratory}password")
@DefaultNull
public String getDBPassword()
{
return null;
}
@Config("${_migratory}reveal_password")
@Default("false")
public Boolean isRevealPassword()
{
return false;
}
}
| apache-2.0 |