gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
package me.lucko.luckperms.standalone.view.scene;
import java.io.File;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXTextField;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import me.lucko.luckperms.DatabaseType;
import me.lucko.luckperms.api.data.Callback;
import me.lucko.luckperms.standalone.controller.LoginController;
import me.lucko.luckperms.standalone.model.StorageOptions;
import me.lucko.luckperms.standalone.view.elements.RaisedButton;
public class Login extends VBox {
private LoginController controller;
private DatabaseForm form;
public Login(LoginController controller) {
super(8);
setAlignment(Pos.TOP_CENTER);
this.controller = controller;
setup();
}
private void setup() {
GridPane grid = new GridPane();
grid.setPadding(new Insets(8));
HBox row = new HBox(8);
row.setAlignment(Pos.CENTER);
Label databaseTypeLabel = new Label("Database type");
ComboBox<DatabaseType> databaseTypeField = new JFXComboBox<>();
databaseTypeField.getItems().addAll(DatabaseType.values());
row.getChildren().addAll(databaseTypeLabel, databaseTypeField);
Button loginButton = new RaisedButton("Login");
loginButton.setOnAction((ActionEvent click) -> {
StorageOptions options = form.onConfirm();
controller.startupManageView(options);
});
databaseTypeField.valueProperty().addListener(change -> {
DatabaseType selected = databaseTypeField.getValue();
if (selected == null) {
return;
}
changeForm(selected, grid);
});
databaseTypeField.valueProperty().setValue(databaseTypeField.getItems().get(0));
getChildren().addAll(row, grid, loginButton);
}
private void changeForm(DatabaseType type, GridPane grid) {
grid.getChildren().clear();
switch (type) {
case MYSQL:
form = new MySQLForm();
break;
case SQLITE:
form = new SQLiteForm();
break;
case H2:
form = new H2Form();
break;
case JSON:
form = new JSONForm();
break;
case YAML:
form = new YAMLForm();
break;
case MONGODB:
form = new MongoDBForm();
break;
}
form.build(grid);
}
public interface DatabaseForm {
void build(GridPane pane);
StorageOptions onConfirm();
}
public class MySQLForm extends LoginForm {
@Override
public DatabaseType getType() {
return DatabaseType.MYSQL;
}
}
public class SQLiteForm extends FileForm {
@Override
public DatabaseType getType() {
return DatabaseType.SQLITE;
}
}
public class H2Form extends FileForm {
@Override
public DatabaseType getType() {
return DatabaseType.H2;
}
}
public class JSONForm extends FileForm {
@Override
public DatabaseType getType() {
return DatabaseType.JSON;
}
}
public class YAMLForm extends FileForm {
@Override
public DatabaseType getType() {
return DatabaseType.YAML;
}
}
public class MongoDBForm extends LoginForm {
@Override
public DatabaseType getType() {
return DatabaseType.MONGODB;
}
}
public abstract class FileForm implements DatabaseForm {
private File file;
private TextField fileLocation;
@Override
public void build(GridPane pane) {
int row = 0;
Label fileLocationLabel = new Label("Location");
fileLocation = new JFXTextField();
fileLocation.setPromptText("path/to/file");
GridPane.setConstraints(fileLocationLabel, 1, ++row);
GridPane.setConstraints(fileLocation, 2, row);
Button buttonBrowse = new RaisedButton("Browse...");
buttonBrowse.setOnMouseClicked(click -> {
chooseFile(newFile -> fileLocation.setText(newFile.getAbsolutePath()));
});
GridPane.setConstraints(buttonBrowse, 1, ++row, 2, 1);
pane.getChildren().addAll(fileLocationLabel, fileLocation, buttonBrowse);
}
@Override
public StorageOptions onConfirm() {
return new StorageOptions(getType(), file);
}
private void chooseFile(Callback<File> fileCallback) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Choose database file for type '" + getType().getType() + "'.");
File file = fileChooser.showOpenDialog(Login.this.getScene().getWindow());
if (file != null) {
this.file = file;
fileCallback.onComplete(file);
}
}
public abstract DatabaseType getType();
}
public abstract class LoginForm implements DatabaseForm {
private TextField databaseHostField;
private TextField databasePortField;
private TextField databaseField;
private TextField usernameField;
private TextField passwordField;
@Override
public void build(GridPane pane) {
int row = 0;
Label databaseHostLabel = new Label("Host");
databaseHostField = new JFXTextField();
databaseHostField.setPromptText("example.com");
GridPane.setConstraints(databaseHostLabel, 1, ++row);
GridPane.setConstraints(databaseHostField, 2, row);
Label databasePortLabel = new Label("Port");
databasePortField = new JFXTextField();
databasePortField.setPromptText("3306");
GridPane.setConstraints(databasePortLabel, 1, ++row);
GridPane.setConstraints(databasePortField, 2, row);
Label databaseLabel = new Label("Database");
databaseField = new JFXTextField();
GridPane.setConstraints(databaseLabel, 1, ++row);
GridPane.setConstraints(databaseField, 2, row);
Label usernameLabel = new Label("Username");
usernameField = new JFXTextField();
usernameField.setPromptText("My Awesome Username");
GridPane.setConstraints(usernameLabel, 1, ++row);
GridPane.setConstraints(usernameField, 2, row);
Label passwordLabel = new Label("Password");
passwordField = new JFXPasswordField();
passwordField.setPromptText("My Secret Password");
GridPane.setConstraints(passwordLabel, 1, ++row);
GridPane.setConstraints(passwordField, 2, row);
pane.getChildren().addAll(databaseHostLabel, databaseHostField, databasePortLabel, databasePortField,
databaseLabel, databaseField, usernameLabel, usernameField, passwordLabel, passwordField);
}
@Override
public StorageOptions onConfirm() {
return new StorageOptions(getType(), databaseHostField.getText() + ":" + databasePortField.getText(),
databaseField.getText(), usernameField.getText(), passwordField.getText());
}
public abstract DatabaseType getType();
}
}
| |
/**
* Copyright 2005-2013 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.krad.impls;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.joda.time.DateTime;
import org.kuali.rice.core.api.uif.RemotableAttributeErrorContract;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.action.ActionRequest;
import org.kuali.rice.kew.api.action.ActionRequestType;
import org.kuali.rice.kew.api.action.ActionTaken;
import org.kuali.rice.kew.api.action.ActionType;
import org.kuali.rice.kew.api.action.AdHocRevoke;
import org.kuali.rice.kew.api.action.MovePoint;
import org.kuali.rice.kew.api.action.RequestedActions;
import org.kuali.rice.kew.api.action.ReturnPoint;
import org.kuali.rice.kew.api.action.ValidActions;
import org.kuali.rice.kew.api.document.Document;
import org.kuali.rice.kew.api.document.DocumentContent;
import org.kuali.rice.kew.api.document.DocumentContentUpdate;
import org.kuali.rice.kew.api.document.DocumentDetail;
import org.kuali.rice.kew.api.document.DocumentStatus;
import org.kuali.rice.kew.api.document.attribute.WorkflowAttributeDefinition;
import org.kuali.rice.kew.api.document.node.RouteNodeInstance;
/**
* MockWorkflowDocument is the base class for a MockWorkflowDocument
*
* <p>It can be extended by any other kind of
* mock document that needs to override certain methods. This class has absolutely no state or
* behavior. There is no public constructor, and no member variables. All void methods do nothing.
* All methods with a return value return null. All state and behavior needs to be added via a
* subclass.</p>
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
public abstract class MockWorkflowDocument implements WorkflowDocument {
@Override
public DateTime getDateLastModified() {
return null;
}
@Override
public DateTime getDateApproved() {
return null;
}
@Override
public DateTime getDateFinalized() {
return null;
}
@Override
public String getInitiatorPrincipalId() {
return null;
}
@Override
public String getRoutedByPrincipalId() {
return null;
}
@Override
public String getDocumentTypeId() {
return null;
}
@Override
public String getDocumentHandlerUrl() {
return null;
}
@Override
public String getApplicationDocumentStatus() {
return null;
}
@Override
public DateTime getApplicationDocumentStatusDate() {
return null;
}
@Override
public Map<String, String> getVariables() {
return null;
}
@Override
public String getDocumentId() {
return null;
}
@Override
public Document getDocument() {
return null;
}
@Override
public DocumentContent getDocumentContent() {
return null;
}
@Override
public String getApplicationContent() {
return null;
}
@Override
public void setApplicationContent(String applicationContent) {}
@Override
public void clearAttributeContent() {}
@Override
public String getAttributeContent() {
return null;
}
@Override
public void addAttributeDefinition(WorkflowAttributeDefinition attributeDefinition) {}
@Override
public void removeAttributeDefinition(WorkflowAttributeDefinition attributeDefinition) {}
@Override
public void clearAttributeDefinitions() {}
@Override
public List<WorkflowAttributeDefinition> getAttributeDefinitions() {
return null;
}
@Override
public void addSearchableDefinition(WorkflowAttributeDefinition searchableDefinition) {}
@Override
public void removeSearchableDefinition(WorkflowAttributeDefinition searchableDefinition) {}
@Override
public void clearSearchableDefinitions() {}
@Override
public void clearSearchableContent() {}
@Override
public List<WorkflowAttributeDefinition> getSearchableDefinitions() {
return null;
}
@Override
public List<? extends RemotableAttributeErrorContract> validateAttributeDefinition(
WorkflowAttributeDefinition attributeDefinition) {
return null;
}
@Override
public List<ActionRequest> getRootActionRequests() {
return null;
}
@Override
public List<ActionTaken> getActionsTaken() {
return null;
}
@Override
public void setApplicationDocumentId(String applicationDocumentId) {}
@Override
public String getApplicationDocumentId() {
return null;
}
@Override
public DateTime getDateCreated() {
return null;
}
@Override
public String getTitle() {
return null;
}
@Override
public ValidActions getValidActions() {
return null;
}
@Override
public RequestedActions getRequestedActions() {
return null;
}
@Override
public void saveDocument(String annotation) {}
@Override
public void route(String annotation) {}
@Override
public void disapprove(String annotation) {}
@Override
public void approve(String annotation) {}
@Override
public void cancel(String annotation) {}
@Override
public void recall(String annotation, boolean cancel) {}
@Override
public void blanketApprove(String annotation) {}
@Override
public void blanketApprove(String annotation, String... nodeNames) {}
@Override
public void saveDocumentData() {}
@Override
public void setApplicationDocumentStatus(String applicationDocumentStatus) {}
@Override
public void acknowledge(String annotation) {}
@Override
public void fyi(String annotation) {}
@Override
public void fyi() {}
@Override
public void delete() {}
@Override
public void refresh() {}
@Override
public void adHocToPrincipal(ActionRequestType actionRequested, String annotation, String targetPrincipalId,
String responsibilityDescription, boolean forceAction) {}
@Override
public void adHocToPrincipal(ActionRequestType actionRequested, String nodeName, String annotation,
String targetPrincipalId, String responsibilityDescription, boolean forceAction) {}
@Override
public void adHocToPrincipal(ActionRequestType actionRequested, String nodeName, String annotation,
String targetPrincipalId, String responsibilityDescription, boolean forceAction, String requestLabel) {}
@Override
public void adHocToGroup(ActionRequestType actionRequested, String annotation, String targetGroupId,
String responsibilityDescription, boolean forceAction) {}
@Override
public void adHocToGroup(ActionRequestType actionRequested, String nodeName, String annotation,
String targetGroupId, String responsibilityDescription, boolean forceAction) {
}
@Override
public void adHocToGroup(ActionRequestType actionRequested, String nodeName, String annotation,
String targetGroupId, String responsibilityDescription, boolean forceAction, String requestLabel) {}
@Override
public void revokeAdHocRequestById(String actionRequestId, String annotation) {}
@Override
public void revokeAdHocRequests(AdHocRevoke revoke, String annotation) {}
@Override
public void revokeAllAdHocRequests(String annotation) {}
@Override
public void setTitle(String title) {}
@Override
public String getDocumentTypeName() {
return null;
}
@Override
public boolean isCompletionRequested() {
return false;
}
@Override
public boolean isApprovalRequested() {
return false;
}
@Override
public boolean isAcknowledgeRequested() {
return false;
}
@Override
public boolean isFYIRequested() {
return false;
}
@Override
public boolean isBlanketApproveCapable() {
return false;
}
@Override
public boolean isRouteCapable() {
return false;
}
@Override
public boolean isValidAction(ActionType actionType) {
return false;
}
@Override
public void superUserBlanketApprove(String annotation) {}
@Override
public void superUserNodeApprove(String nodeName, String annotation) {}
@Override
public void superUserTakeRequestedAction(String actionRequestId, String annotation) {}
@Override
public void superUserDisapprove(String annotation) {}
@Override
public void superUserCancel(String annotation) {}
@Override
public void superUserReturnToPreviousNode(ReturnPoint returnPoint, String annotation) {}
@Override
public void complete(String annotation) {}
@Override
public void logAnnotation(String annotation) {}
@Override
public DocumentStatus getStatus() {
return null;
}
@Override
public boolean checkStatus(DocumentStatus status) {
return false;
}
@Override
public boolean isInitiated() {
return false;
}
@Override
public boolean isSaved() {
return false;
}
@Override
public boolean isEnroute() {
return false;
}
@Override
public boolean isException() {
return false;
}
@Override
public boolean isCanceled() {
return false;
}
@Override
public boolean isRecalled() {
return false;
}
@Override
public boolean isDisapproved() {
return false;
}
@Override
public boolean isApproved() {
return false;
}
@Override
public boolean isProcessed() {
return false;
}
@Override
public boolean isFinal() {
return false;
}
@Override
public String getPrincipalId() {
return null;
}
@Override
public void switchPrincipal(String principalId) {}
@Override
public void takeGroupAuthority(String annotation, String groupId) {}
@Override
public void releaseGroupAuthority(String annotation, String groupId) {}
@Override
public Set<String> getNodeNames() {
return null;
}
@Override
public void returnToPreviousNode(String nodeName, String annotation) {}
@Override
public void returnToPreviousNode(String annotation, ReturnPoint returnPoint) {}
@Override
public void move(MovePoint movePoint, String annotation) {}
@Override
public List<RouteNodeInstance> getActiveRouteNodeInstances() {
return null;
}
@Override
public List<RouteNodeInstance> getRouteNodeInstances() {
return null;
}
@Override
public List<String> getPreviousNodeNames() {
return null;
}
@Override
public DocumentDetail getDocumentDetail() {
return null;
}
@Override
public void updateDocumentContent(DocumentContentUpdate documentContentUpdate) {}
@Override
public void placeInExceptionRouting(String annotation) {}
@Override
public void setVariable(String name, String value) {}
@Override
public String getVariableValue(String name) {
return null;
}
@Override
public void setReceiveFutureRequests() {}
@Override
public void setDoNotReceiveFutureRequests() {}
@Override
public void setClearFutureRequests() {}
@Override
public String getReceiveFutureRequestsValue() {
return null;
}
@Override
public String getDoNotReceiveFutureRequestsValue() {
return null;
}
@Override
public String getClearFutureRequestsValue() {
return null;
}
}
| |
/*
* 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.oak.segment;
import static com.google.common.collect.Lists.newArrayList;
import static org.apache.jackrabbit.oak.plugins.memory.MultiBinaryPropertyState.binaryPropertyFromBlob;
import static org.apache.jackrabbit.oak.segment.DefaultSegmentWriterBuilder.defaultSegmentWriterBuilder;
import static org.apache.jackrabbit.oak.segment.file.FileStoreBuilder.fileStoreBuilder;
import static org.apache.jackrabbit.oak.segment.file.tar.GCGeneration.newGCGeneration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Random;
import org.apache.jackrabbit.oak.api.Blob;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.segment.file.FileStore;
import org.apache.jackrabbit.oak.segment.file.GCNodeWriteMonitor;
import org.apache.jackrabbit.oak.segment.file.InvalidFileStoreVersionException;
import org.apache.jackrabbit.oak.segment.file.cancel.Canceller;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class CompactorTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder(new File("target"));
private FileStore fileStore;
private SegmentNodeStore nodeStore;
@Before
public void setup() throws IOException, InvalidFileStoreVersionException {
fileStore = fileStoreBuilder(folder.getRoot()).build();
nodeStore = SegmentNodeStoreBuilders.builder(fileStore).build();
}
@After
public void tearDown() {
fileStore.close();
}
@Test
public void testCompact() throws Exception {
Compactor compactor = createCompactor(fileStore, null);
addTestContent(nodeStore);
SegmentNodeState uncompacted = (SegmentNodeState) nodeStore.getRoot();
SegmentNodeState compacted = compactor.compact(uncompacted, Canceller.newCanceller());
assertNotNull(compacted);
assertFalse(uncompacted == compacted);
assertEquals(uncompacted, compacted);
assertEquals(uncompacted.getSegment().getGcGeneration().nextFull(), compacted.getSegment().getGcGeneration());
modifyTestContent(nodeStore);
NodeState modified = nodeStore.getRoot();
compacted = compactor.compact(uncompacted, modified, compacted, Canceller.newCanceller());
assertNotNull(compacted);
assertFalse(modified == compacted);
assertEquals(modified, compacted);
assertEquals(uncompacted.getSegment().getGcGeneration().nextFull(), compacted.getSegment().getGcGeneration());
}
@Test
public void testExceedUpdateLimit() throws Exception {
Compactor compactor = createCompactor(fileStore, null);
addNodes(nodeStore, Compactor.UPDATE_LIMIT * 2 + 1);
SegmentNodeState uncompacted = (SegmentNodeState) nodeStore.getRoot();
SegmentNodeState compacted = compactor.compact(uncompacted, Canceller.newCanceller());
assertNotNull(compacted);
assertFalse(uncompacted == compacted);
assertEquals(uncompacted, compacted);
assertEquals(uncompacted.getSegment().getGcGeneration().nextFull(), compacted.getSegment().getGcGeneration());
}
@Test
public void testCancel() throws IOException, CommitFailedException {
Compactor compactor = createCompactor(fileStore, null);
addTestContent(nodeStore);
NodeBuilder builder = nodeStore.getRoot().builder();
builder.setChildNode("cancel").setProperty("cancel", "cancel");
nodeStore.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
assertNull(compactor.compact(nodeStore.getRoot(), Canceller.newCanceller().withCondition("reason", () -> true)));
}
@Test(expected = IOException.class)
public void testIOException() throws IOException, CommitFailedException {
Compactor compactor = createCompactor(fileStore, "IOException");
addTestContent(nodeStore);
compactor.compact(nodeStore.getRoot(), Canceller.newCanceller());
}
@NotNull
private static Compactor createCompactor(FileStore fileStore, String failOnName) {
SegmentWriter writer = defaultSegmentWriterBuilder("c")
.withGeneration(newGCGeneration(1, 1, true))
.build(fileStore);
if (failOnName != null) {
writer = new FailingSegmentWriter(writer, failOnName);
}
return new Compactor(fileStore.getReader(), writer, fileStore.getBlobStore(), GCNodeWriteMonitor.EMPTY);
}
private static void addNodes(SegmentNodeStore nodeStore, int count)
throws CommitFailedException {
NodeBuilder builder = nodeStore.getRoot().builder();
for (int k = 0; k < count; k++) {
builder.setChildNode("n-" + k);
}
nodeStore.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
}
private static void addTestContent(NodeStore nodeStore) throws CommitFailedException, IOException {
NodeBuilder builder = nodeStore.getRoot().builder();
builder.setChildNode("a").setChildNode("aa").setProperty("p", 42);
builder.getChildNode("a").setChildNode("error").setChildNode("IOException");
builder.setChildNode("b").setProperty("bin", createBlob(nodeStore, 42));
builder.setChildNode("c").setProperty(binaryPropertyFromBlob("bins", createBlobs(nodeStore, 42, 43, 44)));
nodeStore.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
}
private static void modifyTestContent(NodeStore nodeStore) throws CommitFailedException {
NodeBuilder builder = nodeStore.getRoot().builder();
builder.getChildNode("a").getChildNode("aa").remove();
builder.getChildNode("b").setProperty("bin", "changed");
builder.getChildNode("c").removeProperty("bins");
nodeStore.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
}
private static Blob createBlob(NodeStore nodeStore, int size) throws IOException {
byte[] data = new byte[size];
new Random().nextBytes(data);
return nodeStore.createBlob(new ByteArrayInputStream(data));
}
private static List<Blob> createBlobs(NodeStore nodeStore, int... sizes) throws IOException {
List<Blob> blobs = newArrayList();
for (int size : sizes) {
blobs.add(createBlob(nodeStore, size));
}
return blobs;
}
private static class FailingSegmentWriter implements SegmentWriter {
@NotNull
private final SegmentWriter delegate;
@NotNull
private final String failOnName;
public FailingSegmentWriter(@NotNull SegmentWriter delegate, @NotNull String failOnName) {
this.delegate = delegate;
this.failOnName = failOnName;
}
@Override
public void flush() throws IOException {
delegate.flush();
}
@NotNull
@Override
public RecordId writeBlob(@NotNull Blob blob) throws IOException {
return delegate.writeBlob(blob);
}
@NotNull
@Override
public RecordId writeStream(@NotNull InputStream stream) throws IOException {
return delegate.writeStream(stream);
}
@NotNull
@Override
public RecordId writeNode(@NotNull NodeState state, @Nullable ByteBuffer stableIdBytes)
throws IOException {
if (state.hasChildNode(failOnName)) {
throw new IOException("Encountered node with name " + failOnName);
}
return delegate.writeNode(state, stableIdBytes);
}
}
}
| |
/*
* Copyright 2015-2016 DevCon5 GmbH, info@devcon5.ch
*
* 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.inkstand.scribble.inject;
import static org.junit.Assert.*;
import javax.inject.Inject;
import java.lang.reflect.Field;
import org.apache.deltaspike.core.api.config.ConfigProperty;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ConfigPropertyInjectionTest {
private ConfigPropertyInjection subject;
@Before
public void setUp() throws Exception {
subject = new ConfigPropertyInjection("config.property", "testValue");
}
@After
public void tearDown() throws Exception {
}
@Test
public void testInjectInto_NullValue_AutoConverted_primitiveTypes_defaultInjected() throws Exception {
//prepare
String var = null;
test_autoConversionDefaultValue_into("booleanProperty");
test_autoConversionDefaultValue_into("charProperty");
test_autoConversionDefaultValue_into("byteProperty");
test_autoConversionDefaultValue_into("shortProperty");
test_autoConversionDefaultValue_into("intProperty");
test_autoConversionDefaultValue_into("longProperty");
test_autoConversionDefaultValue_into("floatProperty");
test_autoConversionDefaultValue_into("doubleProperty");
}
private void test_autoConversionDefaultValue_into(String fieldName)
throws NoSuchFieldException, IllegalAccessException {
//prepare
Object injectedValue = null;
final ConfigPropertyInjection injection = new ConfigPropertyInjection(fieldName, injectedValue);
final AutoConversionInjectionTarget target = new AutoConversionInjectionTarget();
//act
injection.into(target);
//assert
final Field field = AutoConversionInjectionTarget.class.getDeclaredField(fieldName);
String defaultValue = field.getAnnotation(ConfigProperty.class).defaultValue();
assertEquals(TypeUtil.convert(defaultValue, field.getType()), field.get(target));
}
@Test
public void testInjectInto_NullValue_AutoConverted_objectTypes_defaultInjected() throws Exception {
//prepare
String var = null;
test_autoConversionDefaultValue_into("BooleanProperty");
test_autoConversionDefaultValue_into("CharacterProperty");
test_autoConversionDefaultValue_into("ByteProperty");
test_autoConversionDefaultValue_into("ShortProperty");
test_autoConversionDefaultValue_into("IntegerProperty");
test_autoConversionDefaultValue_into("LongProperty");
test_autoConversionDefaultValue_into("FloatProperty");
test_autoConversionDefaultValue_into("DoubleProperty");
}
@Test
public void testInjectInto_StringValue_AutoConverted_primitiveTypes_valueInjected() throws Exception {
//prepare
String var = "123";
//act
test_autoConversion_into("booleanProperty", "true");
test_autoConversion_into("charProperty", "c");
test_autoConversion_into("byteProperty", var);
test_autoConversion_into("shortProperty", var);
test_autoConversion_into("intProperty", var);
test_autoConversion_into("longProperty", var);
test_autoConversion_into("floatProperty", var);
test_autoConversion_into("doubleProperty", var);
}
private void test_autoConversion_into(String fieldName, String value)
throws NoSuchFieldException, IllegalAccessException {
//prepare
final ConfigPropertyInjection injection = new ConfigPropertyInjection(fieldName, value);
final AutoConversionInjectionTarget target = new AutoConversionInjectionTarget();
//act
injection.into(target);
//assert
final Field field = AutoConversionInjectionTarget.class.getDeclaredField(fieldName);
assertEquals(TypeUtil.convert(value, field.getType()), field.get(target));
}
@Test
public void testInjectInto_StringValue_AutoConverted_objectTypes_valueInjected() throws Exception {
//prepare
String var = "123";
//act
test_autoConversion_into("BooleanProperty", "true");
test_autoConversion_into("CharacterProperty", "c");
test_autoConversion_into("ByteProperty", var);
test_autoConversion_into("ShortProperty", var);
test_autoConversion_into("IntegerProperty", var);
test_autoConversion_into("LongProperty", var);
test_autoConversion_into("FloatProperty", var);
test_autoConversion_into("DoubleProperty", var);
}
@Test
public void testGetValue() throws Exception {
assertEquals("testValue", subject.getValue());
}
@Test
public void testGetDefaultValue_defaultValueOfMatchingConfigProperty() throws Exception {
// prepare
// create an injection with no value (null) for a config property with a default value
final ConfigPropertyInjection subject = new ConfigPropertyInjection("config.property.default", null);
assertNull(subject.getValue());
// get the field of the config property that has a default value and matches the injection name
final Field field = SimpleInjectionTarget.class.getDeclaredField("configPropertyWithDefault");
// act
final String value = (String) subject.getDefaultValue(field);
// assert
assertNotNull(value);
assertEquals("defaultValue", value);
}
@Test
public void testIsMatching_configPropertyNameMatch_True() throws Exception {
final Field field = SimpleInjectionTarget.class.getDeclaredField("configProperty");
assertTrue(subject.isMatching(field));
}
@Test
public void testIsMatching_configPropertyNameMismatch_false() throws Exception {
final Field field = SimpleInjectionTarget.class.getDeclaredField("configPropertyWithDefault");
assertFalse(subject.isMatching(field));
}
@Test
public void testIsMatching_configPropertyUndefined_false() throws Exception {
ConfigPropertyInjection subject = new ConfigPropertyInjection("noDefinedProperty", null);
final Field field = SimpleInjectionTarget.class.getDeclaredField("configProperty");
assertFalse(subject.isMatching(field));
}
@Test
public void testIsMatching_noInjectConfigProperty_false() throws Exception {
final Field field = SimpleInjectionTarget.class.getDeclaredField("noInjectConfigProperty");
assertFalse(subject.isMatching(field));
}
@Test
public void testIsMatching_noConfigPropertyAnnotation_false() throws Exception {
final Field field = SimpleInjectionTarget.class.getDeclaredField("noConfigProperty");
assertFalse(subject.isMatching(field));
}
@Test
public void testIsFieldCandidate_noConfigPropertyAnnotation_false() throws Exception {
//prepare
Field field = SimpleInjectionTarget.class.getDeclaredField("noConfigProperty");
//act
boolean result = subject.isFieldCandidate(field, "");
//assert
assertFalse(result);
}
@Test
public void testIsFieldCandidate_injectedValueNull_true() throws Exception {
//prepare
Field field = SimpleInjectionTarget.class.getDeclaredField("configProperty");
//act
boolean result = subject.isFieldCandidate(field, null);
//assert
assertTrue(result);
}
@Test
public void testIsFieldCandidate_matchingField_true() throws Exception {
//prepare
Field field = SimpleInjectionTarget.class.getDeclaredField("configProperty");
//act
boolean result = subject.isFieldCandidate(field, "");
//assert
assertTrue(result);
}
@Test
public void testIsFieldCandidate_notMatchingField_false() throws Exception {
//prepare
Field field = SimpleInjectionTarget.class.getDeclaredField("configProperty");
//act
boolean result = subject.isFieldCandidate(field, new Object());
//assert
assertFalse(result);
}
@Test
public void testIsFieldCandidate_autoConvertible_true() throws Exception {
//prepare
Field field = SimpleInjectionTarget.class.getDeclaredField("autoConvertibleField");
//act
boolean result = subject.isFieldCandidate(field, "123");
//assert
assertTrue(result);
}
static class SimpleInjectionTarget {
@ConfigProperty(name = "config.property")
String noInjectConfigProperty;
@Inject
@ConfigProperty(name = "config.property")
String configProperty;
@Inject
@ConfigProperty(name = "config.property.default",
defaultValue = "defaultValue")
String configPropertyWithDefault;
@Inject
String noConfigProperty;
@Inject
@ConfigProperty(name = "config.property")
int autoConvertibleField;
@Inject
@ConfigProperty(name = "config.property")
Object nonMatchingNonAutoConvertible;
}
static class AutoConversionInjectionTarget {
@Inject
@ConfigProperty(name = "booleanProperty",
defaultValue = "true")
boolean booleanProperty;
@Inject
@ConfigProperty(name = "charProperty",
defaultValue = "a")
boolean charProperty;
@Inject
@ConfigProperty(name = "byteProperty",
defaultValue = "123")
byte byteProperty;
@Inject
@ConfigProperty(name = "shortProperty",
defaultValue = "123")
short shortProperty;
@Inject
@ConfigProperty(name = "intProperty",
defaultValue = "123")
int intProperty;
@Inject
@ConfigProperty(name = "longProperty",
defaultValue = "123")
long longProperty;
@Inject
@ConfigProperty(name = "floatProperty",
defaultValue = "123")
float floatProperty;
@Inject
@ConfigProperty(name = "doubleProperty",
defaultValue = "123")
double doubleProperty;
@Inject
@ConfigProperty(name = "BooleanProperty",
defaultValue = "true")
Boolean BooleanProperty;
@Inject
@ConfigProperty(name = "CharacterProperty",
defaultValue = "a")
Character CharacterProperty;
@Inject
@ConfigProperty(name = "ByteProperty",
defaultValue = "123")
Byte ByteProperty;
@Inject
@ConfigProperty(name = "ShortProperty",
defaultValue = "123")
Short ShortProperty;
@Inject
@ConfigProperty(name = "IntegerProperty",
defaultValue = "123")
Integer IntegerProperty;
@Inject
@ConfigProperty(name = "LongProperty",
defaultValue = "123")
Long LongProperty;
@Inject
@ConfigProperty(name = "FloatProperty",
defaultValue = "123")
Float FloatProperty;
@Inject
@ConfigProperty(name = "DoubleProperty",
defaultValue = "123")
Double DoubleProperty;
}
}
| |
package com.rajendarreddyj.basics.xml;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Logger;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import com.rajendarreddyj.basics.enums.TokenType;
/**
* EvalXML
*
*
* Support for evaluating expressions in XML form.
* <p>
* A validated DOM Object is built for the XML expression. The recursive methods in this class walk over the DOM tree
* and evaluate the expression.
* </p>
* <p>
* The tree walk reflects the structure of the expression. The expression structure is shown below in BNF like syntax.
* </p>
*
* <pre>
statement: assignment | addExp
assignment: ident "=" addExp
addExp: term | addExp addOp addExp
term: unaryExpr | term mulOp term
unaryExpr: factor | minus factor
factor: ident | number | "(" addExp ")"
* </pre>
* <p>
* The XML expression is validated by an XML schema (see expression.xsd).
* </p>
* <p>
* Expressions may be evaluated by themselves or assigned to a variable. The class supports a basic symbol table to
* support symbols and their associated values.
* </p>
*
*/
public class EvalXML {
private static final Logger logger = Logger.getAnonymousLogger();
/**
* The symbol table consists of a set of String, Integer pairs, where the String object is the key.
*/
private HashMap<String, Integer> mSymTab = new HashMap<>();
/**
* Parse the XML into a DOM Document
*/
private static Document bytesToDocument(final DOMParser parser, final byte[] xmlBytes) throws SAXException, IOException {
ByteArrayInputStream istream = new ByteArrayInputStream(xmlBytes);
InputSource isource = new InputSource(istream);
parser.parse(isource);
Document xmlDoc = parser.getDocument();
return xmlDoc;
} // bytesToDocument
/**
* A DOM NodeList may include a variety of different node types. This is awkward when it comes to expression
* processing, since most of the time we only care about ELEMENT_NODEs. The toElementNodeList method builds an
* ArrayList that consists only of ELEMENT_NODES.
*
* @param list
* a NodeList of DOM Node objects
*
* @return return a Vector of ELEMENT_TYPE nodes. If there are no element type nodes, the size() of the Vector will
* zero.
*
*/
private ArrayList<Node> toElementNodeList(final NodeList list) {
ArrayList<Node> elemList = new ArrayList<>();
if (list != null) {
int len = list.getLength();
for (int i = 0; i < len; i++) {
if (list.item(i).getNodeType() == Node.ELEMENT_NODE) {
elemList.add(list.item(i));
}
}
}
return elemList;
} // toElementNodeList
/**
* Given a symbol name, look the symbol up in the symbol table.
*
* @return the value of the symbol, or 0 if the symbol is not found.
*/
private int symbolLookup(final String name) {
int symVal = 0;
Integer i = this.mSymTab.get(name);
if (i != null) {
symVal = i.intValue();
} else {
logger.info("No symbol found for " + name);
}
return symVal;
} // symbolLookup
/**
* Enter a symbol and its value into the symbol table
*
* @param name
* symbol name
* @param value
* symbol value
*/
private void symbolEnter(final String name, final int value) {
Integer i = new Integer(value);
this.mSymTab.put(name, i);
} // symbolEnter
/**
* Get the type name associated with the numeric Node type value. This method is called from error messages.
*/
private String nodeTypeToString(final short type) {
String typeName = "Unknow Node type";
if (type == Node.ATTRIBUTE_NODE) {
typeName = "ATTRIBUTE_NODE";
} else if (type == Node.CDATA_SECTION_NODE) {
typeName = "CDATA_SECTION_NODE";
} else if (type == Node.COMMENT_NODE) {
typeName = "COMMENT_NODE";
} else if (type == Node.DOCUMENT_FRAGMENT_NODE) {
typeName = "DOCUMENT_FRAGMENT_NODE";
} else if (type == Node.DOCUMENT_NODE) {
typeName = "DOCUMENT_NODE";
} else if (type == Node.DOCUMENT_TYPE_NODE) {
typeName = "DOCUMENT_TYPE_NODE";
} else if (type == Node.ELEMENT_NODE) {
typeName = "ELEMENT_NODE";
} else if (type == Node.ENTITY_NODE) {
typeName = "ENTITY_NODE";
} else if (type == Node.ENTITY_REFERENCE_NODE) {
typeName = "ENTITY_REFERENCE_NODE";
} else if (type == Node.NOTATION_NODE) {
typeName = "NOTATION_NODE";
} else if (type == Node.PROCESSING_INSTRUCTION_NODE) {
typeName = "PROCESSING_INSTRUCTION_NODE";
} else if (type == Node.TEXT_NODE) {
typeName = "TEXT_NODE ";
}
return typeName;
} // nodeTypeToString
/**
* Evaluate identifiers, numbers or parenthesized expressions (via a recursive call to the addExp method).
*
* <pre>
factor: ident | number | paren addExp
* </pre>
*/
private int factor(final Node root) {
int rslt = 0;
String tagName = root.getLocalName();
if (tagName.equals(TokenType.IDENT.toString()) || tagName.equals(TokenType.INT.toString())) {
NodeList children = root.getChildNodes();
if (children.getLength() == 1) {
Node child = children.item(0);
if (child.getNodeType() == Node.TEXT_NODE) {
Text textNode = (Text) child;
String textData = textNode.getData();
if (tagName.equals(TokenType.IDENT.toString())) {
rslt = this.symbolLookup(textData);
} else {
try {
rslt = Integer.parseInt(textData);
} catch (NumberFormatException e) {
logger.info("factor: bad format for number \"" + textData + "\"");
}
}
} else {
logger.info("factor: unexpected node type = " + this.nodeTypeToString(child.getNodeType()));
}
} else {
logger.info("factor: 1 child expected for " + tagName + ", got " + children.getLength() + " children");
}
} // root is not an IDENT or an INT, so it should be an expression
else if (tagName.equals(TokenType.PAREN.toString())) {
ArrayList<Node> children = this.toElementNodeList(root.getChildNodes());
if (children.size() == 1) {
Node expr = children.get(0);
rslt = this.addExp(expr);
} else {
logger.info("factor: extra children of PAREN");
}
} else {
logger.info("factor: Unexpected tag = " + tagName);
}
return rslt;
} // factor
/**
* Process a factor or a unary minus expression (the silly unary plus is not supported).
*
* <pre>
unaryExp: factor | uminus factor
* </pre>
*/
private int unaryExp(Node root) {
int rslt = 0;
boolean unaryMinus = false;
if (root.getLocalName().equals(TokenType.UMINUS.toString())) {
ArrayList<Node> children = this.toElementNodeList(root.getChildNodes());
if (children.size() == 1) {
unaryMinus = true;
root = children.get(0);
} else {
logger.info("unaryExp: more than one child found for UMINUS");
}
}
rslt = this.factor(root);
if (unaryMinus) {
rslt = -rslt;
}
return rslt;
} // unaryExp
/**
* Process a factor expression
*
* <pre>
term: factor | term mulOp term
* </pre>
*/
private int term(final Node root) {
int rslt = 0;
if (root.getLocalName().equals(TokenType.TIMES.toString()) || root.getLocalName().equals(TokenType.DIV.toString())
|| root.getLocalName().equals(TokenType.MOD.toString())) {
ArrayList<Node> children = this.toElementNodeList(root.getChildNodes());
Node lhs = children.get(0);
Node rhs = children.get(1);
int lhsInt = this.term(lhs);
int rhsInt = this.term(rhs);
if (root.getLocalName().equals(TokenType.TIMES.toString())) {
rslt = lhsInt * rhsInt;
} else if (root.getLocalName().equals(TokenType.DIV.toString())) {
if (rhsInt != 0) { // don't allow divide by zero
rslt = lhsInt / rhsInt;
}
} else { // root.getLocalName().equals( TokenType.MOD )
if (rhsInt != 0) { // don't allow mod by zero
rslt = lhsInt % rhsInt;
}
}
} else {
rslt = this.unaryExp(root);
}
return rslt;
} // term
/**
* <pre>
addExp: term | addExp addOp addExp
* </pre>
*/
private int addExp(final Node root) {
int rslt = 0;
if (root.getLocalName().equals(TokenType.MINUS.toString()) || root.getLocalName().equals(TokenType.PLUS.toString())) {
ArrayList<Node> children = this.toElementNodeList(root.getChildNodes());
Node lhs = children.get(0);
Node rhs = children.get(1);
int lhsInt = this.addExp(lhs);
int rhsInt = this.addExp(rhs);
if (root.getLocalName().equals(TokenType.MINUS.toString())) {
rslt = lhsInt - rhsInt;
} else {
rslt = lhsInt + rhsInt;
}
} else {
rslt = this.term(root);
}
return rslt;
} // addExp
/**
* "Store" a value in a symbol
*/
private void store(final Node lhs, final int value) {
NodeList children = lhs.getChildNodes();
Node child = children.item(0);
if (child.getNodeType() == Node.TEXT_NODE) {
Text textNode = (Text) child;
String symbolName = textNode.getData();
this.symbolEnter(symbolName, value);
}
} // store
/**
* Process and assignment statement or an expression
*
* <pre>
statement: assignment | addExp
* </pre>
*/
private Integer statement(final Node root) {
Integer rslt = null;
Node expr = root;
Node lhs = null;
if (root.getLocalName().equals(TokenType.EQUAL.toString())) {
ArrayList<Node> children = this.toElementNodeList(root.getChildNodes());
int len = children.size();
if (len == 2) {
lhs = children.get(0);
expr = children.get(1);
} else {
logger.info("statement: two children expected, got " + len + " instead");
}
} else {
expr = root;
}
int expRslt = this.addExp(expr);
if (lhs != null) {
this.store(lhs, expRslt);
} else {
rslt = new Integer(expRslt);
}
return rslt;
} // statement
/**
* This function is passed an assignment statement or an expression, formatted in XML. If the argument is an
* assignment statement, the right hand side (RHS) value is assigned to the variable on the left hand side (LHS). In
* the case of an assignment statement the function will return null.
* <p>
* If the argument is an expression the expression will be evaluated. The function will return the result as an
* Integer object.
* </p>
*
*/
public Integer eval(final DOMParser parser, final byte[] xmlBytes) {
Integer result = null;
Document doc = null;
try {
doc = bytesToDocument(parser, xmlBytes);
Node root = doc.getDocumentElement();
if (root.getLocalName().equals("EXPRESSION")) {
ArrayList<Node> children = this.toElementNodeList(root.getChildNodes());
root = children.get(0);
result = this.statement(root);
} else {
logger.info("eval: EXPRESSION XML Document expected");
}
} catch (SAXException e) {
String msg = null;
if (e instanceof SAXParseException) {
int lineNum = ((SAXParseException) e).getLineNumber();
int columnNumber = ((SAXParseException) e).getColumnNumber();
String exceptionMsg = ((SAXParseException) e).getMessage();
msg = "Error: line = " + lineNum + ", column = " + columnNumber + ": " + exceptionMsg;
} else {
msg = "TestXerces.bytesToDocument: SAX Exception = " + e;
}
logger.info(msg);
} catch (IOException e) {
logger.info("TestXerces.bytesToDocument: IOException = " + e);
}
return result;
} // eval
}
| |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.taobao.android.dx.rop.code;
import com.taobao.android.dx.util.Hex;
/**
* All the register-based opcodes, and related utilities.
*
* <p><b>Note:</b> Opcode descriptions use a rough pseudocode. {@code r}
* is the result register, {@code x} is the first argument,
* {@code y} is the second argument, and {@code z} is the
* third argument. The expression which describes
* the operation uses Java-ish syntax but is preceded by type indicators for
* each of the values.
*/
public final class RegOps {
/** {@code nop()} */
public static final int NOP = 1;
/** {@code T: any type; r,x: T :: r = x;} */
public static final int MOVE = 2;
/** {@code T: any type; r,param(x): T :: r = param(x)} */
public static final int MOVE_PARAM = 3;
/**
* {@code T: Throwable; r: T :: r = caught_exception}.
* <b>Note:</b> This opcode should only ever be used in the
* first instruction of a block, and such blocks must be
* the start of an exception handler.
*/
public static final int MOVE_EXCEPTION = 4;
/** {@code T: any type; r, literal: T :: r = literal;} */
public static final int CONST = 5;
/** {@code goto label} */
public static final int GOTO = 6;
/**
* {@code T: int or Object; x,y: T :: if (x == y) goto
* label}
*/
public static final int IF_EQ = 7;
/**
* {@code T: int or Object; x,y: T :: if (x != y) goto
* label}
*/
public static final int IF_NE = 8;
/** {@code x,y: int :: if (x < y) goto label} */
public static final int IF_LT = 9;
/** {@code x,y: int :: if (x >= y) goto label} */
public static final int IF_GE = 10;
/** {@code x,y: int :: if (x <= y) goto label} */
public static final int IF_LE = 11;
/** {@code x,y: int :: if (x > y) goto label} */
public static final int IF_GT = 12;
/** {@code x: int :: goto table[x]} */
public static final int SWITCH = 13;
/** {@code T: any numeric type; r,x,y: T :: r = x + y} */
public static final int ADD = 14;
/** {@code T: any numeric type; r,x,y: T :: r = x - y} */
public static final int SUB = 15;
/** {@code T: any numeric type; r,x,y: T :: r = x * y} */
public static final int MUL = 16;
/** {@code T: any numeric type; r,x,y: T :: r = x / y} */
public static final int DIV = 17;
/**
* {@code T: any numeric type; r,x,y: T :: r = x % y}
* (Java-style remainder)
*/
public static final int REM = 18;
/** {@code T: any numeric type; r,x: T :: r = -x} */
public static final int NEG = 19;
/** {@code T: any integral type; r,x,y: T :: r = x & y} */
public static final int AND = 20;
/** {@code T: any integral type; r,x,y: T :: r = x | y} */
public static final int OR = 21;
/** {@code T: any integral type; r,x,y: T :: r = x ^ y} */
public static final int XOR = 22;
/**
* {@code T: any integral type; r,x: T; y: int :: r = x << y}
*/
public static final int SHL = 23;
/**
* {@code T: any integral type; r,x: T; y: int :: r = x >> y}
* (signed right-shift)
*/
public static final int SHR = 24;
/**
* {@code T: any integral type; r,x: T; y: int :: r = x >>> y}
* (unsigned right-shift)
*/
public static final int USHR = 25;
/** {@code T: any integral type; r,x: T :: r = ~x} */
public static final int NOT = 26;
/**
* {@code T: any numeric type; r: int; x,y: T :: r = (x == y) ? 0
* : (x > y) ? 1 : -1} (Java-style "cmpl" where a NaN is
* considered "less than" all other values; also used for integral
* comparisons)
*/
public static final int CMPL = 27;
/**
* {@code T: any floating point type; r: int; x,y: T :: r = (x == y) ? 0
* : (x < y) ? -1 : 1} (Java-style "cmpg" where a NaN is
* considered "greater than" all other values)
*/
public static final int CMPG = 28;
/**
* {@code T: any numeric type; U: any numeric type; r: T; x: U ::
* r = (T) x} (numeric type conversion between the four
* "real" numeric types)
*/
public static final int CONV = 29;
/**
* {@code r,x: int :: r = (x << 24) >> 24} (Java-style
* convert int to byte)
*/
public static final int TO_BYTE = 30;
/**
* {@code r,x: int :: r = x & 0xffff} (Java-style convert int to char)
*/
public static final int TO_CHAR = 31;
/**
* {@code r,x: int :: r = (x << 16) >> 16} (Java-style
* convert int to short)
*/
public static final int TO_SHORT = 32;
/** {@code T: return type for the method; x: T; return x} */
public static final int RETURN = 33;
/** {@code T: any type; r: int; x: T[]; :: r = x.length} */
public static final int ARRAY_LENGTH = 34;
/** {@code x: Throwable :: throw(x)} */
public static final int THROW = 35;
/** {@code x: Object :: monitorenter(x)} */
public static final int MONITOR_ENTER = 36;
/** {@code x: Object :: monitorexit(x)} */
public static final int MONITOR_EXIT = 37;
/** {@code T: any type; r: T; x: T[]; y: int :: r = x[y]} */
public static final int AGET = 38;
/** {@code T: any type; x: T; y: T[]; z: int :: x[y] = z} */
public static final int APUT = 39;
/**
* {@code T: any non-array object type :: r =
* alloc(T)} (allocate heap space for an object)
*/
public static final int NEW_INSTANCE = 40;
/** {@code T: any array type; r: T; x: int :: r = new T[x]} */
public static final int NEW_ARRAY = 41;
/**
* {@code T: any array type; r: T; x: int; v0..vx: T :: r = new T[x]
* {v0, ..., vx}}
*/
public static final int FILLED_NEW_ARRAY = 42;
/**
* {@code T: any object type; x: Object :: (T) x} (can
* throw {@code ClassCastException})
*/
public static final int CHECK_CAST = 43;
/**
* {@code T: any object type; x: Object :: x instanceof T}
*/
public static final int INSTANCE_OF = 44;
/**
* {@code T: any type; r: T; x: Object; f: instance field spec of
* type T :: r = x.f}
*/
public static final int GET_FIELD = 45;
/**
* {@code T: any type; r: T; f: static field spec of type T :: r =
* f}
*/
public static final int GET_STATIC = 46;
/**
* {@code T: any type; x: T; y: Object; f: instance field spec of type
* T :: y.f = x}
*/
public static final int PUT_FIELD = 47;
/**
* {@code T: any type; f: static field spec of type T; x: T :: f = x}
*/
public static final int PUT_STATIC = 48;
/**
* {@code Tr, T0, T1...: any types; r: Tr; m: static method spec;
* y0: T0; y1: T1 ... :: r = m(y0, y1, ...)} (call static
* method)
*/
public static final int INVOKE_STATIC = 49;
/**
* {@code Tr, T0, T1...: any types; r: Tr; x: Object; m: instance method
* spec; y0: T0; y1: T1 ... :: r = x.m(y0, y1, ...)} (call normal
* virtual method)
*/
public static final int INVOKE_VIRTUAL = 50;
/**
* {@code Tr, T0, T1...: any types; r: Tr; x: Object; m: instance method
* spec; y0: T0; y1: T1 ... :: r = x.m(y0, y1, ...)} (call
* superclass virtual method)
*/
public static final int INVOKE_SUPER = 51;
/**
* {@code Tr, T0, T1...: any types; r: Tr; x: Object; m: instance method
* spec; y0: T0; y1: T1 ... :: r = x.m(y0, y1, ...)} (call
* direct/special method)
*/
public static final int INVOKE_DIRECT = 52;
/**
* {@code Tr, T0, T1...: any types; r: Tr; x: Object; m: interface
* (instance) method spec; y0: T0; y1: T1 ... :: r = x.m(y0, y1,
* ...)} (call interface method)
*/
public static final int INVOKE_INTERFACE = 53;
/**
* {@code T0: any type; name: local variable name :: mark(name,T0)}
* (mark beginning or end of local variable name)
*/
public static final int MARK_LOCAL = 54;
/**
* {@code T: Any type; r: T :: r = return_type}.
* <b>Note:</b> This opcode should only ever be used in the
* first instruction of a block following an invoke-*.
*/
public static final int MOVE_RESULT = 55;
/**
* {@code T: Any type; r: T :: r = return_type}.
* <b>Note:</b> This opcode should only ever be used in the
* first instruction of a block following a non-invoke throwing insn
*/
public static final int MOVE_RESULT_PSEUDO = 56;
/** {@code T: Any primitive type; v0..vx: T :: {v0, ..., vx}} */
public static final int FILL_ARRAY_DATA = 57;
/**
* This class is uninstantiable.
*/
private RegOps() {
// This space intentionally left blank.
}
/**
* Gets the name of the given opcode.
*
* @param opcode the opcode
* @return {@code non-null;} its name
*/
public static String opName(int opcode) {
switch (opcode) {
case NOP: return "nop";
case MOVE: return "move";
case MOVE_PARAM: return "move-param";
case MOVE_EXCEPTION: return "move-exception";
case CONST: return "const";
case GOTO: return "goto";
case IF_EQ: return "if-eq";
case IF_NE: return "if-ne";
case IF_LT: return "if-lt";
case IF_GE: return "if-ge";
case IF_LE: return "if-le";
case IF_GT: return "if-gt";
case SWITCH: return "switch";
case ADD: return "add";
case SUB: return "sub";
case MUL: return "mul";
case DIV: return "div";
case REM: return "rem";
case NEG: return "neg";
case AND: return "and";
case OR: return "or";
case XOR: return "xor";
case SHL: return "shl";
case SHR: return "shr";
case USHR: return "ushr";
case NOT: return "not";
case CMPL: return "cmpl";
case CMPG: return "cmpg";
case CONV: return "conv";
case TO_BYTE: return "to-byte";
case TO_CHAR: return "to-char";
case TO_SHORT: return "to-short";
case RETURN: return "return";
case ARRAY_LENGTH: return "array-length";
case THROW: return "throw";
case MONITOR_ENTER: return "monitor-enter";
case MONITOR_EXIT: return "monitor-exit";
case AGET: return "aget";
case APUT: return "aput";
case NEW_INSTANCE: return "new-instance";
case NEW_ARRAY: return "new-array";
case FILLED_NEW_ARRAY: return "filled-new-array";
case CHECK_CAST: return "check-cast";
case INSTANCE_OF: return "instance-of";
case GET_FIELD: return "get-field";
case GET_STATIC: return "get-static";
case PUT_FIELD: return "put-field";
case PUT_STATIC: return "put-static";
case INVOKE_STATIC: return "invoke-static";
case INVOKE_VIRTUAL: return "invoke-virtual";
case INVOKE_SUPER: return "invoke-super";
case INVOKE_DIRECT: return "invoke-direct";
case INVOKE_INTERFACE: return "invoke-interface";
case MOVE_RESULT: return "move-result";
case MOVE_RESULT_PSEUDO: return "move-result-pseudo";
case FILL_ARRAY_DATA: return "fill-array-data";
}
return "unknown-" + Hex.u1(opcode);
}
/**
* Given an IF_* RegOp, returns the right-to-left flipped version. For
* example, IF_GT becomes IF_LT.
*
* @param opcode An IF_* RegOp
* @return flipped IF Regop
*/
public static int flippedIfOpcode(final int opcode) {
switch (opcode) {
case RegOps.IF_EQ:
case RegOps.IF_NE:
return opcode;
case RegOps.IF_LT:
return RegOps.IF_GT;
case RegOps.IF_GE:
return RegOps.IF_LE;
case RegOps.IF_LE:
return RegOps.IF_GE;
case RegOps.IF_GT:
return RegOps.IF_LT;
default:
throw new RuntimeException("Unrecognized IF regop: " + opcode);
}
}
}
| |
//pakage joney_000[let_me_start]
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
/******************** Main Class ***********************/
class D
{
public static InputStream inputStream = System.in;
public static OutputStream outputStream = System.out;
public static FastReader in = new FastReader(inputStream);;
public static PrintWriter out = new PrintWriter(outputStream);;
/*
Overhead [Additional Temporary Strorage]
*/
public static int tempints[] = new int[100005];
public static long templongs[] = new long[100005];
public static double tempdoubles[] = new double[100005];
public static char tempchars[] = new char[100005];
public static long mod = 1000000000+7;
public static void main(String[] args) throws java.lang.Exception{
//let_me_start
//int tests = i();
int arr[] = new int[25];
//for(int t=1;t<=tests;t++){
int n = i(); //int k=i();
arr = is(n);
//long sum=0;
//for(int i=1;i<=n;i++)sum+=arr[i];
for(int i=0;i<n;i++)arr[i]=arr[i+1];
int ans = f(arr,n);
out.write(""+ans+"\n");
//}
out.flush();
return;
}
public static int f(int []arr , int n )throws Exception{
if(n==1)return 1;
int powersetsize = 1<<n;
//long temp = 0;
LinkedList<Integer> ll = new LinkedList<Integer>();
int ch=0,ans=0;
for(int c = 0; c < powersetsize; c++)
{
ch=0;
for(int j = 0; j < n; j++)
{
if((c & (1<<j))>0){
if(arr[j]<0){
ll.add(arr[j]);
}else{
if(ll.size()==0){ch=1;break;}
int temp = ll.removeLast();
temp=-temp;
if(temp!=arr[j]){
ch=1;break;
}
}
}
//System.out.print(arr[j]+" ");
}
if(ch==0&&ll.size()==0)ans++;
while(ll.size()!=0)ll.removeLast();
//System.out.print("\n");
}
return ans;
}
//****************************** Utilities ***********************//
public static boolean isPrime(long n)throws Exception{
if(n==1)return false;
if(n<=3)return true;
if(n%2==0)return false;
for(int i=2 ;i <= Math.sqrt(n); i++){
if(n%i==0)return false;
}
return true;
}
// sieve
public static int[] primes(int n)throws Exception{ // for(int i=1;i<=arr.length-1;i++)out.write(""+arr[i]+" ");
boolean arr[] = new boolean[n+1];
Arrays.fill(arr,true);
for(int i=1;i<=Math.sqrt(n);i++){
if(!arr[i])continue;
for(int j = 2*i ;j<=n;j+=i){
arr[i]=false;
}
}
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i=1;i<=n;i++){
if(arr[i])ll.add(i);
}
n = ll.size();
int primes[] = new int[n+1];
for(int i=1;i<=n;i++){
primes[i]=ll.removeFirst();
}
return primes;
}
public static long gcd (long a , long b)throws Exception{
if(b==0)return a;
return gcd(b , a%b);
}
public static long lcm (long a , long b)throws Exception{
if(a==0||b==0)return 0;
return (a*b)/gcd(a,b);
}
public static long mulmod(long a , long b ,long mod)throws Exception{
if(a==0||b==0)return 0;
if(b==1)return a;
long ans = mulmod(a,b/2,mod);
ans = (ans*2)% mod;
if(b%2==1)ans = (a + ans)% mod;
return ans;
}
public static long pow(long a , long b ,long mod)throws Exception{
if(b==0)return 1;
if(b==1)return a;
long ans = pow(a,b/2,mod);
ans = (ans * ans)% mod;
if(b%2==1)ans = (a * ans)% mod;
return ans;
}
// 20*20 nCr Pascal Table
public static long[][] ncrTable()throws Exception{
long ncr[][] = new long[21][21];
for(int i=0 ;i<=20 ;i++){ncr[i][0]=1;ncr[i][i]=1;}
for(int j=0;j<=20 ;j++){
for(int i=j+1;i<= 20 ;i++){
ncr[i][j] = ncr[i-1][j]+ncr[i-1][j-1];
}
}
return ncr;
}
//*******************************I/O******************************//
public static int i()throws Exception{
//return Integer.parseInt(br.readLine().trim());
return in.nextInt();
}
public static int[] is(int n)throws Exception{
//int arr[] = new int[n+1];
for(int i=1 ; i <= n ;i++)tempints[i] = in.nextInt();
return tempints;
}
public static long l()throws Exception{
return in.nextLong();
}
public static long[] ls(int n)throws Exception{
for(int i=1 ; i <= n ;i++)templongs[i] = in.nextLong();
return templongs;
}
public static double d()throws Exception{
return in.nextDouble();
}
public static double[] ds(int n)throws Exception{
for(int i=1 ; i <= n ;i++)tempdoubles[i] = in.nextDouble();
return tempdoubles;
}
public static char c()throws Exception{
return in.nextCharacter();
}
public static char[] cs(int n)throws Exception{
for(int i=1 ; i <= n ;i++)tempchars[i] = in.nextCharacter();
return tempchars;
}
public static String s()throws Exception{
return in.nextString();
}
public static BigInteger bi()throws Exception{
return in.nextBigInteger();
}
//***********************I/O ENDS ***********************//
//*********************** 0.3%f [precision]***********************//
/* roundoff upto 2 digits
double roundOff = Math.round(a * 100.0) / 100.0;
or
System.out.printf("%.2f", val);
*/
/*
print upto 2 digits after decimal
val = ((long)(val * 100.0))/100.0;
*/
}
class FastReader{
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream){
this.stream = stream;
}
public int read(){
if (numChars == -1){
throw new InputMismatchException ();
}
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read (buf);
} catch (IOException e){
throw new InputMismatchException ();
}
if (numChars <= 0){
return -1;
}
}
return buf[curChar++];
}
public int peek(){
if (numChars == -1){
return -1;
}
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read (buf);
} catch (IOException e){
return -1;
}
if (numChars <= 0){
return -1;
}
}
return buf[curChar];
}
public int nextInt(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
int res = 0;
do{
if(c==','){
c = read();
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
} while (!isSpaceChar (c));
return res * sgn;
}
public long nextLong(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
long res = 0;
do{
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
} while (!isSpaceChar (c));
return res * sgn;
}
public String nextString(){
int c = read ();
while (isSpaceChar (c))
c = read ();
StringBuilder res = new StringBuilder ();
do{
res.appendCodePoint (c);
c = read ();
} while (!isSpaceChar (c));
return res.toString ();
}
public boolean isSpaceChar(int c){
if (filter != null){
return filter.isSpaceChar (c);
}
return isWhitespace (c);
}
public static boolean isWhitespace(int c){
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0(){
StringBuilder buf = new StringBuilder ();
int c = read ();
while (c != '\n' && c != -1){
if (c != '\r'){
buf.appendCodePoint (c);
}
c = read ();
}
return buf.toString ();
}
public String nextLine(){
String s = readLine0 ();
while (s.trim ().length () == 0)
s = readLine0 ();
return s;
}
public String nextLine(boolean ignoreEmptyLines){
if (ignoreEmptyLines){
return nextLine ();
}else{
return readLine0 ();
}
}
public BigInteger nextBigInteger(){
try{
return new BigInteger (nextString ());
} catch (NumberFormatException e){
throw new InputMismatchException ();
}
}
public char nextCharacter(){
int c = read ();
while (isSpaceChar (c))
c = read ();
return (char) c;
}
public double nextDouble(){
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-'){
sgn = -1;
c = read ();
}
double res = 0;
while (!isSpaceChar (c) && c != '.'){
if (c == 'e' || c == 'E'){
return res * Math.pow (10, nextInt ());
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
}
if (c == '.'){
c = read ();
double m = 1;
while (!isSpaceChar (c)){
if (c == 'e' || c == 'E'){
return res * Math.pow (10, nextInt ());
}
if (c < '0' || c > '9'){
throw new InputMismatchException ();
}
m /= 10;
res += (c - '0') * m;
c = read ();
}
}
return res * sgn;
}
public boolean isExhausted(){
int value;
while (isSpaceChar (value = peek ()) && value != -1)
read ();
return value == -1;
}
public String next(){
return nextString ();
}
public SpaceCharFilter getFilter(){
return filter;
}
public void setFilter(SpaceCharFilter filter){
this.filter = filter;
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}
/******************** Pair class ***********************/
class Pair implements Comparable<Pair>{
public int a;
public int b;
public Pair(){
this.a = 0;
this.b = 0;
}
public Pair(int a,int b){
this.a = a;
this.b = b;
}
public int compareTo(Pair p){
if(this.a==p.a){
return this.b-p.b;
}
return this.a-p.a;
}
public String toString(){
return "a="+this.a+" b="+this.b;
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.gen;
import com.facebook.presto.bytecode.BytecodeBlock;
import com.facebook.presto.bytecode.ClassDefinition;
import com.facebook.presto.bytecode.DynamicClassLoader;
import com.facebook.presto.bytecode.FieldDefinition;
import com.facebook.presto.bytecode.MethodDefinition;
import com.facebook.presto.bytecode.Parameter;
import com.facebook.presto.bytecode.Variable;
import com.facebook.presto.bytecode.control.IfStatement;
import com.facebook.presto.bytecode.expression.BytecodeExpression;
import com.facebook.presto.bytecode.instruction.JumpInstruction;
import com.facebook.presto.bytecode.instruction.LabelNode;
import com.facebook.presto.operator.JoinProbe;
import com.facebook.presto.operator.JoinProbeFactory;
import com.facebook.presto.operator.LookupJoinOperator;
import com.facebook.presto.operator.LookupJoinOperatorFactory;
import com.facebook.presto.operator.LookupJoinOperators.JoinType;
import com.facebook.presto.operator.LookupSource;
import com.facebook.presto.operator.LookupSourceFactory;
import com.facebook.presto.operator.OperatorFactory;
import com.facebook.presto.operator.SimpleJoinProbe;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.BigintType;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.UncheckedExecutionException;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import static com.facebook.presto.bytecode.Access.FINAL;
import static com.facebook.presto.bytecode.Access.PRIVATE;
import static com.facebook.presto.bytecode.Access.PUBLIC;
import static com.facebook.presto.bytecode.Access.a;
import static com.facebook.presto.bytecode.CompilerUtils.defineClass;
import static com.facebook.presto.bytecode.CompilerUtils.makeClassName;
import static com.facebook.presto.bytecode.Parameter.arg;
import static com.facebook.presto.bytecode.ParameterizedType.type;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantLong;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.newInstance;
import static com.facebook.presto.sql.gen.SqlTypeBytecodeExpression.constantType;
import static com.google.common.collect.ImmutableList.toImmutableList;
public class JoinProbeCompiler
{
private final LoadingCache<JoinOperatorCacheKey, HashJoinOperatorFactoryFactory> joinProbeFactories = CacheBuilder.newBuilder()
.recordStats()
.maximumSize(1000)
.build(new CacheLoader<JoinOperatorCacheKey, HashJoinOperatorFactoryFactory>()
{
@Override
public HashJoinOperatorFactoryFactory load(JoinOperatorCacheKey key)
throws Exception
{
return internalCompileJoinOperatorFactory(key.getTypes(), key.getProbeOutputChannels(), key.getProbeChannels(), key.getProbeHashChannel());
}
});
@Managed
@Nested
public CacheStatsMBean getJoinProbeFactoriesStats()
{
return new CacheStatsMBean(joinProbeFactories);
}
public OperatorFactory compileJoinOperatorFactory(int operatorId,
PlanNodeId planNodeId,
LookupSourceFactory lookupSourceFactory,
List<? extends Type> probeTypes,
List<Integer> probeJoinChannel,
Optional<Integer> probeHashChannel,
List<Integer> probeOutputChannels,
JoinType joinType)
{
try {
List<Type> probeOutputChannelTypes = probeOutputChannels.stream()
.map(probeTypes::get)
.collect(toImmutableList());
HashJoinOperatorFactoryFactory operatorFactoryFactory = joinProbeFactories.get(new JoinOperatorCacheKey(
probeTypes,
probeOutputChannels,
probeJoinChannel,
probeHashChannel,
joinType));
return operatorFactoryFactory.createHashJoinOperatorFactory(operatorId, planNodeId, lookupSourceFactory, probeTypes, probeOutputChannelTypes, joinType);
}
catch (ExecutionException | UncheckedExecutionException | ExecutionError e) {
throw Throwables.propagate(e.getCause());
}
}
@VisibleForTesting
public HashJoinOperatorFactoryFactory internalCompileJoinOperatorFactory(List<Type> types, List<Integer> probeOutputChannels, List<Integer> probeJoinChannel, Optional<Integer> probeHashChannel)
{
Class<? extends JoinProbe> joinProbeClass = compileJoinProbe(types, probeOutputChannels, probeJoinChannel, probeHashChannel);
ClassDefinition classDefinition = new ClassDefinition(
a(PUBLIC, FINAL),
makeClassName("JoinProbeFactory"),
type(Object.class),
type(JoinProbeFactory.class));
classDefinition.declareDefaultConstructor(a(PUBLIC));
Parameter lookupSource = arg("lookupSource", LookupSource.class);
Parameter page = arg("page", Page.class);
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "createJoinProbe", type(JoinProbe.class), lookupSource, page);
method.getBody()
.newObject(joinProbeClass)
.dup()
.append(lookupSource)
.append(page)
.invokeConstructor(joinProbeClass, LookupSource.class, Page.class)
.retObject();
DynamicClassLoader classLoader = new DynamicClassLoader(joinProbeClass.getClassLoader());
JoinProbeFactory joinProbeFactory;
if (probeJoinChannel.isEmpty()) {
// see comment in PagesIndex#createLookupSource
joinProbeFactory = new SimpleJoinProbe.SimpleJoinProbeFactory(types, probeOutputChannels, probeJoinChannel, probeHashChannel);
}
else {
Class<? extends JoinProbeFactory> joinProbeFactoryClass = defineClass(classDefinition, JoinProbeFactory.class, classLoader);
try {
joinProbeFactory = joinProbeFactoryClass.newInstance();
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
Class<? extends OperatorFactory> operatorFactoryClass = IsolatedClass.isolateClass(
classLoader,
OperatorFactory.class,
LookupJoinOperatorFactory.class,
LookupJoinOperator.class);
return new HashJoinOperatorFactoryFactory(joinProbeFactory, operatorFactoryClass);
}
@VisibleForTesting
public JoinProbeFactory internalCompileJoinProbe(List<Type> types, List<Integer> probeOutputChannels, List<Integer> probeChannels, Optional<Integer> probeHashChannel)
{
return new ReflectionJoinProbeFactory(compileJoinProbe(types, probeOutputChannels, probeChannels, probeHashChannel));
}
private Class<? extends JoinProbe> compileJoinProbe(List<Type> types, List<Integer> probeOutputChannels, List<Integer> probeChannels, Optional<Integer> probeHashChannel)
{
CallSiteBinder callSiteBinder = new CallSiteBinder();
ClassDefinition classDefinition = new ClassDefinition(
a(PUBLIC, FINAL),
makeClassName("JoinProbe"),
type(Object.class),
type(JoinProbe.class));
// declare fields
FieldDefinition lookupSourceField = classDefinition.declareField(a(PRIVATE, FINAL), "lookupSource", LookupSource.class);
FieldDefinition positionCountField = classDefinition.declareField(a(PRIVATE, FINAL), "positionCount", int.class);
List<FieldDefinition> blockFields = new ArrayList<>();
for (int i = 0; i < types.size(); i++) {
FieldDefinition channelField = classDefinition.declareField(a(PRIVATE, FINAL), "block_" + i, Block.class);
blockFields.add(channelField);
}
List<FieldDefinition> probeBlockFields = new ArrayList<>();
for (int i = 0; i < probeChannels.size(); i++) {
FieldDefinition channelField = classDefinition.declareField(a(PRIVATE, FINAL), "probeBlock_" + i, Block.class);
probeBlockFields.add(channelField);
}
FieldDefinition probeBlocksArrayField = classDefinition.declareField(a(PRIVATE, FINAL), "probeBlocks", Block[].class);
FieldDefinition probePageField = classDefinition.declareField(a(PRIVATE, FINAL), "probePage", Page.class);
FieldDefinition pageField = classDefinition.declareField(a(PRIVATE, FINAL), "page", Page.class);
FieldDefinition positionField = classDefinition.declareField(a(PRIVATE), "position", int.class);
FieldDefinition probeHashBlockField = classDefinition.declareField(a(PRIVATE, FINAL), "probeHashBlock", Block.class);
generateConstructor(classDefinition, probeChannels, probeHashChannel, lookupSourceField, blockFields, probeBlockFields, probeBlocksArrayField, probePageField, pageField, probeHashBlockField, positionField, positionCountField);
generateGetChannelCountMethod(classDefinition, probeOutputChannels.size());
generateAppendToMethod(classDefinition, callSiteBinder, types, probeOutputChannels, blockFields, positionField);
generateAdvanceNextPosition(classDefinition, positionField, positionCountField);
generateGetCurrentJoinPosition(classDefinition, callSiteBinder, lookupSourceField, probePageField, pageField, probeHashChannel, probeHashBlockField, positionField);
generateCurrentRowContainsNull(classDefinition, probeBlockFields, positionField);
generateGetPosition(classDefinition, positionField);
generateGetPage(classDefinition, pageField);
return defineClass(classDefinition, JoinProbe.class, callSiteBinder.getBindings(), getClass().getClassLoader());
}
private static void generateConstructor(ClassDefinition classDefinition,
List<Integer> probeChannels,
Optional<Integer> probeHashChannel,
FieldDefinition lookupSourceField,
List<FieldDefinition> blockFields,
List<FieldDefinition> probeChannelFields,
FieldDefinition probeBlocksArrayField,
FieldDefinition probePageField,
FieldDefinition pageField,
FieldDefinition probeHashBlockField,
FieldDefinition positionField,
FieldDefinition positionCountField)
{
Parameter lookupSource = arg("lookupSource", LookupSource.class);
Parameter page = arg("page", Page.class);
MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC), lookupSource, page);
Variable thisVariable = constructorDefinition.getThis();
BytecodeBlock constructor = constructorDefinition
.getBody()
.comment("super();")
.append(thisVariable)
.invokeConstructor(Object.class);
constructor.comment("this.lookupSource = lookupSource;")
.append(thisVariable.setField(lookupSourceField, lookupSource));
constructor.comment("this.positionCount = page.getPositionCount();")
.append(thisVariable.setField(positionCountField, page.invoke("getPositionCount", int.class)));
constructor.comment("Set block fields");
for (int index = 0; index < blockFields.size(); index++) {
constructor.append(thisVariable.setField(
blockFields.get(index),
page.invoke("getBlock", Block.class, constantInt(index))));
}
constructor.comment("Set probe channel fields");
for (int index = 0; index < probeChannelFields.size(); index++) {
constructor.append(thisVariable.setField(
probeChannelFields.get(index),
thisVariable.getField(blockFields.get(probeChannels.get(index)))));
}
constructor.comment("this.probeBlocks = new Block[<probeChannelCount>];");
constructor
.append(thisVariable)
.push(probeChannelFields.size())
.newArray(Block.class)
.putField(probeBlocksArrayField);
for (int index = 0; index < probeChannelFields.size(); index++) {
constructor
.append(thisVariable)
.getField(probeBlocksArrayField)
.push(index)
.append(thisVariable)
.getField(probeChannelFields.get(index))
.putObjectArrayElement();
}
constructor.comment("this.page = page")
.append(thisVariable.setField(pageField, page));
constructor.comment("this.probePage = new Page(probeBlocks)")
.append(thisVariable.setField(probePageField, newInstance(Page.class, thisVariable.getField(probeBlocksArrayField))));
if (probeHashChannel.isPresent()) {
Integer index = probeHashChannel.get();
constructor.comment("this.probeHashBlock = blocks[hashChannel.get()]")
.append(thisVariable.setField(
probeHashBlockField,
thisVariable.getField(blockFields.get(index))));
}
constructor.comment("this.position = -1;")
.append(thisVariable.setField(positionField, constantInt(-1)));
constructor.ret();
}
private static void generateGetChannelCountMethod(ClassDefinition classDefinition, int channelCount)
{
classDefinition.declareMethod(
a(PUBLIC),
"getOutputChannelCount",
type(int.class))
.getBody()
.push(channelCount)
.retInt();
}
private static void generateAppendToMethod(
ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
List<Type> types,
List<Integer> probeOutputChannels,
List<FieldDefinition> blockFields,
FieldDefinition positionField)
{
Parameter pageBuilder = arg("pageBuilder", PageBuilder.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"appendTo",
type(void.class),
pageBuilder);
Variable thisVariable = method.getThis();
int pageBuilderOutputChannel = 0;
for (int outputChannel : probeOutputChannels) {
Type type = types.get(outputChannel);
method.getBody()
.comment("%s.appendTo(block_%s, position, pageBuilder.getBlockBuilder(%s));", type.getClass(), outputChannel, pageBuilderOutputChannel)
.append(constantType(callSiteBinder, type).invoke("appendTo", void.class,
thisVariable.getField(blockFields.get(outputChannel)),
thisVariable.getField(positionField),
pageBuilder.invoke("getBlockBuilder", BlockBuilder.class, constantInt(pageBuilderOutputChannel++))));
}
method.getBody()
.ret();
}
private static void generateAdvanceNextPosition(ClassDefinition classDefinition, FieldDefinition positionField, FieldDefinition positionCountField)
{
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"advanceNextPosition",
type(boolean.class));
Variable thisVariable = method.getThis();
method.getBody()
.comment("this.position = this.position + 1;")
.append(thisVariable)
.append(thisVariable)
.getField(positionField)
.push(1)
.intAdd()
.putField(positionField);
LabelNode lessThan = new LabelNode("lessThan");
LabelNode end = new LabelNode("end");
method.getBody()
.comment("return position < positionCount;")
.append(thisVariable)
.getField(positionField)
.append(thisVariable)
.getField(positionCountField)
.append(JumpInstruction.jumpIfIntLessThan(lessThan))
.push(false)
.gotoLabel(end)
.visitLabel(lessThan)
.push(true)
.visitLabel(end)
.retBoolean();
}
private static void generateGetCurrentJoinPosition(ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
FieldDefinition lookupSourceField,
FieldDefinition probePageField,
FieldDefinition pageField,
Optional<Integer> probeHashChannel,
FieldDefinition probeHashBlockField,
FieldDefinition positionField)
{
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"getCurrentJoinPosition",
type(long.class));
Variable thisVariable = method.getThis();
BytecodeBlock body = method.getBody()
.append(new IfStatement()
.condition(thisVariable.invoke("currentRowContainsNull", boolean.class))
.ifTrue(constantLong(-1).ret()));
BytecodeExpression position = thisVariable.getField(positionField);
BytecodeExpression hashChannelsPage = thisVariable.getField(probePageField);
BytecodeExpression allChannelsPage = thisVariable.getField(pageField);
BytecodeExpression probeHashBlock = thisVariable.getField(probeHashBlockField);
if (probeHashChannel.isPresent()) {
body.append(thisVariable.getField(lookupSourceField).invoke("getJoinPosition", long.class,
position,
hashChannelsPage,
allChannelsPage,
constantType(callSiteBinder, BigintType.BIGINT).invoke("getLong",
long.class,
probeHashBlock,
position)))
.retLong();
}
else {
body.append(thisVariable.getField(lookupSourceField).invoke("getJoinPosition", long.class, position, hashChannelsPage, allChannelsPage)).retLong();
}
}
private static void generateCurrentRowContainsNull(ClassDefinition classDefinition, List<FieldDefinition> probeBlockFields, FieldDefinition positionField)
{
MethodDefinition method = classDefinition.declareMethod(
a(PRIVATE),
"currentRowContainsNull",
type(boolean.class));
Variable thisVariable = method.getThis();
for (FieldDefinition probeBlockField : probeBlockFields) {
LabelNode checkNextField = new LabelNode("checkNextField");
method.getBody()
.append(thisVariable.getField(probeBlockField).invoke("isNull", boolean.class, thisVariable.getField(positionField)))
.ifFalseGoto(checkNextField)
.push(true)
.retBoolean()
.visitLabel(checkNextField);
}
method.getBody()
.push(false)
.retInt();
}
private static void generateGetPosition(ClassDefinition classDefinition, FieldDefinition positionField)
{
// dummy implementation for now
// compiled class is used only in usecase case when result of this method is ignored.
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"getPosition",
type(int.class));
Variable thisVariable = method.getThis();
method.getBody()
.append(thisVariable.getField(positionField))
.retInt();
}
private static void generateGetPage(ClassDefinition classDefinition, FieldDefinition pageField)
{
// dummy implementation for now
// compiled class is used only in usecase case when result of this method is ignored.
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"getPage",
type(Page.class));
Variable thisVariable = method.getThis();
method.getBody()
.append(thisVariable.getField(pageField))
.ret(Page.class);
}
public static class ReflectionJoinProbeFactory
implements JoinProbeFactory
{
private final Constructor<? extends JoinProbe> constructor;
public ReflectionJoinProbeFactory(Class<? extends JoinProbe> joinProbeClass)
{
try {
constructor = joinProbeClass.getConstructor(LookupSource.class, Page.class);
}
catch (NoSuchMethodException e) {
throw Throwables.propagate(e);
}
}
@Override
public JoinProbe createJoinProbe(LookupSource lookupSource, Page page)
{
try {
return constructor.newInstance(lookupSource, page);
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
private static final class JoinOperatorCacheKey
{
private final List<Type> types;
private final List<Integer> probeOutputChannels;
private final List<Integer> probeChannels;
private final JoinType joinType;
private final Optional<Integer> probeHashChannel;
private JoinOperatorCacheKey(List<? extends Type> types,
List<Integer> probeOutputChannels,
List<Integer> probeChannels,
Optional<Integer> probeHashChannel,
JoinType joinType)
{
this.probeHashChannel = probeHashChannel;
this.types = ImmutableList.copyOf(types);
this.probeOutputChannels = ImmutableList.copyOf(probeOutputChannels);
this.probeChannels = ImmutableList.copyOf(probeChannels);
this.joinType = joinType;
}
private List<Type> getTypes()
{
return types;
}
private List<Integer> getProbeOutputChannels()
{
return probeOutputChannels;
}
private List<Integer> getProbeChannels()
{
return probeChannels;
}
private Optional<Integer> getProbeHashChannel()
{
return probeHashChannel;
}
@Override
public int hashCode()
{
return Objects.hash(types, probeOutputChannels, probeChannels, joinType);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (!(obj instanceof JoinOperatorCacheKey)) {
return false;
}
JoinOperatorCacheKey other = (JoinOperatorCacheKey) obj;
return Objects.equals(this.types, other.types) &&
Objects.equals(this.probeOutputChannels, other.probeOutputChannels) &&
Objects.equals(this.probeChannels, other.probeChannels) &&
Objects.equals(this.probeHashChannel, other.probeHashChannel) &&
Objects.equals(this.joinType, other.joinType);
}
}
private static class HashJoinOperatorFactoryFactory
{
private final JoinProbeFactory joinProbeFactory;
private final Constructor<? extends OperatorFactory> constructor;
private HashJoinOperatorFactoryFactory(JoinProbeFactory joinProbeFactory, Class<? extends OperatorFactory> operatorFactoryClass)
{
this.joinProbeFactory = joinProbeFactory;
try {
constructor = operatorFactoryClass.getConstructor(int.class, PlanNodeId.class, LookupSourceFactory.class, List.class, List.class, JoinType.class, JoinProbeFactory.class);
}
catch (NoSuchMethodException e) {
throw Throwables.propagate(e);
}
}
public OperatorFactory createHashJoinOperatorFactory(
int operatorId,
PlanNodeId planNodeId,
LookupSourceFactory lookupSourceFactory,
List<? extends Type> probeTypes,
List<? extends Type> probeOutputTypes,
JoinType joinType)
{
try {
return constructor.newInstance(operatorId, planNodeId, lookupSourceFactory, probeTypes, probeOutputTypes, joinType, joinProbeFactory);
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
public static void checkState(boolean left, boolean right)
{
if (left != right) {
throw new IllegalStateException();
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.linalg.crash;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import lombok.var;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.linalg.BaseNd4jTest;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.memory.conf.WorkspaceConfiguration;
import org.nd4j.linalg.api.memory.enums.AllocationPolicy;
import org.nd4j.linalg.api.memory.enums.LearningPolicy;
import org.nd4j.linalg.api.memory.enums.ResetPolicy;
import org.nd4j.linalg.api.memory.enums.SpillPolicy;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.DynamicCustomOp;
import org.nd4j.linalg.api.ops.impl.reduce.longer.MatchCondition;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.exception.ND4JIllegalStateException;
import org.nd4j.linalg.factory.Broadcast;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.linalg.indexing.conditions.Conditions;
import org.nd4j.linalg.ops.transforms.Transforms;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.nd4j.linalg.indexing.NDArrayIndex.*;
/**
* @author raver119@gmail.com
*/
@Slf4j
@RunWith(Parameterized.class)
public class SpecialTests extends BaseNd4jTest {
public SpecialTests(Nd4jBackend backend) {
super(backend);
}
@Test
public void testDimensionalThings1() {
INDArray x = Nd4j.rand(new int[] {20, 30, 50});
INDArray y = Nd4j.rand(x.shape());
INDArray result = transform(x, y);
}
@Test
public void testDimensionalThings2() {
INDArray x = Nd4j.rand(new int[] {20, 30, 50});
INDArray y = Nd4j.rand(x.shape());
for (int i = 0; i < 1; i++) {
int number = 5;
int start = RandomUtils.nextInt(0, (int) x.shape()[2] - number);
transform(getView(x, start, 5), getView(y, start, 5));
}
}
protected static INDArray getView(INDArray x, int from, int number) {
return x.get(all(), all(), interval(from, from + number));
}
protected static INDArray transform(INDArray a, INDArray b) {
int nShape[] = new int[] {1, 2};
INDArray a_reduced = a.sum(nShape);
INDArray b_reduced = b.sum(nShape);
//log.info("reduced shape: {}", Arrays.toString(a_reduced.shapeInfoDataBuffer().asInt()));
return Transforms.abs(a_reduced.sub(b_reduced)).div(a_reduced);
}
@Test(expected = ND4JIllegalStateException.class)
public void testScalarShuffle1() {
List<DataSet> listData = new ArrayList<>();
for (int i = 0; i < 3; i++) {
INDArray features = Nd4j.ones(25, 25);
INDArray label = Nd4j.create(new float[] {1}, new int[] {1});
DataSet dataset = new DataSet(features, label);
listData.add(dataset);
}
DataSet data = DataSet.merge(listData);
data.shuffle();
}
@Test
public void testScalarShuffle2() {
List<DataSet> listData = new ArrayList<>();
for (int i = 0; i < 3; i++) {
INDArray features = Nd4j.ones(14, 25);
INDArray label = Nd4j.create(14, 50);
DataSet dataset = new DataSet(features, label);
listData.add(dataset);
}
DataSet data = DataSet.merge(listData);
data.shuffle();
}
@Test
public void testVstack2() {
INDArray matrix = Nd4j.create(10000, 100);
List<INDArray> views = new ArrayList<>();
views.add(matrix.getRow(1));
views.add(matrix.getRow(4));
views.add(matrix.getRow(7));
INDArray result = Nd4j.vstack(views);
}
@Test
public void testVstack1() {
INDArray matrix = Nd4j.create(10000, 100);
List<INDArray> views = new ArrayList<>();
for (int i = 0; i < matrix.rows() / 2; i++) {
views.add(matrix.getRow(RandomUtils.nextInt(0, matrix.rows())));
//views.add(Nd4j.create(1, 10));
}
// log.info("Starting...");
//while (true) {
for (int i = 0; i < 1; i++) {
INDArray result = Nd4j.vstack(views);
System.gc();
}
}
@Test
public void testConcatMulti() throws Exception {
val shapeA = new int[] {50, 20};
val shapeB = new int[] {50, 497};
//Nd4j.create(1);
val executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
for (int e = 0; e < 1; e++) {
executor.submit(new Runnable() {
@Override
public void run() {
val arrayA = Nd4j.createUninitialized(shapeA);
}
});
}
Thread.sleep(1000);
}
@Test
public void testConcatMulti2() {
Nd4j.create(1);
val executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
executor.submit(new Runnable() {
@Override
public void run() {
// System.out.println("A");
}
});
}
@Test
public void testMigrationMultiGpu_1() throws Exception {
if (Nd4j.getAffinityManager().getNumberOfDevices() < 2)
return;
val list = new CopyOnWriteArrayList<INDArray>();
val threads = new ArrayList<Thread>();
val devices = Nd4j.getAffinityManager().getNumberOfDevices();
for (int e = 0; e < devices; e++) {
val f = e;
val t = new Thread(new Runnable() {
@Override
public void run() {
val deviceId = Nd4j.getAffinityManager().getDeviceForCurrentThread();
log.info("Current device: {}", deviceId);
for (int i = 0; i < 10; i++) {
val ar = Nd4j.create(100, 100).assign(1.0f);
assertEquals(deviceId, Nd4j.getAffinityManager().getDeviceForArray(ar));
list.add(ar);
Nd4j.getExecutioner().commit();
}
}
});
t.start();
t.join();
threads.add(t);
// log.info("------------------------");
}
for (val t:threads)
t.join();
for (val a:list) {
val device = Nd4j.getAffinityManager().getDeviceForArray(a);
try {
assertEquals(1.0f, a.meanNumber().floatValue(), 1e-5);
} catch (Exception e) {
log.error("Failed for array from device [{}]", device);
throw e;
}
}
}
@Test
public void testMigrationMultiGpu_2() throws Exception {
if (Nd4j.getAffinityManager().getNumberOfDevices() < 2)
return;
val wsConf = WorkspaceConfiguration.builder()
.policyReset(ResetPolicy.ENDOFBUFFER_REACHED)
.policyAllocation(AllocationPolicy.STRICT)
.initialSize(50 * 1024L * 1024L)
.build();
for (int x = 0; x < 10; x++) {
val list = new CopyOnWriteArrayList<INDArray>();
val threads = new ArrayList<Thread>();
for (int e = 0; e < Nd4j.getAffinityManager().getNumberOfDevices(); e++) {
val f = e;
val t = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try (val ws = Nd4j.getWorkspaceManager().getAndActivateWorkspace(wsConf, "id")) {
list.add(Nd4j.create(3, 3).assign(1.0f));
Nd4j.getExecutioner().commit();
}
}
}
});
t.start();
threads.add(t);
}
for (val t : threads)
t.join();
for (val a : list) {
assertTrue(a.isAttached());
assertEquals(1.0f, a.meanNumber().floatValue(), 1e-5);
}
System.gc();
}
}
@Test
public void testBroadcastLt(){
for( int i=0; i<10; i++) {
INDArray x = Nd4j.create(DataType.DOUBLE, 1, 3, 2, 4, 4);
INDArray y = Nd4j.create(DataType.DOUBLE, 1, 2, 4, 4);
INDArray z = Nd4j.create(DataType.BOOL, 1, 3, 2, 4, 4);
Broadcast.lt(x, y, z, 0, 2, 3, 4);
}
}
@Test
public void testBroadcastLt2(){
for( int i=0; i<10; i++) {
INDArray orig = Nd4j.create(DataType.DOUBLE, 1, 7, 4, 4);
INDArray y = orig.get(all(), interval(0,2), all(), all());
INDArray x = Nd4j.create(DataType.DOUBLE, 1, 3, 2, 4, 4);
INDArray z = Nd4j.create(DataType.BOOL, 1, 3, 2, 4, 4);
Broadcast.lt(x, y, z, 0, 2, 3, 4);
}
}
@Test
public void reproduceWorkspaceCrash(){
val conf = WorkspaceConfiguration.builder().build();
val ws = Nd4j.getWorkspaceManager().getWorkspaceForCurrentThread(conf, "WS");
INDArray arr = Nd4j.create(new double[]{1, 0, 0, 0, 1, 0, 0, 0, 0, 0}, new long[]{1, 10});
//assertNotEquals(Nd4j.defaultFloatingPointType(), arr.dataType());
Nd4j.setDefaultDataTypes(DataType.DOUBLE, DataType.DOUBLE);
for( int i=0; i<100; i++ ) {
try(val ws2 = ws.notifyScopeEntered()) {
// System.out.println("Iteration: " + i);
INDArray ok = arr.eq(0.0);
ok.dup();
assertEquals(arr.dataType(), Nd4j.defaultFloatingPointType());
assertEquals(DataType.DOUBLE, Nd4j.defaultFloatingPointType());
INDArray crash = arr.eq(0.0).castTo(Nd4j.defaultFloatingPointType());
crash.dup(); //Crashes here on i=1 iteration
}
}
}
@Test
public void reproduceWorkspaceCrash_2(){
val dtypes = new DataType[]{DataType.DOUBLE, DataType.FLOAT, DataType.HALF, DataType.LONG, DataType.INT, DataType.SHORT, DataType.BYTE, DataType.UBYTE, DataType.BOOL};
for (val dX : dtypes) {
for (val dZ: dtypes) {
val array = Nd4j.create(dX, 2, 5).assign(1);
// log.info("Trying to cast {} to {}", dX, dZ);
val casted = array.castTo(dZ);
val exp = Nd4j.create(dZ, 2, 5).assign(1);
assertEquals(exp, casted);
}
}
}
@Test
public void reproduceWorkspaceCrash_3(){
val conf = WorkspaceConfiguration.builder().build();
val ws = Nd4j.getWorkspaceManager().getWorkspaceForCurrentThread(conf, "WS");
val dtypes = new DataType[]{DataType.DOUBLE, DataType.FLOAT, DataType.HALF, DataType.LONG, DataType.INT, DataType.SHORT, DataType.BYTE, DataType.UBYTE, DataType.BOOL};
for (val dX : dtypes) {
for (val dZ: dtypes) {
try(val ws2 = ws.notifyScopeEntered()) {
val array = Nd4j.create(dX, 2, 5).assign(1);
// log.info("Trying to cast {} to {}", dX, dZ);
val casted = array.castTo(dZ);
val exp = Nd4j.create(dZ, 2, 5).assign(1);
assertEquals(exp, casted);
Nd4j.getExecutioner().commit();
}
}
}
}
@Test
public void testCastLong_1() {
val array = Nd4j.create(DataType.LONG, 100, 100).assign(1);
val second = Nd4j.create(DataType.LONG, 100, 100).assign(1);
// log.info("----------------");
val castedA = array.castTo(DataType.BYTE).assign(3);
val castedB = array.castTo(DataType.BYTE).assign(3);
Nd4j.getExecutioner().commit();
assertEquals(castedA, castedB);
assertEquals(array, second);
}
@Test
public void testCastHalf_1() {
val array = Nd4j.create(DataType.HALF, 2, 5).assign(1);
assertEquals(10.f, array.sumNumber().floatValue(), 1e-3);
}
@Test
public void testCastHalf_2() {
val array = Nd4j.create(DataType.HALF, 2, 5).assign(1);
assertEquals(10.f, array.sumNumber().floatValue(), 1e-3);
}
@Test
public void testCastHalf_3() {
val arrayY = Nd4j.create(DataType.FLOAT, 2, 5).assign(2);
val arrayX = Nd4j.create(DataType.HALF, 2, 5).assign(arrayY);
assertEquals(20.f, arrayX.sumNumber().floatValue(), 1e-3);
}
@Test
public void testReduce_Small_1() {
val array = Nd4j.create(DataType.SHORT, 100, 30).assign(1);
assertEquals(3000, array.sumNumber().intValue());
}
@Test
public void testReduce_Small_2() {
val array = Nd4j.create(DataType.BYTE, 100, 100).assign(0);
assertEquals(0, array.sumNumber().intValue());
}
@Test
public void testReduce3_Small_1() {
val arrayA = Nd4j.create(DataType.SHORT, 100, 100).assign(1);
val arrayB = Nd4j.create(DataType.SHORT, 100, 100).assign(1);
assertEquals(arrayA, arrayB);
}
@Test
public void testReduce3_Small_2() {
val arrayA = Nd4j.create(DataType.BYTE, 100, 100).assign(1);
val arrayB = Nd4j.create(DataType.BYTE, 100, 100).assign(1);
assertEquals(arrayA, arrayB);
}
@Test
public void reproduceWorkspaceCrash_4(){
val conf = WorkspaceConfiguration.builder().build();
val ws = Nd4j.getWorkspaceManager().getWorkspaceForCurrentThread(conf, "WS");
val dtypes = new DataType[]{DataType.LONG, DataType.DOUBLE, DataType.FLOAT, DataType.HALF, DataType.INT, DataType.SHORT, DataType.BYTE, DataType.UBYTE, DataType.BOOL};
for (val dX : dtypes) {
for (val dZ: dtypes) {
try(val ws2 = Nd4j.getWorkspaceManager().getAndActivateWorkspace("WS")) {
val array = Nd4j.create(dX, 100, 100).assign(1);
// log.info("Trying to cast {} to {}", dX, dZ);
val casted = array.castTo(dZ);
val exp = Nd4j.create(dZ, 100, 100).assign(1);
assertEquals(exp, casted);
}
}
}
}
@Test
public void reproduceWorkspaceCrash_5(){
val conf = WorkspaceConfiguration.builder().build();
val ws = Nd4j.getWorkspaceManager().getWorkspaceForCurrentThread(conf, "WS");
INDArray arr = Nd4j.create(new double[]{1, 0, 0, 0, 1, 0, 0, 0, 0, 0}, new long[]{1, 10});
Nd4j.setDefaultDataTypes(DataType.DOUBLE, DataType.DOUBLE);
assertEquals(DataType.DOUBLE, arr.dataType());
for( int i=0; i<100; i++ ) {
try(val ws2 = ws.notifyScopeEntered()) {
INDArray crash = arr.castTo(DataType.BOOL).castTo(DataType.DOUBLE);
crash.dup();
}
}
}
@Test
public void testConcatAgain(){
INDArray[] toConcat = new INDArray[3];
for( int i=0; i<toConcat.length; i++ ) {
toConcat[i] = Nd4j.valueArrayOf(new long[]{10, 1}, i).castTo(DataType.FLOAT);
}
INDArray out = Nd4j.concat(1, toConcat);
// System.out.println(out);
}
@Test
public void testConcat2(){
//Nd4j.getExecutioner().enableDebugMode(true);
//Nd4j.getExecutioner().enableVerboseMode(true);
int n = 784; //OK for 10, 100, 500
//Fails for 784, 783, 750, 720, 701, 700
INDArray[] arrs = new INDArray[n];
for( int i=0; i<n; i++ ){
INDArray a = Nd4j.create(DataType.DOUBLE, 10,1).assign(i); //Also fails for FLOAT
arrs[i] = a;
}
Nd4j.getExecutioner().commit();
INDArray out = null;
for (int e = 0; e < 5; e++) {
if (e % 10 == 0)
// log.info("Iteration: [{}]", e);
out = Nd4j.concat(1, arrs);
}
Nd4j.getExecutioner().commit();
// System.out.println(out);
}
@Test
public void testYoloStyle(){
WorkspaceConfiguration WS_ALL_LAYERS_ACT_CONFIG = WorkspaceConfiguration.builder()
.initialSize(0)
.overallocationLimit(0.05)
.policyLearning(LearningPolicy.FIRST_LOOP)
.policyReset(ResetPolicy.BLOCK_LEFT)
.policySpill(SpillPolicy.REALLOCATE)
.policyAllocation(AllocationPolicy.OVERALLOCATE)
.build();
for( int i=0; i<10; i++ ){
try(val ws = Nd4j.getWorkspaceManager().getAndActivateWorkspace(WS_ALL_LAYERS_ACT_CONFIG, "ws")){
// System.out.println("STARTING: " + i);
INDArray objectPresentMask = Nd4j.create(DataType.BOOL, 1,4,4);
long[] shape = {1,3,2,4,4};
INDArray noIntMask1 = Nd4j.createUninitialized(DataType.BOOL, shape, 'c');
INDArray noIntMask2 = Nd4j.createUninitialized(DataType.BOOL, shape, 'c');
noIntMask1 = Transforms.or(noIntMask1.get(all(), all(), point(0), all(), all()), noIntMask1.get(all(), all(), point(1), all(), all()) ); //Shape: [mb, b, H, W]. Values 1 if no intersection
noIntMask2 = Transforms.or(noIntMask2.get(all(), all(), point(0), all(), all()), noIntMask2.get(all(), all(), point(1), all(), all()) );
INDArray noIntMask = Transforms.or(noIntMask1, noIntMask2 );
Nd4j.getExecutioner().commit();
INDArray intMask = Transforms.not(noIntMask); //Values 0 if no intersection
Nd4j.getExecutioner().commit();
Broadcast.mul(intMask, objectPresentMask, intMask, 0, 2, 3);
Nd4j.getExecutioner().commit();
// System.out.println("DONE: " + i);
}
}
}
@Test
public void testSpaceToBatch() {
Nd4j.getRandom().setSeed(7331);
int miniBatch = 4;
int[] inputShape = new int[]{1, 2, 2, 1};
int M = 2;
INDArray input = Nd4j.randn(inputShape).castTo(DataType.DOUBLE);
INDArray blocks = Nd4j.createFromArray(2, 2);
INDArray padding = Nd4j.createFromArray(0, 0, 0, 0).reshape(2,2);
INDArray expOut = Nd4j.create(DataType.DOUBLE, miniBatch, 1, 1, 1);
val op = DynamicCustomOp.builder("space_to_batch_nd")
.addInputs(input, blocks, padding)
.addOutputs(expOut).build();
Nd4j.getExecutioner().execAndReturn(op);
}
@Test
public void testBatchToSpace() {
Nd4j.getRandom().setSeed(1337);
int miniBatch = 4;
int[] inputShape = new int[]{miniBatch, 1, 1, 1};
int M = 2;
INDArray input = Nd4j.randn(inputShape).castTo(DataType.DOUBLE);
INDArray blocks = Nd4j.createFromArray(2, 2);
INDArray crops = Nd4j.createFromArray(0, 0, 0, 0).reshape(2,2);
INDArray expOut = Nd4j.create(DataType.DOUBLE, 1, 2, 2, 1);
DynamicCustomOp op = DynamicCustomOp.builder("batch_to_space_nd")
.addInputs(input, blocks, crops)
.addOutputs(expOut).build();
Nd4j.getExecutioner().execAndReturn(op);
}
@Test
public void testYoloS(){
//Nd4j.getExecutioner().enableDebugMode(true);
//Nd4j.getExecutioner().enableVerboseMode(true);
//Nd4j.setDefaultDataTypes(DataType.DOUBLE, DataType.DOUBLE);
WorkspaceConfiguration WS_ALL_LAYERS_ACT_CONFIG = WorkspaceConfiguration.builder()
.initialSize(10 * 1024 * 1024)
.overallocationLimit(0.05)
.policyLearning(LearningPolicy.FIRST_LOOP)
.policyReset(ResetPolicy.BLOCK_LEFT)
.policySpill(SpillPolicy.REALLOCATE)
.policyAllocation(AllocationPolicy.OVERALLOCATE)
.build();
INDArray labels = Nd4j.create(DataType.DOUBLE, 1,7,5,7);
for( int i=0; i<10; i++ ){
try(val ws = Nd4j.getWorkspaceManager().getAndActivateWorkspace(WS_ALL_LAYERS_ACT_CONFIG, "ws")){
// System.out.println("STARTING: " + i);
val nhw = new long[]{1, 5, 7};
val size1 = labels.size(1);
INDArray classLabels = labels.get(all(), interval(4,size1), all(), all()); //Shape: [minibatch, nClasses, H, W]
INDArray maskObjectPresent = classLabels.sum(Nd4j.createUninitialized(DataType.DOUBLE, nhw, 'c'), 1).castTo(DataType.BOOL); //Shape: [minibatch, H, W]
INDArray labelTLXY = labels.get(all(), interval(0,2), all(), all());
INDArray labelBRXY = labels.get(all(), interval(2,4), all(), all());
Nd4j.getExecutioner().commit();
INDArray labelCenterXY = labelTLXY.add(labelBRXY);
val m = labelCenterXY.muli(0.5); //In terms of grid units
INDArray labelsCenterXYInGridBox = labelCenterXY.dup(labelCenterXY.ordering()); //[mb, 2, H, W]
Nd4j.getExecutioner().commit();
// System.out.println("DONE: " + i);
}
}
}
@Test
public void testMatchCondition(){
INDArray x = Nd4j.valueArrayOf(new long[]{10,10}, 2.0, DataType.DOUBLE);
val op = new MatchCondition(x, Conditions.equals(2));
INDArray z = Nd4j.getExecutioner().exec(op);
int count = z.getInt(0);
assertEquals(100, count);
}
@Test
public void testBroadcastMul_bool() {
val mask = Nd4j.create(DataType.BOOL, 1, 3, 4, 4);
val object = Nd4j.create(DataType.BOOL, 1, 4, 4);
Broadcast.mul(mask, object, mask, 0, 2, 3);
Nd4j.getExecutioner().commit();
}
@Test
public void testReshape(){
INDArray c = Nd4j.linspace(1,6,6, DataType.DOUBLE).reshape('c', 2,3);
INDArray f = c.dup('f');
val fr = f.reshape('f', 3, 2).dup('f');
// log.info("FO: {}", f.data().asFloat());
// log.info("FR: {}", fr.data().asFloat());
INDArray outC = Nd4j.create(DataType.DOUBLE, 3,2);
INDArray outF = Nd4j.create(DataType.DOUBLE, 3,2);
var op = DynamicCustomOp.builder("reshape")
.addInputs(c)
.addOutputs(outC)
.addIntegerArguments(3,2)
.build();
Nd4j.getExecutioner().exec(op);
op = DynamicCustomOp.builder("reshape")
.addInputs(f)
.addOutputs(outF)
.addIntegerArguments(-99, 3,2)
.build();
Nd4j.getExecutioner().exec(op);
assertEquals(outC, outF);
}
@Override
public char ordering() {
return 'c';
}
}
| |
/*
* 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.druid.segment.indexing;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import org.apache.druid.data.input.impl.DimensionsSpec;
import org.apache.druid.data.input.impl.InputRowParser;
import org.apache.druid.data.input.impl.TimestampSpec;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.segment.indexing.granularity.GranularitySpec;
import org.apache.druid.segment.indexing.granularity.UniformGranularitySpec;
import org.apache.druid.segment.transform.TransformSpec;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
*/
public class DataSchema
{
private static final Logger log = new Logger(DataSchema.class);
private final String dataSource;
private final Map<String, Object> parser;
private final AggregatorFactory[] aggregators;
private final GranularitySpec granularitySpec;
private final TransformSpec transformSpec;
private final ObjectMapper jsonMapper;
private InputRowParser cachedParser;
@JsonCreator
public DataSchema(
@JsonProperty("dataSource") String dataSource,
@JsonProperty("parser") Map<String, Object> parser,
@JsonProperty("metricsSpec") AggregatorFactory[] aggregators,
@JsonProperty("granularitySpec") GranularitySpec granularitySpec,
@JsonProperty("transformSpec") TransformSpec transformSpec,
@JacksonInject ObjectMapper jsonMapper
)
{
this.jsonMapper = Preconditions.checkNotNull(jsonMapper, "null ObjectMapper.");
this.parser = parser;
this.transformSpec = transformSpec == null ? TransformSpec.NONE : transformSpec;
Preconditions.checkArgument(!Strings.isNullOrEmpty(dataSource), "dataSource cannot be null or empty. Please provide a dataSource.");
Preconditions.checkArgument(!dataSource.contains("/"), "dataSource cannot contain the '/' character.");
this.dataSource = dataSource;
if (granularitySpec == null) {
log.warn("No granularitySpec has been specified. Using UniformGranularitySpec as default.");
this.granularitySpec = new UniformGranularitySpec(null, null, null);
} else {
this.granularitySpec = granularitySpec;
}
if (aggregators != null && aggregators.length != 0) {
// validate for no duplication
Set<String> names = new HashSet<>();
for (AggregatorFactory factory : aggregators) {
if (!names.add(factory.getName())) {
throw new IAE("duplicate aggregators found with name [%s].", factory.getName());
}
}
} else if (this.granularitySpec.isRollup()) {
log.warn("No metricsSpec has been specified. Are you sure this is what you want?");
}
this.aggregators = aggregators == null ? new AggregatorFactory[]{} : aggregators;
}
@JsonProperty
public String getDataSource()
{
return dataSource;
}
@JsonProperty("parser")
public Map<String, Object> getParserMap()
{
return parser;
}
@JsonIgnore
public InputRowParser getParser()
{
if (parser == null) {
log.warn("No parser has been specified");
return null;
}
if (cachedParser != null) {
return cachedParser;
}
final InputRowParser inputRowParser = transformSpec.decorate(
jsonMapper.convertValue(this.parser, InputRowParser.class)
);
final Set<String> dimensionExclusions = Sets.newHashSet();
for (AggregatorFactory aggregator : aggregators) {
dimensionExclusions.addAll(aggregator.requiredFields());
dimensionExclusions.add(aggregator.getName());
}
if (inputRowParser.getParseSpec() != null) {
final DimensionsSpec dimensionsSpec = inputRowParser.getParseSpec().getDimensionsSpec();
final TimestampSpec timestampSpec = inputRowParser.getParseSpec().getTimestampSpec();
// exclude timestamp from dimensions by default, unless explicitly included in the list of dimensions
if (timestampSpec != null) {
final String timestampColumn = timestampSpec.getTimestampColumn();
if (!(dimensionsSpec.hasCustomDimensions() && dimensionsSpec.getDimensionNames().contains(timestampColumn))) {
dimensionExclusions.add(timestampColumn);
}
}
if (dimensionsSpec != null) {
final Set<String> metSet = Sets.newHashSet();
for (AggregatorFactory aggregator : aggregators) {
metSet.add(aggregator.getName());
}
final Set<String> dimSet = Sets.newHashSet(dimensionsSpec.getDimensionNames());
final Set<String> overlap = Sets.intersection(metSet, dimSet);
if (!overlap.isEmpty()) {
throw new IAE(
"Cannot have overlapping dimensions and metrics of the same name. Please change the name of the metric. Overlap: %s",
overlap
);
}
cachedParser = inputRowParser.withParseSpec(
inputRowParser.getParseSpec()
.withDimensionsSpec(
dimensionsSpec
.withDimensionExclusions(
Sets.difference(dimensionExclusions, dimSet)
)
)
);
} else {
cachedParser = inputRowParser;
}
} else {
log.warn("No parseSpec in parser has been specified.");
cachedParser = inputRowParser;
}
return cachedParser;
}
@JsonProperty("metricsSpec")
public AggregatorFactory[] getAggregators()
{
return aggregators;
}
@JsonProperty
public GranularitySpec getGranularitySpec()
{
return granularitySpec;
}
@JsonProperty
public TransformSpec getTransformSpec()
{
return transformSpec;
}
public DataSchema withGranularitySpec(GranularitySpec granularitySpec)
{
return new DataSchema(dataSource, parser, aggregators, granularitySpec, transformSpec, jsonMapper);
}
public DataSchema withTransformSpec(TransformSpec transformSpec)
{
return new DataSchema(dataSource, parser, aggregators, granularitySpec, transformSpec, jsonMapper);
}
@Override
public String toString()
{
return "DataSchema{" +
"dataSource='" + dataSource + '\'' +
", parser=" + parser +
", aggregators=" + Arrays.toString(aggregators) +
", granularitySpec=" + granularitySpec +
", transformSpec=" + transformSpec +
'}';
}
}
| |
/*
* Copyright 2015 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.
*/
package org.onosproject.segmentrouting;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.packet.Ethernet;
import org.onlab.packet.IPv4;
import org.onlab.util.KryoNamespace;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.event.Event;
import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
import org.onosproject.segmentrouting.grouphandler.NeighborSet;
import org.onosproject.segmentrouting.grouphandler.NeighborSetNextObjectiveStoreKey;
import org.onosproject.mastership.MastershipService;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Link;
import org.onosproject.net.Port;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.flowobjective.FlowObjectiveService;
import org.onosproject.net.group.GroupKey;
import org.onosproject.net.host.HostService;
import org.onosproject.net.intent.IntentService;
import org.onosproject.net.link.LinkEvent;
import org.onosproject.net.link.LinkListener;
import org.onosproject.net.link.LinkService;
import org.onosproject.net.packet.InboundPacket;
import org.onosproject.net.packet.PacketContext;
import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketService;
import org.onosproject.net.topology.TopologyService;
import org.onosproject.segmentrouting.config.NetworkConfigManager;
import org.onosproject.store.service.EventuallyConsistentMap;
import org.onosproject.store.service.EventuallyConsistentMapBuilder;
import org.onosproject.store.service.StorageService;
import org.onosproject.store.service.WallClockTimestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("ALL")
@Service
@Component(immediate = true)
public class SegmentRoutingManager implements SegmentRoutingService {
private static Logger log = LoggerFactory
.getLogger(SegmentRoutingManager.class);
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected CoreService coreService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected TopologyService topologyService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected PacketService packetService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected IntentService intentService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected HostService hostService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected DeviceService deviceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected FlowObjectiveService flowObjectiveService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected LinkService linkService;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected MastershipService mastershipService;
protected ArpHandler arpHandler = null;
protected IcmpHandler icmpHandler = null;
protected IpHandler ipHandler = null;
protected RoutingRulePopulator routingRulePopulator = null;
protected ApplicationId appId;
protected DeviceConfiguration deviceConfiguration = null;
private DefaultRoutingHandler defaultRoutingHandler = null;
private TunnelHandler tunnelHandler = null;
private PolicyHandler policyHandler = null;
private InternalPacketProcessor processor = new InternalPacketProcessor();
private InternalEventHandler eventHandler = new InternalEventHandler();
private ScheduledExecutorService executorService = Executors
.newScheduledThreadPool(1);
private static ScheduledFuture<?> eventHandlerFuture = null;
private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<Event>();
private Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<DeviceId, DefaultGroupHandler>();
// Per device next objective ID store with (device id + neighbor set) as key
private EventuallyConsistentMap<NeighborSetNextObjectiveStoreKey,
Integer> nsNextObjStore = null;
private EventuallyConsistentMap<String, Tunnel> tunnelStore = null;
private EventuallyConsistentMap<String, Policy> policyStore = null;
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
protected StorageService storageService;
private NetworkConfigManager networkConfigService = new NetworkConfigManager();;
private Object threadSchedulerLock = new Object();
private static int numOfEventsQueued = 0;
private static int numOfEventsExecuted = 0;
private static int numOfHandlerExecution = 0;
private static int numOfHandlerScheduled = 0;
private KryoNamespace.Builder kryoBuilder = null;
@Activate
protected void activate() {
appId = coreService
.registerApplication("org.onosproject.segmentrouting");
kryoBuilder = new KryoNamespace.Builder()
.register(NeighborSetNextObjectiveStoreKey.class,
NeighborSet.class,
DeviceId.class,
URI.class,
WallClockTimestamp.class,
org.onosproject.cluster.NodeId.class,
HashSet.class,
Tunnel.class,
DefaultTunnel.class,
Policy.class,
TunnelPolicy.class,
Policy.Type.class
);
log.debug("Creating EC map nsnextobjectivestore");
EventuallyConsistentMapBuilder<NeighborSetNextObjectiveStoreKey, Integer>
nsNextObjMapBuilder = storageService.eventuallyConsistentMapBuilder();
nsNextObjStore = nsNextObjMapBuilder
.withName("nsnextobjectivestore")
.withSerializer(kryoBuilder)
.withTimestampProvider((k, v) -> new WallClockTimestamp())
.build();
log.trace("Current size {}", nsNextObjStore.size());
EventuallyConsistentMapBuilder<String, Tunnel> tunnelMapBuilder =
storageService.eventuallyConsistentMapBuilder();
tunnelStore = tunnelMapBuilder
.withName("tunnelstore")
.withSerializer(kryoBuilder)
.withTimestampProvider((k, v) -> new WallClockTimestamp())
.build();
EventuallyConsistentMapBuilder<String, Policy> policyMapBuilder =
storageService.eventuallyConsistentMapBuilder();
policyStore = policyMapBuilder
.withName("policystore")
.withSerializer(kryoBuilder)
.withTimestampProvider((k, v) -> new WallClockTimestamp())
.build();
networkConfigService.init();
deviceConfiguration = new DeviceConfiguration(networkConfigService);
arpHandler = new ArpHandler(this);
icmpHandler = new IcmpHandler(this);
ipHandler = new IpHandler(this);
routingRulePopulator = new RoutingRulePopulator(this);
defaultRoutingHandler = new DefaultRoutingHandler(this);
tunnelHandler = new TunnelHandler(linkService, deviceConfiguration,
groupHandlerMap, tunnelStore);
policyHandler = new PolicyHandler(appId, deviceConfiguration,
flowObjectiveService, tunnelHandler, policyStore);
packetService.addProcessor(processor, PacketProcessor.ADVISOR_MAX + 2);
linkService.addListener(new InternalLinkListener());
deviceService.addListener(new InternalDeviceListener());
for (Device device : deviceService.getDevices()) {
//Irrespective whether the local is a MASTER or not for this device,
//create group handler instance and push default TTP flow rules.
//Because in a multi-instance setup, instances can initiate
//groups for any devices. Also the default TTP rules are needed
//to be pushed before inserting any IP table entries for any device
DefaultGroupHandler groupHandler = DefaultGroupHandler
.createGroupHandler(device.id(), appId,
deviceConfiguration, linkService,
flowObjectiveService,
nsNextObjStore);
groupHandlerMap.put(device.id(), groupHandler);
defaultRoutingHandler.populateTtpRules(device.id());
}
defaultRoutingHandler.startPopulationProcess();
log.info("Started");
}
@Deactivate
protected void deactivate() {
packetService.removeProcessor(processor);
processor = null;
log.info("Stopped");
}
@Override
public List<Tunnel> getTunnels() {
return tunnelHandler.getTunnels();
}
@Override
public TunnelHandler.Result createTunnel(Tunnel tunnel) {
return tunnelHandler.createTunnel(tunnel);
}
@Override
public TunnelHandler.Result removeTunnel(Tunnel tunnel) {
for (Policy policy: policyHandler.getPolicies()) {
if (policy.type() == Policy.Type.TUNNEL_FLOW) {
TunnelPolicy tunnelPolicy = (TunnelPolicy) policy;
if (tunnelPolicy.tunnelId().equals(tunnel.id())) {
log.warn("Cannot remove the tunnel used by a policy");
return TunnelHandler.Result.TUNNEL_IN_USE;
}
}
}
return tunnelHandler.removeTunnel(tunnel);
}
@Override
public PolicyHandler.Result removePolicy(Policy policy) {
return policyHandler.removePolicy(policy);
}
@Override
public PolicyHandler.Result createPolicy(Policy policy) {
return policyHandler.createPolicy(policy);
}
@Override
public List<Policy> getPolicies() {
return policyHandler.getPolicies();
}
/**
* Returns the tunnel object with the tunnel ID.
*
* @param tunnelId Tunnel ID
* @return Tunnel reference
*/
public Tunnel getTunnel(String tunnelId) {
return tunnelHandler.getTunnel(tunnelId);
}
/**
* Returns the GrouopKey object for the device and the NighborSet given.
*
* @param ns NeightborSet object for the GroupKey
* @return GroupKey object for the NeighborSet
*/
public GroupKey getGroupKey(NeighborSet ns) {
for (DefaultGroupHandler groupHandler : groupHandlerMap.values()) {
return groupHandler.getGroupKey(ns);
}
return null;
}
/**
* Returns the next objective ID for the NeighborSet given. If the nextObjectiveID does not exist,
* a new one is created and returned.
*
* @param deviceId Device ID
* @param ns NegighborSet
* @return next objective ID
*/
public int getNextObjectiveId(DeviceId deviceId, NeighborSet ns) {
if (groupHandlerMap.get(deviceId) != null) {
log.trace("getNextObjectiveId query in device {}", deviceId);
return groupHandlerMap
.get(deviceId).getNextObjectiveId(ns);
} else {
log.warn("getNextObjectiveId query in device {} not found", deviceId);
return -1;
}
}
private class InternalPacketProcessor implements PacketProcessor {
@Override
public void process(PacketContext context) {
if (context.isHandled()) {
return;
}
InboundPacket pkt = context.inPacket();
Ethernet ethernet = pkt.parsed();
if (ethernet.getEtherType() == Ethernet.TYPE_ARP) {
arpHandler.processPacketIn(pkt);
} else if (ethernet.getEtherType() == Ethernet.TYPE_IPV4) {
IPv4 ipPacket = (IPv4) ethernet.getPayload();
ipHandler.addToPacketBuffer(ipPacket);
if (ipPacket.getProtocol() == IPv4.PROTOCOL_ICMP) {
icmpHandler.processPacketIn(pkt);
} else {
ipHandler.processPacketIn(pkt);
}
}
}
}
private class InternalLinkListener implements LinkListener {
@Override
public void event(LinkEvent event) {
if (event.type() == LinkEvent.Type.LINK_ADDED
|| event.type() == LinkEvent.Type.LINK_REMOVED) {
log.debug("Event {} received from Link Service", event.type());
scheduleEventHandlerIfNotScheduled(event);
}
}
}
private class InternalDeviceListener implements DeviceListener {
@Override
public void event(DeviceEvent event) {
/*if (mastershipService.getLocalRole(event.subject().id()) != MastershipRole.MASTER) {
log.debug("Local role {} is not MASTER for device {}",
mastershipService.getLocalRole(event.subject().id()),
event.subject().id());
return;
}*/
switch (event.type()) {
case DEVICE_ADDED:
case PORT_REMOVED:
case DEVICE_UPDATED:
case DEVICE_AVAILABILITY_CHANGED:
log.debug("Event {} received from Device Service", event.type());
scheduleEventHandlerIfNotScheduled(event);
break;
default:
}
}
}
private void scheduleEventHandlerIfNotScheduled(Event event) {
synchronized (threadSchedulerLock) {
eventQueue.add(event);
numOfEventsQueued++;
if ((numOfHandlerScheduled - numOfHandlerExecution) == 0) {
//No pending scheduled event handling threads. So start a new one.
eventHandlerFuture = executorService
.schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
numOfHandlerScheduled++;
}
log.trace("numOfEventsQueued {}, numOfEventHanlderScheduled {}",
numOfEventsQueued,
numOfHandlerScheduled);
}
}
private class InternalEventHandler implements Runnable {
@Override
public void run() {
try {
while (true) {
Event event = null;
synchronized (threadSchedulerLock) {
if (!eventQueue.isEmpty()) {
event = eventQueue.poll();
numOfEventsExecuted++;
} else {
numOfHandlerExecution++;
log.debug("numOfHandlerExecution {} numOfEventsExecuted {}",
numOfHandlerExecution, numOfEventsExecuted);
break;
}
}
if (event.type() == LinkEvent.Type.LINK_ADDED) {
processLinkAdded((Link) event.subject());
} else if (event.type() == LinkEvent.Type.LINK_REMOVED) {
processLinkRemoved((Link) event.subject());
//} else if (event.type() == GroupEvent.Type.GROUP_ADDED) {
// processGroupAdded((Group) event.subject());
} else if (event.type() == DeviceEvent.Type.DEVICE_ADDED ||
event.type() == DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED ||
event.type() == DeviceEvent.Type.DEVICE_UPDATED) {
if (deviceService.isAvailable(((Device) event.subject()).id())) {
processDeviceAdded((Device) event.subject());
}
} else if (event.type() == DeviceEvent.Type.PORT_REMOVED) {
processPortRemoved((Device) event.subject(),
((DeviceEvent) event).port());
} else {
log.warn("Unhandled event type: {}", event.type());
}
}
} catch (Exception e) {
log.error("SegmentRouting event handler "
+ "thread thrown an exception: {}", e);
}
}
}
private void processLinkAdded(Link link) {
log.debug("A new link {} was added", link.toString());
//Irrespective whether the local is a MASTER or not for this device,
//create group handler instance and push default TTP flow rules.
//Because in a multi-instance setup, instances can initiate
//groups for any devices. Also the default TTP rules are needed
//to be pushed before inserting any IP table entries for any device
DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
.deviceId());
if (groupHandler != null) {
groupHandler.linkUp(link);
} else {
Device device = deviceService.getDevice(link.src().deviceId());
if (device != null) {
log.warn("processLinkAdded: Link Added "
+ "Notification without Device Added "
+ "event, still handling it");
processDeviceAdded(device);
groupHandler = groupHandlerMap.get(link.src()
.deviceId());
groupHandler.linkUp(link);
}
}
log.trace("Starting optimized route population process");
defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(null);
//log.trace("processLinkAdded: re-starting route population process");
//defaultRoutingHandler.startPopulationProcess();
}
private void processLinkRemoved(Link link) {
log.debug("A link {} was removed", link.toString());
DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src().deviceId());
if (groupHandler != null) {
groupHandler.portDown(link.src().port());
}
log.trace("Starting optimized route population process");
defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link);
//log.trace("processLinkRemoved: re-starting route population process");
//defaultRoutingHandler.startPopulationProcess();
}
private void processDeviceAdded(Device device) {
log.debug("A new device with ID {} was added", device.id());
//Irrespective whether the local is a MASTER or not for this device,
//create group handler instance and push default TTP flow rules.
//Because in a multi-instance setup, instances can initiate
//groups for any devices. Also the default TTP rules are needed
//to be pushed before inserting any IP table entries for any device
DefaultGroupHandler dgh = DefaultGroupHandler.
createGroupHandler(device.id(),
appId,
deviceConfiguration,
linkService,
flowObjectiveService,
nsNextObjStore);
groupHandlerMap.put(device.id(), dgh);
defaultRoutingHandler.populateTtpRules(device.id());
}
private void processPortRemoved(Device device, Port port) {
log.debug("Port {} was removed", port.toString());
DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
if (groupHandler != null) {
groupHandler.portDown(port.number());
}
}
}
| |
/**********************************************************************
Copyright (c) 2005 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.tests;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import org.datanucleus.tests.JDOPersistenceTestCase;
import org.jpox.samples.one_many.map.MapFKKeyItem;
import org.jpox.samples.one_many.map.MapFKValueItem;
import org.jpox.samples.one_many.map.MapHolder;
/**
* Series of tests for Maps using ForeignKey relations.
*
* @version $Revision: 1.1 $
*/
public class MapForeignKeyTest extends JDOPersistenceTestCase
{
/**
* @param name
*/
public MapForeignKeyTest(String name)
{
super(name);
}
/**
* Test for persistence of a Map with the key stored in the value object.
*/
public void testMapWithKeyAsFieldInValue()
{
try
{
Object containerId = null;
MapHolder container = new MapHolder();
MapFKValueItem item1 = new MapFKValueItem("First", "First element", "Item1");
MapFKValueItem item3 = new MapFKValueItem("Third", "Third element", "Item3");
MapFKValueItem item2 = new MapFKValueItem("Second", "Second element", "Item2");
container.getFkMapKey().put(item1.getKey(), item1);
container.getFkMapKey().put(item3.getKey(), item3);
container.getFkMapKey().put(item2.getKey(), item2);
// Persist the objects
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
pm.makePersistent(container);
tx.commit();
containerId = JDOHelper.getObjectId(container);
}
catch (Exception e)
{
e.printStackTrace();
fail(e.toString());
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
pm.close();
}
// Retrieve the object and inspect it
pm = pmf.getPersistenceManager();
tx = pm.currentTransaction();
try
{
tx.begin();
container = (MapHolder)pm.getObjectById(containerId);
assertTrue("Container map was not found!", container != null);
Map map = container.getFkMapKey();
assertEquals("Number of items in the container map is incorrect", map.size(), 3);
// Check Entry set
Set entries = map.entrySet();
Iterator entryIter = entries.iterator();
while (entryIter.hasNext())
{
Map.Entry entry = (Map.Entry)entryIter.next();
MapFKValueItem item = (MapFKValueItem)entry.getValue();
if (entry.getKey().equals("Item1"))
{
assertEquals("item has incorrect name for key Item1", item.getName(), "First");
}
else if (entry.getKey().equals("Item2"))
{
assertEquals("item has incorrect name for key Item2", item.getName(), "Second");
}
else if (entry.getKey().equals("Item3"))
{
assertEquals("item has incorrect name for key Item3", item.getName(), "Third");
}
else
{
fail("Unknown Map entry found with key " + entry.getKey());
}
}
// Check Key set
Set keys = map.keySet();
assertEquals("Number of keys in Map.keySet() is incorrect", keys.size(), 3);
Iterator keyIter = keys.iterator();
boolean item1Present = false;
boolean item2Present = false;
boolean item3Present = false;
while (keyIter.hasNext())
{
Object obj = keyIter.next();
assertEquals("Type of value objects returned from Map.keySet().iterator() is incorrect",
obj.getClass().getName(), String.class.getName());
String key = (String)obj;
if (key.equals("Item1"))
{
item1Present = true;
}
else if (key.equals("Item2"))
{
item2Present = true;
}
else if (key.equals("Item3"))
{
item3Present = true;
}
}
assertTrue("Item1 was not present in the keySet", item1Present);
assertTrue("Item2 was not present in the keySet", item2Present);
assertTrue("Item3 was not present in the keySet", item3Present);
// Check Value set
Collection values = map.values();
assertEquals("Number of values in Map.values() is incorrect", values.size(), 3);
Iterator valueIter = values.iterator();
item1Present = false;
item2Present = false;
item3Present = false;
while (valueIter.hasNext())
{
Object obj = valueIter.next();
assertEquals("Type of value objects returned from Map.values().iterator() is incorrect",
obj.getClass().getName(), MapFKValueItem.class.getName());
MapFKValueItem value = (MapFKValueItem)obj;
if (value.getName().equals("First"))
{
item1Present = true;
}
else if (value.getName().equals("Second"))
{
item2Present = true;
}
else if (value.getName().equals("Third"))
{
item3Present = true;
}
}
assertTrue("Item1 was not present in the values()", item1Present);
assertTrue("Item2 was not present in the values()", item2Present);
assertTrue("Item3 was not present in the values()", item3Present);
tx.commit();
}
catch (Exception e)
{
e.printStackTrace();
fail(e.toString());
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
pm.close();
}
}
finally
{
// Clean out our data
clean(MapHolder.class);
}
}
/**
* Test for persistence of a Map with the value stored in the key object.
*/
public void testMapWithValueAsFieldInKey()
{
try
{
Object containerId = null;
MapHolder container = new MapHolder();
MapFKKeyItem item1 = new MapFKKeyItem("First", "First element", "Item1");
MapFKKeyItem item3 = new MapFKKeyItem("Third", "Third element", "Item3");
MapFKKeyItem item2 = new MapFKKeyItem("Second", "Second element", "Item2");
container.getFkMapValue().put(item1, item1.getValue());
container.getFkMapValue().put(item3, item3.getValue());
container.getFkMapValue().put(item2, item2.getValue());
// Persist the objects
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
pm.makePersistent(container);
tx.commit();
containerId = JDOHelper.getObjectId(container);
}
catch (Exception e)
{
e.printStackTrace();
fail(e.toString());
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
pm.close();
}
// Retrieve the object and inspect it
pm = pmf.getPersistenceManager();
tx = pm.currentTransaction();
try
{
tx.begin();
container = (MapHolder)pm.getObjectById(containerId);
assertTrue("Container map was not found!", container != null);
Map map = container.getFkMapValue();
assertEquals("Number of items in the container map is incorrect", map.size(), 3);
// Check Entry set
Set entries = map.entrySet();
Iterator entryIter = entries.iterator();
while (entryIter.hasNext())
{
Map.Entry entry = (Map.Entry)entryIter.next();
MapFKKeyItem item = (MapFKKeyItem)entry.getKey();
if (entry.getValue().equals("Item1"))
{
assertEquals("item has incorrect name for value Item1", item.getName(), "First");
}
else if (entry.getValue().equals("Item2"))
{
assertEquals("item has incorrect name for value Item2", item.getName(), "Second");
}
else if (entry.getValue().equals("Item3"))
{
assertEquals("item has incorrect name for value Item3", item.getName(), "Third");
}
else
{
fail("Unknown Map entry found with value " + entry.getValue());
}
}
// Check Key set
Set keys = map.keySet();
assertEquals("Number of keys in Map.keySet() is incorrect", keys.size(), 3);
Iterator keyIter = keys.iterator();
boolean item1Present = false;
boolean item2Present = false;
boolean item3Present = false;
while (keyIter.hasNext())
{
Object obj = keyIter.next();
assertEquals("Type of key objects returned from Map.keySet().iterator() is incorrect",
obj.getClass().getName(), MapFKKeyItem.class.getName());
MapFKKeyItem key = (MapFKKeyItem)obj;
if (key.getName().equals("First"))
{
item1Present = true;
}
else if (key.getName().equals("Second"))
{
item2Present = true;
}
else if (key.getName().equals("Third"))
{
item3Present = true;
}
}
assertTrue("Item1 was not present in the keySet", item1Present);
assertTrue("Item2 was not present in the keySet", item2Present);
assertTrue("Item3 was not present in the keySet", item3Present);
// Check Value set
Collection values = map.values();
assertEquals("Number of values in Map.values() is incorrect", values.size(), 3);
Iterator valueIter = values.iterator();
item1Present = false;
item2Present = false;
item3Present = false;
while (valueIter.hasNext())
{
Object obj = valueIter.next();
assertEquals("Type of value objects returned from Map.values().iterator() is incorrect",
obj.getClass().getName(), String.class.getName());
String value = (String)obj;
if (value.equals("Item1"))
{
item1Present = true;
}
else if (value.equals("Item2"))
{
item2Present = true;
}
else if (value.equals("Item3"))
{
item3Present = true;
}
}
assertTrue("Item1 was not present in the values()", item1Present);
assertTrue("Item2 was not present in the values()", item2Present);
assertTrue("Item3 was not present in the values()", item3Present);
tx.commit();
}
catch (Exception e)
{
e.printStackTrace();
fail(e.toString());
}
finally
{
if (tx.isActive())
{
tx.rollback();
}
pm.close();
}
}
finally
{
// Clean out our data
clean(MapHolder.class);
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;
import javax.net.ssl.SSLContext;
import java.security.AccessController;
import java.security.NoSuchAlgorithmException;
import java.security.PrivilegedAction;
import java.util.List;
import java.util.Objects;
/**
* Helps creating a new {@link RestClient}. Allows to set the most common http client configuration options when internally
* creating the underlying {@link org.apache.http.nio.client.HttpAsyncClient}. Also allows to provide an externally created
* {@link org.apache.http.nio.client.HttpAsyncClient} in case additional customization is needed.
*/
public final class RestClientBuilder {
public static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 1000;
public static final int DEFAULT_SOCKET_TIMEOUT_MILLIS = 30000;
public static final int DEFAULT_MAX_CONN_PER_ROUTE = 10;
public static final int DEFAULT_MAX_CONN_TOTAL = 30;
private static final Header[] EMPTY_HEADERS = new Header[0];
private final List<Node> nodes;
private Header[] defaultHeaders = EMPTY_HEADERS;
private RestClient.FailureListener failureListener;
private HttpClientConfigCallback httpClientConfigCallback;
private RequestConfigCallback requestConfigCallback;
private String pathPrefix;
private NodeSelector nodeSelector = NodeSelector.ANY;
private boolean strictDeprecationMode = false;
/**
* Creates a new builder instance and sets the hosts that the client will send requests to.
*
* @throws IllegalArgumentException if {@code nodes} is {@code null} or empty.
*/
RestClientBuilder(List<Node> nodes) {
if (nodes == null || nodes.isEmpty()) {
throw new IllegalArgumentException("nodes must not be null or empty");
}
for (Node node : nodes) {
if (node == null) {
throw new IllegalArgumentException("node cannot be null");
}
}
this.nodes = nodes;
}
/**
* Sets the default request headers, which will be sent along with each request.
* <p>
* Request-time headers will always overwrite any default headers.
*
* @throws NullPointerException if {@code defaultHeaders} or any header is {@code null}.
*/
public RestClientBuilder setDefaultHeaders(Header[] defaultHeaders) {
Objects.requireNonNull(defaultHeaders, "defaultHeaders must not be null");
for (Header defaultHeader : defaultHeaders) {
Objects.requireNonNull(defaultHeader, "default header must not be null");
}
this.defaultHeaders = defaultHeaders;
return this;
}
/**
* Sets the {@link RestClient.FailureListener} to be notified for each request failure
*
* @throws NullPointerException if {@code failureListener} is {@code null}.
*/
public RestClientBuilder setFailureListener(RestClient.FailureListener failureListener) {
Objects.requireNonNull(failureListener, "failureListener must not be null");
this.failureListener = failureListener;
return this;
}
/**
* Sets the {@link HttpClientConfigCallback} to be used to customize http client configuration
*
* @throws NullPointerException if {@code httpClientConfigCallback} is {@code null}.
*/
public RestClientBuilder setHttpClientConfigCallback(HttpClientConfigCallback httpClientConfigCallback) {
Objects.requireNonNull(httpClientConfigCallback, "httpClientConfigCallback must not be null");
this.httpClientConfigCallback = httpClientConfigCallback;
return this;
}
/**
* Sets the {@link RequestConfigCallback} to be used to customize http client configuration
*
* @throws NullPointerException if {@code requestConfigCallback} is {@code null}.
*/
public RestClientBuilder setRequestConfigCallback(RequestConfigCallback requestConfigCallback) {
Objects.requireNonNull(requestConfigCallback, "requestConfigCallback must not be null");
this.requestConfigCallback = requestConfigCallback;
return this;
}
/**
* Sets the path's prefix for every request used by the http client.
* <p>
* For example, if this is set to "/my/path", then any client request will become <code>"/my/path/" + endpoint</code>.
* <p>
* In essence, every request's {@code endpoint} is prefixed by this {@code pathPrefix}. The path prefix is useful for when
* Elasticsearch is behind a proxy that provides a base path or a proxy that requires all paths to start with '/';
* it is not intended for other purposes and it should not be supplied in other scenarios.
*
* @throws NullPointerException if {@code pathPrefix} is {@code null}.
* @throws IllegalArgumentException if {@code pathPrefix} is empty, or ends with more than one '/'.
*/
public RestClientBuilder setPathPrefix(String pathPrefix) {
Objects.requireNonNull(pathPrefix, "pathPrefix must not be null");
if (pathPrefix.isEmpty()) {
throw new IllegalArgumentException("pathPrefix must not be empty");
}
String cleanPathPrefix = pathPrefix;
if (cleanPathPrefix.startsWith("/") == false) {
cleanPathPrefix = "/" + cleanPathPrefix;
}
// best effort to ensure that it looks like "/base/path" rather than "/base/path/"
if (cleanPathPrefix.endsWith("/") && cleanPathPrefix.length() > 1) {
cleanPathPrefix = cleanPathPrefix.substring(0, cleanPathPrefix.length() - 1);
if (cleanPathPrefix.endsWith("/")) {
throw new IllegalArgumentException("pathPrefix is malformed. too many trailing slashes: [" + pathPrefix + "]");
}
}
this.pathPrefix = cleanPathPrefix;
return this;
}
/**
* Sets the {@link NodeSelector} to be used for all requests.
* @throws NullPointerException if the provided nodeSelector is null
*/
public RestClientBuilder setNodeSelector(NodeSelector nodeSelector) {
Objects.requireNonNull(nodeSelector, "nodeSelector must not be null");
this.nodeSelector = nodeSelector;
return this;
}
/**
* Whether the REST client should return any response containing at least
* one warning header as a failure.
*/
public RestClientBuilder setStrictDeprecationMode(boolean strictDeprecationMode) {
this.strictDeprecationMode = strictDeprecationMode;
return this;
}
/**
* Creates a new {@link RestClient} based on the provided configuration.
*/
public RestClient build() {
if (failureListener == null) {
failureListener = new RestClient.FailureListener();
}
CloseableHttpAsyncClient httpClient = AccessController.doPrivileged(
(PrivilegedAction<CloseableHttpAsyncClient>) this::createHttpClient);
RestClient restClient = new RestClient(httpClient, defaultHeaders, nodes,
pathPrefix, failureListener, nodeSelector, strictDeprecationMode);
httpClient.start();
return restClient;
}
private CloseableHttpAsyncClient createHttpClient() {
//default timeouts are all infinite
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS)
.setSocketTimeout(DEFAULT_SOCKET_TIMEOUT_MILLIS);
if (requestConfigCallback != null) {
requestConfigBuilder = requestConfigCallback.customizeRequestConfig(requestConfigBuilder);
}
try {
HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClientBuilder.create().setDefaultRequestConfig(requestConfigBuilder.build())
//default settings for connection pooling may be too constraining
.setMaxConnPerRoute(DEFAULT_MAX_CONN_PER_ROUTE).setMaxConnTotal(DEFAULT_MAX_CONN_TOTAL)
.setSSLContext(SSLContext.getDefault())
.setTargetAuthenticationStrategy(new PersistentCredentialsAuthenticationStrategy());
if (httpClientConfigCallback != null) {
httpClientBuilder = httpClientConfigCallback.customizeHttpClient(httpClientBuilder);
}
final HttpAsyncClientBuilder finalBuilder = httpClientBuilder;
return AccessController.doPrivileged((PrivilegedAction<CloseableHttpAsyncClient>) finalBuilder::build);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("could not create the default ssl context", e);
}
}
/**
* Callback used the default {@link RequestConfig} being set to the {@link CloseableHttpClient}
* @see HttpClientBuilder#setDefaultRequestConfig
*/
public interface RequestConfigCallback {
/**
* Allows to customize the {@link RequestConfig} that will be used with each request.
* It is common to customize the different timeout values through this method without losing any other useful default
* value that the {@link RestClientBuilder} internally sets.
*/
RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder);
}
/**
* Callback used to customize the {@link CloseableHttpClient} instance used by a {@link RestClient} instance.
* Allows to customize default {@link RequestConfig} being set to the client and any parameter that
* can be set through {@link HttpClientBuilder}
*/
public interface HttpClientConfigCallback {
/**
* Allows to customize the {@link CloseableHttpAsyncClient} being created and used by the {@link RestClient}.
* Commonly used to customize the default {@link org.apache.http.client.CredentialsProvider} for authentication
* or the {@link SchemeIOSessionStrategy} for communication through ssl without losing any other useful default
* value that the {@link RestClientBuilder} internally sets, like connection pooling.
*/
HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder);
}
}
| |
/*
* 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 com.gemstone.gemfire.distributed.internal;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.xpath.XPathExpressionException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.logging.log4j.Logger;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import com.gemstone.gemfire.CancelException;
import com.gemstone.gemfire.LogWriter;
import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.DataPolicy;
import com.gemstone.gemfire.cache.DiskStore;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.Scope;
import com.gemstone.gemfire.cache.execute.ResultCollector;
import com.gemstone.gemfire.distributed.DistributedLockService;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.distributed.internal.locks.DLockService;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.InternalRegionArguments;
import com.gemstone.gemfire.internal.cache.persistence.PersistentMemberID;
import com.gemstone.gemfire.internal.cache.persistence.PersistentMemberManager;
import com.gemstone.gemfire.internal.cache.persistence.PersistentMemberPattern;
import com.gemstone.gemfire.internal.cache.xmlcache.CacheXml;
import com.gemstone.gemfire.internal.cache.xmlcache.CacheXmlGenerator;
import com.gemstone.gemfire.internal.lang.StringUtils;
import com.gemstone.gemfire.internal.logging.LogService;
import com.gemstone.gemfire.management.internal.cli.CliUtil;
import com.gemstone.gemfire.management.internal.cli.functions.ImportSharedConfigurationArtifactsFunction;
import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
import com.gemstone.gemfire.management.internal.configuration.callbacks.ConfigurationChangeListener;
import com.gemstone.gemfire.management.internal.configuration.domain.Configuration;
import com.gemstone.gemfire.management.internal.configuration.domain.SharedConfigurationStatus;
import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;
import com.gemstone.gemfire.management.internal.configuration.functions.GetAllJarsFunction;
import com.gemstone.gemfire.management.internal.configuration.messages.ConfigurationRequest;
import com.gemstone.gemfire.management.internal.configuration.messages.ConfigurationResponse;
import com.gemstone.gemfire.management.internal.configuration.messages.SharedConfigurationStatusResponse;
import com.gemstone.gemfire.management.internal.configuration.utils.XmlUtils;
import com.gemstone.gemfire.management.internal.configuration.utils.ZipUtils;
/*********
*
* @author bansods
*
*/
@SuppressWarnings("deprecation")
public class SharedConfiguration {
private static final Logger logger = LogService.getLogger();
static class JarFileFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
}
/****
* Name of the directory where the shared configuration artifacts are stored
*/
public static final String CLUSTER_CONFIG_ARTIFACTS_DIR_NAME = "cluster_config";
public static final String CLUSTER_CONFIG_DISK_STORE_NAME = "cluster_config";
public static String CONFIG_DIR_PATH;//FilenameUtils.concat(System.getProperty("user.dir"), CONFIG_ARTIFACTS_DIR_NAME);
public static final String CLUSTER_CONFIG_DISK_DIR_PREFIX = "ConfigDiskDir_";
public static final String CLUSTER_CONFIG = "cluster";
/***
* Name of the lock service used for shared configuration
*/
public static final String SHARED_CONFIG_LOCK_SERVICE_NAME = "__CLUSTER_CONFIG_LS";
/***
* Name of the lock for locking the shared configuration
*/
public static final String SHARED_CONFIG_LOCK_NAME = "__CLUSTER_CONFIG_LOCK";
/***
* Name of the region which is used to store the configuration information
*/
public static final String CONFIG_REGION_NAME = "_ConfigurationRegion";
public String CONFIG_DISK_DIR_NAME;
public String CONFIG_DISK_DIR_PATH;;
private final Set<PersistentMemberPattern> newerSharedConfigurationLocatorInfo = new HashSet<PersistentMemberPattern>();
private final AtomicReference<SharedConfigurationStatus> status = new AtomicReference<SharedConfigurationStatus>();
private static final GetAllJarsFunction getAllJarsFunction = new GetAllJarsFunction();
private static final JarFileFilter jarFileFilter = new JarFileFilter();
private GemFireCacheImpl cache;
private final DistributedLockService sharedConfigLockingService;
/****
* Gets or creates (if not created) shared configuration lock service
* @return DistributedLockService
*/
public static DistributedLockService getSharedConfigLockService(DistributedSystem ds) {
DistributedLockService sharedConfigDls = DLockService.getServiceNamed(SHARED_CONFIG_LOCK_SERVICE_NAME);
try {
if (sharedConfigDls == null) {
sharedConfigDls = DLockService.create(SHARED_CONFIG_LOCK_SERVICE_NAME, (InternalDistributedSystem) ds, true, true);
}
} catch (IllegalArgumentException e) {
return DLockService.getServiceNamed(SHARED_CONFIG_LOCK_SERVICE_NAME);
}
return sharedConfigDls;
}
/**
* Returns an array containing the names of the subdirectories in a given directory
* @param path Path of the directory whose subdirectories are listed
* @return String[] names of first level subdirectories, null if no subdirectories are found or if the path is incorrect
*/
private static String[] getSubdirectories(String path) {
File directory = new File(path);
return directory.list(DirectoryFileFilter.INSTANCE);
}
public SharedConfiguration(Cache cache) throws IOException {
this.cache = (GemFireCacheImpl)cache;
CONFIG_DISK_DIR_NAME = CLUSTER_CONFIG_DISK_DIR_PREFIX + cache.getDistributedSystem().getName();
String clusterConfigDir = cache.getDistributedSystem().getProperties().getProperty(DistributionConfig.CLUSTER_CONFIGURATION_DIR);
if (StringUtils.isBlank(clusterConfigDir)) {
clusterConfigDir = System.getProperty("user.dir");
} else {
File diskDir = new File(clusterConfigDir);
if (!diskDir.exists() && !diskDir.mkdirs()) {
throw new IOException("Cannot create directory : " + clusterConfigDir);
}
clusterConfigDir = diskDir.getCanonicalPath();
}
CONFIG_DISK_DIR_PATH = FilenameUtils.concat(clusterConfigDir, CONFIG_DISK_DIR_NAME);
CONFIG_DIR_PATH = FilenameUtils.concat(clusterConfigDir, CLUSTER_CONFIG_ARTIFACTS_DIR_NAME);
sharedConfigLockingService = getSharedConfigLockService(cache.getDistributedSystem());
status.set(SharedConfigurationStatus.NOT_STARTED);
}
/*****
* Add jar information into the shared configuration and save the jars in the file system
* @param jarNames
* @param jarBytes
* @param groups
* @return true on success
*/
public boolean addJars(String []jarNames, byte[][]jarBytes, String[]groups) {
boolean success = true;
try {
if (groups == null) {
groups = new String[] {SharedConfiguration.CLUSTER_CONFIG};
}
Region<String, Configuration> configRegion = getConfigurationRegion();
for (String group : groups) {
Configuration configuration = (Configuration) configRegion.get(group);
if (configuration == null) {
configuration = new Configuration(group);
writeConfig(configuration);
}
configuration.addJarNames(jarNames);
configRegion.put(group, configuration);
String groupDir = FilenameUtils.concat(CONFIG_DIR_PATH, group);
writeJarFiles(groupDir, jarNames, jarBytes);
}
} catch (Exception e) {
success = false;
logger.info(e.getMessage(), e);
}
return success;
}
/***
* Adds/replaces the xml entity in the shared configuration
* @param xmlEntity
* @param groups
* @throws Exception
*/
public void addXmlEntity(XmlEntity xmlEntity, String[] groups) throws Exception {
Region<String, Configuration> configRegion = getConfigurationRegion();
if (groups == null || groups.length == 0) {
groups = new String[]{SharedConfiguration.CLUSTER_CONFIG};
}
for (String group : groups) {
Configuration configuration = (Configuration) configRegion.get(group);
if (configuration == null) {
configuration = new Configuration(group);
}
String xmlContent = configuration.getCacheXmlContent();
if (xmlContent == null || xmlContent.isEmpty()) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
CacheXmlGenerator.generateDefault(pw);
xmlContent = sw.toString();
}
final Document doc = createAndUpgradeDocumentFromXml(xmlContent);
XmlUtils.addNewNode(doc, xmlEntity);
configuration.setCacheXmlContent(XmlUtils.prettyXml(doc));
configRegion.put(group, configuration);
writeConfig(configuration);
}
}
/**
* Create a {@link Document} using
* {@link XmlUtils#createDocumentFromXml(String)} and if the version attribute
* is not equal to the current version then update the XML to the current
* schema and return the document.
*
* @param xmlContent
* XML content to load and upgrade.
* @return {@link Document} from xmlContent.
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
* @throws XPathExpressionException
* @since 8.1
*/
// UnitTest SharedConfigurationJUnitTest.testCreateAndUpgradeDocumentFromXml
static Document createAndUpgradeDocumentFromXml(final String xmlContent) throws SAXException, ParserConfigurationException, IOException, XPathExpressionException {
Document doc = XmlUtils.createDocumentFromXml(xmlContent);
if (!CacheXml.VERSION_LATEST.equals(XmlUtils.getAttribute(doc.getDocumentElement(), CacheXml.VERSION, CacheXml.NAMESPACE))) {
doc = XmlUtils.upgradeSchema(doc, CacheXml.NAMESPACE, CacheXml.LATEST_SCHEMA_LOCATION, CacheXml.VERSION_LATEST);
}
return doc;
}
public void clearSharedConfiguration() throws Exception {
Region<String, Configuration> configRegion = getConfigurationRegion();
if (configRegion != null) {
configRegion.clear();
}
}
/*****
* Creates the shared configuration service
* @param loadSharedConfigFromDir when set to true, loads the configuration from the share_config directory
* @throws Exception
*/
public void initSharedConfiguration(boolean loadSharedConfigFromDir) throws Exception {
status.set(SharedConfigurationStatus.STARTED);
Region<String, Configuration> configRegion = this.getConfigurationRegion();
if (loadSharedConfigFromDir) {
lockSharedConfiguration();
try {
logger.info("Reading cluster configuration from '{}' directory", SharedConfiguration.CLUSTER_CONFIG_ARTIFACTS_DIR_NAME);
Map<String, Configuration> sharedConfigMap = this.readSharedConfigurationFromDisk();
final DM dm = cache.getDistributedSystem().getDistributionManager();
if (dm.getNormalDistributionManagerIds().isEmpty()) {
Set<DistributedMember> locatorsWithSC = new HashSet<DistributedMember>(dm.getAllHostedLocatorsWithSharedConfiguration().keySet());
//Send the config to other locators which host the shared configuration.
if (!locatorsWithSC.isEmpty()) {
final ImportSharedConfigurationArtifactsFunction fn = new ImportSharedConfigurationArtifactsFunction();
final Date date = new Date();
String zipFileName = CliStrings.format(CliStrings.EXPORT_SHARED_CONFIG__FILE__NAME, new Timestamp(date.getTime()).toString());
try {
ZipUtils.zip(getSharedConfigurationDirPath(), zipFileName);
File zipFile = new File(zipFileName);
byte[] zipBytes = FileUtils.readFileToByteArray(zipFile);
Object [] args = new Object[] {zipFileName, zipBytes};
CliUtil.executeFunction(fn, args, locatorsWithSC);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
//Clear the configuration region and load the configuration read from the 'shared_config' directory
configRegion.clear();
configRegion.putAll(sharedConfigMap);
}
}finally {
unlockSharedConfiguration();
}
} else {
//Write out the existing configuration into the 'shared_config' directory
//And get deployed jars from other locators.
lockSharedConfiguration();
try {
Set<Entry<String, Configuration>> configEntries = configRegion.entrySet();
for (Entry<String, Configuration> configEntry : configEntries) {
Configuration configuration = configEntry.getValue();
try {
this.writeConfig(configuration);
} catch (Exception e) {
logger.info(e.getMessage(), e);
}
}
logger.info("Completed writing the shared configuration to 'cluster_config' directory");
this.getAllJarsFromOtherLocators();
} finally {
unlockSharedConfiguration();
}
}
status.set(SharedConfigurationStatus.RUNNING);
}
public boolean lockSharedConfiguration() {
return sharedConfigLockingService.lock(SHARED_CONFIG_LOCK_NAME, -1, -1);
}
public void unlockSharedConfiguration() {
sharedConfigLockingService.unlock(SHARED_CONFIG_LOCK_NAME);
}
/****
* Creates a ConfigurationResponse based on the configRequest, configuration response contains the requested shared configuration
* This method locks the SharedConfiguration
* @param configRequest
* @return ConfigurationResponse
* @throws Exception
*/
public ConfigurationResponse createConfigurationReponse(ConfigurationRequest configRequest) throws Exception {
ConfigurationResponse configResponse = new ConfigurationResponse();
for (int i=0; i<configRequest.getNumAttempts(); i++) {
boolean isLocked = sharedConfigLockingService.lock(SHARED_CONFIG_LOCK_NAME, 5000, 5000);
try {
if (isLocked) {
logger.info("Building up configuration response with following configurations");
Set<String> groups = configRequest.getGroups();
groups.add(SharedConfiguration.CLUSTER_CONFIG);
for (String group : groups) {
Configuration configuration = getConfiguration(group);
configResponse.addConfiguration(configuration);
}
Object[] jars = getAllJars(groups);
if (jars != null) {
String[] jarNames = (String[])jars[0];
byte[][] jarBytes = (byte[][]) jars[1];
configResponse.addJarsToBeDeployed(jarNames, jarBytes);
}
configResponse.setFailedToGetSharedConfig(false);
return configResponse;
}
} finally {
sharedConfigLockingService.unlock(SHARED_CONFIG_LOCK_NAME);
}
}
configResponse.setFailedToGetSharedConfig(true);
return configResponse;
}
/***
* Create a response containing the status of the Shared configuration and information about other locators containing newer
* shared configuration data (if at all)
* @return {@link SharedConfigurationStatusResponse} containing the {@link SharedConfigurationStatus}
*/
public SharedConfigurationStatusResponse createStatusResponse() {
SharedConfigurationStatusResponse response = new SharedConfigurationStatusResponse();
response.setStatus(getStatus());
response.addWaitingLocatorInfo(newerSharedConfigurationLocatorInfo);
return response;
}
/*****
* Deletes the xml entity from the shared configuration.
* @param xmlEntity
* @param groups
* @throws Exception
*/
public void deleteXmlEntity (XmlEntity xmlEntity, String[] groups) throws Exception {
Region<String, Configuration> configRegion = getConfigurationRegion();
//No group is specified, so delete in every single group if it exists.
if (groups == null) {
Set<String> groupSet = configRegion.keySet();
groups = groupSet.toArray(new String[groupSet.size()]);
}
for (String group : groups) {
Configuration configuration = (Configuration) configRegion.get(group);
if (configuration != null) {
String xmlContent = configuration.getCacheXmlContent();
if (xmlContent != null && !xmlContent.isEmpty()) {
Document doc = createAndUpgradeDocumentFromXml(xmlContent);
XmlUtils.deleteNode(doc, xmlEntity);
configuration.setCacheXmlContent(XmlUtils.prettyXml(doc));
configRegion.put(group, configuration);
writeConfig(configuration);
}
}
}
}
public void modifyCacheAttributes(XmlEntity xmlEntity, String [] groups) throws Exception {
Region<String, Configuration> configRegion = getConfigurationRegion();
//No group is specified, so modify the cache attributes for a in every single group if it exists.
if (groups == null) {
Set<String> groupSet = configRegion.keySet();
groups = groupSet.toArray(new String[groupSet.size()]);
}
for (String group : groups) {
Configuration configuration = (Configuration) configRegion.get(group);
if (configuration == null) {
configuration = new Configuration(group);
}
String xmlContent = configuration.getCacheXmlContent();
if (xmlContent == null || xmlContent.isEmpty()) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
CacheXmlGenerator.generateDefault(pw);
xmlContent = sw.toString();
}
Document doc = createAndUpgradeDocumentFromXml(xmlContent);
//Modify the cache attributes
XmlUtils.modifyRootAttributes(doc, xmlEntity);
//Change the xml content of the configuration and put it the config region
configuration.setCacheXmlContent(XmlUtils.prettyXml(doc));
configRegion.put(group, configuration);
writeConfig(configuration);
}
}
/***
* Only to be used for clean up in DUnits.
*/
public void destroySharedConfiguration() {
Region<String, Configuration> configRegion;
try {
configRegion = getConfigurationRegion();
if (configRegion != null) {
configRegion.destroyRegion();
}
DiskStore configDiskStore = this.cache.findDiskStore(CLUSTER_CONFIG_ARTIFACTS_DIR_NAME);
if (configDiskStore != null) {
configDiskStore.destroy();
File file = new File(CONFIG_DISK_DIR_PATH);
FileUtils.deleteDirectory(file);
}
FileUtils.deleteDirectory(new File(CONFIG_DIR_PATH));
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
}
public Object[] getAllJars(Set<String> groups) throws Exception {
Set<String> jarsAdded = new HashSet<String>();
Object[] jars = new Object[2];
for (String group : groups) {
Configuration configuration = getConfiguration(group);
if (configuration != null) {
jarsAdded.addAll(configuration.getJarNames());
}
}
int numJars = jarsAdded.size();
jarsAdded.clear();
if (numJars > 0) {
String [] jarNames = new String[numJars];
byte[][] jarBytes = new byte[numJars][];
int ctr = 0;
for (String group : groups) {
Configuration configuration = getConfiguration(group);
if (configuration != null) {
Set<String> jarNameSet = configuration.getJarNames();
for (String jarName : jarNameSet) {
String groupDirPath = FilenameUtils.concat(CONFIG_DIR_PATH, group);
if (!jarsAdded.contains(jarName)) {
String jarFilePath = FilenameUtils.concat(groupDirPath, jarName);
jarNames[ctr]=jarName;
jarBytes[ctr] = FileUtils.readFileToByteArray(new File(jarFilePath));
ctr++;
}
}
}
}
jars[0] = jarNames;
jars[1] = jarBytes;
}
return jars;
}
/***
* Gets the Jar from existing locators in the system
* @throws Exception
*/
public void getAllJarsFromOtherLocators() throws Exception {
logger.info("Getting Jar files from other locators");
DM dm = cache.getDistributionManager();
DistributedMember me = cache.getMyId();
Set<DistributedMember> locators = new HashSet<DistributedMember>(dm.getAllHostedLocatorsWithSharedConfiguration().keySet());
locators.remove(me);
String [] jarNames = null;
byte [][] jarBytes = null;
if (locators.isEmpty()) {
logger.info("No other locators present");
return;
}
@SuppressWarnings("unchecked")
ResultCollector<?, List<Object>> rc = (ResultCollector<?, List<Object>>) CliUtil.executeFunction(getAllJarsFunction, null , locators);
List<Object> results = rc.getResult();
for (Object result : results) {
if (result != null) {
if (!(result instanceof Exception)) {
Object[] jars = (Object[]) result;
jarNames = (String[])jars[0];
jarBytes = (byte[][]) jars[1];
break;
}
}
}
if (jarNames != null && jarBytes != null) {
Map<String, Integer> jarIndex = new HashMap<String, Integer>();
for (int i=0; i<jarNames.length; i++) {
String jarName = jarNames[i];
jarIndex.put(jarName, i);
}
Map<String, Configuration> entireConfiguration = getEntireConfiguration();
Set<String> groups = entireConfiguration.keySet();
for (String group : groups) {
Configuration config = entireConfiguration.get(group);
Set<String> groupJarNames = config.getJarNames();
String groupDirPath = FilenameUtils.concat(CONFIG_DIR_PATH, group);
for (String groupJarName : groupJarNames) {
Integer index = jarIndex.get(groupJarName);
if (index != null) {
String jarFilePath = FilenameUtils.concat(groupDirPath, groupJarName);
byte[] jarData = jarBytes[index.intValue()];
try {
FileUtils.writeByteArrayToFile(new File(jarFilePath), jarData);
} catch (IOException e) {
logger.info(e.getMessage(), e);
}
} else {
//This should NEVER happen
logger.error("JarFile {} not delivered.", groupJarName);
}
}
}
} else {
logger.info("No deployed jars found on other locators.");
}
}
public Configuration getConfiguration(String groupName) throws Exception {
Configuration configuration = (Configuration)getConfigurationRegion().get(groupName);
return configuration;
}
/*****
* Gets the region containing the shared configuration data.
* The region is created , if it does not exist already.
* Note : this could block if this locator contains stale persistent configuration data.
* @return {@link Region} ConfigurationRegion
* @throws Exception
*/
private Region<String, Configuration> getConfigurationRegion() throws Exception {
@SuppressWarnings("unchecked")
Region<String, Configuration> configRegion = cache.getRegion(CONFIG_REGION_NAME);
try {
if (configRegion == null) {
File diskDir = new File(CONFIG_DISK_DIR_PATH);
if (!diskDir.exists()) {
if (!diskDir.mkdirs()) {
throw new IOException("Cannot create directory at " + CONFIG_DISK_DIR_PATH);
}
}
File [] diskDirs = {diskDir};
cache.createDiskStoreFactory()
.setDiskDirs(diskDirs)
.setAutoCompact(true)
.setMaxOplogSize(10)
.create(CLUSTER_CONFIG_DISK_STORE_NAME);
AttributesFactory<String, Configuration> regionAttrsFactory = new AttributesFactory<String, Configuration>();
regionAttrsFactory.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
regionAttrsFactory.setCacheListener(new ConfigurationChangeListener(this));
regionAttrsFactory.setDiskStoreName(CLUSTER_CONFIG_DISK_STORE_NAME);
InternalRegionArguments internalArgs = new InternalRegionArguments();
internalArgs.setIsUsedForMetaRegion(true);
internalArgs.setMetaRegionWithTransactions(false);
configRegion = cache.createVMRegion(CONFIG_REGION_NAME, regionAttrsFactory.create(), internalArgs);
}
} catch (CancelException e) {
if (configRegion == null) {
this.status.set(SharedConfigurationStatus.STOPPED);
}
throw e; // CONFIG: don't rethrow as Exception, keep it a subclass of CancelException
} catch (Exception e) {
if (configRegion == null) {
this.status.set(SharedConfigurationStatus.STOPPED);
}
throw new Exception("Error occurred while initializing cluster configuration", e);
}
return configRegion;
}
public Map<String, Configuration> getEntireConfiguration() throws Exception {
Set<String> keys = getConfigurationRegion().keySet();
return getConfigurationRegion().getAll(keys);
}
/****
* Returns the path of Shared configuration directory
* @return {@link String} path of the shared configuration directory
*/
public String getSharedConfigurationDirPath() {
return CONFIG_DIR_PATH;
}
/*****
* Gets the current status of the SharedConfiguration
* If the status is started , it determines if the shared configuration is waiting for new configuration on
* other locators
* @return {@link SharedConfigurationStatus}
*/
public SharedConfigurationStatus getStatus() {
SharedConfigurationStatus scStatus = this.status.get();
if (scStatus == SharedConfigurationStatus.STARTED) {
PersistentMemberManager pmm = cache.getPersistentMemberManager();
Map<String, Set<PersistentMemberID>> waitingRegions = pmm.getWaitingRegions();
if (!waitingRegions.isEmpty()) {
this.status.compareAndSet(SharedConfigurationStatus.STARTED, SharedConfigurationStatus.WAITING);
Set<PersistentMemberID> persMemIds = waitingRegions.get(Region.SEPARATOR_CHAR + CONFIG_REGION_NAME);
for (PersistentMemberID persMemId : persMemIds) {
newerSharedConfigurationLocatorInfo.add(new PersistentMemberPattern(persMemId));
}
}
}
return this.status.get();
}
/****
* Loads the
* @throws Exception
*/
public void loadSharedConfigurationFromDisk() throws Exception {
Map<String, Configuration> sharedConfigurationMap = readSharedConfigurationFromDisk();
getConfigurationRegion().clear();
getConfigurationRegion().putAll(sharedConfigurationMap);
}
public void modifyProperties(Properties properties, String[] groups) throws Exception {
if (groups == null) {
groups = new String[] {SharedConfiguration.CLUSTER_CONFIG};
}
Region<String, Configuration> configRegion = getConfigurationRegion();
for (String group : groups) {
Configuration configuration = (Configuration) configRegion.get(group);
if (configuration == null) {
configuration = new Configuration(group);
}
configuration.getGemfireProperties().putAll(properties);
configRegion.put(group, configuration);
writeConfig(configuration);
}
}
/*****
* Reads the configuration information from the shared configuration directory and returns a {@link Configuration} object
* @param configName
* @param configDirectory
* @return {@link Configuration}
* @throws TransformerException
* @throws TransformerFactoryConfigurationError
* @throws ParserConfigurationException
* @throws SAXException
*/
private Configuration readConfiguration(String configName, String configDirectory) throws SAXException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException {
Configuration configuration = new Configuration(configName);
String cacheXmlFullPath = FilenameUtils.concat(configDirectory, configuration.getCacheXmlFileName());
String propertiesFullPath = FilenameUtils.concat(configDirectory, configuration.getPropertiesFileName());
File file = new File(configDirectory);
String [] jarFileNames = file.list(jarFileFilter);
if (jarFileNames != null && jarFileNames.length != 0 ) {
configuration.addJarNames(jarFileNames);
}
try {
configuration.setCacheXmlContent(XmlUtils.readXmlAsStringFromFile(cacheXmlFullPath));
configuration.setGemfireProperties(readProperties(propertiesFullPath));
} catch (IOException e) {
logger.info(e);
}
return configuration;
}
/*****
* Reads the properties from the properties file.
* @param propertiesFilePath
* @return {@link Properties}
* @throws IOException
*/
public Properties readProperties(String propertiesFilePath) throws IOException{
Properties properties = new Properties();
File propsFile = new File(propertiesFilePath);
FileInputStream fis = null;
if (propsFile.exists()) {
try {
fis = new FileInputStream(propsFile);
properties.load(fis);
} finally {
if (fis != null) {
fis.close();
}
}
}
return properties;
}
/****
* Reads the "shared_config" directory and loads all the cache.xml , gemfire.properties and deployd jars information
* @return {@link Map}
* @throws TransformerException
* @throws TransformerFactoryConfigurationError
* @throws ParserConfigurationException
* @throws SAXException
*/
private Map<String, Configuration> readSharedConfigurationFromDisk() throws SAXException, ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException {
String []subdirectoryNames = getSubdirectories(CONFIG_DIR_PATH);
Map<String, Configuration> sharedConfiguration = new HashMap<String, Configuration>();
if (subdirectoryNames != null) {
for (String subdirectoryName : subdirectoryNames) {
String fullpath = FilenameUtils.concat(CONFIG_DIR_PATH, subdirectoryName);
Configuration configuration = readConfiguration(subdirectoryName, fullpath);
sharedConfiguration.put(subdirectoryName, configuration);
}
}
return sharedConfiguration;
}
/****
* Removes the jar files from the given directory
* @param dirPath Path of the configuration directory
* @param jarNames Names of the jar files
* @throws IOException
*/
public void removeJarFiles (String dirPath, String[] jarNames) throws IOException {
if (jarNames != null) {
for (int i=0; i<jarNames.length; i++) {
File jarFile = new File(FilenameUtils.concat(dirPath, jarNames[i]));
if (jarFile.exists()) {
FileUtils.forceDelete(jarFile);
}
}
} else {
File dir = new File(dirPath);
String []jarFileNames = dir.list(jarFileFilter);
if (jarFileNames.length != 0) {
File jarFileToBeDeleted;
for (String jarFileName : jarFileNames) {
String fullPath = FilenameUtils.concat(dirPath, jarFileName);
jarFileToBeDeleted = new File(fullPath);
FileUtils.forceDelete(jarFileToBeDeleted);
}
}
}
}
/****
* Removes the jar files from the shared configuration.
* @param jarNames Names of the jar files.
* @param groups Names of the groups which had the jar file deployed.
* @return true on success.
*/
public boolean removeJars(String []jarNames, String[] groups){
boolean success = true;
try {
Region<String, Configuration> configRegion = getConfigurationRegion();
if (groups == null) {
Set<String> groupSet = configRegion.keySet();
groups = groupSet.toArray(new String[groupSet.size()]);
}
for (String group : groups) {
Configuration configuration = (Configuration) configRegion.get(group);
if (configuration != null) {
String dirPath = FilenameUtils.concat(getSharedConfigurationDirPath(), configuration.getConfigName());
removeJarFiles(dirPath, jarNames);
}
}
for (String group : groups) {
Configuration configuration = (Configuration) configRegion.get(group);
if (configuration != null) {
if (!configuration.getJarNames().isEmpty()) {
configuration.removeJarNames(jarNames);
configRegion.put(group, configuration);
}
}
}
} catch (Exception e) {
logger.info("Exception occurred while deleting the jar files", e);
success = false;
}
return success;
}
public void renameExistingSharedConfigDirectory() {
File configDirFile = new File(CONFIG_DIR_PATH);
if (configDirFile.exists()) {
String configDirFileName2 = CLUSTER_CONFIG_ARTIFACTS_DIR_NAME + new SimpleDateFormat("yyyyMMddhhmm").format(new Date()) + "." + System.nanoTime();
File configDirFile2 = new File(FilenameUtils.concat(configDirFileName2, configDirFileName2));
try {
FileUtils.moveDirectoryToDirectory(configDirFile, configDirFile2, true);
} catch (IOException e) {
logger.info(e);
}
}
}
/***
* Writes the cache.xml to the file , based on Configuration
* @param dirPath Path of the directory in which the configuration is written
* @param configuration
* @throws IOException
*/
private void writeCacheXml(String dirPath, Configuration configuration) throws IOException {
String fullPath = FilenameUtils.concat(dirPath,configuration.getCacheXmlFileName());
FileUtils.writeStringToFile(new File(fullPath), configuration.getCacheXmlContent(), "UTF-8") ;
}
/***
* Writes the contents of the {@link Configuration} to the file system
* @param configuration
* @throws Exception
*/
public void writeConfig(Configuration configuration) throws Exception {
File configDir = new File(getSharedConfigurationDirPath());
if (!configDir.exists()) {
if (!configDir.mkdirs()) {
throw new IOException("Cannot create directory : " + getSharedConfigurationDirPath());
}
}
String dirPath = FilenameUtils.concat(getSharedConfigurationDirPath(), configuration.getConfigName());
File file = new File(dirPath);
if (!file.exists()) {
if (!file.mkdir()) {
throw new IOException("Cannot create directory : " + dirPath);
}
}
writeProperties(dirPath, configuration);
writeCacheXml(dirPath, configuration);
}
/*****
* Writes the
* @param dirPath target directory , where the jar files are to be written
* @param jarNames Array containing the name of the jar files.
* @param jarBytes Array of byte arrays for the jar files.
*/
private void writeJarFiles(String dirPath , String[] jarNames, byte[][] jarBytes) {
for (int i=0; i<jarNames.length; i++) {
String filePath = FilenameUtils.concat(dirPath, jarNames[i]);
File jarFile = new File(filePath);
try {
FileUtils.writeByteArrayToFile(jarFile, jarBytes[i]);
} catch (IOException e) {
logger.info(e);
}
}
}
/****
* Writes the properties to the file based on the {@link Configuration}
* @param dirPath
* @param configuration
* @throws IOException
*/
private void writeProperties(String dirPath, Configuration configuration) throws IOException {
String fullPath = FilenameUtils.concat(dirPath,configuration.getPropertiesFileName());
BufferedWriter bw = new BufferedWriter(new FileWriter(fullPath));
configuration.getGemfireProperties().store(bw, "");
bw.close();
}
}
| |
/**
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
import com.android.internal.telephony.RetryManager;
import junit.framework.TestCase;
import android.test.suitebuilder.annotation.SmallTest;
public class TelephonyUtilsTest extends TestCase {
/**
* After first creating the RetryManager
* isRetryNeeded should be false and the time 0
*/
@SmallTest
public void testRetryManagerEmpty() throws Exception {
RetryManager rm = new RetryManager();
assertEquals(0, rm.getRetryCount());
assertFalse(rm.isRetryForever());
assertFalse(rm.isRetryNeeded());
assertEquals(0, rm.getRetryCount());
assertEquals(0, rm.getRetryTimer());
rm.increaseRetryCount();
assertFalse(rm.isRetryForever());
assertFalse(rm.isRetryNeeded());
assertEquals(0, rm.getRetryCount());
assertEquals(0, rm.getRetryTimer());
rm.setRetryCount(123);
assertFalse(rm.isRetryForever());
assertFalse(rm.isRetryNeeded());
assertEquals(0, rm.getRetryCount());
assertEquals(0, rm.getRetryTimer());
rm.retryForeverUsingLastTimeout();
assertTrue(rm.isRetryForever());
assertTrue(rm.isRetryNeeded());
assertEquals(0, rm.getRetryCount());
assertEquals(0, rm.getRetryTimer());
rm.setRetryCount(2);
assertTrue(rm.isRetryForever());
assertTrue(rm.isRetryNeeded());
assertEquals(0, rm.getRetryCount());
assertEquals(0, rm.getRetryTimer());
}
/**
* A simple test and that randomization is doing something.
*/
@SmallTest
public void testRetryManagerSimplest() throws Exception {
RetryManager rm = new RetryManager();
assertTrue(rm.configure(1, 500, 10));
int loops = 10;
int count = 0;
for (int i = 0; i < loops; i++) {
assertTrue(rm.isRetryNeeded());
int time = rm.getRetryTimer();
assertTrue((time >= 500) && (time < 600));
if (time == 500) {
count++;
}
}
assertFalse(count == loops);
rm.increaseRetryCount();
assertFalse(rm.isRetryNeeded());
rm.setRetryCount(0);
assertTrue(rm.isRetryNeeded());
}
/**
* Test multiple values using simple configuration.
*/
@SmallTest
public void testRetryManagerSimple() throws Exception {
RetryManager rm = new RetryManager();
assertTrue(rm.configure(3, 1000, 0));
assertTrue(rm.isRetryNeeded());
assertEquals(1000, rm.getRetryTimer());
assertEquals(rm.getRetryTimer(), 1000);
rm.increaseRetryCount();
assertTrue(rm.isRetryNeeded());
assertEquals(1000, rm.getRetryTimer());
rm.increaseRetryCount();
assertTrue(rm.isRetryNeeded());
assertEquals(1000, rm.getRetryTimer());
rm.increaseRetryCount();
assertFalse(rm.isRetryNeeded());
assertEquals(1000, rm.getRetryTimer());
}
/**
* Test string configuration, simplest
*/
@SmallTest
public void testRetryManageSimpleString() throws Exception {
RetryManager rm = new RetryManager();
assertTrue(rm.configure("101"));
assertTrue(rm.isRetryNeeded());
assertEquals(101, rm.getRetryTimer());
rm.increaseRetryCount();
assertFalse(rm.isRetryNeeded());
}
/**
* Test infinite retires
*/
@SmallTest
public void testRetryManageInfinite() throws Exception {
RetryManager rm = new RetryManager();
assertTrue(rm.configure("1000,2000,3000,max_retries=infinite"));
assertTrue(rm.isRetryNeeded());
assertEquals(1000, rm.getRetryTimer());
rm.increaseRetryCount();
assertTrue(rm.isRetryNeeded());
assertEquals(2000, rm.getRetryTimer());
rm.increaseRetryCount();
assertTrue(rm.isRetryNeeded());
// All others are 3000 and isRetryNeeded is always true
for (int i=0; i < 100; i++) {
assertEquals(3000, rm.getRetryTimer());
rm.increaseRetryCount();
assertTrue(rm.isRetryNeeded());
}
}
/**
* Test string configuration using all options and with quotes.
*/
@SmallTest
public void testRetryManageString() throws Exception {
RetryManager rm = new RetryManager();
int time;
assertTrue(rm.configure(
"\"max_retries=4, default_randomization=100,1000, 2000 :200 , 3000\""));
assertTrue(rm.isRetryNeeded());
time = rm.getRetryTimer();
assertTrue((time >= 1000) && (time < 1100));
rm.increaseRetryCount();
assertTrue(rm.isRetryNeeded());
time = rm.getRetryTimer();
assertTrue((time >= 2000) && (time < 2200));
rm.increaseRetryCount();
assertTrue(rm.isRetryNeeded());
time = rm.getRetryTimer();
assertTrue((time >= 3000) && (time < 3100));
rm.increaseRetryCount();
assertTrue(rm.isRetryNeeded());
time = rm.getRetryTimer();
assertTrue((time >= 3000) && (time < 3100));
rm.increaseRetryCount();
assertFalse(rm.isRetryNeeded());
}
/**
* Test string configuration using all options.
*/
@SmallTest
public void testRetryManageForever() throws Exception {
RetryManager rm = new RetryManager();
int time;
assertTrue(rm.configure("1000, 2000, 3000"));
assertTrue(rm.isRetryNeeded());
assertFalse(rm.isRetryForever());
assertEquals(0, rm.getRetryCount());
assertEquals(1000, rm.getRetryTimer());
rm.retryForeverUsingLastTimeout();
rm.increaseRetryCount();
rm.increaseRetryCount();
rm.increaseRetryCount();
assertTrue(rm.isRetryNeeded());
assertTrue(rm.isRetryForever());
assertEquals(3, rm.getRetryCount());
assertEquals(3000, rm.getRetryTimer());
rm.setRetryCount(1);
assertTrue(rm.isRetryNeeded());
assertTrue(rm.isRetryForever());
assertEquals(1, rm.getRetryCount());
assertEquals(2000, rm.getRetryTimer());
rm.retryForeverUsingLastTimeout();
assertTrue(rm.isRetryNeeded());
assertTrue(rm.isRetryForever());
rm.resetRetryCount();
assertTrue(rm.isRetryNeeded());
assertTrue(rm.isRetryForever());
assertEquals(0, rm.getRetryCount());
assertEquals(1000, rm.getRetryTimer());
}
}
| |
package galaxyspace.systems.BarnardsSystem.planets.barnarda_c.blocks;
import java.util.Random;
import galaxyspace.core.util.GSCreativeTabs;
import galaxyspace.systems.BarnardsSystem.core.BRBlocks;
import net.minecraft.block.Block;
import net.minecraft.block.IGrowable;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class Barnarda_C_Grass extends Block implements IGrowable{
public static final PropertyEnum<EnumBlockGrass> BASIC_TYPE = PropertyEnum.create("type", EnumBlockGrass.class);
public Barnarda_C_Grass() {
super(Material.GRASS);
this.setUnlocalizedName("barnarda_c_grasses");
this.setHardness(0.8F);
this.setSoundType(SoundType.GROUND);
this.setHarvestLevel("shovel", 0);
}
@Override
public CreativeTabs getCreativeTabToDisplayOn()
{
return GSCreativeTabs.GSBlocksTab;
}
@Override
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) {
return new ItemStack(Item.getItemFromBlock(this), 1, this.getMetaFromState(state));
}
@SideOnly(Side.CLIENT)
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list)
{
for (EnumBlockGrass blockBasic : EnumBlockGrass.values())
{
list.add(new ItemStack(this, 1, blockBasic.getMeta()));
}
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
{
//Block block = worldIn.getBlockState(pos.up()).getBlock();
return state;//state.withProperty(SNOWY, Boolean.valueOf(block == Blocks.SNOW || block == Blocks.SNOW_LAYER));
}
@Override
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if (!worldIn.isRemote)
{
if (!worldIn.isAreaLoaded(pos, 3)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light and spreading
if (worldIn.getLightFromNeighbors(pos.up()) < 4 && worldIn.getBlockState(pos.up()).getLightOpacity(worldIn, pos.up()) > 2)
{
worldIn.setBlockState(pos, BRBlocks.BARNARDA_C_BLOCKS.getDefaultState().withProperty(Barnarda_C_Blocks.BASIC_TYPE, Barnarda_C_Blocks.EnumBlockBarnardaC.DIRT));
}
else
{
if (worldIn.getLightFromNeighbors(pos.up()) >= 9)
{
for (int i = 0; i < 4; ++i)
{
BlockPos blockpos = pos.add(rand.nextInt(3) - 1, rand.nextInt(5) - 3, rand.nextInt(3) - 1);
if (blockpos.getY() >= 0 && blockpos.getY() < 256 && !worldIn.isBlockLoaded(blockpos))
{
return;
}
IBlockState iblockstate = worldIn.getBlockState(blockpos.up());
IBlockState iblockstate1 = worldIn.getBlockState(blockpos);
/*
if (iblockstate1.getBlock() == BRBlocks.BARNARDA_C_GRASS && iblockstate1.getValue(Barnarda_C_Blocks.BASIC_TYPE) == Barnarda_C_Blocks.EnumBlockBarnardaC.DIRT && worldIn.getLightFromNeighbors(blockpos.up()) >= 4 && iblockstate.getLightOpacity(worldIn, pos.up()) <= 2)
{
worldIn.setBlockState(blockpos, BRBlocks.BARNARDA_C_GRASS.getDefaultState());
}*/
}
}
}
}
}
@Override
public Item getItemDropped(IBlockState state, Random rand, int fortune)
{
return BRBlocks.BARNARDA_C_BLOCKS.getItemDropped(BRBlocks.BARNARDA_C_BLOCKS.getDefaultState().withProperty(Barnarda_C_Blocks.BASIC_TYPE, Barnarda_C_Blocks.EnumBlockBarnardaC.DIRT), rand, fortune);
}
@SideOnly(Side.CLIENT)
public BlockRenderLayer getBlockLayer() {
return BlockRenderLayer.CUTOUT_MIPPED;
}
@Override
public boolean canSustainPlant(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing direction, net.minecraftforge.common.IPlantable plantable)
{
return true;
}
@Override
public boolean canGrow(World worldIn, BlockPos pos, IBlockState state, boolean isClient) {
return true;
}
@Override
public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, IBlockState state) {
return true;
}
@Override
public void grow(World worldIn, Random rand, BlockPos pos, IBlockState state) {
BlockPos blockpos = pos.up();
for (int i = 0; i < 128; ++i)
{
BlockPos blockpos1 = blockpos;
int j = 0;
while (true)
{
if (j >= i / 16)
{
if (worldIn.isAirBlock(blockpos1))
{
/*if (rand.nextInt(8) == 0)
{
worldIn.getBiome(blockpos1).plantFlower(worldIn, rand, blockpos1);
}
else*/
{
IBlockState iblockstate1 = BRBlocks.BARNARDA_C_DANDELIONS.getDefaultState().withProperty(Barnarda_C_Dandelions.BASIC_TYPE, Barnarda_C_Dandelions.EnumBlockDandelions.GRASS);
if (((Barnarda_C_Dandelions) BRBlocks.BARNARDA_C_DANDELIONS).canPlaceBlockAt(worldIn, blockpos1))
{
worldIn.setBlockState(blockpos1, iblockstate1, 3);
}
}
}
break;
}
blockpos1 = blockpos1.add(rand.nextInt(3) - 1, (rand.nextInt(3) - 1) * rand.nextInt(3) / 2, rand.nextInt(3) - 1);
if (worldIn.getBlockState(blockpos1.down()).getBlock() != BRBlocks.BARNARDA_C_GRASS || worldIn.getBlockState(blockpos1).isNormalCube())
{
break;
}
++j;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
public static enum EnumBlockGrass implements IStringSerializable {
GRASS(0, "barnarda_c_grass");
//GRASS_2(1, "barnarda_c_grass_1");
private final int meta;
private final String name;
private EnumBlockGrass(int meta, String name) {
this.meta = meta;
this.name = name;
}
public int getMeta() {
return this.meta;
}
public static EnumBlockGrass byMetadata(int meta) {
return values()[meta];
}
@Override
public String getName() {
return this.name;
}
}
@Override
public IBlockState getStateFromMeta(int meta) {
return this.getDefaultState().withProperty(BASIC_TYPE, EnumBlockGrass.byMetadata(meta));
}
@Override
public int getMetaFromState(IBlockState state) {
return ((EnumBlockGrass) state.getValue(BASIC_TYPE)).getMeta();
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, BASIC_TYPE);
}
}
| |
/*
Copyright 2011-2013 Frederic Langlet
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 kanzi.test;
import java.util.Arrays;
import java.util.Random;
import kanzi.IndexedByteArray;
import kanzi.function.LZ4Codec;
public class TestLZ4Codec
{
public static void main(String[] args)
{
System.out.println("TestLZ4");
testCorrectness();
testSpeed();
}
public static void testCorrectness()
{
byte[] input;
byte[] output;
byte[] reverse;
Random rnd = new Random();
// Test behavior
System.out.println("Correctness test");
{
for (int ii=0; ii<20; ii++)
{
System.out.println("\nTest "+ii);
int[] arr;
if (ii == 0)
{
arr = new int[] {
0, 1, 2, 2, 2, 2, 7, 9, 9, 16, 16, 16, 1, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
};
}
else if (ii == 1)
{
arr = new int[500];
arr[0] = 1;
for (int i=1; i<500; i++)
arr[i] = 8;
}
else if (ii == 2)
{
arr = new int[] { 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3 };
}
else
{
arr = new int[1024];
int idx = 0;
while (idx < arr.length)
{
int len = rnd.nextInt(270);
if (len % 3 == 0)
len = 1;
int val = rnd.nextInt(256);
int end = (idx+len) < arr.length ? idx+len : arr.length;
for (int j=idx; j<end; j++)
arr[j] = val;
idx += len;
System.out.print(val+" ("+len+") ");
}
}
int size = arr.length;
LZ4Codec lz4 = new LZ4Codec(size);
input = new byte[size];
output = new byte[lz4.getMaxEncodedLength(size)];
reverse = new byte[size];
IndexedByteArray iba1 = new IndexedByteArray(input, 0);
IndexedByteArray iba2 = new IndexedByteArray(output, 0);
IndexedByteArray iba3 = new IndexedByteArray(reverse, 0);
Arrays.fill(output, (byte) 0xAA);
for (int i = 0; i < arr.length; i++)
{
input[i] = (byte) (arr[i] & 255);
for (int j=arr.length; j<size; j++)
input[j] = (byte) (0);
}
System.out.println("\nOriginal: ");
for (int i = 0; i < input.length; i++)
{
System.out.print((input[i] & 255) + " ");
}
if (lz4.forward(iba1, iba2) == false)
{
System.out.println("\nEncoding error");
System.exit(1);
}
if (iba1.index != input.length)
{
System.out.println("\nNo compression (ratio > 1.0), skip reverse");
continue;
}
System.out.println("\nCoded: ");
//java.util.Arrays.fill(input, (byte) 0);
for (int i = 0; i < iba2.index; i++)
{
System.out.print((output[i] & 255) + " "); //+"("+Integer.toBinaryString(output[i] & 255)+") ");
}
lz4 = new LZ4Codec(iba2.index);
iba1.index = 0;
iba2.index = 0;
iba3.index = 0;
if (lz4.inverse(iba2, iba3) == false)
{
System.out.println("\nDecoding error");
System.exit(1);
}
System.out.println("\nDecoded: ");
for (int i = 0; i < reverse.length; i++)
{
System.out.print((reverse[i] & 255) + " ");
}
System.out.println();
for (int i = 0; i < input.length; i++)
{
if (input[i] != reverse[i])
{
System.out.println("Different (index "+i+": "+input[i]+" - "+reverse[i]+")");
System.exit(1);
}
}
System.out.println("Identical");
System.out.println();
}
}
}
public static void testSpeed()
{
// Test speed
byte[] input;
byte[] output;
byte[] reverse;
Random rnd = new Random();
final int iter = 50000;
final int size = 50000;
System.out.println("\n\nSpeed test");
System.out.println("Iterations: "+iter);
for (int jj=0; jj<3; jj++)
{
input = new byte[size];
output = new byte[new LZ4Codec().getMaxEncodedLength(size)];
reverse = new byte[size];
IndexedByteArray iba1 = new IndexedByteArray(input, 0);
IndexedByteArray iba2 = new IndexedByteArray(output, 0);
IndexedByteArray iba3 = new IndexedByteArray(reverse, 0);
long before, after;
long delta1 = 0;
long delta2 = 0;
for (int ii = 0; ii < iter; ii++)
{
// Generate random data with runs
int n = 0;
while (n < input.length)
{
byte val = (byte) (rnd.nextInt() & 255);
input[n++] = val;
int run = rnd.nextInt() & 255;
run -= 200;
while ((--run > 0) && (n < input.length))
input[n++] = val;
}
LZ4Codec lz4 = new LZ4Codec();
iba1.index = 0;
iba2.index = 0;
before = System.nanoTime();
if (lz4.forward(iba1, iba2) == false)
{
System.out.println("Encoding error");
System.exit(1);
}
after = System.nanoTime();
delta1 += (after - before);
lz4 = new LZ4Codec(iba2.index);
iba3.index = 0;
iba2.index = 0;
before = System.nanoTime();
if (lz4.inverse(iba2, iba3) == false)
{
System.out.println("Decoding error");
System.exit(1);
}
after = System.nanoTime();
delta2 += (after - before);
}
int idx = -1;
// Sanity check
for (int i=0; i<iba1.index; i++)
{
if (iba1.array[i] != iba3.array[i])
{
idx = i;
break;
}
}
if (idx >= 0)
System.out.println("Failure at index "+idx+" ("+iba1.array[idx]+"<->"+iba3.array[idx]+")");
final long prod = (long) iter * (long) size;
System.out.println("LZ4 encoding [ms] : " + delta1 / 1000000);
System.out.println("Throughput [MB/s] : " + prod * 1000000L / delta1 * 1000L / (1024*1024));
System.out.println("LZ4 decoding [ms] : " + delta2 / 1000000);
System.out.println("Throughput [MB/s] : " + prod * 1000000L / delta2 * 1000L / (1024*1024));
}
}
}
| |
/*
* 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.pig.backend.hadoop.executionengine.mapReduceLayer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobPriority;
import org.apache.hadoop.mapred.jobcontrol.Job;
import org.apache.hadoop.mapred.jobcontrol.JobControl;
import org.apache.pig.ComparisonFunc;
import org.apache.pig.ExecType;
import org.apache.pig.LoadFunc;
import org.apache.pig.PigException;
import org.apache.pig.StoreFuncInterface;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.hadoop.HDataType;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.partitioners.SecondaryKeyPartitioner;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.partitioners.SkewedPartitioner;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.partitioners.WeightedRangePartitioner;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans.MROperPlan;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhyPlanVisitor;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POUserFunc;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POFRJoin;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POLoad;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POMergeCogroup;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POMergeJoin;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POPackage;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POStore;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.util.PlanHelper;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.io.FileLocalizer;
import org.apache.pig.impl.io.FileSpec;
import org.apache.pig.impl.io.NullableBooleanWritable;
import org.apache.pig.impl.io.NullableBytesWritable;
import org.apache.pig.impl.io.NullableDoubleWritable;
import org.apache.pig.impl.io.NullableFloatWritable;
import org.apache.pig.impl.io.NullableIntWritable;
import org.apache.pig.impl.io.NullableLongWritable;
import org.apache.pig.impl.io.NullablePartitionWritable;
import org.apache.pig.impl.io.NullableText;
import org.apache.pig.impl.io.NullableTuple;
import org.apache.pig.impl.io.PigNullableWritable;
import org.apache.pig.impl.plan.DepthFirstWalker;
import org.apache.pig.impl.plan.OperatorKey;
import org.apache.pig.impl.plan.VisitorException;
import org.apache.pig.impl.util.JarManager;
import org.apache.pig.impl.util.ObjectSerializer;
import org.apache.pig.impl.util.Pair;
import org.apache.pig.impl.util.UDFContext;
import org.apache.pig.impl.util.UriUtil;
import org.apache.pig.impl.util.Utils;
import org.apache.pig.tools.pigstats.ScriptState;
/**
* This is compiler class that takes an MROperPlan and converts
* it into a JobControl object with the relevant dependency info
* maintained. The JobControl Object is made up of Jobs each of
* which has a JobConf. The MapReduceOper corresponds to a Job
* and the getJobCong method returns the JobConf that is configured
* as per the MapReduceOper
*
* <h2>Comparator Design</h2>
* <p>
* A few words on how comparators are chosen. In almost all cases we use raw
* comparators (the one exception being when the user provides a comparison
* function for order by). For order by queries the PigTYPERawComparator
* functions are used, where TYPE is Int, Long, etc. These comparators are
* null aware and asc/desc aware. The first byte of each of the
* NullableTYPEWritable classes contains info on whether the value is null.
* Asc/desc is written as an array into the JobConf with the key pig.sortOrder
* so that it can be read by each of the comparators as part of their
* setConf call.
* <p>
* For non-order by queries, PigTYPEWritableComparator classes are used.
* These are all just type specific instances of WritableComparator.
*
*/
public class JobControlCompiler{
MROperPlan plan;
Configuration conf;
PigContext pigContext;
private static final Log log = LogFactory.getLog(JobControlCompiler.class);
public static final String LOG_DIR = "_logs";
public static final String END_OF_INP_IN_MAP = "pig.invoke.close.in.map";
/**
* We will serialize the POStore(s) present in map and reduce in lists in
* the Hadoop Conf. In the case of Multi stores, we could deduce these from
* the map plan and reduce plan but in the case of single store, we remove
* the POStore from the plan - in either case, we serialize the POStore(s)
* so that PigOutputFormat and PigOutputCommiter can get the POStore(s) in
* the same way irrespective of whether it is multi store or single store.
*/
public static final String PIG_MAP_STORES = "pig.map.stores";
public static final String PIG_REDUCE_STORES = "pig.reduce.stores";
// A mapping of job to pair of store locations and tmp locations for that job
private Map<Job, Pair<List<POStore>, Path>> jobStoreMap;
private Map<Job, MapReduceOper> jobMroMap;
public JobControlCompiler(PigContext pigContext, Configuration conf) throws IOException {
this.pigContext = pigContext;
this.conf = conf;
jobStoreMap = new HashMap<Job, Pair<List<POStore>, Path>>();
jobMroMap = new HashMap<Job, MapReduceOper>();
}
/**
* Returns all store locations of a previously compiled job
*/
public List<POStore> getStores(Job job) {
Pair<List<POStore>, Path> pair = jobStoreMap.get(job);
if (pair != null && pair.first != null) {
return pair.first;
} else {
return new ArrayList<POStore>();
}
}
/**
* Resets the state
*/
public void reset() {
jobStoreMap = new HashMap<Job, Pair<List<POStore>, Path>>();
jobMroMap = new HashMap<Job, MapReduceOper>();
UDFContext.getUDFContext().reset();
}
/**
* Gets the map of Job and the MR Operator
*/
public Map<Job, MapReduceOper> getJobMroMap() {
return Collections.unmodifiableMap(jobMroMap);
}
/**
* Moves all the results of a collection of MR jobs to the final
* output directory. Some of the results may have been put into a
* temp location to work around restrictions with multiple output
* from a single map reduce job.
*
* This method should always be called after the job execution
* completes.
*/
public void moveResults(List<Job> completedJobs) throws IOException {
for (Job job: completedJobs) {
Pair<List<POStore>, Path> pair = jobStoreMap.get(job);
if (pair != null && pair.second != null) {
Path tmp = pair.second;
Path abs = new Path(tmp, "abs");
Path rel = new Path(tmp, "rel");
FileSystem fs = tmp.getFileSystem(conf);
if (fs.exists(abs)) {
moveResults(abs, abs.toUri().getPath(), fs);
}
if (fs.exists(rel)) {
moveResults(rel, rel.toUri().getPath()+"/", fs);
}
}
}
}
/**
* Walks the temporary directory structure to move (rename) files
* to their final location.
*/
private void moveResults(Path p, String rem, FileSystem fs) throws IOException {
for (FileStatus fstat: fs.listStatus(p)) {
Path src = fstat.getPath();
if (fstat.isDir()) {
log.info("mkdir: "+src);
fs.mkdirs(removePart(src, rem));
moveResults(fstat.getPath(), rem, fs);
} else {
Path dst = removePart(src, rem);
log.info("mv: "+src+" "+dst);
fs.rename(src,dst);
}
}
}
private Path removePart(Path src, String part) {
URI uri = src.toUri();
String pathStr = uri.getPath().replace(part, "");
return new Path(pathStr);
}
/**
* Compiles all jobs that have no dependencies removes them from
* the plan and returns. Should be called with the same plan until
* exhausted.
* @param plan - The MROperPlan to be compiled
* @param grpName - The name given to the JobControl
* @return JobControl object - null if no more jobs in plan
* @throws JobCreationException
*/
public JobControl compile(MROperPlan plan, String grpName) throws JobCreationException{
// Assert plan.size() != 0
this.plan = plan;
JobControl jobCtrl = new JobControl(grpName);
try {
List<MapReduceOper> roots = new LinkedList<MapReduceOper>();
roots.addAll(plan.getRoots());
for (MapReduceOper mro: roots) {
if(mro instanceof NativeMapReduceOper) {
return null;
}
Job job = getJob(mro, conf, pigContext);
jobMroMap.put(job, mro);
jobCtrl.addJob(job);
}
} catch (JobCreationException jce) {
throw jce;
} catch(Exception e) {
int errCode = 2017;
String msg = "Internal error creating job configuration.";
throw new JobCreationException(msg, errCode, PigException.BUG, e);
}
return jobCtrl;
}
// Update Map-Reduce plan with the execution status of the jobs. If one job
// completely fail (the job has only one store and that job fail), then we
// remove all its dependent jobs. This method will return the number of MapReduceOper
// removed from the Map-Reduce plan
public int updateMROpPlan(List<Job> completeFailedJobs)
{
int sizeBefore = plan.size();
for (Job job : completeFailedJobs) // remove all subsequent jobs
{
MapReduceOper mrOper = jobMroMap.get(job);
plan.trimBelow(mrOper);
plan.remove(mrOper);
}
// Remove successful jobs from jobMroMap
for (Job job : jobMroMap.keySet())
{
if (!completeFailedJobs.contains(job))
{
MapReduceOper mro = jobMroMap.get(job);
plan.remove(mro);
}
}
jobMroMap.clear();
int sizeAfter = plan.size();
return sizeBefore-sizeAfter;
}
/**
* The method that creates the Job corresponding to a MapReduceOper.
* The assumption is that
* every MapReduceOper will have a load and a store. The JobConf removes
* the load operator and serializes the input filespec so that PigInputFormat can
* take over the creation of splits. It also removes the store operator
* and serializes the output filespec so that PigOutputFormat can take over
* record writing. The remaining portion of the map plan and reduce plans are
* serialized and stored for the PigMapReduce or PigMapOnly objects to take over
* the actual running of the plans.
* The Mapper & Reducer classes and the required key value formats are set.
* Checks if this is a map only job and uses PigMapOnly class as the mapper
* and uses PigMapReduce otherwise.
* If it is a Map Reduce job, it is bound to have a package operator. Remove it from
* the reduce plan and serializes it so that the PigMapReduce class can use it to package
* the indexed tuples received by the reducer.
* @param mro - The MapReduceOper for which the JobConf is required
* @param conf - the Configuration object from which JobConf is built
* @param pigContext - The PigContext passed on from execution engine
* @return Job corresponding to mro
* @throws JobCreationException
*/
@SuppressWarnings({ "unchecked", "deprecation" })
private Job getJob(MapReduceOper mro, Configuration config, PigContext pigContext) throws JobCreationException{
org.apache.hadoop.mapreduce.Job nwJob = null;
try{
nwJob = new org.apache.hadoop.mapreduce.Job(config);
}catch(Exception e) {
throw new JobCreationException(e);
}
Configuration conf = nwJob.getConfiguration();
ArrayList<FileSpec> inp = new ArrayList<FileSpec>();
ArrayList<List<OperatorKey>> inpTargets = new ArrayList<List<OperatorKey>>();
ArrayList<String> inpSignatureLists = new ArrayList<String>();
ArrayList<Long> inpLimits = new ArrayList<Long>();
ArrayList<POStore> storeLocations = new ArrayList<POStore>();
Path tmpLocation = null;
// add settings for pig statistics
String setScriptProp = conf.get(ScriptState.INSERT_ENABLED, "true");
if (setScriptProp.equalsIgnoreCase("true")) {
ScriptState ss = ScriptState.get();
ss.addSettingsToConf(mro, conf);
}
conf.set("mapred.mapper.new-api", "true");
conf.set("mapred.reducer.new-api", "true");
String buffPercent = conf.get("mapred.job.reduce.markreset.buffer.percent");
if (buffPercent == null || Double.parseDouble(buffPercent) <= 0) {
log.info("mapred.job.reduce.markreset.buffer.percent is not set, set to default 0.3");
conf.set("mapred.job.reduce.markreset.buffer.percent", "0.3");
}else{
log.info("mapred.job.reduce.markreset.buffer.percent is set to " + conf.get("mapred.job.reduce.markreset.buffer.percent"));
}
// Convert mapred.output.* to output.compression.*, See PIG-1791
if( "true".equals( conf.get( "mapred.output.compress" ) ) ) {
conf.set( "output.compression.enabled", "true" );
String codec = conf.get( "mapred.output.compression.codec" );
if( codec == null ) {
throw new JobCreationException("'mapred.output.compress' is set but no value is specified for 'mapred.output.compression.codec'." );
} else {
conf.set( "output.compression.codec", codec );
}
}
try{
//Process the POLoads
List<POLoad> lds = PlanHelper.getLoads(mro.mapPlan);
if(lds!=null && lds.size()>0){
for (POLoad ld : lds) {
LoadFunc lf = ld.getLoadFunc();
// Call setLocation as a hacky way of letting a LoadFunc fix up the Job.
// Note that setLocation will get called on the loadFuncs later, as well.
// That's ok as setLocation getting called multiple times is documented behavior.
if (lf !=null) {
lf.setLocation(ld.getLFile().getFileName(), nwJob);
}
//Store the inp filespecs
inp.add(ld.getLFile());
//Store the target operators for tuples read
//from this input
List<PhysicalOperator> ldSucs = mro.mapPlan.getSuccessors(ld);
List<OperatorKey> ldSucKeys = new ArrayList<OperatorKey>();
if(ldSucs!=null){
for (PhysicalOperator operator2 : ldSucs) {
ldSucKeys.add(operator2.getOperatorKey());
}
}
inpTargets.add(ldSucKeys);
inpSignatureLists.add(ld.getSignature());
inpLimits.add(ld.getLimit());
//Remove the POLoad from the plan
if (!pigContext.inIllustrator)
mro.mapPlan.remove(ld);
}
}
if (!pigContext.inIllustrator && pigContext.getExecType() != ExecType.LOCAL)
{
//Create the jar of all functions and classes required
File submitJarFile = File.createTempFile("Job", ".jar");
log.info("creating jar file "+submitJarFile.getName());
// ensure the job jar is deleted on exit
submitJarFile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(submitJarFile);
JarManager.createJar(fos, mro.UDFs, pigContext);
log.info("jar file "+submitJarFile.getName()+" created");
//Start setting the JobConf properties
conf.set("mapred.jar", submitJarFile.getPath());
}
conf.set("pig.inputs", ObjectSerializer.serialize(inp));
conf.set("pig.inpTargets", ObjectSerializer.serialize(inpTargets));
conf.set("pig.inpSignatures", ObjectSerializer.serialize(inpSignatureLists));
conf.set("pig.inpLimits", ObjectSerializer.serialize(inpLimits));
conf.set("pig.pigContext", ObjectSerializer.serialize(pigContext));
conf.set("udf.import.list", ObjectSerializer.serialize(PigContext.getPackageImportList()));
// this is for unit tests since some don't create PigServer
// if user specified the job name using -D switch, Pig won't reset the name then.
if (System.getProperty("mapred.job.name") == null &&
pigContext.getProperties().getProperty(PigContext.JOB_NAME) != null){
nwJob.setJobName(pigContext.getProperties().getProperty(PigContext.JOB_NAME));
}
if (pigContext.getProperties().getProperty(PigContext.JOB_PRIORITY) != null) {
// If the job priority was set, attempt to get the corresponding enum value
// and set the hadoop job priority.
String jobPriority = pigContext.getProperties().getProperty(PigContext.JOB_PRIORITY).toUpperCase();
try {
// Allow arbitrary case; the Hadoop job priorities are all upper case.
conf.set("mapred.job.priority", JobPriority.valueOf(jobPriority).toString());
} catch (IllegalArgumentException e) {
StringBuffer sb = new StringBuffer("The job priority must be one of [");
JobPriority[] priorities = JobPriority.values();
for (int i = 0; i < priorities.length; ++i) {
if (i > 0) sb.append(", ");
sb.append(priorities[i]);
}
sb.append("]. You specified [" + jobPriority + "]");
throw new JobCreationException(sb.toString());
}
}
// Setup the DistributedCache for this job
setupDistributedCache(pigContext, nwJob.getConfiguration(), pigContext.getProperties(),
"pig.streaming.ship.files", true);
setupDistributedCache(pigContext, nwJob.getConfiguration(), pigContext.getProperties(),
"pig.streaming.cache.files", false);
nwJob.setInputFormatClass(PigInputFormat.class);
//Process POStore and remove it from the plan
LinkedList<POStore> mapStores = PlanHelper.getStores(mro.mapPlan);
LinkedList<POStore> reduceStores = PlanHelper.getStores(mro.reducePlan);
for (POStore st: mapStores) {
storeLocations.add(st);
StoreFuncInterface sFunc = st.getStoreFunc();
sFunc.setStoreLocation(st.getSFile().getFileName(), new org.apache.hadoop.mapreduce.Job(nwJob.getConfiguration()));
}
for (POStore st: reduceStores) {
storeLocations.add(st);
StoreFuncInterface sFunc = st.getStoreFunc();
sFunc.setStoreLocation(st.getSFile().getFileName(), new org.apache.hadoop.mapreduce.Job(nwJob.getConfiguration()));
}
// the OutputFormat we report to Hadoop is always PigOutputFormat
nwJob.setOutputFormatClass(PigOutputFormat.class);
if (mapStores.size() + reduceStores.size() == 1) { // single store case
log.info("Setting up single store job");
POStore st;
if (reduceStores.isEmpty()) {
st = mapStores.get(0);
if(!pigContext.inIllustrator)
mro.mapPlan.remove(st);
}
else {
st = reduceStores.get(0);
if(!pigContext.inIllustrator)
mro.reducePlan.remove(st);
}
// set out filespecs
String outputPathString = st.getSFile().getFileName();
if (!outputPathString.contains("://") || outputPathString.startsWith("hdfs://")) {
conf.set("pig.streaming.log.dir",
new Path(outputPathString, LOG_DIR).toString());
} else {
String tmpLocationStr = FileLocalizer
.getTemporaryPath(pigContext).toString();
tmpLocation = new Path(tmpLocationStr);
conf.set("pig.streaming.log.dir",
new Path(tmpLocation, LOG_DIR).toString());
}
conf.set("pig.streaming.task.output.dir", outputPathString);
}
else if (mapStores.size() + reduceStores.size() > 0) { // multi store case
log.info("Setting up multi store job");
String tmpLocationStr = FileLocalizer
.getTemporaryPath(pigContext).toString();
tmpLocation = new Path(tmpLocationStr);
nwJob.setOutputFormatClass(PigOutputFormat.class);
boolean disableCounter = conf.getBoolean("pig.disable.counter", false);
if (disableCounter) {
log.info("Disable Pig custom output counters");
}
int idx = 0;
for (POStore sto: storeLocations) {
sto.setDisableCounter(disableCounter);
sto.setMultiStore(true);
sto.setIndex(idx++);
}
conf.set("pig.streaming.log.dir",
new Path(tmpLocation, LOG_DIR).toString());
conf.set("pig.streaming.task.output.dir", tmpLocation.toString());
}
// store map key type
// this is needed when the key is null to create
// an appropriate NullableXXXWritable object
conf.set("pig.map.keytype", ObjectSerializer.serialize(new byte[] { mro.mapKeyType }));
// set parent plan in all operators in map and reduce plans
// currently the parent plan is really used only when POStream is present in the plan
new PhyPlanSetter(mro.mapPlan).visit();
new PhyPlanSetter(mro.reducePlan).visit();
// this call modifies the ReplFiles names of POFRJoin operators
// within the MR plans, must be called before the plans are
// serialized
setupDistributedCacheForJoin(mro, pigContext, conf);
// Search to see if we have any UDFs that need to pack things into the
// distrubted cache.
setupDistributedCacheForUdfs(mro, pigContext, conf);
POPackage pack = null;
if(mro.reducePlan.isEmpty()){
//MapOnly Job
nwJob.setMapperClass(PigMapOnly.Map.class);
nwJob.setNumReduceTasks(0);
if(!pigContext.inIllustrator)
conf.set("pig.mapPlan", ObjectSerializer.serialize(mro.mapPlan));
if(mro.isEndOfAllInputSetInMap()) {
// this is used in Map.close() to decide whether the
// pipeline needs to be rerun one more time in the close()
// The pipeline is rerun if there either was a stream or POMergeJoin
conf.set(END_OF_INP_IN_MAP, "true");
}
}
else{
//Map Reduce Job
//Process the POPackage operator and remove it from the reduce plan
if(!mro.combinePlan.isEmpty()){
POPackage combPack = (POPackage)mro.combinePlan.getRoots().get(0);
mro.combinePlan.remove(combPack);
nwJob.setCombinerClass(PigCombiner.Combine.class);
conf.set("pig.combinePlan", ObjectSerializer.serialize(mro.combinePlan));
conf.set("pig.combine.package", ObjectSerializer.serialize(combPack));
} else if (mro.needsDistinctCombiner()) {
nwJob.setCombinerClass(DistinctCombiner.Combine.class);
log.info("Setting identity combiner class.");
}
pack = (POPackage)mro.reducePlan.getRoots().get(0);
if(!pigContext.inIllustrator)
mro.reducePlan.remove(pack);
nwJob.setMapperClass(PigMapReduce.Map.class);
nwJob.setReducerClass(PigMapReduce.Reduce.class);
// first check the PARALLE in query, then check the defaultParallel in PigContext, and last do estimation
if (mro.requestedParallelism > 0)
nwJob.setNumReduceTasks(mro.requestedParallelism);
else if (pigContext.defaultParallel > 0)
conf.set("mapred.reduce.tasks", ""+pigContext.defaultParallel);
else
estimateNumberOfReducers(conf,lds);
if (mro.customPartitioner != null)
nwJob.setPartitionerClass(PigContext.resolveClassName(mro.customPartitioner));
if(!pigContext.inIllustrator)
conf.set("pig.mapPlan", ObjectSerializer.serialize(mro.mapPlan));
if(mro.isEndOfAllInputSetInMap()) {
// this is used in Map.close() to decide whether the
// pipeline needs to be rerun one more time in the close()
// The pipeline is rerun only if there was a stream or merge-join.
conf.set(END_OF_INP_IN_MAP, "true");
}
if(!pigContext.inIllustrator)
conf.set("pig.reducePlan", ObjectSerializer.serialize(mro.reducePlan));
if(mro.isEndOfAllInputSetInReduce()) {
// this is used in Map.close() to decide whether the
// pipeline needs to be rerun one more time in the close()
// The pipeline is rerun only if there was a stream
conf.set("pig.stream.in.reduce", "true");
}
if (!pigContext.inIllustrator)
conf.set("pig.reduce.package", ObjectSerializer.serialize(pack));
conf.set("pig.reduce.key.type", Byte.toString(pack.getKeyType()));
if (mro.getUseSecondaryKey()) {
nwJob.setGroupingComparatorClass(PigSecondaryKeyGroupComparator.class);
nwJob.setPartitionerClass(SecondaryKeyPartitioner.class);
nwJob.setSortComparatorClass(PigSecondaryKeyComparator.class);
nwJob.setOutputKeyClass(NullableTuple.class);
conf.set("pig.secondarySortOrder",
ObjectSerializer.serialize(mro.getSecondarySortOrder()));
}
else
{
Class<? extends WritableComparable> keyClass = HDataType.getWritableComparableTypes(pack.getKeyType()).getClass();
nwJob.setOutputKeyClass(keyClass);
selectComparator(mro, pack.getKeyType(), nwJob);
}
nwJob.setOutputValueClass(NullableTuple.class);
}
if(mro.isGlobalSort() || mro.isLimitAfterSort()){
// Only set the quantiles file and sort partitioner if we're a
// global sort, not for limit after sort.
if (mro.isGlobalSort()) {
String symlink = addSingleFileToDistributedCache(
pigContext, conf, mro.getQuantFile(), "pigsample");
conf.set("pig.quantilesFile", symlink);
nwJob.setPartitionerClass(WeightedRangePartitioner.class);
}
if (mro.isUDFComparatorUsed) {
boolean usercomparator = false;
for (String compFuncSpec : mro.UDFs) {
Class comparator = PigContext.resolveClassName(compFuncSpec);
if(ComparisonFunc.class.isAssignableFrom(comparator)) {
nwJob.setMapperClass(PigMapReduce.MapWithComparator.class);
nwJob.setReducerClass(PigMapReduce.ReduceWithComparator.class);
conf.set("pig.reduce.package", ObjectSerializer.serialize(pack));
conf.set("pig.usercomparator", "true");
nwJob.setOutputKeyClass(NullableTuple.class);
nwJob.setSortComparatorClass(comparator);
usercomparator = true;
break;
}
}
if (!usercomparator) {
String msg = "Internal error. Can't find the UDF comparator";
throw new IOException (msg);
}
} else {
conf.set("pig.sortOrder",
ObjectSerializer.serialize(mro.getSortOrder()));
}
}
if (mro.isSkewedJoin()) {
String symlink = addSingleFileToDistributedCache(pigContext,
conf, mro.getSkewedJoinPartitionFile(), "pigdistkey");
conf.set("pig.keyDistFile", symlink);
nwJob.setPartitionerClass(SkewedPartitioner.class);
nwJob.setMapperClass(PigMapReduce.MapWithPartitionIndex.class);
nwJob.setMapOutputKeyClass(NullablePartitionWritable.class);
nwJob.setGroupingComparatorClass(PigGroupingPartitionWritableComparator.class);
}
if (!pigContext.inIllustrator)
{
// unset inputs for POStore, otherwise, map/reduce plan will be unnecessarily deserialized
for (POStore st: mapStores) { st.setInputs(null); st.setParentPlan(null);}
for (POStore st: reduceStores) { st.setInputs(null); st.setParentPlan(null);}
conf.set(PIG_MAP_STORES, ObjectSerializer.serialize(mapStores));
conf.set(PIG_REDUCE_STORES, ObjectSerializer.serialize(reduceStores));
}
// tmp file compression setups
if (Utils.tmpFileCompression(pigContext)) {
conf.setBoolean("pig.tmpfilecompression", true);
conf.set("pig.tmpfilecompression.codec", Utils.tmpFileCompressionCodec(pigContext));
}
String tmp;
long maxCombinedSplitSize = 0;
if (!mro.combineSmallSplits() || pigContext.getProperties().getProperty("pig.splitCombination", "true").equals("false"))
conf.setBoolean("pig.noSplitCombination", true);
else if ((tmp = pigContext.getProperties().getProperty("pig.maxCombinedSplitSize", null)) != null) {
try {
maxCombinedSplitSize = Long.parseLong(tmp);
} catch (NumberFormatException e) {
log.warn("Invalid numeric format for pig.maxCombinedSplitSize; use the default maximum combined split size");
}
}
if (maxCombinedSplitSize > 0)
conf.setLong("pig.maxCombinedSplitSize", maxCombinedSplitSize);
// It's a hack to set distributed cache file for hadoop 23. Once MiniMRCluster do not require local
// jar on fixed location, this can be removed
if (pigContext.getExecType() == ExecType.MAPREDUCE) {
String newfiles = conf.get("alternative.mapreduce.job.cache.files");
if (newfiles!=null) {
String files = conf.get("mapreduce.job.cache.files");
conf.set("mapreduce.job.cache.files",
files == null ? newfiles.toString() : files + "," + newfiles);
}
}
// Serialize the UDF specific context info.
UDFContext.getUDFContext().serialize(conf);
Job cjob = new Job(new JobConf(nwJob.getConfiguration()), new ArrayList());
jobStoreMap.put(cjob,new Pair<List<POStore>, Path>(storeLocations, tmpLocation));
return cjob;
} catch (JobCreationException jce) {
throw jce;
} catch(Exception e) {
int errCode = 2017;
String msg = "Internal error creating job configuration.";
throw new JobCreationException(msg, errCode, PigException.BUG, e);
}
}
/**
* Currently the estimation of reducer number is only applied to HDFS, The estimation is based on the input size of data storage on HDFS.
* Two parameters can been configured for the estimation, one is pig.exec.reducers.max which constrain the maximum number of reducer task (default is 999). The other
* is pig.exec.reducers.bytes.per.reducer(default value is 1000*1000*1000) which means the how much data can been handled for each reducer.
* e.g. the following is your pig script
* a = load '/data/a';
* b = load '/data/b';
* c = join a by $0, b by $0;
* store c into '/tmp';
*
* The size of /data/a is 1000*1000*1000, and size of /data/b is 2*1000*1000*1000.
* Then the estimated reducer number is (1000*1000*1000+2*1000*1000*1000)/(1000*1000*1000)=3
* @param conf
* @param lds
* @throws IOException
*/
static int estimateNumberOfReducers(Configuration conf, List<POLoad> lds) throws IOException {
long bytesPerReducer = conf.getLong("pig.exec.reducers.bytes.per.reducer", (1000 * 1000 * 1000));
int maxReducers = conf.getInt("pig.exec.reducers.max", 999);
long totalInputFileSize = getTotalInputFileSize(conf, lds);
log.info("BytesPerReducer=" + bytesPerReducer + " maxReducers="
+ maxReducers + " totalInputFileSize=" + totalInputFileSize);
int reducers = (int)Math.ceil((totalInputFileSize+0.0) / bytesPerReducer);
reducers = Math.max(1, reducers);
reducers = Math.min(maxReducers, reducers);
conf.setInt("mapred.reduce.tasks", reducers);
log.info("Neither PARALLEL nor default parallelism is set for this job. Setting number of reducers to " + reducers);
return reducers;
}
private static long getTotalInputFileSize(Configuration conf, List<POLoad> lds) throws IOException {
List<String> inputs = new ArrayList<String>();
if(lds!=null && lds.size()>0){
for (POLoad ld : lds) {
inputs.add(ld.getLFile().getFileName());
}
}
long size = 0;
for (String input : inputs){
//Using custom uri parsing because 'new Path(location).toUri()' fails
// for some valid uri's (eg jdbc style), and 'new Uri(location)' fails
// for valid hdfs paths that contain curly braces
if(!UriUtil.isHDFSFileOrLocalOrS3N(input)){
//skip if it is not hdfs or local file or s3n
continue;
}
//the input file location might be a list of comma separeated files,
// separate them out
for(String location : LoadFunc.getPathStrings(input)){
if(! UriUtil.isHDFSFileOrLocalOrS3N(location)){
continue;
}
Path path = new Path(location);
FileSystem fs = path.getFileSystem(conf);
FileStatus[] status=fs.globStatus(path);
if (status != null){
for (FileStatus s : status){
size += getPathLength(fs, s);
}
}
}
}
return size;
}
private static long getPathLength(FileSystem fs,FileStatus status) throws IOException{
if (!status.isDir()){
return status.getLen();
}else{
FileStatus[] children = fs.listStatus(status.getPath());
long size=0;
for (FileStatus child : children){
size +=getPathLength(fs, child);
}
return size;
}
}
public static class PigSecondaryKeyGroupComparator extends WritableComparator {
public PigSecondaryKeyGroupComparator() {
// super(TupleFactory.getInstance().tupleClass(), true);
super(NullableTuple.class, true);
}
@SuppressWarnings("unchecked")
@Override
public int compare(WritableComparable a, WritableComparable b)
{
PigNullableWritable wa = (PigNullableWritable)a;
PigNullableWritable wb = (PigNullableWritable)b;
if ((wa.getIndex() & PigNullableWritable.mqFlag) != 0) { // this is a multi-query index
if ((wa.getIndex() & PigNullableWritable.idxSpace) < (wb.getIndex() & PigNullableWritable.idxSpace)) return -1;
else if ((wa.getIndex() & PigNullableWritable.idxSpace) > (wb.getIndex() & PigNullableWritable.idxSpace)) return 1;
// If equal, we fall through
}
// wa and wb are guaranteed to be not null, POLocalRearrange will create a tuple anyway even if main key and secondary key
// are both null; however, main key can be null, we need to check for that using the same logic we have in PigNullableWritable
Object valuea = null;
Object valueb = null;
try {
// Get the main key from compound key
valuea = ((Tuple)wa.getValueAsPigType()).get(0);
valueb = ((Tuple)wb.getValueAsPigType()).get(0);
} catch (ExecException e) {
throw new RuntimeException("Unable to access tuple field", e);
}
if (!wa.isNull() && !wb.isNull()) {
int result = DataType.compare(valuea, valueb);
// If any of the field inside tuple is null, then we do not merge keys
// See PIG-927
if (result == 0 && valuea instanceof Tuple && valueb instanceof Tuple)
{
try {
for (int i=0;i<((Tuple)valuea).size();i++)
if (((Tuple)valueb).get(i)==null)
return (wa.getIndex()&PigNullableWritable.idxSpace) - (wb.getIndex()&PigNullableWritable.idxSpace);
} catch (ExecException e) {
throw new RuntimeException("Unable to access tuple field", e);
}
}
return result;
} else if (valuea==null && valueb==null) {
// If they're both null, compare the indicies
if ((wa.getIndex() & PigNullableWritable.idxSpace) < (wb.getIndex() & PigNullableWritable.idxSpace)) return -1;
else if ((wa.getIndex() & PigNullableWritable.idxSpace) > (wb.getIndex() & PigNullableWritable.idxSpace)) return 1;
else return 0;
}
else if (valuea==null) return -1;
else return 1;
}
}
public static class PigWritableComparator extends WritableComparator {
@SuppressWarnings("unchecked")
protected PigWritableComparator(Class c) {
super(c);
}
@Override
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2){
return WritableComparator.compareBytes(b1, s1, l1, b2, s2, l2);
}
}
public static class PigBooleanWritableComparator extends PigWritableComparator {
public PigBooleanWritableComparator() {
super(NullableBooleanWritable.class);
}
}
public static class PigIntWritableComparator extends PigWritableComparator {
public PigIntWritableComparator() {
super(NullableIntWritable.class);
}
}
public static class PigLongWritableComparator extends PigWritableComparator {
public PigLongWritableComparator() {
super(NullableLongWritable.class);
}
}
public static class PigFloatWritableComparator extends PigWritableComparator {
public PigFloatWritableComparator() {
super(NullableFloatWritable.class);
}
}
public static class PigDoubleWritableComparator extends PigWritableComparator {
public PigDoubleWritableComparator() {
super(NullableDoubleWritable.class);
}
}
public static class PigCharArrayWritableComparator extends PigWritableComparator {
public PigCharArrayWritableComparator() {
super(NullableText.class);
}
}
public static class PigDBAWritableComparator extends PigWritableComparator {
public PigDBAWritableComparator() {
super(NullableBytesWritable.class);
}
}
public static class PigTupleWritableComparator extends PigWritableComparator {
public PigTupleWritableComparator() {
super(TupleFactory.getInstance().tupleClass());
}
}
public static class PigBagWritableComparator extends PigWritableComparator {
public PigBagWritableComparator() {
super(BagFactory.getInstance().newDefaultBag().getClass());
}
}
// XXX hadoop 20 new API integration: we need to explicitly set the Grouping
// Comparator
public static class PigGroupingBooleanWritableComparator extends WritableComparator {
public PigGroupingBooleanWritableComparator() {
super(NullableBooleanWritable.class, true);
}
}
public static class PigGroupingIntWritableComparator extends WritableComparator {
public PigGroupingIntWritableComparator() {
super(NullableIntWritable.class, true);
}
}
public static class PigGroupingLongWritableComparator extends WritableComparator {
public PigGroupingLongWritableComparator() {
super(NullableLongWritable.class, true);
}
}
public static class PigGroupingFloatWritableComparator extends WritableComparator {
public PigGroupingFloatWritableComparator() {
super(NullableFloatWritable.class, true);
}
}
public static class PigGroupingDoubleWritableComparator extends WritableComparator {
public PigGroupingDoubleWritableComparator() {
super(NullableDoubleWritable.class, true);
}
}
public static class PigGroupingCharArrayWritableComparator extends WritableComparator {
public PigGroupingCharArrayWritableComparator() {
super(NullableText.class, true);
}
}
public static class PigGroupingDBAWritableComparator extends WritableComparator {
public PigGroupingDBAWritableComparator() {
super(NullableBytesWritable.class, true);
}
}
public static class PigGroupingTupleWritableComparator extends WritableComparator {
public PigGroupingTupleWritableComparator() {
super(NullableTuple.class, true);
}
}
public static class PigGroupingPartitionWritableComparator extends WritableComparator {
public PigGroupingPartitionWritableComparator() {
super(NullablePartitionWritable.class, true);
}
}
public static class PigGroupingBagWritableComparator extends WritableComparator {
public PigGroupingBagWritableComparator() {
super(BagFactory.getInstance().newDefaultBag().getClass(), true);
}
}
private void selectComparator(
MapReduceOper mro,
byte keyType,
org.apache.hadoop.mapreduce.Job job) throws JobCreationException {
// If this operator is involved in an order by, use the pig specific raw
// comparators. If it has a cogroup, we need to set the comparator class
// to the raw comparator and the grouping comparator class to pig specific
// raw comparators (which skip the index). Otherwise use the hadoop provided
// raw comparator.
// An operator has an order by if global sort is set or if it's successor has
// global sort set (because in that case it's the sampling job) or if
// it's a limit after a sort.
boolean hasOrderBy = false;
if (mro.isGlobalSort() || mro.isLimitAfterSort() || mro.usingTypedComparator()) {
hasOrderBy = true;
} else {
List<MapReduceOper> succs = plan.getSuccessors(mro);
if (succs != null) {
MapReduceOper succ = succs.get(0);
if (succ.isGlobalSort()) hasOrderBy = true;
}
}
if (hasOrderBy) {
switch (keyType) {
case DataType.BOOLEAN:
job.setSortComparatorClass(PigBooleanRawComparator.class);
break;
case DataType.INTEGER:
job.setSortComparatorClass(PigIntRawComparator.class);
break;
case DataType.LONG:
job.setSortComparatorClass(PigLongRawComparator.class);
break;
case DataType.FLOAT:
job.setSortComparatorClass(PigFloatRawComparator.class);
break;
case DataType.DOUBLE:
job.setSortComparatorClass(PigDoubleRawComparator.class);
break;
case DataType.CHARARRAY:
job.setSortComparatorClass(PigTextRawComparator.class);
break;
case DataType.BYTEARRAY:
job.setSortComparatorClass(PigBytesRawComparator.class);
break;
case DataType.MAP:
int errCode = 1068;
String msg = "Using Map as key not supported.";
throw new JobCreationException(msg, errCode, PigException.INPUT);
case DataType.TUPLE:
job.setSortComparatorClass(PigTupleSortComparator.class);
break;
case DataType.BAG:
errCode = 1068;
msg = "Using Bag as key not supported.";
throw new JobCreationException(msg, errCode, PigException.INPUT);
default:
break;
}
return;
}
switch (keyType) {
case DataType.BOOLEAN:
job.setSortComparatorClass(PigBooleanWritableComparator.class);
job.setGroupingComparatorClass(PigGroupingBooleanWritableComparator.class);
break;
case DataType.INTEGER:
job.setSortComparatorClass(PigIntWritableComparator.class);
job.setGroupingComparatorClass(PigGroupingIntWritableComparator.class);
break;
case DataType.LONG:
job.setSortComparatorClass(PigLongWritableComparator.class);
job.setGroupingComparatorClass(PigGroupingLongWritableComparator.class);
break;
case DataType.FLOAT:
job.setSortComparatorClass(PigFloatWritableComparator.class);
job.setGroupingComparatorClass(PigGroupingFloatWritableComparator.class);
break;
case DataType.DOUBLE:
job.setSortComparatorClass(PigDoubleWritableComparator.class);
job.setGroupingComparatorClass(PigGroupingDoubleWritableComparator.class);
break;
case DataType.CHARARRAY:
job.setSortComparatorClass(PigCharArrayWritableComparator.class);
job.setGroupingComparatorClass(PigGroupingCharArrayWritableComparator.class);
break;
case DataType.BYTEARRAY:
job.setSortComparatorClass(PigDBAWritableComparator.class);
job.setGroupingComparatorClass(PigGroupingDBAWritableComparator.class);
break;
case DataType.MAP:
int errCode = 1068;
String msg = "Using Map as key not supported.";
throw new JobCreationException(msg, errCode, PigException.INPUT);
case DataType.TUPLE:
job.setSortComparatorClass(PigTupleWritableComparator.class);
job.setGroupingComparatorClass(PigGroupingTupleWritableComparator.class);
break;
case DataType.BAG:
errCode = 1068;
msg = "Using Bag as key not supported.";
throw new JobCreationException(msg, errCode, PigException.INPUT);
default:
errCode = 2036;
msg = "Unhandled key type " + DataType.findTypeName(keyType);
throw new JobCreationException(msg, errCode, PigException.BUG);
}
}
private void setupDistributedCacheForJoin(MapReduceOper mro,
PigContext pigContext, Configuration conf) throws IOException {
new JoinDistributedCacheVisitor(mro.mapPlan, pigContext, conf)
.visit();
new JoinDistributedCacheVisitor(mro.reducePlan, pigContext, conf)
.visit();
}
private void setupDistributedCacheForUdfs(MapReduceOper mro,
PigContext pigContext,
Configuration conf) throws IOException {
new UdfDistributedCacheVisitor(mro.mapPlan, pigContext, conf).visit();
new UdfDistributedCacheVisitor(mro.reducePlan, pigContext, conf).visit();
}
private static void setupDistributedCache(PigContext pigContext,
Configuration conf,
Properties properties, String key,
boolean shipToCluster)
throws IOException {
// Set up the DistributedCache for this job
String fileNames = properties.getProperty(key);
if (fileNames != null) {
String[] paths = fileNames.split(",");
setupDistributedCache(pigContext, conf, paths, shipToCluster);
}
}
private static void setupDistributedCache(PigContext pigContext,
Configuration conf, String[] paths, boolean shipToCluster) throws IOException {
// Turn on the symlink feature
DistributedCache.createSymlink(conf);
for (String path : paths) {
path = path.trim();
if (path.length() != 0) {
Path src = new Path(path);
// Ensure that 'src' is a valid URI
URI srcURI = null;
try {
srcURI = new URI(src.toString());
} catch (URISyntaxException ue) {
int errCode = 6003;
String msg = "Invalid cache specification. " +
"File doesn't exist: " + src;
throw new ExecException(msg, errCode, PigException.USER_ENVIRONMENT);
}
// Ship it to the cluster if necessary and add to the
// DistributedCache
if (shipToCluster) {
Path dst =
new Path(FileLocalizer.getTemporaryPath(pigContext).toString());
FileSystem fs = dst.getFileSystem(conf);
fs.copyFromLocalFile(src, dst);
// Construct the dst#srcName uri for DistributedCache
URI dstURI = null;
try {
dstURI = new URI(dst.toString() + "#" + src.getName());
} catch (URISyntaxException ue) {
byte errSrc = pigContext.getErrorSource();
int errCode = 0;
switch(errSrc) {
case PigException.REMOTE_ENVIRONMENT:
errCode = 6004;
break;
case PigException.USER_ENVIRONMENT:
errCode = 4004;
break;
default:
errCode = 2037;
break;
}
String msg = "Invalid ship specification. " +
"File doesn't exist: " + dst;
throw new ExecException(msg, errCode, errSrc);
}
DistributedCache.addCacheFile(dstURI, conf);
} else {
DistributedCache.addCacheFile(srcURI, conf);
}
}
}
}
private static String addSingleFileToDistributedCache(
PigContext pigContext, Configuration conf, String filename,
String prefix) throws IOException {
if (!pigContext.inIllustrator && !FileLocalizer.fileExists(filename, pigContext)) {
throw new IOException(
"Internal error: skew join partition file "
+ filename + " does not exist");
}
String symlink = filename;
// XXX Hadoop currently doesn't support distributed cache in local mode.
// This line will be removed after the support is added by Hadoop team.
if (pigContext.getExecType() != ExecType.LOCAL) {
symlink = prefix + "_"
+ Integer.toString(System.identityHashCode(filename)) + "_"
+ Long.toString(System.currentTimeMillis());
filename = filename + "#" + symlink;
setupDistributedCache(pigContext, conf, new String[] { filename },
false);
}
return symlink;
}
private static class JoinDistributedCacheVisitor extends PhyPlanVisitor {
private PigContext pigContext = null;
private Configuration conf = null;
public JoinDistributedCacheVisitor(PhysicalPlan plan,
PigContext pigContext, Configuration conf) {
super(plan, new DepthFirstWalker<PhysicalOperator, PhysicalPlan>(
plan));
this.pigContext = pigContext;
this.conf = conf;
}
@Override
public void visitFRJoin(POFRJoin join) throws VisitorException {
// XXX Hadoop currently doesn't support distributed cache in local mode.
// This line will be removed after the support is added
if (pigContext.getExecType() == ExecType.LOCAL) return;
// set up distributed cache for the replicated files
FileSpec[] replFiles = join.getReplFiles();
ArrayList<String> replicatedPath = new ArrayList<String>();
FileSpec[] newReplFiles = new FileSpec[replFiles.length];
// the first input is not replicated
for (int i = 0; i < replFiles.length; i++) {
// ignore fragmented file
String symlink = "";
if (i != join.getFragment()) {
symlink = "pigrepl_" + join.getOperatorKey().toString() + "_"
+ Integer.toString(System.identityHashCode(replFiles[i].getFileName()))
+ "_" + Long.toString(System.currentTimeMillis())
+ "_" + i;
replicatedPath.add(replFiles[i].getFileName() + "#"
+ symlink);
}
newReplFiles[i] = new FileSpec(symlink,
(replFiles[i] == null ? null : replFiles[i].getFuncSpec()));
}
join.setReplFiles(newReplFiles);
try {
setupDistributedCache(pigContext, conf, replicatedPath
.toArray(new String[0]), false);
} catch (IOException e) {
String msg = "Internal error. Distributed cache could not " +
"be set up for the replicated files";
throw new VisitorException(msg, e);
}
}
@Override
public void visitMergeJoin(POMergeJoin join) throws VisitorException {
// XXX Hadoop currently doesn't support distributed cache in local mode.
// This line will be removed after the support is added
if (pigContext.getExecType() == ExecType.LOCAL) return;
String indexFile = join.getIndexFile();
// merge join may not use an index file
if (indexFile == null) return;
try {
String symlink = addSingleFileToDistributedCache(pigContext,
conf, indexFile, "indexfile_");
join.setIndexFile(symlink);
} catch (IOException e) {
String msg = "Internal error. Distributed cache could not " +
"be set up for merge join index file";
throw new VisitorException(msg, e);
}
}
@Override
public void visitMergeCoGroup(POMergeCogroup mergeCoGrp)
throws VisitorException {
// XXX Hadoop currently doesn't support distributed cache in local mode.
// This line will be removed after the support is added
if (pigContext.getExecType() == ExecType.LOCAL) return;
String indexFile = mergeCoGrp.getIndexFileName();
if (indexFile == null) throw new VisitorException("No index file");
try {
String symlink = addSingleFileToDistributedCache(pigContext,
conf, indexFile, "indexfile_mergecogrp_");
mergeCoGrp.setIndexFileName(symlink);
} catch (IOException e) {
String msg = "Internal error. Distributed cache could not " +
"be set up for merge cogrp index file";
throw new VisitorException(msg, e);
}
}
}
private static class UdfDistributedCacheVisitor extends PhyPlanVisitor {
private PigContext pigContext = null;
private Configuration conf = null;
public UdfDistributedCacheVisitor(PhysicalPlan plan,
PigContext pigContext,
Configuration conf) {
super(plan, new DepthFirstWalker<PhysicalOperator, PhysicalPlan>(
plan));
this.pigContext = pigContext;
this.conf = conf;
}
@Override
public void visitUserFunc(POUserFunc func) throws VisitorException {
// XXX Hadoop currently doesn't support distributed cache in local mode.
// This line will be removed after the support is added
if (pigContext.getExecType() == ExecType.LOCAL) return;
// set up distributed cache for files indicated by the UDF
String[] files = func.getCacheFiles();
if (files == null) return;
try {
setupDistributedCache(pigContext, conf, files, false);
} catch (IOException e) {
String msg = "Internal error. Distributed cache could not " +
"be set up for the requested files";
throw new VisitorException(msg, e);
}
}
}
}
| |
/**
* Copyright (C) 2015 DataTorrent, 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.datatorrent.stram.engine;
import java.io.File;
import java.io.Serializable;
import java.util.*;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datatorrent.api.Context;
import com.datatorrent.api.DAG;
import com.datatorrent.api.Stats.OperatorStats;
import com.datatorrent.api.Stats.OperatorStats.PortStats;
import com.datatorrent.api.StatsListener;
import com.datatorrent.common.util.AsyncFSStorageAgent;
import com.datatorrent.common.util.BaseOperator;
import com.datatorrent.stram.StramLocalCluster;
import com.datatorrent.stram.StreamingContainerManager;
import com.datatorrent.stram.engine.StatsTest.TestCollector.TestCollectorStatsListener;
import com.datatorrent.stram.engine.StatsTest.TestOperator.TestInputStatsListener;
import com.datatorrent.stram.plan.logical.LogicalPlan;
import com.datatorrent.stram.plan.physical.PTOperator;
import com.datatorrent.stram.support.StramTestSupport;
/**
* Tests the stats generated in the system.
*
*/
public class StatsTest
{
private static final Logger LOG = LoggerFactory.getLogger(StatsTest.class);
public static class TestOperator extends TestGeneratorInputOperator
{
transient long windowId;
boolean shutdown = false; // make sure shutdown happens after endwindow when stats are generated
@Override
public void beginWindow(long windowId)
{
if (shutdown) {
BaseOperator.shutdown();
}
this.windowId = windowId;
}
@Override
public void emitTuples()
{
try {
if (!shutdown) {
super.emitTuples();
}
}
catch (ShutdownException ex) {
shutdown = true;
}
}
public static class TestInputStatsListener implements StatsListener, Serializable
{
private static final long serialVersionUID = 1L;
private List<OperatorStats> inputOperatorStats = new ArrayList<OperatorStats>();
@Override
public Response processStats(BatchedOperatorStats stats)
{
inputOperatorStats.addAll(stats.getLastWindowedStats());
Response rsp = new Response();
return rsp;
}
}
}
@StatsListener.DataQueueSize
public static class TestCollector extends GenericTestOperator implements StatsListener
{
transient long windowId;
List<OperatorStats> collectorOperatorStats = new ArrayList<OperatorStats>();
@Override
public Response processStats(BatchedOperatorStats stats)
{
collectorOperatorStats.addAll(stats.getLastWindowedStats());
Response rsp = new Response();
return rsp;
}
public void validateStats()
{
for (OperatorStats operatorStats : collectorOperatorStats) {
for (PortStats inputPortStats : operatorStats.inputPorts) {
Assert.assertTrue("Validate input port queue size " + inputPortStats.queueSize, inputPortStats.queueSize == 0);
}
}
}
@Override
public void beginWindow(long windowId)
{
this.windowId = windowId;
}
public static class TestCollectorStatsListener implements StatsListener, Serializable
{
private static final long serialVersionUID = 1L;
List<OperatorStats> collectorOperatorStats = new ArrayList<OperatorStats>();
@Override
public Response processStats(BatchedOperatorStats stats)
{
collectorOperatorStats.addAll(stats.getLastWindowedStats());
Response rsp = new Response();
return rsp;
}
public void validateStats()
{
for (OperatorStats operatorStats : collectorOperatorStats) {
for (PortStats inputPortStats : operatorStats.inputPorts) {
Assert.assertTrue("Validate input port queue size " + inputPortStats.queueSize, inputPortStats.queueSize >= 0);
}
}
}
}
@StatsListener.DataQueueSize
public static class QueueAwareTestCollectorStatsListener extends TestCollectorStatsListener
{
private static final long serialVersionUID = 2L;
public void validateStats()
{
for (OperatorStats operatorStats : collectorOperatorStats) {
for (PortStats inputPortStats : operatorStats.inputPorts) {
Assert.assertTrue("Validate input port queue size " + inputPortStats.queueSize, inputPortStats.queueSize == 0);
}
}
}
}
}
/**
* Verify buffer server bytes and tuple count.
*
* @throws Exception
*/
@Test
@SuppressWarnings("SleepWhileInLoop")
public void testPortStatsPropagation() throws Exception
{
int tupleCount = 10;
LogicalPlan dag = new LogicalPlan();
String workingDir = new File("target").getAbsolutePath();
dag.setAttribute(OperatorContext.STORAGE_AGENT, new AsyncFSStorageAgent(workingDir + "/localPath", workingDir, null));
TestOperator testOper = dag.addOperator("TestOperator", TestOperator.class);
TestInputStatsListener testInputStatsListener = new TestInputStatsListener();
dag.setAttribute(testOper, OperatorContext.STATS_LISTENERS, Arrays.asList(new StatsListener[]{testInputStatsListener}));
testOper.setMaxTuples(tupleCount);
testOper.setEmitInterval(0);
TestCollector collector = dag.addOperator("Collector", new TestCollector());
TestCollectorStatsListener testCollectorStatsListener = new TestCollectorStatsListener();
dag.setAttribute(collector, OperatorContext.STATS_LISTENERS, Arrays.asList(new StatsListener[]{testCollectorStatsListener}));
dag.addStream("TestTuples", testOper.outport, collector.inport1).setLocality(null);
StramLocalCluster lc = new StramLocalCluster(dag);
lc.run();
Assert.assertFalse("input operator stats", testInputStatsListener.inputOperatorStats.isEmpty());
Assert.assertFalse("collector operator stats", testCollectorStatsListener.collectorOperatorStats.isEmpty());
try {
int outputPortTupleCount = 0;
long outputPortBufferServerBytes = 0L;
for (Iterator<OperatorStats> it = testInputStatsListener.inputOperatorStats.iterator(); it.hasNext(); ) {
OperatorStats operatorStats = it.next();
for (PortStats outputPortStats : operatorStats.outputPorts) {
outputPortTupleCount += outputPortStats.tupleCount;
outputPortBufferServerBytes += outputPortStats.bufferServerBytes;
}
}
int inputPortTupleCount = 0;
long inputPortBufferServerBytes = 0L;
for (Iterator<OperatorStats> it = testCollectorStatsListener.collectorOperatorStats.iterator(); it.hasNext(); ) {
OperatorStats operatorStats = it.next();
for (PortStats inputPortStats : operatorStats.inputPorts) {
inputPortTupleCount += inputPortStats.tupleCount;
inputPortBufferServerBytes += inputPortStats.bufferServerBytes;
}
}
Assert.assertEquals("Tuple Count emitted", tupleCount, outputPortTupleCount);
Assert.assertTrue("Buffer server bytes", inputPortBufferServerBytes > 0);
Assert.assertEquals("Tuple Count processed", tupleCount, inputPortTupleCount);
Assert.assertTrue("Buffer server bytes", outputPortBufferServerBytes > 0);
}
finally {
lc.shutdown();
}
}
@SuppressWarnings("SleepWhileInLoop")
private void baseTestForQueueSize(int maxTuples, TestCollectorStatsListener statsListener, DAG.Locality locality) throws Exception
{
LogicalPlan dag = new LogicalPlan();
String workingDir = new File("target/baseTestForQueueSize").getAbsolutePath();
dag.setAttribute(Context.OperatorContext.STORAGE_AGENT, new AsyncFSStorageAgent(workingDir + "/localPath", workingDir, null));
dag.getAttributes().put(LogicalPlan.STREAMING_WINDOW_SIZE_MILLIS, 200);
TestOperator testOper = dag.addOperator("TestOperator", TestOperator.class);
testOper.setMaxTuples(maxTuples);
TestCollector collector = dag.addOperator("Collector", new TestCollector());
if (statsListener != null) {
dag.setAttribute(collector, OperatorContext.STATS_LISTENERS, Arrays.asList(new StatsListener[]{statsListener}));
}
dag.addStream("TestTuples", testOper.outport, collector.inport1).setLocality(locality);
StramLocalCluster lc = new StramLocalCluster(dag);
lc.runAsync();
StreamingContainerManager dnmgr = lc.getStreamingContainerManager();
Map<Integer, PTOperator> operatorMap = dnmgr.getPhysicalPlan().getAllOperators();
for (PTOperator p : operatorMap.values()) {
StramTestSupport.waitForActivation(lc, p);
}
long startTms = System.currentTimeMillis();
if (statsListener != null) {
while (statsListener.collectorOperatorStats.isEmpty() && (StramTestSupport.DEFAULT_TIMEOUT_MILLIS > System.currentTimeMillis() - startTms)) {
Thread.sleep(300);
LOG.debug("Waiting for stats");
}
}
else {
while (collector.collectorOperatorStats.isEmpty() && (StramTestSupport.DEFAULT_TIMEOUT_MILLIS > System.currentTimeMillis() - startTms)) {
Thread.sleep(300);
LOG.debug("Waiting for stats");
}
}
if (statsListener != null) {
statsListener.validateStats();
}
else {
collector.validateStats();
}
lc.shutdown();
}
/**
* Verify queue size.
*
* @throws Exception
*/
@Test
public void testQueueSizeForContainerLocalOperators() throws Exception
{
baseTestForQueueSize(10, new TestCollectorStatsListener(), DAG.Locality.CONTAINER_LOCAL);
}
@Test
public void testQueueSize() throws Exception
{
baseTestForQueueSize(10, new TestCollectorStatsListener(), null);
}
/**
* Verify queue size.
*
* @throws Exception
*/
@Test
public void testQueueSizeWithQueueAwareStatsListenerForContainerLocalOperators() throws Exception
{
baseTestForQueueSize(0, new TestCollector.QueueAwareTestCollectorStatsListener(), DAG.Locality.CONTAINER_LOCAL);
}
@Test
public void testQueueSizeWithQueueAwareStatsListener() throws Exception
{
baseTestForQueueSize(0, new TestCollector.QueueAwareTestCollectorStatsListener(), null);
}
@Test
public void testQueueSizeWithOperatorAsStatsListener() throws Exception
{
baseTestForQueueSize(0, null, null);
}
}
| |
package com.nethergrim.combogymdiary.fragments;
import android.app.ActionBar;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.nethergrim.combogymdiary.DB;
import com.nethergrim.combogymdiary.R;
import com.nethergrim.combogymdiary.activities.HistoryDetailedActivity;
import com.nethergrim.combogymdiary.dialogs.DialogAddCommentToTraining;
import com.nethergrim.combogymdiary.dialogs.DialogAddExercises;
import com.nethergrim.combogymdiary.dialogs.DialogExitFromTraining;
import com.nethergrim.combogymdiary.model.Exercise;
import com.nethergrim.combogymdiary.model.ExerciseTrainingObject;
import com.nethergrim.combogymdiary.model.TrainingRow;
import com.nethergrim.combogymdiary.service.TrainingService;
import com.nethergrim.combogymdiary.tools.Prefs;
import com.nethergrim.combogymdiary.view.DraggableListView;
import com.nethergrim.combogymdiary.view.FAB;
import com.nethergrim.combogymdiary.view.TextViewLight;
import com.yandex.metrica.Counter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelTextAdapter;
public class TrainingFragment extends Fragment implements
OnCheckedChangeListener, OnClickListener, DraggableListView.OnListItemSwapListener, DialogAddExercises.OnExerciseAddCallback {
public static final String BUNDLE_KEY_TRAINING_ID = "com.nethergrim.combogymdiary.TRAINING_ID";
private ActionBar actionBar;
private Boolean tglChecked = true, vibrate = false;
private EditText etTimer;
private DB db;
private String trainingName = "", currentExerciseName = "", date = "";
private int currentCheckedPosition = 0, set = 0, currentSet = 0, oldReps = 0,
oldWeight = 0, timerValue = 0, vibrateLenght = 0, currentId = 0;
private long startTime = 0;
private Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = (seconds / 60);
seconds = (seconds % 60);
if (resumed){
actionBar.setSubtitle((String.format("%d:%02d", minutes, seconds)) + " " + " [" + ((set == currentSet ? set : currentSet) + 1) + " " + getResources().getString(R.string.set) + "] ");
}
timerHandler.postDelayed(this, 500);
}
};
private Handler handler;
private WheelView repsWheel, weightWheel;
private TextView tvInfoText;
private boolean btnBlocked = false;
private PopupWindow popupWindow;
private Handler timerHandler = new Handler();
private LinearLayout llBottom;
private Animation anim = null;
private boolean isTrainingAtProgress = false, toPlaySound = false;
private ProgressDialog pd;
private boolean isActiveDialog = false, blocked = false, blockedSelection = false;
private DraggableListView listView;
private TrainingAdapter adapter;
private FAB fabSave, fabBack, fabForward;
private boolean isInActionMode = false;
private boolean resumed = false;
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
isInActionMode = true;
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.cab_training, menu);
fabSave.setVisibility(View.GONE);
fabBack.setVisibility(View.GONE);
fabForward.setVisibility(View.GONE);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
blockedSelection = true;
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
for (int i = 0; i < listView.getCount(); ++i) {
listView.setItemChecked(i, false);
}
llBottom.setVisibility(View.GONE);
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == R.id.cab_delete) {
SparseBooleanArray deletingPositions = listView.getCheckedItemPositions();
for (int i = deletingPositions.size() - 1; i >= 0; --i) {
if (deletingPositions.get(i)) {
adapter.deleteItem(i);
}
}
for (int i = 0; i < listView.getCount(); ++i) {
listView.setItemChecked(i, false);
}
blockedSelection = false;
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
if (listView.getCount() > 0) {
onSelected(0, true);
listView.setItemChecked(0, true);
llBottom.setVisibility(View.VISIBLE);
}
saveExercicesToDatabase();
mode.finish();
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
for (int i = 0; i < listView.getCount(); ++i) {
listView.setItemChecked(i, false);
}
blockedSelection = false;
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
if (listView.getCount() > 0) {
onSelected(0, true);
listView.setItemChecked(0, true);
llBottom.setVisibility(View.VISIBLE);
}
fabSave.setVisibility(View.VISIBLE);
initSetButtons();
isInActionMode = false;
}
};
private int trainingId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
db = new DB(getActivity());
db.open();
trainingId = getArguments().getInt(BUNDLE_KEY_TRAINING_ID);
adapter = new TrainingAdapter(getActivity());
adapter.addData(db.getTrainingRows(trainingId));
isTrainingAtProgress = Prefs.get().getTrainingAtProgress();
Prefs.get().setTrainingAtProgress(true);
Prefs.get().setCurrentTrainingId(trainingId);
trainingName = db.getTrainingName(trainingId);
actionBar = getActivity().getActionBar();
actionBar.setTitle(trainingName);
getActivity().startService(new Intent(getActivity(), TrainingService.class));
if (isTrainingAtProgress){
startTime = Prefs.get().getStartTime();
} else {
startTime = System.currentTimeMillis();
Prefs.get().setStartTime(startTime);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.training_at_progress_new_wheel_new_list, null);
fabBack = (FAB) v.findViewById(R.id.fabBack);
fabBack.setOnClickListener(this);
fabSave = (FAB) v.findViewById(R.id.fabSaveSet);
fabSave.setOnClickListener(this);
fabForward = (FAB) v.findViewById(R.id.fabForward);
fabForward.setOnClickListener(this);
llBottom = (LinearLayout) v.findViewById(R.id.LLBottom);
anim = AnimationUtils.loadAnimation(getActivity(), R.anim.setfortraining);
repsWheel = (WheelView) v.findViewById(R.id.wheelReps);
repsWheel.setVisibleItems(7);
repsWheel.setWheelBackground(R.drawable.card);
repsWheel.setWheelForeground(R.drawable.wheel_foreground);
repsWheel.setShadowColor(0xFFFFFF, 0xFFFFFF, 0xFFFFFF);
repsWheel.setViewAdapter(new RepsAdapter(getActivity()));
weightWheel = (WheelView) v.findViewById(R.id.wheelWeight);
weightWheel.setVisibleItems(7);
weightWheel.setWheelBackground(R.drawable.card);
weightWheel.setWheelForeground(R.drawable.wheel_foreground);
weightWheel.setShadowColor(0xFFFFFF, 0xFFFFFF, 0xFFFFFF);
weightWheel.setViewAdapter(new WeightsAdapter(getActivity()));
ToggleButton tglTimerOn = (ToggleButton) v.findViewById(R.id.tglTurnOff);
tglTimerOn.setOnCheckedChangeListener(this);
etTimer = (EditText) v.findViewById(R.id.etTimerValueAtTraining);
etTimer.setOnClickListener(this);
etTimer.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
updateTimer(s.toString());
}
});
tvInfoText = (TextView) v.findViewById(R.id.infoText);
listView = (DraggableListView) v.findViewById(R.id.listViewExerciseList);
listView.setListener(this);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (!isInActionMode) {
listView.startSwapping();
return true;
}
return false;
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id) {
onSelected(position, true);
}
});
listView.setItemChecked(Prefs.get().getCheckedPosition(), true);
onSelected(Prefs.get().getCheckedPosition(), true);
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
date = sdf.format(new Date(System.currentTimeMillis()));
boolean isTimerOn = Prefs.get().getTimerOn();
if (isTimerOn) {
tglTimerOn.setChecked(true);
tglChecked = true;
etTimer.setEnabled(true);
} else {
tglTimerOn.setChecked(false);
tglChecked = false;
etTimer.setEnabled(false);
}
return v;
}
private void initSetButtons() {
try {
if (set > 0 && currentSet > 0) {
fabBack.setVisibility(View.VISIBLE);
} else {
fabBack.setVisibility(View.GONE);
}
if (currentSet < set) {
fabForward.setVisibility(View.VISIBLE);
} else {
fabForward.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void onSelected(int position, boolean withScroll) {
if (blockedSelection)
return;
if (adapter.getData().size() == 0) {
llBottom.setVisibility(View.GONE);
Toast.makeText(getActivity(), R.string.please_add_an_exe, Toast.LENGTH_LONG).show();
return;
} else {
llBottom.setVisibility(View.VISIBLE);
}
Prefs.get().setCheckedPosition(position);
currentExerciseName = adapter.getData().get(position).getExerciseName();
listView.setItemChecked(position,true);
if (withScroll){
listView.smoothScrollToPosition(position);
}
currentCheckedPosition = position;
set = adapter.getData().get(currentCheckedPosition).getSetsCount();
try {
timerValue = Integer.parseInt(db.getTimerValueByExerciseName(currentExerciseName));
} catch (NumberFormatException e) {
Toast.makeText(getActivity(), R.string.parsing_error, Toast.LENGTH_LONG).show();
timerValue = 60;
Counter.sharedInstance().reportError("", e);
}
currentSet = set;
etTimer.setText(String.valueOf(timerValue));
initSetButtons();
oldReps = db.getLastWeightOrReps(currentExerciseName, set, false);
oldWeight = db.getLastWeightOrReps(currentExerciseName, set, true);
if (oldReps > 0 && oldWeight > 0) {
tvInfoText.setText(getResources().getString(R.string.previous_result_was) + " " + oldWeight + "x" + oldReps);
weightWheel.setCurrentItem(oldWeight - 1);
repsWheel.setCurrentItem(oldReps - 1);
} else {
tvInfoText.setText(getResources().getString(R.string.new_set) + " (" + (set + 1) + ")");
}
blocked = false;
}
@Override
public void onResume() {
super.onResume();
resumed = true;
actionBar.setTitle(trainingName);
listView.setKeepScreenOn(!Prefs.get().getTurnScreenOff());
vibrate = Prefs.get().getVibrateOn();
String vl = Prefs.get().getVibrateLenght();
try {
vibrateLenght = Integer.parseInt(vl) * 1000;
} catch (Exception e) {
vibrateLenght = 2000;
}
toPlaySound = Prefs.get().getNotifyWithSound();
if (isTrainingAtProgress) {
startTime = Prefs.get().getStartTime();
restoreSetsFromPreferences();
try {
listView.setItemChecked(Prefs.get().getCheckedPosition(), true);
onSelected(Prefs.get().getCheckedPosition(), true);
} catch (Exception e) {
listView.setItemChecked(0, true);
onSelected(0, true);
}
}
timerHandler.postDelayed(timerRunnable, 0);
fabSave.setVisibility(View.VISIBLE);
initSetButtons();
handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0) {
this.removeMessages(0);
} else {
pd.setIndeterminate(false);
if (pd.getProgress() < pd.getMax()) {
pd.incrementProgressBy(1);
handler.sendEmptyMessageDelayed(1, 1000);
} else {
if (toPlaySound) {
String sound = Prefs.get().getRingtone();
if (sound == null) {
playSound(getActivity(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
);
} else {
Uri uri = Uri.parse(sound);
playSound(getActivity(), uri);
}
}
if (vibrate) {
try {
Vibrator v = (Vibrator) getActivity()
.getSystemService(
Context.VIBRATOR_SERVICE);
v.vibrate(vibrateLenght);
} catch (Exception e) {
Counter.sharedInstance().reportError("error vibrating", e);
}
}
pd.dismiss();
}
}
}
};
}
private void showProgressDialog(boolean ignoreSuperset) {
if (tglChecked && !adapter.getData().get(currentCheckedPosition).isSuperset() || tglChecked && ignoreSuperset){
Prefs.get().setProgress(0);
pd = new ProgressDialog(getActivity());
pd.setTitle(R.string.resting);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(timerValue);
pd.setCancelable(false);
pd.setButton(DialogInterface.BUTTON_NEGATIVE,
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
handler.removeCallbacksAndMessages(null);
}
}
);
pd.show();
isActiveDialog = true;
handler.sendEmptyMessageDelayed(1, 100);
}
}
@Override
public void onPause() {
super.onPause();
resumed = false;
timerHandler.removeCallbacks(timerRunnable);
saveSetsToPreferences();
isTrainingAtProgress = true;
saveExercicesToDatabase();
getActivity().getActionBar().setSubtitle(null);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.itemExit) {
if (popupWindow != null && popupWindow.isShowing()) {
return false;
}
DialogFragment dlg1 = new DialogExitFromTraining();
dlg1.setCancelable(false);
if (!dlg1.isAdded())
dlg1.show(getFragmentManager(), "dlg1");
} else if (itemId == R.id.item_add_exercises) {
DialogAddExercises dialogAddExercises = new DialogAddExercises();
dialogAddExercises.show(getFragmentManager(), DialogAddExercises.class.getName());
dialogAddExercises.setListener(this);
} else if (itemId == R.id.itemSeePreviousTraining) {
String[] args = {trainingName};
Cursor tmpCursor = db.getDataMain(null, DB.TRAINING_NAME + "=?", args, DB.DATE, null, null);
if (tmpCursor.moveToLast()
&& (tmpCursor.getCount() > 1 || !tmpCursor.getString(3)
.equals(date))) {
if (tmpCursor.getString(3).equals(date)) {
tmpCursor.moveToPrevious();
}
Intent intent_history_detailed = new Intent(getActivity(), HistoryDetailedActivity.class);
intent_history_detailed.putExtra(HistoryDetailedActivity.BUNDLE_KEY_DATE, tmpCursor.getString(3));
intent_history_detailed.putExtra(HistoryDetailedActivity.BUNDLE_KEY_TRAINING_NAME, tmpCursor.getString(1));
startActivity(intent_history_detailed);
tmpCursor.close();
} else {
Toast.makeText(
getActivity(),
getResources().getString(R.string.no_history) + trainingName,
Toast.LENGTH_SHORT).show();
}
} else if (itemId == R.id.itemAddCommentToTraining) {
DialogAddCommentToTraining dialog = new DialogAddCommentToTraining();
dialog.show(getFragmentManager(), "");
} else if (itemId == R.id.itemDeleteExercise) {
getActivity().startActionMode(mActionModeCallback);
}
return false;
}
private void updateTimer(String tmp) {
String timerv;
if (tmp != null) {
timerv = tmp;
} else {
timerv = etTimer.getText().toString();
}
String tmpStr = db.getTimerValueByExerciseName(currentExerciseName);
if (tmpStr != null && timerv != null && !tmpStr.equals(timerv)) {
int exe_id = db.getExeIdByName(currentExerciseName);
db.updateExercise(exe_id, DB.TIMER_VALUE, timerv);
}
try {
timerValue = Integer.parseInt(timerv);
} catch (Exception e) {
timerValue = 60;
}
}
@Override
public void onClick(View arg0) {
int id = arg0.getId();
if (blocked) {
Toast.makeText(getActivity(), getResources().getString(R.string.select_an_exercise), Toast.LENGTH_LONG).show();
return;
}
if (id == R.id.fabSaveSet && currentSet == set && !btnBlocked) {
int wei = (weightWheel.getCurrentItem() + 1);
int rep_s = (repsWheel.getCurrentItem() + 1);
TrainingRow row = adapter.getData().get(currentCheckedPosition);
adapter.getData().get(currentCheckedPosition).incrementSetsCount();
set = adapter.getData().get(currentCheckedPosition).getSetsCount();
db.addRecMainTable(trainingName, currentExerciseName, date, wei, rep_s, set,row.isSuperset(),row.getSupersetId(), row.getSupersetColor(), trainingId, row.getExerciseId());
currentSet = set;
initSetButtons();
try {
Toast.makeText(getActivity(), R.string.saved, Toast.LENGTH_SHORT).show();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
if (isActiveDialog) {
handler.sendEmptyMessage(0);
}
showPopup();
oldReps = db.getLastWeightOrReps(currentExerciseName, set, false);
oldWeight = db.getLastWeightOrReps(currentExerciseName, set, true);
if (oldReps > 0 && oldWeight > 0) {
tvInfoText.setText(getResources().getString(
R.string.previous_result_was) + " " + oldWeight + "x" + oldReps);
weightWheel.setCurrentItem(oldWeight - 1);
repsWheel.setCurrentItem(oldReps - 1);
} else {
tvInfoText.setText(getResources().getString(R.string.new_set) + " (" + (set + 1) + ")");
}
} else if (id == R.id.fabSaveSet && currentSet < set) {
int wei = (weightWheel.getCurrentItem() + 1);
int rep_s = (repsWheel.getCurrentItem() + 1);
db.updateRec_Main(currentId, 4, null, wei);
db.updateRec_Main(currentId, 5, null, rep_s);
Toast.makeText(getActivity(), R.string.resaved, Toast.LENGTH_SHORT).show();
currentSet = set;
onSelected(currentCheckedPosition, true);
} else if (id == R.id.fabBack) {
if (currentSet > 0) {
llBottom.startAnimation(anim);
currentSet--;
int weitghsS = db.getThisWeight(currentSet + 1, currentExerciseName) - 1;
int repsS = db.getThisReps(currentSet + 1, currentExerciseName) - 1;
currentId = db.getThisId(currentSet + 1, currentExerciseName);
weightWheel.setCurrentItem(weitghsS);
repsWheel.setCurrentItem(repsS);
tvInfoText.setText(getResources().getString(
R.string.resaved_text) + " " + (weitghsS + 1) + "x" + (repsS + 1) + " (" + (currentSet + 1) + ")");
}
} else if (id == R.id.fabForward) {
if (currentSet < set - 1) {
llBottom.startAnimation(anim);
currentSet++;
int weitghsS = db.getThisWeight(currentSet + 1, currentExerciseName) - 1;
int repsS = db.getThisReps(currentSet + 1, currentExerciseName) - 1;
weightWheel.setCurrentItem(weitghsS);
repsWheel.setCurrentItem(repsS);
tvInfoText.setText(getResources().getString(
R.string.resaved_text) + " " + (weitghsS + 1) + "x" + (repsS + 1) + " (" + (currentSet + 1) + ")");
} else if (currentSet == set - 1) {
llBottom.startAnimation(anim);
onSelected(currentCheckedPosition, true);
}
}
initSetButtons();
}
private void showPopup() {
if (oldReps > 0 && oldWeight > 0) {
int wei = (weightWheel.getCurrentItem() + 1);
int rep_s = (repsWheel.getCurrentItem() + 1);
int weightDelta = wei - oldWeight;
int repsDelta = rep_s - oldReps;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.popup_training_layout, null);
TextView textViewWeightDelta = (TextView) v.findViewById(R.id.text_weight_delta);
TextView text1 = (TextView) v.findViewById(R.id.text_1);
TextView textViewRepsDelta = (TextView) v.findViewById(R.id.text_reps_delta);
TextView text2 = (TextView) v.findViewById(R.id.text2);
int green = getActivity().getResources().getColor(R.color.material_green_a400);
int red = getActivity().getResources().getColor(R.color.material_pink_a400);
if (weightDelta >= 0) {
textViewWeightDelta.setTextColor(green);
text1.setTextColor(green);
textViewWeightDelta.setText("+" + String.valueOf(weightDelta));
} else {
textViewWeightDelta.setTextColor(red);
text1.setTextColor(red);
textViewWeightDelta.setText(String.valueOf(weightDelta));
}
if (repsDelta >= 0) {
textViewRepsDelta.setTextColor(green);
text2.setTextColor(green);
textViewRepsDelta.setText("+" + String.valueOf(weightDelta));
} else {
textViewRepsDelta.setText(String.valueOf(repsDelta));
textViewRepsDelta.setTextColor(red);
text2.setTextColor(red);
}
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int widthDp = dpFromPx(display.getWidth());
popupWindow = new PopupWindow(v, pxFromDp(widthDp - 24), pxFromDp(120));
popupWindow.setAnimationStyle(R.style.PopupAnimation);
popupWindow.showAsDropDown(listView, pxFromDp(8), pxFromDp(20));
btnBlocked = true;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2500);
} catch (Exception e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
hidePopup();
}
});
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
showProgressDialog(false);
}
});
}
});
thread.start();
} else {
showProgressDialog(false);
}
goToNextExerciseInSuperset();
}
private void hidePopup() {
btnBlocked = false;
if (popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
}
}
@Override
public void onCheckedChanged(CompoundButton tglTimerOn, boolean isChecked) {
if (isChecked) {
Prefs.get().setTimerOn(true);
tglChecked = true;
etTimer.setEnabled(true);
} else {
Prefs.get().setTimerOn(false);
tglChecked = false;
etTimer.setEnabled(false);
}
}
public void saveSetsToPreferences() {// FIXME make at background
List<TrainingRow> currentData = adapter.getData();
JSONArray jsonArray = new JSONArray();
for (TrainingRow aCurrentData : currentData) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("setCount", aCurrentData.getSetsCount());
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
Prefs.get().saveSets(jsonArray.toString());
}
public void restoreSetsFromPreferences() {// FIXME make at background
try {
JSONArray jsonArray = new JSONArray(Prefs.get().getSavedSets());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject tmp = (JSONObject) jsonArray.get(i);
if (i < adapter.getCount())
adapter.getData().get(i).setSetsCount(tmp.getInt("setCount"));
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void saveExercicesToDatabase() { // FIXME make at background
List<TrainingRow> currentData = adapter.getData();
db.deleteTrainingProgram(trainingId, true);
for (int i = 0; i < currentData.size(); i++) {
ExerciseTrainingObject exerciseTrainingObject = new ExerciseTrainingObject();
TrainingRow row = currentData.get(i);
exerciseTrainingObject.setTrainingProgramId(trainingId);
exerciseTrainingObject.setExerciseId(row.getExerciseId());
exerciseTrainingObject.setPositionAtTraining(i);
if (row.isSuperset()) {
exerciseTrainingObject.setSuperset(true);
exerciseTrainingObject.setSupersetColor(row.getSupersetColor());
exerciseTrainingObject.setPositionAtSuperset(row.getPositionAtSuperset());
exerciseTrainingObject.setSupersetId(row.getSupersetId());
} else {
exerciseTrainingObject.setSupersetId(0);
exerciseTrainingObject.setSupersetColor(0);
exerciseTrainingObject.setSuperset(false);
exerciseTrainingObject.setPositionAtSuperset(0);
}
db.addExerciseTrainingObject(exerciseTrainingObject);
}
}
private void playSound(Context context, Uri sound) {
MediaPlayer mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, sound);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private int dpFromPx(float px) {
return (int) (px / getActivity().getResources().getDisplayMetrics().density);
}
private int pxFromDp(float dp) {
return (int) (dp * getActivity().getResources().getDisplayMetrics().density);
}
@Override
public void onListItemSwapped(int i1, int i2) {
swapElements(adapter.getData(), i1, i2);
if (currentCheckedPosition == i1) {
currentCheckedPosition = i2;
} else if (currentCheckedPosition == i2) {
currentCheckedPosition = i1;
}
onSelected(currentCheckedPosition ,false);
adapter.notifyDataSetChanged();
}
private void swapElements(List list, int indexOne, int indexTwo) {
Object temp = list.get(indexOne);
list.set(indexOne, list.get(indexTwo));
list.set(indexTwo, temp);
}
@Override
public void onExerciseAddedCallback(List<Integer> idList) {// TODO make at background
List<TrainingRow> newData = new ArrayList<TrainingRow>();
Random random = new Random();
for (Integer anIdList : idList) {
TrainingRow row = new TrainingRow();
Exercise exercise = db.getExercise(anIdList);
if (adapter.containsId((int) exercise.getId())) continue;
row.setExerciseName(exercise.getName());
row.setExerciseId(anIdList);
row.setSuperset(false);
row.setSetsCount(0);
row.setTrainingProgramId(trainingId);
row.setPositionAtSuperset(0);
row.setSupersetColor(0);
row.setSupersetId(0);
row.setId(random.nextInt());
newData.add(row);
}
adapter.addData(newData);
saveExercicesToDatabase();
}
private void goToNextExerciseInSuperset(){
if (adapter.getData().get(currentCheckedPosition).isSuperset()){
int supersetId = adapter.getData().get(currentCheckedPosition).getSupersetId();
int supersetPosition = adapter.getData().get(currentCheckedPosition).getPositionAtSuperset();
int next = getNextSuperSetExercise(supersetId, supersetPosition);
if (next >= 0){
onSelected(next, true);
} else {
checkFirstSupersetExercise(supersetId);
showProgressDialog(true);
}
}
}
private int getNextSuperSetExercise(int supersetId, int supersetPosition){
for (int j = 0; j < 10; j++){
for (int i = 0; i < adapter.getData().size(); i++){
if (adapter.getData().get(i).getSupersetId() == supersetId && adapter.getData().get(i).getPositionAtSuperset() == supersetPosition + j + 1){
return i;
}
}
}
return -1;
}
private void checkFirstSupersetExercise(int supersetId){
int minSupersetPosition = 100;
for (int i = 0; i < adapter.getData().size(); i++){
if (adapter.getData().get(i).getSupersetId() == supersetId && adapter.getData().get(i).getPositionAtSuperset() < minSupersetPosition){
minSupersetPosition = adapter.getData().get(i).getPositionAtSuperset();
}
}
for (int i = 0; i < adapter.getData().size(); i++){
if (adapter.getData().get(i).getSupersetId() == supersetId && adapter.getData().get(i).getPositionAtSuperset() == minSupersetPosition){
onSelected(i, true);
}
}
}
private class RepsAdapter extends AbstractWheelTextAdapter {
ArrayList<String> reps = new ArrayList<String>();
protected RepsAdapter(Context context) {
super(context, R.layout.city_holo_layout, NO_RESOURCE);
for (int i = 0; i < 300; i++) {
reps.add("" + (i + 1));
}
setItemTextResource(R.id.city_name);
}
@Override
public View getItem(int index, View cachedView, ViewGroup parent) {
return super.getItem(index, cachedView, parent);
}
@Override
public int getItemsCount() {
return reps.size();
}
@Override
protected CharSequence getItemText(int index) {
return reps.get(index);
}
}
private class WeightsAdapter extends AbstractWheelTextAdapter {
ArrayList<String> weights = new ArrayList<String>();
protected WeightsAdapter(Context context) {
super(context, R.layout.city_holo_layout, NO_RESOURCE);
for (int i = 0; i < 1000; i++) {
weights.add("" + (i + 1));
}
setItemTextResource(R.id.city_name);
}
@Override
public View getItem(int index, View cachedView, ViewGroup parent) {
return super.getItem(index, cachedView, parent);
}
@Override
public int getItemsCount() {
return weights.size();
}
@Override
protected CharSequence getItemText(int index) {
return weights.get(index);
}
}
private class TrainingAdapter extends BaseAdapter {
private final static int INVALID_ID = -1;
private LayoutInflater inflater;
private List<TrainingRow> data;
public TrainingAdapter(Context context) {
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
data = new ArrayList<TrainingRow>();
}
public void addData(List<TrainingRow> newData) {
data.addAll(newData);
notifyDataSetChanged();
}
public void deleteItem(int position) {
data.remove(position);
notifyDataSetChanged();
}
public boolean containsId(int exerciseId){
for (TrainingRow aData : data) {
if (aData.getExerciseId() == exerciseId) return true;
}
return false;
}
public List<TrainingRow> getData() {
return this.data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public TrainingRow getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
if (position >= 0 && position < data.size()) {
return data.get(position).getId();
} else {
return INVALID_ID;
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.list_item_creating_programm, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvExerciseName = (TextViewLight) view.findViewById(R.id.text_exercise);
viewHolder.tvSupersetNumber = (TextViewLight) view.findViewById(R.id.text_number_of_superset);
viewHolder.color = view.findViewById(R.id.color_superset);
viewHolder.imageViewSuperset = (ImageView) view.findViewById(R.id.imageSuperset);
view.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.tvExerciseName.setText(data.get(position).getExerciseName());
if (data.get(position).isSuperset()) {
holder.color.setVisibility(View.VISIBLE);
holder.color.setBackgroundColor(data.get(position).getSupersetColor());
holder.tvSupersetNumber.setVisibility(View.VISIBLE);
holder.tvSupersetNumber.setText(String.valueOf(data.get(position).getPositionAtSuperset() + 1));
holder.imageViewSuperset.setVisibility(View.VISIBLE);
} else {
holder.color.setVisibility(View.GONE);
holder.tvSupersetNumber.setVisibility(View.GONE);
holder.imageViewSuperset.setVisibility(View.GONE);
}
return view;
}
private class ViewHolder {
TextViewLight tvExerciseName;
ImageView imageViewSuperset;
View color;
TextViewLight tvSupersetNumber;
}
}
}
| |
package net.java.cargotracker.application.util;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import net.java.cargotracker.domain.model.cargo.Cargo;
import net.java.cargotracker.domain.model.cargo.Itinerary;
import net.java.cargotracker.domain.model.cargo.Leg;
import net.java.cargotracker.domain.model.cargo.RouteSpecification;
import net.java.cargotracker.domain.model.cargo.TrackingId;
import net.java.cargotracker.domain.model.handling.CannotCreateHandlingEventException;
import net.java.cargotracker.domain.model.handling.HandlingEvent;
import net.java.cargotracker.domain.model.handling.HandlingEventFactory;
import net.java.cargotracker.domain.model.handling.HandlingEventRepository;
import net.java.cargotracker.domain.model.handling.HandlingHistory;
import net.java.cargotracker.domain.model.location.SampleLocations;
import net.java.cargotracker.domain.model.voyage.SampleVoyages;
/**
* Loads sample data for demo.
*/
@Singleton
@Startup
public class SampleDataGenerator {
// TODO See if the logger can be injected.
private static final Logger logger = Logger.getLogger(
SampleDataGenerator.class.getName());
@PersistenceContext
private EntityManager entityManager;
@Inject
private HandlingEventFactory handlingEventFactory;
@Inject
private HandlingEventRepository handlingEventRepository;
@PostConstruct
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void loadSampleData() {
logger.info("Loading sample data.");
unLoadAll(); // Fail-safe in case of application restart that does not trigger a JPA schema drop.
loadSampleLocations();
loadSampleVoyages();
loadSampleCargos();
}
private void unLoadAll() {
logger.info("Unloading all existing data.");
// In order to remove handling events, must remove refrences in cargo.
// Dropping cargo first won't work since handling events have references
// to it.
// TODO See if there is a better way to do this.
List<Cargo> cargos = entityManager.createQuery("Select c from Cargo c",
Cargo.class).getResultList();
for (Cargo cargo : cargos) {
cargo.getDelivery().setLastEvent(null);
entityManager.merge(cargo);
}
// Delete all entities
// TODO See why cascade delete is not working.
entityManager.createQuery("Delete from HandlingEvent").executeUpdate();
entityManager.createQuery("Delete from Leg").executeUpdate();
entityManager.createQuery("Delete from Cargo").executeUpdate();
entityManager.createQuery("Delete from CarrierMovement").executeUpdate();
entityManager.createQuery("Delete from Voyage").executeUpdate();
entityManager.createQuery("Delete from Location").executeUpdate();
}
private void loadSampleLocations() {
logger.info("Loading sample locations.");
entityManager.persist(SampleLocations.HONGKONG);
entityManager.persist(SampleLocations.MELBOURNE);
entityManager.persist(SampleLocations.STOCKHOLM);
entityManager.persist(SampleLocations.HELSINKI);
entityManager.persist(SampleLocations.CHICAGO);
entityManager.persist(SampleLocations.TOKYO);
entityManager.persist(SampleLocations.HAMBURG);
entityManager.persist(SampleLocations.SHANGHAI);
entityManager.persist(SampleLocations.ROTTERDAM);
entityManager.persist(SampleLocations.GOTHENBURG);
entityManager.persist(SampleLocations.HANGZOU);
entityManager.persist(SampleLocations.NEWYORK);
entityManager.persist(SampleLocations.DALLAS);
}
private void loadSampleVoyages() {
logger.info("Loading sample voyages.");
entityManager.persist(SampleVoyages.HONGKONG_TO_NEW_YORK);
entityManager.persist(SampleVoyages.NEW_YORK_TO_DALLAS);
entityManager.persist(SampleVoyages.DALLAS_TO_HELSINKI);
entityManager.persist(SampleVoyages.HELSINKI_TO_HONGKONG);
entityManager.persist(SampleVoyages.DALLAS_TO_HELSINKI_ALT);
}
private void loadSampleCargos() {
logger.info("Loading sample cargo data.");
// Cargo ABC123
TrackingId trackingId1 = new TrackingId("ABC123");
RouteSpecification routeSpecification1 = new RouteSpecification(
SampleLocations.HONGKONG, SampleLocations.HELSINKI,
DateUtil.toDate("2014-03-15"));
Cargo abc123 = new Cargo(trackingId1, routeSpecification1);
Itinerary itinerary1 = new Itinerary(Arrays.asList(
new Leg(SampleVoyages.HONGKONG_TO_NEW_YORK,
SampleLocations.HONGKONG, SampleLocations.NEWYORK,
DateUtil.toDate("2014-03-02"),
DateUtil.toDate("2014-03-05")),
new Leg(SampleVoyages.NEW_YORK_TO_DALLAS,
SampleLocations.NEWYORK,
SampleLocations.DALLAS,
DateUtil.toDate("2014-03-06"),
DateUtil.toDate("2014-03-08")),
new Leg(SampleVoyages.DALLAS_TO_HELSINKI,
SampleLocations.DALLAS,
SampleLocations.HELSINKI,
DateUtil.toDate("2014-03-09"),
DateUtil.toDate("2014-03-12"))));
abc123.assignToRoute(itinerary1);
entityManager.persist(abc123);
try {
HandlingEvent event1 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2014-03-01"), trackingId1, null,
SampleLocations.HONGKONG.getUnLocode(),
HandlingEvent.Type.RECEIVE);
entityManager.persist(event1);
HandlingEvent event2 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2014-03-02"), trackingId1,
SampleVoyages.HONGKONG_TO_NEW_YORK.getVoyageNumber(),
SampleLocations.HONGKONG.getUnLocode(),
HandlingEvent.Type.LOAD);
entityManager.persist(event2);
HandlingEvent event3 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2014-03-05"), trackingId1,
SampleVoyages.HONGKONG_TO_NEW_YORK.getVoyageNumber(),
SampleLocations.NEWYORK.getUnLocode(),
HandlingEvent.Type.UNLOAD);
entityManager.persist(event3);
} catch (CannotCreateHandlingEventException e) {
throw new RuntimeException(e);
}
HandlingHistory handlingHistory1
= handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId1);
abc123.deriveDeliveryProgress(handlingHistory1);
entityManager.persist(abc123);
// Cargo JKL567
TrackingId trackingId2 = new TrackingId("JKL567");
RouteSpecification routeSpecification2 = new RouteSpecification(
SampleLocations.HANGZOU, SampleLocations.STOCKHOLM,
DateUtil.toDate("2014-03-18"));
Cargo jkl567 = new Cargo(trackingId2, routeSpecification2);
Itinerary itinerary2 = new Itinerary(Arrays.asList(
new Leg(SampleVoyages.HONGKONG_TO_NEW_YORK,
SampleLocations.HANGZOU, SampleLocations.NEWYORK,
DateUtil.toDate("2014-03-03"),
DateUtil.toDate("2014-03-05")),
new Leg(SampleVoyages.NEW_YORK_TO_DALLAS,
SampleLocations.NEWYORK, SampleLocations.DALLAS,
DateUtil.toDate("2014-03-06"),
DateUtil.toDate("2014-03-08")),
new Leg(SampleVoyages.DALLAS_TO_HELSINKI, SampleLocations.DALLAS,
SampleLocations.STOCKHOLM,
DateUtil.toDate("2014-03-09"),
DateUtil.toDate("2014-03-11"))));
jkl567.assignToRoute(itinerary2);
entityManager.persist(jkl567);
try {
HandlingEvent event1 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2014-03-01"), trackingId2, null,
SampleLocations.HANGZOU.getUnLocode(),
HandlingEvent.Type.RECEIVE);
entityManager.persist(event1);
HandlingEvent event2 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2014-03-03"), trackingId2,
SampleVoyages.HONGKONG_TO_NEW_YORK.getVoyageNumber(),
SampleLocations.HANGZOU.getUnLocode(),
HandlingEvent.Type.LOAD);
entityManager.persist(event2);
HandlingEvent event3 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2014-03-05"), trackingId2,
SampleVoyages.HONGKONG_TO_NEW_YORK.getVoyageNumber(),
SampleLocations.NEWYORK.getUnLocode(),
HandlingEvent.Type.UNLOAD);
entityManager.persist(event3);
HandlingEvent event4 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2014-03-06"), trackingId2,
SampleVoyages.HONGKONG_TO_NEW_YORK.getVoyageNumber(),
SampleLocations.NEWYORK.getUnLocode(),
HandlingEvent.Type.LOAD);
entityManager.persist(event4);
} catch (CannotCreateHandlingEventException e) {
throw new RuntimeException(e);
}
HandlingHistory handlingHistory2
= handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId2);
jkl567.deriveDeliveryProgress(handlingHistory2);
entityManager.persist(jkl567);
// Cargo definition DEF789. This one will remain unrouted.
TrackingId trackingId3 = new TrackingId("DEF789");
RouteSpecification routeSpecification3 = new RouteSpecification(
SampleLocations.HONGKONG, SampleLocations.MELBOURNE,
DateUtil.toDate("2014-11-18"));
Cargo def789 = new Cargo(trackingId3, routeSpecification3);
entityManager.persist(def789);
// Cargo definition MNO456. This one will be claimed properly.
TrackingId trackingId4 = new TrackingId("MNO456");
RouteSpecification routeSpecification4 = new RouteSpecification(
SampleLocations.NEWYORK, SampleLocations.DALLAS, DateUtil.toDate("2014-3-27"));
Cargo mno456 = new Cargo(trackingId4, routeSpecification4);
Itinerary itinerary4 = new Itinerary(
Arrays.asList(
new Leg(SampleVoyages.NEW_YORK_TO_DALLAS,
SampleLocations.NEWYORK,
SampleLocations.DALLAS,
DateUtil.toDate("2013-10-24"),
DateUtil.toDate("2013-10-25"))
));
mno456.assignToRoute(itinerary4);
entityManager.persist(mno456);
try {
HandlingEvent event1 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2013-10-18"), trackingId4,
null, SampleLocations.NEWYORK.getUnLocode(), HandlingEvent.Type.RECEIVE);
entityManager.persist(event1);
HandlingEvent event2 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2013-10-24"), trackingId4,
SampleVoyages.NEW_YORK_TO_DALLAS.getVoyageNumber(),
SampleLocations.NEWYORK.getUnLocode(), HandlingEvent.Type.LOAD);
entityManager.persist(event2);
HandlingEvent event3 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2013-10-25"), trackingId4,
SampleVoyages.NEW_YORK_TO_DALLAS.getVoyageNumber(),
SampleLocations.DALLAS.getUnLocode(), HandlingEvent.Type.UNLOAD);
entityManager.persist(event3);
HandlingEvent event4 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2013-10-26"), trackingId4,
null, SampleLocations.DALLAS.getUnLocode(), HandlingEvent.Type.CUSTOMS);
entityManager.persist(event4);
HandlingEvent event5 = handlingEventFactory.createHandlingEvent(
new Date(), DateUtil.toDate("2013-10-27"), trackingId4,
null, SampleLocations.DALLAS.getUnLocode(), HandlingEvent.Type.CLAIM);
entityManager.persist(event5);
HandlingHistory handlingHistory3
= handlingEventRepository.lookupHandlingHistoryOfCargo(trackingId4);
mno456.deriveDeliveryProgress(handlingHistory3);
entityManager.persist(mno456);
} catch (CannotCreateHandlingEventException e) {
throw new RuntimeException(e);
}
}
}
| |
/*
* 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.pig.test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import junit.framework.TestCase;
import org.apache.pig.ExecType;
import org.apache.pig.EvalFunc;
import org.apache.pig.FuncSpec;
import org.apache.pig.PigServer;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.io.FileLocalizer;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.test.utils.MyUDFReturnMap;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class TestUDF extends TestCase {
static String[] ScriptStatement = {
"A = LOAD 'test/org/apache/pig/test/data/passwd' USING PigStorage();",
"B = FOREACH A GENERATE org.apache.pig.test.utils.MyUDFReturnMap(1);" };
static File TempScriptFile = null;
static MiniCluster cluster = MiniCluster.buildCluster();
@Override
@Before
public void setUp() throws Exception {
FileLocalizer.setInitialized(false);
TempScriptFile = File.createTempFile("temp_jira_851", ".pig");
FileWriter writer = new FileWriter(TempScriptFile);
for (String line : ScriptStatement) {
writer.write(line + "\n");
}
writer.close();
}
@AfterClass
public static void oneTimeTearDown() throws Exception {
cluster.shutDown();
}
@Test
public void testUDFReturnMap_LocalMode() {
try {
PigServer pig = new PigServer(ExecType.LOCAL);
pig.registerScript(TempScriptFile.getAbsolutePath());
Iterator<Tuple> iterator = pig.openIterator("B");
int index = 0;
while (iterator.hasNext()) {
Tuple tuple = iterator.next();
index++;
Map<Object, Object> result = (Map<Object, Object>) tuple.get(0);
assertEquals(result, MyUDFReturnMap.map);
}
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testUDFReturnMap_MapReduceMode() {
try {
Util.createInputFile(cluster, "a.txt", new String[] { "dummy",
"dummy" });
FileLocalizer.deleteTempFiles();
PigServer pig = new PigServer(ExecType.MAPREDUCE, cluster
.getProperties());
pig.registerQuery("A = LOAD 'a.txt';");
pig
.registerQuery("B = FOREACH A GENERATE org.apache.pig.test.utils.MyUDFReturnMap();");
Iterator<Tuple> iterator = pig.openIterator("B");
int index = 0;
while (iterator.hasNext()) {
Tuple tuple = iterator.next();
index++;
Map<Object, Object> result = (Map<Object, Object>) tuple.get(0);
assertEquals(result, MyUDFReturnMap.map);
}
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testUDFMultiLevelOutputSchema() {
try {
PigServer pig = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
pig.registerQuery("A = LOAD 'a.txt';");
pig.registerQuery("B = FOREACH A GENERATE org.apache.pig.test.utils.MultiLevelDerivedUDF1();");
pig.registerQuery("C = FOREACH A GENERATE org.apache.pig.test.utils.MultiLevelDerivedUDF2();");
pig.registerQuery("D = FOREACH A GENERATE org.apache.pig.test.utils.MultiLevelDerivedUDF3();");
Schema s = pig.dumpSchema("B");
assertTrue(s.getField(0).type == DataType.DOUBLE);
s = pig.dumpSchema("C");
assertTrue(s.getField(0).type == DataType.DOUBLE);
s = pig.dumpSchema("D");
assertTrue(s.getField(0).type == DataType.DOUBLE);
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
//see PIG-2430
@Test
public void testEvalFuncGetArgToFunc() throws Throwable {
String input = "udf_test_jira_2430.txt";
Util.createLocalInputFile(input, new String[]{"1,hey"});
try {
PigServer pigServer = new PigServer(ExecType.LOCAL);
pigServer.registerQuery("A = LOAD '"+input+"' USING PigStorage(',') AS (x:int,y:chararray);");
pigServer.registerQuery("B = FOREACH A GENERATE org.apache.pig.test.TestUDF$UdfWithFuncSpecWithArgs(x);");
pigServer.registerQuery("C = FOREACH A GENERATE org.apache.pig.test.TestUDF$UdfWithFuncSpecWithArgs(y);");
pigServer.registerQuery("D = FOREACH A GENERATE org.apache.pig.test.TestUDF$UdfWithFuncSpecWithArgs((long)x);");
pigServer.registerQuery("E = FOREACH A GENERATE org.apache.pig.test.TestUDF$UdfWithFuncSpecWithArgs((double)x);");
pigServer.registerQuery("F = FOREACH A GENERATE org.apache.pig.test.TestUDF$UdfWithFuncSpecWithArgs((float)x);");
Iterator<Tuple> it = pigServer.openIterator("B");
assertEquals(Integer.valueOf(2),(Integer)it.next().get(0));
it = pigServer.openIterator("C");
assertEquals(Integer.valueOf(1), (Integer)it.next().get(0));
it = pigServer.openIterator("D");
assertEquals(Integer.valueOf(3),(Integer)it.next().get(0));
it = pigServer.openIterator("E");
assertEquals(Integer.valueOf(4),(Integer)it.next().get(0));
it = pigServer.openIterator("F");
assertEquals(Integer.valueOf(5),(Integer)it.next().get(0));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
//see PIG-2430
@Test
public void testNormalDefine() throws Throwable {
String input = "udf_test_jira_2430_2.txt";
Util.createLocalInputFile(input, new String[]{"1"});
try {
PigServer pigServer = new PigServer(ExecType.LOCAL);
pigServer.registerQuery("A = LOAD '"+input+"' as (x:int);");
pigServer.registerQuery("DEFINE udftest1 org.apache.pig.test.TestUDF$UdfWithFuncSpecWithArgs('1');");
pigServer.registerQuery("DEFINE udftest2 org.apache.pig.test.TestUDF$UdfWithFuncSpecWithArgs('2');");
pigServer.registerQuery("DEFINE udftest3 org.apache.pig.test.TestUDF$UdfWithFuncSpecWithArgs('3');");
pigServer.registerQuery("B = FOREACH A GENERATE udftest1(x), udftest2(x), udftest3(x);");
Iterator<Tuple> its = pigServer.openIterator("B");
Tuple t = its.next();
assertEquals(Integer.valueOf(1),t.get(0));
assertEquals(Integer.valueOf(2),t.get(1));
assertEquals(Integer.valueOf(3),t.get(2));
} catch (IOException e) {
e.printStackTrace();
fail();
}
}
@Test
public void testHelperEvalFunc() throws Exception {
String pref="org.apache.pig.test.utils.HelperEvalFuncUtils$";
String[][] UDF = {
{pref + "BasicSUM", pref + "AccSUM", pref + "AlgSUM", "SUM"},
{pref + "BasicCOUNT", pref + "AccCOUNT", pref + "AlgCOUNT", "COUNT"},
{"BasLCWC", "AccLCWC", "AlgLCWC", "5*COUNT"}
};
String input = "udf_test_helper_eval_func.txt";
Util.createLocalInputFile(input, new String[]{"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15"});
for (String[] udfs : UDF) {
for (int i = 0; i < udfs.length - 1; i++) {
String query = "DEFINE BasLCWC " + pref + "BasicLongCountWithConstructor('5');";
query += "DEFINE AccLCWC " + pref +" AccLongCountWithConstructor('5');";
query += "DEFINE AlgLCWC " + pref + "AlgLongCountWithConstructor('5');";
query += "A = load '" + input + "' as (x:long);";
query += "B = foreach (group A all) generate ";
for (String s : Arrays.copyOfRange(udfs, i, udfs.length - 1)) {
query += s + "(A),";
}
query += udfs[udfs.length - 1] + "(A);";
PigServer pigServer = new PigServer(ExecType.LOCAL);
pigServer.registerQuery(query);
Iterator<Tuple> it = pigServer.openIterator("B");
while (it.hasNext()) {
Tuple t = it.next();
Long val = (Long)t.get(0);
for (int j = 1; j < i; j++) {
assertEquals(val, t.get(j));
}
}
}
}
}
@Override
@After
public void tearDown() throws Exception {
TempScriptFile.delete();
}
public static class UdfWithFuncSpecWithArgs extends EvalFunc<Integer> {
private Integer ret = 0;
public UdfWithFuncSpecWithArgs() {}
public UdfWithFuncSpecWithArgs(String ret) {
this.ret=Integer.parseInt(ret);
}
@Override
public Integer exec(Tuple input) throws IOException {
return ret;
}
@Override
public List<FuncSpec> getArgToFuncMapping() throws FrontendException {
List<FuncSpec> l = new ArrayList<FuncSpec>(5);
l.add(new FuncSpec(this.getClass().getName(), new String[]{"1"}, new Schema(new Schema.FieldSchema(null,DataType.CHARARRAY))));
l.add(new FuncSpec(this.getClass().getName(), new String[]{"2"}, new Schema(new Schema.FieldSchema(null,DataType.INTEGER))));
l.add(new FuncSpec(this.getClass().getName(), new String[]{"3"}, new Schema(new Schema.FieldSchema(null,DataType.LONG))));
l.add(new FuncSpec(this.getClass().getName(), new String[]{"4"}, new Schema(new Schema.FieldSchema(null,DataType.DOUBLE))));
l.add(new FuncSpec(this.getClass().getName(), new String[]{"5"}, new Schema(new Schema.FieldSchema(null,DataType.FLOAT))));
return l;
}
}
}
| |
/*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel.kqueue;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SelectStrategy;
import io.netty.channel.SingleThreadEventLoop;
import io.netty.channel.kqueue.AbstractKQueueChannel.AbstractKQueueUnsafe;
import io.netty.channel.unix.FileDescriptor;
import io.netty.channel.unix.IovArray;
import io.netty.util.IntSupplier;
import io.netty.util.concurrent.RejectedExecutionHandler;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import static io.netty.channel.kqueue.KQueueEventArray.deleteGlobalRefs;
import static java.lang.Math.min;
/**
* {@link EventLoop} which uses kqueue under the covers. Only works on BSD!
*/
final class KQueueEventLoop extends SingleThreadEventLoop {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(KQueueEventLoop.class);
private static final AtomicIntegerFieldUpdater<KQueueEventLoop> WAKEN_UP_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(KQueueEventLoop.class, "wakenUp");
private static final int KQUEUE_WAKE_UP_IDENT = 0;
static {
// Ensure JNI is initialized by the time this class is loaded by this time!
// We use unix-common methods in this class which are backed by JNI methods.
KQueue.ensureAvailability();
}
private final NativeLongArray jniChannelPointers;
private final boolean allowGrowing;
private final FileDescriptor kqueueFd;
private final KQueueEventArray changeList;
private final KQueueEventArray eventList;
private final SelectStrategy selectStrategy;
private final IovArray iovArray = new IovArray();
private final IntSupplier selectNowSupplier = new IntSupplier() {
@Override
public int get() throws Exception {
return kqueueWaitNow();
}
};
private final Callable<Integer> pendingTasksCallable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return KQueueEventLoop.super.pendingTasks();
}
};
private volatile int wakenUp;
private volatile int ioRatio = 50;
KQueueEventLoop(EventLoopGroup parent, Executor executor, int maxEvents,
SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler) {
super(parent, executor, false, DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler);
selectStrategy = ObjectUtil.checkNotNull(strategy, "strategy");
this.kqueueFd = Native.newKQueue();
if (maxEvents == 0) {
allowGrowing = true;
maxEvents = 4096;
} else {
allowGrowing = false;
}
changeList = new KQueueEventArray(maxEvents);
eventList = new KQueueEventArray(maxEvents);
jniChannelPointers = new NativeLongArray(4096);
int result = Native.keventAddUserEvent(kqueueFd.intValue(), KQUEUE_WAKE_UP_IDENT);
if (result < 0) {
cleanup();
throw new IllegalStateException("kevent failed to add user event with errno: " + (-result));
}
}
void evSet(AbstractKQueueChannel ch, short filter, short flags, int fflags) {
changeList.evSet(ch, filter, flags, fflags);
}
void remove(AbstractKQueueChannel ch) throws IOException {
assert inEventLoop();
if (ch.jniSelfPtr == 0) {
return;
}
jniChannelPointers.add(ch.jniSelfPtr);
ch.jniSelfPtr = 0;
}
/**
* Return a cleared {@link IovArray} that can be used for writes in this {@link EventLoop}.
*/
IovArray cleanArray() {
iovArray.clear();
return iovArray;
}
@Override
protected void wakeup(boolean inEventLoop) {
if (!inEventLoop && WAKEN_UP_UPDATER.compareAndSet(this, 0, 1)) {
wakeup();
}
}
private void wakeup() {
Native.keventTriggerUserEvent(kqueueFd.intValue(), KQUEUE_WAKE_UP_IDENT);
// Note that the result may return an error (e.g. errno = EBADF after the event loop has been shutdown).
// So it is not very practical to assert the return value is always >= 0.
}
private int kqueueWait(boolean oldWakeup) throws IOException {
// TODO(scott): do we need to loop here ... we already loop in keventWait to ensure we wait the expected time.
// We also do the same thing in EPOLL ... do we need to loop there?
// If a task was submitted when wakenUp value was 1, the task didn't get a chance to produce wakeup event.
// So we need to check task queue again before calling epoll_wait. If we don't, the task might be pended
// until epoll_wait was timed out. It might be pended until idle timeout if IdleStateHandler existed
// in pipeline.
if (oldWakeup && hasTasks()) {
return kqueueWaitNow();
}
long totalDelay = delayNanos(System.nanoTime());
int delaySeconds = (int) min(totalDelay / 1000000000L, Integer.MAX_VALUE);
return kqueueWait(delaySeconds, (int) min(totalDelay - delaySeconds * 1000000000L, Integer.MAX_VALUE));
}
private int kqueueWaitNow() throws IOException {
return kqueueWait(0, 0);
}
private int kqueueWait(int timeoutSec, int timeoutNs) throws IOException {
deleteJniChannelPointers();
int numEvents = Native.keventWait(kqueueFd.intValue(), changeList, eventList, timeoutSec, timeoutNs);
changeList.clear();
return numEvents;
}
private void deleteJniChannelPointers() {
if (!jniChannelPointers.isEmpty()) {
deleteGlobalRefs(jniChannelPointers.memoryAddress(), jniChannelPointers.memoryAddressEnd());
jniChannelPointers.clear();
}
}
private void processReady(int ready) {
for (int i = 0; i < ready; ++i) {
final short filter = eventList.filter(i);
final short flags = eventList.flags(i);
if (filter == Native.EVFILT_USER || (flags & Native.EV_ERROR) != 0) {
// EV_ERROR is returned if the FD is closed synchronously (which removes from kqueue) and then
// we later attempt to delete the filters from kqueue.
assert filter != Native.EVFILT_USER ||
(filter == Native.EVFILT_USER && eventList.fd(i) == KQUEUE_WAKE_UP_IDENT);
continue;
}
AbstractKQueueChannel channel = eventList.channel(i);
if (channel == null) {
// This may happen if the channel has already been closed, and it will be removed from kqueue anyways.
// We also handle EV_ERROR above to skip this even early if it is a result of a referencing a closed and
// thus removed from kqueue FD.
logger.warn("events[{}]=[{}, {}] had no channel!", i, eventList.fd(i), filter);
continue;
}
AbstractKQueueUnsafe unsafe = (AbstractKQueueUnsafe) channel.unsafe();
// First check for EPOLLOUT as we may need to fail the connect ChannelPromise before try
// to read from the file descriptor.
if (filter == Native.EVFILT_WRITE) {
unsafe.writeReady();
} else if (filter == Native.EVFILT_READ) {
// Check READ before EOF to ensure all data is read before shutting down the input.
unsafe.readReady(eventList.data(i));
}
// Check if EV_EOF was set, this will notify us for connection-reset in which case
// we may close the channel directly or try to read more data depending on the state of the
// Channel and also depending on the AbstractKQueueChannel subtype.
if ((flags & Native.EV_EOF) != 0) {
unsafe.readEOF();
}
}
}
@Override
protected void run() {
for (;;) {
try {
int strategy = selectStrategy.calculateStrategy(selectNowSupplier, hasTasks());
switch (strategy) {
case SelectStrategy.CONTINUE:
continue;
case SelectStrategy.SELECT:
strategy = kqueueWait(WAKEN_UP_UPDATER.getAndSet(this, 0) == 1);
// 'wakenUp.compareAndSet(false, true)' is always evaluated
// before calling 'selector.wakeup()' to reduce the wake-up
// overhead. (Selector.wakeup() is an expensive operation.)
//
// However, there is a race condition in this approach.
// The race condition is triggered when 'wakenUp' is set to
// true too early.
//
// 'wakenUp' is set to true too early if:
// 1) Selector is waken up between 'wakenUp.set(false)' and
// 'selector.select(...)'. (BAD)
// 2) Selector is waken up between 'selector.select(...)' and
// 'if (wakenUp.get()) { ... }'. (OK)
//
// In the first case, 'wakenUp' is set to true and the
// following 'selector.select(...)' will wake up immediately.
// Until 'wakenUp' is set to false again in the next round,
// 'wakenUp.compareAndSet(false, true)' will fail, and therefore
// any attempt to wake up the Selector will fail, too, causing
// the following 'selector.select(...)' call to block
// unnecessarily.
//
// To fix this problem, we wake up the selector again if wakenUp
// is true immediately after selector.select(...).
// It is inefficient in that it wakes up the selector for both
// the first case (BAD - wake-up required) and the second case
// (OK - no wake-up required).
if (wakenUp == 1) {
wakeup();
}
// fallthrough
default:
}
final int ioRatio = this.ioRatio;
if (ioRatio == 100) {
try {
if (strategy > 0) {
processReady(strategy);
}
} finally {
runAllTasks();
}
} else {
final long ioStartTime = System.nanoTime();
try {
if (strategy > 0) {
processReady(strategy);
}
} finally {
final long ioTime = System.nanoTime() - ioStartTime;
runAllTasks(ioTime * (100 - ioRatio) / ioRatio);
}
}
if (allowGrowing && strategy == eventList.capacity()) {
//increase the size of the array as we needed the whole space for the events
eventList.realloc(false);
}
} catch (Throwable t) {
handleLoopException(t);
}
// Always handle shutdown even if the loop processing threw an exception.
try {
if (isShuttingDown()) {
closeAll();
if (confirmShutdown()) {
break;
}
}
} catch (Throwable t) {
handleLoopException(t);
}
}
}
@Override
protected Queue<Runnable> newTaskQueue(int maxPendingTasks) {
// This event loop never calls takeTask()
return maxPendingTasks == Integer.MAX_VALUE ? PlatformDependent.<Runnable>newMpscQueue()
: PlatformDependent.<Runnable>newMpscQueue(maxPendingTasks);
}
@Override
public int pendingTasks() {
// As we use a MpscQueue we need to ensure pendingTasks() is only executed from within the EventLoop as
// otherwise we may see unexpected behavior (as size() is only allowed to be called by a single consumer).
// See https://github.com/netty/netty/issues/5297
return inEventLoop() ? super.pendingTasks() : submit(pendingTasksCallable).syncUninterruptibly().getNow();
}
/**
* Returns the percentage of the desired amount of time spent for I/O in the event loop.
*/
public int getIoRatio() {
return ioRatio;
}
/**
* Sets the percentage of the desired amount of time spent for I/O in the event loop. The default value is
* {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks.
*/
public void setIoRatio(int ioRatio) {
if (ioRatio <= 0 || ioRatio > 100) {
throw new IllegalArgumentException("ioRatio: " + ioRatio + " (expected: 0 < ioRatio <= 100)");
}
this.ioRatio = ioRatio;
}
@Override
protected void cleanup() {
try {
try {
kqueueFd.close();
} catch (IOException e) {
logger.warn("Failed to close the kqueue fd.", e);
}
} finally {
// Cleanup all native memory!
// The JNI channel pointers should already be deleted because we should wait on kevent before this method,
// but lets just be sure we cleanup native memory.
deleteJniChannelPointers();
jniChannelPointers.free();
changeList.free();
eventList.free();
}
}
private void closeAll() {
try {
kqueueWaitNow();
} catch (IOException e) {
// ignore on close
}
}
private static void handleLoopException(Throwable t) {
logger.warn("Unexpected exception in the selector loop.", t);
// Prevent possible consecutive immediate failures that lead to
// excessive CPU consumption.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore.
}
}
}
| |
/*
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.am.integration.ui.tests;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.extensions.selenium.BrowserManager;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;
/**
* In order to run this test case, there needs to mount registry in API Manager
*/
public class APIMANAGER3250CrossTenantSubscriptionTestCase extends AMIntegrationUiTestBase {
public static final String PUBLISHED = "PUBLISHED";
//public static final String AVAILABLE_TO_ALL_TENANTS = "Available to all the Tenants";
public static final String DEFAULT_APPLICATION = "DefaultApplication";
private WebDriver driver;
private static final Log log = LogFactory.getLog(APIMANAGER3250CrossTenantSubscriptionTestCase.class);
private String TEST_DATA_TENANT_FIRST_NAME = "admin",
TEST_DATA_TENANT_LAST_NAME = "admin",
TEST_DATA_ADMIN_USER_NAME = "admin",
TEST_DATA_PASSWORD = "123456",
TEST_DATA_API_NAME = "testAPI",
TEST_DATA_API_END_POINT = "http://localhost:8080/api",
TEST_DATA_API_VERSION = "1.0.0";
@BeforeClass(alwaysRun = true)
protected void init() throws Exception {
super.init();
driver = BrowserManager.getWebDriver();
}
public void generateTenant(String postfix) throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 10);
// wait until load the page
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#menu-panel-button3 > span")));
driver.findElement(By.cssSelector("#menu-panel-button3 > span")).click();
driver.findElement(By.linkText("Add New Tenant")).click();
// wait until load the page
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("domain")));
driver.findElement(By.id("domain")).clear();
driver.findElement(By.id("domain")).sendKeys("test" + postfix + ".com");
driver.findElement(By.id("admin-firstname")).clear();
driver.findElement(By.id("admin-firstname")).sendKeys(TEST_DATA_TENANT_FIRST_NAME);
driver.findElement(By.id("admin-lastname")).clear();
driver.findElement(By.id("admin-lastname")).sendKeys(TEST_DATA_TENANT_LAST_NAME);
driver.findElement(By.id("admin")).clear();
driver.findElement(By.id("admin")).sendKeys(TEST_DATA_ADMIN_USER_NAME);
driver.findElement(By.id("admin-password")).clear();
driver.findElement(By.id("admin-password")).sendKeys(TEST_DATA_PASSWORD);
driver.findElement(By.id("admin-password-repeat")).clear();
driver.findElement(By.id("admin-password-repeat")).sendKeys(TEST_DATA_PASSWORD);
driver.findElement(By.id("admin-email")).clear();
driver.findElement(By.id("admin-email")).sendKeys("admin@test" + postfix + ".com");
driver.findElement(By.cssSelector("input.button")).click();
driver.findElement(By.cssSelector("button[type=\"button\"]")).click();
}
@Test(groups = "wso2.am")
public void checkCrossTenantSubscription() throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get(getLoginURL());
// wait until load the page
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("txtUserName")));
driver.findElement(By.id("txtUserName")).clear();
driver.findElement(By.id("txtUserName")).sendKeys(userInfo.getUserName());
driver.findElement(By.id("txtPassword")).clear();
driver.findElement(By.id("txtPassword")).sendKeys(userInfo.getPassword());
driver.findElement(By.cssSelector("input.button")).click();
// create two tenant
generateTenant("1");
generateTenant("2");
//login to publisher
driver.get(getPublisherURL() + "/site/pages/login.jag");
// wait until load the page
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys("admin@test1.com");
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys(TEST_DATA_PASSWORD);
driver.findElement(By.id("loginButton")).click();
// wait until load the page
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Add")));
// create new API
driver.findElement(By.linkText("Add")).click();
driver.findElement(By.id("name")).clear();
driver.findElement(By.id("name")).sendKeys(TEST_DATA_API_NAME);
driver.findElement(By.id("context")).clear();
driver.findElement(By.id("context")).sendKeys(TEST_DATA_API_NAME);
driver.findElement(By.id("version")).clear();
driver.findElement(By.id("version")).sendKeys(TEST_DATA_API_VERSION);
driver.findElement(By.id("go_to_implement")).click();
driver.findElement(By.cssSelector("a.btn:nth-child(4)")).click();
driver.findElement(By.id("jsonform-0-elt-production_endpoints")).clear();
driver.findElement(By.id("jsonform-0-elt-production_endpoints")).sendKeys(TEST_DATA_API_END_POINT);
driver.findElement(By.id("go_to_manage")).click();
driver.findElement(By.cssSelector("button.multiselect")).click();
driver.findElement(By.cssSelector(
".multiselect-container > li:nth-child(2) > a:nth-child(1) > label:nth-child(1) > input:nth-child(1)"))
.click();
new Select(driver.findElement(By.id("subscriptions"))).selectByValue("all_tenants");
driver.findElement(By.id("publish_api")).click();
//check whether the publish is success
driver.findElement(By.id("lifecyclesLink")).click();
//browse store
driver.get(getStoreURL() + "?tenant=test2.com");
log.info("Started to Login to Store");
driver.findElement(By.id("login-link")).click();
WebElement userNameField = driver.findElement(By.id("username"));
WebElement passwordField = driver.findElement(By.id("password"));
userNameField.sendKeys("admin@test2.com");
passwordField.sendKeys(TEST_DATA_PASSWORD);
driver.findElement(By.id("loginBtn")).click();
//check the presence of admin name in store home page to verify the user has logged to store.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("admin@test2.com")));
log.info("Logging to store is successful");
driver.get(getStoreURL() + "?tenant=test1.com");
//wait for few seconds and refresh the store since it will take little time to appear the published APIs in store
Thread.sleep(30000);
driver.navigate().refresh();
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".title")));
driver.findElement(By.cssSelector(".title")).click();
new Select(driver.findElement(By.id("application-list"))).selectByVisibleText(DEFAULT_APPLICATION);
driver.findElement(By.id("subscribe-button")).click();
//restart the server to unload the tenants
ServerConfigurationManager serverConfigurationManager = new ServerConfigurationManager(apimContext);
serverConfigurationManager.restartGracefully();
//browse store
driver.get(getStoreURL() + "?tenant=test2.com");
log.info("Started to Login to Store");
driver.findElement(By.id("login-link")).click();
WebElement userNameField1 = driver.findElement(By.id("username"));
WebElement passwordField1 = driver.findElement(By.id("password"));
userNameField1.sendKeys("admin@test2.com");
passwordField1.sendKeys(TEST_DATA_PASSWORD);
driver.findElement(By.id("loginBtn")).click();
//check the presence of admin name in store home page to verify the user has logged to store.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("admin@test2.com")));
log.info("Logging to store is successful");
//go to my subscription page
driver.get(getStoreURL() + "?tenant=test1.com");
driver.findElement(By.cssSelector(".link-mysubscriptions")).click();
//wait until subscribed APIs visible in UI
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".content-data > div:nth-child(8) > h3:nth-child(2)")));
}
@AfterClass(alwaysRun = true)
public void tearDown() throws Exception {
if (driver != null) {
driver.quit();
}
}
}
| |
/*
* Frame.java $Revision: 1.21 $ $Date: 2003/04/23 15:23:04 $
*
* Copyright (c) 2001 Invisible Worlds, Inc. All rights reserved.
* Copyright (c) 2001,2002 Huston Franklin. All rights reserved.
*
* The contents of this file are subject to the Blocks Public License (the
* "License"); You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at http://www.beepcore.org/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
*/
package org.beepcore.beep.core;
import java.util.Iterator;
import java.util.LinkedList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beepcore.beep.util.BufferSegment;
import org.beepcore.beep.util.HeaderParser;
import org.beepcore.beep.util.StringUtil;
/**
* Frame encapsulates a BEEP protocol frame for MSG, RPY, ERR, ANS and NUL
* BEEP message types.
* Contains a the <code>Channel</code> this frame belongs to, the BEEP Frame
* Payload which holds the BEEP Frames's Header, Trailer, and the message
* payload.
*
* @author Eric Dixon
* @author Huston Franklin
* @author Jay Kint
* @author Scott Pead
* @version $Revision: 1.21 $, $Date: 2003/04/23 15:23:04 $
*
* @see BufferSegment
*/
public class Frame {
private static final String CRLF = "\r\n";
public static final String TRAILER = "END\r\n";
public static final int MAX_HEADER_SIZE = (3 // msg type
+ 1 // space
+ 10 // channel number
+ 1 // space
+ 10 // msgno
+ 1 // space
+ 1 // more
+ 1 // space
+ 10 // seqno
+ 1 // space
+ 10 // size
+ 1 // space
+ 10 // ansno
+ CRLF.length());
public static final int MIN_HEADER_SIZE = (3 // msg type
+ 1 // space
+ 1 // channel number
+ 1 // space
+ 1 // msgno
+ 1 // space
+ 1 // more
+ 1 // space
+ 1 // seqno
+ 1 // space
+ 1 // size
+ CRLF.length());
public static final int MIN_FRAME_SIZE = MIN_HEADER_SIZE +
Frame.TRAILER.length();
public static final int MAX_ANS_NUMBER = Integer.MAX_VALUE; // 2147483647;
public static final int MAX_CHANNEL_NUMBER = Integer.MAX_VALUE;
public static final int MAX_MESSAGE_NUMBER = Integer.MAX_VALUE;
public static final long MAX_SEQUENCE_NUMBER = 4294967295L;
public static final int MAX_SIZE = Integer.MAX_VALUE;
private static final BufferSegment trailerBufferSegment =
new BufferSegment(TRAILER.getBytes());
private Log log = LogFactory.getLog(this.getClass());
/** BEEP message type of <code>Frame</code>. */
private int messageType;
/** <code>Channel</code> to which <code>Frame</code> belongs. */
private ChannelImpl channel;
/** Message number of <code>Frame</code>. */
private int msgno;
/** Answer number of this BEEP <code>Frame</code>. */
private int ansno;
/**
* Sequence number of a BEEP message. <code>seqno</code> is equal to
* the 'seqno' of the BEEP message header.
*/
private long seqno;
/**
* Size of the payload of a BEEP message. <code>size</code> is equal to
* the 'size' of the BEEP message header.
*/
private int size;
/**
* Specifies whether this is the final frame of the message (i.e. the
* continuation indicator 'more' is equal to a '.' and not a '*').
*/
private boolean last;
/**
* The payload of a BEEP message.
*/
private LinkedList payload = new LinkedList();
Frame(int messageType, ChannelImpl channel, int msgno, boolean last,
long seqno, int size, int ansno)
{
this.messageType = messageType;
this.channel = channel;
this.msgno = msgno;
this.last = last;
this.seqno = seqno;
this.size = size;
this.ansno = ansno;
}
/**
* Adds the <code>BufferSegment</code> to the list representing the
* payload for this frame.
*/
public void addPayload(BufferSegment buf)
{
this.payload.add(buf);
}
/**
* Returns an <code>iterator</code> to iterate over a collection of
* <code>BufferSegment</code> objects.
*
*/
public BufferSegment[] getBytes()
{
BufferSegment[] b = new BufferSegment[this.payload.size() + 2];
this.size = 0;
int j=1;
Iterator i = this.payload.iterator();
while (i.hasNext()) {
b[j] = (BufferSegment) i.next();
this.size += b[j].getLength();
++j;
}
b[0] = new BufferSegment(buildHeader());
b[j] = trailerBufferSegment;
return b;
}
/**
* Returns the <code>payload</code> of a <code>Frame</code>.
* A <code>BufferSegment</code> contains a BEEP Frames Payload.
*
* @see BufferSegment
*/
public Iterator getPayload()
{
return this.payload.iterator();
}
/**
* Returns the message type of this <code>Frame</code>.
*/
public int getMessageType()
{
return this.messageType;
}
/**
* Returns the message type of this <code>Frame</code>.
*/
public String getMessageTypeString()
{
return MessageType.getMessageType(this.messageType);
}
/**
* Returns the <code>Channel</code> to which this <code>Frame</code>
* belongs.
*
* @see Channel
*/
public Channel getChannel()
{
return this.channel;
}
/**
* Returns the message number of this <code>Frame</code>.
*/
public int getMsgno()
{
return this.msgno;
}
/**
* Returns the <code>seqno</code> of this <code>Frame</code>.
*/
public long getSeqno()
{
return this.seqno;
}
/**
* Returns the <code>size</code> of the payload for this
* <code>Frame</code>.
*/
public int getSize()
{
return this.size;
}
/**
* Returns the answer number of this <code>Frame</code>.
*/
public int getAnsno()
{
return this.ansno;
}
/**
* Indicates if this is the last <code>Frame</code> in a sequence of frames
*/
public boolean isLast()
{
return this.last;
}
void setLast()
{
this.last = true;
}
/**
* Builds a BEEP Header from the given <code>Frame</code> and returns it
* as a byte array.
*
* @param f <code>Frame</code> from which we derive the BEEP Header.
*/
byte[] buildHeader()
{
StringBuffer header = new StringBuffer(Frame.MAX_HEADER_SIZE);
// Create header
header.append(MessageType.getMessageType(this.messageType));
header.append(' ');
header.append(this.channel.getNumberAsString());
header.append(' ');
header.append(this.msgno);
header.append(' ');
header.append((this.last ? '.' : '*'));
header.append(' ');
header.append(this.seqno);
header.append(' ');
header.append(this.size);
if (this.messageType == Message.MESSAGE_TYPE_ANS) {
header.append(' ');
header.append(this.ansno);
}
header.append(Frame.CRLF);
if (log.isTraceEnabled()) {
log.trace(header);
}
return StringUtil.stringBufferToAscii(header);
}
static Frame parseHeader(SessionImpl session, byte[] headerBuffer, int length)
throws BEEPException
{
HeaderParser header = new HeaderParser(headerBuffer, length);
int msgType =
MessageType.getMessageType(new String(header.parseType()));
int channelNum = header.parseInt();
int msgNum = header.parseInt();
boolean last = header.parseLast();
long seqNum = header.parseUnsignedInt();
int size = header.parseInt();
int ansNum = -1;
if (header.hasMoreTokens()) {
ansNum = header.parseInt();
}
if (header.hasMoreTokens()) {
throw new BEEPException("Malformed BEEP Header");
}
return new Frame(msgType, session.getValidChannel(channelNum), msgNum,
last, seqNum, size, ansNum);
}
private static class MessageType {
public static final String MESSAGE_TYPE_UNK = "UNK";
public static final String MESSAGE_TYPE_MSG = "MSG";
public static final String MESSAGE_TYPE_RPY = "RPY";
public static final String MESSAGE_TYPE_ERR = "ERR";
public static final String MESSAGE_TYPE_ANS = "ANS";
public static final String MESSAGE_TYPE_NUL = "NUL";
/**
* BEEP message type for utility only.
*/
private static final int MESSAGE_TYPE_MAX = 6;
// public static LinkedList types = new LinkedList();
public static String[] types = new String[MESSAGE_TYPE_MAX];
private MessageType() {}
static {
types[Message.MESSAGE_TYPE_UNK] = MessageType.MESSAGE_TYPE_UNK;
types[Message.MESSAGE_TYPE_ANS] = MessageType.MESSAGE_TYPE_ANS;
types[Message.MESSAGE_TYPE_MSG] = MessageType.MESSAGE_TYPE_MSG;
types[Message.MESSAGE_TYPE_ERR] = MessageType.MESSAGE_TYPE_ERR;
types[Message.MESSAGE_TYPE_RPY] = MessageType.MESSAGE_TYPE_RPY;
types[Message.MESSAGE_TYPE_NUL] = MessageType.MESSAGE_TYPE_NUL;
}
static int getMessageType(String type)
throws IndexOutOfBoundsException
{
int ret = 0;
int i = 0;
for (i = 0; i < MESSAGE_TYPE_MAX; i++) {
if (type.equals(types[i])) {
ret = i;
break;
}
}
return ret;
}
static String getMessageType(int type)
throws IndexOutOfBoundsException
{
return types[type];
}
}
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.intention.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.ide.scratch.ScratchFileService;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.tree.Factory;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.siyeh.ig.psiutils.CommentTracker;
import org.jetbrains.annotations.NotNull;
/**
* @author max
*/
public class SplitDeclarationAction extends PsiElementBaseIntentionAction {
@Override
@NotNull
public String getFamilyName() {
return CodeInsightBundle.message("intention.split.declaration.family");
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
if (element instanceof PsiCompiledElement) return false;
if (!ScratchFileService.isInProjectOrScratch(element)) return false;
if (!element.getLanguage().isKindOf(JavaLanguage.INSTANCE)) return false;
final PsiElement context = PsiTreeUtil.getParentOfType(element, PsiDeclarationStatement.class, PsiClass.class);
if (context instanceof PsiDeclarationStatement) {
return isAvailableOnDeclarationStatement((PsiDeclarationStatement)context, element);
}
PsiField field = PsiTreeUtil.getParentOfType(element, PsiField.class);
if (field != null && PsiTreeUtil.getParentOfType(element, PsiDocComment.class) == null && isAvailableOnField(field)) {
setText(CodeInsightBundle.message("intention.split.declaration.text"));
return true;
}
return false;
}
private static boolean isAvailableOnField(PsiField field) {
final PsiTypeElement typeElement = field.getTypeElement();
if (typeElement == null) return false;
if (PsiTreeUtil.getParentOfType(typeElement, PsiField.class) != field) return true;
PsiElement nextField = field.getNextSibling();
while (nextField != null && !(nextField instanceof PsiField)) nextField = nextField.getNextSibling();
if (nextField != null && ((PsiField)nextField).getTypeElement() == typeElement) return true;
return false;
}
private boolean isAvailableOnDeclarationStatement(PsiDeclarationStatement decl, PsiElement element) {
PsiElement[] declaredElements = decl.getDeclaredElements();
if (declaredElements.length == 0) return false;
if (!(declaredElements[0] instanceof PsiLocalVariable)) return false;
if (declaredElements.length == 1) {
PsiLocalVariable var = (PsiLocalVariable)declaredElements[0];
if (var.getInitializer() == null) return false;
if (var.getTypeElement().isInferredType() && !PsiTypesUtil.isDenotableType(var.getType(), var)) {
return false;
}
PsiElement parent = decl.getParent();
if (parent instanceof PsiForStatement) {
String varName = var.getName();
if (varName == null) {
return false;
}
parent = parent.getNextSibling();
while (parent != null) {
Ref<Boolean> conflictFound = new Ref<>(false);
parent.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitClass(PsiClass aClass) { }
@Override
public void visitVariable(PsiVariable variable) {
super.visitVariable(variable);
if (varName.equals(variable.getName())) {
conflictFound.set(true);
stopWalking();
}
}
});
if (conflictFound.get()) {
return false;
}
parent = parent.getNextSibling();
}
}
setText(CodeInsightBundle.message("intention.split.declaration.assignment.text"));
return true;
}
else {
if (decl.getParent() instanceof PsiForStatement) return false;
setText(CodeInsightBundle.message("intention.split.declaration.text"));
return true;
}
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
final PsiDeclarationStatement decl = PsiTreeUtil.getParentOfType(element, PsiDeclarationStatement.class);
final PsiManager psiManager = PsiManager.getInstance(project);
if (decl != null) {
invokeOnDeclarationStatement(decl, psiManager, project);
}
else {
PsiField field = PsiTreeUtil.getParentOfType(element, PsiField.class);
if (field != null) {
field.normalizeDeclaration();
}
}
}
public static PsiAssignmentExpression invokeOnDeclarationStatement(PsiDeclarationStatement decl, PsiManager psiManager,
Project project) {
if (decl.getDeclaredElements().length == 1) {
PsiLocalVariable var = (PsiLocalVariable)decl.getDeclaredElements()[0];
var.normalizeDeclaration();
final PsiTypeElement typeElement = var.getTypeElement();
if (typeElement.isInferredType()) {
PsiTypesUtil.replaceWithExplicitType(typeElement);
}
final String name = var.getName();
assert name != null;
PsiExpressionStatement statement = (PsiExpressionStatement)JavaPsiFacade.getElementFactory(psiManager.getProject())
.createStatementFromText(name + "=xxx;", decl);
statement = (PsiExpressionStatement)CodeStyleManager.getInstance(project).reformat(statement);
PsiAssignmentExpression assignment = (PsiAssignmentExpression)statement.getExpression();
PsiExpression initializer = var.getInitializer();
assert initializer != null;
PsiExpression rExpression = RefactoringUtil.convertInitializerToNormalExpression(initializer, var.getType());
final PsiExpression expression = assignment.getRExpression();
assert expression != null;
expression.replace(rExpression);
PsiElement block = decl.getParent();
if (block instanceof PsiForStatement) {
final PsiDeclarationStatement varDeclStatement =
JavaPsiFacade.getElementFactory(psiManager.getProject()).createVariableDeclarationStatement(name, var.getType(), null);
// For index can't be final, right?
for (PsiElement varDecl : varDeclStatement.getDeclaredElements()) {
if (varDecl instanceof PsiModifierListOwner) {
final PsiModifierList modList = ((PsiModifierListOwner)varDecl).getModifierList();
assert modList != null;
modList.setModifierProperty(PsiModifier.FINAL, false);
}
}
final PsiElement parent = block.getParent();
PsiExpressionStatement replaced = (PsiExpressionStatement)new CommentTracker().replaceAndRestoreComments(decl, statement);
if (!(parent instanceof PsiCodeBlock)) {
final PsiBlockStatement blockStatement =
(PsiBlockStatement)JavaPsiFacade.getElementFactory(project).createStatementFromText("{}", block);
final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
codeBlock.add(varDeclStatement);
codeBlock.add(block);
block.replace(blockStatement);
}
else {
parent.addBefore(varDeclStatement, block);
}
return (PsiAssignmentExpression)replaced.getExpression();
}
else {
try {
PsiElement declaredElement = decl.getDeclaredElements()[0];
if (!PsiUtil.isJavaToken(declaredElement.getLastChild(), JavaTokenType.SEMICOLON)) {
TreeElement semicolon = Factory.createSingleLeafElement(JavaTokenType.SEMICOLON, ";", 0, 1, null, decl.getManager());
CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(decl.addAfter(semicolon.getPsi(), declaredElement));
}
return (PsiAssignmentExpression)((PsiExpressionStatement)block.addAfter(statement, decl)).getExpression();
}
finally {
initializer.delete();
}
}
}
else {
((PsiLocalVariable)decl.getDeclaredElements()[0]).normalizeDeclaration();
}
return null;
}
}
| |
/**
* Copyright (C) 2015 Orange
* 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.francetelecom.clara.cloud.scalability.helper;
import com.francetelecom.clara.cloud.commons.BusinessException;
import com.francetelecom.clara.cloud.commons.InvalidMavenReferenceException;
import com.francetelecom.clara.cloud.commons.MavenReference;
import com.francetelecom.clara.cloud.commons.TechnicalException;
import com.francetelecom.clara.cloud.core.service.ManageApplication;
import com.francetelecom.clara.cloud.core.service.ManageApplicationRelease;
import com.francetelecom.clara.cloud.core.service.ManageEnvironment;
import com.francetelecom.clara.cloud.core.service.ManagePaasUser;
import com.francetelecom.clara.cloud.core.service.exception.*;
import com.francetelecom.clara.cloud.coremodel.*;
import com.francetelecom.clara.cloud.deployment.logical.service.ManageLogicalDeployment;
import com.francetelecom.clara.cloud.logicalmodel.*;
import com.francetelecom.clara.cloud.logicalmodel.samplecatalog.SampleAppProperties;
import com.francetelecom.clara.cloud.services.dto.EnvironmentDto;
import com.francetelecom.clara.cloud.services.dto.EnvironmentDto.EnvironmentStatusEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.util.*;
/**
* ScalabilityHelper Class used to create set of user data Sample usage : cf.
* ManageScalabilityImplTest
*
* @author Clara
*/
public class ScalabilityHelper {
/**
* Logger
*/
private static final transient org.slf4j.Logger logger = LoggerFactory.getLogger(ScalabilityHelper.class);
private static final EnvironmentDto.EnvironmentTypeEnum DEFAULT_ENV_TYPE = EnvironmentDto.EnvironmentTypeEnum.DEVELOPMENT;
private static final String LETTER_GUI = "G";
private static final String LETTER_NODE = "N";
private static final String LETTER_DATABASE = "D";
private static final String LETTER_STORE = "S";
/**
* paas managers
*/
private final ManagePaasUser managePaasUser;
private final ManageApplication manageApplication;
private final ManageApplicationRelease manageApplicationRelease;
private final ManageLogicalDeployment manageLogicalDeployment;
private final ManageEnvironment manageEnvironment;
private final SampleAppProperties sampleAppProperties;
private final boolean isFakeWorld;
/**
* scalability functions manager are provided by impl or mocks bean context
*
* @param managePaasUser
* paas user
* @param manageApplication
* app manager
* @param manageApplicationRelease
* appRelease manager
* @param manageLogicalDeployment
* ld manager
* @param manageEnvironment
* env manager
* @param sampleAppProperties
* app properties
* @param isFakeWorld
* must be true on mocked env or when incomplete activation plugin found this arg will determine if we skip environment creation
*/
public ScalabilityHelper(ManagePaasUser managePaasUser, ManageApplication manageApplication, ManageApplicationRelease manageApplicationRelease,
ManageLogicalDeployment manageLogicalDeployment, ManageEnvironment manageEnvironment, SampleAppProperties sampleAppProperties, boolean isFakeWorld) {
this.managePaasUser = managePaasUser;
this.manageApplication = manageApplication;
this.manageApplicationRelease = manageApplicationRelease;
this.manageLogicalDeployment = manageLogicalDeployment;
this.manageEnvironment = manageEnvironment;
this.sampleAppProperties = sampleAppProperties;
this.isFakeWorld = isFakeWorld;
}
public void razData(boolean activationIsAvailable) throws BusinessException {
Collection<Application> apps = manageApplication.findApplications();
if (apps != null && apps.size() > 0) {
logger.debug("remove {} apps", apps.size());
for (Application app : apps) {
try {
List<ApplicationRelease> applicationReleases = manageApplicationRelease.findApplicationReleasesByAppUID(app.getUID());
logger.debug("remove app {} releases", applicationReleases.size());
for (ApplicationRelease ar : applicationReleases) {
List<EnvironmentDto> allAREnvironments = manageEnvironment.findEnvironmentsByAppRelease(ar.getUID());
logger.debug("remove app {} envs", allAREnvironments.size());
for (EnvironmentDto env : allAREnvironments) {
String envName = env.getUid();
logger.debug("remove env '{}'", envName);
if (activationIsAvailable) {
manageEnvironment.deleteEnvironment(envName);
logger.debug("wait env '{}' to be removed", envName);
waitForStatus(envName, EnvironmentStatusEnum.REMOVED);
} else {
manageEnvironment.forceStatusForAndEnvironment(envName, EnvironmentStatus.REMOVED);
}
logger.debug("purge env '{}'", envName);
manageEnvironment.purgeRemovedEnvironment(envName);
}
logger.debug("purge release '{}'", ar.getUID());
manageApplicationRelease.deleteAndPurgeApplicationRelease(ar.getUID());
}
manageApplication.purgeApplication(app.getUID());
} catch (ObjectNotFoundException onfe) {
logger.warn(onfe.getMessage());
}
}
logger.info("remove users");
try {
List<PaasUser> users = managePaasUser.findAllPaasUsers();
if (users != null) {
for (PaasUser usr : users) {
managePaasUser.deletePaasUser(usr.getId());
}
}
} catch (ObjectNotFoundException onfe) {
logger.warn(onfe.getMessage());
}
}
}
private void waitForStatus(String environmentId, EnvironmentStatusEnum expectedStatus) throws ObjectNotFoundException {
int timeoutInMinutes = 60;
long timeoutMs = System.currentTimeMillis() + timeoutInMinutes * 60 * 1000;
EnvironmentDto envDto = manageEnvironment.findEnvironmentByUID(environmentId);
EnvironmentStatusEnum actualStatus = envDto.getStatus();
logger.debug("wait for status {}, currently {}", expectedStatus.toString(), actualStatus.toString());
while (expectedStatus != actualStatus) {
if (!actualStatus.toString().endsWith("ING")
&& actualStatus != EnvironmentStatusEnum.RUNNING) {
// In a final step, will not change until an action is requested
throw new TechnicalException("Activation process failed : " + envDto.getStatusMessage() + " status=" + actualStatus);
}
if (System.currentTimeMillis() > timeoutMs) {
throw new TechnicalException("Activation process timeout: environment not " + expectedStatus + " after " + timeoutInMinutes + " minutes");
}
try {
Thread.sleep(2000);
logger.debug("wait for status {}, currently {}", expectedStatus.toString(), actualStatus.toString());
} catch (InterruptedException e) {
// ignore
}
envDto = manageEnvironment.findEnvironmentByUID(environmentId);
actualStatus = envDto.getStatus();
}
}
public Collection<PaasUser> createPaasUsers(String namePrefix, int nbToCreate) {
Collection<PaasUser> createdUsers = new ArrayList<PaasUser>();
for (int nbCreated = 0; nbCreated < nbToCreate; nbCreated++) {
String nameToUse = namePrefix + nbCreated;
if (nbCreated > 1) {
nameToUse += nbCreated;
}
PaasUser pUsr = new PaasUser(nameToUse, "aLastName", new SSOId(nameToUse), nameToUse+"@orange.com");
managePaasUser.checkBeforeCreatePaasUser(pUsr);
createdUsers.add(pUsr);
}
return createdUsers;
}
public Collection<PaasUser> createTeam(String namePrefix) {
Collection<PaasUser> createdUsers = new ArrayList<PaasUser>();
Collection<String> opsTeam = new ArrayList<String>();
opsTeam.add("Manager");
opsTeam.add("Architect");
opsTeam.add("QA");
opsTeam.add("Dev1");
opsTeam.add("Dev2");
int i=0;
for (String name : opsTeam) {
String nameToUse = namePrefix + "." + name;
PaasUser pUsr = new PaasUser(nameToUse,nameToUse,new SSOId("ssoid"+i++),nameToUse + "." + nameToUse + "@orange.com");
managePaasUser.checkBeforeCreatePaasUser(pUsr);
createdUsers.add(pUsr);
}
return createdUsers;
}
private Application appFactory(String appLabel, String appCode, PaasUser author) throws DuplicateApplicationException, ApplicationNotFoundException, PaasUserNotFoundException {
logger.debug("appFactory({})", appLabel);
long start = System.currentTimeMillis();
String appUid = manageApplication.createPublicApplication(appCode, appLabel, "demo application " + appLabel, null, author.getSsoId());
Application demoApp = manageApplication.findApplicationByUID(appUid);
logger.debug("STATS createApplication duration: " + (System.currentTimeMillis() - start) + "ms");
return demoApp;
}
private ApplicationRelease releaseFactory(PaasUser author, Application app, String releaseVersion) throws MalformedURLException, ObjectNotFoundException,
DuplicateApplicationReleaseException {
// ApplicationRelease demoAppRelease = new ApplicationRelease(app,
// releaseVersion);
// demoAppRelease.setReleaseVersion(releaseVersion);
long start = System.currentTimeMillis();
String releaseUid = manageApplicationRelease.createApplicationRelease(app.getUID(), author.getSsoId().getValue(), releaseVersion);
ApplicationRelease demoAppRelease = manageApplicationRelease.findApplicationReleaseByUID(releaseUid);
demoAppRelease.setDescription("Scalability demo application - initial release");
demoAppRelease = manageApplicationRelease.updateApplicationRelease(demoAppRelease);
logger.debug("STATS createApplicationRelease duration: " + (System.currentTimeMillis() - start) + "ms");
return demoAppRelease;
}
private void logicalModelFactory(ApplicationRelease appRelease, String logicalModelPattern) throws ObjectNotFoundException, InvalidMavenReferenceException {
String releaseName = appRelease.getUID();
// CREATE SPRINGOO LOGICAL MODEL
LogicalDeployment ld = manageLogicalDeployment.findLogicalDeployment(appRelease.getLogicalDeployment().getId());
int nbGui = StringUtils.countMatches(logicalModelPattern, LETTER_GUI);
int nbDB = StringUtils.countMatches(logicalModelPattern, LETTER_DATABASE);
int nbStore = StringUtils.countMatches(logicalModelPattern, LETTER_STORE);
int nbNode = StringUtils.countMatches(logicalModelPattern, LETTER_NODE);
logger.debug("logicalModelFactory {} ", releaseName);
Collection<LogicalWebGUIService> guis = new ArrayList<LogicalWebGUIService>();
Collection<LogicalRelationalService> dbs = new ArrayList<LogicalRelationalService>();
Collection<LogicalOnlineStorageService> stores = new ArrayList<LogicalOnlineStorageService>();
Collection<ProcessingNode> nodes = new ArrayList<ProcessingNode>();
for (int g = 0; g < nbGui; g++) {
LogicalWebGUIService webGuiService = webGuiServiceFactory(releaseName + String.valueOf(g));
ld.addLogicalService(webGuiService);
guis.add(webGuiService);
}
for (int d = 0; d < nbDB; d++) {
LogicalRelationalService rdbService = relationalDBServiceFactory(releaseName + String.valueOf(d));
ld.addLogicalService(rdbService);
dbs.add(rdbService);
}
for (int s = 0; s < nbStore; s++) {
LogicalOnlineStorageService onlineStorageService = onlineStorageServiceFactory(releaseName + String.valueOf(s));
ld.addLogicalService(onlineStorageService);
stores.add(onlineStorageService);
}
Iterator<LogicalWebGUIService> itGuis = guis.iterator();
for (int n = 0; n < nbNode; n++) {
LogicalWebGUIService gui = null;
if (itGuis.hasNext()) {
gui = itGuis.next();
}
ProcessingNode lenService = cfJavaProcessingFactory(ld, releaseName + "Node." + n, gui, dbs, stores);
// ld.addExecutionNode(lenService);
nodes.add(lenService);
}
logger.debug("updateLogicalDeployment {}", ld.getName());
long start = System.currentTimeMillis();
try {
ld = manageLogicalDeployment.checkOverallConsistencyAndUpdateLogicalDeployment(ld);
} catch (BusinessException e) {
e.printStackTrace(); // To change body of catch statement use File |
// Settings | File Templates.
}
logger.debug("STATS updateLogicalDeployment duration: " + (System.currentTimeMillis() - start) + "ms");
}
/**
* Creates the environment if not in real world
*
* @param author
* env creation author
* @param appReleaseUid
* app release unique id
* @param envNumber
* id used to name env
* @return envOutputName
* @throws com.francetelecom.clara.cloud.core.service.exception.ObjectNotFoundException
*/
private String environmentFactory(PaasUser author, String appReleaseUid, int envNumber) throws BusinessException {
String environmentUid = "noenv";
if (this.isFakeWorld) {
String releaseName = appReleaseUid;
String envInputName = releaseName + "Env" + String.valueOf(envNumber);
long start = System.currentTimeMillis();
environmentUid = manageEnvironment.createEnvironment(appReleaseUid, DEFAULT_ENV_TYPE, author.getSsoId().getValue(), envInputName);
logger.debug("STATS createEnvironment duration: " + (System.currentTimeMillis() - start) + "ms");
logger.info("wait env '{}' to be created", environmentUid);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} else {
logger.error("You are running scalability feature in a real world! Ignoring environment creation...");
}
return environmentUid;
}
/**
* WEB_GUI Service production
*
* @param releaseName
* @return
*/
private LogicalWebGUIService webGuiServiceFactory(String releaseName) {
LogicalWebGUIService lsWebUi = new LogicalWebGUIService();
lsWebUi.setLabel(releaseName + "WebUi");
lsWebUi.setContextRoot(new ContextRoot("/"));
lsWebUi.setSecure(false);
lsWebUi.setStateful(false);
return lsWebUi;
}
/**
* RelationalDB Service production
*
* @param releaseName
* @return
*/
private LogicalRelationalService relationalDBServiceFactory(String releaseName) {
LogicalRelationalService lsRelational = new LogicalRelationalService();
lsRelational.setLabel(releaseName + "DB");
lsRelational.setServiceName("postgres-db");
lsRelational.setCapacityMo(1000);
lsRelational.setMaxConnection(50);
lsRelational.setRelationalReplicaNumber(0);
lsRelational.setSqlVersion(LogicalRelationalServiceSqlDialectEnum.POSTGRESQL_DEFAULT);
// manageLogicalDeployment.updateLogicalDeployment(lsRelational);
return lsRelational;
}
/**
* Store service production
*
* @param releaseName
* @return
*/
private LogicalOnlineStorageService onlineStorageServiceFactory(String releaseName) {
LogicalOnlineStorageService lsOnline = new LogicalOnlineStorageService();
lsOnline.setLabel(releaseName + "eDB");
lsOnline.setServiceName("demo-edb");
lsOnline.setStorageCapacityMb(100);
return lsOnline;
}
/**
* Execution node production, including service associations.
*
* @param name
* @param gui
* @param dbs
* @param stores
* @return
*/
private ProcessingNode cfJavaProcessingFactory(LogicalDeployment ld, String name, LogicalWebGUIService gui,
Collection<LogicalRelationalService> dbs, Collection<LogicalOnlineStorageService> stores) {
// log only the first logical model
if (logger.isDebugEnabled()) {
String svc = (gui != null ? "1" + LETTER_GUI : "") + (dbs != null ? dbs.size() + LETTER_DATABASE : "")
+ (stores != null ? stores.size() + LETTER_STORE : "");
logger.debug("Create execution node {} with {}", name, svc);
}
ProcessingNode len = new CFJavaProcessing();
len.setLabel(name);
String appName = "cf-wicket-jpa";
String type = "war";
len.setSoftwareReference(sampleAppProperties.getMavenReference(appName, type));
MavenReference lenMr = len.getSoftwareReference();
assert (lenMr != null) : "maven reference should not be null ! for " + appName;
logger.debug("resolve execution node maven reference {}", lenMr.toString());
ld.addExecutionNode(len);
if (gui != null) {
// expecting a single execution node to be producing a webGUI
len.addLogicalServiceUsage(gui, LogicalServiceAccessTypeEnum.NOT_APPLICABLE);
}
// db services
if (dbs != null) {
for (LogicalRelationalService db : dbs) {
len.addLogicalServiceUsage(db, LogicalServiceAccessTypeEnum.READ_WRITE);
}
}
// store services
if (stores != null) {
for (LogicalOnlineStorageService store : stores) {
len.addLogicalServiceUsage(store, LogicalServiceAccessTypeEnum.READ_WRITE);
}
}
// deprecated ? // manageLogicalDeployment.resolveMavenURL(len);
return len;
}
/**
* @param author
* @param appName
* @param nbApp
* @param nbReleasePerApp
* @param logicalModelPattern
* @see com.francetelecom.clara.cloud.scalability.ManageScalability
* @return
* @throws com.francetelecom.clara.cloud.commons.BusinessException
*/
public Collection<ApplicationRelease> createApplications(PaasUser author, String appName, int nbApp, int nbReleasePerApp, String logicalModelPattern)
throws BusinessException {
Collection<ApplicationRelease> appReleases = new ArrayList<ApplicationRelease>();
try {
for (int i = 0; i < nbApp; i++) {
String appId;
String appCode;
Application demoApp;
appId = "CFWicketJPA" + UUID.randomUUID();
appCode = "CWJ" + UUID.randomUUID();
// *** create app
demoApp = appFactory(appId, appCode, author);
for (int j = 0; j < nbReleasePerApp; j++) {
String relMinorId = String.valueOf(j);
String releaseVersion = "G0R0C" + relMinorId;
// *** create app-release
ApplicationRelease demoAppRelease = releaseFactory(author, demoApp, releaseVersion);
// *** create logical models
logicalModelFactory(demoAppRelease, logicalModelPattern);
appReleases.add(demoAppRelease);
}
}
} catch (MalformedURLException mue) {
throw new BusinessException("incorrect URL : ",mue);
}
return appReleases;
}
public Application populateSimpleTestPhase(PaasUser author, boolean createEnv) throws BusinessException {
logger.info("populateSimpleTestPhase()");
int numberOfEnvironmentToCreate = 0;
if (createEnv) {
numberOfEnvironmentToCreate = 1;
}
Collection<ApplicationRelease> applicationReleases = populate("GND", "simpleTestPhase", 1, 1, numberOfEnvironmentToCreate);
ApplicationRelease firstApplicationRelease = applicationReleases.iterator().next();
return firstApplicationRelease.getApplication();
}
/**
* @param pattern a string that include :
* - 'G' to create a gui
* - 'N' to create an execution node,
* - 'D' to create a relational database
* - 'S' to create an online store
* @param teamName name of the set of sample users
* @param nbApp number of application to create
* @param nbReleasePerApp number of release per app to create
* @param nbEnvPerRelease number of environment per release to create
* @return
* @throws BusinessException
*/
public Collection<ApplicationRelease> populate(String pattern, String teamName, int nbApp, int nbReleasePerApp, int nbEnvPerRelease)
throws BusinessException {
// users
Collection<PaasUser> users = createTeam(teamName);
PaasUser author = users.iterator().next();
// app, releases, logicalmodel
Collection<ApplicationRelease> releases = createApplications(author, "App of " + teamName, nbApp, nbReleasePerApp, pattern);
// env
int resultAwaitingEnv = nbApp * nbReleasePerApp * nbEnvPerRelease;
logger.info("Populating " + resultAwaitingEnv + " environment(s)...");
for (ApplicationRelease release : releases) {
final String releaseUid = release.getUID();
for (int k = 0; k < nbEnvPerRelease; k++) {
environmentFactory(author, releaseUid, k);
}
}
return releases;
}
}
| |
/*
* 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.facebook.presto.hive;
import com.facebook.airlift.log.Logger;
import javax.annotation.concurrent.ThreadSafe;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.OperationsException;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.loading.ClassLoaderRepository;
import java.io.ObjectInputStream;
import java.util.Set;
import static java.util.Objects.requireNonNull;
/**
* MBeanServer wrapper that a ignores calls to registerMBean when there is already
* a MBean registered with the specified object name.
*/
@SuppressWarnings("deprecation")
@ThreadSafe
public class RebindSafeMBeanServer
implements MBeanServer
{
private static final Logger log = Logger.get(RebindSafeMBeanServer.class);
private final MBeanServer mbeanServer;
public RebindSafeMBeanServer(MBeanServer mbeanServer)
{
this.mbeanServer = requireNonNull(mbeanServer, "mbeanServer is null");
}
/**
* Delegates to the wrapped mbean server, but if a mbean is already registered
* with the specified name, the existing instance is returned.
*/
@Override
public ObjectInstance registerMBean(Object object, ObjectName name)
throws MBeanRegistrationException, NotCompliantMBeanException
{
while (true) {
try {
// try to register the mbean
return mbeanServer.registerMBean(object, name);
}
catch (InstanceAlreadyExistsException ignored) {
}
try {
// a mbean is already installed, try to return the already registered instance
ObjectInstance objectInstance = mbeanServer.getObjectInstance(name);
log.debug("%s already bound to %s", name, objectInstance);
return objectInstance;
}
catch (InstanceNotFoundException ignored) {
// the mbean was removed before we could get the reference
// start the whole process over again
}
}
}
@Override
public void unregisterMBean(ObjectName name)
throws InstanceNotFoundException, MBeanRegistrationException
{
mbeanServer.unregisterMBean(name);
}
@Override
public ObjectInstance getObjectInstance(ObjectName name)
throws InstanceNotFoundException
{
return mbeanServer.getObjectInstance(name);
}
@Override
public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query)
{
return mbeanServer.queryMBeans(name, query);
}
@Override
public Set<ObjectName> queryNames(ObjectName name, QueryExp query)
{
return mbeanServer.queryNames(name, query);
}
@Override
public boolean isRegistered(ObjectName name)
{
return mbeanServer.isRegistered(name);
}
@Override
public Integer getMBeanCount()
{
return mbeanServer.getMBeanCount();
}
@Override
public Object getAttribute(ObjectName name, String attribute)
throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException
{
return mbeanServer.getAttribute(name, attribute);
}
@Override
public AttributeList getAttributes(ObjectName name, String[] attributes)
throws InstanceNotFoundException, ReflectionException
{
return mbeanServer.getAttributes(name, attributes);
}
@Override
public void setAttribute(ObjectName name, Attribute attribute)
throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
{
mbeanServer.setAttribute(name, attribute);
}
@Override
public AttributeList setAttributes(ObjectName name, AttributeList attributes)
throws InstanceNotFoundException, ReflectionException
{
return mbeanServer.setAttributes(name, attributes);
}
@Override
public Object invoke(ObjectName name, String operationName, Object[] params, String[] signature)
throws InstanceNotFoundException, MBeanException, ReflectionException
{
return mbeanServer.invoke(name, operationName, params, signature);
}
@Override
public String getDefaultDomain()
{
return mbeanServer.getDefaultDomain();
}
@Override
public String[] getDomains()
{
return mbeanServer.getDomains();
}
@Override
public void addNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object context)
throws InstanceNotFoundException
{
mbeanServer.addNotificationListener(name, listener, filter, context);
}
@Override
public void addNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter, Object context)
throws InstanceNotFoundException
{
mbeanServer.addNotificationListener(name, listener, filter, context);
}
@Override
public void removeNotificationListener(ObjectName name, ObjectName listener)
throws InstanceNotFoundException, ListenerNotFoundException
{
mbeanServer.removeNotificationListener(name, listener);
}
@Override
public void removeNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter, Object context)
throws InstanceNotFoundException, ListenerNotFoundException
{
mbeanServer.removeNotificationListener(name, listener, filter, context);
}
@Override
public void removeNotificationListener(ObjectName name, NotificationListener listener)
throws InstanceNotFoundException, ListenerNotFoundException
{
mbeanServer.removeNotificationListener(name, listener);
}
@Override
public void removeNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object context)
throws InstanceNotFoundException, ListenerNotFoundException
{
mbeanServer.removeNotificationListener(name, listener, filter, context);
}
@Override
public MBeanInfo getMBeanInfo(ObjectName name)
throws InstanceNotFoundException, IntrospectionException, ReflectionException
{
return mbeanServer.getMBeanInfo(name);
}
@Override
public boolean isInstanceOf(ObjectName name, String className)
throws InstanceNotFoundException
{
return mbeanServer.isInstanceOf(name, className);
}
@Override
public Object instantiate(String className)
throws ReflectionException, MBeanException
{
return mbeanServer.instantiate(className);
}
@Override
public Object instantiate(String className, ObjectName loaderName)
throws ReflectionException, MBeanException, InstanceNotFoundException
{
return mbeanServer.instantiate(className, loaderName);
}
@Override
public Object instantiate(String className, Object[] params, String[] signature)
throws ReflectionException, MBeanException
{
return mbeanServer.instantiate(className, params, signature);
}
@Override
public Object instantiate(String className, ObjectName loaderName, Object[] params, String[] signature)
throws ReflectionException, MBeanException, InstanceNotFoundException
{
return mbeanServer.instantiate(className, loaderName, params, signature);
}
@Override
@Deprecated
public ObjectInputStream deserialize(ObjectName name, byte[] data)
throws OperationsException
{
return mbeanServer.deserialize(name, data);
}
@Override
@Deprecated
public ObjectInputStream deserialize(String className, byte[] data)
throws OperationsException, ReflectionException
{
return mbeanServer.deserialize(className, data);
}
@Override
@Deprecated
public ObjectInputStream deserialize(String className, ObjectName loaderName, byte[] data)
throws OperationsException, ReflectionException
{
return mbeanServer.deserialize(className, loaderName, data);
}
@Override
public ClassLoader getClassLoaderFor(ObjectName mbeanName)
throws InstanceNotFoundException
{
return mbeanServer.getClassLoaderFor(mbeanName);
}
@Override
public ClassLoader getClassLoader(ObjectName loaderName)
throws InstanceNotFoundException
{
return mbeanServer.getClassLoader(loaderName);
}
@Override
public ClassLoaderRepository getClassLoaderRepository()
{
return mbeanServer.getClassLoaderRepository();
}
@Override
public ObjectInstance createMBean(String className, ObjectName name)
throws ReflectionException, InstanceAlreadyExistsException, MBeanException, NotCompliantMBeanException
{
return mbeanServer.createMBean(className, name);
}
@Override
public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException
{
return mbeanServer.createMBean(className, name, loaderName);
}
@Override
public ObjectInstance createMBean(String className, ObjectName name, Object[] params, String[] signature)
throws ReflectionException, InstanceAlreadyExistsException, MBeanException, NotCompliantMBeanException
{
return mbeanServer.createMBean(className, name, params, signature);
}
@Override
public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object[] params, String[] signature)
throws ReflectionException, InstanceAlreadyExistsException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException
{
return mbeanServer.createMBean(className, name, loaderName, params, signature);
}
}
| |
/*!\brief This is a printer interface for parsing
* XML wrapped in HTTP POST requests
* \author Xiaofan Li
*/
import java.io.*;
import java.util.*;
public class printer {
//raw inputs from parent prog
private ArrayList<Object> rawInput;
//for http
private String version;
private String userAgent;
private String host;
private int xmlLength;
private int respCode;
private String serverName;
//for xml
private String method;
private String fault;
private ArrayList<Object> params;
private ArrayList<Object> result;
private String xmlContent;
//am i parsing a request?
private boolean request;
/*!\brief Public constructor
*/
public printer (boolean request) {
this.request = request;
}
/*!\brief This function prints the HTTP POST request
* \require printer class with rawInput initialized
* \returns List of Strings including:
* version, user-agent, host, length, and the content
* \exception If length != length(content)
* Or content-type != text/xml
*/
public String printHTTP () throws IOException{
String content = "";
if (this.request){
String first = "POST /RPC2 HTTP/1.0\nUser-Agent: kali\nHost:\nContent-Type: text/xml\nContent-length:";
content = first + this.xmlLength + "\n\n\n\n" + this.xmlContent;
}
else {
String first = "HTTP/1.1 200 OK\nConnection: close\nContent-Length:";
String third = "Content-Type: text/xml\n\n\n";
content = first + this.xmlLength + "\n" + third + this.xmlContent;
}
return content;
}
//helpers
private String bin2str(Object binary) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(binary);
oos.close();
return new String(Base64Coder.encode(baos.toByteArray()));
}
private String divData(String data, int index){
int period = data.indexOf('.');
String first = data.substring(0,period);
String second = data.substring(period,data.length());
String dataName = (first+"_"+index+second);
String content,temp;
content = "";
try {
InputStream dataStream = new FileInputStream("../data/"+dataName);
BufferedReader in = new BufferedReader(new InputStreamReader(dataStream));
while((temp=in.readLine())!=null){
content = content+"\n"+temp;
}
} catch (IOException e){
e.printStackTrace();
}
return "<data-name>"+dataName+"</data-name>\n"+"<data-content>"+content+"</data-content>\n";
}
public void printClientRequest(String mapperName, Object mapperObj, String reducerName,Object reducerObj, String data) throws IOException {
System.out.println("entered printClientRequest");
String content;
//hard code these
String xmlHeader = "<?xml version='1.0'?>\n<job>\n";
String mapper = "<mapper>\n" + "<mapper-name>" + mapperName + "</mapperName>\n";
String reducer = "<reducer>\n" + "<reducer-name>" + reducerName + "</reducerName>\n";
try{
mapper = mapper + "<mapperObj>"+bin2str(mapperObj)+"</mapperObj>\n</mapper>\n";
reducer = reducer + "<reducerObj>"+bin2str(reducerObj)+"</reducerObj>\n</reducer>\n";
} catch (IOException e){
e.printStackTrace();
}
String yourData = "<data>"+data+"</data>\n";
//append footer
content = xmlHeader+mapper+reducer+yourData+"</job>";
this.xmlContent = content;
this.xmlLength = content.length();
System.out.println("exited printClientRequest");
}
public void printMapperRequest(String mapperName, Object mapperObj, String data, int index) throws IOException {
System.out.println("entered printMapperRequest "+ index+"th node");
String content;
//hard code these
String xmlHeader = "<?xml version='1.0'?>\n<DataNodeJob>\n";
String yourType = "<mapper>\n";
String name = "<mapperName>"+mapperName+"</mapperName>\n";
String obj = "<mapperObj>"+bin2str(mapperObj)+"</mapperObj>\n";
String endType = "</mapper>\n";
String yourData = "<data>\n"+divData(data,index)+"</data>\n";
//append footer
content = xmlHeader+yourType+name+obj+endType+yourData+"</DataNodeJob>";
this.xmlContent = content;
this.xmlLength = content.length();
System.out.println("exited printMapperRequest");
}
public void printReducerRequest(String reducerName, Object reducerObj, ArrayList<Object> result,ArrayList<String> types) throws IOException {
System.out.println("entered printReducerRequest");
//hard code these
String xmlHeader = "<?xml version='1.0'?>\n<DataNodeJob>\n";
String yourType = "<reducer>\n";
String name = "<reducerName>"+reducerName+"</reducerName>\n";
String obj = "<reducerObj>"+bin2str(reducerObj)+"</reducerObj>\n";
String endType = "</reducer>\n";
//input data
int numArgs = types.size();
String content = xmlHeader+yourType+name+obj+endType+"<params>\n";
for (int i=0;i<numArgs;i++) {
String paramXML = printOneParam(types.get(i),result.get(i));
//append the next parameter
content = content + paramXML;
}
//append footer
content = content+"</params>\n"+"</DataNodeJob>";
this.xmlContent = content;
this.xmlLength = content.length();
System.out.println("exited printReducerRequest");
}
public void printXML(ArrayList<Object> params,ArrayList<String> types) throws IOException{
System.out.println("entered printXML respond");
String xmlHeader = "<?xml version='1.0'?>\n<Response>\n<params>\n";
String xmlFooter = "</params>\n</Response>\n";
int numArgs = types.size();
String content = xmlHeader;
for (int i=0;i<numArgs;i++) {
String paramXML = printOneParam(types.get(i),params.get(i));
//append the next parameter
content = content + paramXML;
}
//append footer
content = content + xmlFooter;
this.xmlContent = content;
this.xmlLength = content.length();
System.out.println("exited printXML respond");
}
private String printOneParam (String type, Object param){
System.out.println("entered print one param");
String stuff = "";
if (type.equals("Integer")){
stuff = (param).toString();
return "<param>\n<value><i4>"+stuff+"</i4></value>\n</param>\n";
} else if (type.equals("String")){
stuff = (String)param;
return "<param>\n<value><string>"+stuff+"</string></value>\n</param>\n";
} else if (type.equals("Boolean")){
stuff = param.toString();
return "<param>\n<value><boolean>"+stuff+"</boolean></value>\n</param>\n";
} else {
return stuff;
}
}
public ArrayList<Object> getParams(){
return params;
}
}
| |
package midiplayer.frame.action;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.MissingResourceException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Action;
import javax.swing.KeyStroke;
import jswingshell.IJssController;
import jswingshell.action.AbstractJssAction;
import midiplayer.MidiPlayer;
import midiplayer.frame.MidiPlayerWithListener;
import midiplayer.resources.LocaleChangeListener;
import midiplayer.resources.ResourceUtils;
/**
* Action to pause a MIDI song.
*
* @author Mathieu Brunot
*/
public final class PauseAction extends AbstractJssAction
implements LocaleChangeListener, PropertyChangeListener {
/**
* The {@code serialVersionUID}.
*/
private static final long serialVersionUID = 6212819877172342224L;
/**
* Logger.
*/
private static final Logger LOGGER =
Logger.getLogger(PauseAction.class.getName());
/**
* This action default identifier.
*
* @since 1.2
*/
public static final String DEFAULT_IDENTIFIER = "pauseSong";
private static final String[] IDENTIFIERS = {DEFAULT_IDENTIFIER};
private static final String ACTION_LABEL = "Pause";
private static final String ACTION_LABEL_KEY = "midiplayer.action.pause.name";
private static final String COMMAND_BRIEF_HELP =
"Pause the current MIDI song.";
private static final String COMMAND_BRIEF_HELP_KEY =
"midiplayer.action.pause.help.short";
private static final String COMMAND_HELP_KEY =
"midiplayer.action.pause.help.long";
private static final String ICON_KEY = "control_pause_blue.png";
private static String commandHelp;
private static boolean commandHelpInitialized = false;
private static String commandBriefHelp;
private static boolean commandBriefHelpInitialized = false;
/**
* Construct the static command help.
*
* @param action the action reference
*
* @return the static command help.
*/
public static final String getHelp(PauseAction action) {
if (!commandHelpInitialized && action != null) {
StringBuilder stringBuilder = new StringBuilder();
String commandIdsAsString = action.getCommandIdentifiersAsString();
stringBuilder.append(action.getBriefHelp());
stringBuilder.append("\n");
try {
stringBuilder.append(
ResourceUtils.getMessage(COMMAND_HELP_KEY, commandIdsAsString));
} catch (MissingResourceException e) {
LOGGER.log(Level.SEVERE,
"Resource not found: \"" + COMMAND_HELP_KEY + "\"", e);
stringBuilder.append("\n")
.append("Pauses the current song in the playlist:");
stringBuilder.append("\n\t").append(commandIdsAsString);
}
commandHelp = stringBuilder.toString();
commandHelpInitialized = true;
}
return commandHelp;
}
/**
* Construct the static command brief help.
*
* @param action the action reference
*
* @return the static command brief help.
*/
public static final String getBriefHelp(PauseAction action) {
if (!commandBriefHelpInitialized && action != null) {
try {
commandBriefHelp = ResourceUtils.getMessage(COMMAND_BRIEF_HELP_KEY);
} catch (MissingResourceException e) {
LOGGER.log(Level.SEVERE,
"Resource not found: \"" + COMMAND_BRIEF_HELP_KEY + "\"", e);
commandBriefHelp = COMMAND_BRIEF_HELP;
}
commandBriefHelpInitialized = true;
}
return commandBriefHelp;
}
/**
* Reset the static help to force reconstruction on next call.
*
* @since 1.4
*/
public static final void resetHelp() {
commandHelpInitialized = false;
commandHelp = null;
commandBriefHelpInitialized = false;
commandBriefHelp = null;
}
// #########################################################################
private transient MidiPlayer midiPlayer;
public PauseAction(MidiPlayer midiPlayer, IJssController shellController,
String... args) {
super(ACTION_LABEL, ResourceUtils.createImageIcon(ICON_KEY, ACTION_LABEL),
shellController, args);
if (midiPlayer == null) {
throw new IllegalArgumentException("Midi player is null");
}
this.midiPlayer = midiPlayer;
putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD5, 0));
putValue(Action.LARGE_ICON_KEY,
ResourceUtils.createImageIcon(ICON_KEY, ACTION_LABEL, true));
putValue(Action.ACTION_COMMAND_KEY, getDefaultCommandIdentifier());
localeChanged();
}
public PauseAction(MidiPlayer midiPlayer, IJssController shellController) {
this(midiPlayer, shellController, (String[]) null);
}
public PauseAction(MidiPlayer midiPlayer) {
this(midiPlayer, null, (String[]) null);
}
public MidiPlayer getMidiPlayer() {
return midiPlayer;
}
public void setMidiPlayer(MidiPlayer midiPlayer) {
this.midiPlayer = midiPlayer;
}
// #########################################################################
@Override
public String[] getCommandIdentifiers() {
return IDENTIFIERS;
}
@Override
public String getBriefHelp() {
return getBriefHelp(this);
}
@Override
public String getHelp(IJssController shellController) {
return getHelp(this);
}
@Override
public int run(IJssController shellController, String... args) {
return midiPlayer.pausePlaying() ? AbstractJssAction.SUCCESS
: AbstractJssAction.ERROR;
}
// #########################################################################
@Override
public void localeChanged() {
localeChanged(null);
}
@Override
public void localeChanged(PropertyChangeEvent evt) {
resetHelp();
try {
ResourceUtils.setTextAndMnemonic(this, ACTION_LABEL_KEY);
} catch (MissingResourceException e) {
LOGGER.log(Level.SEVERE,
"Resource not found: \"" + ACTION_LABEL_KEY + "\"", e);
putValue(Action.NAME, ACTION_LABEL);
}
putValue(Action.SHORT_DESCRIPTION, this.getBriefHelp());
putValue(Action.LONG_DESCRIPTION,
this.getHelp(this.getDefaultShellController()));
}
// #########################################################################
@Override
public final void putValue(String key, Object newValue) {
super.putValue(key, newValue);
}
@Override
public final String getDefaultCommandIdentifier() {
return super.getDefaultCommandIdentifier();
}
// #########################################################################
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt == null) {
return;
}
Object newValue = evt.getNewValue();
Object oldValue = evt.getOldValue();
switch (evt.getPropertyName()) {
case MidiPlayerWithListener.PLAYLIST_SIZE_CHANGE:
if (newValue instanceof Integer && oldValue instanceof Integer) {
Integer newSize = (Integer) newValue;
Integer oldSize = (Integer) oldValue;
if (oldSize == 0 || newSize == 0) {
this.setEnabled(newSize > 0 && midiPlayer.isPlaying());
}
}
case MidiPlayerWithListener.PLAYING_STOP_CHANGE:
if (newValue instanceof Boolean) {
Boolean isStopped = (Boolean) newValue;
this.setEnabled(!isStopped);
}
break;
case MidiPlayerWithListener.PLAYING_START_CHANGE:
if (newValue instanceof Boolean) {
Boolean isPlaying = (Boolean) newValue;
this.setEnabled(isPlaying);
}
break;
}
}
}
| |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.util.collect;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators;
import com.google.common.collect.Ordering;
import com.google.common.collect.PeekingIterator;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import javax.annotation.Nullable;
public class SortedSets {
private SortedSets() {}
/**
* A view merging the two underlying sorted sets.
*
* <p>This View performs all operations lazily, and sacrifices CPU to reduce memory overhead. If
* operations are being repeatedly performed, it may be better to perform eager copies using
* something like {@link com.google.common.collect.ImmutableSortedSet#copyOf}.
*
* <p>The behavior of this view is unspecified if the underlying SortedSets are modified after
* construction.
*/
public static <T extends Comparable<T>> SortedSet<T> union(SortedSet<T> a, SortedSet<T> b) {
return new MergedSortedSetView<T>(a, b);
}
static class MergedSortedSetView<T extends Comparable<T>> implements SortedSet<T> {
private final SortedSet<T> a;
private final SortedSet<T> b;
private final Comparator<? super T> comparator;
public MergedSortedSetView(SortedSet<T> a, SortedSet<T> b) {
Preconditions.checkArgument(
areSameComparators(a.comparator(), b.comparator()),
"Cannot merge SortedSets with different comparators, got: %s, %s",
a.comparator(),
b.comparator());
this.a = a;
this.b = b;
this.comparator = a.comparator() == null ? Ordering.natural() : a.comparator();
}
/**
* Produce an Iterator which merges the underlying SortedSets in a sorted fashion,
* de-duplicating entries based on their equality-semantics.
*
* <p>The iterated order of values which are not equal but are equivalent according to the
* Comparator is unspecified, but stable for a given instance of MergedSortedSet.
*
* <p>The return Iterator is not threadsafe.
*/
@Override
public Iterator<T> iterator() {
PeekingIterator<T> left = Iterators.peekingIterator(a.iterator());
PeekingIterator<T> right = Iterators.peekingIterator(b.iterator());
return new Iterator<T>() {
@Override
public boolean hasNext() {
return left.hasNext() || right.hasNext();
}
@Override
public T next() {
if (!left.hasNext()) {
return right.next();
} else if (!right.hasNext()) {
return left.next();
} else {
T lval = left.peek();
T rval = right.peek();
if (lval.equals(rval)) {
right.next();
return left.next();
} else {
return comparator.compare(lval, rval) > 0 ? right.next() : left.next();
}
}
}
};
}
/**
* Returns the Comparator used to order the elements in this set.
*
* <p>Note that, like ImmutableSortedSet, this returns Ordering.natural() rather than null when
* the natural ordering is used, in violation of the SortedSet contract.
*/
@Override
@Nullable
public Comparator<? super T> comparator() {
return comparator;
}
@Override
public SortedSet<T> subSet(T fromElement, T toElement) {
return new MergedSortedSetView<>(
a.subSet(fromElement, toElement), b.subSet(fromElement, toElement));
}
@Override
public SortedSet<T> headSet(T toElement) {
return new MergedSortedSetView<>(a.headSet(toElement), b.headSet(toElement));
}
@Override
public SortedSet<T> tailSet(T fromElement) {
return new MergedSortedSetView<>(a.tailSet(fromElement), b.tailSet(fromElement));
}
@Override
public T first() {
return iterator().next();
}
@Override
public T last() {
if (a.isEmpty()) {
return b.last();
}
if (b.isEmpty()) {
return a.last();
}
T a = this.a.last();
T b = this.b.last();
return comparator.compare(a, b) >= 0 ? a : b;
}
/**
* Return the number of de-duplicated elements in the underlying sets.
*
* <p>Note that this is relatively expensive to compute, and {@link #sizeEstimate} may be more
* appropriate.
*/
@Override
public int size() {
return Sets.union(a, b).size();
}
/**
* Return an estimate of the size of this Set, which is quicker to compute than the actual size.
*
* <p>This will always return an over-estimate rather than an under-estimate.
*/
public int sizeEstimate() {
return a.size() + b.size();
}
@Override
public boolean isEmpty() {
return a.isEmpty() && b.isEmpty();
}
@Override
public boolean contains(Object o) {
return a.contains(o) || b.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return c.stream().allMatch(e -> contains(e));
}
@Override
public Object[] toArray() {
return Iterators.toArray(iterator(), Object.class);
}
@SuppressWarnings("unchecked")
@Override
public <T1> T1[] toArray(T1[] a) {
Iterator<T> iterator = iterator();
T1[] destination = a;
int size = size();
if (size > a.length) {
destination = (T1[]) new Object[size];
}
for (int i = 0; i < size; ++i) {
destination[i] = (T1) iterator.next();
}
while (destination.length > size) {
destination[size++] = null;
}
return destination;
}
@Override
public String toString() {
return "[" + Joiner.on(", ").join(iterator()) + "]";
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Set)) {
return false;
}
if (obj instanceof MergedSortedSetView) {
MergedSortedSetView<T> other = (MergedSortedSetView<T>) obj;
if (this.a == other.a && this.b == other.b) {
return true;
}
}
Set<T> other = (Set<T>) obj;
return size() == other.size() && other.containsAll(this);
}
@Override
public int hashCode() {
int hashCode = 0;
for (T e : this) {
hashCode += e != null ? e.hashCode() : 0;
}
return hashCode;
}
@Override
public boolean add(T t) {
throw new UnsupportedOperationException("Cannot modify MergedSortedSetView");
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("Cannot modify MergedSortedSetView");
}
@Override
public boolean addAll(Collection<? extends T> c) {
throw new UnsupportedOperationException("Cannot modify MergedSortedSetView");
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException("Cannot modify MergedSortedSetView");
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException("Cannot modify MergedSortedSetView");
}
@Override
public void clear() {
throw new UnsupportedOperationException("Cannot modify MergedSortedSetView");
}
}
/**
* Comparators which are all equivalents and sort things by natural order.
*
* <p>A HashSet rather than ImmutableSet because it contains null, which is forbidden in
* ImmutableSets.
*/
private static final Set<Comparator<?>> NATURAL_COMPARATORS =
new HashSet<Comparator<?>>() {
{
add(Comparator.naturalOrder());
add(Ordering.natural());
add(null);
}
};
private static boolean areSameComparators(Comparator<?> left, Comparator<?> right) {
if (Objects.equals(left, right)) {
return true;
}
return NATURAL_COMPARATORS.contains(left) && NATURAL_COMPARATORS.contains(right);
}
public static <T> int sizeEstimate(SortedSet<T> set) {
if (set instanceof MergedSortedSetView) {
return ((MergedSortedSetView<?>) set).sizeEstimate();
}
return set.size();
}
}
| |
package org.leores.util;
import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.leores.ecpt.TRuntimeException;
import org.leores.ecpt.UnsupportedTypeException;
import org.leores.ecpt.WrongFormatException;
import org.leores.ecpt.WrongParameterException;
public class StrUtil extends LogUtil {
public static String sBlock = "}"; //Priority high
public static String sEnumerate = ";";
public static String sRepeat = "@";
public static String sStep = ":";//Priority low
public static String sNoEval = "~";
public static String de = ",";
public static String sSet = "=";
//\\S+? Several non-whitespace characters ? makes quantifier "+" reluctant. It tries to find the smallest match.
public static String sPatVar = "\\$(\\S+?)\\$";
public static String sPatExp = "#(\\S+?)#";
public static String sSelf = "%";
public static final int EVAL_InvalidIgnore = 0x00000001;
public static final int EVAL_InvalidException = 0x00000002;
public static final int EVAL_NullIgnore = 0x00000004;
public static final int EVAL_NullException = 0x00000008;
public static String sPatEvalNumOut = null;//set this to null to use the default number out pattern in the system.
public static boolean bAssignable(Class cTo, Class cFrom) {
boolean rtn = false;
if (cFrom == null) {
rtn = true;
} else if (cTo != null) {
rtn = cTo.isAssignableFrom(cFrom);
}
return rtn;
}
public static List parseList(Class type, String[] tokens, boolean bStepped) {
List rtnList = null;
if (bStepped && tokens.length < 3) {
throw new TRuntimeException("Stepped type has less than 3 tokens: " + U.toStr(tokens));
}
if (type != null && tokens != null && tokens.length >= 1) {
rtnList = new ArrayList();
if (bAssignable(Integer.class, type)) {
if (bStepped) {
Integer i1, i2, i3;
i1 = Integer.parseInt(tokens[0]);
i2 = Integer.parseInt(tokens[1]);
i3 = Integer.parseInt(tokens[2]);
for (; i1 <= i3; i1 += i2) {
rtnList.add(i1);
}
} else {
for (int i = 0; i < tokens.length; i++) {
Integer i1 = Integer.parseInt(tokens[i]);
rtnList.add(i1);
}
}
} else if (bAssignable(Float.class, type)) {
if (bStepped) {
BigDecimal i1 = new BigDecimal(tokens[0]);
BigDecimal i2 = new BigDecimal(tokens[1]);
BigDecimal i3 = new BigDecimal(tokens[2]);
for (; i1.compareTo(i3) <= 0; i1 = i1.add(i2)) {
Float f1 = i1.floatValue();
rtnList.add(f1);
}
} else {
for (int i = 0; i < tokens.length; i++) {
Float i1 = Float.parseFloat(tokens[i]);
rtnList.add(i1);
}
}
} else if (bAssignable(Long.class, type)) {
if (bStepped) {
Long i1, i2, i3;
i1 = Long.parseLong(tokens[0]);
i2 = Long.parseLong(tokens[1]);
i3 = Long.parseLong(tokens[2]);
for (; i1 <= i3; i1 += i2) {
rtnList.add(i1);
}
} else {
for (int i = 0; i < tokens.length; i++) {
Long i1 = Long.parseLong(tokens[i]);
rtnList.add(i1);
}
}
} else if (bAssignable(Double.class, type)) {
if (bStepped) {
BigDecimal i1 = new BigDecimal(tokens[0]);
BigDecimal i2 = new BigDecimal(tokens[1]);
BigDecimal i3 = new BigDecimal(tokens[2]);
for (; i1.compareTo(i3) <= 0; i1 = i1.add(i2)) {
Double d1 = i1.doubleValue();
rtnList.add(d1);
}
} else {
for (int i = 0; i < tokens.length; i++) {
Double i1 = Double.parseDouble(tokens[i]);
rtnList.add(i1);
}
}
} else if (bAssignable(BigDecimal.class, type)) {
if (bStepped) {
BigDecimal i1 = new BigDecimal(tokens[0]);
BigDecimal i2 = new BigDecimal(tokens[1]);
BigDecimal i3 = new BigDecimal(tokens[2]);
for (; i1.compareTo(i3) <= 0; i1 = i1.add(i2)) {
rtnList.add(i1);
}
} else {
for (int i = 0; i < tokens.length; i++) {
BigDecimal i1 = new BigDecimal(tokens[i]);
rtnList.add(i1);
}
}
} else if (bAssignable(Boolean.class, type)) {
if (bStepped) {
throw new TRuntimeException("Boolean does not supported bStepped! " + U.toStr(tokens));
} else {
for (int i = 0; i < tokens.length; i++) {
Boolean i1 = Boolean.parseBoolean(tokens[i]);
rtnList.add(i1);
}
}
} else {//String or other classes.
if (bStepped) {
String i1, i2, i3;
i1 = tokens[0];
i2 = tokens[1];
i3 = tokens[2];
if (i2.length() > 0) {
for (; i1.length() <= i3.length(); i1 += i2) {
rtnList.add(i1);
}
}
} else {
for (int i = 0; i < tokens.length; i++) {
String i1 = tokens[i];
rtnList.add(i1);
}
}
}
}
return rtnList;
}
public static String[] split(String str, int limit) {
String[] rtn = null;
if (str != null) {
rtn = new String[] { str };
if (str.indexOf(sBlock) >= 0) {
rtn = str.split(sBlock, limit);
} else if (str.indexOf(sEnumerate) >= 0) {
rtn = str.split(sEnumerate, limit);
} else if (str.indexOf(de) >= 0) {
rtn = str.split(de, limit);
}
}
return rtn;
}
/**
* Trailing empty strings are not included in the resulting array.
*
* @param str
* @return
*/
public static String[] split(String str) {
return split(str, 0);
}
/**
* Here only when s == null we return null, when s == "", it returns a size
* 0 list. <br>
* <br>
* sBlock = "}" sEnumerate = ";" sRepeat = "@" sStep = ":"<br>
* <br>
* Use ; to separate enumerate vals (v1;v2;v3;...), @ to separate repeat
* vals (value@times), : to separate stepped vals (from:step:to), } to
* separate block of vals (v1;v2}v3:v4:v5}v6;v7)
*
* @param type
* @param s
* @return
*/
public static <A> List<A> parseList(Class<A> type, String s) {
List<A> rtn = null;
//Use ; to separate enumerate vals (v1;v2;v3;...), @ to separate repeat vals (value@times), : to separate stepped vals (from:step:to), } to separate block of vals (v1;v2}v3:v4:v5}v6;v7)
try {
if (bNoEval(s)) {
rtn = new ArrayList<A>();
rtn.add((A) s);
} else if (type != null && s != null) {
String s_ = s.trim();
if ("".equals(s_)) {
rtn = new ArrayList<A>();
} else if (s_.indexOf(sBlock) >= 0) {
String[] tokens = s_.split(sBlock);
rtn = parseList(type, tokens, false);
} else if (s_.indexOf(sEnumerate) >= 0) {
String[] tokens = s_.split(sEnumerate);
rtn = new ArrayList<A>();
for (int i = 0; i < tokens.length; i++) {
List<A> listi = parseList(type, tokens[i]);
rtn.addAll(listi);
}
} else if (s_.indexOf(sRepeat) >= 0) {
String[] tokens = s_.split(sRepeat);
Integer nRepeat = Integer.parseInt(tokens[1]);
String[] tokens2 = new String[nRepeat];
for (int i = 0; i < nRepeat; i++) {
tokens2[i] = tokens[0];
}
rtn = parseList(type, tokens2, false);
} else if (s_.indexOf(sStep) >= 0) {
String[] tokens = s_.split(sStep);
if (tokens.length >= 3) {
rtn = parseList(type, tokens, true);
} else {
throw new WrongFormatException(s_);
}
} else {
String[] tokens = { s_ };
rtn = parseList(type, tokens, false);
}
}
} catch (Exception e) {
tLog(e);
}
return rtn;
}
public static List parseList(String sType, String s) {
List rtnList = null;
try {
rtnList = parseList(Class.forName(sType), s);
} catch (Exception e) {
tLog(e);
}
return rtnList;
}
public static boolean valid(String s) {
boolean rtn = false;
if (s != null && s.length() > 0) {
rtn = true;
}
return rtn;
}
public static String format(Date date, String sFormat) {
String rtn = null;
if (date != null && sFormat != null) {
SimpleDateFormat sdf = new SimpleDateFormat(sFormat);
rtn = sdf.format(date);
}
return rtn;
}
public static String insert(String sOrig, int offset, String sToBeInserted) {
String rtn = null;
if (sOrig != null && offset >= 0 && sToBeInserted != null) {
StringBuffer sb = new StringBuffer(sOrig);
rtn = sb.insert(offset, sToBeInserted).toString();
}
return rtn;
}
public static String insert(String sOrig, String sBefore, String sToBeInserted) {
String rtn = null;
if (sOrig != null && sBefore != null && sToBeInserted != null) {
int i = sOrig.indexOf(sBefore);
rtn = insert(sOrig, i, sToBeInserted);
}
return rtn;
}
public static String insert(String sOrig, String sBefore, Object oToBeInserted) {
String rtn = null;
if (oToBeInserted != null) {
rtn = insert(sOrig, sBefore, oToBeInserted.toString());
}
return rtn;
}
public static String wrap(String[] strs, String before, String after, String delimiter, Integer iFrom, Integer iTo) {
String rtn = null;
if (strs != null && before != null && delimiter != null && after != null && iFrom != null && iTo != null) {
StringBuffer sBuffer = new StringBuffer();
for (int i = iFrom; i <= iTo && i < strs.length; i++) {
sBuffer.append(before);
sBuffer.append(strs[i]);
sBuffer.append(after);
if (i < iTo && i < strs.length - 1) {
sBuffer.append(delimiter);
}
}
rtn = sBuffer.toString();
}
return rtn;
}
public static String wrap(String[] strs, String before, String after, String delimiter) {
String rtn = null;
if (strs != null) {
rtn = wrap(strs, before, after, delimiter, 0, strs.length - 1);
}
return rtn;
}
public static String wrapCSVArray(String[] strs) {
String before = "\"";
String after = "\"";
String delimiter = ",";
return wrap(strs, before, after, delimiter);
}
public static String wrapCSV(String... strs) {
String before = "\"";
String after = "\"";
String delimiter = ",";
return wrap(strs, before, after, delimiter);
}
public static String wrap(String before, String after, String delimiter, String... strs) {
String rtn = null;
if (strs != null) {
rtn = wrap(strs, before, after, delimiter, 0, strs.length - 1);
}
return rtn;
}
public static String[] unWrap(String str, String before, String after, String delimiter) {
String[] rtn = null;
if (str != null && before != null && after != null && delimiter != null) {
String[] tokens = str.split(delimiter, -1);
rtn = new String[tokens.length];
for (int i = 0; i < tokens.length; i++) {
int iBegin = 0;
int iEnd = tokens[i].length();
if (tokens[i].startsWith(before)) {
iBegin = before.length();
}
if (tokens[i].endsWith(after) && !tokens[i].equals(before)) {
iEnd = iEnd - after.length();
}
if (iEnd >= iBegin && iBegin >= 0) {
rtn[i] = tokens[i].substring(iBegin, iEnd);
} else {
throw new TRuntimeException("unWarp: wrong format string: [str,before,after,delimiter]:", str, before, after, delimiter);
}
}
}
return rtn;
}
public static String getCmdArg(String argName, String[] args) {
String rtn = null;
if (args != null && argName != null) {
for (int i = 0; i < args.length; i++) {
if (args[i] != null) {
int iArg = args[i].indexOf(argName);
if (iArg == 0) {
if (args[i].length() > argName.length()) {
rtn = args[i].substring(argName.length());
} else {
rtn = "";
}
break;
}
}
}
}
return rtn;
}
public static String cap1stLetter(String str) {
String rtn = null;
if (str != null) {
if (str.length() > 0) {
StringBuffer sBuffer = new StringBuffer();
char c0 = str.charAt(0);
sBuffer.append(Character.toUpperCase(c0));
if (str.length() > 1) {
sBuffer.append(str.substring(1));
}
rtn = sBuffer.toString();
} else {
rtn = "";
}
}
return rtn;
}
public static String getterMethodName(String sVar) {
String rtn = null;
if (sVar != null) {
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("get");
sBuffer.append(cap1stLetter(sVar));
rtn = sBuffer.toString();
}
return rtn;
}
public static String setterMethodName(String sVar) {
String rtn = null;
if (sVar != null) {
StringBuffer sBuffer = new StringBuffer();
sBuffer.append("set");
sBuffer.append(cap1stLetter(sVar));
rtn = sBuffer.toString();
}
return rtn;
}
public static String regexQuote(String str) {
return Pattern.quote(str);
}
public static String[] trim(String[] strs) {
String[] rtn = null;
if (strs != null) {
int i, j, k, l;
for (i = 0; i < strs.length; i++) {
if (valid(strs[i])) {
break;
}
}
for (j = strs.length - 1; j >= 0; j--) {
if (valid(strs[j])) {
break;
}
}
if (j - i + 1 > 0) {
rtn = new String[j - i + 1];
for (l = 0, k = i; k <= j; k++, l++) {
rtn[l] = strs[k];
}
}
}
return rtn;
}
public static boolean hasPattern(String str, String regex) {
boolean rtn = false;
if (str != null && regex != null) {
Pattern pat = Pattern.compile(regex);
Matcher matcher = pat.matcher(str);
rtn = matcher.find();
}
return rtn;
}
public static boolean hasVariable(String str) {
return hasPattern(str, sPatVar);
}
public static boolean hasExpression(String str) {
return hasPattern(str, sPatExp);
}
/**
* \n does not count as a character represented by "." in regular
* expression. So a valid evaluation (Variable or Expression) should be
* within a same line.
*
* @param str
* @return
*/
public static boolean hasEvaluation(String str) {
return hasPattern(str, "(" + sPatVar + "|" + sPatExp + ")");
}
public static boolean bNoEval(String str) {
boolean rtn = false;
if (str != null && str.length() >= sNoEval.length()) {
String sBeginning = str.substring(0, sNoEval.length());
rtn = sNoEval.equals(sBeginning);
}
return rtn;
}
public static boolean canEval(String str) {
return hasEvaluation(str) && !bNoEval(str);
}
public static String removeNoEval(String str) {
String rtn = str;
if (str != null && str.indexOf(sNoEval) == 0) {
rtn = str.substring(sNoEval.length());
}
return rtn;
}
/**
* Convert tObj to String. If tObj is a number, it will be converted
* according to sPatNumOut. If tObj is a List or array, each of its elements
* will be converted. Otherwise, it will be
* converted as tObj+"".
*
* @param tObj
* @param sPatNumOut
* @return will never be null (could be a string "null" when tObj == null);
*/
public static String valToStr(Object tObj, String sPatNumOut) {
String rtn = "null";
if (tObj != null) {
if (sPatNumOut != null && tObj instanceof Number) {
DecimalFormat df = new DecimalFormat(sPatNumOut);
rtn = df.format(tObj);
} else if (bAssignable(Object[].class, tObj.getClass())) {
Object[] ao = (Object[]) tObj;
rtn = "[";
for (int i = 0; i < ao.length; i++) {
rtn += valToStr(ao[i], sPatNumOut);
if (i < ao.length - 1) {
rtn += de;
}
}
rtn += "]";
} else if (bAssignable(List.class, tObj.getClass())) {
List lo = (List) tObj;
rtn = "[";
for (int i = 0, mi = lo.size(); i < mi; i++) {
rtn += valToStr(lo.get(i), sPatNumOut);
if (i < mi - 1) {
rtn += de;
}
}
rtn += "]";
} else {
rtn = tObj + "";
}
}
return rtn;
}
public static String valToStr(Object tObj) {
return valToStr(tObj, null);
}
/**
*
* @param str
* @return null if str is not a valid expression, otherwise a BigDeciaml
* number.
*/
public static BigDecimal eval1Expression(String str) {
BigDecimal rtn = null;
if (str != null && Expression.bValid(str)) {
Expression expression = new Expression(str);
rtn = expression.eval();
}
return rtn;
}
public static String evalExpression(String str, String sPatNumOut, int flags) {
String rtn = str;
if (hasExpression(str) && (!bNoEval(str))) {
rtn = "";
Pattern pat = Pattern.compile(sPatExp);
Matcher matcher = pat.matcher(str);
int iLastTo = 0;
while (matcher.find()) {
int iFrom = matcher.start(), iTo = matcher.end();
rtn += str.substring(iLastTo, iFrom);
String sExp = matcher.group(1);
BigDecimal bdVal = eval1Expression(sExp);
if (bdVal == null) {
if ((flags & EVAL_InvalidException) > 0) {
throw new TRuntimeException("invalid expression: ", sExp);
}
if ((flags & EVAL_InvalidIgnore) > 0) {
rtn += str.substring(iFrom, iTo);
}
} else {
rtn += valToStr(bdVal, sPatNumOut);
}
iLastTo = iTo;
}
rtn += str.substring(iLastTo);
}
return rtn;
}
/**
* Get substrings in a string using groups in regular expression.
*
* @param str
* @param regex
* @return
*/
public static String[] regexMatch(String str, String regex) {
String[] rtn = null;
if (str != null && regex != null) {
Pattern pat = Pattern.compile(regex);
Matcher matcher = pat.matcher(str);
if (matcher.find()) {
int nGroup = matcher.groupCount();
rtn = new String[nGroup];
for (int i = 0; i < nGroup; i++) {//group 0 represents all match should be skipped.
rtn[i] = matcher.group(i + 1);
}
}
}
return rtn;
}
/**
* Count the occurrences of the regex pattern in str.
*
* @param str
* @param regex
* @return
*/
public static int regexCount(String str, String regex) {
int rtn = -1;
String[] subStrs = regexMatch(str, regex);
if (subStrs != null) {
rtn = subStrs.length;
}
return rtn;
}
/**
* Only support one method in str!
*
* @param str
* @return
*/
public static List<String> parseMethodAsStrList(String str, boolean bSplitPars) {
List<String> rtn = null;
if (str != null) {
int i0 = str.indexOf("("), i1 = str.indexOf(")");
if (i0 > 0 && i1 > i0) {
rtn = new ArrayList();
String sMethod = str.substring(0, i0);
rtn.add(sMethod);
if (i1 > i0 + 1) {
String sPars = str.substring(i0 + 1, i1);
if (bSplitPars) {
String[] tokens = split(sPars, -1);
for (int i = 0; i < tokens.length; i++) {
rtn.add(tokens[i]);
}
} else {
rtn.add(sPars);
}
}
}
}
return rtn;
}
public static List<String> parseMethodAsStrList(String str) {
return parseMethodAsStrList(str, true);
}
public static URL getURL(Class tClass) {
URL rtn = null;
if (tClass != null) {
ClassLoader cl = tClass.getClassLoader();
rtn = cl.getResource(tClass.getName().replace('.', '/') + ".class");
}
return rtn;
}
public static String getPath(Class tClass) {
String rtn = null;
URL url = getURL(tClass);
if (url != null) {
rtn = url.getPath();
rtn = rtn.replace(tClass.getSimpleName() + ".class", "");
}
return rtn;
}
public static String getWorkingPath() {
return new File(".").getAbsolutePath();
}
public static String trim(String str, boolean bFromStart, boolean bFromEnd) {
String rtn = str;
if (str != null) {
String sBeginPattern = "^\\s+";
String sEndPattern = "\\s+$";
if (bFromStart) {
rtn = rtn.replaceAll(sBeginPattern, "");
}
if (bFromEnd) {
rtn = rtn.replaceAll(sEndPattern, "");
}
}
return rtn;
}
public static Double toDouble(String str) {
Double rtn = null;
if (str != null) {
try {
rtn = new Double(str);
} catch (NumberFormatException e) {
rtn = null;
}
}
return rtn;
}
public static boolean bNumber(String str) {
return toDouble(str) != null;
}
public static String[] parseStrArray(String str, String regexPattern) {
String[] rtn = null;
if (str != null && regexPattern != null) {
List<String> lRtn = new ArrayList<String>();
Pattern pat = Pattern.compile(regexPattern);
Matcher matcher = pat.matcher(str);
while (matcher.find()) {
String sElement = matcher.group(1);
lRtn.add(sElement);
}
rtn = new String[lRtn.size()];
rtn = lRtn.toArray(rtn);
}
return rtn;
}
public static String toValidFileName(String sFile) {
String rtn = sFile;
if (sFile != null) {
String sInvalidPattern = "[\\?<>\\|\\*/:\"\\\\]";
rtn = rtn.replaceAll(sInvalidPattern, "");
}
return rtn;
}
}
| |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import static org.openqa.selenium.testing.Ignore.Driver.CHROME;
import static org.openqa.selenium.testing.Ignore.Driver.FIREFOX;
import static org.openqa.selenium.testing.Ignore.Driver.IE;
import static org.openqa.selenium.testing.Ignore.Driver.MARIONETTE;
import static org.openqa.selenium.testing.Ignore.Driver.PHANTOMJS;
import static org.openqa.selenium.testing.Ignore.Driver.SAFARI;
import com.google.common.collect.Sets;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import javax.imageio.ImageIO;
/**
* Test screenshot feature.
*
* 1. check output for all possible types
*
* 2. check screenshot image
*
* Logic of screenshot check test is simple:
* - open page with fixed amount of fixed sized and coloured areas
* - take screenshot
* - calculate expected colors as in tested HTML page
* - scan screenshot for actual colors * compare
*
*/
// TODO(user): verify expected behaviour after frame switching
// TODO(user): test screenshots at guaranteed maximized browsers
// TODO(user): test screenshots at guaranteed non maximized browsers
// TODO(user): test screenshots at guaranteed minimized browsers
// TODO(user): test screenshots at guaranteed fullscreened/kiosked browsers (WINDOWS platform specific)
@Ignore(value = {IE}, reason = "IE: strange colors appeared")
public class TakesScreenshotTest extends JUnit4TestBase {
private TakesScreenshot screenshoter;
private File tempFile = null;
@Before
public void setUp() throws Exception {
assumeTrue(driver instanceof TakesScreenshot);
screenshoter = (TakesScreenshot) driver;
}
@After
public void tearDown() {
if (tempFile != null) {
tempFile.delete();
tempFile = null;
}
}
@Test
@Ignore(MARIONETTE)
public void testGetScreenshotAsFile() throws Exception {
driver.get(pages.simpleTestPage);
tempFile = screenshoter.getScreenshotAs(OutputType.FILE);
assertTrue(tempFile.exists());
assertTrue(tempFile.length() > 0);
}
@Test
public void testGetScreenshotAsBase64() throws Exception {
driver.get(pages.simpleTestPage);
String screenshot = screenshoter.getScreenshotAs(OutputType.BASE64);
assertTrue(screenshot.length() > 0);
}
@Test
public void testGetScreenshotAsBinary() throws Exception {
driver.get(pages.simpleTestPage);
byte[] screenshot = screenshoter.getScreenshotAs(OutputType.BYTES);
assertTrue(screenshot.length > 0);
}
@Test
public void testShouldCaptureScreenshotOfCurrentViewport() throws Exception {
driver.get(appServer.whereIs("screen/screen.html"));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step */ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
compareColors(expectedColors, actualColors);
}
@Test
@Ignore(value = {SAFARI, CHROME, MARIONETTE},
reason = " SAFARI: takes only visible viewport." +
" CHROME: takes only visible viewport.")
public void testShouldCaptureScreenshotOfPageWithLongX() throws Exception {
driver.get(appServer.whereIs("screen/screen_x_long.html"));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 50,
/* stepY in pixels */ 5);
Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
compareColors(expectedColors, actualColors);
}
@Test
@Ignore(value = {SAFARI, CHROME, MARIONETTE},
reason = " SAFARI: takes only visible viewport." +
" CHROME: takes only visible viewport.")
public void testShouldCaptureScreenshotOfPageWithLongY() throws Exception {
driver.get(appServer.whereIs("screen/screen_y_long.html"));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 50);
Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
compareColors(expectedColors, actualColors);
}
@Test
@Ignore(value = {PHANTOMJS, SAFARI, CHROME, IE, FIREFOX, MARIONETTE},
reason = " IE: cuts captured image at driver level." +
" FF: captured image is cat at driver level." +
" SAFARI: takes only visible viewport." +
" CHROME: takes only visible viewport." +
" PHANTOMJS: diffs at colors - small dimensions or coloring problem.")
public void testShouldCaptureScreenshotOfPageWithTooLongX() throws Exception {
driver.get(appServer.whereIs("screen/screen_x_too_long.html"));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 100,
/* stepY in pixels */ 5);
Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
compareColors(expectedColors, actualColors);
}
@Test
@Ignore(value = {PHANTOMJS, SAFARI, CHROME, IE, FIREFOX, MARIONETTE},
reason = " IE: cuts captured image at driver level." +
" FF: captured image is cat at driver level." +
" SAFARI: takes only visible viewport." +
" CHROME: takes only visible viewport." +
" PHANTOMJS: diffs at colors - small dimensions or coloring problem.")
public void testShouldCaptureScreenshotOfPageWithTooLongY() throws Exception {
driver.get(appServer.whereIs("screen/screen_y_too_long.html"));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 100);
Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
compareColors(expectedColors, actualColors);
}
@Test
@Ignore(value = {PHANTOMJS, SAFARI, CHROME, IE, FIREFOX, MARIONETTE},
reason = " IE: returns null." +
" FF: failed due NS_ERROR_FAILURE at context.drawWindow." +
" SAFARI: takes only visible viewport." +
" CHROME: takes only visible viewport." +
" PHANTOMJS: takes empty data of byte[], no errors. ")
public void testShouldCaptureScreenshotOfPageWithTooLongXandY() throws Exception {
driver.get(appServer.whereIs("screen/screen_too_long.html"));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 100,
/* stepY in pixels */ 100);
Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
compareColors(expectedColors, actualColors);
}
@Test
@Ignore(
value = {IE, MARIONETTE},
reason = " IE: v9 shows strange border which broke color comparison"
)
public void testShouldCaptureScreenshotAtFramePage() throws Exception {
driver.get(appServer.whereIs("screen/screen_frames.html"));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
Set<String> expectedColors = new HashSet<String>();
expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with frames will be taken for full page
compareColors(expectedColors, actualColors);
}
@Test
@Ignore(value = {CHROME, MARIONETTE},
reason = " CHROME: Unknown actual colors are presented at screenshot")
public void testShouldCaptureScreenshotAtIFramePage() throws Exception {
driver.get(appServer.whereIs("screen/screen_iframes.html"));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
Set<String> expectedColors = new HashSet<String>();
expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with Iframes will be taken for full page
compareColors(expectedColors, actualColors);
}
@Test
@Ignore(
value = {IE, MARIONETTE},
reason = "IE: v9 shows strange border which broke color comparison"
)
public void testShouldCaptureScreenshotAtFramePageAfterSwitching() throws Exception {
driver.get(appServer.whereIs("screen/screen_frames.html"));
driver.switchTo().frame(driver.findElement(By.id("frame2")));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
Set<String> expectedColors = new HashSet<String>();
expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with frames after switching to a frame
// will be taken for full page
compareColors(expectedColors, actualColors);
}
@Test
@Ignore(
value = {IE, CHROME, MARIONETTE},
reason = " IE: v9 takes screesnhot only of switched-in frame area " +
" CHROME: Unknown actual colors are presented at screenshot"
)
public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() throws Exception {
driver.get(appServer.whereIs("screen/screen_iframes.html"));
driver.switchTo().frame(driver.findElement(By.id("iframe2")));
BufferedImage screenshot = getImage();
Set<String> actualColors = scanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
Set<String> expectedColors = new HashSet<String>();
expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with Iframes after switching to a Iframe
// will be taken for full page
compareColors(expectedColors, actualColors);
}
/**
* get actual image screenshot
*
* @return Image object
*/
private BufferedImage getImage() {
BufferedImage image = null;
try {
byte[] imageData = screenshoter.getScreenshotAs(OutputType.BYTES);
assertTrue(imageData != null);
assertTrue(imageData.length > 0);
image = ImageIO.read(new ByteArrayInputStream(imageData));
assertTrue(image != null);
} catch (IOException e) {
fail("Image screenshot file is invalid: " + e.getMessage());
}
//saveImageToTmpFile(image);
return image;
}
/**
* generate expected colors as in checked page.
*
* @param initialColor - initial color of first (right top) cell of grid
* @param stepColor - step b/w grid colors as number
* @param nX - grid size at X dimension
* @param nY - grid size at Y dimension
* @return set of colors in string hex presentation
*/
private Set<String> generateExpectedColors(final int initialColor, final int stepColor,
final int nX, final int nY) {
Set<String> colors = new TreeSet<String>();
int cnt = 1;
for (int i = 1; i < nX; i++) {
for (int j = 1; j < nY; j++) {
int color = initialColor + (cnt * stepColor);
String hex =
String.format("#%02x%02x%02x", ((color & 0xFF0000) >> 16), ((color & 0x00FF00) >> 8),
((color & 0x0000FF)));
colors.add(hex);
cnt++;
}
}
return colors;
}
/**
* Get colors from image from each point at grid defined by stepX/stepY.
*
* @param image - image
* @param stepX - interval in pixels b/w point in X dimension
* @param stepY - interval in pixels b/w point in Y dimension
* @return set of colors in string hex presentation
*/
private Set<String> scanActualColors(BufferedImage image, final int stepX, final int stepY) {
Set<String> colors = new TreeSet<String>();
try {
int height = image.getHeight();
int width = image.getWidth();
assertTrue(width > 0);
assertTrue(height > 0);
Raster raster = image.getRaster();
for (int i = 0; i < width; i = i + stepX) {
for (int j = 0; j < height; j = j + stepY) {
String hex = String.format("#%02x%02x%02x",
(raster.getSample(i, j, 0)),
(raster.getSample(i, j, 1)),
(raster.getSample(i, j, 2)));
colors.add(hex);
}
}
} catch (Exception e) {
fail("Unable to get actual colors from screenshot: " + e.getMessage());
}
assertTrue(colors.size() > 0);
return colors;
}
/**
* Compares sets of colors are same.
*
* @param expectedColors - set of expected colors
* @param actualColors - set of actual colors
*/
private void compareColors(Set<String> expectedColors, Set<String> actualColors) {
assertFalse("Actual image has only black color", onlyBlack(actualColors));
assertFalse("Actual image has only white color", onlyWhite(actualColors));
// Ignore black and white for further comparison
Set<String> cleanActualColors = Sets.newHashSet(actualColors);
cleanActualColors.remove("#000000");
cleanActualColors.remove("#ffffff");
if (! expectedColors.containsAll(cleanActualColors)) {
fail("There are unexpected colors on the screenshot: " +
Sets.difference(cleanActualColors, expectedColors));
}
if (! cleanActualColors.containsAll(expectedColors)) {
fail("There are expected colors not present on the screenshot: " +
Sets.difference(expectedColors, cleanActualColors));
}
}
private boolean onlyBlack(Set<String> colors) {
return colors.size() == 1 && "#000000".equals(colors.toArray()[0]);
}
private boolean onlyWhite(Set<String> colors) {
return colors.size() == 1 && "#ffffff".equals(colors.toArray()[0]);
}
/**
* Simple helper to save screenshot to tmp file. For debug purposes.
*
* @param im image
*/
private void saveImageToTmpFile(BufferedImage im) {
File outputfile = new File( testName.getMethodName() + "_image.png");
System.out.println("Image file is at " + outputfile.getAbsolutePath());
System.out.println("Sizes -> " + im.getWidth() + "x" + im.getHeight());
try {
ImageIO.write(im, "png", outputfile);
} catch (IOException e) {
fail("Unable to write image to file: " + e.getMessage());
}
}
}
| |
/*******************************************************************************
* Copyright 2002-2015, OpenNebula Project (OpenNebula.org), C12G Labs
*
* 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.opennebula.client.host;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.PoolElement;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula host.
* It also offers static XML-RPC call wrappers.
*/
public class Host extends PoolElement{
private static final String METHOD_PREFIX = "host.";
private static final String ALLOCATE = METHOD_PREFIX + "allocate";
private static final String INFO = METHOD_PREFIX + "info";
private static final String DELETE = METHOD_PREFIX + "delete";
private static final String ENABLE = METHOD_PREFIX + "enable";
private static final String UPDATE = METHOD_PREFIX + "update";
private static final String MONITORING = METHOD_PREFIX + "monitoring";
private static final String RENAME = METHOD_PREFIX + "rename";
private static final String[] HOST_STATES =
{"INIT", "MONITORING_MONITORED", "MONITORED", "ERROR", "DISABLED",
"MONITORING_ERROR", "MONITORING_INIT", "MONITORING_DISABLED"};
private static final String[] SHORT_HOST_STATES =
{"init", "update", "on", "err", "off", "retry", "init", "off"};
/**
* Creates a new Host representation.
*
* @param id The host id (hid) of the machine.
* @param client XML-RPC Client.
*/
public Host(int id, Client client)
{
super(id, client);
}
/**
* @see PoolElement
*/
protected Host(Node xmlElement, Client client)
{
super(xmlElement, client);
}
// =================================
// Static XML-RPC methods
// =================================
/**
* Allocates a new host in OpenNebula
*
* @param client XML-RPC Client.
* @param hostname Hostname of the machine we want to add
* @param im The name of the information manager (im_mad_name),
* this values are taken from the oned.conf with the tag name IM_MAD (name)
* @param vmm The name of the virtual machine manager mad name
* (vmm_mad_name), this values are taken from the oned.conf with the
* tag name VM_MAD (name)
* @param vnm The name of the virtual network manager mad name
* (vnm_mad_name), this values are taken from the oned.conf with the
* tag name VN_MAD (name)
* @param clusterId The cluster ID. If it is -1, this host won't be
* added to any cluster.
*
* @return If successful the message contains the associated
* id generated for this host
*/
public static OneResponse allocate(Client client,
String hostname,
String im,
String vmm,
String vnm,
int clusterId)
{
return client.call(ALLOCATE, hostname, im, vmm, vnm, clusterId);
}
/**
* Allocates a new host in OpenNebula
*
* @param client XML-RPC Client.
* @param hostname Hostname of the machine we want to add
* @param im The name of the information manager (im_mad_name),
* this values are taken from the oned.conf with the tag name IM_MAD (name)
* @param vmm The name of the virtual machine manager mad name
* (vmm_mad_name), this values are taken from the oned.conf with the
* tag name VM_MAD (name)
* @param vnm The name of the virtual network manager mad name
* (vnm_mad_name), this values are taken from the oned.conf with the
* tag name VN_MAD (name)
*
* @return If successful the message contains the associated
* id generated for this host
*/
public static OneResponse allocate(
Client client,
String hostname,
String im,
String vmm,
String vnm)
{
return allocate(client, hostname, im, vmm, vnm, -1);
}
/**
* Retrieves the information of the given host.
*
* @param client XML-RPC Client.
* @param id The host id (hid) of the target machine.
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public static OneResponse info(Client client, int id)
{
return client.call(INFO, id);
}
/**
* Deletes a host from OpenNebula.
*
* @param client XML-RPC Client.
* @param id The host id (hid) of the target machine.
* @return A encapsulated response.
*/
public static OneResponse delete(Client client, int id)
{
return client.call(DELETE, id);
}
/**
* Enables or disables a given host.
*
* @param client XML-RPC Client.
* @param id The host id (hid) of the target machine.
* @param enable If set true OpenNebula will enable the
* target host, if set false it will disable it.
* @return A encapsulated response.
*/
public static OneResponse enable(Client client, int id, boolean enable)
{
return client.call(ENABLE, id, enable);
}
/**
* Replaces the template contents.
*
* @param client XML-RPC Client.
* @param id The image id of the target host we want to modify.
* @param new_template New template contents
* @param append True to append new attributes instead of replace the whole template
* @return If successful the message contains the host id.
*/
public static OneResponse update(Client client, int id, String new_template,
boolean append)
{
return client.call(UPDATE, id, new_template, append ? 1 : 0);
}
/**
* Retrieves the monitoring information of the given host, in XML
*
* @param client XML-RPC Client.
* @param id The host id (hid) of the target machine.
* @return If successful the message contains the string
* with the monitoring information returned by OpenNebula.
*/
public static OneResponse monitoring(Client client, int id)
{
return client.call(MONITORING, id);
}
/**
* Renames this Host.
*
* @param client XML-RPC Client.
* @param id The image id of the target host we want to modify.
* @param name New name for the Host
* @return If successful the message contains the host id.
*/
public static OneResponse rename(Client client, int id, String name)
{
return client.call(RENAME, id, name);
}
// =================================
// Instanced object XML-RPC methods
// =================================
/**
* Loads the xml representation of the host.
* The info is also stored internally.
*
* @see Host#info(Client, int)
*/
public OneResponse info()
{
OneResponse response = info(client, id);
super.processInfo(response);
return response;
}
/**
* Deletes the host from OpenNebula.
*
* @see Host#delete(Client, int)
*/
public OneResponse delete()
{
return delete(client, id);
}
/**
* Enables or disables the host.
*
* @see Host#enable(Client, int, boolean)
*/
public OneResponse enable(boolean enable)
{
return enable(client, id, enable);
}
/**
* Enables the host.
*
* @return A encapsulated response.
*/
public OneResponse enable()
{
return enable(true);
}
/**
* Disables the host
*
* @return A encapsulated response.
*/
public OneResponse disable()
{
return enable(false);
}
/**
* Replaces the template contents.
*
* @param new_template New template contents
* @return If successful the message contains the host id.
*/
public OneResponse update(String new_template)
{
return update(new_template, false);
}
/**
* Replaces the template contents.
*
* @param new_template New template contents
* @param append True to append new attributes instead of replace the whole template
* @return If successful the message contains the host id.
*/
public OneResponse update(String new_template, boolean append)
{
return update(client, id, new_template, append);
}
/**
* Retrieves the monitoring information of the given host, in XML
*
* @return If successful the message contains the string
* with the monitoring information returned by OpenNebula.
*/
public OneResponse monitoring()
{
return monitoring(client, id);
}
/**
* Renames this Host.
*
* @param name New name for the Host
* @return If successful the message contains the host id.
*/
public OneResponse rename(String name)
{
return rename(client, id, name);
}
// =================================
// Helpers
// =================================
/**
* Returns the state of the Host.
* <br/>
* The method {@link Host#info()} must be called before.
*
* @return The state of the Host.
*/
public String stateStr()
{
int state = state();
return state != -1 ? HOST_STATES[state()] : null;
}
/**
* Returns the short length string state of the Host.
* <br/>
* The method {@link Host#info()} must be called before.
*
* @return The short length string state of the Host.
*/
public String shortStateStr()
{
int state = state();
return state != -1 ? SHORT_HOST_STATES[state()] : null;
}
/**
* Returns true if the host is enabled.
*
* @return True if the host is enabled.
*/
public boolean isEnabled()
{
return state() != 4;
}
}
| |
/*
* Copyright 2012-2016 bambooCORE, greenstep of copyright Chen Xin Nien
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* -----------------------------------------------------------------------
*
* author: Chen Xin Nien
* contact: chen.xin.nien@gmail.com
*
*/
package com.netsteadfast.greenstep.action;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.netsteadfast.greenstep.action.utils.DateFieldCheckUtils;
import com.netsteadfast.greenstep.action.utils.IdFieldCheckUtils;
import com.netsteadfast.greenstep.action.utils.NotBlankFieldCheckUtils;
import com.netsteadfast.greenstep.action.utils.SelectItemFieldCheckUtils;
import com.netsteadfast.greenstep.base.Constants;
import com.netsteadfast.greenstep.base.action.BaseJsonAction;
import com.netsteadfast.greenstep.base.exception.AuthorityException;
import com.netsteadfast.greenstep.base.exception.ControllerException;
import com.netsteadfast.greenstep.base.exception.ServiceException;
import com.netsteadfast.greenstep.base.model.ControllerAuthority;
import com.netsteadfast.greenstep.base.model.ControllerMethodAuthority;
import com.netsteadfast.greenstep.base.model.DefaultResult;
import com.netsteadfast.greenstep.base.model.YesNo;
import com.netsteadfast.greenstep.service.logic.ISystemMessageNoticeLogicService;
import com.netsteadfast.greenstep.vo.SysMsgNoticeVO;
@ControllerAuthority(check=true)
@Controller("core.web.controller.SystemMessageNoticeSaveOrUpdateAction")
@Scope
public class SystemMessageNoticeSaveOrUpdateAction extends BaseJsonAction {
private static final long serialVersionUID = 2995601401550856228L;
protected Logger logger=Logger.getLogger(SystemMessageNoticeSaveOrUpdateAction.class);
private ISystemMessageNoticeLogicService systemMessageNoticeLogicService;
private String message = "";
private String success = IS_NO;
public SystemMessageNoticeSaveOrUpdateAction() {
super();
}
@JSON(serialize=false)
public ISystemMessageNoticeLogicService getSystemMessageNoticeLogicService() {
return systemMessageNoticeLogicService;
}
@Autowired
@Resource(name="core.service.logic.SystemMessageNoticeLogicService")
public void setSystemMessageNoticeLogicService(
ISystemMessageNoticeLogicService systemMessageNoticeLogicService) {
this.systemMessageNoticeLogicService = systemMessageNoticeLogicService;
}
private void checkFields() throws ControllerException {
this.getCheckFieldHandler()
.add("msgOid", SelectItemFieldCheckUtils.class, this.getText("MESSAGE.CORE_PROG001D0006A_msgOid") )
.add("noticeId", IdFieldCheckUtils.class, this.getText("MESSAGE.CORE_PROG001D0006A_noticeId") )
.add("title", NotBlankFieldCheckUtils.class, this.getText("MESSAGE.CORE_PROG001D0006A_title") )
.add("date1", DateFieldCheckUtils.class, this.getText("MESSAGE.CORE_PROG001D0006A_date1") )
.add("date2", DateFieldCheckUtils.class, this.getText("MESSAGE.CORE_PROG001D0006A_date2") )
.add("message", NotBlankFieldCheckUtils.class, this.getText("MESSAGE.CORE_PROG001D0006A_message") )
.process().throwMessage();
String date1 = this.getFields().get("date1").replaceAll("/", "").replaceAll("-", "");
String date2 = this.getFields().get("date2").replaceAll("/", "").replaceAll("-", "");
this.getCheckFieldHandler().single(
"date1|date2",
(Integer.parseInt(date1) > Integer.parseInt(date2)),
this.getText("MESSAGE.CORE_PROG001D0006A_dateRange") )
.throwMessage();
this.getCheckFieldHandler().single(
"startHour|startMinutes|endHour|endMinutes",
( Integer.parseInt( this.getFields().get("startHour")+this.getFields().get("startMinutes") ) > Integer.parseInt( this.getFields().get("endHour")+this.getFields().get("endMinutes") ) ),
this.getText("MESSAGE.CORE_PROG001D0006A_timeRange") )
.throwMessage();
this.getCheckFieldHandler().single(
"toAccountOid",
(!"true".equals(this.getFields().get("isGlobal")) && this.isNoSelectId(this.getFields().get("toAccountOid"))),
this.getText("MESSAGE.CORE_PROG001D0006A_toAccountOid") )
.throwMessage();
}
private String getNoticeDate() {
String date = this.getFields().get("date1").replaceAll("/", "").replaceAll("-", "") + Constants.DATETIME_DELIMITER
+ this.getFields().get("date2").replaceAll("/", "").replaceAll("-", "");
return date;
}
private String getNoticeTime() {
String time = this.getFields().get("startHour") + this.getFields().get("startMinutes") + Constants.DATETIME_DELIMITER +
this.getFields().get("endHour") + this.getFields().get("endMinutes");
return time;
}
private void save() throws ControllerException, AuthorityException, ServiceException, Exception {
this.checkFields();
SysMsgNoticeVO notice = new SysMsgNoticeVO();
this.getFields().put("date", this.getNoticeDate());
this.getFields().put("time", this.getNoticeTime());
this.transformFields2ValueObject(notice, new String[]{"noticeId", "title", "message", "date", "time"} );
notice.setIsGlobal(YesNo.NO);
if ("true".equals(this.getFields().get("isGlobal"))) {
notice.setIsGlobal(YesNo.YES);
}
DefaultResult<SysMsgNoticeVO> result = this.systemMessageNoticeLogicService.create(
notice, this.getFields().get("msgOid"), this.getFields().get("toAccountOid") );
this.message = result.getSystemMessage().getValue();
if (result.getValue()!=null) {
this.success = IS_YES;
}
}
private void update() throws ControllerException, AuthorityException, ServiceException, Exception {
this.checkFields();
SysMsgNoticeVO notice = new SysMsgNoticeVO();
this.getFields().put("date", this.getNoticeDate());
this.getFields().put("time", this.getNoticeTime());
this.transformFields2ValueObject(notice, new String[]{"oid", "noticeId", "title", "message", "date", "time"} );
notice.setIsGlobal(YesNo.NO);
if ("true".equals(this.getFields().get("isGlobal"))) {
notice.setIsGlobal(YesNo.YES);
}
DefaultResult<SysMsgNoticeVO> result = this.systemMessageNoticeLogicService.update(
notice, this.getFields().get("toAccountOid") );
this.message = result.getSystemMessage().getValue();
if (result.getValue()!=null) {
this.success = IS_YES;
}
}
private void delete() throws ControllerException, AuthorityException, ServiceException, Exception {
SysMsgNoticeVO notice = new SysMsgNoticeVO();
this.transformFields2ValueObject(notice, new String[]{"oid"} );
DefaultResult<Boolean> result = this.systemMessageNoticeLogicService.delete(notice);
this.message = result.getSystemMessage().getValue();
if (result.getValue()!=null && result.getValue()) {
this.success = IS_YES;
}
}
/**
* core.systemMessageNoticeSaveAction.action
*
* @return
* @throws Exception
*/
@ControllerMethodAuthority(programId="CORE_PROG001D0006A")
public String doSave() throws Exception {
try {
if (!this.allowJob()) {
this.message = this.getNoAllowMessage();
return SUCCESS;
}
this.save();
} catch (AuthorityException | ControllerException | ServiceException e) {
this.message = e.getMessage().toString();
} catch (Exception e) {
this.message = this.logException(e);
this.success = IS_EXCEPTION;
}
return SUCCESS;
}
/**
* core.systemMessageNoticeUpdateAction.action
*
* @return
* @throws Exception
*/
@ControllerMethodAuthority(programId="CORE_PROG001D0006E")
public String doUpdate() throws Exception {
try {
if (!this.allowJob()) {
this.message = this.getNoAllowMessage();
return SUCCESS;
}
this.update();
} catch (AuthorityException | ControllerException | ServiceException e) {
this.message = e.getMessage().toString();
} catch (Exception e) {
this.message = this.logException(e);
this.success = IS_EXCEPTION;
}
return SUCCESS;
}
/**
* core.systemMessageNoticeDeleteAction.action
*
* @return
* @throws Exception
*/
@ControllerMethodAuthority(programId="CORE_PROG001D0006Q")
public String doDelete() throws Exception {
try {
if (!this.allowJob()) {
this.message = this.getNoAllowMessage();
return SUCCESS;
}
this.delete();
} catch (AuthorityException | ControllerException | ServiceException e) {
this.message = e.getMessage().toString();
} catch (Exception e) {
this.message = this.logException(e);
this.success = IS_EXCEPTION;
}
return SUCCESS;
}
@JSON
@Override
public String getLogin() {
return super.isAccountLogin();
}
@JSON
@Override
public String getIsAuthorize() {
return super.isActionAuthorize();
}
@JSON
@Override
public String getMessage() {
return this.message;
}
@JSON
@Override
public String getSuccess() {
return this.success;
}
@JSON
@Override
public List<String> getFieldsId() {
return this.fieldsId;
}
@JSON
@Override
public Map<String, String> getFieldsMessage() {
return this.fieldsMessage;
}
}
| |
package home.smart.fly.animations.customview.canvas;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by Rookie on 2017/6/29.
*/
public class DrawingBoard extends View {
private static final String TAG = "DrawingBoard";
public static final float BASE = 200.0f;
private Context mContext;
private int screenW, screenH;
//
private int widht, height;
//
private Paint mPaint;
private Paint pointPaint;
private Paint linePaint;
private PointF startP;
private PointF endP;
private PointF controllP;
private Path path;
//Animations
private ValueAnimator mValueAnimator;
public DrawingBoard(Context context) {
super(context);
init(context);
}
public DrawingBoard(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public DrawingBoard(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
mContext = context;
Log.e(TAG, "init:UNSPECIFIED= " + MeasureSpec.UNSPECIFIED);
Log.e(TAG, "init:EXACTLY= " + MeasureSpec.EXACTLY);
Log.e(TAG, "init:AT_MOST= " + MeasureSpec.AT_MOST);
DisplayMetrics dm = context.getResources().getDisplayMetrics();
screenW = dm.widthPixels;
screenH = dm.heightPixels;
initPaint();
}
private void initPaint() {
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStrokeWidth(8.0f);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setAntiAlias(true);
pointPaint = new Paint();
pointPaint.setColor(Color.WHITE);
pointPaint.setStrokeWidth(20.0f);
pointPaint.setAntiAlias(true);
linePaint = new Paint();
linePaint.setColor(Color.DKGRAY);
linePaint.setStrokeWidth(2.0f);
linePaint.setAntiAlias(true);
startP = new PointF(-BASE, 0);
endP = new PointF(BASE, 0);
controllP = new PointF(0, -BASE);
path = new Path();
mValueAnimator = ValueAnimator.ofFloat(-BASE, BASE);
mValueAnimator.setRepeatCount(ValueAnimator.INFINITE);
mValueAnimator.setRepeatMode(ValueAnimator.REVERSE);
mValueAnimator.setDuration(3000);
mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
Log.e(TAG, "onAnimationUpdate: value=" + value);
controllP.y = value;
controllP.x = value;
// controllP.x = (float) (BASE * Math.sin(value * Math.PI / BASE));
invalidate();
}
});
// mValueAnimator.start();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
widht = w;
height = h;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode == MeasureSpec.AT_MOST) {
widthSize = Math.min(screenW, screenH);
}
if (heightMode == MeasureSpec.AT_MOST) {
heightSize = Math.min(screenW, screenH);
}
setMeasuredDimension(widthSize, heightSize);
Log.e(TAG, "onMeasure:widthMode " + widthMode);
Log.e(TAG, "onMeasure:widthSize " + widthSize);
Log.e(TAG, "onMeasure:heightMode " + heightMode);
Log.e(TAG, "onMeasure:heightSize " + heightSize);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
path.reset();
canvas.drawColor(Color.GRAY);
canvas.translate(widht / 2, height / 2);
canvas.drawPoint(startP.x, startP.y, pointPaint);
canvas.drawPoint(endP.x, endP.y, pointPaint);
canvas.drawPoint(controllP.x, controllP.y, pointPaint);
//controll line
canvas.drawLine(startP.x, startP.y, controllP.x, controllP.y, linePaint);
canvas.drawLine(endP.x, endP.y, controllP.x, controllP.y, linePaint);
path.moveTo(startP.x, startP.y);
path.quadTo(controllP.x, controllP.y, endP.x, endP.y);
canvas.drawPath(path, mPaint);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mValueAnimator.cancel();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - widht / 2;
float y = event.getY() - height / 2;
Log.e(TAG, "onTouchEvent: x=" + x);
Log.e(TAG, "onTouchEvent: y=" + y);
controllP.x = x;
controllP.y = y;
invalidate();
return true;
}
}
| |
/*
* 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.tomcat.util.http.fileupload;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.tomcat.util.http.fileupload.util.mime.MimeUtility;
/**
* A simple parser intended to parse sequences of name/value pairs.
*
* Parameter values are expected to be enclosed in quotes if they
* contain unsafe characters, such as '=' characters or separators.
* Parameter values are optional and can be omitted.
*
* <p>
* <code>param1 = value; param2 = "anything goes; really"; param3</code>
* </p>
*/
public class ParameterParser {
/**
* String to be parsed.
*/
private char[] chars = null;
/**
* Current position in the string.
*/
private int pos = 0;
/**
* Maximum position in the string.
*/
private int len = 0;
/**
* Start of a token.
*/
private int i1 = 0;
/**
* End of a token.
*/
private int i2 = 0;
/**
* Whether names stored in the map should be converted to lower case.
*/
private boolean lowerCaseNames = false;
/**
* Default ParameterParser constructor.
*/
public ParameterParser() {
super();
}
/**
* Are there any characters left to parse?
*
* @return {@code true} if there are unparsed characters,
* {@code false} otherwise.
*/
private boolean hasChar() {
return this.pos < this.len;
}
/**
* A helper method to process the parsed token. This method removes
* leading and trailing blanks as well as enclosing quotation marks,
* when necessary.
*
* @param quoted {@code true} if quotation marks are expected,
* {@code false} otherwise.
* @return the token
*/
private String getToken(boolean quoted) {
// Trim leading white spaces
while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) {
i1++;
}
// Trim trailing white spaces
while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1]))) {
i2--;
}
// Strip away quotation marks if necessary
if (quoted
&& ((i2 - i1) >= 2)
&& (chars[i1] == '"')
&& (chars[i2 - 1] == '"')) {
i1++;
i2--;
}
String result = null;
if (i2 > i1) {
result = new String(chars, i1, i2 - i1);
}
return result;
}
/**
* Tests if the given character is present in the array of characters.
*
* @param ch the character to test for presense in the array of characters
* @param charray the array of characters to test against
*
* @return {@code true} if the character is present in the array of
* characters, {@code false} otherwise.
*/
private boolean isOneOf(char ch, final char[] charray) {
boolean result = false;
for (char element : charray) {
if (ch == element) {
result = true;
break;
}
}
return result;
}
/**
* Parses out a token until any of the given terminators
* is encountered.
*
* @param terminators the array of terminating characters. Any of these
* characters when encountered signify the end of the token
*
* @return the token
*/
private String parseToken(final char[] terminators) {
char ch;
i1 = pos;
i2 = pos;
while (hasChar()) {
ch = chars[pos];
if (isOneOf(ch, terminators)) {
break;
}
i2++;
pos++;
}
return getToken(false);
}
/**
* Parses out a token until any of the given terminators
* is encountered outside the quotation marks.
*
* @param terminators the array of terminating characters. Any of these
* characters when encountered outside the quotation marks signify the end
* of the token
*
* @return the token
*/
private String parseQuotedToken(final char[] terminators) {
char ch;
i1 = pos;
i2 = pos;
boolean quoted = false;
boolean charEscaped = false;
while (hasChar()) {
ch = chars[pos];
if (!quoted && isOneOf(ch, terminators)) {
break;
}
if (!charEscaped && ch == '"') {
quoted = !quoted;
}
charEscaped = (!charEscaped && ch == '\\');
i2++;
pos++;
}
return getToken(true);
}
/**
* Returns {@code true} if parameter names are to be converted to lower
* case when name/value pairs are parsed.
*
* @return {@code true} if parameter names are to be
* converted to lower case when name/value pairs are parsed.
* Otherwise returns {@code false}
*/
public boolean isLowerCaseNames() {
return this.lowerCaseNames;
}
/**
* Sets the flag if parameter names are to be converted to lower case when
* name/value pairs are parsed.
*
* @param b {@code true} if parameter names are to be
* converted to lower case when name/value pairs are parsed.
* {@code false} otherwise.
*/
public void setLowerCaseNames(boolean b) {
this.lowerCaseNames = b;
}
/**
* Extracts a map of name/value pairs from the given string. Names are
* expected to be unique. Multiple separators may be specified and
* the earliest found in the input string is used.
*
* @param str the string that contains a sequence of name/value pairs
* @param separators the name/value pairs separators
*
* @return a map of name/value pairs
*/
public Map<String,String> parse(final String str, char[] separators) {
if (separators == null || separators.length == 0) {
return new HashMap<String,String>();
}
char separator = separators[0];
if (str != null) {
int idx = str.length();
for (char separator2 : separators) {
int tmp = str.indexOf(separator2);
if (tmp != -1 && tmp < idx) {
idx = tmp;
separator = separator2;
}
}
}
return parse(str, separator);
}
/**
* Extracts a map of name/value pairs from the given string. Names are
* expected to be unique.
*
* @param str the string that contains a sequence of name/value pairs
* @param separator the name/value pairs separator
*
* @return a map of name/value pairs
*/
public Map<String,String> parse(final String str, char separator) {
if (str == null) {
return new HashMap<String,String>();
}
return parse(str.toCharArray(), separator);
}
/**
* Extracts a map of name/value pairs from the given array of
* characters. Names are expected to be unique.
*
* @param charArray the array of characters that contains a sequence of
* name/value pairs
* @param separator the name/value pairs separator
*
* @return a map of name/value pairs
*/
public Map<String,String> parse(final char[] charArray, char separator) {
if (charArray == null) {
return new HashMap<String,String>();
}
return parse(charArray, 0, charArray.length, separator);
}
/**
* Extracts a map of name/value pairs from the given array of
* characters. Names are expected to be unique.
*
* @param charArray the array of characters that contains a sequence of
* name/value pairs
* @param offset - the initial offset.
* @param length - the length.
* @param separator the name/value pairs separator
*
* @return a map of name/value pairs
*/
public Map<String,String> parse(
final char[] charArray,
int offset,
int length,
char separator) {
if (charArray == null) {
return new HashMap<String,String>();
}
HashMap<String,String> params = new HashMap<String,String>();
this.chars = charArray;
this.pos = offset;
this.len = length;
String paramName = null;
String paramValue = null;
while (hasChar()) {
paramName = parseToken(new char[] {
'=', separator });
paramValue = null;
if (hasChar() && (charArray[pos] == '=')) {
pos++; // skip '='
paramValue = parseQuotedToken(new char[] {
separator });
if (paramValue != null) {
try {
paramValue = MimeUtility.decodeText(paramValue);
} catch (UnsupportedEncodingException e) {
// let's keep the original value in this case
}
}
}
if (hasChar() && (charArray[pos] == separator)) {
pos++; // skip separator
}
if ((paramName != null) && (paramName.length() > 0)) {
if (this.lowerCaseNames) {
paramName = paramName.toLowerCase(Locale.ENGLISH);
}
params.put(paramName, paramValue);
}
}
return params;
}
}
| |
/*
* 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.activemq.artemis.api.core.client;
import java.net.URI;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.ActiveMQInterruptedException;
import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.loadbalance.RoundRobinConnectionLoadBalancingPolicy;
import org.apache.activemq.artemis.core.client.ActiveMQClientLogger;
import org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl;
import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl;
import org.apache.activemq.artemis.uri.ServerLocatorParser;
import org.apache.activemq.artemis.utils.ActiveMQThreadFactory;
import org.apache.activemq.artemis.utils.ActiveMQThreadPoolExecutor;
/**
* Utility class for creating ActiveMQ Artemis {@link ClientSessionFactory} objects.
* <p>
* Once a {@link ClientSessionFactory} has been created, it can be further configured using its
* setter methods before creating the sessions. Once a session is created, the factory can no longer
* be modified (its setter methods will throw a {@link IllegalStateException}.
*/
public final class ActiveMQClient {
private static int globalThreadPoolSize;
private static int globalScheduledThreadPoolSize;
public static final String DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME = RoundRobinConnectionLoadBalancingPolicy.class.getCanonicalName();
public static final long DEFAULT_CLIENT_FAILURE_CHECK_PERIOD = ActiveMQDefaultConfiguration.getDefaultClientFailureCheckPeriod();
public static final long DEFAULT_CLIENT_FAILURE_CHECK_PERIOD_INVM = -1;
// 1 minute - this should be higher than ping period
public static final long DEFAULT_CONNECTION_TTL = ActiveMQDefaultConfiguration.getDefaultConnectionTtl();
public static final long DEFAULT_CONNECTION_TTL_INVM = -1;
// Any message beyond this size is considered a large message (to be sent in chunks)
public static final int DEFAULT_MIN_LARGE_MESSAGE_SIZE = 100 * 1024;
public static final boolean DEFAULT_COMPRESS_LARGE_MESSAGES = false;
public static final int DEFAULT_CONSUMER_WINDOW_SIZE = 1024 * 1024;
public static final int DEFAULT_CONSUMER_MAX_RATE = -1;
public static final int DEFAULT_CONFIRMATION_WINDOW_SIZE = -1;
public static final int DEFAULT_PRODUCER_WINDOW_SIZE = 64 * 1024;
public static final int DEFAULT_PRODUCER_MAX_RATE = -1;
public static final boolean DEFAULT_BLOCK_ON_ACKNOWLEDGE = false;
public static final boolean DEFAULT_BLOCK_ON_DURABLE_SEND = true;
public static final boolean DEFAULT_BLOCK_ON_NON_DURABLE_SEND = false;
public static final boolean DEFAULT_AUTO_GROUP = false;
public static final long DEFAULT_CALL_TIMEOUT = 30000;
public static final long DEFAULT_CALL_FAILOVER_TIMEOUT = 30000;
public static final int DEFAULT_ACK_BATCH_SIZE = 1024 * 1024;
public static final boolean DEFAULT_PRE_ACKNOWLEDGE = false;
public static final long DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT = 10000;
public static final long DEFAULT_DISCOVERY_REFRESH_TIMEOUT = 10000;
public static final int DEFAULT_DISCOVERY_PORT = 9876;
public static final long DEFAULT_RETRY_INTERVAL = 2000;
public static final double DEFAULT_RETRY_INTERVAL_MULTIPLIER = ActiveMQDefaultConfiguration.getDefaultRetryIntervalMultiplier();
public static final long DEFAULT_MAX_RETRY_INTERVAL = ActiveMQDefaultConfiguration.getDefaultMaxRetryInterval();
public static final int DEFAULT_RECONNECT_ATTEMPTS = 0;
public static final int INITIAL_CONNECT_ATTEMPTS = 1;
public static final boolean DEFAULT_FAILOVER_ON_INITIAL_CONNECTION = false;
public static final boolean DEFAULT_IS_HA = false;
public static final boolean DEFAULT_USE_GLOBAL_POOLS = true;
public static final int DEFAULT_THREAD_POOL_MAX_SIZE = -1;
public static final int DEFAULT_GLOBAL_THREAD_POOL_MAX_SIZE = 8 * Runtime.getRuntime().availableProcessors();
public static final int DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE = 5;
public static final boolean DEFAULT_CACHE_LARGE_MESSAGE_CLIENT = false;
public static final int DEFAULT_INITIAL_MESSAGE_PACKET_SIZE = 1500;
public static final boolean DEFAULT_XA = false;
public static final boolean DEFAULT_HA = false;
public static final String DEFAULT_CORE_PROTOCOL = "CORE";
public static final String THREAD_POOL_MAX_SIZE_PROPERTY_KEY = "activemq.artemis.client.global.thread.pool.max.size";
public static final String SCHEDULED_THREAD_POOL_SIZE_PROPERTY_KEY = "activemq.artemis.client.global.scheduled.thread.pool.core.size";
private static ExecutorService globalThreadPool;
private static boolean injectedPools = false;
private static ScheduledExecutorService globalScheduledThreadPool;
static {
initializeGlobalThreadPoolProperties();
}
public static synchronized void clearThreadPools() {
clearThreadPools(10, TimeUnit.SECONDS);
}
public static synchronized void clearThreadPools(long time, TimeUnit unit) {
if (injectedPools) {
globalThreadPool = null;
globalScheduledThreadPool = null;
injectedPools = false;
return;
}
if (globalThreadPool != null) {
globalThreadPool.shutdown();
try {
if (!globalThreadPool.awaitTermination(time, unit)) {
globalThreadPool.shutdownNow();
ActiveMQClientLogger.LOGGER.warn("Couldn't finish the client globalThreadPool in less than 10 seconds, interrupting it now");
}
} catch (InterruptedException e) {
throw new ActiveMQInterruptedException(e);
} finally {
globalThreadPool = null;
}
}
if (globalScheduledThreadPool != null) {
globalScheduledThreadPool.shutdown();
try {
if (!globalScheduledThreadPool.awaitTermination(time, unit)) {
globalScheduledThreadPool.shutdownNow();
ActiveMQClientLogger.LOGGER.warn("Couldn't finish the client scheduled in less than 10 seconds, interrupting it now");
}
} catch (InterruptedException e) {
throw new ActiveMQInterruptedException(e);
} finally {
globalScheduledThreadPool = null;
}
}
}
/**
* Warning: This method has to be called before any clients or servers is started on the JVM otherwise previous ServerLocator would be broken after this call.
*/
public static synchronized void injectPools(ExecutorService globalThreadPool,
ScheduledExecutorService scheduledThreadPool) {
if (globalThreadPool == null || scheduledThreadPool == null)
throw new IllegalArgumentException("thread pools must not be null");
// We call clearThreadPools as that will shutdown any previously used executor
clearThreadPools();
ActiveMQClient.globalThreadPool = globalThreadPool;
ActiveMQClient.globalScheduledThreadPool = scheduledThreadPool;
injectedPools = true;
}
public static synchronized ExecutorService getGlobalThreadPool() {
if (globalThreadPool == null) {
ThreadFactory factory = AccessController.doPrivileged(new PrivilegedAction<ThreadFactory>() {
@Override
public ThreadFactory run() {
return new ActiveMQThreadFactory("ActiveMQ-client-global-threads", true, ClientSessionFactoryImpl.class.getClassLoader());
}
});
if (globalThreadPoolSize == -1) {
globalThreadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), factory);
} else {
globalThreadPool = new ActiveMQThreadPoolExecutor(0, ActiveMQClient.globalThreadPoolSize, 60L, TimeUnit.SECONDS, factory);
}
}
return globalThreadPool;
}
public static synchronized ScheduledExecutorService getGlobalScheduledThreadPool() {
if (globalScheduledThreadPool == null) {
ThreadFactory factory = AccessController.doPrivileged(new PrivilegedAction<ThreadFactory>() {
@Override
public ThreadFactory run() {
return new ActiveMQThreadFactory("ActiveMQ-client-global-scheduled-threads", true, ClientSessionFactoryImpl.class.getClassLoader());
}
});
globalScheduledThreadPool = new ScheduledThreadPoolExecutor(ActiveMQClient.globalScheduledThreadPoolSize, factory);
}
return globalScheduledThreadPool;
}
public static int getGlobalThreadPoolSize() {
return globalThreadPoolSize;
}
public static int getGlobalScheduledThreadPoolSize() {
return globalScheduledThreadPoolSize;
}
/**
* Initializes the global thread pools properties from System properties. This method will update the global
* thread pool configuration based on defined System properties (or defaults if they are not set).
* The System properties key names are as follow:
*
* ActiveMQClient.THREAD_POOL_MAX_SIZE_PROPERTY_KEY="activemq.artemis.client.global.thread.pool.max.size"
* ActiveMQClient.SCHEDULED_THREAD_POOL_SIZE_PROPERTY_KEY="activemq.artemis.client.global.scheduled.thread.pool.core.size
*
* The min value for max thread pool size is 2. If the value is not -1, but lower than 2, it will be ignored and will default to 2.
* A value of -1 configures an unbounded thread pool.
*
* Note: If global thread pools have already been created, they will not be updated with these new values.
*/
public static void initializeGlobalThreadPoolProperties() {
setGlobalThreadPoolProperties(Integer.valueOf(System.getProperty(ActiveMQClient.THREAD_POOL_MAX_SIZE_PROPERTY_KEY, "" + ActiveMQClient.DEFAULT_GLOBAL_THREAD_POOL_MAX_SIZE)), Integer.valueOf(System.getProperty(ActiveMQClient.SCHEDULED_THREAD_POOL_SIZE_PROPERTY_KEY, "" + ActiveMQClient.DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE)));
}
/**
* Allows programmatical configuration of global thread pools properties. This method will update the global
* thread pool configuration based on the provided values notifying all globalThreadPoolListeners.
*
* Note: If global thread pools have already been created, they will not be updated with these new values.
*
* The min value for globalThreadMaxPoolSize is 2. If the value is not -1, but lower than 2, it will be ignored and will default to 2.
* A value of -1 configures an unbounded thread pool.
*/
public static void setGlobalThreadPoolProperties(int globalThreadMaxPoolSize, int globalScheduledThreadPoolSize) {
if (globalThreadMaxPoolSize < 2 && globalThreadMaxPoolSize != -1)
globalThreadMaxPoolSize = 2;
ActiveMQClient.globalScheduledThreadPoolSize = globalScheduledThreadPoolSize;
ActiveMQClient.globalThreadPoolSize = globalThreadMaxPoolSize;
}
/**
* Creates an ActiveMQConnectionFactory;
*
* @return the ActiveMQConnectionFactory
*/
public static ServerLocator createServerLocator(final String url) throws Exception {
ServerLocatorParser parser = new ServerLocatorParser();
return parser.newObject(new URI(url), null);
}
/**
* Create a ServerLocator which creates session factories using a static list of transportConfigurations, the ServerLocator is not updated automatically
* as the cluster topology changes, and no HA backup information is propagated to the client
*
* @param transportConfigurations
* @return the ServerLocator
*/
public static ServerLocator createServerLocatorWithoutHA(TransportConfiguration... transportConfigurations) {
return new ServerLocatorImpl(false, transportConfigurations);
}
/**
* Create a ServerLocator which creates session factories using a static list of transportConfigurations, the ServerLocator is not updated automatically
* as the cluster topology changes, and no HA backup information is propagated to the client
*
* @param ha The Locator will support topology updates and ha (this required the server to be clustered, otherwise the first connection will timeout)
* @param transportConfigurations
* @return the ServerLocator
*/
public static ServerLocator createServerLocator(final boolean ha,
TransportConfiguration... transportConfigurations) {
return new ServerLocatorImpl(ha, transportConfigurations);
}
/**
* Create a ServerLocator which creates session factories from a set of live servers, no HA
* backup information is propagated to the client
* <p>
* The UDP address and port are used to listen for live servers in the cluster
*
* @param groupConfiguration
* @return the ServerLocator
*/
public static ServerLocator createServerLocatorWithoutHA(final DiscoveryGroupConfiguration groupConfiguration) {
return new ServerLocatorImpl(false, groupConfiguration);
}
/**
* Create a ServerLocator which creates session factories from a set of live servers, no HA
* backup information is propagated to the client The UDP address and port are used to listen for
* live servers in the cluster
*
* @param ha The Locator will support topology updates and ha (this required the server to be
* clustered, otherwise the first connection will timeout)
* @param groupConfiguration
* @return the ServerLocator
*/
public static ServerLocator createServerLocator(final boolean ha,
final DiscoveryGroupConfiguration groupConfiguration) {
return new ServerLocatorImpl(ha, groupConfiguration);
}
/**
* Create a ServerLocator which will receive cluster topology updates from the cluster as servers
* leave or join and new backups are appointed or removed.
* <p>
* The initial list of servers supplied in this method is simply to make an initial connection to
* the cluster, once that connection is made, up to date cluster topology information is
* downloaded and automatically updated whenever the cluster topology changes.
* <p>
* If the topology includes backup servers that information is also propagated to the client so
* that it can know which server to failover onto in case of live server failure.
*
* @param initialServers The initial set of servers used to make a connection to the cluster.
* Each one is tried in turn until a successful connection is made. Once a connection
* is made, the cluster topology is downloaded and the rest of the list is ignored.
* @return the ServerLocator
*/
public static ServerLocator createServerLocatorWithHA(TransportConfiguration... initialServers) {
return new ServerLocatorImpl(true, initialServers);
}
/**
* Create a ServerLocator which will receive cluster topology updates from the cluster as servers
* leave or join and new backups are appointed or removed.
* <p>
* The discoveryAddress and discoveryPort parameters in this method are used to listen for UDP
* broadcasts which contain connection information for members of the cluster. The broadcasted
* connection information is simply used to make an initial connection to the cluster, once that
* connection is made, up to date cluster topology information is downloaded and automatically
* updated whenever the cluster topology changes.
* <p>
* If the topology includes backup servers that information is also propagated to the client so
* that it can know which server to failover onto in case of live server failure.
*
* @param groupConfiguration
* @return the ServerLocator
*/
public static ServerLocator createServerLocatorWithHA(final DiscoveryGroupConfiguration groupConfiguration) {
return new ServerLocatorImpl(true, groupConfiguration);
}
private ActiveMQClient() {
// Utility class
}
}
| |
/*******************************************************************************
* Copyright (c) 2014-2015 SRCC MSU
*
* Distributed under the MIT License - see the accompanying file LICENSE.txt.
******************************************************************************/
package ru.parallel.octotron.logic;
import ru.parallel.octotron.bg_services.BGExecutorWrapper;
import ru.parallel.utils.Timer;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* simplifies statistics collection
* add is thread safe, read functions are not
* */
public class Statistics
{
private final List<BGExecutorWrapper> registered_services = new CopyOnWriteArrayList<>();
public static final class Metric
{
private Long total;
private Long sum;
private Long min_value;
private Long max_value;
private Long current;
private int count;
public Metric()
{
total = 0L;
Reset();
}
public void Reset()
{
sum = null;
min_value = null;
max_value = null;
count = 0;
}
public void Collect(long value)
{
current = value;
if(total == null)
total = value;
else
total += value;
if(sum == null)
sum = value;
else
sum += value;
if(min_value == null || min_value > value)
min_value = value;
if(max_value == null || max_value < value)
max_value = value;
count++;
}
public double GetAvg()
{
if(sum == null || count == 0)
return 0.0;
return 1.0 * sum / count;
}
public long GetMin()
{
if(min_value == null)
return 0;
return min_value;
}
public long GetMax()
{
if(max_value == null)
return 0;
return max_value;
}
public long GetSum()
{
if(sum == null)
return 0;
return sum;
}
public long GetTotal()
{
return total;
}
public long GetCurrent()
{
return current;
}
}
public static class Stat
{
public final String name;
public final Metric queue_size_metric = new Metric();
public final Metric total_metric = new Metric();
public Stat(String name)
{
this.name = name;
}
}
final Map<String, Stat> stats = new HashMap<>();
private final Timer timer_60 = new Timer();
public void RegisterService(BGExecutorWrapper service)
{
registered_services.add(service);
}
public Statistics()
{
timer_60.Start();
}
private void Add(String name, long added_count, long queue_size)
{
Stat stat = stats.get(name);
if(stat == null)
{
stat = new Stat(name);
stats.put(name, stat);
}
stat.total_metric.Collect(added_count);
stat.queue_size_metric.Collect(queue_size);
}
private static Map<String, Object> GetAvgs(Metric metric, String name)
{
Map<String, Object> res = new HashMap<>();
res.put(name + " current", String.valueOf(metric.GetCurrent()));
res.put(name + " min", String.valueOf(metric.GetMin()));
res.put(name + " max", String.valueOf(metric.GetMax()));
res.put(name + " avg", String.format("%.2f", metric.GetAvg()));
return res;
}
private static Map<String, Object> GetChange(Metric metric, int seconds, String name)
{
Map<String, Object> res = new HashMap<>();
res.put(name + " total"
, String.valueOf(metric.GetTotal()));
res.put(name + " for " + seconds + " secs"
, String.valueOf(metric.GetSum()));
if(seconds > 0)
res.put(name + " per sec"
, String.format("%.2f", 1.0 * metric.GetSum() / seconds));
return res;
}
public List<Map<String, Object>> GetRepresentation()
{
List<Map<String, Object>> res = new LinkedList<>();
for(Stat stat : stats.values())
{
Map<String, Object> to_add = Statistics.GetAvgs(stat.queue_size_metric, stat.name + " queue");
to_add.putAll(Statistics.GetChange(stat.total_metric, (int) timer_60.Get(), stat.name));
res.add(to_add);
}
return res;
}
public void Process()
{
for(BGExecutorWrapper service : registered_services)
Add(service.GetName(), service.GetRecentCompletedCount(), service.GetWaitingCount());
if(timer_60.Get() > 60) /*secs in min..*/
{
for(Stat stat : stats.values())
{
stat.queue_size_metric.Reset();
stat.total_metric.Reset();
}
timer_60.Start();
}
}
}
| |
/* Copyright (C) 2013-2014 Computer Sciences 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 ezbake.app.sample.rest.resource;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import static ezbake.app.sample.rest.WebServiceUtils.getSecurityToken;
import static ezbake.app.sample.rest.WebServiceUtils.isValidJsonObject;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ezbake.app.sample.rest.WebServiceException;
import ezbake.configuration.EzConfiguration;
import ezbake.configuration.EzConfigurationLoaderException;
import ezbake.data.elastic.thrift.MalformedQueryException;
import ezbake.data.image.frack.utilities.pojo.ImageSearchPojo;
import ezbake.data.image.frack.utilities.pojo.IndexedImagePojo;
import ezbake.data.image.frack.utilities.pojo.SearchResultsPojo;
import ezbake.services.indexing.image.thrift.ImageBinaryMissing;
import ezbake.services.indexing.image.thrift.ImageIndexerService;
import ezbake.services.indexing.image.thrift.ImageIndexerServiceConstants;
import ezbake.services.indexing.image.thrift.ImageSearch;
import ezbake.services.indexing.image.thrift.IndexedImage;
import ezbake.services.indexing.image.thrift.MaybeIndexedImage;
import ezbake.services.indexing.image.thrift.MaybeThumbnail;
import ezbake.services.indexing.image.thrift.SearchResults;
import ezbake.services.indexing.image.thrift.Thumbnail;
import ezbake.services.indexing.image.thrift.ThumbnailSize;
import ezbake.thrift.ThriftClientPool;
/**
* REST endpoint to get and query images associated with Tweets.
*/
@Path("images")
public final class ImageResource {
private static final Logger logger = LoggerFactory.getLogger(ImageResource.class);
/**
* Client pool used to create connections to the Image Indexer Thrift common service.
*/
private final ThriftClientPool pool;
/**
* The current request.
*/
@Context
private HttpServletRequest httpRequest;
/**
* Constructor.
*/
public ImageResource() {
try {
final Properties props = new EzConfiguration().getProperties();
pool = new ThriftClientPool(props);
} catch (final EzConfigurationLoaderException e) {
final String errMsg = "Could not read EzBake configuration";
logger.error(errMsg, e);
throw new WebApplicationException(
e, Response.status(INTERNAL_SERVER_ERROR).entity(errMsg).build());
}
}
/**
* Retrieves an image by its EzBake image ID.
*
* @param ezBakeImageId EzBake image ID of the image to retrieve
* @return Response containing the binary and MIME type of the image
*/
@GET
@Path("binary/{ezBakeImageId : \\p{Alnum}{64}}")
public Response getBinary(@PathParam("ezBakeImageId") String ezBakeImageId) {
final IndexedImage image = retrieveImage(ezBakeImageId, true);
return Response.ok(image.getImageData().getBlob(), image.getImageData().getMimeType()).build();
}
/**
* Retrieves an image's metadata by its EzBake image ID.
*
* @param ezBakeImageId EzBake image ID of the image whose metadata to retrieve
* @return JSON string of the metadata
*/
@GET
@Path("metadata/{ezBakeImageId : \\p{Alnum}{64}}")
@Produces(MediaType.APPLICATION_JSON)
public String getMetadata(@PathParam("ezBakeImageId") String ezBakeImageId) {
final IndexedImage image = retrieveImage(ezBakeImageId, false);
try {
return IndexedImagePojo.fromThrift(image).toJson(true, false);
} catch (final TException e) {
final String errMsg = String.format(
"Could not convert image metadata for image with EzBake image ID of '%s' to JSON", ezBakeImageId);
logger.error(errMsg, e);
throw new WebServiceException(INTERNAL_SERVER_ERROR, errMsg);
}
}
/**
* Retrieves an image's thumbnail of the specified size.
*
* @param ezBakeImageId EzBake image ID of the image whose thumbnail to retrieve
* @param size Size of the thumbnail (can be "small", "medium", or "large")
* @return Response containing the binary and MIME type of the thumbnail
*/
@GET
@Path("thumbnail/{size}/{ezBakeImageId : \\p{Alnum}{64}}")
public Response getThumbnail(@PathParam("ezBakeImageId") String ezBakeImageId, @PathParam("size") String size) {
ImageIndexerService.Client client = null;
try {
client = getImageIndexerClient();
final MaybeThumbnail maybeThumbnail = client.getThumbnail(
ezBakeImageId, ThumbnailSize.valueOf(size.toUpperCase()), getSecurityToken(httpRequest));
if (!maybeThumbnail.isSetThumbnail()) {
throw new WebServiceException(
NOT_FOUND, String.format(
"Thumbnail of size '%s' for EzBake image ID '%s' could not be found", size, ezBakeImageId));
}
final Thumbnail thumbnail = maybeThumbnail.getThumbnail();
return Response.ok(thumbnail.getThumbnailBytes(), thumbnail.getMimeType()).build();
} catch (final TException e) {
final String errMsg = String.format(
"Thrift error when trying to retrieve thumbnail of size '%s' for image with EzBake image ID '%s'",
size, ezBakeImageId);
logger.error(errMsg, e);
throw new WebServiceException(INTERNAL_SERVER_ERROR, errMsg);
} finally {
if (client != null) {
pool.returnToPool(client);
}
}
}
/**
* Search images by metadata or similarity via a JSON query.
*
* @param jsonQuery JSON image query
* @return JSON string of the search results
*/
@POST
@Path("search")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String searchImages(String jsonQuery) {
if (!isValidJsonObject(jsonQuery)) {
final String errMsg = "Image search query must be a valid JSON object";
logger.error(errMsg);
throw new WebServiceException(BAD_REQUEST, errMsg);
}
ImageSearch search = null;
try {
search = ImageSearchPojo.fromJson(jsonQuery).toThrift();
} catch (final TException e) {
final String errMsg = "JSON object is not a valid image search query";
logger.error(errMsg, e);
throw new WebServiceException(BAD_REQUEST, errMsg);
}
ImageIndexerService.Client client = null;
try {
client = getImageIndexerClient();
final SearchResults results = client.searchImages(search, getSecurityToken(httpRequest));
return SearchResultsPojo.fromThrift(results).toJson();
} catch (final MalformedQueryException e) {
final String errMsg = "Malformed image search query";
logger.error(errMsg, e);
throw new WebServiceException(BAD_REQUEST, errMsg + ": " + e.getMessage());
} catch (final TException e) {
final String errMsg = "Thrift error when trying to search images with query: " + jsonQuery;
logger.error(errMsg, e);
throw new WebServiceException(INTERNAL_SERVER_ERROR, errMsg);
} finally {
if (client != null) {
pool.returnToPool(client);
}
}
}
/**
* Retrieves an image from the image indexing service.
*
* @param ezBakeImageId EzBake image ID of the image to retrieve
* @param withBinary true to retrieve binary along with metadata, false for just metadata
* @return Retrieved image
*/
private IndexedImage retrieveImage(String ezBakeImageId, boolean withBinary) {
ImageIndexerService.Client client = null;
try {
client = getImageIndexerClient();
MaybeIndexedImage maybeImage = null;
if (withBinary) {
maybeImage = client.getImageWithBinary(ezBakeImageId, getSecurityToken(httpRequest));
} else {
maybeImage = client.getImage(ezBakeImageId, getSecurityToken(httpRequest));
}
if (!maybeImage.isSetIndexedImage()) {
throw new WebServiceException(
NOT_FOUND, String.format("Image with EzBake image ID '%s' not found", ezBakeImageId));
}
return maybeImage.getIndexedImage();
} catch (final ImageBinaryMissing e) {
final String errMsg = String.format(
"Image binary is missing for image with EzBake image ID '%s'", ezBakeImageId);
logger.error(errMsg, e);
throw new WebServiceException(INTERNAL_SERVER_ERROR, errMsg);
} catch (final TException e) {
final String errMsg = String.format(
"Thrift error when trying to retrieve binary for image with EzBake image ID '%s'", ezBakeImageId);
logger.error(errMsg, e);
throw new WebServiceException(INTERNAL_SERVER_ERROR, errMsg);
} finally {
if (client != null) {
pool.returnToPool(client);
}
}
}
/**
* Gets an image indexer service client from the Thrift client pool.
*
* @return An image indexer service client
* @throws TException if the client could not be retrieved from the pool
*/
private ImageIndexerService.Client getImageIndexerClient() throws TException {
return pool.getClient(ImageIndexerServiceConstants.SERVICE_NAME, ImageIndexerService.Client.class);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package org.apache.storm.daemon.worker;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
import org.apache.storm.Config;
import org.apache.storm.Constants;
import org.apache.storm.StormTimer;
import org.apache.storm.cluster.DaemonType;
import org.apache.storm.cluster.IStateStorage;
import org.apache.storm.cluster.IStormClusterState;
import org.apache.storm.cluster.VersionedData;
import org.apache.storm.daemon.StormCommon;
import org.apache.storm.daemon.supervisor.AdvancedFSOps;
import org.apache.storm.daemon.worker.BackPressureTracker.BackpressureState;
import org.apache.storm.executor.IRunningExecutor;
import org.apache.storm.generated.Assignment;
import org.apache.storm.generated.DebugOptions;
import org.apache.storm.generated.Grouping;
import org.apache.storm.generated.InvalidTopologyException;
import org.apache.storm.generated.NodeInfo;
import org.apache.storm.generated.StormBase;
import org.apache.storm.generated.StormTopology;
import org.apache.storm.generated.StreamInfo;
import org.apache.storm.generated.TopologyStatus;
import org.apache.storm.grouping.Load;
import org.apache.storm.grouping.LoadMapping;
import org.apache.storm.hooks.IWorkerHook;
import org.apache.storm.messaging.ConnectionWithStatus;
import org.apache.storm.messaging.DeserializingConnectionCallback;
import org.apache.storm.messaging.IConnection;
import org.apache.storm.messaging.IConnectionCallback;
import org.apache.storm.messaging.IContext;
import org.apache.storm.messaging.TransportFactory;
import org.apache.storm.messaging.netty.BackPressureStatus;
import org.apache.storm.metrics2.StormMetricRegistry;
import org.apache.storm.policy.IWaitStrategy;
import org.apache.storm.security.auth.IAutoCredentials;
import org.apache.storm.serialization.ITupleSerializer;
import org.apache.storm.serialization.KryoTupleSerializer;
import org.apache.storm.shade.com.google.common.collect.ImmutableMap;
import org.apache.storm.shade.com.google.common.collect.Sets;
import org.apache.storm.shade.org.apache.commons.lang.Validate;
import org.apache.storm.task.WorkerTopologyContext;
import org.apache.storm.tuple.AddressedTuple;
import org.apache.storm.tuple.Fields;
import org.apache.storm.utils.ConfigUtils;
import org.apache.storm.utils.JCQueue;
import org.apache.storm.utils.ObjectReader;
import org.apache.storm.utils.SupervisorClient;
import org.apache.storm.utils.SupervisorIfaceFactory;
import org.apache.storm.utils.ThriftTopologyUtils;
import org.apache.storm.utils.Utils;
import org.apache.storm.utils.Utils.SmartThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WorkerState {
private static final Logger LOG = LoggerFactory.getLogger(WorkerState.class);
private static final long LOAD_REFRESH_INTERVAL_MS = 5000L;
private static final int RESEND_BACKPRESSURE_SIZE = 10000;
private static long dropCount = 0;
final Map<String, Object> conf;
final IContext mqContext;
final IConnection receiver;
final String topologyId;
final String assignmentId;
private final Supplier<SupervisorIfaceFactory> supervisorIfaceSupplier;
final int port;
final String workerId;
final IStateStorage stateStorage;
final IStormClusterState stormClusterState;
// when worker bootup, worker will start to setup initial connections to
// other workers. When all connection is ready, we will count down this latch
// and spout and bolt will be activated, assuming the topology is not deactivated.
// used in worker only, keep it as a latch
final CountDownLatch isWorkerActive;
final AtomicBoolean isTopologyActive;
final AtomicReference<Map<String, DebugOptions>> stormComponentToDebug;
// local executors and localTaskIds running in this worker
final Set<List<Long>> localExecutors;
final ArrayList<Integer> localTaskIds;
// [taskId]-> JCQueue : initialized after local executors are initialized
final Map<Integer, JCQueue> localReceiveQueues = new HashMap<>();
final Map<String, Object> topologyConf;
final StormTopology topology;
final StormTopology systemTopology;
final Map<Integer, String> taskToComponent;
final Map<String, Map<String, Fields>> componentToStreamToFields;
final Map<String, List<Integer>> componentToSortedTasks;
final ConcurrentMap<String, Long> blobToLastKnownVersion;
final ReentrantReadWriteLock endpointSocketLock;
final AtomicReference<Map<Integer, NodeInfo>> cachedTaskToNodePort;
final AtomicReference<Map<NodeInfo, IConnection>> cachedNodeToPortSocket;
// executor id is in form [start_task_id end_task_id]
final Map<List<Long>, JCQueue> executorReceiveQueueMap;
final Map<Integer, JCQueue> taskToExecutorQueue;
final Runnable suicideCallback;
final Utils.UptimeComputer uptime;
final Map<String, Object> defaultSharedResources;
final Map<String, Object> userSharedResources;
final LoadMapping loadMapping;
final AtomicReference<Map<String, VersionedData<Assignment>>> assignmentVersions;
// Timers
final StormTimer heartbeatTimer = mkHaltingTimer("heartbeat-timer");
final StormTimer refreshLoadTimer = mkHaltingTimer("refresh-load-timer");
final StormTimer refreshConnectionsTimer = mkHaltingTimer("refresh-connections-timer");
final StormTimer refreshCredentialsTimer = mkHaltingTimer("refresh-credentials-timer");
final StormTimer checkForUpdatedBlobsTimer = mkHaltingTimer("check-for-updated-blobs-timer");
final StormTimer resetLogLevelsTimer = mkHaltingTimer("reset-log-levels-timer");
final StormTimer refreshActiveTimer = mkHaltingTimer("refresh-active-timer");
final StormTimer executorHeartbeatTimer = mkHaltingTimer("executor-heartbeat-timer");
final StormTimer flushTupleTimer = mkHaltingTimer("flush-tuple-timer");
final StormTimer userTimer = mkHaltingTimer("user-timer");
final StormTimer backPressureCheckTimer = mkHaltingTimer("backpressure-check-timer");
private final WorkerTransfer workerTransfer;
private final BackPressureTracker bpTracker;
private final List<IWorkerHook> deserializedWorkerHooks;
// global variables only used internally in class
private final Set<Integer> outboundTasks;
private final AtomicLong nextLoadUpdate = new AtomicLong(0);
private final boolean trySerializeLocal;
private final Collection<IAutoCredentials> autoCredentials;
private final StormMetricRegistry metricRegistry;
public WorkerState(Map<String, Object> conf,
IContext mqContext,
String topologyId,
String assignmentId,
Supplier<SupervisorIfaceFactory> supervisorIfaceSupplier,
int port,
String workerId,
Map<String, Object> topologyConf,
IStateStorage stateStorage,
IStormClusterState stormClusterState,
Collection<IAutoCredentials> autoCredentials,
StormMetricRegistry metricRegistry) throws IOException,
InvalidTopologyException {
this.metricRegistry = metricRegistry;
this.autoCredentials = autoCredentials;
this.conf = conf;
this.supervisorIfaceSupplier = supervisorIfaceSupplier;
this.localExecutors = new HashSet<>(readWorkerExecutors(stormClusterState, topologyId, assignmentId, port));
this.mqContext = (null != mqContext) ? mqContext : TransportFactory.makeContext(topologyConf);
this.topologyId = topologyId;
this.assignmentId = assignmentId;
this.port = port;
this.workerId = workerId;
this.stateStorage = stateStorage;
this.stormClusterState = stormClusterState;
this.isWorkerActive = new CountDownLatch(1);
this.isTopologyActive = new AtomicBoolean(false);
this.stormComponentToDebug = new AtomicReference<>();
this.executorReceiveQueueMap = mkReceiveQueueMap(topologyConf, localExecutors);
this.localTaskIds = new ArrayList<>();
this.taskToExecutorQueue = new HashMap<>();
this.blobToLastKnownVersion = new ConcurrentHashMap<>();
for (Map.Entry<List<Long>, JCQueue> entry : executorReceiveQueueMap.entrySet()) {
List<Integer> taskIds = StormCommon.executorIdToTasks(entry.getKey());
for (Integer taskId : taskIds) {
this.taskToExecutorQueue.put(taskId, entry.getValue());
}
this.localTaskIds.addAll(taskIds);
}
Collections.sort(localTaskIds);
this.topologyConf = topologyConf;
this.topology = ConfigUtils.readSupervisorTopology(conf, topologyId, AdvancedFSOps.make(conf));
this.systemTopology = StormCommon.systemTopology(topologyConf, topology);
this.taskToComponent = StormCommon.stormTaskInfo(topology, topologyConf);
this.componentToStreamToFields = new HashMap<>();
for (String c : ThriftTopologyUtils.getComponentIds(systemTopology)) {
Map<String, Fields> streamToFields = new HashMap<>();
for (Map.Entry<String, StreamInfo> stream :
ThriftTopologyUtils.getComponentCommon(systemTopology, c).get_streams().entrySet()) {
streamToFields.put(stream.getKey(), new Fields(stream.getValue().get_output_fields()));
}
componentToStreamToFields.put(c, streamToFields);
}
this.componentToSortedTasks = Utils.reverseMap(taskToComponent);
this.componentToSortedTasks.values().forEach(Collections::sort);
this.endpointSocketLock = new ReentrantReadWriteLock();
this.cachedNodeToPortSocket = new AtomicReference<>(new HashMap<>());
this.cachedTaskToNodePort = new AtomicReference<>(new HashMap<>());
this.suicideCallback = Utils.mkSuicideFn();
this.uptime = Utils.makeUptimeComputer();
this.defaultSharedResources = makeDefaultResources();
this.userSharedResources = makeUserResources();
this.loadMapping = new LoadMapping();
this.assignmentVersions = new AtomicReference<>(new HashMap<>());
this.outboundTasks = workerOutboundTasks();
this.trySerializeLocal = topologyConf.containsKey(Config.TOPOLOGY_TESTING_ALWAYS_TRY_SERIALIZE)
&& (Boolean) topologyConf.get(Config.TOPOLOGY_TESTING_ALWAYS_TRY_SERIALIZE);
if (trySerializeLocal) {
LOG.warn("WILL TRY TO SERIALIZE ALL TUPLES (Turn off {} for production", Config.TOPOLOGY_TESTING_ALWAYS_TRY_SERIALIZE);
}
int maxTaskId = getMaxTaskId(componentToSortedTasks);
this.workerTransfer = new WorkerTransfer(this, topologyConf, maxTaskId);
this.bpTracker = new BackPressureTracker(workerId, taskToExecutorQueue);
this.deserializedWorkerHooks = deserializeWorkerHooks();
LOG.info("Registering IConnectionCallbacks for {}:{}", assignmentId, port);
IConnectionCallback cb = new DeserializingConnectionCallback(topologyConf,
getWorkerTopologyContext(),
this::transferLocalBatch);
Supplier<Object> newConnectionResponse = () -> {
BackPressureStatus bpStatus = bpTracker.getCurrStatus();
LOG.info("Sending BackPressure status to new client. BPStatus: {}", bpStatus);
return bpStatus;
};
this.receiver = this.mqContext.bind(topologyId, port, cb, newConnectionResponse);
}
private static double getQueueLoad(JCQueue queue) {
JCQueue.QueueMetrics queueMetrics = queue.getMetrics();
return ((double) queueMetrics.population()) / queueMetrics.capacity();
}
public static boolean isConnectionReady(IConnection connection) {
return !(connection instanceof ConnectionWithStatus)
|| ((ConnectionWithStatus) connection).status() == ConnectionWithStatus.Status.Ready;
}
private static int getMaxTaskId(Map<String, List<Integer>> componentToSortedTasks) {
int maxTaskId = -1;
for (List<Integer> integers : componentToSortedTasks.values()) {
if (!integers.isEmpty()) {
int tempMax = integers.stream().max(Integer::compareTo).get();
if (tempMax > maxTaskId) {
maxTaskId = tempMax;
}
}
}
return maxTaskId;
}
public List<IWorkerHook> getDeserializedWorkerHooks() {
return deserializedWorkerHooks;
}
public Map<String, Object> getConf() {
return conf;
}
public IConnection getReceiver() {
return receiver;
}
public String getTopologyId() {
return topologyId;
}
public int getPort() {
return port;
}
public String getWorkerId() {
return workerId;
}
public IStateStorage getStateStorage() {
return stateStorage;
}
public CountDownLatch getIsWorkerActive() {
return isWorkerActive;
}
public AtomicBoolean getIsTopologyActive() {
return isTopologyActive;
}
public AtomicReference<Map<String, DebugOptions>> getStormComponentToDebug() {
return stormComponentToDebug;
}
public Set<List<Long>> getLocalExecutors() {
return localExecutors;
}
public List<Integer> getLocalTaskIds() {
return localTaskIds;
}
public Map<Integer, JCQueue> getLocalReceiveQueues() {
return localReceiveQueues;
}
public Map<String, Object> getTopologyConf() {
return topologyConf;
}
public StormTopology getTopology() {
return topology;
}
public StormTopology getSystemTopology() {
return systemTopology;
}
public Map<Integer, String> getTaskToComponent() {
return taskToComponent;
}
public Map<String, Map<String, Fields>> getComponentToStreamToFields() {
return componentToStreamToFields;
}
public Map<String, List<Integer>> getComponentToSortedTasks() {
return componentToSortedTasks;
}
public Map<String, Long> getBlobToLastKnownVersion() {
return blobToLastKnownVersion;
}
public AtomicReference<Map<NodeInfo, IConnection>> getCachedNodeToPortSocket() {
return cachedNodeToPortSocket;
}
public Map<List<Long>, JCQueue> getExecutorReceiveQueueMap() {
return executorReceiveQueueMap;
}
public Runnable getSuicideCallback() {
return suicideCallback;
}
public Utils.UptimeComputer getUptime() {
return uptime;
}
public Map<String, Object> getDefaultSharedResources() {
return defaultSharedResources;
}
public Map<String, Object> getUserSharedResources() {
return userSharedResources;
}
public LoadMapping getLoadMapping() {
return loadMapping;
}
public AtomicReference<Map<String, VersionedData<Assignment>>> getAssignmentVersions() {
return assignmentVersions;
}
public StormTimer getUserTimer() {
return userTimer;
}
public SmartThread makeTransferThread() {
return workerTransfer.makeTransferThread();
}
public void refreshConnections() {
Assignment assignment = null;
try {
assignment = getLocalAssignment(stormClusterState, topologyId);
} catch (Exception e) {
LOG.warn("Failed to read assignment. This should only happen when topology is shutting down.", e);
}
Set<NodeInfo> neededConnections = new HashSet<>();
Map<Integer, NodeInfo> newTaskToNodePort = new HashMap<>();
if (null != assignment) {
Map<Integer, NodeInfo> taskToNodePort = StormCommon.taskToNodeport(assignment.get_executor_node_port());
for (Map.Entry<Integer, NodeInfo> taskToNodePortEntry : taskToNodePort.entrySet()) {
Integer task = taskToNodePortEntry.getKey();
if (outboundTasks.contains(task)) {
newTaskToNodePort.put(task, taskToNodePortEntry.getValue());
if (!localTaskIds.contains(task)) {
neededConnections.add(taskToNodePortEntry.getValue());
}
}
}
}
Set<NodeInfo> currentConnections = cachedNodeToPortSocket.get().keySet();
Set<NodeInfo> newConnections = Sets.difference(neededConnections, currentConnections);
Set<NodeInfo> removeConnections = Sets.difference(currentConnections, neededConnections);
Map<String, String> nodeHost = assignment != null ? assignment.get_node_host() : null;
// Add new connections atomically
cachedNodeToPortSocket.getAndUpdate(prev -> {
Map<NodeInfo, IConnection> next = new HashMap<>(prev);
for (NodeInfo nodeInfo : newConnections) {
next.put(nodeInfo,
mqContext.connect(
topologyId,
//nodeHost is not null here, as newConnections is only non-empty if assignment was not null above.
nodeHost.get(nodeInfo.get_node()), // Host
nodeInfo.get_port().iterator().next().intValue(), // Port
workerTransfer.getRemoteBackPressureStatus()));
}
return next;
});
try {
endpointSocketLock.writeLock().lock();
cachedTaskToNodePort.set(newTaskToNodePort);
} finally {
endpointSocketLock.writeLock().unlock();
}
for (NodeInfo nodeInfo : removeConnections) {
cachedNodeToPortSocket.get().get(nodeInfo).close();
}
// Remove old connections atomically
cachedNodeToPortSocket.getAndUpdate(prev -> {
Map<NodeInfo, IConnection> next = new HashMap<>(prev);
removeConnections.forEach(next::remove);
return next;
});
}
public void refreshStormActive() {
refreshStormActive(() -> refreshActiveTimer.schedule(0, this::refreshStormActive));
}
public void refreshStormActive(Runnable callback) {
StormBase base = stormClusterState.stormBase(topologyId, callback);
isTopologyActive.set(
(null != base)
&& (base.get_status() == TopologyStatus.ACTIVE));
if (null != base) {
Map<String, DebugOptions> debugOptionsMap = new HashMap<>(base.get_component_debug());
for (DebugOptions debugOptions : debugOptionsMap.values()) {
if (!debugOptions.is_set_samplingpct()) {
debugOptions.set_samplingpct(10);
}
if (!debugOptions.is_set_enable()) {
debugOptions.set_enable(false);
}
}
stormComponentToDebug.set(debugOptionsMap);
LOG.debug("Events debug options {}", stormComponentToDebug.get());
}
}
public void refreshLoad(List<IRunningExecutor> execs) {
Set<Integer> remoteTasks = Sets.difference(new HashSet<>(outboundTasks), new HashSet<>(localTaskIds));
Map<Integer, Double> localLoad = new HashMap<>();
for (IRunningExecutor exec : execs) {
double receiveLoad = getQueueLoad(exec.getReceiveQueue());
localLoad.put(exec.getExecutorId().get(0).intValue(), receiveLoad);
}
Map<Integer, Load> remoteLoad = new HashMap<>();
cachedNodeToPortSocket.get().values().stream().forEach(conn -> remoteLoad.putAll(conn.getLoad(remoteTasks)));
loadMapping.setLocal(localLoad);
loadMapping.setRemote(remoteLoad);
Long now = System.currentTimeMillis();
if (now > nextLoadUpdate.get()) {
receiver.sendLoadMetrics(localLoad);
nextLoadUpdate.set(now + LOAD_REFRESH_INTERVAL_MS);
}
}
// checks if the tasks which had back pressure are now free again. if so, sends an update to other workers
public void refreshBackPressureStatus() {
LOG.debug("Checking for change in Backpressure status on worker's tasks");
boolean bpSituationChanged = bpTracker.refreshBpTaskList();
if (bpSituationChanged) {
BackPressureStatus bpStatus = bpTracker.getCurrStatus();
receiver.sendBackPressureStatus(bpStatus);
}
}
/**
* we will wait all connections to be ready and then activate the spout/bolt when the worker bootup.
*/
public void activateWorkerWhenAllConnectionsReady() {
int delaySecs = 0;
int recurSecs = 1;
refreshActiveTimer.schedule(delaySecs,
() -> {
if (areAllConnectionsReady()) {
LOG.info("All connections are ready for worker {}:{} with id {}", assignmentId, port, workerId);
isWorkerActive.countDown();
} else {
refreshActiveTimer.schedule(recurSecs, () -> activateWorkerWhenAllConnectionsReady(), false, 0);
}
}
);
}
/* Not a Blocking call. If cannot emit, will add 'tuple' to pendingEmits and return 'false'. 'pendingEmits' can be null */
public boolean tryTransferRemote(AddressedTuple tuple, Queue<AddressedTuple> pendingEmits, ITupleSerializer serializer) {
return workerTransfer.tryTransferRemote(tuple, pendingEmits, serializer);
}
public void flushRemotes() throws InterruptedException {
workerTransfer.flushRemotes();
}
public boolean tryFlushRemotes() {
return workerTransfer.tryFlushRemotes();
}
// Receives msgs from remote workers and feeds them to local executors. If any receiving local executor is under Back Pressure,
// informs other workers about back pressure situation. Runs in the NettyWorker thread.
private void transferLocalBatch(ArrayList<AddressedTuple> tupleBatch) {
for (int i = 0; i < tupleBatch.size(); i++) {
AddressedTuple tuple = tupleBatch.get(i);
JCQueue queue = taskToExecutorQueue.get(tuple.dest);
// 1- try adding to main queue if its overflow is not empty
if (queue.isEmptyOverflow()) {
if (queue.tryPublish(tuple)) {
continue;
}
}
// 2- BP detected (i.e MainQ is full). So try adding to overflow
int currOverflowCount = queue.getOverflowCount();
// get BP state object so only have to lookup once
BackpressureState bpState = bpTracker.getBackpressureState(tuple.dest);
if (bpTracker.recordBackPressure(bpState)) {
receiver.sendBackPressureStatus(bpTracker.getCurrStatus());
bpTracker.setLastOverflowCount(bpState, currOverflowCount);
} else {
if (currOverflowCount - bpTracker.getLastOverflowCount(bpState) > RESEND_BACKPRESSURE_SIZE) {
// resend BP status, in case prev notification was missed or reordered
BackPressureStatus bpStatus = bpTracker.getCurrStatus();
receiver.sendBackPressureStatus(bpStatus);
bpTracker.setLastOverflowCount(bpState, currOverflowCount);
LOG.debug("Re-sent BackPressure Status. OverflowCount = {}, BP Status ID = {}. ", currOverflowCount, bpStatus.id);
}
}
if (!queue.tryPublishToOverflow(tuple)) {
dropMessage(tuple, queue);
}
}
}
private void dropMessage(AddressedTuple tuple, JCQueue queue) {
++dropCount;
queue.recordMsgDrop();
LOG.warn(
"Dropping message as overflow threshold has reached for Q = {}. OverflowCount = {}. Total Drop Count= {}, Dropped Message : {}",
queue.getName(), queue.getOverflowCount(), dropCount, tuple);
}
public void checkSerialize(KryoTupleSerializer serializer, AddressedTuple tuple) {
if (trySerializeLocal) {
serializer.serialize(tuple.getTuple());
}
}
public final WorkerTopologyContext getWorkerTopologyContext() {
try {
String codeDir = ConfigUtils.supervisorStormResourcesPath(ConfigUtils.supervisorStormDistRoot(conf, topologyId));
String pidDir = ConfigUtils.workerPidsRoot(conf, topologyId);
return new WorkerTopologyContext(systemTopology, topologyConf, taskToComponent, componentToSortedTasks,
componentToStreamToFields, topologyId, codeDir, pidDir, port, localTaskIds,
defaultSharedResources,
userSharedResources, cachedTaskToNodePort, assignmentId);
} catch (IOException e) {
throw Utils.wrapInRuntime(e);
}
}
private List<IWorkerHook> deserializeWorkerHooks() {
List<IWorkerHook> myHookList = new ArrayList<>();
if (topology.is_set_worker_hooks()) {
for (ByteBuffer hook : topology.get_worker_hooks()) {
byte[] hookBytes = Utils.toByteArray(hook);
IWorkerHook hookObject = Utils.javaDeserialize(hookBytes, IWorkerHook.class);
myHookList.add(hookObject);
}
}
return myHookList;
}
public void runWorkerStartHooks() {
WorkerTopologyContext workerContext = getWorkerTopologyContext();
for (IWorkerHook hook : getDeserializedWorkerHooks()) {
hook.start(topologyConf, workerContext);
}
}
public void runWorkerShutdownHooks() {
for (IWorkerHook hook : getDeserializedWorkerHooks()) {
hook.shutdown();
}
}
public void closeResources() {
LOG.info("Shutting down default resources");
((ExecutorService) defaultSharedResources.get(WorkerTopologyContext.SHARED_EXECUTOR)).shutdownNow();
LOG.info("Shut down default resources");
}
public boolean areAllConnectionsReady() {
return cachedNodeToPortSocket.get().values()
.stream()
.map(WorkerState::isConnectionReady)
.reduce((left, right) -> left && right)
.orElse(true);
}
public Collection<IAutoCredentials> getAutoCredentials() {
return this.autoCredentials;
}
private List<List<Long>> readWorkerExecutors(IStormClusterState stormClusterState, String topologyId, String assignmentId,
int port) {
LOG.info("Reading assignments");
List<List<Long>> executorsAssignedToThisWorker = new ArrayList<>();
executorsAssignedToThisWorker.add(Constants.SYSTEM_EXECUTOR_ID);
Map<List<Long>, NodeInfo> executorToNodePort =
getLocalAssignment(stormClusterState, topologyId).get_executor_node_port();
for (Map.Entry<List<Long>, NodeInfo> entry : executorToNodePort.entrySet()) {
NodeInfo nodeInfo = entry.getValue();
if (nodeInfo.get_node().equals(assignmentId) && nodeInfo.get_port().iterator().next() == port) {
executorsAssignedToThisWorker.add(entry.getKey());
}
}
return executorsAssignedToThisWorker;
}
private Assignment getLocalAssignment(IStormClusterState stormClusterState, String topologyId) {
try (SupervisorIfaceFactory fac = supervisorIfaceSupplier.get()) {
return fac.getIface().getLocalAssignmentForStorm(topologyId);
} catch (Throwable e) {
//if any error/exception thrown, fetch it from zookeeper
Assignment assignment = stormClusterState.remoteAssignmentInfo(topologyId, null);
if (assignment == null) {
throw new RuntimeException("Failed to read worker assignment."
+ " Supervisor client threw exception, and assignment in Zookeeper was null", e);
}
return assignment;
}
}
private Map<List<Long>, JCQueue> mkReceiveQueueMap(Map<String, Object> topologyConf, Set<List<Long>> executors) {
Integer recvQueueSize = ObjectReader.getInt(topologyConf.get(Config.TOPOLOGY_EXECUTOR_RECEIVE_BUFFER_SIZE));
Integer recvBatchSize = ObjectReader.getInt(topologyConf.get(Config.TOPOLOGY_PRODUCER_BATCH_SIZE));
Integer overflowLimit = ObjectReader.getInt(topologyConf.get(Config.TOPOLOGY_EXECUTOR_OVERFLOW_LIMIT));
if (recvBatchSize > recvQueueSize / 2) {
throw new IllegalArgumentException(Config.TOPOLOGY_PRODUCER_BATCH_SIZE + ":" + recvBatchSize
+ " is greater than half of " + Config.TOPOLOGY_EXECUTOR_RECEIVE_BUFFER_SIZE + ":"
+ recvQueueSize);
}
IWaitStrategy backPressureWaitStrategy = IWaitStrategy.createBackPressureWaitStrategy(topologyConf);
Map<List<Long>, JCQueue> receiveQueueMap = new HashMap<>();
for (List<Long> executor : executors) {
int port = this.getPort();
receiveQueueMap.put(executor, new JCQueue("receive-queue" + executor.toString(),
recvQueueSize, overflowLimit, recvBatchSize, backPressureWaitStrategy,
this.getTopologyId(), Constants.SYSTEM_COMPONENT_ID, -1, this.getPort(), metricRegistry));
}
return receiveQueueMap;
}
private Map<String, Object> makeDefaultResources() {
int threadPoolSize = ObjectReader.getInt(conf.get(Config.TOPOLOGY_WORKER_SHARED_THREAD_POOL_SIZE));
return ImmutableMap.of(WorkerTopologyContext.SHARED_EXECUTOR, Executors.newFixedThreadPool(threadPoolSize));
}
private Map<String, Object> makeUserResources() {
/* TODO: need to invoke a hook provided by the topology, giving it a chance to create user resources.
* this would be part of the initialization hook
* need to separate workertopologycontext into WorkerContext and WorkerUserContext.
* actually just do it via interfaces. just need to make sure to hide setResource from tasks
*/
return new HashMap<>();
}
private StormTimer mkHaltingTimer(String name) {
return new StormTimer(name, (thread, exception) -> {
LOG.error("Error when processing event", exception);
Utils.exitProcess(20, "Error when processing an event");
});
}
/**
* Get worker outbound tasks.
* @return seq of task ids that receive messages from this worker
*/
private Set<Integer> workerOutboundTasks() {
WorkerTopologyContext context = getWorkerTopologyContext();
Set<String> components = new HashSet<>();
for (Integer taskId : localTaskIds) {
for (Map<String, Grouping> value : context.getTargets(context.getComponentId(taskId)).values()) {
components.addAll(value.keySet());
}
}
Set<Integer> outboundTasks = new HashSet<>();
for (Map.Entry<String, List<Integer>> entry : Utils.reverseMap(taskToComponent).entrySet()) {
if (components.contains(entry.getKey())) {
outboundTasks.addAll(entry.getValue());
}
}
return outboundTasks;
}
public Set<Integer> getOutboundTasks() {
return this.outboundTasks;
}
/**
* Check if this worker has remote outbound tasks.
* @return true if this worker has remote outbound tasks; false otherwise.
*/
public boolean hasRemoteOutboundTasks() {
Set<Integer> remoteTasks = Sets.difference(new HashSet<>(outboundTasks), new HashSet<>(localTaskIds));
return !remoteTasks.isEmpty();
}
/**
* If all the tasks are local tasks, the topology has only one worker.
* @return true if this worker is the single worker; false otherwise.
*/
public boolean isSingleWorker() {
Set<Integer> nonLocalTasks = Sets.difference(getTaskToComponent().keySet(),
new HashSet<>(localTaskIds));
return nonLocalTasks.isEmpty();
}
public void haltWorkerTransfer() {
workerTransfer.haltTransferThd();
}
public JCQueue getTransferQueue() {
return workerTransfer.getTransferQueue();
}
public StormMetricRegistry getMetricRegistry() {
return metricRegistry;
}
public interface ILocalTransferCallback {
void transfer(ArrayList<AddressedTuple> tupleBatch);
}
}
| |
/*
Copyright (C) 2013-2015 The Open University
Copyright (C) 2017 Simon Butler
SPDX-FileCopyrightText: 2013-2015 The Open University
SPDX-FileCopyrightText: 2017 Simon Butler
SPDX-License-Identifier: Apache-2.0
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 uk.ac.open.crc.nominal.rules.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.open.crc.nominal.rules.AcronymTypographyRule;
import uk.ac.open.crc.nominal.rules.BodyTypographyRule;
import uk.ac.open.crc.nominal.rules.CaseType;
import uk.ac.open.crc.nominal.rules.CipherMap;
import uk.ac.open.crc.nominal.rules.CipherMapStore;
import uk.ac.open.crc.nominal.rules.CipherRule;
import uk.ac.open.crc.nominal.rules.FirstCharacterTypographyRule;
import uk.ac.open.crc.nominal.rules.IdentifierClassification;
import uk.ac.open.crc.nominal.rules.PhraseRule;
import uk.ac.open.crc.nominal.rules.PluralRule;
import uk.ac.open.crc.nominal.rules.Ruleset;
import uk.ac.open.crc.nominal.rules.RulesetGroup;
import uk.ac.open.crc.nominal.rules.SeparatorRule;
import uk.ac.open.crc.nominal.rules.StandaloneAbbreviationRule;
import uk.ac.open.crc.nominal.rules.TypeAcronymRule;
/**
* Visitor that creates rules defined in .nom files.
*/
public class NominalVisitorImplementation extends NominalBaseVisitor<String> {
private static final Logger LOGGER
= LoggerFactory.getLogger( NominalVisitorImplementation.class );
private final RulesetGroup rulesetGroup;
private Ruleset currentRuleset;
private final HashMap<String,ArrayList<CipherRule>> cipherRules;
private Set<String> phrases;
/**
* Creates a visitor and injects a rule set group instance to be
* populated from the rules in the .nom file being parsed.
*
* @param ruleSetGroup a rule set group
*/
public NominalVisitorImplementation( RulesetGroup ruleSetGroup ) {
super();
this.rulesetGroup = ruleSetGroup;
this.cipherRules = new HashMap<>();
}
@Override
public String visitTypeRule( NominalParser.TypeRuleContext context ) {
String ruleName = context.TYPE_SELECTOR().toString();
IdentifierClassification classification =
IdentifierClassification.getClassificationFor( ruleName );
this.currentRuleset = this.rulesetGroup.get( classification );
if ( this.currentRuleset == null ) {
this.currentRuleset = new Ruleset( classification );
this.rulesetGroup.add( currentRuleset );
}
visitChildren( context ); // now traverse the definitions and collect the rules.
return "";
}
@Override
public String visitMethodRule( NominalParser.MethodRuleContext context ) {
String ruleName = context.METHOD_SELECTOR().toString();
IdentifierClassification classification =
IdentifierClassification.getClassificationFor( ruleName );
this.currentRuleset = this.rulesetGroup.get( classification );
if ( this.currentRuleset == null ) {
this.currentRuleset = new Ruleset( classification );
this.rulesetGroup.add( currentRuleset );
}
visitChildren( context ); // now traverse the definitions and collect the rules.
return "";
}
@Override
public String visitReferenceRule( NominalParser.ReferenceRuleContext context ) {
String ruleName = context.REFERENCE_SELECTOR().toString();
IdentifierClassification classification =
IdentifierClassification.getClassificationFor( ruleName );
this.currentRuleset = this.rulesetGroup.get( classification );
if ( this.currentRuleset == null ) {
this.currentRuleset = new Ruleset( classification );
this.rulesetGroup.add( currentRuleset );
}
visitChildren( context ); // now traverse the definitions and collect the rules.
return "";
}
@Override
public String visitLabelRule( NominalParser.LabelRuleContext context ) {
String ruleName = context.LABEL_SELECTOR().toString();
IdentifierClassification classification =
IdentifierClassification.getClassificationFor( ruleName );
this.currentRuleset = this.rulesetGroup.get( classification );
if ( this.currentRuleset == null ) {
this.currentRuleset = new Ruleset( classification );
this.rulesetGroup.add( currentRuleset );
}
visitChildren( context ); // now traverse the definitions and collect the rules.
return "";
}
@Override
public String visitCipherDefinition( NominalParser.CipherDefinitionContext context ) {
String listIdentifier;
if ( context.ListIdentifier() != null ) {
listIdentifier = context.ListIdentifier().getText();
}
else {
listIdentifier = "default";
}
this.currentRuleset.add( new CipherRule( listIdentifier ) );
return "";
}
// this is defined or not and off by default
// so when defined this allows standalone abbreviations
@Override
public String visitStandaloneAbbreviation(
NominalParser.StandaloneAbbreviationContext context ) {
this.currentRuleset.add( new StandaloneAbbreviationRule( true ) );
// there are no children to visit!
return "";
}
@Override
public String visitTypeAcronym( NominalParser.TypeAcronymContext context ) {
this.currentRuleset.add( new TypeAcronymRule( true ) );
// no children to visit
return "";
}
@Override
public String visitBodyDefinition( NominalParser.BodyDefinitionContext context ) {
String value = context.bodyValue().getText();
CaseType caseType = CaseType.getCaseTypeFor( value );
this.currentRuleset.add(new BodyTypographyRule( caseType ) );
visitChildren( context ); // Is this necessary??
return "";
}
@Override
public String visitFirstCharDefinition(
NominalParser.FirstCharDefinitionContext context ) {
String value = context.firstCharValue().getText();
CaseType caseType = CaseType.getCaseTypeFor( value );
this.currentRuleset.add(new FirstCharacterTypographyRule( caseType ) );
visitChildren( context ); // Is this necessary??
return "";
}
// use this to put the set in place for the phrase rules
// and to create and add phrase rules following
// visit to children
@Override
public String visitTypeContentDefinition(
NominalParser.TypeContentDefinitionContext context ) {
this.phrases = new HashSet<>();
visitChildren( context );
this.currentRuleset.add( new PhraseRule( phrases ) );
this.phrases = null; // unnecessary, but will cause NPE if misused
return "";
}
@Override
public String visitMethodContentDefinition(
NominalParser.MethodContentDefinitionContext context ) {
this.phrases = new HashSet<>();
visitChildren( context );
this.currentRuleset.add( new PhraseRule( phrases ) );
this.phrases = null; // unnecessary, but will cause NPE if misused
return "";
}
@Override
public String visitReferenceContentDefinition( NominalParser.ReferenceContentDefinitionContext context ) {
this.phrases = new HashSet<>();
visitChildren( context );
this.currentRuleset.add( new PhraseRule( phrases ) );
this.phrases = null; // unnecessary, but will cause NPE if misused
return "";
}
@Override
public String visitLabelContentDefinition(
NominalParser.LabelContentDefinitionContext context ) {
this.phrases = new HashSet<>();
visitChildren( context );
this.currentRuleset.add( new PhraseRule( phrases ) );
this.phrases = null; // unnecessary, but will cause NPE if misused
return "";
}
// there may be multiple phrase value definitions
// in a given content declaration
@Override
public String visitPhraseValue( NominalParser.PhraseValueContext context ) {
String specifiedPhrase = context.COMPOUND_PHRASE_NAME().getText();
boolean isDuplicate = ! this.phrases.add( specifiedPhrase );
if ( isDuplicate ) {
LOGGER.warn(
"duplicate declaration of \"{}\" found at line {} column {}",
specifiedPhrase,
context.start.getLine(),
context.start.getCharPositionInLine() );
}
return "";
}
@Override
public String visitSeparatorDefinition(
NominalParser.SeparatorDefinitionContext context ) {
Set<String> separators = new HashSet<>();
context.separatorValue().SEPARATOR_CHARACTER()
.stream().forEach( separatorCharacter -> {
separators.add( separatorCharacter.getText() );
} );
boolean hasMultiplier = context.separatorValue().MULTIPLIER() != null; // as multiplier has only one possible meaning ATM
this.currentRuleset.add( new SeparatorRule( separators, hasMultiplier ) );
visitChildren( context ); // Is this necessary??
return "";
}
@Override
public String visitPluralDefinition( NominalParser.PluralDefinitionContext context ) {
boolean isPlural = Boolean.valueOf( context.BooleanValue().getText() );
this.currentRuleset.add(new PluralRule( isPlural ) );
return "";
}
@Override
public String visitCipherListDefinition( NominalParser.CipherListDefinitionContext context ) {
CipherMapStore store = CipherMapStore.getInstance();
String listIdentifier;
if ( context.DEFAULT() != null ) {
listIdentifier = "default";
}
else {
listIdentifier = context.ListIdentifier().getText();
}
CipherMap map = new CipherMap( listIdentifier );
store.store( listIdentifier, map );
// iterate over each line of the cipher definitions
// and add to the map
context.cipherDeclaration()
.stream()
.forEach( declaration -> {
Set<String> types = new HashSet<>();
declaration.javaTypeName()
.stream()
.forEach( typeName -> {
boolean isDuplicate = ! types.add( typeName.getText() );
if ( isDuplicate ) {
LOGGER.warn(
"Duplicate type declaration in "
+ "cipher list \"{}\" "
+ "at line:{} column:{}",
listIdentifier,
context.start.getLine(),
context.start.getCharPositionInLine() );
}
} );
declaration.CipherName()
.stream()
.forEach( cipherName -> map.put( cipherName.getText(), types ) );
} );
return "";
}
@Override
public String visitAcronymTypographyRule(
NominalParser.AcronymTypographyRuleContext context ) {
CaseType caseType =
CaseType.getCaseTypeFor( context.acronymTypography().getText() );
AcronymTypographyRule rule = new AcronymTypographyRule( caseType );
this.rulesetGroup.add( rule );
return "";
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.ValidateActions;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.NamedWriteable;
import org.elasticsearch.common.xcontent.ToXContentFragment;
import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.Rewriteable;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.bucket.histogram.AutoDateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
/**
* A factory that knows how to create an {@link PipelineAggregator} of a
* specific type.
*/
public abstract class PipelineAggregationBuilder
implements
NamedWriteable,
BaseAggregationBuilder,
ToXContentFragment,
Rewriteable<PipelineAggregationBuilder> {
protected final String name;
protected final String[] bucketsPaths;
/**
* Constructs a new pipeline aggregator factory.
*
* @param name
* The aggregation name
*/
protected PipelineAggregationBuilder(String name, String[] bucketsPaths) {
if (name == null) {
throw new IllegalArgumentException("[name] must not be null: [" + name + "]");
}
if (bucketsPaths == null) {
throw new IllegalArgumentException("[bucketsPaths] must not be null: [" + name + "]");
}
this.name = name;
this.bucketsPaths = bucketsPaths;
}
/** Return this aggregation's name. */
public String getName() {
return name;
}
/** Return the consumed buckets paths. */
public final String[] getBucketsPaths() {
return bucketsPaths;
}
/**
* Makes sure this builder is properly configured.
*/
protected abstract void validate(ValidationContext context);
public abstract static class ValidationContext {
/**
* Build the context for the root of the aggregation tree.
*/
public static ValidationContext forTreeRoot(Collection<AggregationBuilder> siblingAggregations,
Collection<PipelineAggregationBuilder> siblingPipelineAggregations,
ActionRequestValidationException validationFailuresSoFar) {
return new ForTreeRoot(siblingAggregations, siblingPipelineAggregations, validationFailuresSoFar);
}
/**
* Build the context for a node inside the aggregation tree.
*/
public static ValidationContext forInsideTree(AggregationBuilder parent,
ActionRequestValidationException validationFailuresSoFar) {
return new ForInsideTree(parent, validationFailuresSoFar);
}
private ActionRequestValidationException e;
private ValidationContext(ActionRequestValidationException validationFailuresSoFar) {
this.e = validationFailuresSoFar;
}
private static class ForTreeRoot extends ValidationContext {
private final Collection<AggregationBuilder> siblingAggregations;
private final Collection<PipelineAggregationBuilder> siblingPipelineAggregations;
ForTreeRoot(Collection<AggregationBuilder> siblingAggregations,
Collection<PipelineAggregationBuilder> siblingPipelineAggregations,
ActionRequestValidationException validationFailuresSoFar) {
super(validationFailuresSoFar);
this.siblingAggregations = Objects.requireNonNull(siblingAggregations);
this.siblingPipelineAggregations = Objects.requireNonNull(siblingPipelineAggregations);
}
@Override
public Collection<AggregationBuilder> getSiblingAggregations() {
return siblingAggregations;
}
@Override
public Collection<PipelineAggregationBuilder> getSiblingPipelineAggregations() {
return siblingPipelineAggregations;
}
@Override
public void validateHasParent(String type, String name) {
addValidationError(type + " aggregation [" + name + "] must be declared inside of another aggregation");
}
@Override
public void validateParentAggSequentiallyOrdered(String type, String name) {
addValidationError(type + " aggregation [" + name
+ "] must have a histogram, date_histogram or auto_date_histogram as parent but doesn't have a parent");
}
}
private static class ForInsideTree extends ValidationContext {
private final AggregationBuilder parent;
ForInsideTree(AggregationBuilder parent, ActionRequestValidationException validationFailuresSoFar) {
super(validationFailuresSoFar);
this.parent = Objects.requireNonNull(parent);
}
@Override
public Collection<AggregationBuilder> getSiblingAggregations() {
return parent.getSubAggregations();
}
@Override
public Collection<PipelineAggregationBuilder> getSiblingPipelineAggregations() {
return parent.getPipelineAggregations();
}
@Override
public void validateHasParent(String type, String name) {
// There is a parent inside the tree.
}
@Override
public void validateParentAggSequentiallyOrdered(String type, String name) {
if (parent instanceof HistogramAggregationBuilder) {
HistogramAggregationBuilder histoParent = (HistogramAggregationBuilder) parent;
if (histoParent.minDocCount() != 0) {
addValidationError(
"parent histogram of " + type + " aggregation [" + name + "] must have min_doc_count of 0");
}
} else if (parent instanceof DateHistogramAggregationBuilder) {
DateHistogramAggregationBuilder histoParent = (DateHistogramAggregationBuilder) parent;
if (histoParent.minDocCount() != 0) {
addValidationError(
"parent histogram of " + type + " aggregation [" + name + "] must have min_doc_count of 0");
}
} else if (parent instanceof AutoDateHistogramAggregationBuilder) {
// Nothing to check
} else {
addValidationError(
type + " aggregation [" + name + "] must have a histogram, date_histogram or auto_date_histogram as parent");
}
}
}
/**
* Aggregations that are siblings to the aggregation being validated.
*/
public abstract Collection<AggregationBuilder> getSiblingAggregations();
/**
* Pipeline aggregations that are siblings to the aggregation being validated.
*/
public abstract Collection<PipelineAggregationBuilder> getSiblingPipelineAggregations();
/**
* Add a validation error to this context. All validation errors
* are accumulated in a list and, if there are any, the request
* is not executed and the entire list is returned as the error
* response.
*/
public void addValidationError(String error) {
e = ValidateActions.addValidationError(error, e);
}
/**
* Add a validation error about the {@code buckets_path}.
*/
public void addBucketPathValidationError(String error) {
addValidationError(PipelineAggregator.Parser.BUCKETS_PATH.getPreferredName() + ' ' + error);
}
/**
* Validates that there <strong>is</strong> a parent aggregation.
*/
public abstract void validateHasParent(String type, String name);
/**
* Validates that the parent is sequentially ordered.
*/
public abstract void validateParentAggSequentiallyOrdered(String type, String name);
/**
* The validation exception, if there is one. It'll be {@code null}
* if the context wasn't provided with any exception on creation
* and none were added.
*/
public ActionRequestValidationException getValidationException() {
return e;
}
}
/**
* Creates the pipeline aggregator
*
* @return The created aggregator
*/
protected abstract PipelineAggregator create();
/** Associate metadata with this {@link PipelineAggregationBuilder}. */
@Override
public abstract PipelineAggregationBuilder setMetadata(Map<String, Object> metadata);
@Override
public PipelineAggregationBuilder subAggregations(Builder subFactories) {
throw new IllegalArgumentException("Aggregation [" + name + "] cannot define sub-aggregations");
}
@Override
public String toString() {
return Strings.toString(this, true, true);
}
/**
* {@inheritDoc}
* <p>
* The default implementation return the same instance. It should be
* overridden by aggregations that must load data before they can be run,
* particularly if that load must by asynchronous.
*/
@Override
public PipelineAggregationBuilder rewrite(QueryRewriteContext context) throws IOException {
return this;
}
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.env.ut;
import com.google.common.collect.Lists;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.RunManager;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionEnvironmentBuilder;
import com.intellij.execution.testframework.AbstractTestProxy;
import com.intellij.execution.testframework.Filter;
import com.intellij.execution.testframework.sm.runner.SMTestProxy;
import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView;
import com.intellij.execution.testframework.sm.runner.ui.TestResultsViewer;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.testFramework.EdtTestUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.XDebuggerTestUtil;
import com.jetbrains.env.PyExecutionFixtureTestTask;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.sdk.PythonEnvUtil;
import com.jetbrains.python.sdk.flavors.JythonSdkFlavor;
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor;
import com.jetbrains.python.testing.AbstractPythonLegacyTestRunConfiguration;
import com.jetbrains.python.testing.PythonTestConfigurationType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* TODO: Move {@link com.jetbrains.python.gherkin.PyBDDEnvTestTask} to the new API and git rid of this class
*/
/**
* Tasks to run unit test configurations.
* You should extend it either implementing {@link #after()} and {@link #before()} or implement {@link #runTestOn(String)}
* yourself and use {@link #runConfiguration(com.intellij.execution.configurations.ConfigurationFactory, String, com.intellij.openapi.project.Project)}
* or {@link #runConfiguration(com.intellij.execution.RunnerAndConfigurationSettings, com.intellij.execution.configurations.RunConfiguration)} .
* Use {@link #myDescriptor} and {@link #myConsoleView} to check output
*
* @author traff
* @deprecated Consider using {@link com.jetbrains.env.PyProcessWithConsoleTestTask} instead. It has runner for python tests.
* This class is here only because {@link com.jetbrains.python.gherkin.PyBDDEnvTestTask} uses it.
*/
@Deprecated
public abstract class PyUnitTestTask extends PyExecutionFixtureTestTask {
protected ProcessHandler myProcessHandler;
private boolean shouldPrintOutput = false;
/**
* Test root node
*/
protected SMTestProxy.SMRootTestProxy myTestProxy;
/**
* Output test console
*/
protected SMTRunnerConsoleView myConsoleView;
/**
* Test run descriptor
*/
protected RunContentDescriptor myDescriptor;
private StringBuilder myOutput;
private boolean mySetUp = false;
protected PyUnitTestTask(@Nullable final String relativeTestDataPath, String scriptName, String scriptParameters) {
super(relativeTestDataPath);
setScriptName(scriptName);
setScriptParameters(scriptParameters);
}
private static void deletePycFiles(@NotNull final File directory) {
FileUtil.processFilesRecursively(directory, file -> {
if (file.getParentFile().getName().equals(PyNames.PYCACHE) ||
FileUtilRt.extensionEquals(file.getName(), "pyc") ||
FileUtilRt.extensionEquals(file.getName(), "pyo") ||
file.getName().endsWith("$py.class")) {
FileUtil.delete(file);
}
return true;
});
}
@Override
public void setUp(final String testName) throws Exception {
if (myFixture == null) {
super.setUp(testName);
mySetUp = true;
}
deletePycFiles(new File(myFixture.getTempDirPath()));
}
@NotNull
protected String output() {
return myOutput.toString();
}
@Override
public void tearDown() {
EdtTestUtil.runInEdtAndWait(() -> {
if (mySetUp) {
if (myConsoleView != null) {
Disposer.dispose(myConsoleView);
myConsoleView = null;
}
if (myDescriptor != null) {
Disposer.dispose(myDescriptor);
myDescriptor = null;
}
super.tearDown();
mySetUp = false;
}
});
}
@Override
public void runTestOn(String sdkHome) throws Exception {
final Project project = getProject();
final ConfigurationFactory factory = PythonTestConfigurationType.getInstance().LEGACY_UNITTEST_FACTORY;
runConfiguration(factory, sdkHome, project);
}
protected void runConfiguration(ConfigurationFactory factory, String sdkHome, final Project project) throws Exception {
final RunnerAndConfigurationSettings settings =
RunManager.getInstance(project).createRunConfiguration("test", factory);
AbstractPythonLegacyTestRunConfiguration config = (AbstractPythonLegacyTestRunConfiguration)settings.getConfiguration();
config.setSdkHome(sdkHome);
config.setScriptName(getScriptName());
config.setWorkingDirectory(myFixture.getTempDirPath());
PythonSdkFlavor sdk = PythonSdkFlavor.getFlavor(sdkHome);
if (sdk instanceof JythonSdkFlavor) {
config.setInterpreterOptions(JythonSdkFlavor.getPythonPathCmdLineArgument(Lists.newArrayList(myFixture.getTempDirPath())));
}
else {
PythonEnvUtil.addToPythonPath(config.getEnvs(), myFixture.getTempDirPath());
}
configure(config);
new WriteAction() {
@Override
protected void run(@NotNull Result result) {
RunManager runManager = RunManager.getInstance(project);
runManager.addConfiguration(settings);
runManager.setSelectedConfiguration(settings);
Assert.assertSame(settings, runManager.getSelectedConfiguration());
}
}.execute();
runConfiguration(settings, config);
}
/**
* Run configuration.
*
* @param settings settings (if have any, null otherwise)
* @param config configuration to run
* @throws Exception
*/
protected void runConfiguration(@Nullable final RunnerAndConfigurationSettings settings,
@NotNull final RunConfiguration config) throws Exception {
final ExecutionEnvironment environment;
if (settings == null) {
environment = ExecutionEnvironmentBuilder.create(DefaultRunExecutor.getRunExecutorInstance(), config).build();
}
else {
environment = ExecutionEnvironmentBuilder.create(DefaultRunExecutor.getRunExecutorInstance(), settings).build();
}
//noinspection ConstantConditions
Assert.assertTrue(environment.getRunner().canRun(DefaultRunExecutor.EXECUTOR_ID, config));
before();
final com.intellij.util.concurrency.Semaphore s = new com.intellij.util.concurrency.Semaphore();
s.down();
myOutput = new StringBuilder();
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
try {
TransactionGuard.submitTransaction(config.getProject(), () -> {
try {
environment.getRunner().execute(environment, descriptor -> {
myDescriptor = descriptor;
myProcessHandler = myDescriptor.getProcessHandler();
myProcessHandler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) {
myOutput.append(event.getText());
}
});
myConsoleView = (SMTRunnerConsoleView)descriptor.getExecutionConsole();
myTestProxy = myConsoleView.getResultsViewer().getTestsRootNode();
myConsoleView.getResultsViewer().addEventsListener(new TestResultsViewer.SMEventsAdapter() {
@Override
public void onTestingFinished(TestResultsViewer sender) {
s.up();
}
});
});
}
catch (final ExecutionException e) {
throw new ProcessCanceledException(e);
}
});
}
catch (Exception e) {
throw new RuntimeException(e);
}
});
Assert.assertTrue(s.waitFor(getTestTimeout()));
XDebuggerTestUtil.waitForSwing();
assertFinished();
Assert.assertTrue(output(), allTestsCount() > 0);
after();
disposeProcess(myProcessHandler);
}
protected int getTestTimeout() {
return 60000;
}
protected void configure(AbstractPythonLegacyTestRunConfiguration config) {
}
/**
* Searches for test by its name recursevly in test, passed as arumuent.
*
* @param testName test name to find
* @param test root test
* @return test or null if not found
*/
@Nullable
private static AbstractTestProxy findTestByName(@NotNull final String testName, @NotNull final AbstractTestProxy test) {
if (test.getName().equals(testName)) {
return test;
}
for (final AbstractTestProxy testProxy : test.getChildren()) {
final AbstractTestProxy result = findTestByName(testName, testProxy);
if (result != null) {
return result;
}
}
return null;
}
public void assertFinished() {
Assert.assertTrue("State is " + myTestProxy.getMagnitudeInfo().getTitle() + "\n" + output(),
myTestProxy.wasLaunched() && !myTestProxy.wasTerminated());
}
public int allTestsCount() {
return myTestProxy.collectChildren(NOT_SUIT).size();
}
/**
* Gets highlighted information from test console. Some parts of output (like file links) may be highlighted, and you need to check them.
*
* @return pair of [[ranges], [texts]] where range is [from,to] in doc. for each region, and "text" is text extracted from this region.
* For example assume that in document "spam eggs ham" words "ham" and "spam" are highlighted.
* You should have 2 ranges (0, 4) and (10, 13) and 2 strings (spam and ham)
*/
@NotNull
public final Pair<List<Pair<Integer, Integer>>, List<String>> getHighlightedStrings() {
final ConsoleView console = myConsoleView.getConsole();
assert console instanceof ConsoleViewImpl : "Console has no editor!";
final ConsoleViewImpl consoleView = (ConsoleViewImpl)console;
final Editor editor = consoleView.getEditor();
final List<String> resultStrings = new ArrayList<>();
final List<Pair<Integer, Integer>> resultRanges = new ArrayList<>();
UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
/**
* To fetch data from console we need to flush it first.
* It works locally, but does not work on TC (reasons are not clear yet and need to be investigated).
* So, we flush it explicitly to make test run on TC.
*/
consoleView.flushDeferredText();
for (final RangeHighlighter highlighter : editor.getMarkupModel().getAllHighlighters()) {
if (highlighter instanceof RangeHighlighterEx) {
final int start = ((RangeHighlighterEx)highlighter).getAffectedAreaStartOffset();
final int end = ((RangeHighlighterEx)highlighter).getAffectedAreaEndOffset();
resultRanges.add(Pair.create(start, end));
resultStrings.add(editor.getDocument().getText().substring(start, end));
}
}
});
final String message = String.format("Following output is searched for hightlighed strings: %s \n", editor.getDocument().getText());
Logger.getInstance(getClass()).warn(message);
return Pair.create(resultRanges, resultStrings);
}
public static final Filter<SMTestProxy> NOT_SUIT = new Filter<SMTestProxy>() {
@Override
public boolean shouldAccept(SMTestProxy test) {
return !test.isSuite();
}
};
}
| |
/**
* Copyright 2015 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.atlasdb.stream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.util.Map;
import javax.annotation.Nullable;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import com.google.common.io.CountingInputStream;
import com.google.protobuf.ByteString;
import com.palantir.atlasdb.encoding.PtBytes;
import com.palantir.atlasdb.protos.generated.StreamPersistence.Status;
import com.palantir.atlasdb.protos.generated.StreamPersistence.StreamMetadata;
import com.palantir.atlasdb.transaction.api.Transaction;
import com.palantir.atlasdb.transaction.api.TransactionManager;
import com.palantir.atlasdb.transaction.api.TransactionTask;
import com.palantir.atlasdb.transaction.impl.TxTask;
import com.palantir.common.base.Throwables;
import com.palantir.util.Pair;
import com.palantir.util.crypto.Sha256Hash;
public abstract class AbstractPersistentStreamStore extends AbstractGenericStreamStore<Long> implements PersistentStreamStore {
protected AbstractPersistentStreamStore(TransactionManager txManager) {
super(txManager);
}
private final void storeMetadataAndIndex(final long streamId, final StreamMetadata metadata){
Preconditions.checkNotNull(txnMgr);
txnMgr.runTaskThrowOnConflict(new TxTask() {
@Override
public Void execute(Transaction t) {
putMetadataAndHashIndexTask(t, streamId, metadata);
return null;
}
});
}
private Long lookupStreamIdByHash(Transaction t, Sha256Hash hash) {
Map<Sha256Hash, Long> hashToId = lookupStreamIdsByHash(t, Sets.newHashSet(hash));
if (hashToId.isEmpty()) {
return null;
}
return Iterables.getOnlyElement(hashToId.entrySet()).getValue();
}
@Override
public final long getByHashOrStoreStreamAndMarkAsUsed(Transaction t, Sha256Hash hash, InputStream stream, byte[] reference) {
Long streamId = lookupStreamIdByHash(t, hash);
if (streamId != null) {
markStreamsAsUsed(t, ImmutableMap.<Long, byte[]>builder().put(streamId, reference).build());
return streamId;
}
Pair<Long, Sha256Hash> pair = storeStream(stream);
Preconditions.checkArgument(hash.equals(pair.rhSide), "passed hash: %s does not equal stream hash: %s", hash, pair.rhSide);
markStreamsAsUsedInternal(t, ImmutableMap.<Long, byte[]>builder().put(pair.lhSide, reference).build());
return pair.lhSide;
}
@Override
public void unmarkStreamAsUsed(Transaction t, long streamId, byte[] reference) {
unmarkStreamsAsUsed(t, ImmutableMap.<Long, byte[]>builder().put(streamId, reference).build());
}
@Override
public void markStreamAsUsed(Transaction t, long streamId, byte[] reference) {
markStreamsAsUsed(t, ImmutableMap.<Long, byte[]>builder().put(streamId, reference).build());
}
@Override
public void markStreamsAsUsed(Transaction t, Map<Long, byte[]> streamIdsToReference) {
touchMetadataWhileMarkingUsedForConflicts(t, streamIdsToReference.keySet());
markStreamsAsUsedInternal(t, streamIdsToReference);
}
private long storeEmptyMetadata() {
Preconditions.checkNotNull(txnMgr);
return txnMgr.runTaskThrowOnConflict(new TransactionTask<Long, RuntimeException>() {
@Override
public Long execute(Transaction t) {
putMetadataAndHashIndexTask(t, t.getTimestamp(), getEmptyMetadata());
return t.getTimestamp();
}
});
}
@Override
public final Pair<Long, Sha256Hash> storeStream(InputStream stream) {
// Store empty metadata before doing anything
long id = storeEmptyMetadata();
StreamMetadata metadata = storeBlocksAndGetFinalMetadata(null, id, stream);
storeMetadataAndIndex(id, metadata);
return Pair.create(id, new Sha256Hash(metadata.getHash().toByteArray()));
}
@Override
public Map<Long, Sha256Hash> storeStreams(final Transaction t, final Map<Long, InputStream> streams) {
if (streams.isEmpty()) {
return ImmutableMap.of();
}
Map<Long, StreamMetadata> idsToEmptyMetadata = Maps.transformValues(streams, Functions.constant(getEmptyMetadata()));
putMetadataAndHashIndexTask(t, idsToEmptyMetadata);
Map<Long, StreamMetadata> idsToMetadata = Maps.transformEntries(streams, new Maps.EntryTransformer<Long, InputStream, StreamMetadata>() {
@Override
public StreamMetadata transformEntry(Long id, InputStream stream) {
return storeBlocksAndGetFinalMetadata(t, id, stream);
}
});
putMetadataAndHashIndexTask(t, idsToMetadata);
Map<Long, Sha256Hash> hashes = Maps.transformValues(idsToMetadata, new Function<StreamMetadata, Sha256Hash>() {
@Override
public Sha256Hash apply(StreamMetadata metadata) {
return new Sha256Hash(metadata.getHash().toByteArray());
}
});
return hashes;
}
protected final StreamMetadata storeBlocksAndGetFinalMetadata(@Nullable Transaction t, long id, InputStream stream) {
// Set up for finding hash and length
MessageDigest digest = Sha256Hash.getMessageDigest();
stream = new DigestInputStream(stream, digest);
CountingInputStream countingStream = new CountingInputStream(stream);
// Try to store the bytes to the stream and get length
try {
storeBlocksFromStream(t, id, countingStream);
} catch (IOException e) {
long length = countingStream.getCount();
StreamMetadata metadata = StreamMetadata.newBuilder()
.setStatus(Status.FAILED)
.setLength(length)
.setHash(com.google.protobuf.ByteString.EMPTY)
.build();
storeMetadataAndIndex(id, metadata);
log.error("Could not store stream " + id + ". Failed after " + length + " bytes.", e);
throw Throwables.rewrapAndThrowUncheckedException("Failed to store stream.", e);
}
// Get hash and length
ByteString hashByteString = ByteString.copyFrom(digest.digest());
long length = countingStream.getCount();
// Return the final metadata.
StreamMetadata metadata = StreamMetadata.newBuilder()
.setStatus(Status.STORED)
.setLength(length)
.setHash(hashByteString)
.build();
return metadata;
}
private void storeBlocksFromStream(@Nullable Transaction t, long id, InputStream stream) throws IOException {
// We need to use a buffered stream here because we assume each read will fill the whole buffer.
stream = new BufferedInputStream(stream);
byte[] bytesToStore = new byte[BLOCK_SIZE_IN_BYTES];
long blockNumber = 0;
while (true) {
int length = ByteStreams.read(stream, bytesToStore, 0, BLOCK_SIZE_IN_BYTES);
// Store only relevant data if it only filled a partial block
if (length == 0) {
break;
}
if (length < BLOCK_SIZE_IN_BYTES) {
// This is the last block.
storeBlockWithNonNullTransaction(t, id, blockNumber, PtBytes.head(bytesToStore, length));
break;
} else {
// Store a full block.
storeBlockWithNonNullTransaction(t, id, blockNumber, bytesToStore);
}
blockNumber++;
}
}
protected void storeBlockWithNonNullTransaction(@Nullable Transaction t, final long id, final long blockNumber, final byte[] bytesToStore) {
if (t != null) {
storeBlock(t, id, blockNumber, bytesToStore);
} else {
Preconditions.checkNotNull(txnMgr);
txnMgr.runTaskThrowOnConflict(
new TransactionTask<Void, RuntimeException>() {
@Override
public Void execute(Transaction t) throws RuntimeException {
storeBlock(t, id, blockNumber, bytesToStore);
return null;
}
});
}
}
private void putMetadataAndHashIndexTask(Transaction t, Long streamId, StreamMetadata metadata) {
putMetadataAndHashIndexTask(t, ImmutableMap.<Long, StreamMetadata>builder().put(streamId, metadata).build());
}
protected abstract void storeBlock(Transaction t, long id, long blockNumber, byte[] block);
protected abstract void touchMetadataWhileMarkingUsedForConflicts(Transaction t, Iterable<Long> ids) throws StreamCleanedException;
protected abstract void markStreamsAsUsedInternal(Transaction t, final Map<Long, byte[]> streamIdsToReference);
protected abstract void putMetadataAndHashIndexTask(Transaction t, Map<Long, StreamMetadata> streamIdsToMetadata);
}
| |
/**
* Sencha GXT 4.0.1 - Sencha for GWT
* Copyright (c) 2006-2016, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Evaluation/Trial License
* ================================================================================
* This version of Sencha GXT is licensed commercially for a limited period for
* evaluation purposes only. Production use or use beyond the applicable evaluation
* period is prohibited under this license.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.chart;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.Editor.Path;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.chart.client.chart.Chart;
import com.sencha.gxt.chart.client.chart.Chart.Position;
import com.sencha.gxt.chart.client.chart.Legend;
import com.sencha.gxt.chart.client.chart.axis.CategoryAxis;
import com.sencha.gxt.chart.client.chart.axis.NumericAxis;
import com.sencha.gxt.chart.client.chart.series.AreaSeries;
import com.sencha.gxt.chart.client.chart.series.SeriesRenderer;
import com.sencha.gxt.chart.client.draw.RGB;
import com.sencha.gxt.chart.client.draw.path.MoveTo;
import com.sencha.gxt.chart.client.draw.path.PathSprite;
import com.sencha.gxt.chart.client.draw.sprite.Sprite;
import com.sencha.gxt.chart.client.draw.sprite.TextSprite;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.PropertyAccess;
import com.sencha.gxt.examples.resources.client.TestData;
import com.sencha.gxt.examples.resources.client.model.Data;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.button.ToggleButton;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;
@Detail(
name = "Area Chart",
category = "Charts",
icon = "areachart",
classes = Data.class,
minHeight = AreaExample.MIN_HEIGHT,
minWidth = AreaExample.MIN_WIDTH
)
public class AreaExample implements IsWidget, EntryPoint {
public interface DataPropertyAccess extends PropertyAccess<Data> {
ValueProvider<Data, Double> data1();
ValueProvider<Data, Double> data2();
ValueProvider<Data, Double> data3();
ValueProvider<Data, Double> data4();
ValueProvider<Data, Double> data5();
ValueProvider<Data, Double> data6();
ValueProvider<Data, Double> data7();
ValueProvider<Data, String> name();
@Path("id")
ModelKeyProvider<Data> nameKey();
}
protected static final int MIN_HEIGHT = 480;
protected static final int MIN_WIDTH = 640;
private static final DataPropertyAccess dataAccess = GWT.create(DataPropertyAccess.class);
private ContentPanel panel;
private Chart<Data> chart;
@Override
public Widget asWidget() {
if (panel == null) {
final ListStore<Data> store = new ListStore<Data>(dataAccess.nameKey());
store.addAll(TestData.getData(12, 20, 100));
TextSprite titleHits = new TextSprite("Number of Hits");
titleHits.setFontSize(18);
TextSprite titleMonthYear = new TextSprite("Month of the Year");
titleMonthYear.setFontSize(18);
PathSprite gridConfig = new PathSprite();
gridConfig.setStroke(new RGB("#bbb"));
gridConfig.setFill(new RGB("#ddd"));
gridConfig.setZIndex(1);
gridConfig.setStrokeWidth(1);
NumericAxis<Data> axis = new NumericAxis<Data>();
axis.setPosition(Position.LEFT);
axis.addField(dataAccess.data1());
axis.addField(dataAccess.data2());
axis.addField(dataAccess.data3());
axis.addField(dataAccess.data4());
axis.addField(dataAccess.data5());
axis.addField(dataAccess.data6());
axis.addField(dataAccess.data7());
axis.setGridOddConfig(gridConfig);
axis.setDisplayGrid(true);
axis.setTitleConfig(titleHits);
axis.setMinorTickSteps(2);
TextSprite labelConfig = new TextSprite();
labelConfig.setRotation(315);
CategoryAxis<Data, String> catAxis = new CategoryAxis<Data, String>();
catAxis.setPosition(Position.BOTTOM);
catAxis.setField(dataAccess.name());
catAxis.setTitleConfig(titleMonthYear);
catAxis.setDisplayGrid(true);
catAxis.setLabelConfig(labelConfig);
catAxis.setLabelPadding(-10);
catAxis.setMinorTickSteps(5);
catAxis.setLabelTolerance(20);
final PathSprite highlightLine = new PathSprite();
highlightLine.setHidden(true);
highlightLine.addCommand(new MoveTo(0, 0));
highlightLine.setZIndex(1000);
highlightLine.setStrokeWidth(5);
highlightLine.setStroke(new RGB("#444"));
highlightLine.setOpacity(0.3);
final AreaSeries<Data> series = new AreaSeries<Data>();
series.setHighlighting(true);
series.setYAxisPosition(Position.LEFT);
series.addYField(dataAccess.data1());
series.addYField(dataAccess.data2());
series.addYField(dataAccess.data3());
series.addYField(dataAccess.data4());
series.addYField(dataAccess.data5());
series.addYField(dataAccess.data6());
series.addYField(dataAccess.data7());
series.addColor(new RGB(148, 174, 10));
series.addColor(new RGB(17, 95, 166));
series.addColor(new RGB(166, 17, 32));
series.addColor(new RGB(255, 136, 9));
series.addColor(new RGB(255, 209, 62));
series.addColor(new RGB(166, 17, 135));
series.addColor(new RGB(36, 173, 154));
series.setHighlightLineConfig(highlightLine);
series.setRenderer(new SeriesRenderer<Data>() {
@Override
public void spriteRenderer(Sprite sprite, int index, ListStore<Data> store) {
sprite.setOpacity(0.93);
sprite.redraw();
}
});
Legend<Data> legend = new Legend<Data>();
legend.setItemHighlighting(true);
legend.setItemHiding(true);
legend.getBorderConfig().setStrokeWidth(0);
chart = new Chart<Data>();
chart.setStore(store);
// Allow room for rotated labels
chart.setDefaultInsets(30);
chart.addAxis(axis);
chart.addAxis(catAxis);
chart.addSeries(series);
chart.setLegend(legend);
TextButton regenerate = new TextButton("Reload Data");
regenerate.addSelectHandler(new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
store.clear();
store.addAll(TestData.getData(12, 20, 100));
chart.redrawChart();
series.setHighlightLineConfig(highlightLine);
}
});
ToggleButton animation = new ToggleButton("Animate");
animation.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
chart.setAnimated(event.getValue());
}
});
animation.setValue(true, true);
ToolBar toolBar = new ToolBar();
toolBar.add(regenerate);
toolBar.add(animation);
toolBar.setLayoutData(new VerticalLayoutData(1, -1));
VerticalLayoutContainer layout = new VerticalLayoutContainer();
layout.add(toolBar, new VerticalLayoutData(1, -1));
layout.add(chart, new VerticalLayoutData(1, 1));
panel = new ContentPanel();
panel.setHeading("Area Chart");
panel.add(layout);
}
return panel;
}
@Override
public void onModuleLoad() {
new ExampleContainer(this)
.setMinHeight(MIN_HEIGHT)
.setMinWidth(MIN_WIDTH)
.doStandalone();
}
}
| |
/*
* Autopsy Forensic Browser
*
* Copyright 2011-2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> 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.sleuthkit.autopsy.timeline;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.util.List;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.scene.Scene;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import static javax.swing.SwingUtilities.isDescendingFrom;
import org.controlsfx.control.Notifications;
import org.joda.time.Interval;
import org.joda.time.format.DateTimeFormatter;
import org.openide.explorer.ExplorerManager;
import static org.openide.explorer.ExplorerUtils.createLookup;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import org.openide.windows.Mode;
import org.openide.windows.RetainLocation;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.actions.AddBookmarkTagAction;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataContent;
import org.sleuthkit.autopsy.corecomponents.DataContentPanel;
import org.sleuthkit.autopsy.corecomponents.DataResultPanel;
import org.sleuthkit.autopsy.corecomponents.TableFilterNode;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.ThreadConfined;
import org.sleuthkit.autopsy.timeline.actions.Back;
import org.sleuthkit.autopsy.timeline.actions.Forward;
import org.sleuthkit.autopsy.timeline.explorernodes.EventNode;
import org.sleuthkit.autopsy.timeline.explorernodes.EventRootNode;
import org.sleuthkit.autopsy.timeline.ui.HistoryToolBar;
import org.sleuthkit.autopsy.timeline.ui.StatusBar;
import org.sleuthkit.autopsy.timeline.ui.TimeZonePanel;
import org.sleuthkit.autopsy.timeline.ui.ViewFrame;
import org.sleuthkit.autopsy.timeline.ui.detailview.tree.EventsTree;
import org.sleuthkit.autopsy.timeline.ui.filtering.FilterSetPanel;
import org.sleuthkit.autopsy.timeline.zooming.ZoomSettingsPane;
import org.sleuthkit.datamodel.TskCoreException;
/**
* TopComponent for the Timeline feature.
*/
@TopComponent.Description(
preferredID = "TimeLineTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", //use this to put icon in window title area,
persistenceType = TopComponent.PERSISTENCE_NEVER)
@TopComponent.Registration(mode = "timeline", openAtStartup = false)
@RetainLocation("timeline")
public final class TimeLineTopComponent extends TopComponent implements ExplorerManager.Provider {
private static final Logger LOGGER = Logger.getLogger(TimeLineTopComponent.class.getName());
@ThreadConfined(type = ThreadConfined.ThreadType.AWT)
private final DataContentExplorerPanel contentViewerPanel;
@ThreadConfined(type = ThreadConfined.ThreadType.AWT)
private final DataResultPanel dataResultPanel;
@ThreadConfined(type = ThreadConfined.ThreadType.AWT)
private final ExplorerManager explorerManager = new ExplorerManager();
private final TimeLineController controller;
/** Lookup that will be exposed through the (Global Actions Context) */
private final ModifiableProxyLookup proxyLookup = new ModifiableProxyLookup();
private final PropertyChangeListener focusPropertyListener = new PropertyChangeListener() {
/**
* Listener that keeps the proxyLookup in sync with the focused area of
* the UI.
*
* Since the embedded MessageContentViewer (attachments panel) inside
* the DataContentPanel is not in its own TopComponenet, its selection
* does not get proxied into the Global Actions Context (GAC)
* automatically, and many of the available actions don't work on it.
* Further, we can't put the selection from both the Result table and
* the Attachments table in the GAC because they could bouth include
* AbstractFiles, muddling the selection seen by the actions. Instead,
* depending on where the focus is in the window, we want to put
* different Content in the Global Actions Context to be picked up by,
* e.g., the tagging actions. The best way I could figure to do this was
* to listen to all focus events and swap out what is in the lookup
* appropriately. An alternative to this would be to investigate using
* the ContextAwareAction interface.
*
* @see org.sleuthkit.autopsy.communications.MessageBrowser for a
* similar situation and a similar solution.
*
* @param focusEvent The focus change event.
*/
@Override
public void propertyChange(final PropertyChangeEvent focusEvent) {
if (focusEvent.getPropertyName().equalsIgnoreCase("focusOwner")) {
final Component newFocusOwner = (Component) focusEvent.getNewValue();
if (newFocusOwner == null) {
return;
}
if (isDescendingFrom(newFocusOwner, contentViewerPanel)) {
//if the focus owner is within the MessageContentViewer (the attachments table)
proxyLookup.setNewLookups(createLookup(contentViewerPanel.getExplorerManager(), getActionMap()));
} else if (isDescendingFrom(newFocusOwner, TimeLineTopComponent.this)) {
//... or if it is within the Results table.
proxyLookup.setNewLookups(createLookup(explorerManager, getActionMap()));
}
}
}
};
@NbBundle.Messages({"TimelineTopComponent.selectedEventListener.errorMsg=There was a problem getting the content for the selected event."})
private final InvalidationListener selectedEventsListener = new InvalidationListener() {
/**
* Listener that drives the result viewer or content viewer (depending
* on view mode) according to the controller's selected event IDs
*
* @param observable Observable that was invalidated. Usually
* irrelevant.
*/
@Override
public void invalidated(Observable observable) {
List<Long> selectedEventIDs = controller.getSelectedEventIDs();
//depending on the active view mode, we either update the dataResultPanel, or update the contentViewerPanel directly.
switch (controller.getViewMode()) {
case LIST:
//make an array of EventNodes for the selected events
EventNode[] childArray = new EventNode[selectedEventIDs.size()];
try {
for (int i = 0; i < selectedEventIDs.size(); i++) {
childArray[i] = EventNode.createEventNode(selectedEventIDs.get(i), controller.getEventsModel());
}
Children children = new Children.Array();
children.add(childArray);
SwingUtilities.invokeLater(() -> {
//set generic container node as root context
explorerManager.setRootContext(new AbstractNode(children));
try {
//set selected nodes for actions
explorerManager.setSelectedNodes(childArray);
} catch (PropertyVetoException ex) {
//I don't know why this would ever happen.
LOGGER.log(Level.SEVERE, "Selecting the event node was vetoed.", ex); // NON-NLS
}
//if there is only one event selected push it into content viewer.
if (childArray.length == 1) {
contentViewerPanel.setNode(childArray[0]);
} else {
contentViewerPanel.setNode(null);
}
});
} catch (NoCurrentCaseException ex) {
//Since the case is closed, the user probably doesn't care about this, just log it as a precaution.
LOGGER.log(Level.SEVERE, "There was no case open to lookup the Sleuthkit object backing a SingleEvent.", ex); // NON-NLS
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to lookup Sleuthkit object backing a SingleEvent.", ex); // NON-NLS
Platform.runLater(() -> {
Notifications.create()
.owner(jFXViewPanel.getScene().getWindow())
.text(Bundle.TimelineTopComponent_selectedEventListener_errorMsg())
.showError();
});
}
break;
case COUNTS:
case DETAIL:
//make a root node with nodes for the selected events as children and push it to the result viewer.
EventRootNode rootNode = new EventRootNode(selectedEventIDs, controller.getEventsModel());
TableFilterNode tableFilterNode = new TableFilterNode(rootNode, true, "Event");
SwingUtilities.invokeLater(() -> {
dataResultPanel.setPath(getResultViewerSummaryString());
dataResultPanel.setNode(tableFilterNode);
});
break;
default:
throw new UnsupportedOperationException("Unknown view mode: " + controller.getViewMode());
}
}
};
private void syncViewMode() {
switch (controller.getViewMode()) {
case COUNTS:
case DETAIL:
/*
* For counts and details mode, restore the result table at the
* bottom left.
*/
SwingUtilities.invokeLater(() -> {
splitYPane.remove(contentViewerPanel);
if (horizontalSplitPane.getParent() != splitYPane) {
splitYPane.setBottomComponent(horizontalSplitPane);
horizontalSplitPane.setRightComponent(contentViewerPanel);
}
});
break;
case LIST:
/*
* For list mode, remove the result table, and let the content
* viewer expand across the bottom.
*/
SwingUtilities.invokeLater(() -> splitYPane.setBottomComponent(contentViewerPanel));
break;
default:
throw new UnsupportedOperationException("Unknown ViewMode: " + controller.getViewMode());
}
}
/**
* Constructor
*
* @param controller The TimeLineController for this topcomponent.
*/
public TimeLineTopComponent(TimeLineController controller) {
initComponents();
associateLookup(proxyLookup);
setName(NbBundle.getMessage(TimeLineTopComponent.class, "CTL_TimeLineTopComponent"));
getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(AddBookmarkTagAction.BOOKMARK_SHORTCUT, "addBookmarkTag"); //NON-NLS
getActionMap().put("addBookmarkTag", new AddBookmarkTagAction()); //NON-NLS
this.controller = controller;
//create linked result and content views
contentViewerPanel = new DataContentExplorerPanel();
dataResultPanel = DataResultPanel.createInstanceUninitialized("", "", Node.EMPTY, 0, contentViewerPanel);
//add them to bottom splitpane
horizontalSplitPane.setLeftComponent(dataResultPanel);
horizontalSplitPane.setRightComponent(contentViewerPanel);
dataResultPanel.open(); //get the explorermanager
contentViewerPanel.initialize();
Platform.runLater(this::initFXComponents);
//set up listeners
TimeLineController.getTimeZone().addListener(timeZone -> dataResultPanel.setPath(getResultViewerSummaryString()));
controller.getSelectedEventIDs().addListener(selectedEventsListener);
//Listen to ViewMode and adjust GUI componenets as needed.
controller.viewModeProperty().addListener(viewMode -> syncViewMode());
syncViewMode();
//add listener that maintains correct selection in the Global Actions Context
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addPropertyChangeListener("focusOwner", focusPropertyListener);
}
/**
* Create and wire up JavaFX components of the interface
*/
@NbBundle.Messages({
"TimeLineTopComponent.eventsTab.name=Events",
"TimeLineTopComponent.filterTab.name=Filters"})
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
void initFXComponents() {
/////init componenets of left most column from top to bottom
final TimeZonePanel timeZonePanel = new TimeZonePanel();
VBox.setVgrow(timeZonePanel, Priority.SOMETIMES);
HistoryToolBar historyToolBar = new HistoryToolBar(controller);
final ZoomSettingsPane zoomSettingsPane = new ZoomSettingsPane(controller);
//set up filter tab
final Tab filterTab = new Tab(Bundle.TimeLineTopComponent_filterTab_name(), new FilterSetPanel(controller));
filterTab.setClosable(false);
filterTab.setGraphic(new ImageView("org/sleuthkit/autopsy/timeline/images/funnel.png")); // NON-NLS
//set up events tab
final EventsTree eventsTree = new EventsTree(controller);
final Tab eventsTreeTab = new Tab(Bundle.TimeLineTopComponent_eventsTab_name(), eventsTree);
eventsTreeTab.setClosable(false);
eventsTreeTab.setGraphic(new ImageView("org/sleuthkit/autopsy/timeline/images/timeline_marker.png")); // NON-NLS
eventsTreeTab.disableProperty().bind(controller.viewModeProperty().isNotEqualTo(ViewMode.DETAIL));
final TabPane leftTabPane = new TabPane(filterTab, eventsTreeTab);
VBox.setVgrow(leftTabPane, Priority.ALWAYS);
controller.viewModeProperty().addListener(viewMode -> {
if (controller.getViewMode() != ViewMode.DETAIL) {
//if view mode is not details, switch back to the filter tab
leftTabPane.getSelectionModel().select(filterTab);
}
});
//assemble left column
final VBox leftVBox = new VBox(5, timeZonePanel, historyToolBar, zoomSettingsPane, leftTabPane);
SplitPane.setResizableWithParent(leftVBox, Boolean.FALSE);
final ViewFrame viewFrame = new ViewFrame(controller, eventsTree);
final SplitPane mainSplitPane = new SplitPane(leftVBox, viewFrame);
mainSplitPane.setDividerPositions(0);
final Scene scene = new Scene(mainSplitPane);
scene.addEventFilter(KeyEvent.KEY_PRESSED, keyEvent -> {
if (new KeyCodeCombination(KeyCode.LEFT, KeyCodeCombination.ALT_DOWN).match(keyEvent)) {
new Back(controller).handle(null);
} else if (new KeyCodeCombination(KeyCode.BACK_SPACE).match(keyEvent)) {
new Back(controller).handle(null);
} else if (new KeyCodeCombination(KeyCode.RIGHT, KeyCodeCombination.ALT_DOWN).match(keyEvent)) {
new Forward(controller).handle(null);
} else if (new KeyCodeCombination(KeyCode.BACK_SPACE, KeyCodeCombination.SHIFT_DOWN).match(keyEvent)) {
new Forward(controller).handle(null);
}
});
//add ui componenets to JFXPanels
jFXViewPanel.setScene(scene);
jFXstatusPanel.setScene(new Scene(new StatusBar(controller)));
}
@Override
public List<Mode> availableModes(List<Mode> modes) {
/*
* This looks like the right thing to do, but online discussions seems
* to indicate this method is effectively deprecated. A break point
* placed here was never hit.
*/
return modes.stream().filter(mode -> mode.getName().equals("timeline") || mode.getName().equals("ImageGallery"))
.collect(Collectors.toList());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jFXstatusPanel = new javafx.embed.swing.JFXPanel();
splitYPane = new javax.swing.JSplitPane();
jFXViewPanel = new javafx.embed.swing.JFXPanel();
horizontalSplitPane = new javax.swing.JSplitPane();
leftFillerPanel = new javax.swing.JPanel();
rightfillerPanel = new javax.swing.JPanel();
jFXstatusPanel.setPreferredSize(new java.awt.Dimension(100, 16));
splitYPane.setDividerLocation(420);
splitYPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
splitYPane.setResizeWeight(0.9);
splitYPane.setPreferredSize(new java.awt.Dimension(1024, 400));
splitYPane.setLeftComponent(jFXViewPanel);
horizontalSplitPane.setDividerLocation(600);
horizontalSplitPane.setResizeWeight(0.5);
horizontalSplitPane.setPreferredSize(new java.awt.Dimension(1200, 300));
horizontalSplitPane.setRequestFocusEnabled(false);
javax.swing.GroupLayout leftFillerPanelLayout = new javax.swing.GroupLayout(leftFillerPanel);
leftFillerPanel.setLayout(leftFillerPanelLayout);
leftFillerPanelLayout.setHorizontalGroup(
leftFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 599, Short.MAX_VALUE)
);
leftFillerPanelLayout.setVerticalGroup(
leftFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 54, Short.MAX_VALUE)
);
horizontalSplitPane.setLeftComponent(leftFillerPanel);
javax.swing.GroupLayout rightfillerPanelLayout = new javax.swing.GroupLayout(rightfillerPanel);
rightfillerPanel.setLayout(rightfillerPanelLayout);
rightfillerPanelLayout.setHorizontalGroup(
rightfillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 364, Short.MAX_VALUE)
);
rightfillerPanelLayout.setVerticalGroup(
rightfillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 54, Short.MAX_VALUE)
);
horizontalSplitPane.setRightComponent(rightfillerPanel);
splitYPane.setRightComponent(horizontalSplitPane);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(splitYPane, javax.swing.GroupLayout.DEFAULT_SIZE, 972, Short.MAX_VALUE)
.addComponent(jFXstatusPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(splitYPane, javax.swing.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE)
.addGap(0, 0, 0)
.addComponent(jFXstatusPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JSplitPane horizontalSplitPane;
private javafx.embed.swing.JFXPanel jFXViewPanel;
private javafx.embed.swing.JFXPanel jFXstatusPanel;
private javax.swing.JPanel leftFillerPanel;
private javax.swing.JPanel rightfillerPanel;
private javax.swing.JSplitPane splitYPane;
// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
super.componentOpened();
WindowManager.getDefault().setTopComponentFloating(this, true);
//add listener that maintains correct selection in the Global Actions Context
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addPropertyChangeListener("focusOwner", focusPropertyListener);
}
@Override
protected void componentClosed() {
super.componentClosed();
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.removePropertyChangeListener("focusOwner", focusPropertyListener);
}
@Override
public ExplorerManager getExplorerManager() {
return explorerManager;
}
/**
* Get the string that should be used as the label above the result table.
* It displays the time range spanned by the selected events.
*
* @return A String representation of all the events displayed.
*/
@NbBundle.Messages({
"# {0} - start of date range",
"# {1} - end of date range",
"TimeLineResultView.startDateToEndDate.text={0} to {1}"})
private String getResultViewerSummaryString() {
Interval selectedTimeRange = controller.getSelectedTimeRange();
if (selectedTimeRange == null) {
return "";
} else {
final DateTimeFormatter zonedFormatter = TimeLineController.getZonedFormatter();
String start = selectedTimeRange.getStart()
.withZone(TimeLineController.getJodaTimeZone())
.toString(zonedFormatter);
String end = selectedTimeRange.getEnd()
.withZone(TimeLineController.getJodaTimeZone())
.toString(zonedFormatter);
return Bundle.TimeLineResultView_startDateToEndDate_text(start, end);
}
}
/**
* Panel that wraps a DataContentPanel and implements
* ExplorerManager.Provider. This allows the explorer manager found by the
* DataContentPanel to be controlled easily.
*
* @see org.sleuthkit.autopsy.communications.MessageDataContent for another
* solution to a very similar problem.
*/
final private static class DataContentExplorerPanel extends JPanel implements ExplorerManager.Provider, DataContent {
private final ExplorerManager explorerManager = new ExplorerManager();
private final DataContentPanel wrapped;
private DataContentExplorerPanel() {
super(new BorderLayout());
wrapped = DataContentPanel.createInstance();
}
@Override
public ExplorerManager getExplorerManager() {
return explorerManager;
}
@Override
public void setNode(Node selectedNode) {
wrapped.setNode(selectedNode);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
wrapped.propertyChange(evt);
}
/**
* Initialize the contents of this panel for use. Specifically add the
* wrapped DataContentPanel to the AWT/Swing containment hierarchy. This
* will trigger the addNotify() method of the embeded Message
* MessageContentViewer causing it to look for a ExplorerManager; it
* should find the one provided by this DataContentExplorerPanel.
*/
private void initialize() {
add(wrapped, BorderLayout.CENTER);
}
}
}
| |
package kernels.parallel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
import kernels.algo.AllOrderedStringExactSubsequences;
import kernels.algo.AllStringSubsequencesSet;
import kernels.algo.CommonSubstring;
import kernels.algo.StringsAlignment;
import kernels.parallel.ted.CleanTED_Symbols;
import settings.Parameters;
import util.ArgumentReader;
import util.IdentityArrayList;
import util.PrintProgress;
import util.PrintProgressPercentage;
import util.Utility;
import util.file.FileUtil;
public class ParallelSubstrings {
protected static String getVersion() { return "1.05"; }
static boolean onlyContiguous = true;
static boolean convertToLowerCase = true;
static char[] ignorePunctChar = new char[] { '.', ',', ':', ';', '?', '!', '"' };
static String[] ignorePunctString = new String[] { "--", "..." };
static int functionalWordThreshold = 100;
static {
//Arrays.sort(ignoreStartChars);
Arrays.sort(ignorePunctChar);
for(int i=0; i<ignorePunctString.length; i++) {
ignorePunctString[i] = ignorePunctString[i].intern();
}
Arrays.sort(ignorePunctString);
}
long reportEvery;
ArrayList<String[]> sentencesSource, sentencesTarget;
File sourceFile, targetFile, printTableFile;
long linesSource, totalPairs;
int minMatchSize;
HashSet<String> functionalWordsSetSource = new HashSet<String>();
HashSet<String> functionalWordsSetTarget = new HashSet<String>();
//final table with source-target-indexes
HashMap<IdentityArrayList<String>,HashMap<IdentityArrayList<String>,TreeSet<Integer>>> finalTable;
PrintProgressPercentage progress;
public ParallelSubstrings(File sourceFile, File targetFile, File outputFile, int minMatchSize) {
CommonSubstring.minMatchLength = minMatchSize; //min length of matchin substring
this.minMatchSize = minMatchSize;
this.printTableFile = outputFile;
this.sourceFile = sourceFile;
this.targetFile = targetFile;
File systemLogFile = FileUtil.changeExtension(printTableFile, "log");
Parameters.openLogFile(systemLogFile);
}
protected void init() throws FileNotFoundException {
getSentences();
getWordsFreq();
linesSource = sentencesSource.size();
totalPairs = ((long) linesSource) * (linesSource - 1) / 2;
reportEvery = totalPairs/100;
printParameters();
finalTable = new HashMap<IdentityArrayList<String>,HashMap<IdentityArrayList<String>,TreeSet<Integer>>>();
progress = new PrintProgressPercentage("Processing pair", 10000, 0, totalPairs);
}
protected void run() throws FileNotFoundException {
init();
long startTime = System.currentTimeMillis();
// compute the matches
computePairwiseMatch();
progress.end();
// print the table to file
printFinalTableToFile();
long endTime = System.currentTimeMillis();
Parameters.logStdOutPrintln("Took " + ((float) (endTime - startTime)) / 1000 + " s");
Parameters.closeLogFile();
}
protected void printParameters() {
Parameters.logStdOutPrintln(this.getClass().getName() + " v. " + getVersion());
Parameters.logStdOutPrintln("");
Parameters.logStdOutPrintln("Min length subsequence: " + CommonSubstring.minMatchLength);
Parameters.logStdOutPrintln("Source File: " + sourceFile);
Parameters.logStdOutPrintln("Target File: " + targetFile);
Parameters.logStdOutPrintln("Number of sentences: " + linesSource);
Parameters.logStdOutPrintln("Number of total pairs: " + totalPairs);
Parameters.logStdOutPrintln("Only Contiguous: " + onlyContiguous);
Parameters.flushLog();
}
protected boolean getSentences() throws FileNotFoundException {
Parameters.logStdOutPrintln("Reading Source Sentence... ");
sentencesSource = getInternedSentences(sourceFile);
Parameters.logStdOutPrintln("Reading Target Sentence... ");
sentencesTarget = getInternedSentences(targetFile);
linesSource = sentencesSource.size();
long linesTarget = sentencesTarget.size();
if (linesSource!=linesTarget) {
System.err.println("Source and target files have different number of lines");
System.err.println(linesSource + " != " + linesTarget);
return false;
}
Parameters.logStdOutPrintln("Total lines: " + linesSource);
//removeBadSentences();
//printCleanedSentencesToFile();
removePunctuations();
return true;
}
/*
private void printCleanedSentencesToFile() throws FileNotFoundException {
String dir = printTableFile.getParent() + "/";
File outputSource = new File(dir + "train_source.txt");
File outputTarget = new File(dir + "train_target.txt");
Parameters.logStdOutPrintln("Printing clean sentences source: " + outputSource);
Parameters.logStdOutPrintln("Printing clean sentences target: " + outputTarget);
PrintWriter pwSource = new PrintWriter(outputSource);
PrintWriter pwTarget = new PrintWriter(outputTarget);
Iterator<String[]> iterSource = sentencesSource.iterator();
Iterator<String[]> iterTarget = sentencesTarget.iterator();
while(iterSource.hasNext()) {
pwSource.println(Utility.joinStringArrayToString(iterSource.next(), " "));
pwTarget.println(Utility.joinStringArrayToString(iterTarget.next(), " "));
}
pwSource.close();
pwTarget.close();
}
*/
/*
private void removeBadSentences() {
int ignored = 0;
Iterator<String[]> iterSouce = sentencesSource.iterator();
Iterator<String[]> iterTarget = sentencesTarget.iterator();
while(iterSouce.hasNext()) {
String[] source = iterSouce.next();
String[] target = iterTarget.next();
if (ignoreSentence(source[0]) || ignoreSentence(target[0])) {
iterSouce.remove();
iterTarget.remove();
}
ignored++;
}
Parameters.logStdOutPrintln("Ignored Sentences: " + ignored);
Parameters.logStdOutPrintln("Remaining Sentences: " + sentencesSource.size());
}
*/
private void removePunctuations() {
String[] cleanedSentence = null;
ListIterator<String[]> iter = sentencesSource.listIterator();
while(iter.hasNext()) {
cleanedSentence = removePunctuation(iter.next());
if (cleanedSentence!=null) {
iter.remove();
iter.add(cleanedSentence);
}
}
iter = sentencesTarget.listIterator();
while(iter.hasNext()) {
cleanedSentence = removePunctuation(iter.next());
if (cleanedSentence!=null) {
iter.remove();
iter.add(cleanedSentence);
}
}
}
private static String[] removePunctuation(String[] lineWords) {
int i = 0;
for(String w : lineWords) {
if (w.length()==1 && Arrays.binarySearch(ignorePunctChar, w.charAt(0))>=0)
continue;
if (Arrays.binarySearch(ignorePunctString, w)>=0)
continue;
lineWords[i++] = w;
}
if (i==lineWords.length)
return null;
return Arrays.copyOf(lineWords, i);
}
private void getWordsFreq() {
HashMap<String,int[]> wordFreqSource = new HashMap<String,int[]>();
HashMap<String,int[]> wordFreqTarget = new HashMap<String,int[]>();
getWordsFreq(sentencesSource, wordFreqSource);
getWordsFreq(sentencesTarget, wordFreqTarget);
HashMap<String, Integer> wordFreqSourceInteger = Utility.convertHashMapIntArrayInteger(wordFreqSource);
HashMap<String, Integer> wordFreqTargetInteger = Utility.convertHashMapIntArrayInteger(wordFreqTarget);
TreeMap<Integer, HashSet<String>> reverseSource = Utility.reverseAndSortTable(wordFreqSourceInteger);
TreeMap<Integer, HashSet<String>> reverseTarget = Utility.reverseAndSortTable(wordFreqTargetInteger);
//Utility.printInvertedSortedTableInt(reverseSource, new File("/tmp/source.txt"));
//Utility.printInvertedSortedTableInt(reverseTarget, new File("/tmp/target.txt"));
makeFunctionalSet(reverseSource, functionalWordsSetSource);
makeFunctionalSet(reverseTarget, functionalWordsSetTarget);
}
private void makeFunctionalSet(
TreeMap<Integer, HashSet<String>> reverseTable,
HashSet<String> functionalWords) {
int i=0;
for(HashSet<String> freqSet : reverseTable.descendingMap().values()) {
functionalWords.addAll(freqSet);
i+= freqSet.size();
if (i>=functionalWordThreshold)
break;
}
}
private static void getWordsFreq(ArrayList<String[]> sentences,
HashMap<String, int[]> table) {
for(String[] s : sentences) {
for(String w : s) {
Utility.increaseInHashMap(table, w);
}
}
}
public static ArrayList<String[]> getInternedSentences(File inputFile) throws FileNotFoundException {
return getInternedSentences(inputFile, false);
}
public static ArrayList<String[]> getInternedSentences(File inputFile, boolean replaceSymbols) throws FileNotFoundException {
ArrayList<String[]> result = new ArrayList<String[]>();
@SuppressWarnings("resource")
Scanner scanner = new Scanner(inputFile, "utf-8");
while(scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (convertToLowerCase)
line = line.toLowerCase();
String[] lineWords = getInternedWordArrayFromSentence(line, replaceSymbols);
result.add(lineWords);
}
return result;
}
public static String[] getInternedWordArrayFromSentence(String line) {
return getInternedWordArrayFromSentence(line,false);
}
public static String[] getInternedWordArrayFromSentence(String line, boolean replaceSymbols) {
String[] lineWords = line.trim().split("\\s+");
for(int i=0; i<lineWords.length; i++) {
String w = replaceSymbols ?
CleanTED_Symbols.replaceSymbols(lineWords[i]) : lineWords[i];
lineWords[i] = w.intern();
// INTERNING ALL WORDS IN FILES
}
return lineWords;
}
/*
private void printCleanedSentencesToFile() throws FileNotFoundException {
String dir = printTableFile.getParent() + "/";
File outputSource = new File(dir + "train_source.txt");
File outputTarget = new File(dir + "train_target.txt");
Parameters.logStdOutPrintln("Printing clean sentences source: " + outputSource);
Parameters.logStdOutPrintln("Printing clean sentences target: " + outputTarget);
PrintWriter pwSource = new PrintWriter(outputSource);
PrintWriter pwTarget = new PrintWriter(outputTarget);
Iterator<String[]> iterSource = sentencesSource.iterator();
Iterator<String[]> iterTarget = sentencesTarget.iterator();
while(iterSource.hasNext()) {
pwSource.println(Utility.joinStringArrayToString(iterSource.next(), " "));
pwTarget.println(Utility.joinStringArrayToString(iterTarget.next(), " "));
}
pwSource.close();
pwTarget.close();
}
*/
/*
private void removeBadSentences() {
int ignored = 0;
Iterator<String[]> iterSouce = sentencesSource.iterator();
Iterator<String[]> iterTarget = sentencesTarget.iterator();
while(iterSouce.hasNext()) {
String[] source = iterSouce.next();
String[] target = iterTarget.next();
if (ignoreSentence(source[0]) || ignoreSentence(target[0])) {
iterSouce.remove();
iterTarget.remove();
}
ignored++;
}
Parameters.logStdOutPrintln("Ignored Sentences: " + ignored);
Parameters.logStdOutPrintln("Remaining Sentences: " + sentencesSource.size());
}
*/
protected void computePairwiseMatch() {
ListIterator<String[]> sourceIter1 = sentencesSource.listIterator();
ListIterator<String[]> targetIter1 = sentencesTarget.listIterator();
int index1 = -1, index2=0;
long count = 0;
while(sourceIter1.hasNext()) {
index1++;
index2 = index1; //incremented immediately
String[] source1 = sourceIter1.next();
String[] target1 = targetIter1.next();
ListIterator<String[]> sourceIter2 = sentencesSource.listIterator(index2);
ListIterator<String[]> targetIter2 = sentencesTarget.listIterator(index2);
while (sourceIter2.hasNext()) {
index2++;
progress.next();
if (++count == reportEvery) {
count = 0;
progress.suspend();
Parameters.logStdOutPrintln("Total size of table keys, subkey " + Arrays.toString(totalKeysAndPairs(finalTable)));
if (CommonSubstring.minMatchLength==1)
Parameters.logStdOutPrintln("Total size of table keys, subkey (of size 1) " + Arrays.toString(totalKeysLengthOneAndPairs()));
progress.resume();
}
String[] source2 = sourceIter2.next();
String[] target2 = targetIter2.next();
computeMatch(index1, index2, source1, source2, target1, target2);
}
}
}
protected static boolean ignoreSentence(String[] s) {
//return Arrays.binarySearch(ignoreStartChars, s.charAt(0))>=0;
return s.length==0 || s[0].charAt(0)=='&';
}
static int maxMatchSize = 0;
protected void computeMatch(int index1, int index2, String[] source1, String[] source2,
String[] target1, String[] target2) {
if (ignoreSentence(source1) || ignoreSentence(source2) ||
ignoreSentence(target1) || ignoreSentence(target2))
return;
// GET ALL SUBSTRING MATCHES FROM SOURCE PAIR
HashSet<IdentityArrayList<String>> resultMatchSource =
onlyContiguous ?
CommonSubstring.getAllMaxCommonSubstringsIdentity(source1, source2):
AllStringSubsequencesSet.getAllMaxCommonSubstringsIdentity(source1, source2, minMatchSize);
// GET ALL SUBSTRING MATCHES FROM TARGET PAIR
HashSet<IdentityArrayList<String>> resultMatchTarget =
onlyContiguous ?
CommonSubstring.getAllMaxCommonSubstringsIdentity(target1, target2) :
AllStringSubsequencesSet.getAllMaxCommonSubstringsIdentity(target1, target2, minMatchSize);
//Remove exact matches (e.b., proper nouns, etc...)
cleanFunctionalWords(resultMatchSource, functionalWordsSetSource);
cleanFunctionalWords(resultMatchTarget, functionalWordsSetTarget);
cleanExactMatches(resultMatchSource, resultMatchTarget);
if (!onlyContiguous) {
removeMoreThanOneGap(resultMatchSource,source1);
removeMoreThanOneGap(resultMatchSource,source2);
removeMoreThanOneGap(resultMatchTarget,target1);
removeMoreThanOneGap(resultMatchTarget,target2);
}
// both not empty
if (!resultMatchSource.isEmpty() && !resultMatchTarget.isEmpty()) {
int totalMatch = resultMatchSource.size() * resultMatchTarget.size();
if (totalMatch>maxMatchSize) {
maxMatchSize = totalMatch;
System.out.println("New Max: " + maxMatchSize);
System.out.println(Arrays.toString(source1));
System.out.println(Arrays.toString(source2));
System.out.println(resultMatchSource);
System.out.println(Arrays.toString(target1));
System.out.println(Arrays.toString(target2));
System.out.println(resultMatchTarget);
System.out.println("------------------------------");
}
addMatchesToFinalTable(index1, index2, resultMatchSource, resultMatchTarget);
}
}
private static void removeMoreThanOneGap(
HashSet<IdentityArrayList<String>> resultMatch, String[] sentece) {
Iterator<IdentityArrayList<String>> iter = resultMatch.iterator();
while(iter.hasNext()) {
IdentityArrayList<String> seq = iter.next();
if (StringsAlignment.getBestAlignemntGaps(seq.toArray(new String[]{}), sentece)>1)
iter.remove();
}
}
private void cleanFunctionalWords(
HashSet<IdentityArrayList<String>> wordSequences,
HashSet<String> functionalWords) {
Iterator<IdentityArrayList<String>> iter = wordSequences.iterator();
while(iter.hasNext()) {
IdentityArrayList<String> next = iter.next();
if (functionalWords.containsAll(next))
iter.remove();
}
}
/*
private void printCleanedSentencesToFile() throws FileNotFoundException {
String dir = printTableFile.getParent() + "/";
File outputSource = new File(dir + "train_source.txt");
File outputTarget = new File(dir + "train_target.txt");
Parameters.logStdOutPrintln("Printing clean sentences source: " + outputSource);
Parameters.logStdOutPrintln("Printing clean sentences target: " + outputTarget);
PrintWriter pwSource = new PrintWriter(outputSource);
PrintWriter pwTarget = new PrintWriter(outputTarget);
Iterator<String[]> iterSource = sentencesSource.iterator();
Iterator<String[]> iterTarget = sentencesTarget.iterator();
while(iterSource.hasNext()) {
pwSource.println(Utility.joinStringArrayToString(iterSource.next(), " "));
pwTarget.println(Utility.joinStringArrayToString(iterTarget.next(), " "));
}
pwSource.close();
pwTarget.close();
}
*/
/*
private void removeBadSentences() {
int ignored = 0;
Iterator<String[]> iterSouce = sentencesSource.iterator();
Iterator<String[]> iterTarget = sentencesTarget.iterator();
while(iterSouce.hasNext()) {
String[] source = iterSouce.next();
String[] target = iterTarget.next();
if (ignoreSentence(source[0]) || ignoreSentence(target[0])) {
iterSouce.remove();
iterTarget.remove();
}
ignored++;
}
Parameters.logStdOutPrintln("Ignored Sentences: " + ignored);
Parameters.logStdOutPrintln("Remaining Sentences: " + sentencesSource.size());
}
*/
public static void testTwoSentences(String a, String b) {
String[] source1 = getInternedWordArrayFromSentence(a);
String[] source2 = getInternedWordArrayFromSentence(b);
HashSet<IdentityArrayList<String>> resultMatchSource =
CommonSubstring.getAllMaxCommonSubstringsIdentity(source1, source2);
if (resultMatchSource.isEmpty()) {
System.out.println("--- No match found ---");
return;
}
for(IdentityArrayList<String> m : resultMatchSource) {
System.out.println(m);
}
}
public static void testTwoSentencePairs(String sa, String sb, String ta, String tb) {
System.out.println("SOURCE:");
testTwoSentences(sa, sb);
System.out.println("\nTARGET:");
testTwoSentences(ta, tb);
}
/**
* Remove exact matches (e.b., proper nouns, etc...)
* @param resultMatchSource
* @param resultMatchTarget
*/
protected void cleanExactMatches(
HashSet<IdentityArrayList<String>> resultMatchSource,
HashSet<IdentityArrayList<String>> resultMatchTarget) {
Iterator<IdentityArrayList<String>> iter1 = resultMatchSource.iterator();
while(iter1.hasNext()) {
IdentityArrayList<String> key1 = iter1.next();
if (resultMatchTarget.remove(key1))
iter1.remove();
}
}
protected void addMatchesToFinalTable(
int index1, int index2,
HashSet<IdentityArrayList<String>> resultMatchSource,
HashSet<IdentityArrayList<String>> resultMatchTarget) {
for(IdentityArrayList<String> sourceMatch : resultMatchSource) {
int sourceSize = sourceMatch.size();
for(IdentityArrayList<String> targetMatch : resultMatchTarget) {
int targetSize = targetMatch.size();
if (sourceSize!=1 || targetSize!=1)
addToFinalTable(sourceMatch, targetMatch, index1, index2);
}
}
}
synchronized private void addToFinalTable(
IdentityArrayList<String> sourceMatch,
IdentityArrayList<String> targetMatch,
int index1, int index2) {
HashMap<IdentityArrayList<String>, TreeSet<Integer>> subtable = finalTable.get(sourceMatch);
if (subtable==null) {
subtable = new HashMap<IdentityArrayList<String>, TreeSet<Integer>>();
finalTable.put(sourceMatch, subtable);
TreeSet<Integer> indexSet = new TreeSet<Integer>();
indexSet.add(index1);
indexSet.add(index2);
subtable.put(targetMatch, indexSet);
}
else {
TreeSet<Integer> indexSet = subtable.get(targetMatch);
if (indexSet==null) {
indexSet = new TreeSet<Integer>();
subtable.put(targetMatch, indexSet);
}
indexSet.add(index1);
indexSet.add(index2);
}
}
/**
* Print final table to file
* @param sourceTargetIndex
* @param outputFileMain
*/
private void printFinalTableToFile() {
Parameters.logStdOutPrintln("Printing final table to " + printTableFile);
Parameters.logStdOutPrintln("Total size of table keys, subkey " + Arrays.toString(totalKeysAndPairs(finalTable)));
Parameters.logStdOutPrintln(" " + printTableFile);
printTable(finalTable, printTableFile);
}
public static int[] totalKeysSubKeys(File inputFile) {
PrintProgress pp = new PrintProgress("Reading table", 10000, 0);
Scanner scan = FileUtil.getGzipScanner(inputFile);
//IdentityArrayList<String> key=null, value=null;
//HashMap<IdentityArrayList<String>, TreeSet<Integer>> subTable = null;
int keys=0, values=0;
//int[] indexes = null;
while(scan.hasNextLine()) {
String line = scan.nextLine();
String[] split = line.split("\t");
if (split.length==1)
continue; //2: //new implementation
if (split.length==2) {
//2: [of, climate] // inlcuding case of old implementation
// [check, for] // new implementation only has these lines
//key = getIdentityArrayList(split[1]);
keys++;
continue;
}
// split.length==4 //\t\t[che, per, la] [23687, 34596, 186687]
pp.next();
values++;
//value = getIdentityArrayList(split[2]);
//indexes = getIndexes(split[3]);
}
pp.end();
return new int[]{keys, values};
}
public static HashMap<IdentityArrayList<String>,HashMap<IdentityArrayList<String>,TreeSet<Integer>>>
readTableFromFile(File inputFile) {
return readTableFromFile(inputFile, false);
}
public static HashMap<IdentityArrayList<String>,HashMap<IdentityArrayList<String>,TreeSet<Integer>>>
readTableFromFile(File inputFile, boolean cleanSymbols) {
HashMap<IdentityArrayList<String>,HashMap<IdentityArrayList<String>,TreeSet<Integer>>> result =
new HashMap<IdentityArrayList<String>,HashMap<IdentityArrayList<String>,TreeSet<Integer>>> ();
PrintProgress pp = new PrintProgress("Reading table", 10000, 0);
Scanner scan = FileUtil.getGzipScanner(inputFile);
IdentityArrayList<String> key=null, value=null;
HashMap<IdentityArrayList<String>, TreeSet<Integer>> subTable = null;
int[] indexes = null;
while(scan.hasNextLine()) {
String line = scan.nextLine();
String[] split = line.split("\t");
if (split.length==1)
continue; //2: //new implementation
if (split.length==2) {
//2: [of, climate] // inlcuding case of old implementation
// [check, for] // new implementation only has these lines
key = getIdentityArrayListFromBracket(split[1], cleanSymbols);
subTable = result.get(key);
if (subTable==null) {
subTable = new HashMap<IdentityArrayList<String>, TreeSet<Integer>>();
result.put(key, subTable);
}
continue;
}
// split.length==4 //\t\t[che, per, la] [23687, 34596, 186687]
pp.next();
value = getIdentityArrayListFromBracket(split[2], cleanSymbols);
indexes = getIndexeArrayFromParenthesis(split[3]);
TreeSet<Integer> valueSet = new TreeSet<Integer>();
subTable.put(value, valueSet);
for(int i : indexes) {
valueSet.add(i);
}
}
pp.end();
return result;
}
public static int[] totalKeysAndPairs(File inputFile) {
int keys=0;
int pairs=0;
PrintProgress pp = new PrintProgress("Reading table", 10000, 0);
Scanner scan = FileUtil.getGzipScanner(inputFile);
while(scan.hasNextLine()) {
String line = scan.nextLine();
String[] split = line.split("\t");
if (split.length==1)
continue; //2: //new implementation
if (split.length==2) {
// [check, for] // new implementation only has these lines
keys++;
continue;
}
// split.length==4 //\t\t[che, per, la] [23687, 34596, 186687]
pp.next();
pairs++;
}
pp.end();
return new int[]{keys, pairs};
}
public static void reportKeysPairsCountPerLength(File inputFile) {
Scanner scan = FileUtil.getGzipScanner(inputFile);
String length = null;
int countKeys = 0, countPairs = 0;
while(scan.hasNextLine()) {
String line = scan.nextLine();
String[] split = line.split("\t");
if (split.length==1) { //2:
if (length!=null) {
System.out.println(length + " " + Arrays.toString(new int[]{countKeys, countPairs}));
}
length = line;
countKeys = 0;
countPairs = 0;
continue;
}
if (split.length==2) { // [check, for] // new implementation only has these lines
countKeys++;
continue;
}
// split.length==4 //\t\t[che, per, la] [23687, 34596, 186687]
countPairs++;
}
if (length!=null)
System.out.println(length + " " + Arrays.toString(new int[]{countKeys, countPairs}));
}
public static IdentityArrayList<String> getIdentityArrayListFromBracket(String string) {
string = string.substring(1, string.length()-1);
return getIdentityArrayList(string, "\\, ");
}
public static IdentityArrayList<String> getIdentityArrayListFromBracket(String string, boolean cleanSymbols) {
string = string.substring(1, string.length()-1);
IdentityArrayList<String> result = getIdentityArrayList(string, "\\, ");
if (cleanSymbols)
CleanTED_Symbols.cleanIdentityArray(result);
return result;
}
public static IdentityArrayList<String> getIdentityArrayList(String string, String splitExp) {
String[] split = string.split(splitExp);
for(int i=0; i<split.length; i++) {
split[i] = split[i].trim().intern();
}
return new IdentityArrayList<String>(split);
}
public static String[] getInternedArrya(String string, String splitExp) {
String[] split = string.split(splitExp);
for(int i=0; i<split.length; i++) {
split[i] = split[i].trim().intern();
}
return split;
}
public static String[] getInternedStringArrayFromBracket(String string) {
string = string.substring(1, string.length()-1);
String[] split = string.split("\\, ");
for(int i=0; i<split.length; i++) {
split[i] = split[i].trim().intern();
}
return split;
}
public static int[] getIndexeArrayFromParenthesis(String string) {
string = string.substring(1, string.length()-1);
String[] split = string.split("\\, ");
int[] result = new int[split.length];
for(int i=0; i<split.length; i++) {
result[i] = Integer.parseInt(split[i]);
}
return result;
}
public static TreeSet<Integer> getIndexeSetFromParenthesis(String string) { //int addToAllIndexes
TreeSet<Integer> result = new TreeSet<Integer>();
string = string.substring(1, string.length()-1);
String[] split = string.split("\\, ");
for(String i : split) {
result.add(Integer.parseInt(i)); //+ addToAllIndexes
}
return result;
}
public static int[] totalKeysAndPairs(
HashMap<IdentityArrayList<String>, HashMap<IdentityArrayList<String>, TreeSet<Integer>>> table) {
int keys = table.size();
int subKeys = 0;
for(HashMap<IdentityArrayList<String>, TreeSet<Integer>> e : table.values()) {
subKeys += e.size();
}
return new int[]{keys, subKeys};
}
protected int[] totalKeysLengthOneAndPairs() {
int keys = 0;
int subkeys = 0;
for(Entry<IdentityArrayList<String>, HashMap<IdentityArrayList<String>, TreeSet<Integer>>> e : finalTable.entrySet()) {
IdentityArrayList<String> source = e.getKey();
if (source.size()==1)
keys++;
for(IdentityArrayList<String> target : e.getValue().keySet()) {
if (target.size()==1)
subkeys++;
}
}
return new int[]{keys, subkeys};
}
public static int getTotalUniqueIndexes(
HashMap<IdentityArrayList<String>, HashMap<IdentityArrayList<String>, TreeSet<Integer>>> table) {
TreeSet<Integer> allIndexes = new TreeSet<Integer>();
for(HashMap<IdentityArrayList<String>, TreeSet<Integer>> subTable : table.values()) {
allIndexes.addAll(getAllIndexes(subTable));
}
return allIndexes.size();
}
public static TreeSet<Integer> getAllIndexes(HashMap<IdentityArrayList<String>, TreeSet<Integer>> subTable) {
TreeSet<Integer> result = new TreeSet<Integer>();
for(TreeSet<Integer> set : subTable.values()) {
result.addAll(set);
}
return result;
}
public static void printTable(
HashMap<IdentityArrayList<String>,HashMap<IdentityArrayList<String>,TreeSet<Integer>>> finalTable,
File printTableFile) {
PrintWriter pw = FileUtil.getGzipPrintWriter(printTableFile);
int size = finalTable.size();
int count = 0;
for(int i=0; i<10000; i++) { // order by the length of the source substring
boolean foundSize = false;
for( Entry<IdentityArrayList<String>, HashMap<IdentityArrayList<String>, TreeSet<Integer>>> e : finalTable.entrySet()) {
IdentityArrayList<String> source = e.getKey();
int length = source.size();
if (length==i) {
count++;
if (!foundSize) {
pw.println(length + ":");
foundSize = true;
}
pw.println("\t" + source);
for( Entry<IdentityArrayList<String>, TreeSet<Integer>> f : e.getValue().entrySet()) {
IdentityArrayList<String> target = f.getKey();
pw.println("\t\t" + target + "\t" + f.getValue().toString());
}
}
}
if (count==size)
break;
}
pw.close();
}
public static void main(String args[]) throws FileNotFoundException {
String dir = "/Users/fedja/Dropbox/ted_experiment/";
args = new String[]{
dir + "corpus_en_it/train.tags.en-it.clean.tok.lc.en", //source
dir + "corpus_en_it/train.tags.en-it.clean.tok.lc.it", //targe
dir + "en_it/kernels/dummy.gz", //output
"2", //minLength
"false" //onlyContiguous
};
String usage = "ParallelSubstrings v. " + getVersion() + "\n" +
"usage: java ParallelSubstringsMatch "
+ "-sourceFile:file, -targetFile:file, -outputFile:file "
+ "-minMatchSize:n -onlyContiguous:true";
if (args.length!=5) {
System.err.println("Wrong number of arguments!");
System.err.println(usage);
}
File sourceFile = ArgumentReader.readFileOption(args[0]);
File targetFile = ArgumentReader.readFileOption(args[1]);
File outputFile = ArgumentReader.readFileOption(args[2]);
int minMatchSize = ArgumentReader.readIntOption(args[3]);
onlyContiguous = ArgumentReader.readBooleanOption(args[4]);
ParallelSubstrings PS = new ParallelSubstrings(
sourceFile, targetFile, outputFile, minMatchSize);
PS.run();
}
}
| |
/*
* Copyright 2021 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.
*/
package com.google.ads.googleads.v9.services.stub;
import com.google.ads.googleads.v9.resources.ConversionValueRuleSet;
import com.google.ads.googleads.v9.services.GetConversionValueRuleSetRequest;
import com.google.ads.googleads.v9.services.MutateConversionValueRuleSetsRequest;
import com.google.ads.googleads.v9.services.MutateConversionValueRuleSetsResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
import org.threeten.bp.Duration;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link ConversionValueRuleSetServiceStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li> The default service address (googleads.googleapis.com) and default port (443) are used.
* <li> Credentials are acquired automatically through Application Default Credentials.
* <li> Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the total timeout of getConversionValueRuleSet to 30 seconds:
*
* <pre>{@code
* ConversionValueRuleSetServiceStubSettings.Builder conversionValueRuleSetServiceSettingsBuilder =
* ConversionValueRuleSetServiceStubSettings.newBuilder();
* conversionValueRuleSetServiceSettingsBuilder
* .getConversionValueRuleSetSettings()
* .setRetrySettings(
* conversionValueRuleSetServiceSettingsBuilder
* .getConversionValueRuleSetSettings()
* .getRetrySettings()
* .toBuilder()
* .setTotalTimeout(Duration.ofSeconds(30))
* .build());
* ConversionValueRuleSetServiceStubSettings conversionValueRuleSetServiceSettings =
* conversionValueRuleSetServiceSettingsBuilder.build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class ConversionValueRuleSetServiceStubSettings
extends StubSettings<ConversionValueRuleSetServiceStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder().add("https://www.googleapis.com/auth/adwords").build();
private final UnaryCallSettings<GetConversionValueRuleSetRequest, ConversionValueRuleSet>
getConversionValueRuleSetSettings;
private final UnaryCallSettings<
MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse>
mutateConversionValueRuleSetsSettings;
/** Returns the object with the settings used for calls to getConversionValueRuleSet. */
public UnaryCallSettings<GetConversionValueRuleSetRequest, ConversionValueRuleSet>
getConversionValueRuleSetSettings() {
return getConversionValueRuleSetSettings;
}
/** Returns the object with the settings used for calls to mutateConversionValueRuleSets. */
public UnaryCallSettings<
MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse>
mutateConversionValueRuleSetsSettings() {
return mutateConversionValueRuleSetsSettings;
}
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public ConversionValueRuleSetServiceStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcConversionValueRuleSetServiceStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return "googleads.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "googleads.mtls.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder()
.setScopesToApply(DEFAULT_SERVICE_SCOPES)
.setUseJwtAccessWithScope(true);
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return InstantiatingGrpcChannelProvider.newBuilder()
.setMaxInboundMessageSize(Integer.MAX_VALUE);
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultGrpcTransportProviderBuilder().build();
}
@BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic",
GaxProperties.getLibraryVersion(ConversionValueRuleSetServiceStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected ConversionValueRuleSetServiceStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
getConversionValueRuleSetSettings = settingsBuilder.getConversionValueRuleSetSettings().build();
mutateConversionValueRuleSetsSettings =
settingsBuilder.mutateConversionValueRuleSetsSettings().build();
}
/** Builder for ConversionValueRuleSetServiceStubSettings. */
public static class Builder
extends StubSettings.Builder<ConversionValueRuleSetServiceStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final UnaryCallSettings.Builder<
GetConversionValueRuleSetRequest, ConversionValueRuleSet>
getConversionValueRuleSetSettings;
private final UnaryCallSettings.Builder<
MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse>
mutateConversionValueRuleSetsSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"retry_policy_0_codes",
ImmutableSet.copyOf(
Lists.<StatusCode.Code>newArrayList(
StatusCode.Code.UNAVAILABLE, StatusCode.Code.DEADLINE_EXCEEDED)));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelay(Duration.ofMillis(60000L))
.setInitialRpcTimeout(Duration.ofMillis(3600000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ofMillis(3600000L))
.setTotalTimeout(Duration.ofMillis(3600000L))
.build();
definitions.put("retry_policy_0_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
getConversionValueRuleSetSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
mutateConversionValueRuleSetsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
getConversionValueRuleSetSettings, mutateConversionValueRuleSetsSettings);
initDefaults(this);
}
protected Builder(ConversionValueRuleSetServiceStubSettings settings) {
super(settings);
getConversionValueRuleSetSettings = settings.getConversionValueRuleSetSettings.toBuilder();
mutateConversionValueRuleSetsSettings =
settings.mutateConversionValueRuleSetsSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
getConversionValueRuleSetSettings, mutateConversionValueRuleSetsSettings);
}
private static Builder createDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setEndpoint(getDefaultEndpoint());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.getConversionValueRuleSetSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.mutateConversionValueRuleSetsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
return builder;
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to getConversionValueRuleSet. */
public UnaryCallSettings.Builder<GetConversionValueRuleSetRequest, ConversionValueRuleSet>
getConversionValueRuleSetSettings() {
return getConversionValueRuleSetSettings;
}
/** Returns the builder for the settings used for calls to mutateConversionValueRuleSets. */
public UnaryCallSettings.Builder<
MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse>
mutateConversionValueRuleSetsSettings() {
return mutateConversionValueRuleSetsSettings;
}
@Override
public ConversionValueRuleSetServiceStubSettings build() throws IOException {
return new ConversionValueRuleSetServiceStubSettings(this);
}
}
}
| |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.dnd.*;
import com.intellij.ide.util.treeView.TreeState;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.actions.VirtualFileDeleteProvider;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.issueLinks.TreeLinkMouseListener;
import com.intellij.openapi.vcs.diff.DiffProvider;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.SmartExpander;
import com.intellij.ui.TreeCopyProvider;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.awt.RelativeRectangle;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.EditSourceOnDoubleClickHandler;
import com.intellij.util.EditSourceOnEnterKeyHandler;
import com.intellij.util.containers.Convertor;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;
/**
* @author max
*/
public class ChangesListView extends Tree implements TypeSafeDataProvider, AdvancedDnDSource {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.ui.ChangesListView");
private ChangesListView.DropTarget myDropTarget;
private DnDManager myDndManager;
private ChangeListOwner myDragOwner;
private final Project myProject;
private TreeState myTreeState;
private boolean myShowFlatten = false;
private final CopyProvider myCopyProvider;
@NonNls public static final String HELP_ID_KEY = "helpId";
@NonNls public static final String ourHelpId = "ideaInterface.changes";
@NonNls public static final DataKey<List<VirtualFile>> UNVERSIONED_FILES_DATA_KEY = DataKey.create("ChangeListView.UnversionedFiles");
@NonNls public static final DataKey<List<FilePath>> MISSING_FILES_DATA_KEY = DataKey.create("ChangeListView.MissingFiles");
@NonNls public static final DataKey<String> HELP_ID_DATA_KEY = DataKey.create(HELP_ID_KEY);
private ActionGroup myMenuGroup;
public ChangesListView(final Project project) {
myProject = project;
getModel().setRoot(ChangesBrowserNode.create(myProject, TreeModelBuilder.ROOT_NODE_VALUE));
setShowsRootHandles(true);
setRootVisible(false);
new TreeSpeedSearch(this, new NodeToTextConvertor());
SmartExpander.installOn(this);
myCopyProvider = new TreeCopyProvider(this);
new TreeLinkMouseListener(new ChangesBrowserNodeRenderer(myProject, false, false)).install(this);
}
public DefaultTreeModel getModel() {
return (DefaultTreeModel)super.getModel();
}
public void installDndSupport(ChangeListOwner owner) {
myDragOwner = owner;
myDropTarget = new DropTarget();
myDndManager = DnDManager.getInstance();
myDndManager.registerSource(this);
myDndManager.registerTarget(myDropTarget, this);
}
public void dispose() {
if (myDropTarget != null) {
myDndManager.unregisterSource(this);
myDndManager.unregisterTarget(myDropTarget, this);
myDropTarget = null;
myDndManager = null;
myDragOwner = null;
}
}
private void storeState() {
myTreeState = TreeState.createOn(this, (ChangesBrowserNode)getModel().getRoot());
}
private void restoreState() {
myTreeState.applyTo(this, (ChangesBrowserNode)getModel().getRoot());
}
public boolean isShowFlatten() {
return myShowFlatten;
}
public void setShowFlatten(final boolean showFlatten) {
myShowFlatten = showFlatten;
}
public void updateModel(List<? extends ChangeList> changeLists, Trinity<List<VirtualFile>, Integer, Integer> unversionedFiles, final List<LocallyDeletedChange> locallyDeletedFiles,
List<VirtualFile> modifiedWithoutEditing,
MultiMap<String, VirtualFile> switchedFiles,
@Nullable Map<VirtualFile, String> switchedRoots,
@Nullable List<VirtualFile> ignoredFiles,
final List<VirtualFile> lockedFolders,
@Nullable final Map<VirtualFile, LogicalLock> logicallyLockedFiles) {
storeState();
TreeModelBuilder builder = new TreeModelBuilder(myProject, isShowFlatten());
final DefaultTreeModel model = builder.buildModel(changeLists, unversionedFiles, locallyDeletedFiles, modifiedWithoutEditing,
switchedFiles, switchedRoots, ignoredFiles, lockedFolders, logicallyLockedFiles);
setModel(model);
setCellRenderer(new ChangesBrowserNodeRenderer(myProject, isShowFlatten(), true));
expandPath(new TreePath(((ChangesBrowserNode)model.getRoot()).getPath()));
restoreState();
}
public void calcData(DataKey key, DataSink sink) {
if (key == VcsDataKeys.CHANGES) {
sink.put(VcsDataKeys.CHANGES, getSelectedChanges());
}
else if (key == VcsDataKeys.CHANGE_LEAD_SELECTION) {
sink.put(VcsDataKeys.CHANGE_LEAD_SELECTION, getLeadSelection());
}
else if (key == VcsDataKeys.CHANGE_LISTS) {
sink.put(VcsDataKeys.CHANGE_LISTS, getSelectedChangeLists());
}
else if (key == PlatformDataKeys.VIRTUAL_FILE_ARRAY) {
sink.put(PlatformDataKeys.VIRTUAL_FILE_ARRAY, getSelectedFiles());
}
else if (key == PlatformDataKeys.NAVIGATABLE) {
final VirtualFile[] files = getSelectedFiles();
if (files.length == 1 && !files [0].isDirectory()) {
sink.put(PlatformDataKeys.NAVIGATABLE, new OpenFileDescriptor(myProject, files[0], 0));
}
}
else if (key == PlatformDataKeys.NAVIGATABLE_ARRAY) {
sink.put(PlatformDataKeys.NAVIGATABLE_ARRAY, ChangesUtil.getNavigatableArray(myProject, getSelectedFiles()));
}
else if (key == PlatformDataKeys.DELETE_ELEMENT_PROVIDER) {
final TreePath[] paths = getSelectionPaths();
if (paths != null) {
for(TreePath path: paths) {
ChangesBrowserNode node = (ChangesBrowserNode) path.getLastPathComponent();
if (!(node.getUserObject() instanceof ChangeList)) {
sink.put(PlatformDataKeys.DELETE_ELEMENT_PROVIDER, new VirtualFileDeleteProvider());
break;
}
}
}
}
else if (key == PlatformDataKeys.COPY_PROVIDER) {
sink.put(PlatformDataKeys.COPY_PROVIDER, myCopyProvider);
}
else if (key == UNVERSIONED_FILES_DATA_KEY) {
sink.put(UNVERSIONED_FILES_DATA_KEY, getSelectedUnversionedFiles());
}
else if (key == VcsDataKeys.MODIFIED_WITHOUT_EDITING_DATA_KEY) {
sink.put(VcsDataKeys.MODIFIED_WITHOUT_EDITING_DATA_KEY, getSelectedModifiedWithoutEditing());
}
else if (key == MISSING_FILES_DATA_KEY) {
sink.put(MISSING_FILES_DATA_KEY, getSelectedMissingFiles());
} else if (VcsDataKeys.HAVE_LOCALLY_DELETED == key) {
sink.put(VcsDataKeys.HAVE_LOCALLY_DELETED, haveLocallyDeleted());
} else if (VcsDataKeys.HAVE_MODIFIED_WITHOUT_EDITING == key) {
sink.put(VcsDataKeys.HAVE_MODIFIED_WITHOUT_EDITING, haveLocallyModified());
} else if (VcsDataKeys.HAVE_SELECTED_CHANGES == key) {
sink.put(VcsDataKeys.HAVE_SELECTED_CHANGES, haveSelectedChanges());
} else if (key == HELP_ID_DATA_KEY) {
sink.put(HELP_ID_DATA_KEY, ourHelpId);
}
else if (key == VcsDataKeys.CHANGES_IN_LIST_KEY) {
final TreePath selectionPath = getSelectionPath();
if (selectionPath != null && selectionPath.getPathCount() > 1) {
ChangesBrowserNode firstNode = (ChangesBrowserNode)selectionPath.getPathComponent(1);
if (firstNode instanceof ChangesBrowserChangeListNode) {
final List<Change> list = firstNode.getAllChangesUnder();
sink.put(VcsDataKeys.CHANGES_IN_LIST_KEY, list);
}
}
}
}
private List<VirtualFile> getSelectedUnversionedFiles() {
return getSelectedVirtualFiles(ChangesBrowserNode.UNVERSIONED_FILES_TAG);
}
private List<VirtualFile> getSelectedModifiedWithoutEditing() {
return getSelectedVirtualFiles(ChangesBrowserNode.MODIFIED_WITHOUT_EDITING_TAG);
}
private List<VirtualFile> getSelectedIgnoredFiles() {
return getSelectedVirtualFiles(ChangesBrowserNode.IGNORED_FILES_TAG);
}
private List<VirtualFile> getSelectedVirtualFiles(final Object tag) {
Set<VirtualFile> files = new HashSet<VirtualFile>();
final TreePath[] paths = getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
if (path.getPathCount() > 1) {
ChangesBrowserNode firstNode = (ChangesBrowserNode)path.getPathComponent(1);
if (tag == null || firstNode.getUserObject() == tag) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
files.addAll(node.getAllFilesUnder());
}
}
}
}
return new ArrayList<VirtualFile>(files);
}
private List<FilePath> getSelectedFilePaths(final Object tag) {
Set<FilePath> files = new HashSet<FilePath>();
final TreePath[] paths = getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
if (path.getPathCount() > 1) {
ChangesBrowserNode firstNode = (ChangesBrowserNode)path.getPathComponent(1);
if (tag == null || firstNode.getUserObject() == tag) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
files.addAll(node.getAllFilePathsUnder());
}
}
}
}
return new ArrayList<FilePath>(files);
}
private List<FilePath> getSelectedMissingFiles() {
return getSelectedFilePaths(TreeModelBuilder.LOCALLY_DELETED_NODE);
}
protected VirtualFile[] getSelectedFiles() {
final Change[] changes = getSelectedChanges();
Collection<VirtualFile> files = new HashSet<VirtualFile>();
for (Change change : changes) {
final ContentRevision afterRevision = change.getAfterRevision();
if (afterRevision != null) {
final VirtualFile file = afterRevision.getFile().getVirtualFile();
if (file != null && file.isValid()) {
files.add(file);
}
}
}
files.addAll(getSelectedVirtualFiles(null));
return VfsUtil.toVirtualFileArray(files);
}
protected boolean haveSelectedFileType(final Object tag) {
final TreePath[] paths = getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
if (path.getPathCount() > 1) {
ChangesBrowserNode firstNode = (ChangesBrowserNode)path.getPathComponent(1);
if ((tag == null || firstNode.getUserObject() == tag) && path.getPathCount() > 2) {
return true;
}
}
}
}
return false;
}
public boolean haveLocallyDeleted() {
return haveSelectedFileType(TreeModelBuilder.LOCALLY_DELETED_NODE);
}
public boolean haveLocallyModified() {
return haveSelectedFileType(ChangesBrowserNode.MODIFIED_WITHOUT_EDITING_TAG);
}
private Boolean haveSelectedChanges() {
final TreePath[] paths = getSelectionPaths();
if (paths == null) return false;
for (TreePath path : paths) {
ChangesBrowserNode node = (ChangesBrowserNode) path.getLastPathComponent();
if (node instanceof ChangesBrowserChangeNode) {
return true;
} else if (node instanceof ChangesBrowserChangeListNode) {
final ChangesBrowserChangeListNode changeListNode = (ChangesBrowserChangeListNode)node;
if (changeListNode.getChildCount() > 0) {
return true;
}
}
}
return false;
}
private Change[] getLeadSelection() {
final Set<Change> changes = new LinkedHashSet<Change>();
final TreePath[] paths = getSelectionPaths();
if (paths == null) return new Change[0];
for (TreePath path : paths) {
ChangesBrowserNode node = (ChangesBrowserNode) path.getLastPathComponent();
if (node instanceof ChangesBrowserChangeNode) {
changes.add(((ChangesBrowserChangeNode) node).getUserObject());
}
}
return changes.toArray(new Change[changes.size()]);
}
@NotNull
private Change[] getSelectedChanges() {
Set<Change> changes = new LinkedHashSet<Change>();
final TreePath[] paths = getSelectionPaths();
if (paths == null) return new Change[0];
for (TreePath path : paths) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
changes.addAll(node.getAllChangesUnder());
}
if (changes.size() == 0) {
final List<VirtualFile> selectedModifiedWithoutEditing = getSelectedModifiedWithoutEditing();
if (selectedModifiedWithoutEditing != null && selectedModifiedWithoutEditing.size() > 0) {
for(VirtualFile file: selectedModifiedWithoutEditing) {
AbstractVcs vcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(file);
final DiffProvider diffProvider = vcs == null ? null : vcs.getDiffProvider();
if (diffProvider != null) {
ContentRevision beforeRevision = new VcsCurrentRevisionProxy(diffProvider, file);
ContentRevision afterRevision = new CurrentContentRevision(new FilePathImpl(file));
changes.add(new Change(beforeRevision, afterRevision, FileStatus.HIJACKED));
}
}
}
}
return changes.toArray(new Change[changes.size()]);
}
@NotNull
private ChangeList[] getSelectedChangeLists() {
Set<ChangeList> lists = new HashSet<ChangeList>();
final TreePath[] paths = getSelectionPaths();
if (paths == null) return new ChangeList[0];
for (TreePath path : paths) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
final Object userObject = node.getUserObject();
if (userObject instanceof ChangeList) {
lists.add((ChangeList)userObject);
}
}
return lists.toArray(new ChangeList[lists.size()]);
}
public void setMenuActions(final ActionGroup menuGroup) {
myMenuGroup = menuGroup;
updateMenu();
editSourceRegistration();
}
protected void editSourceRegistration() {
EditSourceOnDoubleClickHandler.install(this);
EditSourceOnEnterKeyHandler.install(this);
}
private void updateMenu() {
PopupHandler.installPopupHandler(this, myMenuGroup, ActionPlaces.CHANGES_VIEW_POPUP, ActionManager.getInstance());
}
public void updateUI() {
super.updateUI();
if (myMenuGroup != null) {
updateMenu();
}
}
@SuppressWarnings({"UtilityClassWithoutPrivateConstructor"})
private static class DragImageFactory {
private static void drawSelection(JTable table, int column, Graphics g, final int width) {
int y = 0;
final int[] rows = table.getSelectedRows();
final int height = table.getRowHeight();
for (int row : rows) {
final TableCellRenderer renderer = table.getCellRenderer(row, column);
final Component component = renderer.getTableCellRendererComponent(table, table.getValueAt(row, column), false, false, row, column);
g.translate(0, y);
component.setBounds(0, 0, width, height);
boolean wasOpaque = false;
if (component instanceof JComponent) {
final JComponent j = (JComponent)component;
if (j.isOpaque()) wasOpaque = true;
j.setOpaque(false);
}
component.paint(g);
if (wasOpaque) {
((JComponent)component).setOpaque(true);
}
y += height;
g.translate(0, -y);
}
}
private static void drawSelection(JTree tree, Graphics g, final int width) {
int y = 0;
final int[] rows = tree.getSelectionRows();
final int height = tree.getRowHeight();
for (int row : rows) {
final TreeCellRenderer renderer = tree.getCellRenderer();
final Object value = tree.getPathForRow(row).getLastPathComponent();
if (value == null) continue;
final Component component = renderer.getTreeCellRendererComponent(tree, value, false, false, false, row, false);
if (component.getFont() == null) {
component.setFont(tree.getFont());
}
g.translate(0, y);
component.setBounds(0, 0, width, height);
boolean wasOpaque = false;
if (component instanceof JComponent) {
final JComponent j = (JComponent)component;
if (j.isOpaque()) wasOpaque = true;
j.setOpaque(false);
}
component.paint(g);
if (wasOpaque) {
((JComponent)component).setOpaque(true);
}
y += height;
g.translate(0, -y);
}
}
public static Image createImage(final JTable table, int column) {
final int height = Math.max(20, Math.min(100, table.getSelectedRowCount() * table.getRowHeight()));
final int width = table.getColumnModel().getColumn(column).getWidth();
final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
drawSelection(table, column, g2, width);
return image;
}
public static Image createImage(final JTree tree) {
final TreeSelectionModel model = tree.getSelectionModel();
final TreePath[] paths = model.getSelectionPaths();
int count = 0;
final List<ChangesBrowserNode> nodes = new ArrayList<ChangesBrowserNode>();
for (final TreePath path : paths) {
final ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
if (!node.isLeaf()) {
nodes.add(node);
count += node.getCount();
}
}
for (TreePath path : paths) {
final ChangesBrowserNode element = (ChangesBrowserNode)path.getLastPathComponent();
boolean child = false;
for (final ChangesBrowserNode node : nodes) {
if (node.isNodeChild(element)) {
child = true;
break;
}
}
if (!child) {
if (element.isLeaf()) count++;
} else if (!element.isLeaf()) {
count -= element.getCount();
}
}
final JLabel label = new JLabel(VcsBundle.message("changes.view.dnd.label", count));
label.setOpaque(true);
label.setForeground(tree.getForeground());
label.setBackground(tree.getBackground());
label.setFont(tree.getFont());
label.setSize(label.getPreferredSize());
final BufferedImage image = new BufferedImage(label.getWidth(), label.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)image.getGraphics();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
label.paint(g2);
g2.dispose();
return image;
}
}
public class DropTarget implements DnDTarget {
public boolean update(DnDEvent aEvent) {
aEvent.hideHighlighter();
aEvent.setDropPossible(false, "");
Object attached = aEvent.getAttachedObject();
if (!(attached instanceof ChangeListDragBean)) return false;
final ChangeListDragBean dragBean = (ChangeListDragBean)attached;
if (dragBean.getSourceComponent() != ChangesListView.this) return false;
dragBean.setTargetNode(null);
RelativePoint dropPoint = aEvent.getRelativePoint();
Point onTree = dropPoint.getPoint(ChangesListView.this);
final TreePath dropPath = getPathForLocation(onTree.x, onTree.y);
if (dropPath == null) return false;
ChangesBrowserNode dropNode = (ChangesBrowserNode)dropPath.getLastPathComponent();
while(!((ChangesBrowserNode) dropNode.getParent()).isRoot()) {
dropNode = (ChangesBrowserNode)dropNode.getParent();
}
if (!dropNode.canAcceptDrop(dragBean)) {
return false;
}
final Rectangle tableCellRect = getPathBounds(new TreePath(dropNode.getPath()));
if (fitsInBounds(tableCellRect)) {
aEvent.setHighlighting(new RelativeRectangle(ChangesListView.this, tableCellRect), DnDEvent.DropTargetHighlightingType.RECTANGLE);
}
aEvent.setDropPossible(true, null);
dragBean.setTargetNode(dropNode);
return false;
}
public void drop(DnDEvent aEvent) {
Object attached = aEvent.getAttachedObject();
if (!(attached instanceof ChangeListDragBean)) return;
final ChangeListDragBean dragBean = (ChangeListDragBean)attached;
final ChangesBrowserNode changesBrowserNode = dragBean.getTargetNode();
if (changesBrowserNode != null) {
changesBrowserNode.acceptDrop(myDragOwner, dragBean);
}
}
public void cleanUpOnLeave() {
}
public void updateDraggedImage(Image image, Point dropPoint, Point imageOffset) {
}
}
private boolean fitsInBounds(final Rectangle rect) {
final Container container = getParent();
if (container instanceof JViewport) {
final Container scrollPane = container.getParent();
if (scrollPane instanceof JScrollPane) {
final Rectangle rectangle = SwingUtilities.convertRectangle(this, rect, scrollPane.getParent());
return scrollPane.getBounds().contains(rectangle);
}
}
return true;
}
private static class NodeToTextConvertor implements Convertor<TreePath, String> {
public String convert(final TreePath path) {
ChangesBrowserNode node = (ChangesBrowserNode)path.getLastPathComponent();
return node.getTextPresentation();
}
}
public boolean canStartDragging(DnDAction action, Point dragOrigin) {
return action == DnDAction.MOVE &&
(getSelectedChanges().length > 0 || getSelectedUnversionedFiles().size() > 0 || getSelectedIgnoredFiles().size() > 0);
}
public DnDDragStartBean startDragging(DnDAction action, Point dragOrigin) {
return new DnDDragStartBean(new ChangeListDragBean(this, getSelectedChanges(), getSelectedUnversionedFiles(),
getSelectedIgnoredFiles()));
}
@Nullable
public Pair<Image, Point> createDraggedImage(DnDAction action, Point dragOrigin) {
final Image image = DragImageFactory.createImage(this);
return new Pair<Image, Point>(image, new Point(-image.getWidth(null), -image.getHeight(null)));
}
public void dragDropEnd() {
}
public void dropActionChanged(final int gestureModifiers) {
}
@NotNull
public JComponent getComponent() {
return this;
}
public void processMouseEvent(final MouseEvent e) {
if (MouseEvent.MOUSE_RELEASED == e.getID() && !isSelectionEmpty() && !e.isShiftDown() && !e.isControlDown() &&
!e.isMetaDown() && !e.isPopupTrigger()) {
if (isOverSelection(e.getPoint())) {
clearSelection();
final TreePath path = getPathForLocation(e.getPoint().x, e.getPoint().y);
if (path != null) {
setSelectionPath(path);
e.consume();
}
}
}
super.processMouseEvent(e);
}
public boolean isOverSelection(final Point point) {
return TreeUtil.isOverSelection(this, point);
}
public void dropSelectionButUnderPoint(final Point point) {
TreeUtil.dropSelectionButUnderPoint(this, point);
}
}
| |
package de.micromata.opengis.kml.v_2_2_0;
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.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import de.micromata.opengis.kml.v_2_2_0.annotations.Obvious;
import de.micromata.opengis.kml.v_2_2_0.atom.Author;
import de.micromata.opengis.kml.v_2_2_0.xal.AddressDetails;
/**
* <Overlay>
* <p>
* This is an abstract element and cannot be used directly in a KML file. <Overlay>
* is the base type for image overlays drawn on the planet surface or on the screen.
* <Icon> specifies the image to use and can be configured to reload images based on
* a timer or by camera changes. This element also includes specifications for stacking
* order of multiple overlays and for adding color and transparency values to the base
* image.
* </p>
*
* Syntax:
* <pre><!-- abstract element; do not create -->
* <strong><!-- <em>Overlay</em> id="ID" --></strong> <!-- GroundOverlay,ScreenOverlay -->
* <!-- inherited from <em>Feature</em> element -->
* <name><em>...</em></name> <!-- string -->
* <visibility>1</visibility> <!-- boolean -->
* <open>0</open> <!-- boolean -->
* <span><atom:author>...<atom:author> <!-- xmlns:atom -->
* <atom:link>...</atom:link></span><span> <!-- xmlns:atom --></span>
* <address><em>...</em></address> <!-- string -->
* <xal:AddressDetails>...</xal:AddressDetails> <!-- xmlns:xal --><br> <phoneNumber>...</phoneNumber> <!-- string --><br> <Snippet maxLines="2"><em>...</em></Snippet> <!-- string -->
* <description><em>...</em></description> <!-- string -->
* <span><em><AbstractView>...</AbstractView></em> <!-- Camera <em>or</em> LookAt --></span>
* <<em>TimePrimitive</em>>...</<em>TimePrimitive</em>>
* <styleUrl><em>...</em></styleUrl> <!-- anyURI -->
* <<em>StyleSelector>...</StyleSelector></em>
* <Region>...</Region>
* <span><Metadata>...</Metadata> <!-- deprecated in KML 2.2 -->
* <ExtendedData>...</ExtendedData> <!-- new in KML 2.2 --></span>
*
* <!-- specific to <em>Overlay</em> -->
* <color>ffffffff</color> <!-- kml:color -->
* <drawOrder>0</drawOrder> <!-- int -->
* <Icon>
* <href>...</href>
* </Icon>
* <strong><!-- /<em>Overlay --</em>></strong></pre>
*
* Extends:
* @see: <Feature>
*
* Extended By:
* @see: <GroundOverlay>
* @see: <PhotoOverlay
* @see: <ScreenOverlay>
* @see: Syntax
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AbstractOverlayType", propOrder = {
"color",
"drawOrder",
"icon",
"overlaySimpleExtension",
"overlayObjectExtension"
})
@XmlSeeAlso({
ScreenOverlay.class,
PhotoOverlay.class,
GroundOverlay.class
})
public abstract class Overlay
extends Feature
implements Cloneable
{
/**
* <color>
* <p>
* Color and opacity (alpha) values are expressed in hexadecimal notation. The range
* of values for any one color is 0 to 255 (00 to ff). For alpha, 00 is fully transparent
* and ff is fully opaque. The order of expression is aabbggrr, where aa=alpha (00
* to ff); bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff). For example,
* if you want to apply a blue color with 50 percent opacity to an overlay, you would
* specify the following: <color>7fff0000</color>, where alpha=0x7f, blue=0xff, green=0x00,
* and red=0x00.
* </p>
* <p>
* Color values are expressed in hexadecimal notation, including opacity (alpha) values.
* The order of expression is alpha, blue, green, red (aabbggrr). The range of values
* for any one color is 0 to 255 (00 to ff). For opacity, 00 is fully transparent and
* ff is fully opaque. For example, if you want to apply a blue color with 50 percent
* opacity to an overlay, you would specify the following: <color>7fff0000</color>
* </p>
* <p>
* Note: The <geomColor> element has been deprecated. Use <color> instead.
* </p>
*
*
*
*/
@XmlElement(defaultValue = "ffffffff")
protected String color;
/**
* <draworder>
* <p>
* This element defines the stacking order for the images in overlapping overlays.
* Overlays with higher <drawOrder> values are drawn on top of overlays with lower
* <drawOrder> values.
* </p>
*
*
*
*/
@XmlElement(defaultValue = "0")
protected int drawOrder;
/**
* <icon> see also <icon>.
* <p>
* <Icon> <href>Sunset.jpg</href> </Icon>
* </p>
* <p>
* A custom Icon. In <IconStyle>, the only child element of <Icon> is <href>: <href>:
* An HTTP address or a local file specification used to load an icon.
* </p>
* <p>
* Defines an image associated with an Icon style or overlay. <Icon> has the same child
* elements as <Link>. The required <href> child element defines the location of the
* image to be used as the overlay or as the icon for the placemark. This location
* can either be on a local file system or a remote web server.
* </p>
* <p>
* Defines the image associated with the Overlay. The <href> element defines the location
* of the image to be used as the Overlay. This location can be either on a local file
* system or on a web server. If this element is omitted or contains no <href>, a rectangle
* is drawn using the color and size defined by the ground or screen overlay. <Icon>
* <href>icon.jpg</href> </Icon>
* </p>
*
* Syntax:
* <pre><strong><Icon id="ID"></strong>
* <!-- specific to Icon -->
* <href><em>...</em></href> <!-- anyURI -->
* <refreshMode>onChange</refreshMode>
* <!-- kml:refreshModeEnum: onChange, onInterval, <em>or</em> onExpire -->
* <refreshInterval>4</refreshInterval> <!-- float -->
* <viewRefreshMode>never</viewRefreshMode>
* <!-- kml:viewRefreshModeEnum: never, onStop, onRequest, onRegion -->
* <viewRefreshTime>4</viewRefreshTime> <!-- float -->
* <viewBoundScale>1</viewBoundScale> <!-- float -->
* <viewFormat>...</viewFormat> <!-- string -->
* <httpQuery>...</httpQuery> <!-- string -->
* <strong></Icon></strong></pre>
*
* Contained By:
* @see: <GroundOverlay>
* @see: <IconStyle>
* @see: <ScreenOverlay>
*
*
*
*/
@XmlElement(name = "Icon")
protected Icon icon;
@XmlElement(name = "AbstractOverlaySimpleExtensionGroup")
@XmlSchemaType(name = "anySimpleType")
protected List<Object> overlaySimpleExtension;
/**
* <Object>
* <p>
* This is an abstract base class and cannot be used directly in a KML file. It provides
* the id attribute, which allows unique identification of a KML element, and the targetId
* attribute, which is used to reference objects that have already been loaded into
* Google Earth. The id attribute must be assigned if the <Update> mechanism is to
* be used.
* </p>
*
* Syntax:
* <pre><!-- abstract element; do not create --><strong>
* <!-- <em>Object</em> id="ID" targetId="NCName" -->
* <!-- /<em>Object</em>> --></strong></pre>
*
*
*
*/
@XmlElement(name = "AbstractOverlayObjectExtensionGroup")
protected List<AbstractObject> overlayObjectExtension;
public Overlay() {
super();
}
/**
* @see color
*
* @return
* possible object is
* {@link String}
*
*/
public String getColor() {
return color;
}
/**
* @see color
*
* @param value
* allowed object is
* {@link String}
*
*/
public void setColor(String value) {
this.color = value;
}
/**
* @see drawOrder
*
* @return
* possible object is
* {@link Integer}
*
*/
public int getDrawOrder() {
return drawOrder;
}
/**
* @see drawOrder
*
* @param value
* allowed object is
* {@link Integer}
*
*/
public void setDrawOrder(int value) {
this.drawOrder = value;
}
/**
* @see icon
*
* @return
* possible object is
* {@link de.micromata.opengis.kml.v_2_2_0.Link}
*
*/
public Icon getIcon() {
return icon;
}
/**
* @see icon
*
* @param value
* allowed object is
* {@link de.micromata.opengis.kml.v_2_2_0.Link}
*
*/
public void setIcon(Icon value) {
this.icon = value;
}
/**
* @see overlaySimpleExtension
*
*/
public List<Object> getOverlaySimpleExtension() {
if (overlaySimpleExtension == null) {
overlaySimpleExtension = new ArrayList<Object>();
}
return this.overlaySimpleExtension;
}
/**
* @see overlayObjectExtension
*
*/
public List<AbstractObject> getOverlayObjectExtension() {
if (overlayObjectExtension == null) {
overlayObjectExtension = new ArrayList<AbstractObject>();
}
return this.overlayObjectExtension;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = ((prime*result)+((color == null)? 0 :color.hashCode()));
result = ((prime*result)+ drawOrder);
result = ((prime*result)+((icon == null)? 0 :icon.hashCode()));
result = ((prime*result)+((overlaySimpleExtension == null)? 0 :overlaySimpleExtension.hashCode()));
result = ((prime*result)+((overlayObjectExtension == null)? 0 :overlayObjectExtension.hashCode()));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (super.equals(obj) == false) {
return false;
}
if ((obj instanceof Overlay) == false) {
return false;
}
Overlay other = ((Overlay) obj);
if (color == null) {
if (other.color!= null) {
return false;
}
} else {
if (color.equals(other.color) == false) {
return false;
}
}
if (drawOrder!= other.drawOrder) {
return false;
}
if (icon == null) {
if (other.icon!= null) {
return false;
}
} else {
if (icon.equals(other.icon) == false) {
return false;
}
}
if (overlaySimpleExtension == null) {
if (other.overlaySimpleExtension!= null) {
return false;
}
} else {
if (overlaySimpleExtension.equals(other.overlaySimpleExtension) == false) {
return false;
}
}
if (overlayObjectExtension == null) {
if (other.overlayObjectExtension!= null) {
return false;
}
} else {
if (overlayObjectExtension.equals(other.overlayObjectExtension) == false) {
return false;
}
}
return true;
}
/**
* Creates a new instance of {@link Icon} and set it to icon.
*
* This method is a short version for:
* <code>
* Icon icon = new Icon();
* this.setIcon(icon); </code>
*
*
*/
public Icon createAndSetIcon() {
Icon newValue = new Icon();
this.setIcon(newValue);
return newValue;
}
/**
* @see overlaySimpleExtension
*
* @param overlaySimpleExtension
*/
public void setOverlaySimpleExtension(final List<Object> overlaySimpleExtension) {
this.overlaySimpleExtension = overlaySimpleExtension;
}
/**
* add a value to the overlaySimpleExtension property collection
*
* @param overlaySimpleExtension
* Objects of the following type are allowed in the list: {@link Object}
* @return
* <tt>true</tt> (as general contract of <tt>Collection.add</tt>).
*/
public Overlay addToOverlaySimpleExtension(final Object overlaySimpleExtension) {
this.getOverlaySimpleExtension().add(overlaySimpleExtension);
return this;
}
/**
* @see overlayObjectExtension
*
* @param overlayObjectExtension
*/
public void setOverlayObjectExtension(final List<AbstractObject> overlayObjectExtension) {
this.overlayObjectExtension = overlayObjectExtension;
}
/**
* add a value to the overlayObjectExtension property collection
*
* @param overlayObjectExtension
* Objects of the following type are allowed in the list: {@link AbstractObject}
* @return
* <tt>true</tt> (as general contract of <tt>Collection.add</tt>).
*/
public Overlay addToOverlayObjectExtension(final AbstractObject overlayObjectExtension) {
this.getOverlayObjectExtension().add(overlayObjectExtension);
return this;
}
/**
* @see objectSimpleExtension
*
*/
@Obvious
@Override
public void setObjectSimpleExtension(final List<Object> objectSimpleExtension) {
super.setObjectSimpleExtension(objectSimpleExtension);
}
@Obvious
@Override
public Overlay addToObjectSimpleExtension(final Object objectSimpleExtension) {
super.getObjectSimpleExtension().add(objectSimpleExtension);
return this;
}
/**
* @see styleSelector
*
*/
@Obvious
@Override
public void setStyleSelector(final List<StyleSelector> styleSelector) {
super.setStyleSelector(styleSelector);
}
@Obvious
@Override
public Overlay addToStyleSelector(final StyleSelector styleSelector) {
super.getStyleSelector().add(styleSelector);
return this;
}
/**
* @see featureSimpleExtension
*
*/
@Obvious
@Override
public void setFeatureSimpleExtension(final List<Object> featureSimpleExtension) {
super.setFeatureSimpleExtension(featureSimpleExtension);
}
@Obvious
@Override
public Overlay addToFeatureSimpleExtension(final Object featureSimpleExtension) {
super.getFeatureSimpleExtension().add(featureSimpleExtension);
return this;
}
/**
* @see featureObjectExtension
*
*/
@Obvious
@Override
public void setFeatureObjectExtension(final List<AbstractObject> featureObjectExtension) {
super.setFeatureObjectExtension(featureObjectExtension);
}
@Obvious
@Override
public Overlay addToFeatureObjectExtension(final AbstractObject featureObjectExtension) {
super.getFeatureObjectExtension().add(featureObjectExtension);
return this;
}
/**
* fluent setter
* @see #setColor(String)
*
* @param color
* required parameter
*/
public Overlay withColor(final String color) {
this.setColor(color);
return this;
}
/**
* fluent setter
* @see #setDrawOrder(int)
*
* @param drawOrder
* required parameter
*/
public Overlay withDrawOrder(final int drawOrder) {
this.setDrawOrder(drawOrder);
return this;
}
/**
* fluent setter
* @see #setIcon(Icon)
*
* @param icon
* required parameter
*/
public Overlay withIcon(final Icon icon) {
this.setIcon(icon);
return this;
}
/**
* fluent setter
* @see #setOverlaySimpleExtension(List<Object>)
*
* @param overlaySimpleExtension
* required parameter
*/
public Overlay withOverlaySimpleExtension(final List<Object> overlaySimpleExtension) {
this.setOverlaySimpleExtension(overlaySimpleExtension);
return this;
}
/**
* fluent setter
* @see #setOverlayObjectExtension(List<AbstractObject>)
*
* @param overlayObjectExtension
* required parameter
*/
public Overlay withOverlayObjectExtension(final List<AbstractObject> overlayObjectExtension) {
this.setOverlayObjectExtension(overlayObjectExtension);
return this;
}
@Obvious
@Override
public Overlay withObjectSimpleExtension(final List<Object> objectSimpleExtension) {
super.withObjectSimpleExtension(objectSimpleExtension);
return this;
}
@Obvious
@Override
public Overlay withId(final String id) {
super.withId(id);
return this;
}
@Obvious
@Override
public Overlay withTargetId(final String targetId) {
super.withTargetId(targetId);
return this;
}
@Obvious
@Override
public Overlay withName(final String name) {
super.withName(name);
return this;
}
@Obvious
@Override
public Overlay withVisibility(final Boolean visibility) {
super.withVisibility(visibility);
return this;
}
@Obvious
@Override
public Overlay withOpen(final Boolean open) {
super.withOpen(open);
return this;
}
@Obvious
@Override
public Overlay withAtomAuthor(final Author atomAuthor) {
super.withAtomAuthor(atomAuthor);
return this;
}
@Obvious
@Override
public Overlay withAtomLink(final de.micromata.opengis.kml.v_2_2_0.atom.Link atomLink) {
super.withAtomLink(atomLink);
return this;
}
@Obvious
@Override
public Overlay withAddress(final String address) {
super.withAddress(address);
return this;
}
@Obvious
@Override
public Overlay withXalAddressDetails(final AddressDetails xalAddressDetails) {
super.withXalAddressDetails(xalAddressDetails);
return this;
}
@Obvious
@Override
public Overlay withPhoneNumber(final String phoneNumber) {
super.withPhoneNumber(phoneNumber);
return this;
}
@Obvious
@Override
public Overlay withSnippet(final Snippet snippet) {
super.withSnippet(snippet);
return this;
}
@Obvious
@Override
public Overlay withSnippetd(final String snippetd) {
super.withSnippetd(snippetd);
return this;
}
@Obvious
@Override
public Overlay withDescription(final String description) {
super.withDescription(description);
return this;
}
@Obvious
@Override
public Overlay withAbstractView(final AbstractView abstractView) {
super.withAbstractView(abstractView);
return this;
}
@Obvious
@Override
public Overlay withTimePrimitive(final TimePrimitive timePrimitive) {
super.withTimePrimitive(timePrimitive);
return this;
}
@Obvious
@Override
public Overlay withStyleUrl(final String styleUrl) {
super.withStyleUrl(styleUrl);
return this;
}
@Obvious
@Override
public Overlay withStyleSelector(final List<StyleSelector> styleSelector) {
super.withStyleSelector(styleSelector);
return this;
}
@Obvious
@Override
public Overlay withRegion(final Region region) {
super.withRegion(region);
return this;
}
@Obvious
@Override
public Overlay withMetadata(final Metadata metadata) {
super.withMetadata(metadata);
return this;
}
@Obvious
@Override
public Overlay withExtendedData(final ExtendedData extendedData) {
super.withExtendedData(extendedData);
return this;
}
@Obvious
@Override
public Overlay withFeatureSimpleExtension(final List<Object> featureSimpleExtension) {
super.withFeatureSimpleExtension(featureSimpleExtension);
return this;
}
@Obvious
@Override
public Overlay withFeatureObjectExtension(final List<AbstractObject> featureObjectExtension) {
super.withFeatureObjectExtension(featureObjectExtension);
return this;
}
@Override
public Overlay clone() {
Overlay copy;
copy = ((Overlay) super.clone());
copy.icon = ((icon == null)?null:((Icon) icon.clone()));
copy.overlaySimpleExtension = new ArrayList<Object>((getOverlaySimpleExtension().size()));
for (Object iter: overlaySimpleExtension) {
copy.overlaySimpleExtension.add(iter);
}
copy.overlayObjectExtension = new ArrayList<AbstractObject>((getOverlayObjectExtension().size()));
for (AbstractObject iter: overlayObjectExtension) {
copy.overlayObjectExtension.add(iter.clone());
}
return copy;
}
}
| |
/*******************************************************************************
* Copyright 2020 See AUTHORS file
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.mini2Dx.core.collision;
import org.mini2Dx.core.collision.util.*;
import org.mini2Dx.core.util.InterpolationTracker;
import org.mini2Dx.gdx.math.Vector2;
import org.mini2Dx.gdx.utils.Queue;
/**
* Provides pooled collision classes
*/
public class Collisions {
/**
* Default pool size. Modify this value before launching the game to increase the default pool sizes.
*/
public static int DEFAULT_POOL_SIZE = 256;
final Queue<CollisionBox> collisionBoxes = new Queue<CollisionBox>(DEFAULT_POOL_SIZE * 2);
final Queue<CollisionCircle> collisionCircles = new Queue<CollisionCircle>(DEFAULT_POOL_SIZE * 2);
final Queue<CollisionPoint> collisionPoints = new Queue<CollisionPoint>(DEFAULT_POOL_SIZE * 2);
final Queue<CollisionPolygon> collisionPolygons = new Queue<CollisionPolygon>(DEFAULT_POOL_SIZE * 2);
final Queue<QuadTreeAwareCollisionBox> quadTreeAwareCollisionBoxes = new Queue<QuadTreeAwareCollisionBox>(DEFAULT_POOL_SIZE * 2);
final Queue<QuadTreeAwareCollisionCircle> quadTreeAwareCollisionCircles = new Queue<QuadTreeAwareCollisionCircle>(DEFAULT_POOL_SIZE * 2);
final Queue<QuadTreeAwareCollisionPoint> quadTreeAwareCollisionPoints = new Queue<QuadTreeAwareCollisionPoint>(DEFAULT_POOL_SIZE * 2);
final Queue<QuadTreeAwareCollisionPolygon> quadTreeAwareCollisionPolygons = new Queue<QuadTreeAwareCollisionPolygon>(DEFAULT_POOL_SIZE * 2);
final Queue<StaticCollisionBox> staticCollisionBoxes = new Queue<StaticCollisionBox>(DEFAULT_POOL_SIZE * 2);
final Queue<StaticCollisionCircle> staticCollisionCircles = new Queue<StaticCollisionCircle>(DEFAULT_POOL_SIZE * 2);
final Queue<StaticCollisionPoint> staticCollisionPoints = new Queue<StaticCollisionPoint>(DEFAULT_POOL_SIZE * 2);
final Queue<StaticCollisionPolygon> staticCollisionPolygons = new Queue<StaticCollisionPolygon>(DEFAULT_POOL_SIZE * 2);
final Queue<QuadTreeAwareStaticCollisionBox> quadTreeAwareStaticCollisionBoxes = new Queue<QuadTreeAwareStaticCollisionBox>(DEFAULT_POOL_SIZE * 2);
final Queue<QuadTreeAwareStaticCollisionCircle> quadTreeAwareStaticCollisionCircles = new Queue<QuadTreeAwareStaticCollisionCircle>(DEFAULT_POOL_SIZE * 2);
final Queue<QuadTreeAwareStaticCollisionPoint> quadTreeAwareStaticCollisionPoints = new Queue<QuadTreeAwareStaticCollisionPoint>(DEFAULT_POOL_SIZE * 2);
final Queue<QuadTreeAwareStaticCollisionPolygon> quadTreeAwareStaticCollisionPolygons = new Queue<QuadTreeAwareStaticCollisionPolygon>(DEFAULT_POOL_SIZE * 2);
private boolean initialised = false;
public Collisions() {
super();
}
/**
* Initialises the pool
*/
public synchronized void init() {
if(initialised) {
return;
}
for(int i = 0; i < DEFAULT_POOL_SIZE; i++) {
collisionBoxes.addLast(new CollisionBox(CollisionIdSequence.nextId(), this));
collisionBoxes.removeLast().dispose();
collisionCircles.addLast(new CollisionCircle(CollisionIdSequence.nextId(),this));
collisionCircles.removeLast().dispose();
collisionPoints.addLast(new CollisionPoint(CollisionIdSequence.nextId(),this));
collisionPoints.removeLast().dispose();
quadTreeAwareCollisionBoxes.addLast(new QuadTreeAwareCollisionBox(CollisionIdSequence.nextId(),this));
quadTreeAwareCollisionBoxes.removeLast().dispose();
quadTreeAwareCollisionCircles.addLast(new QuadTreeAwareCollisionCircle(CollisionIdSequence.nextId(),this));
quadTreeAwareCollisionCircles.removeLast().dispose();
quadTreeAwareCollisionPoints.addLast(new QuadTreeAwareCollisionPoint(CollisionIdSequence.nextId(),this));
quadTreeAwareCollisionPoints.removeLast().dispose();
staticCollisionBoxes.addLast(new StaticCollisionBox(CollisionIdSequence.nextId(),this));
staticCollisionBoxes.removeLast().dispose();
staticCollisionCircles.addLast(new StaticCollisionCircle(CollisionIdSequence.nextId(),this));
staticCollisionCircles.removeLast().dispose();
staticCollisionPoints.addLast(new StaticCollisionPoint(CollisionIdSequence.nextId(),this));
staticCollisionPoints.removeLast().dispose();
quadTreeAwareStaticCollisionBoxes.addLast(new QuadTreeAwareStaticCollisionBox(CollisionIdSequence.nextId(),this));
quadTreeAwareStaticCollisionBoxes.removeLast().dispose();
quadTreeAwareStaticCollisionCircles.addLast(new QuadTreeAwareStaticCollisionCircle(CollisionIdSequence.nextId(),this));
quadTreeAwareStaticCollisionCircles.removeLast().dispose();
quadTreeAwareStaticCollisionPoints.addLast(new QuadTreeAwareStaticCollisionPoint(CollisionIdSequence.nextId(),this));
quadTreeAwareStaticCollisionPoints.removeLast().dispose();
}
initialised = true;
}
public CollisionBox collisionBox() {
return collisionBox(CollisionIdSequence.nextId());
}
public CollisionBox collisionBox(int id) {
return collisionBox(id, 0f, 0f, 1f, 1f);
}
public CollisionBox collisionBox(int id, float x, float y, float width, float height) {
init();
final CollisionBox result;
synchronized (collisionBoxes) {
if(collisionBoxes.size == 0) {
result = new CollisionBox(CollisionIdSequence.offset(id), this);
InterpolationTracker.deregister(result);
} else {
result = collisionBoxes.removeFirst();
}
}
result.init(id, x, y, width, height);
return result;
}
public CollisionCircle collisionCircle() {
return collisionCircle(CollisionIdSequence.nextId());
}
public CollisionCircle collisionCircle(int id) {
return collisionCircle(id, 0f, 0f, 1f);
}
public CollisionCircle collisionCircle(int id, float x, float y, float radius) {
init();
final CollisionCircle result;
synchronized (collisionCircles) {
if(collisionCircles.size == 0) {
result = new CollisionCircle(CollisionIdSequence.offset(id),this);
InterpolationTracker.deregister(result);
} else {
result = collisionCircles.removeFirst();
}
}
result.init(id, x, y, radius);
return result;
}
public CollisionPoint collisionPoint() {
return collisionPoint(CollisionIdSequence.nextId());
}
public CollisionPoint collisionPoint(int id) {
return collisionPoint(id, 0f, 0f);
}
public CollisionPoint collisionPoint(int id, float x, float y) {
init();
final CollisionPoint result;
synchronized (collisionPoints) {
if(collisionPoints.size == 0) {
result = new CollisionPoint(CollisionIdSequence.offset(id),this);
InterpolationTracker.deregister(result);
} else {
result = collisionPoints.removeFirst();
}
}
result.init(id, x, y);
return result;
}
public CollisionPolygon collisionPolygon(float [] vertices) {
return collisionPolygon(CollisionIdSequence.nextId(), vertices);
}
public CollisionPolygon collisionPolygon(int id, float [] vertices) {
init();
final CollisionPolygon result;
synchronized (collisionPolygons) {
if(collisionPolygons.size == 0) {
result = new CollisionPolygon(CollisionIdSequence.offset(id), this, vertices);
InterpolationTracker.deregister(result);
} else {
result = collisionPolygons.removeFirst();
}
}
result.init(id, vertices);
return result;
}
public CollisionPolygon collisionPolygon(Vector2[] vectors) {
return collisionPolygon(CollisionIdSequence.nextId(), vectors);
}
public CollisionPolygon collisionPolygon(int id, Vector2[] vectors) {
init();
final CollisionPolygon result;
synchronized (collisionPolygons) {
if(collisionPolygons.size == 0) {
result = new CollisionPolygon(CollisionIdSequence.offset(id), this, vectors);
InterpolationTracker.deregister(result);
} else {
result = collisionPolygons.removeFirst();
}
}
result.init(id, vectors);
return result;
}
public QuadTreeAwareCollisionBox quadTreeAwareCollisionBox() {
return quadTreeAwareCollisionBox(CollisionIdSequence.nextId());
}
public QuadTreeAwareCollisionBox quadTreeAwareCollisionBox(int id) {
return quadTreeAwareCollisionBox(id, 0f, 0f, 1f, 1f);
}
public QuadTreeAwareCollisionBox quadTreeAwareCollisionBox(int id, float x, float y, float width, float height) {
init();
final QuadTreeAwareCollisionBox result;
synchronized (quadTreeAwareCollisionBoxes) {
if(quadTreeAwareCollisionBoxes.size == 0) {
result = new QuadTreeAwareCollisionBox(CollisionIdSequence.offset(id), this);
InterpolationTracker.deregister(result);
} else {
result = quadTreeAwareCollisionBoxes.removeFirst();
}
}
result.init(id, x, y, width, height);
return result;
}
public QuadTreeAwareCollisionCircle quadTreeAwareCollisionCircle() {
return quadTreeAwareCollisionCircle(CollisionIdSequence.nextId());
}
public QuadTreeAwareCollisionCircle quadTreeAwareCollisionCircle(int id) {
return quadTreeAwareCollisionCircle(id, 0f, 0f, 1f);
}
public QuadTreeAwareCollisionCircle quadTreeAwareCollisionCircle(int id, float x, float y, float radius) {
init();
final QuadTreeAwareCollisionCircle result;
synchronized (quadTreeAwareCollisionCircles) {
if(quadTreeAwareCollisionCircles.size == 0) {
result = new QuadTreeAwareCollisionCircle(CollisionIdSequence.offset(id), this);
InterpolationTracker.deregister(result);
} else {
result = quadTreeAwareCollisionCircles.removeFirst();
}
}
result.init(id, x, y, radius);
return result;
}
public QuadTreeAwareCollisionPoint quadTreeAwareCollisionPoint() {
return quadTreeAwareCollisionPoint(CollisionIdSequence.nextId());
}
public QuadTreeAwareCollisionPoint quadTreeAwareCollisionPoint(int id) {
return quadTreeAwareCollisionPoint(id, 0f, 0f);
}
public QuadTreeAwareCollisionPoint quadTreeAwareCollisionPoint(int id, float x, float y) {
init();
final QuadTreeAwareCollisionPoint result;
synchronized (quadTreeAwareCollisionPoints) {
if(quadTreeAwareCollisionPoints.size == 0) {
result = new QuadTreeAwareCollisionPoint(CollisionIdSequence.offset(id), this);
InterpolationTracker.deregister(result);
} else {
result = quadTreeAwareCollisionPoints.removeFirst();
}
}
result.init(id, x, y);
return result;
}
public QuadTreeAwareCollisionPolygon quadTreeAwareCollisionPolygon(float [] vertices) {
return quadTreeAwareCollisionPolygon(CollisionIdSequence.nextId(), vertices);
}
public QuadTreeAwareCollisionPolygon quadTreeAwareCollisionPolygon(int id, float [] vertices) {
init();
final QuadTreeAwareCollisionPolygon result;
synchronized (quadTreeAwareCollisionPolygons) {
if(quadTreeAwareCollisionPolygons.size == 0) {
result = new QuadTreeAwareCollisionPolygon(CollisionIdSequence.offset(id), this, vertices);
InterpolationTracker.deregister(result);
} else {
result = quadTreeAwareCollisionPolygons.removeFirst();
}
}
result.init(id, vertices);
return result;
}
public QuadTreeAwareCollisionPolygon quadTreeAwareCollisionPolygon(Vector2[] vectors) {
return quadTreeAwareCollisionPolygon(CollisionIdSequence.nextId(), vectors);
}
public QuadTreeAwareCollisionPolygon quadTreeAwareCollisionPolygon(int id, Vector2[] vectors) {
init();
final QuadTreeAwareCollisionPolygon result;
synchronized (quadTreeAwareCollisionPolygons) {
if(quadTreeAwareCollisionPolygons.size == 0) {
result = new QuadTreeAwareCollisionPolygon(CollisionIdSequence.offset(id), this, vectors);
InterpolationTracker.deregister(result);
} else {
result = quadTreeAwareCollisionPolygons.removeFirst();
}
}
result.init(id, vectors);
return result;
}
public StaticCollisionBox staticCollisionBox() {
return staticCollisionBox(CollisionIdSequence.nextId());
}
public StaticCollisionBox staticCollisionBox(int id) {
return staticCollisionBox(id, 0f, 0f, 1f, 1f);
}
public StaticCollisionBox staticCollisionBox(int id, float x, float y, float width, float height) {
init();
final StaticCollisionBox result;
synchronized (staticCollisionBoxes) {
if(staticCollisionBoxes.size == 0) {
result = new StaticCollisionBox(CollisionIdSequence.offset(id), this);
} else {
result = staticCollisionBoxes.removeFirst();
}
}
result.init(id, x, y, width, height);
return result;
}
public StaticCollisionCircle staticCollisionCircle() {
return staticCollisionCircle(CollisionIdSequence.nextId());
}
public StaticCollisionCircle staticCollisionCircle(int id) {
return staticCollisionCircle(id, 0f, 0f, 1f);
}
public StaticCollisionCircle staticCollisionCircle(int id, float centerX, float centerY, float radius) {
init();
final StaticCollisionCircle result;
synchronized (staticCollisionCircles) {
if(staticCollisionCircles.size == 0) {
result = new StaticCollisionCircle(CollisionIdSequence.offset(id),this);
} else {
result = staticCollisionCircles.removeFirst();
}
}
result.init(id, centerX, centerY, radius);
return result;
}
public StaticCollisionPoint staticCollisionPoint() {
return staticCollisionPoint(CollisionIdSequence.nextId());
}
public StaticCollisionPoint staticCollisionPoint(int id) {
return staticCollisionPoint(id, 0f, 0f);
}
public StaticCollisionPoint staticCollisionPoint(int id, float x, float y) {
init();
final StaticCollisionPoint result;
synchronized (staticCollisionPoints) {
if(staticCollisionPoints.size == 0) {
result = new StaticCollisionPoint(CollisionIdSequence.offset(id), this);
} else {
result = staticCollisionPoints.removeFirst();
}
}
result.init(id, x, y);
return result;
}
public StaticCollisionPolygon staticCollisionPolygon(float [] vertices) {
return staticCollisionPolygon(CollisionIdSequence.nextId(), vertices);
}
public StaticCollisionPolygon staticCollisionPolygon(int id, float [] vertices) {
init();
final StaticCollisionPolygon result;
synchronized (staticCollisionPolygons) {
if(staticCollisionPolygons.size == 0) {
result = new StaticCollisionPolygon(CollisionIdSequence.offset(id), this, vertices);
} else {
result = staticCollisionPolygons.removeFirst();
}
}
result.init(id, vertices);
return result;
}
public StaticCollisionPolygon staticCollisionPolygon(Vector2[] vectors) {
return staticCollisionPolygon(CollisionIdSequence.nextId(), vectors);
}
public StaticCollisionPolygon staticCollisionPolygon(int id, Vector2[] vectors) {
init();
final StaticCollisionPolygon result;
synchronized (staticCollisionPolygons) {
if(staticCollisionPolygons.size == 0) {
result = new StaticCollisionPolygon(CollisionIdSequence.offset(id), this, vectors);
} else {
result = staticCollisionPolygons.removeFirst();
}
}
result.init(id, vectors);
return result;
}
public QuadTreeAwareStaticCollisionBox quadTreeAwareStaticCollisionBox() {
return quadTreeAwareStaticCollisionBox(CollisionIdSequence.nextId());
}
public QuadTreeAwareStaticCollisionBox quadTreeAwareStaticCollisionBox(int id) {
return quadTreeAwareStaticCollisionBox(id, 0f, 0f, 1f, 1f);
}
public QuadTreeAwareStaticCollisionBox quadTreeAwareStaticCollisionBox(int id, float x, float y, float width, float height) {
init();
final QuadTreeAwareStaticCollisionBox result;
synchronized (quadTreeAwareStaticCollisionBoxes) {
if(quadTreeAwareStaticCollisionBoxes.size == 0) {
result = new QuadTreeAwareStaticCollisionBox(CollisionIdSequence.offset(id), this);
} else {
result = quadTreeAwareStaticCollisionBoxes.removeFirst();
}
}
result.init(id, x, y, width, height);
return result;
}
public QuadTreeAwareStaticCollisionCircle quadTreeAwareStaticCollisionCircle() {
return quadTreeAwareStaticCollisionCircle(CollisionIdSequence.nextId());
}
public QuadTreeAwareStaticCollisionCircle quadTreeAwareStaticCollisionCircle(int id) {
return quadTreeAwareStaticCollisionCircle(id, 0f, 0f, 1f);
}
public QuadTreeAwareStaticCollisionCircle quadTreeAwareStaticCollisionCircle(int id, float centerX, float centerY, float radius) {
init();
final QuadTreeAwareStaticCollisionCircle result;
synchronized (quadTreeAwareStaticCollisionCircle()) {
if(quadTreeAwareStaticCollisionCircles.size == 0) {
result = new QuadTreeAwareStaticCollisionCircle(CollisionIdSequence.offset(id),this);
} else {
result = quadTreeAwareStaticCollisionCircles.removeFirst();
}
}
result.init(id, centerX, centerY, radius);
return result;
}
public QuadTreeAwareStaticCollisionPoint quadTreeAwareStaticCollisionPoint() {
return quadTreeAwareStaticCollisionPoint(CollisionIdSequence.nextId());
}
public QuadTreeAwareStaticCollisionPoint quadTreeAwareStaticCollisionPoint(int id) {
return quadTreeAwareStaticCollisionPoint(id, 0f, 0f);
}
public QuadTreeAwareStaticCollisionPoint quadTreeAwareStaticCollisionPoint(int id, float x, float y) {
init();
final QuadTreeAwareStaticCollisionPoint result;
synchronized (quadTreeAwareStaticCollisionPoints) {
if(quadTreeAwareStaticCollisionPoints.size == 0) {
result = new QuadTreeAwareStaticCollisionPoint(CollisionIdSequence.offset(id), this);
} else {
result = quadTreeAwareStaticCollisionPoints.removeFirst();
}
}
result.init(id, x, y);
return result;
}
public QuadTreeAwareStaticCollisionPolygon quadTreeAwareStaticCollisionPolygon(float [] vertices) {
return quadTreeAwareStaticCollisionPolygon(CollisionIdSequence.nextId(), vertices);
}
public QuadTreeAwareStaticCollisionPolygon quadTreeAwareStaticCollisionPolygon(int id, float [] vertices) {
init();
final QuadTreeAwareStaticCollisionPolygon result;
synchronized (quadTreeAwareStaticCollisionPolygons) {
if(quadTreeAwareStaticCollisionPolygons.size == 0) {
result = new QuadTreeAwareStaticCollisionPolygon(CollisionIdSequence.offset(id), this, vertices);
} else {
result = quadTreeAwareStaticCollisionPolygons.removeFirst();
}
}
result.init(id, vertices);
return result;
}
public QuadTreeAwareStaticCollisionPolygon quadTreeAwareStaticCollisionPolygon(Vector2[] vectors) {
return quadTreeAwareStaticCollisionPolygon(CollisionIdSequence.nextId(), vectors);
}
public QuadTreeAwareStaticCollisionPolygon quadTreeAwareStaticCollisionPolygon(int id, Vector2[] vectors) {
init();
final QuadTreeAwareStaticCollisionPolygon result;
synchronized (quadTreeAwareStaticCollisionPolygons) {
if(quadTreeAwareStaticCollisionPolygons.size == 0) {
result = new QuadTreeAwareStaticCollisionPolygon(CollisionIdSequence.offset(id), this, vectors);
} else {
result = quadTreeAwareStaticCollisionPolygons.removeFirst();
}
}
result.init(id, vectors);
return result;
}
public void release(CollisionBox collisionBox) {
synchronized (collisionBoxes) {
collisionBoxes.addLast(collisionBox);
}
}
public void release(CollisionCircle collisionCircle) {
synchronized (collisionCircles) {
collisionCircles.addLast(collisionCircle);
}
}
public void release(CollisionPoint collisionPoint) {
synchronized (collisionPoints) {
collisionPoints.addLast(collisionPoint);
}
}
public void release(CollisionPolygon collisionPolygon) {
synchronized (collisionPolygons) {
collisionPolygons.addLast(collisionPolygon);
}
}
public void release(QuadTreeAwareCollisionBox collisionBox) {
synchronized (quadTreeAwareCollisionBoxes) {
quadTreeAwareCollisionBoxes.addLast(collisionBox);
}
}
public void release(QuadTreeAwareCollisionCircle collisionCircle) {
synchronized (quadTreeAwareCollisionCircles) {
quadTreeAwareCollisionCircles.addLast(collisionCircle);
}
}
public void release(QuadTreeAwareCollisionPoint collisionPoint) {
synchronized (quadTreeAwareCollisionPoints) {
quadTreeAwareCollisionPoints.addLast(collisionPoint);
}
}
public void release(QuadTreeAwareCollisionPolygon collisionPolygon) {
synchronized (quadTreeAwareCollisionPolygons) {
quadTreeAwareCollisionPolygons.addLast(collisionPolygon);
}
}
public void release(StaticCollisionBox collisionBox) {
synchronized (staticCollisionBoxes) {
staticCollisionBoxes.addLast(collisionBox);
}
}
public void release(StaticCollisionCircle collisionCircle) {
synchronized (staticCollisionCircles) {
staticCollisionCircles.addLast(collisionCircle);
}
}
public void release(StaticCollisionPoint collisionPoint) {
synchronized (staticCollisionPoints) {
staticCollisionPoints.addLast(collisionPoint);
}
}
public void release(StaticCollisionPolygon collisionPolygon) {
synchronized (staticCollisionPolygons) {
staticCollisionPolygons.addLast(collisionPolygon);
}
}
public void release(QuadTreeAwareStaticCollisionBox collisionBox) {
synchronized (quadTreeAwareStaticCollisionBoxes) {
quadTreeAwareStaticCollisionBoxes.addLast(collisionBox);
}
}
public void release(QuadTreeAwareStaticCollisionCircle collisionCircle) {
synchronized (quadTreeAwareStaticCollisionCircles) {
quadTreeAwareStaticCollisionCircles.addLast(collisionCircle);
}
}
public void release(QuadTreeAwareStaticCollisionPoint collisionPoint) {
synchronized (quadTreeAwareStaticCollisionPoints) {
quadTreeAwareStaticCollisionPoints.addLast(collisionPoint);
}
}
public void release(QuadTreeAwareStaticCollisionPolygon collisionPolygon) {
synchronized (quadTreeAwareStaticCollisionPolygons) {
quadTreeAwareStaticCollisionPolygons.addLast(collisionPolygon);
}
}
public int getTotalCollisionBoxesAvailable() {
init();
synchronized (collisionBoxes) {
return collisionBoxes.size;
}
}
public int getTotalCollisionCirclesAvailable() {
init();
synchronized (collisionCircles) {
return collisionCircles.size;
}
}
public int getTotalCollisionPointsAvailable() {
init();
synchronized (collisionPoints) {
return collisionPoints.size;
}
}
public int getTotalCollisionPolygonsAvailable() {
init();
synchronized (collisionPolygons) {
return collisionPolygons.size;
}
}
public int getTotalQuadTreeAwareCollisionBoxesAvailable() {
init();
synchronized (quadTreeAwareCollisionBoxes) {
return quadTreeAwareCollisionBoxes.size;
}
}
public int getTotalQuadTreeAwareCollisionCirclesAvailable() {
init();
synchronized (quadTreeAwareCollisionCircles) {
return quadTreeAwareCollisionCircles.size;
}
}
public int getTotalQuadTreeAwareCollisionPointsAvailable() {
init();
synchronized (quadTreeAwareCollisionPoints) {
return quadTreeAwareCollisionPoints.size;
}
}
public int getTotalQuadTreeAwareCollisionPolygonsAvailable() {
init();
synchronized (quadTreeAwareCollisionPolygons) {
return quadTreeAwareCollisionPolygons.size;
}
}
public int getTotalStaticCollisionBoxesAvailable() {
init();
synchronized (staticCollisionBoxes) {
return staticCollisionBoxes.size;
}
}
public int getTotalStaticCollisionCirclesAvailable() {
init();
synchronized (staticCollisionCircles) {
return staticCollisionCircles.size;
}
}
public int getTotalStaticCollisionPointsAvailable() {
init();
synchronized (staticCollisionPoints) {
return staticCollisionPoints.size;
}
}
public int getTotalStaticCollisionPolygonsAvailable() {
init();
synchronized (staticCollisionPolygons) {
return staticCollisionPolygons.size;
}
}
public int getTotalQuadTreeAwareStaticCollisionBoxesAvailable() {
init();
synchronized (quadTreeAwareStaticCollisionBoxes) {
return quadTreeAwareStaticCollisionBoxes.size;
}
}
public int getTotalQuadTreeAwareStaticCollisionCirclesAvailable() {
init();
synchronized (quadTreeAwareStaticCollisionCircles) {
return quadTreeAwareStaticCollisionCircles.size;
}
}
public int getTotalQuadTreeAwareStaticCollisionPointsAvailable() {
init();
synchronized (quadTreeAwareStaticCollisionPoints) {
return quadTreeAwareStaticCollisionPoints.size;
}
}
public int getTotalQuadTreeAwareStaticCollisionPolygonsAvailable() {
init();
synchronized (quadTreeAwareStaticCollisionPolygons) {
return quadTreeAwareStaticCollisionPolygons.size;
}
}
/**
* Warms up CollisionBox pool to specified size
* @param poolSize The amount of CollisionBox instances in the pool
*/
public void warmupCollisionBoxes(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(collisionBoxes) {
collisionBoxes.addLast(new CollisionBox(CollisionIdSequence.nextId(), this));
collisionBoxes.removeLast().dispose();
}
}
}
/**
* Warms up CollisionCircle pool to specified size
* @param poolSize The amount of CollisionCircle instances in the pool
*/
public void warmupCollisionCircles(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(collisionCircles) {
collisionCircles.addLast(new CollisionCircle(CollisionIdSequence.nextId(),this));
collisionCircles.removeLast().dispose();
}
}
}
/**
* Warms up CollisionPoint pool to specified size
* @param poolSize The amount of CollisionPoint instances in the pool
*/
public void warmupCollisionPoints(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(collisionPoints) {
collisionPoints.addLast(new CollisionPoint(CollisionIdSequence.nextId(),this));
collisionPoints.removeLast().dispose();
}
}
}
/**
* Warms up StaticCollisionBox pool to specified size
* @param poolSize The amount of StaticCollisionBox instances in the pool
*/
public void warmupStaticCollisionBoxes(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(staticCollisionBoxes) {
staticCollisionBoxes.addLast(new StaticCollisionBox(CollisionIdSequence.nextId(),this));
staticCollisionBoxes.removeLast().dispose();
}
}
}
/**
* Warms up StaticCollisionCircle pool to specified size
* @param poolSize The amount of StaticCollisionCircle instances in the pool
*/
public void warmupStaticCollisionCircles(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(staticCollisionCircles) {
staticCollisionCircles.addLast(new StaticCollisionCircle(CollisionIdSequence.nextId(),this));
staticCollisionCircles.removeLast().dispose();
}
}
}
/**
* Warms up StaticCollisionPoint pool to specified size
* @param poolSize The amount of StaticCollisionPoint instances in the pool
*/
public void warmupStaticCollisionPoints(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(staticCollisionPoints) {
staticCollisionPoints.addLast(new StaticCollisionPoint(CollisionIdSequence.nextId(),this));
staticCollisionPoints.removeLast().dispose();
}
}
}
/**
* Warms up QuadTreeAwareCollisionBox pool to specified size
* @param poolSize The amount of QuadTreeAwareCollisionBox instances in the pool
*/
public void warmupQuadTreeAwareCollisionBoxes(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(quadTreeAwareCollisionBoxes) {
quadTreeAwareCollisionBoxes.addLast(new QuadTreeAwareCollisionBox(CollisionIdSequence.nextId(),this));
quadTreeAwareCollisionBoxes.removeLast().dispose();
}
}
}
/**
* Warms up QuadTreeAwareCollisionCircle pool to specified size
* @param poolSize The amount of QuadTreeAwareCollisionCircle instances in the pool
*/
public void warmupQuadTreeAwareCollisionCircles(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(quadTreeAwareCollisionCircles) {
quadTreeAwareCollisionCircles.addLast(new QuadTreeAwareCollisionCircle(CollisionIdSequence.nextId(),this));
quadTreeAwareCollisionCircles.removeLast().dispose();
}
}
}
/**
* Warms up QuadTreeAwareCollisionPoint pool to specified size
* @param poolSize The amount of QuadTreeAwareCollisionPoint instances in the pool
*/
public void warmupQuadTreeAwareCollisionPoints(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(quadTreeAwareCollisionPoints) {
quadTreeAwareCollisionPoints.addLast(new QuadTreeAwareCollisionPoint(CollisionIdSequence.nextId(),this));
quadTreeAwareCollisionPoints.removeLast().dispose();
}
}
}
/**
* Warms up QuadTreeAwareStaticCollisionBox pool to specified size
* @param poolSize The amount of QuadTreeAwareStaticCollisionBox instances in the pool
*/
public void warmupQuadTreeAwareStaticCollisionBoxes(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(quadTreeAwareStaticCollisionBoxes) {
quadTreeAwareStaticCollisionBoxes.addLast(new QuadTreeAwareStaticCollisionBox(CollisionIdSequence.nextId(),this));
quadTreeAwareStaticCollisionBoxes.removeLast().dispose();
}
}
}
/**
* Warms up QuadTreeAwareStaticCollisionCircle pool to specified size
* @param poolSize The amount of QuadTreeAwareStaticCollisionCircle instances in the pool
*/
public void warmupQuadTreeAwareStaticCollisionCircles(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(quadTreeAwareStaticCollisionCircles) {
quadTreeAwareStaticCollisionCircles.addLast(new QuadTreeAwareStaticCollisionCircle(CollisionIdSequence.nextId(),this));
quadTreeAwareStaticCollisionCircles.removeLast().dispose();
}
}
}
/**
* Warms up QuadTreeAwareStaticCollisionPoint pool to specified size
* @param poolSize The amount of QuadTreeAwareStaticCollisionPoint instances in the pool
*/
public void warmupQuadTreeAwareStaticCollisionPoints(int poolSize) {
for(int i = 0; i < poolSize; i++) {
synchronized(quadTreeAwareStaticCollisionPoints) {
quadTreeAwareStaticCollisionPoints.addLast(new QuadTreeAwareStaticCollisionPoint(CollisionIdSequence.nextId(),this));
quadTreeAwareStaticCollisionPoints.removeLast().dispose();
}
}
}
}
| |
/*
* 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.ignite.jdbc;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.ConnectorConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
/**
* Statement test.
*/
public class JdbcStatementSelfTest extends GridCommonAbstractTest {
/** IP finder. */
private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
/** URL. */
private static final String URL = "jdbc:ignite://127.0.0.1/";
/** SQL query. */
private static final String SQL = "select * from Person where age > 30";
/** Connection. */
private Connection conn;
/** Statement. */
private Statement stmt;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
CacheConfiguration<?,?> cache = defaultCacheConfiguration();
cache.setCacheMode(PARTITIONED);
cache.setBackups(1);
cache.setWriteSynchronizationMode(FULL_SYNC);
cache.setIndexedTypes(
String.class, Person.class
);
cfg.setCacheConfiguration(cache);
TcpDiscoverySpi disco = new TcpDiscoverySpi();
disco.setIpFinder(IP_FINDER);
cfg.setDiscoverySpi(disco);
cfg.setConnectorConfiguration(new ConnectorConfiguration());
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
startGridsMultiThreaded(3);
IgniteCache<String, Person> cache = grid(0).cache(DEFAULT_CACHE_NAME);
assert cache != null;
cache.put("p1", new Person(1, "John", "White", 25));
cache.put("p2", new Person(2, "Joe", "Black", 35));
cache.put("p3", new Person(3, "Mike", "Green", 40));
Class.forName("org.apache.ignite.IgniteJdbcDriver");
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
stopAllGrids();
}
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
conn = DriverManager.getConnection(URL);
stmt = conn.createStatement();
assert stmt != null;
assert !stmt.isClosed();
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
if (stmt != null && !stmt.isClosed())
stmt.close();
conn.close();
assert stmt.isClosed();
assert conn.isClosed();
}
/**
* @throws Exception If failed.
*/
public void testExecuteQuery() throws Exception {
ResultSet rs = stmt.executeQuery(SQL);
assert rs != null;
int cnt = 0;
while (rs.next()) {
int id = rs.getInt("id");
if (id == 2) {
assert "Joe".equals(rs.getString("firstName"));
assert "Black".equals(rs.getString("lastName"));
assert rs.getInt("age") == 35;
}
else if (id == 3) {
assert "Mike".equals(rs.getString("firstName"));
assert "Green".equals(rs.getString("lastName"));
assert rs.getInt("age") == 40;
}
else
assert false : "Wrong ID: " + id;
cnt++;
}
assert cnt == 2;
}
/**
* @throws Exception If failed.
*/
public void testExecute() throws Exception {
assert stmt.execute(SQL);
ResultSet rs = stmt.getResultSet();
assert rs != null;
assert stmt.getResultSet() == null;
int cnt = 0;
while (rs.next()) {
int id = rs.getInt("id");
if (id == 2) {
assert "Joe".equals(rs.getString("firstName"));
assert "Black".equals(rs.getString("lastName"));
assert rs.getInt("age") == 35;
}
else if (id == 3) {
assert "Mike".equals(rs.getString("firstName"));
assert "Green".equals(rs.getString("lastName"));
assert rs.getInt("age") == 40;
}
else
assert false : "Wrong ID: " + id;
cnt++;
}
assert cnt == 2;
}
/**
* @throws Exception If failed.
*/
public void testMaxRows() throws Exception {
stmt.setMaxRows(1);
ResultSet rs = stmt.executeQuery(SQL);
assert rs != null;
int cnt = 0;
while (rs.next()) {
int id = rs.getInt("id");
if (id == 2) {
assert "Joe".equals(rs.getString("firstName"));
assert "Black".equals(rs.getString("lastName"));
assert rs.getInt("age") == 35;
}
else if (id == 3) {
assert "Mike".equals(rs.getString("firstName"));
assert "Green".equals(rs.getString("lastName"));
assert rs.getInt("age") == 40;
}
else
assert false : "Wrong ID: " + id;
cnt++;
}
assert cnt == 1;
stmt.setMaxRows(0);
rs = stmt.executeQuery(SQL);
assert rs != null;
cnt = 0;
while (rs.next()) {
int id = rs.getInt("id");
if (id == 2) {
assert "Joe".equals(rs.getString("firstName"));
assert "Black".equals(rs.getString("lastName"));
assert rs.getInt("age") == 35;
}
else if (id == 3) {
assert "Mike".equals(rs.getString("firstName"));
assert "Green".equals(rs.getString("lastName"));
assert rs.getInt("age") == 40;
}
else
assert false : "Wrong ID: " + id;
cnt++;
}
assert cnt == 2;
}
/**
* Person.
*/
@SuppressWarnings("UnusedDeclaration")
private static class Person implements Serializable {
/** ID. */
@QuerySqlField
private final int id;
/** First name. */
@QuerySqlField(index = false)
private final String firstName;
/** Last name. */
@QuerySqlField(index = false)
private final String lastName;
/** Age. */
@QuerySqlField
private final int age;
/**
* @param id ID.
* @param firstName First name.
* @param lastName Last name.
* @param age Age.
*/
private Person(int id, String firstName, String lastName, int age) {
assert !F.isEmpty(firstName);
assert !F.isEmpty(lastName);
assert age > 0;
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
}
| |
package com.dts.tpo.dao;
import java.sql.Connection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import com.dts.core.dao.AbstractDataAccessObject;
import com.dts.tpo.mapper.CompanyMapper;
import com.dts.tpo.model.Company_Details;
@SuppressWarnings("serial")
public class CompanyDAO implements java.io.Serializable {
Connection con;
AbstractDataAccessObject dao = AbstractDataAccessObject.getInstance();
boolean hibernateEnabled = dao.getHibernateEnabled();
private JdbcTemplate jdbcTemplate;
public int addCompany(final Company_Details aCompany) {
int returnId = -1;
if(hibernateEnabled)
{
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
System.out.println("company Details : "+aCompany);
returnId = (Integer)session.save(aCompany);
session.save(aCompany);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
}
else
{
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AbstractDataAccessObject dao = (AbstractDataAccessObject) ctx.getBean("edao");
jdbcTemplate = dao.getJdbcTemplate();
String query1 = "select max(companyid) from Company_Details";
int maxCompanyId = jdbcTemplate.queryForInt(query1);
System.out.println("maxCompanyId---------------" + maxCompanyId);
aCompany.setCompanyId(maxCompanyId + 1);
System.out.println("Companyid : "+aCompany.getCompanyId()+"*****************");
String query = "insert into Company_Details values(" + aCompany.getCompanyId() + ",'"
+ aCompany.getCompanyName() + "','"
+ aCompany.getProfile() +"','"
+ aCompany.getStreet() +"','"
+ aCompany.getCity() +"','"
+ aCompany.getState() +"','"
+ aCompany.getCountry() +"','"
+ aCompany.getPhone() +"','"
+ aCompany.getEmail() +"')";
System.out.println("id : "+aCompany.getCompanyId());
System.out.println("name : "+aCompany.getCompanyName());
System.out.println("profile : "+aCompany.getProfile());
System.out.println("street : "+aCompany.getStreet());
System.out.println("city : "+aCompany.getCity());
System.out.println("state : "+aCompany.getState());
System.out.println("Country : "+aCompany.getCountry());
System.out.println("phone : "+aCompany.getPhone());
System.out.println("email : "+aCompany.getEmail());
returnId = jdbcTemplate.update(query);
}
return returnId;
}
/*
public void addCompany(final Company_Details aCompany) {
Session session = factory.openSession();
Transaction tx = null;
Integer companyId = null;
try{
tx = session.beginTransaction();
String name =
Company_details company = new Company_details(name, profile, street, city, state, country, phone, email);
companyId = (Integer) session.save(company);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return companyId;
}
*/
public void updateCompany(final Company_Details aCompany) {
if(hibernateEnabled)
{
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
session.update(aCompany);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
}
else
{
System.out.println("updateCompanyDao else************************************");
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AbstractDataAccessObject dao = (AbstractDataAccessObject) ctx.getBean("edao");
jdbcTemplate = dao.getJdbcTemplate();
System.out.println("id : "+aCompany.getCompanyId());
System.out.println("name : "+aCompany.getCompanyName());
System.out.println("profle : "+aCompany.getProfile());
System.out.println("Street : "+aCompany.getStreet());
System.out.println("city : "+aCompany.getCity());
System.out.println("state : "+aCompany.getState());
System.out.println("country : "+aCompany.getCountry());
System.out.println("phone : "+aCompany.getPhone());
System.out.println("email : "+aCompany.getEmail());
String query = "update Company_Details set companyName='" +aCompany.getCompanyName()
+ "',profile='" + aCompany.getProfile()
+ "',street='" + aCompany.getStreet()
+ "',city='" + aCompany.getCity()
+ "',state='" + aCompany.getState()
+ "',country='" + aCompany.getCountry()
+ "',phone='"+ aCompany.getPhone()
+ "',email='"+ aCompany.getEmail()
+ "' where companyId=" + aCompany.getCompanyId()+ "";
try{
jdbcTemplate.update(query);
}
catch(Throwable t){t.printStackTrace();}
}
}
public Company_Details getCompanyDetails(final int companyid) {
System.out.println("CompanyDAO.getCompanyDetails(companyid) : " + companyid);
Company_Details company_Details = null;
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List companies = session.createQuery("FROM Company_Details where COMPANYID = " + companyid)
.list();
for (Iterator iterator = companies.iterator(); iterator.hasNext();) {
company_Details = (Company_Details) iterator.next();
// System.out.println("Company Id : "
// + company_Details.getCompanyId());
// System.out.println("Company Name : "
// + company_Details.getCompanyName());
// System.out.println("profile : "
// + company_Details.getProfile());
// System.out.println("street : "
// + company_Details.getStreet());
// System.out.println("city : "
// + company_Details.getCity());
// System.out.println("state : " + company_Details.getState());
// System.out.println("country : " + company_Details.getCountry());
// System.out.println("phone : " + company_Details.getPhone());
// System.out.println("email : " + company_Details.getEmail());
}
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
return company_Details;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Hashtable listCompanies() {
final Hashtable aHashtable = new Hashtable();
if(hibernateEnabled)
{
System.out.println("hibernateEnabled *************: "+hibernateEnabled);
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List companies = session.createQuery("FROM Company_Details").list();
for (Iterator iterator = companies.iterator(); iterator.hasNext();) {
Company_Details company = (Company_Details) iterator.next();
// System.out.println("Company Id : " + company.getCompanyId());
// System.out
// .println("Company Name : " + company.getCompanyName());
// System.out.println("Profile : " + company.getProfile());
// System.out.println("Street : " + company.getStreet());
// System.out.println("City : " + company.getCity());
// System.out.println("State : " + company.getState());
// System.out.println("Country : " + company.getCountry());
// System.out.println("Phone : " + company.getPhone());
// System.out.println("Email : " + company.getEmail());
// if (iterator.hasNext()) {
// System.out.println("**********************");
// }
aHashtable.put(Integer.valueOf(company.getCompanyId()),
company);
}
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
}
else
{
//System.out.println("***************else jdbctemplate");
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AbstractDataAccessObject dao = (AbstractDataAccessObject) ctx.getBean("edao");
jdbcTemplate = dao.getJdbcTemplate();
String query = "select * from COMPANY_DETAILS";
List<Company_Details> companies = jdbcTemplate.query(query, new CompanyMapper());
System.out.println("jdbctemplate : "+companies);
for (Iterator iterator = companies.iterator(); iterator.hasNext();) {
Company_Details company = (Company_Details) iterator.next();
aHashtable.put(Integer.valueOf(company.getCompanyId()),
company);
}
}
return aHashtable;
}
public void deleteCompany(final int companyid) {
if(hibernateEnabled)
{
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
Company_Details aCompany = new Company_Details();
aCompany.setCompanyId(companyid);
try {
tx = session.beginTransaction();
session.delete(aCompany);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
}
else
{
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
AbstractDataAccessObject dao = (AbstractDataAccessObject) ctx.getBean("edao");
jdbcTemplate = dao.getJdbcTemplate();
String query = "delete from Company_Details where companyid=" + companyid + " ";
jdbcTemplate.update(query);
}
}
}
| |
package edu.columbia.tjw.item.fit.calculator;
import edu.columbia.tjw.item.algo.DoubleMatrix;
import edu.columbia.tjw.item.algo.DoubleVector;
import edu.columbia.tjw.item.algo.MatrixTools;
import edu.columbia.tjw.item.algo.VectorTools;
import java.util.List;
public final class BlockResult
{
private final int _rowStart;
private final int _rowEnd;
private final double _sumEntropy;
private final double _sumEntropy2;
private final DoubleVector _derivative;
private final DoubleVector _derivativeSquared;
private final DoubleVector _jDiag;
private final DoubleVector _shiftGradient;
private final DoubleVector _scaledGradient;
private final DoubleVector _scaledGradient2;
private final double _gradientMass;
private final DoubleMatrix _secondDerivative;
private final DoubleMatrix _fisherInformation;
private final int _size;
public BlockResult(final int rowStart_, final int rowEnd_, final double sumEntropy_, final double sumEntropy2_,
final DoubleVector derivative_, final DoubleVector derivativeSquared_, final DoubleVector jDiag_,
final DoubleVector shiftGradient_, final DoubleVector scaledGradient_,
final DoubleVector scaledGradient2_, final double gradientMass_,
final DoubleMatrix fisherInformation_, final DoubleMatrix secondDerivative_)
{
if (rowStart_ < 0)
{
throw new IllegalArgumentException("Invalid start row.");
}
if (rowStart_ > rowEnd_)
{
throw new IllegalArgumentException("Size must be nonnegative.");
}
final int size = rowEnd_ - rowStart_;
if (!(sumEntropy_ >= 0.0) || Double.isInfinite(sumEntropy_))
{
throw new IllegalArgumentException("Illegal entropy: " + sumEntropy_);
}
if (!(sumEntropy2_ >= 0.0) || Double.isInfinite(sumEntropy2_))
{
throw new IllegalArgumentException("Illegal entropy: " + sumEntropy2_);
}
_rowStart = rowStart_;
_rowEnd = rowEnd_;
_sumEntropy = sumEntropy_;
_sumEntropy2 = sumEntropy2_;
_size = size;
_derivative = derivative_;
_jDiag = jDiag_;
_shiftGradient = shiftGradient_;
_derivativeSquared = derivativeSquared_;
_secondDerivative = secondDerivative_;
_fisherInformation = fisherInformation_;
_gradientMass = gradientMass_;
_scaledGradient = scaledGradient_;
_scaledGradient2 = scaledGradient2_;
}
public BlockResult(final List<BlockResult> analysisList_)
{
if (analysisList_.size() < 1)
{
throw new IllegalArgumentException("List size must be positive.");
}
int minStart = Integer.MAX_VALUE;
int maxEnd = Integer.MIN_VALUE;
double h = 0.0;
double h2 = 0.0;
double gradientMass = 0.0;
int count = 0;
final boolean hasSecondDerivative = analysisList_.get(0).hasSecondDerivative();
final boolean hasDerivative = hasSecondDerivative || analysisList_.get(0).hasDerivative();
//final DoubleVector.Builder derivative;
DoubleVector derivative = null;
DoubleVector derivativeSquared = null;
DoubleVector jDiag = null;
DoubleVector scaledGradient = null;
DoubleVector scaledGradient2 = null;
DoubleVector shiftGradient = null;
DoubleMatrix fisherInformation = null;
DoubleMatrix secondDerivative = null;
if (hasDerivative)
{
final int dimension = analysisList_.get(0).getDerivativeDimension();
final DoubleVector zero = DoubleVector.constantVector(0, dimension);
derivative = zero;
derivativeSquared = zero;
jDiag = zero;
scaledGradient = zero;
scaledGradient2 = zero;
if (hasSecondDerivative)
{
final DoubleMatrix zeroMatrix = DoubleMatrix.constantMatrix(0.0, dimension, dimension);
fisherInformation = zeroMatrix;
secondDerivative = zeroMatrix;
shiftGradient = zero;
}
else
{
fisherInformation = null;
secondDerivative = null;
shiftGradient = null;
}
}
else
{
derivative = null;
scaledGradient = null;
scaledGradient2 = null;
derivativeSquared = null;
jDiag = null;
fisherInformation = null;
secondDerivative = null;
shiftGradient = null;
}
for (final BlockResult next : analysisList_)
{
minStart = Math.min(next._rowStart, minStart);
maxEnd = Math.max(next._rowEnd, maxEnd);
h += next._sumEntropy;
h2 += next._sumEntropy2;
count += next._size;
if (null != derivative)
{
final double weight = next._size;
final int dimension = derivative.getSize();
gradientMass += next._gradientMass;
derivative = VectorTools.multiplyAccumulate(derivative, next._derivative, weight);
derivativeSquared = VectorTools.multiplyAccumulate(derivativeSquared, next._derivativeSquared, weight);
scaledGradient = VectorTools.multiplyAccumulate(scaledGradient, next._scaledGradient, weight);
scaledGradient2 = VectorTools.multiplyAccumulate(scaledGradient2, next._scaledGradient2, weight);
jDiag = VectorTools.multiplyAccumulate(jDiag, next._jDiag, weight);
if (null != shiftGradient)
{
shiftGradient = VectorTools.multiplyAccumulate(shiftGradient, next._shiftGradient, weight);
}
if (null != secondDerivative)
{
secondDerivative = MatrixTools.multiplyAccumulate(secondDerivative, next.getSecondDerivative(),
weight);
fisherInformation = MatrixTools
.multiplyAccumulate(fisherInformation, next.getFisherInformation(), weight);
}
}
}
if (count != (maxEnd - minStart))
{
throw new IllegalArgumentException("Discontiguous blocks.");
}
if (null != derivative)
{
final double invWeight = 1.0 / count;
final int dimension = derivative.getSize();
derivative = VectorTools.scalarMultiply(derivative, invWeight).collapse();
derivativeSquared = VectorTools.scalarMultiply(derivativeSquared, invWeight).collapse();
scaledGradient = VectorTools.scalarMultiply(scaledGradient, invWeight).collapse();
scaledGradient2 = VectorTools.scalarMultiply(scaledGradient2, invWeight).collapse();
jDiag = VectorTools.scalarMultiply(jDiag, invWeight).collapse();
if (null != shiftGradient)
{
shiftGradient = VectorTools.scalarMultiply(shiftGradient, invWeight).collapse();
if (null != secondDerivative)
{
secondDerivative = MatrixTools.scalarMultiply(secondDerivative, invWeight).collapse();
fisherInformation = MatrixTools.scalarMultiply(fisherInformation, invWeight).collapse();
}
}
}
_derivative = derivative;
_derivativeSquared = derivativeSquared;
_scaledGradient = scaledGradient;
_scaledGradient2 = scaledGradient2;
_jDiag = jDiag;
_shiftGradient = shiftGradient;
_secondDerivative = secondDerivative;
_fisherInformation = fisherInformation;
_rowStart = minStart;
_rowEnd = maxEnd;
_sumEntropy = h;
_sumEntropy2 = h2;
_size = count;
_gradientMass = gradientMass;
}
public int getRowStart()
{
return _rowStart;
}
public int getRowEnd()
{
return _rowEnd;
}
public double getEntropySum()
{
return _sumEntropy;
}
public double getEntropySquareSum()
{
return _sumEntropy2;
}
public double getEntropyMean()
{
return _sumEntropy / _size;
}
public double getEntropySumVariance()
{
final double eX = getEntropyMean();
final double eX2 = _sumEntropy2 / _size;
final double var = Math.max(0.0, eX2 - (eX * eX));
return var;
}
public double getEntropyMeanVariance()
{
return getEntropySumVariance() / _size;
}
public double getEntropyMeanDev()
{
return Math.sqrt(getEntropyMeanVariance());
}
public int getSize()
{
return _size;
}
public boolean hasDerivative()
{
return _derivative != null;
}
public boolean hasSecondDerivative()
{
return _secondDerivative != null;
}
public int getDerivativeDimension()
{
if (!hasDerivative())
{
throw new IllegalArgumentException("Derivative was not calculated.");
}
return _derivative.getSize();
}
public DoubleVector getScaledGradient()
{
return _scaledGradient;
}
public DoubleVector getScaledGradient2()
{
return _scaledGradient2;
}
public double getDerivativeEntry(final int index_)
{
if (!hasDerivative())
{
throw new IllegalArgumentException("Derivative was not calculated.");
}
return _derivative.getEntry(index_);
}
public DoubleVector getDerivativeSquared()
{
return _derivativeSquared;
}
public double getD2Entry(final int index_)
{
return _derivativeSquared.getEntry(index_);
}
public double getJDiagEntry(final int index_)
{
return _jDiag.getEntry(index_);
}
public DoubleVector getJDiag()
{
return _jDiag;
}
public DoubleVector getDerivative()
{
return _derivative;
}
public DoubleMatrix getSecondDerivative()
{
return _secondDerivative;
}
public DoubleMatrix getFisherInformation()
{
return _fisherInformation;
}
public DoubleVector getShiftGradient()
{
return _shiftGradient;
}
public double getShiftGradientEntry(final int index_)
{
return _shiftGradient.getEntry(index_);
}
public double getGradientMass()
{
return _gradientMass;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v9/services/conversion_goal_campaign_config_service.proto
package com.google.ads.googleads.v9.services;
/**
* <pre>
* Request message for
* [ConversionGoalCampaignConfigService.MutateConversionGoalCampaignConfig][].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest}
*/
public final class MutateConversionGoalCampaignConfigsRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest)
MutateConversionGoalCampaignConfigsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use MutateConversionGoalCampaignConfigsRequest.newBuilder() to construct.
private MutateConversionGoalCampaignConfigsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MutateConversionGoalCampaignConfigsRequest() {
customerId_ = "";
operations_ = java.util.Collections.emptyList();
responseContentType_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MutateConversionGoalCampaignConfigsRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private MutateConversionGoalCampaignConfigsRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
customerId_ = s;
break;
}
case 18: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
operations_ = new java.util.ArrayList<com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation>();
mutable_bitField0_ |= 0x00000001;
}
operations_.add(
input.readMessage(com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.parser(), extensionRegistry));
break;
}
case 24: {
validateOnly_ = input.readBool();
break;
}
case 32: {
int rawValue = input.readEnum();
responseContentType_ = rawValue;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
operations_ = java.util.Collections.unmodifiableList(operations_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigServiceProto.internal_static_google_ads_googleads_v9_services_MutateConversionGoalCampaignConfigsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigServiceProto.internal_static_google_ads_googleads_v9_services_MutateConversionGoalCampaignConfigsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest.class, com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest.Builder.class);
}
public static final int CUSTOMER_ID_FIELD_NUMBER = 1;
private volatile java.lang.Object customerId_;
/**
* <pre>
* Required. The ID of the customer whose custom conversion goals are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
@java.lang.Override
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
}
}
/**
* <pre>
* Required. The ID of the customer whose custom conversion goals are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OPERATIONS_FIELD_NUMBER = 2;
private java.util.List<com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation> operations_;
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation> getOperationsList() {
return operations_;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperationOrBuilder>
getOperationsOrBuilderList() {
return operations_;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public int getOperationsCount() {
return operations_.size();
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation getOperations(int index) {
return operations_.get(index);
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperationOrBuilder getOperationsOrBuilder(
int index) {
return operations_.get(index);
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 3;
private boolean validateOnly_;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 3;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
public static final int RESPONSE_CONTENT_TYPE_FIELD_NUMBER = 4;
private int responseContentType_;
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 4;</code>
* @return The enum numeric value on the wire for responseContentType.
*/
@java.lang.Override public int getResponseContentTypeValue() {
return responseContentType_;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 4;</code>
* @return The responseContentType.
*/
@java.lang.Override public com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() {
@SuppressWarnings("deprecation")
com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.valueOf(responseContentType_);
return result == null ? com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_);
}
for (int i = 0; i < operations_.size(); i++) {
output.writeMessage(2, operations_.get(i));
}
if (validateOnly_ != false) {
output.writeBool(3, validateOnly_);
}
if (responseContentType_ != com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) {
output.writeEnum(4, responseContentType_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_);
}
for (int i = 0; i < operations_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, operations_.get(i));
}
if (validateOnly_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(3, validateOnly_);
}
if (responseContentType_ != com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(4, responseContentType_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest)) {
return super.equals(obj);
}
com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest other = (com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest) obj;
if (!getCustomerId()
.equals(other.getCustomerId())) return false;
if (!getOperationsList()
.equals(other.getOperationsList())) return false;
if (getValidateOnly()
!= other.getValidateOnly()) return false;
if (responseContentType_ != other.responseContentType_) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER;
hash = (53 * hash) + getCustomerId().hashCode();
if (getOperationsCount() > 0) {
hash = (37 * hash) + OPERATIONS_FIELD_NUMBER;
hash = (53 * hash) + getOperationsList().hashCode();
}
hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getValidateOnly());
hash = (37 * hash) + RESPONSE_CONTENT_TYPE_FIELD_NUMBER;
hash = (53 * hash) + responseContentType_;
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Request message for
* [ConversionGoalCampaignConfigService.MutateConversionGoalCampaignConfig][].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest)
com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigServiceProto.internal_static_google_ads_googleads_v9_services_MutateConversionGoalCampaignConfigsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigServiceProto.internal_static_google_ads_googleads_v9_services_MutateConversionGoalCampaignConfigsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest.class, com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest.Builder.class);
}
// Construct using com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getOperationsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
customerId_ = "";
if (operationsBuilder_ == null) {
operations_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
operationsBuilder_.clear();
}
validateOnly_ = false;
responseContentType_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigServiceProto.internal_static_google_ads_googleads_v9_services_MutateConversionGoalCampaignConfigsRequest_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest getDefaultInstanceForType() {
return com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest build() {
com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest buildPartial() {
com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest result = new com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest(this);
int from_bitField0_ = bitField0_;
result.customerId_ = customerId_;
if (operationsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
operations_ = java.util.Collections.unmodifiableList(operations_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.operations_ = operations_;
} else {
result.operations_ = operationsBuilder_.build();
}
result.validateOnly_ = validateOnly_;
result.responseContentType_ = responseContentType_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest) {
return mergeFrom((com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest other) {
if (other == com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest.getDefaultInstance()) return this;
if (!other.getCustomerId().isEmpty()) {
customerId_ = other.customerId_;
onChanged();
}
if (operationsBuilder_ == null) {
if (!other.operations_.isEmpty()) {
if (operations_.isEmpty()) {
operations_ = other.operations_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureOperationsIsMutable();
operations_.addAll(other.operations_);
}
onChanged();
}
} else {
if (!other.operations_.isEmpty()) {
if (operationsBuilder_.isEmpty()) {
operationsBuilder_.dispose();
operationsBuilder_ = null;
operations_ = other.operations_;
bitField0_ = (bitField0_ & ~0x00000001);
operationsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getOperationsFieldBuilder() : null;
} else {
operationsBuilder_.addAllMessages(other.operations_);
}
}
}
if (other.getValidateOnly() != false) {
setValidateOnly(other.getValidateOnly());
}
if (other.responseContentType_ != 0) {
setResponseContentTypeValue(other.getResponseContentTypeValue());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer whose custom conversion goals are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The ID of the customer whose custom conversion goals are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The ID of the customer whose custom conversion goals are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
customerId_ = value;
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer whose custom conversion goals are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return This builder for chaining.
*/
public Builder clearCustomerId() {
customerId_ = getDefaultInstance().getCustomerId();
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer whose custom conversion goals are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The bytes for customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
customerId_ = value;
onChanged();
return this;
}
private java.util.List<com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation> operations_ =
java.util.Collections.emptyList();
private void ensureOperationsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
operations_ = new java.util.ArrayList<com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation>(operations_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperationOrBuilder> operationsBuilder_;
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation> getOperationsList() {
if (operationsBuilder_ == null) {
return java.util.Collections.unmodifiableList(operations_);
} else {
return operationsBuilder_.getMessageList();
}
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public int getOperationsCount() {
if (operationsBuilder_ == null) {
return operations_.size();
} else {
return operationsBuilder_.getCount();
}
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation getOperations(int index) {
if (operationsBuilder_ == null) {
return operations_.get(index);
} else {
return operationsBuilder_.getMessage(index);
}
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperations(
int index, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation value) {
if (operationsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOperationsIsMutable();
operations_.set(index, value);
onChanged();
} else {
operationsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperations(
int index, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder builderForValue) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
operations_.set(index, builderForValue.build());
onChanged();
} else {
operationsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addOperations(com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation value) {
if (operationsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOperationsIsMutable();
operations_.add(value);
onChanged();
} else {
operationsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addOperations(
int index, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation value) {
if (operationsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOperationsIsMutable();
operations_.add(index, value);
onChanged();
} else {
operationsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addOperations(
com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder builderForValue) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
operations_.add(builderForValue.build());
onChanged();
} else {
operationsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addOperations(
int index, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder builderForValue) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
operations_.add(index, builderForValue.build());
onChanged();
} else {
operationsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder addAllOperations(
java.lang.Iterable<? extends com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation> values) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, operations_);
onChanged();
} else {
operationsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearOperations() {
if (operationsBuilder_ == null) {
operations_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
operationsBuilder_.clear();
}
return this;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder removeOperations(int index) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
operations_.remove(index);
onChanged();
} else {
operationsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder getOperationsBuilder(
int index) {
return getOperationsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperationOrBuilder getOperationsOrBuilder(
int index) {
if (operationsBuilder_ == null) {
return operations_.get(index); } else {
return operationsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<? extends com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperationOrBuilder>
getOperationsOrBuilderList() {
if (operationsBuilder_ != null) {
return operationsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(operations_);
}
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder addOperationsBuilder() {
return getOperationsFieldBuilder().addBuilder(
com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.getDefaultInstance());
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder addOperationsBuilder(
int index) {
return getOperationsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.getDefaultInstance());
}
/**
* <pre>
* Required. The list of operations to perform on individual conversion goal campaign
* config.
* </pre>
*
* <code>repeated .google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation operations = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public java.util.List<com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder>
getOperationsBuilderList() {
return getOperationsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperationOrBuilder>
getOperationsFieldBuilder() {
if (operationsBuilder_ == null) {
operationsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperation.Builder, com.google.ads.googleads.v9.services.ConversionGoalCampaignConfigOperationOrBuilder>(
operations_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
operations_ = null;
}
return operationsBuilder_;
}
private boolean validateOnly_ ;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 3;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 3;</code>
* @param value The validateOnly to set.
* @return This builder for chaining.
*/
public Builder setValidateOnly(boolean value) {
validateOnly_ = value;
onChanged();
return this;
}
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 3;</code>
* @return This builder for chaining.
*/
public Builder clearValidateOnly() {
validateOnly_ = false;
onChanged();
return this;
}
private int responseContentType_ = 0;
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 4;</code>
* @return The enum numeric value on the wire for responseContentType.
*/
@java.lang.Override public int getResponseContentTypeValue() {
return responseContentType_;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 4;</code>
* @param value The enum numeric value on the wire for responseContentType to set.
* @return This builder for chaining.
*/
public Builder setResponseContentTypeValue(int value) {
responseContentType_ = value;
onChanged();
return this;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 4;</code>
* @return The responseContentType.
*/
@java.lang.Override
public com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType getResponseContentType() {
@SuppressWarnings("deprecation")
com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType result = com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.valueOf(responseContentType_);
return result == null ? com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType.UNRECOGNIZED : result;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 4;</code>
* @param value The responseContentType to set.
* @return This builder for chaining.
*/
public Builder setResponseContentType(com.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType value) {
if (value == null) {
throw new NullPointerException();
}
responseContentType_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* </pre>
*
* <code>.google.ads.googleads.v9.enums.ResponseContentTypeEnum.ResponseContentType response_content_type = 4;</code>
* @return This builder for chaining.
*/
public Builder clearResponseContentType() {
responseContentType_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest)
private static final com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest();
}
public static com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MutateConversionGoalCampaignConfigsRequest>
PARSER = new com.google.protobuf.AbstractParser<MutateConversionGoalCampaignConfigsRequest>() {
@java.lang.Override
public MutateConversionGoalCampaignConfigsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new MutateConversionGoalCampaignConfigsRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<MutateConversionGoalCampaignConfigsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MutateConversionGoalCampaignConfigsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v9.services.MutateConversionGoalCampaignConfigsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig.bugs;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInspection.dataFlow.ControlFlowAnalyzer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.*;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.ObjectUtils;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.psiutils.LibraryUtil;
import com.siyeh.ig.psiutils.MethodMatcher;
import org.intellij.lang.annotations.Pattern;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.Set;
public class IgnoreResultOfCallInspectionBase extends BaseInspection {
/**
* @noinspection PublicField
*/
public boolean m_reportAllNonLibraryCalls = false;
protected final MethodMatcher myMethodMatcher;
public IgnoreResultOfCallInspectionBase() {
myMethodMatcher = new MethodMatcher(true, "callCheckString")
.add("java.io.File", ".*")
.add("java.io.InputStream","read|skip|available|markSupported")
.add("java.io.Reader","read|skip|ready|markSupported")
.add("java.lang.Boolean",".*")
.add("java.lang.Byte",".*")
.add("java.lang.Character",".*")
.add("java.lang.Double",".*")
.add("java.lang.Float",".*")
.add("java.lang.Integer",".*")
.add("java.lang.Long",".*")
.add("java.lang.Math",".*")
.add("java.lang.Object","equals|hashCode|toString")
.add("java.lang.Short",".*")
.add("java.lang.StrictMath",".*")
.add("java.lang.String",".*")
.add("java.math.BigInteger",".*")
.add("java.math.BigDecimal",".*")
.add("java.net.InetAddress",".*")
.add("java.net.URI",".*")
.add("java.util.List", "of")
.add("java.util.Set", "of")
.add("java.util.Map", "of|ofEntries|entry")
.add("java.util.Collections", "unmodifiable.*|singleton.*|checked.*|min|max|stream")
.add("java.util.UUID",".*")
.add("java.util.regex.Matcher","pattern|toMatchResult|start|end|group|groupCount|matches|find|lookingAt|quoteReplacement|replaceAll|replaceFirst|regionStart|regionEnd|hasTransparentBounds|hasAnchoringBounds|hitEnd|requireEnd")
.add("java.util.regex.Pattern",".*")
.add("java.util.stream.BaseStream",".*")
.finishDefault();
}
@Pattern(VALID_ID_PATTERN)
@Override
@NotNull
public String getID() {
return "ResultOfMethodCallIgnored";
}
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("result.of.method.call.ignored.display.name");
}
@Override
@NotNull
public String buildErrorString(Object... infos) {
final PsiClass containingClass = (PsiClass)infos[0];
final String className = containingClass.getName();
return InspectionGadgetsBundle.message("result.of.method.call.ignored.problem.descriptor", className);
}
@Override
public void readSettings(@NotNull Element element) throws InvalidDataException {
super.readSettings(element);
myMethodMatcher.readSettings(element);
}
@Override
public void writeSettings(@NotNull Element element) throws WriteExternalException {
super.writeSettings(element);
myMethodMatcher.writeSettings(element);
}
@Override
public boolean isEnabledByDefault() {
return true;
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new IgnoreResultOfCallVisitor();
}
private class IgnoreResultOfCallVisitor extends BaseInspectionVisitor {
@Override
public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
if (PsiType.VOID.equals(LambdaUtil.getFunctionalInterfaceReturnType(expression))) {
PsiElement resolve = expression.resolve();
if (resolve instanceof PsiMethod) {
visitCalledExpression(expression, (PsiMethod)resolve, null);
}
}
}
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
PsiElement parent = expression.getParent();
if (parent instanceof PsiExpressionStatement ||
parent instanceof PsiLambdaExpression && PsiType.VOID.equals(LambdaUtil.getFunctionalInterfaceReturnType((PsiLambdaExpression)parent))) {
final PsiMethod method = expression.resolveMethod();
if (method == null || method.isConstructor()) {
return;
}
visitCalledExpression(expression, method, parent);
}
}
private void visitCalledExpression(PsiExpression call,
PsiMethod method,
@Nullable PsiElement errorContainer) {
final PsiType returnType = method.getReturnType();
if (PsiType.VOID.equals(returnType)) {
return;
}
final PsiClass aClass = method.getContainingClass();
if (aClass == null) {
return;
}
if (errorContainer != null && PsiUtilCore.hasErrorElementChild(errorContainer)) {
return;
}
if (PropertyUtil.isSimpleGetter(method)) {
registerMethodCallOrRefError(call, aClass);
return;
}
if (m_reportAllNonLibraryCalls && !LibraryUtil.classIsInLibrary(aClass)) {
registerMethodCallOrRefError(call, aClass);
return;
}
final PsiAnnotation anno = ControlFlowAnalyzer.findContractAnnotation(method);
final boolean honorInferred = Registry.is("ide.ignore.call.result.inspection.honor.inferred.pure");
if (anno != null &&
(honorInferred || !AnnotationUtil.isInferredAnnotation(anno)) &&
Boolean.TRUE.equals(AnnotationUtil.getBooleanAttributeValue(anno, "pure"))) {
registerMethodCallOrRefError(call, aClass);
return;
}
final PsiAnnotation annotation = findAnnotationInTree(method, null, Collections.singleton("javax.annotation.CheckReturnValue"));
if (annotation != null) {
final PsiElement owner = (PsiElement)annotation.getOwner();
if (findAnnotationInTree(method, owner, Collections.singleton("com.google.errorprone.annotations.CanIgnoreReturnValue")) != null) {
return;
}
}
if (!myMethodMatcher.matches(method) && annotation == null) {
return;
}
registerMethodCallOrRefError(call, aClass);
}
private void registerMethodCallOrRefError(PsiExpression call, PsiClass aClass) {
if (call instanceof PsiMethodCallExpression) {
registerMethodCallError((PsiMethodCallExpression)call, aClass);
}
else if (call instanceof PsiMethodReferenceExpression){
registerError(ObjectUtils.notNull(((PsiMethodReferenceExpression)call).getReferenceNameElement(), call), aClass);
}
}
@Nullable
private PsiAnnotation findAnnotationInTree(PsiElement element, @Nullable PsiElement stop, @NotNull Set<String> fqAnnotationNames) {
while (element != null) {
if (element == stop) {
return null;
}
if (element instanceof PsiModifierListOwner) {
final PsiModifierListOwner modifierListOwner = (PsiModifierListOwner)element;
final PsiAnnotation annotation =
AnnotationUtil.findAnnotationInHierarchy(modifierListOwner, fqAnnotationNames);
if (annotation != null) {
return annotation;
}
}
if (element instanceof PsiClassOwner) {
final PsiClassOwner classOwner = (PsiClassOwner)element;
final String packageName = classOwner.getPackageName();
final PsiPackage aPackage = JavaPsiFacade.getInstance(element.getProject()).findPackage(packageName);
if (aPackage == null) {
return null;
}
return AnnotationUtil.findAnnotation(aPackage, fqAnnotationNames);
}
element = element.getContext();
}
return null;
}
}
}
| |
/*
* Copyright 2016 The OpenYOLO Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openyolo.testapp;
import android.support.annotation.NonNull;
import com.google.common.io.BaseEncoding;
import java.util.Locale;
import java.util.Random;
/**
* Generates random data useful for populating credentials.
*/
public class RandomData {
/**
* The top-100 given (aka "first") names, from US Census Bureau data.
*/
public static final String[] GIVEN_NAMES = {
"Amanda",
"Amy",
"Andrew",
"Angela",
"Ann",
"Anna",
"Anthony",
"Arthur",
"Barbara",
"Betty",
"Brenda",
"Brian",
"Carl",
"Carol",
"Carolyn",
"Catherine",
"Charles",
"Christine",
"Christopher",
"Cynthia",
"Daniel",
"David",
"Deborah",
"Debra",
"Dennis",
"Diane",
"Donald",
"Donna",
"Dorothy",
"Douglas",
"Edward",
"Elizabeth",
"Eric",
"Frances",
"Frank",
"Gary",
"George",
"Gregory",
"Harold",
"Helen",
"Henry",
"James",
"Janet",
"Jason",
"Jeffrey",
"Jennifer",
"Jerry",
"Jessica",
"John",
"Jose",
"Joseph",
"Joshua",
"Joyce",
"Karen",
"Kathleen",
"Kenneth",
"Kevin",
"Kimberly",
"Larry",
"Laura",
"Linda",
"Lisa",
"Margaret",
"Maria",
"Marie",
"Mark",
"Martha",
"Mary",
"Matthew",
"Melissa",
"Michael",
"Michelle",
"Nancy",
"Pamela",
"Patricia",
"Patrick",
"Paul",
"Peter",
"Raymond",
"Rebecca",
"Richard",
"Robert",
"Roger",
"Ronald",
"Ruth",
"Ryan",
"Sandra",
"Sarah",
"Scott",
"Sharon",
"Shirley",
"Stephanie",
"Stephen",
"Steven",
"Susan",
"Thomas",
"Timothy",
"Virginia",
"Walter",
"William",
};
/**
* The top-100 family names, from US Census Bureau data.
*/
public static final String[] FAMILY_NAMES = {
"Adams",
"Alexander",
"Allen",
"Anderson",
"Bailey",
"Baker",
"Barnes",
"Bell",
"Bennett",
"Brooks",
"Brown",
"Bryant",
"Butler",
"Campbell",
"Carter",
"Clark",
"Coleman",
"Collins",
"Cook",
"Cooper",
"Cox",
"Davis",
"Diaz",
"Edwards",
"Evans",
"Flores",
"Foster",
"Garcia",
"Gonzales",
"Gonzalez",
"Gray",
"Green",
"Griffin",
"Hall",
"Harris",
"Hayes",
"Henderson",
"Hernandez",
"Hill",
"Howard",
"Hughes",
"Jackson",
"James",
"Jenkins",
"Johnson",
"Jones",
"Kelly",
"King",
"Lee",
"Lewis",
"Long",
"Lopez",
"Martin",
"Martinez",
"Miller",
"Mitchell",
"Moore",
"Morgan",
"Morris",
"Murphy",
"Nelson",
"Parker",
"Patterson",
"Perez",
"Perry",
"Peterson",
"Phillips",
"Powell",
"Price",
"Ramirez",
"Reed",
"Richardson",
"Rivera",
"Roberts",
"Robinson",
"Rodriguez",
"Rogers",
"Ross",
"Russell",
"Sanchez",
"Sanders",
"Scott",
"Simmons",
"Smith",
"Stewart",
"Taylor",
"Thomas",
"Thompson",
"Torres",
"Turner",
"Walker",
"Ward",
"Washington",
"Watson",
"White",
"Williams",
"Wilson",
"Wood",
"Wright",
"Young"
};
private static final int ROBOHASH_LENGTH = 32;
private final Random mRandom;
/**
* Instantiates a random user data source.
*/
public RandomData() {
mRandom = new Random();
}
/**
* Generates a given (aka "first") name.
*/
@NonNull
public String generateGivenName() {
return GIVEN_NAMES[mRandom.nextInt(GIVEN_NAMES.length)];
}
/**
* Generates a family name.
*/
@NonNull
public String generateFamilyName() {
return FAMILY_NAMES[mRandom.nextInt(FAMILY_NAMES.length)];
}
/**
* Generates a full display name composed of a given name and family name.
*/
public String generateDisplayName() {
return getDisplayName(generateGivenName(), generateFamilyName());
}
/**
* Generates a display name from the provided given and family names.
*/
public String getDisplayName(String givenName, String familyName) {
return givenName + " " + familyName;
}
/**
* Generates an email address.
*/
public String generateEmailAddress() {
return getEmailAddress(generateGivenName(), generateFamilyName());
}
/**
* Generates an email address using the provided given and family names for the user.
*/
public String getEmailAddress(String givenName, String surname) {
return givenName.toLowerCase(Locale.US).trim()
+ "." + surname.toLowerCase(Locale.US).trim()
+ "@openyolo.org";
}
/**
* Generates a profile picture URI.
*/
public String generateProfilePictureUri() {
return "https://robohash.org/" + generateRandomHexString(ROBOHASH_LENGTH) + "?set=set3";
}
private String generateRandomHexString(int length) {
byte[] randomBytes = new byte[length / 2];
mRandom.nextBytes(randomBytes);
return BaseEncoding.base16().encode(randomBytes);
}
}
| |
/**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.env;
import jetbrains.exodus.ArrayByteIterable;
import jetbrains.exodus.ByteIterable;
import jetbrains.exodus.ExodusException;
import jetbrains.exodus.bindings.LongBinding;
import jetbrains.exodus.bindings.StringBinding;
import jetbrains.exodus.core.dataStructures.Pair;
import jetbrains.exodus.crypto.InvalidCipherParametersException;
import jetbrains.exodus.log.*;
import jetbrains.exodus.tree.*;
import jetbrains.exodus.tree.btree.BTree;
import jetbrains.exodus.tree.btree.BTreeEmpty;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
final class MetaTreeImpl implements MetaTree {
private static final int EMPTY_LOG_BOUND = 5;
final ITree tree;
final long root;
final LogTip logTip;
MetaTreeImpl(final ITree tree, long root, LogTip logTip) {
this.tree = tree;
this.root = root;
this.logTip = logTip;
}
static Pair<MetaTreeImpl, Integer> create(@NotNull final EnvironmentImpl env) {
final Log log = env.getLog();
LogTip logTip = log.getTip();
if (logTip.highAddress > EMPTY_LOG_BOUND) {
Loggable rootLoggable = log.getLastLoggableOfType(DatabaseRoot.DATABASE_ROOT_TYPE);
while (rootLoggable != null) {
final long root = rootLoggable.getAddress();
// work around XD-692: load database root in try-catch block
DatabaseRoot dbRoot = null;
try {
dbRoot = new DatabaseRoot(rootLoggable);
} catch (ExodusException e) {
EnvironmentImpl.loggerError("Failed to load database root at " + rootLoggable.getAddress(), e);
}
if (dbRoot != null && dbRoot.isValid()) {
try {
final LogTip updatedTip = log.setHighAddress(logTip, root + dbRoot.length());
final BTree metaTree = env.loadMetaTree(dbRoot.getRootAddress(), updatedTip);
if (metaTree != null) {
cloneTree(metaTree); // try to traverse meta tree
log.sync(); // flush potential file truncation
return new Pair<>(new MetaTreeImpl(metaTree, root, updatedTip), dbRoot.getLastStructureId());
}
logTip = updatedTip;
} catch (ExodusException e) {
logTip = log.getTip();
EnvironmentImpl.loggerError("Failed to recover to valid root" +
LogUtil.getWrongAddressErrorMessage(dbRoot.getAddress(), env.getEnvironmentConfig().getLogFileSize() * 1024L), e);
// XD-449: try next database root if we failed to traverse whole MetaTree
// TODO: this check should become obsolete after XD-334 is implemented
}
}
// continue recovery
rootLoggable = log.getLastLoggableOfTypeBefore(DatabaseRoot.DATABASE_ROOT_TYPE, root, logTip);
}
// "abnormal program termination", "blue screen of doom"
// Something quite strange with the database: it is not empty, but no valid
// root has found. We can't just reset the database and lose all the contents,
// we should have a chance to investigate the case. So failing...
//
// It's extremely likely the database was ciphered with different/unknown cipher parameters.
log.close();
throw new InvalidCipherParametersException();
}
// no roots found: the database is empty
EnvironmentImpl.loggerDebug("No roots found: the database is empty");
logTip = log.setHighAddress(logTip, 0);
final ITree resultTree = getEmptyMetaTree(env);
final long root;
log.beginWrite();
final LogTip createdTip;
try {
final long rootAddress = resultTree.getMutableCopy().save();
root = log.write(DatabaseRoot.DATABASE_ROOT_TYPE, Loggable.NO_STRUCTURE_ID,
DatabaseRoot.asByteIterable(rootAddress, EnvironmentImpl.META_TREE_ID));
log.flush();
createdTip = log.endWrite();
} catch (Throwable t) {
log.revertWrite(logTip);
throw new ExodusException("Can't init meta tree in log", t);
}
return new Pair<>(new MetaTreeImpl(resultTree, root, createdTip), EnvironmentImpl.META_TREE_ID);
}
static MetaTreeImpl create(@NotNull final EnvironmentImpl env, @NotNull final LogTip logTip, @NotNull final MetaTreePrototype prototype) {
return new MetaTreeImpl(
env.loadMetaTree(prototype.treeAddress(), logTip),
prototype.rootAddress(),
logTip
);
}
static MetaTreeImpl create(@NotNull final EnvironmentImpl env, final long highAddress) {
final Log log = env.getLog();
final LogTip logTip = log.getTip();
final Loggable rootLoggable = log.getLastLoggableOfTypeBefore(DatabaseRoot.DATABASE_ROOT_TYPE, highAddress, logTip);
if (rootLoggable == null) {
throw new ExodusException("Failed to find root loggable before address = " + highAddress);
}
final long root = rootLoggable.getAddress();
if (root + rootLoggable.length() != highAddress) {
throw new ExodusException("Database root should be the last loggable before address = " + highAddress);
}
DatabaseRoot dbRoot = null;
try {
dbRoot = new DatabaseRoot(rootLoggable);
} catch (ExodusException e) {
EnvironmentImpl.loggerError("Failed to load database root at " + root, e);
}
if (dbRoot == null || !dbRoot.isValid()) {
throw new ExodusException("Can't load valid database root by address = " + root);
}
final LogTip truncatedTip = logTip.asTruncatedTo(highAddress);
return new MetaTreeImpl(env.loadMetaTree(dbRoot.getRootAddress(), truncatedTip), root, truncatedTip);
}
@Override
public LogTip getLogTip() {
return logTip;
}
@Override
public long treeAddress() {
return tree.getRootAddress();
}
@Override
public long rootAddress() {
return root;
}
LongIterator addressIterator() {
return tree.addressIterator();
}
@Nullable
TreeMetaInfo getMetaInfo(@NotNull final String storeName, @NotNull final EnvironmentImpl env) {
final ByteIterable value = tree.get(StringBinding.stringToEntry(storeName));
if (value == null) {
return null;
}
return TreeMetaInfo.load(env, value);
}
long getRootAddress(final int structureId) {
final ByteIterable value = tree.get(LongBinding.longToCompressedEntry(structureId));
return value == null ? Loggable.NULL_ADDRESS : CompressedUnsignedLongByteIterable.getLong(value);
}
static void removeStore(@NotNull final ITreeMutable out, @NotNull final String storeName, final long id) {
out.delete(StringBinding.stringToEntry(storeName));
out.delete(LongBinding.longToCompressedEntry(id));
}
static void addStore(@NotNull final ITreeMutable out, @NotNull final String storeName, @NotNull final TreeMetaInfo metaInfo) {
out.put(StringBinding.stringToEntry(storeName), metaInfo.toByteIterable());
}
static void saveTree(@NotNull final ITreeMutable out,
@NotNull final ITreeMutable treeMutable) {
final long treeRootAddress = treeMutable.save();
final int structureId = treeMutable.getStructureId();
out.put(LongBinding.longToCompressedEntry(structureId),
CompressedUnsignedLongByteIterable.getIterable(treeRootAddress));
}
/**
* Saves meta tree, writes database root and flushes the log.
*
* @param metaTree mutable meta tree
* @param env enclosing environment
* @param expired expired loggables (database root to be added)
* @return database root loggable which is read again from the log.
*/
@NotNull
static MetaTreeImpl.Proto saveMetaTree(@NotNull final ITreeMutable metaTree,
@NotNull final EnvironmentImpl env,
@NotNull final ExpiredLoggableCollection expired) {
final long newMetaTreeAddress = metaTree.save();
final Log log = env.getLog();
final int lastStructureId = env.getLastStructureId();
final long dbRootAddress = log.write(DatabaseRoot.DATABASE_ROOT_TYPE, Loggable.NO_STRUCTURE_ID,
DatabaseRoot.asByteIterable(newMetaTreeAddress, lastStructureId));
expired.add(dbRootAddress, (int) (log.getWrittenHighAddress() - dbRootAddress));
return new MetaTreeImpl.Proto(newMetaTreeAddress, dbRootAddress);
}
long getAllStoreCount() {
long size = tree.getSize();
if (size % 2L != 0) {
EnvironmentImpl.loggerError("MetaTree size is not even");
}
return size / 2;
}
@NotNull
List<String> getAllStoreNames() {
final ITree tree = this.tree;
if (tree.getSize() == 0) {
return Collections.emptyList();
}
final List<String> result = new ArrayList<>();
final ITreeCursor cursor = tree.openCursor();
while (cursor.getNext()) {
final ArrayByteIterable key = new ArrayByteIterable(cursor.getKey());
if (isStringKey(key)) {
final String storeName = StringBinding.entryToString(key);
if (!EnvironmentImpl.isUtilizationProfile(storeName)) {
result.add(storeName);
}
}
}
return result;
}
@Nullable
String getStoreNameByStructureId(final int structureId, @NotNull final EnvironmentImpl env) {
try (ITreeCursor cursor = tree.openCursor()) {
while (cursor.getNext()) {
final ByteIterable key = cursor.getKey();
if (isStringKey(new ArrayByteIterable(key))) {
if (TreeMetaInfo.load(env, cursor.getValue()).getStructureId() == structureId) {
return StringBinding.entryToString(key);
}
}
}
}
return null;
}
MetaTreeImpl getClone() {
return new MetaTreeImpl(cloneTree(tree), root, logTip);
}
static boolean isStringKey(final ArrayByteIterable key) {
// last byte of string is zero
return key.getBytesUnsafe()[key.getLength() - 1] == 0;
}
static ITreeMutable cloneTree(@NotNull final ITree tree) {
try (ITreeCursor cursor = tree.openCursor()) {
final ITreeMutable result = tree.getMutableCopy();
while (cursor.getNext()) {
result.put(cursor.getKey(), cursor.getValue());
}
return result;
}
}
private static ITree getEmptyMetaTree(@NotNull final EnvironmentImpl env) {
return new BTreeEmpty(env.getLog(), env.getBTreeBalancePolicy(), false, EnvironmentImpl.META_TREE_ID) {
@NotNull
@Override
public DataIterator getDataIterator(long address) {
return new DataIterator(log, address);
}
};
}
static class Proto implements MetaTreePrototype {
final long address;
final long root;
Proto(long address, long root) {
this.address = address;
this.root = root;
}
@Override
public long treeAddress() {
return address;
}
@Override
public long rootAddress() {
return root;
}
}
}
| |
package com.vinpos.pos;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author sd
*/
public class Tip extends java.awt.Dialog {
/**
* Creates new form JD1
*/
public Tip(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.setAlwaysOnTop(true);
this.setLocationRelativeTo(null);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
setModal(true);
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
closeDialog(evt);
}
});
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setBackground(new java.awt.Color(51, 204, 0));
jButton1.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton1.setText("15% Charge");
jButton1.setBorder(new javax.swing.border.MatteBorder(null));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 249, 70));
jButton2.setBackground(new java.awt.Color(51, 204, 0));
jButton2.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton2.setText("18% Charge");
jButton2.setBorder(new javax.swing.border.MatteBorder(null));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 70, 249, 70));
jButton3.setBackground(new java.awt.Color(51, 204, 0));
jButton3.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton3.setText("20% Charge");
jButton3.setBorder(new javax.swing.border.MatteBorder(null));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jPanel1.add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 140, 249, 70));
jButton4.setBackground(new java.awt.Color(51, 204, 0));
jButton4.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton4.setText("25% Charge");
jButton4.setBorder(new javax.swing.border.MatteBorder(null));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jPanel1.add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 210, 249, 70));
jButton5.setBackground(new java.awt.Color(51, 204, 0));
jButton5.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton5.setText("30% Charge");
jButton5.setBorder(new javax.swing.border.MatteBorder(null));
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jPanel1.add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 280, 249, 70));
jButton10.setBackground(new java.awt.Color(51, 204, 0));
jButton10.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton10.setText("Cancle Charge ");
jButton10.setBorder(new javax.swing.border.MatteBorder(null));
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
jPanel1.add(jButton10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 630, 249, 70));
jButton6.setBackground(new java.awt.Color(51, 204, 0));
jButton6.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton6.setText("35% Charge");
jButton6.setBorder(new javax.swing.border.MatteBorder(null));
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jPanel1.add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 350, 249, 70));
jButton7.setBackground(new java.awt.Color(51, 204, 0));
jButton7.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton7.setText("40% Charge");
jButton7.setBorder(new javax.swing.border.MatteBorder(null));
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jPanel1.add(jButton7, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 420, 249, 70));
jButton8.setBackground(new java.awt.Color(51, 204, 0));
jButton8.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton8.setText("45% Charge");
jButton8.setBorder(new javax.swing.border.MatteBorder(null));
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jPanel1.add(jButton8, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 490, 249, 70));
jButton9.setBackground(new java.awt.Color(51, 204, 0));
jButton9.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
jButton9.setText("50% charge");
jButton9.setToolTipText("");
jButton9.setBorder(new javax.swing.border.MatteBorder(null));
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
jPanel1.add(jButton9, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 560, 249, 70));
add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Closes the dialog
*/
private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
setVisible(false);
}//GEN-LAST:event_closeDialog
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
tip=0.15;
setVisible(false);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
tip=0.18;
setVisible(false);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
tip=0.20;
setVisible(false);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
tip=0.25;
setVisible(false);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
tip=0.30;
setVisible(false);
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
tip=0.35;
setVisible(false);
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
tip=0.40;
setVisible(false);
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
tip=0.45;
setVisible(false);
}//GEN-LAST:event_jButton8ActionPerformed
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
tip=0.50;
setVisible(false);
}//GEN-LAST:event_jButton9ActionPerformed
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
tip =0.00;
setVisible(false);
}//GEN-LAST:event_jButton10ActionPerformed
public Double getTip(){
setVisible(true);
return tip;
}
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
private Double tip = -1.00;
}
| |
/*
* Copyright (C) 1997-2001 Id Software, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE.
*
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
// Created on 11.11.2003 by RST
// $Id: M_Berserk.java,v 1.4 2005/11/20 22:18:33 salomo Exp $
package org.free.jake2.game.monsters;
import org.free.jake2.Defines;
import org.free.jake2.game.*;
import org.free.jake2.util.Lib;
import org.free.jake2.util.Math3D;
public class M_Berserk {
public final static int FRAME_stand1 = 0;
public final static int FRAME_stand2 = 1;
public final static int FRAME_stand3 = 2;
public final static int FRAME_stand4 = 3;
public final static int FRAME_stand5 = 4;
public final static int FRAME_standb1 = 5;
public final static int FRAME_standb2 = 6;
public final static int FRAME_standb3 = 7;
public final static int FRAME_standb4 = 8;
public final static int FRAME_standb5 = 9;
public final static int FRAME_standb6 = 10;
public final static int FRAME_standb7 = 11;
public final static int FRAME_standb8 = 12;
public final static int FRAME_standb9 = 13;
public final static int FRAME_standb10 = 14;
public final static int FRAME_standb11 = 15;
public final static int FRAME_standb12 = 16;
public final static int FRAME_standb13 = 17;
public final static int FRAME_standb14 = 18;
public final static int FRAME_standb15 = 19;
public final static int FRAME_standb16 = 20;
public final static int FRAME_standb17 = 21;
public final static int FRAME_standb18 = 22;
public final static int FRAME_standb19 = 23;
public final static int FRAME_standb20 = 24;
public final static int FRAME_walkc1 = 25;
public final static int FRAME_walkc2 = 26;
public final static int FRAME_walkc3 = 27;
public final static int FRAME_walkc4 = 28;
public final static int FRAME_walkc5 = 29;
public final static int FRAME_walkc6 = 30;
public final static int FRAME_walkc7 = 31;
public final static int FRAME_walkc8 = 32;
public final static int FRAME_walkc9 = 33;
public final static int FRAME_walkc10 = 34;
public final static int FRAME_walkc11 = 35;
public final static int FRAME_run1 = 36;
public final static int FRAME_run2 = 37;
public final static int FRAME_run3 = 38;
public final static int FRAME_run4 = 39;
public final static int FRAME_run5 = 40;
public final static int FRAME_run6 = 41;
public final static int FRAME_att_a1 = 42;
public final static int FRAME_att_a2 = 43;
public final static int FRAME_att_a3 = 44;
public final static int FRAME_att_a4 = 45;
public final static int FRAME_att_a5 = 46;
public final static int FRAME_att_a6 = 47;
public final static int FRAME_att_a7 = 48;
public final static int FRAME_att_a8 = 49;
public final static int FRAME_att_a9 = 50;
public final static int FRAME_att_a10 = 51;
public final static int FRAME_att_a11 = 52;
public final static int FRAME_att_a12 = 53;
public final static int FRAME_att_a13 = 54;
public final static int FRAME_att_b1 = 55;
public final static int FRAME_att_b2 = 56;
public final static int FRAME_att_b3 = 57;
public final static int FRAME_att_b4 = 58;
public final static int FRAME_att_b5 = 59;
public final static int FRAME_att_b6 = 60;
public final static int FRAME_att_b7 = 61;
public final static int FRAME_att_b8 = 62;
public final static int FRAME_att_b9 = 63;
public final static int FRAME_att_b10 = 64;
public final static int FRAME_att_b11 = 65;
public final static int FRAME_att_b12 = 66;
public final static int FRAME_att_b13 = 67;
public final static int FRAME_att_b14 = 68;
public final static int FRAME_att_b15 = 69;
public final static int FRAME_att_b16 = 70;
public final static int FRAME_att_b17 = 71;
public final static int FRAME_att_b18 = 72;
public final static int FRAME_att_b19 = 73;
public final static int FRAME_att_b20 = 74;
public final static int FRAME_att_b21 = 75;
public final static int FRAME_att_c1 = 76;
public final static int FRAME_att_c2 = 77;
public final static int FRAME_att_c3 = 78;
public final static int FRAME_att_c4 = 79;
public final static int FRAME_att_c5 = 80;
public final static int FRAME_att_c6 = 81;
public final static int FRAME_att_c7 = 82;
public final static int FRAME_att_c8 = 83;
public final static int FRAME_att_c9 = 84;
public final static int FRAME_att_c10 = 85;
public final static int FRAME_att_c11 = 86;
public final static int FRAME_att_c12 = 87;
public final static int FRAME_att_c13 = 88;
public final static int FRAME_att_c14 = 89;
public final static int FRAME_att_c15 = 90;
public final static int FRAME_att_c16 = 91;
public final static int FRAME_att_c17 = 92;
public final static int FRAME_att_c18 = 93;
public final static int FRAME_att_c19 = 94;
public final static int FRAME_att_c20 = 95;
public final static int FRAME_att_c21 = 96;
public final static int FRAME_att_c22 = 97;
public final static int FRAME_att_c23 = 98;
public final static int FRAME_att_c24 = 99;
public final static int FRAME_att_c25 = 100;
public final static int FRAME_att_c26 = 101;
public final static int FRAME_att_c27 = 102;
public final static int FRAME_att_c28 = 103;
public final static int FRAME_att_c29 = 104;
public final static int FRAME_att_c30 = 105;
public final static int FRAME_att_c31 = 106;
public final static int FRAME_att_c32 = 107;
public final static int FRAME_att_c33 = 108;
public final static int FRAME_att_c34 = 109;
public final static int FRAME_r_att1 = 110;
public final static int FRAME_r_att2 = 111;
public final static int FRAME_r_att3 = 112;
public final static int FRAME_r_att4 = 113;
public final static int FRAME_r_att5 = 114;
public final static int FRAME_r_att6 = 115;
public final static int FRAME_r_att7 = 116;
public final static int FRAME_r_att8 = 117;
public final static int FRAME_r_att9 = 118;
public final static int FRAME_r_att10 = 119;
public final static int FRAME_r_att11 = 120;
public final static int FRAME_r_att12 = 121;
public final static int FRAME_r_att13 = 122;
public final static int FRAME_r_att14 = 123;
public final static int FRAME_r_att15 = 124;
public final static int FRAME_r_att16 = 125;
public final static int FRAME_r_att17 = 126;
public final static int FRAME_r_att18 = 127;
public final static int FRAME_r_attb1 = 128;
public final static int FRAME_r_attb2 = 129;
public final static int FRAME_r_attb3 = 130;
public final static int FRAME_r_attb4 = 131;
public final static int FRAME_r_attb5 = 132;
public final static int FRAME_r_attb6 = 133;
public final static int FRAME_r_attb7 = 134;
public final static int FRAME_r_attb8 = 135;
public final static int FRAME_r_attb9 = 136;
public final static int FRAME_r_attb10 = 137;
public final static int FRAME_r_attb11 = 138;
public final static int FRAME_r_attb12 = 139;
public final static int FRAME_r_attb13 = 140;
public final static int FRAME_r_attb14 = 141;
public final static int FRAME_r_attb15 = 142;
public final static int FRAME_r_attb16 = 143;
public final static int FRAME_r_attb17 = 144;
public final static int FRAME_r_attb18 = 145;
public final static int FRAME_slam1 = 146;
public final static int FRAME_slam2 = 147;
public final static int FRAME_slam3 = 148;
public final static int FRAME_slam4 = 149;
public final static int FRAME_slam5 = 150;
public final static int FRAME_slam6 = 151;
public final static int FRAME_slam7 = 152;
public final static int FRAME_slam8 = 153;
public final static int FRAME_slam9 = 154;
public final static int FRAME_slam10 = 155;
public final static int FRAME_slam11 = 156;
public final static int FRAME_slam12 = 157;
public final static int FRAME_slam13 = 158;
public final static int FRAME_slam14 = 159;
public final static int FRAME_slam15 = 160;
public final static int FRAME_slam16 = 161;
public final static int FRAME_slam17 = 162;
public final static int FRAME_slam18 = 163;
public final static int FRAME_slam19 = 164;
public final static int FRAME_slam20 = 165;
public final static int FRAME_slam21 = 166;
public final static int FRAME_slam22 = 167;
public final static int FRAME_slam23 = 168;
public final static int FRAME_duck1 = 169;
public final static int FRAME_duck2 = 170;
public final static int FRAME_duck3 = 171;
public final static int FRAME_duck4 = 172;
public final static int FRAME_duck5 = 173;
public final static int FRAME_duck6 = 174;
public final static int FRAME_duck7 = 175;
public final static int FRAME_duck8 = 176;
public final static int FRAME_duck9 = 177;
public final static int FRAME_duck10 = 178;
public final static int FRAME_fall1 = 179;
public final static int FRAME_fall2 = 180;
public final static int FRAME_fall3 = 181;
public final static int FRAME_fall4 = 182;
public final static int FRAME_fall5 = 183;
public final static int FRAME_fall6 = 184;
public final static int FRAME_fall7 = 185;
public final static int FRAME_fall8 = 186;
public final static int FRAME_fall9 = 187;
public final static int FRAME_fall10 = 188;
public final static int FRAME_fall11 = 189;
public final static int FRAME_fall12 = 190;
public final static int FRAME_fall13 = 191;
public final static int FRAME_fall14 = 192;
public final static int FRAME_fall15 = 193;
public final static int FRAME_fall16 = 194;
public final static int FRAME_fall17 = 195;
public final static int FRAME_fall18 = 196;
public final static int FRAME_fall19 = 197;
public final static int FRAME_fall20 = 198;
public final static int FRAME_painc1 = 199;
public final static int FRAME_painc2 = 200;
public final static int FRAME_painc3 = 201;
public final static int FRAME_painc4 = 202;
public final static int FRAME_painb1 = 203;
public final static int FRAME_painb2 = 204;
public final static int FRAME_painb3 = 205;
public final static int FRAME_painb4 = 206;
public final static int FRAME_painb5 = 207;
public final static int FRAME_painb6 = 208;
public final static int FRAME_painb7 = 209;
public final static int FRAME_painb8 = 210;
public final static int FRAME_painb9 = 211;
public final static int FRAME_painb10 = 212;
public final static int FRAME_painb11 = 213;
public final static int FRAME_painb12 = 214;
public final static int FRAME_painb13 = 215;
public final static int FRAME_painb14 = 216;
public final static int FRAME_painb15 = 217;
public final static int FRAME_painb16 = 218;
public final static int FRAME_painb17 = 219;
public final static int FRAME_painb18 = 220;
public final static int FRAME_painb19 = 221;
public final static int FRAME_painb20 = 222;
public final static int FRAME_death1 = 223;
public final static int FRAME_death2 = 224;
public final static int FRAME_death3 = 225;
public final static int FRAME_death4 = 226;
public final static int FRAME_death5 = 227;
public final static int FRAME_death6 = 228;
public final static int FRAME_death7 = 229;
public final static int FRAME_death8 = 230;
public final static int FRAME_death9 = 231;
public final static int FRAME_death10 = 232;
public final static int FRAME_death11 = 233;
public final static int FRAME_death12 = 234;
public final static int FRAME_death13 = 235;
public final static int FRAME_deathc1 = 236;
public final static int FRAME_deathc2 = 237;
public final static int FRAME_deathc3 = 238;
public final static int FRAME_deathc4 = 239;
public final static int FRAME_deathc5 = 240;
public final static int FRAME_deathc6 = 241;
public final static int FRAME_deathc7 = 242;
public final static int FRAME_deathc8 = 243;
public final static float MODEL_SCALE = 1.000000f;
static int sound_pain;
static int sound_die;
static int sound_idle;
static int sound_punch;
static int sound_sight;
static int sound_search;
static EntInteractAdapter berserk_sight = new EntInteractAdapter() {
public String getID() {
return "berserk_sight";
}
public boolean interact(edict_t self, edict_t other) {
GameBase.gi.sound(self, Defines.CHAN_VOICE, sound_sight, 1,
Defines.ATTN_NORM, 0);
return true;
}
};
static EntThinkAdapter berserk_search = new EntThinkAdapter() {
public String getID() {
return "berserk_search";
}
public boolean think(edict_t self) {
GameBase.gi.sound(self, Defines.CHAN_VOICE, sound_search, 1,
Defines.ATTN_NORM, 0);
return true;
}
};
static EntThinkAdapter berserk_fidget = new EntThinkAdapter() {
public String getID() {
return "berserk_fidget";
}
public boolean think(edict_t self) {
if ((self.monsterinfo.aiflags & Defines.AI_STAND_GROUND) != 0) {
return true;
}
if (Lib.random() > 0.15f) {
return true;
}
self.monsterinfo.currentmove = berserk_move_stand_fidget;
GameBase.gi.sound(self, Defines.CHAN_WEAPON, sound_idle, 1,
Defines.ATTN_IDLE, 0);
return true;
}
};
static mframe_t berserk_frames_stand[] = new mframe_t[]{
new mframe_t(GameAI.ai_stand, 0, berserk_fidget),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null)};
static mmove_t berserk_move_stand = new mmove_t(FRAME_stand1, FRAME_stand5,
berserk_frames_stand, null);
static EntThinkAdapter berserk_stand = new EntThinkAdapter() {
public String getID() {
return "berserk_stand";
}
public boolean think(edict_t self) {
self.monsterinfo.currentmove = berserk_move_stand;
return true;
}
};
static mframe_t berserk_frames_stand_fidget[] = new mframe_t[]{
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null),
new mframe_t(GameAI.ai_stand, 0, null)};
static mmove_t berserk_move_stand_fidget = new mmove_t(FRAME_standb1,
FRAME_standb20, berserk_frames_stand_fidget, berserk_stand);
static mframe_t berserk_frames_walk[] = new mframe_t[]{
new mframe_t(GameAI.ai_walk, 9.1f, null),
new mframe_t(GameAI.ai_walk, 6.3f, null),
new mframe_t(GameAI.ai_walk, 4.9f, null),
new mframe_t(GameAI.ai_walk, 6.7f, null),
new mframe_t(GameAI.ai_walk, 6.0f, null),
new mframe_t(GameAI.ai_walk, 8.2f, null),
new mframe_t(GameAI.ai_walk, 7.2f, null),
new mframe_t(GameAI.ai_walk, 6.1f, null),
new mframe_t(GameAI.ai_walk, 4.9f, null),
new mframe_t(GameAI.ai_walk, 4.7f, null),
new mframe_t(GameAI.ai_walk, 4.7f, null),
new mframe_t(GameAI.ai_walk, 4.8f, null)};
static mmove_t berserk_move_walk = new mmove_t(FRAME_walkc1, FRAME_walkc11,
berserk_frames_walk, null);
static EntThinkAdapter berserk_walk = new EntThinkAdapter() {
public String getID() {
return "berserk_walk";
}
public boolean think(edict_t self) {
self.monsterinfo.currentmove = berserk_move_walk;
return true;
}
};
/*
*
* **************************** SKIPPED THIS FOR NOW!
* ****************************
*
* Running . Arm raised in air
*
* void() berserk_runb1 =[ $r_att1 , berserk_runb2 ] {ai_run(21);}; void()
* berserk_runb2 =[ $r_att2 , berserk_runb3 ] {ai_run(11);}; void()
* berserk_runb3 =[ $r_att3 , berserk_runb4 ] {ai_run(21);}; void()
* berserk_runb4 =[ $r_att4 , berserk_runb5 ] {ai_run(25);}; void()
* berserk_runb5 =[ $r_att5 , berserk_runb6 ] {ai_run(18);}; void()
* berserk_runb6 =[ $r_att6 , berserk_runb7 ] {ai_run(19);}; // running with
* arm in air : start loop void() berserk_runb7 =[ $r_att7 , berserk_runb8 ]
* {ai_run(21);}; void() berserk_runb8 =[ $r_att8 , berserk_runb9 ]
* {ai_run(11);}; void() berserk_runb9 =[ $r_att9 , berserk_runb10 ]
* {ai_run(21);}; void() berserk_runb10 =[ $r_att10 , berserk_runb11 ]
* {ai_run(25);}; void() berserk_runb11 =[ $r_att11 , berserk_runb12 ]
* {ai_run(18);}; void() berserk_runb12 =[ $r_att12 , berserk_runb7 ]
* {ai_run(19);}; // running with arm in air : end loop
*/
static mframe_t berserk_frames_run1[] = new mframe_t[]{
new mframe_t(GameAI.ai_run, 21, null),
new mframe_t(GameAI.ai_run, 11, null),
new mframe_t(GameAI.ai_run, 21, null),
new mframe_t(GameAI.ai_run, 25, null),
new mframe_t(GameAI.ai_run, 18, null),
new mframe_t(GameAI.ai_run, 19, null)};
static mmove_t berserk_move_run1 = new mmove_t(FRAME_run1, FRAME_run6,
berserk_frames_run1, null);
static EntThinkAdapter berserk_run = new EntThinkAdapter() {
public String getID() {
return "berserk_run";
}
public boolean think(edict_t self) {
if ((self.monsterinfo.aiflags & Defines.AI_STAND_GROUND) != 0) {
self.monsterinfo.currentmove = berserk_move_stand;
} else {
self.monsterinfo.currentmove = berserk_move_run1;
}
return true;
}
};
static EntThinkAdapter berserk_attack_spike = new EntThinkAdapter() {
public String getID() {
return "berserk_attack_spike";
}
public boolean think(edict_t self) {
float[] aim = {Defines.MELEE_DISTANCE, 0f, -24f};
GameWeapon.fire_hit(self, aim, (15 + (Lib.rand() % 6)), 400);
// Faster attack -- upwards and backwards
return true;
}
};
static EntThinkAdapter berserk_swing = new EntThinkAdapter() {
public String getID() {
return "berserk_swing";
}
public boolean think(edict_t self) {
GameBase.gi.sound(self, Defines.CHAN_WEAPON, sound_punch, 1,
Defines.ATTN_NORM, 0);
return true;
}
};
static mframe_t berserk_frames_attack_spike[] = new mframe_t[]{
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, berserk_swing),
new mframe_t(GameAI.ai_charge, 0, berserk_attack_spike),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null)};
static mmove_t berserk_move_attack_spike = new mmove_t(FRAME_att_c1,
FRAME_att_c8, berserk_frames_attack_spike, berserk_run);
static EntThinkAdapter berserk_attack_club = new EntThinkAdapter() {
public String getID() {
return "berserk_attack_club";
}
public boolean think(edict_t self) {
float aim[] = {0, 0, 0};
Math3D.VectorSet(aim, Defines.MELEE_DISTANCE, self.mins[0], -4);
GameWeapon.fire_hit(self, aim, (5 + (Lib.rand() % 6)), 400); // Slower
// attack
return true;
}
};
static mframe_t berserk_frames_attack_club[] = new mframe_t[]{
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, berserk_swing),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, berserk_attack_club),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null),
new mframe_t(GameAI.ai_charge, 0, null)};
static mmove_t berserk_move_attack_club = new mmove_t(FRAME_att_c9,
FRAME_att_c20, berserk_frames_attack_club, berserk_run);
static EntThinkAdapter berserk_strike = new EntThinkAdapter() {
public String getID() {
return "berserk_strike";
}
public boolean think(edict_t self) {
return true;
}
};
static mframe_t berserk_frames_attack_strike[] = new mframe_t[]{
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, berserk_swing),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, berserk_strike),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 9.7f, null),
new mframe_t(GameAI.ai_move, 13.6f, null)};
static mmove_t berserk_move_attack_strike = new mmove_t(FRAME_att_c21,
FRAME_att_c34, berserk_frames_attack_strike, berserk_run);
static EntThinkAdapter berserk_melee = new EntThinkAdapter() {
public String getID() {
return "berserk_melee";
}
public boolean think(edict_t self) {
if ((Lib.rand() % 2) == 0) {
self.monsterinfo.currentmove = berserk_move_attack_spike;
} else {
self.monsterinfo.currentmove = berserk_move_attack_club;
}
return true;
}
};
/*
* void() berserk_atke1 =[ $r_attb1, berserk_atke2 ] {ai_run(9);}; void()
* berserk_atke2 =[ $r_attb2, berserk_atke3 ] {ai_run(6);}; void()
* berserk_atke3 =[ $r_attb3, berserk_atke4 ] {ai_run(18.4);}; void()
* berserk_atke4 =[ $r_attb4, berserk_atke5 ] {ai_run(25);}; void()
* berserk_atke5 =[ $r_attb5, berserk_atke6 ] {ai_run(14);}; void()
* berserk_atke6 =[ $r_attb6, berserk_atke7 ] {ai_run(20);}; void()
* berserk_atke7 =[ $r_attb7, berserk_atke8 ] {ai_run(8.5);}; void()
* berserk_atke8 =[ $r_attb8, berserk_atke9 ] {ai_run(3);}; void()
* berserk_atke9 =[ $r_attb9, berserk_atke10 ] {ai_run(17.5);}; void()
* berserk_atke10 =[ $r_attb10, berserk_atke11 ] {ai_run(17);}; void()
* berserk_atke11 =[ $r_attb11, berserk_atke12 ] {ai_run(9);}; void()
* berserk_atke12 =[ $r_attb12, berserk_atke13 ] {ai_run(25);}; void()
* berserk_atke13 =[ $r_attb13, berserk_atke14 ] {ai_run(3.7);}; void()
* berserk_atke14 =[ $r_attb14, berserk_atke15 ] {ai_run(2.6);}; void()
* berserk_atke15 =[ $r_attb15, berserk_atke16 ] {ai_run(19);}; void()
* berserk_atke16 =[ $r_attb16, berserk_atke17 ] {ai_run(25);}; void()
* berserk_atke17 =[ $r_attb17, berserk_atke18 ] {ai_run(19.6);}; void()
* berserk_atke18 =[ $r_attb18, berserk_run1 ] {ai_run(7.8);};
*/
static mframe_t berserk_frames_pain1[] = new mframe_t[]{
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null)};
static mmove_t berserk_move_pain1 = new mmove_t(FRAME_painc1, FRAME_painc4,
berserk_frames_pain1, berserk_run);
static mframe_t berserk_frames_pain2[] = new mframe_t[]{
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null)};
static mmove_t berserk_move_pain2 = new mmove_t(FRAME_painb1,
FRAME_painb20, berserk_frames_pain2, berserk_run);
static EntPainAdapter berserk_pain = new EntPainAdapter() {
public String getID() {
return "berserk_pain";
}
public void pain(edict_t self, edict_t other, float kick, int damage) {
if (self.health < (self.max_health / 2)) {
self.s.skinnum = 1;
}
if (GameBase.level.time < self.pain_debounce_time) {
return;
}
self.pain_debounce_time = GameBase.level.time + 3;
GameBase.gi.sound(self, Defines.CHAN_VOICE, sound_pain, 1,
Defines.ATTN_NORM, 0);
if (GameBase.skill.value == 3) {
return; // no pain anims in nightmare
}
if ((damage < 20) || (Lib.random() < 0.5)) {
self.monsterinfo.currentmove = berserk_move_pain1;
} else {
self.monsterinfo.currentmove = berserk_move_pain2;
}
}
};
static EntThinkAdapter berserk_dead = new EntThinkAdapter() {
public String getID() {
return "berserk_dead";
}
public boolean think(edict_t self) {
Math3D.VectorSet(self.mins, -16, -16, -24);
Math3D.VectorSet(self.maxs, 16, 16, -8);
self.movetype = Defines.MOVETYPE_TOSS;
self.svflags |= Defines.SVF_DEADMONSTER;
self.nextthink = 0;
GameBase.gi.linkentity(self);
return true;
}
};
static mframe_t berserk_frames_death1[] = new mframe_t[]{
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null)};
static mmove_t berserk_move_death1 = new mmove_t(FRAME_death1,
FRAME_death13, berserk_frames_death1, berserk_dead);
static mframe_t berserk_frames_death2[] = new mframe_t[]{
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null),
new mframe_t(GameAI.ai_move, 0, null)};
static mmove_t berserk_move_death2 = new mmove_t(FRAME_deathc1,
FRAME_deathc8, berserk_frames_death2, berserk_dead);
static EntDieAdapter berserk_die = new EntDieAdapter() {
public String getID() {
return "berserk_die";
}
public void die(edict_t self, edict_t inflictor, edict_t attacker,
int damage, float point[]) {
int n;
if (self.health <= self.gib_health) {
GameBase.gi.sound(self, Defines.CHAN_VOICE, GameBase.gi.soundindex("misc/udeath.wav"), 1,
Defines.ATTN_NORM, 0);
for (n = 0; n < 2; n++) {
GameMisc.ThrowGib(self, "models/objects/gibs/bone/tris.md2",
damage, Defines.GIB_ORGANIC);
}
for (n = 0; n < 4; n++) {
GameMisc.ThrowGib(self,
"models/objects/gibs/sm_meat/tris.md2", damage,
Defines.GIB_ORGANIC);
}
GameMisc.ThrowHead(self, "models/objects/gibs/head2/tris.md2",
damage, Defines.GIB_ORGANIC);
self.deadflag = Defines.DEAD_DEAD;
return;
}
if (self.deadflag == Defines.DEAD_DEAD) {
return;
}
GameBase.gi.sound(self, Defines.CHAN_VOICE, sound_die, 1,
Defines.ATTN_NORM, 0);
self.deadflag = Defines.DEAD_DEAD;
self.takedamage = Defines.DAMAGE_YES;
if (damage >= 50) {
self.monsterinfo.currentmove = berserk_move_death1;
} else {
self.monsterinfo.currentmove = berserk_move_death2;
}
}
};
/*
* QUAKED monster_berserk (1 .5 0) (-16 -16 -24) (16 16 32) Ambush
* Trigger_Spawn Sight
*/
public static void SP_monster_berserk(edict_t self) {
if (GameBase.deathmatch.value != 0) {
GameUtil.G_FreeEdict(self);
return;
}
// pre-caches
sound_pain = GameBase.gi.soundindex("berserk/berpain2.wav");
sound_die = GameBase.gi.soundindex("berserk/berdeth2.wav");
sound_idle = GameBase.gi.soundindex("berserk/beridle1.wav");
sound_punch = GameBase.gi.soundindex("berserk/attack.wav");
sound_search = GameBase.gi.soundindex("berserk/bersrch1.wav");
sound_sight = GameBase.gi.soundindex("berserk/sight.wav");
self.s.modelindex = GameBase.gi.modelindex("models/monsters/berserk/tris.md2");
Math3D.VectorSet(self.mins, -16, -16, -24);
Math3D.VectorSet(self.maxs, 16, 16, 32);
self.movetype = Defines.MOVETYPE_STEP;
self.solid = Defines.SOLID_BBOX;
self.health = 240;
self.gib_health = -60;
self.mass = 250;
self.pain = berserk_pain;
self.die = berserk_die;
self.monsterinfo.stand = berserk_stand;
self.monsterinfo.walk = berserk_walk;
self.monsterinfo.run = berserk_run;
self.monsterinfo.dodge = null;
self.monsterinfo.attack = null;
self.monsterinfo.melee = berserk_melee;
self.monsterinfo.sight = berserk_sight;
self.monsterinfo.search = berserk_search;
self.monsterinfo.currentmove = berserk_move_stand;
self.monsterinfo.scale = MODEL_SCALE;
GameBase.gi.linkentity(self);
GameAI.walkmonster_start.think(self);
}
}
| |
package textadventure;
import java.util.ArrayList;
import java.util.EnumMap;
import textadventure.MapArea.roomConnectionDirection;
/**
* Represents a single area in the map. Contains connections to other areas
* of the map, a description and a piece of the story, items, locks, and puzzles.
*/
class MapRoom {
// ******************
// ***** Fields *****
// ******************
private String roomName; // A short, 1 - 2 word description for the room
private String roomEntryText; // The description of the room, to be displayed when entering
private String roomEntryStoryText; // The story attached to the room, to be displayed right before entering
private EnumMap<roomConnectionDirection, MapRoom> connectedMapRooms; // A list of connected rooms
private EnumMap<roomConnectionDirection, Boolean> directionIsLocked; // A list of booleans tracking locked directions
private EnumMap<roomConnectionDirection, DirectionLock> directionLockMechanism; // A list of DirectionLocks for connected rooms
private ArrayList<Item> itemsInRoom; // A list of items in the room
private boolean roomHasBeenVisited; // A boolean tracking whether the player has already been in the room
// ************************
// ***** Constructors *****
// ************************
/**
* Creates a room object, using the given name and description.
* @param newRoomName The brief, 1 - 2 word description for the room.
* @param newRoomEntryText The detailed description of the room.
*/
MapRoom(String newRoomName, String newRoomEntryText) {
this.roomName = newRoomName;
this.roomEntryText = newRoomEntryText;
this.connectedMapRooms = new EnumMap<>(roomConnectionDirection.class);
this.directionIsLocked = new EnumMap<>(roomConnectionDirection.class);
this.directionLockMechanism = new EnumMap<>(roomConnectionDirection.class);
setConnectedMapRoomsToNull();
setDirectionLocksToNull();
this.itemsInRoom = new ArrayList<>();
this.roomHasBeenVisited = false;
}
// *******************
// ***** Methods *****
// *******************
/**
* Prints a list of connected rooms to the console in a natural
* sentence-like format.
* @param room Room to print connected rooms for.
*/
private static void printConnectedMapRooms(MapRoom room) {
StringBuffer stringBuffer = new StringBuffer("");
int count = 0;
int stopCount = 0;
// Loop through connected map rooms to count them
// This is important for creating a more natural output
for (roomConnectionDirection direction : roomConnectionDirection.values()) {
if (room.getConnectedMapRooms().get(direction) != null) {
stopCount++;
}
}
// Loop through connected map rooms to output in a sentence-style format.
for (roomConnectionDirection direction : roomConnectionDirection.values()) {
if (room.getConnectedMapRooms().get(direction) != null) {
// If this is the first connected room, start the sentence
if (count == 0) {
// Record connected room and direction
if (direction == roomConnectionDirection.DIRECTION_UP) {
stringBuffer.append("This room is connected to a " + room.getConnectedMapRooms().get(direction).getRoomName() + " upstairs.");
} else if (direction == roomConnectionDirection.DIRECTION_DOWN) {
stringBuffer.append("This room is connected to a " + room.getConnectedMapRooms().get(direction).getRoomName() + " downstairs.");
} else {
stringBuffer.append("This room is connected to a " + room.getConnectedMapRooms().get(direction).getRoomName() +
" to the " + MapArea.convertDirectionToString(direction));
}
count++;
} else if (count > 0 && count < stopCount - 1) {
if (direction == roomConnectionDirection.DIRECTION_UP) {
stringBuffer.append("\na " + room.getConnectedMapRooms().get(direction).getRoomName() + " upstairs,");
} else if (direction == roomConnectionDirection.DIRECTION_DOWN) {
stringBuffer.append("\na " + room.getConnectedMapRooms().get(direction).getRoomName() + " downstairs,");
} else {
stringBuffer.append("\na " + room.getConnectedMapRooms().get(direction).getRoomName() +
" to the " + MapArea.convertDirectionToString(direction) + ",");
}
count++;
} else if (count == stopCount - 1){
if (direction == roomConnectionDirection.DIRECTION_UP) {
stringBuffer.append("\nand a " + room.getConnectedMapRooms().get(direction).getRoomName() + " upstairs");
} else if (direction == roomConnectionDirection.DIRECTION_DOWN) {
stringBuffer.append("\nand a " + room.getConnectedMapRooms().get(direction).getRoomName() + " downstairs");
} else {
stringBuffer.append("\nand a " + room.getConnectedMapRooms().get(direction).getRoomName() +
" to the " + MapArea.convertDirectionToString(direction));
}
}
}
}
stringBuffer.append(".");
System.out.println(stringBuffer);
}
/**
* Adds a DirectionLock to a room, in the given direction.
* @param direction Direction to lock.
* @param lock DirectionLock object to set in that direction.
*/
void addLockToDirection(roomConnectionDirection direction, DirectionLock lock) {
// Check if that direction is already locked
if (!this.isLocked(direction)) {
// Set that direction to locked, add DirectionLock object to travel table
this.directionIsLocked.put(direction, true);
this.directionLockMechanism.put(direction, lock);
}
}
/**
* Checks if a room is locked in the given direction.
* @param direction Direction to check.
* @return Returns true if it is locked, false if it is not.
*/
boolean isLocked(roomConnectionDirection direction) {
return this.directionIsLocked.get(direction) != null && this.directionIsLocked.get(direction);
}
/**
* Unlocks the DirectionLock in a room for the given direction.
* @param direction Direction to unlock.
*/
void unlock(roomConnectionDirection direction) {
if (this.isLocked(direction)) {
this.directionIsLocked.replace(direction, false);
}
}
/**
* Returns the DirectionLock object for the given direction.
* @param direction Direction to get.
* @return The DirectionLock in the given direction.
*/
DirectionLock getDirectionLock(roomConnectionDirection direction) {
if (this.isLocked(direction)) {
return this.directionLockMechanism.get(direction);
}
return null;
}
/**
* Prints a description of the room to the console, including items in the room
* @param room Room to show
*/
static void lookAroundRoom(MapRoom room) {
final int WORDWRAP_LINE_LIMITER = 100;
System.out.println("");
System.out.println(FileIO.formatTextForConsole(room.getRoomEntryText(), WORDWRAP_LINE_LIMITER));
// Display connected rooms to player's current room
System.out.println("");
MapRoom.printConnectedMapRooms(room);
System.out.println("");
// Display items in the room
if (!room.getItemsInRoom().isEmpty()) {
System.out.println("\nItems in room:");
for (Item item : room.getItemsInRoom()) {
System.out.println(item.getName());
}
System.out.println("");
}
}
// *******************************
// ***** Getters and Setters *****
// *******************************
private String getRoomEntryText() {
return this.roomEntryText;
}
String getRoomEntryStoryText() {
return roomEntryStoryText;
}
void setRoomHasBeenVisited(boolean bool) {
this.roomHasBeenVisited = bool;
}
boolean hasRoomBeenVisited() {
return roomHasBeenVisited;
}
void setRoomEntryStoryText(String string) {
this.roomEntryStoryText = string;
}
String getRoomName() {
return this.roomName;
}
EnumMap<roomConnectionDirection, MapRoom> getConnectedMapRooms() {
return this.connectedMapRooms;
}
/**
* Sets all rooms connected to this room to null, to prevent errors with null access exceptions
*/
private void setConnectedMapRoomsToNull() {
for (roomConnectionDirection direction : roomConnectionDirection.values()) {
this.connectedMapRooms.put(direction, null);
}
}
/**
* Sets all DirectionLocks in a room to null, to prevent errors with null access exceptions
*/
private void setDirectionLocksToNull() {
for (roomConnectionDirection direction : directionIsLocked.keySet()) {
directionIsLocked.put(direction, null);
}
for (roomConnectionDirection direction : directionLockMechanism.keySet()) {
directionLockMechanism.put(direction, null);
}
}
ArrayList<Item> getItemsInRoom() {
return this.itemsInRoom;
}
}
| |
/* Copyright (c) 2012 Google 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 common.services.billing;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import com.android.vending.billing.IInAppBillingService;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
/**
* Provides convenience methods for in-app billing. You can create one instance of this
* class for your application and use it to process in-app billing operations.
* It provides synchronous (blocking) and asynchronous (non-blocking) methods for
* many common in-app billing operations, as well as automatic signature
* verification.
*
* After instantiating, you must perform setup in order to start using the object.
* To perform setup, call the {@link #startSetup} method and provide a listener;
* that listener will be notified when setup is complete, after which (and not before)
* you may call other methods.
*
* After setup is complete, you will typically want to request an inventory of owned
* items and subscriptions. See {@link #queryInventory}, {@link #queryInventoryAsync}
* and related methods.
*
* When you are done with this object, don't forget to call {@link #dispose}
* to ensure proper cleanup. This object holds a binding to the in-app billing
* service, which will leak unless you dispose of it correctly. If you created
* the object on an Activity's onCreate method, then the recommended
* place to dispose of it is the Activity's onDestroy method.
*
* A note about threading: When using this object from a background thread, you may
* call the blocking versions of methods; when using from a UI thread, call
* only the asynchronous versions and handle the results via callbacks.
* Also, notice that you can only call one asynchronous operation at a time;
* attempting to start a second asynchronous operation while the first one
* has not yet completed will result in an exception being thrown.
*
* @author Bruno Oliveira (Google)
*
*/
public class IabHelper {
// Is debug logging enabled?
boolean mDebugLog = false;
String mDebugTag = "IabHelper";
// Is setup done?
boolean mSetupDone = false;
// Has this object been disposed of? (If so, we should ignore callbacks, etc)
boolean mDisposed = false;
// Are subscriptions supported?
boolean mSubscriptionsSupported = false;
// Is an asynchronous operation in progress?
// (only one at a time can be in progress)
boolean mAsyncInProgress = false;
// (for logging/debugging)
// if mAsyncInProgress == true, what asynchronous operation is in progress?
String mAsyncOperation = "";
// Context we were passed during initialization
Context mContext;
// Connection to the service
IInAppBillingService mService;
ServiceConnection mServiceConn;
// The request code used to launch purchase flow
int mRequestCode;
// The item type of the current purchase flow
String mPurchasingItemType;
// Public key for verifying signature, in base64 encoding
String mSignatureBase64 = null;
// Billing response codes
public static final int BILLING_RESPONSE_RESULT_OK = 0;
public static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1;
public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3;
public static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4;
public static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5;
public static final int BILLING_RESPONSE_RESULT_ERROR = 6;
public static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7;
public static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8;
// IAB Helper error codes
public static final int IABHELPER_ERROR_BASE = -1000;
public static final int IABHELPER_REMOTE_EXCEPTION = -1001;
public static final int IABHELPER_BAD_RESPONSE = -1002;
public static final int IABHELPER_VERIFICATION_FAILED = -1003;
public static final int IABHELPER_SEND_INTENT_FAILED = -1004;
public static final int IABHELPER_USER_CANCELLED = -1005;
public static final int IABHELPER_UNKNOWN_PURCHASE_RESPONSE = -1006;
public static final int IABHELPER_MISSING_TOKEN = -1007;
public static final int IABHELPER_UNKNOWN_ERROR = -1008;
public static final int IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE = -1009;
public static final int IABHELPER_INVALID_CONSUMPTION = -1010;
// Keys for the responses from InAppBillingService
public static final String RESPONSE_CODE = "RESPONSE_CODE";
public static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST";
public static final String RESPONSE_BUY_INTENT = "BUY_INTENT";
public static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA";
public static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE";
public static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST";
public static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST";
public static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST";
public static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN";
// Item types
public static final String ITEM_TYPE_INAPP = "inapp";
public static final String ITEM_TYPE_SUBS = "subs";
// some fields on the getSkuDetails response bundle
public static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST";
public static final String GET_SKU_DETAILS_ITEM_TYPE_LIST = "ITEM_TYPE_LIST";
/**
* Creates an instance. After creation, it will not yet be ready to use. You must perform
* setup by calling {@link #startSetup} and wait for setup to complete. This constructor does not
* block and is safe to call from a UI thread.
*
* @param ctx Your application or Activity context. Needed to bind to the in-app billing service.
* @param base64PublicKey Your application's public key, encoded in base64.
* This is used for verification of purchase signatures. You can find your app's base64-encoded
* public key in your application's page on Google Play Developer Console. Note that this
* is NOT your "developer public key".
*/
public IabHelper(Context ctx, String base64PublicKey) {
mContext = ctx.getApplicationContext();
mSignatureBase64 = base64PublicKey;
logDebug("IAB helper created.");
}
/**
* Enables or disable debug logging through LogCat.
*/
public void enableDebugLogging(boolean enable, String tag) {
checkNotDisposed();
mDebugLog = enable;
mDebugTag = tag;
}
public void enableDebugLogging(boolean enable) {
checkNotDisposed();
mDebugLog = enable;
}
/**
* Callback for setup process. This listener's {@link #onIabSetupFinished} method is called
* when the setup process is complete.
*/
public interface OnIabSetupFinishedListener {
/**
* Called to notify that setup is complete.
*
* @param result The result of the setup process.
*/
public void onIabSetupFinished(IabResult result);
}
/**
* Starts the setup process. This will start up the setup process asynchronously.
* You will be notified through the listener when the setup process is complete.
* This method is safe to call from a UI thread.
*
* @param listener The listener to notify when the setup process is complete.
*/
public void startSetup(final OnIabSetupFinishedListener listener) {
// If already set up, can't do it again.
checkNotDisposed();
if (mSetupDone) throw new IllegalStateException("IAB helper is already set up.");
// Connection to IAB service
logDebug("Starting in-app billing setup.");
mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
logDebug("Billing service disconnected.");
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (mDisposed) return;
logDebug("Billing service connected.");
mService = IInAppBillingService.Stub.asInterface(service);
String packageName = mContext.getPackageName();
try {
logDebug("Checking for in-app billing 3 support.");
// check for in-app billing v3 support
int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP);
if (response != BILLING_RESPONSE_RESULT_OK) {
if (listener != null) listener.onIabSetupFinished(new IabResult(response,
"Error checking for billing v3 support."));
// if in-app purchases aren't supported, neither are subscriptions.
mSubscriptionsSupported = false;
return;
}
logDebug("In-app billing version 3 supported for " + packageName);
// check for v3 subscriptions support
response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS);
if (response == BILLING_RESPONSE_RESULT_OK) {
logDebug("Subscriptions AVAILABLE.");
mSubscriptionsSupported = true;
}
else {
logDebug("Subscriptions NOT AVAILABLE. Response: " + response);
}
mSetupDone = true;
}
catch (RemoteException e) {
if (listener != null) {
listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION,
"RemoteException while setting up in-app billing."));
}
e.printStackTrace();
return;
}
if (listener != null) {
listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful."));
}
}
};
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
}
/**
* Dispose of object, releasing resources. It's very important to call this
* method when you are done with this object. It will release any resources
* used by it such as service connections. Naturally, once the object is
* disposed of, it can't be used again.
*/
public void dispose() {
logDebug("Disposing.");
mSetupDone = false;
if (mServiceConn != null) {
logDebug("Unbinding from service.");
if (mContext != null) mContext.unbindService(mServiceConn);
}
mDisposed = true;
mContext = null;
mServiceConn = null;
mService = null;
mPurchaseListener = null;
}
private void checkNotDisposed() {
if (mDisposed) throw new IllegalStateException("IabHelper was disposed of, so it cannot be used.");
}
/** Returns whether subscriptions are supported. */
public boolean subscriptionsSupported() {
checkNotDisposed();
return mSubscriptionsSupported;
}
/**
* Callback that notifies when a purchase is finished.
*/
public interface OnIabPurchaseFinishedListener {
/**
* Called to notify that an in-app purchase finished. If the purchase was successful,
* then the sku parameter specifies which item was purchased. If the purchase failed,
* the sku and extraData parameters may or may not be null, depending on how far the purchase
* process went.
*
* @param result The result of the purchase.
* @param info The purchase information (null if purchase failed)
*/
public void onIabPurchaseFinished(IabResult result, Purchase info);
}
// The listener registered on launchPurchaseFlow, which we have to call back when
// the purchase finishes
OnIabPurchaseFinishedListener mPurchaseListener;
public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) {
launchPurchaseFlow(act, sku, requestCode, listener, "");
}
public void launchPurchaseFlow(Activity act, String sku, int requestCode,
OnIabPurchaseFinishedListener listener, String extraData) {
launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, requestCode, listener, extraData);
}
public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode,
OnIabPurchaseFinishedListener listener) {
launchSubscriptionPurchaseFlow(act, sku, requestCode, listener, "");
}
public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode,
OnIabPurchaseFinishedListener listener, String extraData) {
launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, requestCode, listener, extraData);
}
/**
* Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase,
* which will involve bringing up the Google Play screen. The calling activity will be paused while
* the user interacts with Google Play, and the result will be delivered via the activity's
* {@link android.app.Activity#onActivityResult} method, at which point you must call
* this object's {@link #handleActivityResult} method to continue the purchase flow. This method
* MUST be called from the UI thread of the Activity.
*
* @param act The calling activity.
* @param sku The sku of the item to purchase.
* @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS)
* @param requestCode A request code (to differentiate from other responses --
* as in {@link android.app.Activity#startActivityForResult}).
* @param listener The listener to notify when the purchase process finishes
* @param extraData Extra data (developer payload), which will be returned with the purchase data
* when the purchase completes. This extra data will be permanently bound to that purchase
* and will always be returned when the purchase is queried.
*/
public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode,
OnIabPurchaseFinishedListener listener, String extraData) {
checkNotDisposed();
checkSetupDone("launchPurchaseFlow");
flagStartAsync("launchPurchaseFlow");
IabResult result;
if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) {
IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE,
"Subscriptions are not available.");
flagEndAsync();
if (listener != null) listener.onIabPurchaseFinished(r, null);
return;
}
try {
logDebug("Constructing buy intent for " + sku + ", item type: " + itemType);
Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData);
int response = getResponseCodeFromBundle(buyIntentBundle);
if (response != BILLING_RESPONSE_RESULT_OK) {
logError("Unable to buy item, Error response: " + getResponseDesc(response));
flagEndAsync();
result = new IabResult(response, "Unable to buy item");
if (listener != null) listener.onIabPurchaseFinished(result, null);
return;
}
PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode);
mRequestCode = requestCode;
mPurchaseListener = listener;
mPurchasingItemType = itemType;
act.startIntentSenderForResult(pendingIntent.getIntentSender(),
requestCode, new Intent(),
Integer.valueOf(0), Integer.valueOf(0),
Integer.valueOf(0));
}
catch (SendIntentException e) {
logError("SendIntentException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
if (listener != null) listener.onIabPurchaseFinished(result, null);
}
catch (RemoteException e) {
logError("RemoteException while launching purchase flow for sku " + sku);
e.printStackTrace();
flagEndAsync();
result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
if (listener != null) listener.onIabPurchaseFinished(result, null);
}
}
/**
* Handles an activity result that's part of the purchase flow in in-app billing. If you
* are calling {@link #launchPurchaseFlow}, then you must call this method from your
* Activity's {@link android.app.Activity@onActivityResult} method. This method
* MUST be called from the UI thread of the Activity.
*
* @param requestCode The requestCode as you received it.
* @param resultCode The resultCode as you received it.
* @param data The data (Intent) as you received it.
* @return Returns true if the result was related to a purchase flow and was handled;
* false if the result was not related to a purchase, in which case you should
* handle it normally.
*/
public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
IabResult result;
if (requestCode != mRequestCode) return false;
checkNotDisposed();
checkSetupDone("handleActivityResult");
// end of async purchase operation that started on launchPurchaseFlow
flagEndAsync();
if (data == null) {
logError("Null data in IAB activity result.");
result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
return true;
}
int responseCode = getResponseCodeFromIntent(data);
String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA);
String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE);
if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) {
logDebug("Successful resultcode from purchase activity.");
logDebug("Purchase data: " + purchaseData);
logDebug("Data signature: " + dataSignature);
logDebug("Extras: " + data.getExtras());
logDebug("Expected item type: " + mPurchasingItemType);
if (purchaseData == null || dataSignature == null) {
logError("BUG: either purchaseData or dataSignature is null.");
logDebug("Extras: " + data.getExtras().toString());
result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
return true;
}
Purchase purchase = null;
try {
purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature);
String sku = purchase.getSku();
// Verify signature
if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) {
logError("Purchase signature verification FAILED for sku " + sku);
result = new IabResult(IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku);
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, purchase);
return true;
}
logDebug("Purchase signature successfully verified.");
}
catch (JSONException e) {
logError("Failed to parse purchase data.");
e.printStackTrace();
result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data.");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
return true;
}
if (mPurchaseListener != null) {
mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase);
}
}
else if (resultCode == Activity.RESULT_OK) {
// result code was OK, but in-app billing response was not OK.
logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode));
if (mPurchaseListener != null) {
result = new IabResult(responseCode, "Problem purchashing item.");
mPurchaseListener.onIabPurchaseFinished(result, null);
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode));
result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled.");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
}
else {
logError("Purchase failed. Result code: " + Integer.toString(resultCode)
+ ". Response: " + getResponseDesc(responseCode));
result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response.");
if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null);
}
return true;
}
public Inventory queryInventory(boolean querySkuDetails, List<String> moreSkus) throws IabException {
return queryInventory(querySkuDetails, moreSkus, null);
}
/**
* Queries the inventory. This will query all owned items from the server, as well as
* information on additional skus, if specified. This method may block or take long to execute.
* Do not call from a UI thread. For that, use the non-blocking version {@link #refreshInventoryAsync}.
*
* @param querySkuDetails if true, SKU details (price, description, etc) will be queried as well
* as purchase information.
* @param moreItemSkus additional PRODUCT skus to query information on, regardless of ownership.
* Ignored if null or if querySkuDetails is false.
* @param moreSubsSkus additional SUBSCRIPTIONS skus to query information on, regardless of ownership.
* Ignored if null or if querySkuDetails is false.
* @throws IabException if a problem occurs while refreshing the inventory.
*/
public Inventory queryInventory(boolean querySkuDetails, List<String> moreItemSkus,
List<String> moreSubsSkus) throws IabException {
checkNotDisposed();
checkSetupDone("queryInventory");
try {
Inventory inv = new Inventory();
int r = queryPurchases(inv, ITEM_TYPE_INAPP);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying owned items).");
}
if (querySkuDetails) {
r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of items).");
}
}
// if subscriptions are supported, then also query for subscriptions
if (mSubscriptionsSupported) {
r = queryPurchases(inv, ITEM_TYPE_SUBS);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying owned subscriptions).");
}
if (querySkuDetails) {
r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreItemSkus);
if (r != BILLING_RESPONSE_RESULT_OK) {
throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions).");
}
}
}
return inv;
}
catch (RemoteException e) {
throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e);
}
catch (JSONException e) {
throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e);
}
}
/**
* Listener that notifies when an inventory query operation completes.
*/
public interface QueryInventoryFinishedListener {
/**
* Called to notify that an inventory query operation completed.
*
* @param result The result of the operation.
* @param inv The inventory.
*/
public void onQueryInventoryFinished(IabResult result, Inventory inv);
}
/**
* Asynchronous wrapper for inventory query. This will perform an inventory
* query as described in {@link #queryInventory}, but will do so asynchronously
* and call back the specified listener upon completion. This method is safe to
* call from a UI thread.
*
* @param querySkuDetails as in {@link #queryInventory}
* @param moreSkus as in {@link #queryInventory}
* @param listener The listener to notify when the refresh operation completes.
*/
public void queryInventoryAsync(final boolean querySkuDetails,
final List<String> moreSkus,
final QueryInventoryFinishedListener listener) {
final Handler handler = new Handler();
checkNotDisposed();
checkSetupDone("queryInventory");
flagStartAsync("refresh inventory");
(new Thread(new Runnable() {
public void run() {
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
Inventory inv = null;
try {
inv = queryInventory(querySkuDetails, moreSkus);
}
catch (IabException ex) {
result = ex.getResult();
}
flagEndAsync();
final IabResult result_f = result;
final Inventory inv_f = inv;
if (!mDisposed && listener != null) {
handler.post(new Runnable() {
public void run() {
listener.onQueryInventoryFinished(result_f, inv_f);
}
});
}
}
})).start();
}
public void queryInventoryAsync(QueryInventoryFinishedListener listener) {
queryInventoryAsync(true, null, listener);
}
public void queryInventoryAsync(boolean querySkuDetails, QueryInventoryFinishedListener listener) {
queryInventoryAsync(querySkuDetails, null, listener);
}
/**
* Consumes a given in-app product. Consuming can only be done on an item
* that's owned, and as a result of consumption, the user will no longer own it.
* This method may block or take long to return. Do not call from the UI thread.
* For that, see {@link #consumeAsync}.
*
* @param itemInfo The PurchaseInfo that represents the item to consume.
* @throws IabException if there is a problem during consumption.
*/
void consume(Purchase itemInfo) throws IabException {
checkNotDisposed();
checkSetupDone("consume");
if (!itemInfo.mItemType.equals(ITEM_TYPE_INAPP)) {
throw new IabException(IABHELPER_INVALID_CONSUMPTION,
"Items of type '" + itemInfo.mItemType + "' can't be consumed.");
}
try {
String token = itemInfo.getToken();
String sku = itemInfo.getSku();
if (token == null || token.equals("")) {
logError("Can't consume "+ sku + ". No token.");
throw new IabException(IABHELPER_MISSING_TOKEN, "PurchaseInfo is missing token for sku: "
+ sku + " " + itemInfo);
}
logDebug("Consuming sku: " + sku + ", token: " + token);
int response = mService.consumePurchase(3, mContext.getPackageName(), token);
if (response == BILLING_RESPONSE_RESULT_OK) {
logDebug("Successfully consumed sku: " + sku);
}
else {
logDebug("Error consuming consuming sku " + sku + ". " + getResponseDesc(response));
throw new IabException(response, "Error consuming sku " + sku);
}
}
catch (RemoteException e) {
throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while consuming. PurchaseInfo: " + itemInfo, e);
}
}
/**
* Callback that notifies when a consumption operation finishes.
*/
public interface OnConsumeFinishedListener {
/**
* Called to notify that a consumption has finished.
*
* @param purchase The purchase that was (or was to be) consumed.
* @param result The result of the consumption operation.
*/
public void onConsumeFinished(Purchase purchase, IabResult result);
}
/**
* Callback that notifies when a multi-item consumption operation finishes.
*/
public interface OnConsumeMultiFinishedListener {
/**
* Called to notify that a consumption of multiple items has finished.
*
* @param purchases The purchases that were (or were to be) consumed.
* @param results The results of each consumption operation, corresponding to each
* sku.
*/
public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results);
}
/**
* Asynchronous wrapper to item consumption. Works like {@link #consume}, but
* performs the consumption in the background and notifies completion through
* the provided listener. This method is safe to call from a UI thread.
*
* @param purchase The purchase to be consumed.
* @param listener The listener to notify when the consumption operation finishes.
*/
public void consumeAsync(Purchase purchase, OnConsumeFinishedListener listener) {
checkNotDisposed();
checkSetupDone("consume");
List<Purchase> purchases = new ArrayList<Purchase>();
purchases.add(purchase);
consumeAsyncInternal(purchases, listener, null);
}
/**
* Same as {@link consumeAsync}, but for multiple items at once.
* @param purchases The list of PurchaseInfo objects representing the purchases to consume.
* @param listener The listener to notify when the consumption operation finishes.
*/
public void consumeAsync(List<Purchase> purchases, OnConsumeMultiFinishedListener listener) {
checkNotDisposed();
checkSetupDone("consume");
consumeAsyncInternal(purchases, null, listener);
}
/**
* Returns a human-readable description for the given response code.
*
* @param code The response code
* @return A human-readable string explaining the result code.
* It also includes the result code numerically.
*/
public static String getResponseDesc(int code) {
String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" +
"3:Billing Unavailable/4:Item unavailable/" +
"5:Developer Error/6:Error/7:Item Already Owned/" +
"8:Item not owned").split("/");
String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" +
"-1002:Bad response received/" +
"-1003:Purchase signature verification failed/" +
"-1004:Send intent failed/" +
"-1005:User cancelled/" +
"-1006:Unknown purchase response/" +
"-1007:Missing token/" +
"-1008:Unknown error/" +
"-1009:Subscriptions not available/" +
"-1010:Invalid consumption attempt").split("/");
if (code <= IABHELPER_ERROR_BASE) {
int index = IABHELPER_ERROR_BASE - code;
if (index >= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index];
else return String.valueOf(code) + ":Unknown IAB Helper Error";
}
else if (code < 0 || code >= iab_msgs.length)
return String.valueOf(code) + ":Unknown";
else
return iab_msgs[code];
}
// Checks that setup was done; if not, throws an exception.
void checkSetupDone(String operation) {
if (!mSetupDone) {
logError("Illegal state for operation (" + operation + "): IAB helper is not set up.");
throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + operation);
}
}
// Workaround to bug where sometimes response codes come as Long instead of Integer
int getResponseCodeFromBundle(Bundle b) {
Object o = b.get(RESPONSE_CODE);
if (o == null) {
logDebug("Bundle with null response code, assuming OK (known issue)");
return BILLING_RESPONSE_RESULT_OK;
}
else if (o instanceof Integer) return ((Integer)o).intValue();
else if (o instanceof Long) return (int)((Long)o).longValue();
else {
logError("Unexpected type for bundle response code.");
logError(o.getClass().getName());
throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName());
}
}
// Workaround to bug where sometimes response codes come as Long instead of Integer
int getResponseCodeFromIntent(Intent i) {
Object o = i.getExtras().get(RESPONSE_CODE);
if (o == null) {
logError("Intent with no response code, assuming OK (known issue)");
return BILLING_RESPONSE_RESULT_OK;
}
else if (o instanceof Integer) return ((Integer)o).intValue();
else if (o instanceof Long) return (int)((Long)o).longValue();
else {
logError("Unexpected type for intent response code.");
logError(o.getClass().getName());
throw new RuntimeException("Unexpected type for intent response code: " + o.getClass().getName());
}
}
void flagStartAsync(String operation) {
if (mAsyncInProgress) throw new IllegalStateException("Can't start async operation (" +
operation + ") because another async operation(" + mAsyncOperation + ") is in progress.");
mAsyncOperation = operation;
mAsyncInProgress = true;
logDebug("Starting async operation: " + operation);
}
void flagEndAsync() {
logDebug("Ending async operation: " + mAsyncOperation);
mAsyncOperation = "";
mAsyncInProgress = false;
}
int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException {
// Query purchases
logDebug("Querying owned items, item type: " + itemType);
logDebug("Package name: " + mContext.getPackageName());
boolean verificationFailed = false;
String continueToken = null;
do {
logDebug("Calling getPurchases with continuation token: " + continueToken);
Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(),
itemType, continueToken);
int response = getResponseCodeFromBundle(ownedItems);
logDebug("Owned items response: " + String.valueOf(response));
if (response != BILLING_RESPONSE_RESULT_OK) {
logDebug("getPurchases() failed: " + getResponseDesc(response));
return response;
}
if (!ownedItems.containsKey(RESPONSE_INAPP_ITEM_LIST)
|| !ownedItems.containsKey(RESPONSE_INAPP_PURCHASE_DATA_LIST)
|| !ownedItems.containsKey(RESPONSE_INAPP_SIGNATURE_LIST)) {
logError("Bundle returned from getPurchases() doesn't contain required fields.");
return IABHELPER_BAD_RESPONSE;
}
ArrayList<String> ownedSkus = ownedItems.getStringArrayList(
RESPONSE_INAPP_ITEM_LIST);
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList(
RESPONSE_INAPP_PURCHASE_DATA_LIST);
ArrayList<String> signatureList = ownedItems.getStringArrayList(
RESPONSE_INAPP_SIGNATURE_LIST);
for (int i = 0; i < purchaseDataList.size(); ++i) {
String purchaseData = purchaseDataList.get(i);
String signature = signatureList.get(i);
String sku = ownedSkus.get(i);
if (Security.verifyPurchase(mSignatureBase64, purchaseData, signature)) {
logDebug("Sku is owned: " + sku);
Purchase purchase = new Purchase(itemType, purchaseData, signature);
if (TextUtils.isEmpty(purchase.getToken())) {
logWarn("BUG: empty/null token!");
logDebug("Purchase data: " + purchaseData);
}
// Record ownership and token
inv.addPurchase(purchase);
}
else {
logWarn("Purchase signature verification **FAILED**. Not adding item.");
logDebug(" Purchase data: " + purchaseData);
logDebug(" Signature: " + signature);
verificationFailed = true;
}
}
continueToken = ownedItems.getString(INAPP_CONTINUATION_TOKEN);
logDebug("Continuation token: " + continueToken);
} while (!TextUtils.isEmpty(continueToken));
return verificationFailed ? IABHELPER_VERIFICATION_FAILED : BILLING_RESPONSE_RESULT_OK;
}
int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus)
throws RemoteException, JSONException {
logDebug("Querying SKU details.");
ArrayList<String> skuList = new ArrayList<String>();
skuList.addAll(inv.getAllOwnedSkus(itemType));
if (moreSkus != null) {
for (String sku : moreSkus) {
if (!skuList.contains(sku)) {
skuList.add(sku);
}
}
}
if (skuList.size() == 0) {
logDebug("queryPrices: nothing to do because there are no SKUs.");
return BILLING_RESPONSE_RESULT_OK;
}
Bundle querySkus = new Bundle();
querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList);
Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(),
itemType, querySkus);
if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
int response = getResponseCodeFromBundle(skuDetails);
if (response != BILLING_RESPONSE_RESULT_OK) {
logDebug("getSkuDetails() failed: " + getResponseDesc(response));
return response;
}
else {
logError("getSkuDetails() returned a bundle with neither an error nor a detail list.");
return IABHELPER_BAD_RESPONSE;
}
}
ArrayList<String> responseList = skuDetails.getStringArrayList(
RESPONSE_GET_SKU_DETAILS_LIST);
for (String thisResponse : responseList) {
SkuDetails d = new SkuDetails(itemType, thisResponse);
logDebug("Got sku details: " + d);
inv.addSkuDetails(d);
}
return BILLING_RESPONSE_RESULT_OK;
}
void consumeAsyncInternal(final List<Purchase> purchases,
final OnConsumeFinishedListener singleListener,
final OnConsumeMultiFinishedListener multiListener) {
final Handler handler = new Handler();
flagStartAsync("consume");
(new Thread(new Runnable() {
public void run() {
final List<IabResult> results = new ArrayList<IabResult>();
for (Purchase purchase : purchases) {
try {
consume(purchase);
results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku()));
}
catch (IabException ex) {
results.add(ex.getResult());
}
}
flagEndAsync();
if (!mDisposed && singleListener != null) {
handler.post(new Runnable() {
public void run() {
singleListener.onConsumeFinished(purchases.get(0), results.get(0));
}
});
}
if (!mDisposed && multiListener != null) {
handler.post(new Runnable() {
public void run() {
multiListener.onConsumeMultiFinished(purchases, results);
}
});
}
}
})).start();
}
void logDebug(String msg) {
if (mDebugLog) Log.d(mDebugTag, msg);
}
void logError(String msg) {
Log.e(mDebugTag, "In-app billing error: " + msg);
}
void logWarn(String msg) {
Log.w(mDebugTag, "In-app billing warning: " + msg);
}
}
| |
/*
* 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.importexport.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
* Input structure for the CreateJob operation.
*/
public class CreateJobRequest extends AmazonWebServiceRequest implements
Serializable, Cloneable {
private String jobType;
private String manifest;
private String manifestAddendum;
private Boolean validateOnly;
private String aPIVersion;
/**
* @param jobType
* @see JobType
*/
public void setJobType(String jobType) {
this.jobType = jobType;
}
/**
* @return
* @see JobType
*/
public String getJobType() {
return this.jobType;
}
/**
* @param jobType
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see JobType
*/
public CreateJobRequest withJobType(String jobType) {
setJobType(jobType);
return this;
}
/**
* @param jobType
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see JobType
*/
public void setJobType(JobType jobType) {
this.jobType = jobType.toString();
}
/**
* @param jobType
* @return Returns a reference to this object so that method calls can be
* chained together.
* @see JobType
*/
public CreateJobRequest withJobType(JobType jobType) {
setJobType(jobType);
return this;
}
/**
* @param manifest
*/
public void setManifest(String manifest) {
this.manifest = manifest;
}
/**
* @return
*/
public String getManifest() {
return this.manifest;
}
/**
* @param manifest
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public CreateJobRequest withManifest(String manifest) {
setManifest(manifest);
return this;
}
/**
* @param manifestAddendum
*/
public void setManifestAddendum(String manifestAddendum) {
this.manifestAddendum = manifestAddendum;
}
/**
* @return
*/
public String getManifestAddendum() {
return this.manifestAddendum;
}
/**
* @param manifestAddendum
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public CreateJobRequest withManifestAddendum(String manifestAddendum) {
setManifestAddendum(manifestAddendum);
return this;
}
/**
* @param validateOnly
*/
public void setValidateOnly(Boolean validateOnly) {
this.validateOnly = validateOnly;
}
/**
* @return
*/
public Boolean getValidateOnly() {
return this.validateOnly;
}
/**
* @param validateOnly
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public CreateJobRequest withValidateOnly(Boolean validateOnly) {
setValidateOnly(validateOnly);
return this;
}
/**
* @return
*/
public Boolean isValidateOnly() {
return this.validateOnly;
}
/**
* @param aPIVersion
*/
public void setAPIVersion(String aPIVersion) {
this.aPIVersion = aPIVersion;
}
/**
* @return
*/
public String getAPIVersion() {
return this.aPIVersion;
}
/**
* @param aPIVersion
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public CreateJobRequest withAPIVersion(String aPIVersion) {
setAPIVersion(aPIVersion);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getJobType() != null)
sb.append("JobType: " + getJobType() + ",");
if (getManifest() != null)
sb.append("Manifest: " + getManifest() + ",");
if (getManifestAddendum() != null)
sb.append("ManifestAddendum: " + getManifestAddendum() + ",");
if (getValidateOnly() != null)
sb.append("ValidateOnly: " + getValidateOnly() + ",");
if (getAPIVersion() != null)
sb.append("APIVersion: " + getAPIVersion());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateJobRequest == false)
return false;
CreateJobRequest other = (CreateJobRequest) obj;
if (other.getJobType() == null ^ this.getJobType() == null)
return false;
if (other.getJobType() != null
&& other.getJobType().equals(this.getJobType()) == false)
return false;
if (other.getManifest() == null ^ this.getManifest() == null)
return false;
if (other.getManifest() != null
&& other.getManifest().equals(this.getManifest()) == false)
return false;
if (other.getManifestAddendum() == null
^ this.getManifestAddendum() == null)
return false;
if (other.getManifestAddendum() != null
&& other.getManifestAddendum().equals(
this.getManifestAddendum()) == false)
return false;
if (other.getValidateOnly() == null ^ this.getValidateOnly() == null)
return false;
if (other.getValidateOnly() != null
&& other.getValidateOnly().equals(this.getValidateOnly()) == false)
return false;
if (other.getAPIVersion() == null ^ this.getAPIVersion() == null)
return false;
if (other.getAPIVersion() != null
&& other.getAPIVersion().equals(this.getAPIVersion()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getJobType() == null) ? 0 : getJobType().hashCode());
hashCode = prime * hashCode
+ ((getManifest() == null) ? 0 : getManifest().hashCode());
hashCode = prime
* hashCode
+ ((getManifestAddendum() == null) ? 0 : getManifestAddendum()
.hashCode());
hashCode = prime
* hashCode
+ ((getValidateOnly() == null) ? 0 : getValidateOnly()
.hashCode());
hashCode = prime * hashCode
+ ((getAPIVersion() == null) ? 0 : getAPIVersion().hashCode());
return hashCode;
}
@Override
public CreateJobRequest clone() {
return (CreateJobRequest) super.clone();
}
}
| |
/*
* 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 peasy.org.apache.commons.math;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* Base class for commons-math checked exceptions.
* <p>
* Supports nesting, emulating JDK 1.4 behavior if necessary.
* </p>
* <p>
*
* @version $Revision: 620312 $ $Date: 2008-02-10 12:28:59 -0700 (Sun, 10 Feb
* 2008) $
*/
public class MathException extends Exception {
/** Serializable version identifier */
private static final long serialVersionUID = -8602234299177097102L;
/**
* Does JDK support nested exceptions?
*/
private static final boolean JDK_SUPPORTS_NESTED;
static {
boolean flag = false;
try {
Throwable.class.getDeclaredMethod("getCause", new Class[0]);
flag = true;
} catch (final NoSuchMethodException ex) {
flag = false;
}
JDK_SUPPORTS_NESTED = flag;
}
/** Cache for resources bundle. */
private static ResourceBundle cachedResources = null;
/**
* Pattern used to build the message.
*/
private final String pattern;
/**
* Arguments used to build the message.
*/
private final Object[] arguments;
/**
* Root cause of the exception
*/
private final Throwable rootCause;
/**
* Translate a string to a given locale.
*
* @param s
* string to translate
* @param locale
* locale into which to translate the string
* @return translated string or original string for unsupported locales or
* unknown strings
*/
private static String translate(final String s, final Locale locale) {
try {
if ((cachedResources == null)
|| (!cachedResources.getLocale().equals(locale))) {
// caching the resource bundle
cachedResources = ResourceBundle.getBundle(
"peasy.org.apache.commons.math.MessagesResources", locale);
}
if (cachedResources.getLocale().getLanguage().equals(locale.getLanguage())) {
// the value of the resource is the translated string
return cachedResources.getString(s);
}
} catch (final MissingResourceException mre) {
// do nothing here
}
// the locale is not supported or the resource is unknown
// don't translate and fall back to using the string as is
return s;
}
/**
* Builds a message string by from a pattern and its arguments.
*
* @param pattern
* format specifier
* @param arguments
* format arguments
* @param locale
* Locale in which the message should be translated
* @return a message string
*/
private static String buildMessage(final String pattern, final Object[] arguments,
final Locale locale) {
// do it the hard way, for Java 1.3. compatibility
final MessageFormat mf = new MessageFormat(translate(pattern, locale));
mf.setLocale(locale);
return mf.format(arguments);
}
/**
* Constructs a new <code>MathException</code> with no detail message.
*/
public MathException() {
super();
this.pattern = null;
this.arguments = new Object[0];
this.rootCause = null;
}
/**
* Constructs a new <code>MathException</code> with specified detail
* message.
*
* @param msg
* the error message.
* @deprecated as of 1.2, replaced by
* {@link #MathException(String, Object[])}
*/
@Deprecated
public MathException(final String msg) {
super(msg);
this.pattern = msg;
this.arguments = new Object[0];
this.rootCause = null;
}
/**
* Constructs a new <code>MathException</code> with specified formatted
* detail message. Message formatting is delegated to
* {@link MessageFormat}.
*
* @param pattern
* format specifier
* @param arguments
* format arguments
*/
public MathException(final String pattern, final Object[] arguments) {
super(buildMessage(pattern, arguments, Locale.US));
this.pattern = pattern;
this.arguments = arguments.clone();
this.rootCause = null;
}
/**
* Constructs a new <code>MathException</code> with specified nested
* <code>Throwable</code> root cause.
*
* @param rootCause
* the exception or error that caused this exception to be
* thrown.
*/
public MathException(final Throwable rootCause) {
super((rootCause == null ? null : rootCause.getMessage()));
this.pattern = getMessage();
this.arguments = new Object[0];
this.rootCause = rootCause;
}
/**
* Constructs a new <code>MathException</code> with specified detail message
* and nested <code>Throwable</code> root cause.
*
* @param msg
* the error message.
* @param rootCause
* the exception or error that caused this exception to be
* thrown.
* @deprecated as of 1.2, replaced by
* {@link #MathException(String, Object[], Throwable)}
*/
@Deprecated
public MathException(final String msg, final Throwable rootCause) {
super(msg);
this.pattern = msg;
this.arguments = new Object[0];
this.rootCause = rootCause;
}
/**
* Constructs a new <code>MathException</code> with specified formatted
* detail message and nested <code>Throwable</code> root cause. Message
* formatting is delegated to {@link MessageFormat}.
*
* @param pattern
* format specifier
* @param arguments
* format arguments
* @param rootCause
* the exception or error that caused this exception to be
* thrown.
* @since 1.2
*/
public MathException(final String pattern, final Object[] arguments,
final Throwable rootCause) {
super(buildMessage(pattern, arguments, Locale.US));
this.pattern = pattern;
this.arguments = arguments.clone();
this.rootCause = rootCause;
}
/**
* Gets the pattern used to build the message of this throwable.
*
* @return the pattern used to build the message of this throwable
* @since 1.2
*/
public String getPattern() {
return pattern;
}
/**
* Gets the arguments used to build the message of this throwable.
*
* @return the arguments used to build the message of this throwable
* @since 1.2
*/
public Object[] getArguments() {
return arguments.clone();
}
/**
* Gets the message in a specified locale.
*
* @param locale
* Locale in which the message should be translated
*
* @return localized message
* @since 1.2
*/
public String getMessage(final Locale locale) {
return (pattern == null) ? null : buildMessage(pattern, arguments, locale);
}
/**
* Gets the cause of this throwable.
*
* @return the cause of this throwable, or <code>null</code>
*/
@Override
public Throwable getCause() {
return rootCause;
}
/**
* Prints the stack trace of this exception to the standard error stream.
*/
@Override
public void printStackTrace() {
printStackTrace(System.err);
}
/**
* Prints the stack trace of this exception to the specified stream.
*
* @param out
* the <code>PrintStream</code> to use for output
*/
@Override
public void printStackTrace(final PrintStream out) {
synchronized (out) {
final PrintWriter pw = new PrintWriter(out, false);
printStackTrace(pw);
// Flush the PrintWriter before it's GC'ed.
pw.flush();
}
}
/**
* Prints the stack trace of this exception to the specified writer.
*
* @param out
* the <code>PrintWriter</code> to use for output
*/
@Override
public void printStackTrace(final PrintWriter out) {
synchronized (out) {
super.printStackTrace(out);
if (rootCause != null && JDK_SUPPORTS_NESTED == false) {
out.print("Caused by: ");
rootCause.printStackTrace(out);
}
}
}
}
| |
/*
* Copyright@ 2015 PATH
*
* 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.path.common.android.utilities;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.path.common.android.data.PlaceModel;
import org.path.common.android.database.PlaceNameDatabaseFactory;
import org.path.common.android.database.PlaceNameDatabaseHelper;
import org.path.common.android.provider.PlaceColumns;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
/*
* @author: belendia@gmail.com
*/
public class PlaceNameUtil {
protected PlaceNameUtil() {
}
public static void insertPlace(SQLiteDatabase db, PlaceModel place) {
ContentValues values = new ContentValues();
values.put(PlaceColumns.HIERARCHY_NAME, place.getHierarchyName());
values.put(PlaceColumns.CODE, place.getCode());
values.put(PlaceColumns.NAME, place.getName());
values.put(PlaceColumns.RELATIONSHIP, place.getRelationship());
db.insert(PlaceNameDatabaseHelper.PLACE_DATABASES_TABLE, null, values);
}
public static void delete(SQLiteDatabase db) {
db.delete(PlaceNameDatabaseHelper.PLACE_DATABASES_TABLE, null, null);
}
// Returns the number of database records.
public static long getCount(Context context) {
SQLiteDatabase db = PlaceNameDatabaseFactory.get().getDatabase(context,
"survey");
long result = DatabaseUtils.queryNumEntries(db,
PlaceNameDatabaseHelper.PLACE_DATABASES_TABLE);
db.close();
return result;
}
// get all places from the database based on the parameters provided
public static List<PlaceModel> getAll(Context context, String hierarchy,
String relationship) {
SQLiteDatabase db = PlaceNameDatabaseFactory.get().getDatabase(context,
"survey");
String selection = PlaceColumns.HIERARCHY_NAME + " = ?";
String[] selectionArgs = new String[] { hierarchy };
if (relationship != null) {
selection += " AND " + PlaceColumns.RELATIONSHIP + " = ?";
selectionArgs = new String[] { hierarchy, relationship };
}
Cursor cursor = db.query(PlaceNameDatabaseHelper.PLACE_DATABASES_TABLE,
null, selection, selectionArgs, null, null, null);
ArrayList<PlaceModel> places = new ArrayList<PlaceModel>();
PlaceModel place = new PlaceModel();
place.setId(-1);
place.setName("");
places.add(place);
while (cursor.moveToNext()) {
place = new PlaceModel();
place.setId(cursor.getInt(cursor.getColumnIndex(PlaceColumns._ID)));
place.setHierarchyName(cursor.getString(cursor
.getColumnIndex(PlaceColumns.HIERARCHY_NAME)));
place.setCode(cursor.getString(cursor
.getColumnIndex(PlaceColumns.CODE)));
place.setName(cursor.getString(cursor
.getColumnIndex(PlaceColumns.NAME)));
place.setRelationship(cursor.getString(cursor
.getColumnIndex(PlaceColumns.RELATIONSHIP)));
places.add(place);
}
cursor.close();
db.close();
return places;
}
// get name of a place from the database given its code
public static String getName(Context context, String hierarchy, String code) {
SQLiteDatabase db = PlaceNameDatabaseFactory.get().getDatabase(context,
"survey");
String selection = PlaceColumns.CODE + " = ? AND "
+ PlaceColumns.HIERARCHY_NAME + " = ?";
String[] selectionArgs = new String[] { code, hierarchy };
Cursor cursor = db.query(PlaceNameDatabaseHelper.PLACE_DATABASES_TABLE,
new String[] { PlaceColumns.NAME }, selection, selectionArgs,
null, null, null);
String name = "";
if (cursor.moveToNext()) {
name = cursor.getString(cursor.getColumnIndex(PlaceColumns.NAME));
}
cursor.close();
db.close();
return name;
}
private enum Type {
Code, Name
};
// get place name detail given its name or code and hierarchy
private static PlaceModel getPlaceNameDetail(Context context,
String hierarchy, String codeOrName, Type type) {
SQLiteDatabase db = PlaceNameDatabaseFactory.get().getDatabase(context,
"survey");
String selection = "";
if (type == Type.Name) {
selection = PlaceColumns.NAME + " = ? AND "
+ PlaceColumns.HIERARCHY_NAME + " = ?";
} else {
selection = PlaceColumns.CODE + " = ? AND "
+ PlaceColumns.HIERARCHY_NAME + " = ?";
}
String[] selectionArgs = new String[] { codeOrName, hierarchy };
Cursor cursor = db.query(PlaceNameDatabaseHelper.PLACE_DATABASES_TABLE,
null, selection, selectionArgs, null, null, null);
PlaceModel result = null;
if (cursor.moveToNext()) {
result = new PlaceModel();
result.setHierarchyName(cursor.getString(cursor
.getColumnIndex(PlaceColumns.HIERARCHY_NAME)));
result.setName(cursor.getString(cursor
.getColumnIndex(PlaceColumns.NAME)));
result.setCode(cursor.getString(cursor
.getColumnIndex(PlaceColumns.CODE)));
result.setRelationship(cursor.getString(cursor
.getColumnIndex(PlaceColumns.RELATIONSHIP)));
}
cursor.close();
db.close();
return result;
}
// get all distinct hierarchy from the database
public static ArrayList<String> getAllHierarchies(Context context) {
SQLiteDatabase db = PlaceNameDatabaseFactory.get().getDatabase(context,
"survey");
Cursor cursor = db.rawQuery("SELECT distinct "
+ PlaceColumns.HIERARCHY_NAME + " FROM "
+ PlaceNameDatabaseHelper.PLACE_DATABASES_TABLE, null);
ArrayList<String> hierarchy = new ArrayList<String>();
while (cursor.moveToNext()) {
hierarchy.add(cursor.getString(cursor
.getColumnIndex(PlaceColumns.HIERARCHY_NAME)));
}
cursor.close();
db.close();
return hierarchy;
}
public static enum HirarchyOrder {
HigherToLower, LowerToHigher
};
public static ArrayList<PlaceModel> getHierarchiesDetail(Context context,
String placeName, HirarchyOrder order) {
ArrayList<String> hirarchyName = PlaceNameUtil
.getAllHierarchies(context);
ArrayList<PlaceModel> result = null;
if (hirarchyName.size() > 0) {
PlaceModel p = PlaceNameUtil.getPlaceNameDetail(context,
hirarchyName.get(hirarchyName.size() - 1), placeName,
Type.Code);
if (p != null) {
result = new ArrayList<PlaceModel>();
result.add(p);
for (int i = hirarchyName.size() - 2; i >= 0; i--) {
p = PlaceNameUtil
.getPlaceNameDetail(context, hirarchyName.get(i),
p.getRelationship(), Type.Code);
result.add(p);
}
}
}
/*
* result is accumulated from lower hierarchy to higher e.g. EA,
* Chiefdom, District, Province reverse the result to start setting
* place name spinner from the higher hierarchy.
*/
if (order == HirarchyOrder.HigherToLower) {
if (result != null) {
Collections.reverse(result);
}
}
return result;
}
}
| |
/*
* Copyright 2011-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.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* 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.dynamodbv2.datamodeling;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperFieldModel.DynamoDBAttributeType;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.GlobalSecondaryIndex;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndex;
import com.amazonaws.services.dynamodbv2.model.Projection;
import com.amazonaws.services.dynamodbv2.model.ProjectionType;
/**
* A class responsible for parsing the primary key and index schema of a table
* POJO.
*/
class DynamoDBTableSchemaParser {
private final Map<Class<?>, TableIndexesInfo> tableIndexesInfoCache =
new HashMap<Class<?>, TableIndexesInfo>();
/**
* Parse the given POJO class and return the CreateTableRequest for the
* DynamoDB table it represents. Note that the returned request does not
* include the required ProvisionedThroughput parameters for the primary
* table and the GSIs, and that all secondary indexes are initialized with
* the default projection type - KEY_ONLY.
*
* @param clazz
* The POJO class.
* @param config
* The DynamoDBMapperConfig which contains the TableNameOverrides
* parameter used to determine the table name.
* @param reflector
* The DynamoDBReflector that provides all the relevant getters
* of the POJO.
*/
CreateTableRequest parseTablePojoToCreateTableRequest(
Class<?> clazz,
DynamoDBMapperConfig config,
DynamoDBReflector reflector,
ItemConverter converter) {
CreateTableRequest createTableRequest = new CreateTableRequest();
createTableRequest.setTableName(DynamoDBMapper.internalGetTableName(clazz, null, config));
// Primary keys
Method pHashKeyGetter = reflector.getPrimaryHashKeyGetter(clazz);
AttributeDefinition pHashAttrDefinition = getKeyAttributeDefinition(pHashKeyGetter, converter);
createTableRequest.withKeySchema(new KeySchemaElement(pHashAttrDefinition.getAttributeName(), KeyType.HASH));
// Primary range
Method pRangeKeyGetter = reflector.getPrimaryRangeKeyGetter(clazz);
AttributeDefinition pRangeAttrDefinition = null;
if (pRangeKeyGetter != null) {
pRangeAttrDefinition = getKeyAttributeDefinition(pRangeKeyGetter, converter);
createTableRequest.withKeySchema(new KeySchemaElement(pRangeAttrDefinition.getAttributeName(), KeyType.RANGE));
}
// Parse the index schema
TableIndexesInfo indexesInfo = parseTableIndexes(clazz, reflector);
if ( indexesInfo.getGlobalSecondaryIndexes().isEmpty() == false ) {
createTableRequest.setGlobalSecondaryIndexes(indexesInfo.getGlobalSecondaryIndexes());
}
if ( indexesInfo.getLocalSecondaryIndexes().isEmpty() == false ) {
createTableRequest.setLocalSecondaryIndexes(indexesInfo.getLocalSecondaryIndexes());
}
// Aggregate all key attribute definitions
Map<String, AttributeDefinition> attrDefinitions = new HashMap<String, AttributeDefinition>();
// Hash key definition
putAfterCheckConflict(attrDefinitions, pHashAttrDefinition);
// Range key definition
if (pRangeKeyGetter != null) {
putAfterCheckConflict(attrDefinitions, pRangeAttrDefinition);
}
for (Method indexKeyGetter : indexesInfo.getIndexKeyGetters()) {
AttributeDefinition indexKeyAttrDefinition = getKeyAttributeDefinition(indexKeyGetter, converter);
putAfterCheckConflict(attrDefinitions, indexKeyAttrDefinition);
}
createTableRequest.setAttributeDefinitions(attrDefinitions.values());
return createTableRequest;
}
TableIndexesInfo parseTableIndexes(final Class<?> clazz, final DynamoDBReflector reflector) {
synchronized(tableIndexesInfoCache) {
if ( !tableIndexesInfoCache.containsKey(clazz) ) {
TableIndexesInfo tableIndexInfo = new TableIndexesInfo();
String pHashName = reflector.getPrimaryHashKeyName(clazz);
for (Method getter : reflector.getRelevantGetters(clazz)) {
// Only consider 0-arg getters
if (getter.getParameterTypes().length != 0) {
continue;
}
String attributeName = reflector.getAttributeName(getter);
if (ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBIndexHashKey.class)) {
DynamoDBIndexHashKey indexHashKeyAnnotation = ReflectionUtils
.getAnnotationFromGetterOrField(getter, DynamoDBIndexHashKey.class);
String gsiName = indexHashKeyAnnotation.globalSecondaryIndexName();
String[] gsiNames = indexHashKeyAnnotation.globalSecondaryIndexNames();
boolean singleGsiName = gsiName != null &&
gsiName.length() != 0;
boolean multipleGsiNames = gsiNames != null &&
gsiNames.length != 0;
if ( singleGsiName && multipleGsiNames) {
throw new DynamoDBMappingException(
"@DynamoDBIndexHashKey annotation on getter " + getter +
" contains both globalSecondaryIndexName and globalSecondaryIndexNames.");
} else if ( (!singleGsiName) && (!multipleGsiNames) ) {
throw new DynamoDBMappingException(
"@DynamoDBIndexHashKey annotation on getter " + getter +
" doesn't contain any index name.");
}
if (singleGsiName) {
tableIndexInfo.addGsiKeys(gsiName, attributeName, null);
} else if (multipleGsiNames) {
for (String gsi : gsiNames) {
tableIndexInfo.addGsiKeys(gsi, attributeName, null);
}
}
tableIndexInfo.addIndexKeyGetter(getter);
}
if (ReflectionUtils.getterOrFieldHasAnnotation(getter, DynamoDBIndexRangeKey.class)) {
DynamoDBIndexRangeKey indexRangeKeyAnnotation = ReflectionUtils
.getAnnotationFromGetterOrField(getter, DynamoDBIndexRangeKey.class);
String gsiName = indexRangeKeyAnnotation.globalSecondaryIndexName();
String[] gsiNames = indexRangeKeyAnnotation.globalSecondaryIndexNames();
String lsiName = indexRangeKeyAnnotation.localSecondaryIndexName();
String[] lsiNames = indexRangeKeyAnnotation.localSecondaryIndexNames();
boolean singleGsiName = gsiName != null &&
gsiName.length() != 0;
boolean multipleGsiNames = gsiNames != null &&
gsiNames.length != 0;
boolean singleLsiName = lsiName != null &&
lsiName.length() != 0;
boolean multipleLsiNames = lsiNames != null &&
lsiNames.length != 0;
if ( singleGsiName && multipleGsiNames ) {
throw new DynamoDBMappingException(
"@DynamoDBIndexRangeKey annotation on getter " + getter +
" contains both globalSecondaryIndexName and globalSecondaryIndexNames.");
}
if ( singleLsiName && multipleLsiNames ) {
throw new DynamoDBMappingException(
"@DynamoDBIndexRangeKey annotation on getter " + getter +
" contains both localSecondaryIndexName and localSecondaryIndexNames.");
}
if ( (!singleGsiName) && (!multipleGsiNames) && (!singleLsiName) && (!multipleLsiNames) ) {
throw new DynamoDBMappingException(
"@DynamoDBIndexRangeKey annotation on getter " + getter +
" doesn't contain any index name.");
}
if (singleGsiName) {
tableIndexInfo.addGsiKeys(gsiName, null, attributeName);
} else if (multipleGsiNames) {
for (String gsi : gsiNames) {
tableIndexInfo.addGsiKeys(gsi, null, attributeName);
}
}
if (singleLsiName) {
tableIndexInfo.addLsiRangeKey(lsiName, pHashName, attributeName);
} else if (multipleLsiNames) {
for (String lsi : lsiNames) {
tableIndexInfo.addLsiRangeKey(lsi, pHashName, attributeName);
}
}
tableIndexInfo.addIndexKeyGetter(getter);
}
} // end of for loop
tableIndexesInfoCache.put(clazz, tableIndexInfo);
} // end of the if-cache-does-not-contain block
return tableIndexesInfoCache.get(clazz);
} // end of synchronized block
}
private static AttributeDefinition getKeyAttributeDefinition(
Method keyGetter,
ItemConverter converter) {
DynamoDBMapperFieldModel fieldModel = converter.getFieldModel(keyGetter);
String keyAttrName = fieldModel.getDynamoDBAttributeName();
DynamoDBAttributeType keyType = fieldModel.getDynamoDBAttributeType();
if (keyType == DynamoDBAttributeType.S ||
keyType == DynamoDBAttributeType.N ||
keyType == DynamoDBAttributeType.B) {
return new AttributeDefinition(keyAttrName, keyType.toString());
}
throw new DynamoDBMappingException(
"The key attribute must be in a scalar type "
+ "(String, Number or Binary).");
}
private static void putAfterCheckConflict(Map<String, AttributeDefinition> map,
AttributeDefinition attrDefinition) {
String attrName = attrDefinition.getAttributeName();
AttributeDefinition existingDefinition = map.get(attrName);
if (existingDefinition != null && !existingDefinition.equals(attrDefinition)) {
throw new DynamoDBMappingException(
"Found conflicting definitions for attribute [" + attrName + "]: " +
existingDefinition + " and " + attrDefinition + ".");
} else {
map.put(attrName, attrDefinition);
}
}
/**
* This class contains all the information about a table's index schema
* parsed from a table POJO class.
*/
static class TableIndexesInfo {
/** Used for mapping an index key name to all the applicable indexes. */
private final Map<String, Set<String>> lsiRangeKeyNameToIndexNames =
new HashMap<String, Set<String>>();
private final Map<String, Set<String>> gsiHashKeyNameToIndexNames =
new HashMap<String, Set<String>>();
private final Map<String, Set<String>> gsiRangeKeyNameToIndexNames =
new HashMap<String, Set<String>>();
/** Note that the KeySchema in each LocalSecondaryIndex does not include the hash key. */
private final Map<String, LocalSecondaryIndex> lsiNameToLsiDefinition = new HashMap<String, LocalSecondaryIndex>();
private final Map<String, GlobalSecondaryIndex> gsiNameToGsiDefinition = new HashMap<String, GlobalSecondaryIndex>();
/** All getter methods of index key attributes. */
private final Set<Method> indexKeyGetters = new HashSet<Method>();
/**
* Returns the names of all the annotated local secondary indexes that
* use the given attribute as the index range key.
*/
public Set<String> getLsiNamesByIndexRangeKey(String indexRangeKeyName) {
Set<String> lsiNames = lsiRangeKeyNameToIndexNames.get(indexRangeKeyName);
if (lsiNames != null) {
lsiNames = Collections.unmodifiableSet(lsiNames);
}
return lsiNames;
}
/**
* Returns the names of all the annotated global secondary indexes that
* use the given attribute as the index hash key.
*/
public Set<String> getGsiNamesByIndexHashKey(String indexHashKeyName) {
Set<String> gsiNames = gsiHashKeyNameToIndexNames.get(indexHashKeyName);
if (gsiNames != null) {
gsiNames = Collections.unmodifiableSet(gsiNames);
}
return gsiNames;
}
/**
* Returns the names of all the annotated global secondary indexes that
* use the given attribute as the index range key.
*/
public Set<String> getGsiNamesByIndexRangeKey(String indexRangeKeyName) {
Set<String> gsiNames = gsiRangeKeyNameToIndexNames.get(indexRangeKeyName);
if (gsiNames != null) {
gsiNames = Collections.unmodifiableSet(gsiNames);
}
return gsiNames;
}
/**
* Returns the names of all the annotated local secondary indexes of
* this POJO class.
*/
public Set<String> getAllLsiNames() {
return Collections.unmodifiableSet(lsiNameToLsiDefinition.keySet());
}
/**
* Returns the names of all the annotated global secondary indexes of
* this POJO class.
*/
public Set<String> getAllGsiNames() {
return Collections.unmodifiableSet(gsiNameToGsiDefinition.keySet());
}
/*
* Private interfaces
*/
private void addGsiKeys(String gsiName, String gsiHashKeyName, String gsiRangeKeyName) {
GlobalSecondaryIndex gsi;
if (gsiNameToGsiDefinition.containsKey(gsiName)) {
GlobalSecondaryIndex existingGsi = gsiNameToGsiDefinition.get(gsiName);
gsi = existingGsi;
if ( !gsiName.equals(existingGsi.getIndexName()) ) {
throw new IllegalStateException("Found invalid state of an existing GlobalSecondaryIndex object " +
"associated with the GSI [" + gsiName + "].");
}
for (KeySchemaElement existingKey : existingGsi.getKeySchema()) {
String existingKeyName = existingKey.getAttributeName();
String existingKeyType = existingKey.getKeyType();
if (KeyType.HASH.toString().equals(existingKeyType)) {
if (gsiHashKeyName != null && !gsiHashKeyName.equals(existingKeyName)) {
throw new DynamoDBMappingException("Multiple hash keys [" + existingKeyName + ", " + gsiHashKeyName +
"] are found for the GSI [" + gsiName + "]. " +
"Each index allows at most one range key attribute.");
}
} else if (KeyType.RANGE.toString().equals(existingKeyType)) {
if (gsiRangeKeyName != null && !gsiRangeKeyName.equals(existingKeyName)) {
throw new DynamoDBMappingException("Multiple range keys [" + existingKeyName + ", " + gsiRangeKeyName +
"] are found for the GSI [" + gsiName + "]. " +
"Each index allows at most one range key attribute.");
}
} else {
// Existing key element is neither HASH nor RANGE.
throw new IllegalStateException("Found invalid state of an existing GlobalSecondaryIndex object " +
"associated with the GSI [" + gsiName + "].");
}
}
} else {
gsi = new GlobalSecondaryIndex()
.withIndexName(gsiName)
.withProjection(new Projection().withProjectionType(ProjectionType.KEYS_ONLY));
gsiNameToGsiDefinition.put(gsiName, gsi);
}
if (gsiHashKeyName != null) {
// Make sure that the HASH key element is always inserted at the beginning of the list
if (gsi.getKeySchema() == null || gsi.getKeySchema().isEmpty()) {
gsi.withKeySchema(new KeySchemaElement(gsiHashKeyName, KeyType.HASH));
} else {
LinkedList<KeySchemaElement> orderedKeys = new LinkedList<KeySchemaElement>(gsi.getKeySchema());
orderedKeys.addFirst(new KeySchemaElement(gsiHashKeyName, KeyType.HASH));
gsi.setKeySchema(orderedKeys);
}
// Register the mapping from the hash key name to the GSI name
mapGsiHashKeyToIndexName(gsiHashKeyName, gsiName);
}
if (gsiRangeKeyName != null) {
gsi.withKeySchema(new KeySchemaElement(gsiRangeKeyName, KeyType.RANGE));
// Register the mapping from the range key name to the GSI name
mapGsiRangeKeyToIndexName(gsiRangeKeyName, gsiName);
}
}
private void addLsiRangeKey(String lsiName, String pHashKeyName, String lsiRangeKeyName) {
if (pHashKeyName == null) {
throw new IllegalArgumentException("The name of the primary hash key must be specified.");
}
if (lsiNameToLsiDefinition.containsKey(lsiName)) {
LocalSecondaryIndex existingLsi = lsiNameToLsiDefinition.get(lsiName);
if ( !lsiName.equals(existingLsi.getIndexName())
|| existingLsi.getKeySchema() == null
|| existingLsi.getKeySchema().size() != 2 // the hash key element should be already added
|| !KeyType.RANGE.toString().equals(existingLsi.getKeySchema().get(1).getKeyType()) ) {
throw new IllegalStateException("Found invalid state of an existing LocalSecondaryIndex object " +
"associated with the LSI [" + lsiName + "].");
}
String existingLsiRangeKeyName = existingLsi.getKeySchema().get(1).getAttributeName();
if ( !existingLsiRangeKeyName.equals(lsiRangeKeyName) ) {
throw new DynamoDBMappingException("Multiple range keys [" + existingLsiRangeKeyName + ", " + lsiRangeKeyName +
"] are found for the LSI [" + lsiName + "]. " +
"Each index allows at most one range key attribute.");
}
} else {
lsiNameToLsiDefinition.put(
lsiName,
new LocalSecondaryIndex()
.withIndexName(lsiName)
.withKeySchema(
new KeySchemaElement(pHashKeyName, KeyType.HASH),
new KeySchemaElement(lsiRangeKeyName, KeyType.RANGE))
.withProjection(new Projection().withProjectionType(ProjectionType.KEYS_ONLY)));
mapLsiRangeKeyToIndexName(lsiRangeKeyName, lsiName);
}
}
private void mapLsiRangeKeyToIndexName(String lsiRangeKeyName, String lsiName) {
mapIndexKeyToIndexName(lsiRangeKeyNameToIndexNames, lsiRangeKeyName, lsiName);
}
private void mapGsiHashKeyToIndexName(String gsiHashKeyName, String gsiName) {
mapIndexKeyToIndexName(gsiHashKeyNameToIndexNames, gsiHashKeyName, gsiName);
}
private void mapGsiRangeKeyToIndexName(String gsiRangeKeyName, String gsiName) {
mapIndexKeyToIndexName(gsiRangeKeyNameToIndexNames, gsiRangeKeyName, gsiName);
}
private void mapIndexKeyToIndexName(Map<String, Set<String>> indexKeyNameToIndexNames,
String indexKeyName,
String indexName) {
if (indexKeyNameToIndexNames.get(indexKeyName) == null) {
Set<String> indexNames = new HashSet<String>();
indexNames.add(indexName);
indexKeyNameToIndexNames.put(indexKeyName, indexNames);
} else {
indexKeyNameToIndexNames.get(indexKeyName).add(indexName);
}
}
private void addIndexKeyGetter(Method indexKeyGetter) {
indexKeyGetters.add(indexKeyGetter);
}
private Set<Method> getIndexKeyGetters() {
return Collections.unmodifiableSet(indexKeyGetters);
}
private Collection<LocalSecondaryIndex> getLocalSecondaryIndexes() {
return Collections.unmodifiableCollection(lsiNameToLsiDefinition.values());
}
private Collection<GlobalSecondaryIndex> getGlobalSecondaryIndexes() {
return Collections.unmodifiableCollection(gsiNameToGsiDefinition.values());
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.tcp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.fail;
/**
* Various tests used to validate the behaviour of Java Sockets.
*
* The tests were for experimentation and don't have any assertions in them - JUnit provided a convenient framework to explore this behaviour. These tests shouldn't be run with a normal build since
* they don't have any assertions and don't validate any results.
*
* NOTE: This class may be deleted in the future
*/
@Ignore(value = "Tests validating Java Socket behaviours")
public class JavaSocketTests {
Logger log = LoggerFactory.getLogger(this.getClass());
Socket clientSocket;
ServerSocket serverSocket;
int messageCount = 10;
@Before
public void setUp() throws Exception {
serverSocket = new ServerSocket(0);
}
@After
public void tearDown() throws Exception {
if (null != clientSocket) {
clientSocket.close();
}
if (null != serverSocket) {
serverSocket.close();
}
}
@Test
public void testSocketReadOnClosedConnection() throws Exception {
final Thread acceptThread = new Thread() {
Logger log = LoggerFactory.getLogger("acceptThread");
@Override
public void run() {
try {
Socket echoSocket = serverSocket.accept();
log.info("Accepted connection: {}", echoSocket.getInetAddress());
echoSocket.setSoTimeout(2000);
while (echoSocket.isConnected() && !echoSocket.isClosed()) {
StringBuilder responseBuilder = new StringBuilder(500);
InputStream reader = echoSocket.getInputStream();
OutputStream writer = echoSocket.getOutputStream();
do {
int readByte = -1;
int available = -1;
try {
available = reader.available();
log.info("InputStream.available returned {}", available);
readByte = reader.read();
log.trace("Processing byte: {}", readByte);
switch (readByte) {
case -1:
if (echoSocket.isConnected() && !echoSocket.isClosed()) {
log.info("Available returned {}", reader.available());
log.warn("Socket claims to still be open, but END_OF_STREAM received - closing echoSocket");
try {
echoSocket.close();
} catch (Exception ex) {
log.warn("Exception encountered closing echoSocket after END_OF_STREAM received", ex);
}
}
break;
case 10:
log.info("Complete Message - Sending Response");
byte[] response = responseBuilder.toString().getBytes();
responseBuilder.setLength(0);
writer.write(response, 0, response.length);
writer.write('\n');
break;
default:
responseBuilder.append((char) readByte);
}
} catch (SocketTimeoutException timeoutEx) {
log.info("Timeout reading data - available returned {}", available);
}
} while (echoSocket.isConnected() && !echoSocket.isClosed());
}
} catch (IOException ioEx) {
log.error("IOException in run method", ioEx);
} finally {
try {
serverSocket.close();
} catch (IOException ioEx) {
log.error("Exception encountered closing server socket", ioEx);
}
}
log.info("Finished processing connection");
}
};
acceptThread.start();
clientSocket = new Socket();
clientSocket.setSoTimeout(1000);
clientSocket.connect(serverSocket.getLocalSocketAddress(), 10000);
clientSocket.setTcpNoDelay(true);
log.info("Begining message send loop ");
byte[] message = "Hello World".getBytes();
BufferedReader reader;
for (int i = 1; i <= messageCount; ++i) {
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream writer = clientSocket.getOutputStream();
log.info("Sending payload");
writer.write(message, 0, message.length);
writer.flush();
log.info("Sending terminator");
writer.write('\n');
writer.flush();
log.info("Received Response #{}: {}", i, reader.readLine());
Thread.sleep(1000);
}
log.info("Message send loop complete - closing connection");
// Javadoc for Socket says closing the InputStream will close the connection
clientSocket.getInputStream().close();
if (!clientSocket.isClosed()) {
log.warn("Closing input stream didn't close socket");
clientSocket.close();
}
log.info("Sleeping ...");
Thread.sleep(5000);
}
@Test
public void testAvailableOnClosedConnection() throws Exception {
final Thread acceptThread = new Thread() {
Logger log = LoggerFactory.getLogger("acceptThread");
@Override
public void run() {
try {
Socket echoSocket = serverSocket.accept();
log.info("Accepted connection: {}", echoSocket.getInetAddress());
echoSocket.setSoTimeout(2000);
while (echoSocket.isConnected() && !echoSocket.isClosed()) {
StringBuilder responseBuilder = new StringBuilder(500);
InputStream reader = echoSocket.getInputStream();
OutputStream writer = echoSocket.getOutputStream();
do {
int readByte = -1;
int available = -1;
try {
available = reader.available();
log.info("InputStream.available returned {}", available);
readByte = reader.read();
log.trace("Processing byte: {}", readByte);
switch (readByte) {
case -1:
if (echoSocket.isConnected() && !echoSocket.isClosed()) {
log.info("Available returned {}", reader.available());
log.warn("Socket claims to still be open, but END_OF_STREAM received - closing echoSocket");
try {
echoSocket.close();
} catch (Exception ex) {
log.warn("Exception encountered closing echoSocket after END_OF_STREAM received", ex);
}
}
break;
case 27: // Escape
log.info("Received Escape - closing connection");
echoSocket.close();
break;
case 10:
log.info("Complete Message - Sending Response");
byte[] response = responseBuilder.toString().getBytes();
responseBuilder.setLength(0);
writer.write(response, 0, response.length);
writer.write('\n');
break;
default:
responseBuilder.append((char) readByte);
}
} catch (SocketTimeoutException timeoutEx) {
log.info("Timeout reading data - available returned {}", available);
}
} while (echoSocket.isConnected() && !echoSocket.isClosed());
}
} catch (IOException ioEx) {
log.error("IOException in run method", ioEx);
} finally {
try {
serverSocket.close();
} catch (IOException ioEx) {
log.error("Exception encountered closing server socket", ioEx);
}
}
log.info("Finished processing connection");
}
};
acceptThread.start();
clientSocket = new Socket();
clientSocket.setSoTimeout(1000);
clientSocket.connect(serverSocket.getLocalSocketAddress(), 10000);
clientSocket.setTcpNoDelay(true);
log.info("Begining message send loop ");
byte[] message = "Hello World".getBytes();
BufferedReader reader;
for (int i = 1; i <= messageCount; ++i) {
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream writer = clientSocket.getOutputStream();
log.info("Sending payload");
writer.write(message, 0, message.length);
writer.flush();
log.info("Sending terminator");
writer.write('\n');
writer.flush();
log.info("Received Response #{}: {}", i, reader.readLine());
Thread.sleep(1000);
}
log.info("Message send loop complete - closing connection");
log.info("Client Socket available() returned {} before close", clientSocket.getInputStream().available());
try {
clientSocket.getInputStream().read();
fail("read should have timed-out");
} catch (SocketTimeoutException timeoutEx) {
log.info("Client Socket read() timed-out before close");
}
clientSocket.getOutputStream().write(27);
Thread.sleep(1000);
log.info("Client Socket available() returned {} after close", clientSocket.getInputStream().available());
log.info("Client Socket read() returned {} after close", clientSocket.getInputStream().read());
// Javadoc for Socket says closing the InputStream will close the connection
clientSocket.getInputStream().close();
if (!clientSocket.isClosed()) {
log.warn("Closing input stream didn't close socket");
clientSocket.close();
}
log.info("Sleeping ...");
Thread.sleep(5000);
}
}
| |
/*
* Copyright 2014 NAVER Corp.
*
* 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.navercorp.pinpoint.web.controller;
import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.web.applicationmap.ApplicationMap;
import com.navercorp.pinpoint.web.applicationmap.MapWrap;
import com.navercorp.pinpoint.web.applicationmap.link.LinkHistogramSummary;
import com.navercorp.pinpoint.web.applicationmap.link.LinkType;
import com.navercorp.pinpoint.web.applicationmap.nodes.NodeType;
import com.navercorp.pinpoint.web.service.ApplicationFactory;
import com.navercorp.pinpoint.web.service.MapService;
import com.navercorp.pinpoint.web.service.ResponseTimeHistogramService;
import com.navercorp.pinpoint.web.util.Limiter;
import com.navercorp.pinpoint.web.view.ApplicationTimeHistogramViewModel;
import com.navercorp.pinpoint.web.applicationmap.nodes.NodeHistogramSummary;
import com.navercorp.pinpoint.web.vo.Application;
import com.navercorp.pinpoint.web.vo.ApplicationPair;
import com.navercorp.pinpoint.web.vo.ApplicationPairs;
import com.navercorp.pinpoint.web.vo.Range;
import com.navercorp.pinpoint.web.vo.SearchOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* @author emeroad
* @author netspider
* @author jaehong.kim
* @author HyunGil Jeong
*/
@Controller
public class MapController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private MapService mapService;
@Autowired
private ResponseTimeHistogramService responseTimeHistogramService;
@Autowired
private Limiter dateLimit;
@Autowired
private ServiceTypeRegistryService registry;
@Autowired
private ApplicationFactory applicationFactory;
private static final String DEFAULT_SEARCH_DEPTH = "8";
private static final int DEFAULT_MAX_SEARCH_DEPTH = 8;
/**
* Server map data query within from ~ to timeframe
*
* @param applicationName
* @param serviceTypeCode
* @param from
* @param to
* @return
*/
@RequestMapping(value = "/getServerMapData", method = RequestMethod.GET, params="serviceTypeCode")
@ResponseBody
public MapWrap getServerMapData(
@RequestParam("applicationName") String applicationName,
@RequestParam("serviceTypeCode") short serviceTypeCode,
@RequestParam("from") long from,
@RequestParam("to") long to,
@RequestParam(value = "callerRange", defaultValue = DEFAULT_SEARCH_DEPTH) int callerRange,
@RequestParam(value = "calleeRange", defaultValue = DEFAULT_SEARCH_DEPTH) int calleeRange,
@RequestParam(value = "bidirectional", defaultValue = "true", required = false) boolean bidirectional,
@RequestParam(value = "wasOnly", defaultValue="false", required = false) boolean wasOnly) {
final Range range = Range.newRange(from, to);
this.dateLimit.limit(range);
SearchOption searchOption = new SearchOption(callerRange, calleeRange, bidirectional, wasOnly);
assertSearchOption(searchOption);
Application application = applicationFactory.createApplication(applicationName, serviceTypeCode);
return selectApplicationMap(application, range, searchOption, NodeType.DETAILED, LinkType.DETAILED);
}
/**
* Server map data query within from ~ to timeframe
*
* @param applicationName
* @param serviceTypeName
* @param from
* @param to
* @return
*/
@RequestMapping(value = "/getServerMapData", method = RequestMethod.GET, params="serviceTypeName")
@ResponseBody
public MapWrap getServerMapData(
@RequestParam("applicationName") String applicationName,
@RequestParam("serviceTypeName") String serviceTypeName,
@RequestParam("from") long from,
@RequestParam("to") long to,
@RequestParam(value = "callerRange", defaultValue = DEFAULT_SEARCH_DEPTH) int callerRange,
@RequestParam(value = "calleeRange", defaultValue = DEFAULT_SEARCH_DEPTH) int calleeRange,
@RequestParam(value = "bidirectional", defaultValue = "true", required = false) boolean bidirectional,
@RequestParam(value = "wasOnly", defaultValue="false", required = false) boolean wasOnly) {
final Range range = Range.newRange(from, to);
this.dateLimit.limit(range);
SearchOption searchOption = new SearchOption(callerRange, calleeRange, bidirectional, wasOnly);
assertSearchOption(searchOption);
Application application = applicationFactory.createApplicationByTypeName(applicationName, serviceTypeName);
return selectApplicationMap(application, range, searchOption, NodeType.DETAILED, LinkType.DETAILED);
}
/**
* Server map data query within from ~ to timeframe
*
* @param applicationName
* @param serviceTypeCode
* @param from
* @param to
* @return
*/
@RequestMapping(value = "/getServerMapDataV2", method = RequestMethod.GET, params="serviceTypeCode")
@ResponseBody
public MapWrap getServerMapDataV2(
@RequestParam("applicationName") String applicationName,
@RequestParam("serviceTypeCode") short serviceTypeCode,
@RequestParam("from") long from,
@RequestParam("to") long to,
@RequestParam(value = "callerRange", defaultValue = DEFAULT_SEARCH_DEPTH) int callerRange,
@RequestParam(value = "calleeRange", defaultValue = DEFAULT_SEARCH_DEPTH) int calleeRange,
@RequestParam(value = "bidirectional", defaultValue = "true", required = false) boolean bidirectional,
@RequestParam(value = "wasOnly", defaultValue="false", required = false) boolean wasOnly) {
final Range range = Range.newRange(from, to);
this.dateLimit.limit(range);
SearchOption searchOption = new SearchOption(callerRange, calleeRange, bidirectional, wasOnly);
assertSearchOption(searchOption);
Application application = applicationFactory.createApplication(applicationName, serviceTypeCode);
return selectApplicationMap(application, range, searchOption, NodeType.BASIC, LinkType.BASIC);
}
/**
* Server map data query within from ~ to timeframe
*
* @param applicationName
* @param serviceTypeName
* @param from
* @param to
* @return
*/
@RequestMapping(value = "/getServerMapDataV2", method = RequestMethod.GET, params="serviceTypeName")
@ResponseBody
public MapWrap getServerMapDataV2(
@RequestParam("applicationName") String applicationName,
@RequestParam("serviceTypeName") String serviceTypeName,
@RequestParam("from") long from,
@RequestParam("to") long to,
@RequestParam(value = "callerRange", defaultValue = DEFAULT_SEARCH_DEPTH) int callerRange,
@RequestParam(value = "calleeRange", defaultValue = DEFAULT_SEARCH_DEPTH) int calleeRange,
@RequestParam(value = "bidirectional", defaultValue = "true", required = false) boolean bidirectional,
@RequestParam(value = "wasOnly", defaultValue ="false", required = false) boolean wasOnly) {
final Range range = Range.newRange(from, to);
this.dateLimit.limit(range);
SearchOption searchOption = new SearchOption(callerRange, calleeRange, bidirectional, wasOnly);
assertSearchOption(searchOption);
Application application = applicationFactory.createApplicationByTypeName(applicationName, serviceTypeName);
return selectApplicationMap(application, range, searchOption, NodeType.BASIC, LinkType.BASIC);
}
private MapWrap selectApplicationMap(Application application, Range range, SearchOption searchOption, NodeType nodeType, LinkType linkType) {
Objects.requireNonNull(application, "application");
Objects.requireNonNull(range, "range");
Objects.requireNonNull(searchOption, "searchOption");
logger.info("getServerMap() application:{} range:{} searchOption:{}", application, range, searchOption);
ApplicationMap map = mapService.selectApplicationMap(application, range, searchOption, nodeType, linkType);
return new MapWrap(map);
}
private void assertSearchOption(SearchOption searchOption) {
int callerSearchDepth = searchOption.getCallerSearchDepth();
assertSearchDepth(callerSearchDepth, "invalid caller depth:" + callerSearchDepth);
int calleeSearchDepth = searchOption.getCalleeSearchDepth();
assertSearchDepth(calleeSearchDepth, "invalid callee depth:" + calleeSearchDepth);
}
private void assertSearchDepth(int depth, String message) {
if (depth < 0) {
throw new IllegalArgumentException(message);
}
if (depth > DEFAULT_MAX_SEARCH_DEPTH) {
throw new IllegalArgumentException(message);
}
}
@RequestMapping(value = "/getResponseTimeHistogramData", method = RequestMethod.GET, params = "serviceTypeName")
@ResponseBody
public ApplicationTimeHistogramViewModel getResponseTimeHistogramData(
@RequestParam("applicationName") String applicationName,
@RequestParam("serviceTypeName") String serviceTypeName,
@RequestParam("from") long from,
@RequestParam("to") long to) {
final Range range = Range.newRange(from, to);
dateLimit.limit(range);
Application application = applicationFactory.createApplicationByTypeName(applicationName, serviceTypeName);
ApplicationTimeHistogramViewModel applicationTimeHistogramViewModel = responseTimeHistogramService.selectResponseTimeHistogramData(application, range);
return applicationTimeHistogramViewModel;
}
@RequestMapping(value = "/getResponseTimeHistogramDataV2", method = RequestMethod.POST)
@ResponseBody
public NodeHistogramSummary postResponseTimeHistogramDataV2(
@RequestParam("applicationName") String applicationName,
@RequestParam("serviceTypeCode") Short serviceTypeCode,
@RequestParam("from") long from,
@RequestParam("to") long to,
@RequestBody ApplicationPairs applicationPairs) {
final Range range = Range.newRange(from, to);
dateLimit.limit(range);
Application application = applicationFactory.createApplication(applicationName, serviceTypeCode);
List<Application> fromApplications = mapApplicationPairsToApplications(applicationPairs.getFromApplications());
List<Application> toApplications = mapApplicationPairsToApplications(applicationPairs.getToApplications());
return responseTimeHistogramService.selectNodeHistogramData(application, range, fromApplications, toApplications);
}
@RequestMapping(value = "/getResponseTimeHistogramDataV2", method = RequestMethod.GET)
@ResponseBody
public NodeHistogramSummary getResponseTimeHistogramDataV2(
@RequestParam("applicationName") String applicationName,
@RequestParam("serviceTypeCode") Short serviceTypeCode,
@RequestParam("from") long from,
@RequestParam("to") long to,
@RequestParam(value = "fromApplicationNames", defaultValue = "", required = false) List<String> fromApplicationNames,
@RequestParam(value = "fromServiceTypeCodes", defaultValue = "", required = false) List<Short> fromServiceTypeCodes,
@RequestParam(value = "toApplicationNames", defaultValue = "", required = false) List<String> toApplicationNames,
@RequestParam(value = "toServiceTypeCodes", defaultValue = "", required = false) List<Short> toServiceTypeCodes) {
final Range range = Range.newRange(from, to);
dateLimit.limit(range);
if (fromApplicationNames.size() != fromServiceTypeCodes.size()) {
throw new IllegalArgumentException("fromApplicationNames and fromServiceTypeCodes must have the same number of elements");
}
if (toApplicationNames.size() != toServiceTypeCodes.size()) {
throw new IllegalArgumentException("toApplicationNames and toServiceTypeCodes must have the same number of elements");
}
Application application = applicationFactory.createApplication(applicationName, serviceTypeCode);
List<Application> fromApplications = new ArrayList<>(fromApplicationNames.size());
for (int i = 0; i < fromApplicationNames.size(); i++) {
Application fromApplication = applicationFactory.createApplication(fromApplicationNames.get(i), fromServiceTypeCodes.get(i));
fromApplications.add(fromApplication);
}
List<Application> toApplications = new ArrayList<>(toApplicationNames.size());
for (int i = 0; i < toApplicationNames.size(); i++) {
Application toApplication = applicationFactory.createApplication(toApplicationNames.get(i), toServiceTypeCodes.get(i));
toApplications.add(toApplication);
}
return responseTimeHistogramService.selectNodeHistogramData(application, range, fromApplications, toApplications);
}
private List<Application> mapApplicationPairsToApplications(List<ApplicationPair> applicationPairs) {
if (CollectionUtils.isEmpty(applicationPairs)) {
return Collections.emptyList();
}
List<Application> applications = new ArrayList<>(applicationPairs.size());
for (ApplicationPair applicationPair : applicationPairs) {
String applicationName = applicationPair.getApplicationName();
short serviceTypeCode = applicationPair.getServiceTypeCode();
Application application = applicationFactory.createApplication(applicationName, serviceTypeCode);
applications.add(application);
}
return applications;
}
@RequestMapping(value = "/getLinkTimeHistogramData", method = RequestMethod.GET)
@ResponseBody
public LinkHistogramSummary getLinkTimeHistogramData(
@RequestParam(value = "fromApplicationName", required = false) String fromApplicationName,
@RequestParam(value = "fromServiceTypeCode", required = false) Short fromServiceTypeCode,
@RequestParam(value = "toApplicationName", required = false) String toApplicationName,
@RequestParam(value = "toServiceTypeCode", required = false) Short toServiceTypeCode,
@RequestParam("from") long from,
@RequestParam("to") long to) {
final Range range = Range.newRange(from, to);
dateLimit.limit(range);
Application fromApplication = null;
if (StringUtils.hasLength(fromApplicationName)) {
fromApplication = applicationFactory.createApplication(fromApplicationName, fromServiceTypeCode);
}
Application toApplication = null;
if (StringUtils.hasLength(toApplicationName)) {
toApplication = applicationFactory.createApplication(toApplicationName, toServiceTypeCode);
}
return responseTimeHistogramService.selectLinkHistogramData(fromApplication, toApplication, range);
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.editor.impl;
import com.intellij.util.ui.JBUI;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
/**
* This class is exact copy of javax.swing.ScrollPaneLayout except is does not ask component for orientation
* and always assumes right-to-left.
*
* @author max
* @deprecated {@link com.intellij.ui.components.JBScrollPane.Flip}
*/
@Deprecated
public class LeftHandScrollbarLayout extends ScrollPaneLayout {
/**
* The scrollpane's viewport child.
* Default is an empty {@code JViewport}.
*
* @see javax.swing.JScrollPane#setViewport
*/
protected JViewport viewport;
/**
* The scrollpane's vertical scrollbar child.
* Default is a {@code JScrollBar}.
*
* @see javax.swing.JScrollPane#setVerticalScrollBar
*/
protected JScrollBar vsb;
/**
* The scrollpane's horizontal scrollbar child.
* Default is a {@code JScrollBar}.
*
* @see javax.swing.JScrollPane#setHorizontalScrollBar
*/
protected JScrollBar hsb;
/**
* The row header child. Default is {@code null}.
*
* @see javax.swing.JScrollPane#setRowHeader
*/
protected JViewport rowHead;
/**
* The column header child. Default is {@code null}.
*
* @see javax.swing.JScrollPane#setColumnHeader
*/
protected JViewport colHead;
/**
* The component to display in the lower left corner.
* Default is {@code null}.
*
* @see javax.swing.JScrollPane#setCorner
*/
protected Component lowerLeft;
/**
* The component to display in the lower right corner.
* Default is {@code null}.
*
* @see javax.swing.JScrollPane#setCorner
*/
protected Component lowerRight;
/**
* The component to display in the upper left corner.
* Default is {@code null}.
*
* @see javax.swing.JScrollPane#setCorner
*/
protected Component upperLeft;
/**
* The component to display in the upper right corner.
* Default is {@code null}.
*
* @see javax.swing.JScrollPane#setCorner
*/
protected Component upperRight;
/**
* The display policy for the vertical scrollbar.
* The default is {@code JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED}.
* <p/>
* This field is obsolete, please use the {@code JScrollPane} field instead.
*
* @see javax.swing.JScrollPane#setVerticalScrollBarPolicy
*/
protected int vsbPolicy = VERTICAL_SCROLLBAR_AS_NEEDED;
/**
* The display policy for the horizontal scrollbar.
* The default is {@code JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED}.
* <p/>
* This field is obsolete, please use the {@code JScrollPane} field instead.
*
* @see javax.swing.JScrollPane#setHorizontalScrollBarPolicy
*/
protected int hsbPolicy = HORIZONTAL_SCROLLBAR_AS_NEEDED;
/**
* This method is invoked after the ScrollPaneLayout is set as the
* LayoutManager of a {@code JScrollPane}.
* It initializes all of the internal fields that
* are ordinarily set by {@code addLayoutComponent}. For example:
* <pre>
* ScrollPaneLayout mySPLayout = new ScrollPanelLayout() {
* public void layoutContainer(Container p) {
* super.layoutContainer(p);
* // do some extra work here ...
* }
* };
* scrollpane.setLayout(mySPLayout):
* </pre>
*/
@Override
public void syncWithScrollPane(JScrollPane sp) {
viewport = sp.getViewport();
vsb = sp.getVerticalScrollBar();
hsb = sp.getHorizontalScrollBar();
rowHead = sp.getRowHeader();
colHead = sp.getColumnHeader();
lowerLeft = sp.getCorner(LOWER_LEFT_CORNER);
lowerRight = sp.getCorner(LOWER_RIGHT_CORNER);
upperLeft = sp.getCorner(UPPER_LEFT_CORNER);
upperRight = sp.getCorner(UPPER_RIGHT_CORNER);
vsbPolicy = sp.getVerticalScrollBarPolicy();
hsbPolicy = sp.getHorizontalScrollBarPolicy();
}
/**
* Removes an existing component. When a new component, such as
* the left corner, or vertical scrollbar, is added, the old one,
* if it exists, must be removed.
* <p/>
* This method returns {@code newC}. If {@code oldC} is
* not equal to {@code newC} and is non-{@code null},
* it will be removed from its parent.
*
* @param oldC the {@code Component} to replace
* @param newC the {@code Component} to add
* @return the {@code newC}
*/
@Override
protected Component addSingletonComponent(Component oldC, Component newC) {
if ((oldC != null) && (oldC != newC)) {
oldC.getParent().remove(oldC);
}
return newC;
}
/**
* Adds the specified component to the layout. The layout is
* identified using one of:
* <ul>
* <li>JScrollPane.VIEWPORT
* <li>JScrollPane.VERTICAL_SCROLLBAR
* <li>JScrollPane.HORIZONTAL_SCROLLBAR
* <li>JScrollPane.ROW_HEADER
* <li>JScrollPane.COLUMN_HEADER
* <li>JScrollPane.LOWER_LEFT_CORNER
* <li>JScrollPane.LOWER_RIGHT_CORNER
* <li>JScrollPane.UPPER_LEFT_CORNER
* <li>JScrollPane.UPPER_RIGHT_CORNER
* </ul>
*
* @param s the component identifier
* @param c the component to be added
* @throws IllegalArgumentException if {@code s} is an invalid key
*/
@Override
public void addLayoutComponent(String s, Component c) {
if (s.equals(VIEWPORT)) {
viewport = (JViewport)addSingletonComponent(viewport, c);
}
else if (s.equals(VERTICAL_SCROLLBAR)) {
vsb = (JScrollBar)addSingletonComponent(vsb, c);
}
else if (s.equals(HORIZONTAL_SCROLLBAR)) {
hsb = (JScrollBar)addSingletonComponent(hsb, c);
}
else if (s.equals(ROW_HEADER)) {
rowHead = (JViewport)addSingletonComponent(rowHead, c);
}
else if (s.equals(COLUMN_HEADER)) {
colHead = (JViewport)addSingletonComponent(colHead, c);
}
else if (s.equals(LOWER_LEFT_CORNER)) {
lowerLeft = addSingletonComponent(lowerLeft, c);
}
else if (s.equals(LOWER_RIGHT_CORNER)) {
lowerRight = addSingletonComponent(lowerRight, c);
}
else if (s.equals(UPPER_LEFT_CORNER)) {
upperLeft = addSingletonComponent(upperLeft, c);
}
else if (s.equals(UPPER_RIGHT_CORNER)) {
upperRight = addSingletonComponent(upperRight, c);
}
else {
throw new IllegalArgumentException("invalid layout key " + s);
}
}
/**
* Removes the specified component from the layout.
*
* @param c the component to remove
*/
@Override
public void removeLayoutComponent(Component c) {
if (c == viewport) {
viewport = null;
}
else if (c == vsb) {
vsb = null;
}
else if (c == hsb) {
hsb = null;
}
else if (c == rowHead) {
rowHead = null;
}
else if (c == colHead) {
colHead = null;
}
else if (c == lowerLeft) {
lowerLeft = null;
}
else if (c == lowerRight) {
lowerRight = null;
}
else if (c == upperLeft) {
upperLeft = null;
}
else if (c == upperRight) {
upperRight = null;
}
}
/**
* Returns the vertical scrollbar-display policy.
*
* @return an integer giving the display policy
* @see #setVerticalScrollBarPolicy
*/
@Override
public int getVerticalScrollBarPolicy() {
return vsbPolicy;
}
/**
* Sets the vertical scrollbar-display policy. The options
* are:
* <ul>
* <li>JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
* <li>JScrollPane.VERTICAL_SCROLLBAR_NEVER
* <li>JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
* </ul>
* Note: Applications should use the {@code JScrollPane} version
* of this method. It only exists for backwards compatibility
* with the Swing 1.0.2 (and earlier) versions of this class.
*
* @param x an integer giving the display policy
* @throws IllegalArgumentException if {@code x} is an invalid
* vertical scroll bar policy, as listed above
*/
@Override
public void setVerticalScrollBarPolicy(int x) {
switch (x) {
case VERTICAL_SCROLLBAR_AS_NEEDED:
case VERTICAL_SCROLLBAR_NEVER:
case VERTICAL_SCROLLBAR_ALWAYS:
vsbPolicy = x;
break;
default:
throw new IllegalArgumentException("invalid verticalScrollBarPolicy");
}
}
/**
* Returns the horizontal scrollbar-display policy.
*
* @return an integer giving the display policy
* @see #setHorizontalScrollBarPolicy
*/
@Override
public int getHorizontalScrollBarPolicy() {
return hsbPolicy;
}
/**
* Sets the horizontal scrollbar-display policy.
* The options are:<ul>
* <li>JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
* <li>JScrollPane.HOTRIZONTAL_SCROLLBAR_NEVER
* <li>JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
* </ul>
* Note: Applications should use the {@code JScrollPane} version
* of this method. It only exists for backwards compatibility
* with the Swing 1.0.2 (and earlier) versions of this class.
*
* @param x an int giving the display policy
* @throws IllegalArgumentException if {@code x} is not a valid
* horizontal scrollbar policy, as listed above
*/
@Override
public void setHorizontalScrollBarPolicy(int x) {
switch (x) {
case HORIZONTAL_SCROLLBAR_AS_NEEDED:
case HORIZONTAL_SCROLLBAR_NEVER:
case HORIZONTAL_SCROLLBAR_ALWAYS:
hsbPolicy = x;
break;
default:
throw new IllegalArgumentException("invalid horizontalScrollBarPolicy");
}
}
/**
* Returns the {@code JViewport} object that displays the
* scrollable contents.
*
* @return the {@code JViewport} object that displays the scrollable contents
* @see javax.swing.JScrollPane#getViewport
*/
@Override
public JViewport getViewport() {
return viewport;
}
/**
* Returns the {@code JScrollBar} object that handles horizontal scrolling.
*
* @return the {@code JScrollBar} object that handles horizontal scrolling
* @see javax.swing.JScrollPane#getHorizontalScrollBar
*/
@Override
public JScrollBar getHorizontalScrollBar() {
return hsb;
}
/**
* Returns the {@code JScrollBar} object that handles vertical scrolling.
*
* @return the {@code JScrollBar} object that handles vertical scrolling
* @see javax.swing.JScrollPane#getVerticalScrollBar
*/
@Override
public JScrollBar getVerticalScrollBar() {
return vsb;
}
/**
* Returns the {@code JViewport} object that is the row header.
*
* @return the {@code JViewport} object that is the row header
* @see javax.swing.JScrollPane#getRowHeader
*/
@Override
public JViewport getRowHeader() {
return rowHead;
}
/**
* Returns the {@code JViewport} object that is the column header.
*
* @return the {@code JViewport} object that is the column header
* @see javax.swing.JScrollPane#getColumnHeader
*/
@Override
public JViewport getColumnHeader() {
return colHead;
}
/**
* Returns the {@code Component} at the specified corner.
*
* @param key the {@code String} specifying the corner
* @return the {@code Component} at the specified corner, as defined in
* {@link ScrollPaneConstants}; if {@code key} is not one of the
* four corners, {@code null} is returned
* @see javax.swing.JScrollPane#getCorner
*/
@Override
public Component getCorner(String key) {
if (key.equals(LOWER_LEFT_CORNER)) {
return lowerLeft;
}
else if (key.equals(LOWER_RIGHT_CORNER)) {
return lowerRight;
}
else if (key.equals(UPPER_LEFT_CORNER)) {
return upperLeft;
}
else if (key.equals(UPPER_RIGHT_CORNER)) {
return upperRight;
}
else {
return null;
}
}
/**
* The preferred size of a {@code ScrollPane} is the size of the insets,
* plus the preferred size of the viewport, plus the preferred size of
* the visible headers, plus the preferred size of the scrollbars
* that will appear given the current view and the current
* scrollbar displayPolicies.
* <p>Note that the rowHeader is calculated as part of the preferred width
* and the colHeader is calculated as part of the preferred size.
*
* @param parent the {@code Container} that will be laid out
* @return a {@code Dimension} object specifying the preferred size of the
* viewport and any scrollbars
* @see ViewportLayout
* @see LayoutManager
*/
@Override
public Dimension preferredLayoutSize(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane)parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int prefWidth = insets.left + insets.right;
int prefHeight = insets.top + insets.bottom;
/* Note that viewport.getViewSize() is equivalent to
* viewport.getView().getPreferredSize() modulo a null
* view or a view whose size was explicitly set.
*/
Dimension extentSize = null;
Dimension viewSize = null;
Component view = null;
if (viewport != null) {
extentSize = viewport.getPreferredSize();
viewSize = viewport.getViewSize();
view = viewport.getView();
}
/* If there's a viewport add its preferredSize.
*/
if (extentSize != null) {
prefWidth += extentSize.width;
prefHeight += extentSize.height;
}
/* If there's a JScrollPane.viewportBorder, add its insets.
*/
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
prefWidth += vpbInsets.left + vpbInsets.right;
prefHeight += vpbInsets.top + vpbInsets.bottom;
}
/* If a header exists and it's visible, factor its
* preferred size in.
*/
if ((rowHead != null) && rowHead.isVisible()) {
prefWidth += rowHead.getPreferredSize().width;
}
if ((colHead != null) && colHead.isVisible()) {
prefHeight += colHead.getPreferredSize().height;
}
/* If a scrollbar is going to appear, factor its preferred size in.
* If the scrollbars policy is AS_NEEDED, this can be a little
* tricky:
*
* - If the view is a Scrollable then scrollableTracksViewportWidth
* and scrollableTracksViewportHeight can be used to effectively
* disable scrolling (if they're true) in their respective dimensions.
*
* - Assuming that a scrollbar hasn't been disabled by the
* previous constraint, we need to decide if the scrollbar is going
* to appear to correctly compute the JScrollPanes preferred size.
* To do this we compare the preferredSize of the viewport (the
* extentSize) to the preferredSize of the view. Although we're
* not responsible for laying out the view we'll assume that the
* JViewport will always give it its preferredSize.
*/
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
prefWidth += vsb.getPreferredSize().width;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable)view).getScrollableTracksViewportHeight();
}
if (canScroll && (viewSize.height > extentSize.height)) {
prefWidth += vsb.getPreferredSize().width;
}
}
}
if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) {
if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
prefHeight += hsb.getPreferredSize().height;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable)view).getScrollableTracksViewportWidth();
}
if (canScroll && (viewSize.width > extentSize.width)) {
prefHeight += hsb.getPreferredSize().height;
}
}
}
return new Dimension(prefWidth, prefHeight);
}
/**
* The minimum size of a {@code ScrollPane} is the size of the insets
* plus minimum size of the viewport, plus the scrollpane's
* viewportBorder insets, plus the minimum size
* of the visible headers, plus the minimum size of the
* scrollbars whose displayPolicy isn't NEVER.
*
* @param parent the {@code Container} that will be laid out
* @return a {@code Dimension} object specifying the minimum size
*/
@Override
public Dimension minimumLayoutSize(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane)parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int minWidth = insets.left + insets.right;
int minHeight = insets.top + insets.bottom;
/* If there's a viewport add its minimumSize.
*/
if (viewport != null) {
Dimension size = viewport.getMinimumSize();
minWidth += size.width;
minHeight += size.height;
}
/* If there's a JScrollPane.viewportBorder, add its insets.
*/
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
minWidth += vpbInsets.left + vpbInsets.right;
minHeight += vpbInsets.top + vpbInsets.bottom;
}
/* If a header exists and it's visible, factor its
* minimum size in.
*/
if ((rowHead != null) && rowHead.isVisible()) {
Dimension size = rowHead.getMinimumSize();
minWidth += size.width;
minHeight = Math.max(minHeight, size.height);
}
if ((colHead != null) && colHead.isVisible()) {
Dimension size = colHead.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
minHeight += size.height;
}
/* If a scrollbar might appear, factor its minimum
* size in.
*/
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
Dimension size = vsb.getMinimumSize();
minWidth += size.width;
minHeight = Math.max(minHeight, size.height);
}
if ((hsb != null) && (hsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
Dimension size = hsb.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
minHeight += size.height;
}
return new Dimension(minWidth, minHeight);
}
/**
* Lays out the scrollpane. The positioning of components depends on
* the following constraints:
* <ul>
* <li> The row header, if present and visible, gets its preferred
* width and the viewport's height.
* <p/>
* <li> The column header, if present and visible, gets its preferred
* height and the viewport's width.
* <p/>
* <li> If a vertical scrollbar is needed, i.e. if the viewport's extent
* height is smaller than its view height or if the {@code displayPolicy}
* is ALWAYS, it's treated like the row header with respect to its
* dimensions and is made visible.
* <p/>
* <li> If a horizontal scrollbar is needed, it is treated like the
* column header (see the paragraph above regarding the vertical scrollbar).
* <p/>
* <li> If the scrollpane has a non-{@code null}
* {@code viewportBorder}, then space is allocated for that.
* <p/>
* <li> The viewport gets the space available after accounting for
* the previous constraints.
* <p/>
* <li> The corner components, if provided, are aligned with the
* ends of the scrollbars and headers. If there is a vertical
* scrollbar, the right corners appear; if there is a horizontal
* scrollbar, the lower corners appear; a row header gets left
* corners, and a column header gets upper corners.
* </ul>
*
* @param parent the {@code Container} to lay out
*/
@Override
public void layoutContainer(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane)parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Rectangle availR = scrollPane.getBounds();
availR.x = availR.y = 0;
Insets insets = parent.getInsets();
availR.x = insets.left;
availR.y = insets.top;
availR.width -= insets.left + insets.right;
availR.height -= insets.top + insets.bottom;
/* Get the scrollPane's orientation.
*/
boolean leftToRight = false;
/* If there's a visible column header remove the space it
* needs from the top of availR. The column header is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0);
if ((colHead != null) && (colHead.isVisible())) {
int colHeadHeight = Math.min(availR.height,
colHead.getPreferredSize().height);
colHeadR.height = colHeadHeight;
availR.y += colHeadHeight;
availR.height -= colHeadHeight;
}
/* If there's a visible row header remove the space it needs
* from the left or right of availR. The row header is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowHeadR = new Rectangle(0, 0, 0, 0);
if ((rowHead != null) && (rowHead.isVisible())) {
int rowHeadWidth = Math.min(availR.width,
rowHead.getPreferredSize().width);
rowHeadR.width = rowHeadWidth;
availR.width -= rowHeadWidth;
if (leftToRight) {
rowHeadR.x = availR.x;
availR.x += rowHeadWidth;
}
else {
rowHeadR.x = availR.x + availR.width;
}
}
/* If there's a JScrollPane.viewportBorder, remove the
* space it occupies for availR.
*/
Border viewportBorder = scrollPane.getViewportBorder();
Insets vpbInsets;
if (viewportBorder != null) {
vpbInsets = viewportBorder.getBorderInsets(parent);
availR.x += vpbInsets.left;
availR.y += vpbInsets.top;
availR.width -= vpbInsets.left + vpbInsets.right;
availR.height -= vpbInsets.top + vpbInsets.bottom;
}
else {
vpbInsets = new Insets(0, 0, 0, 0);
}
/* At this point availR is the space available for the viewport
* and scrollbars. rowHeadR is correct except for its height and y
* and colHeadR is correct except for its width and x. Once we're
* through computing the dimensions of these three parts we can
* go back and set the dimensions of rowHeadR.height, rowHeadR.y,
* colHeadR.width, colHeadR.x and the bounds for the corners.
*
* We'll decide about putting up scrollbars by comparing the
* viewport views preferred size with the viewports extent
* size (generally just its size). Using the preferredSize is
* reasonable because layout proceeds top down - so we expect
* the viewport to be laid out next. And we assume that the
* viewports layout manager will give the view it's preferred
* size. One exception to this is when the view implements
* Scrollable and Scrollable.getViewTracksViewport{Width,Height}
* methods return true. If the view is tracking the viewports
* width we don't bother with a horizontal scrollbar, similarly
* if view.getViewTracksViewport(Height) is true we don't bother
* with a vertical scrollbar.
*/
Component view = (viewport != null) ? viewport.getView() : null;
Dimension viewPrefSize =
(view != null) ? view.getPreferredSize()
: JBUI.emptySize();
Dimension extentSize =
(viewport != null) ? viewport.toViewCoordinates(availR.getSize())
: JBUI.emptySize();
boolean viewTracksViewportWidth = false;
boolean viewTracksViewportHeight = false;
boolean isEmpty = (availR.width < 0 || availR.height < 0);
Scrollable sv;
// Don't bother checking the Scrollable methods if there is no room
// for the viewport, we aren't going to show any scrollbars in this
// case anyway.
if (!isEmpty && view instanceof Scrollable) {
sv = (Scrollable)view;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
}
else {
sv = null;
}
/* If there's a vertical scrollbar and we need one, allocate
* space for it (we'll make it visible later). A vertical
* scrollbar is considered to be fixed width, arbitrary height.
*/
Rectangle vsbR = new Rectangle(0, availR.y - vpbInsets.top, 0, 0);
boolean vsbNeeded;
if (isEmpty) {
vsbNeeded = false;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
vsbNeeded = true;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) {
vsbNeeded = false;
}
else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED
vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height);
}
if ((vsb != null) && vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
extentSize = viewport.toViewCoordinates(availR.getSize());
}
/* If there's a horizontal scrollbar and we need one, allocate
* space for it (we'll make it visible later). A horizontal
* scrollbar is considered to be fixed height, arbitrary width.
*/
Rectangle hsbR = new Rectangle(availR.x - vpbInsets.left, 0, 0, 0);
boolean hsbNeeded;
if (isEmpty) {
hsbNeeded = false;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
hsbNeeded = true;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
hsbNeeded = false;
}
else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED
hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width);
}
if ((hsb != null) && hsbNeeded) {
adjustForHSB(true, availR, hsbR, vpbInsets);
/* If we added the horizontal scrollbar then we've implicitly
* reduced the vertical space available to the viewport.
* As a consequence we may have to add the vertical scrollbar,
* if that hasn't been done so already. Of course we
* don't bother with any of this if the vsbPolicy is NEVER.
*/
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates(availR.getSize());
vsbNeeded = viewPrefSize.height > extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, leftToRight);
}
}
}
/* Set the size of the viewport first, and then recheck the Scrollable
* methods. Some components base their return values for the Scrollable
* methods on the size of the Viewport, so that if we don't
* ask after resetting the bounds we may have gotten the wrong
* answer.
*/
if (viewport != null) {
viewport.setBounds(availR);
if (sv != null) {
extentSize = viewport.toViewCoordinates(availR.getSize());
boolean oldHSBNeeded = hsbNeeded;
boolean oldVSBNeeded = vsbNeeded;
viewTracksViewportWidth = sv.
getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.
getScrollableTracksViewportHeight();
if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) {
boolean newVSBNeeded = !viewTracksViewportHeight &&
(viewPrefSize.height > extentSize.height);
if (newVSBNeeded != vsbNeeded) {
vsbNeeded = newVSBNeeded;
adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets,
leftToRight);
extentSize = viewport.toViewCoordinates
(availR.getSize());
}
}
if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) {
boolean newHSBbNeeded = !viewTracksViewportWidth &&
(viewPrefSize.width > extentSize.width);
if (newHSBbNeeded != hsbNeeded) {
hsbNeeded = newHSBbNeeded;
adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets);
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates
(availR.getSize());
vsbNeeded = viewPrefSize.height >
extentSize.height;
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets,
leftToRight);
}
}
}
}
if (oldHSBNeeded != hsbNeeded ||
oldVSBNeeded != vsbNeeded) {
viewport.setBounds(availR);
// You could argue that we should recheck the
// Scrollable methods again until they stop changing,
// but they might never stop changing, so we stop here
// and don't do any additional checks.
}
}
}
/* We now have the final size of the viewport: availR.
* Now fixup the header and scrollbar widths/heights.
*/
vsbR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
hsbR.width = availR.width + vpbInsets.left + vpbInsets.right;
rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
rowHeadR.y = availR.y - vpbInsets.top;
colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right;
colHeadR.x = availR.x - vpbInsets.left;
/* Set the bounds of the remaining components. The scrollbars
* are made invisible if they're not needed.
*/
if (rowHead != null) {
rowHead.setBounds(rowHeadR);
}
if (colHead != null) {
colHead.setBounds(colHeadR);
}
if (vsb != null) {
if (vsbNeeded) {
vsb.setVisible(true);
vsb.setBounds(vsbR);
}
else {
vsb.setVisible(false);
}
}
if (hsb != null) {
if (hsbNeeded) {
hsb.setVisible(true);
hsb.setBounds(hsbR);
}
else {
hsb.setVisible(false);
}
}
if (lowerLeft != null) {
lowerLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
hsbR.y,
leftToRight ? rowHeadR.width : vsbR.width,
hsbR.height);
}
if (lowerRight != null) {
lowerRight.setBounds(leftToRight ? vsbR.x : rowHeadR.x,
hsbR.y,
leftToRight ? vsbR.width : rowHeadR.width,
hsbR.height);
}
if (upperLeft != null) {
upperLeft.setBounds(leftToRight ? rowHeadR.x : vsbR.x,
colHeadR.y,
leftToRight ? rowHeadR.width : vsbR.width,
colHeadR.height);
}
if (upperRight != null) {
upperRight.setBounds(leftToRight ? vsbR.x : rowHeadR.x,
colHeadR.y,
leftToRight ? vsbR.width : rowHeadR.width,
colHeadR.height);
}
}
/**
* Adjusts the {@code Rectangle} {@code available} based on if
* the vertical scrollbar is needed ({@code wantsVSB}).
* The location of the vsb is updated in {@code vsbR}, and
* the viewport border insets ({@code vpbInsets}) are used to offset
* the vsb. This is only called when {@code wantsVSB} has
* changed, eg you shouldn't invoke adjustForVSB(true) twice.
*/
private void adjustForVSB(boolean wantsVSB, Rectangle available,
Rectangle vsbR, Insets vpbInsets,
boolean leftToRight) {
int oldWidth = vsbR.width;
if (wantsVSB) {
int vsbWidth = Math.max(0, Math.min(vsb.getPreferredSize().width,
available.width));
available.width -= vsbWidth;
vsbR.width = vsbWidth;
if (leftToRight) {
vsbR.x = available.x + available.width + vpbInsets.right;
}
else {
vsbR.x = available.x - vpbInsets.left;
available.x += vsbWidth;
}
}
else {
available.width += oldWidth;
}
}
/**
* Adjusts the {@code Rectangle} {@code available} based on if
* the horizontal scrollbar is needed ({@code wantsHSB}).
* The location of the hsb is updated in {@code hsbR}, and
* the viewport border insets ({@code vpbInsets}) are used to offset
* the hsb. This is only called when {@code wantsHSB} has
* changed, eg you shouldn't invoked adjustForHSB(true) twice.
*/
private void adjustForHSB(boolean wantsHSB, Rectangle available,
Rectangle hsbR, Insets vpbInsets) {
int oldHeight = hsbR.height;
if (wantsHSB) {
int hsbHeight = Math.max(0, Math.min(available.height,
hsb.getPreferredSize().height));
available.height -= hsbHeight;
hsbR.y = available.y + available.height + vpbInsets.bottom;
hsbR.height = hsbHeight;
}
else {
available.height += oldHeight;
}
}
/**
* Returns the bounds of the border around the specified scroll pane's
* viewport.
*
* @return the size and position of the viewport border
* @deprecated As of JDK version Swing1.1
* replaced by {@code JScrollPane.getViewportBorderBounds()}.
*/
@Deprecated
@Override
public Rectangle getViewportBorderBounds(JScrollPane scrollpane) {
return scrollpane.getViewportBorderBounds();
}
}
| |
/*
* Copyright 2014-2016 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaaproject.kaa.server.common.nosql.cassandra.dao.model;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.OPT_LOCK;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.CassandraDaoUtil.convertDtoToModelList;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.CassandraDaoUtil.convertEcfVersionDtoToModelList;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.CassandraDaoUtil.getByteBuffer;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.CassandraDaoUtil.getBytes;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_ACCESS_TOKEN_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_APP_ID_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_COLUMN_FAMILY_NAME;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_CONFIGURATION_VERSION_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_CONFIG_HASH_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_ECF_VERSION_STATE_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_ENDPOINT_ID_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_EPS_CONFIG_HASH_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_EP_KEY_HASH_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_EP_KEY_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_GROUP_STATE_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_LOG_SCHEMA_VERSION_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_NOTIFICATION_VERSION_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_PROFILE_HASH_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_PROFILE_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_PROFILE_VERSION_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_SDK_TOKEN_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_SEQUENCE_NUMBER_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_SERVER_HASH_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_SERVER_PROFILE_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_SERVER_PROFILE_VERSION_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_SIMPLE_TOPIC_HASH_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_SUBSCRIPTIONS_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_SYSTEM_NOTIFICATION_VERSION_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_TOPIC_HASH_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_USER_CONFIG_HASH_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_USER_ID_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_USER_NOTIFICATION_VERSION_PROPERTY;
import static org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.CassandraModelConstants.EP_USE_RAW_SCHEMA;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.FrozenValue;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
import org.kaaproject.kaa.common.dto.EndpointProfileDto;
import org.kaaproject.kaa.common.dto.EventClassFamilyVersionStateDto;
import org.kaaproject.kaa.server.common.dao.impl.DaoUtil;
import org.kaaproject.kaa.server.common.dao.model.EndpointProfile;
import org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.type.CassandraEndpointGroupState;
import org.kaaproject.kaa.server.common.nosql.cassandra.dao.model.type.CassandraEventClassFamilyVersionState;
import org.kaaproject.kaa.server.common.utils.Utils;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.List;
@Table(name = EP_COLUMN_FAMILY_NAME)
public final class CassandraEndpointProfile implements EndpointProfile, Serializable {
@Transient
private static final long serialVersionUID = -3227246639864687299L;
@PartitionKey
@Column(name = EP_EP_KEY_HASH_PROPERTY)
private ByteBuffer endpointKeyHash;
@Column(name = EP_ENDPOINT_ID_PROPERTY)
private String id;
@Column(name = EP_EP_KEY_PROPERTY)
private ByteBuffer endpointProfileKey;
@Column(name = EP_APP_ID_PROPERTY)
private String applicationId;
@Column(name = EP_USER_ID_PROPERTY)
private String endpointUserId;
@Column(name = EP_ACCESS_TOKEN_PROPERTY)
private String accessToken;
@Column(name = EP_GROUP_STATE_PROPERTY)
@FrozenValue
private List<CassandraEndpointGroupState> groupStates;
@Column(name = EP_SEQUENCE_NUMBER_PROPERTY)
private int sequenceNumber;
@Column(name = EP_PROFILE_PROPERTY)
private String profile;
@Column(name = EP_PROFILE_HASH_PROPERTY)
private ByteBuffer profileHash;
@Column(name = EP_PROFILE_VERSION_PROPERTY)
private int profileVersion;
@Column(name = EP_SERVER_PROFILE_VERSION_PROPERTY)
private int serverProfileVersion;
@Column(name = EP_CONFIG_HASH_PROPERTY)
private ByteBuffer configurationHash;
@Column(name = EP_USER_CONFIG_HASH_PROPERTY)
private ByteBuffer userConfigurationHash;
@Column(name = EP_CONFIGURATION_VERSION_PROPERTY)
private int configurationVersion;
@Column(name = EP_NOTIFICATION_VERSION_PROPERTY)
private int notificationVersion;
@Column(name = EP_EPS_CONFIG_HASH_PROPERTY)
private ByteBuffer epsConfigurationHash;
@Column(name = EP_SUBSCRIPTIONS_PROPERTY)
private List<String> subscriptions;
@Column(name = EP_TOPIC_HASH_PROPERTY)
private ByteBuffer topicHash;
@Column(name = EP_SIMPLE_TOPIC_HASH_PROPERTY)
private int simpleTopicHash;
@Column(name = EP_SYSTEM_NOTIFICATION_VERSION_PROPERTY)
private int systemNfVersion;
@Column(name = EP_USER_NOTIFICATION_VERSION_PROPERTY)
private int userNfVersion;
@Column(name = EP_LOG_SCHEMA_VERSION_PROPERTY)
private int logSchemaVersion;
@Column(name = EP_ECF_VERSION_STATE_PROPERTY)
@FrozenValue
private List<CassandraEventClassFamilyVersionState> ecfVersionStates;
@Column(name = EP_SERVER_HASH_PROPERTY)
private String serverHash;
@Column(name = EP_SDK_TOKEN_PROPERTY)
private String sdkToken;
@Column(name = EP_SERVER_PROFILE_PROPERTY)
private String serverProfile;
@Column(name = EP_USE_RAW_SCHEMA)
private Boolean useConfigurationRawSchema;
@Column(name = OPT_LOCK)
private Long version;
public CassandraEndpointProfile() {
}
/**
* Create new instance of <code>CassandraEndpointProfile</code>.
* @param dto is data transfer object contain data that
* assign on fields of new instance
*/
public CassandraEndpointProfile(EndpointProfileDto dto) {
this.id = dto.getId();
this.applicationId = dto.getApplicationId();
this.endpointProfileKey = getByteBuffer(dto.getEndpointKey());
this.endpointKeyHash = getByteBuffer(dto.getEndpointKeyHash());
this.endpointUserId = dto.getEndpointUserId();
this.accessToken = dto.getAccessToken();
this.groupStates = convertDtoToModelList(dto.getGroupState());
this.sequenceNumber = dto.getSequenceNumber();
this.profile = dto.getClientProfileBody();
this.profileHash = getByteBuffer(dto.getProfileHash());
this.profileVersion = dto.getClientProfileVersion();
this.serverProfileVersion = dto.getServerProfileVersion();
this.configurationHash = getByteBuffer(dto.getConfigurationHash());
this.userConfigurationHash = getByteBuffer(dto.getUserConfigurationHash());
this.configurationVersion = dto.getConfigurationVersion();
this.subscriptions = dto.getSubscriptions();
this.notificationVersion = dto.getNotificationVersion();
this.topicHash = getByteBuffer(dto.getTopicHash());
this.simpleTopicHash = dto.getSimpleTopicHash();
this.systemNfVersion = dto.getSystemNfVersion();
this.userNfVersion = dto.getUserNfVersion();
this.logSchemaVersion = dto.getLogSchemaVersion();
this.ecfVersionStates = convertEcfVersionDtoToModelList(dto.getEcfVersionStates());
this.serverHash = dto.getServerHash();
this.sdkToken = dto.getSdkToken();
this.serverProfile = dto.getServerProfileBody();
this.useConfigurationRawSchema = dto.isUseConfigurationRawSchema();
this.version = dto.getVersion();
this.epsConfigurationHash = getByteBuffer(dto.getEpsConfigurationHash());
}
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public byte[] getEndpointKey() {
return getBytes(endpointProfileKey);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ByteBuffer getEndpointProfileKey() {
return endpointProfileKey;
}
public void setEndpointProfileKey(ByteBuffer endpointProfileKey) {
this.endpointProfileKey = endpointProfileKey;
}
public ByteBuffer getEndpointKeyHash() {
return endpointKeyHash;
}
public void setEndpointKeyHash(ByteBuffer endpointKeyHash) {
this.endpointKeyHash = endpointKeyHash;
}
public String getEndpointUserId() {
return endpointUserId;
}
public void setEndpointUserId(String endpointUserId) {
this.endpointUserId = endpointUserId;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public List<CassandraEndpointGroupState> getGroupStates() {
return groupStates;
}
public void setGroupStates(List<CassandraEndpointGroupState> groupStates) {
this.groupStates = groupStates;
}
public int getSequenceNumber() {
return sequenceNumber;
}
public void setSequenceNumber(int sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public ByteBuffer getProfileHash() {
return profileHash;
}
public void setProfileHash(ByteBuffer profileHash) {
this.profileHash = profileHash;
}
public int getProfileVersion() {
return profileVersion;
}
public void setProfileVersion(int profileVersion) {
this.profileVersion = profileVersion;
}
public ByteBuffer getConfigurationHash() {
return configurationHash;
}
public void setConfigurationHash(ByteBuffer configurationHash) {
this.configurationHash = configurationHash;
}
public ByteBuffer getUserConfigurationHash() {
return userConfigurationHash;
}
public void setUserConfigurationHash(ByteBuffer userConfigurationHash) {
this.userConfigurationHash = userConfigurationHash;
}
public ByteBuffer getEpsConfigurationHash() {
return epsConfigurationHash;
}
public void setEpsConfigurationHash(ByteBuffer epsConfigurationHash) {
this.epsConfigurationHash = epsConfigurationHash;
}
public int getConfigurationVersion() {
return configurationVersion;
}
public void setConfigurationVersion(int configurationVersion) {
this.configurationVersion = configurationVersion;
}
public int getNotificationVersion() {
return notificationVersion;
}
public void setNotificationVersion(int notificationVersion) {
this.notificationVersion = notificationVersion;
}
@Override
public List<String> getSubscriptions() {
return subscriptions;
}
public void setSubscriptions(List<String> subscriptions) {
this.subscriptions = subscriptions;
}
public int getServerProfileVersion() {
return serverProfileVersion;
}
public void setServerProfileVersion(int serverProfileVersion) {
this.serverProfileVersion = serverProfileVersion;
}
public String getServerProfile() {
return serverProfile;
}
public void setServerProfile(String serverProfile) {
this.serverProfile = serverProfile;
}
public ByteBuffer getTopicHash() {
return topicHash;
}
public void setTopicHash(ByteBuffer topicHash) {
this.topicHash = topicHash;
}
public int getSimpleTopicHash() {
return simpleTopicHash;
}
public void setSimpleTopicHash(int simpleTopicHash) {
this.simpleTopicHash = simpleTopicHash;
}
public int getSystemNfVersion() {
return systemNfVersion;
}
public void setSystemNfVersion(int systemNfVersion) {
this.systemNfVersion = systemNfVersion;
}
public int getUserNfVersion() {
return userNfVersion;
}
public void setUserNfVersion(int userNfVersion) {
this.userNfVersion = userNfVersion;
}
public int getLogSchemaVersion() {
return logSchemaVersion;
}
public void setLogSchemaVersion(int logSchemaVersion) {
this.logSchemaVersion = logSchemaVersion;
}
public List<CassandraEventClassFamilyVersionState> getEcfVersionStates() {
return ecfVersionStates;
}
public void setEcfVersionStates(List<CassandraEventClassFamilyVersionState> ecfVersionStates) {
this.ecfVersionStates = ecfVersionStates;
}
public String getServerHash() {
return serverHash;
}
public void setServerHash(String serverHash) {
this.serverHash = serverHash;
}
public String getSdkToken() {
return sdkToken;
}
public void setSdkToken(String sdkToken) {
this.sdkToken = sdkToken;
}
public Boolean getUseConfigurationRawSchema() {
return useConfigurationRawSchema;
}
public void setUseConfigurationRawSchema(Boolean useConfigurationRawSchema) {
this.useConfigurationRawSchema = useConfigurationRawSchema;
}
@Override
public Long getVersion() {
return version;
}
@Override
public void setVersion(Long version) {
this.version = version;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
CassandraEndpointProfile that = (CassandraEndpointProfile) object;
if (sequenceNumber != that.sequenceNumber) {
return false;
}
if (profileVersion != that.profileVersion) {
return false;
}
if (serverProfileVersion != that.serverProfileVersion) {
return false;
}
if (configurationVersion != that.configurationVersion) {
return false;
}
if (epsConfigurationHash != null ? !epsConfigurationHash.equals(that.epsConfigurationHash) : that.epsConfigurationHash != null) {
return false;
}
if (notificationVersion != that.notificationVersion) {
return false;
}
if (systemNfVersion != that.systemNfVersion) {
return false;
}
if (userNfVersion != that.userNfVersion) {
return false;
}
if (logSchemaVersion != that.logSchemaVersion) {
return false;
}
if (endpointKeyHash != null
? !endpointKeyHash.equals(that.endpointKeyHash)
: that.endpointKeyHash != null) {
return false;
}
if (id != null ? !id.equals(that.id) : that.id != null) {
return false;
}
if (endpointProfileKey != null
? !endpointProfileKey.equals(that.endpointProfileKey)
: that.endpointProfileKey != null) {
return false;
}
if (applicationId != null
? !applicationId.equals(that.applicationId)
: that.applicationId != null) {
return false;
}
if (endpointUserId != null
? !endpointUserId.equals(that.endpointUserId)
: that.endpointUserId != null) {
return false;
}
if (accessToken != null
? !accessToken.equals(that.accessToken)
: that.accessToken != null) {
return false;
}
if (groupStates != null
? !groupStates.equals(that.groupStates)
: that.groupStates != null) {
return false;
}
if (profile != null
? !profile.equals(that.profile)
: that.profile != null) {
return false;
}
if (profileHash != null
? !profileHash.equals(that.profileHash)
: that.profileHash != null) {
return false;
}
if (configurationHash != null
? !configurationHash.equals(that.configurationHash)
: that.configurationHash != null) {
return false;
}
if (userConfigurationHash != null
? !userConfigurationHash.equals(that.userConfigurationHash)
: that.userConfigurationHash != null) {
return false;
}
if (subscriptions != null
? !subscriptions.equals(that.subscriptions)
: that.subscriptions != null) {
return false;
}
if (topicHash != null
? !topicHash.equals(that.topicHash)
: that.topicHash != null) {
return false;
}
if (ecfVersionStates != null
? !ecfVersionStates.equals(that.ecfVersionStates)
: that.ecfVersionStates != null) {
return false;
}
if (serverHash != null
? !serverHash.equals(that.serverHash)
: that.serverHash != null) {
return false;
}
if (sdkToken != null
? !sdkToken.equals(that.sdkToken)
: that.sdkToken != null) {
return false;
}
if (useConfigurationRawSchema != null
? !useConfigurationRawSchema.equals(that.useConfigurationRawSchema)
: that.useConfigurationRawSchema != null) {
return false;
}
return serverProfile != null
? serverProfile.equals(that.serverProfile)
: that.serverProfile == null;
}
@Override
public int hashCode() {
int result = endpointKeyHash != null ? endpointKeyHash.hashCode() : 0;
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (endpointProfileKey != null ? endpointProfileKey.hashCode() : 0);
result = 31 * result + (applicationId != null ? applicationId.hashCode() : 0);
result = 31 * result + (endpointUserId != null ? endpointUserId.hashCode() : 0);
result = 31 * result + (accessToken != null ? accessToken.hashCode() : 0);
result = 31 * result + (groupStates != null ? groupStates.hashCode() : 0);
result = 31 * result + sequenceNumber;
result = 31 * result + (profile != null ? profile.hashCode() : 0);
result = 31 * result + (profileHash != null ? profileHash.hashCode() : 0);
result = 31 * result + profileVersion;
result = 31 * result + serverProfileVersion;
result = 31 * result + (configurationHash != null ? configurationHash.hashCode() : 0);
result = 31 * result
+ (userConfigurationHash != null ? userConfigurationHash.hashCode() : 0);
result = 31 * result + (epsConfigurationHash != null ? epsConfigurationHash.hashCode() : 0);
result = 31 * result + configurationVersion;
result = 31 * result + notificationVersion;
result = 31 * result + (subscriptions != null ? subscriptions.hashCode() : 0);
result = 31 * result + (topicHash != null ? topicHash.hashCode() : 0);
result = 31 * result + systemNfVersion;
result = 31 * result + userNfVersion;
result = 31 * result + logSchemaVersion;
result = 31 * result + (ecfVersionStates != null ? ecfVersionStates.hashCode() : 0);
result = 31 * result + (serverHash != null ? serverHash.hashCode() : 0);
result = 31 * result + (sdkToken != null ? sdkToken.hashCode() : 0);
result = 31 * result
+ (useConfigurationRawSchema != null ? useConfigurationRawSchema.hashCode() : 0);
result = 31 * result + (serverProfile != null ? serverProfile.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "CassandraEndpointProfile{"
+ "endpointKeyHash=" + Utils.encodeHexString(endpointKeyHash)
+ ", id='" + id + '\''
+ ", endpointProfileKey=" + Utils.encodeHexString(endpointProfileKey)
+ ", applicationId='" + applicationId + '\''
+ ", endpointUserId='" + endpointUserId + '\''
+ ", accessToken='" + accessToken + '\''
+ ", groupStates=" + groupStates
+ ", sequenceNumber=" + sequenceNumber
+ ", profile='" + profile + '\''
+ ", profileHash=" + Utils.encodeHexString(profileHash)
+ ", profileVersion=" + profileVersion
+ ", serverProfileVersion=" + serverProfileVersion
+ ", configurationHash=" + Utils.encodeHexString(configurationHash)
+ ", userConfigurationHash=" + Utils.encodeHexString(userConfigurationHash)
+ ", epsConfigurationHash=" + Utils.encodeHexString(epsConfigurationHash)
+ ", configurationVersion=" + configurationVersion
+ ", notificationVersion=" + notificationVersion
+ ", subscriptions=" + subscriptions
+ ", topicHash=" + Utils.encodeHexString(topicHash)
+ ", simpleTopicHash=" + simpleTopicHash
+ ", systemNfVersion=" + systemNfVersion
+ ", userNfVersion=" + userNfVersion
+ ", logSchemaVersion=" + logSchemaVersion
+ ", ecfVersionStates=" + ecfVersionStates
+ ", serverHash='" + serverHash + '\''
+ ", sdkToken='" + sdkToken + '\''
+ ", useRawSchema=" + useConfigurationRawSchema
+ ", serverProfile='" + serverProfile + '\''
+ '}';
}
@Override
public EndpointProfileDto toDto() {
EndpointProfileDto dto = new EndpointProfileDto();
dto.setId(id);
dto.setGroupState(DaoUtil.convertDtoList(groupStates));
dto.setSequenceNumber(sequenceNumber);
dto.setConfigurationHash(getBytes(configurationHash));
dto.setUserConfigurationHash(getBytes(userConfigurationHash));
dto.setConfigurationVersion(configurationVersion);
dto.setApplicationId(applicationId);
dto.setEndpointKey(getBytes(endpointProfileKey));
dto.setEndpointKeyHash(getBytes(endpointKeyHash));
dto.setEndpointUserId(endpointUserId);
dto.setAccessToken(accessToken);
dto.setClientProfileBody(profile);
dto.setProfileHash(getBytes(profileHash));
dto.setClientProfileVersion(profileVersion);
dto.setServerProfileVersion(serverProfileVersion);
dto.setNotificationVersion(notificationVersion);
dto.setSubscriptions(subscriptions);
dto.setTopicHash(getBytes(topicHash));
dto.setSimpleTopicHash(simpleTopicHash);
dto.setSystemNfVersion(systemNfVersion);
dto.setUserNfVersion(userNfVersion);
dto.setLogSchemaVersion(logSchemaVersion);
dto.setEcfVersionStates(
DaoUtil.<EventClassFamilyVersionStateDto>convertDtoList(ecfVersionStates)
);
dto.setServerHash(serverHash);
dto.setSdkToken(sdkToken);
dto.setServerProfileBody(serverProfile);
dto.setUseConfigurationRawSchema(useConfigurationRawSchema);
dto.setVersion(version);
dto.setEpsConfigurationHash(getBytes(epsConfigurationHash));
return dto;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.io.kinesis;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verifyZeroInteractions;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.AmazonServiceException.ErrorType;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.model.Datapoint;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest;
import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsResult;
import com.amazonaws.services.kinesis.AmazonKinesis;
import com.amazonaws.services.kinesis.model.DescribeStreamResult;
import com.amazonaws.services.kinesis.model.ExpiredIteratorException;
import com.amazonaws.services.kinesis.model.GetRecordsRequest;
import com.amazonaws.services.kinesis.model.GetRecordsResult;
import com.amazonaws.services.kinesis.model.GetShardIteratorRequest;
import com.amazonaws.services.kinesis.model.GetShardIteratorResult;
import com.amazonaws.services.kinesis.model.LimitExceededException;
import com.amazonaws.services.kinesis.model.ProvisionedThroughputExceededException;
import com.amazonaws.services.kinesis.model.Record;
import com.amazonaws.services.kinesis.model.Shard;
import com.amazonaws.services.kinesis.model.ShardIteratorType;
import com.amazonaws.services.kinesis.model.StreamDescription;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.joda.time.Instant;
import org.joda.time.Minutes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
/** * */
@RunWith(MockitoJUnitRunner.class)
public class SimplifiedKinesisClientTest {
private static final String STREAM = "stream";
private static final String SHARD_1 = "shard-01";
private static final String SHARD_2 = "shard-02";
private static final String SHARD_3 = "shard-03";
private static final String SHARD_ITERATOR = "iterator";
private static final String SEQUENCE_NUMBER = "abc123";
@Mock private AmazonKinesis kinesis;
@Mock private AmazonCloudWatch cloudWatch;
@InjectMocks private SimplifiedKinesisClient underTest;
@Test
public void shouldReturnIteratorStartingWithSequenceNumber() throws Exception {
given(
kinesis.getShardIterator(
new GetShardIteratorRequest()
.withStreamName(STREAM)
.withShardId(SHARD_1)
.withShardIteratorType(ShardIteratorType.AT_SEQUENCE_NUMBER)
.withStartingSequenceNumber(SEQUENCE_NUMBER)))
.willReturn(new GetShardIteratorResult().withShardIterator(SHARD_ITERATOR));
String stream =
underTest.getShardIterator(
STREAM, SHARD_1, ShardIteratorType.AT_SEQUENCE_NUMBER, SEQUENCE_NUMBER, null);
assertThat(stream).isEqualTo(SHARD_ITERATOR);
}
@Test
public void shouldReturnIteratorStartingWithTimestamp() throws Exception {
Instant timestamp = Instant.now();
given(
kinesis.getShardIterator(
new GetShardIteratorRequest()
.withStreamName(STREAM)
.withShardId(SHARD_1)
.withShardIteratorType(ShardIteratorType.AT_SEQUENCE_NUMBER)
.withTimestamp(timestamp.toDate())))
.willReturn(new GetShardIteratorResult().withShardIterator(SHARD_ITERATOR));
String stream =
underTest.getShardIterator(
STREAM, SHARD_1, ShardIteratorType.AT_SEQUENCE_NUMBER, null, timestamp);
assertThat(stream).isEqualTo(SHARD_ITERATOR);
}
@Test
public void shouldHandleExpiredIterationExceptionForGetShardIterator() {
shouldHandleGetShardIteratorError(
new ExpiredIteratorException(""), ExpiredIteratorException.class);
}
@Test
public void shouldHandleLimitExceededExceptionForGetShardIterator() {
shouldHandleGetShardIteratorError(
new LimitExceededException(""), TransientKinesisException.class);
}
@Test
public void shouldHandleProvisionedThroughputExceededExceptionForGetShardIterator() {
shouldHandleGetShardIteratorError(
new ProvisionedThroughputExceededException(""), TransientKinesisException.class);
}
@Test
public void shouldHandleServiceErrorForGetShardIterator() {
shouldHandleGetShardIteratorError(
newAmazonServiceException(ErrorType.Service), TransientKinesisException.class);
}
@Test
public void shouldHandleClientErrorForGetShardIterator() {
shouldHandleGetShardIteratorError(
newAmazonServiceException(ErrorType.Client), RuntimeException.class);
}
@Test
public void shouldHandleUnexpectedExceptionForGetShardIterator() {
shouldHandleGetShardIteratorError(new NullPointerException(), RuntimeException.class);
}
private void shouldHandleGetShardIteratorError(
Exception thrownException, Class<? extends Exception> expectedExceptionClass) {
GetShardIteratorRequest request =
new GetShardIteratorRequest()
.withStreamName(STREAM)
.withShardId(SHARD_1)
.withShardIteratorType(ShardIteratorType.LATEST);
given(kinesis.getShardIterator(request)).willThrow(thrownException);
try {
underTest.getShardIterator(STREAM, SHARD_1, ShardIteratorType.LATEST, null, null);
failBecauseExceptionWasNotThrown(expectedExceptionClass);
} catch (Exception e) {
assertThat(e).isExactlyInstanceOf(expectedExceptionClass);
} finally {
reset(kinesis);
}
}
@Test
public void shouldListAllShards() throws Exception {
Shard shard1 = new Shard().withShardId(SHARD_1);
Shard shard2 = new Shard().withShardId(SHARD_2);
Shard shard3 = new Shard().withShardId(SHARD_3);
given(kinesis.describeStream(STREAM, null))
.willReturn(
new DescribeStreamResult()
.withStreamDescription(
new StreamDescription().withShards(shard1, shard2).withHasMoreShards(true)));
given(kinesis.describeStream(STREAM, SHARD_2))
.willReturn(
new DescribeStreamResult()
.withStreamDescription(
new StreamDescription().withShards(shard3).withHasMoreShards(false)));
List<Shard> shards = underTest.listShards(STREAM);
assertThat(shards).containsOnly(shard1, shard2, shard3);
}
@Test
public void shouldHandleExpiredIterationExceptionForShardListing() {
shouldHandleShardListingError(new ExpiredIteratorException(""), ExpiredIteratorException.class);
}
@Test
public void shouldHandleLimitExceededExceptionForShardListing() {
shouldHandleShardListingError(new LimitExceededException(""), TransientKinesisException.class);
}
@Test
public void shouldHandleProvisionedThroughputExceededExceptionForShardListing() {
shouldHandleShardListingError(
new ProvisionedThroughputExceededException(""), TransientKinesisException.class);
}
@Test
public void shouldHandleServiceErrorForShardListing() {
shouldHandleShardListingError(
newAmazonServiceException(ErrorType.Service), TransientKinesisException.class);
}
@Test
public void shouldHandleClientErrorForShardListing() {
shouldHandleShardListingError(
newAmazonServiceException(ErrorType.Client), RuntimeException.class);
}
@Test
public void shouldHandleUnexpectedExceptionForShardListing() {
shouldHandleShardListingError(new NullPointerException(), RuntimeException.class);
}
private void shouldHandleShardListingError(
Exception thrownException, Class<? extends Exception> expectedExceptionClass) {
given(kinesis.describeStream(STREAM, null)).willThrow(thrownException);
try {
underTest.listShards(STREAM);
failBecauseExceptionWasNotThrown(expectedExceptionClass);
} catch (Exception e) {
assertThat(e).isExactlyInstanceOf(expectedExceptionClass);
} finally {
reset(kinesis);
}
}
@Test
public void shouldCountBytesWhenSingleDataPointReturned() throws Exception {
Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
Instant countTo = new Instant("2017-04-06T11:00:00.000Z");
Minutes periodTime = Minutes.minutesBetween(countSince, countTo);
GetMetricStatisticsRequest metricStatisticsRequest =
underTest.createMetricStatisticsRequest(STREAM, countSince, countTo, periodTime);
GetMetricStatisticsResult result =
new GetMetricStatisticsResult().withDatapoints(new Datapoint().withSum(1.0));
given(cloudWatch.getMetricStatistics(metricStatisticsRequest)).willReturn(result);
long backlogBytes = underTest.getBacklogBytes(STREAM, countSince, countTo);
assertThat(backlogBytes).isEqualTo(1L);
}
@Test
public void shouldCountBytesWhenMultipleDataPointsReturned() throws Exception {
Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
Instant countTo = new Instant("2017-04-06T11:00:00.000Z");
Minutes periodTime = Minutes.minutesBetween(countSince, countTo);
GetMetricStatisticsRequest metricStatisticsRequest =
underTest.createMetricStatisticsRequest(STREAM, countSince, countTo, periodTime);
GetMetricStatisticsResult result =
new GetMetricStatisticsResult()
.withDatapoints(
new Datapoint().withSum(1.0),
new Datapoint().withSum(3.0),
new Datapoint().withSum(2.0));
given(cloudWatch.getMetricStatistics(metricStatisticsRequest)).willReturn(result);
long backlogBytes = underTest.getBacklogBytes(STREAM, countSince, countTo);
assertThat(backlogBytes).isEqualTo(6L);
}
@Test
public void shouldNotCallCloudWatchWhenSpecifiedPeriodTooShort() throws Exception {
Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
Instant countTo = new Instant("2017-04-06T10:00:02.000Z");
long backlogBytes = underTest.getBacklogBytes(STREAM, countSince, countTo);
assertThat(backlogBytes).isEqualTo(0L);
verifyZeroInteractions(cloudWatch);
}
@Test
public void shouldHandleLimitExceededExceptionForGetBacklogBytes() {
shouldHandleGetBacklogBytesError(
new LimitExceededException(""), TransientKinesisException.class);
}
@Test
public void shouldHandleProvisionedThroughputExceededExceptionForGetBacklogBytes() {
shouldHandleGetBacklogBytesError(
new ProvisionedThroughputExceededException(""), TransientKinesisException.class);
}
@Test
public void shouldHandleServiceErrorForGetBacklogBytes() {
shouldHandleGetBacklogBytesError(
newAmazonServiceException(ErrorType.Service), TransientKinesisException.class);
}
@Test
public void shouldHandleClientErrorForGetBacklogBytes() {
shouldHandleGetBacklogBytesError(
newAmazonServiceException(ErrorType.Client), RuntimeException.class);
}
@Test
public void shouldHandleUnexpectedExceptionForGetBacklogBytes() {
shouldHandleGetBacklogBytesError(new NullPointerException(), RuntimeException.class);
}
private void shouldHandleGetBacklogBytesError(
Exception thrownException, Class<? extends Exception> expectedExceptionClass) {
Instant countSince = new Instant("2017-04-06T10:00:00.000Z");
Instant countTo = new Instant("2017-04-06T11:00:00.000Z");
Minutes periodTime = Minutes.minutesBetween(countSince, countTo);
GetMetricStatisticsRequest metricStatisticsRequest =
underTest.createMetricStatisticsRequest(STREAM, countSince, countTo, periodTime);
given(cloudWatch.getMetricStatistics(metricStatisticsRequest)).willThrow(thrownException);
try {
underTest.getBacklogBytes(STREAM, countSince, countTo);
failBecauseExceptionWasNotThrown(expectedExceptionClass);
} catch (Exception e) {
assertThat(e).isExactlyInstanceOf(expectedExceptionClass);
} finally {
reset(kinesis);
}
}
private AmazonServiceException newAmazonServiceException(ErrorType errorType) {
AmazonServiceException exception = new AmazonServiceException("");
exception.setErrorType(errorType);
return exception;
}
@Test
public void shouldReturnLimitedNumberOfRecords() throws Exception {
final Integer limit = 100;
doAnswer(
(Answer<GetRecordsResult>)
invocation -> {
GetRecordsRequest request = (GetRecordsRequest) invocation.getArguments()[0];
List<Record> records = generateRecords(request.getLimit());
return new GetRecordsResult().withRecords(records).withMillisBehindLatest(1000L);
})
.when(kinesis)
.getRecords(any(GetRecordsRequest.class));
GetKinesisRecordsResult result = underTest.getRecords(SHARD_ITERATOR, STREAM, SHARD_1, limit);
assertThat(result.getRecords().size()).isEqualTo(limit);
}
private List<Record> generateRecords(int num) {
List<Record> records = new ArrayList<>();
for (int i = 0; i < num; i++) {
byte[] value = new byte[1024];
Arrays.fill(value, (byte) i);
records.add(
new Record()
.withSequenceNumber(String.valueOf(i))
.withPartitionKey("key")
.withData(ByteBuffer.wrap(value)));
}
return records;
}
}
| |
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis.encoding;
import org.apache.axis.Constants;
import org.apache.axis.Part;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.message.EnvelopeHandler;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.SAX2EventRecorder;
import org.apache.axis.message.SAXOutputter;
import org.apache.axis.message.SOAPHandler;
import org.apache.axis.utils.Messages;
import org.apache.axis.soap.SOAPConstants;
import org.apache.commons.logging.Log;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.namespace.QName;
import java.io.StringWriter;
import java.util.HashSet;
import java.util.Vector;
/** The Deserializer base class.
*
* @author Glen Daniels (gdaniels@allaire.com)
* Re-architected for JAX-RPC Compliance by
* @author Rich Scheuerle (sche@us.ibm.com)
*/
public class DeserializerImpl extends SOAPHandler
implements javax.xml.rpc.encoding.Deserializer, Deserializer, Callback
{
protected static Log log =
LogFactory.getLog(DeserializerImpl.class.getName());
protected Object value = null;
// invariant member variable to track low-level logging requirements
// we cache this once per instance lifecycle to avoid repeated lookups
// in heavily used code.
private final boolean debugEnabled = log.isDebugEnabled();
// isEnded is set when the endElement is called
protected boolean isEnded = false;
protected Vector targets = null;
protected QName defaultType = null;
protected boolean componentsReadyFlag = false;
/**
* A set of sub-deserializers whose values must complete before our
* value is complete.
*/
private HashSet activeDeserializers = new HashSet();
protected boolean isHref = false;
protected boolean isNil = false; // xsd:nil attribute is set to true
protected String id = null; // Set to the id of the element
public DeserializerImpl() {
}
/**
* JAX-RPC compliant method which returns mechanism type.
*/
public String getMechanismType() {
return Constants.AXIS_SAX;
}
/**
* Get the deserialized value.
* @return Object representing deserialized value or null
*/
public Object getValue()
{
return value;
}
/**
* Set the deserialized value.
* @param value Object representing deserialized value
*/
public void setValue(Object value)
{
this.value = value;
}
/**
* If the deserializer has component values (like ArrayDeserializer)
* this method gets the specific component via the hint.
* The default implementation returns null.
* @return Object representing deserialized value or null
*/
public Object getValue(Object hint)
{
return null;
}
/**
* If the deserializer has component values (like ArrayDeserializer)
* this method sets the specific component via the hint.
* The default implementation does nothing.
* @param hint Object representing deserialized value or null
*/
public void setChildValue(Object value, Object hint) throws SAXException
{
}
public void setValue(Object value, Object hint) throws SAXException {
if (hint instanceof Deserializer) {
// This one's done
activeDeserializers.remove(hint);
// If we're past the end of our XML, and this is the last one,
// our value has been assembled completely.
if (componentsReady()) {
// Got everything we need, call valueComplete()
valueComplete();
}
}
}
/**
* In some circumstances an element may not have
* a type attribute, but a default type qname is known from
* information in the container. For example,
* an element of an array may not have a type= attribute,
* so the default qname is the component type of the array.
* This method is used to communicate the default type information
* to the deserializer.
*/
public void setDefaultType(QName qName) {
defaultType = qName;
}
public QName getDefaultType() {
return defaultType;
}
/**
* For deserializers of non-primitives, the value may not be
* known until later (due to multi-referencing). In such
* cases the deserializer registers Target object(s). When
* the value is known, the set(value) will be invoked for
* each Target registered with the Deserializer. The Target
* object abstracts the function of setting a target with a
* value. See the Target interface for more info.
* @param target
*/
public void registerValueTarget(Target target)
{
if (targets == null) {
targets = new Vector();
}
targets.addElement(target);
}
/**
* Get the Value Targets of the Deserializer.
* @return Vector of Target objects or null
*/
public Vector getValueTargets() {
return targets;
}
/**
* Remove the Value Targets of the Deserializer.
*/
public void removeValueTargets() {
if (targets != null) {
targets = null;
}
}
/**
* Move someone else's targets to our own (see DeserializationContext)
*
* The DeserializationContext only allows one Deserializer to
* wait for a unknown multi-ref'ed value. So to ensure
* that all of the targets are updated, this method is invoked
* to copy the Target objects to the waiting Deserializer.
* @param other is the Deserializer to copy targets from.
*/
public void moveValueTargets(Deserializer other)
{
if ((other == null) || (other.getValueTargets() == null)) {
return;
}
if (targets == null) {
targets = new Vector();
}
targets.addAll(other.getValueTargets());
other.removeValueTargets();
}
/**
* Some deserializers (ArrayDeserializer) require
* all of the component values to be known before the
* value is complete.
* (For the ArrayDeserializer this is important because
* the elements are stored in an ArrayList, and all values
* must be known before the ArrayList is converted into the
* expected array.
*
* This routine is used to indicate when the components are ready.
* The default (true) is useful for most Deserializers.
*/
public boolean componentsReady() {
return (componentsReadyFlag ||
(!isHref && isEnded && activeDeserializers.isEmpty()));
}
/**
* The valueComplete() method is invoked when the
* end tag of the element is read. This results
* in the setting of all registered Targets (see
* registerValueTarget).
* Note that the valueComplete() only processes
* the Targets if componentReady() returns true.
* So if you override componentReady(), then your
* specific Deserializer will need to call valueComplete()
* when your components are ready (See ArrayDeserializer)
*/
public void valueComplete() throws SAXException
{
if (componentsReady()) {
if (targets != null) {
for (int i = 0; i < targets.size(); i++) {
Target target = (Target) targets.get(i);
target.set(value);
if (debugEnabled) {
log.debug(Messages.getMessage("setValueInTarget00",
"" + value, "" + target));
}
}
// Don't need targets any more, so clear them
removeValueTargets();
}
}
}
public void addChildDeserializer(Deserializer dSer) {
// Keep track of our active deserializers. This enables us to figure
// out whether or not we're really done in the case where we get to
// our end tag, but still have open hrefs for members.
if (activeDeserializers != null) {
activeDeserializers.add(dSer);
}
// In concert with the above, we make sure each field deserializer
// lets us know when it's done so we can take it off our list.
dSer.registerValueTarget(new CallbackTarget(this, dSer));
}
/**
* Subclasses may override these
*/
/**
* This method is invoked when an element start tag is encountered.
* DeserializerImpl provides default behavior, which involves the following:
* - directly handling the deserialization of a nill value
* - handling the registration of the id value.
* - handling the registration of a fixup if this element is an href.
* - calling onStartElement to do the actual deserialization if not nill or href cases.
* @param namespace is the namespace of the element
* @param localName is the name of the element
* @param prefix is the prefix of the element
* @param attributes are the attributes on the element...used to get the type
* @param context is the DeserializationContext
*
* Normally a specific Deserializer (FooDeserializer) should extend DeserializerImpl.
* Here is the flow that will occur in such cases:
* 1) DeserializerImpl.startElement(...) will be called and do the id/href/nill stuff.
* 2) If real deserialization needs to take place DeserializerImpl.onStartElement will be
* invoked, which will attempt to install the specific Deserializer (FooDeserializer)
* 3) The FooDeserializer.startElement(...) will be called to do the Foo specific stuff.
* This results in a call to FooDeserializer.onStartElement(...) if startElement was
* not overridden.
* 4) The onChildElement(...) method is called for each child element. Nothing occurs
* if not overridden. The FooDeserializer.onStartChild(...) method should return
* the deserializer for the child element.
* 5) When the end tag is reached, the endElement(..) method is invoked. The default
* behavior is to handle hrefs/ids, call onEndElement and then call the Deserializer
* valueComplete method.
*
* So the methods that you potentially want to override are:
* onStartElement, onStartChild, componentsReady, setValue(object, hint)
* You probably should not override startElement or endElement.
* If you need specific behaviour at the end of the element consider overriding
* onEndElement.
*
* See the pre-existing Deserializers for more information.
*/
public void startElement(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException
{
super.startElement(namespace, localName, prefix, attributes, context);
// If the nil attribute is present and true, set the value to null
// and return since there is nothing to deserialize.
if (context.isNil(attributes)) {
value = null;
isNil = true;
return;
}
SOAPConstants soapConstants = context.getSOAPConstants();
// If this element has an id, then associate the value with the id.
// (Prior to this association, the MessageElement of the element is
// associated with the id. Failure to replace the MessageElement at this
// point will cause an infinite loop during deserialization if the
// current element contains child elements that cause an href back to this id.)
// Also note that that endElement() method is responsible for the final
// association of this id with the completed value.
id = attributes.getValue("id");
if (id != null) {
context.addObjectById(id, value);
if (debugEnabled) {
log.debug(Messages.getMessage("deserInitPutValueDebug00", "" + value, id));
}
context.registerFixup("#" + id, this);
}
String href = attributes.getValue(soapConstants.getAttrHref());
if (href != null) {
isHref = true;
Object ref = context.getObjectByRef(href);
if (debugEnabled) {
log.debug(Messages.getMessage(
"gotForID00",
new String[] {"" + ref, href, (ref == null ? "*null*" : ref.getClass().toString())}));
}
if (ref == null) {
// Nothing yet... register for later interest.
context.registerFixup(href, this);
return;
}
if (ref instanceof MessageElement) {
context.replaceElementHandler(new EnvelopeHandler(this));
SAX2EventRecorder r = context.getRecorder();
context.setRecorder(null);
((MessageElement)ref).publishToHandler((DefaultHandler) context);
context.setRecorder(r);
} else {
if( !href.startsWith("#") && defaultType != null && ref instanceof Part ){
//For attachments this is the end of the road-- invoke deserializer
Deserializer dser = context.getDeserializerForType(defaultType );
if(null != dser){
dser.startElement(namespace, localName,
prefix, attributes,
context);
ref = dser.getValue();
}
}
// If the ref is not a MessageElement, then it must be an
// element that has already been deserialized. Use it directly.
value = ref;
componentsReadyFlag = true;
valueComplete();
}
} else {
isHref = false;
onStartElement(namespace, localName, prefix, attributes,
context);
}
}
/**
* This method is invoked after startElement when the element requires
* deserialization (i.e. the element is not an href and the value is not nil.)
* DeserializerImpl provides default behavior, which simply
* involves obtaining a correct Deserializer and plugging its handler.
* @param namespace is the namespace of the element
* @param localName is the name of the element
* @param prefix is the prefix of the element
* @param attributes are the attributes on the element...used to get the type
* @param context is the DeserializationContext
*/
public void onStartElement(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException
{
// If I'm the base class, try replacing myself with an
// appropriate deserializer gleaned from type info.
if (this.getClass().equals(DeserializerImpl.class)) {
QName type = context.getTypeFromAttributes(namespace,
localName,
attributes);
// If no type is specified, use the defaultType if available.
// xsd:string is used if no type is provided.
if (type == null) {
type = defaultType;
if (type == null) {
type = Constants.XSD_STRING;
}
}
if (debugEnabled) {
log.debug(Messages.getMessage("gotType00", "Deser", "" + type));
}
// We know we're deserializing, but we don't have
// a specific deserializer. So create one using the
// attribute type qname.
if (type != null) {
Deserializer dser = context.getDeserializerForType(type);
if (dser == null) {
dser = context.getDeserializerForClass(null);
}
if (dser != null) {
// Move the value targets to the new deserializer
dser.moveValueTargets(this);
context.replaceElementHandler((SOAPHandler) dser);
// And don't forget to give it the start event...
boolean isRef = context.isProcessingRef();
context.setProcessingRef(true);
dser.startElement(namespace, localName, prefix,
attributes, context);
context.setProcessingRef(isRef);
} else {
throw new SAXException(
Messages.getMessage("noDeser00", "" + type));
}
}
}
}
/**
* onStartChild is called on each child element.
* The default behavior supplied by DeserializationImpl is to do nothing.
* A specific deserializer may perform other tasks. For example a
* BeanDeserializer will construct a deserializer for the indicated
* property and return it.
* @param namespace is the namespace of the child element
* @param localName is the local name of the child element
* @param prefix is the prefix used on the name of the child element
* @param attributes are the attributes of the child element
* @param context is the deserialization context.
* @return is a Deserializer to use to deserialize a child (must be
* a derived class of SOAPHandler) or null if no deserialization should
* be performed.
*/
public SOAPHandler onStartChild(String namespace, String localName,
String prefix, Attributes attributes,
DeserializationContext context)
throws SAXException
{
return null;
}
/**
* endElement is called when the end element tag is reached.
* It handles href/id information for multi-ref processing
* and invokes the valueComplete() method of the deserializer
* which sets the targets with the deserialized value.
* @param namespace is the namespace of the child element
* @param localName is the local name of the child element
* @param context is the deserialization context
*/
public final void endElement(String namespace, String localName,
DeserializationContext context)
throws SAXException
{
super.endElement(namespace, localName, context);
isEnded = true;
if (!isHref) {
onEndElement(namespace, localName, context);
}
// Time to call valueComplete to copy the value to
// the targets. First a call is made to componentsReady
// to ensure that all components are ready.
if (componentsReady()) {
valueComplete();
}
// If this element has an id, then associate the value with the id.
// Subsequent hrefs to the id will obtain the value directly.
// This is necessary for proper multi-reference deserialization.
if (id != null) {
context.addObjectById(id, value);
if (debugEnabled) {
log.debug(Messages.getMessage("deserPutValueDebug00", "" + value, id));
}
}
}
/**
* onEndElement is called by endElement. It is not called
* if the element has an href.
* @param namespace is the namespace of the child element
* @param localName is the local name of the child element
* @param context is the deserialization context
*/
public void onEndElement(String namespace, String localName,
DeserializationContext context)
throws SAXException
{
// If we only have SAX events, but someone really wanted a
// value, try sending them the contents of this element
// as a String...
// ??? Is this the right thing to do here?
if (this.getClass().equals(DeserializerImpl.class) &&
targets != null &&
!targets.isEmpty()) {
StringWriter writer = new StringWriter();
SerializationContext serContext =
new SerializationContext(writer,
context.getMessageContext());
serContext.setSendDecl(false);
SAXOutputter so = null;
so = new SAXOutputter(serContext);
context.getCurElement().publishContents(so);
if (!isNil) {
value = writer.getBuffer().toString();
}
}
}
}
| |
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2020 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.runtime;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import com.google.appinventor.components.runtime.errors.YailRuntimeError;
import com.google.appinventor.components.runtime.util.AnimationUtil;
import com.google.appinventor.components.runtime.util.ErrorMessages;
import com.google.appinventor.components.runtime.util.NougatUtil;
import com.google.appinventor.components.runtime.util.YailList;
import java.io.File;
/**
* A component that can launch an activity using the StartActivity method.
*
* Activities that can be launched include:
*
* * Starting another App Inventor for Android app. To do so, first find out the class of the other
* application by downloading the source code and using a file explorer or unzip utility to find
* a file named "youngandroidproject/project.properties". The first line of the file will start
* with "main=" and be followed by the class name; for example,
* `main=com.gmail.Bitdiddle.Ben.HelloPurr.Screen1`. (The first components indicate that it was
* created by Ben.Bitdiddle\@gmail.com.) To make your `ActivityStarter` launch this application,
* set the following properties:
* * `ActivityPackage` to the class name, dropping the last component (for example,
* `com.gmail.Bitdiddle.Ben.HelloPurr`)
* * `ActivityClass` to the entire class name (for example,
* `com.gmail.Bitdiddle.Ben.HelloPurr.Screen1`)
* * Starting the camera application by setting the following properties:
* * `Action`: `android.intent.action.MAIN`
* * `ActivityPackage`: `com.android.camera`
* * `ActivityClass`: `com.android.camera.Camera`
* * Performing web search. Assuming the term you want to search for is "vampire" (feel free to substitute your own choice), set the properties to:
* * `Action`: `android.intent.action.WEB_SEARCH`
* * `ExtraKey`: `query`
* * `ExtraValue`: `vampire`
* * `ActivityPackage`: `com.google.android.providers.enhancedgooglesearch`
* * `ActivityClass`: `com.google.android.providers.enhancedgooglesearch.Launcher`
* * Opening a browser to a specified web page. Assuming the page you want to go to is "www.facebook.com" (feel free to substitute your own choice), set the properties to:
* * `Action`: `android.intent.action.VIEW`
* * `DataUri`: `http://www.facebook.com`
*
* @author markf@google.com (Mark Friedman)
*/
@DesignerComponent(version = YaVersion.ACTIVITYSTARTER_COMPONENT_VERSION,
designerHelpDescription = "A component that can launch an activity " +
"using the <code>StartActivity</code> method." +
"<p>Activities that can be launched include: <ul> \n" +
"<li> starting other App Inventor for Android apps </li> \n" +
"<li> starting the camera application </li> \n" +
"<li> performing web search </li> \n" +
"<li> opening a browser to a specified web page</li> \n" +
"<li> opening the map application to a specified location</li></ul> \n" +
"You can also launch activities that return text data. See the " +
"documentation on using the Activity Starter for examples.</p>",
// TODO(user): Add more information about bringing up maps when
// the issues with html quoting (bug 2386151) are fixed.
description = "A component that can launch an activity using " +
"the <code>StartActivity</code> method. \n" +
"<p>Activities that can be launched include:<ul> " +
"<li> Starting another App Inventor for Android app. \n To do so, first " +
" find out the <em>class</em> of the other application by " +
" downloading the source code and using a file explorer or unzip " +
" utility to find a file named " +
" \"youngandroidproject/project.properties\". \n The first line of " +
" the file will start with \"main=\" and be followed by the class " +
" name; for example, " +
" <code>main=com.gmail.Bitdiddle.Ben.HelloPurr.Screen1</code>. " +
" (The first components indicate that it was created by " +
" Ben.Bitdiddle@gmail.com.) \n To make your " +
" <code>ActivityStarter</code> launch this application, set the " +
" following properties: <ul>\n " +
" <li> <code>ActivityPackage</code> to the class name, dropping the " +
" last component (for example, " +
" <code>com.gmail.Bitdiddle.Ben.HelloPurr</code>)</li>\n " +
" <li> <code>ActivityClass</code> to the entire class name (for " +
" example, " +
" <code>com.gmail.Bitdiddle.Ben.HelloPurr.Screen1</code>)</li> " +
" </ul></li> \n" +
"<li> Starting the camera application by setting the following " +
" properties:<ul> \n" +
" <li> <code>Action: android.intent.action.MAIN</code> </li> \n" +
" <li> <code>ActivityPackage: com.android.camera</code> </li> \n" +
" <li> <code>ActivityClass: com.android.camera.Camera</code></li>\n " +
" </ul></li>\n" +
"<li> Performing web search. Assuming the term you want to search " +
" for is \"vampire\" (feel free to substitute your own choice), \n" +
" set the properties to:\n<ul><code>" +
" <li>Action: android.intent.action.WEB_SEARCH</li> " +
" <li>ExtraKey: query</li> " +
" <li>ExtraValue: vampire</li> " +
" <li>ActivityPackage: com.google.android.providers.enhancedgooglesearch</li>" +
" <li>ActivityClass: com.google.android.providers.enhancedgooglesearch.Launcher</li> " +
" </code></ul></li> \n" +
"<li> Opening a browser to a specified web page. Assuming the page you " +
" want to go to is \"www.facebook.com\" (feel free to substitute " +
" your own choice), set the properties to:\n<ul><code> " +
" <li>Action: android.intent.action.VIEW</li> " +
" <li>DataUri: http://www.facebook.com</li> </code> </ul> </li> " +
"</ul></p>",
category = ComponentCategory.CONNECTIVITY,
nonVisible = true,
iconName = "images/activityStarter.png")
@SimpleObject
public class ActivityStarter extends AndroidNonvisibleComponent
implements ActivityResultListener, Component, Deleteable {
private String action;
private String dataUri;
private String dataType;
private String activityPackage;
private String activityClass;
private String extraKey;
private String extraValue;
private String resultName;
private Intent resultIntent;
private String result;
private int requestCode;
private YailList extras;
private final ComponentContainer container;
private static final String LOG_TAG = "ActivityStarter";
/**
* Creates a new ActivityStarter component.
*
* @param container container, kept for access to form and context
*/
public ActivityStarter(ComponentContainer container) {
super(container.$form());
// Save the container for later
this.container = container;
result = "";
Action(Intent.ACTION_MAIN);
ActivityPackage("");
ActivityClass("");
DataUri("");
DataType("");
ExtraKey("");
ExtraValue("");
Extras(new YailList());
ResultName("");
}
/**
* Returns the action that will be used to start the activity.
*/
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public String Action() {
return action;
}
/**
* Specifies the action that will be used to start the activity.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void Action(String action) {
this.action = action.trim();
}
// TODO(lizlooney) - currently we support just one extra name/value pair that will be passed to
// the activity. The user specifies the ExtraKey and ExtraValue properties.
// We should allow more extra name/value pairs, but we'd need a different interface with regard
// to properties and functions.
// In the documentation for Intent, they use the term "name", not "key", and we might want to use
// the term "name", also.
// There are backwards compatibility issues with removing the ExtraKey and ExtraValue properties.
// Also, while extra names are always Strings, the values can be other types. We'd need to know
// the correct type of the value in order to call the appropriate Intent.putExtra method.
// Adding multiple functions like PutStringExtra, PutStringArrayExtra, PutCharExtra,
// PutCharArrayExtra, PutBooleanExtra, PutBooleanArrayExtra, PutByteExtra, PutByteArrayExtra,
// PutShortExtra, PutShortArrayExtra, PutIntExtra, PutIntArrayExtra, PutLongExtra,
// PutLongArrayExtra, PutFloatExtra, PutFloatArrayExtra, PutDoubleExtra, PutDoubleArrayExtra,
// etc, seems like a bad idea.
/**
* Returns the extra key that will be passed to the activity.
* Obsolete. Should use Extras instead
*/
@SimpleProperty(
description = "Returns the extra key that will be passed to the activity.\n" +
"DEPRECATED: New code should use Extras property instead.",
category = PropertyCategory.BEHAVIOR)
public String ExtraKey() {
return extraKey;
}
/**
* Specifies the extra key that will be passed to the activity.
* Obsolete. Should use Extras instead
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void ExtraKey(String extraKey) {
this.extraKey = extraKey.trim();
}
/**
* Returns the extra value that will be passed to the activity.
* Obsolete. Should use Extras instead
*/
@SimpleProperty(
description = "Returns the extra value that will be passed to the activity.\n" +
"DEPRECATED: New code should use Extras property instead.",
category = PropertyCategory.BEHAVIOR)
public String ExtraValue() {
return extraValue;
}
/**
* Specifies the extra value that will be passed to the activity.
* Obsolete. Should use Extras instead
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void ExtraValue(String extraValue) {
this.extraValue = extraValue.trim();
}
// TODO(lizlooney) - currently we support retrieving just one string extra result from the
// activity. The user specifies the ResultName property and, then after the activity finishes,
// the string extra result corresponding to ResultName is passed as the result parameter to the
// AfterActivity event and is also available from the Result property getter.
// We should allow access to more extra results, but we'd need a different interface with regard
// to properties, functions, and events parameters.
// There are backwards compatibility issues with removing the AfterActivity event's result
// parameter and the Result property.
// Also, while extra names are always Strings, the values can be other types. We'd need to know
// the correct type of the value in order to call the appropriate Intent.get...Extra method.
// Adding multiple functions like GetStringExtra, GetStringArrayExtra, GetCharExtra,
// GetCharArrayExtra, GetBooleanExtra, GetBooleanArrayExtra, GetByteExtra, GetByteArrayExtra,
// GetShortExtra, GetShortArrayExtra, GetIntExtra, GetIntArrayExtra, GetLongExtra,
// GetLongArrayExtra, GetFloatExtra, GetFloatArrayExtra, GetDoubleExtra, GetDoubleArrayExtra,
// etc, seems like a bad idea.
/**
* Returns the name that will be used to retrieve a result from the activity.
*/
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public String ResultName() {
return resultName;
}
/**
* Specifies the name that will be used to retrieve a result from the
* activity.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void ResultName(String resultName) {
this.resultName = resultName.trim();
}
/**
* Returns the result from the activity.
*/
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public String Result() {
return result;
}
/**
* Returns the data URI that will be used to start the activity.
*/
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public String DataUri() {
return dataUri;
}
/**
* Specifies the data URI that will be used to start the activity.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void DataUri(String dataUri) {
this.dataUri = dataUri.trim();
}
/**
* Returns the MIME type to pass to the activity.
*/
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public String DataType() {
return dataType;
}
/**
* Specifies the MIME type to pass to the activity.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void DataType(String dataType) {
this.dataType = dataType.trim();
}
/**
* Returns the package part of the specific component that will be started.
*/
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public String ActivityPackage() {
return activityPackage;
}
/**
* Specifies the package part of the specific component that will be started.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void ActivityPackage(String activityPackage) {
this.activityPackage = activityPackage.trim();
}
/**
* Returns the class part of the specific component that will be started.
*/
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public String ActivityClass() {
return activityClass;
}
/**
* Specifies the class part of the specific component that will be started.
*/
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void ActivityClass(String activityClass) {
this.activityClass = activityClass.trim();
}
/**
* Event raised after this `ActivityStarter` returns.
* @param result The result returned by the activity
*/
@SimpleEvent(description = "Event raised after this ActivityStarter returns.")
public void AfterActivity(String result) {
EventDispatcher.dispatchEvent(this, "AfterActivity", result);
}
/**
* Event raised if this `ActivityStarter returns because the activity was canceled.
*/
@SimpleEvent(description =
"Event raised if this ActivityStarter returns because the activity was canceled.")
public void ActivityCanceled() {
EventDispatcher.dispatchEvent(this, "ActivityCanceled");
}
/**
* Returns the MIME type from the activity.
*/
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public String ResultType() {
if (resultIntent != null) {
String resultType = resultIntent.getType();
if (resultType != null) {
return resultType;
}
}
return "";
}
/**
* Returns the URI from the activity.
*/
@SimpleProperty(
category = PropertyCategory.BEHAVIOR)
public String ResultUri() {
if (resultIntent != null) {
String resultUri = resultIntent.getDataString();
if (resultUri != null) {
return resultUri;
}
}
return "";
}
/**
* Specifies the list of key-value pairs that will be passed as extra data to the activity.
*/
@SimpleProperty
public void Extras(YailList pairs) {
for (Object pair : pairs.toArray()) {
boolean isYailList = pair instanceof YailList;
boolean isPair = isYailList ? ((YailList) pair).size() == 2 : false;
if (!isYailList || !isPair) {
throw new YailRuntimeError("Argument to Extras should be a list of pairs",
"ActivityStarter Error");
}
}
extras = pairs;
}
/**
* Returns the list of key-value pairs that will be passed as extra data to the activity.
*/
@SimpleProperty
public YailList Extras() {
return extras;
}
/**
* Returns the name of the activity that corresponds to this `ActivityStarter`,
* or an empty string if no corresponding activity can be found.
*/
@SimpleFunction(description = "Returns the name of the activity that corresponds to this " +
"ActivityStarter, or an empty string if no corresponding activity can be found.")
public String ResolveActivity() {
Intent intent = buildActivityIntent();
PackageManager pm = container.$context().getPackageManager();
ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
if (resolveInfo != null && resolveInfo.activityInfo != null) {
return resolveInfo.activityInfo.name;
}
return "";
}
/**
* Start the activity corresponding to this `ActivityStarter`.
*/
@SimpleFunction(description = "Start the activity corresponding to this ActivityStarter.")
public void StartActivity() {
resultIntent = null;
result = "";
Intent intent = buildActivityIntent();
if (requestCode == 0) {
// First time, we need to register this as an ActivityResultListener with the Form.
// The Form's onActivityResult method will be called when the activity returns. If we
// register with the Form and then use the requestCode when we start an activity, the Form
// will call our resultReturned method.
requestCode = form.registerForActivityResult(this);
}
if (intent == null) {
form.dispatchErrorOccurredEvent(this, "StartActivity",
ErrorMessages.ERROR_ACTIVITY_STARTER_NO_ACTION_INFO);
} else {
try {
container.$context().startActivityForResult(intent, requestCode);
String openAnim = container.$form().getOpenAnimType();
AnimationUtil.ApplyOpenScreenAnimation(container.$context(), openAnim);
} catch (ActivityNotFoundException e) {
form.dispatchErrorOccurredEvent(this, "StartActivity",
ErrorMessages.ERROR_ACTIVITY_STARTER_NO_CORRESPONDING_ACTIVITY);
}
}
}
private Intent buildActivityIntent() {
Uri uri = (dataUri.length() != 0) ? Uri.parse(dataUri) : null;
Intent intent = new Intent(action);
if (uri != null && dataUri.toLowerCase().startsWith("file://") ) {
Log.d(LOG_TAG, "Using file://");
File file = new File(uri.getPath());
if (file.isFile()) {
Log.d(LOG_TAG, "It's a file");
uri = NougatUtil.getPackageUri(form, file);
intent = new Intent(action);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Log.d(LOG_TAG, "added permissions"); // adb log shows this gets printed
}
}
if (TextUtils.isEmpty(Action())) {
return null;
}
if (dataType.length() != 0) {
if (uri != null) {
intent.setDataAndType(uri, dataType);
} else {
intent.setType(dataType);
}
} else {
intent.setData(uri);
}
if (activityPackage.length() != 0 || activityClass.length() != 0) {
ComponentName component = new ComponentName(activityPackage, activityClass);
intent.setComponent(component);
} else if (Action().equals("android.intent.action.MAIN")) {
return null;
}
if (extraKey.length() != 0 && extraValue.length() != 0) {
Log.i(LOG_TAG, "Adding extra, key = " + extraKey + " value = " + extraValue);
intent.putExtra(extraKey, extraValue);
}
// If the extra value is a string, put it to the intent. If the extra value is a list
// of strings, convert it to a java list and put that to the intent.
for (Object extra : extras.toArray()) {
YailList castExtra = (YailList) extra;
String key = castExtra.getString(0);
Object value = castExtra.getObject(1);
Log.i(LOG_TAG, "Adding extra, key = " + key + " value = " + value);
if ((key.length() != 0)) {
if (value instanceof YailList) {
Log.i(LOG_TAG, "Adding extra list, key = " + key + " value = " + value);
intent.putExtra(key, ((YailList) value).toStringArray());
}
else {
String stringValue = castExtra.getString(1);
Log.i(LOG_TAG, "Adding extra string, key = " + key + " value = " + stringValue);
intent.putExtra(key, stringValue);
}
};
};
return intent;
}
@Override
public void resultReturned(int requestCode, int resultCode, Intent data) {
if (requestCode == this.requestCode) {
Log.i(LOG_TAG, "resultReturned - resultCode = " + resultCode);
if (resultCode == Activity.RESULT_OK) {
resultIntent = data;
if (resultName.length() != 0 && resultIntent != null &&
resultIntent.hasExtra(resultName)) {
result = resultIntent.getStringExtra(resultName);
} else {
result = "";
}
// call user's AfterActivity event handler
AfterActivity(result);
} else if (resultCode == Activity.RESULT_CANCELED) {
ActivityCanceled();
}
}
}
@SimpleEvent(description = "The ActivityError event is no longer used. " +
"Please use the Screen.ErrorOccurred event instead.",
userVisible = false)
public void ActivityError(String message) {
}
// Deleteable implementation
@Override
public void onDelete() {
form.unregisterForActivityResult(this);
}
}
| |
/*
* 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.hyracks.algebricks.core.algebra.expressions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.commons.lang3.mutable.MutableObject;
import org.apache.hyracks.algebricks.core.algebra.base.EquivalenceClass;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalExpressionTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.functions.AlgebricksBuiltinFunctions;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.core.algebra.functions.IFunctionInfo;
import org.apache.hyracks.algebricks.core.algebra.properties.FunctionalDependency;
public abstract class AbstractFunctionCallExpression extends AbstractLogicalExpression {
public enum FunctionKind {
SCALAR,
STATEFUL,
AGGREGATE,
UNNEST
}
protected IFunctionInfo finfo;
final private List<Mutable<ILogicalExpression>> arguments;
private Object[] opaqueParameters;
private final FunctionKind kind;
private final Map<Object, IExpressionAnnotation> annotationMap = new HashMap<Object, IExpressionAnnotation>();
public AbstractFunctionCallExpression(FunctionKind kind, IFunctionInfo finfo,
List<Mutable<ILogicalExpression>> arguments) {
this.kind = kind;
this.finfo = finfo;
this.arguments = arguments;
}
public AbstractFunctionCallExpression(FunctionKind kind, IFunctionInfo finfo) {
this.kind = kind;
this.finfo = finfo;
this.arguments = new ArrayList<Mutable<ILogicalExpression>>();
}
public AbstractFunctionCallExpression(FunctionKind kind, IFunctionInfo finfo,
Mutable<ILogicalExpression>... expressions) {
this(kind, finfo);
for (Mutable<ILogicalExpression> e : expressions) {
this.arguments.add(e);
}
}
public void setOpaqueParameters(Object[] opaqueParameters) {
this.opaqueParameters = opaqueParameters;
}
public Object[] getOpaqueParameters() {
return opaqueParameters;
}
public FunctionKind getKind() {
return kind;
}
protected List<Mutable<ILogicalExpression>> cloneArguments() {
List<Mutable<ILogicalExpression>> clonedArgs = new ArrayList<Mutable<ILogicalExpression>>(arguments.size());
for (Mutable<ILogicalExpression> e : arguments) {
ILogicalExpression e2 = ((AbstractLogicalExpression) e.getValue()).cloneExpression();
clonedArgs.add(new MutableObject<ILogicalExpression>(e2));
}
return clonedArgs;
}
public FunctionIdentifier getFunctionIdentifier() {
return finfo.getFunctionIdentifier();
}
public IFunctionInfo getFunctionInfo() {
return finfo;
}
public void setFunctionInfo(IFunctionInfo finfo) {
this.finfo = finfo;
}
public List<Mutable<ILogicalExpression>> getArguments() {
return arguments;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("function-call: " + finfo.getFunctionIdentifier() + ", Args:[");
// + arguments;
boolean first = true;
for (Mutable<ILogicalExpression> ref : arguments) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(ref.getValue());
}
sb.append("]");
return sb.toString();
}
@Override
public LogicalExpressionTag getExpressionTag() {
return LogicalExpressionTag.FUNCTION_CALL;
}
@Override
public void getUsedVariables(Collection<LogicalVariable> vars) {
for (Mutable<ILogicalExpression> arg : arguments) {
arg.getValue().getUsedVariables(vars);
}
}
@Override
public void substituteVar(LogicalVariable v1, LogicalVariable v2) {
for (Mutable<ILogicalExpression> arg : arguments) {
arg.getValue().substituteVar(v1, v2);
}
}
@Override
public void getConstraintsAndEquivClasses(Collection<FunctionalDependency> fds,
Map<LogicalVariable, EquivalenceClass> equivClasses) {
FunctionIdentifier funId = getFunctionIdentifier();
if (funId.equals(AlgebricksBuiltinFunctions.AND)) {
for (Mutable<ILogicalExpression> a : arguments) {
a.getValue().getConstraintsAndEquivClasses(fds, equivClasses);
}
} else if (funId.equals(AlgebricksBuiltinFunctions.EQ)) {
ILogicalExpression opLeft = arguments.get(0).getValue();
ILogicalExpression opRight = arguments.get(1).getValue();
if (opLeft.getExpressionTag() == LogicalExpressionTag.CONSTANT
&& opRight.getExpressionTag() == LogicalExpressionTag.VARIABLE) {
ConstantExpression op1 = (ConstantExpression) opLeft;
VariableReferenceExpression op2 = (VariableReferenceExpression) opRight;
getFDsAndEquivClassesForEqWithConstant(op1, op2, fds, equivClasses);
} else if (opLeft.getExpressionTag() == LogicalExpressionTag.VARIABLE
&& opRight.getExpressionTag() == LogicalExpressionTag.VARIABLE) {
VariableReferenceExpression op1 = (VariableReferenceExpression) opLeft;
VariableReferenceExpression op2 = (VariableReferenceExpression) opRight;
getFDsAndEquivClassesForColumnEq(op1, op2, fds, equivClasses);
}
}
}
@Override
public void getConstraintsForOuterJoin(Collection<FunctionalDependency> fds,
Collection<LogicalVariable> outerVars) {
FunctionIdentifier funId = getFunctionIdentifier();
if (funId.equals(AlgebricksBuiltinFunctions.AND)) {
for (Mutable<ILogicalExpression> a : arguments) {
a.getValue().getConstraintsForOuterJoin(fds, outerVars);
}
} else if (funId.equals(AlgebricksBuiltinFunctions.EQ)) {
ILogicalExpression opLeft = arguments.get(0).getValue();
ILogicalExpression opRight = arguments.get(1).getValue();
if (opLeft.getExpressionTag() == LogicalExpressionTag.VARIABLE
&& opRight.getExpressionTag() == LogicalExpressionTag.VARIABLE) {
LogicalVariable var1 = ((VariableReferenceExpression) opLeft).getVariableReference();
LogicalVariable var2 = ((VariableReferenceExpression) opRight).getVariableReference();
if (outerVars.contains(var1)) {
addFD(fds, var1, var2);
}
if (outerVars.contains(var2)) {
addFD(fds, var2, var1);
}
}
}
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AbstractFunctionCallExpression)) {
return false;
} else {
AbstractFunctionCallExpression fce = (AbstractFunctionCallExpression) obj;
boolean equal = getFunctionIdentifier().equals(fce.getFunctionIdentifier());
if (!equal) {
return false;
}
for (int i = 0; i < arguments.size(); i++) {
ILogicalExpression argument = arguments.get(i).getValue();
ILogicalExpression fceArgument = fce.getArguments().get(i).getValue();
if (!argument.equals(fceArgument)) {
return false;
}
}
if (opaqueParameters != null) {
if (opaqueParameters.length != fce.opaqueParameters.length) {
return false;
}
for (int i = 0; i < opaqueParameters.length; i++) {
Object opaqueParameter = opaqueParameters[i];
Object fceOpaqueParameter = fce.opaqueParameters[i];
if (!opaqueParameter.equals(fceOpaqueParameter)) {
return false;
}
}
}
return true;
}
}
@Override
public int hashCode() {
int h = finfo.hashCode();
for (Mutable<ILogicalExpression> e : arguments) {
h = h * 41 + e.getValue().hashCode();
}
if (opaqueParameters != null) {
for (int i = 0; i < opaqueParameters.length; i++) {
h = h * 31 + opaqueParameters[i].hashCode();
}
}
return h;
}
@Override
public boolean splitIntoConjuncts(List<Mutable<ILogicalExpression>> conjs) {
if (!getFunctionIdentifier().equals(AlgebricksBuiltinFunctions.AND) || arguments.size() <= 1) {
return false;
} else {
conjs.addAll(arguments);
return true;
}
}
public Map<Object, IExpressionAnnotation> getAnnotations() {
return annotationMap;
}
protected Map<Object, IExpressionAnnotation> cloneAnnotations() {
Map<Object, IExpressionAnnotation> m = new HashMap<Object, IExpressionAnnotation>();
for (Object k : annotationMap.keySet()) {
IExpressionAnnotation annot2 = annotationMap.get(k).copy();
m.put(k, annot2);
}
return m;
}
private final static void addFD(Collection<FunctionalDependency> fds, LogicalVariable var1, LogicalVariable var2) {
LinkedList<LogicalVariable> set1 = new LinkedList<LogicalVariable>();
set1.add(var1);
LinkedList<LogicalVariable> set2 = new LinkedList<LogicalVariable>();
set2.add(var2);
FunctionalDependency fd1 = new FunctionalDependency(set1, set2);
fds.add(fd1);
}
private final static void getFDsAndEquivClassesForEqWithConstant(ConstantExpression c,
VariableReferenceExpression v, Collection<FunctionalDependency> fds,
Map<LogicalVariable, EquivalenceClass> equivClasses) {
LogicalVariable var = v.getVariableReference();
LinkedList<LogicalVariable> head = new LinkedList<LogicalVariable>();
// empty set in the head
LinkedList<LogicalVariable> tail = new LinkedList<LogicalVariable>();
tail.add(var);
FunctionalDependency fd = new FunctionalDependency(head, tail);
fds.add(fd);
EquivalenceClass ec = equivClasses.get(var);
if (ec == null) {
LinkedList<LogicalVariable> members = new LinkedList<LogicalVariable>();
members.add(var);
EquivalenceClass eclass = new EquivalenceClass(members, c);
equivClasses.put(var, eclass);
} else {
if (ec.representativeIsConst()) {
ILogicalExpression c1 = ec.getConstRepresentative();
if (!c1.equals(c)) {
// here I could also rewrite to FALSE
return;
}
}
ec.setConstRepresentative(c);
}
}
/*
* Obs.: mgmt. of equiv. classes should use a more efficient data
* structure,if we are to implem. cost-bazed optim.
*/
private final static void getFDsAndEquivClassesForColumnEq(VariableReferenceExpression v1,
VariableReferenceExpression v2, Collection<FunctionalDependency> fds,
Map<LogicalVariable, EquivalenceClass> equivClasses) {
LogicalVariable var1 = v1.getVariableReference();
LogicalVariable var2 = v2.getVariableReference();
LinkedList<LogicalVariable> set1 = new LinkedList<LogicalVariable>();
set1.add(var1);
LinkedList<LogicalVariable> set2 = new LinkedList<LogicalVariable>();
set2.add(var2);
FunctionalDependency fd1 = new FunctionalDependency(set1, set2);
FunctionalDependency fd2 = new FunctionalDependency(set2, set1);
fds.add(fd1);
fds.add(fd2);
EquivalenceClass ec1 = equivClasses.get(var1);
EquivalenceClass ec2 = equivClasses.get(var2);
if (ec1 == null && ec2 == null) {
LinkedList<LogicalVariable> members = new LinkedList<LogicalVariable>();
members.add(var1);
members.add(var2);
EquivalenceClass ec = new EquivalenceClass(members, var1);
equivClasses.put(var1, ec);
equivClasses.put(var2, ec);
} else if (ec1 == null && ec2 != null) {
ec2.addMember(var1);
equivClasses.put(var1, ec2);
} else if (ec2 == null && ec1 != null) {
ec1.addMember(var2);
equivClasses.put(var2, ec1);
} else {
ec1.merge(ec2);
for (LogicalVariable w : equivClasses.keySet()) {
if (ec2.getMembers().contains(w)) {
equivClasses.put(w, ec1);
}
}
}
}
@Override
public boolean isFunctional() {
if (!finfo.isFunctional()) {
return false;
}
for (Mutable<ILogicalExpression> e : arguments) {
if (!e.getValue().isFunctional()) {
return false;
}
}
return true;
}
}
| |
package de.berger.gomezbutton;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import com.flaviofaria.kenburnsview.KenBurnsView;
import com.flaviofaria.kenburnsview.RandomTransitionGenerator;
import com.flaviofaria.kenburnsview.Transition;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.iid.FirebaseInstanceId;
import com.hanks.htextview.HTextView;
import com.hanks.htextview.HTextViewType;
import de.psdev.licensesdialog.LicensesDialog;
/**
* @author berger
*
* MainActivity Mario Gomez Button.
*/
public class MainActivity extends AppCompatActivity {
public static final String TAG = "GOMEZBUTTON";
private HTextView gomezTextView;
private Button playButton;
private MediaPlayer mp2;
private FirebaseAnalytics mFirebaseAnalytics;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("");
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mp2 = MediaPlayer.create(this, R.raw.mariogomez);
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
playButton.setText("Play");
}
});
// Obtain the FirebaseAnalytics instance.
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
//FMS Token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d("FirebaseIDService", "Refreshed token: " + refreshedToken);
initTextView();
initImageView();
initPlayBtn();
//Android Wear Intent
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
boolean startedFromWear = bundle.getBoolean("wear", false);
if (startedFromWear)
playButton.performClick();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//License Dialog
int id = item.getItemId();
if (id == R.id.about_menuitem) {
new LicensesDialog.Builder(this)
.setNotices(R.raw.notices)
.setIncludeOwnLicense(true)
.build()
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
mp2.stop();
super.onBackPressed();
this.finish();
}
/**
* TextView initialisieren.
*/
private void initTextView() {
gomezTextView = (HTextView) findViewById(R.id.text);
// be sure to set custom typeface before setting the animate type, otherwise the font may not be updated.
gomezTextView.setAnimateType(HTextViewType.LINE);
gomezTextView.animateText("Mario Gomez Button"); // animate
}
/**
* ImageView initialisieren.
*/
private void initImageView() {
KenBurnsView gomezImageView = (KenBurnsView) findViewById(R.id.imageView);
RandomTransitionGenerator generator = new RandomTransitionGenerator(6000, new AccelerateDecelerateInterpolator());
gomezImageView.setTransitionGenerator(generator);
gomezImageView.setTransitionListener(new KenBurnsView.TransitionListener() {
@Override
public void onTransitionStart(Transition transition) {
//..
}
@Override
public void onTransitionEnd(Transition transition) {
//..
}
});
gomezImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("https://shop.vfb.de/heimtrikot-17-18-2950-08.html"));
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e(TAG, e.getMessage());
}
}
});
}
/**
* Play Button initialisieren
*/
private void initPlayBtn() {
playButton = (Button) this.findViewById(R.id.play_button);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "play");
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "playBtn");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "button");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
// If the music is playing
if (mp2.isPlaying()) {
// Pause the music player
mp2.pause();
playButton.setText("Play");
}
// If it's not playing
else {
// Resume the music player
mp2.start();
playButton.setText("Pause");
gomezTextView.animateText("Mario Gomez Button"); // animate
}
}
});
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| |
package xyz.thepathfinder.chimneyswap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PostChimneyActivity extends AppCompatActivity {
private static final int READ_REQUEST_CODE = 4254; // just some random number
private static final String TAG = "PostChimneyActivity";
private Chimney tradedChimney;
private Bitmap chimneyImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_chimney);
ParcelableChimney parcelableChimney = getIntent().getParcelableExtra(TradeChimneyActivity.TRADED_CHIMNEY);
this.tradedChimney = parcelableChimney.getChimney();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if(requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if(resultData != null) {
Uri uri = resultData.getData();
getBitmapFromUri(uri);
}
}
}
private void getBitmapFromUri(Uri uri) {
try {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
this.chimneyImage = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
ImageView imageView = (ImageView) this.findViewById(R.id.chimney_icon);
imageView.setImageBitmap(Bitmap.createScaledBitmap(this.chimneyImage, 200, 200, false));
Button button = (Button) this.findViewById(R.id.add_chimney_image);
button.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
}
private void postChimney(final String name, final String address, Bitmap image) {
String url = TradeChimneyActivity.CHIMNEY_SWAP_URL + "/chimney";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();
final String encodeImage = Base64.encodeToString(imageBytes, Base64.URL_SAFE);
JSONObject json = new JSONObject();
JSONObject imageJson = new JSONObject();
try {
imageJson.put("file_data", encodeImage);
json.put("image", imageJson);
json.put("name", name);
json.put("address", address);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request = new EasyJsonObjectRequest(Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
getChimneyList();
}
});
Volley.newRequestQueue(this).add(request);
}
public void onClickPickImage(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
public void onClickPostChimney(View view) {
ImageView imageView = (ImageView) this.findViewById(R.id.chimney_icon);
Bitmap image = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
EditText nameEditText = (EditText) this.findViewById(R.id.chimney_name_edit_text);
EditText addressEditText = (EditText) this.findViewById(R.id.chimney_address_edit_text);
postChimney(nameEditText.getText().toString(), addressEditText.getText().toString(), image);
}
public void getChimneyList() {
String url = TradeChimneyActivity.CHIMNEY_SWAP_URL + "/chimneys";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JsonArray json = new JsonParser().parse(response).getAsJsonArray();
swapChimneys(json);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
public void swapChimneys(JsonArray jsonArray) {
List<Chimney> chimneyList = new ArrayList<Chimney>();
for(JsonElement chimney : jsonArray) {
chimneyList.add(new Chimney(chimney.getAsJsonObject()));
}
int maxId = -1;
int maxIndex = -1;
for (int k = 0; k < chimneyList.size(); k++) {
Chimney chimney = chimneyList.get(k);
if (chimney.getId() > maxId) {
maxId = chimney.getId();
maxIndex = k;
}
}
Chimney myChimney = chimneyList.get(maxIndex);
SharedPreferences preferences = this.getSharedPreferences(MainActivity.PREFERENCES_FILE, Context.MODE_PRIVATE);
String idToken = preferences.getString(MainActivity.ID_TOKEN, "");
SwapChimneysRequest chimneysRequest = new SwapChimneysRequest(getString(R.string.pathfinder_app_id), idToken, this.tradedChimney, myChimney);
chimneysRequest.swap();
this.deleteChimney(this.tradedChimney.getId());
this.deleteChimney(myChimney.getId());
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, SelectionActivity.class);
this.startActivity(intent);
}
private void deleteChimney(int id) {
String url = TradeChimneyActivity.CHIMNEY_SWAP_URL + "/chimney?id=" + id;
StringRequest stringRequest = new StringRequest(Request.Method.DELETE, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
}
| |
package liquibase.servicelocator;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.jar.Manifest;
import liquibase.exception.ServiceNotFoundException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.logging.Logger;
import liquibase.logging.core.DefaultLogger;
import liquibase.resource.ClassLoaderResourceAccessor;
import liquibase.resource.ResourceAccessor;
import liquibase.util.StringUtils;
public class ServiceLocator {
private static ServiceLocator instance;
static {
try {
Class<?> scanner = Class.forName("Liquibase.ServiceLocator.ClrServiceLocator, Liquibase");
instance = (ServiceLocator) scanner.newInstance();
} catch (Exception e) {
instance = new ServiceLocator();
}
}
private ResourceAccessor resourceAccessor;
private Map<Class, List<Class>> classesBySuperclass;
private List<String> packagesToScan;
private Logger logger = new DefaultLogger(); //cannot look up regular logger because you get a stackoverflow since we are in the servicelocator
private PackageScanClassResolver classResolver;
protected ServiceLocator() {
this.classResolver = defaultClassLoader();
setResourceAccessor(new ClassLoaderResourceAccessor());
}
protected ServiceLocator(ResourceAccessor accessor) {
this.classResolver = defaultClassLoader();
setResourceAccessor(accessor);
}
protected ServiceLocator(PackageScanClassResolver classResolver) {
this.classResolver = classResolver;
setResourceAccessor(new ClassLoaderResourceAccessor());
}
protected ServiceLocator(PackageScanClassResolver classResolver, ResourceAccessor accessor) {
this.classResolver = classResolver;
setResourceAccessor(accessor);
}
public static ServiceLocator getInstance() {
return instance;
}
public static void setInstance(ServiceLocator newInstance) {
instance = newInstance;
}
private PackageScanClassResolver defaultClassLoader(){
if (WebSpherePackageScanClassResolver.isWebSphereClassLoader(this.getClass().getClassLoader())) {
logger.debug("Using WebSphere Specific Class Resolver");
return new WebSpherePackageScanClassResolver("liquibase/parser/core/xml/dbchangelog-2.0.xsd");
} else {
return new DefaultPackageScanClassResolver();
}
}
public void setResourceAccessor(ResourceAccessor resourceAccessor) {
this.resourceAccessor = resourceAccessor;
this.classesBySuperclass = new HashMap<Class, List<Class>>();
this.classResolver.setClassLoaders(new HashSet<ClassLoader>(Arrays.asList(new ClassLoader[] {resourceAccessor.toClassLoader()})));
packagesToScan = new ArrayList<String>();
String packagesToScanSystemProp = System.getProperty("liquibase.scan.packages");
if ((packagesToScanSystemProp != null) &&
((packagesToScanSystemProp = StringUtils.trimToNull(packagesToScanSystemProp)) != null)) {
for (String value : packagesToScanSystemProp.split(",")) {
addPackageToScan(value);
}
} else {
Enumeration<URL> manifests = null;
try {
manifests = resourceAccessor.getResources("META-INF/MANIFEST.MF");
while (manifests.hasMoreElements()) {
URL url = manifests.nextElement();
InputStream is = url.openStream();
Manifest manifest = new Manifest(is);
String attributes = StringUtils.trimToNull(manifest.getMainAttributes().getValue("Liquibase-Package"));
if (attributes != null) {
for (Object value : attributes.split(",")) {
addPackageToScan(value.toString());
}
}
is.close();
}
} catch (IOException e) {
throw new UnexpectedLiquibaseException(e);
}
if (packagesToScan.size() == 0) {
addPackageToScan("liquibase.change");
addPackageToScan("liquibase.database");
addPackageToScan("liquibase.parser");
addPackageToScan("liquibase.precondition");
addPackageToScan("liquibase.datatype");
addPackageToScan("liquibase.serializer");
addPackageToScan("liquibase.sqlgenerator");
addPackageToScan("liquibase.executor");
addPackageToScan("liquibase.snapshot");
addPackageToScan("liquibase.logging");
addPackageToScan("liquibase.diff");
addPackageToScan("liquibase.structure");
addPackageToScan("liquibase.structurecompare");
addPackageToScan("liquibase.lockservice");
addPackageToScan("liquibase.ext");
}
}
}
public void addPackageToScan(String packageName) {
packagesToScan.add(packageName);
}
public Class findClass(Class requiredInterface) throws ServiceNotFoundException {
Class[] classes = findClasses(requiredInterface);
if (PrioritizedService.class.isAssignableFrom(requiredInterface)) {
PrioritizedService returnObject = null;
for (Class clazz : classes) {
PrioritizedService newInstance;
try {
newInstance = (PrioritizedService) clazz.newInstance();
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
if (returnObject == null || newInstance.getPriority() > returnObject.getPriority()) {
returnObject = newInstance;
}
}
if (returnObject == null) {
throw new ServiceNotFoundException("Could not find implementation of " + requiredInterface.getName());
}
return returnObject.getClass();
}
if (classes.length != 1) {
throw new ServiceNotFoundException("Could not find unique implementation of " + requiredInterface.getName() + ". Found " + classes.length + " implementations");
}
return classes[0];
}
public <T> Class<? extends T>[] findClasses(Class<T> requiredInterface) throws ServiceNotFoundException {
logger.debug("ServiceLocator.findClasses for "+requiredInterface.getName());
try {
Class.forName(requiredInterface.getName());
if (!classesBySuperclass.containsKey(requiredInterface)) {
classesBySuperclass.put(requiredInterface, findClassesImpl(requiredInterface));
}
} catch (Exception e) {
throw new ServiceNotFoundException(e);
}
List<Class> classes = classesBySuperclass.get(requiredInterface);
HashSet<Class> uniqueClasses = new HashSet<Class>(classes);
return uniqueClasses.toArray(new Class[uniqueClasses.size()]);
}
public Object newInstance(Class requiredInterface) throws ServiceNotFoundException {
try {
return findClass(requiredInterface).newInstance();
} catch (Exception e) {
throw new ServiceNotFoundException(e);
}
}
private List<Class> findClassesImpl(Class requiredInterface) throws Exception {
logger.debug("ServiceLocator finding classes matching interface " + requiredInterface.getName());
List<Class> classes = new ArrayList<Class>();
classResolver.addClassLoader(resourceAccessor.toClassLoader());
for (Class<?> clazz : classResolver.findImplementations(requiredInterface, packagesToScan.toArray(new String[packagesToScan.size()]))) {
if (clazz.getAnnotation(LiquibaseService.class ) != null && clazz.getAnnotation(LiquibaseService.class).skip()) {
continue;
}
if (!Modifier.isAbstract(clazz.getModifiers()) && !Modifier.isInterface(clazz.getModifiers()) && Modifier.isPublic(clazz.getModifiers())) {
try {
clazz.getConstructor();
logger.debug(clazz.getName() + " matches "+requiredInterface.getName());
classes.add(clazz);
} catch (NoSuchMethodException e) {
logger.info("Can not use "+clazz+" as a Liquibase service because it does not have a no-argument constructor" );
} catch (NoClassDefFoundError e) {
String message = "Can not use " + clazz + " as a Liquibase service because " + e.getMessage().replace("/", ".") + " is not in the classpath";
if (e.getMessage().startsWith("org/yaml/snakeyaml")) {
logger.info(message);
} else {
logger.warning(message);
}
}
}
}
return classes;
}
public static void reset() {
instance = new ServiceLocator();
}
protected Logger getLogger() {
return logger;
}
}
| |
package com.xxmassdeveloper.mpchartexample;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.charts.ScatterChart.ScatterShape;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.data.filter.Approximator;
import com.github.mikephil.charting.data.filter.Approximator.ApproximatorType;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.xxmassdeveloper.mpchartexample.notimportant.DemoBase;
import java.util.ArrayList;
import java.util.List;
public class ScatterChartActivity extends DemoBase implements OnSeekBarChangeListener,
OnChartValueSelectedListener {
private ScatterChart mChart;
private SeekBar mSeekBarX, mSeekBarY;
private TextView tvX, tvY;
private Typeface tf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scatterchart);
tvX = (TextView) findViewById(R.id.tvXMax);
tvY = (TextView) findViewById(R.id.tvYMax);
mSeekBarX = (SeekBar) findViewById(R.id.seekBar1);
mSeekBarX.setOnSeekBarChangeListener(this);
mSeekBarY = (SeekBar) findViewById(R.id.seekBar2);
mSeekBarY.setOnSeekBarChangeListener(this);
mChart = (ScatterChart) findViewById(R.id.chart1);
mChart.setDescription("");
tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
mChart.setOnChartValueSelectedListener(this);
mChart.setDrawGridBackground(false);
mChart.setTouchEnabled(true);
// enable scaling and dragging
mChart.setDragEnabled(true);
mChart.setScaleEnabled(true);
mChart.setMaxVisibleValueCount(200);
mChart.setPinchZoom(true);
mSeekBarX.setProgress(45);
mSeekBarY.setProgress(100);
Legend l = mChart.getLegend();
l.setPosition(LegendPosition.RIGHT_OF_CHART);
l.setTypeface(tf);
YAxis yl = mChart.getAxisLeft();
yl.setTypeface(tf);
yl.setAxisMinValue(0f); // this replaces setStartAtZero(true)
mChart.getAxisRight().setEnabled(false);
XAxis xl = mChart.getXAxis();
xl.setTypeface(tf);
xl.setDrawGridLines(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.scatter, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.actionToggleValues: {
List<IScatterDataSet> sets = mChart.getData()
.getDataSets();
for (IScatterDataSet iSet : sets) {
ScatterDataSet set = (ScatterDataSet) iSet;
set.setDrawValues(!set.isDrawValuesEnabled());
}
mChart.invalidate();
break;
}
case R.id.actionToggleHighlight: {
if(mChart.getData() != null) {
mChart.getData().setHighlightEnabled(!mChart.getData().isHighlightEnabled());
mChart.invalidate();
}
break;
}
case R.id.actionTogglePinch: {
if (mChart.isPinchZoomEnabled())
mChart.setPinchZoom(false);
else
mChart.setPinchZoom(true);
mChart.invalidate();
break;
}
case R.id.actionToggleAutoScaleMinMax: {
mChart.setAutoScaleMinMaxEnabled(!mChart.isAutoScaleMinMaxEnabled());
mChart.notifyDataSetChanged();
break;
}
case R.id.actionSave: {
// mChart.saveToGallery("title"+System.currentTimeMillis());
mChart.saveToPath("title" + System.currentTimeMillis(), "");
break;
}
case R.id.animateX: {
mChart.animateX(3000);
break;
}
case R.id.animateY: {
mChart.animateY(3000);
break;
}
case R.id.animateXY: {
mChart.animateXY(3000, 3000);
break;
}
}
return true;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvX.setText("" + (mSeekBarX.getProgress() + 1));
tvY.setText("" + (mSeekBarY.getProgress()));
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i < mSeekBarX.getProgress() + 1; i++) {
xVals.add((i) + "");
}
ArrayList<Entry> yVals1 = new ArrayList<Entry>();
ArrayList<Entry> yVals2 = new ArrayList<Entry>();
ArrayList<Entry> yVals3 = new ArrayList<Entry>();
for (int i = 0; i < mSeekBarX.getProgress(); i++) {
float val = (float) (Math.random() * mSeekBarY.getProgress()) + 3;
yVals1.add(new Entry(val, i));
}
for (int i = 0; i < mSeekBarX.getProgress(); i++) {
float val = (float) (Math.random() * mSeekBarY.getProgress()) + 3;
yVals2.add(new Entry(val, i));
}
for (int i = 0; i < mSeekBarX.getProgress(); i++) {
float val = (float) (Math.random() * mSeekBarY.getProgress()) + 3;
yVals3.add(new Entry(val, i));
}
// create a dataset and give it a type
ScatterDataSet set1 = new ScatterDataSet(yVals1, "DS 1");
set1.setScatterShape(ScatterShape.SQUARE);
set1.setColor(ColorTemplate.COLORFUL_COLORS[0]);
ScatterDataSet set2 = new ScatterDataSet(yVals2, "DS 2");
set2.setScatterShape(ScatterShape.CIRCLE);
set2.setScatterShapeHoleColor(Color.WHITE);
set2.setScatterShapeHoleRadius(5f);
set2.setColor(ColorTemplate.COLORFUL_COLORS[1]);
ScatterDataSet set3 = new ScatterDataSet(yVals3, "DS 3");
set3.setScatterShape(ScatterShape.CROSS);
set3.setColor(ColorTemplate.COLORFUL_COLORS[2]);
set1.setScatterShapeSize(8f);
set2.setScatterShapeSize(8f);
set3.setScatterShapeSize(8f);
ArrayList<IScatterDataSet> dataSets = new ArrayList<IScatterDataSet>();
dataSets.add(set1); // add the datasets
dataSets.add(set2);
dataSets.add(set3);
// create a data object with the datasets
ScatterData data = new ScatterData(xVals, dataSets);
data.setValueTypeface(tf);
mChart.setData(data);
mChart.invalidate();
}
@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
Log.i("VAL SELECTED",
"Value: " + e.getVal() + ", xIndex: " + e.getXIndex()
+ ", DataSet index: " + dataSetIndex);
}
@Override
public void onNothingSelected() {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
| |
/*******************************************************************************
* Copyright 2016 Antoine Nicolas SAMAHA
*
* 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.foc.web.modules.business;
import com.foc.desc.FocObject;
import com.foc.desc.dataModelTree.DataModelNodeDesc;
import com.foc.desc.dataModelTree.DataModelNodeList;
import com.foc.desc.dataModelTree.DataModelNodeTree;
import com.foc.formula.AbstractFormulaEnvironment;
import com.foc.formula.PropertyFormula;
import com.foc.formula.PropertyFormulaContext;
import com.foc.formula.PropertyFormulaDesc;
import com.foc.list.FocList;
import com.foc.property.FProperty;
import com.foc.shared.xmlView.XMLViewKey;
import com.foc.vaadin.FocWebApplication;
import com.foc.vaadin.ICentralPanel;
import com.foc.vaadin.gui.FVIconFactory;
import com.foc.vaadin.gui.components.FVButton;
import com.foc.vaadin.gui.components.FVLabel;
import com.foc.vaadin.gui.components.FVTextField;
import com.foc.vaadin.gui.components.ITableTree;
import com.foc.vaadin.gui.components.treeGrid.FVTreeGrid;
import com.foc.vaadin.gui.xmlForm.FocXMLLayout;
import com.foc.web.gui.INavigationWindow;
import com.foc.web.server.xmlViewDictionary.XMLViewDictionary;
import com.vaadin.event.FieldEvents.BlurEvent;
import com.vaadin.event.FieldEvents.BlurListener;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Table;
import com.vaadin.ui.themes.BaseTheme;
@SuppressWarnings("serial")
public class FocFormula_Form extends FocXMLLayout {
private ITableTree tableTree = null;
private FProperty selectedProperty = null;
private FVTextField textField = null;
private FVLabel expressionLabel = null;
private FVButton appendButton = null;
private AbstractFormulaEnvironment formulaEnvironment = null;
private Object focObjectRowId = null;
@Override
public void dispose() {
tableTree = null;
selectedProperty = null;
if (textField != null) {
textField.dispose();
}
textField = null;
if (expressionLabel != null) {
expressionLabel.dispose();
}
expressionLabel = null;
if (appendButton != null) {
appendButton.dispose();
}
appendButton = null;
super.dispose();
}
@Override
protected void afterLayoutConstruction() {
// The text field of the formula
textField = (FVTextField) getComponentByName("TEXT_FIELD");
// textField.setColumns(30);
// setExpandRatio(textField, 1);
// The label of the formula
expressionLabel = (FVLabel) getComponentByName("LABEL");
// The add button of the formula
appendButton = (FVButton) getComponentByName("ADD");
appendButton.setStyleName(BaseTheme.BUTTON_LINK);
//appendButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_FORMULA));
appendButton.setIcon(FVIconFactory.getInstance().getFVIcon_Small(FVIconFactory.ICON_EDIT));
appendButton.addClickListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
String fieldPath = popupFieldSelection();
if (fieldPath != null){
textField.setValueString(textField.getValueString() + fieldPath);
}
textField.focus();
}
});
}
public FProperty getSelectedProperty() {
return selectedProperty;
}
public ITableTree getTableOrTree() {
return tableTree;
}
public void setTableOrTree(ITableTree tableTree) {
this.tableTree = tableTree;
}
public Table getTable() {
Table result = null;
if (tableTree != null) {
result = (Table) tableTree;
}
return result;
}
public AbstractFormulaEnvironment getFormulaEnvironment() {
return formulaEnvironment;
}
public void setFormulaEnvironment(AbstractFormulaEnvironment fe) {
this.formulaEnvironment = fe;
}
public FVTextField getTextField(){
return textField;
}
public FVLabel getExpressionLabel(){
return expressionLabel;
}
/**
* This method needs to be called to initialize the table and the formula
* environment
*
* @param table
* The ITableTree to apply formulas to.
* @param forEnv
* The formula environment.
*/
public void initialize(ITableTree table, AbstractFormulaEnvironment forEnv) {
setTableOrTree(table);
setFormulaEnvironment(forEnv);
initializeTextFieldListener();
}
private void initializeTextFieldListener() {
if (textField != null) {
textField.addBlurListener(new BlurListener() {
@Override
public void blur(BlurEvent event) {
applyTextFieldFormulaInTheProperty();
}
});
}
}
public void applyTextFieldFormulaInTheProperty(){
if (selectedProperty != null) {
if (!selectedProperty.isWithFormula() && !textField.getValueString().equals("")) {
formulaEnvironment.applyFormulaToProperty(selectedProperty, "");
}
PropertyFormulaContext propertyFormulaContext = selectedProperty.getPropertyFormulaContext();
if (propertyFormulaContext != null) {
PropertyFormula propertyFormula = propertyFormulaContext.getPropertyFormula();
if (propertyFormula != null) {
// A listener on the field expression will use the
// AbstractFormulaEnvironment to apply the formula
propertyFormula.setExpression(textField.getValueString());
}
}
selectedProperty.notifyListeners();
}
}
public FocObject getSelectedFocObject() {
FocObject result = null;
ITableTree tempTableTree = getTableOrTree();
if (tempTableTree != null) {
FocList list = tempTableTree.getFocList();
if(list != null){
if(focObjectRowId != null){
result = list.searchByReference((Long) focObjectRowId);
}
}
}
return result;
}
public String popupFieldSelection() {
String str = null;
FocObject fatherObj = getSelectedFocObject();
if (fatherObj != null) {
DataModelNodeList dataModelNodeList = new DataModelNodeList(fatherObj.getThisFocDesc(), 5, fatherObj);
DataModelNodeTree dataModelNodeTree = new DataModelNodeTree(dataModelNodeList);
XMLViewKey xmlViewKey = new XMLViewKey(DataModelNodeDesc.getInstance().getStorageName(), XMLViewKey.TYPE_TREE);
ICentralPanel centralPanel = XMLViewDictionary.getInstance().newCentralPanel(getMainWindow(), xmlViewKey, dataModelNodeTree);
FocDataModel_Tree treePanel = (FocDataModel_Tree) centralPanel;
treePanel.setFormulaLayout(this);
INavigationWindow navigationWindow = null;
if(FocWebApplication.getInstanceForThread().getContent() instanceof INavigationWindow){
navigationWindow = (INavigationWindow) FocWebApplication.getInstanceForThread().getContent();
}else{
navigationWindow = getMainWindow();
}
if(navigationWindow != null){
navigationWindow.changeCentralPanelContent(centralPanel, true);
}
}
return str;
}
public void triggerFormulaChanges(FProperty selectedProperty, Object rowId, Object columnId){
focObjectRowId = rowId;
boolean fStringEditable = true;
if (selectedProperty != null) {
FocFormula_Form.this.selectedProperty = selectedProperty;
PropertyFormulaContext propertyFormulaContext = selectedProperty.getPropertyFormulaContext();
if (propertyFormulaContext != null) {
PropertyFormula propertyFormula = propertyFormulaContext.getPropertyFormula();
if (propertyFormula != null) {
FProperty pfProperty = propertyFormula.getFocProperty(PropertyFormulaDesc.FLD_EXPRESSION);
textField.setValue((String) pfProperty.getObject());
}
} else {
String expression = "";
if (selectedProperty.getFocField() != null) {
if (selectedProperty.getFocField().getFormulaString() != null && !selectedProperty.getFocField().getFormulaString().isEmpty()) {
expression = selectedProperty.getFocField().getFormulaString();
fStringEditable = false;
} else {
// if(outputFieldFormulaGetter != null){
// expression =
// outputFieldFormulaGetter.getOutputFieldFormulaExpression(selectionPanel,
// selectedProperty, row, col);
// if(expression != null && !expression.isEmpty()){
// fStringEditable = false;
// }
// }
}
}
textField.setValueString(expression);
}
textField.setEnabled(fStringEditable);
appendButton.setEnabled(fStringEditable);
}
// String rowCode = getTable().getItem(rowId).getItemProperty("CODE").toString();
String rowCode = null;
if(getTableOrTree() instanceof FVTreeGrid){
FVTreeGrid treeGrid = (FVTreeGrid) getTableOrTree();
if(treeGrid.getSelectedObject() != null && treeGrid.getSelectedObject().getItemProperty("CODE") != null){
rowCode = treeGrid.getSelectedObject().getItemProperty("CODE").getValue().toString();
}
}else{
rowCode = getTable().getItem(rowId).getItemProperty("CODE").toString();
}
expressionLabel.setValue(rowCode + " : " + columnId);
}
}
| |
/*
* 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.ambari.server.controller.internal;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.StaticallyInject;
import org.apache.ambari.server.checks.UpgradeCheckRegistry;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.AmbariManagementController;
import org.apache.ambari.server.controller.internal.URLStreamProvider.AmbariHttpUrlConnectionProvider;
import org.apache.ambari.server.controller.spi.NoSuchParentResourceException;
import org.apache.ambari.server.controller.spi.NoSuchResourceException;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.Resource.Type;
import org.apache.ambari.server.controller.spi.SystemException;
import org.apache.ambari.server.controller.spi.UnsupportedPropertyException;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
import org.apache.ambari.server.orm.dao.RepositoryVersionDAO;
import org.apache.ambari.server.orm.entities.RepositoryVersionEntity;
import org.apache.ambari.server.stack.upgrade.Direction;
import org.apache.ambari.server.stack.upgrade.UpgradePack;
import org.apache.ambari.server.stack.upgrade.orchestrate.UpgradeHelper;
import org.apache.ambari.server.state.CheckHelper;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.StackId;
import org.apache.ambari.spi.ClusterInformation;
import org.apache.ambari.spi.RepositoryVersion;
import org.apache.ambari.spi.upgrade.UpgradeCheck;
import org.apache.ambari.spi.upgrade.UpgradeCheckRequest;
import org.apache.ambari.spi.upgrade.UpgradeCheckResult;
import org.apache.ambari.spi.upgrade.UpgradeType;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* Resource provider for pre-upgrade checks.
*/
@StaticallyInject
public class PreUpgradeCheckResourceProvider extends ReadOnlyResourceProvider {
private static final Logger LOG = LoggerFactory.getLogger(PreUpgradeCheckResourceProvider.class);
//----- Property ID constants ---------------------------------------------
public static final String UPGRADE_CHECK_ID_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "id");
public static final String UPGRADE_CHECK_CHECK_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "check");
public static final String UPGRADE_CHECK_STATUS_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "status");
public static final String UPGRADE_CHECK_REASON_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "reason");
public static final String UPGRADE_CHECK_FAILED_ON_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "failed_on");
public static final String UPGRADE_CHECK_FAILED_DETAIL_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "failed_detail");
public static final String UPGRADE_CHECK_CHECK_TYPE_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "check_type");
public static final String UPGRADE_CHECK_CLUSTER_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "cluster_name");
public static final String UPGRADE_CHECK_UPGRADE_TYPE_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "upgrade_type");
public static final String UPGRADE_CHECK_TARGET_REPOSITORY_VERSION_ID_ID = PropertyHelper.getPropertyId("UpgradeChecks", "repository_version_id");
public static final String UPGRADE_CHECK_TARGET_REPOSITORY_VERSION = PropertyHelper.getPropertyId("UpgradeChecks", "repository_version");
/**
* Optional parameter to specify the preferred Upgrade Pack to use.
*/
public static final String UPGRADE_CHECK_UPGRADE_PACK_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "upgrade_pack");
public static final String UPGRADE_CHECK_REPOSITORY_VERSION_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "repository_version");
public static final String UPGRADE_CHECK_FOR_REVERT_PROPERTY_ID = PropertyHelper.getPropertyId("UpgradeChecks", "for_revert");
@Inject
private static Provider<Clusters> clustersProvider;
@Inject
private static RepositoryVersionDAO repositoryVersionDAO;
/**
* Used a {@link Provider} around this instance to force lazy loading so it
* doesn't hold up Ambari's startup process.
*/
@Inject
private static Provider<UpgradeCheckRegistry> upgradeCheckRegistryProvider;
@Inject
private static Provider<UpgradeHelper> upgradeHelper;
@Inject
private static Provider<Configuration> config;
@Inject
private static CheckHelper checkHelper;
private static final Set<String> pkPropertyIds = Collections.singleton(UPGRADE_CHECK_ID_PROPERTY_ID);
public static final Set<String> propertyIds = ImmutableSet.of(
UPGRADE_CHECK_ID_PROPERTY_ID,
UPGRADE_CHECK_CHECK_PROPERTY_ID,
UPGRADE_CHECK_STATUS_PROPERTY_ID,
UPGRADE_CHECK_REASON_PROPERTY_ID,
UPGRADE_CHECK_FAILED_ON_PROPERTY_ID,
UPGRADE_CHECK_FAILED_DETAIL_PROPERTY_ID,
UPGRADE_CHECK_CHECK_TYPE_PROPERTY_ID,
UPGRADE_CHECK_CLUSTER_NAME_PROPERTY_ID,
UPGRADE_CHECK_UPGRADE_TYPE_PROPERTY_ID,
UPGRADE_CHECK_FOR_REVERT_PROPERTY_ID,
UPGRADE_CHECK_TARGET_REPOSITORY_VERSION_ID_ID,
UPGRADE_CHECK_UPGRADE_PACK_PROPERTY_ID);
@SuppressWarnings("serial")
public static final Map<Type, String> keyPropertyIds = ImmutableMap.<Type, String>builder()
.put(Type.PreUpgradeCheck, UPGRADE_CHECK_ID_PROPERTY_ID)
.put(Type.Cluster, UPGRADE_CHECK_CLUSTER_NAME_PROPERTY_ID)
.build();
/**
* Constructor.
*
* @param managementController management controller
*/
public PreUpgradeCheckResourceProvider(AmbariManagementController managementController) {
super(Type.PreUpgradeCheck, propertyIds, keyPropertyIds, managementController);
}
@Override
public Set<Resource> getResources(Request request, Predicate predicate) throws SystemException, UnsupportedPropertyException,
NoSuchResourceException, NoSuchParentResourceException {
final Set<Resource> resources = new HashSet<>();
final Set<String> requestedIds = getRequestPropertyIds(request, predicate);
final Set<Map<String, Object>> propertyMaps = getPropertyMaps(predicate);
for (Map<String, Object> propertyMap: propertyMaps) {
final String clusterName = propertyMap.get(UPGRADE_CHECK_CLUSTER_NAME_PROPERTY_ID).toString();
UpgradeType upgradeType = UpgradeType.ROLLING;
if (propertyMap.containsKey(UPGRADE_CHECK_UPGRADE_TYPE_PROPERTY_ID)) {
try {
upgradeType = UpgradeType.valueOf(propertyMap.get(UPGRADE_CHECK_UPGRADE_TYPE_PROPERTY_ID).toString());
} catch(Exception e){
throw new SystemException(String.format("Property %s has an incorrect value of %s.", UPGRADE_CHECK_UPGRADE_TYPE_PROPERTY_ID, propertyMap.get(UPGRADE_CHECK_UPGRADE_TYPE_PROPERTY_ID)));
}
}
final Cluster cluster;
try {
cluster = clustersProvider.get().getCluster(clusterName);
} catch (AmbariException ambariException) {
throw new NoSuchResourceException(ambariException.getMessage());
}
StackId sourceStackId = cluster.getCurrentStackVersion();
String repositoryVersionId = (String) propertyMap.get(
UPGRADE_CHECK_TARGET_REPOSITORY_VERSION_ID_ID);
if (StringUtils.isBlank(repositoryVersionId)) {
throw new SystemException(
String.format("%s is a required property when executing upgrade checks",
UPGRADE_CHECK_TARGET_REPOSITORY_VERSION_ID_ID));
}
RepositoryVersionEntity repositoryVersion = repositoryVersionDAO.findByPK(
Long.valueOf(repositoryVersionId));
//ambariMetaInfo.getStack(stackName, cluster.getCurrentStackVersion().getStackVersion()).getUpgradePacks()
// TODO AMBARI-12698, filter the upgrade checks to run based on the stack and upgrade type, or the upgrade pack.
UpgradePack upgradePack = null;
String preferredUpgradePackName = propertyMap.containsKey(UPGRADE_CHECK_UPGRADE_PACK_PROPERTY_ID) ?
(String) propertyMap.get(UPGRADE_CHECK_UPGRADE_PACK_PROPERTY_ID) : null;
try{
// Hint: PreChecks currently executing only before UPGRADE direction
upgradePack = upgradeHelper.get().suggestUpgradePack(clusterName, sourceStackId,
repositoryVersion.getStackId(), Direction.UPGRADE, upgradeType,
preferredUpgradePackName);
} catch (AmbariException e) {
throw new SystemException(e.getMessage(), e);
}
if (upgradePack == null) {
throw new SystemException(
String.format("Upgrade pack not found for the target repository version %s",
repositoryVersion));
}
ClusterInformation clusterInformation = cluster.buildClusterInformation();
StackId stackId = repositoryVersion.getStackId();
RepositoryVersion targetRepositoryVersion = new RepositoryVersion(repositoryVersion.getId(),
stackId.getStackName(), stackId.getStackVersion(), stackId.getStackId(),
repositoryVersion.getVersion(), repositoryVersion.getType());
final UpgradeCheckRequest upgradeCheckRequest = new UpgradeCheckRequest(clusterInformation,
upgradeType, targetRepositoryVersion,
upgradePack.getPrerequisiteCheckConfig().getAllProperties(),
new AmbariHttpUrlConnectionProvider());
if (propertyMap.containsKey(UPGRADE_CHECK_FOR_REVERT_PROPERTY_ID)) {
Boolean forRevert = BooleanUtils.toBooleanObject(propertyMap.get(UPGRADE_CHECK_FOR_REVERT_PROPERTY_ID).toString());
upgradeCheckRequest.setRevert(forRevert);
}
UpgradeCheckRegistry upgradeCheckRegistry = upgradeCheckRegistryProvider.get();
// ToDo: properly handle exceptions, i.e. create fake check with error description
final List<UpgradeCheck> upgradeChecksToRun;
try {
upgradeChecksToRun = upgradeCheckRegistry.getFilteredUpgradeChecks(upgradePack);
} catch (AmbariException ambariException) {
throw new SystemException("Unable to load upgrade checks", ambariException);
}
List<UpgradeCheckResult> results = checkHelper.performChecks(upgradeCheckRequest,
upgradeChecksToRun, config.get());
for (UpgradeCheckResult prerequisiteCheck : results) {
final Resource resource = new ResourceImpl(Resource.Type.PreUpgradeCheck);
setResourceProperty(resource, UPGRADE_CHECK_ID_PROPERTY_ID, prerequisiteCheck.getId(), requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_CHECK_PROPERTY_ID, prerequisiteCheck.getDescription(), requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_STATUS_PROPERTY_ID, prerequisiteCheck.getStatus(), requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_REASON_PROPERTY_ID, prerequisiteCheck.getFailReason(), requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_FAILED_ON_PROPERTY_ID, prerequisiteCheck.getFailedOn(), requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_FAILED_DETAIL_PROPERTY_ID,prerequisiteCheck.getFailedDetail(), requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_CHECK_TYPE_PROPERTY_ID, prerequisiteCheck.getType(), requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_CLUSTER_NAME_PROPERTY_ID, cluster.getClusterName(), requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_UPGRADE_TYPE_PROPERTY_ID, upgradeType, requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_TARGET_REPOSITORY_VERSION_ID_ID, repositoryVersion.getId(), requestedIds);
setResourceProperty(resource, UPGRADE_CHECK_TARGET_REPOSITORY_VERSION, repositoryVersion.getVersion(), requestedIds);
resources.add(resource);
}
}
return resources;
}
@Override
protected Set<String> getPKPropertyIds() {
return pkPropertyIds;
}
}
| |
/*
* Copyright 2018 Crown Copyright
*
* 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 stroom.pipeline.reader;
import stroom.pipeline.destination.DestinationProvider;
import stroom.pipeline.factory.PipelineFactoryException;
import stroom.pipeline.factory.TakesInput;
import stroom.pipeline.factory.TakesReader;
import stroom.pipeline.factory.Target;
import stroom.pipeline.parser.CombinedParser;
import stroom.pipeline.parser.CombinedParser.Mode;
import stroom.pipeline.parser.XMLParser;
import stroom.pipeline.reader.ByteStreamDecoder.DecodedChar;
import stroom.pipeline.stepping.Recorder;
import stroom.util.shared.TextRange;
import org.apache.commons.lang3.mutable.MutableInt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.FilterReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class ReaderRecorder extends AbstractIOElement implements TakesInput, TakesReader, Target, Recorder {
private static final Logger LOGGER = LoggerFactory.getLogger(ReaderRecorder.class);
private static final int BASE_LINE_NO = 1;
private static final int BASE_COL_NO = 1;
private Buffer buffer;
private RangeMode rangeMode = RangeMode.INCLUSIVE_INCLUSIVE;
@Override
public void addTarget(final Target target) {
if (target != null) {
if (!(target instanceof DestinationProvider)
&& !(target instanceof TakesInput)
&& !(target instanceof TakesReader)) {
throw new PipelineFactoryException(
"Attempt to link to an element that does not accept input or reader: "
+ getElementId() + " > " + target.getElementId());
}
super.addTarget(target);
// You can have multiple targets which would make this code wrong but the stepper doesn't allow
// stepping on forks so we are ok.
// The XML( fragment) parser delimits records on the start char of the first element in the rec
// so we need to use an exclusive end
if (target instanceof XMLParser) {
rangeMode = RangeMode.INCLUSIVE_EXCLUSIVE;
} else if (target instanceof CombinedParser) {
final Mode parserMode = ((CombinedParser) target).getMode();
if (parserMode == Mode.XML || parserMode == Mode.XML_FRAGMENT) {
rangeMode = RangeMode.INCLUSIVE_EXCLUSIVE;
}
}
}
}
@Override
public void setInputStream(final InputStream inputStream, final String encoding) throws IOException {
final InputBuffer inputBuffer = new InputBuffer(inputStream, encoding, rangeMode);
buffer = inputBuffer;
super.setInputStream(inputBuffer, encoding);
}
@Override
public void setReader(final Reader reader) throws IOException {
final ReaderBuffer readerBuffer = new ReaderBuffer(reader);
buffer = readerBuffer;
super.setReader(readerBuffer);
}
@Override
public Object getData(final TextRange textRange) {
if (buffer == null) {
return null;
}
return buffer.getData(textRange);
}
@Override
public void clear(final TextRange textRange) {
if (buffer != null) {
buffer.clear(textRange);
}
}
@Override
public void startStream() {
super.startStream();
if (buffer != null) {
buffer.reset();
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Buffer for reading character data
*/
private static class ReaderBuffer extends FilterReader implements Buffer {
private static final int MAX_BUFFER_SIZE = 1000000;
private final StringBuilder stringBuilder = new StringBuilder();
private int lineNo = BASE_LINE_NO;
private int colNo = BASE_COL_NO;
ReaderBuffer(final Reader in) {
super(in);
}
@Override
public int read(final char[] cbuf, final int off, final int len) throws IOException {
final int length = super.read(cbuf, off, len);
if (length > 0) {
if (LOGGER.isDebugEnabled() && stringBuilder.length() > MAX_BUFFER_SIZE) {
LOGGER.debug("Exceeding buffer length");
}
stringBuilder.append(cbuf, off, length);
}
return length;
}
@Override
public int read(final char[] cbuf) throws IOException {
return this.read(cbuf, 0, cbuf.length);
}
@Override
public int read() throws IOException {
final int result = super.read();
if (result != -1) {
if (LOGGER.isDebugEnabled() && stringBuilder.length() > MAX_BUFFER_SIZE) {
LOGGER.debug("Exceeding buffer length");
}
stringBuilder.append((char) result);
}
return result;
}
@Override
public Object getData(final TextRange textRange) {
if (textRange != null) {
final StringBuilder sb = new StringBuilder();
consumeHighlightedSection(textRange, sb::append);
return sb.toString();
}
return null;
}
@Override
public void clear(final TextRange textRange) {
if (textRange == null) {
clear();
} else {
consumeHighlightedSection(textRange, c -> {
});
}
}
@Override
public void reset() {
lineNo = BASE_LINE_NO;
colNo = BASE_COL_NO;
clear();
}
private void consumeHighlightedSection(final TextRange textRange,
final Consumer<Character> consumer) {
// range is inclusive at both ends
final int lineFrom = textRange.getFrom().getLineNo();
final int colFrom = textRange.getFrom().getColNo();
final int lineTo = textRange.getTo().getLineNo();
final int colTo = textRange.getTo().getColNo();
boolean found = false;
boolean inRecord = false;
int advance = 0;
int i = 0;
for (; i < length() && !found; i++) {
final char c = charAt(i);
if (!inRecord) {
// Inclusive from
if (lineNo > lineFrom ||
(lineNo == lineFrom && colNo >= colFrom)) {
// This is the start of the range but we don't want to show any leading line breaks
if (c != '\n') {
inRecord = true;
} else {
LOGGER.debug("Ignoring line break at start of range");
}
}
}
if (inRecord) {
// Inclusive to
if (lineNo > lineTo ||
(lineNo == lineTo && colNo > colTo)) {
// Gone past the desired range
inRecord = false;
found = true;
advance = i; // offset of the first char outside the range
}
}
if (inRecord) {
consumer.accept(c);
}
// Advance the line or column number if we haven't found the record.
if (!found) {
if (c == '\n') {
lineNo++;
colNo = BASE_COL_NO;
} else {
colNo++;
}
}
}
// If we went through the whole buffer and didn't find what we are looking for then clear it.
if (!found) {
clear();
} else {
// Move the filter buffer forward and discard any content we no longer need.
move(advance);
}
}
private char charAt(int index) {
return stringBuilder.charAt(index);
}
private int length() {
return stringBuilder.length();
}
private void move(final int len) {
if (len > 0) {
if (len >= stringBuilder.length()) {
stringBuilder.setLength(0);
} else {
stringBuilder.delete(0, len);
}
}
}
private void clear() {
stringBuilder.setLength(0);
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Buffer for reading byte data with a provided encoding
*/
private static class InputBuffer extends FilterInputStream implements Buffer {
private static final int MAX_BUFFER_SIZE = 1000000;
private final String encoding;
private final ByteBuffer byteBuffer = new ByteBuffer();
private final ByteStreamDecoder byteStreamDecoder;
private final RangeMode rangeMode;
private int lineNo = BASE_LINE_NO;
private int colNo = BASE_COL_NO;
InputBuffer(final InputStream in,
final String encoding,
final RangeMode rangeMode) {
super(in);
this.encoding = encoding;
this.byteStreamDecoder = new ByteStreamDecoder(encoding);
this.rangeMode = rangeMode;
LOGGER.debug("Using rangeMode {}", rangeMode);
}
@Override
public int read(final byte[] b, final int off, final int len) throws IOException {
final int length = super.read(b, off, len);
if (length > 0) {
if (LOGGER.isDebugEnabled() && byteBuffer.size() > MAX_BUFFER_SIZE) {
LOGGER.debug("Exceeding buffer length");
}
byteBuffer.write(b, off, length);
}
return length;
}
@Override
public int read(final byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
@Override
public int read() throws IOException {
final int result = super.read();
if (result != -1) {
if (LOGGER.isDebugEnabled() && byteBuffer.size() > MAX_BUFFER_SIZE) {
LOGGER.debug("Exceeding buffer length");
}
byteBuffer.write(result);
}
return result;
}
@Override
public Object getData(final TextRange textRange) {
if (textRange != null) {
return getHighlightedSection(textRange);
}
return null;
}
private String getHighlightedSection(final TextRange textRange) {
try {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
consumeHighlightedSection(textRange, baos::write);
final String str = baos.toString(encoding);
LOGGER.debug("str: [{}]", str);
return str;
} catch (final UnsupportedEncodingException e) {
LOGGER.error(e.getMessage(), e);
return e.getMessage();
}
}
@Override
public void clear(final TextRange textRange) {
if (textRange == null) {
clear();
} else {
consumeHighlightedSection(textRange, c -> {
});
}
}
private void consumeHighlightedSection(final TextRange textRange,
final Consumer<Byte> consumer) {
// range is inclusive at both ends by default unless specified differently by rangeMode
final int lineFrom = textRange.getFrom().getLineNo();
final int colFrom = textRange.getFrom().getColNo();
final int lineTo = textRange.getTo().getLineNo();
final int colTo = textRange.getTo().getColNo();
boolean found = false;
boolean inRecord = false;
boolean isEndInclusive = rangeMode.isEndInclusive();
int advance = 0;
final MutableInt offset = new MutableInt(0);
final Supplier<Byte> byteSupplier = () ->
byteBuffer.getByte(offset.getAndIncrement());
// TODO This could be made more efficient if scans the stream to look for the
// byte value (which may differ for different encodings) of the \n 'chars' until
// we get to the line of interest. From that point we need to decode each char to
// see how may bytes it occupies.
// Need a kind of jumpToLine method
while (offset.intValue() < length() && !found) {
// The offset where our potentially multi-byte char starts
final int startOffset = offset.intValue();
// This will move offset by the number of bytes in the 'character', i.e. 1-4
final DecodedChar decodedChar = byteStreamDecoder.decodeNextChar(byteSupplier);
// Inclusive
if (!inRecord) {
if (lineNo > lineFrom ||
(lineNo == lineFrom && colNo >= colFrom)) {
// This is the start of the range but we don't want to show any leading line breaks
if (!decodedChar.isLineBreak()) {
inRecord = true;
} else {
LOGGER.debug("Ignoring line break at start of range");
}
}
}
// Inclusive or Exclusive depending on rangeMode
if (inRecord) {
if (lineNo > lineTo ||
(lineNo == lineTo && (
(!isEndInclusive && colNo >= colTo) || (isEndInclusive && colNo > colTo)))) {
// Gone past the desired range
inRecord = false;
found = true;
// Work out offset of the first char outside the range
advance = startOffset + decodedChar.getByteCount() - 1;
}
}
if (inRecord) {
// Pass all the bytes that make up our char onto the consumer
// LOGGER.info("Found [{}] at {}:{}", decodedChar.getAsString(), lineNo, colNo);
for (int j = 0; j < decodedChar.getByteCount(); j++) {
final byte b = byteAt(startOffset + j);
consumer.accept(b);
}
}
// Advance the line or column number if we haven't found the record.
if (!found) {
if (decodedChar.isLineBreak()) {
lineNo++;
colNo = BASE_COL_NO;
} else if (decodedChar.isByteOrderMark() || decodedChar.isNonVisibleCharacter()) {
// We don't want to advance the line/col position if it is a non visual char
// but we still need to pass the non visual char on to the consumer
// as they might want to do something with it.
LOGGER.debug("BOM found at [{}:{}]", lineNo, colNo);
} else {
final int charCount = decodedChar.getCharCount();
if (LOGGER.isDebugEnabled() && charCount > 1) {
LOGGER.debug("Found multi-char 'character' [{}] with char count {} at [{}:{}]",
decodedChar.getAsString(),
charCount,
lineNo,
colNo);
}
// Some 'characters', e.g. emoji are not only multi-byte but are
// represented as more than one char so we need
// to increment the colNo by the right number of chars
colNo += decodedChar.getCharCount();
}
}
}
// If we went through the whole buffer and didn't find what we are looking for then clear it.
if (!found) {
clear();
} else {
// Move the filter buffer forward and discard any content we no longer need.
move(advance);
}
}
@Override
public void reset() {
lineNo = BASE_LINE_NO;
colNo = BASE_COL_NO;
clear();
}
private byte byteAt(int index) {
return byteBuffer.getByte(index);
}
private int length() {
return byteBuffer.size();
}
private void move(final int len) {
if (len > 0) {
if (len >= byteBuffer.size()) {
byteBuffer.reset();
} else {
byteBuffer.move(len);
}
}
}
private void clear() {
byteBuffer.reset();
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private static class ByteBuffer extends ByteArrayOutputStream {
byte getByte(final int index) {
return buf[index];
}
void move(final int len) {
if (count >= len) {
System.arraycopy(buf, len, buf, 0, count - len);
count -= len;
}
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private interface Buffer {
Object getData(TextRange textRange);
void clear(TextRange textRange);
void reset();
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private enum RangeMode {
INCLUSIVE_INCLUSIVE(true, true),
INCLUSIVE_EXCLUSIVE(true, false),
EXCLUSIVE_INCLUSIVE(false, true),
EXCLUSIVE_EXCLUSIVE(false, false);
private final boolean isStartInclusive;
private final boolean isEndInclusive;
RangeMode(final boolean isStartInclusive, final boolean isEndInclusive) {
this.isStartInclusive = isStartInclusive;
this.isEndInclusive = isEndInclusive;
}
public boolean isStartInclusive() {
return isStartInclusive;
}
public boolean isEndInclusive() {
return isEndInclusive;
}
}
}
| |
/**
* Copyright (c) 2008-2013, http://www.snakeyaml.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.pyyaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.composer.Composer;
import org.yaml.snakeyaml.constructor.AbstractConstruct;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.events.AliasEvent;
import org.yaml.snakeyaml.events.CollectionStartEvent;
import org.yaml.snakeyaml.events.Event;
import org.yaml.snakeyaml.events.ScalarEvent;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.parser.ParserImpl;
import org.yaml.snakeyaml.reader.StreamReader;
import org.yaml.snakeyaml.reader.UnicodeReader;
import org.yaml.snakeyaml.resolver.Resolver;
/**
* @see imported from PyYAML
*/
public class PyStructureTest extends PyImportTest {
private void compareEvents(List<Event> events1, List<Event> events2, boolean full) {
assertEquals(events1.size(), events2.size());
Iterator<Event> iter1 = events1.iterator();
Iterator<Event> iter2 = events2.iterator();
while (iter1.hasNext()) {
Event event1 = iter1.next();
Event event2 = iter2.next();
assertEquals(event1.getClass(), event2.getClass());
if (event1 instanceof AliasEvent && full) {
assertEquals(((AliasEvent) event1).getAnchor(), ((AliasEvent) event2).getAnchor());
}
if (event1 instanceof CollectionStartEvent) {
String tag1 = ((CollectionStartEvent) event1).getTag();
String tag2 = ((CollectionStartEvent) event1).getTag();
if (tag1 != null && !"!".equals(tag1) && tag2 != null && !"!".equals(tag1)) {
assertEquals(tag1, tag2);
}
}
if (event1 instanceof ScalarEvent) {
ScalarEvent scalar1 = (ScalarEvent) event1;
ScalarEvent scalar2 = (ScalarEvent) event2;
if (scalar1.getImplicit().bothFalse() && scalar2.getImplicit().bothFalse()) {
assertEquals(scalar1.getTag(), scalar2.getTag());
}
assertEquals(scalar1.getValue(), scalar2.getValue());
}
}
}
public void testParser() {
File[] files = getStreamsByExtension(".data", true);
assertTrue("No test files found.", files.length > 0);
for (File file : files) {
if (!file.getName().contains("scan-line-b")) {
continue;
}
try {
InputStream input = new FileInputStream(file);
List<Event> events1 = parse(input);
input.close();
assertFalse(events1.isEmpty());
int index = file.getAbsolutePath().lastIndexOf('.');
String canonicalName = file.getAbsolutePath().substring(0, index) + ".canonical";
File canonical = new File(canonicalName);
List<Event> events2 = canonicalParse(new FileInputStream(canonical));
assertFalse(events2.isEmpty());
compareEvents(events1, events2, false);
} catch (Exception e) {
System.out.println("Failed File: " + file);
// fail("Failed File: " + file + "; " + e.getMessage());
throw new RuntimeException(e);
}
}
}
public void testParserOnCanonical() {
File[] canonicalFiles = getStreamsByExtension(".canonical", false);
assertTrue("No test files found.", canonicalFiles.length > 0);
for (File file : canonicalFiles) {
try {
InputStream input = new FileInputStream(file);
List<Event> events1 = parse(input);
input.close();
assertFalse(events1.isEmpty());
List<Event> events2 = canonicalParse(new FileInputStream(file));
assertFalse(events2.isEmpty());
compareEvents(events1, events2, true);
} catch (Exception e) {
System.out.println("Failed File: " + file);
// fail("Failed File: " + file + "; " + e.getMessage());
throw new RuntimeException(e);
}
}
}
private void compareNodes(Node node1, Node node2) {
assertEquals(node1.getClass(), node2.getClass());
if (node1 instanceof ScalarNode) {
ScalarNode scalar1 = (ScalarNode) node1;
ScalarNode scalar2 = (ScalarNode) node2;
assertEquals(scalar1.getTag(), scalar2.getTag());
assertEquals(scalar1.getValue(), scalar2.getValue());
} else {
if (node1 instanceof SequenceNode) {
SequenceNode seq1 = (SequenceNode) node1;
SequenceNode seq2 = (SequenceNode) node2;
assertEquals(seq1.getTag(), seq2.getTag());
assertEquals(seq1.getValue().size(), seq2.getValue().size());
Iterator<Node> iter2 = seq2.getValue().iterator();
for (Node child1 : seq1.getValue()) {
Node child2 = iter2.next();
compareNodes(child1, child2);
}
} else {
MappingNode seq1 = (MappingNode) node1;
MappingNode seq2 = (MappingNode) node2;
assertEquals(seq1.getTag(), seq2.getTag());
assertEquals(seq1.getValue().size(), seq2.getValue().size());
Iterator<NodeTuple> iter2 = seq2.getValue().iterator();
for (NodeTuple child1 : seq1.getValue()) {
NodeTuple child2 = iter2.next();
compareNodes(child1.getKeyNode(), child2.getKeyNode());
compareNodes(child1.getValueNode(), child2.getValueNode());
}
}
}
}
public void testComposer() {
File[] files = getStreamsByExtension(".data", true);
assertTrue("No test files found.", files.length > 0);
for (File file : files) {
try {
InputStream input = new FileInputStream(file);
List<Node> events1 = compose_all(input);
input.close();
int index = file.getAbsolutePath().lastIndexOf('.');
String canonicalName = file.getAbsolutePath().substring(0, index) + ".canonical";
File canonical = new File(canonicalName);
InputStream input2 = new FileInputStream(canonical);
List<Node> events2 = canonical_compose_all(input2);
input2.close();
assertEquals(events1.size(), events2.size());
Iterator<Node> iter1 = events1.iterator();
Iterator<Node> iter2 = events2.iterator();
while (iter1.hasNext()) {
compareNodes(iter1.next(), iter2.next());
}
} catch (Exception e) {
System.out.println("Failed File: " + file);
// fail("Failed File: " + file + "; " + e.getMessage());
throw new RuntimeException(e);
}
}
}
private List<Node> compose_all(InputStream file) {
Composer composer = new Composer(new ParserImpl(new StreamReader(new UnicodeReader(file))),
new Resolver());
List<Node> documents = new ArrayList<Node>();
while (composer.checkNode()) {
documents.add(composer.getNode());
}
return documents;
}
private List<Node> canonical_compose_all(InputStream file) {
StreamReader reader = new StreamReader(new UnicodeReader(file));
StringBuilder buffer = new StringBuilder();
while (reader.peek() != '\0') {
buffer.append(reader.peek());
reader.forward();
}
CanonicalParser parser = new CanonicalParser(buffer.toString());
Composer composer = new Composer(parser, new Resolver());
List<Node> documents = new ArrayList<Node>();
while (composer.checkNode()) {
documents.add(composer.getNode());
}
return documents;
}
class CanonicalLoader extends Yaml {
public CanonicalLoader() {
super(new MyConstructor());
}
@Override
public Iterable<Object> loadAll(Reader yaml) {
StreamReader reader = new StreamReader(yaml);
StringBuilder buffer = new StringBuilder();
while (reader.peek() != '\0') {
buffer.append(reader.peek());
reader.forward();
}
CanonicalParser parser = new CanonicalParser(buffer.toString());
Composer composer = new Composer(parser, resolver);
this.constructor.setComposer(composer);
Iterator<Object> result = new Iterator<Object>() {
public boolean hasNext() {
return constructor.checkData();
}
public Object next() {
return constructor.getData();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
return new YamlIterable(result);
}
private class YamlIterable implements Iterable<Object> {
private Iterator<Object> iterator;
public YamlIterable(Iterator<Object> iterator) {
this.iterator = iterator;
}
public Iterator<Object> iterator() {
return iterator;
}
}
}
private class MyConstructor extends Constructor {
public MyConstructor() {
this.yamlConstructors.put(null, new ConstructUndefined());
}
private class ConstructUndefined extends AbstractConstruct {
public Object construct(Node node) {
return constructScalar((ScalarNode) node);
}
}
}
public void testConstructor() {
File[] files = getStreamsByExtension(".data", true);
assertTrue("No test files found.", files.length > 0);
Yaml myYaml = new Yaml(new MyConstructor());
Yaml canonicalYaml = new CanonicalLoader();
for (File file : files) {
try {
InputStream input = new FileInputStream(file);
Iterable<Object> documents1 = myYaml.loadAll(input);
int index = file.getAbsolutePath().lastIndexOf('.');
String canonicalName = file.getAbsolutePath().substring(0, index) + ".canonical";
File canonical = new File(canonicalName);
InputStream input2 = new FileInputStream(canonical);
Iterable<Object> documents2 = canonicalYaml.loadAll(input2);
input2.close();
Iterator<Object> iter2 = documents2.iterator();
for (Object object1 : documents1) {
Object object2 = iter2.next();
if (object2 != null) {
assertFalse(System.identityHashCode(object1) == System
.identityHashCode(object2));
}
assertEquals("" + object1, object1, object2);
}
input.close();
} catch (Exception e) {
System.out.println("Failed File: " + file);
// fail("Failed File: " + file + "; " + e.getMessage());
throw new RuntimeException(e);
}
}
}
}
| |
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.pgm;
import static com.google.gerrit.server.schema.DataSourceProvider.Context.MULTI_USER;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.gerrit.common.ChangeHookRunner;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.gerrit.httpd.GerritOptions;
import com.google.gerrit.httpd.GetUserFilter;
import com.google.gerrit.httpd.GitOverHttpModule;
import com.google.gerrit.httpd.H2CacheBasedWebSession;
import com.google.gerrit.httpd.HttpCanonicalWebUrlProvider;
import com.google.gerrit.httpd.RequestContextFilter;
import com.google.gerrit.httpd.WebModule;
import com.google.gerrit.httpd.WebSshGlueModule;
import com.google.gerrit.httpd.auth.oauth.OAuthModule;
import com.google.gerrit.httpd.auth.openid.OpenIdModule;
import com.google.gerrit.httpd.plugins.HttpPluginModule;
import com.google.gerrit.lifecycle.LifecycleManager;
import com.google.gerrit.lucene.LuceneIndexModule;
import com.google.gerrit.pgm.http.jetty.JettyEnv;
import com.google.gerrit.pgm.http.jetty.JettyModule;
import com.google.gerrit.pgm.http.jetty.ProjectQoSFilter;
import com.google.gerrit.pgm.util.ErrorLogFile;
import com.google.gerrit.pgm.util.GarbageCollectionLogFile;
import com.google.gerrit.pgm.util.LogFileCompressor;
import com.google.gerrit.pgm.util.RuntimeShutdown;
import com.google.gerrit.pgm.util.SiteProgram;
import com.google.gerrit.reviewdb.client.AuthType;
import com.google.gerrit.server.account.InternalAccountDirectory;
import com.google.gerrit.server.cache.h2.DefaultCacheFactory;
import com.google.gerrit.server.config.AuthConfig;
import com.google.gerrit.server.config.AuthConfigModule;
import com.google.gerrit.server.config.CanonicalWebUrlModule;
import com.google.gerrit.server.config.CanonicalWebUrlProvider;
import com.google.gerrit.server.config.GerritGlobalModule;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.MasterNodeStartup;
import com.google.gerrit.server.config.RestCacheAdminModule;
import com.google.gerrit.server.contact.ContactStoreModule;
import com.google.gerrit.server.contact.HttpContactStoreConnection;
import com.google.gerrit.server.git.GarbageCollectionRunner;
import com.google.gerrit.server.git.ReceiveCommitsExecutorModule;
import com.google.gerrit.server.git.WorkQueue;
import com.google.gerrit.server.index.DummyIndexModule;
import com.google.gerrit.server.index.IndexModule;
import com.google.gerrit.server.index.IndexModule.IndexType;
import com.google.gerrit.server.mail.SignedTokenEmailTokenVerifier;
import com.google.gerrit.server.mail.SmtpEmailSender;
import com.google.gerrit.server.mime.MimeUtil2Module;
import com.google.gerrit.server.patch.DiffExecutorModule;
import com.google.gerrit.server.plugins.PluginGuiceEnvironment;
import com.google.gerrit.server.plugins.PluginRestApiModule;
import com.google.gerrit.server.schema.DataSourceProvider;
import com.google.gerrit.server.schema.SchemaVersionCheck;
import com.google.gerrit.server.securestore.DefaultSecureStore;
import com.google.gerrit.server.securestore.SecureStore;
import com.google.gerrit.server.securestore.SecureStoreClassName;
import com.google.gerrit.server.securestore.SecureStoreProvider;
import com.google.gerrit.server.ssh.NoSshKeyCache;
import com.google.gerrit.server.ssh.NoSshModule;
import com.google.gerrit.server.ssh.SshAddressesModule;
import com.google.gerrit.solr.SolrIndexModule;
import com.google.gerrit.sshd.SshHostKeyModule;
import com.google.gerrit.sshd.SshKeyCacheImpl;
import com.google.gerrit.sshd.SshModule;
import com.google.gerrit.sshd.commands.DefaultCommandModule;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Stage;
import org.eclipse.jgit.lib.Config;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
/** Run SSH daemon portions of Gerrit. */
public class Daemon extends SiteProgram {
private static final Logger log = LoggerFactory.getLogger(Daemon.class);
@Option(name = "--enable-httpd", usage = "Enable the internal HTTP daemon")
private Boolean httpd;
@Option(name = "--disable-httpd", usage = "Disable the internal HTTP daemon")
void setDisableHttpd(@SuppressWarnings("unused") boolean arg) {
httpd = false;
}
@Option(name = "--enable-sshd", usage = "Enable the internal SSH daemon")
private boolean sshd = true;
@Option(name = "--disable-sshd", usage = "Disable the internal SSH daemon")
void setDisableSshd(@SuppressWarnings("unused") boolean arg) {
sshd = false;
}
@Option(name = "--slave", usage = "Support fetch only")
private boolean slave;
@Option(name = "--console-log", usage = "Log to console (not $site_path/logs)")
private boolean consoleLog;
@Option(name = "-s", usage = "Start interactive shell")
private boolean inspector;
@Option(name = "--run-id", usage = "Cookie to store in $site_path/logs/gerrit.run")
private String runId;
@Option(name = "--headless", usage = "Don't start the UI frontend")
private boolean headless;
@Option(name = "--init", aliases = {"-i"},
usage = "Init site before starting the daemon")
private boolean doInit;
private final LifecycleManager manager = new LifecycleManager();
private Injector dbInjector;
private Injector cfgInjector;
private Injector sysInjector;
private Injector sshInjector;
private Injector webInjector;
private Injector httpdInjector;
private Path runFile;
private boolean test;
private AbstractModule luceneModule;
private Runnable serverStarted;
public Daemon() {
}
@VisibleForTesting
public Daemon(Runnable serverStarted) {
this.serverStarted = serverStarted;
}
public void setEnableHttpd(boolean enable) {
httpd = enable;
}
@Override
public int run() throws Exception {
if (doInit) {
try {
new Init(getSitePath()).run();
} catch (Exception e) {
throw die("Init failed", e);
}
}
mustHaveValidSite();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("Thread " + t.getName() + " threw exception", e);
}
});
if (runId != null) {
runFile = getSitePath().resolve("logs").resolve("gerrit.run");
}
if (httpd == null) {
httpd = !slave;
}
if (!httpd && !sshd) {
throw die("No services enabled, nothing to do");
}
manager.add(GarbageCollectionLogFile.start(getSitePath()));
if (!consoleLog) {
manager.add(ErrorLogFile.start(getSitePath()));
}
try {
start();
RuntimeShutdown.add(new Runnable() {
@Override
public void run() {
log.info("caught shutdown, cleaning up");
if (runId != null) {
try {
Files.delete(runFile);
} catch (IOException err) {
log.warn("failed to delete " + runFile, err);
}
}
manager.stop();
}
});
log.info("Gerrit Code Review " + myVersion() + " ready");
if (runId != null) {
try {
Files.write(runFile, (runId + "\n").getBytes(UTF_8));
runFile.toFile().setReadable(true, false);
} catch (IOException err) {
log.warn("Cannot write --run-id to " + runFile, err);
}
}
if (serverStarted != null) {
serverStarted.run();
}
if (inspector) {
JythonShell shell = new JythonShell();
shell.set("m", manager);
shell.set("ds", dbInjector.getInstance(DataSourceProvider.class));
shell.set("schk", dbInjector.getInstance(SchemaVersionCheck.class));
shell.set("d", this);
shell.run();
} else {
RuntimeShutdown.waitFor();
}
return 0;
} catch (Throwable err) {
log.error("Unable to start daemon", err);
return 1;
}
}
@VisibleForTesting
public LifecycleManager getLifecycleManager() {
return manager;
}
@VisibleForTesting
public void setDatabaseForTesting(List<Module> modules) {
dbInjector = Guice.createInjector(Stage.PRODUCTION, modules);
test = true;
headless = true;
}
@VisibleForTesting
public void setLuceneModule(LuceneIndexModule m) {
luceneModule = m;
test = true;
}
@VisibleForTesting
public void start() {
if (dbInjector == null) {
dbInjector = createDbInjector(MULTI_USER);
}
cfgInjector = createCfgInjector();
sysInjector = createSysInjector();
sysInjector.getInstance(PluginGuiceEnvironment.class)
.setDbCfgInjector(dbInjector, cfgInjector);
manager.add(dbInjector, cfgInjector, sysInjector);
sshd &= !sshdOff();
if (sshd) {
initSshd();
}
if (MoreObjects.firstNonNull(httpd, true)) {
initHttpd();
}
manager.start();
}
@VisibleForTesting
public void stop() {
manager.stop();
}
private boolean sshdOff() {
Config cfg = cfgInjector.getInstance(Key.get(Config.class, GerritServerConfig.class));
return new SshAddressesModule().getListenAddresses(cfg).isEmpty();
}
private String myVersion() {
return com.google.gerrit.common.Version.getVersion();
}
private Injector createCfgInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(new AuthConfigModule());
return dbInjector.createChildInjector(modules);
}
private Injector createSysInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(SchemaVersionCheck.module());
modules.add(new LogFileCompressor.Module());
modules.add(new WorkQueue.Module());
modules.add(new ChangeHookRunner.Module());
modules.add(new ReceiveCommitsExecutorModule());
modules.add(new DiffExecutorModule());
modules.add(new MimeUtil2Module());
modules.add(cfgInjector.getInstance(GerritGlobalModule.class));
modules.add(new InternalAccountDirectory.Module());
modules.add(new DefaultCacheFactory.Module());
modules.add(new SmtpEmailSender.Module());
modules.add(new SignedTokenEmailTokenVerifier.Module());
modules.add(new PluginRestApiModule());
modules.add(new RestCacheAdminModule());
modules.add(createIndexModule());
if (MoreObjects.firstNonNull(httpd, true)) {
modules.add(new CanonicalWebUrlModule() {
@Override
protected Class<? extends Provider<String>> provider() {
return HttpCanonicalWebUrlProvider.class;
}
});
} else {
modules.add(new CanonicalWebUrlModule() {
@Override
protected Class<? extends Provider<String>> provider() {
return CanonicalWebUrlProvider.class;
}
});
}
if (sshd) {
modules.add(SshKeyCacheImpl.module());
} else {
modules.add(NoSshKeyCache.module());
}
if (!slave) {
modules.add(new MasterNodeStartup());
}
modules.add(new AbstractModule() {
@Override
protected void configure() {
bind(GerritOptions.class).toInstance(new GerritOptions(headless, slave));
if (test) {
bind(String.class).annotatedWith(SecureStoreClassName.class)
.toInstance(DefaultSecureStore.class.getName());
bind(SecureStore.class).toProvider(SecureStoreProvider.class);
}
}
});
modules.add(GarbageCollectionRunner.module());
return cfgInjector.createChildInjector(modules);
}
private AbstractModule createIndexModule() {
if (slave) {
return new DummyIndexModule();
}
IndexType indexType = IndexModule.getIndexType(cfgInjector);
switch (indexType) {
case LUCENE:
return luceneModule != null ? luceneModule : new LuceneIndexModule();
case SOLR:
return new SolrIndexModule();
default:
throw new IllegalStateException("unsupported index.type = " + indexType);
}
}
private void initSshd() {
sshInjector = createSshInjector();
sysInjector.getInstance(PluginGuiceEnvironment.class)
.setSshInjector(sshInjector);
manager.add(sshInjector);
}
private Injector createSshInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(sysInjector.getInstance(SshModule.class));
if (!test) {
modules.add(new SshHostKeyModule());
}
modules.add(new DefaultCommandModule(slave));
return sysInjector.createChildInjector(modules);
}
private void initHttpd() {
webInjector = createWebInjector();
sysInjector.getInstance(PluginGuiceEnvironment.class)
.setHttpInjector(webInjector);
sysInjector.getInstance(HttpCanonicalWebUrlProvider.class)
.setHttpServletRequest(
webInjector.getProvider(HttpServletRequest.class));
httpdInjector = createHttpdInjector();
manager.add(webInjector, httpdInjector);
}
private Injector createWebInjector() {
final List<Module> modules = new ArrayList<>();
if (sshd) {
modules.add(new ProjectQoSFilter.Module());
}
modules.add(RequestContextFilter.module());
modules.add(AllRequestFilter.module());
modules.add(H2CacheBasedWebSession.module());
modules.add(HttpContactStoreConnection.module());
modules.add(sysInjector.getInstance(GitOverHttpModule.class));
modules.add(sysInjector.getInstance(WebModule.class));
modules.add(new HttpPluginModule());
modules.add(new ContactStoreModule());
if (sshd) {
modules.add(sshInjector.getInstance(WebSshGlueModule.class));
} else {
modules.add(new NoSshModule());
}
AuthConfig authConfig = cfgInjector.getInstance(AuthConfig.class);
if (authConfig.getAuthType() == AuthType.OPENID ||
authConfig.getAuthType() == AuthType.OPENID_SSO) {
modules.add(new OpenIdModule());
} else if (authConfig.getAuthType() == AuthType.OAUTH) {
modules.add(new OAuthModule());
}
modules.add(sysInjector.getInstance(GetUserFilter.Module.class));
return sysInjector.createChildInjector(modules);
}
private Injector createHttpdInjector() {
final List<Module> modules = new ArrayList<>();
modules.add(new JettyModule(new JettyEnv(webInjector)));
return webInjector.createChildInjector(modules);
}
}
| |
package com.hubspot.baragon.agent;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.github.jknack.handlebars.Handlebars;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.inject.Binder;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.hubspot.baragon.BaragonDataModule;
import com.hubspot.baragon.agent.config.BaragonAgentConfiguration;
import com.hubspot.baragon.agent.config.LoadBalancerConfiguration;
import com.hubspot.baragon.agent.config.TemplateConfiguration;
import com.hubspot.baragon.agent.config.TestingConfiguration;
import com.hubspot.baragon.agent.handlebars.CurrentRackIsPresentHelper;
import com.hubspot.baragon.agent.handlebars.FirstOfHelper;
import com.hubspot.baragon.agent.handlebars.FormatTimestampHelper;
import com.hubspot.baragon.agent.handlebars.IfContainedInHelperSource;
import com.hubspot.baragon.agent.handlebars.IfEqualHelperSource;
import com.hubspot.baragon.agent.handlebars.PreferSameRackWeightingHelper;
import com.hubspot.baragon.agent.handlebars.ResolveHostnameHelper;
import com.hubspot.baragon.agent.handlebars.ToNginxVarHelper;
import com.hubspot.baragon.agent.healthcheck.ConfigChecker;
import com.hubspot.baragon.agent.healthcheck.InternalStateChecker;
import com.hubspot.baragon.agent.healthcheck.LoadBalancerHealthcheck;
import com.hubspot.baragon.agent.healthcheck.ZooKeeperHealthcheck;
import com.hubspot.baragon.agent.lbs.FilesystemConfigHelper;
import com.hubspot.baragon.agent.lbs.LbConfigGenerator;
import com.hubspot.baragon.agent.lbs.LocalLbAdapter;
import com.hubspot.baragon.agent.listeners.DirectoryChangesListener;
import com.hubspot.baragon.agent.listeners.ResyncListener;
import com.hubspot.baragon.agent.managed.BaragonAgentGraphiteReporterManaged;
import com.hubspot.baragon.agent.managed.BootstrapManaged;
import com.hubspot.baragon.agent.managed.LifecycleHelper;
import com.hubspot.baragon.agent.managers.AgentRequestManager;
import com.hubspot.baragon.agent.models.FilePathFormatType;
import com.hubspot.baragon.agent.models.LbConfigTemplate;
import com.hubspot.baragon.agent.resources.BargonAgentResourcesModule;
import com.hubspot.baragon.agent.workers.AgentHeartbeatWorker;
import com.hubspot.baragon.config.AuthConfiguration;
import com.hubspot.baragon.config.HttpClientConfiguration;
import com.hubspot.baragon.config.ZooKeeperConfiguration;
import com.hubspot.baragon.data.BaragonConnectionStateListener;
import com.hubspot.baragon.data.BaragonLoadBalancerDatastore;
import com.hubspot.baragon.models.BaragonAgentEc2Metadata;
import com.hubspot.baragon.models.BaragonAgentMetadata;
import com.hubspot.baragon.models.BaragonAgentState;
import com.hubspot.baragon.models.BasicServiceContext;
import com.hubspot.baragon.utils.JavaUtils;
import com.hubspot.baragon.utils.UpstreamResolver;
import com.hubspot.dropwizard.guicier.DropwizardAwareModule;
import com.hubspot.horizon.HttpConfig;
import com.hubspot.horizon.ning.NingHttpClient;
import io.dropwizard.jetty.HttpConnectorFactory;
import io.dropwizard.server.SimpleServerFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.retry.ExponentialBackoffRetry;
public class BaragonAgentServiceModule
extends DropwizardAwareModule<BaragonAgentConfiguration> {
public static final String AGENT_SCHEDULED_EXECUTOR =
"baragon.service.scheduledExecutor";
public static final String AGENT_LEADER_LATCH = "baragon.agent.leaderLatch";
public static final String AGENT_LOCK = "baragon.agent.lock";
public static final String AGENT_TEMPLATES = "baragon.agent.templates";
public static final String AGENT_MOST_RECENT_REQUEST_ID =
"baragon.agent.mostRecentRequestId";
public static final String AGENT_LOCK_TIMEOUT_MS = "baragon.agent.lock.timeoutMs";
public static final String DEFAULT_TEMPLATE_NAME = "default";
public static final String BARAGON_AGENT_HTTP_CLIENT = "baragon.agent.http.client";
public static final String CONFIG_ERROR_MESSAGE = "baragon.agent.config.error.message";
public static final String LOCAL_STATE_ERROR_MESSAGE =
"baragon.agent.local.state.error.message";
public static final String INTERNAL_STATE_CACHE = "baragon.agent.internal.state.cache";
private static final Pattern FORMAT_PATTERN = Pattern.compile(
"[^%]%([+-]?\\d*.?\\d*)?[sdf]"
);
@Override
public void configure(Binder binder) {
binder.requireExplicitBindings();
binder.requireExactBindingAnnotations();
binder.requireAtInjectOnConstructors();
binder.install(new BaragonDataModule());
binder.install(new BargonAgentResourcesModule());
// Healthchecks
binder.bind(LoadBalancerHealthcheck.class).in(Scopes.SINGLETON);
binder.bind(ZooKeeperHealthcheck.class).in(Scopes.SINGLETON);
binder.bind(ConfigChecker.class).in(Scopes.SINGLETON);
// Managed
binder.bind(BaragonAgentGraphiteReporterManaged.class).asEagerSingleton();
binder.bind(BootstrapManaged.class).asEagerSingleton();
binder.bind(LifecycleHelper.class).asEagerSingleton();
// Manager
binder.bind(AgentRequestManager.class).in(Scopes.SINGLETON);
binder.bind(ResyncListener.class).in(Scopes.SINGLETON);
binder.bind(LocalLbAdapter.class).in(Scopes.SINGLETON);
binder.bind(LbConfigGenerator.class).in(Scopes.SINGLETON);
binder.bind(ServerProvider.class).in(Scopes.SINGLETON);
binder.bind(FilesystemConfigHelper.class).in(Scopes.SINGLETON);
binder.bind(AgentHeartbeatWorker.class).in(Scopes.SINGLETON);
binder.bind(InternalStateChecker.class).in(Scopes.SINGLETON);
binder.bind(DirectoryChangesListener.class).in(Scopes.SINGLETON);
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new GuavaModule());
objectMapper.registerModule(new Jdk8Module());
binder.bind(ObjectMapper.class).toInstance(objectMapper);
}
@Provides
@Singleton
public Handlebars providesHandlebars(
BaragonAgentConfiguration config,
BaragonAgentMetadata agentMetadata,
UpstreamResolver resolver
) {
final Handlebars handlebars = new Handlebars();
handlebars.registerHelper(
FormatTimestampHelper.NAME,
new FormatTimestampHelper(config.getDefaultDateFormat())
);
handlebars.registerHelper(FirstOfHelper.NAME, new FirstOfHelper(""));
handlebars.registerHelper(
CurrentRackIsPresentHelper.NAME,
new CurrentRackIsPresentHelper(agentMetadata.getEc2().getAvailabilityZone())
);
handlebars.registerHelper(
ResolveHostnameHelper.NAME,
new ResolveHostnameHelper(resolver)
);
handlebars.registerHelpers(new PreferSameRackWeightingHelper(config, agentMetadata));
handlebars.registerHelpers(IfEqualHelperSource.class);
handlebars.registerHelpers(IfContainedInHelperSource.class);
handlebars.registerHelper(ToNginxVarHelper.NAME, new ToNginxVarHelper());
return handlebars;
}
@Provides
@Singleton
@Named(AGENT_TEMPLATES)
public Map<String, List<LbConfigTemplate>> providesAgentTemplates(
Handlebars handlebars,
BaragonAgentConfiguration configuration
)
throws Exception {
Map<String, List<LbConfigTemplate>> templates = new HashMap<>();
for (TemplateConfiguration templateConfiguration : configuration.getTemplates()) {
if (!Strings.isNullOrEmpty(templateConfiguration.getDefaultTemplate())) {
if (templates.containsKey(DEFAULT_TEMPLATE_NAME)) {
templates
.get(DEFAULT_TEMPLATE_NAME)
.add(
new LbConfigTemplate(
templateConfiguration.getFilename(),
handlebars.compileInline(templateConfiguration.getDefaultTemplate()),
getFilePathFormatType(templateConfiguration.getFilename())
)
);
} else {
templates.put(
DEFAULT_TEMPLATE_NAME,
Lists.newArrayList(
new LbConfigTemplate(
templateConfiguration.getFilename(),
handlebars.compileInline(templateConfiguration.getDefaultTemplate()),
getFilePathFormatType(templateConfiguration.getFilename())
)
)
);
}
}
if (templateConfiguration.getNamedTemplates() != null) {
for (Map.Entry<String, String> entry : templateConfiguration
.getNamedTemplates()
.entrySet()) {
if (!Strings.isNullOrEmpty(entry.getValue())) {
if (templates.containsKey(entry.getKey())) {
templates
.get(entry.getKey())
.add(
new LbConfigTemplate(
templateConfiguration.getFilename(),
handlebars.compileInline(entry.getValue()),
getFilePathFormatType(templateConfiguration.getFilename())
)
);
} else {
templates.put(
entry.getKey(),
Lists.newArrayList(
new LbConfigTemplate(
templateConfiguration.getFilename(),
handlebars.compileInline(entry.getValue()),
getFilePathFormatType(templateConfiguration.getFilename())
)
)
);
}
}
}
}
}
return templates;
}
private FilePathFormatType getFilePathFormatType(String filenameFormat) {
Matcher m = FORMAT_PATTERN.matcher(filenameFormat);
int count = 0;
while (m.find()) {
count++;
}
if (count == 0) {
return FilePathFormatType.NONE;
} else if (count == 1) {
return FilePathFormatType.SERVICE;
} else {
return FilePathFormatType.DOMAIN_SERVICE;
}
}
@Provides
public LoadBalancerConfiguration provideLoadBalancerInfo(
BaragonAgentConfiguration configuration
) {
return configuration.getLoadBalancerConfiguration();
}
@Provides
public ZooKeeperConfiguration provideZooKeeperConfiguration(
BaragonAgentConfiguration configuration
) {
return configuration.getZooKeeperConfiguration();
}
@Provides
@Named(AGENT_LOCK_TIMEOUT_MS)
public long provideAgentLockTimeoutMs(BaragonAgentConfiguration configuration) {
return configuration.getAgentLockTimeoutMs();
}
@Provides
public AuthConfiguration providesAuthConfiguration(
BaragonAgentConfiguration configuration
) {
return configuration.getAuthConfiguration();
}
@Provides
public HttpClientConfiguration provideHttpClientConfiguration(
BaragonAgentConfiguration configuration
) {
return configuration.getHttpClientConfiguration();
}
@Provides
@Singleton
public BaragonAgentMetadata providesAgentMetadata(BaragonAgentConfiguration config)
throws Exception {
final SimpleServerFactory simpleServerFactory = (SimpleServerFactory) config.getServerFactory();
final HttpConnectorFactory httpFactory = (HttpConnectorFactory) simpleServerFactory.getConnector();
final int httpPort = httpFactory.getPort();
final String hostname = config.getHostname().or(JavaUtils.getHostAddress());
final Optional<String> domain = config.getLoadBalancerConfiguration().getDomain();
final String appRoot = simpleServerFactory.getApplicationContextPath();
final String baseAgentUri = String.format(
config.getBaseUrlTemplate(),
hostname,
httpPort,
appRoot
);
final String agentId = String.format("%s:%s", hostname, httpPort);
return new BaragonAgentMetadata(
baseAgentUri,
agentId,
domain,
BaragonAgentEc2Metadata.fromEnvironment(
config.getPrivateIp(),
config.isSkipPrivateIp()
),
config.getGcloudMetadata(),
config.getExtraAgentData(),
true
);
}
@Provides
@Singleton
@Named(AGENT_LEADER_LATCH)
public LeaderLatch providesAgentLeaderLatch(
BaragonLoadBalancerDatastore loadBalancerDatastore,
BaragonAgentConfiguration config,
BaragonAgentMetadata baragonAgentMetadata
) {
return loadBalancerDatastore.createLeaderLatch(
config.getLoadBalancerConfiguration().getName(),
baragonAgentMetadata
);
}
@Provides
@Singleton
public Optional<TestingConfiguration> providesTestingConfiguration(
BaragonAgentConfiguration configuration
) {
return Optional.fromNullable(configuration.getTestingConfiguration());
}
@Provides
@Singleton
@Named(AGENT_LOCK)
public ReentrantLock providesAgentLock() {
return new ReentrantLock();
}
@Provides
@Singleton
@Named(AGENT_MOST_RECENT_REQUEST_ID)
public AtomicReference<String> providesMostRecentRequestId() {
return new AtomicReference<>();
}
@Provides
@Singleton
@Named(CONFIG_ERROR_MESSAGE)
public AtomicReference<Optional<String>> providesConfigErrorMessage() {
return new AtomicReference<>(Optional.absent());
}
@Provides
@Singleton
@Named(LOCAL_STATE_ERROR_MESSAGE)
public Set<String> providesLocalStateErrorMessage() {
return new HashSet<>();
}
@Provides
@Singleton
@Named(AGENT_SCHEDULED_EXECUTOR)
public ScheduledExecutorService providesScheduledExecutor() {
return Executors.newScheduledThreadPool(4);
}
@Provides
@Singleton
@Named(BARAGON_AGENT_HTTP_CLIENT)
public NingHttpClient providesApacheHttpClient(
HttpClientConfiguration config,
ObjectMapper objectMapper
) {
HttpConfig.Builder configBuilder = HttpConfig
.newBuilder()
.setRequestTimeoutSeconds(config.getRequestTimeoutInMs() / 1000)
.setUserAgent(config.getUserAgent())
.setConnectTimeoutSeconds(config.getConnectionTimeoutInMs() / 1000)
.setFollowRedirects(true)
.setMaxRetries(config.getMaxRequestRetry())
.setObjectMapper(objectMapper);
return new NingHttpClient(configBuilder.build());
}
@Singleton
@Provides
public CuratorFramework provideCurator(
ZooKeeperConfiguration config,
BaragonConnectionStateListener connectionStateListener
) {
CuratorFramework client = CuratorFrameworkFactory.newClient(
config.getQuorum(),
config.getSessionTimeoutMillis(),
config.getConnectTimeoutMillis(),
new ExponentialBackoffRetry(
config.getRetryBaseSleepTimeMilliseconds(),
config.getRetryMaxTries()
)
);
client.getConnectionStateListenable().addListener(connectionStateListener);
client.start();
return client.usingNamespace(config.getZkNamespace());
}
@Singleton
@Provides
public AtomicReference<BaragonAgentState> providesAgentState() {
return new AtomicReference<>(BaragonAgentState.BOOTSTRAPING);
}
@Provides
@Singleton
public UpstreamResolver provideUpstreamResolver(BaragonAgentConfiguration config) {
return new UpstreamResolver(
config.getMaxResolveCacheSize(),
config.getExpireResolveCacheAfterDays()
);
}
@Provides
@Singleton
@Named(INTERNAL_STATE_CACHE)
public Map<String, BasicServiceContext> provideStateCache() {
return new ConcurrentHashMap<>();
}
}
| |
/*
* 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.tomcat.util.net.jsse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CRL;
import java.security.cert.CRLException;
import java.security.cert.CertPathParameters;
import java.security.cert.CertStore;
import java.security.cert.CertStoreParameters;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.X509CertSelector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import javax.net.ssl.CertPathTrustManagerParameters;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
import org.apache.tomcat.util.compat.JreCompat;
import org.apache.tomcat.util.compat.JreVendor;
import org.apache.tomcat.util.file.ConfigFileLoader;
import org.apache.tomcat.util.net.AbstractEndpoint;
import org.apache.tomcat.util.net.Constants;
import org.apache.tomcat.util.net.SSLUtil;
import org.apache.tomcat.util.net.ServerSocketFactory;
import org.apache.tomcat.util.res.StringManager;
/**
* SSL server socket factory. It <b>requires</b> a valid RSA key and
* JSSE.<br>
* keytool -genkey -alias tomcat -keyalg RSA</br>
* Use "changeit" as password (this is the default we use).
*
* @author Harish Prabandham
* @author Costin Manolache
* @author Stefan Freyr Stefansson
* @author EKR -- renamed to JSSESocketFactory
* @author Jan Luehe
* @author Bill Barker
*/
public class JSSESocketFactory implements ServerSocketFactory, SSLUtil {
private static final org.apache.juli.logging.Log log =
org.apache.juli.logging.LogFactory.getLog(JSSESocketFactory.class);
private static final StringManager sm =
StringManager.getManager("org.apache.tomcat.util.net.jsse.res");
// Defaults - made public where re-used
private static final String defaultProtocol = Constants.SSL_PROTO_TLS;
private static final String defaultKeystoreType = "JKS";
private static final String defaultKeystoreFile
= System.getProperty("user.home") + "/.keystore";
private static final int defaultSessionCacheSize = 0;
private static final int defaultSessionTimeout = 86400;
private static final String ALLOW_ALL_SUPPORTED_CIPHERS = "ALL";
public static final String DEFAULT_KEY_PASS = "changeit";
private AbstractEndpoint<?> endpoint;
private final boolean rfc5746Supported;
private final String[] defaultServerProtocols;
private final String[] defaultServerCipherSuites;
protected SSLServerSocketFactory sslProxy = null;
protected String[] enabledCiphers;
protected String[] enabledProtocols;
protected boolean allowUnsafeLegacyRenegotiation = false;
/**
* Flag to state that we require client authentication.
*/
protected boolean requireClientAuth = false;
/**
* Flag to state that we would like client authentication.
*/
protected boolean wantClientAuth = false;
public JSSESocketFactory (AbstractEndpoint<?> endpoint) {
this.endpoint = endpoint;
String sslProtocol = endpoint.getSslProtocol();
if (sslProtocol == null) {
sslProtocol = defaultProtocol;
}
SSLContext context;
try {
context = SSLContext.getInstance(sslProtocol);
context.init(null, null, null);
} catch (NoSuchAlgorithmException e) {
// This is fatal for the connector so throw an exception to prevent
// it from starting
throw new IllegalArgumentException(e);
} catch (KeyManagementException e) {
// This is fatal for the connector so throw an exception to prevent
// it from starting
throw new IllegalArgumentException(e);
}
// Supported cipher suites aren't accessible directly from the
// SSLContext so use the SSL server socket factory
SSLServerSocketFactory ssf = context.getServerSocketFactory();
String supportedCiphers[] = ssf.getSupportedCipherSuites();
boolean found = false;
for (String cipher : supportedCiphers) {
if ("TLS_EMPTY_RENEGOTIATION_INFO_SCSV".equals(cipher)) {
found = true;
break;
}
}
rfc5746Supported = found;
// There is no standard way to determine the default protocols and
// cipher suites so create a server socket to see what the defaults are
SSLServerSocket socket;
try {
socket = (SSLServerSocket) ssf.createServerSocket();
} catch (IOException e) {
// This is very likely to be fatal but there is a slim chance that
// the JSSE implementation just doesn't like creating unbound
// sockets so allow the code to proceed.
defaultServerCipherSuites = new String[0];
defaultServerProtocols = new String[0];
log.warn(sm.getString("jsse.noDefaultCiphers", endpoint.getName()));
log.warn(sm.getString("jsse.noDefaultProtocols", endpoint.getName()));
return;
}
try {
// Many of the default ciphers supported by older JRE versions are
// now considered insecure. This code attempts to filter them out
List<String> filteredCiphers = new ArrayList<String>();
for (String cipher : socket.getEnabledCipherSuites()) {
// Remove export ciphers - FREAK
if (cipher.toUpperCase(Locale.ENGLISH).contains("EXP")) {
log.debug(sm.getString("jsse.excludeDefaultCipher", cipher));
continue;
}
// Remove DES ciphers
if (cipher.toUpperCase(Locale.ENGLISH).contains("_DES_")) {
log.debug(sm.getString("jsse.excludeDefaultCipher", cipher));
continue;
}
// Remove RC4 ciphers
if (cipher.toUpperCase(Locale.ENGLISH).contains("_RC4_")) {
log.debug(sm.getString("jsse.excludeDefaultCipher", cipher));
continue;
}
// Remove DHE ciphers unless running on Java 8 or above
if (!JreCompat.isJre8Available() &&
cipher.toUpperCase(Locale.ENGLISH).contains("_DHE_")) {
log.debug(sm.getString("jsse.excludeDefaultCipher", cipher));
continue;
}
// Remove kRSA ciphers when running on Java 7 or above. Can't
// remove them for Java 6 since they are likely to be the only
// ones left
if (JreCompat.isJre7Available() &&
(cipher.toUpperCase(Locale.ENGLISH).startsWith("TLS_RSA_") ||
cipher.toUpperCase(Locale.ENGLISH).startsWith("SSL_RSA_"))) {
log.debug(sm.getString("jsse.excludeDefaultCipher", cipher));
continue;
}
filteredCiphers.add(cipher);
}
defaultServerCipherSuites = filteredCiphers.toArray(new String[filteredCiphers.size()]);
if (defaultServerCipherSuites.length == 0) {
log.warn(sm.getString("jsse.noDefaultCiphers", endpoint.getName()));
}
// Filter out all the SSL protocols (SSLv2 and SSLv3) from the defaults
// since they are no longer considered secure
List<String> filteredProtocols = new ArrayList<String>();
for (String protocol : socket.getEnabledProtocols()) {
if (protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) {
log.debug(sm.getString("jsse.excludeDefaultProtocol", protocol));
continue;
}
filteredProtocols.add(protocol);
}
defaultServerProtocols = filteredProtocols.toArray(new String[filteredProtocols.size()]);
if (defaultServerProtocols.length == 0) {
log.warn(sm.getString("jsse.noDefaultProtocols", endpoint.getName()));
}
} finally {
try {
socket.close();
} catch (IOException e) {
log.warn(sm.getString("jsse.exceptionOnClose"), e);
}
}
}
@Override
public ServerSocket createSocket (int port)
throws IOException
{
init();
ServerSocket socket = sslProxy.createServerSocket(port);
initServerSocket(socket);
return socket;
}
@Override
public ServerSocket createSocket (int port, int backlog)
throws IOException
{
init();
ServerSocket socket = sslProxy.createServerSocket(port, backlog);
initServerSocket(socket);
return socket;
}
@Override
public ServerSocket createSocket (int port, int backlog,
InetAddress ifAddress)
throws IOException
{
init();
ServerSocket socket = sslProxy.createServerSocket(port, backlog,
ifAddress);
initServerSocket(socket);
return socket;
}
@Override
public Socket acceptSocket(ServerSocket socket)
throws IOException
{
SSLSocket asock = null;
try {
asock = (SSLSocket)socket.accept();
} catch (SSLException e){
throw new SocketException("SSL handshake error" + e.toString());
}
return asock;
}
@Override
public void handshake(Socket sock) throws IOException {
// We do getSession instead of startHandshake() so we can call this multiple times
SSLSession session = ((SSLSocket)sock).getSession();
if (session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL"))
throw new IOException("SSL handshake failed. Ciper suite in SSL Session is SSL_NULL_WITH_NULL_NULL");
if (!allowUnsafeLegacyRenegotiation && !rfc5746Supported) {
// Prevent further handshakes by removing all cipher suites
((SSLSocket) sock).setEnabledCipherSuites(new String[0]);
}
}
@Override
public String[] getEnableableCiphers(SSLContext context) {
String requestedCiphersStr = endpoint.getCiphers();
if (ALLOW_ALL_SUPPORTED_CIPHERS.equals(requestedCiphersStr)) {
return context.getSupportedSSLParameters().getCipherSuites();
}
if ((requestedCiphersStr == null)
|| (requestedCiphersStr.trim().length() == 0)) {
return defaultServerCipherSuites;
}
List<String> requestedCiphers = new ArrayList<String>();
for (String rc : requestedCiphersStr.split(",")) {
final String cipher = rc.trim();
if (cipher.length() > 0) {
requestedCiphers.add(cipher);
}
}
if (requestedCiphers.isEmpty()) {
return defaultServerCipherSuites;
}
List<String> ciphers = new ArrayList<String>(requestedCiphers);
String[] supportedCipherSuiteArray = context.getSupportedSSLParameters().getCipherSuites();
// The IBM JRE will accept cipher suites names SSL_xxx or TLS_xxx but
// only returns the SSL_xxx form for supported cipher suites. Therefore
// need to filter the requested cipher suites using both forms with an
// IBM JRE.
List<String> supportedCipherSuiteList;
if (JreVendor.IS_IBM_JVM) {
supportedCipherSuiteList = new ArrayList<String>(supportedCipherSuiteArray.length * 2);
for (String name : supportedCipherSuiteArray) {
supportedCipherSuiteList.add(name);
if (name.startsWith("SSL")) {
supportedCipherSuiteList.add("TLS" + name.substring(3));
}
}
} else {
supportedCipherSuiteList = Arrays.asList(supportedCipherSuiteArray);
}
ciphers.retainAll(supportedCipherSuiteList);
if (ciphers.isEmpty()) {
log.warn(sm.getString("jsse.requested_ciphers_not_supported",
requestedCiphersStr));
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("jsse.enableable_ciphers", ciphers));
if (ciphers.size() != requestedCiphers.size()) {
List<String> skipped = new ArrayList<String>(requestedCiphers);
skipped.removeAll(ciphers);
log.debug(sm.getString("jsse.unsupported_ciphers", skipped));
}
}
return ciphers.toArray(new String[ciphers.size()]);
}
/*
* Gets the SSL server's keystore password.
*/
protected String getKeystorePassword() {
String keystorePass = endpoint.getKeystorePass();
if (keystorePass == null) {
keystorePass = endpoint.getKeyPass();
}
if (keystorePass == null) {
keystorePass = DEFAULT_KEY_PASS;
}
return keystorePass;
}
/*
* Gets the SSL server's keystore.
*/
protected KeyStore getKeystore(String type, String provider, String pass)
throws IOException {
String keystoreFile = endpoint.getKeystoreFile();
if (keystoreFile == null)
keystoreFile = defaultKeystoreFile;
return getStore(type, provider, keystoreFile, pass);
}
/*
* Gets the SSL server's truststore.
*/
protected KeyStore getTrustStore(String keystoreType,
String keystoreProvider) throws IOException {
KeyStore trustStore = null;
String truststoreFile = endpoint.getTruststoreFile();
if(truststoreFile == null) {
truststoreFile = System.getProperty("javax.net.ssl.trustStore");
}
if(log.isDebugEnabled()) {
log.debug("Truststore = " + truststoreFile);
}
String truststorePassword = endpoint.getTruststorePass();
if( truststorePassword == null) {
truststorePassword =
System.getProperty("javax.net.ssl.trustStorePassword");
}
if(log.isDebugEnabled()) {
log.debug("TrustPass = " + truststorePassword);
}
String truststoreType = endpoint.getTruststoreType();
if( truststoreType == null) {
truststoreType = System.getProperty("javax.net.ssl.trustStoreType");
}
if(truststoreType == null) {
truststoreType = keystoreType;
}
if(log.isDebugEnabled()) {
log.debug("trustType = " + truststoreType);
}
String truststoreProvider = endpoint.getTruststoreProvider();
if( truststoreProvider == null) {
truststoreProvider =
System.getProperty("javax.net.ssl.trustStoreProvider");
}
if (truststoreProvider == null) {
truststoreProvider = keystoreProvider;
}
if(log.isDebugEnabled()) {
log.debug("trustProvider = " + truststoreProvider);
}
if (truststoreFile != null){
try {
trustStore = getStore(truststoreType, truststoreProvider,
truststoreFile, truststorePassword);
} catch (IOException ioe) {
Throwable cause = ioe.getCause();
if (cause instanceof UnrecoverableKeyException) {
// Log a warning we had a password issue
log.warn(sm.getString("jsse.invalid_truststore_password"),
cause);
// Re-try
trustStore = getStore(truststoreType, truststoreProvider,
truststoreFile, null);
} else {
// Something else went wrong - re-throw
throw ioe;
}
}
}
return trustStore;
}
/*
* Gets the key- or truststore with the specified type, path, and password.
*/
private KeyStore getStore(String type, String provider, String path,
String pass) throws IOException {
KeyStore ks = null;
InputStream istream = null;
try {
if (provider == null) {
ks = KeyStore.getInstance(type);
} else {
ks = KeyStore.getInstance(type, provider);
}
if(!("PKCS11".equalsIgnoreCase(type) ||
"".equalsIgnoreCase(path))) {
istream = ConfigFileLoader.getInputStream(path);
}
char[] storePass = null;
if (pass != null && !"".equals(pass)) {
storePass = pass.toCharArray();
}
ks.load(istream, storePass);
} catch (FileNotFoundException fnfe) {
log.error(sm.getString("jsse.keystore_load_failed", type, path,
fnfe.getMessage()), fnfe);
throw fnfe;
} catch (IOException ioe) {
// May be expected when working with a trust store
// Re-throw. Caller will catch and log as required
throw ioe;
} catch(Exception ex) {
String msg = sm.getString("jsse.keystore_load_failed", type, path,
ex.getMessage());
log.error(msg, ex);
throw new IOException(msg);
} finally {
if (istream != null) {
try {
istream.close();
} catch (IOException ioe) {
// Do nothing
}
}
}
return ks;
}
/**
* Reads the keystore and initializes the SSL socket factory.
*/
void init() throws IOException {
try {
String clientAuthStr = endpoint.getClientAuth();
if("true".equalsIgnoreCase(clientAuthStr) ||
"yes".equalsIgnoreCase(clientAuthStr)) {
requireClientAuth = true;
} else if("want".equalsIgnoreCase(clientAuthStr)) {
wantClientAuth = true;
}
SSLContext context = createSSLContext();
context.init(getKeyManagers(), getTrustManagers(), null);
// Configure SSL session cache
SSLSessionContext sessionContext =
context.getServerSessionContext();
if (sessionContext != null) {
configureSessionContext(sessionContext);
}
// create proxy
sslProxy = context.getServerSocketFactory();
// Determine which cipher suites to enable
enabledCiphers = getEnableableCiphers(context);
enabledProtocols = getEnableableProtocols(context);
allowUnsafeLegacyRenegotiation = "true".equals(
endpoint.getAllowUnsafeLegacyRenegotiation());
// Check the SSL config is OK
checkConfig();
} catch(Exception e) {
if( e instanceof IOException )
throw (IOException)e;
throw new IOException(e.getMessage(), e);
}
}
@Override
public SSLContext createSSLContext() throws Exception {
// SSL protocol variant (e.g., TLS, SSL v3, etc.)
String protocol = endpoint.getSslProtocol();
if (protocol == null) {
protocol = defaultProtocol;
}
SSLContext context = SSLContext.getInstance(protocol);
return context;
}
@Override
public KeyManager[] getKeyManagers() throws Exception {
String keystoreType = endpoint.getKeystoreType();
if (keystoreType == null) {
keystoreType = defaultKeystoreType;
}
String algorithm = endpoint.getAlgorithm();
if (algorithm == null) {
algorithm = KeyManagerFactory.getDefaultAlgorithm();
}
return getKeyManagers(keystoreType, endpoint.getKeystoreProvider(),
algorithm, endpoint.getKeyAlias());
}
@Override
public TrustManager[] getTrustManagers() throws Exception {
String truststoreType = endpoint.getTruststoreType();
if (truststoreType == null) {
truststoreType = System.getProperty("javax.net.ssl.trustStoreType");
}
if (truststoreType == null) {
truststoreType = endpoint.getKeystoreType();
}
if (truststoreType == null) {
truststoreType = defaultKeystoreType;
}
String algorithm = endpoint.getTruststoreAlgorithm();
if (algorithm == null) {
algorithm = TrustManagerFactory.getDefaultAlgorithm();
}
return getTrustManagers(truststoreType, endpoint.getKeystoreProvider(),
algorithm);
}
@Override
public void configureSessionContext(SSLSessionContext sslSessionContext) {
int sessionCacheSize;
if (endpoint.getSessionCacheSize() != null) {
sessionCacheSize = Integer.parseInt(
endpoint.getSessionCacheSize());
} else {
sessionCacheSize = defaultSessionCacheSize;
}
int sessionTimeout;
if (endpoint.getSessionTimeout() != null) {
sessionTimeout = Integer.parseInt(endpoint.getSessionTimeout());
} else {
sessionTimeout = defaultSessionTimeout;
}
sslSessionContext.setSessionCacheSize(sessionCacheSize);
sslSessionContext.setSessionTimeout(sessionTimeout);
}
/**
* Gets the initialized key managers.
*/
protected KeyManager[] getKeyManagers(String keystoreType,
String keystoreProvider,
String algorithm,
String keyAlias)
throws Exception {
KeyManager[] kms = null;
String keystorePass = getKeystorePassword();
KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
throw new IOException(
sm.getString("jsse.alias_no_key_entry", keyAlias));
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
String keyPass = endpoint.getKeyPass();
if (keyPass == null) {
keyPass = keystorePass;
}
kmf.init(ks, keyPass.toCharArray());
kms = kmf.getKeyManagers();
if (keyAlias != null) {
String alias = keyAlias;
if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
alias = alias.toLowerCase(Locale.ENGLISH);
}
for(int i=0; i<kms.length; i++) {
kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias);
}
}
return kms;
}
/**
* Gets the initialized trust managers.
*/
protected TrustManager[] getTrustManagers(String keystoreType,
String keystoreProvider, String algorithm)
throws Exception {
String crlf = endpoint.getCrlFile();
String className = endpoint.getTrustManagerClassName();
if(className != null && className.length() > 0) {
ClassLoader classLoader = getClass().getClassLoader();
Class<?> clazz = classLoader.loadClass(className);
if(!(TrustManager.class.isAssignableFrom(clazz))){
throw new InstantiationException(sm.getString(
"jsse.invalidTrustManagerClassName", className));
}
Object trustManagerObject = clazz.newInstance();
TrustManager trustManager = (TrustManager) trustManagerObject;
return new TrustManager[]{ trustManager };
}
TrustManager[] tms = null;
KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider);
if (trustStore != null || endpoint.getTrustManagerClassName() != null) {
if (crlf == null) {
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(algorithm);
tmf.init(trustStore);
tms = tmf.getTrustManagers();
} else {
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(algorithm);
CertPathParameters params =
getParameters(algorithm, crlf, trustStore);
ManagerFactoryParameters mfp =
new CertPathTrustManagerParameters(params);
tmf.init(mfp);
tms = tmf.getTrustManagers();
}
}
return tms;
}
/**
* Return the initialization parameters for the TrustManager.
* Currently, only the default <code>PKIX</code> is supported.
*
* @param algorithm The algorithm to get parameters for.
* @param crlf The path to the CRL file.
* @param trustStore The configured TrustStore.
* @return The parameters including the CRLs and TrustStore.
*/
protected CertPathParameters getParameters(String algorithm,
String crlf,
KeyStore trustStore)
throws Exception {
CertPathParameters params = null;
if("PKIX".equalsIgnoreCase(algorithm)) {
PKIXBuilderParameters xparams =
new PKIXBuilderParameters(trustStore, new X509CertSelector());
Collection<? extends CRL> crls = getCRLs(crlf);
CertStoreParameters csp = new CollectionCertStoreParameters(crls);
CertStore store = CertStore.getInstance("Collection", csp);
xparams.addCertStore(store);
xparams.setRevocationEnabled(true);
String trustLength = endpoint.getTrustMaxCertLength();
if(trustLength != null) {
try {
xparams.setMaxPathLength(Integer.parseInt(trustLength));
} catch(Exception ex) {
log.warn("Bad maxCertLength: "+trustLength);
}
}
params = xparams;
} else {
throw new CRLException("CRLs not supported for type: "+algorithm);
}
return params;
}
/**
* Load the collection of CRLs.
*
*/
protected Collection<? extends CRL> getCRLs(String crlf)
throws IOException, CRLException, CertificateException {
Collection<? extends CRL> crls = null;
InputStream is = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
is = ConfigFileLoader.getInputStream(crlf);
crls = cf.generateCRLs(is);
} catch(IOException iex) {
throw iex;
} catch(CRLException crle) {
throw crle;
} catch(CertificateException ce) {
throw ce;
} finally {
if(is != null) {
try{
is.close();
} catch(Exception ex) {
// Ignore
}
}
}
return crls;
}
@Override
public String[] getEnableableProtocols(SSLContext context) {
String[] requestedProtocols = endpoint.getSslEnabledProtocolsArray();
if ((requestedProtocols == null) || (requestedProtocols.length == 0)) {
return defaultServerProtocols;
}
List<String> protocols = new ArrayList<String>(
Arrays.asList(requestedProtocols));
protocols.retainAll(Arrays.asList(context.getSupportedSSLParameters()
.getProtocols()));
if (protocols.isEmpty()) {
log.warn(sm.getString("jsse.requested_protocols_not_supported",
Arrays.asList(requestedProtocols)));
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("jsse.enableable_protocols", protocols));
if (protocols.size() != requestedProtocols.length) {
List<String> skipped = new ArrayList<String>(
Arrays.asList(requestedProtocols));
skipped.removeAll(protocols);
log.debug(sm.getString("jsse.unsupported_protocols", skipped));
}
}
return protocols.toArray(new String[protocols.size()]);
}
/**
* Configure Client authentication for this version of JSSE. The
* JSSE included in Java 1.4 supports the 'want' value. Prior
* versions of JSSE will treat 'want' as 'false'.
* @param socket the SSLServerSocket
*/
protected void configureClientAuth(SSLServerSocket socket){
if (wantClientAuth){
socket.setWantClientAuth(wantClientAuth);
} else {
socket.setNeedClientAuth(requireClientAuth);
}
}
/**
* Configures SSLEngine to honor cipher suites ordering based upon
* endpoint configuration.
*
* @throws InvalidAlgorithmParameterException If the runtime JVM doesn't
* support this setting.
*/
protected void configureUseServerCipherSuitesOrder(SSLServerSocket socket) {
String useServerCipherSuitesOrderStr = endpoint
.getUseServerCipherSuitesOrder().trim();
// Only use this feature if the user explicitly requested its use.
if(!"".equals(useServerCipherSuitesOrderStr)) {
boolean useServerCipherSuitesOrder =
("true".equalsIgnoreCase(useServerCipherSuitesOrderStr)
|| "yes".equalsIgnoreCase(useServerCipherSuitesOrderStr));
JreCompat jreCompat = JreCompat.getInstance();
jreCompat.setUseServerCipherSuitesOrder(socket, useServerCipherSuitesOrder);
}
}
/**
* Configures the given SSL server socket with the requested cipher suites,
* protocol versions, and need for client authentication
*/
private void initServerSocket(ServerSocket ssocket) {
SSLServerSocket socket = (SSLServerSocket) ssocket;
socket.setEnabledCipherSuites(enabledCiphers);
socket.setEnabledProtocols(enabledProtocols);
// we don't know if client auth is needed -
// after parsing the request we may re-handshake
configureClientAuth(socket);
configureUseServerCipherSuitesOrder(socket);
}
/**
* Checks that the certificate is compatible with the enabled cipher suites.
* If we don't check now, the JIoEndpoint can enter a nasty logging loop.
* See bug 45528.
*/
private void checkConfig() throws IOException {
// Create an unbound server socket
ServerSocket socket = sslProxy.createServerSocket();
initServerSocket(socket);
try {
// Set the timeout to 1ms as all we care about is if it throws an
// SSLException on accept.
socket.setSoTimeout(1);
socket.accept();
// Will never get here - no client can connect to an unbound port
} catch (SSLException ssle) {
// SSL configuration is invalid. Possibly cert doesn't match ciphers
IOException ioe = new IOException(sm.getString(
"jsse.invalid_ssl_conf", ssle.getMessage()));
ioe.initCause(ssle);
throw ioe;
} catch (Exception e) {
/*
* Possible ways of getting here
* socket.accept() throws a SecurityException
* socket.setSoTimeout() throws a SocketException
* socket.accept() throws some other exception (after a JDK change)
* In these cases the test won't work so carry on - essentially
* the behaviour before this patch
* socket.accept() throws a SocketTimeoutException
* In this case all is well so carry on
*/
} finally {
// Should be open here but just in case
if (!socket.isClosed()) {
socket.close();
}
}
}
}
| |
/*
* 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.ignite.schema.model;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.ignite.schema.parser.DbColumn;
import org.apache.ignite.schema.parser.DbTable;
import static java.sql.Types.BIGINT;
import static java.sql.Types.BIT;
import static java.sql.Types.BOOLEAN;
import static java.sql.Types.CHAR;
import static java.sql.Types.CLOB;
import static java.sql.Types.DATE;
import static java.sql.Types.DECIMAL;
import static java.sql.Types.DOUBLE;
import static java.sql.Types.FLOAT;
import static java.sql.Types.INTEGER;
import static java.sql.Types.LONGNVARCHAR;
import static java.sql.Types.LONGVARCHAR;
import static java.sql.Types.NCHAR;
import static java.sql.Types.NCLOB;
import static java.sql.Types.NUMERIC;
import static java.sql.Types.NVARCHAR;
import static java.sql.Types.REAL;
import static java.sql.Types.SMALLINT;
import static java.sql.Types.TIME;
import static java.sql.Types.TIMESTAMP;
import static java.sql.Types.TINYINT;
import static java.sql.Types.VARCHAR;
/**
* Descriptor for java type.
*/
public class PojoDescriptor {
/** Database table. */
private final DbTable tbl;
/** Selected property. */
private final BooleanProperty useProp;
/** Previous name for key class. */
private final String keyClsNamePrev;
/** Key class name to show on screen. */
private final StringProperty keyClsNameProp;
/** Previous name for value class. */
private final String valClsNamePrev;
/** Value class name to show on screen. */
private final StringProperty valClsNameProp;
/** Parent item (schema name). */
private final PojoDescriptor parent;
/** Children items (tables names). */
private Collection<PojoDescriptor> children = Collections.emptyList();
/** Indeterminate state of parent. */
private final BooleanProperty indeterminateProp = new SimpleBooleanProperty(false);
/** Full database name: schema + table. */
private final String fullDbName;
/** Java class fields. */
private final ObservableList<PojoField> fields;
/** Fields map for quick access. */
private final Map<String, PojoField> fieldsMap;
/**
* Constructor of POJO descriptor.
*
* @param prn Parent descriptor.
* @param tbl Database table Tab;e.
*/
public PojoDescriptor(PojoDescriptor prn, DbTable tbl) {
parent = prn;
this.tbl = tbl;
fullDbName = tbl.schema() + "." + tbl.table();
valClsNamePrev = toJavaClassName(tbl.table());
valClsNameProp = new SimpleStringProperty(valClsNamePrev);
keyClsNamePrev = valClsNamePrev.isEmpty() ? "" : valClsNamePrev + "Key";
keyClsNameProp = new SimpleStringProperty(keyClsNamePrev);
Collection<DbColumn> cols = tbl.columns();
List<PojoField> flds = new ArrayList<>(cols.size());
fieldsMap = new HashMap<>(cols.size());
for (DbColumn col : cols) {
String colName = col.name();
PojoField fld = new PojoField(colName, col.type(),
toJavaFieldName(colName), toJavaType(col.type(), col.nullable()).getName(),
col.key(), col.nullable());
fld.owner(this);
flds.add(fld);
fieldsMap.put(colName, fld);
}
fields = FXCollections.observableList(flds);
boolean isTbl = parent != null;
boolean hasKeys = !isTbl || !keyFields().isEmpty();
useProp = new SimpleBooleanProperty(hasKeys);
if (isTbl && !hasKeys && !parent.indeterminateProp.get())
parent.indeterminateProp.set(true);
useProp.addListener(new ChangeListener<Boolean>() {
@Override public void changed(ObservableValue<? extends Boolean> val, Boolean oldVal, Boolean newVal) {
for (PojoDescriptor child : children)
child.useProp.set(newVal);
if (parent != null && !parent.children.isEmpty()) {
Iterator<PojoDescriptor> it = parent.children.iterator();
boolean parentIndeterminate = false;
boolean first = it.next().useProp.get();
while (it.hasNext()) {
if (it.next().useProp.get() != first) {
parentIndeterminate = true;
break;
}
}
parent.indeterminateProp.set(parentIndeterminate);
if (!parentIndeterminate)
parent.useProp.set(first);
}
}
});
}
/**
* @return Parent descriptor.
*/
public PojoDescriptor parent() {
return parent;
}
/**
* @return Full database name: schema + table.
*/
public String fullDbName() {
return fullDbName;
}
/**
* @return {@code true} if POJO descriptor is a table descriptor and checked in GUI.
*/
public boolean checked() {
return parent != null && useProp.get();
}
/**
* @return Boolean property support for {@code use} property.
*/
public BooleanProperty useProperty() {
return useProp;
}
/**
* @return Boolean property support for parent {@code indeterminate} property.
*/
public BooleanProperty indeterminate() {
return indeterminateProp;
}
/**
* @return Key class name.
*/
public String keyClassName() {
return keyClsNameProp.get();
}
/**
* @param name New key class name.
*/
public void keyClassName(String name) {
keyClsNameProp.set(name);
}
/**
* @return Value class name.
*/
public String valueClassName() {
return valClsNameProp.get();
}
/**
* @param name New value class name.
*/
public void valueClassName(String name) {
valClsNameProp.set(name);
}
/**
* @return {@code true} if at least one field checked as "used".
*/
public boolean hasFields() {
for (PojoField field : fields)
if (field.use())
return true;
return false;
}
/**
* @return {@code true} if at least one field checked as "used" and checked as "key".
*/
public boolean hasKeyFields() {
for (PojoField field : fields)
if (field.use() && field.key())
return true;
return false;
}
/**
* @param includeKeys {@code true} if key fields should be included into value class.
* @return {@code true} if at least one field checked as "used" and not checked as "key".
*/
public boolean hasValueFields(boolean includeKeys) {
if (includeKeys)
return hasKeyFields();
for (PojoField field : fields)
if (field.use() && !field.key())
return true;
return false;
}
/**
* @return Collection of key fields.
*/
public Collection<PojoField> keyFields() {
Collection<PojoField> keys = new ArrayList<>();
for (PojoField field : fields)
if (field.use() && field.key() )
keys.add(field);
return keys;
}
/**
* @param includeKeys {@code true} if key fields should be included into value class.
* @return Collection of value fields.
*/
public Collection<PojoField> valueFields(boolean includeKeys) {
Collection<PojoField> vals = new ArrayList<>();
for (PojoField field : fields)
if (field.use() && (includeKeys || !field.key()))
vals.add(field);
return vals;
}
/**
* @return Ascending fields.
*/
public Collection<PojoField> ascendingFields() {
Collection<PojoField> res = new ArrayList<>();
Set<String> asc = tbl.ascendingColumns();
for (PojoField field : fields)
if (field.use() && asc.contains(field.dbName()))
res.add(field);
return res;
}
/**
* @return Descending fields.
*/
public Collection<PojoField> descendingFields() {
Collection<PojoField> res = new ArrayList<>();
Set<String> desc = tbl.descendingColumns();
for (PojoField field : fields)
if (field.use() && desc.contains(field.dbName()))
res.add(field);
return res;
}
/**
* Gets indexes groups.
*
* @return Map with indexes.
*/
public Map<String, Map<String, IndexItem>> groups() {
Map<String, Map<String, Boolean>> idxs = tbl.indexes();
Map<String, Map<String, IndexItem>> groups = new LinkedHashMap<>(idxs.size());
for (Map.Entry<String, Map<String, Boolean>> idx : idxs.entrySet()) {
Map<String, Boolean> idxCols = idx.getValue();
if (idxCols.size() > 1) {
String idxName = idx.getKey();
Map<String, IndexItem> grp = new LinkedHashMap<>();
groups.put(idxName, grp);
for (Map.Entry<String, Boolean> idxCol : idxCols.entrySet()) {
PojoField fld = fieldsMap.get(idxCol.getKey());
grp.put(fld.javaName(), new IndexItem(fld.javaTypeName(), idxCol.getValue()));
}
}
}
return groups;
}
/**
* @return Key class name property.
*/
public StringProperty keyClassNameProperty() {
return keyClsNameProp;
}
/**
* @return Value class name property.
*/
public StringProperty valueClassNameProperty() {
return valClsNameProp;
}
/**
* @return Schema name.
*/
public String schema() {
return tbl.schema();
}
/**
* @return Table name.
*/
public String table() {
return tbl.table();
}
/**
* Sets children items.
*
* @param children Items to set.
*/
public void children(Collection<PojoDescriptor> children) {
this.children = children;
}
/**
* @return {@code true} if descriptor was changed by user via GUI.
*/
public boolean changed() {
if (!keyClsNameProp.get().equals(keyClsNamePrev) || !valClsNameProp.get().equals(valClsNamePrev))
return true;
for (PojoField field : fields)
if (field.changed())
return true;
return false;
}
/**
* Revert changes to key class name made by user.
*/
public void revertKeyClassName() {
keyClsNameProp.set(keyClsNamePrev);
}
/**
* Revert changes to value class name made by user.
*/
public void revertValueClassName() {
valClsNameProp.set(valClsNamePrev);
}
/**
* Revert changes to java names made by user.
*/
public void revertJavaNames() {
for (PojoField field : fields)
field.resetJavaName();
}
/**
* @return Java class fields.
*/
public ObservableList<PojoField> fields() {
return fields;
}
/**
* @param name Source name.
* @return String converted to java class name notation.
*/
private static String toJavaClassName(String name) {
int len = name.length();
StringBuilder buf = new StringBuilder(len);
boolean capitalizeNext = true;
for (int i = 0; i < len; i++) {
char ch = name.charAt(i);
if (Character.isWhitespace(ch) || '_' == ch)
capitalizeNext = true;
else if (capitalizeNext) {
buf.append(Character.toUpperCase(ch));
capitalizeNext = false;
}
else
buf.append(Character.toLowerCase(ch));
}
return buf.toString();
}
/**
* @param name Source name.
* @return String converted to java field name notation.
*/
private static String toJavaFieldName(String name) {
String javaName = toJavaClassName(name);
return Character.toLowerCase(javaName.charAt(0)) + javaName.substring(1);
}
/**
* Convert JDBC data type to java type.
*
* @param type JDBC SQL data type.
* @param nullable {@code true} if {@code NULL} is allowed for this field in database.
* @return Java data type.
*/
private static Class<?> toJavaType(int type, boolean nullable) {
switch (type) {
case BIT:
case BOOLEAN:
return nullable ? Boolean.class : boolean.class;
case TINYINT:
return nullable ? Byte.class : byte.class;
case SMALLINT:
return nullable ? Short.class : short.class;
case INTEGER:
return nullable ? Integer.class : int.class;
case BIGINT:
return nullable ? Long.class : long.class;
case REAL:
return nullable ? Float.class : float.class;
case FLOAT:
case DOUBLE:
return nullable ? Double.class : double.class;
case NUMERIC:
case DECIMAL:
return BigDecimal.class;
case CHAR:
case VARCHAR:
case LONGVARCHAR:
case NCHAR:
case NVARCHAR:
case LONGNVARCHAR:
case CLOB:
case NCLOB:
return String.class;
case DATE:
return java.sql.Date.class;
case TIME:
return java.sql.Time.class;
case TIMESTAMP:
return java.sql.Timestamp.class;
// BINARY, VARBINARY, LONGVARBINARY, ARRAY, BLOB, NULL, DATALINK
// OTHER, JAVA_OBJECT, DISTINCT, STRUCT, REF, ROWID, SQLXML
default:
return Object.class;
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Test that FileLink switches between alternate locations
* when the current location moves or gets deleted.
*/
@Category(MediumTests.class)
public class TestFileLink {
/**
* Test, on HDFS, that the FileLink is still readable
* even when the current file gets renamed.
*/
@Test
public void testHDFSLinkReadDuringRename() throws Exception {
HBaseTestingUtility testUtil = new HBaseTestingUtility();
Configuration conf = testUtil.getConfiguration();
conf.setInt("dfs.blocksize", 1024 * 1024);
conf.setInt("dfs.client.read.prefetch.size", 2 * 1024 * 1024);
testUtil.startMiniDFSCluster(1);
MiniDFSCluster cluster = testUtil.getDFSCluster();
FileSystem fs = cluster.getFileSystem();
assertEquals("hdfs", fs.getUri().getScheme());
try {
testLinkReadDuringRename(fs, testUtil.getDefaultRootDirPath());
} finally {
testUtil.shutdownMiniCluster();
}
}
/**
* Test, on a local filesystem, that the FileLink is still readable
* even when the current file gets renamed.
*/
@Test
public void testLocalLinkReadDuringRename() throws IOException {
HBaseTestingUtility testUtil = new HBaseTestingUtility();
FileSystem fs = testUtil.getTestFileSystem();
assertEquals("file", fs.getUri().getScheme());
testLinkReadDuringRename(fs, testUtil.getDataTestDir());
}
/**
* Test that link is still readable even when the current file gets renamed.
*/
private void testLinkReadDuringRename(FileSystem fs, Path rootDir) throws IOException {
Path originalPath = new Path(rootDir, "test.file");
Path archivedPath = new Path(rootDir, "archived.file");
writeSomeData(fs, originalPath, 256 << 20, (byte)2);
List<Path> files = new ArrayList<Path>();
files.add(originalPath);
files.add(archivedPath);
FileLink link = new FileLink(files);
FSDataInputStream in = link.open(fs);
try {
byte[] data = new byte[8192];
long size = 0;
// Read from origin
int n = in.read(data);
dataVerify(data, n, (byte)2);
size += n;
if (FSUtils.WINDOWS) {
in.close();
}
// Move origin to archive
assertFalse(fs.exists(archivedPath));
fs.rename(originalPath, archivedPath);
assertFalse(fs.exists(originalPath));
assertTrue(fs.exists(archivedPath));
if (FSUtils.WINDOWS) {
in = link.open(fs); // re-read from beginning
in.read(data);
}
// Try to read to the end
while ((n = in.read(data)) > 0) {
dataVerify(data, n, (byte)2);
size += n;
}
assertEquals(256 << 20, size);
} finally {
in.close();
if (fs.exists(originalPath)) fs.delete(originalPath, true);
if (fs.exists(archivedPath)) fs.delete(archivedPath, true);
}
}
/**
* Test that link is still readable even when the current file gets deleted.
*
* NOTE: This test is valid only on HDFS.
* When a file is deleted from a local file-system, it is simply 'unlinked'.
* The inode, which contains the file's data, is not deleted until all
* processes have finished with it.
* In HDFS when the request exceed the cached block locations,
* a query to the namenode is performed, using the filename,
* and the deleted file doesn't exists anymore (FileNotFoundException).
*/
@Test
public void testHDFSLinkReadDuringDelete() throws Exception {
HBaseTestingUtility testUtil = new HBaseTestingUtility();
Configuration conf = testUtil.getConfiguration();
conf.setInt("dfs.blocksize", 1024 * 1024);
conf.setInt("dfs.client.read.prefetch.size", 2 * 1024 * 1024);
testUtil.startMiniDFSCluster(1);
MiniDFSCluster cluster = testUtil.getDFSCluster();
FileSystem fs = cluster.getFileSystem();
assertEquals("hdfs", fs.getUri().getScheme());
try {
List<Path> files = new ArrayList<Path>();
for (int i = 0; i < 3; i++) {
Path path = new Path(String.format("test-data-%d", i));
writeSomeData(fs, path, 1 << 20, (byte)i);
files.add(path);
}
FileLink link = new FileLink(files);
FSDataInputStream in = link.open(fs);
try {
byte[] data = new byte[8192];
int n;
// Switch to file 1
n = in.read(data);
dataVerify(data, n, (byte)0);
fs.delete(files.get(0), true);
skipBuffer(in, (byte)0);
// Switch to file 2
n = in.read(data);
dataVerify(data, n, (byte)1);
fs.delete(files.get(1), true);
skipBuffer(in, (byte)1);
// Switch to file 3
n = in.read(data);
dataVerify(data, n, (byte)2);
fs.delete(files.get(2), true);
skipBuffer(in, (byte)2);
// No more files available
try {
n = in.read(data);
assert(n <= 0);
} catch (FileNotFoundException e) {
assertTrue(true);
}
} finally {
in.close();
}
} finally {
testUtil.shutdownMiniCluster();
}
}
/**
* Write up to 'size' bytes with value 'v' into a new file called 'path'.
*/
private void writeSomeData (FileSystem fs, Path path, long size, byte v) throws IOException {
byte[] data = new byte[4096];
for (int i = 0; i < data.length; i++) {
data[i] = v;
}
FSDataOutputStream stream = fs.create(path);
try {
long written = 0;
while (written < size) {
stream.write(data, 0, data.length);
written += data.length;
}
} finally {
stream.close();
}
}
/**
* Verify that all bytes in 'data' have 'v' as value.
*/
private static void dataVerify(byte[] data, int n, byte v) {
for (int i = 0; i < n; ++i) {
assertEquals(v, data[i]);
}
}
private static void skipBuffer(FSDataInputStream in, byte v) throws IOException {
byte[] data = new byte[8192];
try {
int n;
while ((n = in.read(data)) == data.length) {
for (int i = 0; i < data.length; ++i) {
if (data[i] != v)
throw new Exception("File changed");
}
}
} catch (Exception e) {
}
}
}
| |
package hex.naivebayes;
import hex.*;
import hex.schemas.ModelBuilderSchema;
import hex.schemas.NaiveBayesV3;
import hex.naivebayes.NaiveBayesModel.NaiveBayesOutput;
import hex.naivebayes.NaiveBayesModel.NaiveBayesParameters;
import water.*;
import water.exceptions.H2OModelBuilderIllegalArgumentException;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.ArrayUtils;
import water.util.Log;
import water.util.PrettyPrint;
import water.util.TwoDimTable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Naive Bayes
* This is an algorithm for computing the conditional a-posterior probabilities of a categorical
* response from independent predictors using Bayes rule.
* <a href = "http://en.wikipedia.org/wiki/Naive_Bayes_classifier">Naive Bayes on Wikipedia</a>
* <a href = "http://cs229.stanford.edu/notes/cs229-notes2.pdf">Lecture Notes by Andrew Ng</a>
* @author anqi_fu
*
*/
public class NaiveBayes extends ModelBuilder<NaiveBayesModel,NaiveBayesParameters,NaiveBayesOutput> {
@Override
public ModelBuilderSchema schema() {
return new NaiveBayesV3();
}
public boolean isSupervised(){return true;}
@Override
public Job<NaiveBayesModel> trainModelImpl(long work, boolean restartTimer) {
return start(new NaiveBayesDriver(), work, restartTimer);
}
@Override
public long progressUnits() {
return 6;
}
@Override
public ModelCategory[] can_build() {
return new ModelCategory[]{ ModelCategory.Unknown };
}
@Override public BuilderVisibility builderVisibility() { return BuilderVisibility.Stable; };
@Override
protected void checkMemoryFootPrint() {
// compute memory usage for pcond matrix
long mem_usage = (_train.numCols() - 1) * _train.lastVec().cardinality();
String[][] domains = _train.domains();
long count = 0;
for (int i = 0; i < _train.numCols() - 1; i++) {
count += domains[i] == null ? 2 : domains[i].length;
}
mem_usage *= count;
mem_usage *= 8; //doubles
long max_mem = H2O.SELF.get_max_mem();
if (mem_usage > max_mem) {
String msg = "Conditional probabilities won't fit in the driver node's memory ("
+ PrettyPrint.bytes(mem_usage) + " > " + PrettyPrint.bytes(max_mem)
+ ") - try reducing the number of columns, the number of response classes or the number of categorical factors of the predictors.";
error("_train", msg);
cancel(msg);
}
}
// Called from an http request
public NaiveBayes(NaiveBayesModel.NaiveBayesParameters parms) {
super("NaiveBayes", parms);
init(false);
}
@Override
public void init(boolean expensive) {
super.init(expensive);
if (_response != null) {
if (!_response.isEnum()) error("_response", "Response must be a categorical column");
else if (_response.isConst()) error("_response", "Response must have at least two unique categorical levels");
}
if (_parms._laplace < 0) error("_laplace", "Laplace smoothing must be an integer >= 0");
if (_parms._min_sdev < 1e-10) error("_min_sdev", "Min. standard deviation must be at least 1e-10");
if (_parms._eps_sdev < 0) error("_eps_sdev", "Threshold for standard deviation must be positive");
if (_parms._min_prob < 1e-10) error("_min_prob", "Min. probability must be at least 1e-10");
if (_parms._eps_prob < 0) error("_eps_prob", "Threshold for probability must be positive");
hide("_balance_classes", "Balance classes is not applicable to NaiveBayes.");
hide("_class_sampling_factors", "Class sampling factors is not applicable to NaiveBayes.");
hide("_max_after_balance_size", "Max after balance size is not applicable to NaiveBayes.");
if (expensive && error_count() == 0) checkMemoryFootPrint();
}
private static boolean couldBeBool(Vec v) { return v != null && v.isInt() && v.min()+1==v.max(); }
class NaiveBayesDriver extends H2O.H2OCountedCompleter<NaiveBayesDriver> {
protected NaiveBayesDriver() { super(true); } // bump driver priority
public boolean computeStatsFillModel(NaiveBayesModel model, DataInfo dinfo, NBTask tsk) {
model._output._levels = _response.domain();
model._output._rescnt = tsk._rescnt;
model._output._ncats = dinfo._cats;
if(!isRunning(_key)) return false;
update(1, "Initializing arrays for model statistics");
// String[][] domains = dinfo._adaptedFrame.domains();
String[][] domains = model._output._domains;
double[] apriori = new double[tsk._nrescat];
double[][][] pcond = new double[tsk._npreds][][];
for(int i = 0; i < pcond.length; i++) {
int ncnt = domains[i] == null ? 2 : domains[i].length;
pcond[i] = new double[tsk._nrescat][ncnt];
}
if(!isRunning(_key)) return false;
update(1, "Computing probabilities for categorical cols");
// A-priori probability of response y
for(int i = 0; i < apriori.length; i++)
apriori[i] = ((double)tsk._rescnt[i] + _parms._laplace)/(tsk._nobs + tsk._nrescat * _parms._laplace);
// apriori[i] = tsk._rescnt[i]/tsk._nobs; // Note: R doesn't apply laplace smoothing to priors, even though this is textbook definition
// Probability of categorical predictor x_j conditional on response y
for(int col = 0; col < dinfo._cats; col++) {
assert pcond[col].length == tsk._nrescat;
for(int i = 0; i < pcond[col].length; i++) {
for(int j = 0; j < pcond[col][i].length; j++)
pcond[col][i][j] = ((double)tsk._jntcnt[col][i][j] + _parms._laplace)/((double)tsk._rescnt[i] + domains[col].length * _parms._laplace);
}
}
if(!isRunning(_key)) return false;
update(1, "Computing mean and standard deviation for numeric cols");
// Mean and standard deviation of numeric predictor x_j for every level of response y
for(int col = 0; col < dinfo._nums; col++) {
for(int i = 0; i < pcond[0].length; i++) {
int cidx = dinfo._cats + col;
double num = tsk._rescnt[i];
double pmean = tsk._jntsum[col][i][0]/num;
pcond[cidx][i][0] = pmean;
// double pvar = tsk._jntsum[col][i][1]/num - pmean * pmean;
double pvar = tsk._jntsum[col][i][1]/(num - 1) - pmean * pmean * num/(num - 1);
pcond[cidx][i][1] = Math.sqrt(pvar);
}
}
model._output._apriori_raw = apriori;
model._output._pcond_raw = pcond;
// Create table of conditional probabilities for every predictor
model._output._pcond = new TwoDimTable[pcond.length];
String[] rowNames = _response.domain();
for(int col = 0; col < dinfo._cats; col++) {
String[] colNames = _train.vec(col).domain();
String[] colTypes = new String[colNames.length];
String[] colFormats = new String[colNames.length];
Arrays.fill(colTypes, "double");
Arrays.fill(colFormats, "%5f");
model._output._pcond[col] = new TwoDimTable(_train.name(col), null, rowNames, colNames, colTypes, colFormats,
"Y_by_" + _train.name(col), new String[rowNames.length][], pcond[col]);
}
for(int col = 0; col < dinfo._nums; col++) {
int cidx = dinfo._cats + col;
model._output._pcond[cidx] = new TwoDimTable(_train.name(cidx), null, rowNames, new String[] {"Mean", "Std_Dev"},
new String[] {"double", "double"}, new String[] {"%5f", "%5f"}, "Y_by_" + _train.name(cidx),
new String[rowNames.length][], pcond[cidx]);
}
// Create table of a-priori probabilities for the response
String[] colTypes = new String[_response.cardinality()];
String[] colFormats = new String[_response.cardinality()];
Arrays.fill(colTypes, "double");
Arrays.fill(colFormats, "%5f");
model._output._apriori = new TwoDimTable("A Priori Response Probabilities", null, new String[1], _response.domain(), colTypes, colFormats, "",
new String[1][], new double[][] {apriori});
model._output._model_summary = createModelSummaryTable(model._output);
if(!isRunning(_key)) return false;
update(1, "Scoring and computing metrics on training data");
if (_parms._compute_metrics) {
model.score(_parms.train()).delete(); // This scores on the training data and appends a ModelMetrics
ModelMetricsSupervised mm = DKV.getGet(model._output._model_metrics[model._output._model_metrics.length - 1]);
model._output._training_metrics = mm;
}
// At the end: validation scoring (no need to gather scoring history)
if(!isRunning(_key)) return false;
update(1, "Scoring and computing metrics on validation data");
if (_valid != null) {
Frame pred = model.score(_parms.valid()); //this appends a ModelMetrics on the validation set
model._output._validation_metrics = DKV.getGet(model._output._model_metrics[model._output._model_metrics.length - 1]);
pred.delete();
}
return true;
}
@Override protected void compute2() {
NaiveBayesModel model = null;
DataInfo dinfo = null;
try {
init(true); // Initialize parameters
_parms.read_lock_frames(NaiveBayes.this); // Fetch & read-lock input frames
if (error_count() > 0) throw H2OModelBuilderIllegalArgumentException.makeFromBuilder(NaiveBayes.this);
dinfo = new DataInfo(Key.make(), _train, _valid, 1, false, DataInfo.TransformType.NONE, DataInfo.TransformType.NONE, true, false, false, false, false, false);
// The model to be built
model = new NaiveBayesModel(dest(), _parms, new NaiveBayesOutput(NaiveBayes.this));
model.delete_and_lock(_key);
_train.read_lock(_key);
update(1, "Begin distributed Naive Bayes calculation");
NBTask tsk = new NBTask(_key, dinfo, _response.cardinality()).doAll(dinfo._adaptedFrame);
if (computeStatsFillModel(model, dinfo, tsk))
model.update(_key);
done();
} catch (Throwable t) {
Job thisJob = DKV.getGet(_key);
if (thisJob._state == JobState.CANCELLED) {
Log.info("Job cancelled by user.");
} else {
t.printStackTrace();
failed(t);
throw t;
}
} finally {
updateModelOutput();
_train.unlock(_key);
if (model != null) model.unlock(_key);
if (dinfo != null) dinfo.remove();
_parms.read_unlock_frames(NaiveBayes.this);
}
tryComplete();
}
}
private TwoDimTable createModelSummaryTable(NaiveBayesOutput output) {
List<String> colHeaders = new ArrayList<>();
List<String> colTypes = new ArrayList<>();
List<String> colFormat = new ArrayList<>();
colHeaders.add("Number of Response Levels"); colTypes.add("long"); colFormat.add("%d");
colHeaders.add("Min Apriori Probability"); colTypes.add("double"); colFormat.add("%.5f");
colHeaders.add("Max Apriori Probability"); colTypes.add("double"); colFormat.add("%.5f");
double apriori_min = output._apriori_raw[0];
double apriori_max = output._apriori_raw[0];
for(int i = 1; i < output._apriori_raw.length; i++) {
if(output._apriori_raw[i] < apriori_min) apriori_min = output._apriori_raw[i];
else if(output._apriori_raw[i] > apriori_max) apriori_max = output._apriori_raw[i];
}
final int rows = 1;
TwoDimTable table = new TwoDimTable(
"Model Summary", null,
new String[rows],
colHeaders.toArray(new String[0]),
colTypes.toArray(new String[0]),
colFormat.toArray(new String[0]),
"");
int row = 0;
int col = 0;
table.set(row, col++, output._apriori_raw.length);
table.set(row, col++, apriori_min);
table.set(row, col++, apriori_max);
return table;
}
// Note: NA handling differs from R for efficiency purposes
// R's method: For each predictor x_j, skip counting that row for p(x_j|y) calculation if x_j = NA.
// If response y = NA, skip counting row entirely in all calculations
// H2O's method: Just skip all rows where any x_j = NA or y = NA. Should be more memory-efficient, but results incomparable with R.
private static class NBTask extends MRTask<NBTask> {
final protected Key _jobKey;
final DataInfo _dinfo;
final String[][] _domains; // Domains of the training frame
final int _nrescat; // Number of levels for the response y
final int _npreds; // Number of predictors in the training frame
public int _nobs; // Number of rows counted in calculation
public int[/*nrescat*/] _rescnt; // Count of each level in the response
public int[/*npreds*/][/*nrescat*/][] _jntcnt; // For each categorical predictor, joint count of response and predictor levels
public double[/*npreds*/][/*nrescat*/][] _jntsum; // For each numeric predictor, sum and squared sum of entries for every response level
public NBTask(Key jobKey, DataInfo dinfo, int nres) {
_jobKey = jobKey;
_dinfo = dinfo;
_nrescat = nres;
_domains = dinfo._adaptedFrame.domains();
_npreds = dinfo._adaptedFrame.numCols()-1;
assert _npreds == dinfo._nums + dinfo._cats;
assert _nrescat == _domains[_npreds].length; // Response in last vec of adapted frame
}
@Override public void map(Chunk[] chks) {
if(_jobKey != null && !isRunning(_jobKey)) {
throw new JobCancelledException();
}
_nobs = 0;
_rescnt = new int[_nrescat];
if(_dinfo._cats > 0) {
_jntcnt = new int[_dinfo._cats][][];
for (int i = 0; i < _dinfo._cats; i++) {
_jntcnt[i] = new int[_nrescat][_domains[i].length];
}
}
if(_dinfo._nums > 0) {
_jntsum = new double[_dinfo._nums][][];
for (int i = 0; i < _dinfo._nums; i++) {
_jntsum[i] = new double[_nrescat][2];
}
}
Chunk res = chks[_npreds]; // Response at the end
OUTER:
for(int row = 0; row < chks[0]._len; row++) {
// Skip row if any entries in it are NA
for(int col = 0; col < chks.length; col++) {
if(Double.isNaN(chks[col].atd(row))) continue OUTER;
}
// Record joint counts of categorical predictors and response
int rlevel = (int)res.atd(row);
for(int col = 0; col < _dinfo._cats; col++) {
int plevel = (int)chks[col].atd(row);
_jntcnt[col][rlevel][plevel]++;
}
// Record sum for each pair of numerical predictors and response
for(int col = 0; col < _dinfo._nums; col++) {
int cidx = _dinfo._cats + col;
double x = chks[cidx].atd(row);
_jntsum[col][rlevel][0] += x;
_jntsum[col][rlevel][1] += x*x;
}
_rescnt[rlevel]++;
_nobs++;
}
}
@Override public void reduce(NBTask nt) {
_nobs += nt._nobs;
ArrayUtils.add(_rescnt, nt._rescnt);
if(null != _jntcnt) {
for (int col = 0; col < _jntcnt.length; col++)
ArrayUtils.add(_jntcnt[col], nt._jntcnt[col]);
}
if(null != _jntsum) {
for (int col = 0; col < _jntsum.length; col++)
ArrayUtils.add(_jntsum[col], nt._jntsum[col]);
}
}
}
}
| |
/*
* Copyright 2014 Niek Haarman
*
* 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.nhaarman.listviewanimations.itemmanipulation.swipedismiss;
import android.support.annotation.NonNull;
import android.test.ActivityInstrumentationTestCase2;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import com.nhaarman.listviewanimations.util.AbsListViewWrapper;
import java.util.List;
import static com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.MotionEventUtils.dispatchSwipeMotionEventsAndWait;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@SuppressWarnings({"AnonymousInnerClass", "AnonymousInnerClassMayBeStatic"})
public class SwipeTouchListenerTest extends ActivityInstrumentationTestCase2<SwipeTouchListenerTestActivity> {
/**
* The SwipeTouchListener under test.
*/
private TestSwipeTouchListener mSwipeTouchListener;
/**
* An Activity hosting a ListView with items.
*/
private SwipeTouchListenerTestActivity mActivity;
/**
* The AbsListView that is hosted in mActivity.
*/
private AbsListView mAbsListView;
/**
* The width of the AbsListView.
*/
private float mViewWidth;
public SwipeTouchListenerTest() {
super(SwipeTouchListenerTestActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
mActivity = getActivity();
mAbsListView = mActivity.getAbsListView();
mViewWidth = mAbsListView.getWidth();
mSwipeTouchListener = new TestSwipeTouchListener(new AbsListViewWrapper(mAbsListView));
mAbsListView.setOnTouchListener(mSwipeTouchListener);
getInstrumentation().waitForIdleSync();
}
/**
* Tests whether retrieving the AbsListView yields the original AbsListView that was set.
*/
public void testAbsListViewSet() {
assertThat(mSwipeTouchListener.getListViewWrapper().getListView(), is((ViewGroup) mAbsListView));
}
/**
* Tests whether swiping the first View triggers a call to SwipeTouchListener#afterViewFling.
*/
public void testSwipeFirstViewCallback() throws InterruptedException {
dispatchSwipeMotionEventsAndWait(mActivity, mAbsListView, 0);
assertThat(mSwipeTouchListener.afterViewFlingCalled, is(true));
assertThat(mSwipeTouchListener.position, is(0));
}
/**
* Tests whether swiping the first View from right to left triggers a call to SwipeTouchListener#afterViewFling.
*/
public void testReverseSwipeFirstViewCallback() throws InterruptedException {
MotionEventUtils.dispatchReverseSwipeMotionEventsAndWait(mActivity, mAbsListView, 0);
assertThat(mSwipeTouchListener.afterViewFlingCalled, is(true));
assertThat(mSwipeTouchListener.position, is(0));
}
/**
* Tests whether swiping the last View triggers a call to SwipeTouchListener#afterViewFling.
*/
public void testSwipeLastViewCallback() throws InterruptedException {
dispatchSwipeMotionEventsAndWait(mActivity, mAbsListView, mAbsListView.getLastVisiblePosition());
assertThat(mSwipeTouchListener.afterViewFlingCalled, is(true));
assertThat(mSwipeTouchListener.position, is(mAbsListView.getLastVisiblePosition()));
}
/**
* Tests whether swiping shorter than half of the view width doesn't trigger a call to SwipeTouchLister#afterViewFling.
*/
public void testShortSwipe() throws InterruptedException {
List<MotionEvent> motionEvents = MotionEventUtils.createMotionEvents(mAbsListView, 0, 10, mViewWidth / 2 - mViewWidth / 10);
MotionEventUtils.dispatchMotionEventsAndWait(mActivity, mAbsListView, motionEvents);
assertThat(mSwipeTouchListener.afterViewFlingCalled, is(false));
}
/**
* Tests whether swiping shorter than half of the view width from right to left doesn't trigger a call to SwipeTouchLister#afterViewFling.
*/
public void testReverseShortSwipe() throws InterruptedException {
List<MotionEvent> motionEvents = MotionEventUtils.createMotionEvents(mAbsListView, 0, mViewWidth - 10, mViewWidth / 2 + mViewWidth / 10);
MotionEventUtils.dispatchMotionEventsAndWait(mActivity, mAbsListView, motionEvents);
assertThat(mSwipeTouchListener.afterViewFlingCalled, is(false));
}
/**
* Tests whether calling SwipeTouchListener#fling(int) triggers a call to SwipeTouchListener#afterViewFling.
*/
public void testFling() throws InterruptedException {
mActivity.runOnUiThread(
new Runnable() {
@Override
public void run() {
mSwipeTouchListener.fling(0);
}
}
);
Thread.sleep(1000);
assertThat(mSwipeTouchListener.afterViewFlingCalled, is(true));
assertThat(mSwipeTouchListener.position, is(0));
}
/**
* Tests whether trying to dismiss an item that is specified not to be dismissable doesn't trigger a call to SwipeTouchListener#afterViewFling.
*/
public void testDismissableManager() throws InterruptedException {
mSwipeTouchListener.setDismissableManager(
new DismissableManager() {
@Override
public boolean isDismissable(final long id, final int position) {
return false;
}
}
);
List<MotionEvent> motionEvents = MotionEventUtils.createMotionEvents(mAbsListView, 0, 10, mViewWidth - 10);
MotionEventUtils.dispatchMotionEvents(mActivity, mAbsListView, motionEvents);
assertThat(mSwipeTouchListener.afterViewFlingCalled, is(false));
}
/**
* Tests whether the isSwiping method returns proper values.
*/
public void testIsSwiping() throws InterruptedException {
List<MotionEvent> motionEvents = MotionEventUtils.createMotionEvents(mAbsListView, 0, 10, mViewWidth - 10);
assertThat(mSwipeTouchListener.isSwiping(), is(false));
/* Send first half of the MotionEvents */
MotionEventUtils.dispatchMotionEvents(mActivity, mAbsListView, motionEvents.subList(0, motionEvents.size() / 2));
assertThat(mSwipeTouchListener.isSwiping(), is(true));
/* Send second half of the MotionEvents */
MotionEventUtils.dispatchMotionEvents(mActivity, mAbsListView, motionEvents.subList(motionEvents.size() / 2, motionEvents.size()));
assertThat(mSwipeTouchListener.isSwiping(), is(false));
}
/**
* Test whether disabling swipe and swiping an item does not trigger SwipeTouchListener#afterViewFling, and enabling it again does trigger the call.
*/
public void testEnableDisableSwipe() throws InterruptedException {
mSwipeTouchListener.disableSwipe();
dispatchSwipeMotionEventsAndWait(mActivity, mAbsListView, 0);
assertThat(mSwipeTouchListener.afterViewFlingCalled, is(false));
mSwipeTouchListener.enableSwipe();
dispatchSwipeMotionEventsAndWait(mActivity, mAbsListView, 0);
assertThat(mSwipeTouchListener.afterViewFlingCalled, is(true));
}
private static class TestSwipeTouchListener extends SwipeTouchListener {
boolean afterViewFlingCalled;
int position;
TestSwipeTouchListener(final AbsListViewWrapper absListViewWrapper) {
super(absListViewWrapper);
}
@Override
protected void afterViewFling(@NonNull final View view, final int position) {
afterViewFlingCalled = true;
this.position = position;
}
}
}
| |
/*
* Copyright (c) 2006-2017 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.dmdirc.util.io;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.AccessMode;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.spi.FileSystemProvider;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ConfigFileTest {
@Mock private Path ro;
@Mock private FileSystem mockedFileSystem;
@Mock private FileSystemProvider fileSystemProvider;
private ConfigFile cf;
private Path temp;
private FileSystem fileSystem;
@Before
public void setUp() throws Exception {
fileSystem = Jimfs.newFileSystem(Configuration.unix());
Files.copy(getClass().getResourceAsStream("test2.txt"), fileSystem.getPath("/test2.txt"));
cf = new ConfigFile(fileSystem.getPath("/test2.txt"));
temp = fileSystem.getPath("/temp.txt");
when(mockedFileSystem.provider()).thenReturn(fileSystemProvider);
when(ro.getFileSystem()).thenReturn(mockedFileSystem);
doThrow(new AccessDeniedException("Nup.")).when(fileSystemProvider).checkAccess(ro, AccessMode.WRITE);
}
@After
public void tearDown() throws Exception {
fileSystem.close();
}
@Test
public void testRead() throws IOException, InvalidConfigFileException {
cf.read();
}
@Test(expected = UnsupportedOperationException.class)
public void testWrite() throws IOException {
new ConfigFile(ro).write();
}
@Test
public void testDomains() throws IOException, InvalidConfigFileException {
cf.read();
assertTrue(cf.hasDomain("keysections"));
assertTrue(cf.hasDomain("section alpha"));
assertTrue(cf.hasDomain("section one point one"));
assertTrue(cf.hasDomain("section one"));
assertFalse(cf.hasDomain("random domain"));
}
@Test
public void testKeyDomains() throws IOException, InvalidConfigFileException {
cf.read();
assertTrue(cf.isKeyDomain("section one"));
assertFalse(cf.isKeyDomain("section one point one"));
assertFalse(cf.isKeyDomain("section two"));
}
@Test
public void testFlatDomains() throws IOException, InvalidConfigFileException {
cf.read();
assertTrue(cf.isFlatDomain("keysections"));
assertTrue(cf.isFlatDomain("section alpha"));
assertTrue(cf.isFlatDomain("section one point one"));
assertFalse(cf.isFlatDomain("section one"));
assertFalse(cf.hasDomain("random domain"));
}
@Test
public void testFlatDomainContents() throws IOException, InvalidConfigFileException {
cf.read();
assertEquals(2, cf.getFlatDomain("section alpha").size());
assertEquals("line 1", cf.getFlatDomain("section alpha").get(0));
assertEquals("line 2", cf.getFlatDomain("section alpha").get(1));
}
@Test
public void testKeyDomainContents() throws IOException, InvalidConfigFileException {
cf.read();
assertEquals(3, cf.getKeyDomain("section one").size());
assertEquals("one", cf.getKeyDomain("section one").get("1"));
assertEquals("two", cf.getKeyDomain("section one").get("2"));
assertEquals("three", cf.getKeyDomain("section one").get("3"));
}
@Test
public void testColons() throws IOException, InvalidConfigFileException {
final ConfigFile config = new ConfigFile(temp);
final Map<String, String> data = new HashMap<>();
data.put("test1", "hello");
data.put("test:2", "hello");
data.put("test3", "hello:");
config.addDomain("test", data);
config.write();
final ConfigFile config2 = new ConfigFile(temp);
config2.read();
assertTrue(config2.isKeyDomain("test"));
final Map<String, String> test = config2.getKeyDomain("test");
assertEquals("hello", test.get("test1"));
assertEquals("hello", test.get("test:2"));
assertEquals("hello:", test.get("test3"));
}
@Test
public void testEquals() throws IOException, InvalidConfigFileException {
final ConfigFile config = new ConfigFile(temp);
final Map<String, String> data = new HashMap<>();
data.put("test1", "hello");
data.put("test=2", "hello");
data.put("test3", "hello=");
config.addDomain("test", data);
config.write();
final ConfigFile config2 = new ConfigFile(temp);
config2.read();
assertTrue(config2.isKeyDomain("test"));
final Map<String, String> test = config2.getKeyDomain("test");
assertEquals("hello", test.get("test1"));
assertEquals("hello", test.get("test=2"));
assertEquals("hello=", test.get("test3"));
}
@Test
public void testNewlines() throws IOException, InvalidConfigFileException {
final ConfigFile config = new ConfigFile(temp);
final Map<String, String> data = new HashMap<>();
data.put("test1", "hello");
data.put("test2", "hello\ngoodbye");
data.put("test3", "hello\n");
data.put("test4", "hello\r\ngoodbye");
config.addDomain("test", data);
config.write();
final ConfigFile config2 = new ConfigFile(temp);
config2.read();
assertTrue(config2.isKeyDomain("test"));
final Map<String, String> test = config2.getKeyDomain("test");
assertEquals("hello", test.get("test1"));
assertEquals("hello\ngoodbye", test.get("test2"));
assertEquals("hello\n", test.get("test3"));
assertEquals("hello\r\ngoodbye", test.get("test4"));
}
@Test
public void testBackslash() throws IOException, InvalidConfigFileException {
final ConfigFile config = new ConfigFile(temp);
final Map<String, String> data = new HashMap<>();
data.put("test1", "hello\\");
data.put("test2", "\\nhello");
data.put("test3\\", "hello");
config.addDomain("test", data);
config.write();
final ConfigFile config2 = new ConfigFile(temp);
config2.read();
assertTrue(config2.isKeyDomain("test"));
final Map<String, String> test = config2.getKeyDomain("test");
assertEquals("hello\\", test.get("test1"));
assertEquals("\\nhello", test.get("test2"));
assertEquals("hello", test.get("test3\\"));
}
@Test
public void testHash() throws IOException, InvalidConfigFileException {
final ConfigFile config = new ConfigFile(temp);
final Map<String, String> data = new HashMap<>();
data.put("test1#", "hello");
data.put("#test2", "hello");
data.put("test3", "#hello");
config.addDomain("test", data);
config.write();
final ConfigFile config2 = new ConfigFile(temp);
config2.read();
assertTrue(config2.isKeyDomain("test"));
final Map<String, String> test = config2.getKeyDomain("test");
assertEquals("hello", test.get("test1#"));
assertEquals("hello", test.get("#test2"));
assertEquals("#hello", test.get("test3"));
}
@Test
public void testEscape() {
final String input = "blah blah\\foo\r\nbar=:";
final String output = "blah blah\\\\foo\\r\\nbar\\=\\:";
assertEquals(output, ConfigFile.escape(input));
}
@Test
public void testUnescape() {
final String input = "blah blah\\foo\r\nbar=:";
assertEquals(input, ConfigFile.unescape(ConfigFile.escape(input)));
}
@Test
public void testDelete() throws IOException {
final ConfigFile config = new ConfigFile(temp);
config.write();
assertTrue(Files.exists(temp));
config.delete();
assertFalse(Files.exists(temp));
}
@Test
public void testDuplicateKeys() throws IOException, InvalidConfigFileException {
final ConfigFile file = new ConfigFile(getClass().getResourceAsStream("test2.txt"));
file.read();
assertTrue(file.isKeyDomain("section one"));
assertEquals(3, file.getKeyDomain("section one").size());
assertTrue(file.isFlatDomain("section one point one"));
}
@Test(expected = InvalidConfigFileException.class)
public void testInvalidLine() throws IOException, InvalidConfigFileException {
final ConfigFile file = new ConfigFile(getClass().getResourceAsStream("test1.txt"));
file.read();
}
}
| |
package com.timgroup.statsd;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* A simple StatsD client implementation facilitating metrics recording.
*
* <p>Upon instantiation, this client will establish a socket connection to a StatsD instance
* running on the specified host and port. Metrics are then sent over this connection as they are
* received by the client.
* </p>
*
* <p>Three key methods are provided for the submission of data-points for the application under
* scrutiny:
* <ul>
* <li>{@link #incrementCounter} - adds one to the value of the specified named counter</li>
* <li>{@link #recordGaugeValue} - records the latest fixed value for the specified named gauge</li>
* <li>{@link #recordExecutionTime} - records an execution time in milliseconds for the specified named operation</li>
* <li>{@link #recordHistogramValue} - records a value, to be tracked with average, maximum, and percentiles</li>
* <li>{@link #recordEvent} - records an event</li>
* </ul>
* From the perspective of the application, these methods are non-blocking, with the resulting
* IO operations being carried out in a separate thread. Furthermore, these methods are guaranteed
* not to throw an exception which may disrupt application execution.
* </p>
*
* <p>As part of a clean system shutdown, the {@link #stop()} method should be invoked
* on any StatsD clients.</p>
*
* @author Tom Denley
*
*/
public final class NonBlockingStatsDClient implements StatsDClient {
private static final int PACKET_SIZE_BYTES = 1500;
private static final StatsDClientErrorHandler NO_OP_HANDLER = new StatsDClientErrorHandler() {
@Override public void handle(Exception e) { /* No-op */ }
};
/**
* Because NumberFormat is not thread-safe we cannot share instances across threads. Use a ThreadLocal to
* create one pre thread as this seems to offer a significant performance improvement over creating one per-thread:
* http://stackoverflow.com/a/1285297/2648
* https://github.com/indeedeng/java-dogstatsd-client/issues/4
*/
private static final ThreadLocal<NumberFormat> NUMBER_FORMATTERS = new ThreadLocal<NumberFormat>() {
@Override
protected NumberFormat initialValue() {
// Always create the formatter for the US locale in order to avoid this bug:
// https://github.com/indeedeng/java-dogstatsd-client/issues/3
NumberFormat numberFormatter = NumberFormat.getInstance(Locale.US);
numberFormatter.setGroupingUsed(false);
numberFormatter.setMaximumFractionDigits(6);
// we need to specify a value for Double.NaN that is recognized by dogStatsD
DecimalFormatSymbols symbols = ((DecimalFormat) numberFormatter).getDecimalFormatSymbols();
symbols.setNaN("NaN");
((DecimalFormat) numberFormatter).setDecimalFormatSymbols(symbols);
return numberFormatter;
}
};
private final String prefix;
private final DatagramChannel clientChannel;
private final InetSocketAddress address;
private final StatsDClientErrorHandler handler;
private final String constantTagsRendered;
private final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
final ThreadFactory delegate = Executors.defaultThreadFactory();
@Override public Thread newThread(Runnable r) {
Thread result = delegate.newThread(r);
result.setName("StatsD-" + result.getName());
result.setDaemon(true);
return result;
}
});
private final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
/**
* Create a new StatsD client communicating with a StatsD instance on the
* specified host and port. All messages send via this client will have
* their keys prefixed with the specified string. The new client will
* attempt to open a connection to the StatsD server immediately upon
* instantiation, and may throw an exception if that a connection cannot
* be established. Once a client has been instantiated in this way, all
* exceptions thrown during subsequent usage are consumed, guaranteeing
* that failures in metrics will not affect normal code execution.
*
* @param prefix
* the prefix to apply to keys sent via this client
* @param hostname
* the host name of the targeted StatsD server
* @param port
* the port of the targeted StatsD server
* @throws StatsDClientException
* if the client could not be started
*/
public NonBlockingStatsDClient(String prefix, String hostname, int port) throws StatsDClientException {
this(prefix, hostname, port, null, NO_OP_HANDLER);
}
/**
* Create a new StatsD client communicating with a StatsD instance on the
* specified host and port. All messages send via this client will have
* their keys prefixed with the specified string. The new client will
* attempt to open a connection to the StatsD server immediately upon
* instantiation, and may throw an exception if that a connection cannot
* be established. Once a client has been instantiated in this way, all
* exceptions thrown during subsequent usage are consumed, guaranteeing
* that failures in metrics will not affect normal code execution.
*
* @param prefix
* the prefix to apply to keys sent via this client
* @param hostname
* the host name of the targeted StatsD server
* @param port
* the port of the targeted StatsD server
* @param constantTags
* tags to be added to all content sent
* @throws StatsDClientException
* if the client could not be started
*/
public NonBlockingStatsDClient(String prefix, String hostname, int port, String... constantTags) throws StatsDClientException {
this(prefix, hostname, port, constantTags, NO_OP_HANDLER);
}
/**
* Create a new StatsD client communicating with a StatsD instance on the
* specified host and port. All messages send via this client will have
* their keys prefixed with the specified string. The new client will
* attempt to open a connection to the StatsD server immediately upon
* instantiation, and may throw an exception if that a connection cannot
* be established. Once a client has been instantiated in this way, all
* exceptions thrown during subsequent usage are passed to the specified
* handler and then consumed, guaranteeing that failures in metrics will
* not affect normal code execution.
*
* @param prefix
* the prefix to apply to keys sent via this client
* @param hostname
* the host name of the targeted StatsD server
* @param port
* the port of the targeted StatsD server
* @param constantTags
* tags to be added to all content sent
* @param errorHandler
* handler to use when an exception occurs during usage
* @throws StatsDClientException
* if the client could not be started
*/
public NonBlockingStatsDClient(String prefix, String hostname, int port, String[] constantTags, StatsDClientErrorHandler errorHandler) throws StatsDClientException {
if(prefix != null && prefix.length() > 0) {
this.prefix = String.format("%s.", prefix);
} else {
this.prefix = "";
}
this.handler = errorHandler;
/* Empty list should be null for faster comparison */
if(constantTags != null && constantTags.length == 0) {
constantTags = null;
}
if(constantTags != null) {
this.constantTagsRendered = tagString(constantTags, null);
} else {
this.constantTagsRendered = null;
}
try {
this.clientChannel = DatagramChannel.open();
this.address = new InetSocketAddress(hostname, port);
} catch (Exception e) {
throw new StatsDClientException("Failed to start StatsD client", e);
}
this.executor.submit(new QueueConsumer());
}
/**
* Cleanly shut down this StatsD client. This method may throw an exception if
* the socket cannot be closed.
*/
@Override
public void stop() {
try {
executor.shutdown();
executor.awaitTermination(30, TimeUnit.SECONDS);
}
catch (Exception e) {
handler.handle(e);
}
finally {
if (clientChannel != null) {
try {
clientChannel.close();
}
catch (IOException e) {
handler.handle(e);
}
}
}
}
/**
* Generate a suffix conveying the given tag list to the client
*/
static String tagString(final String[] tags, final String tagPrefix) {
StringBuilder sb;
if(tagPrefix != null) {
if(tags == null || tags.length == 0) {
return tagPrefix;
}
sb = new StringBuilder(tagPrefix);
sb.append(",");
} else {
if(tags == null || tags.length == 0) {
return "";
}
sb = new StringBuilder("|#");
}
for(int n=tags.length - 1; n>=0; n--) {
sb.append(tags[n]);
if(n > 0) {
sb.append(",");
}
}
return sb.toString();
}
/**
* Generate a suffix conveying the given tag list to the client
*/
String tagString(final String[] tags) {
return tagString(tags, constantTagsRendered);
}
/**
* Adjusts the specified counter by a given delta.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the counter to adjust
* @param delta
* the amount to adjust the counter by
* @param tags
* array of tags to be added to the data
*/
@Override
public void count(String aspect, long delta, String... tags) {
send(String.format("%s%s:%d|c%s", prefix, aspect, delta, tagString(tags)));
}
/**
* Increments the specified counter by one.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the counter to increment
* @param tags
* array of tags to be added to the data
*/
@Override
public void incrementCounter(String aspect, String... tags) {
count(aspect, 1, tags);
}
/**
* Convenience method equivalent to {@link #incrementCounter(String, String[])}.
*/
@Override
public void increment(String aspect, String... tags) {
incrementCounter(aspect, tags);
}
/**
* Decrements the specified counter by one.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the counter to decrement
* @param tags
* array of tags to be added to the data
*/
@Override
public void decrementCounter(String aspect, String... tags) {
count(aspect, -1, tags);
}
/**
* Convenience method equivalent to {@link #decrementCounter(String, String[])}.
*/
@Override
public void decrement(String aspect, String... tags) {
decrementCounter(aspect, tags);
}
/**
* Records the latest fixed value for the specified named gauge.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the gauge
* @param value
* the new reading of the gauge
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordGaugeValue(String aspect, double value, String... tags) {
/* Intentionally using %s rather than %f here to avoid
* padding with extra 0s to represent precision */
send(String.format("%s%s:%s|g%s", prefix, aspect, NUMBER_FORMATTERS.get().format(value), tagString(tags)));
}
/**
* Convenience method equivalent to {@link #recordGaugeValue(String, double, String[])}.
*/
@Override
public void gauge(String aspect, double value, String... tags) {
recordGaugeValue(aspect, value, tags);
}
/**
* Records the latest fixed value for the specified named gauge.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the gauge
* @param value
* the new reading of the gauge
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordGaugeValue(String aspect, long value, String... tags) {
send(String.format("%s%s:%d|g%s", prefix, aspect, value, tagString(tags)));
}
/**
* Convenience method equivalent to {@link #recordGaugeValue(String, long, String[])}.
*/
@Override
public void gauge(String aspect, long value, String... tags) {
recordGaugeValue(aspect, value, tags);
}
/**
* Records an execution time in milliseconds for the specified named operation.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the timed operation
* @param timeInMs
* the time in milliseconds
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordExecutionTime(String aspect, long timeInMs, String... tags) {
send(String.format("%s%s:%d|ms%s", prefix, aspect, timeInMs, tagString(tags)));
}
/**
* Convenience method equivalent to {@link #recordExecutionTime(String, long, String[])}.
*/
@Override
public void time(String aspect, long value, String... tags) {
recordExecutionTime(aspect, value, tags);
}
/**
* Records a value for the specified named histogram.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the histogram
* @param value
* the value to be incorporated in the histogram
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordHistogramValue(String aspect, double value, String... tags) {
/* Intentionally using %s rather than %f here to avoid
* padding with extra 0s to represent precision */
send(String.format("%s%s:%s|h%s", prefix, aspect, NUMBER_FORMATTERS.get().format(value), tagString(tags)));
}
/**
* Convenience method equivalent to {@link #recordHistogramValue(String, double, String[])}.
*/
@Override
public void histogram(String aspect, double value, String... tags) {
recordHistogramValue(aspect, value, tags);
}
/**
* Records a value for the specified named histogram.
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param aspect
* the name of the histogram
* @param value
* the value to be incorporated in the histogram
* @param tags
* array of tags to be added to the data
*/
@Override
public void recordHistogramValue(String aspect, long value, String... tags) {
send(String.format("%s%s:%d|h%s", prefix, aspect, value, tagString(tags)));
}
/**
* Convenience method equivalent to {@link #recordHistogramValue(String, long, String[])}.
*/
@Override
public void histogram(String aspect, long value, String... tags) {
recordHistogramValue(aspect, value, tags);
}
private String eventMap(final Event event) {
final StringBuilder res = new StringBuilder("");
final long millisSinceEpoch = event.getMillisSinceEpoch();
if (millisSinceEpoch != -1) {
res.append("|d:").append(millisSinceEpoch / 1000);
}
final String hostname = event.getHostname();
if (hostname != null) {
res.append("|h:").append(hostname);
}
final String aggregationKey = event.getAggregationKey();
if (aggregationKey != null) {
res.append("|k:").append(aggregationKey);
}
final String priority = event.getPriority();
if (priority != null) {
res.append("|p:").append(priority);
}
final String alertType = event.getAlertType();
if (alertType != null) {
res.append("|t:").append(alertType);
}
return res.toString();
}
/**
* Records an event
*
* <p>This method is a DataDog extension, and may not work with other servers.</p>
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param event
* The event to record
* @param tags
* array of tags to be added to the data
*
* @see <a href="http://docs.datadoghq.com/guides/dogstatsd/#events-1">http://docs.datadoghq.com/guides/dogstatsd/#events-1</a>
*/
@Override
public void recordEvent(final Event event, final String... tags) {
final String title = prefix + event.getTitle();
final String text = event.getText();
send(String.format("_e{%d,%d}:%s|%s%s%s",
title.length(), text.length(), title, text, eventMap(event), tagString(tags)));
}
/**
* Records a run status for the specified named service check.
*
* <p>This method is a DataDog extension, and may not work with other servers.</p>
*
* <p>This method is non-blocking and is guaranteed not to throw an exception.</p>
*
* @param sc
* the service check object
*/
@Override
public void recordServiceCheckRun(final ServiceCheck sc) {
send(toStatsDString(sc));
}
private String toStatsDString(final ServiceCheck sc) {
// see http://docs.datadoghq.com/guides/dogstatsd/#service-checks
final StringBuilder sb = new StringBuilder();
sb.append(String.format("_sc|%s|%d", sc.getName(), sc.getStatus()));
if (sc.getTimestamp() > 0) {
sb.append(String.format("|d:%d", sc.getTimestamp()));
}
if (sc.getHostname() != null) {
sb.append(String.format("|h:%s", sc.getHostname()));
}
sb.append(tagString(sc.getTags()));
if (sc.getMessage() != null) {
sb.append(String.format("|m:%s", sc.getEscapedMessage()));
}
return sb.toString();
}
/**
* Convenience method equivalent to {@link #recordServiceCheckRun(ServiceCheck sc)}.
*/
@Override
public void serviceCheck(final ServiceCheck sc) {
recordServiceCheckRun(sc);
}
private void send(String message) {
queue.offer(message);
}
public static final Charset MESSAGE_CHARSET = Charset.forName("UTF-8");
private class QueueConsumer implements Runnable {
private final ByteBuffer sendBuffer = ByteBuffer.allocate(PACKET_SIZE_BYTES);
@Override public void run() {
while(!executor.isShutdown()) {
try {
String message = queue.poll(1, TimeUnit.SECONDS);
if(null != message) {
byte[] data = message.getBytes(MESSAGE_CHARSET);
if(sendBuffer.remaining() < (data.length + 1)) {
blockingSend();
}
if(sendBuffer.position() > 0) {
sendBuffer.put( (byte) '\n');
}
sendBuffer.put(data);
if(null == queue.peek()) {
blockingSend();
}
}
} catch (Exception e) {
handler.handle(e);
}
}
}
private void blockingSend() throws IOException {
int sizeOfBuffer = sendBuffer.position();
sendBuffer.flip();
int sentBytes = clientChannel.send(sendBuffer, address);
sendBuffer.limit(sendBuffer.capacity());
sendBuffer.rewind();
if (sizeOfBuffer != sentBytes) {
handler.handle(
new IOException(
String.format(
"Could not send entirely stat %s to host %s:%d. Only sent %d bytes out of %d bytes",
sendBuffer.toString(),
address.getHostName(),
address.getPort(),
sentBytes,
sizeOfBuffer)));
}
}
}
}
| |
/*
* Copyright (c) 2008-2015 Citrix Systems, 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.citrix.netscaler.nitro.resource.stat.basic;
import com.citrix.netscaler.nitro.resource.base.*;
import com.citrix.netscaler.nitro.service.nitro_service;
import com.citrix.netscaler.nitro.service.options;
import com.citrix.netscaler.nitro.util.*;
import com.citrix.netscaler.nitro.exception.nitro_exception;
class service_response extends base_response
{
public service_stats[] service;
}
/**
* Statistics for service resource.
*/
public class service_stats extends base_resource
{
private String name;
private String clearstats;
private Long throughput;
private Long throughputrate;
private Long avgsvrttfb;
private String primaryipaddress;
private Integer primaryport;
private String servicetype;
private String state;
private Long totalrequests;
private Long requestsrate;
private Long totalresponses;
private Long responsesrate;
private Long totalrequestbytes;
private Long requestbytesrate;
private Long totalresponsebytes;
private Long responsebytesrate;
private Long curclntconnections;
private Long surgecount;
private Long cursrvrconnections;
private Long svrestablishedconn;
private Long curreusepool;
private Long maxclients;
private Long curload;
private Long curtflags;
private Long vsvrservicehits;
private Long vsvrservicehitsrate;
private Long activetransactions;
/**
* <pre>
* Name of the service.
* </pre>
*/
public void set_name(String name) throws Exception{
this.name = name;
}
/**
* <pre>
* Name of the service.<br> Minimum length = 1
* </pre>
*/
public String get_name() throws Exception {
return this.name;
}
/**
* <pre>
* Clear the statsistics / counters
* </pre>
*/
public void set_clearstats(String clearstats) throws Exception{
this.clearstats = clearstats;
}
/**
* <pre>
* Clear the statsistics / counters.<br> Possible values = basic, full
* </pre>
*/
public String get_clearstats() throws Exception {
return this.clearstats;
}
/**
* <pre>
* Number of server connections in ESTABLISHED state.
* </pre>
*/
public Long get_svrestablishedconn() throws Exception {
return this.svrestablishedconn;
}
/**
* <pre>
* Number of current client connections.
* </pre>
*/
public Long get_curclntconnections() throws Exception {
return this.curclntconnections;
}
/**
* <pre>
* The service type of this service.Possible values are ADNS, DNS, MYSQL, RTSP, SSL_DIAMETER, ADNS_TCP, DNS_TCP, NNTP, SIP_UDP, SSL_TCP, ANY, FTP, RADIUS, SNMP, TCP, DHCPRA, HTTP, RDP, SSL, TFTP, DIAMETER, MSSQL, RPCSVR, SSL_BRIDGE, UDP
* </pre>
*/
public String get_servicetype() throws Exception {
return this.servicetype;
}
/**
* <pre>
* Total number of requests received on this service or virtual server. (This applies to HTTP/SSL services and servers.)
* </pre>
*/
public Long get_totalrequests() throws Exception {
return this.totalrequests;
}
/**
* <pre>
* Number of requests in the surge queue.
* </pre>
*/
public Long get_surgecount() throws Exception {
return this.surgecount;
}
/**
* <pre>
* Rate (/s) counter for totalresponsebytes
* </pre>
*/
public Long get_responsebytesrate() throws Exception {
return this.responsebytesrate;
}
/**
* <pre>
* Number of responses received on this service or virtual server. (This applies to HTTP/SSL services and servers.)
* </pre>
*/
public Long get_totalresponses() throws Exception {
return this.totalresponses;
}
/**
* <pre>
* Rate (/s) counter for totalrequestbytes
* </pre>
*/
public Long get_requestbytesrate() throws Exception {
return this.requestbytesrate;
}
/**
* <pre>
* Number of bytes received or sent by this service (Mbps).
* </pre>
*/
public Long get_throughput() throws Exception {
return this.throughput;
}
/**
* <pre>
* Rate (/s) counter for throughput
* </pre>
*/
public Long get_throughputrate() throws Exception {
return this.throughputrate;
}
/**
* <pre>
* Current flags on the service for internal use in display handlers.
* </pre>
*/
public Long get_curtflags() throws Exception {
return this.curtflags;
}
/**
* <pre>
* Number of current connections to the actual servers behind the virtual server.
* </pre>
*/
public Long get_cursrvrconnections() throws Exception {
return this.cursrvrconnections;
}
/**
* <pre>
* The IP address on which the service is running.
* </pre>
*/
public String get_primaryipaddress() throws Exception {
return this.primaryipaddress;
}
/**
* <pre>
* Number of active transactions handled by this service. (Including those in the surge queue.)
Active Transaction means number of transactions currently served by the server including those waiting in the SurgeQ
* </pre>
*/
public Long get_activetransactions() throws Exception {
return this.activetransactions;
}
/**
* <pre>
* Rate (/s) counter for totalresponses
* </pre>
*/
public Long get_responsesrate() throws Exception {
return this.responsesrate;
}
/**
* <pre>
* Maximum open connections allowed on this service.
* </pre>
*/
public Long get_maxclients() throws Exception {
return this.maxclients;
}
/**
* <pre>
* Average TTFB between the NetScaler appliance and the server.TTFB is the time interval between sending the request packet to a service and receiving the first response from the service
* </pre>
*/
public Long get_avgsvrttfb() throws Exception {
return this.avgsvrttfb;
}
/**
* <pre>
* Load on the service that is calculated from the bound load based monitor.
* </pre>
*/
public Long get_curload() throws Exception {
return this.curload;
}
/**
* <pre>
* Total number of request bytes received on this service or virtual server.
* </pre>
*/
public Long get_totalrequestbytes() throws Exception {
return this.totalrequestbytes;
}
/**
* <pre>
* Number of requests in the idle queue/reuse pool.
* </pre>
*/
public Long get_curreusepool() throws Exception {
return this.curreusepool;
}
/**
* <pre>
* Current state of the server. Possible values are UP, DOWN, UNKNOWN, OFS(Out of Service), TROFS(Transition Out of Service), TROFS_DOWN(Down When going Out of Service)
* </pre>
*/
public String get_state() throws Exception {
return this.state;
}
/**
* <pre>
* Number of times that the service has been provided.
* </pre>
*/
public Long get_vsvrservicehits() throws Exception {
return this.vsvrservicehits;
}
/**
* <pre>
* Number of response bytes received by this service or virtual server.
* </pre>
*/
public Long get_totalresponsebytes() throws Exception {
return this.totalresponsebytes;
}
/**
* <pre>
* The port on which the service is running.
* </pre>
*/
public Integer get_primaryport() throws Exception {
return this.primaryport;
}
/**
* <pre>
* Rate (/s) counter for totalrequests
* </pre>
*/
public Long get_requestsrate() throws Exception {
return this.requestsrate;
}
/**
* <pre>
* Rate (/s) counter for vsvrservicehits
* </pre>
*/
public Long get_vsvrservicehitsrate() throws Exception {
return this.vsvrservicehitsrate;
}
/**
* <pre>
* converts nitro response into object and returns the object array in case of get request.
* </pre>
*/
protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception{
service_response result = (service_response) service.get_payload_formatter().string_to_resource(service_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
return result.service;
}
/**
* <pre>
* Returns the value of object identifier argument
* </pre>
*/
protected String get_object_name() {
return this.name;
}
/**
* Use this API to fetch the statistics of all service_stats resources that are configured on netscaler.
*/
public static service_stats[] get(nitro_service service) throws Exception{
service_stats obj = new service_stats();
service_stats[] response = (service_stats[])obj.stat_resources(service);
return response;
}
/**
* Use this API to fetch the statistics of all service_stats resources that are configured on netscaler.
*/
public static service_stats[] get(nitro_service service, options option) throws Exception{
service_stats obj = new service_stats();
service_stats[] response = (service_stats[])obj.stat_resources(service,option);
return response;
}
/**
* Use this API to fetch statistics of service_stats resource of given name .
*/
public static service_stats get(nitro_service service, String name) throws Exception{
service_stats obj = new service_stats();
obj.set_name(name);
service_stats response = (service_stats) obj.stat_resource(service);
return response;
}
public static class clearstatsEnum {
public static final String basic = "basic";
public static final String full = "full";
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.devtestlabs.implementation;
import com.azure.core.management.Region;
import com.azure.core.util.Context;
import com.azure.resourcemanager.devtestlabs.fluent.models.ArtifactSourceInner;
import com.azure.resourcemanager.devtestlabs.models.ArtifactSource;
import com.azure.resourcemanager.devtestlabs.models.ArtifactSourceFragment;
import com.azure.resourcemanager.devtestlabs.models.EnableStatus;
import com.azure.resourcemanager.devtestlabs.models.SourceControlType;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.Map;
public final class ArtifactSourceImpl implements ArtifactSource, ArtifactSource.Definition, ArtifactSource.Update {
private ArtifactSourceInner innerObject;
private final com.azure.resourcemanager.devtestlabs.DevTestLabsManager serviceManager;
public String id() {
return this.innerModel().id();
}
public String name() {
return this.innerModel().name();
}
public String type() {
return this.innerModel().type();
}
public String location() {
return this.innerModel().location();
}
public Map<String, String> tags() {
Map<String, String> inner = this.innerModel().tags();
if (inner != null) {
return Collections.unmodifiableMap(inner);
} else {
return Collections.emptyMap();
}
}
public String displayName() {
return this.innerModel().displayName();
}
public String uri() {
return this.innerModel().uri();
}
public SourceControlType sourceType() {
return this.innerModel().sourceType();
}
public String folderPath() {
return this.innerModel().folderPath();
}
public String armTemplateFolderPath() {
return this.innerModel().armTemplateFolderPath();
}
public String branchRef() {
return this.innerModel().branchRef();
}
public String securityToken() {
return this.innerModel().securityToken();
}
public EnableStatus status() {
return this.innerModel().status();
}
public OffsetDateTime createdDate() {
return this.innerModel().createdDate();
}
public String provisioningState() {
return this.innerModel().provisioningState();
}
public String uniqueIdentifier() {
return this.innerModel().uniqueIdentifier();
}
public Region region() {
return Region.fromName(this.regionName());
}
public String regionName() {
return this.location();
}
public ArtifactSourceInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.devtestlabs.DevTestLabsManager manager() {
return this.serviceManager;
}
private String resourceGroupName;
private String labName;
private String name;
private ArtifactSourceFragment updateArtifactSource;
public ArtifactSourceImpl withExistingLab(String resourceGroupName, String labName) {
this.resourceGroupName = resourceGroupName;
this.labName = labName;
return this;
}
public ArtifactSource create() {
this.innerObject =
serviceManager
.serviceClient()
.getArtifactSources()
.createOrUpdateWithResponse(resourceGroupName, labName, name, this.innerModel(), Context.NONE)
.getValue();
return this;
}
public ArtifactSource create(Context context) {
this.innerObject =
serviceManager
.serviceClient()
.getArtifactSources()
.createOrUpdateWithResponse(resourceGroupName, labName, name, this.innerModel(), context)
.getValue();
return this;
}
ArtifactSourceImpl(String name, com.azure.resourcemanager.devtestlabs.DevTestLabsManager serviceManager) {
this.innerObject = new ArtifactSourceInner();
this.serviceManager = serviceManager;
this.name = name;
}
public ArtifactSourceImpl update() {
this.updateArtifactSource = new ArtifactSourceFragment();
return this;
}
public ArtifactSource apply() {
this.innerObject =
serviceManager
.serviceClient()
.getArtifactSources()
.updateWithResponse(resourceGroupName, labName, name, updateArtifactSource, Context.NONE)
.getValue();
return this;
}
public ArtifactSource apply(Context context) {
this.innerObject =
serviceManager
.serviceClient()
.getArtifactSources()
.updateWithResponse(resourceGroupName, labName, name, updateArtifactSource, context)
.getValue();
return this;
}
ArtifactSourceImpl(
ArtifactSourceInner innerObject, com.azure.resourcemanager.devtestlabs.DevTestLabsManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
this.resourceGroupName = Utils.getValueFromIdByName(innerObject.id(), "resourceGroups");
this.labName = Utils.getValueFromIdByName(innerObject.id(), "labs");
this.name = Utils.getValueFromIdByName(innerObject.id(), "artifactsources");
}
public ArtifactSource refresh() {
String localExpand = null;
this.innerObject =
serviceManager
.serviceClient()
.getArtifactSources()
.getWithResponse(resourceGroupName, labName, name, localExpand, Context.NONE)
.getValue();
return this;
}
public ArtifactSource refresh(Context context) {
String localExpand = null;
this.innerObject =
serviceManager
.serviceClient()
.getArtifactSources()
.getWithResponse(resourceGroupName, labName, name, localExpand, context)
.getValue();
return this;
}
public ArtifactSourceImpl withRegion(Region location) {
this.innerModel().withLocation(location.toString());
return this;
}
public ArtifactSourceImpl withRegion(String location) {
this.innerModel().withLocation(location);
return this;
}
public ArtifactSourceImpl withTags(Map<String, String> tags) {
if (isInCreateMode()) {
this.innerModel().withTags(tags);
return this;
} else {
this.updateArtifactSource.withTags(tags);
return this;
}
}
public ArtifactSourceImpl withDisplayName(String displayName) {
this.innerModel().withDisplayName(displayName);
return this;
}
public ArtifactSourceImpl withUri(String uri) {
this.innerModel().withUri(uri);
return this;
}
public ArtifactSourceImpl withSourceType(SourceControlType sourceType) {
this.innerModel().withSourceType(sourceType);
return this;
}
public ArtifactSourceImpl withFolderPath(String folderPath) {
this.innerModel().withFolderPath(folderPath);
return this;
}
public ArtifactSourceImpl withArmTemplateFolderPath(String armTemplateFolderPath) {
this.innerModel().withArmTemplateFolderPath(armTemplateFolderPath);
return this;
}
public ArtifactSourceImpl withBranchRef(String branchRef) {
this.innerModel().withBranchRef(branchRef);
return this;
}
public ArtifactSourceImpl withSecurityToken(String securityToken) {
this.innerModel().withSecurityToken(securityToken);
return this;
}
public ArtifactSourceImpl withStatus(EnableStatus status) {
this.innerModel().withStatus(status);
return this;
}
private boolean isInCreateMode() {
return this.innerModel().id() == null;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.maven.connector;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.camel.maven.connector.model.ComponentModel;
import org.apache.camel.maven.connector.model.ComponentOptionModel;
import org.apache.camel.maven.connector.util.JSonSchemaHelper;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.source.AnnotationSource;
import org.jboss.forge.roaster.model.source.Import;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.MethodSource;
import org.jboss.forge.roaster.model.source.PropertySource;
import org.jboss.forge.roaster.model.util.Formatter;
import org.jboss.forge.roaster.model.util.Strings;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.DeprecatedConfigurationProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import static org.apache.camel.maven.connector.util.FileHelper.loadText;
import static org.apache.camel.maven.connector.util.StringHelper.getSafeValue;
import static org.apache.camel.maven.connector.util.StringHelper.getShortJavaType;
/**
* Generate Spring Boot auto configuration files for Camel connectors.
*/
@Mojo(name = "prepare-spring-boot-auto-configuration",
defaultPhase = LifecyclePhase.PACKAGE,
requiresProject = true, threadSafe = true)
public class SpringBootAutoConfigurationMojo extends AbstractMojo {
@Parameter(defaultValue = "${project.build.outputDirectory}", required = true)
private File classesDirectory;
@Parameter(defaultValue = "true")
private boolean includeLicenseHeader;
@Parameter(defaultValue = "camel.connector")
private String configurationPrefix;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
executeConnector();
} catch (Exception e) {
throw new MojoFailureException("Error generating Spring-Boot auto configuration for connector", e);
}
}
@SuppressWarnings("unchecked")
private void executeConnector() throws Exception {
String javaType = null;
String connectorScheme = null;
List<String> componentOptions = null;
File file = new File(classesDirectory, "camel-connector.json");
if (file.exists()) {
ObjectMapper mapper = new ObjectMapper();
Map dto = mapper.readValue(file, Map.class);
javaType = (String) dto.get("javaType");
connectorScheme = (String) dto.get("scheme");
componentOptions = (List) dto.get("componentOptions");
}
// find the component dependency and get its .json file
file = new File(classesDirectory, "camel-component-schema.json");
if (file.exists() && javaType != null && connectorScheme != null) {
String json = loadText(new FileInputStream(file));
ComponentModel model = generateComponentModel(json);
// resolvePropertyPlaceholders is an option which only make sense to use if the component has other options
boolean hasOptions = model.getComponentOptions().stream().anyMatch(o -> !o.getName().equals("resolvePropertyPlaceholders"));
// use springboot as sub package name so the code is not in normal
// package so the Spring Boot JARs can be optional at runtime
int pos = javaType.lastIndexOf(".");
String pkg = javaType.substring(0, pos) + ".springboot";
// we only create spring boot auto configuration if there is options to configure
if (hasOptions) {
getLog().info("Generating Spring Boot AutoConfiguration for Connector: " + model.getScheme());
createConnectorConfigurationSource(pkg, model, javaType, connectorScheme, componentOptions);
createConnectorAutoConfigurationSource(pkg, hasOptions, javaType, connectorScheme);
createConnectorSpringFactorySource(pkg, javaType);
}
}
}
private void createConnectorSpringFactorySource(String packageName, String javaType) throws MojoFailureException {
int pos = javaType.lastIndexOf(".");
String name = javaType.substring(pos + 1);
name = name.replace("Component", "ConnectorAutoConfiguration");
writeComponentSpringFactorySource(packageName, name);
}
private void writeComponentSpringFactorySource(String packageName, String name) throws MojoFailureException {
StringBuilder sb = new StringBuilder();
sb.append("org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\\n");
String lineToAdd = packageName + "." + name + "\n";
sb.append(lineToAdd);
// project root folder
File root = classesDirectory.getParentFile().getParentFile();
String fileName = "src/main/resources/META-INF/spring.factories";
File target = new File(root, fileName);
// create new file
try {
String header = "";
if (includeLicenseHeader) {
InputStream is = getClass().getClassLoader().getResourceAsStream("license-header.txt");
header = loadText(is);
}
String code = sb.toString();
// add empty new line after header
code = header + "\n" + code;
getLog().debug("Source code generated:\n" + code);
FileUtils.write(target, code);
getLog().info("Created file: " + target);
} catch (Exception e) {
throw new MojoFailureException("IOError with file " + target, e);
}
}
private void createConnectorConfigurationSource(String packageName, ComponentModel model, String javaType,
String connectorScheme, List<String> componentOptions) throws MojoFailureException {
final JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
int pos = javaType.lastIndexOf(".");
String name = javaType.substring(pos + 1);
name = name.replace("Component", "ConnectorConfiguration");
javaClass.setPackage(packageName).setName(name);
String doc = "Generated by camel-connector-maven-plugin - do not edit this file!";
if (!Strings.isBlank(model.getDescription())) {
doc = model.getDescription() + "\n\n" + doc;
}
// replace Component with Connector
doc = doc.replaceAll("Component", "Connector");
doc = doc.replaceAll("component", "connector");
javaClass.getJavaDoc().setFullText(doc);
// compute the configuration prefix to use with spring boot configuration
String prefix = "";
if (!"false".equalsIgnoreCase(configurationPrefix)) {
// make sure prefix is in lower case
prefix = configurationPrefix.toLowerCase(Locale.US);
if (!prefix.endsWith(".")) {
prefix += ".";
}
}
prefix += connectorScheme.toLowerCase(Locale.US);
javaClass.addAnnotation("org.springframework.boot.context.properties.ConfigurationProperties").setStringValue("prefix", prefix);
for (ComponentOptionModel option : model.getComponentOptions()) {
// only include the options that has been explicit configured in the camel-connector.json file
boolean accepted = false;
if (componentOptions != null) {
accepted = componentOptions.stream().anyMatch(o -> o.equals(option.getName()));
}
if (accepted) {
String type = option.getJavaType();
PropertySource<JavaClassSource> prop = javaClass.addProperty(type, option.getName());
if ("true".equals(option.getDeprecated())) {
prop.getField().addAnnotation(Deprecated.class);
prop.getAccessor().addAnnotation(Deprecated.class);
prop.getMutator().addAnnotation(Deprecated.class);
// DeprecatedConfigurationProperty must be on getter when deprecated
prop.getAccessor().addAnnotation(DeprecatedConfigurationProperty.class);
}
if (!Strings.isBlank(option.getDescription())) {
prop.getField().getJavaDoc().setFullText(option.getDescription());
}
if (!Strings.isBlank(option.getDefaultValue())) {
if ("java.lang.String".equals(option.getJavaType())) {
prop.getField().setStringInitializer(option.getDefaultValue());
} else if ("long".equals(option.getJavaType()) || "java.lang.Long".equals(option.getJavaType())) {
// the value should be a Long number
String value = option.getDefaultValue() + "L";
prop.getField().setLiteralInitializer(value);
} else if ("integer".equals(option.getType()) || "boolean".equals(option.getType())) {
prop.getField().setLiteralInitializer(option.getDefaultValue());
} else if (!Strings.isBlank(option.getEnums())) {
String enumShortName = type.substring(type.lastIndexOf(".") + 1);
prop.getField().setLiteralInitializer(enumShortName + "." + option.getDefaultValue());
javaClass.addImport(model.getJavaType());
}
}
}
}
sortImports(javaClass);
String fileName = packageName.replaceAll("\\.", "\\/") + "/" + name + ".java";
writeSourceIfChanged(javaClass, fileName);
}
private void createConnectorAutoConfigurationSource(String packageName, boolean hasOptions,
String javaType, String connectorScheme) throws MojoFailureException {
final JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
int pos = javaType.lastIndexOf(".");
String name = javaType.substring(pos + 1);
name = name.replace("Component", "ConnectorAutoConfiguration");
javaClass.setPackage(packageName).setName(name);
String doc = "Generated by camel-connector-maven-plugin - do not edit this file!";
javaClass.getJavaDoc().setFullText(doc);
javaClass.addAnnotation(Configuration.class);
javaClass.addAnnotation(ConditionalOnBean.class).setStringValue("type", "org.apache.camel.spring.boot.CamelAutoConfiguration");
javaClass.addAnnotation(AutoConfigureAfter.class).setStringValue("name", "org.apache.camel.spring.boot.CamelAutoConfiguration");
String configurationName = name.replace("ConnectorAutoConfiguration", "ConnectorConfiguration");
if (hasOptions) {
AnnotationSource<JavaClassSource> ann = javaClass.addAnnotation(EnableConfigurationProperties.class);
ann.setLiteralValue("value", configurationName + ".class");
javaClass.addImport("java.util.HashMap");
javaClass.addImport("java.util.Map");
javaClass.addImport("org.apache.camel.util.IntrospectionSupport");
}
javaClass.addImport(javaType);
javaClass.addImport("org.apache.camel.CamelContext");
// add method for auto configure
String shortJavaType = getShortJavaType(javaType);
String body = createComponentBody(shortJavaType, hasOptions);
String methodName = "configure" + shortJavaType;
MethodSource<JavaClassSource> method = javaClass.addMethod()
.setName(methodName)
.setPublic()
.setBody(body)
.setReturnType(shortJavaType)
.addThrows(Exception.class);
method.addParameter("CamelContext", "camelContext");
if (hasOptions) {
method.addParameter(configurationName, "configuration");
}
// must be named -component because camel-spring-boot uses that to lookup components
String beanName = connectorScheme + "-component";
method.addAnnotation(Lazy.class);
method.addAnnotation(Bean.class).setStringValue("name", beanName);
method.addAnnotation(ConditionalOnClass.class).setLiteralValue("value", "CamelContext.class");
method.addAnnotation(ConditionalOnMissingBean.class).setLiteralValue("value", javaType + ".class");
sortImports(javaClass);
String fileName = packageName.replaceAll("\\.", "\\/") + "/" + name + ".java";
writeSourceIfChanged(javaClass, fileName);
}
private void writeSourceIfChanged(JavaClassSource source, String fileName) throws MojoFailureException {
// project root folder
File root = classesDirectory.getParentFile().getParentFile();
File target = new File(root, "src/main/java/" + fileName);
try {
String header = "";
if (includeLicenseHeader) {
InputStream is = getClass().getClassLoader().getResourceAsStream("license-header-java.txt");
header = loadText(is);
}
String code = sourceToString(source);
code = header + code;
getLog().debug("Source code generated:\n" + code);
if (target.exists()) {
String existing = FileUtils.readFileToString(target);
if (!code.equals(existing)) {
FileUtils.write(target, code, false);
getLog().info("Updated existing file: " + target);
} else {
getLog().debug("No changes to existing file: " + target);
}
} else {
FileUtils.write(target, code);
getLog().info("Created file: " + target);
}
} catch (Exception e) {
throw new MojoFailureException("IOError with file " + target, e);
}
}
private static String createComponentBody(String shortJavaType, boolean hasOptions) {
StringBuilder sb = new StringBuilder();
sb.append(shortJavaType).append(" connector = new ").append(shortJavaType).append("();").append("\n");
sb.append("connector.setCamelContext(camelContext);\n");
sb.append("\n");
if (hasOptions) {
sb.append("Map<String, Object> parameters = new HashMap<>();\n");
sb.append("IntrospectionSupport.getProperties(configuration, parameters, null, false);\n");
sb.append("IntrospectionSupport.setProperties(camelContext, camelContext.getTypeConverter(), connector, parameters);\n");
sb.append("connector.setComponentOptions(parameters);\n");
}
sb.append("\n");
sb.append("return connector;");
return sb.toString();
}
private static void sortImports(JavaClassSource javaClass) {
// sort imports
List<Import> imports = javaClass.getImports();
// sort imports
List<String> names = new ArrayList<>();
for (Import imp : imports) {
names.add(imp.getQualifiedName());
}
// sort
Collections.sort(names, (s1, s2) -> {
// java comes first
if (s1.startsWith("java.")) {
s1 = "___" + s1;
}
if (s2.startsWith("java.")) {
s2 = "___" + s2;
}
// then javax comes next
if (s1.startsWith("javax.")) {
s1 = "__" + s1;
}
if (s2.startsWith("javax.")) {
s2 = "__" + s2;
}
// org.w3c is for some odd reason also before others
if (s1.startsWith("org.w3c.")) {
s1 = "_" + s1;
}
if (s2.startsWith("org.w3c.")) {
s2 = "_" + s2;
}
return s1.compareTo(s2);
});
// remove all imports first
for (String name : names) {
javaClass.removeImport(name);
}
// and add them back in correct order
for (String name : names) {
javaClass.addImport(name);
}
}
private static String sourceToString(JavaClassSource javaClass) {
String code = Formatter.format(javaClass);
// convert tabs to 4 spaces
code = code.replaceAll("\\t", " ");
return code;
}
private static ComponentModel generateComponentModel(String json) {
List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("component", json, false);
ComponentModel component = new ComponentModel();
component.setScheme(getSafeValue("scheme", rows));
component.setSyntax(getSafeValue("syntax", rows));
component.setAlternativeSyntax(getSafeValue("alternativeSyntax", rows));
component.setTitle(getSafeValue("title", rows));
component.setDescription(getSafeValue("description", rows));
component.setFirstVersion(getSafeValue("firstVersion", rows));
component.setLabel(getSafeValue("label", rows));
component.setDeprecated(getSafeValue("deprecated", rows));
component.setConsumerOnly(getSafeValue("consumerOnly", rows));
component.setProducerOnly(getSafeValue("producerOnly", rows));
component.setJavaType(getSafeValue("javaType", rows));
component.setGroupId(getSafeValue("groupId", rows));
component.setArtifactId(getSafeValue("artifactId", rows));
component.setVersion(getSafeValue("version", rows));
rows = JSonSchemaHelper.parseJsonSchema("componentProperties", json, true);
for (Map<String, String> row : rows) {
ComponentOptionModel option = new ComponentOptionModel();
option.setName(getSafeValue("name", row));
option.setDisplayName(getSafeValue("displayName", row));
option.setKind(getSafeValue("kind", row));
option.setType(getSafeValue("type", row));
option.setJavaType(getSafeValue("javaType", row));
option.setDeprecated(getSafeValue("deprecated", row));
option.setDescription(getSafeValue("description", row));
option.setDefaultValue(getSafeValue("defaultValue", row));
option.setEnums(getSafeValue("enum", row));
component.addComponentOption(option);
}
return component;
}
}
| |
/*
* Copyright 2013 Google 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.google.android.apps.dashclock.phone;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import net.nurik.roman.dashclock.R;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
/**
* Unread SMS and MMS's extension.
*/
public class SmsExtension extends DashClockExtension {
private static final String TAG = LogUtils.makeLogTag(SmsExtension.class);
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
if (!isReconnect) {
addWatchContentUris(new String[]{
TelephonyProviderConstants.MmsSms.CONTENT_URI.toString(),
});
}
}
@Override
protected void onUpdateData(int reason) {
int unreadConversations = 0;
StringBuilder names = new StringBuilder();
Cursor cursor = openMmsSmsCursor();
long threadId = 0;
while (cursor.moveToNext()) {
++unreadConversations;
// Get display name. SMS's are easy; MMS's not so much.
long id = cursor.getLong(MmsSmsQuery._ID);
long contactId = cursor.getLong(MmsSmsQuery.PERSON);
String address = cursor.getString(MmsSmsQuery.ADDRESS);
threadId = cursor.getLong(MmsSmsQuery.THREAD_ID);
if (contactId == 0 && TextUtils.isEmpty(address) && id != 0) {
// Try MMS addr query
Cursor addrCursor = openMmsAddrCursor(id);
if (addrCursor.moveToFirst()) {
contactId = addrCursor.getLong(MmsAddrQuery.CONTACT_ID);
address = addrCursor.getString(MmsAddrQuery.ADDRESS);
}
addrCursor.close();
}
String displayName = address;
if (contactId > 0) {
Cursor contactCursor = openContactsCursorById(contactId);
if (contactCursor.moveToFirst()) {
displayName = contactCursor.getString(RawContactsQuery.DISPLAY_NAME);
} else {
contactId = 0;
}
contactCursor.close();
}
if (contactId <= 0) {
Cursor contactCursor = openContactsCursorByAddress(address);
if (contactCursor.moveToFirst()) {
displayName = contactCursor.getString(ContactsQuery.DISPLAY_NAME);
}
contactCursor.close();
}
if (names.length() > 0) {
names.append(", ");
}
names.append(displayName);
}
cursor.close();
Intent clickIntent;
if (unreadConversations == 1 && threadId > 0) {
clickIntent = new Intent(Intent.ACTION_VIEW,
TelephonyProviderConstants.MmsSms.CONTENT_CONVERSATIONS_URI.buildUpon()
.appendPath(Long.toString(threadId)).build());
} else {
clickIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
Intent.CATEGORY_APP_MESSAGING);
}
publishUpdate(new ExtensionData()
.visible(unreadConversations > 0)
.icon(R.drawable.ic_extension_sms)
.status(Integer.toString(unreadConversations))
.expandedTitle(
getResources().getQuantityString(
R.plurals.sms_title_template, unreadConversations,
unreadConversations))
.expandedBody(getString(R.string.sms_body_template, names.toString()))
.clickIntent(clickIntent));
}
private Cursor openMmsSmsCursor() {
return getContentResolver().query(
TelephonyProviderConstants.MmsSms.CONTENT_CONVERSATIONS_URI,
MmsSmsQuery.PROJECTION,
TelephonyProviderConstants.Mms.READ + "=0 AND ("
+ TelephonyProviderConstants.Mms.MESSAGE_BOX + "="
+ TelephonyProviderConstants.Mms.MESSAGE_BOX_INBOX + " OR "
+ TelephonyProviderConstants.Sms.TYPE + "="
+ TelephonyProviderConstants.Sms.MESSAGE_TYPE_INBOX + ")",
null,
null);
}
private Cursor openMmsAddrCursor(long mmsMsgId) {
return getContentResolver().query(
TelephonyProviderConstants.Mms.CONTENT_URI.buildUpon()
.appendPath(Long.toString(mmsMsgId))
.appendPath("addr")
.build(),
MmsAddrQuery.PROJECTION,
TelephonyProviderConstants.Mms.Addr.MSG_ID + "=?",
new String[]{Long.toString(mmsMsgId)},
null);
}
private Cursor openContactsCursorById(long contactId) {
return getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI.buildUpon()
.appendPath(Long.toString(contactId))
.build(),
RawContactsQuery.PROJECTION,
null,
null,
null);
}
private Cursor openContactsCursorByAddress(String phoneNumber) {
return getContentResolver().query(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI.buildUpon()
.appendPath(Uri.encode(phoneNumber)).build(),
ContactsQuery.PROJECTION,
null,
null,
null);
}
private interface MmsSmsQuery {
String[] PROJECTION = {
TelephonyProviderConstants.Sms._ID,
TelephonyProviderConstants.Sms.ADDRESS,
TelephonyProviderConstants.Sms.PERSON,
TelephonyProviderConstants.Sms.THREAD_ID,
};
int _ID = 0;
int ADDRESS = 1;
int PERSON = 2;
int THREAD_ID = 3;
}
private interface MmsAddrQuery {
String[] PROJECTION = {
TelephonyProviderConstants.Mms.Addr.ADDRESS,
TelephonyProviderConstants.Mms.Addr.CONTACT_ID,
};
int ADDRESS = 0;
int CONTACT_ID = 1;
}
private interface RawContactsQuery {
String[] PROJECTION = {
ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY,
};
int DISPLAY_NAME = 0;
}
private interface ContactsQuery {
String[] PROJECTION = {
ContactsContract.Contacts.DISPLAY_NAME,
};
int DISPLAY_NAME = 0;
}
}
| |
/*
* 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.zookeeper.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.Time;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClientHammerTest extends ClientBase {
protected static final Logger LOG = LoggerFactory.getLogger(ClientHammerTest.class);
private static final long HAMMERTHREAD_LATENCY = 5;
private abstract static class HammerThread extends Thread {
protected final int count;
protected volatile int current = 0;
HammerThread(String name, int count) {
super(name);
this.count = count;
}
}
private static class BasicHammerThread extends HammerThread {
private final ZooKeeper zk;
private final String prefix;
BasicHammerThread(String name, ZooKeeper zk, String prefix, int count) {
super(name, count);
this.zk = zk;
this.prefix = prefix;
}
public void run() {
byte[] b = new byte[256];
try {
for (; current < count; current++) {
// Simulate a bit of network latency...
Thread.sleep(HAMMERTHREAD_LATENCY);
zk.create(prefix + current, b, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} catch (Throwable t) {
LOG.error("Client create operation failed", t);
} finally {
try {
zk.close();
} catch (InterruptedException e) {
LOG.warn("Unexpected", e);
}
}
}
}
private static class SuperHammerThread extends HammerThread {
private final ClientHammerTest parent;
private final String prefix;
SuperHammerThread(String name, ClientHammerTest parent, String prefix, int count) {
super(name, count);
this.parent = parent;
this.prefix = prefix;
}
public void run() {
byte[] b = new byte[256];
try {
for (; current < count; current++) {
ZooKeeper zk = parent.createClient();
try {
zk.create(prefix + current, b, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} finally {
try {
zk.close();
} catch (InterruptedException e) {
LOG.warn("Unexpected", e);
}
}
}
} catch (Throwable t) {
LOG.error("Client create operation failed", t);
}
}
}
/**
* Separate threads each creating a number of nodes. Each thread
* is using a non-shared (owned by thread) client for all node creations.
* @throws Throwable
*/
@Test
public void testHammerBasic() throws Throwable {
runHammer(10, 1000);
}
public void runHammer(final int threadCount, final int childCount) throws Throwable {
try {
HammerThread[] threads = new HammerThread[threadCount];
long start = Time.currentElapsedTime();
for (int i = 0; i < threads.length; i++) {
ZooKeeper zk = createClient();
String prefix = "/test-" + i;
zk.create(prefix, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
prefix += "/";
HammerThread thread = new BasicHammerThread("BasicHammerThread-" + i, zk, prefix, childCount);
thread.start();
threads[i] = thread;
}
verifyHammer(start, threads, childCount);
} catch (Throwable t) {
LOG.error("test failed", t);
throw t;
}
}
/**
* Separate threads each creating a number of nodes. Each thread
* is creating a new client for each node creation.
* @throws Throwable
*/
@Test
public void testHammerSuper() throws Throwable {
try {
final int threadCount = 5;
final int childCount = 10;
HammerThread[] threads = new HammerThread[threadCount];
long start = Time.currentElapsedTime();
for (int i = 0; i < threads.length; i++) {
String prefix = "/test-" + i;
{
ZooKeeper zk = createClient();
try {
zk.create(prefix, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} finally {
zk.close();
}
}
prefix += "/";
HammerThread thread = new SuperHammerThread("SuperHammerThread-" + i, this, prefix, childCount);
thread.start();
threads[i] = thread;
}
verifyHammer(start, threads, childCount);
} catch (Throwable t) {
LOG.error("test failed", t);
throw t;
}
}
public void verifyHammer(long start, HammerThread[] threads, int childCount) throws IOException, InterruptedException, KeeperException {
// look for the clients to finish their create operations
LOG.info("Starting check for completed hammers");
int workingCount = threads.length;
for (int i = 0; i < 120; i++) {
Thread.sleep(10000);
for (HammerThread h : threads) {
if (!h.isAlive() || h.current == h.count) {
workingCount--;
}
}
if (workingCount == 0) {
break;
}
workingCount = threads.length;
}
if (workingCount > 0) {
for (HammerThread h : threads) {
LOG.warn("{} never finished creation, current:{}", h.getName(), h.current);
}
} else {
LOG.info("Hammer threads completed creation operations");
}
for (HammerThread h : threads) {
final int safetyFactor = 3;
verifyThreadTerminated(h, (long) threads.length
* (long) childCount
* HAMMERTHREAD_LATENCY
* (long) safetyFactor);
}
LOG.info("{} Total time {}", new Date(), (Time.currentElapsedTime() - start));
ZooKeeper zk = createClient();
try {
LOG.info("******************* Connected to ZooKeeper{}", new Date());
for (int i = 0; i < threads.length; i++) {
LOG.info("Doing thread: {} {}", i, new Date());
List<String> children = zk.getChildren("/test-" + i, false);
assertEquals(childCount, children.size());
children = zk.getChildren("/test-" + i, false, null);
assertEquals(childCount, children.size());
}
for (int i = 0; i < threads.length; i++) {
List<String> children = zk.getChildren("/test-" + i, false);
assertEquals(childCount, children.size());
children = zk.getChildren("/test-" + i, false, null);
assertEquals(childCount, children.size());
}
} finally {
zk.close();
}
}
}
| |
/*
* Copyright 2014-present Facebook, 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.facebook.buck.python;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.cxx.CxxBuckConfig;
import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.DefaultCxxPlatforms;
import com.facebook.buck.io.MorePathsForTests;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleParamsFactory;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.FakeBuildRuleParamsBuilder;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TestSourcePath;
import com.facebook.buck.shell.Genrule;
import com.facebook.buck.shell.GenruleBuilder;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import org.hamcrest.Matchers;
import org.junit.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PythonBinaryDescriptionTest {
private static final Path PEX_PATH = Paths.get("pex");
private static final Path PEX_EXECUTER_PATH = MorePathsForTests.rootRelativePath("/not/python2");
private static final String PEX_EXTENSION = ".pex";
private static final CxxPlatform CXX_PLATFORM = DefaultCxxPlatforms.build(
new CxxBuckConfig(new FakeBuckConfig()));
private static final FlavorDomain<CxxPlatform> CXX_PLATFORMS =
new FlavorDomain<>("platform", ImmutableMap.<Flavor, CxxPlatform>of());
@Test
public void thatComponentSourcePathDepsPropagateProperly() {
BuildRuleResolver resolver = new BuildRuleResolver();
Genrule genrule = (Genrule) GenruleBuilder
.newGenruleBuilder(BuildTargetFactory.newInstance("//:gen"))
.setOut("blah.py")
.build(resolver);
BuildRuleParams libParams = BuildRuleParamsFactory.createTrivialBuildRuleParams(
BuildTargetFactory.newInstance("//:lib"));
PythonLibrary lib = new PythonLibrary(
libParams,
new SourcePathResolver(resolver),
ImmutableMap.<Path, SourcePath>of(
Paths.get("hello"),
new BuildTargetSourcePath(genrule.getBuildTarget())),
ImmutableMap.<Path, SourcePath>of(),
Optional.<Boolean>absent());
BuildRuleParams params =
new FakeBuildRuleParamsBuilder(BuildTargetFactory.newInstance("//:bin"))
.setDeps(ImmutableSortedSet.<BuildRule>of(lib))
.build();
PythonBinaryDescription desc = new PythonBinaryDescription(
PEX_PATH,
PEX_EXECUTER_PATH,
PEX_EXTENSION,
new PythonEnvironment(Paths.get("fake_python"), PythonVersion.of("Python 2.7")),
CXX_PLATFORM,
CXX_PLATFORMS);
PythonBinaryDescription.Arg arg = desc.createUnpopulatedConstructorArg();
arg.deps = Optional.of(ImmutableSortedSet.<BuildTarget>of());
arg.mainModule = Optional.absent();
arg.main = Optional.<SourcePath>of(new TestSourcePath("blah.py"));
arg.baseModule = Optional.absent();
arg.zipSafe = Optional.absent();
BuildRule rule = desc.createBuildRule(params, resolver, arg);
assertEquals(
ImmutableSortedSet.<BuildRule>of(genrule),
rule.getDeps());
}
@Test
public void thatMainSourcePathPropagatesToDeps() {
BuildRuleResolver resolver = new BuildRuleResolver();
Genrule genrule = (Genrule) GenruleBuilder
.newGenruleBuilder(BuildTargetFactory.newInstance("//:gen"))
.setOut("blah.py")
.build(resolver);
BuildRuleParams params = BuildRuleParamsFactory.createTrivialBuildRuleParams(
BuildTargetFactory.newInstance("//:bin"));
PythonBinaryDescription desc = new PythonBinaryDescription(
PEX_PATH,
PEX_EXECUTER_PATH,
PEX_EXTENSION,
new PythonEnvironment(Paths.get("fake_python"), PythonVersion.of("Python 2.7")),
CXX_PLATFORM,
CXX_PLATFORMS);
PythonBinaryDescription.Arg arg = desc.createUnpopulatedConstructorArg();
arg.deps = Optional.of(ImmutableSortedSet.<BuildTarget>of());
arg.mainModule = Optional.absent();
arg.main =
Optional.<SourcePath>of(
new BuildTargetSourcePath(genrule.getBuildTarget()));
arg.baseModule = Optional.absent();
arg.zipSafe = Optional.absent();
BuildRule rule = desc.createBuildRule(params, resolver, arg);
assertEquals(
ImmutableSortedSet.<BuildRule>of(genrule),
rule.getDeps());
}
@Test
public void baseModule() {
BuildRuleResolver resolver = new BuildRuleResolver();
BuildTarget target = BuildTargetFactory.newInstance("//foo:bin");
BuildRuleParams params = BuildRuleParamsFactory.createTrivialBuildRuleParams(target);
String mainName = "main.py";
PythonBinaryDescription desc = new PythonBinaryDescription(
PEX_PATH,
PEX_EXECUTER_PATH,
PEX_EXTENSION,
new PythonEnvironment(Paths.get("python"), PythonVersion.of("2.5")),
CXX_PLATFORM,
CXX_PLATFORMS);
PythonBinaryDescription.Arg arg = desc.createUnpopulatedConstructorArg();
arg.deps = Optional.of(ImmutableSortedSet.<BuildTarget>of());
arg.mainModule = Optional.absent();
arg.main = Optional.<SourcePath>of(new TestSourcePath("foo/" + mainName));
arg.zipSafe = Optional.absent();
// Run without a base module set and verify it defaults to using the build target
// base name.
arg.baseModule = Optional.absent();
PythonBinary normalRule = desc.createBuildRule(params, resolver, arg);
assertEquals(
PythonUtil.toModuleName(target, target.getBasePath().resolve(mainName).toString()),
normalRule.getMainModule());
// Run *with* a base module set and verify it gets used to build the main module path.
arg.baseModule = Optional.of("blah");
PythonBinary baseModuleRule = desc.createBuildRule(params, resolver, arg);
assertEquals(
PythonUtil.toModuleName(
target,
Paths.get(arg.baseModule.get()).resolve(mainName).toString()),
baseModuleRule.getMainModule());
}
@Test
public void mainModule() {
BuildRuleResolver resolver = new BuildRuleResolver();
BuildTarget target = BuildTargetFactory.newInstance("//foo:bin");
BuildRuleParams params = BuildRuleParamsFactory.createTrivialBuildRuleParams(target);
String mainModule = "foo.main";
PythonBinaryDescription desc = new PythonBinaryDescription(
PEX_PATH,
PEX_EXECUTER_PATH,
PEX_EXTENSION,
new PythonEnvironment(Paths.get("python"), PythonVersion.of("2.5")),
CXX_PLATFORM,
CXX_PLATFORMS);
PythonBinaryDescription.Arg arg = desc.createUnpopulatedConstructorArg();
arg.deps = Optional.of(ImmutableSortedSet.<BuildTarget>of());
arg.mainModule = Optional.of(mainModule);
arg.main = Optional.absent();
arg.baseModule = Optional.absent();
arg.zipSafe = Optional.absent();
PythonBinary rule = desc.createBuildRule(params, resolver, arg);
assertEquals(mainModule, rule.getMainModule());
}
@Test
public void pexExtension() {
BuildRuleResolver resolver = new BuildRuleResolver();
BuildTarget target = BuildTargetFactory.newInstance("//foo:bin");
BuildRuleParams params = BuildRuleParamsFactory.createTrivialBuildRuleParams(target);
PythonBinaryDescription desc =
new PythonBinaryDescription(
PEX_PATH,
PEX_EXECUTER_PATH,
".different_extension",
new PythonEnvironment(Paths.get("python"), PythonVersion.of("2.5")),
CXX_PLATFORM,
CXX_PLATFORMS);
PythonBinaryDescription.Arg arg = desc.createUnpopulatedConstructorArg();
arg.deps = Optional.of(ImmutableSortedSet.<BuildTarget>of());
arg.mainModule = Optional.of("main");
arg.main = Optional.absent();
arg.baseModule = Optional.absent();
arg.zipSafe = Optional.absent();
PythonBinary rule = desc.createBuildRule(params, resolver, arg);
assertThat(
Preconditions.checkNotNull(rule.getPathToOutput()).toString(),
Matchers.endsWith(".different_extension"));
}
}
| |
/*
* 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.cache.query.dunit;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.CacheException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.query.CqAttributes;
import org.apache.geode.cache.query.CqAttributesFactory;
import org.apache.geode.cache.query.CqEvent;
import org.apache.geode.cache.query.CqListener;
import org.apache.geode.cache.query.CqQuery;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.SelectResults;
import org.apache.geode.cache.query.Struct;
import org.apache.geode.cache.query.cq.dunit.CqQueryTestListener;
import org.apache.geode.cache.query.dunit.PdxQueryCQTestBase.TestObject;
import org.apache.geode.cache30.CacheSerializableRunnable;
import org.apache.geode.cache30.ClientServerTestCase;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.dunit.NetworkUtils;
import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.Wait;
import org.apache.geode.test.dunit.WaitCriterion;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
import org.apache.geode.test.junit.categories.ClientSubscriptionTest;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.SerializationTest;
@Category({DistributedTest.class, SerializationTest.class, ClientSubscriptionTest.class})
public class PdxQueryCQDUnitTest extends PdxQueryCQTestBase {
public PdxQueryCQDUnitTest() {
super();
}
/**
* Tests client-server query on PdxInstance.
*/
@Test
public void testCq() throws CacheException {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
final int numberOfEntries = 10;
final int queryLimit = 6; // where id > 5 (0-5)
// Start server1
vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
configAndStartBridgeServer();
Region region = getRootRegion().getSubregion(regionName);
for (int i = 0; i < numberOfEntries; i++) {
region.put("key-" + i, new TestObject(i, "vmware"));
}
}
});
// Start server2
vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
configAndStartBridgeServer();
Region region = getRootRegion().getSubregion(regionName);
}
});
// Client pool.
final int port0 = vm0.invoke(() -> PdxQueryCQTestBase.getCacheServerPort());
final int port1 = vm1.invoke(() -> PdxQueryCQTestBase.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(vm0.getHost());
// Create client pool.
final String poolName = "testCqPool";
createPool(vm2, poolName, new String[] {host0}, new int[] {port0}, true);
createPool(vm3, poolName, new String[] {host0}, new int[] {port1}, true);
final String cqName = "testCq";
// Execute CQ
SerializableRunnable executeCq = new CacheSerializableRunnable("Execute queries") {
public void run2() throws CacheException {
LogWriterUtils.getLogWriter().info("### Create CQ. ###" + cqName);
// Get CQ Service.
QueryService qService = null;
try {
qService = (PoolManager.find(poolName)).getQueryService();
} catch (Exception cqe) {
Assert.fail("Failed to getCQService.", cqe);
}
// Create CQ Attributes.
CqAttributesFactory cqf = new CqAttributesFactory();
CqListener[] cqListeners = {new CqQueryTestListener(LogWriterUtils.getLogWriter())};
((CqQueryTestListener) cqListeners[0]).cqName = cqName;
cqf.initCqListeners(cqListeners);
CqAttributes cqa = cqf.create();
// Create CQ.
try {
CqQuery cq = qService.newCq(cqName, queryString[3], cqa);
SelectResults sr = cq.executeWithInitialResults();
for (Object o : sr.asSet()) {
Struct s = (Struct) o;
Object value = s.get("value");
if (!(value instanceof TestObject)) {
fail(
"Expected type TestObject, not found in result set. Found type :" + o.getClass());
}
}
} catch (Exception ex) {
AssertionError err = new AssertionError("Failed to create CQ " + cqName + " . ");
err.initCause(ex);
LogWriterUtils.getLogWriter().info("QueryService is :" + qService, err);
throw err;
}
}
};
vm2.invoke(executeCq);
vm3.invoke(executeCq);
// Check for TestObject instances on Server2.
// It should be 0
vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
assertEquals(0, TestObject.numInstance);
}
});
// update
vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
for (int i = 0; i < numberOfEntries * 2; i++) {
region.put("key-" + i, new TestObject(i, "vmware"));
}
// Check for TestObject instances.
assertEquals(numberOfEntries * 3, TestObject.numInstance);
}
});
// Check for TestObject instances on Server2.
// It should be 0
vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
assertEquals(0, TestObject.numInstance);
}
});
SerializableRunnable validateCq = new CacheSerializableRunnable("Validate CQs") {
public void run2() throws CacheException {
LogWriterUtils.getLogWriter().info("### Validating CQ. ### " + cqName);
// Get CQ Service.
QueryService cqService = null;
try {
cqService = getCache().getQueryService();
} catch (Exception cqe) {
Assert.fail("Failed to getCQService.", cqe);
}
CqQuery cQuery = cqService.getCq(cqName);
if (cQuery == null) {
fail("Failed to get CqQuery for CQ : " + cqName);
}
CqAttributes cqAttr = cQuery.getCqAttributes();
CqListener cqListeners[] = cqAttr.getCqListeners();
final CqQueryTestListener listener = (CqQueryTestListener) cqListeners[0];
// Wait for the events to show up on the client.
Wait.waitForCriterion(new WaitCriterion() {
public boolean done() {
return listener.getTotalEventCount() >= (numberOfEntries * 2 - queryLimit);
}
public String description() {
return null;
}
}, 30000, 100, false);
listener.printInfo(false);
// Check for event type.
Object[] cqEvents = listener.getEvents();
for (Object o : cqEvents) {
CqEvent cqEvent = (CqEvent) o;
Object value = cqEvent.getNewValue();
if (!(value instanceof TestObject)) {
fail("Expected type TestObject, not found in result set. Found type :" + o.getClass());
}
}
// Check for totalEvents count.
assertEquals("Total Event Count mismatch", (numberOfEntries * 2 - queryLimit),
listener.getTotalEventCount());
// Check for create count.
assertEquals("Create Event mismatch", numberOfEntries, listener.getCreateEventCount());
// Check for update count.
assertEquals("Update Event mismatch", numberOfEntries - queryLimit,
listener.getUpdateEventCount());
}
};
vm2.invoke(validateCq);
vm3.invoke(validateCq);
this.closeClient(vm2);
this.closeClient(vm3);
this.closeClient(vm1);
this.closeClient(vm0);
}
/**
* Tests client-server query on PdxInstance.
*/
@Test
public void testCqAndInterestRegistrations() throws CacheException {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
final int numberOfEntries = 10;
final int queryLimit = 6; // where id > 5 (0-5)
final String[] queries =
new String[] {"SELECT * FROM " + regName + " p WHERE p.ticker = 'vmware'",
"SELECT * FROM " + regName + " WHERE id > 5",};
// Start server1
vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
configAndStartBridgeServer(false, true);
Region region = getRootRegion().getSubregion(regionName);
}
});
// Start server2
vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
configAndStartBridgeServer(false, true);
Region region = getRootRegion().getSubregion(regionName);
}
});
// Client pool.
final int port0 = vm0.invoke(() -> PdxQueryCQTestBase.getCacheServerPort());
final int port1 = vm1.invoke(() -> PdxQueryCQTestBase.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(vm0.getHost());
// Create client pool.
final String poolName = "testCqPool";
createPool(vm2, poolName, new String[] {host0, host0}, new int[] {port0, port1}, true);
createPool(vm3, poolName, new String[] {host0, host0}, new int[] {port1, port0}, true);
final String cqName = "testCq";
vm3.invoke(new CacheSerializableRunnable("init region") {
public void run2() throws CacheException {
QueryService localQueryService = null;
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
ClientServerTestCase.configureConnectionPool(factory, host0, port1, -1, true, -1, -1, null);
Region region = createRegion(regionName, rootRegionName, factory.create());
for (int i = 0; i < numberOfEntries; i++) {
region.put("key-" + i, new TestObject(i, "vmware"));
}
}
});
vm2.invoke(new CacheSerializableRunnable("init region") {
public void run2() throws CacheException {
QueryService localQueryService = null;
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
ClientServerTestCase.configureConnectionPool(factory, host0, port0, -1, true, -1, -1, null);
Region region = createRegion(regionName, rootRegionName, factory.create());
}
});
SerializableRunnable subscribe = new CacheSerializableRunnable("subscribe") {
public void run2() throws CacheException {
// Register interest
Region region = getRootRegion().getSubregion(regionName);
List list = new ArrayList();
for (int i = 1; i <= numberOfEntries * 3; i++) {
if (i % 4 == 0) {
list.add("key-" + i);
}
}
region.registerInterest(list);
LogWriterUtils.getLogWriter().info("### Create CQ. ###" + cqName);
// Get CQ Service.
QueryService qService = null;
try {
qService = (PoolManager.find(poolName)).getQueryService();
} catch (Exception cqe) {
Assert.fail("Failed to getCQService.", cqe);
}
// Create CQ Attributes.
for (int i = 0; i < queries.length; i++) {
CqAttributesFactory cqf = new CqAttributesFactory();
CqListener[] cqListeners = {new CqQueryTestListener(LogWriterUtils.getLogWriter())};
((CqQueryTestListener) cqListeners[0]).cqName = (cqName + i);
cqf.initCqListeners(cqListeners);
CqAttributes cqa = cqf.create();
// Create CQ.
try {
CqQuery cq = qService.newCq(cqName + i, queries[i], cqa);
SelectResults sr = cq.executeWithInitialResults();
for (Object o : sr.asSet()) {
Struct s = (Struct) o;
Object value = s.get("value");
if (!(value instanceof TestObject)) {
fail("Expected type TestObject, not found in result set. Found type :"
+ o.getClass());
}
}
} catch (Exception ex) {
AssertionError err = new AssertionError("Failed to create CQ " + cqName + " . ");
err.initCause(ex);
LogWriterUtils.getLogWriter().info("QueryService is :" + qService, err);
throw err;
}
}
}
};
vm2.invoke(subscribe);
vm3.invoke(subscribe);
// Check for TestObject instances on Server2.
// It should be 0
vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
assertEquals(0, TestObject.numInstance);
}
});
vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
// Check for TestObject instances.
assertEquals(0, TestObject.numInstance);
}
});
vm3.invoke(new CacheSerializableRunnable("Update") {
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
for (int i = 0; i < numberOfEntries * 2; i++) {
region.put("key-" + i, new TestObject(i, "vmware"));
}
}
});
// Validate CQs.
for (int i = 0; i < queries.length; i++) {
int expectedEvent = 0;
int updateEvents = 0;
if (i != 0) {
expectedEvent = numberOfEntries * 2 - queryLimit;
updateEvents = numberOfEntries - queryLimit;
} else {
expectedEvent = numberOfEntries * 2;
updateEvents = numberOfEntries;
}
validateCq(vm2, cqName + i, expectedEvent, numberOfEntries, updateEvents);
validateCq(vm3, cqName + i, expectedEvent, numberOfEntries, updateEvents);
}
vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
// Check for TestObject instances.
assertEquals(0, TestObject.numInstance);
}
});
// Check for TestObject instances on Server2.
// It should be 0
vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
assertEquals(0, TestObject.numInstance);
}
});
this.closeClient(vm2);
this.closeClient(vm3);
this.closeClient(vm1);
this.closeClient(vm0);
}
/**
* Tests client-server query on PdxInstance.
*/
@Test
public void testCqAndInterestRegistrationsWithFailOver() throws CacheException {
final Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
final int numberOfEntries = 10;
final int queryLimit = 6; // where id > 5 (0-5)
final String[] queries =
new String[] {"SELECT * FROM " + regName + " p WHERE p.ticker = 'vmware'",
"SELECT * FROM " + regName + " WHERE id > 5",};
// Start server1
vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
configAndStartBridgeServer(false, true);
Region region = getRootRegion().getSubregion(regionName);
}
});
// Start server2
vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
configAndStartBridgeServer(false, true);
Region region = getRootRegion().getSubregion(regionName);
}
});
// Start server3
vm2.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
configAndStartBridgeServer(false, true);
Region region = getRootRegion().getSubregion(regionName);
}
});
// Client pool.
final int port0 = vm0.invoke(() -> PdxQueryCQTestBase.getCacheServerPort());
final int port1 = vm1.invoke(() -> PdxQueryCQTestBase.getCacheServerPort());
final int port2 = vm2.invoke(() -> PdxQueryCQTestBase.getCacheServerPort());
final String host0 = NetworkUtils.getServerHostName(vm0.getHost());
// Create client pool.
final String poolName = "testCqPool";
createPool(vm3, poolName, new String[] {host0, host0, host0}, new int[] {port1, port0, port2},
true, 1);
final String cqName = "testCq";
vm3.invoke(new CacheSerializableRunnable("init region") {
public void run2() throws CacheException {
QueryService localQueryService = null;
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
ClientServerTestCase.configureConnectionPool(factory, host0, port1, -1, true, -1, -1, null);
Region region = createRegion(regionName, rootRegionName, factory.create());
for (int i = 0; i < numberOfEntries; i++) {
region.put("key-" + i, new TestObject(i, "vmware"));
}
}
});
SerializableRunnable subscribe = new CacheSerializableRunnable("subscribe") {
public void run2() throws CacheException {
// Register interest
Region region = getRootRegion().getSubregion(regionName);
List list = new ArrayList();
for (int i = 1; i <= numberOfEntries * 3; i++) {
if (i % 4 == 0) {
list.add("key-" + i);
}
}
region.registerInterest(list);
LogWriterUtils.getLogWriter().info("### Create CQ. ###" + cqName);
// Get CQ Service.
QueryService qService = null;
try {
qService = (PoolManager.find(poolName)).getQueryService();
} catch (Exception cqe) {
Assert.fail("Failed to getCQService.", cqe);
}
// Create CQ Attributes.
for (int i = 0; i < queries.length; i++) {
CqAttributesFactory cqf = new CqAttributesFactory();
CqListener[] cqListeners = {new CqQueryTestListener(LogWriterUtils.getLogWriter())};
((CqQueryTestListener) cqListeners[0]).cqName = (cqName + i);
cqf.initCqListeners(cqListeners);
CqAttributes cqa = cqf.create();
// Create CQ.
try {
CqQuery cq = qService.newCq(cqName + i, queries[i], cqa);
SelectResults sr = cq.executeWithInitialResults();
for (Object o : sr.asSet()) {
Struct s = (Struct) o;
Object value = s.get("value");
if (!(value instanceof TestObject)) {
fail("Expected type TestObject, not found in result set. Found type :"
+ o.getClass());
}
}
} catch (Exception ex) {
AssertionError err = new AssertionError("Failed to create CQ " + cqName + " . ");
err.initCause(ex);
LogWriterUtils.getLogWriter().info("QueryService is :" + qService, err);
throw err;
}
}
}
};
vm3.invoke(subscribe);
// Check for TestObject instances on Server2.
// It should be 0
vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
assertEquals(0, TestObject.numInstance);
}
});
vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
// Check for TestObject instances.
assertEquals(0, TestObject.numInstance);
}
});
// update
vm3.invoke(new CacheSerializableRunnable("Update") {
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
for (int i = 0; i < numberOfEntries * 2; i++) {
region.put("key-" + i, new TestObject(i, "vmware"));
}
}
});
// Validate CQs.
for (int i = 0; i < queries.length; i++) {
int expectedEvent = 0;
int updateEvents = 0;
if (i != 0) {
expectedEvent = (numberOfEntries * 2) - queryLimit;
updateEvents = numberOfEntries - queryLimit;
} else {
expectedEvent = numberOfEntries * 2;
updateEvents = numberOfEntries;
}
validateCq(vm3, cqName + i, expectedEvent, numberOfEntries, updateEvents);
}
vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
// Check for TestObject instances.
assertEquals(0, TestObject.numInstance);
}
});
vm1.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
assertEquals(0, TestObject.numInstance);
}
});
// Update
vm3.invokeAsync(new CacheSerializableRunnable("Update") {
public void run2() throws CacheException {
Region region = getRootRegion().getSubregion(regionName);
for (int i = 0; i < numberOfEntries * 2; i++) {
region.put("key-" + i, new TestObject(i, "vmware"));
}
}
});
// Kill server
this.closeClient(vm0);
// validate cq
for (int i = 0; i < queries.length; i++) {
int expectedEvent = 0;
int updateEvents = 0;
if (i != 0) {
expectedEvent = (numberOfEntries * 4) - (queryLimit * 2); // Double the previous time
updateEvents = (numberOfEntries * 3) - (queryLimit * 2);
} else {
expectedEvent = numberOfEntries * 4;
updateEvents = numberOfEntries * 3;
}
validateCq(vm3, cqName + i, expectedEvent, numberOfEntries, updateEvents);
}
this.closeClient(vm1);
// Check for TestObject instances on Server3.
// It should be 0
vm2.invoke(new CacheSerializableRunnable("Create Bridge Server") {
public void run2() throws CacheException {
assertEquals(0, TestObject.numInstance);
}
});
this.closeClient(vm2);
this.closeClient(vm3);
}
public void validateCq(VM vm, final String cqName, final int expectedEvents,
final int createEvents, final int updateEvents) {
vm.invoke(new CacheSerializableRunnable("Validate CQs") {
public void run2() throws CacheException {
LogWriterUtils.getLogWriter().info("### Validating CQ. ### " + cqName);
// Get CQ Service.
QueryService cqService = null;
try {
cqService = getCache().getQueryService();
} catch (Exception cqe) {
Assert.fail("Failed to getCQService.", cqe);
}
CqQuery cQuery = cqService.getCq(cqName);
if (cQuery == null) {
fail("Failed to get CqQuery for CQ : " + cqName);
}
CqAttributes cqAttr = cQuery.getCqAttributes();
CqListener cqListeners[] = cqAttr.getCqListeners();
CqQueryTestListener listener = (CqQueryTestListener) cqListeners[0];
listener.printInfo(false);
// Check for event type.
Object[] cqEvents = listener.getEvents();
for (Object o : cqEvents) {
CqEvent cqEvent = (CqEvent) o;
Object value = cqEvent.getNewValue();
if (!(value instanceof TestObject)) {
fail("Expected type TestObject, not found in result set. Found type :" + o.getClass());
}
}
// Check for totalEvents count.
if (listener.getTotalEventCount() != expectedEvents) {
listener.waitForTotalEvents(expectedEvents);
}
assertEquals("Total Event Count mismatch", (expectedEvents), listener.getTotalEventCount());
// Check for create count.
assertEquals("Create Event mismatch", createEvents, listener.getCreateEventCount());
// Check for update count.
assertEquals("Update Event mismatch", updateEvents, listener.getUpdateEventCount());
}
});
}
}
| |
import javax.sound.midi.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
public class BeatBox {
JFrame frame;
JPanel panel;
ArrayList<JCheckBox> checkBoxes;
Sequencer sequencer;
Sequence sequence;
Track track;
String[] instrumentNames = {
"Bass Drum",
"Closed Hi-Hat",
"Open Hi-Hat",
"Acoustic Snare",
"Crash Cymbal",
"Hand Clap",
"High Tom",
"Hi Bongo",
"Maracas",
"Whistle",
"Low Conga",
"Cowbell",
"Vibraslap",
"Low-mid Tom",
"High Agogo",
"Open Hi Conga"
};
int[] instruments = {
35,
42,
46,
38,
49,
39,
50,
60,
70,
72,
64,
56,
58,
47,
67,
63
};
final static int ticks = 16;
final static int BMP = 120;
final static String CHECKBOXES_FILENAME = "checkboxes.ser";
public static void main (String args[]){
new BeatBox().build();
}
public void build(){
//setting up main frame
frame = new JFrame("Cyber Beatbox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel background = new JPanel(new BorderLayout());
background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
//checkboxes array
checkBoxes = new ArrayList<>();
//buttons box
Box buttons = new Box(BoxLayout.Y_AXIS);
//creating and adding buttons into buttons box
JButton start = new JButton("Start");
start.addActionListener(new StartListener());
buttons.add(start);
JButton stop = new JButton("Stop");
stop.addActionListener(new StopListener());
buttons.add(stop);
JButton tempoUP = new JButton("Tempo Up");
tempoUP.addActionListener(new TempoUPListener());
buttons.add(tempoUP);
JButton tempoDOWN = new JButton("Tempo Down");
tempoDOWN.addActionListener(new TempoDOWNListener());
buttons.add(tempoDOWN);
JButton reset = new JButton("Reset");
reset.addActionListener(new ResetListener());
buttons.add(reset);
JButton save = new JButton("Save this schema");
save.addActionListener(new SaveListener());
buttons.add(save);
JButton restore = new JButton("Restore last saved schema");
restore.addActionListener(new RestoreListener());
buttons.add(restore);
//instrument names box
Box names = new Box(BoxLayout.Y_AXIS);
for (int i = 0; i < instrumentNames.length; i++)
names.add(new Label(instrumentNames[i]));
//adding buttons and instument names boxes onto background panel
background.add(BorderLayout.EAST, buttons);
background.add(BorderLayout.WEST, names);
//adding background panel to main frame
frame.getContentPane().add(background);
//creating and adding grid 16x16 onto background panel
GridLayout grid = new GridLayout(instrumentNames.length, instruments.length);
grid.setVgap(1);
grid.setVgap(2);
panel = new JPanel(grid);
background.add(BorderLayout.CENTER, panel);
for (int i = 0; i < instrumentNames.length*instruments.length; i++) {
JCheckBox item = new JCheckBox();
item.setSelected(false);
checkBoxes.add(item);
panel.add(item);
}
setupMIDI();
frame.setBounds(50,50,300,300);
frame.pack();
frame.setVisible(true);
}
public void setupMIDI(){
try{
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequence = new Sequence(Sequence.PPQ, 4);
track = sequence.createTrack();
sequencer.setTempoInBPM(BMP);
} catch (Exception e){
e.printStackTrace();
}
}
public void buildTrackAndStrat(){
//to store value for each instrument for 16 ticks
int[] tracklist = null;
sequence.deleteTrack(track);
track = sequence.createTrack();
for (int i = 0; i < instruments.length; i++) {
tracklist = new int[ticks];
for (int j = 0; j < ticks; j++) {
if(checkBoxes.get(j+(16*i)).isSelected()){
tracklist[j] = instruments[i];
} else{
tracklist[j] = 0;
}
}
//creating events for this instrument for all 16 ticks and adding these into the track
makeTracks(tracklist);
track.add(makeEvent(176,1,127,0,16));
}
track.add(makeEvent(192,9,1,0,15));
try{
sequencer.setSequence(sequence);
sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
sequencer.setTempoInBPM(BMP);
} catch(Exception e){
e.printStackTrace();
}
}
public void makeTracks(int[] list){
for (int i = 0; i < ticks; i++) {
if(list[i] != 0){
track.add(makeEvent(144,9,list[i],100,i));
track.add(makeEvent(144,9,list[i],100,i+1));
}
}
}
public static MidiEvent makeEvent(int command, int channel, int data1, int data2, int tick){
MidiEvent event = null;
try {
ShortMessage a = new ShortMessage();
a.setMessage(command, channel, data1, data2);
event = new MidiEvent(a, tick);
}
catch (Exception e){
e.printStackTrace();
}
return event;
}
private class StartListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
buildTrackAndStrat();
}
}
private class StopListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
sequencer.stop();
}
}
private class TempoUPListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
sequencer.setTempoFactor(sequencer.getTempoFactor()*1.03f);
}
}
private class TempoDOWNListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
sequencer.setTempoFactor(sequencer.getTempoFactor()*0.97f);
}
}
private class ResetListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox cb:checkBoxes) {
cb.setSelected(false);
}
}
}
//turn to 494 page and do the task at the bottom of the page!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
private class SaveListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
boolean[] checkboxes = new boolean[256];
for (int i = 0; i < 256; i++)
checkboxes[i] = checkBoxes.get(i).isSelected();
try(FileOutputStream fs = new FileOutputStream(new File(CHECKBOXES_FILENAME))) {
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(checkboxes);
} catch (IOException ex){
ex.printStackTrace();
}
}
}
private class RestoreListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
boolean[] checkboxes = null;
try(FileInputStream fi = new FileInputStream(new File(CHECKBOXES_FILENAME))){
ObjectInputStream os = new ObjectInputStream(fi);
checkboxes = (boolean[]) os.readObject();
} catch(Exception ex) {
ex.printStackTrace();
}
for (int i = 0; i < checkboxes.length; i++)
checkBoxes.get(i).setSelected(checkboxes[i]);
sequencer.stop();
buildTrackAndStrat();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.