gt stringclasses 1 value | context stringlengths 2.05k 161k |
|---|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.storage.file.share.implementation.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.DateTimeRfc1123;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.time.OffsetDateTime;
/** The FilesSetHttpHeadersHeaders model. */
@JacksonXmlRootElement(localName = "null")
@Fluent
public final class FilesSetHttpHeadersHeaders {
/*
* The x-ms-version property.
*/
@JsonProperty(value = "x-ms-version")
private String xMsVersion;
/*
* The x-ms-file-permission-key property.
*/
@JsonProperty(value = "x-ms-file-permission-key")
private String xMsFilePermissionKey;
/*
* The x-ms-file-id property.
*/
@JsonProperty(value = "x-ms-file-id")
private String xMsFileId;
/*
* The x-ms-file-creation-time property.
*/
@JsonProperty(value = "x-ms-file-creation-time")
private OffsetDateTime xMsFileCreationTime;
/*
* The Last-Modified property.
*/
@JsonProperty(value = "Last-Modified")
private DateTimeRfc1123 lastModified;
/*
* The x-ms-request-server-encrypted property.
*/
@JsonProperty(value = "x-ms-request-server-encrypted")
private Boolean xMsRequestServerEncrypted;
/*
* The Date property.
*/
@JsonProperty(value = "Date")
private DateTimeRfc1123 dateProperty;
/*
* The ETag property.
*/
@JsonProperty(value = "ETag")
private String eTag;
/*
* The x-ms-file-attributes property.
*/
@JsonProperty(value = "x-ms-file-attributes")
private String xMsFileAttributes;
/*
* The x-ms-file-change-time property.
*/
@JsonProperty(value = "x-ms-file-change-time")
private OffsetDateTime xMsFileChangeTime;
/*
* The x-ms-file-parent-id property.
*/
@JsonProperty(value = "x-ms-file-parent-id")
private String xMsFileParentId;
/*
* The x-ms-request-id property.
*/
@JsonProperty(value = "x-ms-request-id")
private String xMsRequestId;
/*
* The x-ms-file-last-write-time property.
*/
@JsonProperty(value = "x-ms-file-last-write-time")
private OffsetDateTime xMsFileLastWriteTime;
/**
* Get the xMsVersion property: The x-ms-version property.
*
* @return the xMsVersion value.
*/
public String getXMsVersion() {
return this.xMsVersion;
}
/**
* Set the xMsVersion property: The x-ms-version property.
*
* @param xMsVersion the xMsVersion value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsVersion(String xMsVersion) {
this.xMsVersion = xMsVersion;
return this;
}
/**
* Get the xMsFilePermissionKey property: The x-ms-file-permission-key property.
*
* @return the xMsFilePermissionKey value.
*/
public String getXMsFilePermissionKey() {
return this.xMsFilePermissionKey;
}
/**
* Set the xMsFilePermissionKey property: The x-ms-file-permission-key property.
*
* @param xMsFilePermissionKey the xMsFilePermissionKey value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsFilePermissionKey(String xMsFilePermissionKey) {
this.xMsFilePermissionKey = xMsFilePermissionKey;
return this;
}
/**
* Get the xMsFileId property: The x-ms-file-id property.
*
* @return the xMsFileId value.
*/
public String getXMsFileId() {
return this.xMsFileId;
}
/**
* Set the xMsFileId property: The x-ms-file-id property.
*
* @param xMsFileId the xMsFileId value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsFileId(String xMsFileId) {
this.xMsFileId = xMsFileId;
return this;
}
/**
* Get the xMsFileCreationTime property: The x-ms-file-creation-time property.
*
* @return the xMsFileCreationTime value.
*/
public OffsetDateTime getXMsFileCreationTime() {
return this.xMsFileCreationTime;
}
/**
* Set the xMsFileCreationTime property: The x-ms-file-creation-time property.
*
* @param xMsFileCreationTime the xMsFileCreationTime value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsFileCreationTime(OffsetDateTime xMsFileCreationTime) {
this.xMsFileCreationTime = xMsFileCreationTime;
return this;
}
/**
* Get the lastModified property: The Last-Modified property.
*
* @return the lastModified value.
*/
public OffsetDateTime getLastModified() {
if (this.lastModified == null) {
return null;
}
return this.lastModified.getDateTime();
}
/**
* Set the lastModified property: The Last-Modified property.
*
* @param lastModified the lastModified value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setLastModified(OffsetDateTime lastModified) {
if (lastModified == null) {
this.lastModified = null;
} else {
this.lastModified = new DateTimeRfc1123(lastModified);
}
return this;
}
/**
* Get the xMsRequestServerEncrypted property: The x-ms-request-server-encrypted property.
*
* @return the xMsRequestServerEncrypted value.
*/
public Boolean isXMsRequestServerEncrypted() {
return this.xMsRequestServerEncrypted;
}
/**
* Set the xMsRequestServerEncrypted property: The x-ms-request-server-encrypted property.
*
* @param xMsRequestServerEncrypted the xMsRequestServerEncrypted value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsRequestServerEncrypted(Boolean xMsRequestServerEncrypted) {
this.xMsRequestServerEncrypted = xMsRequestServerEncrypted;
return this;
}
/**
* Get the dateProperty property: The Date property.
*
* @return the dateProperty value.
*/
public OffsetDateTime getDateProperty() {
if (this.dateProperty == null) {
return null;
}
return this.dateProperty.getDateTime();
}
/**
* Set the dateProperty property: The Date property.
*
* @param dateProperty the dateProperty value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setDateProperty(OffsetDateTime dateProperty) {
if (dateProperty == null) {
this.dateProperty = null;
} else {
this.dateProperty = new DateTimeRfc1123(dateProperty);
}
return this;
}
/**
* Get the eTag property: The ETag property.
*
* @return the eTag value.
*/
public String getETag() {
return this.eTag;
}
/**
* Set the eTag property: The ETag property.
*
* @param eTag the eTag value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setETag(String eTag) {
this.eTag = eTag;
return this;
}
/**
* Get the xMsFileAttributes property: The x-ms-file-attributes property.
*
* @return the xMsFileAttributes value.
*/
public String getXMsFileAttributes() {
return this.xMsFileAttributes;
}
/**
* Set the xMsFileAttributes property: The x-ms-file-attributes property.
*
* @param xMsFileAttributes the xMsFileAttributes value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsFileAttributes(String xMsFileAttributes) {
this.xMsFileAttributes = xMsFileAttributes;
return this;
}
/**
* Get the xMsFileChangeTime property: The x-ms-file-change-time property.
*
* @return the xMsFileChangeTime value.
*/
public OffsetDateTime getXMsFileChangeTime() {
return this.xMsFileChangeTime;
}
/**
* Set the xMsFileChangeTime property: The x-ms-file-change-time property.
*
* @param xMsFileChangeTime the xMsFileChangeTime value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsFileChangeTime(OffsetDateTime xMsFileChangeTime) {
this.xMsFileChangeTime = xMsFileChangeTime;
return this;
}
/**
* Get the xMsFileParentId property: The x-ms-file-parent-id property.
*
* @return the xMsFileParentId value.
*/
public String getXMsFileParentId() {
return this.xMsFileParentId;
}
/**
* Set the xMsFileParentId property: The x-ms-file-parent-id property.
*
* @param xMsFileParentId the xMsFileParentId value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsFileParentId(String xMsFileParentId) {
this.xMsFileParentId = xMsFileParentId;
return this;
}
/**
* Get the xMsRequestId property: The x-ms-request-id property.
*
* @return the xMsRequestId value.
*/
public String getXMsRequestId() {
return this.xMsRequestId;
}
/**
* Set the xMsRequestId property: The x-ms-request-id property.
*
* @param xMsRequestId the xMsRequestId value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsRequestId(String xMsRequestId) {
this.xMsRequestId = xMsRequestId;
return this;
}
/**
* Get the xMsFileLastWriteTime property: The x-ms-file-last-write-time property.
*
* @return the xMsFileLastWriteTime value.
*/
public OffsetDateTime getXMsFileLastWriteTime() {
return this.xMsFileLastWriteTime;
}
/**
* Set the xMsFileLastWriteTime property: The x-ms-file-last-write-time property.
*
* @param xMsFileLastWriteTime the xMsFileLastWriteTime value to set.
* @return the FilesSetHttpHeadersHeaders object itself.
*/
public FilesSetHttpHeadersHeaders setXMsFileLastWriteTime(OffsetDateTime xMsFileLastWriteTime) {
this.xMsFileLastWriteTime = xMsFileLastWriteTime;
return this;
}
}
| |
/**
* BaseActivity.java
*
* Created by Gan Jianping on 07/01/15.
* Copyright (c) 2015 GANJP. All rights reserved.
*/
package org.ganjp.glib.core.base;
import org.ganjp.glib.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
/**
* <p>Base Activity</p>
*
* @author GanJianping
* @since v1.0.0
*/
public abstract class BaseActivity extends Activity implements OnClickListener {
/**
* Called when the activity is first created
*/
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* <p>Called after your activity has been stopped, prior to it being started again.</p>
*/
@Override
protected void onRestart() {
super.onRestart();
}
/**
* <p>Called when the activity is becoming visible to the user.</p>
*/
@Override
protected void onStart() {
super.onStart();
}
/**
* <p>Called when the activity will start interacting with the user.</p>
*/
@Override
protected void onResume() {
super.onResume();
}
/**
* <p>Called when the system is about to start resuming a previous activity.</p>
*/
@Override
protected void onPause() {
super.onPause();
}
/**
* <p>Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one.</p>
*/
@Override
protected void onStop() {
super.onStop();
}
/**
* <p>The final call you receive before your activity is destroyed. This can happen either because the activity is finishing.</p>
*/
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* <p>Click Button Event</p>
*
* @param view
*/
@Override
public void onClick(View view) {
Log.i("BaseActivity", "onClick:"+view.getId());
}
/**
* refresh current activity
*/
protected void refresh() {
finish();
startActivity(getIntent());
}
/**
* Log info
*
* @param msg
*/
protected void log(String msg) {
Log.i(this.getClass().getName(), msg);
}
/**
* Get current activity context
*
* @return
*/
protected Context getContext() {
return this;
}
/**
* <p>Get screen width</p>
*
* @return int
*/
protected int getScreenWidth() {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
return displaymetrics.widthPixels;
}
/**
* <p>Get screen height</p>
*
* @return
*/
protected int getScreenHeight() {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
return displaymetrics.heightPixels;
}
/**
* <p>Transit forward</p>
*/
protected void transitForward() {
transitSlideLeft();
}
/**
* <p>Transit back</p>
*/
protected void transitBack() {
transitSlideRight();
}
/**
* <p>slide from left to right</p>
*/
protected void transitSlideLeft() {
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}
/**
* <p>Slide from right to left</p>
*/
protected void transitSlideRight() {
overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
}
/**
* <p>Slide from up to down</p>
*/
protected void transitSlideDown() {
overridePendingTransition(0, R.anim.slide_up);
}
/**
* <p>Slide from down to up</p>
*/
protected void transitSlideUp() {
overridePendingTransition(0, R.anim.slide_down);
}
/**
* <p>Flip from shrink to grow</p>
*/
protected void transitShrinkGrow() {
overridePendingTransition(R.anim.grow_from_middle, R.anim.shrink_to_middle);
}
public void showToastFromBackground(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (message.equals(Const.VALUE_FAIL)) {
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.fail), Toast.LENGTH_SHORT).show();
} else if (message.equals(Const.VALUE_FAIL)) {
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.success), Toast.LENGTH_SHORT).show();
} else if (message.equals(Const.VALUE_TIMEOUT)) {
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.timeout), Toast.LENGTH_SHORT).show();
}
}
});
}
}
| |
/*
* Copyright 2014, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.grpc.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static io.grpc.internal.GrpcUtil.CANCEL_REASONS;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import io.grpc.Metadata;
import io.grpc.Status;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The abstract base class for {@link ClientStream} implementations.
*/
public abstract class AbstractClientStream<IdT> extends AbstractStream<IdT>
implements ClientStream {
private static final Logger log = Logger.getLogger(AbstractClientStream.class.getName());
private final ClientStreamListener listener;
private boolean listenerClosed;
// Stored status & trailers to report when deframer completes or
// transportReportStatus is directly called.
private Status status;
private Metadata trailers;
private Runnable closeListenerTask;
private volatile boolean cancelled;
protected AbstractClientStream(WritableBufferAllocator bufferAllocator,
ClientStreamListener listener,
int maxMessageSize) {
super(bufferAllocator, maxMessageSize);
this.listener = Preconditions.checkNotNull(listener);
}
@Override
protected final ClientStreamListener listener() {
return listener;
}
@Override
protected void receiveMessage(InputStream is) {
if (!listenerClosed) {
listener.messageRead(is);
}
}
/**
* The transport implementation has detected a protocol error on the stream. Transports are
* responsible for properly closing streams when protocol errors occur.
*
* @param errorStatus the error to report
*/
protected void inboundTransportError(Status errorStatus) {
if (inboundPhase() == Phase.STATUS) {
log.log(Level.INFO, "Received transport error on closed stream {0} {1}",
new Object[]{id(), errorStatus});
return;
}
// For transport errors we immediately report status to the application layer
// and do not wait for additional payloads.
transportReportStatus(errorStatus, false, new Metadata());
}
/**
* Called by transport implementations when they receive headers.
*
* @param headers the parsed headers
*/
protected void inboundHeadersReceived(Metadata headers) {
if (inboundPhase() == Phase.STATUS) {
log.log(Level.INFO, "Received headers on closed stream {0} {1}",
new Object[]{id(), headers});
}
if (headers.containsKey(GrpcUtil.MESSAGE_ENCODING_KEY)) {
String messageEncoding = headers.get(GrpcUtil.MESSAGE_ENCODING_KEY);
try {
setDecompressor(messageEncoding);
} catch (IllegalArgumentException e) {
// Don't use INVALID_ARGUMENT since that is for servers to send clients.
Status status = Status.INTERNAL.withDescription("Unable to decompress message from server.")
.withCause(e);
// TODO(carl-mastrangelo): look back into tearing down this stream. sendCancel() can be
// buffered.
inboundTransportError(status);
sendCancel(status);
return;
}
}
inboundPhase(Phase.MESSAGE);
listener.headersRead(headers);
}
/**
* Processes the contents of a received data frame from the server.
*
* @param frame the received data frame. Its ownership is transferred to this method.
*/
protected void inboundDataReceived(ReadableBuffer frame) {
Preconditions.checkNotNull(frame, "frame");
boolean needToCloseFrame = true;
try {
if (inboundPhase() == Phase.STATUS) {
return;
}
if (inboundPhase() == Phase.HEADERS) {
// Have not received headers yet so error
inboundTransportError(Status.INTERNAL
.withDescription("headers not received before payload"));
return;
}
inboundPhase(Phase.MESSAGE);
needToCloseFrame = false;
deframe(frame, false);
} finally {
if (needToCloseFrame) {
frame.close();
}
}
}
@Override
protected void inboundDeliveryPaused() {
runCloseListenerTask();
}
@Override
protected final void deframeFailed(Throwable cause) {
cancel(Status.INTERNAL.withDescription("Exception deframing message").withCause(cause));
}
/**
* Processes the trailers and status from the server.
*
* @param trailers the received trailers
* @param status the status extracted from the trailers
*/
protected void inboundTrailersReceived(Metadata trailers, Status status) {
Preconditions.checkNotNull(trailers, "trailers");
if (inboundPhase() == Phase.STATUS) {
log.log(Level.INFO, "Received trailers on closed stream {0}\n {1}\n {2}",
new Object[]{id(), status, trailers});
}
// Stash the status & trailers so they can be delivered by the deframer calls
// remoteEndClosed
this.status = status;
this.trailers = trailers;
deframe(ReadableBuffers.empty(), true);
}
@Override
protected void remoteEndClosed() {
transportReportStatus(status, true, trailers);
}
@Override
protected final void internalSendFrame(WritableBuffer frame, boolean endOfStream, boolean flush) {
Preconditions.checkArgument(frame != null || endOfStream, "null frame before EOS");
sendFrame(frame, endOfStream, flush);
}
/**
* Sends an outbound frame to the remote end point.
*
* @param frame a buffer containing the chunk of data to be sent or {@code null} if the framer is
* closing and has no data to send.
* @param endOfStream if {@code true} indicates that no more data will be sent on the stream by
* this endpoint.
* @param flush {@code true} if more data may not be arriving soon
*/
protected abstract void sendFrame(WritableBuffer frame, boolean endOfStream, boolean flush);
/**
* Report stream closure with status to the application layer if not already reported. This method
* must be called from the transport thread.
*
* @param newStatus the new status to set
* @param stopDelivery if {@code true}, interrupts any further delivery of inbound messages that
* may already be queued up in the deframer. If {@code false}, the listener will be
* notified immediately after all currently completed messages in the deframer have been
* delivered to the application.
* @param trailers new instance of {@code Trailers}, either empty or those returned by the server
*/
public void transportReportStatus(final Status newStatus, boolean stopDelivery,
final Metadata trailers) {
Preconditions.checkNotNull(newStatus, "newStatus");
boolean closingLater = closeListenerTask != null && !stopDelivery;
if (listenerClosed || closingLater) {
// We already closed (or are about to close) the listener.
return;
}
inboundPhase(Phase.STATUS);
status = newStatus;
closeListenerTask = null;
// Determine if the deframer is stalled (i.e. currently has no complete messages to deliver).
boolean deliveryStalled = isDeframerStalled();
if (stopDelivery || deliveryStalled) {
// Close the listener immediately.
closeListener(newStatus, trailers);
} else {
// Delay close until inboundDeliveryStalled()
closeListenerTask = newCloseListenerTask(newStatus, trailers);
}
}
/**
* Creates a new {@link Runnable} to close the listener with the given status/trailers.
*/
private Runnable newCloseListenerTask(final Status status, final Metadata trailers) {
return new Runnable() {
@Override
public void run() {
closeListener(status, trailers);
}
};
}
/**
* Closes the listener if not previously closed.
*/
private void closeListener(Status newStatus, Metadata trailers) {
if (!listenerClosed) {
listenerClosed = true;
closeDeframer();
listener.closed(newStatus, trailers);
}
}
/**
* Executes the pending listener close task, if one exists.
*/
private void runCloseListenerTask() {
if (closeListenerTask != null) {
closeListenerTask.run();
closeListenerTask = null;
}
}
@Override
public final void halfClose() {
if (outboundPhase(Phase.STATUS) != Phase.STATUS) {
closeFramer();
}
}
/**
* Cancel the stream. Called by the application layer, never called by the transport.
*/
@Override
public final void cancel(Status reason) {
checkArgument(CANCEL_REASONS.contains(reason.getCode()), "Invalid cancellation reason");
cancelled = true;
sendCancel(reason);
dispose();
}
@Override
public final boolean isReady() {
return !cancelled && super.isReady();
}
/**
* Cancel the stream and send a stream cancellation message to the remote server, if necessary.
* Can be called by either the application or transport layers. This method is safe to be called
* at any time and multiple times.
*/
protected abstract void sendCancel(Status reason);
@Override
protected MoreObjects.ToStringHelper toStringHelper() {
MoreObjects.ToStringHelper toStringHelper = super.toStringHelper();
if (status != null) {
toStringHelper.add("status", status);
}
return toStringHelper;
}
@Override
public boolean isClosed() {
return super.isClosed() || listenerClosed;
}
}
| |
package org.sagebionetworks.web.test.helper.examples;
import java.util.LinkedList;
import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* This is an example Presenter class that is used to drive the asynchronous service and capture the
* results.
*
* @author jmhill
*
*/
public class ExamplePresenter {
private ExampleServiceAsync asyncService = null;
// No args
private List<SampleDTO> noArgSuccess = null;
private Throwable noArgFailure = null;
// with args
private List<SampleDTO> withArgSuccess = null;
private Throwable withArgFailure = null;
// null return
private List<SampleDTO> nullReturnSuccess = null;
private Throwable nullReturnFailure = null;
// void return
private boolean voidReturnSuccess = false;
private Throwable voidReturnFailure = null;
// createSampel
private Integer createSucces = null;
private Throwable createFailure = null;
public ExamplePresenter(ExampleServiceAsync asyncService) {
if (asyncService == null)
throw new IllegalArgumentException("ExampleServiceAsync cannot be null");
this.asyncService = asyncService;
}
public void doNoArgs() {
// Make the call
asyncService.noArgs(new AsyncCallback<List<SampleDTO>>() {
@Override
public void onSuccess(List<SampleDTO> result) {
setNoArgSuccess(result);
}
@Override
public void onFailure(Throwable caught) {
setNoArgFailure(caught);
}
});
// Note, if the asycnh service calls either onSuccess() or onFailure()
// before returning than the data will be lost.
setNoArgFailure(null);
setNoArgSuccess(null);
}
public void doWithArgs(final List<Integer> idList) {
asyncService.withArgs(idList, new AsyncCallback<List<SampleDTO>>() {
@Override
public void onSuccess(List<SampleDTO> result) {
setWithArgSuccess(result);
}
@Override
public void onFailure(Throwable caught) {
setWithArgFailure(caught);
}
});
// Note, if the asycnh service calls either onSuccess() or onFailure()
// before returning than the data will be lost.
setWithArgFailure(null);
setWithArgSuccess(null);
}
public void doNullReturn() {
asyncService.nullReturn(new AsyncCallback<List<SampleDTO>>() {
@Override
public void onSuccess(List<SampleDTO> result) {
setNullReturnSuccess(result);
}
@Override
public void onFailure(Throwable caught) {
setNullReturnFailure(caught);
}
});
// Note, if the asycnh service calls either onSuccess() or onFailure()
// before returning than the data will be lost.
setNullReturnFailure(null);
// Since onSuccess will set this to null, start with a non-null list
setNullReturnSuccess(new LinkedList<SampleDTO>());
}
public void doVoidReturn(int id) {
asyncService.voidReturn(id, new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
setVoidReturnSuccess(true);
}
@Override
public void onFailure(Throwable caught) {
setVoidReturnFailure(caught);
}
});
// Note, if the asycnh service calls either onSuccess() or onFailure()
// before returning than the data will be lost.
setVoidReturnSuccess(false);
setVoidReturnFailure(null);
}
public void doCreateSample(String name, String description) {
asyncService.createSample(name, description, new AsyncCallback<Integer>() {
@Override
public void onSuccess(Integer result) {
setCreateSucces(result);
}
@Override
public void onFailure(Throwable caught) {
setCreateFailure(caught);
}
});
// Note, if the asycnh service calls either onSuccess() or onFailure()
// before returning than the data will be lost.
setCreateSucces(null);
setCreateFailure(null);
}
public Integer getCreateSucces() {
return createSucces;
}
public void setCreateSucces(Integer createSucces) {
this.createSucces = createSucces;
}
public Throwable getCreateFailure() {
return createFailure;
}
public void setCreateFailure(Throwable createFailure) {
this.createFailure = createFailure;
}
public List<SampleDTO> getWithArgSuccess() {
return withArgSuccess;
}
public void setWithArgSuccess(List<SampleDTO> withArgSuccess) {
this.withArgSuccess = withArgSuccess;
}
public Throwable getWithArgFailure() {
return withArgFailure;
}
public void setWithArgFailure(Throwable withArgFailure) {
this.withArgFailure = withArgFailure;
}
public List<SampleDTO> getNoArgSuccess() {
return noArgSuccess;
}
public void setNoArgSuccess(List<SampleDTO> noArgSuccess) {
this.noArgSuccess = noArgSuccess;
}
public Throwable getNoArgFailure() {
return noArgFailure;
}
public void setNoArgFailure(Throwable noArgFailure) {
this.noArgFailure = noArgFailure;
}
public List<SampleDTO> getNullReturnSuccess() {
return nullReturnSuccess;
}
public void setNullReturnSuccess(List<SampleDTO> nullReturnSuccess) {
this.nullReturnSuccess = nullReturnSuccess;
}
public Throwable getNullReturnFailure() {
return nullReturnFailure;
}
public void setNullReturnFailure(Throwable nullReturnFailure) {
this.nullReturnFailure = nullReturnFailure;
}
public boolean isVoidReturnSuccess() {
return voidReturnSuccess;
}
public void setVoidReturnSuccess(boolean voidReturnSuccess) {
this.voidReturnSuccess = voidReturnSuccess;
}
public Throwable getVoidReturnFailure() {
return voidReturnFailure;
}
public void setVoidReturnFailure(Throwable voidReturnFailure) {
this.voidReturnFailure = voidReturnFailure;
}
}
| |
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Neustar Inc.
*
* 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.neulevel.epp.core.command;
import java.util.*;
import org.w3c.dom.*;
import com.neulevel.epp.core.*;
/**
* This <code>EppCommandUpdateDomain</code> class implements EPP Command Update
* entity for EPP Domain objects.
*
* @author Ning Zhang ning.zhang@neustar.com
* @version $Revision: 1.2 $ $Date: 2006/03/01 01:35:38 $
*/
public class EppCommandUpdateDomain extends EppCommandUpdate
{
private String name;
private Vector nsAdded;
private Vector nsRemoved;
private Vector nsAttrAdded;
private Vector nsAttrRemoved;
private Vector contactAdded;
private Vector contactRemoved;
private String newRegistrant;
private EppAuthInfo newAuthInfo;
/**
* Creates an <code>EppCommandUpdateDomain</code> given the name of the
* domain
*/
public EppCommandUpdateDomain( String name )
{
this(name, null);
}
/**
* Creates an <code>EppCommandUpdateDomain</code> given the name of the
* domain and a client transaction id
*/
public EppCommandUpdateDomain( String name, String xid )
{
this.name = name;
this.nsAdded = null;
this.nsRemoved = null;
this.nsAttrAdded = null;
this.nsAttrRemoved = null;
this.contactAdded = new Vector();
this.contactRemoved = new Vector();
this.clTRID = xid;
}
/**
* Gets the name of the domain to be updated
*/
public String getName()
{
return this.name;
}
/**
* Sets the name of the domain to be updated
*/
public void setName( String name )
{
this.name = name;
}
/**
* Gets the list of new name servers to be added to the domain
*/
public Vector getNameServerAdded()
{
return this.nsAdded;
}
/**
* Adds a new name server to be associated with the domain
*/
public void addNameServer( String nameServer )
{
this.nsAttrAdded = null;
if( this.nsAdded == null )
{
this.nsAdded = new Vector();
}
this.nsAdded.addElement(nameServer);
}
/**
* Gets the list of old name servers to be removed from the domain
*/
public Vector getNameServerRemoved()
{
return this.nsRemoved;
}
/**
* Removes an old name server associated with the domain
*/
public void removeNameServer( String nameServer )
{
this.nsAttrRemoved = null;
if( this.nsRemoved == null )
{
this.nsRemoved = new Vector();
}
this.nsRemoved.addElement(nameServer);
}
/**
* Gets the list of new name servers, specified as host attributes, to be added to the domain
*/
public Vector getNameServerHostAttributeAdded()
{
return this.nsAttrAdded;
}
/**
* Adds a new name server, specified as host attribute, to be associated with the domain
*/
public void addNameServer( EppHostAttribute nameServer )
{
this.nsAdded = null;
if( this.nsAttrAdded == null )
{
this.nsAttrAdded = new Vector();
}
this.nsAttrAdded.addElement(nameServer);
}
/**
* Gets the list of old name servers, specified as host attributes, to be removed from the domain
*/
public Vector getNameServerHostAttributeRemoved()
{
return this.nsAttrRemoved;
}
/**
* Removes an old name server, specified as a host attributes, associated with the domain
*/
public void removeNameServer( EppHostAttribute nameServer )
{
this.nsRemoved = null;
if( this.nsAttrRemoved == null )
{
this.nsAttrRemoved = new Vector();
}
this.nsAttrRemoved.addElement(nameServer);
}
/**
* Gets the list of new contacts to be added to the domain
*/
public Vector getContactAdded()
{
return this.contactAdded;
}
/**
* Adds a new contact to be associated with the domain
*/
public void addContact( EppContactType contact )
{
this.contactAdded.addElement(contact);
}
/**
* Gets the list of old contacts to be removed from the domain
*/
public Vector getContactRemoved()
{
return this.contactRemoved;
}
/*
* Removes an old contact associated with the domain
*/
public void removeContact( EppContactType contact )
{
this.contactRemoved.addElement(contact);
}
/**
* Gets the new registrant's contact id for the domain, or null if the
* registrant of the domain is not to be changed
*/
public String getNewRegistrant()
{
return this.newRegistrant;
}
/**
* Sets the new registrant's contact id for the domain if a new registrant
* claims the ownership of the domain
*/
public void setNewRegistrant( String registrant )
{
this.newRegistrant = registrant;
}
/**
* Gets the new authorization information for the domain, or null if
* the authorization information of the domain is not to be changed
*/
public EppAuthInfo getNewAuthInfo()
{
return this.newAuthInfo;
}
/**
* Sets the new authorization information for the domain if it needs
* to be changed
*/
public void setNewAuthInfo( EppAuthInfo authInfo )
{
this.newAuthInfo = authInfo;
}
/**
* Converts the <code>EppCommandUpdateDomain</code> object into
* an XML element
*
* @param doc the XML <code>Document</code> object
* @param tag the tag/element name for the
* <code>EppCommandUpdateDomain</code> object
*
* @return an <code>Element</code> object
*/
public Element toXML( Document doc, String tag )
{
Element elm;
Element body = EppUtil.createElementNS(doc, "domain", tag);
if( name != null )
{
elm = doc.createElement("name");
elm.appendChild(doc.createTextNode(name));
body.appendChild(elm);
}
if( ((nsAdded != null) && (nsAdded.size() > 0))
|| ((nsAttrAdded != null) && (nsAttrAdded.size() > 0))
|| (contactAdded.size() > 0)
|| (statusAdded.size() > 0) )
{
elm = doc.createElement("add");
if( (nsAdded != null) && (nsAdded.size() > 0) )
{
nameServerToXML(doc, elm, nsAdded);
}
else if( (nsAttrAdded != null) && (nsAttrAdded.size() > 0) )
{
nameServerHostAttributeToXML(doc, elm, nsAttrAdded);
}
if( contactAdded.size() > 0 )
{
contactToXML(doc, elm, contactAdded);
}
if( statusAdded.size() > 0 )
{
statusToXML(doc, elm, statusAdded);
}
body.appendChild(elm);
}
if( ((nsRemoved != null) && (nsRemoved.size() > 0))
|| ((nsAttrRemoved != null) && (nsAttrRemoved.size() > 0))
|| (contactRemoved.size() > 0)
|| (statusRemoved.size() > 0) )
{
elm = doc.createElement("rem");
if( (nsRemoved != null) && (nsRemoved.size() > 0) )
{
nameServerToXML(doc, elm, nsRemoved);
}
else if( (nsAttrRemoved != null) && (nsAttrRemoved.size() > 0) )
{
nameServerHostAttributeToXML(doc, elm, nsAttrRemoved);
}
if( contactRemoved.size() > 0 )
{
contactToXML(doc, elm, contactRemoved);
}
if( statusRemoved.size() > 0 )
{
statusToXML(doc, elm, statusRemoved);
}
body.appendChild(elm);
}
if( (newRegistrant != null) || (newAuthInfo != null) )
{
elm = doc.createElement("chg");
if( newRegistrant != null )
{
Element name = doc.createElement("registrant");
name.appendChild(doc.createTextNode(newRegistrant));
elm.appendChild(name);
}
if( newAuthInfo != null )
{
elm.appendChild(newAuthInfo.toXML(doc, "authInfo"));
}
body.appendChild(elm);
}
return toXMLCommon(doc, tag, body);
}
/**
* Converts a list of name servers into XML
*
* @param doc the XML <code>Document</code> object
* @param body the XML <code>Element</code> object to which the list
* of IP addresses is appended
* @param list the list of name servers to be converted
*/
private void nameServerToXML( Document doc, Element body, Vector list )
{
Element elm = null;
if( list != null )
{
for( int i = 0; i < list.size(); i++ )
{
Object obj = list.elementAt(i);
if( obj instanceof String )
{
String ns = (String) obj;
if( (ns == null) || (ns.length() == 0) )
{
continue;
}
if( elm == null )
{
elm = doc.createElement("ns");
body.appendChild(elm);
}
Element t = doc.createElement("hostObj");
t.appendChild(doc.createTextNode(ns));
elm.appendChild(t);
}
}
}
}
/**
* Converts a list of name servers, specified as host attributes, into XML
*
* @param doc the XML <code>Document</code> object
* @param body the XML <code>Element</code> object to which the list
* of IP addresses is appended
* @param list the list of name servers to be converted
*/
private void nameServerHostAttributeToXML( Document doc, Element body, Vector list )
{
Element elm = null;
if( list != null )
{
for( int i = 0; i < list.size(); i++ )
{
Object obj = list.elementAt(i);
if( obj instanceof EppHostAttribute )
{
EppHostAttribute ns = (EppHostAttribute) obj;
if( ns == null )
{
continue;
}
if( elm == null )
{
elm = doc.createElement("ns");
body.appendChild(elm);
}
Element t = ns.toXML(doc, "hostAttr");
elm.appendChild(t);
}
}
}
}
/**
* Converts a list of contacts into XML
*
* @param doc the XML <code>Document</code> object
* @param body the XML <code>Element</code> object to which the list
* of IP addresses is appended
* @param list the list of contacts to be converted
*/
private void contactToXML( Document doc, Element body, Vector list )
{
Element elm;
if( list != null )
{
for( int i = 0; i < list.size(); i++ )
{
Object obj = list.elementAt(i);
if( obj instanceof EppContactType )
{
EppContactType ct = (EppContactType) obj;
elm = ct.toXML(doc, "contact");
body.appendChild(elm);
}
}
}
}
/**
* Converts an XML element into an <code>EppCommandUpdateDomain</code>
* object. The caller of this method must make sure that the root node
* is of an EPP Command Update entity for an EPP Domain object.
*
* @param root root node for an <code>EppCommandUpdate</code> object
* in XML format
*
* @return an <code>EppCommandUpdateDomain</code> object, or null
* if the node is invalid
*/
public static EppEntity fromXML( Node root )
{
EppCommandUpdateDomain cmd = null;
NodeList list = root.getChildNodes();
for( int i = 0; i < list.getLength(); i++ )
{
Node node = list.item(i);
String name = node.getLocalName();
if( name == null )
{
continue;
}
if( name.equals("name") )
{
String host = EppUtil.getText(node);
cmd = new EppCommandUpdateDomain(host);
}
else if( name.equals("add") )
{
if( cmd != null )
{
cmd.nameServerFromXML(node, true);
cmd.contactFromXML(node, cmd.contactAdded);
cmd.statusFromXML(node, cmd.statusAdded);
}
}
else if( name.equals("rem") )
{
if( cmd != null )
{
cmd.nameServerFromXML(node, false);
cmd.contactFromXML(node, cmd.contactRemoved);
cmd.statusFromXML(node, cmd.statusRemoved);
}
}
else if( name.equals("chg") )
{
NodeList tlist = node.getChildNodes();
for( int j = 0; j < tlist.getLength(); j++ )
{
Node tnode = tlist.item(j);
String tname = tnode.getLocalName();
if( tname == null )
{
continue;
}
if( tname.equals("registrant") )
{
String id = EppUtil.getText(tnode);
if( cmd != null )
{
cmd.setNewRegistrant(id);
}
}
else if( tname.equals("authInfo") )
{
EppAuthInfo authInfo = (EppAuthInfo) EppAuthInfo.fromXML(tnode);
if( cmd != null )
{
cmd.setNewAuthInfo(authInfo);
}
}
}
}
}
return cmd;
}
/**
* Converts a list of name servers from XML format
*
* @param root the XML <code>Node</code> object containing the list
* of IP addresses
* @param addOrRem boolean flag for adding or removing name servers
*/
private void nameServerFromXML( Node root, boolean addOrRem )
{
NodeList list = root.getChildNodes();
for( int i = 0; i < list.getLength(); i++ )
{
Node node = list.item(i);
String name = node.getLocalName();
if( name == null )
{
continue;
}
if( name.equals("ns") == false )
{
continue;
}
NodeList clist = node.getChildNodes();
if( clist == null )
{
continue;
}
for( int j = 0; j < clist.getLength(); j++ )
{
Node cnode = clist.item(j);
String cname = cnode.getLocalName();
if( cname == null )
{
continue;
}
if( cname.equals("hostObj") )
{
String ns = EppUtil.getText(cnode);
if( (ns != null) && (ns.length() > 0) )
{
if( addOrRem == true )
{
this.addNameServer(ns);
}
else
{
this.removeNameServer(ns);
}
}
}
else if( cname.equals("hostAttr") )
{
EppHostAttribute ns;
ns = (EppHostAttribute) EppHostAttribute.fromXML(cnode);
if( ns != null )
{
if( addOrRem == true )
{
this.addNameServer(ns);
}
else
{
this.removeNameServer(ns);
}
}
}
}
}
}
/**
* Converts a list of contacts from XML format
*
* @param root the XML <code>Node</code> object containing the list
* of IP addresses
* @param contactList the list of contacts to be stored
*/
private void contactFromXML( Node root, Vector contactList )
{
NodeList list = root.getChildNodes();
for( int i = 0; i < list.getLength(); i++ )
{
Node node = list.item(i);
String name = node.getLocalName();
if( name == null )
{
continue;
}
if( name.equals("contact") )
{
EppContactType ct = (EppContactType) EppContactType.fromXML(node);
contactList.addElement(ct);
}
}
}
}
| |
package org.agzamovr.collectors;
import org.junit.Test;
import java.util.AbstractMap.SimpleEntry;
import java.util.*;
import java.util.Map.Entry;
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsLast;
import static java.util.stream.Collectors.*;
import static org.assertj.core.api.Assertions.assertThat;
public class RankingCollectorTest {
private final Entry<Integer, List<Integer>> entry1 = new SimpleEntry<>(1, singletonList(1));
private final Entry<Integer, List<Integer>> entry2 = new SimpleEntry<>(2, singletonList(2));
private final Entry<Integer, List<Integer>> entry3 = new SimpleEntry<>(3, singletonList(3));
private final Entry<Integer, List<Integer>> entry4 = new SimpleEntry<>(4, singletonList(4));
@Test
public void testRankWithEmptyList() {
List<Integer> list = Collections.emptyList();
SortedMap<Integer, List<Integer>> result = list.stream()
.collect(CollectorEx.rank());
assertThat(result.isEmpty());
}
@Test
public void testRankWithSortedIntegerList() {
List<Integer> list = asList(1, 2, 3, 4);
SortedMap<Integer, List<Integer>> rankedMap = list.stream()
.collect(CollectorEx.rank());
assertThat(rankedMap).containsExactly(entry1, entry2, entry3, entry4);
}
@Test
public void testRankWithReverseSortedIntegerList() {
List<Integer> list = asList(4, 3, 2, 1);
SortedMap<Integer, List<Integer>> rankedMap = list.stream()
.collect(CollectorEx.rank());
assertThat(rankedMap).containsExactly(entry1, entry2, entry3, entry4);
}
@Test
public void testRankWithDuplicates() {
List<Integer> list = asList(1, 2, 3, 4, 4, 3, 2, 1);
SortedMap<Integer, List<Integer>> rankedMap = list.stream()
.collect(CollectorEx.rank());
Entry<Integer, List<Integer>> entry1 = new SimpleEntry<>(1, asList(1, 1));
Entry<Integer, List<Integer>> entry2 = new SimpleEntry<>(3, asList(2, 2));
Entry<Integer, List<Integer>> entry3 = new SimpleEntry<>(5, asList(3, 3));
Entry<Integer, List<Integer>> entry4 = new SimpleEntry<>(7, asList(4, 4));
assertThat(rankedMap).containsExactly(entry1, entry2, entry3, entry4);
}
@Test
public void testDenseRankWithDuplicates() {
List<Integer> list = asList(1, 2, 3, 4, 4, 3, 2, 1);
SortedMap<Integer, List<Integer>> rankedMap = list.stream()
.collect(CollectorEx.denseRank());
Entry<Integer, List<Integer>> entry1 = new SimpleEntry<>(1, asList(1, 1));
Entry<Integer, List<Integer>> entry2 = new SimpleEntry<>(2, asList(2, 2));
Entry<Integer, List<Integer>> entry3 = new SimpleEntry<>(3, asList(3, 3));
Entry<Integer, List<Integer>> entry4 = new SimpleEntry<>(4, asList(4, 4));
assertThat(rankedMap).containsExactly(entry1, entry2, entry3, entry4);
}
@Test
public void testRankOrder() {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Comparator<Integer> intComparator = Integer::compare;
SortedMap<Integer, List<Integer>> rankedMap = list.stream()
.collect(CollectorEx.rank(intComparator, intComparator.reversed()));
assertThat(rankedMap).containsExactly(entry4, entry3, entry2, entry1);
}
@Test
public void testRankWithCustomComparator() {
List<Integer> list = asList(1, 2, 3, 4);
SortedMap<Integer, List<Integer>> rankedMap = list.stream()
.collect(CollectorEx.rank(this::evenOddComparator));
Entry<Integer, List<Integer>> entry1 = new SimpleEntry<>(1, asList(1, 3));
Entry<Integer, List<Integer>> entry2 = new SimpleEntry<>(3, asList(2, 4));
assertThat(rankedMap).containsExactly(entry1, entry2);
}
int evenOddComparator(int x, int y) {
boolean xeven = x % 2 == 0, yeven = y % 2 == 0;
if ((xeven && yeven) || (!xeven && !yeven))
return 0;
return xeven ? 1 : -1;
}
@Test
public void testRankWithSetCollector() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 4, 3, 2, 1);
SortedMap<Integer, Set<Integer>> rankedMap = list.stream()
.collect(CollectorEx.rank(toSet()));
Entry<Integer, Set<Integer>> entry1 = new SimpleEntry<>(1, singleton(1));
Entry<Integer, Set<Integer>> entry2 = new SimpleEntry<>(3, singleton(2));
Entry<Integer, Set<Integer>> entry3 = new SimpleEntry<>(5, singleton(3));
Entry<Integer, Set<Integer>> entry4 = new SimpleEntry<>(7, singleton(4));
assertThat(rankedMap).containsExactly(entry1, entry2, entry3, entry4);
}
@Test
public void testRankWithMapperCollector() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 4, 3, 2, 1);
SortedMap<Integer, Set<Integer>> rankedMap = list.stream()
.collect(CollectorEx.rank(mapping(i -> i * i, toSet())));
Entry<Integer, Set<Integer>> entry1 = new SimpleEntry<>(1, singleton(1));
Entry<Integer, Set<Integer>> entry2 = new SimpleEntry<>(3, singleton(4));
Entry<Integer, Set<Integer>> entry3 = new SimpleEntry<>(5, singleton(9));
Entry<Integer, Set<Integer>> entry4 = new SimpleEntry<>(7, singleton(16));
assertThat(rankedMap).containsExactly(entry1, entry2, entry3, entry4);
}
@Test
public void testGroupingByCollectorWithRankCollector() {
List<Integer> list = asList(1, 2, 3, 4);
Map<Integer, SortedMap<Integer, List<Integer>>> rankedMap = list.stream()
.collect(groupingBy(i -> i % 2, CollectorEx.rank()));
SortedMap<Integer, List<Integer>> odds = new TreeMap<>();
odds.put(1, singletonList(1));
odds.put(2, singletonList(3));
SortedMap<Integer, List<Integer>> evens = new TreeMap<>();
evens.put(1, singletonList(2));
evens.put(2, singletonList(4));
Entry<Integer, SortedMap<Integer, List<Integer>>> entry1 = new SimpleEntry<>(0, evens);
Entry<Integer, SortedMap<Integer, List<Integer>>> entry2 = new SimpleEntry<>(1, odds);
assertThat(rankedMap).containsExactly(entry1, entry2);
}
@Test
public void testMapObjToDenseRank() {
List<Integer> list = asList(-1, -2, -3, -4, -4, -3, -2, -1);
Map<Integer, Integer> rankedMap = list.stream().collect(CollectorEx.mapObjToDenseRank());
Entry<Integer, Integer> entry1 = new SimpleEntry<>(-1, 4);
Entry<Integer, Integer> entry2 = new SimpleEntry<>(-2, 3);
Entry<Integer, Integer> entry3 = new SimpleEntry<>(-3, 2);
Entry<Integer, Integer> entry4 = new SimpleEntry<>(-4, 1);
assertThat(rankedMap).contains(entry1, entry2, entry3, entry4);
}
@Test
public void testMapObjToDenseRankWithComparator() {
List<Integer> list = asList(-1, -2, -3, -4, -4, -3, -2, -1);
Comparator<Integer> integerComparator = Integer::compareTo;
Map<Integer, Integer> rankedMap = list.stream()
.collect(CollectorEx.mapObjToDenseRank(integerComparator.reversed()));
Entry<Integer, Integer> entry1 = new SimpleEntry<>(-1, 1);
Entry<Integer, Integer> entry2 = new SimpleEntry<>(-2, 2);
Entry<Integer, Integer> entry3 = new SimpleEntry<>(-3, 3);
Entry<Integer, Integer> entry4 = new SimpleEntry<>(-4, 4);
assertThat(rankedMap).contains(entry1, entry2, entry3, entry4);
}
@Test
public void testMapObjToRank() {
List<Integer> list = asList(-1, -2, -3, -4, -4, -3, -2, -1);
Map<Integer, Integer> rankedMap = list.stream().collect(CollectorEx.mapObjToRank());
Entry<Integer, Integer> entry1 = new SimpleEntry<>(-1, 7);
Entry<Integer, Integer> entry2 = new SimpleEntry<>(-2, 5);
Entry<Integer, Integer> entry3 = new SimpleEntry<>(-3, 3);
Entry<Integer, Integer> entry4 = new SimpleEntry<>(-4, 1);
assertThat(rankedMap).contains(entry1, entry2, entry3, entry4);
}
@Test
public void testMapObjToRankWithComparator() {
List<Integer> list = asList(-1, -2, -3, -4, -4, -3, -2, -1);
Comparator<Integer> integerComparator = Integer::compareTo;
Map<Integer, Integer> rankedMap = list.stream()
.collect(CollectorEx.mapObjToRank(integerComparator.reversed()));
Entry<Integer, Integer> entry1 = new SimpleEntry<>(-1, 1);
Entry<Integer, Integer> entry2 = new SimpleEntry<>(-2, 3);
Entry<Integer, Integer> entry3 = new SimpleEntry<>(-3, 5);
Entry<Integer, Integer> entry4 = new SimpleEntry<>(-4, 7);
assertThat(rankedMap).contains(entry1, entry2, entry3, entry4);
}
@Test
public void testMapToObjWithMapper() {
List<Integer> list = asList(-1, -2, -3, -4, -4, -3, -2, -1);
Map<Integer, Integer> rankedMap = list.stream()
.collect(CollectorEx.mapObjToRank(a -> (a < 0) ? -a : a));
Entry<Integer, Integer> entry1 = new SimpleEntry<>(4, 1);
Entry<Integer, Integer> entry2 = new SimpleEntry<>(3, 3);
Entry<Integer, Integer> entry3 = new SimpleEntry<>(2, 5);
Entry<Integer, Integer> entry4 = new SimpleEntry<>(1, 7);
assertThat(rankedMap).contains(entry1, entry2, entry3, entry4);
}
@Test
public void testMapObjToRankWithComplexComparator() {
Comparator<Bid> bidComparator = buildComplexComparator();
List<Bid> bids = Bid.getBids();
Map<Bid, Integer> rankedMaps = bids.stream()
.collect(CollectorEx.mapObjToDenseRank(bidComparator));
rankedMaps.forEach((bid, rank) -> assertThat(bid.num).isEqualTo(rank));
}
@Test
public void testComplexComparator() {
Comparator<Bid> bidComparator = buildComplexComparator();
List<Bid> bids = Bid.getBids();
SortedMap<Integer, List<Bid>> rankedMap = bids.stream()
.collect(CollectorEx.rank(bidComparator));
assertThat(rankedMap.size()).isEqualTo(bids.size());
List<Bid> actualBid = rankedMap.get(1);
//first bid
assertThat(actualBid.size()).isEqualTo(1);
assertThat(actualBid.get(0).num).isEqualTo(1);
//second bid
actualBid = rankedMap.get(2);
assertThat(actualBid.size()).isEqualTo(1);
assertThat(actualBid.get(0).num).isEqualTo(2);
//third bid
actualBid = rankedMap.get(3);
assertThat(actualBid.size()).isEqualTo(1);
assertThat(actualBid.get(0).num).isEqualTo(3);
//4th bid
actualBid = rankedMap.get(4);
assertThat(actualBid.size()).isEqualTo(1);
assertThat(actualBid.get(0).num).isEqualTo(4);
//5th bid
actualBid = rankedMap.get(5);
assertThat(actualBid.size()).isEqualTo(1);
assertThat(actualBid.get(0).num).isEqualTo(5);
//6th bid
actualBid = rankedMap.get(6);
assertThat(actualBid.size()).isEqualTo(1);
assertThat(actualBid.get(0).num).isEqualTo(6);
//7th bid
actualBid = rankedMap.get(7);
assertThat(actualBid.size()).isEqualTo(1);
assertThat(actualBid.get(0).num).isEqualTo(7);
}
private Comparator<Bid> buildComplexComparator() {
return Comparator
.comparing(Bid::getPrice, naturalOrder())
.thenComparing(Bid::getShippingDate, nullsLast(naturalOrder()))
.thenComparing(Bid::getExperience, nullsLast(Comparator.<Integer>naturalOrder().reversed()))
.thenComparing(Bid::getSentDate);
}
}
| |
package alien4cloud.it.application;
import static alien4cloud.it.Context.getRestClientInstance;
import static org.junit.Assert.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alien4cloud.tosca.editor.operations.nodetemplate.AddNodeOperation;
import org.alien4cloud.tosca.model.templates.NodeTemplate;
import org.alien4cloud.tosca.model.templates.Topology;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.collect.Maps;
import org.junit.Assert;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import alien4cloud.dao.model.FacetedSearchResult;
import alien4cloud.dao.model.GetMultipleDataResult;
import alien4cloud.it.Context;
import alien4cloud.it.common.CommonStepDefinitions;
import alien4cloud.it.security.AuthenticationStepDefinitions;
import alien4cloud.it.topology.EditorStepDefinitions;
import alien4cloud.it.topology.TopologyStepDefinitions;
import alien4cloud.it.topology.TopologyTemplateStepDefinitions;
import alien4cloud.model.application.Application;
import alien4cloud.model.application.ApplicationEnvironment;
import alien4cloud.model.application.ApplicationVersion;
import alien4cloud.model.application.EnvironmentType;
import alien4cloud.model.common.Tag;
import alien4cloud.rest.application.model.ApplicationEnvironmentDTO;
import alien4cloud.rest.application.model.ApplicationEnvironmentRequest;
import alien4cloud.rest.application.model.CreateApplicationRequest;
import alien4cloud.rest.application.model.UpdateApplicationEnvironmentRequest;
import alien4cloud.rest.component.SearchRequest;
import alien4cloud.rest.component.UpdateTagRequest;
import alien4cloud.rest.model.RestResponse;
import alien4cloud.rest.utils.JsonUtil;
import alien4cloud.topology.TopologyDTO;
import alien4cloud.utils.ReflectionUtil;
import cucumber.api.DataTable;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ApplicationStepDefinitions {
private static final String TEST_APPLICATION_IMAGE = "src/test/resources/data/test-image.png";
public static Application CURRENT_APPLICATION;
private final ObjectMapper jsonMapper = new ObjectMapper();
public static Map<String, Application> CURRENT_APPLICATIONS = Maps.newHashMap(); // | APP_NAME -> APP_OBJECT |
private AuthenticationStepDefinitions authSteps = new AuthenticationStepDefinitions();
private CommonStepDefinitions commonStepDefinitions = new CommonStepDefinitions();
private TopologyStepDefinitions topoSteps = new TopologyStepDefinitions();
private void setAppVersionIdToContext(String appId) throws IOException {
String applicationVersionJson = getRestClientInstance().get("/rest/v1/applications/" + appId + "/versions");
RestResponse<ApplicationVersion> appVersion = JsonUtil.read(applicationVersionJson, ApplicationVersion.class);
Context.getInstance().registerApplicationVersionId(appVersion.getData().getVersion(), appVersion.getData().getId());
}
@SuppressWarnings("rawtypes")
public void setAppEnvironmentIdToContext(String applicationName) throws IOException {
String applicationId = Context.getInstance().getApplicationId(applicationName);
SearchRequest request = new SearchRequest();
request.setFrom(0);
request.setSize(10);
String applicationEnvironmentsJson = getRestClientInstance().postJSon("/rest/v1/applications/" + applicationId + "/environments/search",
JsonUtil.toString(request));
RestResponse<GetMultipleDataResult> restResponse = JsonUtil.read(applicationEnvironmentsJson, GetMultipleDataResult.class);
GetMultipleDataResult searchResp = restResponse.getData();
ApplicationEnvironmentDTO appEnvDTO = JsonUtil.readObject(JsonUtil.toString(searchResp.getData()[0]), ApplicationEnvironmentDTO.class);
Context.getInstance().registerApplicationEnvironmentId(applicationName, appEnvDTO.getName(), appEnvDTO.getId());
}
@When("^I create a new application with name \"([^\"]*)\" and description \"([^\"]*)\"$")
public void I_create_a_new_application_with_name_and_description(String name, String description) throws Throwable {
createApplication(name, description, null);
}
private String getTopologyIdFromApplication(String name) throws IOException {
String response = getRestClientInstance().get("/rest/v1/applications/" + Context.getInstance().getApplicationId(name) + "/environments/"
+ Context.getInstance().getDefaultApplicationEnvironmentId(name) + "/topology");
return JsonUtil.read(response, String.class).getData();
}
@Then("^The RestResponse should contain an id string$")
public void The_RestResponse_should_contain_an_id_string() throws Throwable {
String response = Context.getInstance().getRestResponse();
assertNotNull(response);
RestResponse<String> restResponse = JsonUtil.read(response, String.class);
assertNotNull(restResponse);
assertNotNull(restResponse.getData());
assertEquals(String.class, restResponse.getData().getClass());
}
private void createApplication(String name, String description, String fromTopologyId) throws Throwable {
doCreateApplication(name, description, fromTopologyId);
// check the created application (topologyId)
RestResponse<String> response = JsonUtil.read(Context.getInstance().getRestResponse(), String.class);
String applicationJson = getRestClientInstance().get("/rest/v1/applications/" + response.getData());
Application application = JsonUtil.read(applicationJson, Application.class).getData();
if (application != null) {
CURRENT_APPLICATION = application;
CURRENT_APPLICATIONS.put(name, application);
Context.getInstance().registerApplication(application);
Context.getInstance().registerApplicationId(name, application.getId());
setAppEnvironmentIdToContext(application.getName());
setAppVersionIdToContext(application.getId());
String topologyId = getTopologyIdFromApplication(application.getName());
assertNotNull(topologyId);
Context.getInstance().registerTopologyId(topologyId);
}
}
private void doCreateApplication(String name, String description, String fromTopologyId) throws IOException {
// create the application
CreateApplicationRequest request = new CreateApplicationRequest(getArchiveNameFromApplicationName(name), name, description, fromTopologyId);
Context.getInstance().registerRestResponse(getRestClientInstance().postJSon("/rest/v1/applications/", JsonUtil.toString(request)));
}
private String getArchiveNameFromApplicationName(String name) {
return name.replaceAll("\\W", "");
}
@When("^I create a new application with name \"([^\"]*)\" and description \"([^\"]*)\" without errors$")
public void I_create_a_new_application_with_name_and_description_without_errors(String name, String description) throws Throwable {
I_create_a_new_application_with_name_and_description(name, description);
commonStepDefinitions.I_should_receive_a_RestResponse_with_no_error();
}
@When("^I retrieve the newly created application$")
public void I_retrieve_the_newly_created_application() throws Throwable {
// App from context
Application contextApp = Context.getInstance().getApplication();
Context.getInstance().registerRestResponse(getRestClientInstance().get("/rest/v1/applications/" + contextApp.getId()));
}
@Given("^There is a \"([^\"]*)\" application$")
public void There_is_a_application(String applicationName) throws Throwable {
SearchRequest searchRequest = new SearchRequest(null, applicationName, 0, 50, null);
String searchResponse = getRestClientInstance().postJSon("/rest/v1/applications/search", JsonUtil.toString(searchRequest));
RestResponse<FacetedSearchResult> response = JsonUtil.read(searchResponse, FacetedSearchResult.class);
boolean hasApplication = false;
for (Object appAsObj : response.getData().getData()) {
Application app = JsonUtil.readObject(JsonUtil.toString(appAsObj), Application.class);
if (applicationName.equals(app.getName())) {
hasApplication = true;
CURRENT_APPLICATION = app;
}
}
if (!hasApplication) {
I_create_a_new_application_with_name_and_description(applicationName, "");
}
}
@When("^I add a tag with key \"([^\"]*)\" and value \"([^\"]*)\" to the application$")
public void I_add_a_tag_with_key_and_value_to_the_component(String key, String value) throws Throwable {
addTag(CURRENT_APPLICATION.getId(), key, value);
}
private void addTag(String applicationId, String key, String value) throws JsonProcessingException, IOException {
UpdateTagRequest updateTagRequest = new UpdateTagRequest();
updateTagRequest.setTagKey(key);
updateTagRequest.setTagValue(value);
Context.getInstance().registerRestResponse(
getRestClientInstance().postJSon("/rest/v1/applications/" + applicationId + "/tags", jsonMapper.writeValueAsString(updateTagRequest)));
}
@Given("^There is a \"([^\"]*)\" application with tags:$")
public void There_is_a_application_with_tags(String applicationName, DataTable tags) throws Throwable {
// Create a new application with tags
doCreateApplication(applicationName, null, null);
String responseAsJson = Context.getInstance().getRestResponse();
String applicationId = JsonUtil.read(responseAsJson, String.class).getData();
Context.getInstance().registerApplicationId(applicationName, applicationId);
// Add tags to the application
for (List<String> rows : tags.raw()) {
addTag(applicationId, rows.get(0), rows.get(1));
}
setAppEnvironmentIdToContext(applicationName);
Context.getInstance().registerRestResponse(responseAsJson);
}
@Given("^I have an application tag \"([^\"]*)\"$")
public boolean I_have_and_a_tag(String tag) throws Throwable {
Context.getInstance().registerRestResponse(getRestClientInstance().get("/rest/v1/applications/" + CURRENT_APPLICATION.getId()));
Application application = JsonUtil.read(Context.getInstance().takeRestResponse(), Application.class).getData();
assertTrue(application.getTags().contains(new Tag(tag, null)));
return application.getTags().contains(new Tag(tag, null));
}
@When("^I delete an application tag with key \"([^\"]*)\"$")
public void I_delete_a_tag_with_key(String tagId) throws Throwable {
Context.getInstance()
.registerRestResponse(getRestClientInstance().delete("/rest/v1/applications/" + CURRENT_APPLICATION.getId() + "/tags/" + tagId));
}
private Set<String> registeredApps = Sets.newHashSet();
private String previousRestResponse;
@Given("^There is (\\d+) applications indexed in ALIEN$")
public void There_is_applications_indexed_in_ALIEN(int applicationCount) throws Throwable {
CURRENT_APPLICATIONS.clear();
registeredApps.clear();
for (int i = 0; i < applicationCount; i++) {
String appName = "name" + i;
I_create_a_new_application_with_name_and_description(appName, "");
registeredApps.add(appName);
CURRENT_APPLICATIONS.put(appName, CURRENT_APPLICATION);
}
}
@When("^I search applications from (\\d+) with result size of (\\d+)$")
public void I_search_applications_from_with_result_size_of(int from, int to) throws Throwable {
SearchRequest searchRequest = new SearchRequest(null, "", from, to, null);
previousRestResponse = Context.getInstance().getRestResponse();
Context.getInstance().registerRestResponse(getRestClientInstance().postJSon("/rest/v1/applications/search", JsonUtil.toString(searchRequest)));
}
@Then("^The RestResponse must contain (\\d+) applications.$")
public void The_RestResponse_must_contain_applications(int count) throws Throwable {
RestResponse<FacetedSearchResult> response = JsonUtil.read(Context.getInstance().getRestResponse(), FacetedSearchResult.class);
assertEquals(count, response.getData().getTotalResults());
assertEquals(count, response.getData().getData().length);
}
@Then("^I should be able to view the (\\d+) other applications.$")
public void I_should_be_able_to_view_the_other_applications(int count) throws Throwable {
removeFromRegisteredApps(previousRestResponse);
removeFromRegisteredApps(Context.getInstance().getRestResponse());
assertEquals(0, registeredApps.size());
}
@SuppressWarnings("unchecked")
private void removeFromRegisteredApps(String responseAsJson) throws Throwable {
RestResponse<FacetedSearchResult> response = JsonUtil.read(responseAsJson, FacetedSearchResult.class);
for (Object appAsObj : response.getData().getData()) {
Map<String, Object> appAsMap = (Map<String, Object>) appAsObj;
registeredApps.remove(appAsMap.get("name"));
}
}
@When("^i update its image$")
public void i_update_its_image() throws Throwable {
String appId = JsonUtil.read(Context.getInstance().getRestResponse(), String.class).getData();
RestResponse<String> response = JsonUtil.read(getRestClientInstance().postMultipart("/rest/v1/applications/" + appId + "/image", "file",
Files.newInputStream(Paths.get(TEST_APPLICATION_IMAGE))), String.class);
assertNull(response.getError());
}
@Then("^the application can be found in ALIEN$")
public Application the_application_can_be_found_in_ALIEN() throws Throwable {
String appId = CURRENT_APPLICATION.getId();
RestResponse<Application> response = JsonUtil.read(getRestClientInstance().get("/rest/v1/applications/" + appId), Application.class);
assertNotNull(response.getData());
return response.getData();
}
@Then("^the application can be found in ALIEN with its new image$")
public void the_application_can_be_found_in_ALIEN_with_its_new_image() throws Throwable {
Application app = the_application_can_be_found_in_ALIEN();
assertNotNull(app.getImageId());
}
@Given("^I create a new application with name \"([^\"]*)\" and description \"([^\"]*)\" and node templates$")
public void I_create_a_new_application_with_name_and_description_and_node_templates(String applicationName, String applicationDescription,
DataTable nodeTemplates) throws Throwable {
// create the topology
I_create_a_new_application_with_name_and_description(applicationName, applicationDescription);
EditorStepDefinitions.do_i_get_the_current_topology();
// add all specified node template to a specific topology (from Application or Topology template)
for (List<String> row : nodeTemplates.raw()) {
Map<String, String> operationMap = Maps.newHashMap();
operationMap.put("type", AddNodeOperation.class.getName());
operationMap.put("nodeName", row.get(0));
operationMap.put("indexedNodeTypeId", row.get(1));
EditorStepDefinitions.do_i_execute_the_operation(operationMap);
}
// Save the topology
EditorStepDefinitions.do_i_save_the_topology();
}
@When("^I add a role \"([^\"]*)\" to user \"([^\"]*)\" on the application \"([^\"]*)\"$")
public void I_add_a_role_to_user_on_the_application(String role, String username, String applicationName) throws Throwable {
I_search_for_application(applicationName);
Context.getInstance().registerRestResponse(
getRestClientInstance().put("/rest/v1/applications/" + CURRENT_APPLICATION.getId() + "/roles/users/" + username + "/" + role));
}
@When("^I search for \"([^\"]*)\" application$")
public void I_search_for_application(String applicationName) throws Throwable {
SearchRequest searchRequest = new SearchRequest(null, applicationName, 0, 10, null);
String searchResponse = getRestClientInstance().postJSon("/rest/v1/applications/search", JsonUtil.toString(searchRequest));
Context.getInstance().registerRestResponse(searchResponse);
RestResponse<FacetedSearchResult> response = JsonUtil.read(searchResponse, FacetedSearchResult.class);
for (Object appAsObj : response.getData().getData()) {
Application app = JsonUtil.readObject(JsonUtil.toString(appAsObj), Application.class);
if (applicationName.equals(app.getName())) {
CURRENT_APPLICATION = app;
}
}
}
@Then("^The application should have a user \"([^\"]*)\" having \"([^\"]*)\" role$")
public void The_application_should_have_a_user_having_role(String username, String expectedRole) throws Throwable {
assertNotNull(CURRENT_APPLICATION);
assertNotNull(CURRENT_APPLICATION.getUserRoles());
Set<String> userRoles = CURRENT_APPLICATION.getUserRoles().get(username);
assertNotNull(userRoles);
assertTrue(userRoles.contains(expectedRole));
}
@Given("^there is a user \"([^\"]*)\" with the \"([^\"]*)\" role on the application \"([^\"]*)\"$")
public void there_is_a_user_with_the_role_on_the_application(String username, String expectedRole, String applicationName) throws Throwable {
authSteps.There_is_a_user_in_the_system(username);
I_search_for_application(applicationName);
Map<String, Set<String>> userRoles = CURRENT_APPLICATION.getUserRoles();
if (userRoles != null && userRoles.containsKey(username)) {
if (userRoles.get(username) != null && userRoles.get(username).contains(expectedRole)) {
return;
}
}
I_add_a_role_to_user_on_the_application(expectedRole, username, applicationName);
}
@Given("^there is a user \"([^\"]*)\" with the following roles on the application \"([^\"]*)\"$")
public void there_is_a_user_with_the_following_roles_on_the_application(String username, String applicationName, List<String> expectedRoles)
throws Throwable {
for (String expectedRole : expectedRoles) {
there_is_a_user_with_the_role_on_the_application(username, expectedRole, applicationName);
}
}
@When("^I remove a role \"([^\"]*)\" to user \"([^\"]*)\" on the application \"([^\"]*)\"$")
public void I_remove_a_role_to_user_on_the_application(String role, String username, String applicationName) throws Throwable {
I_search_for_application(applicationName);
Context.getInstance().registerRestResponse(
getRestClientInstance().delete("/rest/v1/applications/" + CURRENT_APPLICATION.getId() + "/roles/users/" + username + "/" + role));
}
@Then("^The application should have a user \"([^\"]*)\" not having \"([^\"]*)\" role$")
public void The_application_should_have_a_user_not_having_role(String username, String expectedRole) throws Throwable {
if (CURRENT_APPLICATION != null && CURRENT_APPLICATION.getUserRoles() != null) {
Set<String> userRoles = CURRENT_APPLICATION.getUserRoles().get(username);
assertNotNull(userRoles);
if (userRoles != null) {
assertFalse(userRoles.contains(expectedRole));
}
}
}
@When("^I delete the application \"([^\"]*)\"$")
public void I_delete_the_application(String applicationName) throws Throwable {
String id = CURRENT_APPLICATION.getName().equals(applicationName) ? CURRENT_APPLICATION.getId() : CURRENT_APPLICATIONS.get(applicationName).getId();
Context.getInstance().registerRestResponse(getRestClientInstance().delete("/rest/v1/applications/" + id));
}
@Then("^the application should not be found$")
public Application the_application_should_not_be_found() throws Throwable {
RestResponse<Application> response = JsonUtil.read(getRestClientInstance().get("/rest/v1/applications/" + CURRENT_APPLICATION.getId()),
Application.class);
assertNull(response.getData());
return response.getData();
}
@Given("^I have applications with names and descriptions$")
public void I_have_applications_with_names_and_description(DataTable applicationNames) throws Throwable {
CURRENT_APPLICATIONS.clear();
// Create each application and store in CURRENT_APPS
for (List<String> app : applicationNames.raw()) {
doCreateApplication(app.get(0), app.get(1), null);
RestResponse<String> reponse = JsonUtil.read(Context.getInstance().getRestResponse(), String.class);
String applicationJson = getRestClientInstance().get("/rest/v1/applications/" + reponse.getData());
RestResponse<Application> application = JsonUtil.read(applicationJson, Application.class);
CURRENT_APPLICATIONS.put(app.get(0), application.getData());
Context.getInstance().registerApplicationId(application.getData().getName(), application.getData().getId());
setAppEnvironmentIdToContext(application.getData().getName());
}
assertEquals(CURRENT_APPLICATIONS.size(), applicationNames.raw().size());
}
@Given("^I have applications with names and descriptions and a topology containing a nodeTemplate \"([^\"]*)\" related to \"([^\"]*)\"$")
public void I_have_applications_with_names_and_description_containing_nodetemplate(String nodeName, String componentType,
Map<String, String> applicationRequests) throws Throwable {
CURRENT_APPLICATIONS.clear();
// Prepare a cucumber data table using the node infos.
List<String> nodeData = Lists.newArrayList(nodeName, componentType);
List<List<String>> raw = Lists.newArrayList();
raw.add(nodeData);
DataTable dataTable = DataTable.create(raw);
// Create each application and store in CURRENT_APPS
for (java.util.Map.Entry<String, String> request : applicationRequests.entrySet()) {
I_create_a_new_application_with_name_and_description_and_node_templates(request.getKey(), request.getValue(), dataTable);
CURRENT_APPLICATIONS.put(request.getKey(), CURRENT_APPLICATION);
}
assertEquals(CURRENT_APPLICATIONS.size(), applicationRequests.size());
}
@Given("^I add a role \"([^\"]*)\" to group \"([^\"]*)\" on the application \"([^\"]*)\"$")
public void I_add_a_role_to_group_on_the_application(String role, String groupName, String applicationName) throws Throwable {
I_search_for_application(applicationName);
Context.getInstance().registerRestResponse(getRestClientInstance()
.put("/rest/v1/applications/" + CURRENT_APPLICATION.getId() + "/roles/groups/" + Context.getInstance().getGroupId(groupName) + "/" + role));
}
@And("^The application should have a group \"([^\"]*)\" having \"([^\"]*)\" role$")
public void The_application_should_have_a_group_having_role(String groupName, String role) throws Throwable {
assertNotNull(CURRENT_APPLICATION);
assertNotNull(CURRENT_APPLICATION.getGroupRoles());
Set<String> groupRoles = CURRENT_APPLICATION.getGroupRoles().get(Context.getInstance().getGroupId(groupName));
assertNotNull(groupRoles);
assertTrue(groupRoles.contains(role));
}
@And("^There is a group \"([^\"]*)\" with the following roles on the application \"([^\"]*)\"$")
public void There_is_a_group_with_the_following_roles_on_the_application(String groupName, String applicationName, List<String> expectedRoles)
throws Throwable {
for (String expectedRole : expectedRoles) {
I_add_a_role_to_group_on_the_application(expectedRole, groupName, applicationName);
}
}
@When("^I remove a role \"([^\"]*)\" from group \"([^\"]*)\" on the application \"([^\"]*)\"$")
public void I_remove_a_role_from_group_on_the_application(String role, String groupName, String applicationName) throws Throwable {
I_search_for_application(applicationName);
Context.getInstance().registerRestResponse(getRestClientInstance()
.delete("/rest/v1/applications/" + CURRENT_APPLICATION.getId() + "/roles/groups/" + Context.getInstance().getGroupId(groupName) + "/" + role));
}
@And("^The application should have the group \"([^\"]*)\" not having \"([^\"]*)\" role$")
public void The_application_should_have_the_group_not_having_role(String groupName, String role) throws Throwable {
if (CURRENT_APPLICATION.getGroupRoles() != null) {
Set<String> groupRoles = CURRENT_APPLICATION.getGroupRoles().get(groupName);
if (groupRoles != null) {
assertFalse(groupRoles.contains(role));
}
}
}
@And("^The application should have the group \"([^\"]*)\" having \"([^\"]*)\" role$")
public void The_application_should_have_the_group_having_role(String groupName, String role) throws Throwable {
assertNotNull(CURRENT_APPLICATION.getGroupRoles());
Set<String> groupRoles = CURRENT_APPLICATION.getGroupRoles().get(Context.getInstance().getGroupId(groupName));
assertNotNull(groupRoles);
assertTrue(groupRoles.contains(role));
}
@And("^The RestResponse must contain these applications$")
public void The_RestResponse_must_contain_these_applications(List<String> expectedApplications) throws Throwable {
RestResponse<FacetedSearchResult> response = JsonUtil.read(Context.getInstance().getRestResponse(), FacetedSearchResult.class);
assertNotNull(response.getData());
assertEquals(expectedApplications.size(), response.getData().getTotalResults());
assertEquals(expectedApplications.size(), response.getData().getData().length);
Set<String> actualApplications = Sets.newHashSet();
for (Object appObj : response.getData().getData()) {
actualApplications.add(((Map) appObj).get("name").toString());
}
assertEquals(Sets.newHashSet(expectedApplications), actualApplications);
}
@Then("^I should receive an application without \"([^\"]*)\" as user$")
public void I_should_receive_an_application_without_as_user(String userName) throws Throwable {
RestResponse<Application> response = JsonUtil.read(Context.getInstance().getRestResponse(), Application.class);
Assert.assertNull(response.getError());
Assert.assertNotNull(response.getData());
Application application = response.getData();
if (application.getUserRoles() != null) {
Assert.assertFalse(application.getUserRoles().containsKey(userName));
}
}
@When("^I set the \"([^\"]*)\" of this application to \"([^\"]*)\"$")
public void I_set_the_of_this_application_to(String fieldName, String fieldValue) throws Throwable {
Map<String, Object> request = Maps.newHashMap();
request.put(fieldName, fieldValue);
Context.getInstance().registerRestResponse(
getRestClientInstance().putJSon("/rest/v1/applications/" + CURRENT_APPLICATION.getId(), JsonUtil.toString(request)));
ReflectionUtil.setPropertyValue(CURRENT_APPLICATION, fieldName, fieldValue);
}
@And("^The application can be found in ALIEN with its \"([^\"]*)\" set to \"([^\"]*)\"$")
public void The_application_can_be_found_in_ALIEN_with_its_set_to(String fieldName, String fieldValue) throws Throwable {
Application application = the_application_can_be_found_in_ALIEN();
Assert.assertEquals(fieldValue, ReflectionUtil.getPropertyValue(application, fieldName).toString());
}
@When("^I create an application environment of type \"([^\"]*)\" with name \"([^\"]*)\" and description \"([^\"]*)\" for the newly created application$")
public void I_create_an_application_environment_of_type_with_name_and_description_for_the_newly_created_application(String appEnvType, String appEnvName,
String appEnvDescription) throws Throwable {
Assert.assertNotNull(CURRENT_APPLICATION.getId());
Assert.assertTrue(EnvironmentType.valueOf(appEnvType).toString().equals(appEnvType));
Assert.assertNotNull(appEnvName);
ApplicationEnvironmentRequest appEnvRequest = new ApplicationEnvironmentRequest();
appEnvRequest.setEnvironmentType(EnvironmentType.valueOf(appEnvType));
appEnvRequest.setName(appEnvName);
appEnvRequest.setDescription(appEnvDescription);
appEnvRequest.setVersionId(Context.getInstance().getApplicationVersionId("0.1.0-SNAPSHOT"));
Context.getInstance().registerRestResponse(
getRestClientInstance()
.postJSon("/rest/v1/applications/" + CURRENT_APPLICATION.getId() + "/environments", JsonUtil.toString(appEnvRequest)));
RestResponse<String> appEnvId = JsonUtil.read(Context.getInstance().getRestResponse(), String.class);
if (appEnvId.getData() != null) {
Context.getInstance().registerApplicationEnvironmentId(CURRENT_APPLICATION.getName(), appEnvName, appEnvId.getData());
}
}
@When("^I get the application environment named \"([^\"]*)\"$")
public void I_get_the_application_environment_named(String applicationEnvironmentName) throws Throwable {
Assert.assertNotNull(CURRENT_APPLICATION);
String applicationEnvId = Context.getInstance().getApplicationEnvironmentId(CURRENT_APPLICATION.getName(), applicationEnvironmentName);
Context.getInstance().registerRestResponse(
getRestClientInstance().get("/rest/v1/applications/" + CURRENT_APPLICATION.getId() + "/environments/" + applicationEnvId));
RestResponse<ApplicationEnvironment> appEnvironment = JsonUtil.read(Context.getInstance().getRestResponse(), ApplicationEnvironment.class);
Assert.assertNotNull(appEnvironment.getData());
Assert.assertEquals(appEnvironment.getData().getId(), applicationEnvId);
}
@When("^I update the application environment named \"([^\"]*)\" with values$")
public void I_update_the_application_environment_named_with_values(String applicationEnvironmentName, DataTable appEnvAttributeValues) throws Throwable {
UpdateApplicationEnvironmentRequest appEnvRequest = new UpdateApplicationEnvironmentRequest();
String attribute = null, attributeValue = null;
for (List<String> attributesToUpdate : appEnvAttributeValues.raw()) {
attribute = attributesToUpdate.get(0);
attributeValue = attributesToUpdate.get(1);
switch (attribute) {
case "name":
appEnvRequest.setName(attributeValue);
break;
case "description":
appEnvRequest.setDescription(attributeValue);
break;
case "environmentType":
appEnvRequest.setEnvironmentType(EnvironmentType.valueOf(attributeValue));
break;
default:
log.info("Attribute <{}> not found in ApplicationEnvironmentRequest object", attribute);
break;
}
}
// send the update request
Context.getInstance()
.registerRestResponse(getRestClientInstance().putJSon(
"/rest/v1/applications/" + CURRENT_APPLICATION.getId() + "/environments/"
+ Context.getInstance().getApplicationEnvironmentId(CURRENT_APPLICATION.getName(), applicationEnvironmentName),
JsonUtil.toString(appEnvRequest)));
}
@When("^I update the environment named \"([^\"]*)\" to use cloud \"([^\"]*)\" for application \"([^\"]*)\"$")
public void I_update_the_environment_named_to_use_cloud_for_application(String envName, String cloudName, String appName) throws Throwable {
UpdateApplicationEnvironmentRequest appEnvRequest = new UpdateApplicationEnvironmentRequest();
// appEnvRequest.setCloudId(Context.getInstance().getCloudId(cloudName));
Assert.fail("Fix test");
String applicationId = Context.getInstance().getApplicationId(appName);
String applicationEnvironmentId = Context.getInstance().getApplicationEnvironmentId(appName, envName);
// send the update request
Context.getInstance().registerRestResponse(getRestClientInstance()
.putJSon("/rest/v1/applications/" + applicationId + "/environments/" + applicationEnvironmentId, JsonUtil.toString(appEnvRequest)));
}
@When("^I delete the registered application environment named \"([^\"]*)\" from its id$")
public void I_delete_the_registered_application_environment_named_from_its_id(String applicationEnvironmentName) throws Throwable {
Context.getInstance().registerRestResponse(getRestClientInstance().delete("/rest/v1/applications/" + CURRENT_APPLICATION.getId()
+ "/environments/" + Context.getInstance().getApplicationEnvironmentId(CURRENT_APPLICATION.getName(), applicationEnvironmentName)));
RestResponse<Boolean> appEnvironment = JsonUtil.read(Context.getInstance().getRestResponse(), Boolean.class);
Assert.assertNotNull(appEnvironment.getData());
}
@Given("^I must have an environment named \"([^\"]*)\" for application \"([^\"]*)\"$")
public void I_must_have_an_environment_named_for_application(String envName, String appName) throws Throwable {
Assert.assertNotNull(envName);
Assert.assertNotNull(appName);
String environmentId = Context.getInstance().getApplicationEnvironmentId(appName, envName);
Assert.assertNotNull(environmentId);
}
@Then("^The application update date has changed$")
public void The_application_update_date_has_changed() throws Throwable {
Application application = CURRENT_APPLICATION;
Assert.assertNotEquals(application.getCreationDate(), application.getLastUpdateDate());
}
@When("^I create a new application with name \"([^\"]*)\" and description \"([^\"]*)\" based on this created template$")
public void I_create_a_new_application_with_name_and_description_based_this_created_template(String name, String description) throws Throwable {
String topologyTemplateId = TopologyTemplateStepDefinitions.CURRENT_TOPOLOGY_TEMP_ID;
assertFalse(StringUtils.isBlank(topologyTemplateId));
createApplication(name, description, topologyTemplateId);
}
@Then("^The created application topology is the same as the one in the base topology template$")
public void The_created_application_topology_is_the_same_as_the_one_in_the_base_topology_template() throws Throwable {
// created topology
String topologyId = getTopologyIdFromApplication(CURRENT_APPLICATION.getName());
Context.getInstance().registerRestResponse(getRestClientInstance().get("/rest/v1/topologies/" + topologyId));
TopologyDTO createdTopology = JsonUtil.read(Context.getInstance().getRestResponse(), TopologyDTO.class, Context.getJsonMapper()).getData();
// base topology template
authSteps.I_am_authenticated_with_role("ARCHITECT"); // quick win solution
String topoResponse = Context.getRestClientInstance().get("/rest/v1/catalog/topologies/" + TopologyTemplateStepDefinitions.CURRENT_TOPOLOGY_TEMP_ID);
Topology topologyTemplateBase = JsonUtil.read(topoResponse, Topology.class, Context.getJsonMapper()).getData();
Map<String, NodeTemplate> nodeTemplates = topologyTemplateBase.getNodeTemplates();
// node templates count test
assertEquals(createdTopology.getTopology().getNodeTemplates().size(), nodeTemplates.size());
// node templates name / type test
for (Map.Entry<String, NodeTemplate> entry : createdTopology.getTopology().getNodeTemplates().entrySet()) {
assertTrue(nodeTemplates.containsKey(entry.getKey()));
assertTrue(nodeTemplates.get(entry.getKey()).getType().equals(entry.getValue().getType()));
}
}
@And("^I create a new application with name \"([^\"]*)\" and description \"([^\"]*)\" based on the template with name \"([^\"]*)\"$")
public void iCreateANewApplicationWithNameAndDescriptionBasedOnTheTemplateWithName(String name, String description, String templateName) throws Throwable {
String topologyTemplateId = TopologyTemplateStepDefinitions.getTopologyTemplateIdFromName(templateName);
assertFalse(StringUtils.isBlank(topologyTemplateId));
createApplication(name, description, topologyTemplateId);
}
}
| |
package com.fsryan.forsuredb.gsonserialization;
import com.fsryan.forsuredb.info.TableForeignKeyInfo;
import com.fsryan.forsuredb.migration.MigrationSet;
import com.fsryan.forsuredb.serialization.FSDbInfoSerializer;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Arrays;
import java.util.Set;
import static org.junit.Assert.assertEquals;
public abstract class SerializationTest {
private final String jsonResource;
protected URL source;
protected FSDbInfoSerializer serializerUnderTest;
public SerializationTest(String jsonResource) {
this.jsonResource = jsonResource;
}
@Before
public void setUpInputStream() {
serializerUnderTest = new FSDbInfoGsonSerializer();
source = SerializationTest.class.getClassLoader().getResource(jsonResource);
}
public static abstract class SymmetricReadWrite<IS, T> extends SerializationTest {
private IS inputSource;
public SymmetricReadWrite(String jsonResource) {
super(jsonResource);
}
@Before
public void convertInputSource() {
inputSource = convertToInputSource(source);
}
@Test
public void shouldReadAndWriteSymmetrically() throws Exception {
T read = readObject(inputSource);
String wrote = writeObject(read);
IS wroteIs = convertToInputSource(wrote);
T readAfterWrote = readObject(wroteIs);
assertEquals(read, readAfterWrote);
cleanUp(wroteIs);
}
protected abstract IS convertToInputSource(URL input);
protected abstract IS convertToInputSource(String json);
protected abstract T readObject(IS source);
protected abstract String writeObject(T object);
protected abstract void cleanUp(IS objectToClean);
}
public static abstract class SymmetricReadWriteString<T> extends SymmetricReadWrite<String, T> {
public SymmetricReadWriteString(String jsonResource) {
super(jsonResource);
}
@Override
protected final String convertToInputSource(URL input) {
try (BufferedReader inBuf = new BufferedReader(new InputStreamReader(input.openStream()))) {
String line = null;
StringBuilder outBuf = new StringBuilder();
while ((line = inBuf.readLine()) != null) {
outBuf.append(line).append("\n");
}
return outBuf.delete(outBuf.length() - 1, outBuf.length()).toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected final String convertToInputSource(String input) {
return input;
}
@Override
protected final void cleanUp(String objectToClean) {
// do nothing
}
}
public static abstract class SymmetricReadWriteInputStream<T> extends SymmetricReadWrite<InputStream, T> {
public SymmetricReadWriteInputStream(String jsonResource) {
super(jsonResource);
}
@Override
protected final InputStream convertToInputSource(URL input) {
try {
return input.openStream();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
protected final InputStream convertToInputSource(String json) {
return new ByteArrayInputStream(json.getBytes());
}
@Override
protected final void cleanUp(InputStream objectToClean) {
try {
objectToClean.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@RunWith(Parameterized.class)
public static class MigrationSetFromStream extends SymmetricReadWriteInputStream<MigrationSet> {
public MigrationSetFromStream(String jsonResource) {
super(jsonResource);
}
@Parameterized.Parameters
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{"00_first_schema.json"},
{"01_a_legacy_schema.json"},
{"02_schema_0_7_0.json"},
{"03_schema_0_8_0.json"},
{"04_schema_0_9_0.json"},
{"05_schema_0_12_0.json"}
});
}
@Override
protected MigrationSet readObject(InputStream source) {
return serializerUnderTest.deserializeMigrationSet(source);
}
@Override
protected String writeObject(MigrationSet migrationSet) {
return serializerUnderTest.serialize(migrationSet);
}
}
@RunWith(Parameterized.class)
public static class MigrationSetFromString extends SymmetricReadWriteString<MigrationSet> {
public MigrationSetFromString(String jsonResource) {
super(jsonResource);
}
@Parameterized.Parameters
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{"00_first_schema.json"},
{"01_a_legacy_schema.json"},
{"02_schema_0_7_0.json"},
{"03_schema_0_8_0.json"},
{"04_schema_0_9_0.json"},
{"05_schema_0_12_0.json"}
});
}
@Override
protected MigrationSet readObject(String source) {
return serializerUnderTest.deserializeMigrationSet(source);
}
@Override
protected String writeObject(MigrationSet migrationSet) {
return serializerUnderTest.serialize(migrationSet);
}
}
@RunWith(Parameterized.class)
public static class TableForeignKeyInfoSets extends SymmetricReadWriteString<Set<TableForeignKeyInfo>> {
public TableForeignKeyInfoSets(String jsonResource) {
super(jsonResource);
}
@Parameterized.Parameters
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{"table_foreign_keys_set.json"},
});
}
@Override
protected Set<TableForeignKeyInfo> readObject(String json) {
return serializerUnderTest.deserializeForeignKeys(json);
}
@Override
protected String writeObject(Set<TableForeignKeyInfo> object) {
return acquireSubjectGson().toJson(object);
}
}
@RunWith(Parameterized.class)
public static class ColumnNames extends SymmetricReadWriteString<Set<String>> {
public ColumnNames(String jsonResource) {
super(jsonResource);
}
@Parameterized.Parameters
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{"string_set.json"},
});
}
@Override
protected Set<String> readObject(String json) {
return serializerUnderTest.deserializeColumnNames(json);
}
@Override
protected String writeObject(Set<String> object) {
try {
return acquireSubjectGson().toJson(object);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
static Gson acquireSubjectGson() {
try {
Field gsonField = FSDbInfoGsonSerializer.class.getDeclaredField("gson");
gsonField.setAccessible(true);
return (Gson) gsonField.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| |
/*
* Copyright 2003-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package groovy.ui.text;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.Segment;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyleContext;
/**
* @author Evan "Hippy" Slatis
*/
public class GroovyFilter extends StructuredSyntaxDocumentFilter {
// java tab policy action
private static final Action AUTO_TAB_ACTION = new AutoTabAction();
// Style names
public static final String COMMENT = "comment";
public static final String SLASH_STAR_COMMENT = "/\\*(?s:.)*?(?:\\*/|\\z)";
public static final String SLASH_SLASH_COMMENT = "//.*";
public static final String QUOTES =
"(?ms:\"{3}(?!\\\"{1,3}).*?(?:\"{3}|\\z))|(?:\"{1}(?!\\\").*?(?:\"|\\Z))";
public static final String SINGLE_QUOTES =
"(?ms:'{3}(?!'{1,3}).*?(?:'{3}|\\z))|(?:'[^'].*?(?:'|\\z))";
public static final String SLASHY_QUOTES = "(?:/[^/*].*?/|(?ms:\\$/.*?(?:/\\$|\\z)))";
public static final String DIGIT = "\\d+?[efld]?";
public static final String IDENT = "[\\w\\$&&[\\D]][\\w\\$]*";
public static final String OPERATION = "[\\w\\$&&[\\D]][\\w\\$]* *\\(";
public static final String LEFT_PARENS = "\\(";
private static final Color COMMENT_COLOR =
Color.LIGHT_GRAY.darker().darker();
public static final String RESERVED_WORD = "reserved";
public static final String[] RESERVED_WORDS = {"\\babstract\\b",
"\\bassert\\b",
"\\bdefault\\b",
"\\bif\\b",
"\\bprivate\\b",
"\\bthis\\b",
"\\bboolean\\b",
"\\bdo\\b",
"\\bimplements\\b",
"\\bprotected\\b",
"\\bthrow\\b",
"\\bbreak\\b",
"\\bdouble\\b",
"\\bimport\\b",
"\\bpublic\\b",
"\\bthrows\\b",
"\\bbyte\\b",
"\\belse\\b",
"\\binstanceof\\b",
"\\breturn\\b",
"\\btransient\\b",
"\\bcase\\b",
"\\bextends\\b",
"\\bint\\b",
"\\bshort\\b",
"\\btry\\b",
"\\bcatch\\b",
"\\bfinal\\b",
"\\binterface\\b",
"\\benum\\b",
"\\bstatic\\b",
"\\bvoid\\b",
"\\bchar\\b",
"\\bfinally\\b",
"\\blong\\b",
"\\bstrictfp\\b",
"\\bvolatile\\b",
"\\bclass\\b",
"\\bfloat\\b",
"\\bnative\\b",
"\\bsuper\\b",
"\\bwhile\\b",
"\\bconst\\b",
"\\bfor\\b",
"\\bnew\\b",
"\\bswitch\\b",
"\\bcontinue\\b",
"\\bgoto\\b",
"\\bpackage\\b",
"\\bdef\\b",
"\\bas\\b",
"\\bin\\b",
"\\bsynchronized\\b",
"\\bnull\\b"};
/**
* Creates a new instance of GroovyFilter
*/
public GroovyFilter(DefaultStyledDocument doc) {
super(doc);
init();
}
private void init() {
StyleContext styleContext = StyleContext.getDefaultStyleContext();
Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
Style comment = styleContext.addStyle(COMMENT, defaultStyle);
StyleConstants.setForeground(comment, COMMENT_COLOR);
StyleConstants.setItalic(comment, true);
Style quotes = styleContext.addStyle(QUOTES, defaultStyle);
StyleConstants.setForeground(quotes, Color.MAGENTA.darker().darker());
Style charQuotes = styleContext.addStyle(SINGLE_QUOTES, defaultStyle);
StyleConstants.setForeground(charQuotes, Color.GREEN.darker().darker());
Style slashyQuotes = styleContext.addStyle(SLASHY_QUOTES, defaultStyle);
StyleConstants.setForeground(slashyQuotes, Color.ORANGE.darker());
Style digit = styleContext.addStyle(DIGIT, defaultStyle);
StyleConstants.setForeground(digit, Color.RED.darker());
Style operation = styleContext.addStyle(OPERATION, defaultStyle);
StyleConstants.setBold(operation, true);
Style ident = styleContext.addStyle(IDENT, defaultStyle);
Style reservedWords = styleContext.addStyle(RESERVED_WORD, defaultStyle);
StyleConstants.setBold(reservedWords, true);
StyleConstants.setForeground(reservedWords, Color.BLUE.darker().darker());
Style leftParens = styleContext.addStyle(IDENT, defaultStyle);
getRootNode().putStyle(SLASH_STAR_COMMENT, comment);
getRootNode().putStyle(SLASH_SLASH_COMMENT, comment);
getRootNode().putStyle(QUOTES, quotes);
getRootNode().putStyle(SINGLE_QUOTES, charQuotes);
getRootNode().putStyle(SLASHY_QUOTES, slashyQuotes);
getRootNode().putStyle(DIGIT, digit);
getRootNode().putStyle(OPERATION, operation);
StructuredSyntaxDocumentFilter.LexerNode node = createLexerNode();
node.putStyle(RESERVED_WORDS, reservedWords);
node.putStyle(LEFT_PARENS, leftParens);
getRootNode().putChild(OPERATION, node);
getRootNode().putStyle(IDENT, ident);
node = createLexerNode();
node.putStyle(RESERVED_WORDS, reservedWords);
getRootNode().putChild(IDENT, node);
}
public static void installAutoTabAction(JTextComponent tComp) {
tComp.getActionMap().put("GroovyFilter-autoTab", AUTO_TAB_ACTION);
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
tComp.getInputMap().put(keyStroke, "GroovyFilter-autoTab");
}
private static class AutoTabAction extends AbstractAction {
private StyledDocument doc;
private final Segment segment = new Segment();
private final StringBuffer buffer = new StringBuffer();
public void actionPerformed(ActionEvent ae) {
JTextComponent tComp = (JTextComponent) ae.getSource();
if (tComp.getDocument() instanceof StyledDocument) {
doc = (StyledDocument) tComp.getDocument();
try {
doc.getText(0, doc.getLength(), segment);
}
catch (Exception e) {
// should NEVER reach here
e.printStackTrace();
}
int offset = tComp.getCaretPosition();
int index = findTabLocation(offset);
buffer.delete(0, buffer.length());
buffer.append('\n');
if (index > -1) {
for (int i = 0; i < index + 4; i++) {
buffer.append(' ');
}
}
try {
doc.insertString(offset, buffer.toString(),
doc.getDefaultRootElement().getAttributes());
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
public int findTabLocation(int offset) {
// find first {
boolean cont = true;
while (offset > -1 && cont) {
Element el = doc.getCharacterElement(offset);
Object color =
el.getAttributes().getAttribute(StyleConstants.Foreground);
if (!COMMENT_COLOR.equals(color)) {
cont = segment.array[offset] != '{' &&
segment.array[offset] != '}';
}
offset -= cont ? 1 : 0;
}
if (offset > -1 && segment.array[offset] == '{') {
while (offset > -1 &&
!Character.isWhitespace(segment.array[offset--])) {
}
}
int index = offset < 0 || segment.array[offset] == '}' ? -4 : 0;
if (offset > -1) {
Element top = doc.getDefaultRootElement();
offset = top.getElement(top.getElementIndex(offset)).getStartOffset();
while (Character.isWhitespace(segment.array[offset++])) {
index++;
}
}
return index;
}
}
}
| |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.networkservices.v1beta1.model;
/**
* EndpointPolicy is a resource that helps apply desired configuration on the endpoints that match
* specific criteria. For example, this resource can be used to apply "authentication config" an all
* endpoints that serve on port 8080.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Network Services API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class EndpointPolicy extends com.google.api.client.json.GenericJson {
/**
* Optional. This field specifies the URL of AuthorizationPolicy resource that applies
* authorization policies to the inbound traffic at the matched endpoints. Refer to Authorization.
* If this field is not specified, authorization is disabled(no authz checks) for this endpoint.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String authorizationPolicy;
/**
* Optional. A URL referring to a ClientTlsPolicy resource. ClientTlsPolicy can be set to specify
* the authentication for traffic from the proxy to the actual endpoints. More specifically, it is
* applied to the outgoing traffic from the proxy to the endpoint. This is typically used for
* sidecar model where the proxy identifies itself as endpoint to the control plane, with the
* connection between sidecar and endpoint requiring authentication. If this field is not set,
* authentication is disabled(open). Applicable only when EndpointPolicyType is SIDECAR_PROXY.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String clientTlsPolicy;
/**
* Output only. The timestamp when the resource was created.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String createTime;
/**
* Optional. A free-text description of the resource. Max length 1024 characters.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* Required. A matcher that selects endpoints to which the policies should be applied.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private EndpointMatcher endpointMatcher;
/**
* Optional. Set of label tags associated with the EndpointPolicy resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* Required. Name of the EndpointPolicy resource. It matches pattern
* `projects/{project}/locations/global/endpointPolicies/{endpoint_policy}`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Optional. A URL referring to ServerTlsPolicy resource. ServerTlsPolicy is used to determine the
* authentication policy to be applied to terminate the inbound traffic at the identified
* backends. If this field is not set, authentication is disabled(open) for this endpoint.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String serverTlsPolicy;
/**
* Optional. Port selector for the (matched) endpoints. If no port selector is provided, the
* matched config is applied to all ports.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TrafficPortSelector trafficPortSelector;
/**
* Required. The type of endpoint policy. This is primarily used to validate the configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Output only. The timestamp when the resource was updated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String updateTime;
/**
* Optional. This field specifies the URL of AuthorizationPolicy resource that applies
* authorization policies to the inbound traffic at the matched endpoints. Refer to Authorization.
* If this field is not specified, authorization is disabled(no authz checks) for this endpoint.
* @return value or {@code null} for none
*/
public java.lang.String getAuthorizationPolicy() {
return authorizationPolicy;
}
/**
* Optional. This field specifies the URL of AuthorizationPolicy resource that applies
* authorization policies to the inbound traffic at the matched endpoints. Refer to Authorization.
* If this field is not specified, authorization is disabled(no authz checks) for this endpoint.
* @param authorizationPolicy authorizationPolicy or {@code null} for none
*/
public EndpointPolicy setAuthorizationPolicy(java.lang.String authorizationPolicy) {
this.authorizationPolicy = authorizationPolicy;
return this;
}
/**
* Optional. A URL referring to a ClientTlsPolicy resource. ClientTlsPolicy can be set to specify
* the authentication for traffic from the proxy to the actual endpoints. More specifically, it is
* applied to the outgoing traffic from the proxy to the endpoint. This is typically used for
* sidecar model where the proxy identifies itself as endpoint to the control plane, with the
* connection between sidecar and endpoint requiring authentication. If this field is not set,
* authentication is disabled(open). Applicable only when EndpointPolicyType is SIDECAR_PROXY.
* @return value or {@code null} for none
*/
public java.lang.String getClientTlsPolicy() {
return clientTlsPolicy;
}
/**
* Optional. A URL referring to a ClientTlsPolicy resource. ClientTlsPolicy can be set to specify
* the authentication for traffic from the proxy to the actual endpoints. More specifically, it is
* applied to the outgoing traffic from the proxy to the endpoint. This is typically used for
* sidecar model where the proxy identifies itself as endpoint to the control plane, with the
* connection between sidecar and endpoint requiring authentication. If this field is not set,
* authentication is disabled(open). Applicable only when EndpointPolicyType is SIDECAR_PROXY.
* @param clientTlsPolicy clientTlsPolicy or {@code null} for none
*/
public EndpointPolicy setClientTlsPolicy(java.lang.String clientTlsPolicy) {
this.clientTlsPolicy = clientTlsPolicy;
return this;
}
/**
* Output only. The timestamp when the resource was created.
* @return value or {@code null} for none
*/
public String getCreateTime() {
return createTime;
}
/**
* Output only. The timestamp when the resource was created.
* @param createTime createTime or {@code null} for none
*/
public EndpointPolicy setCreateTime(String createTime) {
this.createTime = createTime;
return this;
}
/**
* Optional. A free-text description of the resource. Max length 1024 characters.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* Optional. A free-text description of the resource. Max length 1024 characters.
* @param description description or {@code null} for none
*/
public EndpointPolicy setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* Required. A matcher that selects endpoints to which the policies should be applied.
* @return value or {@code null} for none
*/
public EndpointMatcher getEndpointMatcher() {
return endpointMatcher;
}
/**
* Required. A matcher that selects endpoints to which the policies should be applied.
* @param endpointMatcher endpointMatcher or {@code null} for none
*/
public EndpointPolicy setEndpointMatcher(EndpointMatcher endpointMatcher) {
this.endpointMatcher = endpointMatcher;
return this;
}
/**
* Optional. Set of label tags associated with the EndpointPolicy resource.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* Optional. Set of label tags associated with the EndpointPolicy resource.
* @param labels labels or {@code null} for none
*/
public EndpointPolicy setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* Required. Name of the EndpointPolicy resource. It matches pattern
* `projects/{project}/locations/global/endpointPolicies/{endpoint_policy}`.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Required. Name of the EndpointPolicy resource. It matches pattern
* `projects/{project}/locations/global/endpointPolicies/{endpoint_policy}`.
* @param name name or {@code null} for none
*/
public EndpointPolicy setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Optional. A URL referring to ServerTlsPolicy resource. ServerTlsPolicy is used to determine the
* authentication policy to be applied to terminate the inbound traffic at the identified
* backends. If this field is not set, authentication is disabled(open) for this endpoint.
* @return value or {@code null} for none
*/
public java.lang.String getServerTlsPolicy() {
return serverTlsPolicy;
}
/**
* Optional. A URL referring to ServerTlsPolicy resource. ServerTlsPolicy is used to determine the
* authentication policy to be applied to terminate the inbound traffic at the identified
* backends. If this field is not set, authentication is disabled(open) for this endpoint.
* @param serverTlsPolicy serverTlsPolicy or {@code null} for none
*/
public EndpointPolicy setServerTlsPolicy(java.lang.String serverTlsPolicy) {
this.serverTlsPolicy = serverTlsPolicy;
return this;
}
/**
* Optional. Port selector for the (matched) endpoints. If no port selector is provided, the
* matched config is applied to all ports.
* @return value or {@code null} for none
*/
public TrafficPortSelector getTrafficPortSelector() {
return trafficPortSelector;
}
/**
* Optional. Port selector for the (matched) endpoints. If no port selector is provided, the
* matched config is applied to all ports.
* @param trafficPortSelector trafficPortSelector or {@code null} for none
*/
public EndpointPolicy setTrafficPortSelector(TrafficPortSelector trafficPortSelector) {
this.trafficPortSelector = trafficPortSelector;
return this;
}
/**
* Required. The type of endpoint policy. This is primarily used to validate the configuration.
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Required. The type of endpoint policy. This is primarily used to validate the configuration.
* @param type type or {@code null} for none
*/
public EndpointPolicy setType(java.lang.String type) {
this.type = type;
return this;
}
/**
* Output only. The timestamp when the resource was updated.
* @return value or {@code null} for none
*/
public String getUpdateTime() {
return updateTime;
}
/**
* Output only. The timestamp when the resource was updated.
* @param updateTime updateTime or {@code null} for none
*/
public EndpointPolicy setUpdateTime(String updateTime) {
this.updateTime = updateTime;
return this;
}
@Override
public EndpointPolicy set(String fieldName, Object value) {
return (EndpointPolicy) super.set(fieldName, value);
}
@Override
public EndpointPolicy clone() {
return (EndpointPolicy) super.clone();
}
}
| |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE;
import static java.util.Arrays.asList;
import static org.junit.contrib.truth.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.DerivedComparable;
import com.google.common.collect.testing.IteratorTester;
import com.google.common.testing.SerializableTester;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
/**
* Unit tests for {@code TreeMultimap} with natural ordering.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class TreeMultimapNaturalTest<E> extends AbstractSetMultimapTest {
@Override protected Multimap<String, Integer> create() {
return TreeMultimap.create();
}
/* Null keys and values aren't supported. */
@Override protected String nullKey() {
return "null";
}
@Override protected Integer nullValue() {
return 42;
}
/**
* Create and populate a {@code TreeMultimap} with the natural ordering of
* keys and values.
*/
private TreeMultimap<String, Integer> createPopulate() {
TreeMultimap<String, Integer> multimap = TreeMultimap.create();
multimap.put("google", 2);
multimap.put("google", 6);
multimap.put("foo", 3);
multimap.put("foo", 1);
multimap.put("foo", 7);
multimap.put("tree", 4);
multimap.put("tree", 0);
return multimap;
}
public void testToString() {
assertEquals("{bar=[1, 2, 3], foo=[-1, 1, 2, 3, 4]}",
createSample().toString());
}
public void testOrderedGet() {
TreeMultimap<String, Integer> multimap = createPopulate();
ASSERT.that(multimap.get("foo")).hasContentsInOrder(1, 3, 7);
ASSERT.that(multimap.get("google")).hasContentsInOrder(2, 6);
ASSERT.that(multimap.get("tree")).hasContentsInOrder(0, 4);
}
public void testOrderedKeySet() {
TreeMultimap<String, Integer> multimap = createPopulate();
ASSERT.that(multimap.keySet()).hasContentsInOrder("foo", "google", "tree");
}
public void testOrderedAsMapEntries() {
TreeMultimap<String, Integer> multimap = createPopulate();
Iterator<Map.Entry<String, Collection<Integer>>> iterator =
multimap.asMap().entrySet().iterator();
Map.Entry<String, Collection<Integer>> entry = iterator.next();
assertEquals("foo", entry.getKey());
ASSERT.that(entry.getValue()).hasContentsAnyOrder(1, 3, 7);
entry = iterator.next();
assertEquals("google", entry.getKey());
ASSERT.that(entry.getValue()).hasContentsAnyOrder(2, 6);
entry = iterator.next();
assertEquals("tree", entry.getKey());
ASSERT.that(entry.getValue()).hasContentsAnyOrder(0, 4);
}
public void testOrderedEntries() {
TreeMultimap<String, Integer> multimap = createPopulate();
ASSERT.that(multimap.entries()).hasContentsInOrder(
Maps.immutableEntry("foo", 1),
Maps.immutableEntry("foo", 3),
Maps.immutableEntry("foo", 7),
Maps.immutableEntry("google", 2),
Maps.immutableEntry("google", 6),
Maps.immutableEntry("tree", 0),
Maps.immutableEntry("tree", 4));
}
public void testOrderedValues() {
TreeMultimap<String, Integer> multimap = createPopulate();
ASSERT.that(multimap.values()).hasContentsInOrder(
1, 3, 7, 2, 6, 0, 4);
}
public void testFirst() {
TreeMultimap<String, Integer> multimap = createPopulate();
assertEquals(Integer.valueOf(1), multimap.get("foo").first());
try {
multimap.get("missing").first();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException expected) {}
}
public void testLast() {
TreeMultimap<String, Integer> multimap = createPopulate();
assertEquals(Integer.valueOf(7), multimap.get("foo").last());
try {
multimap.get("missing").last();
fail("Expected NoSuchElementException");
} catch (NoSuchElementException expected) {}
}
public void testComparatorFromGet() {
TreeMultimap<String, Integer> multimap = createPopulate();
assertSame(Ordering.natural(), multimap.get("foo").comparator());
assertSame(Ordering.natural(), multimap.get("missing").comparator());
}
public void testHeadSet() {
TreeMultimap<String, Integer> multimap = createPopulate();
Set<Integer> fooSet = multimap.get("foo").headSet(4);
assertEquals(Sets.newHashSet(1, 3), fooSet);
Set<Integer> missingSet = multimap.get("missing").headSet(4);
assertEquals(Sets.newHashSet(), missingSet);
multimap.put("foo", 0);
assertEquals(Sets.newHashSet(0, 1, 3), fooSet);
missingSet.add(2);
assertEquals(Sets.newHashSet(2), multimap.get("missing"));
}
public void testTailSet() {
TreeMultimap<String, Integer> multimap = createPopulate();
Set<Integer> fooSet = multimap.get("foo").tailSet(2);
assertEquals(Sets.newHashSet(3, 7), fooSet);
Set<Integer> missingSet = multimap.get("missing").tailSet(4);
assertEquals(Sets.newHashSet(), missingSet);
multimap.put("foo", 6);
assertEquals(Sets.newHashSet(3, 6, 7), fooSet);
missingSet.add(9);
assertEquals(Sets.newHashSet(9), multimap.get("missing"));
}
public void testSubSet() {
TreeMultimap<String, Integer> multimap = createPopulate();
Set<Integer> fooSet = multimap.get("foo").subSet(2, 6);
assertEquals(Sets.newHashSet(3), fooSet);
multimap.put("foo", 5);
assertEquals(Sets.newHashSet(3, 5), fooSet);
fooSet.add(4);
assertEquals(Sets.newHashSet(1, 3, 4, 5, 7), multimap.get("foo"));
}
public void testMultimapConstructor() {
Multimap<String, Integer> multimap = createSample();
TreeMultimap<String, Integer> copy = TreeMultimap.create(multimap);
assertEquals(multimap, copy);
}
private static final Comparator<Double> KEY_COMPARATOR =
Ordering.natural();
private static final Comparator<Double> VALUE_COMPARATOR =
Ordering.natural().reverse().nullsFirst();
/**
* Test that creating one TreeMultimap from another does not copy the
* comparators from the source TreeMultimap.
*/
public void testCreateFromTreeMultimap() {
Multimap<Double, Double> tree = TreeMultimap.create(KEY_COMPARATOR, VALUE_COMPARATOR);
tree.put(1.0, 2.0);
tree.put(2.0, 3.0);
tree.put(3.0, 4.0);
tree.put(4.0, 5.0);
TreeMultimap<Double, Double> copyFromTree = TreeMultimap.create(tree);
assertEquals(tree, copyFromTree);
assertSame(Ordering.natural(), copyFromTree.keyComparator());
assertSame(Ordering.natural(), copyFromTree.valueComparator());
assertSame(Ordering.natural(), copyFromTree.get(1.0).comparator());
}
/**
* Test that creating one TreeMultimap from a non-TreeMultimap
* results in natural ordering.
*/
public void testCreateFromHashMultimap() {
Multimap<Double, Double> hash = HashMultimap.create();
hash.put(1.0, 2.0);
hash.put(2.0, 3.0);
hash.put(3.0, 4.0);
hash.put(4.0, 5.0);
TreeMultimap<Double, Double> copyFromHash = TreeMultimap.create(hash);
assertEquals(hash, copyFromHash);
assertEquals(Ordering.natural(), copyFromHash.keyComparator());
assertEquals(Ordering.natural(), copyFromHash.valueComparator());
}
/**
* Test that creating one TreeMultimap from a SortedSetMultimap uses natural
* ordering.
*/
public void testCreateFromSortedSetMultimap() {
SortedSetMultimap<Double, Double> tree = TreeMultimap.create(KEY_COMPARATOR, VALUE_COMPARATOR);
tree.put(1.0, 2.0);
tree.put(2.0, 3.0);
tree.put(3.0, 4.0);
tree.put(4.0, 5.0);
SortedSetMultimap<Double, Double> sorted = Multimaps.unmodifiableSortedSetMultimap(tree);
TreeMultimap<Double, Double> copyFromSorted = TreeMultimap.create(sorted);
assertEquals(tree, copyFromSorted);
assertSame(Ordering.natural(), copyFromSorted.keyComparator());
assertSame(Ordering.natural(), copyFromSorted.valueComparator());
assertSame(Ordering.natural(), copyFromSorted.get(1.0).comparator());
}
public void testComparators() {
TreeMultimap<String, Integer> multimap = TreeMultimap.create();
assertEquals(Ordering.natural(), multimap.keyComparator());
assertEquals(Ordering.natural(), multimap.valueComparator());
}
public void testSortedKeySet() {
TreeMultimap<String, Integer> multimap = createPopulate();
SortedSet<String> keySet = multimap.keySet();
assertEquals("foo", keySet.first());
assertEquals("tree", keySet.last());
assertEquals(Ordering.natural(), keySet.comparator());
assertEquals(ImmutableSet.of("foo", "google"), keySet.headSet("hi"));
assertEquals(ImmutableSet.of("tree"), keySet.tailSet("hi"));
assertEquals(ImmutableSet.of("google"), keySet.subSet("gap", "hi"));
}
public void testKeySetSubSet() {
TreeMultimap<String, Integer> multimap = createPopulate();
SortedSet<String> keySet = multimap.keySet();
SortedSet<String> subSet = keySet.subSet("gap", "hi");
assertEquals(1, subSet.size());
assertTrue(subSet.contains("google"));
assertFalse(subSet.contains("foo"));
assertTrue(subSet.containsAll(Collections.singleton("google")));
assertFalse(subSet.containsAll(Collections.singleton("foo")));
Iterator<String> iterator = subSet.iterator();
assertTrue(iterator.hasNext());
assertEquals("google", iterator.next());
assertFalse(iterator.hasNext());
assertFalse(subSet.remove("foo"));
assertTrue(multimap.containsKey("foo"));
assertEquals(7, multimap.size());
assertTrue(subSet.remove("google"));
assertFalse(multimap.containsKey("google"));
assertEquals(5, multimap.size());
}
@GwtIncompatible("unreasonable slow")
public void testGetIteration() {
new IteratorTester<Integer>(6, MODIFIABLE,
Sets.newTreeSet(asList(2, 3, 4, 7, 8)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
private Multimap<String, Integer> multimap;
@Override protected Iterator<Integer> newTargetIterator() {
multimap = create();
multimap.putAll("foo", asList(3, 8, 4));
multimap.putAll("bar", asList(5, 6));
multimap.putAll("foo", asList(7, 2));
return multimap.get("foo").iterator();
}
@Override protected void verify(List<Integer> elements) {
assertEquals(newHashSet(elements), multimap.get("foo"));
}
}.test();
}
@SuppressWarnings("unchecked")
@GwtIncompatible("unreasonable slow")
public void testEntriesIteration() {
Set<Entry<String, Integer>> set = Sets.newLinkedHashSet(asList(
Maps.immutableEntry("bar", 4),
Maps.immutableEntry("bar", 5),
Maps.immutableEntry("foo", 2),
Maps.immutableEntry("foo", 3),
Maps.immutableEntry("foo", 6)));
new IteratorTester<Entry<String, Integer>>(6, MODIFIABLE, set,
IteratorTester.KnownOrder.KNOWN_ORDER) {
private Multimap<String, Integer> multimap;
@Override protected Iterator<Entry<String, Integer>> newTargetIterator() {
multimap = create();
multimap.putAll("foo", asList(6, 3));
multimap.putAll("bar", asList(4, 5));
multimap.putAll("foo", asList(2));
return multimap.entries().iterator();
}
@Override protected void verify(List<Entry<String, Integer>> elements) {
assertEquals(newHashSet(elements), multimap.entries());
}
}.test();
}
@GwtIncompatible("unreasonable slow")
public void testKeysIteration() {
new IteratorTester<String>(6, MODIFIABLE, Lists.newArrayList("bar", "bar",
"foo", "foo", "foo"), IteratorTester.KnownOrder.KNOWN_ORDER) {
private Multimap<String, Integer> multimap;
@Override protected Iterator<String> newTargetIterator() {
multimap = create();
multimap.putAll("foo", asList(2, 3));
multimap.putAll("bar", asList(4, 5));
multimap.putAll("foo", asList(6));
return multimap.keys().iterator();
}
@Override protected void verify(List<String> elements) {
assertEquals(elements, Lists.newArrayList(multimap.keys()));
}
}.test();
}
@GwtIncompatible("unreasonable slow")
public void testValuesIteration() {
new IteratorTester<Integer>(6, MODIFIABLE, newArrayList(4, 5, 2, 3, 6),
IteratorTester.KnownOrder.KNOWN_ORDER) {
private Multimap<String, Integer> multimap;
@Override protected Iterator<Integer> newTargetIterator() {
multimap = create();
multimap.putAll("foo", asList(2, 3));
multimap.putAll("bar", asList(4, 5));
multimap.putAll("foo", asList(6));
return multimap.values().iterator();
}
@Override protected void verify(List<Integer> elements) {
assertEquals(elements, Lists.newArrayList(multimap.values()));
}
}.test();
}
@GwtIncompatible("unreasonable slow")
public void testKeySetIteration() {
new IteratorTester<String>(6, MODIFIABLE,
Sets.newTreeSet(asList("bar", "baz", "cat", "dog", "foo")),
IteratorTester.KnownOrder.KNOWN_ORDER) {
private Multimap<String, Integer> multimap;
@Override protected Iterator<String> newTargetIterator() {
multimap = create();
multimap.putAll("foo", asList(2, 3));
multimap.putAll("bar", asList(4, 5));
multimap.putAll("foo", asList(6));
multimap.putAll("baz", asList(7, 8));
multimap.putAll("dog", asList(9));
multimap.putAll("bar", asList(10, 11));
multimap.putAll("cat", asList(12, 13, 14));
return multimap.keySet().iterator();
}
@Override protected void verify(List<String> elements) {
assertEquals(newHashSet(elements), multimap.keySet());
}
}.test();
}
@SuppressWarnings("unchecked")
@GwtIncompatible("unreasonable slow")
public void testAsSetIteration() {
Set<Entry<String, Collection<Integer>>> set = Sets.newTreeSet(
new Comparator<Entry<String, ?>>() {
@Override
public int compare(Entry<String, ?> o1, Entry<String, ?> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
Collections.addAll(set,
Maps.immutableEntry("bar",
(Collection<Integer>) Sets.newHashSet(4, 5, 10, 11)),
Maps.immutableEntry("baz",
(Collection<Integer>) Sets.newHashSet(7, 8)),
Maps.immutableEntry("cat",
(Collection<Integer>) Sets.newHashSet(12, 13, 14)),
Maps.immutableEntry("dog",
(Collection<Integer>) Sets.newHashSet(9)),
Maps.immutableEntry("foo",
(Collection<Integer>) Sets.newHashSet(2, 3, 6))
);
new IteratorTester<Entry<String, Collection<Integer>>>(6, MODIFIABLE, set,
IteratorTester.KnownOrder.KNOWN_ORDER) {
private Multimap<String, Integer> multimap;
@Override protected Iterator<Entry<String, Collection<Integer>>>
newTargetIterator() {
multimap = create();
multimap.putAll("foo", asList(2, 3));
multimap.putAll("bar", asList(4, 5));
multimap.putAll("foo", asList(6));
multimap.putAll("baz", asList(7, 8));
multimap.putAll("dog", asList(9));
multimap.putAll("bar", asList(10, 11));
multimap.putAll("cat", asList(12, 13, 14));
return multimap.asMap().entrySet().iterator();
}
@Override protected void verify(
List<Entry<String, Collection<Integer>>> elements) {
assertEquals(newHashSet(elements), multimap.asMap().entrySet());
}
}.test();
}
@GwtIncompatible("SerializableTester")
public void testExplicitComparatorSerialization() {
TreeMultimap<String, Integer> multimap = createPopulate();
TreeMultimap<String, Integer> copy
= SerializableTester.reserializeAndAssert(multimap);
ASSERT.that(copy.values()).hasContentsInOrder(1, 3, 7, 2, 6, 0, 4);
ASSERT.that(copy.keySet()).hasContentsInOrder("foo", "google", "tree");
assertEquals(multimap.keyComparator(), copy.keyComparator());
assertEquals(multimap.valueComparator(), copy.valueComparator());
}
@GwtIncompatible("SerializableTester")
public void testTreeMultimapDerived() {
TreeMultimap<DerivedComparable, DerivedComparable> multimap = TreeMultimap.create();
assertEquals(ImmutableMultimap.of(), multimap);
multimap.put(new DerivedComparable("foo"), new DerivedComparable("f"));
multimap.put(new DerivedComparable("foo"), new DerivedComparable("o"));
multimap.put(new DerivedComparable("foo"), new DerivedComparable("o"));
multimap.put(new DerivedComparable("bar"), new DerivedComparable("b"));
multimap.put(new DerivedComparable("bar"), new DerivedComparable("a"));
multimap.put(new DerivedComparable("bar"), new DerivedComparable("r"));
ASSERT.that(multimap.keySet()).hasContentsInOrder(
new DerivedComparable("bar"), new DerivedComparable("foo"));
ASSERT.that(multimap.values()).hasContentsInOrder(
new DerivedComparable("a"), new DerivedComparable("b"), new DerivedComparable("r"),
new DerivedComparable("f"), new DerivedComparable("o"));
assertEquals(Ordering.natural(), multimap.keyComparator());
assertEquals(Ordering.natural(), multimap.valueComparator());
SerializableTester.reserializeAndAssert(multimap);
}
@GwtIncompatible("SerializableTester")
public void testTreeMultimapNonGeneric() {
TreeMultimap<LegacyComparable, LegacyComparable> multimap
= TreeMultimap.create();
assertEquals(ImmutableMultimap.of(), multimap);
multimap.put(new LegacyComparable("foo"), new LegacyComparable("f"));
multimap.put(new LegacyComparable("foo"), new LegacyComparable("o"));
multimap.put(new LegacyComparable("foo"), new LegacyComparable("o"));
multimap.put(new LegacyComparable("bar"), new LegacyComparable("b"));
multimap.put(new LegacyComparable("bar"), new LegacyComparable("a"));
multimap.put(new LegacyComparable("bar"), new LegacyComparable("r"));
ASSERT.that(multimap.keySet()).hasContentsInOrder(
new LegacyComparable("bar"), new LegacyComparable("foo"));
ASSERT.that(multimap.values()).hasContentsInOrder(
new LegacyComparable("a"),
new LegacyComparable("b"),
new LegacyComparable("r"),
new LegacyComparable("f"),
new LegacyComparable("o"));
assertEquals(Ordering.natural(), multimap.keyComparator());
assertEquals(Ordering.natural(), multimap.valueComparator());
SerializableTester.reserializeAndAssert(multimap);
}
public void testTreeMultimapAsMapSorted() {
TreeMultimap<String, Integer> multimap = createPopulate();
SortedMap<String, Collection<Integer>> asMap = multimap.asMap();
assertEquals(Ordering.natural(), asMap.comparator());
assertEquals("foo", asMap.firstKey());
assertEquals("tree", asMap.lastKey());
Set<Integer> fooValues = ImmutableSet.of(1, 3, 7);
Set<Integer> googleValues = ImmutableSet.of(2, 6);
Set<Integer> treeValues = ImmutableSet.of(4, 0);
assertEquals(ImmutableMap.of("google", googleValues, "tree", treeValues),
asMap.tailMap("g"));
assertEquals(ImmutableMap.of("google", googleValues, "foo", fooValues),
asMap.headMap("h"));
assertEquals(ImmutableMap.of("google", googleValues),
asMap.subMap("g", "h"));
}
public void testTailSetClear() {
TreeMultimap<String, Integer> multimap = TreeMultimap.create();
multimap.put("a", 1);
multimap.put("a", 11);
multimap.put("b", 2);
multimap.put("c", 3);
multimap.put("d", 4);
multimap.put("e", 5);
multimap.put("e", 55);
multimap.keySet().tailSet("d").clear();
assertEquals(ImmutableSet.of("a", "b", "c"), multimap.keySet());
assertEquals(4, multimap.size());
assertEquals(4, multimap.values().size());
assertEquals(4, multimap.keys().size());
}
}
| |
/*L
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/stats-analysis/LICENSE.txt for details.
*/
/*
* Created on Jul 17, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package gov.nih.nci.system.dao;
import gov.nih.nci.system.dao.impl.orm.ORMConnection;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
/**
*
* @author Ekagra Software Technologies Ltd.
*/
public class WritableDAO {
static final Logger log = Logger.getLogger(WritableDAO.class.getName());
public Object createObject(Object obj) throws DAOException {
Session session = null;
Transaction transaction = null;
String objName = obj.getClass().getName();
try {
ORMConnection.getInstance();
session = ORMConnection.openSession(objName);
} catch (Exception ex) {
log.error("Could not obtain a session! Could not create " + objName);
throw new SessionException("Could not obtain a session! Could not create " + objName, ex);
}
if (session == null) {
log.error("Could not obtain a session");
throw new SessionException("Could not obtain a session");
}
try {
transaction = session.beginTransaction();
session.save(obj);
transaction.commit();
} catch (Exception ex) {
try {
transaction.rollback();
} catch (Exception ex3) {
log.error("Error while rolling back transaction: "
+ ex3.getMessage() + " for original Exception: "
+ ex.getMessage());
throw new RollbackException(
"Error while rolling back transaction", ex);
}
log.error("Error while creating object " + objName + ": " + ex.getMessage());
throw new CreateException("An error occured while creating object " + objName, ex);
} finally {
try {
session.close();
} catch (Exception ex2) {
log.error("Error while closing the Session: "
+ ex2.getMessage());
throw new SessionException("Error while closing the Session",
ex2);
}
}
log.debug("Successful in creating " + objName);
return obj;
}
public Object updateObject(Object obj) throws DAOException {
Session session = null;
Transaction transaction = null;
String objName = obj.getClass().getName();
try {
ORMConnection.getInstance();
session = ORMConnection.openSession(objName);
} catch (Exception ex) {
log.error("Could not obtain a session");
throw new SessionException(
"Could not obtain a session! Could not update " + objName, ex);
}
if (session == null) {
log.error("Could not obtain a session");
throw new SessionException(
"Could not obtain a session! Could not update " + objName);
}
try {
transaction = session.beginTransaction();
session.update(obj);
transaction.commit();
} catch (Exception ex) {
try {
transaction.rollback();
} catch (Exception ex3) {
log.error("Error while rolling back transaction: "
+ ex3.getMessage() + " for original Exception: "
+ ex.getMessage());
throw new RollbackException(
"Error while rolling back transaction: "
+ ex3.getMessage()
+ " for original Exception: " + ex.getMessage(),
ex3);
}
log.error("Error while updating " + objName);
throw new UpdateException("An error occured while updating " + objName, ex);
} finally {
try {
session.close();
} catch (Exception ex2) {
log.error("Error while closing the Session: "
+ ex2.getMessage());
throw new SessionException("Error while closing the Session",
ex2);
}
}
log.debug("Successful in updating " + objName);
return obj;
}
public void removeObject(Object obj) throws DAOException {
Session session = null;
Transaction transaction = null;
String objName = obj.getClass().getName();
try {
ORMConnection.getInstance();
session = ORMConnection.openSession(objName);
} catch (Exception ex) {
log.error("Could not obtain a session! Could not delete " + objName);
throw new SessionException(
"Could not obtain a session! Could not delete " + objName, ex);
}
if (session == null) {
log.error("Could not obtain a session! Could not delete " + objName);
throw new SessionException(
"Could not obtain a session! Could not delete " + objName);
}
try {
transaction = session.beginTransaction();
session.delete(obj);
transaction.commit();
} catch (Exception ex) {
try {
transaction.rollback();
} catch (Exception ex3) {
log.error("Error while rolling back transaction: "
+ ex3.getMessage());
throw new RollbackException(
"An error occured rolling back transaction while deleting " + objName, ex);
}
log.error("Error while deleting " + objName + ": " + ex.getMessage());
throw new DeleteException("An error occured while deleting " + objName, ex);
} finally {
try {
session.close();
} catch (Exception ex2) {
log.error("Error closing the session while deleting " + objName + ex2.getMessage());
throw new SessionException(
"Error while closing the Session while removing object " + objName, ex2);
}
}
log.debug("Successful in deleting " + objName);
}
public List getObjects(Object obj) throws DAOException {
Session session = null;
String objName = obj.getClass().getName();
log.debug("objName: " + objName);
try {
ORMConnection.getInstance();
session = ORMConnection.openSession(objName);
} catch (Exception ex) {
log.error("Could not obtain a session! Could not get " + objName + " objects");
throw new QueryException(
"Could not obtain a session! Could not get " + objName + " objects", ex);
}
if (session == null) {
log.error("Could not obtain a session! Could not get " + objName + " objects");
throw new QueryException(
"Could not obtain a session! Could not get " + objName + " objects");
}
List list = null;
try {
Criteria criteria = session.createCriteria(obj.getClass());
criteria.add(Example.create(obj));
list = criteria.list();
} catch (Exception ex) {
log.error("Error while getting objects: " + ex.getMessage());
throw new QueryException("An error occured while getting objects: "
+ ex.getMessage());
} finally {
try {
session.close();
} catch (Exception ex2) {
log.error("Error while closing the Session: "
+ ex2.getMessage());
throw new SessionException("Error while closing the Session",
ex2);
}
}
log.debug("Successful in getting " + objName + " objects");
return list;
}
}
| |
/*
* 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.das.integration.tests.globalpurging;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.api.CarbonAnalyticsAPI;
import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTable;
import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTableRecord;
import org.wso2.carbon.analytics.webservice.stub.beans.EventBean;
import org.wso2.carbon.analytics.webservice.stub.beans.RecordValueEntryBean;
import org.wso2.carbon.analytics.webservice.stub.beans.StreamDefAttributeBean;
import org.wso2.carbon.analytics.webservice.stub.beans.StreamDefinitionBean;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;
import org.wso2.das.integration.common.clients.AnalyticsWebServiceClient;
import org.wso2.das.integration.common.clients.EventStreamPersistenceClient;
import org.wso2.das.integration.common.utils.DASIntegrationTest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class GlobalPurgingTestCase extends DASIntegrationTest {
private static final String STREAM_VERSION_1 = "1.0.0";
public static final String SOMETABLE_PATTERN1_TABLE1 = "sometable.pattern1.table1";
public static final String SOMETABLE_PATTERN1_TABLE2 = "sometable.pattern1.table2";
public static final String PREFIX_TABLE_1 = "prefix_table1";
public static final String PREFIX_TABLE_2 = "prefix_table2";
public static final String DAS_PREFIX_TABLE_1 = "DAS_prefix_table1";
public static final String RANDOM_TABLE_1 = "random_table1";
public static final String RANDOM_TABLE_2 = "random_table2";
private AnalyticsWebServiceClient webServiceClient;
private EventStreamPersistenceClient persistenceClient;
private ServerConfigurationManager serverManager;
@BeforeClass(alwaysRun = true, dependsOnGroups = "wso2.das")
protected void init() throws Exception {
super.init();
String session = getSessionCookie();
webServiceClient = new AnalyticsWebServiceClient(backendURL, session);
persistenceClient = new EventStreamPersistenceClient(backendURL, session);
String apiConf =
new File(this.getClass().getClassLoader().
getResource("dasconfig" + File.separator + "api" + File.separator + "analytics-data-config.xml").toURI())
.getAbsolutePath();
AnalyticsDataAPI analyticsDataAPI = new CarbonAnalyticsAPI(apiConf);
}
@Test(groups = "wso2.das.purging", description = "Checking global data purging")
public void publishData() throws Exception {
StreamDefinitionBean patternDef1 = getEventStreamBeanTable(SOMETABLE_PATTERN1_TABLE1);
webServiceClient.addStreamDefinition(patternDef1);
AnalyticsTable patternTable1 = getAnalyticsTable(SOMETABLE_PATTERN1_TABLE1);
persistenceClient.addAnalyticsTable(patternTable1);
StreamDefinitionBean patternDef2 = getEventStreamBeanTable(SOMETABLE_PATTERN1_TABLE2);
webServiceClient.addStreamDefinition(patternDef2);
AnalyticsTable patternTable2 = getAnalyticsTable(SOMETABLE_PATTERN1_TABLE2);
persistenceClient.addAnalyticsTable(patternTable2);
StreamDefinitionBean prefixDef1 = getEventStreamBeanTable(PREFIX_TABLE_1);
webServiceClient.addStreamDefinition(prefixDef1);
AnalyticsTable prefixTable1 = getAnalyticsTable(PREFIX_TABLE_1);
persistenceClient.addAnalyticsTable(prefixTable1);
StreamDefinitionBean prefixDef2 = getEventStreamBeanTable(PREFIX_TABLE_2);
webServiceClient.addStreamDefinition(prefixDef2);
AnalyticsTable prefixTable2 = getAnalyticsTable(PREFIX_TABLE_2);
persistenceClient.addAnalyticsTable(prefixTable2);
StreamDefinitionBean dasPrefixDef1 = getEventStreamBeanTable(DAS_PREFIX_TABLE_1);
webServiceClient.addStreamDefinition(dasPrefixDef1);
AnalyticsTable dasPrefixTable1 = getAnalyticsTable(DAS_PREFIX_TABLE_1);
persistenceClient.addAnalyticsTable(dasPrefixTable1);
StreamDefinitionBean randomDef1 = getEventStreamBeanTable(RANDOM_TABLE_1);
webServiceClient.addStreamDefinition(randomDef1);
AnalyticsTable randomTable1 = getAnalyticsTable(RANDOM_TABLE_1);
persistenceClient.addAnalyticsTable(randomTable1);
StreamDefinitionBean randomDef2 = getEventStreamBeanTable(RANDOM_TABLE_2);
webServiceClient.addStreamDefinition(randomDef2);
AnalyticsTable randomTable2 = getAnalyticsTable(RANDOM_TABLE_2);
persistenceClient.addAnalyticsTable(randomTable2);
Thread.sleep(15000);
List<EventBean> eventBeans = getEventBeans(patternDef1);
for (EventBean eventBean : eventBeans) {
webServiceClient.publishEvent(eventBean);
}
eventBeans = getEventBeans(patternDef2);
for (EventBean eventBean : eventBeans) {
webServiceClient.publishEvent(eventBean);
}
eventBeans = getEventBeans(prefixDef1);
for (EventBean eventBean : eventBeans) {
webServiceClient.publishEvent(eventBean);
}
eventBeans = getEventBeans(prefixDef2);
for (EventBean eventBean : eventBeans) {
webServiceClient.publishEvent(eventBean);
}
eventBeans = getEventBeans(dasPrefixDef1);
for (EventBean eventBean : eventBeans) {
webServiceClient.publishEvent(eventBean);
}
eventBeans = getEventBeans(randomDef1);
for (EventBean eventBean : eventBeans) {
webServiceClient.publishEvent(eventBean);
}
eventBeans = getEventBeans(randomDef2);
for (EventBean eventBean : eventBeans) {
webServiceClient.publishEvent(eventBean);
}
Thread.sleep(2000);
Assert.assertEquals(webServiceClient.getByRange(SOMETABLE_PATTERN1_TABLE1.replace('.', '_'), 0, System.
currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
Assert.assertEquals(webServiceClient.getByRange(SOMETABLE_PATTERN1_TABLE2.replace('.', '_'), 0, System
.currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
Assert.assertEquals(webServiceClient.getByRange(PREFIX_TABLE_1.replace('.', '_'), 0, System.currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
Assert.assertEquals(webServiceClient.getByRange(PREFIX_TABLE_2.replace('.', '_'), 0, System.currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
Assert.assertEquals(webServiceClient.getByRange(DAS_PREFIX_TABLE_1.replace('.', '_'), 0, System.currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
Assert.assertEquals(webServiceClient.getByRange(RANDOM_TABLE_1.replace('.', '_'), 0, System.currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
Assert.assertEquals(webServiceClient.getByRange(RANDOM_TABLE_2.replace('.', '_'), 0, System.currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
String artifactsLocation = FrameworkPathUtil.getSystemResourceLocation() + File.separator + "gloablepurging" +
File.separator + "analytics-config.xml";
String dataserviceConfigLocation =
FrameworkPathUtil.getCarbonHome() + File.separator + "repository" + File.separator + "conf" + File
.separator + "analytics" + File.separator + "analytics-config.xml";
serverManager = new ServerConfigurationManager(dasServer);
File sourceFile = new File(artifactsLocation);
File targetFile = new File(dataserviceConfigLocation);
serverManager.applyConfigurationWithoutRestart(sourceFile, targetFile, true);
serverManager.restartGracefully();
Thread.sleep(150000);
webServiceClient = new AnalyticsWebServiceClient(backendURL, getSessionCookie());
Assert.assertEquals(webServiceClient.getByRange(SOMETABLE_PATTERN1_TABLE1.replace('.', '_'), 0, System
.currentTimeMillis(), 0, 100).length, 0, "Record not deleteing from " + SOMETABLE_PATTERN1_TABLE1);
Assert.assertEquals(webServiceClient.getByRange(SOMETABLE_PATTERN1_TABLE2.replace('.', '_'), 0, System
.currentTimeMillis(), 0, 100).length, 0, "Record not deleteing from " + SOMETABLE_PATTERN1_TABLE2);
Assert.assertEquals(webServiceClient.getByRange(PREFIX_TABLE_1.replace('.', '_'), 0, System.currentTimeMillis(), 0, 100).length, 0, "Record not deleteing from " + PREFIX_TABLE_1);
Assert.assertEquals(webServiceClient.getByRange(PREFIX_TABLE_2.replace('.', '_'), 0, System.currentTimeMillis(), 0, 100).length, 0, "Record not deleteing from " + PREFIX_TABLE_2);
Assert.assertEquals(webServiceClient.getByRange(DAS_PREFIX_TABLE_1.replace('.', '_'), 0, System
.currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
Assert.assertEquals(webServiceClient.getByRange(RANDOM_TABLE_1.replace('.', '_'), 0, System
.currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
Assert.assertEquals(webServiceClient.getByRange(RANDOM_TABLE_2.replace('.', '_'), 0, System
.currentTimeMillis(), 0, 100).length, 25, "Record count is incorrect");
}
private List<EventBean> getEventBeans(StreamDefinitionBean streamDefinitionBean) {
List<EventBean> eventBeans = new ArrayList<>(25);
for (int i = 0; i < 25; i++) {
EventBean eventBean = new EventBean();
eventBean.setStreamName(streamDefinitionBean.getName());
eventBean.setStreamVersion(STREAM_VERSION_1);
RecordValueEntryBean[] payloadData = new RecordValueEntryBean[2];
RecordValueEntryBean uuid = new RecordValueEntryBean();
uuid.setFieldName("uuid");
uuid.setType("LONG");
uuid.setLongValue(i);
payloadData[0] = uuid;
RecordValueEntryBean name = new RecordValueEntryBean();
name.setFieldName("name");
name.setType("STRING");
name.setStringValue(String.valueOf(i));
payloadData[1] = name;
eventBean.setPayloadData(payloadData);
eventBeans.add(eventBean);
}
return eventBeans;
}
@AfterTest(alwaysRun = true)
public void startRestoreAnalyticsConfigFile() throws Exception {
serverManager.restoreToLastConfiguration();
serverManager.restartGracefully();
}
private StreamDefinitionBean getEventStreamBeanTable(String tableName) {
StreamDefinitionBean definitionBean = new StreamDefinitionBean();
definitionBean.setName(tableName);
definitionBean.setVersion(STREAM_VERSION_1);
StreamDefAttributeBean[] attributeBeans = new StreamDefAttributeBean[2];
StreamDefAttributeBean uuid = new StreamDefAttributeBean();
uuid.setName("uuid");
uuid.setType("LONG");
attributeBeans[0] = uuid;
StreamDefAttributeBean name = new StreamDefAttributeBean();
name.setName("name");
name.setType("STRING");
attributeBeans[1] = name;
definitionBean.setPayloadData(attributeBeans);
return definitionBean;
}
private AnalyticsTable getAnalyticsTable(String tableName) {
AnalyticsTable table = new AnalyticsTable();
table.setPersist(true);
table.setTableName(tableName);
table.setStreamVersion(STREAM_VERSION_1);
AnalyticsTableRecord[] records = new AnalyticsTableRecord[2];
AnalyticsTableRecord uuid = new AnalyticsTableRecord();
uuid.setPersist(true);
uuid.setPrimaryKey(true);
uuid.setIndexed(true);
uuid.setColumnName("uuid");
uuid.setColumnType("LONG");
uuid.setScoreParam(false);
records[0] = uuid;
AnalyticsTableRecord name = new AnalyticsTableRecord();
name.setPersist(true);
name.setPrimaryKey(false);
name.setIndexed(false);
name.setColumnName("name");
name.setColumnType("STRING");
name.setScoreParam(false);
records[1] = name;
table.setAnalyticsTableRecords(records);
return table;
}
}
| |
/*
* Copyright 2010-2016 Rajendra Patil
*
* 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.googlecode.webutilities.common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static com.googlecode.webutilities.common.Constants.HTTP_CONTENT_TYPE_HEADER;
/**
* Common Simple Servlet Response Wrapper using WebUtilitiesResponseOutputStream
*
* @author rpatil
* @version 1.0
* @see WebUtilitiesResponseOutputStream
*/
public class WebUtilitiesResponseWrapper extends HttpServletResponseWrapper {
public static final Logger LOGGER = LoggerFactory
.getLogger(WebUtilitiesResponseWrapper.class
.getName());
private WebUtilitiesResponseOutputStream stream;
private Map<String, Serializable> headers = new HashMap<>();
private Set<Cookie> cookies = new HashSet<>();
private String contentType;
private int status = 0;
private boolean getWriterCalled = false;
private boolean getStreamCalled = false;
private PrintWriter printWriter;
@Override
public void addCookie(Cookie cookie) {
super.addCookie(cookie);
cookies.add(cookie);
}
@Override
public void setStatus(int sc) {
if (this.status != 0) return;
super.setStatus(sc);
this.status = sc;
}
@Override
public void sendError(int sc) throws IOException {
if (this.status != 0) return;
super.sendError(sc);
this.status = sc;
}
@Override
public void sendError(int sc, String msg) throws IOException {
if (this.status != 0) return;
super.sendError(sc, msg);
this.status = sc;
}
@Override
public void addDateHeader(String name, long date) {
super.addDateHeader(name, date);
headers.put(name, date);
}
@Override
public void addHeader(String name, String value) {
if (HTTP_CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) {
this.setContentType(value);
} else {
super.addHeader(name, value);
headers.put(name, value);
}
}
@Override
public void addIntHeader(String name, int value) {
super.addIntHeader(name, value);
headers.put(name, value);
}
@Override
public void setDateHeader(String name, long date) {
super.setDateHeader(name, date);
headers.put(name, date);
}
@Override
public void setHeader(String name, String value) {
if (HTTP_CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) {
this.setContentType(value);
} else {
super.setHeader(name, value);
headers.put(name, value);
}
}
@Override
public void setIntHeader(String name, int value) {
super.setIntHeader(name, value);
headers.put(name, value);
}
@Override
public String getContentType() {
return contentType;
}
@Override
public void setContentType(String type) {
super.setContentType(type);
this.contentType = type;
}
@Override
public boolean containsHeader(String name) {
return headers.containsKey(name);
}
public Map<String, Serializable> getHeaders() {
return headers;
}
public Set<Cookie> getCookies() {
return cookies;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (getWriterCalled) {
throw new IllegalStateException("getWriter already called.");
}
getStreamCalled = true;
return this.stream;
}
@Override
public PrintWriter getWriter() throws IOException {
if (getStreamCalled) {
throw new IllegalStateException("getStream already called.");
}
getWriterCalled = true;
if (printWriter == null) {
printWriter = new PrintWriter(stream);
}
return printWriter;
}
public int getStatus() {
return status;
}
private void flushWriter() {
if (getWriterCalled && printWriter != null) {
printWriter.flush();
}
}
@Override
public void flushBuffer() throws IOException {
flushWriter(); // make sure nothing is buffered in the writer, if applicable
if (stream != null) {
stream.flush();
}
}
@Override
public void reset() {
flushWriter(); // make sure nothing is buffered in the writer, if applicable
if (stream != null) {
stream.reset();
}
//getResponse().reset();
}
@Override
public void resetBuffer() {
flushWriter(); // make sure nothing is buffered in the writer, if applicable
if (stream != null) {
stream.reset();
}
//getResponse().resetBuffer();
}
public String getContents() {
return new String(getBytes());
}
public byte[] getBytes() {
return stream.getByteArrayOutputStream().toByteArray();
}
public WebUtilitiesResponseWrapper(HttpServletResponse response) {
super(response);
stream = new WebUtilitiesResponseOutputStream(this);
}
public void fill(HttpServletResponse response) throws IOException {
response.setCharacterEncoding(this.getCharacterEncoding());
response.setContentType(this.getContentType());
this.getCookies().forEach(response::addCookie);
for (String headerName : this.getHeaders().keySet()) {
Object value = this.getHeaders().get(headerName);
if (value instanceof Long) {
response.setDateHeader(headerName, ((Long) value));
} else if (value instanceof Integer) {
response.setIntHeader(headerName, ((Integer) value));
} else {
response.setHeader(headerName, value.toString());
}
}
if (this.getStatus() > 0)
response.setStatus(this.getStatus());
this.flushWriter();
try {
response.getOutputStream().write(this.getBytes());
response.getOutputStream().close();
} catch (RuntimeException ex) {
try {
response.getWriter().write(this.getContents());
response.getWriter().close();
} catch (Exception ex1) {
LOGGER.error(ex1.getMessage(), ex1);
}
// ex.printStackTrace();
}
if (response instanceof WebUtilitiesResponseWrapper) {
((WebUtilitiesResponseWrapper) response).fill((HttpServletResponse) ((WebUtilitiesResponseWrapper) response).getResponse());
}
}
}
| |
/************************************************************************************************
* _________ _ ____ _ __ __ _ _ _ _ _ ___
* |__ / ___|__ _ ___| |__ / ___|_ _(_)_ __ __ \ \ / /_ _| | | ___| |_| | | |_ _|
* / / | / _` / __| '_ \\___ \ \ /\ / / | '_ \ / _` \ \ /\ / / _` | | |/ _ \ __| | | || |
* / /| |__| (_| \__ \ | | |___) \ V V /| | | | | (_| |\ V V / (_| | | | __/ |_| |_| || |
* /____\____\__,_|___/_| |_|____/ \_/\_/ |_|_| |_|\__, | \_/\_/ \__,_|_|_|\___|\__|\___/|___|
* |___/
*
* Copyright (c) 2016 Ivan Vaklinov <ivan@vaklinov.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
**********************************************************************************/
package com.vaklinov.zcashui;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.plaf.FontUIResource;
import com.vaklinov.zcashui.OSUtil.OS_TYPE;
import com.vaklinov.zcashui.ZCashClientCaller.NetworkAndBlockchainInfo;
import com.vaklinov.zcashui.ZCashClientCaller.WalletCallException;
import com.vaklinov.zcashui.ZCashInstallationObserver.DAEMON_STATUS;
import com.vaklinov.zcashui.ZCashInstallationObserver.DaemonInfo;
import com.vaklinov.zcashui.ZCashInstallationObserver.InstallationDetectionException;
/**
* Main ZCash Window.
*
* @author Ivan Vaklinov <ivan@vaklinov.com>
*/
public class ZCashUI
extends JFrame
{
private ZCashInstallationObserver installationObserver;
private ZCashClientCaller clientCaller;
private StatusUpdateErrorReporter errorReporter;
private WalletOperations walletOps;
private JMenuItem menuItemExit;
private JMenuItem menuItemAbout;
private JMenuItem menuItemEncrypt;
private JMenuItem menuItemBackup;
private JMenuItem menuItemExportKeys;
private JMenuItem menuItemImportKeys;
private JMenuItem menuItemShowPrivateKey;
private JMenuItem menuItemImportOnePrivateKey;
private JMenuItem menuItemAddressBook;
private DashboardPanel dashboard;
private AddressesPanel addresses;
private SendCashPanel sendPanel;
JTabbedPane tabs;
public ZCashUI(StartupProgressDialog progressDialog)
throws IOException, InterruptedException, WalletCallException
{
super("ZClassic Swing Wallet UI 0.62.2 (beta)");
if (progressDialog != null)
{
progressDialog.setProgressText("Starting GUI wallet...");
}
ClassLoader cl = this.getClass().getClassLoader();
this.setIconImage(new ImageIcon(cl.getResource("images/Z-yellow.orange-logo.png")).getImage());
Container contentPane = this.getContentPane();
errorReporter = new StatusUpdateErrorReporter(this);
installationObserver = new ZCashInstallationObserver(OSUtil.getProgramDirectory());
clientCaller = new ZCashClientCaller(OSUtil.getProgramDirectory());
// Build content
tabs = new JTabbedPane();
Font oldTabFont = tabs.getFont();
Font newTabFont = new Font(oldTabFont.getName(), Font.BOLD | Font.ITALIC, oldTabFont.getSize() * 57 / 50);
tabs.setFont(newTabFont);
tabs.addTab("Overview ",
new ImageIcon(cl.getResource("images/overview.png")),
dashboard = new DashboardPanel(this, installationObserver, clientCaller, errorReporter));
tabs.addTab("Own addresses ",
new ImageIcon(cl.getResource("images/address-book.png")),
addresses = new AddressesPanel(clientCaller, errorReporter));
tabs.addTab("Send cash ",
new ImageIcon(cl.getResource("images/send.png")),
sendPanel = new SendCashPanel(clientCaller, errorReporter));
contentPane.add(tabs);
this.walletOps = new WalletOperations(
this, tabs, dashboard, addresses, sendPanel, installationObserver, clientCaller, errorReporter);
this.setSize(new Dimension(870, 427));
// Build menu
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("Main");
file.setMnemonic(KeyEvent.VK_M);
int accelaratorKeyMask = Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask();
file.add(menuItemAbout = new JMenuItem("About...", KeyEvent.VK_T));
menuItemAbout.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, accelaratorKeyMask));
file.addSeparator();
file.add(menuItemExit = new JMenuItem("Quit", KeyEvent.VK_Q));
menuItemExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, accelaratorKeyMask));
mb.add(file);
JMenu wallet = new JMenu("Wallet");
wallet.setMnemonic(KeyEvent.VK_W);
wallet.add(menuItemBackup = new JMenuItem("Backup...", KeyEvent.VK_B));
menuItemBackup.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, accelaratorKeyMask));
wallet.add(menuItemEncrypt = new JMenuItem("Encrypt...", KeyEvent.VK_E));
menuItemEncrypt.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, accelaratorKeyMask));
wallet.add(menuItemExportKeys = new JMenuItem("Export private keys...", KeyEvent.VK_K));
menuItemExportKeys.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, accelaratorKeyMask));
wallet.add(menuItemImportKeys = new JMenuItem("Import private keys...", KeyEvent.VK_I));
menuItemImportKeys.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, accelaratorKeyMask));
wallet.add(menuItemShowPrivateKey = new JMenuItem("Show private key...", KeyEvent.VK_P));
menuItemShowPrivateKey.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, accelaratorKeyMask));
wallet.add(menuItemImportOnePrivateKey = new JMenuItem("Import one private key...", KeyEvent.VK_N));
menuItemImportOnePrivateKey.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, accelaratorKeyMask));
mb.add(wallet);
JMenu extras = new JMenu("Extras");
extras.setMnemonic(KeyEvent.VK_R);
extras.add(menuItemAddressBook = new JMenuItem("Address book...", KeyEvent.VK_D));
menuItemAddressBook.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, accelaratorKeyMask));
mb.add(extras);
// TODO: Temporarily disable encryption until further notice - Oct 24 2016
menuItemEncrypt.setEnabled(false);
this.setJMenuBar(mb);
// Add listeners etc.
menuItemExit.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
ZCashUI.this.exitProgram();
}
}
);
menuItemAbout.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
AboutDialog ad = new AboutDialog(ZCashUI.this);
ad.setVisible(true);
} catch (UnsupportedEncodingException uee)
{
uee.printStackTrace();
ZCashUI.this.errorReporter.reportError(uee);
}
}
}
);
menuItemBackup.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
ZCashUI.this.walletOps.backupWallet();
}
}
);
menuItemEncrypt.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
ZCashUI.this.walletOps.encryptWallet();
}
}
);
menuItemExportKeys.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
ZCashUI.this.walletOps.exportWalletPrivateKeys();
}
}
);
menuItemImportKeys.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
ZCashUI.this.walletOps.importWalletPrivateKeys();
}
}
);
menuItemShowPrivateKey.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
ZCashUI.this.walletOps.showPrivateKey();
}
}
);
menuItemImportOnePrivateKey.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
ZCashUI.this.walletOps.importSinglePrivateKey();
}
}
);
menuItemAddressBook.addActionListener(
new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
ZCashUI.this.walletOps.showAddressBook();
}
}
);
// Close operation
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
ZCashUI.this.exitProgram();
}
});
// Show initial message
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
String userDir = OSUtil.getSettingsDirectory();
File warningFlagFile = new File(userDir + File.separator + "initialInfoShown.flag");
if (warningFlagFile.exists())
{
return;
} else
{
warningFlagFile.createNewFile();
}
} catch (IOException ioe)
{
/* TODO: report exceptions to the user */
ioe.printStackTrace();
}
JOptionPane.showMessageDialog(
ZCashUI.this.getRootPane().getParent(),
"The ZClassic GUI Wallet is currently considered experimental. Use of this software\n" +
"comes at your own risk! Be sure to read the list of known issues and limitations\n" +
"at this page: https://github.com/vaklinov/zclassic-swing-wallet-ui\n\n" +
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n" +
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n" +
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n" +
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n" +
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n" +
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n" +
"THE SOFTWARE.\n\n" +
"(This message will be shown only once)",
"Disclaimer", JOptionPane.INFORMATION_MESSAGE);
}
});
// Finally dispose of the progress dialog
if (progressDialog != null)
{
progressDialog.doDispose();
}
}
public void exitProgram()
{
System.out.println("Exiting ...");
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
this.dashboard.stopThreadsAndTimers();
this.addresses.stopThreadsAndTimers();
this.sendPanel.stopThreadsAndTimers();
// Integer blockchainProgress = this.dashboard.getBlockchainPercentage();
//
// if ((blockchainProgress != null) && (blockchainProgress >= 100))
// {
// this.dashboard.waitForEndOfThreads(3000);
// this.addresses.waitForEndOfThreads(3000);
// this.sendPanel.waitForEndOfThreads(3000);
// }
ZCashUI.this.setVisible(false);
ZCashUI.this.dispose();
System.exit(0);
}
public static void main(String argv[])
throws IOException
{
try
{
OS_TYPE os = OSUtil.getOSType();
System.out.println("Starting ZClassic Swing Wallet ...");
System.out.println("OS: " + System.getProperty("os.name") + " = " + os);
System.out.println("Current directory: " + new File(".").getCanonicalPath());
System.out.println("Class path: " + System.getProperty("java.class.path"));
System.out.println("Environment PATH: " + System.getenv("PATH"));
// Look and feel settings - for now a custom OS-look and feel is set for Windows,
// Mac OS will follow later.
if (os == OS_TYPE.WINDOWS)
{
// Custom Windows L&F and font settings
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
// This font looks good but on Windows 7 it misses some chars like the stars...
//FontUIResource font = new FontUIResource("Lucida Sans Unicode", Font.PLAIN, 11);
//UIManager.put("Table.font", font);
} else
{
for (LookAndFeelInfo ui : UIManager.getInstalledLookAndFeels())
{
System.out.println("Available look and feel: " + ui.getName() + " " + ui.getClassName());
if (ui.getName().equals("Nimbus"))
{
UIManager.setLookAndFeel(ui.getClassName());
break;
};
}
}
// If zcashd is currently not running, do a startup of the daemon as a child process
// It may be started but not ready - then also show dialog
ZCashInstallationObserver initialInstallationObserver =
new ZCashInstallationObserver(OSUtil.getProgramDirectory());
DaemonInfo zcashdInfo = initialInstallationObserver.getDaemonInfo();
initialInstallationObserver = null;
ZCashClientCaller initialClientCaller = new ZCashClientCaller(OSUtil.getProgramDirectory());
boolean daemonStartInProgress = false;
try
{
if (zcashdInfo.status == DAEMON_STATUS.RUNNING)
{
NetworkAndBlockchainInfo info = initialClientCaller.getNetworkAndBlockchainInfo();
// If more than 20 minutes behind in the blockchain - startup in progress
if ((System.currentTimeMillis() - info.lastBlockDate.getTime()) > (20 * 60 * 1000))
{
System.out.println("Current blockchain synchronization date is" +
new Date(info.lastBlockDate.getTime()));
daemonStartInProgress = true;
}
}
} catch (WalletCallException wce)
{
if ((wce.getMessage().indexOf("{\"code\":-28") != -1) || // Started but not ready
(wce.getMessage().indexOf("error code: -28") != -1))
{
System.out.println("zcashd is currently starting...");
daemonStartInProgress = true;
}
}
StartupProgressDialog startupBar = null;
if ((zcashdInfo.status != DAEMON_STATUS.RUNNING) || (daemonStartInProgress))
{
System.out.println(
"zcashd is not runing at the moment or has not started/synchronized 100% - showing splash...");
startupBar = new StartupProgressDialog(initialClientCaller);
startupBar.setVisible(true);
startupBar.waitForStartup();
}
initialClientCaller = null;
// Main GUI is created here
ZCashUI ui = new ZCashUI(startupBar);
ui.setVisible(true);
} catch (InstallationDetectionException ide)
{
ide.printStackTrace();
JOptionPane.showMessageDialog(
null,
"This program was started in directory: " + OSUtil.getProgramDirectory() + "\n" +
ide.getMessage() + "\n" +
"See the console output for more detailed error information!",
"Installation error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
} catch (WalletCallException wce)
{
wce.printStackTrace();
if ((wce.getMessage().indexOf("{\"code\":-28,\"message\"") != -1) ||
(wce.getMessage().indexOf("error code: -28") != -1))
{
JOptionPane.showMessageDialog(
null,
"It appears that zcashd has been started but is not ready to accept wallet\n" +
"connections. It is still loading the wallet and blockchain. Please try to \n" +
"start the GUI wallet later...",
"Wallet communication error",
JOptionPane.ERROR_MESSAGE);
} else
{
JOptionPane.showMessageDialog(
null,
"There was a problem communicating with the ZClassic daemon/wallet. \n" +
"Please ensure that the ZClassic server zcashd is started (e.g. via \n" +
"command \"zcashd --daemon\"). Error message is: \n" +
wce.getMessage() +
"See the console output for more detailed error information!",
"Wallet communication error",
JOptionPane.ERROR_MESSAGE);
}
System.exit(2);
} catch (Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(
null,
"A general unexpected critical error has occurred: \n" + e.getMessage() + "\n" +
"See the console output for more detailed error information!",
"Error",
JOptionPane.ERROR_MESSAGE);
System.exit(3);
}
}
}
| |
/*
* Copyright 2014 Alexander Oprisnik
*
* 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.oprisnik.semdroid.service;
import android.app.IntentService;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import com.oprisnik.semdroid.BuildConfig;
import com.oprisnik.semdroid.SemdroidAnalyzer;
import com.oprisnik.semdroid.analysis.AnalysisProgressListener;
import com.oprisnik.semdroid.analysis.results.SemdroidReport;
import com.oprisnik.semdroid.analysis.results.lite.LiteSemdroidReport;
import com.oprisnik.semdroid.permissions.AndroidPermissionMapFactory;
import com.oprisnik.semdroid.permissions.PermissionMapFactory;
import com.oprisnik.semdroid.plugins.PluginCardEntry;
import com.oprisnik.semdroid.plugins.PluginCardManager;
import com.oprisnik.semdroid.util.AndroidUtils;
import com.oprisnik.semdroid.utils.FileUtils;
import java.io.File;
import java.util.Arrays;
public class AnalysisIntentService extends IntentService {
public static final String ACTION_ANALYSIS_FINISHED = "com.oprisnik.semdroid.ANALYSIS_FINISHED";
public static final String ACTION_ANALYSIS_STATUS_UPDATE = "com.oprisnik.semdroid.ANALYSIS_STATUS_UPDATE";
public static final String PERMISSION_ACCESS_ANALYSIS_RESULTS = "com.oprisnik.semdroid.ACCESS_ANALYSIS_RESULTS";
public static final String KEY_PACKAGE_NAME = "package";
public static final String KEY_RESULTS_KEY = "results-key";
public static final String KEY_PLUGINS = "plugins";
public static final String KEY_ANALYSIS_STATUS = "status";
public static final String KEY_ANALYSIS_STATUS_PERCENTAGE = "percentage";
private static final String TAG = "AnalysisIntentService";
private SemdroidAnalyzer mSemdroid = null;
private boolean mFactorySet = false;
public AnalysisIntentService(String name) {
super(name);
}
public AnalysisIntentService() {
super(TAG);
}
public static String getResultsKey(String packageName) {
return packageName + ".sr";
}
public static String getResultsKey(String packageName, String[] plugins) {
if (plugins == null || plugins.length <= 0) {
return getResultsKey(packageName);
}
return packageName + "-" + Arrays.toString(plugins) + ".sr";
}
protected SemdroidAnalyzer createInstance() {
if (!mFactorySet) {
PermissionMapFactory.setFactory(new AndroidPermissionMapFactory(getApplicationContext()));
mFactorySet = true;
}
SemdroidAnalyzer semdroid = new SemdroidAnalyzer();
semdroid.init(); // use default values
// TODO: maybe init with semdroid.xml instead of using default values
return semdroid;
}
protected SemdroidAnalyzer getAnalyzer() {
if (mSemdroid != null) {
return mSemdroid; // already initialized
}
mSemdroid = createInstance();
for (PluginCardEntry e : PluginCardManager.DEFAULT_PLUGINS.getPlugins()) {
try {
if (e.isClassOnly()) {
mSemdroid.addAnalysisPlugin(e.getPluginClass());
} else {
mSemdroid.addAnalysisPlugin(e.getConfig());
}
} catch (Exception ex) {
Log.e(TAG, "Could not load plugin " +
e.getName(getApplicationContext()) +
" " + ex.getMessage());
}
}
return mSemdroid;
}
protected SemdroidAnalyzer getAnalyzer(String[] plugins) {
SemdroidAnalyzer semdroid = createInstance();
for (String s : plugins) {
try {
try {
semdroid.addAnalysisPlugin(s);
} catch (Exception e) {
semdroid.addAnalysisPluginFromClassName(s);
}
} catch (Exception ex) {
Log.e(TAG, "Could not load plugin " +
s + " " + ex.getMessage());
}
}
return semdroid;
}
protected SemdroidAnalyzer getSemdroid(final boolean useAllPlugins, final String[] plugins) {
// Starting with ART, the stack is big enough to load all plugins
// (ObjectInputStream for Semantic Pattern Network etc.)
// Dalvik needs bigger stack
// https://developer.android.com/guide/practices/verifying-apps-art.html#Stack_Size
// or we optimize the Semantic Pattern Framework:
// at.tuflowgraphy.semanticapps.dalvikcode.DalvikBaseAnalyzer#loadNet
if (AndroidUtils.hasAtLeastArtRuntime()) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Device uses ART runtime -> adding plugins directly");
}
return useAllPlugins ? getAnalyzer() : getAnalyzer(plugins);
} else {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Device does not use ART runtime -> adding plugins via thread");
}
try {
ThreadGroup group = new ThreadGroup("SemdroidPlugins");
SemdroidAnalyzerLoaderRunnable runnable =
new SemdroidAnalyzerLoaderRunnable(useAllPlugins, plugins);
Thread thread = new Thread(group, runnable, "PluginLoader", 2000000);
thread.start();
if (thread.isAlive()) {
thread.join();
}
return runnable.getNewAnalyzer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
final String packageName = intent.getStringExtra(KEY_PACKAGE_NAME);
final String[] plugins = intent.getStringArrayExtra(KEY_PLUGINS);
final boolean useAllPlugins = plugins == null;
if (BuildConfig.DEBUG) {
Log.d(TAG, "Got intent for package: " + packageName);
}
String cacheFileName = useAllPlugins ? getResultsKey(packageName) :
getResultsKey(packageName, plugins);
try {
File resultFile = new File(getExternalCacheDir(), cacheFileName);
if (!resultFile.exists()) {
PackageManager pm = getPackageManager();
ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
long start = System.currentTimeMillis();
if (BuildConfig.DEBUG) {
Log.d(TAG, "ApplicationInfo.publicSourceDir: " + applicationInfo.publicSourceDir);
}
SemdroidAnalyzer semdroid = getSemdroid(useAllPlugins, plugins);
BroadcastAnalysisProgressListener listener = new BroadcastAnalysisProgressListener(packageName);
// register listener
semdroid.registerProgressListener(listener);
// analyze app
SemdroidReport report = semdroid.analyze(new File(applicationInfo.publicSourceDir));
LiteSemdroidReport results = LiteSemdroidReport.fromTestSuiteReport(report);
// unregister listener since the analysis is done
semdroid.unregisterProgressListener(listener);
if (BuildConfig.DEBUG) {
Log.d(TAG, "Done. " + packageName + " Time: "
+ (System.currentTimeMillis() - start));
}
// we write the object to the result file - even if it already exists
// since we could have newer results
FileUtils.writeObjectToZipFile(results, resultFile);
}
Intent broadcastIntent = new Intent(ACTION_ANALYSIS_FINISHED)
.putExtra(KEY_PACKAGE_NAME, packageName)
.putExtra(KEY_RESULTS_KEY, resultFile.getAbsolutePath());
sendOrderedBroadcast(broadcastIntent, PERMISSION_ACCESS_ANALYSIS_RESULTS);
} catch (Exception e) {
if (e.getMessage() != null) {
Log.e(TAG, e.getMessage());
}
e.printStackTrace();
}
}
protected class BroadcastAnalysisProgressListener implements AnalysisProgressListener {
private String mPackageName;
public BroadcastAnalysisProgressListener(String packageName) {
mPackageName = packageName;
}
@Override
public void onStatusUpdated(int status, int percentageCompleted) {
Intent intent = new Intent(ACTION_ANALYSIS_STATUS_UPDATE)
.putExtra(KEY_PACKAGE_NAME, mPackageName)
.putExtra(KEY_ANALYSIS_STATUS, status)
.putExtra(KEY_ANALYSIS_STATUS_PERCENTAGE, percentageCompleted);
sendOrderedBroadcast(intent, PERMISSION_ACCESS_ANALYSIS_RESULTS);
}
}
protected class SemdroidAnalyzerLoaderRunnable implements Runnable {
private boolean mUseAllPlugins;
private String[] mPlugins;
private SemdroidAnalyzer newAnalyzer = null;
public SemdroidAnalyzerLoaderRunnable(boolean useAllPlugins, String[] plugins) {
mUseAllPlugins = useAllPlugins;
mPlugins = plugins;
}
@Override
public void run() {
newAnalyzer = mUseAllPlugins ? getAnalyzer() : getAnalyzer(mPlugins);
}
public SemdroidAnalyzer getNewAnalyzer() {
return newAnalyzer;
}
}
}
| |
/*
* 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.fluo.core.impl;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Map.Entry;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.curator.framework.CuratorFramework;
import org.apache.fluo.accumulo.util.AccumuloProps;
import org.apache.fluo.accumulo.util.ZookeeperPath;
import org.apache.fluo.api.config.FluoConfiguration;
import org.apache.fluo.api.config.SimpleConfiguration;
import org.apache.fluo.api.metrics.MetricsReporter;
import org.apache.fluo.core.client.FluoAdminImpl;
import org.apache.fluo.core.metrics.MetricNames;
import org.apache.fluo.core.metrics.MetricsReporterImpl;
import org.apache.fluo.core.observer.ObserverUtil;
import org.apache.fluo.core.observer.RegisteredObservers;
import org.apache.fluo.core.util.AccumuloUtil;
import org.apache.fluo.core.util.CuratorUtil;
/**
* Holds common environment configuration and shared resources
*/
public class Environment implements AutoCloseable {
private String table;
private Authorizations auths = new Authorizations();
private String accumuloInstance;
private RegisteredObservers observers;
private AccumuloClient client;
private String accumuloInstanceID;
private String fluoApplicationID;
private FluoConfiguration config;
private SharedResources resources;
private MetricNames metricNames;
private SimpleConfiguration appConfig;
private String metricsReporterID;
private void ensureDeletesAreDisabled() {
String value = null;
Iterable<Entry<String, String>> props;
try {
props = client.tableOperations().getProperties(table);
} catch (AccumuloException | TableNotFoundException e) {
throw new IllegalStateException(e);
}
for (Entry<String, String> entry : props) {
if (entry.getKey().equals(AccumuloProps.TABLE_DELETE_BEHAVIOR)) {
value = entry.getValue();
}
}
Preconditions.checkState(AccumuloProps.TABLE_DELETE_BEHAVIOR_VALUE.equals(value),
"The Accumulo table %s is not configured correctly. Please set %s=%s for this table in Accumulo.",
table, AccumuloProps.TABLE_DELETE_BEHAVIOR, AccumuloProps.TABLE_DELETE_BEHAVIOR_VALUE);
}
/**
* Constructs an environment from given FluoConfiguration
*
* @param configuration Configuration used to configure environment
*/
public Environment(FluoConfiguration configuration) {
config = configuration;
client = AccumuloUtil.getClient(config);
readZookeeperConfig();
ensureDeletesAreDisabled();
String instanceName = client.properties().getProperty(AccumuloProps.CLIENT_INSTANCE_NAME);
if (!instanceName.equals(accumuloInstance)) {
throw new IllegalArgumentException(
"unexpected accumulo instance name " + instanceName + " != " + accumuloInstance);
}
if (!client.instanceOperations().getInstanceID().equals(accumuloInstanceID)) {
throw new IllegalArgumentException("unexpected accumulo instance id "
+ client.instanceOperations().getInstanceID() + " != " + accumuloInstanceID);
}
try {
resources = new SharedResources(this);
} catch (TableNotFoundException e1) {
throw new IllegalStateException(e1);
}
}
/**
* Constructs an environment from another environment
*
* @param env Environment
*/
@VisibleForTesting
public Environment(Environment env) throws Exception {
this.table = env.table;
this.auths = env.auths;
this.accumuloInstance = env.accumuloInstance;
this.observers = env.observers;
this.client = env.client;
this.accumuloInstanceID = env.accumuloInstanceID;
this.fluoApplicationID = env.fluoApplicationID;
this.config = env.config;
this.resources = new SharedResources(this);
}
/**
* Read configuration from zookeeper
*/
private void readZookeeperConfig() {
try (CuratorFramework curator = CuratorUtil.newAppCurator(config)) {
curator.start();
accumuloInstance =
new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_NAME),
StandardCharsets.UTF_8);
accumuloInstanceID =
new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_INSTANCE_ID),
StandardCharsets.UTF_8);
fluoApplicationID =
new String(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID),
StandardCharsets.UTF_8);
table = new String(curator.getData().forPath(ZookeeperPath.CONFIG_ACCUMULO_TABLE),
StandardCharsets.UTF_8);
observers = ObserverUtil.load(curator);
config = FluoAdminImpl.mergeZookeeperConfig(config);
// make sure not to include config passed to env, only want config from zookeeper
appConfig = config.getAppConfiguration();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public void setAuthorizations(Authorizations auths) {
this.auths = auths;
// TODO the following is a big hack, this method is currently not exposed in API
resources.close();
try {
this.resources = new SharedResources(this);
} catch (TableNotFoundException e) {
throw new RuntimeException(e);
}
}
public Authorizations getAuthorizations() {
return auths;
}
public String getAccumuloInstance() {
return accumuloInstance;
}
public String getAccumuloInstanceID() {
return accumuloInstanceID;
}
public String getFluoApplicationID() {
return fluoApplicationID;
}
public RegisteredObservers getConfiguredObservers() {
return observers;
}
public String getTable() {
return table;
}
public AccumuloClient getAccumuloClient() {
return client;
}
public SharedResources getSharedResources() {
return resources;
}
public FluoConfiguration getConfiguration() {
return config;
}
public synchronized String getMetricsReporterID() {
if (metricsReporterID == null) {
String mid = System.getProperty(MetricNames.METRICS_REPORTER_ID_PROP);
if (mid == null) {
try {
String hostname = InetAddress.getLocalHost().getHostName();
int idx = hostname.indexOf('.');
if (idx > 0) {
hostname = hostname.substring(0, idx);
}
mid = hostname + "_" + getSharedResources().getTransactorID();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
metricsReporterID = mid.replace('.', '_');
}
return metricsReporterID;
}
public String getMetricsAppName() {
return config.getApplicationName().replace('.', '_');
}
public synchronized MetricNames getMetricNames() {
if (metricNames == null) {
metricNames = new MetricNames(getMetricsReporterID(), getMetricsAppName());
}
return metricNames;
}
public MetricsReporter getMetricsReporter() {
return new MetricsReporterImpl(getConfiguration(), getSharedResources().getMetricRegistry(),
getMetricsReporterID());
}
public SimpleConfiguration getAppConfiguration() {
// TODO create immutable wrapper
return new SimpleConfiguration(appConfig);
}
@Override
public void close() {
resources.close();
client.close();
}
}
| |
package com.leonardobishop.quests.commands;
import com.leonardobishop.quests.Quests;
import com.leonardobishop.quests.QuestsConfigLoader;
import com.leonardobishop.quests.api.enums.QuestStartResult;
import com.leonardobishop.quests.obj.Messages;
import com.leonardobishop.quests.obj.Options;
import com.leonardobishop.quests.player.QPlayer;
import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile;
import com.leonardobishop.quests.quests.Category;
import com.leonardobishop.quests.quests.Quest;
import com.leonardobishop.quests.quests.tasktypes.TaskType;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Map;
import java.util.UUID;
public class CommandQuests implements CommandExecutor {
private final Quests plugin;
public CommandQuests(Quests plugin) {
this.plugin = plugin;
}
@SuppressWarnings("deprecation")
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (plugin.isBrokenConfig() &&
!(args.length >= 2 &&
(args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("admin")) &&
args[1].equalsIgnoreCase("reload"))) {
sender.sendMessage(ChatColor.RED + "The main config must be in tact before quests can be used. Quests has failed to load the following files:");
for (Map.Entry<String, QuestsConfigLoader.ConfigLoadError> entry : plugin.getQuestsConfigLoader().getBrokenFiles().entrySet()) {
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + entry.getKey() + ": " + ChatColor.GRAY + entry.getValue().getMessage());
}
return true;
}
if (args.length >= 1 && args[0].equalsIgnoreCase("help")) {
showHelp(sender);
return true;
}
if (args.length == 0 && sender instanceof Player) {
Player player = (Player) sender;
QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId());
qPlayer.openQuests();
return true;
} else if (args.length >= 1) {
if ((args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("admin")) && sender.hasPermission("quests.admin")) {
if (args.length == 2) {
if (args[1].equalsIgnoreCase("opengui")) {
showAdminHelp(sender, "opengui");
return true;
} else if (args[1].equalsIgnoreCase("moddata")) {
showAdminHelp(sender, "moddata");
return true;
} else if (args[1].equalsIgnoreCase("reload")) {
plugin.reloadConfig();
plugin.reloadQuests();
if (!plugin.getQuestsConfigLoader().getBrokenFiles().isEmpty()) {
sender.sendMessage(ChatColor.RED + "Quests has failed to load the following files:");
for (Map.Entry<String, QuestsConfigLoader.ConfigLoadError> entry : plugin.getQuestsConfigLoader().getBrokenFiles().entrySet()) {
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + entry.getKey() + ": " + ChatColor.GRAY + entry.getValue().getMessage());
}
} else {
sender.sendMessage(ChatColor.GRAY + "Quests was reloaded.");
}
return true;
} else if (args[1].equalsIgnoreCase("types")) {
sender.sendMessage(ChatColor.GRAY + "Registered task types:");
for (TaskType taskType : plugin.getTaskTypeManager().getTaskTypes()) {
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + taskType.getType());
}
sender.sendMessage(ChatColor.DARK_GRAY + "View info using /q a types [type].");
return true;
} else if (args[1].equalsIgnoreCase("update")) {
sender.sendMessage(ChatColor.GRAY + "Checking for updates...");
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
plugin.getUpdater().check();
if (plugin.getUpdater().isUpdateReady()) {
sender.sendMessage(plugin.getUpdater().getMessage());
} else {
sender.sendMessage(ChatColor.GRAY + "No updates were found.");
}
});
return true;
}
} else if (args.length == 3) {
if (args[1].equalsIgnoreCase("opengui")) {
showAdminHelp(sender, "opengui");
return true;
} else if (args[1].equalsIgnoreCase("moddata")) {
showAdminHelp(sender, "moddata");
return true;
} else if (args[1].equalsIgnoreCase("types")) {
TaskType taskType = null;
for (TaskType task : plugin.getTaskTypeManager().getTaskTypes()) {
if (task.getType().equals(args[2])) {
taskType = task;
}
}
if (taskType == null) {
sender.sendMessage(Messages.COMMAND_TASKVIEW_ADMIN_FAIL.getMessage().replace("{task}", args[2]));
} else {
sender.sendMessage(ChatColor.RED + "Task type: " + ChatColor.GRAY + taskType.getType());
sender.sendMessage(ChatColor.RED + "Author: " + ChatColor.GRAY + taskType.getAuthor());
sender.sendMessage(ChatColor.RED + "Description: " + ChatColor.GRAY + taskType.getDescription());
}
return true;
}
} else if (args.length == 4) {
if (args[1].equalsIgnoreCase("opengui")) {
if (args[2].equalsIgnoreCase("q") || args[2].equalsIgnoreCase("quests")) {
Player player = Bukkit.getPlayer(args[3]);
if (player != null) {
QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId());
if (qPlayer != null) {
qPlayer.openQuests();
sender.sendMessage(Messages.COMMAND_QUEST_OPENQUESTS_ADMIN_SUCCESS.getMessage().replace("{player}", player.getName()));
return true;
}
}
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_PLAYERNOTFOUND.getMessage().replace("{player}", args[3]));
return true;
}
showAdminHelp(sender, "opengui");
return true;
} else if (args[1].equalsIgnoreCase("moddata")) {
OfflinePlayer ofp = Bukkit.getOfflinePlayer(args[3]);
UUID uuid;
String name;
// Player.class is a superclass for OfflinePlayer.
// getofflinePlayer return a player regardless if exists or not
if (ofp != null) {
uuid = ofp.getUniqueId();
name = ofp.getName();
} else {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_PLAYERNOTFOUND.getMessage().replace("{player}", args[3]));
return true;
}
if (args[2].equalsIgnoreCase("fullreset")) {
QPlayer qPlayer = plugin.getPlayerManager().getPlayer(uuid);
if (qPlayer == null) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_LOADDATA.getMessage().replace("{player}", name));
plugin.getPlayerManager().loadPlayer(uuid, true);
qPlayer = plugin.getPlayerManager().getPlayer(uuid); //get again
}
if (qPlayer == null) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_NODATA.getMessage().replace("{player}", name));
return true;
}
QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile();
questProgressFile.clear();
questProgressFile.saveToDisk(false);
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_FULLRESET.getMessage().replace("{player}", name));
return true;
}
if (plugin.getPlayerManager().getPlayer(uuid).isOnlyDataLoaded()) {
plugin.getPlayerManager().removePlayer(uuid);
}
showAdminHelp(sender, "moddata");
return true;
}
} else if (args.length == 5) {
if (args[1].equalsIgnoreCase("opengui")) {
if (args[2].equalsIgnoreCase("c") || args[2].equalsIgnoreCase("category")) {
if (!Options.CATEGORIES_ENABLED.getBooleanValue()) {
sender.sendMessage(Messages.COMMAND_CATEGORY_OPEN_DISABLED.getMessage());
return true;
}
Category category = plugin.getQuestManager().getCategoryById(args[4]);
if (category == null) {
sender.sendMessage(Messages.COMMAND_CATEGORY_OPEN_DOESNTEXIST.getMessage().replace("{category}", args[4]));
return true;
}
Player player = Bukkit.getPlayer(args[3]);
if (player != null) {
QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId());
if (qPlayer != null) {
if (qPlayer.openCategory(category, null, false) == 0) {
sender.sendMessage(Messages.COMMAND_QUEST_OPENCATEGORY_ADMIN_SUCCESS.getMessage().replace("{player}", player.getName())
.replace("{category}", category.getId()));
} else {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_CATEGORY_PERMISSION.getMessage().replace("{player}", player.getName())
.replace("{category}", category.getId()));
}
return true;
}
}
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_PLAYERNOTFOUND.getMessage().replace("{player}", args[3]));
return true;
}
} else if (args[1].equalsIgnoreCase("moddata")) {
boolean success = false;
OfflinePlayer ofp = Bukkit.getOfflinePlayer(args[3]);
UUID uuid;
String name;
if (ofp != null) {
uuid = ofp.getUniqueId();
name = ofp.getName();
} else {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_PLAYERNOTFOUND.getMessage().replace("{player}", args[3]));
return true;
}
QPlayer qPlayer = plugin.getPlayerManager().getPlayer(uuid);
if (qPlayer == null) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_LOADDATA.getMessage().replace("{player}", name));
plugin.getPlayerManager().loadPlayer(uuid, true);
}
if (qPlayer == null) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_NODATA.getMessage().replace("{player}", name));
success = true;
}
qPlayer = plugin.getPlayerManager().getPlayer(uuid); //get again
QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile();
Quest quest = plugin.getQuestManager().getQuestById(args[4]);
if (quest == null) {
sender.sendMessage(Messages.COMMAND_QUEST_START_DOESNTEXIST.getMessage().replace("{quest}", args[4]));
//success = true;
return true;
}
if (args[2].equalsIgnoreCase("reset")) {
questProgressFile.generateBlankQuestProgress(quest.getId());
questProgressFile.saveToDisk(false);
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_RESET_SUCCESS.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
success = true;
} else if (args[2].equalsIgnoreCase("start")) {
QuestStartResult response = questProgressFile.startQuest(quest);
if (response == QuestStartResult.QUEST_LIMIT_REACHED) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILLIMIT.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
return true;
} else if (response == QuestStartResult.QUEST_ALREADY_COMPLETED) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILCOMPLETE.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
return true;
} else if (response == QuestStartResult.QUEST_COOLDOWN) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILCOOLDOWN.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
return true;
} else if (response == QuestStartResult.QUEST_LOCKED) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILLOCKED.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
return true;
} else if (response == QuestStartResult.QUEST_ALREADY_STARTED) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILSTARTED.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
return true;
} else if (response == QuestStartResult.QUEST_NO_PERMISSION) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILPERMISSION.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
return true;
} else if (response == QuestStartResult.NO_PERMISSION_FOR_CATEGORY) {
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILCATEGORYPERMISSION.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
return true;
}
questProgressFile.saveToDisk(false);
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_SUCCESS.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
success = true;
} else if (args[2].equalsIgnoreCase("complete")) {
questProgressFile.completeQuest(quest);
questProgressFile.saveToDisk(false);
sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_COMPLETE_SUCCESS.getMessage().replace("{player}", name).replace("{quest}", quest.getId()));
success = true;
}
if (plugin.getPlayerManager().getPlayer(uuid).isOnlyDataLoaded()) {
plugin.getPlayerManager().removePlayer(uuid);
}
if (!success) {
showAdminHelp(sender, "moddata");
}
return true;
}
}
showAdminHelp(sender, null);
return true;
}
if (sender instanceof Player && (args[0].equalsIgnoreCase("q") || args[0].equalsIgnoreCase("quests") || args[0].equalsIgnoreCase("quest"))) {
Player player = (Player) sender;
if (args.length >= 3) {
Quest quest = plugin.getQuestManager().getQuestById(args[1]);
QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId());
if (args[2].equalsIgnoreCase("s") || args[2].equalsIgnoreCase("start")) {
if (quest == null) {
sender.sendMessage(Messages.COMMAND_QUEST_START_DOESNTEXIST.getMessage().replace("{quest}", args[1]));
} else {
if (qPlayer == null) {
// shit + fan
sender.sendMessage(ChatColor.RED + "An error occurred finding your player."); //lazy? :)
} else {
qPlayer.getQuestProgressFile().startQuest(quest);
}
}
} else if (args[2].equalsIgnoreCase("c") || args[2].equalsIgnoreCase("cancel")) {
if (qPlayer == null) {
sender.sendMessage(ChatColor.RED + "An error occurred finding your player."); //lazy x2? ;)
} else {
qPlayer.getQuestProgressFile().cancelQuest(quest);
}
} else {
sender.sendMessage(Messages.COMMAND_SUB_DOESNTEXIST.getMessage().replace("{sub}", args[2]));
}
return true;
}
} else if (sender instanceof Player && (args[0].equalsIgnoreCase("c") || args[0].equalsIgnoreCase("category"))) {
if (!Options.CATEGORIES_ENABLED.getBooleanValue()) {
sender.sendMessage(Messages.COMMAND_CATEGORY_OPEN_DISABLED.getMessage());
return true;
}
Player player = (Player) sender;
if (args.length >= 2) {
Category category = plugin.getQuestManager().getCategoryById(args[1]);
if (category == null) {
sender.sendMessage(Messages.COMMAND_CATEGORY_OPEN_DOESNTEXIST.getMessage().replace("{category}", args[1]));
} else {
QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId());
qPlayer.openCategory(category, null, false);
return true;
}
return true;
}
}
showHelp(sender);
return true;
} else {
sender.sendMessage(ChatColor.RED + "Only admin commands are available to non-player senders.");
}
return true;
}
private void showHelp(CommandSender sender) {
sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "------------=[" + ChatColor.RED + " Quests v" + plugin
.getDescription().getVersion() + " " + ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "]=------------");
sender.sendMessage(ChatColor.GRAY + "The following commands are available: ");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests " + ChatColor.DARK_GRAY + ": show quests");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests c/category <categoryid> " + ChatColor.DARK_GRAY + ": open category by ID");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests q/quest <questid> <start/cancel>" + ChatColor.DARK_GRAY + ": start or cancel quest by ID");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a/admin " + ChatColor.DARK_GRAY + ": view help for admins");
sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "--------=[" + ChatColor.RED + " made with <3 by LMBishop " + ChatColor
.GRAY.toString() + ChatColor.STRIKETHROUGH + "]=--------");
}
private void showAdminHelp(CommandSender sender, String command) {
if (command != null && command.equalsIgnoreCase("opengui")) {
sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "------------=[" + ChatColor.RED + " Quests Admin: opengui " + ChatColor
.GRAY.toString() + ChatColor.STRIKETHROUGH + "]=------------");
sender.sendMessage(ChatColor.GRAY + "The following commands are available: ");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a opengui q/quest <player> " + ChatColor.DARK_GRAY + ": forcefully show" +
" quests for player");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a opengui c/category <player> <category> " + ChatColor.DARK_GRAY + ": " +
"forcefully " +
"open category by ID for player");
sender.sendMessage(ChatColor.GRAY + "These commands are useful for command NPCs. These will bypass the usual quests.command permission.");
} else if (command != null && command.equalsIgnoreCase("moddata")) {
sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "------------=[" + ChatColor.RED + " Quests Admin: moddata " + ChatColor
.GRAY.toString() + ChatColor.STRIKETHROUGH + "]=------------");
sender.sendMessage(ChatColor.GRAY + "The following commands are available: ");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata fullreset <player> " + ChatColor.DARK_GRAY + ": clear a " +
"players quest data file");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata reset <player> <questid>" + ChatColor.DARK_GRAY + ": clear a " +
"players data for specifc quest");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata start <player> <questid>" + ChatColor.DARK_GRAY + ": start a " +
"quest for a player");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata complete <player> <questid>" + ChatColor.DARK_GRAY + ": " +
"complete a quest for a player");
sender.sendMessage(ChatColor.GRAY + "These commands modify quest progress for players. Use them cautiously. Changes are irreversible.");
} else {
sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "------------=[" + ChatColor.RED + " Quests Admin " + ChatColor.GRAY
.toString() + ChatColor.STRIKETHROUGH + "]=------------");
sender.sendMessage(ChatColor.GRAY + "The following commands are available: ");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a opengui " + ChatColor.DARK_GRAY + ": view help for opengui");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata " + ChatColor.DARK_GRAY + ": view help for quest progression");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a types [type]" + ChatColor.DARK_GRAY + ": view registered task types");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a reload " + ChatColor.DARK_GRAY + ": reload Quests configuration");
sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a update " + ChatColor.DARK_GRAY + ": check for updates");
}
sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "-----=[" + ChatColor.RED + " requires permission: quests.admin " +
ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "]=-----");
}
}
| |
/*
* Copyright 2007 Penn State University
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.psu.citeseerx.dao;
import java.sql.*;
import java.util.*;
import edu.psu.citeseerx.domain.Author;
public class AuthorDAOImpl implements AuthorDAO {
private static final String DEF_GET_AUTH_QUERY =
"select id, cluster, name, affil, address, email, ord from authors " +
"where paperid=? order by ord ASC";
private static final String DEF_GET_AUTH_SRC_QUERY =
"select name, affil, address, email, ord from " +
"authors_versionShadow where id=?";
public List<Author> getDocAuthors(String doi, boolean getSource,
Connection con) throws SQLException {
ArrayList<Author> authors = new ArrayList<Author>();
PreparedStatement stmt = con.prepareStatement(DEF_GET_AUTH_QUERY);
PreparedStatement sstmt =
con.prepareStatement(DEF_GET_AUTH_SRC_QUERY);
stmt.setString(1, doi);
ResultSet ars = stmt.executeQuery();
while (ars.next()) {
Author auth = new Author();
auth.setDatum(Author.DOI_KEY, ars.getString("id"));
auth.setClusterID(ars.getLong("cluster"));
auth.setDatum(Author.NAME_KEY, ars.getString("name"));
auth.setDatum(Author.AFFIL_KEY, ars.getString("affil"));
auth.setDatum(Author.ADDR_KEY, ars.getString("address"));
auth.setDatum(Author.EMAIL_KEY, ars.getString("email"));
auth.setDatum(Author.ORD_KEY, ars.getString("ord"));
if (getSource) {
sstmt.setLong(1,
new Long(auth.getDatum(Author.DOI_KEY,
Author.UNENCODED)));
ResultSet srs = sstmt.executeQuery();
if (srs.first()) {
auth.setSource(Author.NAME_KEY, srs.getString("name"));
auth.setSource(Author.AFFIL_KEY, srs.getString("affil"));
auth.setSource(Author.ADDR_KEY, srs.getString("address"));
auth.setSource(Author.EMAIL_KEY, srs.getString("email"));
auth.setSource(Author.ORD_KEY, srs.getString("ord"));
}
srs.close();
}
authors.add(auth);
}
ars.close();
stmt.close();
sstmt.close();
return authors;
} //- getDocAuthors
/* cluster, name, affil, address, email, ord, paperid */
private static final String DEF_INSERT_AUTH_QUERY =
"insert into authors values (NULL, ?, ?, ?, ?, ?, ?, ?)";
/* id, name, affil, address, email, ord */
private static final String DEF_INSERT_AUTH_SRC_QUERY =
"insert into authors_versionShadow values (?, ?, ?, ?, ?, ?)";
public void insertAuthor(String doi, Author auth, Connection con)
throws SQLException {
PreparedStatement stmt = con.prepareStatement(DEF_INSERT_AUTH_QUERY);
stmt.setLong(1, auth.getClusterID());
stmt.setString(2, auth.getDatum(Author.NAME_KEY, Author.UNENCODED));
stmt.setString(3, auth.getDatum(Author.AFFIL_KEY, Author.UNENCODED));
stmt.setString(4, auth.getDatum(Author.ADDR_KEY, Author.UNENCODED));
stmt.setString(5, auth.getDatum(Author.EMAIL_KEY, Author.UNENCODED));
stmt.setString(6, auth.getDatum(Author.ORD_KEY, Author.UNENCODED));
stmt.setString(7, doi);
stmt.executeUpdate();
ResultSet krs = stmt.getGeneratedKeys();
Long id = null;
if (krs.first()) {
id = new Long(krs.getLong(1));
auth.setDatum(Author.DOI_KEY, Long.toString(id));
}
krs.close();
stmt.close();
if (auth.hasSourceData()) {
PreparedStatement sstmt =
con.prepareStatement(DEF_INSERT_AUTH_SRC_QUERY);
sstmt.setLong(1, id);
sstmt.setString(2, auth.getSource(Author.NAME_KEY));
sstmt.setString(3, auth.getSource(Author.AFFIL_KEY));
sstmt.setString(4, auth.getSource(Author.ADDR_KEY));
sstmt.setString(5, auth.getSource(Author.EMAIL_KEY));
sstmt.setString(6, auth.getSource(Author.ORD_KEY));
sstmt.executeUpdate();
sstmt.close();
}
} //- insertAuthors
private static final String DEF_UPDATE_AUTH_QUERY =
"update authors set cluster=?, name=?, affil=?, address=?, email=?, " +
"ord=? where id=?";
private static final String DEF_UPDATE_AUTH_SRC_QUERY =
"update authors_versionShadow set name=?, affil=?, address=?, " +
"email=?, ord=? where id=?";
public void updateAuthor(Author auth, Connection con) throws SQLException {
PreparedStatement stmt = con.prepareStatement(DEF_UPDATE_AUTH_QUERY);
stmt.setLong(1, auth.getClusterID());
stmt.setString(2, auth.getDatum(Author.NAME_KEY, Author.UNENCODED));
stmt.setString(3, auth.getDatum(Author.AFFIL_KEY, Author.UNENCODED));
stmt.setString(4, auth.getDatum(Author.ADDR_KEY, Author.UNENCODED));
stmt.setString(5, auth.getDatum(Author.EMAIL_KEY, Author.UNENCODED));
stmt.setString(6, auth.getDatum(Author.ORD_KEY, Author.UNENCODED));
stmt.setLong(7, Long.parseLong(
auth.getDatum(Author.DOI_KEY, Author.UNENCODED)));
stmt.executeUpdate();
stmt.close();
if (auth.hasSourceData()) {
PreparedStatement sstmt =
con.prepareStatement(DEF_UPDATE_AUTH_SRC_QUERY);
sstmt.setString(1, auth.getSource(Author.NAME_KEY));
sstmt.setString(2, auth.getSource(Author.AFFIL_KEY));
sstmt.setString(3, auth.getSource(Author.ADDR_KEY));
sstmt.setString(4, auth.getSource(Author.EMAIL_KEY));
sstmt.setString(5, auth.getSource(Author.ORD_KEY));
sstmt.setLong(6, Long.parseLong(
auth.getDatum(Author.DOI_KEY, Author.UNENCODED)));
sstmt.executeUpdate();
sstmt.close();
}
} //- updateAuthor
private static final String DEF_UPDATE_CLUSTER_QUERY =
"update authors set cluster=? where id=?";
public void setCluster(Author auth, Long clusterID, Connection con)
throws SQLException {
PreparedStatement stmt = con.prepareStatement(DEF_UPDATE_CLUSTER_QUERY);
stmt.setLong(1, clusterID);
stmt.setLong(2, Long.parseLong(
auth.getDatum(Author.DOI_KEY, Author.UNENCODED)));
stmt.executeUpdate();
stmt.close();
} //- setCluster
private static final String DEF_DEL_AUTHORS_QUERY =
"delete from authors where paperid=?";
public void deleteAuthors(String doi, Connection con) throws SQLException {
PreparedStatement stmt = con.prepareStatement(DEF_DEL_AUTHORS_QUERY);
stmt.setString(1, doi);
stmt.executeUpdate();
stmt.close();
} //- deleteAuthors
private static final String DEF_DEL_AUTHOR_QUERY =
"delete from authors where id=?";
public void deleteAuthor(Long authorID, Connection con)
throws SQLException {
PreparedStatement stmt = con.prepareStatement(DEF_DEL_AUTHOR_QUERY);
stmt.setLong(1, authorID);
stmt.executeUpdate();
stmt.close();
} //- deleteAuthor
} //- class AuthorDAOImpl
| |
/*
* Copyright 2000-2016 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.updateSettings.impl;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.plugins.*;
import com.intellij.ide.startup.StartupActionScriptManager;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.BuildNumber;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PathUtil;
import com.intellij.util.io.HttpRequests;
import com.intellij.util.io.ZipUtil;
import com.intellij.util.text.VersionComparatorUtil;
import org.apache.http.client.utils.URIBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author anna
* @since 10-Aug-2007
*/
public class PluginDownloader {
private static final Logger LOG = Logger.getInstance("#" + PluginDownloader.class.getName());
private static final String FILENAME = "filename=";
private final String myPluginId;
private final String myPluginUrl;
private final String myPluginName;
private String myPluginVersion;
private BuildNumber myBuildNumber;
private File myFile;
private File myOldFile;
private String myDescription;
private List<PluginId> myDepends;
private IdeaPluginDescriptor myDescriptor;
private final boolean myForceHttps;
private PluginDownloader(@NotNull String pluginId,
@NotNull String pluginUrl,
@Nullable String pluginName,
@Nullable String pluginVersion,
@Nullable BuildNumber buildNumber,
boolean forceHttps) {
myPluginId = pluginId;
myPluginUrl = pluginUrl;
myPluginVersion = pluginVersion;
myPluginName = pluginName;
myBuildNumber = buildNumber;
myForceHttps = forceHttps;
}
public String getPluginId() {
return myPluginId;
}
public String getPluginVersion() {
return myPluginVersion;
}
public String getPluginName() {
return myPluginName != null ? myPluginName : myPluginId;
}
public BuildNumber getBuildNumber() {
return myBuildNumber;
}
public String getDescription() {
return myDescription;
}
public void setDescription(String description) {
myDescription = description;
}
public List<PluginId> getDepends() {
return myDepends;
}
public void setDepends(List<PluginId> depends) {
myDepends = depends;
}
public IdeaPluginDescriptor getDescriptor() {
return myDescriptor;
}
public void setDescriptor(IdeaPluginDescriptor descriptor) {
myDescriptor = descriptor;
}
public boolean prepareToInstall(@NotNull ProgressIndicator indicator) throws IOException {
if (myFile != null) {
return true;
}
IdeaPluginDescriptor descriptor = null;
if (!Boolean.getBoolean(StartupActionScriptManager.STARTUP_WIZARD_MODE) && PluginManager.isPluginInstalled(PluginId.getId(myPluginId))) {
//store old plugins file
descriptor = PluginManager.getPlugin(PluginId.getId(myPluginId));
LOG.assertTrue(descriptor != null);
if (myPluginVersion != null && compareVersionsSkipBrokenAndIncompatible(descriptor, myPluginVersion) <= 0) {
LOG.info("Plugin " + myPluginId + ": current version (max) " + myPluginVersion);
return false;
}
myOldFile = descriptor.isBundled() ? null : descriptor.getPath();
}
// download plugin
String errorMessage = IdeBundle.message("unknown.error");
try {
myFile = downloadPlugin(indicator);
}
catch (IOException ex) {
myFile = null;
LOG.warn(ex);
errorMessage = ex.getMessage();
}
if (myFile == null) {
if (ApplicationManager.getApplication() != null) {
final String text = IdeBundle.message("error.plugin.was.not.installed", getPluginName(), errorMessage);
final String title = IdeBundle.message("title.failed.to.download");
ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(text, title));
}
return false;
}
IdeaPluginDescriptorImpl actualDescriptor = loadDescriptionFromJar(myFile);
if (actualDescriptor != null) {
InstalledPluginsState state = InstalledPluginsState.getInstanceIfLoaded();
if (state != null && state.wasUpdated(actualDescriptor.getPluginId())) {
return false; //already updated
}
myPluginVersion = actualDescriptor.getVersion();
if (descriptor != null && compareVersionsSkipBrokenAndIncompatible(descriptor, myPluginVersion) <= 0) {
LOG.info("Plugin " + myPluginId + ": current version (max) " + myPluginVersion);
return false; //was not updated
}
setDescriptor(actualDescriptor);
if (PluginManagerCore.isIncompatible(actualDescriptor, myBuildNumber)) {
LOG.info("Plugin " + myPluginId + " is incompatible with current installation " +
"(since:" + actualDescriptor.getSinceBuild() + " until:" + actualDescriptor.getUntilBuild() + ")");
return false; //host outdated plugins, no compatible plugin for new version
}
}
return true;
}
public static int compareVersionsSkipBrokenAndIncompatible(@NotNull IdeaPluginDescriptor existingPlugin, String newPluginVersion) {
int state = comparePluginVersions(newPluginVersion, existingPlugin.getVersion());
if (state < 0 && (PluginManagerCore.isBrokenPlugin(existingPlugin) || PluginManagerCore.isIncompatible(existingPlugin))) {
state = 1;
}
return state;
}
public static int comparePluginVersions(String newPluginVersion, String oldPluginVersion) {
return VersionComparatorUtil.compare(newPluginVersion, oldPluginVersion);
}
@Nullable
public static IdeaPluginDescriptorImpl loadDescriptionFromJar(final File file) throws IOException {
IdeaPluginDescriptorImpl descriptor = PluginManagerCore.loadDescriptor(file, PluginManagerCore.PLUGIN_XML);
if (descriptor == null) {
if (file.getName().endsWith(".zip")) {
final File outputDir = FileUtil.createTempDirectory("plugin", "");
try {
ZipUtil.extract(file, outputDir, null);
final File[] files = outputDir.listFiles();
if (files != null && files.length == 1) {
descriptor = PluginManagerCore.loadDescriptor(files[0], PluginManagerCore.PLUGIN_XML);
}
}
finally {
FileUtil.delete(outputDir);
}
}
}
return descriptor;
}
public void install() throws IOException {
LOG.assertTrue(myFile != null, "Cannot install plugin '" + getPluginName()+"'");
if (myFile == null) throw new IOException("Cannot find file for plugin '" + getPluginName()+"'");
if (myOldFile != null) {
StartupActionScriptManager.ActionCommand deleteOld = new StartupActionScriptManager.DeleteCommand(myOldFile);
StartupActionScriptManager.addActionCommand(deleteOld);
}
PluginInstaller.install(myFile, getPluginName(), true, myDescriptor);
InstalledPluginsState state = InstalledPluginsState.getInstanceIfLoaded();
if (state != null) {
state.onPluginInstall(myDescriptor);
}
}
@NotNull
private File downloadPlugin(@NotNull final ProgressIndicator indicator) throws IOException {
File pluginsTemp = new File(PathManager.getPluginTempPath());
if (!pluginsTemp.exists() && !pluginsTemp.mkdirs()) {
throw new IOException(IdeBundle.message("error.cannot.create.temp.dir", pluginsTemp));
}
final File file = FileUtil.createTempFile(pluginsTemp, "plugin_", "_download", true, false);
indicator.checkCanceled();
indicator.setText2(IdeBundle.message("progress.downloading.plugin", getPluginName()));
return HttpRequests.request(myPluginUrl).gzip(false).forceHttps(myForceHttps).connect(new HttpRequests.RequestProcessor<File>() {
@Override
public File process(@NotNull HttpRequests.Request request) throws IOException {
request.saveToFile(file, indicator);
String fileName = guessFileName(request.getConnection(), file);
File newFile = new File(file.getParentFile(), fileName);
FileUtil.rename(file, newFile);
return newFile;
}
});
}
@NotNull
private String guessFileName(@NotNull URLConnection connection, @NotNull File file) throws IOException {
String fileName = null;
final String contentDisposition = connection.getHeaderField("Content-Disposition");
LOG.debug("header: " + contentDisposition);
if (contentDisposition != null && contentDisposition.contains(FILENAME)) {
final int startIdx = contentDisposition.indexOf(FILENAME);
final int endIdx = contentDisposition.indexOf(';', startIdx);
fileName = contentDisposition.substring(startIdx + FILENAME.length(), endIdx > 0 ? endIdx : contentDisposition.length());
if (StringUtil.startsWithChar(fileName, '\"') && StringUtil.endsWithChar(fileName, '\"')) {
fileName = fileName.substring(1, fileName.length() - 1);
}
}
if (fileName == null) {
// try to find a filename in an URL
final String usedURL = connection.getURL().toString();
LOG.debug("url: " + usedURL);
fileName = usedURL.substring(usedURL.lastIndexOf('/') + 1);
if (fileName.length() == 0 || fileName.contains("?")) {
fileName = myPluginUrl.substring(myPluginUrl.lastIndexOf('/') + 1);
}
}
if (!PathUtil.isValidFileName(fileName)) {
LOG.debug("fileName: " + fileName);
FileUtil.delete(file);
throw new IOException("Invalid filename returned by a server");
}
return fileName;
}
// creators-converters
public static PluginDownloader createDownloader(@NotNull IdeaPluginDescriptor descriptor) throws IOException {
return createDownloader(descriptor, null, null);
}
@NotNull
public static PluginDownloader createDownloader(@NotNull IdeaPluginDescriptor descriptor,
@Nullable String host,
@Nullable BuildNumber buildNumber) throws IOException {
boolean forceHttps = host == null
&& (ApplicationManager.getApplication() == null || UpdateSettings.getInstance().canUseSecureConnection());
return createDownloader(descriptor, host, buildNumber, forceHttps);
}
@NotNull
public static PluginDownloader createDownloader(@NotNull IdeaPluginDescriptor descriptor,
@Nullable String host,
@Nullable BuildNumber buildNumber,
boolean forceHttps) throws IOException {
try {
String url = getUrl(descriptor, host, buildNumber);
String id = descriptor.getPluginId().getIdString();
PluginDownloader downloader = new PluginDownloader(id, url, descriptor.getName(), descriptor.getVersion(), buildNumber, forceHttps);
downloader.setDescriptor(descriptor);
downloader.setDescription(descriptor.getDescription());
List<PluginId> depends;
if (descriptor instanceof PluginNode) {
depends = ((PluginNode)descriptor).getDepends();
}
else {
depends = new ArrayList<>(Arrays.asList(descriptor.getDependentPluginIds()));
}
downloader.setDepends(depends);
return downloader;
}
catch (URISyntaxException e) {
throw new IOException(e);
}
}
@NotNull
private static String getUrl(@NotNull IdeaPluginDescriptor descriptor,
@Nullable String host,
@Nullable BuildNumber buildNumber) throws URISyntaxException, MalformedURLException {
if (host != null && descriptor instanceof PluginNode) {
String url = ((PluginNode)descriptor).getDownloadUrl();
return new URI(url).isAbsolute() ? url : new URL(new URL(host), url).toExternalForm();
}
else {
Application app = ApplicationManager.getApplication();
ApplicationInfoEx appInfo = ApplicationInfoImpl.getShadowInstance();
String buildNumberAsString = buildNumber != null ? buildNumber.asString() :
app != null ? ApplicationInfo.getInstance().getApiVersion() :
appInfo.getBuild().asString();
URIBuilder uriBuilder = new URIBuilder(appInfo.getPluginsDownloadUrl());
uriBuilder.addParameter("action", "download");
uriBuilder.addParameter("id", descriptor.getPluginId().getIdString());
uriBuilder.addParameter("build", buildNumberAsString);
uriBuilder.addParameter("uuid", PermanentInstallationID.get());
return uriBuilder.build().toString();
}
}
@Nullable
public static PluginNode createPluginNode(@Nullable String host, @NotNull PluginDownloader downloader) {
IdeaPluginDescriptor descriptor = downloader.getDescriptor();
if (descriptor instanceof PluginNode) {
return (PluginNode)descriptor;
}
PluginNode node = new PluginNode(PluginId.getId(downloader.getPluginId()));
node.setName(downloader.getPluginName());
node.setVersion(downloader.getPluginVersion());
node.setRepositoryName(host);
node.setDownloadUrl(downloader.myPluginUrl);
node.setDepends(downloader.getDepends(), null);
node.setDescription(downloader.getDescription());
return node;
}
}
| |
/*
* 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.sling.launchpad.webapp.integrationtest.jcrinstall;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.sling.commons.testing.integration.HttpTestBase;
import org.apache.sling.launchpad.webapp.integrationtest.jcrinstall.util.BundleCloner;
import org.osgi.framework.Bundle;
/** Base class for jcrinstall test cases */
public class JcrinstallTestBase extends HttpTestBase {
public static final String JCRINSTALL_STATUS_PATH = "/system/sling/jcrinstall";
public static final String DEFAULT_INSTALL_PATH = "/libs/integration-testing/install";
public static final String DEFAULT_BUNDLE_NAME_PATTERN = "observer";
private static long bundleCounter = System.currentTimeMillis();
private static Set<String> installedClones;
public static final String SCALE_FACTOR_PROP = "sling.test.scale.factor";
public static final String DEFAULT_TIMEOUT_PROP = "sling.test.bundles.wait.seconds";
protected int scaleFactor;
protected int defaultBundlesTimeout;
static interface StringCondition {
boolean eval(String input);
}
private class ShutdownThread extends Thread {
@Override
public void run() {
try {
System.out.println("Deleting " + installedClones.size() + " cloned bundles...");
for(String path : installedClones) {
testClient.delete(WEBDAV_BASE_URL + path);
}
} catch(Exception e) {
System.out.println("Exception in ShutdownThread:" + e);
}
}
};
@Override
protected void setUp() throws Exception {
super.setUp();
scaleFactor = requireIntProperty(SCALE_FACTOR_PROP);
defaultBundlesTimeout = requireIntProperty(DEFAULT_TIMEOUT_PROP);
enableJcrinstallService(true);
}
@Override
protected void tearDown() throws Exception {
// TODO Auto-generated method stub
super.tearDown();
enableJcrinstallService(true);
}
protected int requireIntProperty(String systemPropertyKey) throws Exception {
final String s = System.getProperty(systemPropertyKey);
if(s == null) {
throw new Exception("Missing system property '" + systemPropertyKey + "'");
}
return Integer.valueOf(s);
}
/** Fail test if active bundles count is not expectedCount, after
* at most timeoutSeconds */
protected void assertActiveBundleCount(String message, int expectedCount, int timeoutSeconds) throws IOException {
final long start = System.currentTimeMillis();
final long timeout = start + timeoutSeconds * 1000L;
int count = 0;
int lastCount = -1;
while(System.currentTimeMillis() < timeout) {
count = getActiveBundlesCount();
if(count != lastCount) {
// continue until the count is stable for at least one second
lastCount = count;
sleep(1000);
continue;
} else if(count == expectedCount) {
return;
}
sleep(500);
}
final long delta = System.currentTimeMillis() - start;
fail(message + ": expected " + expectedCount + " active bundles, found " + count
+ " after waiting " + delta / 1000.0 + " seconds");
}
protected void assertContentWithTimeout(String message, String contentUrl, String expectedContentType,
StringCondition condition, int timeoutSeconds) throws IOException
{
final long start = System.currentTimeMillis();
final long timeout = start + timeoutSeconds * 1000L;
while(System.currentTimeMillis() < timeout) {
final String content = getContent(contentUrl, expectedContentType);
if(condition.eval(content)) {
return;
}
sleep(200);
}
final long delta = System.currentTimeMillis() - start;
fail(message + ": StringCondition did not return true"
+ " after waiting " + delta / 1000.0 + " seconds");
}
protected void sleep(long millis) {
try {
Thread.sleep(millis);
} catch(InterruptedException ignore) {
}
}
protected int getActiveBundlesCount() throws IOException {
final String key = "bundles.in.state." + Bundle.ACTIVE;
final Properties props = getJcrInstallProperties();
int result = 0;
if(props.containsKey(key)) {
result = Integer.valueOf(props.getProperty(key));
}
return result;
}
protected boolean getJcrinstallServiceEnabled() throws IOException {
final Properties props = getJcrInstallProperties();
return "true".equals(props.get("jcrinstall.enabled"));
}
protected void enableJcrinstallService(boolean enable) throws IOException {
if(enable != getJcrinstallServiceEnabled()) {
final PostMethod post = new PostMethod(HTTP_BASE_URL + JCRINSTALL_STATUS_PATH);
post.setFollowRedirects(false);
post.addParameter("enabled", String.valueOf(enable));
final int status = httpClient.executeMethod(post);
assertEquals("Expected status 200 in enableJcrinstallService", 200, status);
assertEquals("Expected jcrinstall.enabled to be " + enable, enable, getJcrinstallServiceEnabled());
}
}
/** Return the Properties found at /system/sling/jcrinstall */
protected Properties getJcrInstallProperties() throws IOException {
final String content = getContent(HTTP_BASE_URL + JCRINSTALL_STATUS_PATH, CONTENT_TYPE_PLAIN);
final Properties result = new Properties();
result.load(new ByteArrayInputStream(content.getBytes("UTF-8")));
return result;
}
/** Remove a cloned bundle that had been installed before */
protected void removeClonedBundle(String path) throws IOException {
testClient.delete(WEBDAV_BASE_URL + path);
installedClones.remove(path);
}
/** Generate a clone of one of our test bundles, with unique bundle name and
* symbolic name, and install it via WebDAV.
* @param bundleNamePattern The first test bundle that contains this pattern
* is used as a source. If null, uses DEFAULT_BUNDLE_NAME_PATTERN
* @param installPath if null, use DEFAULT_INSTALL_PATH
* @return the path of the installed bundle
*/
protected String installClonedBundle(String bundleNamePattern, String installPath) throws Exception {
if(bundleNamePattern == null) {
bundleNamePattern = DEFAULT_BUNDLE_NAME_PATTERN;
}
if(installPath == null) {
installPath = DEFAULT_INSTALL_PATH;
}
// find test bundle to clone
final File testBundlesDir = new File(System.getProperty("sling.testbundles.path"));
if(!testBundlesDir.isDirectory()) {
throw new IOException(testBundlesDir.getAbsolutePath() + " is not a directory");
}
File bundleSrc = null;
for(String bundle : testBundlesDir.list()) {
if(bundle.contains(bundleNamePattern)) {
bundleSrc = new File(testBundlesDir, bundle);
break;
}
}
// clone bundle
final File outputDir = new File(testBundlesDir, "cloned-bundles");
outputDir.mkdirs();
final String bundleId = bundleNamePattern + "_clone_" + bundleCounter++;
final File clone = new File(outputDir, bundleId + ".jar");
new BundleCloner().cloneBundle(bundleSrc, clone, bundleId, bundleId);
// install clone by copying to repository - jcrinstall should then pick it up
FileInputStream fis = new FileInputStream(clone);
final String path = installPath + "/" + clone.getName();
final String url = WEBDAV_BASE_URL + path;
try {
testClient.mkdirs(WEBDAV_BASE_URL, installPath);
testClient.upload(url, fis);
setupBundlesCleanup();
installedClones.add(path);
} finally {
if(fis != null) {
fis.close();
}
}
return path;
}
/** If not done yet, register a shutdown hook to delete cloned bundles that
* we installed.
*/
private void setupBundlesCleanup() {
synchronized (JcrinstallTestBase.class) {
if(installedClones == null) {
installedClones = new HashSet<String>();
Runtime.getRuntime().addShutdownHook(new ShutdownThread());
}
}
}
}
| |
package com.google.devcoin.protocols.channels;
import com.google.devcoin.core.*;
import com.google.devcoin.protocols.channels.PaymentChannelCloseException.CloseReason;
import com.google.devcoin.utils.Threading;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.ByteString;
import net.jcip.annotations.GuardedBy;
import org.devcoin.paymentchannel.Protos;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* <p>A class which handles most of the complexity of creating a payment channel connection by providing a
* simple in/out interface which is provided with protobufs from the server and which generates protobufs which should
* be sent to the server.</p>
*
* <p>Does all required verification of server messages and properly stores state objects in the wallet-attached
* {@link StoredPaymentChannelClientStates} so that they are automatically closed when necessary and refund
* transactions are not lost if the application crashes before it unlocks.</p>
*
* <p>Though this interface is largely designed with stateful protocols (eg simple TCP connections) in mind, it is also
* possible to use it with stateless protocols (eg sending protobufs when required over HTTP headers). In this case, the
* "connection" translates roughly into the server-client relationship. See the javadocs for specific functions for more
* details.</p>
*/
public class PaymentChannelClient {
private static final org.slf4j.Logger log = LoggerFactory.getLogger(PaymentChannelClient.class);
protected final ReentrantLock lock = Threading.lock("channelclient");
/**
* Implements the connection between this client and the server, providing an interface which allows messages to be
* sent to the server, requests for the connection to the server to be closed, and a callback which occurs when the
* channel is fully open.
*/
public interface ClientConnection {
/**
* <p>Requests that the given message be sent to the server. There are no blocking requirements for this method,
* however the order of messages must be preserved.</p>
*
* <p>If the send fails, no exception should be thrown, however
* {@link PaymentChannelClient#connectionClosed()} should be called immediately. In the case of messages which
* are a part of initialization, initialization will simply fail and the refund transaction will be broadcasted
* when it unlocks (if necessary). In the case of a payment message, the payment will be lost however if the
* channel is resumed it will begin again from the channel value <i>after</i> the failed payment.</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelClient} object - be careful about reentrancy</p>
*/
public void sendToServer(Protos.TwoWayChannelMessage msg);
/**
* <p>Requests that the connection to the server be closed. For stateless protocols, note that after this call,
* no more messages should be received from the server and this object is no longer usable. A
* {@link PaymentChannelClient#connectionClosed()} event should be generated immediately after this call.</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelClient} object - be careful about reentrancy</p>
*
* @param reason The reason for the closure, see the individual values for more details.
* It is usually safe to ignore this and treat any value below
* {@link CloseReason#CLIENT_REQUESTED_CLOSE} as "unrecoverable error" and all others as
* "try again once and see if it works then"
*/
public void destroyConnection(CloseReason reason);
/**
* <p>Indicates the channel has been successfully opened and
* {@link PaymentChannelClient#incrementPayment(java.math.BigInteger)} may be called at will.</p>
*
* <p>Called while holding a lock on the {@link PaymentChannelClient} object - be careful about reentrancy</p>
*/
public void channelOpen();
}
@GuardedBy("lock") private final ClientConnection conn;
// Used to keep track of whether or not the "socket" ie connection is open and we can generate messages
@VisibleForTesting @GuardedBy("lock") boolean connectionOpen = false;
// The state object used to step through initialization and pay the server
@GuardedBy("lock") private PaymentChannelClientState state;
// The step we are at in initialization, this is partially duplicated in the state object
private enum InitStep {
WAITING_FOR_CONNECTION_OPEN,
WAITING_FOR_VERSION_NEGOTIATION,
WAITING_FOR_INITIATE,
WAITING_FOR_REFUND_RETURN,
WAITING_FOR_CHANNEL_OPEN,
CHANNEL_OPEN
}
@GuardedBy("lock") private InitStep step = InitStep.WAITING_FOR_CONNECTION_OPEN;
// Will either hold the StoredClientChannel of this channel or null after connectionOpen
private StoredClientChannel storedChannel;
// An arbitrary hash which identifies this channel (specified by the API user)
private final Sha256Hash serverId;
// The wallet associated with this channel
private final Wallet wallet;
// Information used during channel initialization to send to the server or check what the server sends to us
private final ECKey myKey;
private final BigInteger maxValue;
/**
* <p>The maximum amount of time for which we will accept the server locking up our funds for the multisig
* contract.</p>
*
* <p>Note that though this is not final, it is in all caps because it should generally not be modified unless you
* have some guarantee that the server will not request at least this (channels will fail if this is too small).</p>
*
* <p>24 hours is the default as it is expected that clients limit risk exposure by limiting channel size instead of
* limiting lock time when dealing with potentially malicious servers.</p>
*/
public long MAX_TIME_WINDOW = 24*60*60;
/**
* Constructs a new channel manager which waits for {@link PaymentChannelClient#connectionOpen()} before acting.
*
* @param wallet The wallet which will be paid from, and where completed transactions will be committed.
* Must already have a {@link StoredPaymentChannelClientStates} object in its extensions set.
* @param myKey A freshly generated keypair used for the multisig contract and refund output.
* @param maxValue The maximum value the server is allowed to request that we lock into this channel until the
* refund transaction unlocks. Note that if there is a previously open channel, the refund
* transaction used in this channel may be larger than maxValue. Thus, maxValue is not a method for
* limiting the amount payable through this channel.
* @param serverId An arbitrary hash representing this channel. This must uniquely identify the server. If an
* existing stored channel exists in the wallet's {@link StoredPaymentChannelClientStates}, then an
* attempt will be made to resume that channel.
* @param conn A callback listener which represents the connection to the server (forwards messages we generate to
* the server)
*/
public PaymentChannelClient(Wallet wallet, ECKey myKey, BigInteger maxValue, Sha256Hash serverId, ClientConnection conn) {
this.wallet = checkNotNull(wallet);
this.myKey = checkNotNull(myKey);
this.maxValue = checkNotNull(maxValue);
this.serverId = checkNotNull(serverId);
this.conn = checkNotNull(conn);
}
@GuardedBy("lock")
private void receiveInitiate(Protos.Initiate initiate, BigInteger contractValue) throws VerificationException, ValueOutOfRangeException {
log.info("Got INITIATE message, providing refund transaction");
state = new PaymentChannelClientState(wallet, myKey,
new ECKey(null, initiate.getMultisigKey().toByteArray()),
contractValue, initiate.getExpireTimeSecs());
state.initiate();
step = InitStep.WAITING_FOR_REFUND_RETURN;
Protos.ProvideRefund.Builder provideRefundBuilder = Protos.ProvideRefund.newBuilder()
.setMultisigKey(ByteString.copyFrom(myKey.getPubKey()))
.setTx(ByteString.copyFrom(state.getIncompleteRefundTransaction().devcoinSerialize()));
conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
.setProvideRefund(provideRefundBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.PROVIDE_REFUND)
.build());
}
@GuardedBy("lock")
private void receiveRefund(Protos.TwoWayChannelMessage msg) throws VerificationException {
checkState(step == InitStep.WAITING_FOR_REFUND_RETURN && msg.hasReturnRefund());
log.info("Got RETURN_REFUND message, providing signed contract");
Protos.ReturnRefund returnedRefund = msg.getReturnRefund();
state.provideRefundSignature(returnedRefund.getSignature().toByteArray());
step = InitStep.WAITING_FOR_CHANNEL_OPEN;
// Before we can send the server the contract (ie send it to the network), we must ensure that our refund
// transaction is safely in the wallet - thus we store it (this also keeps it up-to-date when we pay)
state.storeChannelInWallet(serverId);
Protos.ProvideContract.Builder provideContractBuilder = Protos.ProvideContract.newBuilder()
.setTx(ByteString.copyFrom(state.getMultisigContract().devcoinSerialize()));
conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
.setProvideContract(provideContractBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.PROVIDE_CONTRACT)
.build());
}
@GuardedBy("lock")
private void receiveChannelOpen() throws VerificationException {
checkState(step == InitStep.WAITING_FOR_CHANNEL_OPEN || (step == InitStep.WAITING_FOR_INITIATE && storedChannel != null), step);
log.info("Got CHANNEL_OPEN message, ready to pay");
if (step == InitStep.WAITING_FOR_INITIATE)
state = new PaymentChannelClientState(storedChannel, wallet);
step = InitStep.CHANNEL_OPEN;
// channelOpen should disable timeouts, but
// TODO accomodate high latency between PROVIDE_CONTRACT and here
conn.channelOpen();
}
/**
* Called when a message is received from the server. Processes the given message and generates events based on its
* content.
*/
public void receiveMessage(Protos.TwoWayChannelMessage msg) {
lock.lock();
try {
checkState(connectionOpen);
// If we generate an error, we set errorBuilder and closeReason and break, otherwise we return
Protos.Error.Builder errorBuilder;
CloseReason closeReason;
try {
switch (msg.getType()) {
case SERVER_VERSION:
checkState(step == InitStep.WAITING_FOR_VERSION_NEGOTIATION && msg.hasServerVersion());
// Server might send back a major version lower than our own if they want to fallback to a lower version
// We can't handle that, so we just close the channel
if (msg.getServerVersion().getMajor() != 0) {
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.NO_ACCEPTABLE_VERSION);
closeReason = CloseReason.NO_ACCEPTABLE_VERSION;
break;
}
log.info("Got version handshake, awaiting INITIATE or resume CHANNEL_OPEN");
step = InitStep.WAITING_FOR_INITIATE;
return;
case INITIATE:
checkState(step == InitStep.WAITING_FOR_INITIATE && msg.hasInitiate());
Protos.Initiate initiate = msg.getInitiate();
checkState(initiate.getExpireTimeSecs() > 0 && initiate.getMinAcceptedChannelSize() >= 0);
if (initiate.getExpireTimeSecs() > Utils.now().getTime()/1000 + MAX_TIME_WINDOW) {
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.TIME_WINDOW_TOO_LARGE);
closeReason = CloseReason.TIME_WINDOW_TOO_LARGE;
break;
}
BigInteger minChannelSize = BigInteger.valueOf(initiate.getMinAcceptedChannelSize());
if (maxValue.compareTo(minChannelSize) < 0) {
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.CHANNEL_VALUE_TOO_LARGE);
closeReason = CloseReason.SERVER_REQUESTED_TOO_MUCH_VALUE;
break;
}
receiveInitiate(initiate, maxValue);
return;
case RETURN_REFUND:
receiveRefund(msg);
return;
case CHANNEL_OPEN:
receiveChannelOpen();
return;
case CLOSE:
conn.destroyConnection(CloseReason.SERVER_REQUESTED_CLOSE);
return;
case ERROR:
checkState(msg.hasError());
log.error("Server sent ERROR {} with explanation {}", msg.getError().getCode().name(),
msg.getError().hasExplanation() ? msg.getError().getExplanation() : "");
conn.destroyConnection(CloseReason.REMOTE_SENT_ERROR);
return;
default:
log.error("Got unknown message type or type that doesn't apply to clients.");
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.SYNTAX_ERROR);
closeReason = CloseReason.REMOTE_SENT_INVALID_MESSAGE;
break;
}
} catch (VerificationException e) {
log.error("Caught verification exception handling message from server", e);
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.BAD_TRANSACTION)
.setExplanation(e.getMessage());
closeReason = CloseReason.REMOTE_SENT_INVALID_MESSAGE;
} catch (ValueOutOfRangeException e) {
log.error("Caught value out of range exception handling message from server", e);
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.BAD_TRANSACTION)
.setExplanation(e.getMessage());
closeReason = CloseReason.REMOTE_SENT_INVALID_MESSAGE;
} catch (IllegalStateException e) {
log.error("Caught illegal state exception handling message from server", e);
errorBuilder = Protos.Error.newBuilder()
.setCode(Protos.Error.ErrorCode.SYNTAX_ERROR);
closeReason = CloseReason.REMOTE_SENT_INVALID_MESSAGE;
}
conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
.setError(errorBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.ERROR)
.build());
conn.destroyConnection(closeReason);
} finally {
lock.unlock();
}
}
/**
* <p>Called when the connection terminates. Notifies the {@link StoredClientChannel} object that we can attempt to
* resume this channel in the future and stops generating messages for the server.</p>
*
* <p>For stateless protocols, this translates to a client not using the channel for the immediate future, but
* intending to reopen the channel later. There is likely little reason to use this in a stateless protocol.</p>
*
* <p>Note that this <b>MUST</b> still be called even after either
* {@link ClientConnection#destroyConnection(CloseReason)} or
* {@link PaymentChannelClient#close()} is called to actually handle the connection close logic.</p>
*/
public void connectionClosed() {
lock.lock();
try {
connectionOpen = false;
if (state != null)
state.disconnectFromChannel();
} finally {
lock.unlock();
}
}
/**
* <p>Closes the connection, notifying the server it should close the channel by broadcasting the most recent payment
* transaction.</p>
*
* <p>Note that this only generates a CLOSE message for the server and calls
* {@link ClientConnection#destroyConnection(CloseReason)} to close the connection, it does not
* actually handle connection close logic, and {@link PaymentChannelClient#connectionClosed()} must still be called
* after the connection fully closes.</p>
*
* @throws IllegalStateException If the connection is not currently open (ie the CLOSE message cannot be sent)
*/
public void close() throws IllegalStateException {
lock.lock();
try {
checkState(connectionOpen);
conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
.setType(Protos.TwoWayChannelMessage.MessageType.CLOSE)
.build());
conn.destroyConnection(CloseReason.CLIENT_REQUESTED_CLOSE);
} finally {
lock.unlock();
}
}
/**
* <p>Called to indicate the connection has been opened and messages can now be generated for the server.</p>
*
* <p>Attempts to find a channel to resume and generates a CLIENT_VERSION message for the server based on the
* result.</p>
*/
public void connectionOpen() {
lock.lock();
try {
connectionOpen = true;
StoredPaymentChannelClientStates channels = (StoredPaymentChannelClientStates) wallet.getExtensions().get(StoredPaymentChannelClientStates.EXTENSION_ID);
if (channels != null)
storedChannel = channels.getUsableChannelForServerID(serverId);
step = InitStep.WAITING_FOR_VERSION_NEGOTIATION;
Protos.ClientVersion.Builder versionNegotiationBuilder = Protos.ClientVersion.newBuilder()
.setMajor(0).setMinor(1);
if (storedChannel != null) {
versionNegotiationBuilder.setPreviousChannelContractHash(ByteString.copyFrom(storedChannel.contract.getHash().getBytes()));
log.info("Begun version handshake, attempting to reopen channel with contract hash {}", storedChannel.contract.getHash());
} else
log.info("Begun version handshake creating new channel");
conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
.setType(Protos.TwoWayChannelMessage.MessageType.CLIENT_VERSION)
.setClientVersion(versionNegotiationBuilder)
.build());
} finally {
lock.unlock();
}
}
/**
* <p>Gets the {@link PaymentChannelClientState} object which stores the current state of the connection with the
* server.</p>
*
* <p>Note that if you call any methods which update state directly the server will not be notified and channel
* initialization logic in the connection may fail unexpectedly.</p>
*/
public PaymentChannelClientState state() {
lock.lock();
try {
return state;
} finally {
lock.unlock();
}
}
/**
* Increments the total value which we pay the server.
*
* @param size How many satoshis to increment the payment by (note: not the new total).
* @throws ValueOutOfRangeException If the size is negative or would pay more than this channel's total value
* ({@link PaymentChannelClientConnection#state()}.getTotalValue())
* @throws IllegalStateException If the channel has been closed or is not yet open
* (see {@link PaymentChannelClientConnection#getChannelOpenFuture()} for the second)
*/
public void incrementPayment(BigInteger size) throws ValueOutOfRangeException, IllegalStateException {
lock.lock();
try {
if (state() == null || !connectionOpen || step != InitStep.CHANNEL_OPEN)
throw new IllegalStateException("Channel is not fully initialized/has already been closed");
byte[] signature = state().incrementPaymentBy(size);
Protos.UpdatePayment.Builder updatePaymentBuilder = Protos.UpdatePayment.newBuilder()
.setSignature(ByteString.copyFrom(signature))
.setClientChangeValue(state.getValueRefunded().longValue());
conn.sendToServer(Protos.TwoWayChannelMessage.newBuilder()
.setUpdatePayment(updatePaymentBuilder)
.setType(Protos.TwoWayChannelMessage.MessageType.UPDATE_PAYMENT)
.build());
} finally {
lock.unlock();
}
}
}
| |
/*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.model.modules.typing;
import java.util.HashMap;
import java.util.HashSet;
import im.actor.model.annotation.Verified;
import im.actor.model.api.TypingType;
import im.actor.model.droidkit.actors.ActorCreator;
import im.actor.model.droidkit.actors.ActorRef;
import im.actor.model.droidkit.actors.ActorSystem;
import im.actor.model.droidkit.actors.MailboxCreator;
import im.actor.model.droidkit.actors.Props;
import im.actor.model.droidkit.actors.mailbox.Envelope;
import im.actor.model.droidkit.actors.mailbox.Mailbox;
import im.actor.model.droidkit.actors.mailbox.MailboxesQueue;
import im.actor.model.modules.Modules;
import im.actor.model.modules.utils.ModuleActor;
@Verified
public class TypingActor extends ModuleActor {
public static ActorRef get(final Modules messenger) {
return ActorSystem.system().actorOf(Props.create(TypingActor.class, new ActorCreator<TypingActor>() {
@Override
public TypingActor create() {
return new TypingActor(messenger);
}
}, new MailboxCreator() {
@Override
public Mailbox createMailbox(MailboxesQueue queue) {
return new Mailbox(queue) {
@Override
protected boolean isEqualEnvelope(Envelope a, Envelope b) {
return a.getMessage().equals(b.getMessage());
}
};
}
}), "actor/typing");
}
private static final int TYPING_TEXT_TIMEOUT = 3000;
private HashSet<Integer> typings = new HashSet<Integer>();
private HashMap<Integer, HashSet<Integer>> groupTypings = new HashMap<Integer, HashSet<Integer>>();
public TypingActor(Modules messenger) {
super(messenger);
}
@Verified
private void privateTyping(int uid, TypingType type) {
// Support only text typings
if (type != TypingType.TEXT) {
return;
}
if (getUser(uid) == null) {
return;
}
if (!typings.contains(uid)) {
typings.add(uid);
modules().getTypingModule().getTyping(uid).getTyping().change(true);
}
self().sendOnce(new StopTyping(uid), TYPING_TEXT_TIMEOUT);
}
@Verified
private void stopPrivateTyping(int uid) {
if (typings.contains(uid)) {
typings.remove(uid);
modules().getTypingModule().getTyping(uid).getTyping().change(false);
}
}
@Verified
private void groupTyping(int gid, int uid, TypingType type) {
// Support only text typings
if (type != TypingType.TEXT) {
return;
}
if (getGroup(gid) == null) {
return;
}
if (getUser(uid) == null) {
return;
}
if (!groupTypings.containsKey(gid)) {
HashSet<Integer> set = new HashSet<Integer>();
set.add(uid);
groupTypings.put(gid, set);
modules().getTypingModule()
.getGroupTyping(gid)
.getActive()
.change(new int[]{uid});
} else {
HashSet<Integer> src = groupTypings.get(gid);
if (!src.contains(uid)) {
src.add(uid);
Integer[] ids = src.toArray(new Integer[src.size()]);
int[] ids2 = new int[ids.length];
for (int i = 0; i < ids.length; i++) {
ids2[i] = ids[i];
}
modules().getTypingModule()
.getGroupTyping(gid)
.getActive()
.change(ids2);
}
}
self().sendOnce(new StopGroupTyping(gid, uid), TYPING_TEXT_TIMEOUT);
}
@Verified
private void stopGroupTyping(int gid, int uid) {
if (!groupTypings.containsKey(gid)) {
return;
}
HashSet<Integer> set = groupTypings.get(gid);
if (set.contains(uid)) {
set.remove(uid);
Integer[] ids = set.toArray(new Integer[set.size()]);
int[] ids2 = new int[ids.length];
for (int i = 0; i < ids.length; i++) {
ids2[i] = ids[i];
}
modules().getTypingModule()
.getGroupTyping(gid)
.getActive()
.change(ids2);
}
}
// Messages
@Override
public void onReceive(Object message) {
if (message instanceof PrivateTyping) {
PrivateTyping typing = (PrivateTyping) message;
privateTyping(typing.getUid(), typing.getType());
} else if (message instanceof GroupTyping) {
GroupTyping typing = (GroupTyping) message;
groupTyping(typing.getGid(), typing.getUid(), typing.getType());
} else if (message instanceof StopTyping) {
StopTyping typing = (StopTyping) message;
stopPrivateTyping(typing.getUid());
} else if (message instanceof StopGroupTyping) {
StopGroupTyping typing = (StopGroupTyping) message;
stopGroupTyping(typing.getGid(), typing.getUid());
} else {
drop(message);
}
}
public static class StopTyping {
private int uid;
public StopTyping(int uid) {
this.uid = uid;
}
public int getUid() {
return uid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StopTyping that = (StopTyping) o;
if (uid != that.uid) return false;
return true;
}
@Override
public int hashCode() {
return uid;
}
}
public static class StopGroupTyping {
private int gid;
private int uid;
public StopGroupTyping(int gid, int uid) {
this.gid = gid;
this.uid = uid;
}
public int getGid() {
return gid;
}
public int getUid() {
return uid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StopGroupTyping that = (StopGroupTyping) o;
if (gid != that.gid) return false;
if (uid != that.uid) return false;
return true;
}
@Override
public int hashCode() {
int result = gid;
result = 31 * result + uid;
return result;
}
}
public static class PrivateTyping {
private int uid;
private TypingType type;
public PrivateTyping(int uid, TypingType type) {
this.uid = uid;
this.type = type;
}
public int getUid() {
return uid;
}
public TypingType getType() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PrivateTyping that = (PrivateTyping) o;
if (type != that.type) return false;
if (uid != that.uid) return false;
return true;
}
@Override
public int hashCode() {
int result = uid;
result = 31 * result + type.getValue();
return result;
}
}
public static class GroupTyping {
private int gid;
private int uid;
private TypingType type;
public GroupTyping(int gid, int uid, TypingType type) {
this.gid = gid;
this.uid = uid;
this.type = type;
}
public int getGid() {
return gid;
}
public int getUid() {
return uid;
}
public TypingType getType() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GroupTyping that = (GroupTyping) o;
if (gid != that.gid) return false;
if (type != that.type) return false;
if (uid != that.uid) return false;
return true;
}
@Override
public int hashCode() {
int result = gid;
result = 31 * result + uid;
result = 31 * result + type.getValue();
return result;
}
}
}
| |
package org.apereo.cas.support.pac4j.config.support.authentication;
import com.github.scribejava.core.model.Verb;
import com.nimbusds.jose.JWSAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.apereo.cas.authentication.AuthenticationEventExecutionPlan;
import org.apereo.cas.authentication.AuthenticationHandler;
import org.apereo.cas.authentication.AuthenticationMetaDataPopulator;
import org.apereo.cas.authentication.principal.DefaultPrincipalFactory;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.authentication.principal.PrincipalResolver;
import org.apereo.cas.authentication.AuthenticationEventExecutionPlanConfigurer;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.support.pac4j.Pac4jProperties;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.pac4j.authentication.ClientAuthenticationMetaDataPopulator;
import org.apereo.cas.support.pac4j.authentication.handler.support.ClientAuthenticationHandler;
import org.apereo.cas.support.pac4j.web.flow.SAML2ClientLogoutAction;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.pac4j.cas.client.CasClient;
import org.pac4j.cas.config.CasConfiguration;
import org.pac4j.core.client.BaseClient;
import org.pac4j.core.client.Clients;
import org.pac4j.oauth.client.BitbucketClient;
import org.pac4j.oauth.client.DropBoxClient;
import org.pac4j.oauth.client.FacebookClient;
import org.pac4j.oauth.client.FoursquareClient;
import org.pac4j.oauth.client.GenericOAuth20Client;
import org.pac4j.oauth.client.GitHubClient;
import org.pac4j.oauth.client.Google2Client;
import org.pac4j.oauth.client.LinkedIn2Client;
import org.pac4j.oauth.client.PayPalClient;
import org.pac4j.oauth.client.TwitterClient;
import org.pac4j.oauth.client.WindowsLiveClient;
import org.pac4j.oauth.client.WordPressClient;
import org.pac4j.oauth.client.YahooClient;
import org.pac4j.oidc.client.AzureAdClient;
import org.pac4j.oidc.client.GoogleOidcClient;
import org.pac4j.oidc.client.OidcClient;
import org.pac4j.oidc.config.OidcConfiguration;
import org.pac4j.saml.client.SAML2Client;
import org.pac4j.saml.client.SAML2ClientConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.webflow.execution.Action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This is {@link Pac4jAuthenticationEventExecutionPlanConfiguration}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
@Configuration("pac4jAuthenticationEventExecutionPlanConfiguration")
public class Pac4jAuthenticationEventExecutionPlanConfiguration implements AuthenticationEventExecutionPlanConfigurer {
private static final Logger LOGGER = LoggerFactory.getLogger(Pac4jAuthenticationEventExecutionPlanConfiguration.class);
@Autowired
private CasConfigurationProperties casProperties;
@Autowired
@Qualifier("servicesManager")
private ServicesManager servicesManager;
@Autowired
@Qualifier("personDirectoryPrincipalResolver")
private PrincipalResolver personDirectoryPrincipalResolver;
private void configureGithubClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Github github = casProperties.getAuthn().getPac4j().getGithub();
if (StringUtils.isNotBlank(github.getId()) && StringUtils.isNotBlank(github.getSecret())) {
final GitHubClient client = new GitHubClient(github.getId(), github.getSecret());
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureDropboxClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Dropbox db = casProperties.getAuthn().getPac4j().getDropbox();
if (StringUtils.isNotBlank(db.getId()) && StringUtils.isNotBlank(db.getSecret())) {
final DropBoxClient client = new DropBoxClient(db.getId(), db.getSecret());
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureWindowsLiveClient(final Collection<BaseClient> properties) {
final Pac4jProperties.WindowsLive live = casProperties.getAuthn().getPac4j().getWindowsLive();
if (StringUtils.isNotBlank(live.getId()) && StringUtils.isNotBlank(live.getSecret())) {
final WindowsLiveClient client = new WindowsLiveClient(live.getId(), live.getSecret());
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureYahooClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Yahoo yahoo = casProperties.getAuthn().getPac4j().getYahoo();
if (StringUtils.isNotBlank(yahoo.getId()) && StringUtils.isNotBlank(yahoo.getSecret())) {
final YahooClient client = new YahooClient(yahoo.getId(), yahoo.getSecret());
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureFoursquareClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Foursquare foursquare = casProperties.getAuthn().getPac4j().getFoursquare();
if (StringUtils.isNotBlank(foursquare.getId()) && StringUtils.isNotBlank(foursquare.getSecret())) {
final FoursquareClient client = new FoursquareClient(foursquare.getId(), foursquare.getSecret());
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureGoogleClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Google google = casProperties.getAuthn().getPac4j().getGoogle();
final Google2Client client = new Google2Client(google.getId(), google.getSecret());
if (StringUtils.isNotBlank(google.getId()) && StringUtils.isNotBlank(google.getSecret())) {
if (StringUtils.isNotBlank(google.getScope())) {
client.setScope(Google2Client.Google2Scope.valueOf(google.getScope().toUpperCase()));
}
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureFacebookClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Facebook fb = casProperties.getAuthn().getPac4j().getFacebook();
if (StringUtils.isNotBlank(fb.getId()) && StringUtils.isNotBlank(fb.getSecret())) {
final FacebookClient client = new FacebookClient(fb.getId(), fb.getSecret());
if (StringUtils.isNotBlank(fb.getScope())) {
client.setScope(fb.getScope());
}
if (StringUtils.isNotBlank(fb.getFields())) {
client.setFields(fb.getFields());
}
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureLinkedInClient(final Collection<BaseClient> properties) {
final Pac4jProperties.LinkedIn ln = casProperties.getAuthn().getPac4j().getLinkedIn();
if (StringUtils.isNotBlank(ln.getId()) && StringUtils.isNotBlank(ln.getSecret())) {
final LinkedIn2Client client = new LinkedIn2Client(ln.getId(), ln.getSecret());
if (StringUtils.isNotBlank(ln.getScope())) {
client.setScope(ln.getScope());
}
if (StringUtils.isNotBlank(ln.getFields())) {
client.setFields(ln.getFields());
}
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureTwitterClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Twitter twitter = casProperties.getAuthn().getPac4j().getTwitter();
if (StringUtils.isNotBlank(twitter.getId()) && StringUtils.isNotBlank(twitter.getSecret())) {
final TwitterClient client = new TwitterClient(twitter.getId(), twitter.getSecret());
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureWordpressClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Wordpress wp = casProperties.getAuthn().getPac4j().getWordpress();
if (StringUtils.isNotBlank(wp.getId()) && StringUtils.isNotBlank(wp.getSecret())) {
final WordPressClient client = new WordPressClient(wp.getId(), wp.getSecret());
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureBitbucketClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Bitbucket bb = casProperties.getAuthn().getPac4j().getBitbucket();
if (StringUtils.isNotBlank(bb.getId()) && StringUtils.isNotBlank(bb.getSecret())) {
final BitbucketClient client = new BitbucketClient(bb.getId(), bb.getSecret());
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configurePaypalClient(final Collection<BaseClient> properties) {
final Pac4jProperties.Paypal paypal = casProperties.getAuthn().getPac4j().getPaypal();
if (StringUtils.isNotBlank(paypal.getId()) && StringUtils.isNotBlank(paypal.getSecret())) {
final PayPalClient client = new PayPalClient(paypal.getId(), paypal.getSecret());
LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
}
private void configureCasClient(final Collection<BaseClient> properties) {
final AtomicInteger index = new AtomicInteger();
casProperties.getAuthn().getPac4j().getCas()
.stream()
.filter(cas -> StringUtils.isNotBlank(cas.getLoginUrl()))
.forEach(cas -> {
final CasConfiguration cfg = new CasConfiguration(cas.getLoginUrl(), cas.getProtocol());
final CasClient client = new CasClient(cfg);
final int count = index.intValue();
if (count > 0) {
client.setName(client.getClass().getSimpleName() + count);
}
index.incrementAndGet();
LOGGER.debug("Created client [{}]", client);
properties.add(client);
});
}
private void configureSamlClient(final Collection<BaseClient> properties) {
final AtomicInteger index = new AtomicInteger();
casProperties.getAuthn().getPac4j().getSaml()
.stream()
.filter(saml -> StringUtils.isNotBlank(saml.getKeystorePath()) && StringUtils.isNotBlank(saml.getIdentityProviderMetadataPath()))
.forEach(saml -> {
final SAML2ClientConfiguration cfg = new SAML2ClientConfiguration(saml.getKeystorePath(), saml.getKeystorePassword(),
saml.getPrivateKeyPassword(), saml.getIdentityProviderMetadataPath());
cfg.setMaximumAuthenticationLifetime(saml.getMaximumAuthenticationLifetime());
cfg.setServiceProviderEntityId(saml.getServiceProviderEntityId());
cfg.setServiceProviderMetadataPath(saml.getServiceProviderMetadataPath());
cfg.setDestinationBindingType(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
final SAML2Client client = new SAML2Client(cfg);
final int count = index.intValue();
if (saml.getClientName() != null) {
client.setName(saml.getClientName());
} else if (count > 0) {
client.setName(client.getClass().getSimpleName() + count);
}
index.incrementAndGet();
LOGGER.debug("Created client [{}]", client);
properties.add(client);
});
}
private void configureOAuth20Client(final Collection<BaseClient> properties) {
final AtomicInteger index = new AtomicInteger();
casProperties.getAuthn().getPac4j().getOauth2()
.stream()
.filter(oauth -> StringUtils.isNotBlank(oauth.getId()) && StringUtils.isNotBlank(oauth.getSecret()))
.forEach(oauth -> {
final GenericOAuth20Client client = new GenericOAuth20Client();
client.setKey(oauth.getId());
client.setSecret(oauth.getSecret());
client.setProfileAttrs(oauth.getProfileAttrs());
client.setProfileNodePath(oauth.getProfilePath());
client.setProfileUrl(oauth.getProfileUrl());
client.setProfileVerb(Verb.valueOf(oauth.getProfileVerb().toUpperCase()));
client.setTokenUrl(oauth.getTokenUrl());
client.setAuthUrl(oauth.getAuthUrl());
client.setCustomParams(oauth.getCustomParams());
final int count = index.intValue();
if (count > 0) {
client.setName(client.getClass().getSimpleName() + count);
}
index.incrementAndGet();
LOGGER.debug("Created client [{}]", client);
properties.add(client);
});
}
private void configureOidcClient(final Collection<BaseClient> properties) {
final AtomicInteger index = new AtomicInteger();
casProperties.getAuthn().getPac4j().getOidc()
.stream()
.filter(oidc -> StringUtils.isNotBlank(oidc.getId()) && StringUtils.isNotBlank(oidc.getSecret()))
.forEach(oidc -> {
final OidcConfiguration cfg = new OidcConfiguration();
if (StringUtils.isNotBlank(oidc.getScope())) {
cfg.setScope(oidc.getScope());
}
cfg.setUseNonce(oidc.isUseNonce());
cfg.setSecret(oidc.getSecret());
cfg.setClientId(oidc.getId());
if (StringUtils.isNotBlank(oidc.getPreferredJwsAlgorithm())) {
cfg.setPreferredJwsAlgorithm(JWSAlgorithm.parse(oidc.getPreferredJwsAlgorithm().toUpperCase()));
}
cfg.setMaxClockSkew(oidc.getMaxClockSkew());
cfg.setDiscoveryURI(oidc.getDiscoveryUri());
cfg.setCustomParams(oidc.getCustomParams());
final OidcClient client;
switch (oidc.getType().toUpperCase()) {
case "GOOGLE":
client = new GoogleOidcClient(cfg);
break;
case "AZURE":
client = new AzureAdClient(cfg);
break;
case "GENERIC":
default:
client = new OidcClient(cfg);
break;
}
final int count = index.intValue();
if (count > 0) {
client.setName(client.getClass().getSimpleName() + count);
}
index.incrementAndGet();
LOGGER.debug("Created client [{}]", client);
properties.add(client);
});
}
@RefreshScope
@Bean
public Clients builtClients() {
final Set<BaseClient> clients = new LinkedHashSet<>();
configureCasClient(clients);
configureFacebookClient(clients);
configureOidcClient(clients);
configureOAuth20Client(clients);
configureSamlClient(clients);
configureTwitterClient(clients);
configureDropboxClient(clients);
configureFoursquareClient(clients);
configureGithubClient(clients);
configureGoogleClient(clients);
configureWindowsLiveClient(clients);
configureYahooClient(clients);
configureLinkedInClient(clients);
configurePaypalClient(clients);
configureWordpressClient(clients);
configureBitbucketClient(clients);
LOGGER.debug("The following clients are built: [{}]", clients);
if (clients.isEmpty()) {
LOGGER.warn("No delegated authentication clients are defined/configured");
}
LOGGER.info("Located and prepared [{}] delegated authentication client(s)", clients.size());
return new Clients(casProperties.getServer().getLoginUrl(), new ArrayList<>(clients));
}
@ConditionalOnMissingBean(name = "clientPrincipalFactory")
@Bean
public PrincipalFactory clientPrincipalFactory() {
return new DefaultPrincipalFactory();
}
@Bean
public AuthenticationMetaDataPopulator clientAuthenticationMetaDataPopulator() {
return new ClientAuthenticationMetaDataPopulator();
}
@Bean
public Action saml2ClientLogoutAction() {
return new SAML2ClientLogoutAction(builtClients());
}
@RefreshScope
@Bean
public AuthenticationHandler clientAuthenticationHandler() {
final ClientAuthenticationHandler h = new ClientAuthenticationHandler(casProperties.getAuthn().getPac4j().getName(), servicesManager,
clientPrincipalFactory(), builtClients());
h.setTypedIdUsed(casProperties.getAuthn().getPac4j().isTypedIdUsed());
return h;
}
@Override
public void configureAuthenticationExecutionPlan(final AuthenticationEventExecutionPlan plan) {
if (!builtClients().findAllClients().isEmpty()) {
LOGGER.info("Registering delegated authentication clients...");
plan.registerAuthenticationHandlerWithPrincipalResolver(clientAuthenticationHandler(), personDirectoryPrincipalResolver);
plan.registerMetadataPopulator(clientAuthenticationMetaDataPopulator());
}
}
}
| |
package org.plovr;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Map;
import org.plovr.ModuleConfig.BadDependencyTreeException;
import org.plovr.webdriver.ReflectionWebDriverFactory;
import org.plovr.webdriver.WebDriverFactory;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.CustomPassExecutionTime;
import com.google.javascript.jscomp.WarningLevel;
public enum ConfigOption {
// DO NOT alpha-sort this list!
// The enum order is the order in which these options appear in the generated
// HTML documentation, so the most important options are deliberately listed
// first.
ID("id", new ConfigUpdater() {
@Override
public void apply(String id, Config.Builder builder) {
builder.setId(id);
}
}),
INPUTS("inputs", new ConfigUpdater() {
@Override
public void apply(String input, Config.Builder builder) {
builder.addInputByName(input);
}
@Override
public void apply(JsonArray inputs, Config.Builder builder) {
for (JsonElement item : inputs) {
String input = GsonUtil.stringOrNull(item);
if (input != null) {
apply(input, builder);
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetInputs();
return true;
}
}),
PATHS("paths", new ConfigUpdater() {
@Override
public void apply(String path, Config.Builder builder) {
File resolvedPath = maybeResolvePathFile(path, builder);
builder.addPath(new ConfigPath(resolvedPath, path));
}
@Override
public void apply(JsonArray paths, Config.Builder builder) {
for (JsonElement item : paths) {
String path = GsonUtil.stringOrNull(item);
if (path != null) {
apply(path, builder);
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetPaths();
return true;
}
}),
EXTERNS("externs", new ConfigUpdater() {
@Override
public void apply(String extern, Config.Builder builder) {
if (extern.startsWith("//")) {
builder.addBuiltInExtern(extern);
} else {
String resolvedPath = maybeResolvePath(extern, builder);
builder.addExtern(resolvedPath);
}
}
@Override
public void apply(JsonArray externs, Config.Builder builder) {
for (JsonElement item : externs) {
String extern = GsonUtil.stringOrNull(item);
if (extern != null) {
apply(extern, builder);
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetExterns();
return true;
}
}),
CUSTOM_EXTERNS_ONLY("custom-externs-only", new ConfigUpdater() {
@Override
public void apply(boolean customExternsOnly, Config.Builder builder) {
builder.setCustomExternsOnly(customExternsOnly);
}
}),
CLOSURE_LIBRARY("closure-library", new ConfigUpdater() {
@Override
public void apply(String path, Config.Builder builder) {
String resolvedPath = maybeResolvePath(path, builder);
builder.setPathToClosureLibrary(resolvedPath);
}
}),
EXCLUDE_CLOSURE_LIBRARY("experimental-exclude-closure-library", new ConfigUpdater() {
@Override
public void apply(boolean excludeClosureLibrary, Config.Builder builder) {
builder.setExcludeClosureLibrary(excludeClosureLibrary);
}
}),
COMPILATION_MODE("mode", new ConfigUpdater() {
@Override
public void apply(String mode, Config.Builder builder) {
try {
CompilationMode compilationMode = CompilationMode.valueOf(mode.toUpperCase());
builder.setCompilationMode(compilationMode);
} catch (IllegalArgumentException e) {
// OK
}
}
@Override
public boolean update(String mode, Config.Builder builder) {
apply(mode, builder);
return true;
}
}),
WARNING_LEVEL("level", new ConfigUpdater() {
@Override
public void apply(String level, Config.Builder builder) {
try {
WarningLevel warningLevel = WarningLevel.valueOf(level.toUpperCase());
builder.setWarningLevel(warningLevel);
} catch (IllegalArgumentException e) {
// OK
}
}
@Override
public boolean update(String level, Config.Builder builder) {
apply(level, builder);
return true;
}
}),
INHERITS("inherits", new ConfigUpdater() {
@Override
public void apply(String mode, Config.Builder builder) {
// Do nothing: this option is handled in a special way in ConfigParser.
// This entry exists so that it is included in the generated options
// documentation.
}
}),
DEBUG("debug", new ConfigUpdater() {
@Override
public void apply(boolean debug, Config.Builder builder) {
builder.setDebugOptions(debug);
}
@Override
public boolean update(String debugParam, Config.Builder builder) {
boolean debug = Boolean.valueOf(debugParam);
builder.setDebugOptions(debug);
return true;
}
}),
PRETTY_PRINT("pretty-print", new ConfigUpdater() {
@Override
public void apply(boolean prettyPrint, Config.Builder builder) {
builder.setPrettyPrint(prettyPrint);
}
@Override
public boolean update(String prettyPrintParam, Config.Builder builder) {
boolean prettyPrint = Boolean.valueOf(prettyPrintParam);
builder.setPrettyPrint(prettyPrint);
return true;
}
}),
PRINT_INPUT_DELIMITER("print-input-delimiter", new ConfigUpdater() {
@Override
public void apply(boolean printInputDelimiter, Config.Builder builder) {
builder.setPrintInputDelimiter(printInputDelimiter);
}
@Override
public boolean update(String printInputDelimiterParam, Config.Builder builder) {
boolean printInputDelimiter = Boolean.valueOf(printInputDelimiterParam);
builder.setPrintInputDelimiter(printInputDelimiter);
return true;
}
}),
OUTPUT_FILE("output-file", new ConfigUpdater() {
@Override
public void apply(String outputFilePath, Config.Builder builder) {
File outputFile = (outputFilePath == null) ? null :
new File(maybeResolvePath(outputFilePath, builder));
builder.setOutputFile(outputFile);
}
}),
OUTPUT_WRAPPER("output-wrapper", new ConfigUpdater() {
@Override
public void apply(String outputWrapper, Config.Builder builder) {
builder.setOutputWrapper(outputWrapper);
}
/**
* output-wrapper can also be an array of strings that will be
* concatenated together.
*/
@Override
public void apply(JsonArray outputWrapperParts, Config.Builder builder) {
StringBuilder outputWrapper = new StringBuilder();
for (JsonElement item : outputWrapperParts) {
outputWrapper.append(GsonUtil.stringOrNull(item));
}
apply(outputWrapper.toString(), builder);
}
}),
OUTPUT_CHARSET("output-charset", new ConfigUpdater() {
@Override
public void apply(String outputCharset, Config.Builder builder) {
builder.setOutputCharset(Charset.forName(outputCharset));
}
}),
FINGERPRINT("fingerprint", new ConfigUpdater() {
@Override
public void apply(boolean fingerprint, Config.Builder builder) {
builder.setFingerprintJsFiles(fingerprint);
}
}),
MODULES("modules", new ConfigUpdater() {
@Override
public void apply(JsonObject modules, Config.Builder builder) {
try {
ModuleConfig.Builder moduleConfigBuilder = builder.getModuleConfigBuilder();
moduleConfigBuilder.setModuleInfo(modules);
} catch (BadDependencyTreeException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetModuleConfigBuilder();
return true;
}
}),
MODULE_OUTPUT_PATH("module-output-path", new ConfigUpdater() {
@Override
public void apply(String outputPath, Config.Builder builder) {
ModuleConfig.Builder moduleConfigBuilder = builder.getModuleConfigBuilder();
moduleConfigBuilder.setOutputPath(outputPath);
}
}),
MODULE_PRODUCTION_URI("module-production-uri", new ConfigUpdater() {
@Override
public void apply(String productionUri, Config.Builder builder) {
ModuleConfig.Builder moduleConfigBuilder = builder.getModuleConfigBuilder();
moduleConfigBuilder.setProductionUri(productionUri);
}
}),
/**
* This option is used to write the plovr module info JS into a separate file
* instead of prepending it to the root module. Prepending the JS causes the
* source map to be several lines off in the root module, so doing this avoids
* that issue.
*/
// TODO(bolinfest): A better approach may be to fix the source map, in which
// case this option could be eliminated.
// Note: even if sourcemaps are fixed, this option should still be supported:
// http://code.google.com/p/plovr/issues/detail?id=41
// http://code.google.com/p/plovr/issues/detail?id=50
MODULE_INFO_PATH("module-info-path",
new ConfigUpdater() {
@Override
public void apply(String moduleInfoPath, Config.Builder builder) {
ModuleConfig.Builder moduleConfigBuilder = builder.getModuleConfigBuilder();
moduleConfigBuilder.setModuleInfoPath(moduleInfoPath);
}
}),
GLOBAL_SCOPE_NAME("global-scope-name", new ConfigUpdater() {
@Override
public void apply(String scope, Config.Builder builder) {
builder.setGlobalScopeName(scope);
}
}),
DEFINE("define", new ConfigUpdater() {
@Override
public void apply(JsonObject obj, Config.Builder builder) {
for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
JsonElement element = entry.getValue();
if (element.isJsonPrimitive()) {
String name = entry.getKey();
builder.addDefine(name, element.getAsJsonPrimitive());
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetDefines();
return true;
}
}),
DIAGNOSTIC_GROUPS("checks", new ConfigUpdater() {
@Override
public void apply(JsonObject obj, Config.Builder builder) {
Map<String, CheckLevel> groups = Maps.newHashMap();
for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
String checkLevelString = GsonUtil.stringOrNull(entry.getValue());
if (checkLevelString == null) {
continue;
}
CheckLevel checkLevel = CheckLevel.valueOf(checkLevelString.toUpperCase());
groups.put(entry.getKey(), checkLevel);
}
builder.setCheckLevelsForDiagnosticGroups(groups);
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetChecks();
return true;
}
}),
TREAT_WARNINGS_AS_ERRORS("treat-warnings-as-errors", new ConfigUpdater() {
@Override
public void apply(boolean treatWarningsAsErrors, Config.Builder builder) {
builder.setTreatWarningsAsErrors(treatWarningsAsErrors);
}
}),
EXPORT_TEST_FUNCTIONS("export-test-functions", new ConfigUpdater() {
@Override
public void apply(boolean exportTestFunctions, Config.Builder builder) {
builder.setExportTestFunctions(exportTestFunctions);
}
}),
NAME_SUFFIXES_TO_STRIP("name-suffixes-to-strip", new ConfigUpdater() {
@Override
public void apply(String suffix, Config.Builder builder) {
JsonArray suffixes = new JsonArray();
suffixes.add(new JsonPrimitive(suffix));
apply(suffixes, builder);
}
@Override
public void apply(JsonArray suffixes, Config.Builder builder) {
ImmutableSet.Builder<String> suffixesBuilder = ImmutableSet.builder();
for (JsonElement item : suffixes) {
String suffix = GsonUtil.stringOrNull(item);
if (suffix != null) {
suffixesBuilder.add(suffix);
}
}
builder.setStripNameSuffixes(suffixesBuilder.build());
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetStripNameSuffixes();
return true;
}
}),
TYPE_PREFIXES_TO_STRIP("type-prefixes-to-strip", new ConfigUpdater() {
@Override
public void apply(String type, Config.Builder builder) {
JsonArray types = new JsonArray();
types.add(new JsonPrimitive(type));
apply(types, builder);
}
@Override
public void apply(JsonArray types, Config.Builder builder) {
ImmutableSet.Builder<String> typesBuilder = ImmutableSet.builder();
for (JsonElement item : types) {
String type = GsonUtil.stringOrNull(item);
if (type != null) {
typesBuilder.add(type);
}
}
builder.setStripTypePrefixes(typesBuilder.build());
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetStripTypePrefixes();
return true;
}
}),
ID_GENERATORS("id-generators", new ConfigUpdater() {
@Override
public void apply(String idGenerator, Config.Builder builder) {
JsonArray idGenerators = new JsonArray();
idGenerators.add(new JsonPrimitive(idGenerator));
apply(idGenerators, builder);
}
@Override
public void apply(JsonArray idGenerators, Config.Builder builder) {
ImmutableSet.Builder<String> idGeneratorsBuilder = ImmutableSet.builder();
for (JsonElement item : idGenerators) {
String idGenerator = GsonUtil.stringOrNull(item);
if (idGenerator != null) {
idGeneratorsBuilder.add(idGenerator);
}
}
builder.setIdGenerators(idGeneratorsBuilder.build());
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetIdGenerators();
return true;
}
}),
AMBIGUATE_PROPERTIES("ambiguate-properties", new ConfigUpdater() {
@Override
public void apply(boolean ambiguateProperties, Config.Builder builder) {
builder.setAmbiguateProperties(ambiguateProperties);
}
}),
DISAMBIGUATE_PROPERTIES("disambiguate-properties", new ConfigUpdater() {
@Override
public void apply(boolean disambiguateProperties, Config.Builder builder) {
builder.setDisambiguateProperties(disambiguateProperties);
}
}),
EXPERIMENTAL_COMPILER_OPTIONS("experimental-compiler-options", new ConfigUpdater() {
@Override
public void apply(JsonObject value, Config.Builder builder) {
builder.setExperimentalCompilerOptions(value);
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetExperimentalCompilerOptions();
return true;
}
}),
CUSTOM_PASSES("custom-passes", new ConfigUpdater() {
@Override
public void apply(JsonArray value, Config.Builder builder) {
ImmutableListMultimap.Builder<CustomPassExecutionTime, CompilerPassFactory>
customPasses = ImmutableListMultimap.builder();
Gson gson = new GsonBuilder().
registerTypeAdapter(CustomPassConfig.class,
new CustomPassConfig.CustomPassConfigDeserializer())
.create();
for (JsonElement entry : value) {
CustomPassConfig pass = gson.fromJson(entry, CustomPassConfig.class);
Class<?> clazz;
try {
clazz = Class.forName(pass.getClassName());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
CompilerPassFactory factory = new CompilerPassFactory(clazz);
customPasses.put(pass.getWhen(), factory);
}
builder.setCustomPasses(customPasses.build());
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetCustomPasses();
return true;
}
}),
SOY_FUNCTION_PLUGINS("soy-function-plugins", new ConfigUpdater() {
@Override
public void apply(String input, Config.Builder builder) {
builder.addSoyFunctionPlugin(input);
}
@Override
public void apply(JsonArray inputs, Config.Builder builder) {
for (JsonElement item : inputs) {
String input = GsonUtil.stringOrNull(item);
if (input != null) {
apply(input, builder);
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetSoyFunctionPlugins();
return true;
}
}),
SOY_USE_INJECTED_DATA("soy-use-injected-data", new ConfigUpdater() {
@Override
public void apply(boolean soyUseInjectedData, Config.Builder builder) {
builder.setSoyUseInjectedData(soyUseInjectedData);
}
@Override
public boolean update(String soyUseInjectedDataParam, Config.Builder builder) {
boolean soyUseInjectedData = Boolean.valueOf(soyUseInjectedDataParam);
builder.setSoyUseInjectedData(soyUseInjectedData);
return true;
}
}),
JSDOC_HTML_OUTPUT_PATH("jsdoc-html-output-path", new ConfigUpdater() {
@Override
public void apply(String jsDocHtmlOutputPath, Config.Builder builder) {
String fullPath = maybeResolvePath(jsDocHtmlOutputPath, builder);
builder.setDocumentationOutputDirectory(new File(fullPath));
}
}),
VARIABLE_MAP_INPUT_FILE("variable-map-input-file", new ConfigUpdater() {
@Override
public void apply(String file, Config.Builder builder) {
File inputFile = (file == null) ? null :
new File(maybeResolvePath(file, builder));
builder.setVariableMapInputFile(inputFile);
}
}),
VARIABLE_MAP_OUTPUT_FILE("variable-map-output-file", new ConfigUpdater() {
@Override
public void apply(String file, Config.Builder builder) {
File outputFile = (file == null) ? null :
new File(maybeResolvePath(file, builder));
builder.setVariableMapOutputFile(outputFile);
}
}),
PROPERTY_MAP_INPUT_FILE("property-map-input-file", new ConfigUpdater() {
@Override
public void apply(String file, Config.Builder builder) {
File inputFile = (file == null) ? null :
new File(maybeResolvePath(file, builder));
builder.setPropertyMapInputFile(inputFile);
}
}),
PROPERTY_MAP_OUTPUT_FILE("property-map-output-file", new ConfigUpdater() {
@Override
public void apply(String file, Config.Builder builder) {
File outputFile = (file == null) ? null :
new File(maybeResolvePath(file, builder));
builder.setPropertyMapOutputFile(outputFile);
}
}),
TEST_DRIVERS("test-drivers", new ConfigUpdater() {
@Override
public void apply(JsonObject driver, Config.Builder builder) {
String clazz = driver.get("class").getAsString();
WebDriverFactory factory = new ReflectionWebDriverFactory(clazz);
builder.addTestDriverFactory(factory);
}
@Override
public void apply(JsonArray drivers, Config.Builder builder) {
for (JsonElement item : drivers) {
apply(item.getAsJsonObject(), builder);
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetTestDrivers();
return true;
}
}),
TEST_TEMPLATE("test-template", new ConfigUpdater() {
@Override
public void apply(String path, Config.Builder builder) {
String resolvedPath = maybeResolvePath(path, builder);
builder.setTestTemplate(new File(resolvedPath));
}
}),
TEST_EXCLUDES("test-excludes", new ConfigUpdater() {
@Override
public void apply(String path, Config.Builder builder) {
String resolvedPath = maybeResolvePath(path, builder);
builder.addTestExcludePath(new File(resolvedPath));
}
@Override
public void apply(JsonArray paths, Config.Builder builder) {
for (JsonElement item : paths) {
String path = GsonUtil.stringOrNull(item);
if (path != null) {
apply(path, builder);
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetTestExcludePaths();
return true;
}
}),
/************************* CSS OPTIONS *************************/
CSS_INPUTS("css-inputs", new ConfigUpdater() {
@Override
public void apply(String input, Config.Builder builder) {
String resolvedPath = maybeResolvePath(input, builder);
builder.addCssInput(new File(resolvedPath));
}
@Override
public void apply(JsonArray inputs, Config.Builder builder) {
for (JsonElement item : inputs) {
String path = GsonUtil.stringOrNull(item);
if (path != null) {
apply(path, builder);
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetCssInputs();
return true;
}
}),
CSS_DEFINES("css-defines", new ConfigUpdater() {
@Override
public void apply(String define, Config.Builder builder) {
builder.addCssDefine(define);
}
@Override
public void apply(JsonArray inputs, Config.Builder builder) {
for (JsonElement item : inputs) {
String define = GsonUtil.stringOrNull(item);
if (define != null) {
apply(define, builder);
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetCssDefines();
return true;
}
}),
CSS_ALLOWED_UNRECOGNIZED_PROPERTIES("css-allowed-unrecognized-properties",
new ConfigUpdater() {
@Override
public void apply(String property, Config.Builder builder) {
builder.addAllowedUnrecognizedProperty(property);
}
@Override
public void apply(JsonArray properties, Config.Builder builder) {
for (JsonElement item : properties) {
String property = GsonUtil.stringOrNull(item);
if (property != null) {
apply(property, builder);
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetAllowedUnrecognizedProperties();
return true;
}
}),
CSS_ALLOWED_NON_STANDARD_FUNCTIONS("css-allowed-non-standard-functions",
new ConfigUpdater() {
@Override
public void apply(String function, Config.Builder builder) {
builder.addAllowedNonStandardCssFunction(function);
}
@Override
public void apply(JsonArray functions, Config.Builder builder) {
for (JsonElement item : functions) {
String function = GsonUtil.stringOrNull(item);
if (function != null) {
apply(function, builder);
}
}
}
@Override
public boolean reset(Config.Builder builder) {
builder.resetAllowedNonStandardCssFunctions();
return true;
}
}),
CSS_GSS_FUNCTION_MAP_PROVIDER("css-gss-function-map-provider",
new ConfigUpdater() {
@Override
public void apply(String functionMapProviderClass, Config.Builder builder) {
builder.setGssFunctionMapProvider(functionMapProviderClass);
}
}),
CSS_OUTPUT_FILE("css-output-file", new ConfigUpdater() {
@Override
public void apply(String outputFilePath, Config.Builder builder) {
File outputFile = (outputFilePath == null) ? null :
new File(maybeResolvePath(outputFilePath, builder));
builder.setCssOutputFile(outputFile);
}
}),
;
private static class ConfigUpdater {
public void apply(String json, Config.Builder builder) {
throw new UnsupportedOperationException();
}
public void apply(boolean value, Config.Builder builder) {
throw new UnsupportedOperationException();
}
public void apply(Number value, Config.Builder builder) {
throw new UnsupportedOperationException();
}
public void apply(JsonArray value, Config.Builder builder) {
throw new UnsupportedOperationException();
}
public void apply(JsonObject value, Config.Builder builder) {
throw new UnsupportedOperationException();
}
private void apply(JsonElement json, Config.Builder builder) {
if (json.isJsonPrimitive()) {
JsonPrimitive primitive = json.getAsJsonPrimitive();
if (primitive.isString()) {
apply(primitive.getAsString(), builder);
} else if (primitive.isBoolean()) {
apply(primitive.getAsBoolean(), builder);
} else if (primitive.isNumber()) {
apply(primitive.getAsNumber(), builder);
}
} else if (json.isJsonArray()) {
apply(json.getAsJsonArray(), builder);
} else if (json.isJsonObject()) {
apply(json.getAsJsonObject(), builder);
}
}
/**
* Only override this method if this option can be overridden using query
* data.
* @param queryDataValue
* @param builder
*/
public boolean update(String queryDataValue, Config.Builder builder) {
// By default, does nothing. Only override if it is safe to update the
// Config using a query data parameter, which anyone could pass in.
return false;
}
public boolean reset(Config.Builder builder) {
return false;
}
}
private final String name;
private final ConfigUpdater configUpdater;
ConfigOption(String name, ConfigUpdater configUpdater) {
this.name = name;
this.configUpdater = configUpdater;
}
public String getName() {
return name;
}
public void update(Config.Builder builder, JsonElement json) {
if (json == null) {
return;
}
configUpdater.apply(json, builder);
}
/**
* @return true to indicate that the parameter was processed
*/
public boolean update(Config.Builder builder, QueryData data) {
String value = data.getParam(name);
if (value == null) {
return false;
}
return configUpdater.update(value, builder);
}
/**
* Reset the values associated with this option in the specified builder.
* This is important for config inheritance to ensure that a sub-config
* completely overrides an option from its parent config.
* @param builder
*/
public boolean reset(Config.Builder builder) {
return configUpdater.reset(builder);
}
/**
* Config files often contain relative paths, so it is important to resolve
* them against the directory that contains the config file when that is the
* case.
*
* @param path
* @param builder
* @return
*/
static String maybeResolvePath(String path, Config.Builder builder) {
return maybeResolvePath(path, builder.getRelativePathBase());
}
static String maybeResolvePath(String path, File relativePathBase) {
// Unfortunately, a File object must be constructed in order to determine
// whether the path is absolute.
File file = new File(path);
if (file.isAbsolute()) {
return path;
} else {
return (new File(relativePathBase, path)).getAbsolutePath();
}
}
static File maybeResolvePathFile(String path, Config.Builder builder) {
return maybeResolvePathFile(path, builder.getRelativePathBase());
}
static File maybeResolvePathFile(String path, File relativePathBase) {
// Unfortunately, a File object must be constructed in order to determine
// whether the path is absolute.
File file = new File(path);
if (file.isAbsolute()) {
return file;
} else {
return new File(relativePathBase, path);
}
}
static void assertContainsModuleNamePlaceholder(String path) {
if (path == null || !path.contains("%s")) {
throw new IllegalArgumentException("Does not contain %s: " + path);
}
}
}
| |
/*
* Copyright 2013-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.bootstrap.config;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
/**
* @author Dave Syer
*
*/
public class BootstrapConfigurationTests {
private ConfigurableApplicationContext context;
@Rule
public ExpectedException expected = ExpectedException.none();
@After
public void close() {
// Expected.* is bound to the PropertySourceConfiguration below
System.clearProperty("expected.name");
System.clearProperty("expected.fail");
// Used to test system properties override
System.clearProperty("bootstrap.foo");
PropertySourceConfiguration.MAP.clear();
if (this.context != null) {
this.context.close();
}
}
@Test
public void pickupExternalBootstrapProperties() {
String externalPropertiesPath = getExternalProperties();
this.context = new SpringApplicationBuilder().web(false)
.sources(BareConfiguration.class)
.properties("spring.cloud.bootstrap.location:" + externalPropertiesPath)
.run();
assertEquals("externalPropertiesInfoName", this.context.getEnvironment()
.getProperty("info.name"));
assertTrue(this.context.getEnvironment().getPropertySources()
.contains("bootstrap"));
}
/**
* Running the test from maven will start from a different directory then starting it
* from intellij
*
* @return
*/
private String getExternalProperties() {
String externalPropertiesPath = "";
File externalProperties = new File(
"src/test/resources/external-properties/bootstrap.properties");
if (externalProperties.exists()) {
externalPropertiesPath = externalProperties.getAbsolutePath();
}
else {
externalProperties = new File(
"spring-cloud-config-client/src/test/resources/external-properties/bootstrap.properties");
externalPropertiesPath = externalProperties.getAbsolutePath();
}
return externalPropertiesPath;
}
@Test
public void picksUpAdditionalPropertySource() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
System.setProperty("expected.name", "bootstrap");
this.context = new SpringApplicationBuilder().web(false)
.sources(BareConfiguration.class).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
assertTrue(this.context.getEnvironment().getPropertySources()
.contains("bootstrap"));
}
@Test
public void failsOnPropertySource() {
System.setProperty("expected.fail", "true");
this.expected.expectMessage("Planned");
this.context = new SpringApplicationBuilder().web(false)
.sources(BareConfiguration.class).run();
}
@Test
public void overrideSystemPropertySourceByDefault() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(false)
.sources(BareConfiguration.class).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
}
@Test
public void systemPropertyOverrideFalse() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
PropertySourceConfiguration.MAP.put(
"spring.cloud.config.overrideSystemProperties", "false");
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(false)
.sources(BareConfiguration.class).run();
assertEquals("system", this.context.getEnvironment().getProperty("bootstrap.foo"));
}
@Test
public void systemPropertyOverrideWhenOverrideDisallowed() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
PropertySourceConfiguration.MAP.put(
"spring.cloud.config.overrideSystemProperties", "false");
// If spring.cloud.config.allowOverride=false is in the remote property sources
// with sufficiently high priority it always wins. Admins can enforce it by adding
// their own remote property source.
PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "false");
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(false)
.sources(BareConfiguration.class).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
}
@Test
public void systemPropertyOverrideFalseWhenOverrideAllowed() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
PropertySourceConfiguration.MAP.put(
"spring.cloud.config.overrideSystemProperties", "false");
PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "true");
System.setProperty("bootstrap.foo", "system");
this.context = new SpringApplicationBuilder().web(false)
.sources(BareConfiguration.class).run();
assertEquals("system", this.context.getEnvironment().getProperty("bootstrap.foo"));
}
@Test
public void overrideAllWhenOverrideAllowed() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
PropertySourceConfiguration.MAP.put("spring.cloud.config.overrideNone", "true");
PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "true");
ConfigurableEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addLast(
new MapPropertySource("last", Collections.<String, Object> singletonMap(
"bootstrap.foo", "splat")));
this.context = new SpringApplicationBuilder().web(false).environment(environment)
.sources(BareConfiguration.class).run();
assertEquals("splat", this.context.getEnvironment().getProperty("bootstrap.foo"));
}
@Test
public void applicationNameInBootstrapAndMain() {
System.setProperty("expected.name", "main");
this.context = new SpringApplicationBuilder()
.web(false)
.properties("spring.cloud.bootstrap.name:other",
"spring.config.name:plain").sources(BareConfiguration.class)
.run();
assertEquals("app",
this.context.getEnvironment().getProperty("spring.application.name"));
// The parent is called "main" because spring.application.name is specified in
// other.properties (the bootstrap properties)
assertEquals(
"main",
this.context.getParent().getEnvironment()
.getProperty("spring.application.name"));
// The bootstrap context has a different "bootstrap" property source
assertNotSame(
this.context.getEnvironment().getPropertySources().get("bootstrap"),
((ConfigurableEnvironment) this.context.getParent().getEnvironment())
.getPropertySources().get("bootstrap"));
assertEquals("app", this.context.getId());
}
@Test
public void applicationNameNotInBootstrap() {
System.setProperty("expected.name", "main");
this.context = new SpringApplicationBuilder()
.web(false)
.properties("spring.cloud.bootstrap.name:application",
"spring.config.name:other").sources(BareConfiguration.class)
.run();
assertEquals("main",
this.context.getEnvironment().getProperty("spring.application.name"));
// The parent is called "application" because spring.application.name is not
// defined in the bootstrap properties
assertEquals("application", this.context.getParent().getEnvironment()
.getProperty("spring.application.name"));
}
@Test
public void applicationNameOnlyInBootstrap() {
System.setProperty("expected.name", "main");
this.context = new SpringApplicationBuilder().web(false)
.properties("spring.cloud.bootstrap.name:other")
.sources(BareConfiguration.class).run();
// The main context is called "main" because spring.application.name is specified
// in other.properties (and not in the main config file)
assertEquals("main",
this.context.getEnvironment().getProperty("spring.application.name"));
// The parent is called "main" because spring.application.name is specified in
// other.properties (the bootstrap properties this time)
assertEquals(
"main",
this.context.getParent().getEnvironment()
.getProperty("spring.application.name"));
assertEquals("main", this.context.getId());
}
@Test
public void environmentEnrichedOnceWhenSharedWithChildContext() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
.environment(new StandardEnvironment()).child(BareConfiguration.class)
.web(false).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
assertEquals(this.context.getEnvironment(), this.context.getParent()
.getEnvironment());
MutablePropertySources sources = this.context.getEnvironment()
.getPropertySources();
PropertySource<?> bootstrap = sources.get("bootstrap");
assertNotNull(bootstrap);
assertEquals(0, sources.precedenceOf(bootstrap));
}
@Test
public void environmentEnrichedInParentContext() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
this.context = new SpringApplicationBuilder().sources(BareConfiguration.class)
.child(BareConfiguration.class).web(false).run();
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
assertNotSame(this.context.getEnvironment(), this.context.getParent()
.getEnvironment());
assertTrue(this.context.getEnvironment().getPropertySources()
.contains("bootstrap"));
assertTrue(((ConfigurableEnvironment) this.context.getParent().getEnvironment())
.getPropertySources().contains("bootstrap"));
}
@Test
public void differentProfileInChild() {
PropertySourceConfiguration.MAP.put("bootstrap.foo", "bar");
// Profiles are always merged with the child
ConfigurableApplicationContext parent = new SpringApplicationBuilder()
.sources(BareConfiguration.class).profiles("parent").web(false).run();
this.context = new SpringApplicationBuilder(BareConfiguration.class)
.profiles("child").parent(parent).web(false).run();
assertNotSame(this.context.getEnvironment(), this.context.getParent()
.getEnvironment());
// The ApplicationContext merges profiles (profiles and property sources), see
// AbstractEnvironment.merge()
assertTrue(this.context.getEnvironment().acceptsProfiles("child", "parent"));
// But the parent is not a child
assertFalse(this.context.getParent().getEnvironment().acceptsProfiles("child"));
assertTrue(this.context.getParent().getEnvironment().acceptsProfiles("parent"));
assertTrue(((ConfigurableEnvironment) this.context.getParent().getEnvironment())
.getPropertySources().contains("bootstrap"));
assertEquals("bar", this.context.getEnvironment().getProperty("bootstrap.foo"));
// The "bootstrap" property source is not shared now, but it has the same
// properties in it because they are pulled from the PropertySourceConfiguration
// below
assertEquals("bar",
this.context.getParent().getEnvironment().getProperty("bootstrap.foo"));
// The parent property source is there in the child because they are both in the
// "parent" profile (by virtue of the merge in AbstractEnvironment)
assertEquals("parent", this.context.getEnvironment().getProperty("info.name"));
}
@Configuration
@EnableConfigurationProperties
protected static class BareConfiguration {
}
@Configuration
@ConfigurationProperties("expected")
// This is added to bootstrap context as a source in bootstrap.properties
protected static class PropertySourceConfiguration implements PropertySourceLocator {
public static Map<String, Object> MAP = new HashMap<String, Object>(
Collections.<String, Object> singletonMap("bootstrap.foo", "bar"));
private String name;
private boolean fail = false;
@Override
public PropertySource<?> locate(Environment environment) {
if (this.name != null) {
assertEquals(this.name,
environment.getProperty("spring.application.name"));
}
if (this.fail) {
throw new RuntimeException("Planned");
}
return new MapPropertySource("testBootstrap", MAP);
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFail() {
return this.fail;
}
public void setFail(boolean fail) {
this.fail = fail;
}
}
}
| |
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.context.properties.bind;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link Bindable}.
*
* @author Phillip Webb
* @author Madhura Bhave
*/
public class BindableTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void ofClassWhenTypeIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must not be null");
Bindable.of((Class<?>) null);
}
@Test
public void ofTypeWhenTypeIsNullShouldThrowException() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("Type must not be null");
Bindable.of((ResolvableType) null);
}
@Test
public void ofClassShouldSetType() throws Exception {
assertThat(Bindable.of(String.class).getType())
.isEqualTo(ResolvableType.forClass(String.class));
}
@Test
public void ofTypeShouldSetType() throws Exception {
ResolvableType type = ResolvableType.forClass(String.class);
assertThat(Bindable.of(type).getType()).isEqualTo(type);
}
@Test
public void ofInstanceShouldSetTypeAndExistingValue() throws Exception {
String instance = "foo";
ResolvableType type = ResolvableType.forClass(String.class);
assertThat(Bindable.ofInstance(instance).getType()).isEqualTo(type);
assertThat(Bindable.ofInstance(instance).getValue().get()).isEqualTo("foo");
}
@Test
public void ofClassWithExistingValueShouldSetTypeAndExistingValue() throws Exception {
assertThat(Bindable.of(String.class).withExistingValue("foo").getValue().get())
.isEqualTo("foo");
}
@Test
public void ofTypeWithExistingValueShouldSetTypeAndExistingValue() throws Exception {
assertThat(Bindable.of(ResolvableType.forClass(String.class))
.withExistingValue("foo").getValue().get()).isEqualTo("foo");
}
@Test
public void ofTypeWhenExistingValueIsNotInstanceOfTypeShouldThrowException()
throws Exception {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage(
"ExistingValue must be an instance of " + String.class.getName());
Bindable.of(ResolvableType.forClass(String.class)).withExistingValue(123);
}
@Test
public void ofTypeWhenPrimitiveWithExistingValueWrapperShouldNotThrowException()
throws Exception {
Bindable<Integer> bindable = Bindable
.<Integer>of(ResolvableType.forClass(int.class)).withExistingValue(123);
assertThat(bindable.getType().resolve()).isEqualTo(int.class);
assertThat(bindable.getValue().get()).isEqualTo(123);
}
@Test
public void getBoxedTypeWhenNotBoxedShouldReturnType() throws Exception {
Bindable<String> bindable = Bindable.of(String.class);
assertThat(bindable.getBoxedType())
.isEqualTo(ResolvableType.forClass(String.class));
}
@Test
public void getBoxedTypeWhenPrimitiveShouldReturnBoxedType() throws Exception {
Bindable<Integer> bindable = Bindable.of(int.class);
assertThat(bindable.getType()).isEqualTo(ResolvableType.forClass(int.class));
assertThat(bindable.getBoxedType())
.isEqualTo(ResolvableType.forClass(Integer.class));
}
@Test
public void getBoxedTypeWhenPrimitiveArrayShouldReturnBoxedType() throws Exception {
Bindable<int[]> bindable = Bindable.of(int[].class);
assertThat(bindable.getType().getComponentType())
.isEqualTo(ResolvableType.forClass(int.class));
assertThat(bindable.getBoxedType().isArray()).isTrue();
assertThat(bindable.getBoxedType().getComponentType())
.isEqualTo(ResolvableType.forClass(Integer.class));
}
@Test
public void getAnnotationsShouldReturnEmptyArray() throws Exception {
assertThat(Bindable.of(String.class).getAnnotations()).isEmpty();
}
@Test
public void withAnnotationsShouldSetAnnotations() throws Exception {
Annotation annotation = mock(Annotation.class);
assertThat(Bindable.of(String.class).withAnnotations(annotation).getAnnotations())
.containsExactly(annotation);
}
@Test
public void toStringShouldShowDetails() throws Exception {
Annotation annotation = AnnotationUtils
.synthesizeAnnotation(TestAnnotation.class);
Bindable<String> bindable = Bindable.of(String.class).withExistingValue("foo")
.withAnnotations(annotation);
System.out.println(bindable.toString());
assertThat(bindable.toString()).contains("type = java.lang.String, "
+ "value = 'provided', annotations = array<Annotation>["
+ "@org.springframework.boot.context.properties.bind."
+ "BindableTests$TestAnnotation()]");
}
@Test
public void equalsAndHashCode() throws Exception {
Annotation annotation = AnnotationUtils
.synthesizeAnnotation(TestAnnotation.class);
Bindable<String> bindable1 = Bindable.of(String.class).withExistingValue("foo")
.withAnnotations(annotation);
Bindable<String> bindable2 = Bindable.of(String.class).withExistingValue("foo")
.withAnnotations(annotation);
Bindable<String> bindable3 = Bindable.of(String.class).withExistingValue("fof")
.withAnnotations(annotation);
assertThat(bindable1.hashCode()).isEqualTo(bindable2.hashCode());
assertThat(bindable1).isEqualTo(bindable1).isEqualTo(bindable2);
assertThat(bindable1).isEqualTo(bindable3);
}
@Retention(RetentionPolicy.RUNTIME)
static @interface TestAnnotation {
}
static class TestNewInstance {
private String foo = "hello world";
public String getFoo() {
return this.foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
static class TestNewInstanceWithNoDefaultConstructor {
TestNewInstanceWithNoDefaultConstructor(String foo) {
this.foo = foo;
}
private String foo = "hello world";
public String getFoo() {
return this.foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
}
| |
package com.eaw1805.orders.army;
import com.eaw1805.data.constants.GoodConstants;
import com.eaw1805.data.constants.MilitaryCalculators;
import com.eaw1805.data.constants.RegionConstants;
import com.eaw1805.data.managers.army.ArmyManager;
import com.eaw1805.data.managers.army.CommanderManager;
import com.eaw1805.data.managers.army.CorpManager;
import com.eaw1805.data.model.army.Army;
import com.eaw1805.data.model.army.Commander;
import com.eaw1805.data.model.army.Corp;
import com.eaw1805.data.model.map.Position;
import com.eaw1805.orders.AbstractOrderProcessor;
import com.eaw1805.orders.OrderProcessor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Order - Commander join Army.
* ticket:32.
*/
public class CommanderJoinArmy
extends AbstractOrderProcessor
implements GoodConstants, RegionConstants {
/**
* a log4j logger to print messages.
*/
private static final Logger LOGGER = LogManager.getLogger(CommanderJoinArmy.class);
/**
* Type of the order.
*/
public static final int ORDER_TYPE = ORDER_ARMY_COM;
/**
* Default constructor.
*
* @param myParent the parent object that invoked us.
*/
public CommanderJoinArmy(final OrderProcessor myParent) {
super(myParent);
LOGGER.debug("CommanderJoinArmy instantiated.");
}
/**
* Process this particular order.
*/
public void process() {
final int commId = Integer.parseInt(getOrder().getParameter1());
// Retrieve the commander
final Commander thisComm = CommanderManager.getInstance().getByID(commId);
if (thisComm == null) {
getOrder().setResult(-5);
getOrder().setExplanation("cannot locate subject of order");
} else if (thisComm.getDead()) {
getOrder().setResult(-4);
getOrder().setExplanation("commander is dead");
} else if (thisComm.getNation().getId() == getOrder().getNation().getId()) {
// Check ownership of commander
final int armyId = Integer.parseInt(getOrder().getParameter2());
if (armyId == 0) {
// Remove from army
if (thisComm.getArmy() == 0) {
getOrder().setResult(-1);
getOrder().setExplanation("commander not leading an army");
} else {
removeCommander(thisComm);
getOrder().setResult(1);
getOrder().setExplanation("commander " + thisComm.getName() + " removed from army");
}
} else {
final Army thisArmy = ArmyManager.getInstance().getByID(armyId);
if (thisArmy == null) {
// Check if this is a newly created army
if (getParent().armyAssocExists(armyId)) {
// remove commander from army or corp
removeCommander(thisComm);
// this is a new army
thisComm.setArmy(getParent().retrieveArmyAssoc(armyId));
CommanderManager.getInstance().update(thisComm);
final Army thatArmy = ArmyManager.getInstance().getByID(getParent().retrieveArmyAssoc(armyId));
thatArmy.setCommander(thisComm);
ArmyManager.getInstance().update(thatArmy);
// check if this commander arrived from the pool
if (thisComm.getPool()) {
// if it is in the same continent then automatic
if (thisComm.getPosition().getRegion().getId() == thatArmy.getPosition().getRegion().getId()
|| getParent().getGame().isFastAppointmentOfCommanders()) {
thisComm.setPool(false);
thisComm.setInTransit(false);
thisComm.setPosition((Position) thatArmy.getPosition().clone());
} else {
thisComm.setPool(true);
thisComm.setInTransit(true);
thisComm.setTransit(MilitaryCalculators.getTransitDistance(thisComm.getPosition().getRegion().getId(), thatArmy.getPosition().getRegion().getId()));
}
CommanderManager.getInstance().update(thisComm);
} else {
// set position of commander to match army
thisComm.setPosition((Position) thatArmy.getPosition().clone());
CommanderManager.getInstance().update(thisComm);
}
getOrder().setResult(1);
getOrder().setExplanation("commander " + thisComm.getName() + " joined newly created army");
}
} else {
// check ownership of army
if (thisArmy.getNation().getId() == thisComm.getNation().getId()) {
// Check location of army
if (thisComm.getPosition().equals(thisArmy.getPosition()) || thisComm.getPool()) {
// remove commander
removeCommander(thisComm);
// remove previous commander (if any)
clearArmy(thisArmy);
// update commander's position
thisComm.setArmy(armyId);
CommanderManager.getInstance().update(thisComm);
// update army's position
thisArmy.setCommander(thisComm);
ArmyManager.getInstance().update(thisArmy);
// check if this commander arrived from the pool
if (thisComm.getPool()) {
// if it is in the same continent then automatic
if (thisComm.getPosition().getRegion().getId() == thisArmy.getPosition().getRegion().getId()
|| getParent().getGame().isFastAppointmentOfCommanders()) {
thisComm.setPool(false);
thisComm.setInTransit(false);
thisComm.setTransit(0);
thisComm.setPosition((Position) thisArmy.getPosition().clone());
} else {
thisComm.setPool(true);
thisComm.setInTransit(true);
thisComm.setTransit(MilitaryCalculators.getTransitDistance(thisComm.getPosition().getRegion().getId(), thisArmy.getPosition().getRegion().getId()));
}
CommanderManager.getInstance().update(thisComm);
} else {
// set position of commander to match army
thisComm.setPosition((Position) thisArmy.getPosition().clone());
CommanderManager.getInstance().update(thisComm);
}
getOrder().setResult(1);
getOrder().setExplanation("commander " + thisComm.getName() + " joined army " + thisArmy.getName());
} else {
getOrder().setResult(-1);
getOrder().setExplanation("army located at a different sector");
}
} else {
getOrder().setResult(-2);
getOrder().setExplanation("not owner of army");
}
}
}
} else {
getOrder().setResult(-3);
getOrder().setExplanation("not owner of commander");
}
}
/**
* Remove commanders from army.
*
* @param thisArmy the army object.
*/
protected void clearArmy(final Army thisArmy) {
// check if commander exists
if (thisArmy.getCommander() != null) {
// update commander
thisArmy.getCommander().setArmy(0);
CommanderManager.getInstance().update(thisArmy.getCommander());
// remove commander
thisArmy.setCommander(null);
// update entity
ArmyManager.getInstance().update(thisArmy);
}
}
/**
* Remove commanders from corps.
*
* @param thisCorp the corps object.
*/
protected void clearCorp(final Corp thisCorp) {
// check if commander exists
if (thisCorp.getCommander() != null) {
// update commander
thisCorp.getCommander().setCorp(0);
CommanderManager.getInstance().update(thisCorp.getCommander());
// remove commander
thisCorp.setCommander(null);
// update entity
CorpManager.getInstance().update(thisCorp);
}
}
}
| |
/*
* 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.orc.tools.convert;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.orc.OrcFile;
import org.apache.orc.Reader;
import org.apache.orc.RecordReader;
import org.apache.orc.TypeDescription;
import org.apache.orc.Writer;
import org.apache.orc.tools.json.JsonSchemaFinder;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
/**
* A conversion tool to convert CSV or JSON files into ORC files.
*/
public class ConvertTool {
static final String DEFAULT_TIMESTAMP_FORMAT =
"yyyy[[-][/]]MM[[-][/]]dd[['T'][ ]]HH:mm:ss[ ][XXX][X]";
private final List<FileInformation> fileList;
private final TypeDescription schema;
private final char csvSeparator;
private final char csvQuote;
private final char csvEscape;
private final int csvHeaderLines;
private final String csvNullString;
private final String timestampFormat;
private final String bloomFilterColumns;
private final String unionTag;
private final String unionValue;
private final Writer writer;
private final VectorizedRowBatch batch;
TypeDescription buildSchema(List<FileInformation> files,
Configuration conf) throws IOException {
JsonSchemaFinder schemaFinder = new JsonSchemaFinder();
int filesScanned = 0;
for(FileInformation file: files) {
if (file.format == Format.JSON) {
System.err.println("Scanning " + file.path + " for schema");
filesScanned += 1;
schemaFinder.addFile(file.getReader(file.filesystem.open(file.path)), file.path.getName());
} else if (file.format == Format.ORC) {
System.err.println("Merging schema from " + file.path);
filesScanned += 1;
Reader reader = OrcFile.createReader(file.path,
OrcFile.readerOptions(conf)
.filesystem(file.filesystem));
if (files.size() == 1) {
return reader.getSchema();
}
schemaFinder.addSchema(reader.getSchema());
}
}
if (filesScanned == 0) {
throw new IllegalArgumentException("Please specify a schema using" +
" --schema for converting CSV files.");
}
return schemaFinder.getSchema();
}
enum Compression {
NONE, GZIP
}
enum Format {
JSON, CSV, ORC
}
class FileInformation {
private final Compression compression;
private final Format format;
private final Path path;
private final FileSystem filesystem;
private final Configuration conf;
private final long size;
FileInformation(Path path, Configuration conf) throws IOException {
this.path = path;
this.conf = conf;
this.filesystem = path.getFileSystem(conf);
this.size = filesystem.getFileStatus(path).getLen();
String name = path.getName();
int lastDot = name.lastIndexOf(".");
if (lastDot >= 0 && ".gz".equals(name.substring(lastDot))) {
this.compression = Compression.GZIP;
name = name.substring(0, lastDot);
lastDot = name.lastIndexOf(".");
} else {
this.compression = Compression.NONE;
}
if (lastDot >= 0) {
String ext = name.substring(lastDot);
if (".json".equals(ext) || ".jsn".equals(ext)) {
format = Format.JSON;
} else if (".csv".equals(ext)) {
format = Format.CSV;
} else if (".orc".equals(ext)) {
format = Format.ORC;
} else {
throw new IllegalArgumentException("Unknown kind of file " + path);
}
} else {
throw new IllegalArgumentException("No extension on file " + path);
}
}
java.io.Reader getReader(InputStream input) throws IOException {
if (compression == Compression.GZIP) {
input = new GZIPInputStream(input);
}
return new InputStreamReader(input, StandardCharsets.UTF_8);
}
public RecordReader getRecordReader() throws IOException {
switch (format) {
case ORC: {
Reader reader = OrcFile.createReader(path, OrcFile.readerOptions(conf));
return reader.rows(reader.options().schema(schema));
}
case JSON: {
FSDataInputStream underlying = filesystem.open(path);
return new JsonReader(getReader(underlying), underlying, size, schema, timestampFormat,
unionTag, unionValue);
}
case CSV: {
FSDataInputStream underlying = filesystem.open(path);
return new CsvReader(getReader(underlying), underlying, size, schema,
csvSeparator, csvQuote, csvEscape, csvHeaderLines, csvNullString, timestampFormat);
}
default:
throw new IllegalArgumentException("Unhandled format " + format +
" for " + path);
}
}
}
public static void main(Configuration conf,
String[] args) throws IOException, ParseException {
new ConvertTool(conf, args).run();
}
List<FileInformation> buildFileList(String[] files,
Configuration conf) throws IOException {
List<FileInformation> result = new ArrayList<>(files.length);
for(String fn: files) {
result.add(new FileInformation(new Path(fn), conf));
}
return result;
}
public ConvertTool(Configuration conf,
String[] args) throws IOException, ParseException {
CommandLine opts = parseOptions(args);
fileList = buildFileList(opts.getArgs(), conf);
if (opts.hasOption('s')) {
this.schema = TypeDescription.fromString(opts.getOptionValue('s'));
} else {
this.schema = buildSchema(fileList, conf);
}
this.csvQuote = getCharOption(opts, 'q', '"');
this.csvEscape = getCharOption(opts, 'e', '\\');
this.csvSeparator = getCharOption(opts, 'S', ',');
this.csvHeaderLines = getIntOption(opts, 'H', 0);
this.csvNullString = opts.getOptionValue('n', "");
this.timestampFormat = opts.getOptionValue("t", DEFAULT_TIMESTAMP_FORMAT);
this.bloomFilterColumns = opts.getOptionValue('b', null);
this.unionTag = opts.getOptionValue("union-tag", "tag");
this.unionValue = opts.getOptionValue("union-value", "value");
String outFilename = opts.hasOption('o')
? opts.getOptionValue('o') : "output.orc";
boolean overwrite = opts.hasOption('O');
OrcFile.WriterOptions writerOpts = OrcFile.writerOptions(conf)
.setSchema(schema)
.overwrite(overwrite);
if (this.bloomFilterColumns != null) {
writerOpts.bloomFilterColumns(this.bloomFilterColumns);
}
writer = OrcFile.createWriter(new Path(outFilename), writerOpts);
batch = schema.createRowBatch();
}
void run() throws IOException {
for (FileInformation file: fileList) {
System.err.println("Processing " + file.path);
RecordReader reader = file.getRecordReader();
while (reader.nextBatch(batch)) {
writer.addRowBatch(batch);
}
reader.close();
}
writer.close();
}
private static int getIntOption(CommandLine opts, char letter, int mydefault) {
if (opts.hasOption(letter)) {
return Integer.parseInt(opts.getOptionValue(letter));
} else {
return mydefault;
}
}
private static char getCharOption(CommandLine opts, char letter, char mydefault) {
if (opts.hasOption(letter)) {
return opts.getOptionValue(letter).charAt(0);
} else {
return mydefault;
}
}
private static CommandLine parseOptions(String[] args) throws ParseException {
Options options = new Options();
options.addOption(
Option.builder("h").longOpt("help").desc("Provide help").build());
options.addOption(
Option.builder("s").longOpt("schema").hasArg()
.desc("The schema to write in to the file").build());
options.addOption(
Option.builder("b").longOpt("bloomFilterColumns").hasArg()
.desc("Comma separated values of column names for which bloom filter is " +
"to be created").build());
options.addOption(
Option.builder("o").longOpt("output").desc("Output filename")
.hasArg().build());
options.addOption(
Option.builder("n").longOpt("null").desc("CSV null string")
.hasArg().build());
options.addOption(
Option.builder("q").longOpt("quote").desc("CSV quote character")
.hasArg().build());
options.addOption(
Option.builder("e").longOpt("escape").desc("CSV escape character")
.hasArg().build());
options.addOption(
Option.builder("S").longOpt("separator").desc("CSV separator character")
.hasArg().build());
options.addOption(
Option.builder("H").longOpt("header").desc("CSV header lines")
.hasArg().build());
options.addOption(
Option.builder("t").longOpt("timestampformat").desc("Timestamp Format")
.hasArg().build());
options.addOption(
Option.builder("O").longOpt("overwrite").desc("Overwrite an existing file")
.build()
);
options.addOption(
Option.builder().longOpt("union-tag")
.desc("JSON key name representing UNION tag. Default to \"tag\".")
.hasArg().build());
options.addOption(
Option.builder().longOpt("union-value")
.desc("JSON key name representing UNION value. Default to \"value\".")
.hasArg().build());
CommandLine cli = new DefaultParser().parse(options, args);
if (cli.hasOption('h') || cli.getArgs().length == 0) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("convert", options);
System.exit(1);
}
return cli;
}
}
| |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.06.29 at 10:15:17 AM BST
//
package org.w3._1999.xhtml;
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.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://www.w3.org/1999/xhtml}a.content">
* <attGroup ref="{http://www.w3.org/1999/xhtml}focus"/>
* <attGroup ref="{http://www.w3.org/1999/xhtml}attrs"/>
* <attribute name="charset" type="{http://www.w3.org/1999/xhtml}Charset" />
* <attribute name="type" type="{http://www.w3.org/1999/xhtml}ContentType" />
* <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
* <attribute name="href" type="{http://www.w3.org/1999/xhtml}URI" />
* <attribute name="hreflang" type="{http://www.w3.org/1999/xhtml}LanguageCode" />
* <attribute name="rel" type="{http://www.w3.org/1999/xhtml}LinkTypes" />
* <attribute name="rev" type="{http://www.w3.org/1999/xhtml}LinkTypes" />
* <attribute name="shape" type="{http://www.w3.org/1999/xhtml}Shape" default="rect" />
* <attribute name="coords" type="{http://www.w3.org/1999/xhtml}Coords" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "a")
public class A
extends AContent
{
@XmlAttribute
protected String charset;
@XmlAttribute
protected String type;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String name;
@XmlAttribute
protected String href;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String hreflang;
@XmlAttribute
protected List<String> rel;
@XmlAttribute
protected List<String> rev;
@XmlAttribute
protected Shape shape;
@XmlAttribute
protected String coords;
@XmlAttribute
protected String accesskey;
@XmlAttribute
protected Integer tabindex;
@XmlAttribute
protected String onfocus;
@XmlAttribute
protected String onblur;
@XmlAttribute
protected String onclick;
@XmlAttribute
protected String ondblclick;
@XmlAttribute
protected String onmousedown;
@XmlAttribute
protected String onmouseup;
@XmlAttribute
protected String onmouseover;
@XmlAttribute
protected String onmousemove;
@XmlAttribute
protected String onmouseout;
@XmlAttribute
protected String onkeypress;
@XmlAttribute
protected String onkeydown;
@XmlAttribute
protected String onkeyup;
@XmlAttribute(name = "lang")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String langCode;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
protected String lang;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String dir;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute(name = "class")
@XmlSchemaType(name = "NMTOKENS")
protected List<String> clazz;
@XmlAttribute
protected String style;
@XmlAttribute
protected String title;
/**
* Gets the value of the charset property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCharset() {
return charset;
}
/**
* Sets the value of the charset property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCharset(String value) {
this.charset = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the href property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Sets the value of the href property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Gets the value of the hreflang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHreflang() {
return hreflang;
}
/**
* Sets the value of the hreflang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHreflang(String value) {
this.hreflang = value;
}
/**
* Gets the value of the rel property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the rel property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRel().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getRel() {
if (rel == null) {
rel = new ArrayList<String>();
}
return this.rel;
}
/**
* Gets the value of the rev property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the rev property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRev().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getRev() {
if (rev == null) {
rev = new ArrayList<String>();
}
return this.rev;
}
/**
* Gets the value of the shape property.
*
* @return
* possible object is
* {@link Shape }
*
*/
public Shape getShape() {
if (shape == null) {
return Shape.RECT;
} else {
return shape;
}
}
/**
* Sets the value of the shape property.
*
* @param value
* allowed object is
* {@link Shape }
*
*/
public void setShape(Shape value) {
this.shape = value;
}
/**
* Gets the value of the coords property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCoords() {
return coords;
}
/**
* Sets the value of the coords property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCoords(String value) {
this.coords = value;
}
/**
* Gets the value of the accesskey property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAccesskey() {
return accesskey;
}
/**
* Sets the value of the accesskey property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAccesskey(String value) {
this.accesskey = value;
}
/**
* Gets the value of the tabindex property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getTabindex() {
return tabindex;
}
/**
* Sets the value of the tabindex property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setTabindex(Integer value) {
this.tabindex = value;
}
/**
* Gets the value of the onfocus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnfocus() {
return onfocus;
}
/**
* Sets the value of the onfocus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnfocus(String value) {
this.onfocus = value;
}
/**
* Gets the value of the onblur property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnblur() {
return onblur;
}
/**
* Sets the value of the onblur property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnblur(String value) {
this.onblur = value;
}
/**
* Gets the value of the onclick property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnclick() {
return onclick;
}
/**
* Sets the value of the onclick property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnclick(String value) {
this.onclick = value;
}
/**
* Gets the value of the ondblclick property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOndblclick() {
return ondblclick;
}
/**
* Sets the value of the ondblclick property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOndblclick(String value) {
this.ondblclick = value;
}
/**
* Gets the value of the onmousedown property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnmousedown() {
return onmousedown;
}
/**
* Sets the value of the onmousedown property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnmousedown(String value) {
this.onmousedown = value;
}
/**
* Gets the value of the onmouseup property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnmouseup() {
return onmouseup;
}
/**
* Sets the value of the onmouseup property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnmouseup(String value) {
this.onmouseup = value;
}
/**
* Gets the value of the onmouseover property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnmouseover() {
return onmouseover;
}
/**
* Sets the value of the onmouseover property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnmouseover(String value) {
this.onmouseover = value;
}
/**
* Gets the value of the onmousemove property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnmousemove() {
return onmousemove;
}
/**
* Sets the value of the onmousemove property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnmousemove(String value) {
this.onmousemove = value;
}
/**
* Gets the value of the onmouseout property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnmouseout() {
return onmouseout;
}
/**
* Sets the value of the onmouseout property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnmouseout(String value) {
this.onmouseout = value;
}
/**
* Gets the value of the onkeypress property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnkeypress() {
return onkeypress;
}
/**
* Sets the value of the onkeypress property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnkeypress(String value) {
this.onkeypress = value;
}
/**
* Gets the value of the onkeydown property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnkeydown() {
return onkeydown;
}
/**
* Sets the value of the onkeydown property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnkeydown(String value) {
this.onkeydown = value;
}
/**
* Gets the value of the onkeyup property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOnkeyup() {
return onkeyup;
}
/**
* Sets the value of the onkeyup property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOnkeyup(String value) {
this.onkeyup = value;
}
/**
* Gets the value of the langCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLangCode() {
return langCode;
}
/**
* Sets the value of the langCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLangCode(String value) {
this.langCode = value;
}
/**
* Gets the value of the lang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLang() {
return lang;
}
/**
* Sets the value of the lang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLang(String value) {
this.lang = value;
}
/**
* Gets the value of the dir property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDir() {
return dir;
}
/**
* Sets the value of the dir property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDir(String value) {
this.dir = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the clazz property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the clazz property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getClazz().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getClazz() {
if (clazz == null) {
clazz = new ArrayList<String>();
}
return this.clazz;
}
/**
* Gets the value of the style property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyle() {
return style;
}
/**
* Sets the value of the style property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStyle(String value) {
this.style = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
}
| |
package com.github.stigmata.result;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import com.github.stigmata.BirthmarkContext;
import com.github.stigmata.BirthmarkEnvironment;
import com.github.stigmata.BirthmarkSet;
import com.github.stigmata.BirthmarkStoreException;
import com.github.stigmata.ExtractionResultSet;
import com.github.stigmata.ExtractionTarget;
import com.github.stigmata.ExtractionUnit;
/**
* Abstract class for ExtractionResultSet.
*
* @author Haruaki Tamada
*/
public abstract class AbstractExtractionResultSet implements ExtractionResultSet{
private BirthmarkContext context;
private boolean tableType = true;
private String id;
/**
* constructor.
*/
public AbstractExtractionResultSet(BirthmarkContext context){
this(context, true);
}
/**
* constructor.
*/
public AbstractExtractionResultSet(BirthmarkContext context, boolean tableType){
this.context = context;
id = generateId();
}
void setId(String id){
this.id = id;
}
@Override
public String getId(){
return id;
}
/**
* returns a birthmark environment.
*/
@Override
public BirthmarkEnvironment getEnvironment(){
return context.getEnvironment();
}
/**
* returns a birthmark context.
*/
@Override
public BirthmarkContext getContext(){
return context;
}
@Override
public abstract void addBirthmarkSet(ExtractionTarget target, BirthmarkSet set) throws BirthmarkStoreException;
@Override
public abstract void removeBirthmarkSet(ExtractionTarget target, BirthmarkSet set);
@Override
public abstract void removeAllBirthmarkSets(ExtractionTarget target);
@Override
public abstract int getBirthmarkSetSize(ExtractionTarget target);
@Override
public abstract Iterator<BirthmarkSet> birthmarkSets(ExtractionTarget target);
/**
* returns the sum of birthmark set size this instance has.
* <code>getBirthmarkSetSize(ExtractionTarget.TARGET_BOTH)</code>
*/
@Override
public int getBirthmarkSetSize(){
return getBirthmarkSetSize(ExtractionTarget.TARGET_BOTH);
}
/**
* returns an iterator.
* <code>birthmarkSets(ExtractionTarget.TARGET_BOTH)</code>
*/
@Override
public Iterator<BirthmarkSet> iterator(){
return birthmarkSets(ExtractionTarget.TARGET_BOTH);
}
/**
* returns a birthmark set related of given index.
* <code>getBirthmarkSet(ExtractionTarget.TARGET_BOTH, index)</code>
*/
@Override
public BirthmarkSet getBirthmarkSet(int index){
return getBirthmarkSet(ExtractionTarget.TARGET_BOTH, index);
}
/**
* returns a birthmark set related with given name.
* <code>getBirthmarkSet(ExtractionTarget.TARGET_BOTH, name)</code>
*/
@Override
public BirthmarkSet getBirthmarkSet(String name){
return getBirthmarkSet(ExtractionTarget.TARGET_BOTH, name);
}
/**
* returns all of birthmark sets.
* <code>getBirthmarkSets(ExtractionTarget.TARGET_BOTH)</code>
*/
@Override
public BirthmarkSet[] getBirthmarkSets(){
return getBirthmarkSets(ExtractionTarget.TARGET_BOTH);
}
/**
* remove specified birthmark set from this instance.
* <code>removeBirthmarkSet(ExtractionTarget.TARGET_BOTH, bs)</code>
*/
@Override
public void removeBirthmarkSet(BirthmarkSet bs){
removeBirthmarkSet(ExtractionTarget.TARGET_BOTH, bs);
}
/**
* remove all of birthmark sets.
* <code>removeBirthmarkSet(ExtractionTarget.TARGET_BOTH)</code>
*/
@Override
public void removeAllBirthmarkSets(){
removeAllBirthmarkSets(ExtractionTarget.TARGET_BOTH);
}
/**
* returns an array of extracted birthmark types.
*/
@Override
public String[] getBirthmarkTypes(){
return context.getBirthmarkTypes();
}
/**
* returns an unit of extraction from.
*/
@Override
public ExtractionUnit getExtractionUnit(){
return context.getExtractionUnit();
}
/**
* returns the birthmark set at the specified position in the specified target.
*/
@Override
public BirthmarkSet getBirthmarkSet(ExtractionTarget target, int index){
int currentIndex = 0;
for(Iterator<BirthmarkSet> i = birthmarkSets(target); i.hasNext(); ){
if(currentIndex == index){
return i.next();
}
i.next();
currentIndex++;
}
return null;
}
/**
* returns the birthmark set related with the specified name in the specified target.
*/
@Override
public BirthmarkSet getBirthmarkSet(ExtractionTarget target, String setname){
for(Iterator<BirthmarkSet> i = birthmarkSets(target); i.hasNext(); ){
BirthmarkSet bs = i.next();
if(bs.getName().equals(setname)){
return bs;
}
}
return null;
}
/**
* @return all of BirthmarkSet this instance have. elements is obtained from birthmarkSet.
*/
@Override
public synchronized BirthmarkSet[] getBirthmarkSets(ExtractionTarget target){
return AbstractComparisonResultSet.<BirthmarkSet>getArrays(birthmarkSets(target), new BirthmarkSet[0]);
}
@Override
public void setBirthmarkSets(ExtractionTarget target, BirthmarkSet[] sets) throws BirthmarkStoreException{
removeAllBirthmarkSets(target);
for(int i = 0; i < sets.length; i++){
addBirthmarkSet(target, sets[i]);
}
}
@Override
public boolean isTableType(){
return tableType;
}
@Override
public void setTableType(boolean flag){
this.tableType = flag;
}
protected static String generateId(){
SimpleDateFormat cdf = new SimpleDateFormat("yyyyMMdd-HHmmss.SSS");
return cdf.format(Calendar.getInstance().getTime());
}
}
| |
// 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.firefox;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteStreams;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.net.PortProber;
import org.openqa.selenium.remote.BrowserType;
import org.openqa.selenium.remote.service.DriverService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Manages the life and death of an GeckoDriver aka 'wires'.
*/
public class GeckoDriverService extends FirefoxDriverService {
/**
* System property that defines the location of the GeckoDriver executable
* that will be used by the {@link #createDefaultService() default service}.
*/
public static final String GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver";
/**
* @param executable The GeckoDriver executable.
* @param port Which port to start the GeckoDriver on.
* @param args The arguments to the launched server.
* @param environment The environment for the launched server.
* @throws IOException If an I/O error occurs.
*/
public GeckoDriverService(
File executable,
int port,
ImmutableList<String> args,
ImmutableMap<String, String> environment) throws IOException {
super(executable, port, args, environment);
}
/**
* Configures and returns a new {@link GeckoDriverService} using the default configuration. In
* this configuration, the service will use the GeckoDriver executable identified by the
* {@link #GECKO_DRIVER_EXE_PROPERTY} system property. Each service created by this method will
* be configured to use a free port on the current system.
*
* @return A new GeckoDriverService using the default configuration.
*/
public static GeckoDriverService createDefaultService() {
return new Builder().build();
}
static GeckoDriverService createDefaultService(Capabilities caps) {
Builder builder = new Builder();
Object binary = caps.getCapability(FirefoxDriver.BINARY);
if (binary != null) {
FirefoxBinary actualBinary;
if (binary instanceof FirefoxBinary) {
actualBinary = (FirefoxBinary) binary;
} else if (binary instanceof String) {
actualBinary = new FirefoxBinary(new File(String.valueOf(binary)));
} else {
throw new IllegalArgumentException(
"Expected binary to be a string or a binary: " + binary);
}
builder.usingFirefoxBinary(actualBinary);
}
return new Builder().build();
}
@Override
protected void waitUntilAvailable() {
PortProber.waitForPortUp(getUrl().getPort(), 20, SECONDS);
}
@Override
protected boolean hasShutdownEndpoint() {
return false;
}
/**
* Builder used to configure new {@link GeckoDriverService} instances.
*/
@AutoService(DriverService.Builder.class)
public static class Builder extends FirefoxDriverService.Builder<
GeckoDriverService, GeckoDriverService.Builder> {
private FirefoxBinary firefoxBinary;
public Builder() {
}
@Override
protected boolean isLegacy() {
return false;
}
@Override
public int score(Capabilities capabilities) {
if (capabilities.getCapability(FirefoxDriver.MARIONETTE) != null
&& ! capabilities.is(FirefoxDriver.MARIONETTE)) {
return 0;
}
int score = 0;
if (BrowserType.FIREFOX.equals(capabilities.getBrowserName())) {
score++;
}
if (capabilities.getCapability(FirefoxOptions.FIREFOX_OPTIONS) != null) {
score++;
}
return score;
}
/**
* Sets which browser executable the builder will use.
*
* @param firefoxBinary The browser executable to use.
* @return A self reference.
*/
public Builder usingFirefoxBinary(FirefoxBinary firefoxBinary) {
checkNotNull(firefoxBinary);
checkExecutable(firefoxBinary.getFile());
this.firefoxBinary = firefoxBinary;
return this;
}
@Override
protected FirefoxDriverService.Builder withOptions(FirefoxOptions options) {
usingFirefoxBinary(options.getBinary());
return this;
}
@Override
protected File findDefaultExecutable() {
return findExecutable(
"geckodriver", GECKO_DRIVER_EXE_PROPERTY,
"https://github.com/mozilla/geckodriver",
"https://github.com/mozilla/geckodriver/releases");
}
@Override
protected ImmutableList<String> createArgs() {
ImmutableList.Builder<String> argsBuilder = ImmutableList.builder();
argsBuilder.add(String.format("--port=%d", getPort()));
if (firefoxBinary != null) {
argsBuilder.add("-b");
argsBuilder.add(firefoxBinary.getPath());
} // else GeckoDriver will be responsible for finding Firefox on the PATH or via a capability.
return argsBuilder.build();
}
@Override
protected GeckoDriverService createDriverService(File exe, int port,
ImmutableList<String> args,
ImmutableMap<String, String> environment) {
try {
GeckoDriverService service = new GeckoDriverService(exe, port, args, environment);
String firefoxLogFile = System.getProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE);
if (firefoxLogFile != null) { // System property has higher precedence
if ("/dev/stdout".equals(firefoxLogFile)) {
service.sendOutputTo(System.out);
} else if ("/dev/stderr".equals(firefoxLogFile)) {
service.sendOutputTo(System.err);
} else if ("/dev/null".equals(firefoxLogFile)) {
service.sendOutputTo(ByteStreams.nullOutputStream());
} else {
service.sendOutputTo(new FileOutputStream(firefoxLogFile));
}
} else {
if (getLogFile() != null) {
service.sendOutputTo(new FileOutputStream(getLogFile()));
} else {
service.sendOutputTo(System.err);
}
}
return service;
} catch (IOException e) {
throw new WebDriverException(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.jmeter.control.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.apache.jmeter.control.IfController;
import org.apache.jmeter.gui.GUIMenuSortOrder;
import org.apache.jmeter.gui.util.JSyntaxTextArea;
import org.apache.jmeter.gui.util.JTextScrollPane;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
/**
* The user interface for a controller which specifies that its subcomponents
* should be executed while a condition holds. This component can be used
* standalone or embedded into some other component.
*
*/
@GUIMenuSortOrder(1)
public class IfControllerPanel extends AbstractControllerGui implements ChangeListener {
private static final long serialVersionUID = 240L;
/**
* Used to warn about performance penalty
*/
private JLabel warningLabel;
private JLabel conditionLabel;
/**
* A field allowing the user to specify the number of times the controller
* should loop.
*/
private JSyntaxTextArea theCondition;
private JCheckBox useExpression;
private JCheckBox evaluateAll;
/**
* Boolean indicating whether or not this component should display its name.
* If true, this is a standalone component. If false, this component is
* intended to be used as a subpanel for another component.
*/
private boolean displayName = true;
/**
* Create a new LoopControlPanel as a standalone component.
*/
public IfControllerPanel() {
this(true);
}
/**
* Create a new IfControllerPanel as either a standalone or an embedded
* component.
*
* @param displayName
* indicates whether or not this component should display its
* name. If true, this is a standalone component. If false, this
* component is intended to be used as a subpanel for another
* component.
*/
public IfControllerPanel(boolean displayName) {
this.displayName = displayName;
init();
}
/**
* A newly created component can be initialized with the contents of a Test
* Element object by calling this method. The component is responsible for
* querying the Test Element object for the relevant information to display
* in its GUI.
*
* @param element
* the TestElement to configure
*/
@Override
public void configure(TestElement element) {
super.configure(element);
if (element instanceof IfController) {
IfController ifController = (IfController) element;
theCondition.setText(ifController.getCondition());
evaluateAll.setSelected(ifController.isEvaluateAll());
useExpression.setSelected(ifController.isUseExpression());
}
}
/**
* Implements JMeterGUIComponent.createTestElement()
*/
@Override
public TestElement createTestElement() {
IfController controller = new IfController();
modifyTestElement(controller);
return controller;
}
/**
* Implements JMeterGUIComponent.modifyTestElement(TestElement)
*/
@Override
public void modifyTestElement(TestElement controller) {
configureTestElement(controller);
if (controller instanceof IfController) {
IfController ifController = (IfController) controller;
ifController.setCondition(theCondition.getText());
ifController.setEvaluateAll(evaluateAll.isSelected());
ifController.setUseExpression(useExpression.isSelected());
}
}
/**
* Implements JMeterGUIComponent.clearGui
*/
@Override
public void clearGui() {
super.clearGui();
useExpression.setSelected(true);
theCondition.setText(""); // $NON-NLS-1$
evaluateAll.setSelected(false);
}
@Override
public String getLabelResource() {
return "if_controller_title"; // $NON-NLS-1$
}
/**
* Initialize the GUI components and layout for this component.
*/
private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final)
// Standalone
if (displayName) {
setLayout(new BorderLayout(0, 5));
setBorder(makeBorder());
add(makeTitlePanel(), BorderLayout.NORTH);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(createConditionPanel(), BorderLayout.NORTH);
add(mainPanel, BorderLayout.CENTER);
} else {
// Embedded
setLayout(new BorderLayout());
add(createConditionPanel(), BorderLayout.NORTH);
}
}
/**
* Create a GUI panel containing the condition.
*
* @return a GUI panel containing the condition components
*/
private JPanel createConditionPanel() {
JPanel conditionPanel = new JPanel(new BorderLayout(5, 0));
// Condition LABEL
conditionLabel = new JLabel(JMeterUtils.getResString("if_controller_label")); // $NON-NLS-1$
conditionPanel.add(conditionLabel, BorderLayout.WEST);
ImageIcon image = JMeterUtils.getImage("warning.png");
warningLabel = new JLabel(JMeterUtils.getResString("if_controller_warning"), image, SwingConstants.CENTER); // $NON-NLS-1$
warningLabel.setForeground(Color.RED);
Font font = warningLabel.getFont();
warningLabel.setFont(new Font(font.getFontName(), Font.BOLD, (int)(font.getSize()*1.1)));
// Condition
theCondition = JSyntaxTextArea.getInstance(5, 50); // $NON-NLS-1$
conditionLabel.setLabelFor(theCondition);
conditionPanel.add(JTextScrollPane.getInstance(theCondition), BorderLayout.CENTER);
conditionPanel.add(warningLabel, BorderLayout.NORTH);
JPanel optionPanel = new JPanel();
// Use expression instead of Javascript
useExpression = new JCheckBox(JMeterUtils.getResString("if_controller_expression")); // $NON-NLS-1$
useExpression.addChangeListener(this);
optionPanel.add(useExpression);
// Evaluate All checkbox
evaluateAll = new JCheckBox(JMeterUtils.getResString("if_controller_evaluate_all")); // $NON-NLS-1$
optionPanel.add(evaluateAll);
conditionPanel.add(optionPanel,BorderLayout.SOUTH);
return conditionPanel;
}
@Override
public void stateChanged(ChangeEvent e) {
if(e.getSource() == useExpression) {
if(useExpression.isSelected()) {
warningLabel.setForeground(Color.BLACK);
conditionLabel.setText(JMeterUtils.getResString("if_controller_expression_label"));
} else {
warningLabel.setForeground(Color.RED);
conditionLabel.setText(JMeterUtils.getResString("if_controller_label"));
}
}
}
}
| |
/*
* 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.internal;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Delayed;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
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;
/**
* A ScheduledThreadPoolExecutor which allows threads to time out after the keep
* alive time. With the normal ScheduledThreadPoolExecutor, there is no way to
* configure it such that it only add threads as needed.
*
* This executor is not very useful if you only want to have 1 thread. Use the
* ScheduledThreadPoolExecutor in that case. This class with throw an exception
* if you try to configure it with one thread.
*
* @author dsmith
*
*/
@SuppressWarnings("synthetic-access")
public class ScheduledThreadPoolExecutorWithKeepAlive extends ThreadPoolExecutor implements ScheduledExecutorService {
private final ScheduledThreadPoolExecutor timer;
/**
* @param corePoolSize
* @param threadFactory
*/
public ScheduledThreadPoolExecutorWithKeepAlive(int corePoolSize,
long keepAlive, TimeUnit timeUnit, ThreadFactory threadFactory) {
super(0, corePoolSize - 1, keepAlive,
timeUnit, new SynchronousQueue(), threadFactory, new BlockCallerPolicy());
timer = new ScheduledThreadPoolExecutor(1, threadFactory) {
@Override
protected void terminated() {
super.terminated();
ScheduledThreadPoolExecutorWithKeepAlive.super.shutdown();
}
};
}
@Override
public void execute(Runnable command) {
timer.execute(new HandOffTask(command));
}
@Override
public Future submit(Callable task) {
return schedule(task, 0, TimeUnit.NANOSECONDS);
}
@Override
public Future submit(Runnable task, Object result) {
return schedule(task, 0, TimeUnit.NANOSECONDS, result);
}
@Override
public Future submit(Runnable task) {
return schedule(task, 0, TimeUnit.NANOSECONDS);
}
public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) {
DelegatingScheduledFuture future = new DelegatingScheduledFuture(callable);
ScheduledFuture timerFuture = timer.schedule(new HandOffTask(future), delay, unit);
future.setDelegate(timerFuture);
return future;
}
public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) {
return schedule(command, delay, unit, null);
}
private ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit, Object result) {
DelegatingScheduledFuture future = new DelegatingScheduledFuture(command, result);
ScheduledFuture timerFuture = timer.schedule(new HandOffTask(future), delay, unit);
future.setDelegate(timerFuture);
return future;
}
public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
DelegatingScheduledFuture future = new DelegatingScheduledFuture(command, null, true);
ScheduledFuture timerFuture = timer.scheduleAtFixedRate(new HandOffTask(future), initialDelay, period, unit);
future.setDelegate(timerFuture);
return future;
}
public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
DelegatingScheduledFuture future = new DelegatingScheduledFuture(command, null, true);
ScheduledFuture timerFuture = timer.scheduleWithFixedDelay(new HandOffTask(future), initialDelay, delay, unit);
future.setDelegate(timerFuture);
return future;
}
@Override
public void shutdown() {
//note - the timer has a "hook" which will shutdown our
//worker pool once the timer is shutdown.
timer.shutdown();
}
/**
* Shutdown the executor immediately, returning a list of tasks that haven't
* been run. Like ScheduledThreadPoolExecutor, this returns a list of
* RunnableScheduledFuture objects, instead of the actual tasks submitted.
* However, these Future objects are even less useful than the ones returned
* by ScheduledThreadPoolExecutor. In particular, they don't match the future
* returned by the {{@link #submit(Runnable)} method, and the run method won't
* do anything useful. This list should only be used as a count of the number
* of tasks that didn't execute.
*
* @see ScheduledThreadPoolExecutor#shutdownNow()
*/
@Override
public List shutdownNow() {
List tasks = timer.shutdownNow();
super.shutdownNow();
return tasks;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
long start = System.nanoTime();
if(!timer.awaitTermination(timeout, unit)) {
return false;
}
long elapsed = System.nanoTime() - start;
long remaining = unit.toNanos(timeout) - elapsed;
if(remaining < 0) {
return false;
}
return super.awaitTermination(remaining, TimeUnit.NANOSECONDS);
}
@Override
public int getCorePoolSize() {
return super.getCorePoolSize() + 1;
}
@Override
public int getLargestPoolSize() {
return super.getLargestPoolSize() + 1;
}
@Override
public int getMaximumPoolSize() {
return super.getMaximumPoolSize() + 1;
}
@Override
public int getPoolSize() {
return super.getPoolSize() + 1;
}
@Override
public boolean isShutdown() {
return timer.isShutdown();
}
@Override
public boolean isTerminated() {
return super.isTerminated() && timer.isTerminated();
}
//method that is in ScheduledThreadPoolExecutor that we should expose here
public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean b) {
timer.setContinueExistingPeriodicTasksAfterShutdownPolicy(b);
}
//method that is in ScheduledThreadPoolExecutor that we should expose here
public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean b) {
timer.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
}
/**
* A Runnable which we put in the timer which
* simply hands off the contain task for execution
* in the thread pool when the timer fires.
* @author dsmith
*
*/
private class HandOffTask implements Runnable {
private final Runnable task;
public HandOffTask(Runnable task) {
this.task = task;
}
public void run() {
try {
ScheduledThreadPoolExecutorWithKeepAlive.super.execute(task);
} catch(RejectedExecutionException e) {
//do nothing, we'll only get this if we're shutting down.
}
}
}
/**
* The future returned by the schedule* methods on this class. This future
* will not return a value until the task has actually executed in the thread pool,
* but it allows us to cancel associated timer task.
* @author dsmith
*
*/
private static class DelegatingScheduledFuture<V> extends FutureTask<V> implements ScheduledFuture<V> {
private ScheduledFuture<V> delegate;
private final boolean periodic;
public DelegatingScheduledFuture(Runnable runnable, V result) {
this(runnable, result, false);
}
public DelegatingScheduledFuture(Callable<V> callable) {
this(callable, false);
}
public DelegatingScheduledFuture(Runnable runnable, V result, boolean periodic) {
super(runnable, result);
this.periodic = periodic;
}
public DelegatingScheduledFuture(Callable<V> callable, boolean periodic) {
super(callable);
this.periodic = periodic;
}
@Override
public void run() {
if(periodic) {
super.runAndReset();
} else {
super.run();
}
}
public void setDelegate(ScheduledFuture<V> future) {
this.delegate = future;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
delegate.cancel(true);
return super.cancel(mayInterruptIfRunning);
}
public long getDelay(TimeUnit unit) {
return delegate.getDelay(unit);
}
public int compareTo(Delayed o) {
return delegate.compareTo(o);
}
@Override
public boolean equals(Object o) {
return delegate.equals(o);
}
@Override
public int hashCode() {
return delegate.hashCode();
}
}
/** A RejectedExecutionHandler which causes the caller to block until
* there is space in the queue for the task.
* @author dsmith
*/
protected static class BlockCallerPolicy implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
throw new RejectedExecutionException("executor has been shutdown");
} else {
try {
executor.getQueue().put(r);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
RejectedExecutionException e = new RejectedExecutionException("interrupted");
e.initCause(ie);
throw e;
}
}
}
}
}
| |
package edu.umkc.permitme.service;
import edu.umkc.permitme.domain.Authority;
import edu.umkc.permitme.domain.User;
import edu.umkc.permitme.repository.AuthorityRepository;
import edu.umkc.permitme.repository.PersistentTokenRepository;
import edu.umkc.permitme.repository.UserRepository;
import edu.umkc.permitme.security.SecurityUtils;
import edu.umkc.permitme.service.util.RandomUtil;
import edu.umkc.permitme.web.rest.dto.ManagedUserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import javax.inject.Inject;
import java.util.*;
/**
* Service class for managing users.
*/
@Service
@Transactional
public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
@Inject
private SocialService socialService;
@Inject
private PasswordEncoder passwordEncoder;
@Inject
private UserRepository userRepository;
@Inject
private PersistentTokenRepository persistentTokenRepository;
@Inject
private AuthorityRepository authorityRepository;
public Optional<User> activateRegistration(String key) {
log.debug("Activating user for activation key {}", key);
return userRepository.findOneByActivationKey(key)
.map(user -> {
// activate given user for the registration key.
user.setActivated(true);
user.setActivationKey(null);
userRepository.save(user);
log.debug("Activated user: {}", user);
return user;
});
}
public Optional<User> completePasswordReset(String newPassword, String key) {
log.debug("Reset user password for reset key {}", key);
return userRepository.findOneByResetKey(key)
.filter(user -> {
ZonedDateTime oneDayAgo = ZonedDateTime.now().minusHours(24);
return user.getResetDate().isAfter(oneDayAgo);
})
.map(user -> {
user.setPassword(passwordEncoder.encode(newPassword));
user.setResetKey(null);
user.setResetDate(null);
userRepository.save(user);
return user;
});
}
public Optional<User> requestPasswordReset(String mail) {
return userRepository.findOneByEmail(mail)
.filter(User::getActivated)
.map(user -> {
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(ZonedDateTime.now());
userRepository.save(user);
return user;
});
}
public User createUserInformation(String login, String password, String firstName, String lastName, String email,
String langKey) {
User newUser = new User();
Authority authority = authorityRepository.findOne("ROLE_USER");
Set<Authority> authorities = new HashSet<>();
String encryptedPassword = passwordEncoder.encode(password);
newUser.setLogin(login);
// new user gets initially a generated password
newUser.setPassword(encryptedPassword);
newUser.setFirstName(firstName);
newUser.setLastName(lastName);
newUser.setEmail(email);
newUser.setLangKey(langKey);
// new user is not active
newUser.setActivated(false);
// new user gets registration key
newUser.setActivationKey(RandomUtil.generateActivationKey());
authorities.add(authority);
newUser.setAuthorities(authorities);
userRepository.save(newUser);
log.debug("Created Information for User: {}", newUser);
return newUser;
}
public User createUser(ManagedUserDTO managedUserDTO) {
User user = new User();
user.setLogin(managedUserDTO.getLogin());
user.setFirstName(managedUserDTO.getFirstName());
user.setLastName(managedUserDTO.getLastName());
user.setEmail(managedUserDTO.getEmail());
if (managedUserDTO.getLangKey() == null) {
user.setLangKey("en"); // default language
} else {
user.setLangKey(managedUserDTO.getLangKey());
}
if (managedUserDTO.getAuthorities() != null) {
Set<Authority> authorities = new HashSet<>();
managedUserDTO.getAuthorities().stream().forEach(
authority -> authorities.add(authorityRepository.findOne(authority))
);
user.setAuthorities(authorities);
}
String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
user.setPassword(encryptedPassword);
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(ZonedDateTime.now());
user.setActivated(true);
userRepository.save(user);
log.debug("Created Information for User: {}", user);
return user;
}
public void updateUserInformation(String firstName, String lastName, String email, String langKey) {
userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(u -> {
u.setFirstName(firstName);
u.setLastName(lastName);
u.setEmail(email);
u.setLangKey(langKey);
userRepository.save(u);
log.debug("Changed Information for User: {}", u);
});
}
public void deleteUserInformation(String login) {
userRepository.findOneByLogin(login).ifPresent(u -> {
socialService.deleteUserSocialConnection(u.getLogin());
userRepository.delete(u);
log.debug("Deleted User: {}", u);
});
}
public void changePassword(String password) {
userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(u -> {
String encryptedPassword = passwordEncoder.encode(password);
u.setPassword(encryptedPassword);
userRepository.save(u);
log.debug("Changed password for User: {}", u);
});
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneByLogin(login).map(u -> {
u.getAuthorities().size();
return u;
});
}
@Transactional(readOnly = true)
public User getUserWithAuthorities(Long id) {
User user = userRepository.findOne(id);
user.getAuthorities().size(); // eagerly load the association
return user;
}
@Transactional(readOnly = true)
public User getUserWithAuthorities() {
User user = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).get();
user.getAuthorities().size(); // eagerly load the association
return user;
}
/**
* Persistent Token are used for providing automatic authentication, they should be automatically deleted after
* 30 days.
* <p>
* This is scheduled to get fired everyday, at midnight.
* </p>
*/
@Scheduled(cron = "0 0 0 * * ?")
public void removeOldPersistentTokens() {
LocalDate now = LocalDate.now();
persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1)).stream().forEach(token -> {
log.debug("Deleting token {}", token.getSeries());
User user = token.getUser();
user.getPersistentTokens().remove(token);
persistentTokenRepository.delete(token);
});
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
* This is scheduled to get fired everyday, at 01:00 (am).
* </p>
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
ZonedDateTime now = ZonedDateTime.now();
List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3));
for (User user : users) {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
}
}
}
| |
/*
* Copyright (c) 2010 Red Hat, 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.ovirt.engine.api.restapi.resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import org.ovirt.engine.api.common.util.JAXBHelper;
import org.ovirt.engine.api.common.util.LinkHelper;
import org.ovirt.engine.api.common.util.LinkHelper.LinkFlags;
import org.ovirt.engine.api.common.util.QueryHelper;
import org.ovirt.engine.api.model.API;
import org.ovirt.engine.api.model.ApiSummary;
import org.ovirt.engine.api.model.BaseResource;
import org.ovirt.engine.api.model.DetailedLink;
import org.ovirt.engine.api.model.Hosts;
import org.ovirt.engine.api.model.Link;
import org.ovirt.engine.api.model.LinkHeader;
import org.ovirt.engine.api.model.ObjectFactory;
//import org.ovirt.engine.api.model.Parameter;
//import org.ovirt.engine.api.model.ParametersSet;
import org.ovirt.engine.api.model.ProductInfo;
import org.ovirt.engine.api.model.RSDL;
//import org.ovirt.engine.api.model.SpecialObjects;
//import org.ovirt.engine.api.model.StorageDomains;
import org.ovirt.engine.api.model.Users;
//import org.ovirt.engine.api.model.VMs;
import org.ovirt.engine.api.resource.ApiResource;
import org.ovirt.engine.api.common.util.FileUtils;
import org.ovirt.engine.api.restapi.util.VersionHelper;
import org.ovirt.engine.core.common.queries.ConfigurationValues;
import org.ovirt.engine.core.common.queries.GetSystemStatisticsQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.api.restapi.rsdl.RsdlBuilder;
import org.ovirt.engine.api.restapi.rsdl.SchemaBuilder;
public class BackendApiResource
extends BackendResource
implements ApiResource {
private static final String SYSTEM_STATS_ERROR = "Unknown error querying system statistics";
private static final String RESOURCES_PACKAGE = "org.ovirt.engine.api.resource";
private static final String API_SCHEMA = "api.xsd";
private static final String RSDL_CONSTRAINT_PARAMETER = "rsdl";
private static final String RSDL_REL = "rsdl";
private static final String SCHEMA_REL = "schema";
private static final String SCHEMA_CONSTRAINT_PARAMETER = "schema";
private static final String RSDL_DESCRIPTION = "The Gluster RESTful API description language.";
private static final String SCHEMA_DESCRIPTION = "oVirt API entities schema.";
private static final String SCHEMA_NAME = "ovirt-engine-api-schema.xsd";
private static RSDL rsdl = null;
private static final String QUERY_PARAMETER = "?";
protected final ObjectFactory OBJECT_FACTORY = new ObjectFactory();
private Collection<DetailedLink> getLinks() {
Collection<DetailedLink> links = new LinkedList<DetailedLink>();
// links.add(createLink("capabilities"));
links.add(createLink("clusters", LinkFlags.SEARCHABLE));
links.add(createLink("datacenters", LinkFlags.SEARCHABLE));
// links.add(createLink("events", LinkFlags.SEARCHABLE, getEventParams()));
links.add(createLink("hosts", LinkFlags.SEARCHABLE));
// links.add(createLink("networks"));
// links.add(createLink("roles"));
// links.add(createLink("storagedomains", LinkFlags.SEARCHABLE));
// links.add(createLink("tags"));
// links.add(createLink("templates", LinkFlags.SEARCHABLE));
// links.add(createLink("users", LinkFlags.SEARCHABLE));
// links.add(createLink("groups", LinkFlags.SEARCHABLE));
// links.add(createLink("domains"));
// links.add(createLink("vmpools", LinkFlags.SEARCHABLE));
// links.add(createLink("vms", LinkFlags.SEARCHABLE));
return links;
}
private API getApi() {
API api = new API();
for (DetailedLink detailedLink : getLinks()) {
//add thin link
api.getLinks().add(LinkHelper.createLink(detailedLink.getHref(), detailedLink.getRel()));
//when required - add extra link for search
if (detailedLink.isSetLinkCapabilities() && detailedLink.getLinkCapabilities().isSetSearchable() && detailedLink.getLinkCapabilities().isSearchable()) {
api.getLinks().add(LinkHelper.createLink(detailedLink.getHref(), detailedLink.getRel(), detailedLink.getRequest().getUrl().getParametersSets()));
}
}
return api;
}
// private ParametersSet getEventParams() {
// ParametersSet ps = new ParametersSet();
// Parameter param = new Parameter();
// param.setName("from");
// param.setValue("event_id");
// ps.getParameters().add(param);
// return ps;
// }
public List<String> getRels() {
List<String> rels = new ArrayList<String>();
for (Link link : getLinks()) {
rels.add(link.getRel());
}
return rels;
}
// private BaseResource getSpecialObjects(API api) {
// api.setSpecialObjects(new SpecialObjects());
// return api.getSpecialObjects();
// }
//
// private String getTagRootUri() {
// return LinkHelper.combine(getUriInfo().getBaseUri().getPath(), "tags/00000000-0000-0000-0000-000000000000");
// }
//
// private String getTemplateBlankUri() {
// return LinkHelper.combine(getUriInfo().getBaseUri().getPath(), "templates/00000000-0000-0000-0000-000000000000");
// }
//
// private void addStaticLinks(List<Link> linker, String[] rels, String[] refs) {
// if(rels.length == refs.length){
// for(int i = 0; i < rels.length; i++){
// Link link = new Link();
// link.setRel(rels[i]);
// link.setHref(refs[i]);
// linker.add(link);
// }
// }
// }
private DetailedLink createLink(String rel, LinkFlags flags) {
return LinkHelper.createLink(getUriInfo().getBaseUri().getPath(), rel, flags);
}
// private DetailedLink createLink(String rel, LinkFlags flags, ParametersSet params) {
// return LinkHelper.createLink(getUriInfo().getBaseUri().getPath(), rel, flags, params);
// }
//
// private DetailedLink createLink(String rel) {
// return LinkHelper.createLink(getUriInfo().getBaseUri().getPath(), rel, LinkFlags.NONE);
// }
private String addPath(UriBuilder uriBuilder, Link link) {
String query = "";
String path = relative(link);
// otherwise UriBuilder.build() will substitute {query}
if (path.contains("?")) {
query = path.substring(path.indexOf("?"));
path = path.substring(0, path.indexOf("?"));
}
link = JAXBHelper.clone(OBJECT_FACTORY.createLink(link));
link.setHref(uriBuilder.clone().path(path).build() + query);
return LinkHeader.format(link);
}
private void addHeader(BaseResource response, Response.ResponseBuilder responseBuilder, UriBuilder uriBuilder) {
// concantenate links in a single header with a comma-separated value,
// which is the canonical form according to:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
//
StringBuffer header = new StringBuffer();
for (Link l : response.getLinks()) {
header.append(addPath(uriBuilder, l)).append(",");
}
header.setLength(header.length() - 1);
responseBuilder.header("Link", header);
}
private Response.ResponseBuilder getResponseBuilder(BaseResource response) {
UriBuilder uriBuilder = getUriInfo().getBaseUriBuilder();
Response.ResponseBuilder responseBuilder = Response.ok();
if(response instanceof API) {
addHeader(response, responseBuilder, uriBuilder);
}
return responseBuilder;
}
@Override
public Response head() {
API api = getApi();
return getResponseBuilder(api).build();
}
@Override
public Response get() {
if (QueryHelper.hasConstraint(getUriInfo(), RSDL_CONSTRAINT_PARAMETER)) {
RSDL rsdl = addSystemVersion(getRSDL());
return Response.ok().entity(rsdl).build();
} else if (QueryHelper.hasConstraint(getUriInfo(), SCHEMA_CONSTRAINT_PARAMETER)) {
return getSchema();
} else {
BaseResource response = addSummary(addSystemVersion(getApi()));
return getResponseBuilder(response).entity(response).build();
}
}
private Response getSchema() {
ByteArrayOutputStream baos = null;
InputStream is = null;
int thisLine;
try {
baos = new ByteArrayOutputStream();
is = FileUtils.get(RESOURCES_PACKAGE, API_SCHEMA);
while ((thisLine = is.read()) != -1) {
baos.write(thisLine);
}
baos.flush();
return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition","attachment; filename = " + SCHEMA_NAME)
.build();
} catch (IOException e) {
LOG.error("Loading api.xsd file failed.", e);
return Response.serverError().build();
} finally {
try {
if (baos != null) baos.close();
if (is != null) is.close();
} catch (IOException e) {;}
}
}
private RSDL addSystemVersion(RSDL rsdl) {
rsdl.setVersion(VersionHelper.parseVersion(getConfigurationValue(String.class, ConfigurationValues.VdcVersion, null)));
return rsdl;
}
private synchronized RSDL getRSDL() {
if (rsdl == null) {
rsdl = new RsdlBuilder(this).description(RSDL_DESCRIPTION).
rel(RSDL_REL).
href(getUriInfo().getBaseUri().getPath() + QUERY_PARAMETER + RSDL_CONSTRAINT_PARAMETER).
schema(new SchemaBuilder().rel(SCHEMA_REL)
.href(getUriInfo().getBaseUri().getPath() + QUERY_PARAMETER + SCHEMA_CONSTRAINT_PARAMETER)
.name(SCHEMA_NAME)
.description(SCHEMA_DESCRIPTION)
.build()).
build();
}
return rsdl;
}
private API addSystemVersion(API api) {
api.setProductInfo(new ProductInfo());
api.getProductInfo().setName("oVirt Enterprise Virtualization Engine");
api.getProductInfo().setVendor("Red Hat");
api.getProductInfo().setVersion(VersionHelper.parseVersion(getConfigurationValue(String.class, ConfigurationValues.VdcVersion, null)));
return api;
}
private HashMap<String, Integer> getSystemStatistics() {
try {
VdcQueryReturnValue result = backend.RunQuery(VdcQueryType.GetSystemStatistics,
sessionize(new GetSystemStatisticsQueryParameters(-1)));
if (!result.getSucceeded() || result.getReturnValue() == null) {
String failure;
if (result.getExceptionString() != null) {
failure = localize(result.getExceptionString());
} else {
failure = SYSTEM_STATS_ERROR;
}
throw new BackendFailureException(failure);
}
return asStatisticsMap(result.getReturnValue());
} catch (Exception e) {
return handleError(e, false);
}
}
@SuppressWarnings("unchecked")
private HashMap<String, Integer> asStatisticsMap(Object result) {
return (HashMap<String, Integer>)result;
}
private API addSummary(API api) {
HashMap<String, Integer> stats = getSystemStatistics();
ApiSummary summary = new ApiSummary();
// summary.setVMs(new VMs());
// summary.getVMs().setTotal(get(stats, "total_vms"));
// summary.getVMs().setActive(get(stats, "active_vms"));
summary.setHosts(new Hosts());
summary.getHosts().setTotal(get(stats, "total_vds"));
summary.getHosts().setActive(get(stats, "active_vds"));
summary.setUsers(new Users());
summary.getUsers().setTotal(get(stats, "total_users"));
summary.getUsers().setActive(get(stats, "active_users"));
// summary.setStorageDomains(new StorageDomains());
// summary.getStorageDomains().setTotal(get(stats, "total_storage_domains"));
// summary.getStorageDomains().setActive(get(stats, "active_storage_domains"));
api.setSummary(summary);
return api;
}
private long get(HashMap<String, Integer> stats, String key) {
return stats.get(key).longValue();
}
private String relative(Link link) {
return link.getHref().substring(link.getHref().indexOf(link.getRel().split("/")[0]), link.getHref().length());
}
}
| |
/**
* Copyright 2011 - 2013 OpenCDS.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.opencds.vmr.v1_0.mappings.in;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.omg.dss.DSSRuntimeExceptionFault;
import org.opencds.vmr.v1_0.internal.AdministrableSubstance;
import org.opencds.vmr.v1_0.internal.AdverseEvent;
import org.opencds.vmr.v1_0.internal.AppointmentProposal;
import org.opencds.vmr.v1_0.internal.AppointmentRequest;
import org.opencds.vmr.v1_0.internal.Assertion;
import org.opencds.vmr.v1_0.internal.CDSInput;
import org.opencds.vmr.v1_0.internal.CDSOutput;
import org.opencds.vmr.v1_0.internal.ClinicalStatementRelationship;
import org.opencds.vmr.v1_0.internal.DeniedAdverseEvent;
import org.opencds.vmr.v1_0.internal.DeniedProblem;
import org.opencds.vmr.v1_0.internal.EncounterEvent;
import org.opencds.vmr.v1_0.internal.Entity;
import org.opencds.vmr.v1_0.internal.EntityRelationship;
import org.opencds.vmr.v1_0.internal.EvalTime;
import org.opencds.vmr.v1_0.internal.EvaluatedPerson;
import org.opencds.vmr.v1_0.internal.EvaluatedPersonAgeAtEvalTime;
import org.opencds.vmr.v1_0.internal.EvaluatedPersonRelationship;
import org.opencds.vmr.v1_0.internal.Facility;
import org.opencds.vmr.v1_0.internal.FocalPersonId;
import org.opencds.vmr.v1_0.internal.Goal;
import org.opencds.vmr.v1_0.internal.GoalProposal;
import org.opencds.vmr.v1_0.internal.MissedAppointment;
import org.opencds.vmr.v1_0.internal.NamedObject;
import org.opencds.vmr.v1_0.internal.ObservationOrder;
import org.opencds.vmr.v1_0.internal.ObservationProposal;
import org.opencds.vmr.v1_0.internal.ObservationResult;
import org.opencds.vmr.v1_0.internal.Organization;
import org.opencds.vmr.v1_0.internal.Person;
import org.opencds.vmr.v1_0.internal.Problem;
import org.opencds.vmr.v1_0.internal.ProcedureEvent;
import org.opencds.vmr.v1_0.internal.ProcedureOrder;
import org.opencds.vmr.v1_0.internal.ProcedureProposal;
import org.opencds.vmr.v1_0.internal.ScheduledAppointment;
import org.opencds.vmr.v1_0.internal.ScheduledProcedure;
import org.opencds.vmr.v1_0.internal.Specimen;
import org.opencds.vmr.v1_0.internal.SubstanceAdministrationEvent;
import org.opencds.vmr.v1_0.internal.SubstanceAdministrationOrder;
import org.opencds.vmr.v1_0.internal.SubstanceAdministrationProposal;
import org.opencds.vmr.v1_0.internal.SubstanceDispensationEvent;
import org.opencds.vmr.v1_0.internal.SupplyEvent;
import org.opencds.vmr.v1_0.internal.SupplyOrder;
import org.opencds.vmr.v1_0.internal.SupplyProposal;
import org.opencds.vmr.v1_0.internal.UnconductedObservation;
import org.opencds.vmr.v1_0.internal.UndeliveredProcedure;
import org.opencds.vmr.v1_0.internal.UndeliveredSubstanceAdministration;
import org.opencds.vmr.v1_0.internal.UndeliveredSupply;
import org.opencds.vmr.v1_0.internal.VMR;
/**
* Collection of FactLists for input to Drools, moved to this class from BuildCDSInputFactLists.java
*
* @author David Shields
*
*/
public class FactLists
{
// ================= Send these as both globals and as facts =======================//
public List<FocalPersonId> focalPersonIdList = Collections.synchronizedList(new ArrayList<FocalPersonId>());
public List<EvalTime> evalTimeList = Collections.synchronizedList(new ArrayList<EvalTime>());
// ================= Helper lists for temporary data elements within Drools =======================//
public List<Assertion> assertionList = Collections.synchronizedList(new ArrayList<Assertion>());
public List<NamedObject> namedObjectList = Collections.synchronizedList(new ArrayList<NamedObject>());
// ================= VMR (in same order as schema, alpha within category) =======================//
// following deprecated since the ids are easily found in internalEvaluatedPersonList des 2012-02-20
// public List<String> evaluatedPersonIdList = Collections.synchronizedList(new ArrayList<String>());
/* Extended VMR Datatypes */
/* Entities */
public List<AdministrableSubstance> internalAdministrableSubstanceList = Collections.synchronizedList(new ArrayList<AdministrableSubstance>());
public List<Entity> internalEntityList = Collections.synchronizedList(new ArrayList<Entity>());
public List<EvaluatedPerson> internalEvaluatedPersonList = Collections.synchronizedList(new ArrayList<EvaluatedPerson>());
public List<EvaluatedPersonAgeAtEvalTime> internalPersonAgeAtEvalTimeList = Collections.synchronizedList(new ArrayList<EvaluatedPersonAgeAtEvalTime>());
public List<Facility> internalFacilityList = Collections.synchronizedList(new ArrayList<Facility>());
public List<Organization> internalOrganizationList = Collections.synchronizedList(new ArrayList<Organization>());
public List<Person> internalPersonList = Collections.synchronizedList(new ArrayList<Person>());
public List<Specimen> internalSpecimenList = Collections.synchronizedList(new ArrayList<Specimen>());
/* Relationships */
// following list deprecated des 201202-11
// public List<ClinicalStatementEntityInRoleRelationship> internalClinicalStatementEntityInRoleRelationshipList = new ArrayList<ClinicalStatementEntityInRoleRelationship>());
public List<ClinicalStatementRelationship> internalClinicalStatementRelationshipList = Collections.synchronizedList(new ArrayList<ClinicalStatementRelationship>());
public List<EntityRelationship> internalEntityRelationshipList = Collections.synchronizedList(new ArrayList<EntityRelationship>());
public List<EvaluatedPersonRelationship> internalEvaluatedPersonRelationshipList = Collections.synchronizedList(new ArrayList<EvaluatedPersonRelationship>());
/* The Whole Thing */
public List<CDSInput> internalCDSInputList = Collections.synchronizedList(new ArrayList<CDSInput>());
public List<CDSOutput> internalCDSOutputList = Collections.synchronizedList(new ArrayList<CDSOutput>());
public List<VMR> internalVMRList = Collections.synchronizedList(new ArrayList<VMR>());
/* BaseClinicalStatement */
/* Adverse Event Clinical Statements */
public List<AdverseEvent> internalAdverseEventList = Collections.synchronizedList(new ArrayList<AdverseEvent>());
public List<DeniedAdverseEvent> internalDeniedAdverseEventList = Collections.synchronizedList(new ArrayList<DeniedAdverseEvent>());
/* Encounter Clinical Statements */
public List<AppointmentProposal> internalAppointmentProposalList = Collections.synchronizedList(new ArrayList<AppointmentProposal>());
public List<AppointmentRequest> internalAppointmentRequestList = Collections.synchronizedList(new ArrayList<AppointmentRequest>());
public List<EncounterEvent> internalEncounterEventList = Collections.synchronizedList(new ArrayList<EncounterEvent>());
public List<MissedAppointment> internalMissedAppointmentList = Collections.synchronizedList(new ArrayList<MissedAppointment>());
public List<ScheduledAppointment> internalScheduledAppointmentList = Collections.synchronizedList(new ArrayList<ScheduledAppointment>());
/* Goal Clinical Statements */
public List<Goal> internalGoalList = Collections.synchronizedList(new ArrayList<Goal>());
public List<GoalProposal> internalGoalProposalList = Collections.synchronizedList(new ArrayList<GoalProposal>());
/* Observation Clinical Statements */
public List<ObservationOrder> internalObservationOrderList = Collections.synchronizedList(new ArrayList<ObservationOrder>());
public List<ObservationProposal> internalObservationProposalList = Collections.synchronizedList(new ArrayList<ObservationProposal>());
public List<ObservationResult> internalObservationResultList = Collections.synchronizedList(new ArrayList<ObservationResult>());
public List<UnconductedObservation> internalUnconductedObservationList = Collections.synchronizedList(new ArrayList<UnconductedObservation>());
/* Problem Clinical Statements */
public List<DeniedProblem> internalDeniedProblemList = Collections.synchronizedList(new ArrayList<DeniedProblem>());
public List<Problem> internalProblemList = Collections.synchronizedList(new ArrayList<Problem>());
/* Procedure Clinical Statements */
public List<ProcedureEvent> internalProcedureEventList = Collections.synchronizedList(new ArrayList<ProcedureEvent>());
public List<ProcedureOrder> internalProcedureOrderList = Collections.synchronizedList(new ArrayList<ProcedureOrder>());
public List<ProcedureProposal> internalProcedureProposalList = Collections.synchronizedList(new ArrayList<ProcedureProposal>());
public List<ScheduledProcedure> internalScheduledProcedureList = Collections.synchronizedList(new ArrayList<ScheduledProcedure>());
public List<UndeliveredProcedure> internalUndeliveredProcedureList = Collections.synchronizedList(new ArrayList<UndeliveredProcedure>());
/* Substance Administration Clinical Statements */
public List<SubstanceAdministrationEvent> internalSubstanceAdministrationEventList = Collections.synchronizedList(new ArrayList<SubstanceAdministrationEvent>());
public List<SubstanceAdministrationOrder> internalSubstanceAdministrationOrderList = Collections.synchronizedList(new ArrayList<SubstanceAdministrationOrder>());
public List<SubstanceAdministrationProposal> internalSubstanceAdministrationProposalList = Collections.synchronizedList(new ArrayList<SubstanceAdministrationProposal>());
public List<SubstanceDispensationEvent> internalSubstanceDispensationEventList = Collections.synchronizedList(new ArrayList<SubstanceDispensationEvent>());
public List<UndeliveredSubstanceAdministration> internalUndeliveredSubstanceAdministrationList = Collections.synchronizedList(new ArrayList<UndeliveredSubstanceAdministration>());
/* Supply Clinical Statements */
public List<SupplyEvent> internalSupplyEventList = Collections.synchronizedList(new ArrayList<SupplyEvent>());
public List<SupplyOrder> internalSupplyOrderList = Collections.synchronizedList(new ArrayList<SupplyOrder>());
public List<SupplyProposal> internalSupplyProposalList = Collections.synchronizedList(new ArrayList<SupplyProposal>());
public List<UndeliveredSupply> internalUndeliveredSupplyList = Collections.synchronizedList(new ArrayList<UndeliveredSupply>());
public synchronized void clearAllFactLists() throws DSSRuntimeExceptionFault
{
focalPersonIdList.clear();
evalTimeList.clear();
assertionList.clear();
namedObjectList.clear();
internalAdministrableSubstanceList.clear();
internalEntityList.clear();
internalEvaluatedPersonList.clear();
internalPersonAgeAtEvalTimeList.clear();
internalFacilityList.clear();
internalOrganizationList.clear();
internalPersonList.clear();
internalSpecimenList.clear();
internalClinicalStatementRelationshipList.clear();
internalEntityRelationshipList.clear();
internalEvaluatedPersonRelationshipList.clear();
internalCDSInputList.clear();
internalCDSOutputList.clear();
internalVMRList.clear();
internalAdverseEventList.clear();
internalDeniedAdverseEventList.clear();
internalAppointmentProposalList.clear();
internalAppointmentRequestList.clear();
internalEncounterEventList.clear();
internalMissedAppointmentList.clear();
internalScheduledAppointmentList.clear();
internalGoalList.clear();
internalGoalProposalList.clear();
internalObservationOrderList.clear();
internalObservationProposalList.clear();
internalObservationResultList.clear();
internalUnconductedObservationList.clear();
internalDeniedProblemList.clear();
internalProblemList.clear();
internalProcedureEventList.clear();
internalProcedureOrderList.clear();
internalProcedureOrderList.clear();
internalScheduledProcedureList.clear();
internalUndeliveredProcedureList.clear();
internalSubstanceAdministrationEventList.clear();
internalSubstanceAdministrationOrderList.clear();
internalSubstanceAdministrationProposalList.clear();
internalSubstanceDispensationEventList.clear();
internalUndeliveredSubstanceAdministrationList.clear();
internalSupplyEventList.clear();
internalSupplyOrderList.clear();
internalSupplyProposalList.clear();
internalUndeliveredSupplyList.clear();
}
public synchronized void populateAllFactLists(Map<String,List<?>> allFactLists)
{
//moved to globals addToAllFactLists(allFactLists, focalPersonIdList);
//changed back to both exist as global and as factList, des 20111212
if (focalPersonIdList.size() > 0) allFactLists.put("FocalPersonId", focalPersonIdList);
if (evalTimeList.size() > 0) allFactLists.put("EvalTime", evalTimeList);
/* Extended VMR Datatypes */
/* Entities */
if (internalAdministrableSubstanceList.size() > 0) allFactLists.put("AdministrableSubstance", internalAdministrableSubstanceList);
if (internalEntityList.size() > 0) allFactLists.put("Entity", internalEntityList);
if (internalEvaluatedPersonList.size() > 0) allFactLists.put("EvaluatedPerson", internalEvaluatedPersonList);
if (internalPersonAgeAtEvalTimeList.size() > 0) allFactLists.put("PersonAgeAtEvalTime", internalPersonAgeAtEvalTimeList);
if (internalFacilityList.size() > 0) allFactLists.put("Facility", internalFacilityList);
if (internalOrganizationList.size() > 0) allFactLists.put("Organization", internalOrganizationList);
if (internalPersonList.size() > 0) allFactLists.put("Person", internalPersonList);
if (internalSpecimenList.size() > 0) allFactLists.put("Specimen", internalSpecimenList);
/* Relationships */
// following deprecated des 2012-02-14
// if (internalClinicalStatementEntityInRoleRelationshipList() > 0) allFactLists.put("FocalPersonId", internalClinicalStatementEntityInRoleRelationshipList);
if (internalClinicalStatementRelationshipList.size() > 0) allFactLists.put("ClinicalStatementRelationship", internalClinicalStatementRelationshipList);
if (internalEntityRelationshipList.size() > 0) allFactLists.put("EntityRelationship", internalEntityRelationshipList);
if (internalEvaluatedPersonRelationshipList.size() > 0) allFactLists.put("EvaluatedPersonRelationship", internalEvaluatedPersonRelationshipList);
/* The Whole Thing */
if (internalCDSInputList.size() > 0) allFactLists.put("CDSInput", internalCDSInputList);
if (internalCDSOutputList.size() > 0) allFactLists.put("CDSOutput", internalCDSOutputList);
if (internalVMRList.size() > 0) allFactLists.put("VMR", internalVMRList);
/* BaseClinicalStatement */
/* Adverse Event Clinical Statements */
if (internalAdverseEventList.size() > 0) allFactLists.put("AdverseEvent", internalAdverseEventList);
if (internalDeniedAdverseEventList.size() > 0) allFactLists.put("DeniedAdverseEvent", internalDeniedAdverseEventList);
/* Encounter Clinical Statements */
if (internalAppointmentProposalList.size() > 0) allFactLists.put("AppointmentProposal", internalAppointmentProposalList);
if (internalAppointmentRequestList.size() > 0) allFactLists.put("AppointmentRequest", internalAppointmentRequestList);
if (internalEncounterEventList.size() > 0) allFactLists.put("EncounterEvent", internalEncounterEventList);
if (internalMissedAppointmentList.size() > 0) allFactLists.put("MissedAppointment", internalMissedAppointmentList);
if (internalScheduledAppointmentList.size() > 0) allFactLists.put("ScheduledAppointment", internalScheduledAppointmentList);
/* Goal Clinical Statements */
if (internalGoalList.size() > 0) allFactLists.put("Goal", internalGoalList);
if (internalGoalProposalList.size() > 0) allFactLists.put("GoalProposal", internalGoalProposalList);
/* Observation Clinical Statements */
if (internalObservationOrderList.size() > 0) allFactLists.put("ObservationOrder", internalObservationOrderList);
if (internalObservationProposalList.size() > 0) allFactLists.put("ObservationProposal", internalObservationProposalList);
if (internalObservationResultList.size() > 0) allFactLists.put("ObservationResult", internalObservationResultList);
if (internalUnconductedObservationList.size() > 0) allFactLists.put("UnconductedObservation", internalUnconductedObservationList);
/* Problem Clinical Statements */
if (internalDeniedProblemList.size() > 0) allFactLists.put("DeniedProblem", internalDeniedProblemList);
if (internalProblemList.size() > 0) allFactLists.put("Problem", internalProblemList);
/* Procedure Clinical Statements */
if (internalProcedureEventList.size() > 0) allFactLists.put("ProcedureEvent", internalProcedureEventList);
if (internalProcedureOrderList.size() > 0) allFactLists.put("ProcedureOrder", internalProcedureOrderList);
if (internalProcedureProposalList.size() > 0) allFactLists.put("ProcedureProposal", internalProcedureProposalList);
if (internalScheduledProcedureList.size() > 0) allFactLists.put("ScheduledProcedure", internalScheduledProcedureList);
if (internalUndeliveredProcedureList.size() > 0) allFactLists.put("UndeliveredProcedure", internalUndeliveredProcedureList);
/* Substance Administration Clinical Statements */
if (internalSubstanceAdministrationEventList.size() > 0) allFactLists.put("SubstanceAdministrationEvent", internalSubstanceAdministrationEventList);
if (internalSubstanceAdministrationOrderList.size() > 0) allFactLists.put("SubstanceAdministrationOrder", internalSubstanceAdministrationOrderList);
if (internalSubstanceAdministrationProposalList.size() > 0) allFactLists.put("SubstanceAdministrationProposal", internalSubstanceAdministrationProposalList);
if (internalSubstanceDispensationEventList.size() > 0) allFactLists.put("SubstanceDispensationEvent", internalSubstanceDispensationEventList);
if (internalUndeliveredSubstanceAdministrationList.size() > 0) allFactLists.put("UndeliveredSubstanceAdministration", internalUndeliveredSubstanceAdministrationList);
/* Supply Clinical Statements */
if (internalSupplyEventList.size() > 0) allFactLists.put("SupplyEvent", internalSupplyEventList);
if (internalSupplyOrderList.size() > 0) allFactLists.put("SupplyOrder", internalSupplyOrderList);
if (internalSupplyProposalList.size() > 0) allFactLists.put("SupplyProposal", internalSupplyProposalList);
if (internalUndeliveredSupplyList.size() > 0) allFactLists.put("UndeliveredSupply", internalUndeliveredSupplyList);
}
}
| |
/*
* Copyright (C) 2008 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.dx.dex.code;
import com.android.dx.rop.code.BasicBlock;
import com.android.dx.rop.code.BasicBlockList;
import com.android.dx.rop.code.RopMethod;
import com.android.dx.rop.cst.CstType;
import com.android.dx.rop.type.Type;
import com.android.dx.rop.type.TypeList;
import com.android.dx.util.IntList;
import java.util.ArrayList;
import java.util.HashSet;
/**
* Constructor of {@link CatchTable} instances from {@link RopMethod}
* and associated data.
*/
public final class StdCatchBuilder implements CatchBuilder {
/** the maximum range of a single catch handler, in code units */
private static final int MAX_CATCH_RANGE = 65535;
/** {@code non-null;} method to build the list for */
private final RopMethod method;
/** {@code non-null;} block output order */
private final int[] order;
/** {@code non-null;} address objects for each block */
private final BlockAddresses addresses;
/**
* Constructs an instance. It merely holds onto its parameters for
* a subsequent call to {@link #build}.
*
* @param method {@code non-null;} method to build the list for
* @param order {@code non-null;} block output order
* @param addresses {@code non-null;} address objects for each block
*/
public StdCatchBuilder(RopMethod method, int[] order,
BlockAddresses addresses) {
if (method == null) {
throw new NullPointerException("method == null");
}
if (order == null) {
throw new NullPointerException("order == null");
}
if (addresses == null) {
throw new NullPointerException("addresses == null");
}
this.method = method;
this.order = order;
this.addresses = addresses;
}
/** {@inheritDoc} */
public CatchTable build() {
return build(method, order, addresses);
}
/** {@inheritDoc} */
public boolean hasAnyCatches() {
BasicBlockList blocks = method.getBlocks();
int size = blocks.size();
for (int i = 0; i < size; i++) {
BasicBlock block = blocks.get(i);
TypeList catches = block.getLastInsn().getCatches();
if (catches.size() != 0) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
public HashSet<Type> getCatchTypes() {
HashSet<Type> result = new HashSet<Type>(20);
BasicBlockList blocks = method.getBlocks();
int size = blocks.size();
for (int i = 0; i < size; i++) {
BasicBlock block = blocks.get(i);
TypeList catches = block.getLastInsn().getCatches();
int catchSize = catches.size();
for (int j = 0; j < catchSize; j++) {
result.add(catches.getType(j));
}
}
return result;
}
/**
* Builds and returns the catch table for a given method.
*
* @param method {@code non-null;} method to build the list for
* @param order {@code non-null;} block output order
* @param addresses {@code non-null;} address objects for each block
* @return {@code non-null;} the constructed table
*/
public static CatchTable build(RopMethod method, int[] order,
BlockAddresses addresses) {
int len = order.length;
BasicBlockList blocks = method.getBlocks();
ArrayList<CatchTable.Entry> resultList =
new ArrayList<CatchTable.Entry>(len);
CatchHandlerList currentHandlers = CatchHandlerList.EMPTY;
BasicBlock currentStartBlock = null;
BasicBlock currentEndBlock = null;
for (int i = 0; i < len; i++) {
BasicBlock block = blocks.labelToBlock(order[i]);
if (!block.canThrow()) {
/*
* There is no need to concern ourselves with the
* placement of blocks that can't throw with respect
* to the blocks that *can* throw.
*/
continue;
}
CatchHandlerList handlers = handlersFor(block, addresses);
if (currentHandlers.size() == 0) {
// This is the start of a new catch range.
currentStartBlock = block;
currentEndBlock = block;
currentHandlers = handlers;
continue;
}
if (currentHandlers.equals(handlers)
&& rangeIsValid(currentStartBlock, block, addresses)) {
/*
* The block we are looking at now has the same handlers
* as the block that started the currently open catch
* range, and adding it to the currently open range won't
* cause it to be too long.
*/
currentEndBlock = block;
continue;
}
/*
* The block we are looking at now has incompatible handlers,
* so we need to finish off the last entry and start a new
* one. Note: We only emit an entry if it has associated handlers.
*/
if (currentHandlers.size() != 0) {
CatchTable.Entry entry =
makeEntry(currentStartBlock, currentEndBlock,
currentHandlers, addresses);
resultList.add(entry);
}
currentStartBlock = block;
currentEndBlock = block;
currentHandlers = handlers;
}
if (currentHandlers.size() != 0) {
// Emit an entry for the range that was left hanging.
CatchTable.Entry entry =
makeEntry(currentStartBlock, currentEndBlock,
currentHandlers, addresses);
resultList.add(entry);
}
// Construct the final result.
int resultSz = resultList.size();
if (resultSz == 0) {
return CatchTable.EMPTY;
}
CatchTable result = new CatchTable(resultSz);
for (int i = 0; i < resultSz; i++) {
result.set(i, resultList.get(i));
}
result.setImmutable();
return result;
}
/**
* Makes the {@link CatchHandlerList} for the given basic block.
*
* @param block {@code non-null;} block to get entries for
* @param addresses {@code non-null;} address objects for each block
* @return {@code non-null;} array of entries
*/
private static CatchHandlerList handlersFor(BasicBlock block,
BlockAddresses addresses) {
IntList successors = block.getSuccessors();
int succSize = successors.size();
int primary = block.getPrimarySuccessor();
TypeList catches = block.getLastInsn().getCatches();
int catchSize = catches.size();
if (catchSize == 0) {
return CatchHandlerList.EMPTY;
}
if (((primary == -1) && (succSize != catchSize))
|| ((primary != -1) &&
((succSize != (catchSize + 1))
|| (primary != successors.get(catchSize))))) {
/*
* Blocks that throw are supposed to list their primary
* successor -- if any -- last in the successors list, but
* that constraint appears to be violated here.
*/
throw new RuntimeException(
"shouldn't happen: weird successors list");
}
/*
* Reduce the effective catchSize if we spot a catch-all that
* isn't at the end.
*/
for (int i = 0; i < catchSize; i++) {
Type type = catches.getType(i);
if (type.equals(Type.OBJECT)) {
catchSize = i + 1;
break;
}
}
CatchHandlerList result = new CatchHandlerList(catchSize);
for (int i = 0; i < catchSize; i++) {
CstType oneType = new CstType(catches.getType(i));
CodeAddress oneHandler = addresses.getStart(successors.get(i));
result.set(i, oneType, oneHandler.getAddress());
}
result.setImmutable();
return result;
}
/**
* Makes a {@link CatchTable#Entry} for the given block range and
* handlers.
*
* @param start {@code non-null;} the start block for the range (inclusive)
* @param end {@code non-null;} the start block for the range (also inclusive)
* @param handlers {@code non-null;} the handlers for the range
* @param addresses {@code non-null;} address objects for each block
*/
private static CatchTable.Entry makeEntry(BasicBlock start,
BasicBlock end, CatchHandlerList handlers,
BlockAddresses addresses) {
/*
* We start at the *last* instruction of the start block, since
* that's the instruction that can throw...
*/
CodeAddress startAddress = addresses.getLast(start);
// ...And we end *after* the last instruction of the end block.
CodeAddress endAddress = addresses.getEnd(end);
return new CatchTable.Entry(startAddress.getAddress(),
endAddress.getAddress(), handlers);
}
/**
* Gets whether the address range for the given two blocks is valid
* for a catch handler. This is true as long as the covered range is
* under 65536 code units.
*
* @param start {@code non-null;} the start block for the range (inclusive)
* @param end {@code non-null;} the start block for the range (also inclusive)
* @param addresses {@code non-null;} address objects for each block
* @return {@code true} if the range is valid as a catch range
*/
private static boolean rangeIsValid(BasicBlock start, BasicBlock end,
BlockAddresses addresses) {
if (start == null) {
throw new NullPointerException("start == null");
}
if (end == null) {
throw new NullPointerException("end == null");
}
// See above about selection of instructions.
int startAddress = addresses.getLast(start).getAddress();
int endAddress = addresses.getEnd(end).getAddress();
return (endAddress - startAddress) <= MAX_CATCH_RANGE;
}
}
| |
package org.cagrid.dorian;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.cagrid.dorian.model.idp.LocalUserFilter;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy;
import org.jvnet.jaxb2_commons.lang.HashCode;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy;
import org.jvnet.jaxb2_commons.lang.ToString;
import org.jvnet.jaxb2_commons.lang.ToStringStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="f">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://cagrid.nci.nih.gov/1/dorian-idp}LocalUserFilter"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"f"
})
@XmlRootElement(name = "FindLocalUsersRequest")
public class FindLocalUsersRequest
implements Serializable, Equals, HashCode, ToString
{
@XmlElement(required = true)
protected FindLocalUsersRequest.F f;
/**
* Gets the value of the f property.
*
* @return
* possible object is
* {@link FindLocalUsersRequest.F }
*
*/
public FindLocalUsersRequest.F getF() {
return f;
}
/**
* Sets the value of the f property.
*
* @param value
* allowed object is
* {@link FindLocalUsersRequest.F }
*
*/
public void setF(FindLocalUsersRequest.F value) {
this.f = value;
}
public String toString() {
final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
final StringBuilder buffer = new StringBuilder();
append(null, buffer, strategy);
return buffer.toString();
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
strategy.appendStart(locator, this, buffer);
appendFields(locator, buffer, strategy);
strategy.appendEnd(locator, this, buffer);
return buffer;
}
public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
{
FindLocalUsersRequest.F theF;
theF = this.getF();
strategy.appendField(locator, this, "f", buffer, theF);
}
return buffer;
}
public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) {
int currentHashCode = 1;
{
FindLocalUsersRequest.F theF;
theF = this.getF();
currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "f", theF), currentHashCode, theF);
}
return currentHashCode;
}
public int hashCode() {
final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE;
return this.hashCode(null, strategy);
}
public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) {
if (!(object instanceof FindLocalUsersRequest)) {
return false;
}
if (this == object) {
return true;
}
final FindLocalUsersRequest that = ((FindLocalUsersRequest) object);
{
FindLocalUsersRequest.F lhsF;
lhsF = this.getF();
FindLocalUsersRequest.F rhsF;
rhsF = that.getF();
if (!strategy.equals(LocatorUtils.property(thisLocator, "f", lhsF), LocatorUtils.property(thatLocator, "f", rhsF), lhsF, rhsF)) {
return false;
}
}
return true;
}
public boolean equals(Object object) {
final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
return equals(null, null, object, strategy);
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://cagrid.nci.nih.gov/1/dorian-idp}LocalUserFilter"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"localUserFilter"
})
public static class F
implements Serializable, Equals, HashCode, ToString
{
@XmlElement(name = "LocalUserFilter", namespace = "http://cagrid.nci.nih.gov/1/dorian-idp", required = true)
protected LocalUserFilter localUserFilter;
/**
* Gets the value of the localUserFilter property.
*
* @return
* possible object is
* {@link LocalUserFilter }
*
*/
public LocalUserFilter getLocalUserFilter() {
return localUserFilter;
}
/**
* Sets the value of the localUserFilter property.
*
* @param value
* allowed object is
* {@link LocalUserFilter }
*
*/
public void setLocalUserFilter(LocalUserFilter value) {
this.localUserFilter = value;
}
public String toString() {
final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
final StringBuilder buffer = new StringBuilder();
append(null, buffer, strategy);
return buffer.toString();
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
strategy.appendStart(locator, this, buffer);
appendFields(locator, buffer, strategy);
strategy.appendEnd(locator, this, buffer);
return buffer;
}
public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
{
LocalUserFilter theLocalUserFilter;
theLocalUserFilter = this.getLocalUserFilter();
strategy.appendField(locator, this, "localUserFilter", buffer, theLocalUserFilter);
}
return buffer;
}
public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) {
int currentHashCode = 1;
{
LocalUserFilter theLocalUserFilter;
theLocalUserFilter = this.getLocalUserFilter();
currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "localUserFilter", theLocalUserFilter), currentHashCode, theLocalUserFilter);
}
return currentHashCode;
}
public int hashCode() {
final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE;
return this.hashCode(null, strategy);
}
public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) {
if (!(object instanceof FindLocalUsersRequest.F)) {
return false;
}
if (this == object) {
return true;
}
final FindLocalUsersRequest.F that = ((FindLocalUsersRequest.F) object);
{
LocalUserFilter lhsLocalUserFilter;
lhsLocalUserFilter = this.getLocalUserFilter();
LocalUserFilter rhsLocalUserFilter;
rhsLocalUserFilter = that.getLocalUserFilter();
if (!strategy.equals(LocatorUtils.property(thisLocator, "localUserFilter", lhsLocalUserFilter), LocatorUtils.property(thatLocator, "localUserFilter", rhsLocalUserFilter), lhsLocalUserFilter, rhsLocalUserFilter)) {
return false;
}
}
return true;
}
public boolean equals(Object object) {
final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
return equals(null, null, object, strategy);
}
}
}
| |
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.internal.operators.flowable;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.*;
import org.reactivestreams.*;
import io.reactivex.*;
import io.reactivex.annotations.Nullable;
import io.reactivex.exceptions.*;
import io.reactivex.functions.Function;
import io.reactivex.internal.fuseable.*;
import io.reactivex.internal.queue.SpscArrayQueue;
import io.reactivex.internal.subscriptions.*;
import io.reactivex.internal.util.*;
import io.reactivex.plugins.RxJavaPlugins;
public final class FlowableFlattenIterable<T, R> extends AbstractFlowableWithUpstream<T, R> {
final Function<? super T, ? extends Iterable<? extends R>> mapper;
final int prefetch;
public FlowableFlattenIterable(Flowable<T> source,
Function<? super T, ? extends Iterable<? extends R>> mapper, int prefetch) {
super(source);
this.mapper = mapper;
this.prefetch = prefetch;
}
@SuppressWarnings("unchecked")
@Override
public void subscribeActual(Subscriber<? super R> s) {
if (source instanceof Callable) {
T v;
try {
v = ((Callable<T>)source).call();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, s);
return;
}
if (v == null) {
EmptySubscription.complete(s);
return;
}
Iterator<? extends R> it;
try {
Iterable<? extends R> iterable = mapper.apply(v);
it = iterable.iterator();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptySubscription.error(ex, s);
return;
}
FlowableFromIterable.subscribe(s, it);
return;
}
source.subscribe(new FlattenIterableSubscriber<T, R>(s, mapper, prefetch));
}
static final class FlattenIterableSubscriber<T, R>
extends BasicIntQueueSubscription<R>
implements FlowableSubscriber<T> {
private static final long serialVersionUID = -3096000382929934955L;
final Subscriber<? super R> actual;
final Function<? super T, ? extends Iterable<? extends R>> mapper;
final int prefetch;
final int limit;
final AtomicLong requested;
Subscription s;
SimpleQueue<T> queue;
volatile boolean done;
volatile boolean cancelled;
final AtomicReference<Throwable> error;
Iterator<? extends R> current;
int consumed;
int fusionMode;
FlattenIterableSubscriber(Subscriber<? super R> actual,
Function<? super T, ? extends Iterable<? extends R>> mapper, int prefetch) {
this.actual = actual;
this.mapper = mapper;
this.prefetch = prefetch;
this.limit = prefetch - (prefetch >> 2);
this.error = new AtomicReference<Throwable>();
this.requested = new AtomicLong();
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.s, s)) {
this.s = s;
if (s instanceof QueueSubscription) {
@SuppressWarnings("unchecked")
QueueSubscription<T> qs = (QueueSubscription<T>) s;
int m = qs.requestFusion(ANY);
if (m == SYNC) {
fusionMode = m;
this.queue = qs;
done = true;
actual.onSubscribe(this);
return;
}
if (m == ASYNC) {
fusionMode = m;
this.queue = qs;
actual.onSubscribe(this);
s.request(prefetch);
return;
}
}
queue = new SpscArrayQueue<T>(prefetch);
actual.onSubscribe(this);
s.request(prefetch);
}
}
@Override
public void onNext(T t) {
if (done) {
return;
}
if (fusionMode == NONE && !queue.offer(t)) {
onError(new MissingBackpressureException("Queue is full?!"));
return;
}
drain();
}
@Override
public void onError(Throwable t) {
if (!done && ExceptionHelper.addThrowable(error, t)) {
done = true;
drain();
} else {
RxJavaPlugins.onError(t);
}
}
@Override
public void onComplete() {
if (done) {
return;
}
done = true;
drain();
}
@Override
public void request(long n) {
if (SubscriptionHelper.validate(n)) {
BackpressureHelper.add(requested, n);
drain();
}
}
@Override
public void cancel() {
if (!cancelled) {
cancelled = true;
s.cancel();
if (getAndIncrement() == 0) {
queue.clear();
}
}
}
void drain() {
if (getAndIncrement() != 0) {
return;
}
final Subscriber<? super R> a = actual;
final SimpleQueue<T> q = queue;
final boolean replenish = fusionMode != SYNC;
int missed = 1;
Iterator<? extends R> it = current;
for (;;) {
if (it == null) {
boolean d = done;
T t;
try {
t = q.poll();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
s.cancel();
ExceptionHelper.addThrowable(error, ex);
ex = ExceptionHelper.terminate(error);
current = null;
q.clear();
a.onError(ex);
return;
}
boolean empty = t == null;
if (checkTerminated(d, empty, a, q)) {
return;
}
if (t != null) {
Iterable<? extends R> iterable;
boolean b;
try {
iterable = mapper.apply(t);
it = iterable.iterator();
b = it.hasNext();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
s.cancel();
ExceptionHelper.addThrowable(error, ex);
ex = ExceptionHelper.terminate(error);
a.onError(ex);
return;
}
if (!b) {
it = null;
consumedOne(replenish);
continue;
}
current = it;
}
}
if (it != null) {
long r = requested.get();
long e = 0L;
while (e != r) {
if (checkTerminated(done, false, a, q)) {
return;
}
R v;
try {
v = it.next();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
current = null;
s.cancel();
ExceptionHelper.addThrowable(error, ex);
ex = ExceptionHelper.terminate(error);
a.onError(ex);
return;
}
a.onNext(v);
if (checkTerminated(done, false, a, q)) {
return;
}
e++;
boolean b;
try {
b = it.hasNext();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
current = null;
s.cancel();
ExceptionHelper.addThrowable(error, ex);
ex = ExceptionHelper.terminate(error);
a.onError(ex);
return;
}
if (!b) {
consumedOne(replenish);
it = null;
current = null;
break;
}
}
if (e == r) {
boolean d = done;
boolean empty = q.isEmpty() && it == null;
if (checkTerminated(d, empty, a, q)) {
return;
}
}
if (e != 0L) {
if (r != Long.MAX_VALUE) {
requested.addAndGet(-e);
}
}
if (it == null) {
continue;
}
}
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
void consumedOne(boolean enabled) {
if (enabled) {
int c = consumed + 1;
if (c == limit) {
consumed = 0;
s.request(c);
} else {
consumed = c;
}
}
}
boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a, SimpleQueue<?> q) {
if (cancelled) {
current = null;
q.clear();
return true;
}
if (d) {
Throwable ex = error.get();
if (ex != null) {
ex = ExceptionHelper.terminate(error);
current = null;
q.clear();
a.onError(ex);
return true;
} else if (empty) {
a.onComplete();
return true;
}
}
return false;
}
@Override
public void clear() {
current = null;
queue.clear();
}
@Override
public boolean isEmpty() {
Iterator<? extends R> it = current;
if (it == null) {
return queue.isEmpty();
}
return !it.hasNext();
}
@Nullable
@Override
public R poll() throws Exception {
Iterator<? extends R> it = current;
for (;;) {
if (it == null) {
T v = queue.poll();
if (v == null) {
return null;
}
it = mapper.apply(v).iterator();
if (!it.hasNext()) {
it = null;
continue;
}
current = it;
}
R r = it.next();
if (!it.hasNext()) {
current = null;
}
return r;
}
}
@Override
public int requestFusion(int requestedMode) {
if ((requestedMode & SYNC) != 0 && fusionMode == SYNC) {
return SYNC;
}
return NONE;
}
}
}
| |
/*
* 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.cassandra.thrift;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLServerSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.NamedThreadFactory;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.EncryptionOptions.ClientEncryptionOptions;
import org.apache.cassandra.utils.JVMStabilityInspector;
import org.apache.cassandra.security.SSLFactory;
import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.TSSLTransportFactory.TSSLTransportParameters;
import com.google.common.util.concurrent.Uninterruptibles;
/**
* Slightly modified version of the Apache Thrift TThreadPoolServer.
* <p>
* This allows passing an executor so you have more control over the actual
* behaviour of the tasks being run.
* <p/>
* Newer version of Thrift should make this obsolete.
*/
public class CustomTThreadPoolServer extends TServer
{
private static final Logger logger = LoggerFactory.getLogger(CustomTThreadPoolServer.class.getName());
// Executor service for handling client connections
private final ExecutorService executorService;
// Flag for stopping the server
private volatile boolean stopped;
// Server options
private final TThreadPoolServer.Args args;
//Track and Limit the number of connected clients
private final AtomicInteger activeClients = new AtomicInteger(0);
public CustomTThreadPoolServer(TThreadPoolServer.Args args, ExecutorService executorService) {
super(args);
this.executorService = executorService;
this.args = args;
}
@SuppressWarnings("resource")
public void serve()
{
try
{
serverTransport_.listen();
}
catch (TTransportException ttx)
{
logger.error("Error occurred during listening.", ttx);
return;
}
stopped = false;
while (!stopped)
{
// block until we are under max clients
while (activeClients.get() >= args.maxWorkerThreads)
{
Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
}
try
{
TTransport client = serverTransport_.accept();
activeClients.incrementAndGet();
WorkerProcess wp = new WorkerProcess(client);
executorService.execute(wp);
}
catch (TTransportException ttx)
{
if (ttx.getCause() instanceof SocketTimeoutException) // thrift sucks
continue;
if (!stopped)
{
logger.warn("Transport error occurred during acceptance of message.", ttx);
}
}
catch (RejectedExecutionException e)
{
// worker thread decremented activeClients but hadn't finished exiting
logger.debug("Dropping client connection because our limit of {} has been reached", args.maxWorkerThreads);
continue;
}
if (activeClients.get() >= args.maxWorkerThreads)
logger.warn("Maximum number of clients {} reached", args.maxWorkerThreads);
}
executorService.shutdown();
// Thrift's default shutdown waits for the WorkerProcess threads to complete. We do not,
// because doing that allows a client to hold our shutdown "hostage" by simply not sending
// another message after stop is called (since process will block indefinitely trying to read
// the next meessage header).
//
// The "right" fix would be to update thrift to set a socket timeout on client connections
// (and tolerate unintentional timeouts until stopped is set). But this requires deep
// changes to the code generator, so simply setting these threads to daemon (in our custom
// CleaningThreadPool) and ignoring them after shutdown is good enough.
//
// Remember, our goal on shutdown is not necessarily that each client request we receive
// gets answered first [to do that, you should redirect clients to a different coordinator
// first], but rather (1) to make sure that for each update we ack as successful, we generate
// hints for any non-responsive replicas, and (2) to make sure that we quickly stop
// accepting client connections so shutdown can continue. Not waiting for the WorkerProcess
// threads here accomplishes (2); MessagingService's shutdown method takes care of (1).
//
// See CASSANDRA-3335 and CASSANDRA-3727.
}
public void stop()
{
stopped = true;
serverTransport_.interrupt();
}
private class WorkerProcess implements Runnable
{
/**
* Client that this services.
*/
private TTransport client_;
/**
* Default constructor.
*
* @param client Transport to process
*/
private WorkerProcess(TTransport client)
{
client_ = client;
}
/**
* Loops on processing a client forever
*/
public void run()
{
TProcessor processor = null;
TProtocol inputProtocol = null;
TProtocol outputProtocol = null;
SocketAddress socket = null;
try (TTransport inputTransport = inputTransportFactory_.getTransport(client_);
TTransport outputTransport = outputTransportFactory_.getTransport(client_))
{
socket = ((TCustomSocket) client_).getSocket().getRemoteSocketAddress();
ThriftSessionManager.instance.setCurrentSocket(socket);
processor = processorFactory_.getProcessor(client_);
inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);
// we check stopped first to make sure we're not supposed to be shutting
// down. this is necessary for graceful shutdown. (but not sufficient,
// since process() can take arbitrarily long waiting for client input.
// See comments at the end of serve().)
while (!stopped && processor.process(inputProtocol, outputProtocol))
{
inputProtocol = inputProtocolFactory_.getProtocol(inputTransport);
outputProtocol = outputProtocolFactory_.getProtocol(outputTransport);
}
}
catch (TTransportException ttx)
{
// Assume the client died and continue silently
// Log at debug to allow debugging of "frame too large" errors (see CASSANDRA-3142).
logger.debug("Thrift transport error occurred during processing of message.", ttx);
}
catch (TException tx)
{
logger.error("Thrift error occurred during processing of message.", tx);
}
catch (Exception e)
{
JVMStabilityInspector.inspectThrowable(e);
logger.error("Error occurred during processing of message.", e);
}
finally
{
if (socket != null)
ThriftSessionManager.instance.connectionComplete(socket);
activeClients.decrementAndGet();
}
}
}
public static class Factory implements TServerFactory
{
@SuppressWarnings("resource")
public TServer buildTServer(Args args)
{
final InetSocketAddress addr = args.addr;
TServerTransport serverTransport;
try
{
final ClientEncryptionOptions clientEnc = DatabaseDescriptor.getClientEncryptionOptions();
if (clientEnc.enabled)
{
logger.info("enabling encrypted thrift connections between client and server");
TSSLTransportParameters params = new TSSLTransportParameters(clientEnc.protocol, clientEnc.cipher_suites);
params.setKeyStore(clientEnc.keystore, clientEnc.keystore_password);
if (clientEnc.require_client_auth)
{
params.setTrustStore(clientEnc.truststore, clientEnc.truststore_password);
params.requireClientAuth(true);
}
TServerSocket sslServer = TSSLTransportFactory.getServerSocket(addr.getPort(), 0, addr.getAddress(), params);
SSLServerSocket sslServerSocket = (SSLServerSocket) sslServer.getServerSocket();
sslServerSocket.setEnabledProtocols(SSLFactory.ACCEPTED_PROTOCOLS);
serverTransport = new TCustomServerSocket(sslServer.getServerSocket(), args.keepAlive, args.sendBufferSize, args.recvBufferSize);
}
else
{
serverTransport = new TCustomServerSocket(addr, args.keepAlive, args.sendBufferSize, args.recvBufferSize, args.listenBacklog);
}
}
catch (TTransportException e)
{
throw new RuntimeException(String.format("Unable to create thrift socket to %s:%s", addr.getAddress(), addr.getPort()), e);
}
// ThreadPool Server and will be invocation per connection basis...
TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport)
.minWorkerThreads(DatabaseDescriptor.getRpcMinThreads())
.maxWorkerThreads(DatabaseDescriptor.getRpcMaxThreads())
.inputTransportFactory(args.inTransportFactory)
.outputTransportFactory(args.outTransportFactory)
.inputProtocolFactory(args.tProtocolFactory)
.outputProtocolFactory(args.tProtocolFactory)
.processor(args.processor);
ExecutorService executorService = new ThreadPoolExecutor(serverArgs.minWorkerThreads,
serverArgs.maxWorkerThreads,
60,
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new NamedThreadFactory("Thrift"));
return new CustomTThreadPoolServer(serverArgs, executorService);
}
}
}
| |
package project1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.xml.transform.Source;
public class generate_report extends JFrame implements ActionListener{
//private ResultSet rs;
private Statement st;
private String Txtcmb;
private int option;
private JComboBox<String>cmbDay,cmbSite,cmbYear;
private String[] month = {"January","February","March","April","May","June","July","August","September","October","November","December"};
private String msAccDB;
private String dbURL;
private Connection conn;
private String d;
private String m,y;
private String[] year={"2018","2019","2020","2021","2022","2023","2024","2025","2026","2027","2028","2029","2030","2031","2032","2033","2034","2035","2036","2037","2038","2039","2040","2041","2042","2043","2044","2045","2046","2047","2048","2049","2050"};
private String value;
private String date;
private JTable table;
JPanel main = new JPanel();
private Container c;
private JButton print;
private JButton cancle;
private JPanel butpan;
private JScrollPane sp;
private String dd;
private ResultSet set;
private String s;
private JPanel buttonPanel;
private JButton btn1,btn2,btn3;
private static java.util.Date currDate = new java.util.Date (); //Creating Object.
private static SimpleDateFormat sdf = new SimpleDateFormat ("dd/MM/yyyy", Locale.getDefault()); //Changing Format.
private static String dat = sdf.format (currDate);
generate_report() throws SQLException{
//setVisible(true);
//btnInfo();
popup();
noDataFromDB();
//displayData();
}
/*
private void display(){
setVisible(true);
setSize(780, 500);
setLocationRelativeTo(null);
}*/
private void connectiondatabase() throws SQLException {
msAccDB = "C://Brem_NG//Samuel//database//brem_database.accdb";
dbURL = "jdbc:ucanaccess://" + msAccDB;
conn = DriverManager.getConnection(dbURL
+ ";jackcessOpener=project1.CryptCodecOpener", "", "brem");
st = conn.createStatement(); }
private void popup() {
cmbDay= new JComboBox(month);
cmbYear = new JComboBox<>(year);
cmbSite= new JComboBox();
String site = returnSiteFromDB();
try{
if(!site.isEmpty()){
Object[] message = { "Select Month", cmbDay, "Select Year",cmbYear,"Select Site ", cmbSite};
option = JOptionPane.showConfirmDialog(null, message, "",
JOptionPane.CLOSED_OPTION);
return;
}
}
catch(Exception ex){
//System.out.println("invl");
}
}
private void returnNumberForMonth(){
//private String[] month = {"January","February","March","April","May","June","July","August","September","October","November","December"};
m = (String) cmbDay.getSelectedItem();
y = (String) cmbYear.getSelectedItem();
value = "00";
switch (m) {
case "January":
value = "01";
break;
case "February":
value = "02";
break;
case "March":
value = "03";
break;
case "April":
value = "04";
break;
case "May":
value = "05";
break;
case "June":
value = "06";
break;
case "July":
value = "07";
break;
case "August":
value = "08";
break;
case "September":
value = "09";
break;
case "October":
value = "10";
break;
case "November":
value = "11";
break;
case "December":
value = "12";
break;
default:
break;
}
}
private void returnMonthYear(){
returnNumberForMonth();
date = value+"/"+y;
//System.out.println(date);
}
/*
* this method will fetch data from database
* base on the provided information.
*/
private void dataFromDatabaseSiteMonthYeear(){
String a;
String query = "Select * from generatorNepa where dategenerated like '" + date+ "' AND sites like '" + d+ "' order by generatorondate";
try {
connectiondatabase();
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
returnMonthYear();
try {
set = st.executeQuery(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int row = 0;
int i = 0;
try {
while (set.next()) {
row++;
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DefaultTableModel model = new DefaultTableModel(new String[] {
"Date Generated", "Time Generated", "NEPA Time ON",
"NEPA Time Of", "NEPA Run Hour(s)", "GEN. Time ON",
"GEN. Time Of", "GEN. Run Hour(s)", "Remark", }, row);
table = new JTable(model);
try {
if (!Txtcmb.isEmpty()) {
set = st.executeQuery(query);
} }catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (set.next()) {
model.setValueAt(set.getString(4).trim(), i, 0);
model.setValueAt(set.getString(3).trim(), i, 1);
model.setValueAt(set.getString(5).trim(), i, 2);
model.setValueAt(set.getString(6).trim(), i, 3);
model.setValueAt(set.getString(7).trim(), i, 4);
model.setValueAt(set.getString(9).trim(), i, 5);
model.setValueAt(set.getString(10).trim(), i, 6);
model.setValueAt(set.getString(11).trim(), i, 7);
model.setValueAt(set.getString(12).trim(), i, 8);
s = set.getString(10);
/* displayData();
setVisible(true);*/
i++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
table = new JTable(model);
sp = new JScrollPane(table);
table.setSelectionMode(0);
table.setFont(new Font("Times New Roman", Font.BOLD, 15));
table.setForeground(Color.BLACK);
table.setGridColor(new Color(0, 128, 192));
table.setRowHeight(35);
table.getTableHeader().setFont(
new Font("SansSerif", Font.ITALIC, 14));
table.setEnabled(false);
table.getTableHeader().setReorderingAllowed(false);
try{
if (!s.isEmpty()) {
}}
catch (Exception e) {
// TODO: handle exception
}
}
private void noDataFromDB(){
try{
d = (String) cmbSite.getSelectedItem();
if (option == JOptionPane.OK_OPTION) {
isData();
returnMonthYear();
dataFromDatabaseSiteMonthYeear();
//System.out.println("TXTCMB"+Txtcmb);
if (cmbDay.getSelectedIndex()<0 || cmbYear.getSelectedIndex()<0 || cmbSite.getSelectedIndex()<0) {
System.out.println("Error in Fetching data");
}
else if(!s.isEmpty()){
ButtonInfo info = new ButtonInfo();
}
else{
JOptionPane.showMessageDialog(null, "NO Data ");
}
}
else{
System.out.println("Dispose");
}
}
catch(Exception xc){
JOptionPane.showMessageDialog(null, "NO Data for the specified info");
}
}
private void isData(){
try {
while (set.next()) {
Txtcmb = set.getString("sites").trim();
}
} catch (SQLException e) {
}}
private void displayData(){
setSize(1320, 520);
setTitle("Nepa|Generator Operation List Via Date");
setLocation(12, 10);
/*
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
}
});*/
setResizable(false);
setIconImage(Toolkit.getDefaultToolkit().getImage(
"images//mainicon.png"));
c = getContentPane();
main.setLayout(new BorderLayout());
main.setBackground(new Color(245, 240, 255));
JLabel l = new JLabel(
"<html><font size=6 color=#800080><i>Nepa|Generator Operation List");
JPanel title = new JPanel() {
public void paintComponent(Graphics g) {
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.getImage("images//Gradien.jpg");
MediaTracker t = new MediaTracker(this);
t.addImage(img, 1);
while (true) {
try {
t.waitForID(1);
break;
} catch (Exception e) {
}
}
g.drawImage(img, 0, 0, 1350, 50, null);
}
};
title.add(l);
main.add("North", title);
Icon prt = new ImageIcon("images//PRINT.png");
print = new JButton("Generate Pdf");
print.setToolTipText("Print");
cancle = new JButton("Exit");
cancle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
Home sa = new Home();
sa.setLocationRelativeTo(null);
sa.setVisible(true);
}
});
cancle.setToolTipText("Exit");
butpan = new JPanel();
butpan.add(print);
butpan.add(cancle);
butpan.setBackground(new Color(255, 197, 68));
c.add("South", butpan);
main.add(sp);
c.add(main);
}
private String returnSiteFromDB() {
try{
String query = "SELECT * FROM sites ORDER BY site ASC";
connectiondatabase();
set = st.executeQuery(query);
while (set.next()) {
Txtcmb = set.getString("site").trim();
cmbSite.addItem(Txtcmb);
}
}
catch(Exception exception){
//exception.printStackTrace();
}
return Txtcmb;}
public static void main(String[] args) throws SQLException {
generate_report monthly_report = new generate_report();
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
| |
/*
* Copyright 2003-2013 Dave Griffith, Bas Leijdekkers
*
* 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.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.HardcodedMethodConstants;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.callMatcher.CallMatcher;
import com.siyeh.ig.psiutils.ControlFlowUtils;
import com.siyeh.ig.psiutils.ExpressionUtils;
import com.siyeh.ig.psiutils.MethodUtils;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import static com.intellij.util.ObjectUtils.tryCast;
public class EqualsWhichDoesntCheckParameterClassInspection extends BaseInspection {
private static final CallMatcher REFLECTION_EQUALS =
CallMatcher.staticCall("org.apache.commons.lang.builder.EqualsBuilder", "reflectionEquals");
private static final CallMatcher CLASS_IS_INSTANCE =
CallMatcher.instanceCall(CommonClassNames.JAVA_LANG_CLASS, "isInstance").parameterCount(1);
private static final CallMatcher OBJECT_GET_CLASS =
CallMatcher.instanceCall(CommonClassNames.JAVA_LANG_OBJECT, "getClass").parameterCount(0);
@Override
@NotNull
public String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message("equals.doesnt.check.class.parameter.problem.descriptor");
}
@Override
public boolean isEnabledByDefault() {
return true;
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new EqualsWhichDoesntCheckParameterClassVisitor();
}
private static class EqualsWhichDoesntCheckParameterClassVisitor extends BaseInspectionVisitor {
@Override
public void visitMethod(@NotNull PsiMethod method) {
// note: no call to super
if (!MethodUtils.isEquals(method)) {
return;
}
final PsiParameterList parameterList = method.getParameterList();
final PsiParameter[] parameters = parameterList.getParameters();
final PsiParameter parameter = parameters[0];
final PsiCodeBlock body = method.getBody();
if (body == null || isParameterChecked(body, parameter) || isParameterCheckNotNeeded(body, parameter)) {
return;
}
registerMethodError(method);
}
private static boolean isParameterChecked(PsiCodeBlock body, PsiParameter parameter) {
final ParameterClassCheckVisitor visitor = new ParameterClassCheckVisitor(parameter);
body.accept(visitor);
return visitor.isChecked();
}
private static boolean isParameterCheckNotNeeded(PsiCodeBlock body, PsiParameter parameter) {
if (ControlFlowUtils.isEmptyCodeBlock(body)) {
return true; // incomplete code
}
final PsiStatement statement = ControlFlowUtils.getOnlyStatementInBlock(body);
if (statement == null) {
return false;
}
if (!(statement instanceof PsiReturnStatement)) {
return true; // incomplete code
}
final PsiReturnStatement returnStatement = (PsiReturnStatement)statement;
final PsiExpression returnValue = returnStatement.getReturnValue();
final Object constant = ExpressionUtils.computeConstantExpression(returnValue);
if (Boolean.FALSE.equals(constant)) {
return true; // incomplete code
}
if (REFLECTION_EQUALS.matches(returnValue)) {
return true;
}
if (isIdentityEquals(returnValue, parameter)) {
return true;
}
return false;
}
private static boolean isIdentityEquals(PsiExpression expression, PsiParameter parameter) {
if (!(expression instanceof PsiBinaryExpression)) {
return false;
}
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression;
final PsiExpression lhs = binaryExpression.getLOperand();
final PsiExpression rhs = binaryExpression.getROperand();
return isIdentityEquals(lhs, rhs, parameter) || isIdentityEquals(rhs, lhs, parameter);
}
private static boolean isIdentityEquals(PsiExpression lhs, PsiExpression rhs, PsiParameter parameter) {
return ExpressionUtils.isReferenceTo(lhs, parameter) &&
rhs instanceof PsiThisExpression &&
((PsiThisExpression)rhs).getQualifier() == null;
}
}
private static class ParameterClassCheckVisitor extends JavaRecursiveElementWalkingVisitor {
private final PsiParameter myParameter;
private boolean myChecked;
ParameterClassCheckVisitor(@NotNull PsiParameter parameter) {
myParameter = parameter;
}
private void makeChecked() {
myChecked = true;
stopWalking();
}
@Contract("null -> false")
private boolean isParameterReference(PsiExpression operand) {
PsiReferenceExpression ref = tryCast(PsiUtil.skipParenthesizedExprDown(operand), PsiReferenceExpression.class);
if (ref == null) return false;
PsiParameter target = tryCast(ref.resolve(), PsiParameter.class);
if (target == myParameter) return true;
if (target == null) return false;
return target.getParent() instanceof PsiParameterList && target.getParent().getParent() instanceof PsiLambdaExpression;
}
private boolean isGetInstanceCall(PsiMethodCallExpression call) {
if (!CLASS_IS_INSTANCE.test(call)) return false;
final PsiExpression arg = call.getArgumentList().getExpressions()[0];
return isParameterReference(arg);
}
private boolean isGetClassCall(PsiMethodCallExpression call) {
if (!OBJECT_GET_CLASS.test(call)) return false;
final PsiExpression qualifier = call.getMethodExpression().getQualifierExpression();
return isParameterReference(qualifier);
}
private boolean isCallToSuperEquals(PsiMethodCallExpression call) {
final PsiReferenceExpression methodExpression = call.getMethodExpression();
final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
if (!(qualifierExpression instanceof PsiSuperExpression)) return false;
final String name = methodExpression.getReferenceName();
if (!HardcodedMethodConstants.EQUALS.equals(name)) return false;
final PsiExpression[] arguments = call.getArgumentList().getExpressions();
if (arguments.length != 1) return false;
return isParameterReference(arguments[0]);
}
@Override
public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
if (isGetClassCall(expression) || isGetInstanceCall(expression) || isCallToSuperEquals(expression)) {
makeChecked();
}
}
@Override
public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
super.visitMethodReferenceExpression(expression);
if (CLASS_IS_INSTANCE.methodReferenceMatches(expression)) {
makeChecked();
}
}
@Override
public void visitInstanceOfExpression(@NotNull PsiInstanceOfExpression expression) {
super.visitInstanceOfExpression(expression);
if (isParameterReference(expression.getOperand())) {
makeChecked();
}
}
@Override
public void visitTypeCastExpression(PsiTypeCastExpression expression) {
super.visitTypeCastExpression(expression);
final PsiExpression operand = expression.getOperand();
if (!isParameterReference(operand)) return;
final PsiTryStatement statement = PsiTreeUtil.getParentOfType(expression, PsiTryStatement.class);
if (statement == null) return;
final PsiParameter[] parameters = statement.getCatchBlockParameters();
if (parameters.length < 2) return;
boolean nullPointerExceptionFound = false;
boolean classCastExceptionFound = false;
for (PsiParameter parameter : parameters) {
final PsiType type = parameter.getType();
if (type.equalsToText("java.lang.NullPointerException")) {
nullPointerExceptionFound = true;
if (classCastExceptionFound) break;
}
else if (type.equalsToText("java.lang.ClassCastException")) {
classCastExceptionFound = true;
if (nullPointerExceptionFound) break;
}
}
if (classCastExceptionFound && nullPointerExceptionFound) {
makeChecked();
}
}
public boolean isChecked() {
return myChecked;
}
}
}
| |
/*
* 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.drill.exec.planner.sql.handlers;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.schema.Table;
import org.apache.calcite.sql.SqlNode;
import org.apache.commons.io.IOUtils;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.physical.PhysicalPlan;
import org.apache.drill.exec.planner.sql.DirectPlan;
import org.apache.drill.exec.planner.sql.SchemaUtilites;
import org.apache.drill.exec.planner.sql.parser.SqlCreateType;
import org.apache.drill.exec.planner.sql.parser.SqlSchema;
import org.apache.drill.exec.record.metadata.ColumnMetadata;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.exec.record.metadata.TupleSchema;
import org.apache.drill.exec.record.metadata.schema.InlineSchemaProvider;
import org.apache.drill.exec.record.metadata.schema.PathSchemaProvider;
import org.apache.drill.exec.record.metadata.schema.SchemaContainer;
import org.apache.drill.exec.record.metadata.schema.SchemaProvider;
import org.apache.drill.exec.record.metadata.schema.SchemaProviderFactory;
import org.apache.drill.exec.record.metadata.schema.StorageProperties;
import org.apache.drill.exec.store.AbstractSchema;
import org.apache.drill.exec.store.StorageStrategy;
import org.apache.drill.exec.store.dfs.WorkspaceSchemaFactory;
import org.apache.drill.exec.util.ImpersonationUtil;
import org.apache.drill.shaded.guava.com.google.common.base.Preconditions;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Parent class for CREATE / DROP / DESCRIBE / ALTER SCHEMA handlers.
* Contains common logic on how extract workspace, output error result.
*/
public abstract class SchemaHandler extends DefaultSqlHandler {
static final Logger logger = LoggerFactory.getLogger(SchemaHandler.class);
SchemaHandler(SqlHandlerConfig config) {
super(config);
}
public WorkspaceSchemaFactory.WorkspaceSchema getWorkspaceSchema(List<String> tableSchema, String tableName) {
SchemaPlus defaultSchema = config.getConverter().getDefaultSchema();
AbstractSchema temporarySchema = SchemaUtilites.resolveToTemporarySchema(tableSchema, defaultSchema, context.getConfig());
if (context.getSession().isTemporaryTable(temporarySchema, context.getConfig(), tableName)) {
produceErrorResult(String.format("Indicated table [%s] is temporary table", tableName), true);
}
AbstractSchema drillSchema = SchemaUtilites.resolveToMutableDrillSchema(defaultSchema, tableSchema);
Table table = SqlHandlerUtil.getTableFromSchema(drillSchema, tableName);
if (table == null || table.getJdbcTableType() != Schema.TableType.TABLE) {
produceErrorResult(String.format("Table [%s] was not found", tableName), true);
}
if (!(drillSchema instanceof WorkspaceSchemaFactory.WorkspaceSchema)) {
produceErrorResult(String.format("Table [`%s`.`%s`] must belong to file storage plugin",
drillSchema.getFullSchemaName(), tableName), true);
}
Preconditions.checkState(drillSchema instanceof WorkspaceSchemaFactory.WorkspaceSchema);
return (WorkspaceSchemaFactory.WorkspaceSchema) drillSchema;
}
PhysicalPlan produceErrorResult(String message, boolean doFail) {
if (doFail) {
throw UserException.validationError().message(message).build(logger);
} else {
return DirectPlan.createDirectPlan(context, false, message);
}
}
/**
* Provides storage strategy which will create schema file
* with same permission as used for persistent tables.
*
* @return storage strategy
*/
StorageStrategy getStorageStrategy() {
return new StorageStrategy(context.getOption(
ExecConstants.PERSISTENT_TABLE_UMASK).string_val, false);
}
/**
* CREATE SCHEMA command handler.
*/
public static class Create extends SchemaHandler {
public Create(SqlHandlerConfig config) {
super(config);
}
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) {
SqlSchema.Create sqlCall = ((SqlSchema.Create) sqlNode);
String schemaString = getSchemaString(sqlCall);
String schemaSource = sqlCall.hasTable() ? sqlCall.getTable().toString() : sqlCall.getPath();
try {
SchemaProvider schemaProvider = SchemaProviderFactory.create(sqlCall, this);
if (schemaProvider.exists()) {
if (SqlCreateType.OR_REPLACE == sqlCall.getSqlCreateType()) {
schemaProvider.delete();
} else {
return produceErrorResult(String.format("Schema already exists for [%s]", schemaSource), true);
}
}
StorageProperties storageProperties = StorageProperties.builder()
.storageStrategy(getStorageStrategy())
.overwrite(false)
.build();
schemaProvider.store(schemaString, sqlCall.getProperties(), storageProperties);
return DirectPlan.createDirectPlan(context, true, String.format("Created schema for [%s]", schemaSource));
} catch (IOException e) {
throw UserException.resourceError(e)
.message(e.getMessage())
.addContext("Error while preparing / creating schema for [%s]", schemaSource)
.build(logger);
} catch (IllegalArgumentException e) {
throw UserException.validationError(e)
.message(e.getMessage())
.addContext("Error while preparing / creating schema for [%s]", schemaSource)
.build(logger);
}
}
/**
* If raw schema was present in create schema command, returns schema from command,
* otherwise loads raw schema from the given file.
*
* @param sqlCall sql create schema call
* @return string representation of raw schema (column names, types and nullability)
*/
private String getSchemaString(SqlSchema.Create sqlCall) {
if (sqlCall.hasSchema()) {
return sqlCall.getSchema();
}
Path path = new Path(sqlCall.getLoad());
try {
FileSystem rawFs = path.getFileSystem(new Configuration());
FileSystem fs = ImpersonationUtil.createFileSystem(ImpersonationUtil.getProcessUserName(), rawFs.getConf());
if (!fs.exists(path)) {
throw UserException.resourceError()
.message("File with raw schema [%s] does not exist", path.toUri().getPath())
.build(logger);
}
try (InputStream stream = fs.open(path)) {
return IOUtils.toString(stream);
}
} catch (IOException e) {
throw UserException.resourceError(e)
.message("Unable to load raw schema from file %s", path.toUri().getPath())
.build(logger);
}
}
}
/**
* DROP SCHEMA command handler.
*/
public static class Drop extends SchemaHandler {
public Drop(SqlHandlerConfig config) {
super(config);
}
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) {
SqlSchema.Drop sqlCall = ((SqlSchema.Drop) sqlNode);
try {
SchemaProvider schemaProvider = SchemaProviderFactory.create(sqlCall, this);
if (!schemaProvider.exists()) {
return produceErrorResult(String.format("Schema [%s] does not exist in table [%s] root directory",
SchemaProvider.DEFAULT_SCHEMA_NAME, sqlCall.getTable()), !sqlCall.ifExists());
}
schemaProvider.delete();
return DirectPlan.createDirectPlan(context, true,
String.format("Dropped schema for table [%s]", sqlCall.getTable()));
} catch (IOException e) {
throw UserException.resourceError(e)
.message(e.getMessage())
.addContext("Error while accessing table location or deleting schema for [%s]", sqlCall.getTable())
.build(logger);
}
}
}
/**
* DESCRIBE SCHEMA FOR TABLE command handler.
*/
public static class Describe extends SchemaHandler {
public Describe(SqlHandlerConfig config) {
super(config);
}
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) {
SqlSchema.Describe sqlCall = ((SqlSchema.Describe) sqlNode);
try {
SchemaProvider schemaProvider = SchemaProviderFactory.create(sqlCall, this);
if (schemaProvider.exists()) {
SchemaContainer schemaContainer = schemaProvider.read();
String schema;
switch (sqlCall.getFormat()) {
case JSON:
schema = PathSchemaProvider.WRITER.writeValueAsString(schemaContainer);
break;
case STATEMENT:
TupleMetadata metadata = schemaContainer.getSchema();
StringBuilder builder = new StringBuilder("CREATE OR REPLACE SCHEMA \n");
List<ColumnMetadata> columnsMetadata = metadata.toMetadataList();
if (columnsMetadata.isEmpty()) {
builder.append("() \n");
} else {
builder.append("(\n");
builder.append(columnsMetadata.stream()
.map(ColumnMetadata::columnString)
.collect(Collectors.joining(", \n")));
builder.append("\n) \n");
}
builder.append("FOR TABLE ").append(schemaContainer.getTable()).append(" \n");
Map<String, String> properties = metadata.properties();
if (!properties.isEmpty()) {
builder.append("PROPERTIES (\n");
builder.append(properties.entrySet().stream()
.map(e -> String.format("'%s' = '%s'", e.getKey(), e.getValue()))
.collect(Collectors.joining(", \n")));
builder.append("\n)");
}
schema = builder.toString();
break;
default:
throw UserException.validationError()
.message("Unsupported describe schema format: [%s]", sqlCall.getFormat())
.build(logger);
}
return DirectPlan.createDirectPlan(context, new SchemaResult(schema));
}
return DirectPlan.createDirectPlan(context, false,
String.format("Schema for table [%s] is absent", sqlCall.getTable()));
} catch (IOException e) {
throw UserException.resourceError(e)
.message(e.getMessage())
.addContext("Error while accessing schema for table [%s]", sqlCall.getTable())
.build(logger);
}
}
/**
* Wrapper to output schema in a form of table with one column named `schema`.
*/
public static class SchemaResult {
public String schema;
public SchemaResult(String schema) {
this.schema = schema;
}
}
}
/**
* ALTER SCHEMA ADD command handler.
*/
public static class Add extends SchemaHandler {
public Add(SqlHandlerConfig config) {
super(config);
}
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) {
SqlSchema.Add addCall = ((SqlSchema.Add) sqlNode);
String schemaSource = addCall.hasTable() ? addCall.getTable().toString() : addCall.getPath();
try {
SchemaProvider schemaProvider = SchemaProviderFactory.create(addCall, this);
if (!schemaProvider.exists()) {
throw UserException.resourceError()
.message("Schema does not exist for [%s]", schemaSource)
.addContext("Command: ALTER SCHEMA ADD")
.build(logger);
}
TupleMetadata currentSchema = schemaProvider.read().getSchema();
TupleMetadata newSchema = new TupleSchema();
if (addCall.hasSchema()) {
InlineSchemaProvider inlineSchemaProvider = new InlineSchemaProvider(addCall.getSchema());
TupleMetadata providedSchema = inlineSchemaProvider.read().getSchema();
if (addCall.isReplace()) {
Map<String, ColumnMetadata> columnsMap = Stream.concat(currentSchema.toMetadataList().stream(), providedSchema.toMetadataList().stream())
.collect(Collectors.toMap(
ColumnMetadata::name,
Function.identity(),
(o, n) -> n, // replace existing columns
LinkedHashMap::new)); // preserve initial order of the columns
columnsMap.values().forEach(newSchema::addColumn);
} else {
Stream.concat(currentSchema.toMetadataList().stream(), providedSchema.toMetadataList().stream())
.forEach(newSchema::addColumn);
}
} else {
currentSchema.toMetadataList().forEach(newSchema::addColumn);
}
if (addCall.hasProperties()) {
if (addCall.isReplace()) {
newSchema.setProperties(currentSchema.properties());
newSchema.setProperties(addCall.getProperties());
} else {
Map<String, String> newProperties = Stream.concat(currentSchema.properties().entrySet().stream(), addCall.getProperties().entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue)); // no merge strategy is provided to fail on duplicate
newSchema.setProperties(newProperties);
}
} else {
newSchema.setProperties(currentSchema.properties());
}
String schemaString = newSchema.toMetadataList().stream()
.map(ColumnMetadata::columnString)
.collect(Collectors.joining(", "));
StorageProperties storageProperties = StorageProperties.builder()
.storageStrategy(getStorageStrategy())
.overwrite()
.build();
schemaProvider.store(schemaString, newSchema.properties(), storageProperties);
return DirectPlan.createDirectPlan(context, true, String.format("Schema for [%s] was updated", schemaSource));
} catch (IOException e) {
throw UserException.resourceError(e)
.message("Error while accessing / modifying schema for [%s]: %s", schemaSource, e.getMessage())
.build(logger);
} catch (IllegalArgumentException | IllegalStateException e) {
throw UserException.validationError(e)
.message(e.getMessage())
.addContext("Error while preparing / creating schema for [%s]", schemaSource)
.build(logger);
}
}
}
/**
* ALTER SCHEMA REMOVE command handler.
*/
public static class Remove extends SchemaHandler {
public Remove(SqlHandlerConfig config) {
super(config);
}
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) {
SqlSchema.Remove removeCall = ((SqlSchema.Remove) sqlNode);
String schemaSource = removeCall.hasTable() ? removeCall.getTable().toString() : removeCall.getPath();
try {
SchemaProvider schemaProvider = SchemaProviderFactory.create(removeCall, this);
if (!schemaProvider.exists()) {
throw UserException.resourceError()
.message("Schema does not exist for [%s]", schemaSource)
.addContext("Command: ALTER SCHEMA REMOVE")
.build(logger);
}
TupleMetadata currentSchema = schemaProvider.read().getSchema();
TupleMetadata newSchema = new TupleSchema();
List<String> columns = removeCall.getColumns();
currentSchema.toMetadataList().stream()
.filter(column -> columns == null || !columns.contains(column.name()))
.forEach(newSchema::addColumn);
newSchema.setProperties(currentSchema.properties());
if (removeCall.hasProperties()) {
removeCall.getProperties().forEach(newSchema::removeProperty);
}
StorageProperties storageProperties = StorageProperties.builder()
.storageStrategy(getStorageStrategy())
.overwrite()
.build();
String schemaString = newSchema.toMetadataList().stream()
.map(ColumnMetadata::columnString)
.collect(Collectors.joining(", "));
schemaProvider.store(schemaString, newSchema.properties(), storageProperties);
return DirectPlan.createDirectPlan(context, true, String.format("Schema for [%s] was updated", schemaSource));
} catch (IOException e) {
throw UserException.resourceError(e)
.message("Error while accessing / modifying schema for [%s]: %s", schemaSource, e.getMessage())
.build(logger);
} catch (IllegalArgumentException e) {
throw UserException.validationError(e)
.message(e.getMessage())
.addContext("Error while preparing / creating schema for [%s]", schemaSource)
.build(logger);
}
}
}
}
| |
/*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
/*
* BayesNet.java
* Copyright (C) 2001-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.classifiers.bayes;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.bayes.net.ADNode;
import weka.classifiers.bayes.net.BIFReader;
import weka.classifiers.bayes.net.ParentSet;
import weka.classifiers.bayes.net.estimate.BayesNetEstimator;
import weka.classifiers.bayes.net.estimate.DiscreteEstimatorBayes;
import weka.classifiers.bayes.net.estimate.SimpleEstimator;
import weka.classifiers.bayes.net.search.SearchAlgorithm;
import weka.classifiers.bayes.net.search.local.K2;
import weka.classifiers.bayes.net.search.local.LocalScoreSearchAlgorithm;
import weka.classifiers.bayes.net.search.local.Scoreable;
import weka.core.AdditionalMeasureProducer;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Drawable;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
import weka.core.WeightedInstancesHandler;
import weka.estimators.Estimator;
import weka.filters.Filter;
import weka.filters.supervised.attribute.Discretize;
import weka.filters.unsupervised.attribute.ReplaceMissingValues;
/**
* <!-- globalinfo-start --> Bayes Network learning using various search
* algorithms and quality measures.<br/>
* Base class for a Bayes Network classifier. Provides datastructures (network
* structure, conditional probability distributions, etc.) and facilities common
* to Bayes Network learning algorithms like K2 and B.<br/>
* <br/>
* For more information see:<br/>
* <br/>
* http://sourceforge.net/projects/weka/files/documentation/WekaManual-3-7-0.pdf
* /download
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Do not use ADTree data structure
* </pre>
*
* <pre>
* -B <BIF file>
* BIF file to compare with
* </pre>
*
* <pre>
* -Q weka.classifiers.bayes.net.search.SearchAlgorithm
* Search algorithm
* </pre>
*
* <pre>
* -E weka.classifiers.bayes.net.estimate.SimpleEstimator
* Estimator algorithm
* </pre>
*
* <!-- options-end -->
*
* @author Remco Bouckaert (rrb@xm.co.nz)
* @version $Revision: 10386 $
*/
public class BayesNet extends AbstractClassifier implements OptionHandler,
WeightedInstancesHandler, Drawable, AdditionalMeasureProducer {
/** for serialization */
static final long serialVersionUID = 746037443258775954L;
/**
* The parent sets.
*/
protected ParentSet[] m_ParentSets;
/**
* The attribute estimators containing CPTs.
*/
public Estimator[][] m_Distributions;
/** filter used to quantize continuous variables, if any **/
protected Discretize m_DiscretizeFilter = null;
/** attribute index of a non-nominal attribute */
int m_nNonDiscreteAttribute = -1;
/** filter used to fill in missing values, if any **/
protected ReplaceMissingValues m_MissingValuesFilter = null;
/**
* The number of classes
*/
protected int m_NumClasses;
/**
* The dataset header for the purposes of printing out a semi-intelligible
* model
*/
public Instances m_Instances;
/**
* The number of instances the model was built from
*/
private int m_NumInstances;
/**
* Datastructure containing ADTree representation of the database. This may
* result in more efficient access to the data.
*/
ADNode m_ADTree;
/**
* Bayes network to compare the structure with.
*/
protected BIFReader m_otherBayesNet = null;
/**
* Use the experimental ADTree datastructure for calculating contingency
* tables
*/
boolean m_bUseADTree = false;
/**
* Search algorithm used for learning the structure of a network.
*/
SearchAlgorithm m_SearchAlgorithm = new K2();
/**
* Search algorithm used for learning the structure of a network.
*/
BayesNetEstimator m_BayesNetEstimator = new SimpleEstimator();
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
// instances
result.setMinimumNumberInstances(0);
return result;
}
/**
* Generates the classifier.
*
* @param instances set of instances serving as training data
* @throws Exception if the classifier has not been generated successfully
*/
@Override
public void buildClassifier(Instances instances) throws Exception {
// can classifier handle the data?
getCapabilities().testWithFail(instances);
// remove instances with missing class
instances = new Instances(instances);
instances.deleteWithMissingClass();
// ensure we have a data set with discrete variables only and with no
// missing values
instances = normalizeDataSet(instances);
// Copy the instances
m_Instances = new Instances(instances);
m_NumInstances = m_Instances.numInstances();
// sanity check: need more than 1 variable in datat set
m_NumClasses = instances.numClasses();
// initialize ADTree
if (m_bUseADTree) {
m_ADTree = ADNode.makeADTree(instances);
// System.out.println("Oef, done!");
}
// build the network structure
initStructure();
// build the network structure
buildStructure();
// build the set of CPTs
estimateCPTs();
// Save space
m_Instances = new Instances(m_Instances, 0);
m_ADTree = null;
} // buildClassifier
/**
* Returns the number of instances the model was built from.
*/
public int getNumInstances() {
return m_NumInstances;
}
/**
* ensure that all variables are nominal and that there are no missing values
*
* @param instances data set to check and quantize and/or fill in missing
* values
* @return filtered instances
* @throws Exception if a filter (Discretize, ReplaceMissingValues) fails
*/
protected Instances normalizeDataSet(Instances instances) throws Exception {
m_nNonDiscreteAttribute = -1;
Enumeration<Attribute> enu = instances.enumerateAttributes();
while (enu.hasMoreElements()) {
Attribute attribute = enu.nextElement();
if (attribute.type() != Attribute.NOMINAL) {
m_nNonDiscreteAttribute = attribute.index();
}
}
if ((m_nNonDiscreteAttribute > -1)
&& (instances.attribute(m_nNonDiscreteAttribute).type() != Attribute.NOMINAL)) {
m_DiscretizeFilter = new Discretize();
m_DiscretizeFilter.setInputFormat(instances);
instances = Filter.useFilter(instances, m_DiscretizeFilter);
}
m_MissingValuesFilter = new ReplaceMissingValues();
m_MissingValuesFilter.setInputFormat(instances);
instances = Filter.useFilter(instances, m_MissingValuesFilter);
return instances;
} // normalizeDataSet
/**
* ensure that all variables are nominal and that there are no missing values
*
* @param instance instance to check and quantize and/or fill in missing
* values
* @return filtered instance
* @throws Exception if a filter (Discretize, ReplaceMissingValues) fails
*/
protected Instance normalizeInstance(Instance instance) throws Exception {
if ((m_nNonDiscreteAttribute > -1)
&& (instance.attribute(m_nNonDiscreteAttribute).type() != Attribute.NOMINAL)) {
m_DiscretizeFilter.input(instance);
instance = m_DiscretizeFilter.output();
}
m_MissingValuesFilter.input(instance);
instance = m_MissingValuesFilter.output();
return instance;
} // normalizeInstance
/**
* Init structure initializes the structure to an empty graph or a Naive Bayes
* graph (depending on the -N flag).
*
* @throws Exception in case of an error
*/
public void initStructure() throws Exception {
// initialize topological ordering
// m_nOrder = new int[m_Instances.numAttributes()];
// m_nOrder[0] = m_Instances.classIndex();
int nAttribute = 0;
for (int iOrder = 1; iOrder < m_Instances.numAttributes(); iOrder++) {
if (nAttribute == m_Instances.classIndex()) {
nAttribute++;
}
// m_nOrder[iOrder] = nAttribute++;
}
// reserve memory
m_ParentSets = new ParentSet[m_Instances.numAttributes()];
for (int iAttribute = 0; iAttribute < m_Instances.numAttributes(); iAttribute++) {
m_ParentSets[iAttribute] = new ParentSet(m_Instances.numAttributes());
}
} // initStructure
/**
* buildStructure determines the network structure/graph of the network. The
* default behavior is creating a network where all nodes have the first node
* as its parent (i.e., a BayesNet that behaves like a naive Bayes
* classifier). This method can be overridden by derived classes to restrict
* the class of network structures that are acceptable.
*
* @throws Exception in case of an error
*/
public void buildStructure() throws Exception {
m_SearchAlgorithm.buildStructure(this, m_Instances);
} // buildStructure
/**
* estimateCPTs estimates the conditional probability tables for the Bayes Net
* using the network structure.
*
* @throws Exception in case of an error
*/
public void estimateCPTs() throws Exception {
m_BayesNetEstimator.estimateCPTs(this);
} // estimateCPTs
/**
* initializes the conditional probabilities
*
* @throws Exception in case of an error
*/
public void initCPTs() throws Exception {
m_BayesNetEstimator.initCPTs(this);
} // estimateCPTs
/**
* Updates the classifier with the given instance.
*
* @param instance the new training instance to include in the model
* @throws Exception if the instance could not be incorporated in the model.
*/
public void updateClassifier(Instance instance) throws Exception {
instance = normalizeInstance(instance);
m_BayesNetEstimator.updateClassifier(this, instance);
} // updateClassifier
/**
* Calculates the class membership probabilities for the given test instance.
*
* @param instance the instance to be classified
* @return predicted class probability distribution
* @throws Exception if there is a problem generating the prediction
*/
@Override
public double[] distributionForInstance(Instance instance) throws Exception {
instance = normalizeInstance(instance);
return m_BayesNetEstimator.distributionForInstance(this, instance);
} // distributionForInstance
/**
* Calculates the counts for Dirichlet distribution for the class membership
* probabilities for the given test instance.
*
* @param instance the instance to be classified
* @return counts for Dirichlet distribution for class probability
* @throws Exception if there is a problem generating the prediction
*/
public double[] countsForInstance(Instance instance) throws Exception {
double[] fCounts = new double[m_NumClasses];
for (int iClass = 0; iClass < m_NumClasses; iClass++) {
fCounts[iClass] = 0.0;
}
for (int iClass = 0; iClass < m_NumClasses; iClass++) {
double fCount = 0;
for (int iAttribute = 0; iAttribute < m_Instances.numAttributes(); iAttribute++) {
double iCPT = 0;
for (int iParent = 0; iParent < m_ParentSets[iAttribute]
.getNrOfParents(); iParent++) {
int nParent = m_ParentSets[iAttribute].getParent(iParent);
if (nParent == m_Instances.classIndex()) {
iCPT = iCPT * m_NumClasses + iClass;
} else {
iCPT = iCPT * m_Instances.attribute(nParent).numValues()
+ instance.value(nParent);
}
}
if (iAttribute == m_Instances.classIndex()) {
fCount += ((DiscreteEstimatorBayes) m_Distributions[iAttribute][(int) iCPT])
.getCount(iClass);
} else {
fCount += ((DiscreteEstimatorBayes) m_Distributions[iAttribute][(int) iCPT])
.getCount(instance.value(iAttribute));
}
}
fCounts[iClass] += fCount;
}
return fCounts;
} // countsForInstance
/**
* Returns an enumeration describing the available options
*
* @return an enumeration of all the available options
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(4);
newVector.addElement(new Option("\tDo not use ADTree data structure\n",
"D", 0, "-D"));
newVector.addElement(new Option("\tBIF file to compare with\n", "B", 1,
"-B <BIF file>"));
newVector.addElement(new Option("\tSearch algorithm\n", "Q", 1,
"-Q weka.classifiers.bayes.net.search.SearchAlgorithm"));
newVector.addElement(new Option("\tEstimator algorithm\n", "E", 1,
"-E weka.classifiers.bayes.net.estimate.SimpleEstimator"));
newVector.addAll(Collections.list(super.listOptions()));
newVector.addElement(new Option("", "", 0,
"\nOptions specific to search method "
+ getSearchAlgorithm().getClass().getName() + ":"));
newVector.addAll(Collections.list(getSearchAlgorithm().listOptions()));
newVector.addElement(new Option("", "", 0,
"\nOptions specific to estimator method "
+ getEstimator().getClass().getName() + ":"));
newVector.addAll(Collections.list(getEstimator().listOptions()));
return newVector.elements();
} // listOptions
/**
* Parses a given list of options.
* <p>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -D
* Do not use ADTree data structure
* </pre>
*
* <pre>
* -B <BIF file>
* BIF file to compare with
* </pre>
*
* <pre>
* -Q weka.classifiers.bayes.net.search.SearchAlgorithm
* Search algorithm
* </pre>
*
* <pre>
* -E weka.classifiers.bayes.net.estimate.SimpleEstimator
* Estimator algorithm
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
super.setOptions(options);
m_bUseADTree = !(Utils.getFlag('D', options));
String sBIFFile = Utils.getOption('B', options);
if (sBIFFile != null && !sBIFFile.equals("")) {
setBIFFile(sBIFFile);
}
String searchAlgorithmName = Utils.getOption('Q', options);
if (searchAlgorithmName.length() != 0) {
setSearchAlgorithm((SearchAlgorithm) Utils.forName(SearchAlgorithm.class,
searchAlgorithmName, partitionOptions(options)));
} else {
setSearchAlgorithm(new K2());
}
String estimatorName = Utils.getOption('E', options);
if (estimatorName.length() != 0) {
setEstimator((BayesNetEstimator) Utils.forName(BayesNetEstimator.class,
estimatorName, Utils.partitionOptions(options)));
} else {
setEstimator(new SimpleEstimator());
}
Utils.checkForRemainingOptions(options);
} // setOptions
/**
* Returns the secondary set of options (if any) contained in the supplied
* options array. The secondary set is defined to be any options after the
* first "--" but before the "-E". These options are removed from the original
* options array.
*
* @param options the input array of options
* @return the array of secondary options
*/
public static String[] partitionOptions(String[] options) {
for (int i = 0; i < options.length; i++) {
if (options[i].equals("--")) {
// ensure it follows by a -E option
int j = i;
while ((j < options.length) && !(options[j].equals("-E"))) {
j++;
}
/*
* if (j >= options.length) { return new String[0]; }
*/
options[i++] = "";
String[] result = new String[options.length - i];
j = i;
while ((j < options.length) && !(options[j].equals("-E"))) {
result[j - i] = options[j];
options[j] = "";
j++;
}
while (j < options.length) {
result[j - i] = "";
j++;
}
return result;
}
}
return new String[0];
}
/**
* Gets the current settings of the classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
Collections.addAll(options, super.getOptions());
if (!m_bUseADTree) {
options.add("-D");
}
if (m_otherBayesNet != null) {
options.add("-B");
options.add(m_otherBayesNet.getFileName());
}
options.add("-Q");
options.add("" + getSearchAlgorithm().getClass().getName());
options.add("--");
Collections.addAll(options, getSearchAlgorithm().getOptions());
options.add("-E");
options.add("" + getEstimator().getClass().getName());
options.add("--");
Collections.addAll(options, getEstimator().getOptions());
return options.toArray(new String[0]);
} // getOptions
/**
* Set the SearchAlgorithm used in searching for network structures.
*
* @param newSearchAlgorithm the SearchAlgorithm to use.
*/
public void setSearchAlgorithm(SearchAlgorithm newSearchAlgorithm) {
m_SearchAlgorithm = newSearchAlgorithm;
}
/**
* Get the SearchAlgorithm used as the search algorithm
*
* @return the SearchAlgorithm used as the search algorithm
*/
public SearchAlgorithm getSearchAlgorithm() {
return m_SearchAlgorithm;
}
/**
* Set the Estimator Algorithm used in calculating the CPTs
*
* @param newBayesNetEstimator the Estimator to use.
*/
public void setEstimator(BayesNetEstimator newBayesNetEstimator) {
m_BayesNetEstimator = newBayesNetEstimator;
}
/**
* Get the BayesNetEstimator used for calculating the CPTs
*
* @return the BayesNetEstimator used.
*/
public BayesNetEstimator getEstimator() {
return m_BayesNetEstimator;
}
/**
* Set whether ADTree structure is used or not
*
* @param bUseADTree true if an ADTree structure is used
*/
public void setUseADTree(boolean bUseADTree) {
m_bUseADTree = bUseADTree;
}
/**
* Method declaration
*
* @return whether ADTree structure is used or not
*/
public boolean getUseADTree() {
return m_bUseADTree;
}
/**
* Set name of network in BIF file to compare with
*
* @param sBIFFile the name of the BIF file
*/
public void setBIFFile(String sBIFFile) {
try {
m_otherBayesNet = new BIFReader().processFile(sBIFFile);
} catch (Throwable t) {
m_otherBayesNet = null;
}
}
/**
* Get name of network in BIF file to compare with
*
* @return BIF file name
*/
public String getBIFFile() {
if (m_otherBayesNet != null) {
return m_otherBayesNet.getFileName();
}
return "";
}
/**
* Returns a description of the classifier.
*
* @return a description of the classifier as a string.
*/
@Override
public String toString() {
StringBuffer text = new StringBuffer();
text.append("Bayes Network Classifier");
text.append("\n" + (m_bUseADTree ? "Using " : "not using ") + "ADTree");
if (m_Instances == null) {
text.append(": No model built yet.");
} else {
// flatten BayesNet down to text
text.append("\n#attributes=");
text.append(m_Instances.numAttributes());
text.append(" #classindex=");
text.append(m_Instances.classIndex());
text.append("\nNetwork structure (nodes followed by parents)\n");
for (int iAttribute = 0; iAttribute < m_Instances.numAttributes(); iAttribute++) {
text.append(m_Instances.attribute(iAttribute).name() + "("
+ m_Instances.attribute(iAttribute).numValues() + "): ");
for (int iParent = 0; iParent < m_ParentSets[iAttribute]
.getNrOfParents(); iParent++) {
text.append(m_Instances.attribute(
m_ParentSets[iAttribute].getParent(iParent)).name()
+ " ");
}
text.append("\n");
// Description of distributions tends to be too much detail, so it is
// commented out here
// for (int iParent = 0; iParent <
// m_ParentSets[iAttribute].GetCardinalityOfParents(); iParent++) {
// text.append('(' + m_Distributions[iAttribute][iParent].toString() +
// ')');
// }
// text.append("\n");
}
text.append("LogScore Bayes: " + measureBayesScore() + "\n");
text.append("LogScore BDeu: " + measureBDeuScore() + "\n");
text.append("LogScore MDL: " + measureMDLScore() + "\n");
text.append("LogScore ENTROPY: " + measureEntropyScore() + "\n");
text.append("LogScore AIC: " + measureAICScore() + "\n");
if (m_otherBayesNet != null) {
text.append("Missing: " + m_otherBayesNet.missingArcs(this)
+ " Extra: " + m_otherBayesNet.extraArcs(this) + " Reversed: "
+ m_otherBayesNet.reversedArcs(this) + "\n");
text.append("Divergence: " + m_otherBayesNet.divergence(this) + "\n");
}
}
return text.toString();
} // toString
/**
* Returns the type of graph this classifier represents.
*
* @return Drawable.TREE
*/
@Override
public int graphType() {
return Drawable.BayesNet;
}
/**
* Returns a BayesNet graph in XMLBIF ver 0.3 format.
*
* @return String representing this BayesNet in XMLBIF ver 0.3
* @throws Exception in case BIF generation fails
*/
@Override
public String graph() throws Exception {
return toXMLBIF03();
}
public String getBIFHeader() {
StringBuffer text = new StringBuffer();
text.append("<?xml version=\"1.0\"?>\n");
text.append("<!-- DTD for the XMLBIF 0.3 format -->\n");
text.append("<!DOCTYPE BIF [\n");
text.append(" <!ELEMENT BIF ( NETWORK )*>\n");
text.append(" <!ATTLIST BIF VERSION CDATA #REQUIRED>\n");
text
.append(" <!ELEMENT NETWORK ( NAME, ( PROPERTY | VARIABLE | DEFINITION )* )>\n");
text.append(" <!ELEMENT NAME (#PCDATA)>\n");
text.append(" <!ELEMENT VARIABLE ( NAME, ( OUTCOME | PROPERTY )* ) >\n");
text
.append(" <!ATTLIST VARIABLE TYPE (nature|decision|utility) \"nature\">\n");
text.append(" <!ELEMENT OUTCOME (#PCDATA)>\n");
text
.append(" <!ELEMENT DEFINITION ( FOR | GIVEN | TABLE | PROPERTY )* >\n");
text.append(" <!ELEMENT FOR (#PCDATA)>\n");
text.append(" <!ELEMENT GIVEN (#PCDATA)>\n");
text.append(" <!ELEMENT TABLE (#PCDATA)>\n");
text.append(" <!ELEMENT PROPERTY (#PCDATA)>\n");
text.append("]>\n");
return text.toString();
} // getBIFHeader
/**
* Returns a description of the classifier in XML BIF 0.3 format. See
* http://www-2.cs.cmu.edu/~fgcozman/Research/InterchangeFormat/ for details
* on XML BIF.
*
* @return an XML BIF 0.3 description of the classifier as a string.
*/
public String toXMLBIF03() {
if (m_Instances == null) {
return ("<!--No model built yet-->");
}
StringBuffer text = new StringBuffer();
text.append(getBIFHeader());
text.append("\n");
text.append("\n");
text.append("<BIF VERSION=\"0.3\">\n");
text.append("<NETWORK>\n");
text.append("<NAME>" + XMLNormalize(m_Instances.relationName())
+ "</NAME>\n");
for (int iAttribute = 0; iAttribute < m_Instances.numAttributes(); iAttribute++) {
text.append("<VARIABLE TYPE=\"nature\">\n");
text.append("<NAME>"
+ XMLNormalize(m_Instances.attribute(iAttribute).name()) + "</NAME>\n");
for (int iValue = 0; iValue < m_Instances.attribute(iAttribute)
.numValues(); iValue++) {
text.append("<OUTCOME>"
+ XMLNormalize(m_Instances.attribute(iAttribute).value(iValue))
+ "</OUTCOME>\n");
}
text.append("</VARIABLE>\n");
}
for (int iAttribute = 0; iAttribute < m_Instances.numAttributes(); iAttribute++) {
text.append("<DEFINITION>\n");
text.append("<FOR>"
+ XMLNormalize(m_Instances.attribute(iAttribute).name()) + "</FOR>\n");
for (int iParent = 0; iParent < m_ParentSets[iAttribute].getNrOfParents(); iParent++) {
text
.append("<GIVEN>"
+ XMLNormalize(m_Instances.attribute(
m_ParentSets[iAttribute].getParent(iParent)).name())
+ "</GIVEN>\n");
}
text.append("<TABLE>\n");
for (int iParent = 0; iParent < m_ParentSets[iAttribute]
.getCardinalityOfParents(); iParent++) {
for (int iValue = 0; iValue < m_Instances.attribute(iAttribute)
.numValues(); iValue++) {
text.append(m_Distributions[iAttribute][iParent]
.getProbability(iValue));
text.append(' ');
}
text.append('\n');
}
text.append("</TABLE>\n");
text.append("</DEFINITION>\n");
}
text.append("</NETWORK>\n");
text.append("</BIF>\n");
return text.toString();
} // toXMLBIF03
/**
* XMLNormalize converts the five standard XML entities in a string g.e. the
* string V&D's is returned as V&D's
*
* @param sStr string to normalize
* @return normalized string
*/
protected String XMLNormalize(String sStr) {
StringBuffer sStr2 = new StringBuffer();
for (int iStr = 0; iStr < sStr.length(); iStr++) {
char c = sStr.charAt(iStr);
switch (c) {
case '&':
sStr2.append("&");
break;
case '\'':
sStr2.append("'");
break;
case '\"':
sStr2.append(""");
break;
case '<':
sStr2.append("<");
break;
case '>':
sStr2.append(">");
break;
default:
sStr2.append(c);
}
}
return sStr2.toString();
} // XMLNormalize
/**
* @return a string to describe the UseADTreeoption.
*/
public String useADTreeTipText() {
return "When ADTree (the data structure for increasing speed on counts,"
+ " not to be confused with the classifier under the same name) is used"
+ " learning time goes down typically. However, because ADTrees are memory"
+ " intensive, memory problems may occur. Switching this option off makes"
+ " the structure learning algorithms slower, and run with less memory."
+ " By default, ADTrees are used.";
}
/**
* @return a string to describe the SearchAlgorithm.
*/
public String searchAlgorithmTipText() {
return "Select method used for searching network structures.";
}
/**
* This will return a string describing the BayesNetEstimator.
*
* @return The string.
*/
public String estimatorTipText() {
return "Select Estimator algorithm for finding the conditional probability tables"
+ " of the Bayes Network.";
}
/**
* @return a string to describe the BIFFile.
*/
public String BIFFileTipText() {
return "Set the name of a file in BIF XML format. A Bayes network learned"
+ " from data can be compared with the Bayes network represented by the BIF file."
+ " Statistics calculated are o.a. the number of missing and extra arcs.";
}
/**
* This will return a string describing the classifier.
*
* @return The string.
*/
public String globalInfo() {
return "Bayes Network learning using various search algorithms and "
+ "quality measures.\n"
+ "Base class for a Bayes Network classifier. Provides "
+ "datastructures (network structure, conditional probability "
+ "distributions, etc.) and facilities common to Bayes Network "
+ "learning algorithms like K2 and B.\n\n"
+ "For more information see:\n\n"
+ "http://www.cs.waikato.ac.nz/~remco/weka.pdf";
}
/**
* Main method for testing this class.
*
* @param argv the options
*/
public static void main(String[] argv) {
runClassifier(new BayesNet(), argv);
} // main
/**
* get name of the Bayes network
*
* @return name of the Bayes net
*/
public String getName() {
return m_Instances.relationName();
}
/**
* get number of nodes in the Bayes network
*
* @return number of nodes
*/
public int getNrOfNodes() {
return m_Instances.numAttributes();
}
/**
* get name of a node in the Bayes network
*
* @param iNode index of the node
* @return name of the specified node
*/
public String getNodeName(int iNode) {
return m_Instances.attribute(iNode).name();
}
/**
* get number of values a node can take
*
* @param iNode index of the node
* @return cardinality of the specified node
*/
public int getCardinality(int iNode) {
return m_Instances.attribute(iNode).numValues();
}
/**
* get name of a particular value of a node
*
* @param iNode index of the node
* @param iValue index of the value
* @return cardinality of the specified node
*/
public String getNodeValue(int iNode, int iValue) {
return m_Instances.attribute(iNode).value(iValue);
}
/**
* get number of parents of a node in the network structure
*
* @param iNode index of the node
* @return number of parents of the specified node
*/
public int getNrOfParents(int iNode) {
return m_ParentSets[iNode].getNrOfParents();
}
/**
* get node index of a parent of a node in the network structure
*
* @param iNode index of the node
* @param iParent index of the parents, e.g., 0 is the first parent, 1 the
* second parent, etc.
* @return node index of the iParent's parent of the specified node
*/
public int getParent(int iNode, int iParent) {
return m_ParentSets[iNode].getParent(iParent);
}
/**
* Get full set of parent sets.
*
* @return parent sets;
*/
public ParentSet[] getParentSets() {
return m_ParentSets;
}
/**
* Get full set of estimators.
*
* @return estimators;
*/
public Estimator[][] getDistributions() {
return m_Distributions;
}
/**
* get number of values the collection of parents of a node can take
*
* @param iNode index of the node
* @return cardinality of the parent set of the specified node
*/
public int getParentCardinality(int iNode) {
return m_ParentSets[iNode].getCardinalityOfParents();
}
/**
* get particular probability of the conditional probability distribtion of a
* node given its parents.
*
* @param iNode index of the node
* @param iParent index of the parent set, 0 <= iParent <=
* getParentCardinality(iNode)
* @param iValue index of the value, 0 <= iValue <= getCardinality(iNode)
* @return probability
*/
public double getProbability(int iNode, int iParent, int iValue) {
return m_Distributions[iNode][iParent].getProbability(iValue);
}
/**
* get the parent set of a node
*
* @param iNode index of the node
* @return Parent set of the specified node.
*/
public ParentSet getParentSet(int iNode) {
return m_ParentSets[iNode];
}
/**
* get ADTree strucrture containing efficient representation of counts.
*
* @return ADTree strucrture
*/
public ADNode getADTree() {
return m_ADTree;
}
// implementation of AdditionalMeasureProducer interface
/**
* Returns an enumeration of the measure names. Additional measures must
* follow the naming convention of starting with "measure", eg. double
* measureBlah()
*
* @return an enumeration of the measure names
*/
@Override
public Enumeration<String> enumerateMeasures() {
Vector<String> newVector = new Vector<String>(4);
newVector.addElement("measureExtraArcs");
newVector.addElement("measureMissingArcs");
newVector.addElement("measureReversedArcs");
newVector.addElement("measureDivergence");
newVector.addElement("measureBayesScore");
newVector.addElement("measureBDeuScore");
newVector.addElement("measureMDLScore");
newVector.addElement("measureAICScore");
newVector.addElement("measureEntropyScore");
return newVector.elements();
} // enumerateMeasures
public double measureExtraArcs() {
if (m_otherBayesNet != null) {
return m_otherBayesNet.extraArcs(this);
}
return 0;
} // measureExtraArcs
public double measureMissingArcs() {
if (m_otherBayesNet != null) {
return m_otherBayesNet.missingArcs(this);
}
return 0;
} // measureMissingArcs
public double measureReversedArcs() {
if (m_otherBayesNet != null) {
return m_otherBayesNet.reversedArcs(this);
}
return 0;
} // measureReversedArcs
public double measureDivergence() {
if (m_otherBayesNet != null) {
return m_otherBayesNet.divergence(this);
}
return 0;
} // measureDivergence
public double measureBayesScore() {
LocalScoreSearchAlgorithm s = new LocalScoreSearchAlgorithm(this,
m_Instances);
return s.logScore(Scoreable.BAYES);
} // measureBayesScore
public double measureBDeuScore() {
LocalScoreSearchAlgorithm s = new LocalScoreSearchAlgorithm(this,
m_Instances);
return s.logScore(Scoreable.BDeu);
} // measureBDeuScore
public double measureMDLScore() {
LocalScoreSearchAlgorithm s = new LocalScoreSearchAlgorithm(this,
m_Instances);
return s.logScore(Scoreable.MDL);
} // measureMDLScore
public double measureAICScore() {
LocalScoreSearchAlgorithm s = new LocalScoreSearchAlgorithm(this,
m_Instances);
return s.logScore(Scoreable.AIC);
} // measureAICScore
public double measureEntropyScore() {
LocalScoreSearchAlgorithm s = new LocalScoreSearchAlgorithm(this,
m_Instances);
return s.logScore(Scoreable.ENTROPY);
} // measureEntropyScore
/**
* Returns the value of the named measure
*
* @param measureName the name of the measure to query for its value
* @return the value of the named measure
* @throws IllegalArgumentException if the named measure is not supported
*/
@Override
public double getMeasure(String measureName) {
if (measureName.equals("measureExtraArcs")) {
return measureExtraArcs();
}
if (measureName.equals("measureMissingArcs")) {
return measureMissingArcs();
}
if (measureName.equals("measureReversedArcs")) {
return measureReversedArcs();
}
if (measureName.equals("measureDivergence")) {
return measureDivergence();
}
if (measureName.equals("measureBayesScore")) {
return measureBayesScore();
}
if (measureName.equals("measureBDeuScore")) {
return measureBDeuScore();
}
if (measureName.equals("measureMDLScore")) {
return measureMDLScore();
}
if (measureName.equals("measureAICScore")) {
return measureAICScore();
}
if (measureName.equals("measureEntropyScore")) {
return measureEntropyScore();
}
return 0;
} // getMeasure
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 10386 $");
}
} // class BayesNet
| |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.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.jkiss.dbeaver.ui.editors.binary.pref;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.widgets.List;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.editors.binary.HexEditControl;
import org.jkiss.dbeaver.ui.editors.binary.internal.BinaryEditorMessages;
import java.util.*;
/**
* Manager of all preferences-editing widgets, with an optional standalone dialog.
*
* @author Jordi
*/
public class HexPreferencesManager {
private static final int itemsDisplayed = 9; // Number of font names displayed in list
private static final Set<Integer> scalableSizes = new TreeSet<>(
Arrays.asList(6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 22, 32, 72));
private static final String TEXT_BOLD = BinaryEditorMessages.editor_binary_hex_font_style_bold;
private static final String TEXT_BOLD_ITALIC = BinaryEditorMessages.editor_binary_hex_font_style_bold_italic;
private static final String TEXT_ITALIC = BinaryEditorMessages.editor_binary_hex_font_style_italic;
private static final String TEXT_REGULAR = BinaryEditorMessages.editor_binary_hex_font_style_regular;
private static final String SAMPLE_TEXT = BinaryEditorMessages.editor_binary_hex_sample_text;
private java.util.List<FontData> fontsListCurrent = null;
private java.util.List<FontData> fontsNonScalable = null;
private java.util.List<FontData> fontsScalable = null;
private GC fontsGc = null;
private java.util.Set<String> fontsRejected = null;
private java.util.Map<String, Set<Integer>> fontsSorted = null;
private FontData sampleFontData = null;
private Composite composite = null;
private Composite parent = null;
private Text textName = null;
private Text textStyle = null;
private Text textSize = null;
private List listFont = null;
private List listStyle = null;
private List listSize = null;
private Font sampleFont = null;
private Text sampleText = null;
private Combo cmbByteWidth = null;
private String defWidthValue;
private static String[] arrDefValuetoIndex = new String[] { "4", "8", "16" };
private static int fontStyleToInt(String styleString)
{
int style = SWT.NORMAL;
if (TEXT_BOLD.equals(styleString))
style = SWT.BOLD;
else if (TEXT_ITALIC.equals(styleString))
style = SWT.ITALIC;
else if (TEXT_BOLD_ITALIC.equals(styleString))
style = SWT.BOLD | SWT.ITALIC;
return style;
}
private static String fontStyleToString(int style)
{
switch (style) {
case SWT.BOLD:
return TEXT_BOLD;
case SWT.ITALIC:
return TEXT_ITALIC;
case SWT.BOLD | SWT.ITALIC:
return TEXT_BOLD_ITALIC;
default:
return TEXT_REGULAR;
}
}
HexPreferencesManager(FontData aFontData, String defWidth) {
sampleFontData = aFontData;
fontsSorted = new TreeMap<>();
defWidthValue = defWidth;
}
/**
* Creates all internal widgets
*/
private void createComposite()
{
composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, true));
{
Group fontGroup = UIUtils.createControlGroup(composite, BinaryEditorMessages.editor_binary_hex_froup_font_selection, 3, GridData.FILL_HORIZONTAL, 0);
Label label = UIUtils.createControlLabel(fontGroup, BinaryEditorMessages.editor_binary_hex_label_available_fix_width_fonts);
GridData gridData = new GridData();
gridData.horizontalSpan = 3;
label.setLayoutData(gridData);
UIUtils.createControlLabel(fontGroup, BinaryEditorMessages.editor_binary_hex_label_name);
UIUtils.createControlLabel(fontGroup, BinaryEditorMessages.editor_binary_hex_label_style);
UIUtils.createControlLabel(fontGroup, BinaryEditorMessages.editor_binary_hex_label_size);
textName = new Text(fontGroup, SWT.SINGLE | SWT.BORDER);
GridData gridData4 = new GridData();
gridData4.horizontalAlignment = GridData.FILL;
textName.setLayoutData(gridData4);
textStyle = new Text(fontGroup, SWT.BORDER);
GridData gridData5 = new GridData();
gridData5.horizontalAlignment = GridData.FILL;
textStyle.setLayoutData(gridData5);
textStyle.setEnabled(false);
textSize = new Text(fontGroup, SWT.BORDER);
GridData gridData6 = new GridData();
gridData6.horizontalAlignment = GridData.FILL;
GC gc = new GC(fontGroup);
int averageCharWidth = gc.getFontMetrics().getAverageCharWidth();
gc.dispose();
gridData6.widthHint = averageCharWidth * 6;
textSize.setLayoutData(gridData6);
listFont = new List(fontGroup, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
GridData gridData52 = new GridData();
gridData52.heightHint = itemsDisplayed * listFont.getItemHeight();
gridData52.widthHint = averageCharWidth * 40;
listFont.setLayoutData(gridData52);
listFont.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
textName.setText(listFont.getSelection()[0]);
updateSizeItemsAndGuessSelected();
updateAndRefreshSample();
}
});
listStyle = new List(fontGroup, SWT.SINGLE | SWT.BORDER);
GridData gridData21 = new GridData();
gridData21.verticalAlignment = GridData.FILL;
gridData21.widthHint = averageCharWidth * TEXT_BOLD_ITALIC.length() * 2;
listStyle.setLayoutData(gridData21);
listStyle.setItems(new String[] { TEXT_REGULAR, TEXT_BOLD, TEXT_ITALIC, TEXT_BOLD_ITALIC });
listStyle.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
textStyle.setText(listStyle.getSelection()[0]);
updateAndRefreshSample();
}
});
listSize = new List(fontGroup, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
GridData gridData7 = new GridData();
gridData7.widthHint = gridData6.widthHint;
gridData7.heightHint = gridData52.heightHint;
listSize.setLayoutData(gridData7);
listSize.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
textSize.setText(listSize.getSelection()[0]);
updateAndRefreshSample();
}
});
sampleText = new Text(fontGroup, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY | SWT.BORDER);
sampleText.setText(SAMPLE_TEXT);
sampleText.setEditable(false);
GridData gridData8 = new GridData();
gridData8.horizontalSpan = 3;
gridData8.widthHint = gridData52.widthHint + gridData21.widthHint + gridData7.widthHint + 10;
gridData8.heightHint = 50;
gridData8.horizontalAlignment = GridData.FILL;
sampleText.setLayoutData(gridData8);
sampleText.addDisposeListener(e -> {
if (sampleFont != null && !sampleFont.isDisposed()) {
sampleFont.dispose();
}
});
}
{
Group cmpByteSettings = UIUtils.createControlGroup(composite, "Settings", 2, GridData.FILL_HORIZONTAL, 0);
UIUtils.createControlLabel(cmpByteSettings, "Default width");
cmbByteWidth = new Combo(cmpByteSettings, SWT.BORDER);
cmbByteWidth.setItems(arrDefValuetoIndex);
int index = Arrays.asList(arrDefValuetoIndex).indexOf(defWidthValue);
cmbByteWidth.select(index);
}
}
String getDefWidth() {
return cmbByteWidth.getText();
}
/**
* Creates the part containing all preferences-editing widgets, that is, ok and cancel
* buttons are left out so we can call this method from both standalone and plugin.
*
* @param aParent composite where preferences will be drawn
*/
Composite createPreferencesPart(Composite aParent)
{
parent = aParent;
createComposite();
if (fontsSorted.size() < 1) {
populateFixedCharWidthFonts();
} else {
listFont.setItems(fontsSorted.keySet().toArray(new String[fontsSorted.keySet().size()]));
refreshWidgets();
}
return composite;
}
/**
* Get the preferred font data
*
* @return a copy of the preferred font data
*/
public FontData getFontData()
{
return new FontData(
sampleFontData.getName(),
sampleFontData.getHeight(),
sampleFontData.getStyle());
}
private FontData getNextFontData()
{
if (fontsListCurrent.size() == 0) {
fontsListCurrent = fontsScalable;
}
FontData aData = fontsListCurrent.get(0);
fontsListCurrent.remove(0);
while (fontsRejected.contains(aData.getName()) && fontsScalable.size() > 0) {
if (fontsListCurrent.size() == 0) {
fontsListCurrent = fontsScalable;
}
aData = fontsListCurrent.get(0);
fontsListCurrent.remove(0);
}
return aData;
}
int getSize()
{
int size = 0;
if (!"".equals(textSize.getText())) { //$NON-NLS-1$
try {
size = Integer.parseInt(textSize.getText());
}
catch (NumberFormatException e) {
// do nothing
} // was not a number, keep it 0
}
// bugfix: HexText's raw array overflows when font is very small and window very big
// very small sizes would compromise responsiveness in large windows, and they are too small
// to see anyway
if (size == 1 || size == 2) size = 3;
return size;
}
private void populateFixedCharWidthFonts()
{
fontsNonScalable = new ArrayList<>(Arrays.asList(Display.getCurrent().getFontList(null, false)));
fontsScalable = new ArrayList<>(Arrays.asList(Display.getCurrent().getFontList(null, true)));
if (fontsNonScalable.size() == 0 && fontsScalable.size() == 0) {
fontsNonScalable = null;
fontsScalable = null;
return;
}
fontsListCurrent = fontsNonScalable;
fontsRejected = new HashSet<>();
fontsGc = new GC(parent);
UIUtils.asyncExec(this::populateFixedCharWidthFontsAsync);
}
private void populateFixedCharWidthFontsAsync()
{
FontData fontData = getNextFontData();
if (!fontsRejected.contains(fontData.getName())) {
boolean isScalable = fontsListCurrent == fontsScalable;
int height = 10;
if (!isScalable) height = fontData.getHeight();
Font font = new Font(Display.getCurrent(), fontData.getName(), height, SWT.NORMAL);
fontsGc.setFont(font);
int width = fontsGc.getAdvanceWidth((char) 0x020);
boolean isFixedWidth = true;
for (int j = 0x021; j < 0x0100 && isFixedWidth; ++j) {
if (((char)j) == '.' && j != '.') continue;
if (width != fontsGc.getAdvanceWidth((char) j)) isFixedWidth = false;
}
font.dispose();
if (isFixedWidth) {
if (isScalable) {
fontsSorted.put(fontData.getName(), scalableSizes);
} else {
Set<Integer> heights = fontsSorted.get(fontData.getName());
if (heights == null) {
heights = new TreeSet<>();
fontsSorted.put(fontData.getName(), heights);
}
heights.add(fontData.getHeight());
}
if (!listFont.isDisposed())
listFont.setItems(fontsSorted.keySet().toArray(new String[fontsSorted.keySet().size()]));
refreshWidgets();
} else {
fontsRejected.add(fontData.getName());
}
}
if (fontsNonScalable.size() == 0 && fontsScalable.size() == 0) {
if (!parent.isDisposed()) fontsGc.dispose();
fontsGc = null;
fontsNonScalable = fontsScalable = fontsListCurrent = null;
fontsRejected = null;
} else {
UIUtils.asyncExec(this::populateFixedCharWidthFontsAsync);
}
}
private void refreshSample()
{
if (sampleFont != null && !sampleFont.isDisposed()) {
sampleFont.dispose();
}
sampleFont = new Font(Display.getCurrent(), sampleFontData);
sampleText.setFont(sampleFont);
}
private void refreshWidgets()
{
if (composite.isDisposed() || textName == null)
return;
if (fontsSorted == null || !fontsSorted.containsKey(sampleFontData.getName())) {
textName.setText(BinaryEditorMessages.editor_binary_hex_default_font);
} else {
textName.setText(sampleFontData.getName());
}
showSelected(listFont, sampleFontData.getName());
textStyle.setText(fontStyleToString(sampleFontData.getStyle()));
listStyle.select(listStyle.indexOf(fontStyleToString(sampleFontData.getStyle())));
updateSizeItems();
textSize.setText(Integer.toString(sampleFontData.getHeight()));
showSelected(listSize, Integer.toString(sampleFontData.getHeight()));
refreshSample();
}
/**
* Set preferences to show a font. Use null to show default font.
*
* @param aFontData the font to be shown.
*/
void setFontData(FontData aFontData)
{
if (aFontData == null)
aFontData = HexEditControl.DEFAULT_FONT_DATA;
sampleFontData = aFontData;
refreshWidgets();
}
private static void showSelected(List aList, String item)
{
int selected = aList.indexOf(item);
if (selected >= 0) {
aList.setSelection(selected);
aList.setTopIndex(Math.max(0, selected - itemsDisplayed + 1));
} else {
aList.deselectAll();
aList.setTopIndex(0);
}
}
private void updateAndRefreshSample()
{
sampleFontData = new FontData(textName.getText(), getSize(), fontStyleToInt(textStyle.getText()));
refreshSample();
}
private void updateSizeItems()
{
Set<Integer> sizes = fontsSorted.get(textName.getText());
if (sizes == null) {
listSize.removeAll();
return;
}
String[] items = new String[sizes.size()];
int i = 0;
for (Iterator<Integer> j = sizes.iterator(); i < items.length; ++i) items[i] = j.next().toString();
listSize.setItems(items);
}
private void updateSizeItemsAndGuessSelected()
{
int lastSize = getSize();
updateSizeItems();
int position = 0;
String[] items = listSize.getItems();
for (int i = 1; i < items.length; ++i) {
if (lastSize >= Integer.parseInt(items[i]))
position = i;
}
textSize.setText(items[position]);
showSelected(listSize, items[position]);
}
}
| |
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2020 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing 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 org.killbill.billing.plugin.notification.email;
import java.io.IOException;
import java.util.List;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.SimpleEmail;
import org.killbill.billing.osgi.libs.killbill.OSGIConfigPropertiesService;
import org.killbill.billing.plugin.notification.exception.EmailNotificationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import static org.killbill.billing.plugin.notification.exception.EmailNotificationErrorCode.EMAIL_ADDRESS_INVALID;
import static org.killbill.billing.plugin.notification.exception.EmailNotificationErrorCode.RECIPIENT_EMAIL_ADDRESS_REQUIRED;
import static org.killbill.billing.plugin.notification.exception.EmailNotificationErrorCode.SENDER_EMAIL_ADDRESS_REQUIRED;
import static org.killbill.billing.plugin.notification.exception.EmailNotificationErrorCode.SMTP_AUTHENTICATION_REQUIRED;
import static org.killbill.billing.plugin.notification.exception.EmailNotificationErrorCode.SMTP_HOSTNAME_REQUIRED;
import static org.killbill.billing.plugin.notification.exception.EmailNotificationErrorCode.SUBJECT_REQUIRED;
public class EmailSender {
private static final Joiner JOINER_ON_COMMA = Joiner.on(", ");
private static final Logger logger = LoggerFactory.getLogger(EmailSender.class);
/* Reuse Kill Bill email properties; if needed we can have a different set for the plugin */
private static final String SERVER_NAME_PROP = "org.killbill.mail.smtp.host";
private static final String SERVER_PORT_PROP = "org.killbill.mail.smtp.port";
private static final String IS_SMTP_AUTH_PROP = "org.killbill.mail.smtp.auth";
private static final String SMTP_USER_PROP = "org.killbill.mail.smtp.user";
private static final String SMTP_PWD_PROP = "org.killbill.mail.smtp.password";
private static final String IS_USE_SSL_PROP = "org.killbill.mail.useSSL";
private static final String SMTP_FROM_PROP = "org.killbill.mail.from";
private static final String DEBUG_LOG_ONLY = "org.killbill.billing.plugin.notification.email.logOnly";
private final boolean useSmtpAuth;
private final int useSmtpPort;
private final String smtpUserName;
private final String smtpUserPassword;
private final String smtpServerName;
private final String from;
private final boolean useSSL;
private final boolean logOnly;
public EmailSender(final OSGIConfigPropertiesService configProperties) {
this(configProperties.getString(SERVER_NAME_PROP),
(configProperties.getString(SERVER_PORT_PROP) != null ? Integer.parseInt(configProperties.getString(SERVER_PORT_PROP)) : 25),
configProperties.getString(SMTP_USER_PROP),
configProperties.getString(SMTP_PWD_PROP),
configProperties.getString(SMTP_FROM_PROP),
(configProperties.getString(IS_SMTP_AUTH_PROP) != null ? Boolean.valueOf(configProperties.getString(IS_SMTP_AUTH_PROP)) : false),
(configProperties.getString(IS_USE_SSL_PROP) != null ? Boolean.valueOf(configProperties.getString(IS_USE_SSL_PROP)) : false),
(configProperties.getString(DEBUG_LOG_ONLY) != null ? Boolean.valueOf(configProperties.getString(DEBUG_LOG_ONLY)) : false));
}
public EmailSender(final String smtpServerName, final int useSmtpPort, final String smtpUserName, final String smtpUserPassword, final String from, final boolean useSmtpAuth, final boolean useSSL, final boolean logOnly) {
this.useSmtpAuth = useSmtpAuth;
this.useSmtpPort = useSmtpPort;
this.smtpUserName = smtpUserName;
this.smtpUserPassword = smtpUserPassword;
this.smtpServerName = smtpServerName;
this.from = from;
this.useSSL = useSSL;
this.logOnly = logOnly;
}
// Backward compatibility. If no configuration exists, then reuse Kill Bill email properties
public SmtpProperties precheckSmtp(SmtpProperties smtp) {
if (smtp.getHost() == null && smtpServerName != null){
smtp.setHost(smtpServerName);
smtp.setDefaultSender(this.from);
smtp.setPort(this.useSmtpPort);
smtp.setPassword(this.smtpUserPassword);
smtp.setUserName(this.smtpUserName);
smtp.setUseAuthentication(this.useSmtpAuth);
smtp.setUseSSL(this.useSSL);
}
logger.info("EmailSender configured with serverName={}, serverPort={}, from={}, logOnly={}",
smtp.getHost(), smtp.getPort(), smtp.getFrom(), logOnly);
return smtp;
}
public void sendHTMLEmail(final List<String> to, final List<String> cc, final String subject, final String htmlBody, final SmtpProperties smtp) throws EmailException, EmailNotificationException {
logger.debug("Sending email to={}, cc={}, subject={}, body=[{}]",
to,
JOINER_ON_COMMA.join(cc),
subject,
htmlBody);
final HtmlEmail email = new HtmlEmail();
email.setHtmlMsg(htmlBody);
sendEmail(to, cc, subject, email, precheckSmtp(smtp));
}
public void sendPlainTextEmail(final List<String> to, final List<String> cc, final String subject, final String body, final SmtpProperties smtp) throws IOException, EmailException, EmailNotificationException {
logger.debug("Sending email to={}, cc={}, subject={}, body=[{}]",
to,
JOINER_ON_COMMA.join(cc),
subject,
body);
final SimpleEmail email = new SimpleEmail();
email.setCharset("utf-8");
email.setMsg(body);
sendEmail(to, cc, subject, email, precheckSmtp(smtp));
}
private void sendEmail(final List<String> to, final List<String> cc, final String subject, final Email email, final SmtpProperties smtp) throws EmailException, EmailNotificationException {
if (logOnly) {
return;
}
validateEmailFields(to, cc, subject, smtp);
email.setSmtpPort(smtp.getPort());
if (smtp.isUseAuthentication()) {
email.setAuthentication(smtp.getUserName(), smtp.getPassword());
}
email.setHostName(smtp.getHost());
email.setFrom(smtp.getFrom());
email.setSubject(subject);
if (to != null) {
for (final String recipient : to) {
email.addTo(recipient);
}
}
if (cc != null) {
for (final String recipient : cc) {
email.addCc(recipient);
}
}
email.setSSLOnConnect(smtp.isUseSSL());
logger.info("Sending email to={}, cc={}, subject={}", to, cc, subject);
email.send();
}
private void validateEmailFields(final List<String> to, final List<String> cc, final String subject, final SmtpProperties smtp) throws EmailNotificationException {
if (to == null || to.size() == 0 || to.get(0).trim().isEmpty()){
throw new EmailNotificationException(RECIPIENT_EMAIL_ADDRESS_REQUIRED);
}
if (smtp.getFrom() == null || smtp.getFrom().trim().isEmpty()){
throw new EmailNotificationException(SENDER_EMAIL_ADDRESS_REQUIRED);
}
if (smtp.isUseAuthentication() && ( (smtp.getUserName() == null || smtp.getUserName().trim().isEmpty()) || (smtp.getPassword() == null || smtp.getPassword().trim().isEmpty()) )){
throw new EmailNotificationException(SMTP_AUTHENTICATION_REQUIRED);
}
if (subject == null || subject.trim().isEmpty()){
throw new EmailNotificationException(SUBJECT_REQUIRED);
}
if (smtp.getHost() == null || smtp.getHost().trim().isEmpty()){
throw new EmailNotificationException(SMTP_HOSTNAME_REQUIRED);
}
validateEmailAddress(smtp.getFrom());
for(String recipient: to){
validateEmailAddress(recipient);
}
for(String recipient: cc){
validateEmailAddress(recipient);
}
}
private void validateEmailAddress(String email) throws EmailNotificationException {
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
throw new EmailNotificationException(ex, EMAIL_ADDRESS_INVALID, email);
}
}
}
| |
/*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to TO_YEAR PrismTech
* Limited, its affiliated companies and licensors. 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 chatroom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import org.omg.dds.core.DDSException;
import org.omg.dds.core.ServiceEnvironment;
import org.omg.dds.core.policy.Durability;
import org.omg.dds.core.policy.History;
import org.omg.dds.core.policy.Partition;
import org.omg.dds.core.policy.PolicyFactory;
import org.omg.dds.core.policy.Reliability;
import org.omg.dds.core.status.Status;
import org.omg.dds.domain.DomainParticipant;
import org.omg.dds.domain.DomainParticipantFactory;
import org.omg.dds.pub.DataWriter;
import org.omg.dds.pub.DataWriterQos;
import org.omg.dds.pub.Publisher;
import org.omg.dds.pub.PublisherQos;
import org.omg.dds.sub.DataReader;
import org.omg.dds.sub.DataReaderListener;
import org.omg.dds.sub.DataReaderQos;
import org.omg.dds.sub.Sample;
import org.omg.dds.sub.Subscriber;
import org.omg.dds.sub.SubscriberQos;
import org.omg.dds.topic.ContentFilteredTopic;
import org.omg.dds.topic.Topic;
import org.omg.dds.topic.TopicQos;
import Chat.ChatMessage;
import Chat.NameService;
import Chat.NamedMessage;
public class MessageBoard {
private static ServiceEnvironment env = null;
private static DomainParticipantFactory dpf = null;
private static DomainParticipant participant = null;
private static PolicyFactory policyFactory = null;
private static TopicQos reliableTopicQos = null;
private static Topic<ChatMessage> chatMessageTopic = null;
private static Topic<NameService> nameServiceTopic = null;
private static Topic<NamedMessage> namedMessageTopic = null;
private static Subscriber subscriber = null;
private static Publisher publisher = null;
private static DataReader<ChatMessage> chatMessageDataReader = null;
private static DataReader<NameService> nameServiceDataReader = null;
private static DataWriter<NamedMessage> namedMessageDataWriter = null;
private static ContentFilteredTopic<ChatMessage> cfm =null;
private static boolean terminated = false;
public static final int TERMINATION_MESSAGE = -1;
private static String[] parameterList = new String[1];
public static void create_simulated_multitopic() {
/*
* A Topic is created for the Chat_ChatMessage sample type on the
* domain participant.
*/
Collection<Class<? extends Status>> status = new HashSet<Class<? extends Status>>();
/*
* A TopicQos is created with Durability set to Transient to
* ensure that if a subscriber joins after the sample is written then DDS
* will still retain the sample for it.
*/
Durability durability = policyFactory.Durability().withTransient();
TopicQos transientTopicQos = participant.getDefaultTopicQos().withPolicy(durability);
/*
* A Topic is created for the Chat_NameService sample type on the
* domain participant.
*/
nameServiceTopic = participant.createTopic("Chat_NameService", NameService.class, transientTopicQos, null, status);
/*
* A Topic is created for the Chat_NamedMessage sample type on the
* domain participant.
*/
namedMessageTopic = participant.createTopic("Chat_NamedMessage", NamedMessage.class, reliableTopicQos, null, status);
/* A content-filtered topic is created, filtering out our own ID. */
List<String> p = new ArrayList<String>();
p.add(parameterList[0]);
String filter = "userID <> %0";
cfm = participant.createContentFilteredTopic("Chat_FilteredMessage", chatMessageTopic, filter, p);
/* Create a KEEP_ALL datareader for the chat-messages */
DataReaderQos drQos = subscriber.copyFromTopicQos(subscriber.getDefaultDataReaderQos(), reliableTopicQos);
History history = policyFactory.History().withKeepAll();
drQos = drQos.withPolicy(history);
chatMessageDataReader = subscriber.createDataReader(cfm, drQos);
/* Create a TRANSIENT datareader for the name-service topic */
drQos = subscriber.copyFromTopicQos(subscriber.getDefaultDataReaderQos(), transientTopicQos);
nameServiceDataReader = subscriber.createDataReader(nameServiceTopic, drQos);
/* Create a publisher and datawriter for the simulated multitopic */
Partition chatroom = policyFactory.Partition().withName("ChatRoom");
PublisherQos chatPartitionQos = participant.getDefaultPublisherQos().withPolicy(chatroom);
publisher = participant.createPublisher(chatPartitionQos);
DataWriterQos dwQos = publisher.copyFromTopicQos(publisher.getDefaultDataWriterQos(), reliableTopicQos);
namedMessageDataWriter = publisher.createDataWriter(namedMessageTopic,dwQos);
/* Create and set the listener for the ChatMessage */
DataReaderListener<ChatMessage> drl = new DataReaderListenerClass(chatMessageDataReader, nameServiceDataReader, namedMessageDataWriter);
chatMessageDataReader.setListener(drl);
}
public static void main(String[] args) {
/* Options: MessageBoard [ownID] */
/* Messages having owner ownID will be ignored */
if (args.length >0) {
parameterList[0] = args[0];
}
else {
parameterList[0] = new String("0");
}
/* The service environment is created for the application. */
System.setProperty(ServiceEnvironment.IMPLEMENTATION_CLASS_NAME_PROPERTY,
"org.opensplice.dds.core.OsplServiceEnvironment");
env = ServiceEnvironment.createInstance(MessageBoard.class.getClassLoader());
/* A DomainParticipant is created for the default domain. */
dpf = DomainParticipantFactory.getInstance(env);
try {
participant = dpf.createParticipant();
/*
* A TopicQos is created with Reliability set to Reliable to
* guarantee delivery.
*/
policyFactory = env.getSPI().getPolicyFactory();
Reliability reliable = policyFactory.Reliability().withReliable();
reliableTopicQos = participant.getDefaultTopicQos().withPolicy(reliable);
/* Set the Reliable TopicQos as the new default */
participant.setDefaultTopicQos(reliableTopicQos);
/*
* A Topic is created for the Chat_ChatMessage sample type on the
* domain participant.
*/
Collection<Class<? extends Status>> status = new HashSet<Class<? extends Status>>();
chatMessageTopic = participant.createTopic("Chat_ChatMessage", ChatMessage.class, reliableTopicQos, null, status);
/*
* Create a Subscriber and a NamedMessageDataReader whose
* QoS Settings comply with that on the topic.
*/
Partition chatroom = policyFactory.Partition().withName("ChatRoom");
SubscriberQos chatPartitionQos = participant.getDefaultSubscriberQos().withPolicy(chatroom);
subscriber = participant.createSubscriber(chatPartitionQos);
create_simulated_multitopic();
DataReaderQos drQos = subscriber.copyFromTopicQos(subscriber.getDefaultDataReaderQos(), reliableTopicQos);
History history = policyFactory.History().withKeepAll();
drQos = drQos.withPolicy(history);
DataReader<NamedMessage> namedMessageDataReader = subscriber.createDataReader(namedMessageTopic,drQos);
System.out.println(
"MessageBoard has opened: send a ChatMessage " +
"with userID = -1 to close it....\n");
while (!terminated) {
/* Note: using read does not remove the samples from unregistered
* instances from the DataReader. This means that the DataReader
* would use more and more resources. That's why we use take here
* instead. */
List<Sample<NamedMessage>> samples = new ArrayList<Sample<NamedMessage>>();
namedMessageDataReader.take(samples);
for (Sample<NamedMessage> sample : samples) {
NamedMessage message = sample.getData();
if (message != null) {
if (message.userID == TERMINATION_MESSAGE) {
System.out.println("Termination message received: exiting...");
terminated = true;
} else {
System.out.println(message.userName + " : " + message.content);
}
}
}
/* Sleep for some amount of time, as not to consume too much CPU cycles. */
try {
Thread.sleep(100);
} catch (InterruptedException ignore) { /* Do nothing */ }
}
} catch (DDSException e) {
System.out.println("Error occurred. Terminating MessageBoard (" + e.getMessage() + ")");
}
System.out.println("MessageBoard has terminated.");
}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.safeDelete.SafeDeleteHandler;
import com.intellij.testFramework.PsiTestUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.java.JavaSourceRootType;
import org.jetbrains.jps.model.java.JpsJavaExtensionService;
public class SafeDeleteTest extends MultiFileTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
}
@NotNull
@Override
protected String getTestRoot() {
return "/refactoring/safeDelete/";
}
public void testImplicitCtrCall() throws Exception {
try {
doTest("Super");
fail();
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
String message = e.getMessage();
assertTrue(message, message.startsWith("constructor <b><code>Super.Super()</code></b> has 1 usage that is not safe to delete"));
}
}
public void testImplicitCtrCall2() throws Exception {
try {
doTest("Super");
fail();
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
String message = e.getMessage();
assertTrue(message, message.startsWith("constructor <b><code>Super.Super()</code></b> has 1 usage that is not safe to delete"));
}
}
public void testMultipleInterfacesImplementation() throws Exception {
doTest("IFoo");
}
public void testMultipleInterfacesImplementationThroughCommonInterface() throws Exception {
doTest("IFoo");
}
public void testUsageInExtendsList() throws Exception {
doSingleFileTest();
}
public void testDeepDeleteParameterSimple() throws Exception {
doSingleFileTest();
}
public void testDeepDeleteParameterOtherTypeInBinaryExpression() throws Exception {
doSingleFileTest();
}
public void testImpossibleToDeepDeleteParameter() throws Exception {
doSingleFileTest();
}
public void testNoDeepDeleteParameterUsedInCallQualifier() throws Exception {
doSingleFileTest();
}
public void testNoDeepDeleteParameterUsedInNextArgumentExpression() throws Exception {
doSingleFileTest();
}
public void testToDeepDeleteParameterOverriders() throws Exception {
doSingleFileTest();
}
public void testDeleteMethodCascade() throws Exception {
doSingleFileTest();
}
public void testDeleteMethodCascadeRecursive() throws Exception {
doSingleFileTest();
}
public void testDeleteMethodCascadeOverridden() throws Exception {
doSingleFileTest();
}
public void testDeleteParameterAndUpdateJavadocRef() throws Exception {
doSingleFileTest();
}
public void testDeleteConstructorParameterWithAnonymousClassUsage() throws Exception {
doSingleFileTest();
}
public void testParameterInHierarchy() throws Exception {
doTest("C2");
}
public void testTopLevelDocComment() throws Exception {
doTest("foo.C1");
}
public void testOverloadedMethods() throws Exception {
doTest("foo.A");
}
public void testTopParameterInHierarchy() throws Exception {
doTest("I");
}
public void testExtendsList() throws Exception {
doTest("B");
}
public void testJavadocParamRef() throws Exception {
doTest("Super");
}
public void testEnumConstructorParameter() throws Exception {
doTest("UserFlags");
}
public void testSafeDeleteStaticImports() throws Exception {
doTest("A");
}
public void testSafeDeleteImports() throws Exception {
doTest("B");
}
public void testRemoveOverridersInspiteOfUnsafeUsages() throws Exception {
try {
BaseRefactoringProcessor.ConflictsInTestsException.setTestIgnore(true);
doTest("A");
}
finally {
BaseRefactoringProcessor.ConflictsInTestsException.setTestIgnore(false);
}
}
public void testLocalVariable() throws Exception {
doTest("Super");
}
public void testOverrideAnnotation() throws Exception {
doTest("Super");
}
public void testSuperCall() throws Exception {
try {
doTest("Super");
fail("Conflict was not detected");
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
String message = e.getMessage();
assertEquals("method <b><code>Super.foo()</code></b> has 1 usage that is not safe to delete.", message);
}
}
public void testParameterFromFunctionalInterface() throws Exception {
try {
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_8);
doSingleFileTest();
fail("Conflict was not detected");
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
String message = e.getMessage();
assertEquals("class <b><code>SAM</code></b> has 1 usage that is not safe to delete.", message);
}
}
public void testFunctionalInterfaceMethod() throws Exception {
try {
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_8);
doSingleFileTest();
fail("Conflict was not detected");
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
String message = e.getMessage();
assertEquals("class <b><code>SAM</code></b> has 1 usage that is not safe to delete.", message);
}
}
public void testAmbiguityAfterParameterDelete() throws Exception {
try {
doSingleFileTest();
fail("Conflict was not detected");
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
String message = e.getMessage();
assertEquals("Method foo() is already defined in the class <b><code>Test</code></b>", message);
}
}
public void testFunctionalInterfaceDefaultMethod() throws Exception {
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_8);
doSingleFileTest();
}
public void testMethodDeepHierarchy() throws Exception {
doTest("Super");
}
public void testInterfaceAsTypeParameterBound() throws Exception {
doSingleFileTest();
}
public void testLocalVariableSideEffect() throws Exception {
try {
doTest("Super");
fail("Side effect was ignored");
}
catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
String message = e.getMessage();
assertEquals("local variable <b><code>varName</code></b> has 1 usage that is not safe to delete.", message);
}
}
public void testUsageInGenerated() throws Exception {
doTest("A");
}
public void testLastResourceVariable() throws Exception {
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
doSingleFileTest();
}
public void testLastResourceVariableWithFinallyBlock() throws Exception {
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
doSingleFileTest();
}
public void testLastTypeParam() throws Exception {
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
doSingleFileTest();
}
public void testTypeParamFromDiamond() throws Exception {
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
doSingleFileTest();
}
public void testStripOverride() throws Exception {
doSingleFileTest();
}
public void testEmptyIf() throws Exception {
doSingleFileTest();
}
private void doTest(@NonNls final String qClassName) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
SafeDeleteTest.this.performAction(qClassName);
}
});
}
@Override
protected void prepareProject(VirtualFile rootDir) {
VirtualFile src = rootDir.findChild("src");
if (src == null) {
super.prepareProject(rootDir);
}
else {
PsiTestUtil.addContentRoot(myModule, rootDir);
PsiTestUtil.addSourceRoot(myModule, src);
}
VirtualFile gen = rootDir.findChild("gen");
if (gen != null) {
PsiTestUtil.addSourceRoot(myModule, gen, JavaSourceRootType.SOURCE, JpsJavaExtensionService.getInstance().createSourceRootProperties("", true));
}
}
private void doSingleFileTest() throws Exception {
configureByFile(getTestRoot() + getTestName(false) + ".java");
performAction();
checkResultByFile(getTestRoot() + getTestName(false) + "_after.java");
}
private void performAction(final String qClassName) throws Exception {
final PsiClass aClass = myJavaFacade.findClass(qClassName, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class " + qClassName + " not found", aClass);
configureByExistingFile(aClass.getContainingFile().getVirtualFile());
performAction();
}
private void performAction() {
final PsiElement psiElement = TargetElementUtil
.findTargetElement(myEditor, TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED);
assertNotNull("No element found in text:\n" + getFile().getText(), psiElement);
SafeDeleteHandler.invoke(getProject(), new PsiElement[]{psiElement}, true);
}
}
| |
/*
* Copyright (c) 2014-2015 University of Ulm
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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 models;
import de.uniulm.omi.cloudiator.common.os.LoginNameSupplier;
import de.uniulm.omi.cloudiator.common.os.RemotePortProvider;
import models.generic.RemoteResourceInLocation;
import models.generic.RemoteState;
import javax.annotation.Nullable;
import javax.persistence.*;
import java.util.*;
/**
* Created by daniel on 31.10.14.
*/
@Entity public class VirtualMachine extends RemoteResourceInLocation implements LoginNameSupplier {
@Column(unique = true, nullable = false) private String name;
@Nullable @Column(nullable = true) private String generatedLoginUsername;
@Nullable @Column(nullable = true) private String generatedLoginPassword;
@Nullable @Lob @Column(nullable = true) private String generatedPrivateKey;
@Nullable @ManyToOne(optional = true) private Image image;
@Nullable @ManyToOne(optional = true) private Hardware hardware;
@Nullable @ManyToOne(optional = true) private TemplateOptions templateOptions;
@OneToMany(mappedBy = "virtualMachine") private List<Instance> instances;
/**
* Use set to avoid duplicate entries due to hibernate bug
* https://hibernate.atlassian.net/browse/HHH-7404
*/
@OneToMany(mappedBy = "virtualMachine", cascade = {CascadeType.ALL}, orphanRemoval = true)
private Set<IpAddress> ipAddresses;
/**
* Empty constructor for hibernate.
*/
protected VirtualMachine() {
}
public VirtualMachine(@Nullable String remoteId, @Nullable String providerId,
@Nullable String swordId, Cloud cloud, @Nullable CloudCredential owner, Location location,
String name, @Nullable String generatedLoginUsername,
@Nullable String generatedLoginPassword, @Nullable String generatedPrivateKey,
@Nullable Image image, @Nullable Hardware hardware,
@Nullable TemplateOptions templateOptions) {
super(remoteId, providerId, swordId, cloud, owner, location);
this.name = name;
this.generatedLoginUsername = generatedLoginUsername;
this.generatedLoginPassword = generatedLoginPassword;
this.generatedPrivateKey = generatedPrivateKey;
this.image = image;
this.hardware = hardware;
this.templateOptions = templateOptions;
}
public Optional<Image> image() {
return Optional.ofNullable(image);
}
public Optional<Hardware> hardware() {
return Optional.ofNullable(hardware);
}
public void addIpAddress(IpAddress ipAddress) {
if (ipAddresses == null) {
this.ipAddresses = new HashSet<>();
}
this.ipAddresses.add(ipAddress);
}
public void removeIpAddress(IpAddress ipAddress) {
if (ipAddresses == null) {
return;
}
ipAddresses.remove(ipAddress);
}
public void removeIpAddresses() {
if (ipAddresses == null) {
return;
}
ipAddresses.clear();
}
public Optional<IpAddress> publicIpAddress() {
return ipAddresses.stream().filter(ipAddress -> ipAddress.getIpType().equals(IpType.PUBLIC))
.findAny();
}
public Optional<IpAddress> privateIpAddress(boolean fallbackToPublic) {
final Optional<IpAddress> any =
ipAddresses.stream().filter(ipAddress -> ipAddress.getIpType().equals(IpType.PRIVATE))
.findAny();
if (!any.isPresent() && fallbackToPublic) {
return publicIpAddress();
}
return any;
}
public String name() {
return name;
}
public Optional<String> loginPrivateKey() {
return Optional.ofNullable(generatedPrivateKey);
}
public int remotePort() {
if (image == null) {
throw new RemotePortProvider.UnknownRemotePortException(
"Remote port is unknown as image is no longer known.");
}
return image.operatingSystem().operatingSystemFamily().remotePort();
}
public Optional<TemplateOptions> templateOptions() {
return Optional.ofNullable(templateOptions);
}
public void setGeneratedLoginUsername(@Nullable String generatedLoginUsername) {
if (this.generatedLoginUsername != null) {
throw new IllegalStateException("Changing generatedLoginUsername not permitted.");
}
this.generatedLoginUsername = generatedLoginUsername;
}
public void setGeneratedLoginPassword(@Nullable String generatedLoginPassword) {
if (this.generatedLoginPassword != null) {
throw new IllegalStateException("Changing generatedLoginPassword not permitted.");
}
this.generatedLoginPassword = generatedLoginPassword;
}
public void setGeneratedPrivateKey(@Nullable String generatedPrivateKey) {
if (this.generatedPrivateKey != null) {
throw new IllegalStateException("Changing generatedPrivateKey not permitted.");
}
this.generatedPrivateKey = generatedPrivateKey;
}
public String loginName() {
if (generatedLoginUsername != null) {
return generatedLoginUsername;
}
if (image == null) {
throw new UnknownLoginNameException(
"Login name is unknown as image is not longer known.");
}
return image.loginName();
}
public Optional<String> loginPassword() {
if (generatedLoginPassword != null) {
return Optional.of(generatedLoginPassword);
}
if (image == null) {
return Optional.empty();
} else {
return image.getLoginPasswordOverride();
}
}
public List<Instance> instances() {
if (instances == null) {
return Collections.emptyList();
}
return instances;
}
public OperatingSystem operatingSystem() {
if (image == null) {
throw new IllegalStateException("Image is not longer known.");
}
return image.operatingSystem();
}
public void unbind() {
unbindProviderIds();
unbindRemoteId();
removeIpAddresses();
setRemoteState(RemoteState.INPROGRESS);
generatedLoginUsername = null;
generatedLoginPassword = null;
generatedPrivateKey = null;
}
}
| |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.indicator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.hisp.dhis.DhisSpringTest;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.common.IdentifiableObjectStore;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
/**
* @author Lars Helge Overland
* @version $Id: IndicatorStoreTest.java 3286 2007-05-07 18:05:21Z larshelg $
*/
class IndicatorStoreTest extends DhisSpringTest
{
@Autowired
private IndicatorStore indicatorStore;
@Autowired
private IdentifiableObjectManager idObjectManager;
@Autowired
@Qualifier( "org.hisp.dhis.indicator.IndicatorTypeStore" )
private IdentifiableObjectStore<IndicatorType> indicatorTypeStore;
// -------------------------------------------------------------------------
// Support methods
// -------------------------------------------------------------------------
private void assertEq( char uniqueCharacter, Indicator indicator )
{
assertEquals( "Indicator" + uniqueCharacter, indicator.getName() );
assertEquals( "IndicatorShort" + uniqueCharacter, indicator.getShortName() );
assertEquals( "IndicatorCode" + uniqueCharacter, indicator.getCode() );
assertEquals( "IndicatorDescription" + uniqueCharacter, indicator.getDescription() );
}
// -------------------------------------------------------------------------
// IndicatorType
// -------------------------------------------------------------------------
@Test
void testAddIndicatorType()
{
IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
IndicatorType typeB = new IndicatorType( "IndicatorTypeB", 1, false );
indicatorTypeStore.save( typeA );
long idA = typeA.getId();
indicatorTypeStore.save( typeB );
long idB = typeB.getId();
typeA = indicatorTypeStore.get( idA );
assertNotNull( typeA );
assertEquals( idA, typeA.getId() );
typeB = indicatorTypeStore.get( idB );
assertNotNull( typeB );
assertEquals( idB, typeB.getId() );
}
@Test
void testUpdateIndicatorType()
{
IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
indicatorTypeStore.save( typeA );
long idA = typeA.getId();
typeA = indicatorTypeStore.get( idA );
assertEquals( typeA.getName(), "IndicatorTypeA" );
typeA.setName( "IndicatorTypeB" );
indicatorTypeStore.update( typeA );
typeA = indicatorTypeStore.get( idA );
assertNotNull( typeA );
assertEquals( typeA.getName(), "IndicatorTypeB" );
}
@Test
void testGetAndDeleteIndicatorType()
{
IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
IndicatorType typeB = new IndicatorType( "IndicatorTypeB", 1, false );
indicatorTypeStore.save( typeA );
long idA = typeA.getId();
indicatorTypeStore.save( typeB );
long idB = typeB.getId();
assertNotNull( indicatorTypeStore.get( idA ) );
assertNotNull( indicatorTypeStore.get( idB ) );
indicatorTypeStore.delete( typeA );
assertNull( indicatorTypeStore.get( idA ) );
assertNotNull( indicatorTypeStore.get( idB ) );
indicatorTypeStore.delete( typeB );
assertNull( indicatorTypeStore.get( idA ) );
assertNull( indicatorTypeStore.get( idB ) );
}
@Test
void testGetAllIndicatorTypes()
{
IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
IndicatorType typeB = new IndicatorType( "IndicatorTypeB", 1, false );
indicatorTypeStore.save( typeA );
indicatorTypeStore.save( typeB );
List<IndicatorType> types = indicatorTypeStore.getAll();
assertEquals( types.size(), 2 );
assertTrue( types.contains( typeA ) );
assertTrue( types.contains( typeB ) );
}
@Test
void testGetIndicatorTypeByName()
{
IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
IndicatorType typeB = new IndicatorType( "IndicatorTypeB", 1, false );
indicatorTypeStore.save( typeA );
long idA = typeA.getId();
indicatorTypeStore.save( typeB );
long idB = typeB.getId();
assertNotNull( indicatorTypeStore.get( idA ) );
assertNotNull( indicatorTypeStore.get( idB ) );
typeA = indicatorTypeStore.getByName( "IndicatorTypeA" );
assertNotNull( typeA );
assertEquals( typeA.getId(), idA );
IndicatorType typeC = indicatorTypeStore.getByName( "IndicatorTypeC" );
assertNull( typeC );
}
// -------------------------------------------------------------------------
// Indicator
// -------------------------------------------------------------------------
@Test
void testAddIndicator()
{
IndicatorType type = new IndicatorType( "IndicatorType", 100, false );
indicatorTypeStore.save( type );
Indicator indicatorA = createIndicator( 'A', type );
Indicator indicatorB = createIndicator( 'B', type );
indicatorStore.save( indicatorA );
long idA = indicatorA.getId();
indicatorStore.save( indicatorB );
long idB = indicatorB.getId();
indicatorA = indicatorStore.get( idA );
assertNotNull( indicatorA );
assertEq( 'A', indicatorA );
indicatorB = indicatorStore.get( idB );
assertNotNull( indicatorB );
assertEq( 'B', indicatorB );
}
@Test
void testUpdateIndicator()
{
IndicatorType type = new IndicatorType( "IndicatorType", 100, false );
indicatorTypeStore.save( type );
Indicator indicatorA = createIndicator( 'A', type );
indicatorStore.save( indicatorA );
long idA = indicatorA.getId();
indicatorA = indicatorStore.get( idA );
assertEq( 'A', indicatorA );
indicatorA.setName( "IndicatorB" );
indicatorStore.update( indicatorA );
indicatorA = indicatorStore.get( idA );
assertNotNull( indicatorA );
assertEquals( indicatorA.getName(), "IndicatorB" );
}
@Test
void testGetAndDeleteIndicator()
{
IndicatorType type = new IndicatorType( "IndicatorType", 100, false );
indicatorTypeStore.save( type );
Indicator indicatorA = createIndicator( 'A', type );
Indicator indicatorB = createIndicator( 'B', type );
Indicator indicatorC = createIndicator( 'C', type );
indicatorStore.save( indicatorA );
long idA = indicatorA.getId();
indicatorStore.save( indicatorB );
long idB = indicatorB.getId();
indicatorStore.save( indicatorC );
long idC = indicatorC.getId();
assertNotNull( indicatorStore.get( idA ) );
assertNotNull( indicatorStore.get( idB ) );
assertNotNull( indicatorStore.get( idC ) );
indicatorStore.delete( indicatorA );
indicatorStore.delete( indicatorC );
assertNull( indicatorStore.get( idA ) );
assertNotNull( indicatorStore.get( idB ) );
assertNull( indicatorStore.get( idC ) );
}
@Test
void testGetAllIndicators()
{
IndicatorType type = new IndicatorType( "IndicatorType", 100, false );
indicatorTypeStore.save( type );
Indicator indicatorA = createIndicator( 'A', type );
Indicator indicatorB = createIndicator( 'B', type );
indicatorStore.save( indicatorA );
indicatorStore.save( indicatorB );
List<Indicator> indicators = indicatorStore.getAll();
assertEquals( indicators.size(), 2 );
assertTrue( indicators.contains( indicatorA ) );
assertTrue( indicators.contains( indicatorB ) );
}
@Test
void testGetIndicatorByName()
{
IndicatorType type = new IndicatorType( "IndicatorType", 100, false );
indicatorTypeStore.save( type );
Indicator indicatorA = createIndicator( 'A', type );
Indicator indicatorB = createIndicator( 'B', type );
indicatorStore.save( indicatorA );
long idA = indicatorA.getId();
indicatorStore.save( indicatorB );
long idB = indicatorB.getId();
assertNotNull( indicatorStore.get( idA ) );
assertNotNull( indicatorStore.get( idB ) );
indicatorA = indicatorStore.getByName( "IndicatorA" );
assertNotNull( indicatorA );
assertEq( 'A', indicatorA );
Indicator indicatorC = indicatorStore.getByName( "IndicatorC" );
assertNull( indicatorC );
}
@Test
void testGetIndicatorsWithoutGroups()
{
IndicatorType type = new IndicatorType( "IndicatorType", 100, false );
indicatorTypeStore.save( type );
Indicator indicatorA = createIndicator( 'A', type );
Indicator indicatorB = createIndicator( 'B', type );
Indicator indicatorC = createIndicator( 'C', type );
indicatorStore.save( indicatorA );
indicatorStore.save( indicatorB );
indicatorStore.save( indicatorC );
IndicatorGroup igA = createIndicatorGroup( 'A' );
igA.addIndicator( indicatorA );
igA.addIndicator( indicatorB );
idObjectManager.save( igA );
List<Indicator> indicators = indicatorStore.getIndicatorsWithoutGroups();
assertEquals( 1, indicators.size() );
assertTrue( indicators.contains( indicatorC ) );
}
}
| |
/*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.process.workitem.email;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.mail.AuthenticationFailedException;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.drools.core.process.instance.impl.DefaultWorkItemManager;
import org.drools.core.process.instance.impl.WorkItemImpl;
import org.jbpm.test.util.AbstractBaseTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.runtime.process.WorkItemManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.AuthenticationHandler;
import org.subethamail.smtp.AuthenticationHandlerFactory;
import org.subethamail.smtp.auth.LoginAuthenticationHandlerFactory;
import org.subethamail.smtp.auth.LoginFailedException;
import org.subethamail.smtp.auth.MultipleAuthenticationHandlerFactory;
import org.subethamail.smtp.auth.PlainAuthenticationHandlerFactory;
import org.subethamail.smtp.auth.UsernamePasswordValidator;
import org.subethamail.wiser.Wiser;
import org.subethamail.wiser.WiserMessage;
public class SendHtmlTest extends AbstractBaseTest {
private static final Logger logger = LoggerFactory.getLogger(SendHtmlTest.class);
private Wiser wiser;
private String emailHost;
private String emailPort;
private static String authUsername = "cpark";
private static String authPassword = "yourbehindwhat?";
private Random random = new Random();
private int uniqueTestNum = -1;
@Before
public void setUp() throws Exception {
uniqueTestNum = random.nextInt(Integer.MAX_VALUE);
emailHost = "localhost";
int emailPortInt;
do {
emailPortInt = random.nextInt((2*Short.MAX_VALUE-1));
} while( emailPortInt < 4096 );
emailPort = Integer.toString(emailPortInt);
wiser = new Wiser(Integer.parseInt(emailPort));
wiser.start();
}
@After
public void tearDown() throws Exception {
if( wiser != null ) {
wiser.getMessages().clear();
wiser.stop();
wiser = null;
}
}
@SuppressWarnings("unused")
private class ExtendedConnection extends Connection {
private String extraField;
}
@Test
public void testConnectionEquals() {
Connection connA = new Connection();
Connection connB = new Connection();
// null test
assertTrue( !connA.equals(null));
// different class test
assertTrue( !connA.equals("og"));
// extended class test
ExtendedConnection connExt = new ExtendedConnection();
assertTrue( !connA.equals(connExt) );
// null fields test
assertTrue( connA.equals(connB));
// all null vs filled field test
connA.setHost("Human");
connA.setPort("Skin");
connA.setUserName("Viral");
connA.setPassword("Protein Gate");
assertTrue( ! connA.equals(connB));
// filled field test
connB.setHost(connA.getHost());
connB.setPort(new String(connA.getPort()));
connB.setUserName(connA.getUserName());
connB.setPassword(connA.getPassword());
assertTrue( connA.equals(connB));
// some null vs filled field test
connA.setPassword(null);
connB.setPassword(null);
assertTrue( connA.equals(connB));
// boolean
connA.setStartTls(true);
assertTrue( !connA.equals(connB));
connB.setStartTls(true);
assertTrue( connA.equals(connB));
connB.setStartTls(false);
assertTrue( !connA.equals(connB));
}
@Test
public void verifyWiserServerWorks() throws Exception {
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1].getMethodName();
String toAddress = "boyd@crowdergang.org";
String fromAddress = "rgivens@kty.us.gov";
// Setup email
WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress, testMethodName);
Connection connection = new Connection(emailHost, emailPort);
sendAndCheckThatMessagesAreSent(workItem, connection);
}
@Test
public void sendHtmlWithAuthentication() throws Exception {
// Add authentication to Wiser SMTP server
wiser.getServer().setAuthenticationHandlerFactory(new TestAuthHandlerFactory());
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1].getMethodName();
String toAddress = "rgivens@kty.us.gov";
String fromAddress = "whawkins@kty.us.gov";
// Setup email
WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress, testMethodName);
Connection connection = new Connection(emailHost, emailPort, authUsername, authPassword);
sendAndCheckThatMessagesAreSent(workItem, connection);
}
@Test
public void sendHtmlWithAuthenticationAndAttachments() throws Exception {
// Add authentication to Wiser SMTP server
wiser.getServer().setAuthenticationHandlerFactory(new TestAuthHandlerFactory());
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1].getMethodName();
String toAddress = "rgivens@kty.us.gov";
String fromAddress = "whawkins@kty.us.gov";
// Setup email
WorkItemImpl workItem = createEmailWorkItemWithAttachment(toAddress, fromAddress, testMethodName);
Connection connection = new Connection(emailHost, emailPort, authUsername, authPassword);
// send email
Email email = EmailWorkItemHandler.createEmail(workItem, connection);
SendHtml.sendHtml(email, connection);
List<WiserMessage> messages = wiser.getMessages();
assertEquals(1, messages.size());
MimeMessage message = messages.get(0).getMimeMessage();
assertEquals(workItem.getParameter("Subject"), message.getSubject());
assertTrue(Arrays.equals(InternetAddress.parse((String) workItem.getParameter("To")),
message.getRecipients(RecipientType.TO)));
assertTrue(message.getContent() instanceof Multipart);
Multipart multipart = (Multipart) message.getContent();
assertEquals(2, multipart.getCount());
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
continue; // dealing with attachments only
}
assertEquals("email.gif", bodyPart.getFileName());
}
}
@Test
public void sendHtmlWithBadAuthentication() throws Exception {
// Add authentication to Wiser SMTP server
wiser.getServer().setAuthenticationHandlerFactory(new TestAuthHandlerFactory());
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1].getMethodName();
String toAddress = "mags@bennetstore.com";
String fromAddress = "rgivens@kty.us.gov";
checkBadAuthentication(toAddress, fromAddress, testMethodName, authUsername, "bad password");
checkBadAuthentication(toAddress, fromAddress, testMethodName, "badUserName", authPassword);
}
@Test
public void useEmailWorkItemHandlerWithAuthentication() throws Exception {
// Add authentication to Wiser SMTP server
wiser.getServer().setAuthenticationHandlerFactory(new TestAuthHandlerFactory());
// Input
String testMethodName = Thread.currentThread().getStackTrace()[1].getMethodName();
String toAddress = "rgivens@yahoo.com";
String fromAddress = "rgivens@kty.us.gov";
EmailWorkItemHandler handler = new EmailWorkItemHandler();
handler.setConnection( emailHost, emailPort, authUsername, authPassword );
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter( "To", toAddress );
workItem.setParameter( "From", fromAddress );
workItem.setParameter( "Reply-To", fromAddress );
workItem.setParameter( "Subject", "Test mail for " + testMethodName );
workItem.setParameter( "Body", "Don't forget to check on Boyd later today." );
WorkItemManager manager = new DefaultWorkItemManager(null);
handler.executeWorkItem( workItem, manager );
List<WiserMessage> messages = wiser.getMessages();
assertEquals(1, messages.size());
for (WiserMessage wiserMessage : messages ) {
MimeMessage message = wiserMessage.getMimeMessage();
assertEquals(workItem.getParameter("Subject"), message.getSubject());
assertTrue(Arrays.equals(InternetAddress.parse(toAddress),
message.getRecipients(RecipientType.TO)));
}
}
/**
* Helper methods
*/
private void sendAndCheckThatMessagesAreSent(WorkItemImpl workItem, Connection connection) throws Exception {
// send email
Email email = EmailWorkItemHandler.createEmail(workItem, connection);
SendHtml.sendHtml(email, connection);
List<WiserMessage> messages = wiser.getMessages();
assertEquals(1, messages.size());
for (WiserMessage wiserMessage : messages ) {
MimeMessage message = wiserMessage.getMimeMessage();
assertEquals(workItem.getParameter("Subject"), message.getSubject());
assertTrue(Arrays.equals(InternetAddress.parse((String) workItem.getParameter("To")),
message.getRecipients(RecipientType.TO)));
}
}
private void checkBadAuthentication(String toAddress, String fromAddress, String testMethodName,
String username, String password) {
// Setup email
WorkItemImpl workItem = createEmailWorkItem(toAddress, fromAddress, testMethodName);
Connection connection = new Connection(emailHost, emailPort, username, password);
// send email
Email email = EmailWorkItemHandler.createEmail(workItem, connection);
try {
SendHtml.sendHtml(email, connection);
} catch (Throwable t) {
assertTrue( "Unexpected exception of type " + t.getClass().getSimpleName()
+ ", not " + t.getClass().getSimpleName(), (t instanceof RuntimeException));
assertNotNull("Expected RuntimeException to have a cause.", t.getCause());
Throwable cause = t.getCause();
assertNotNull("Expected cause to have a cause.", cause.getCause());
cause = cause.getCause();
assertTrue( "Unexpected exception of type " + cause.getClass().getSimpleName()
+ ", not " + cause.getClass().getSimpleName(), (cause instanceof AuthenticationFailedException));
}
}
private WorkItemImpl createEmailWorkItem(String toAddress, String fromAddress, String testMethodName) {
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter( "To", toAddress );
workItem.setParameter( "From", fromAddress );
workItem.setParameter( "Reply-To", fromAddress );
String subject = this.getClass().getSimpleName() + " test message [" + uniqueTestNum + "]";
String body = "\nThis is the test message generated by the " + testMethodName + " test (" + uniqueTestNum + ").\n";
workItem.setParameter( "Subject", subject );
workItem.setParameter( "Body", body );
return workItem;
}
private WorkItemImpl createEmailWorkItemWithAttachment(String toAddress, String fromAddress, String testMethodName) {
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter( "To", toAddress );
workItem.setParameter( "From", fromAddress );
workItem.setParameter( "Reply-To", fromAddress );
String subject = this.getClass().getSimpleName() + " test message [" + uniqueTestNum + "]";
String body = "\nThis is the test message generated by the " + testMethodName + " test (" + uniqueTestNum + ").\n";
workItem.setParameter( "Subject", subject );
workItem.setParameter( "Body", body );
workItem.setParameter("Attachments", "classpath:/icons/email.gif");
return workItem;
}
private static class TestAuthHandlerFactory implements AuthenticationHandlerFactory {
MultipleAuthenticationHandlerFactory authHandleFactory = new MultipleAuthenticationHandlerFactory();
public TestAuthHandlerFactory() {
UsernamePasswordValidator validator = new UsernamePasswordValidator() {
public void login(String username, String password) throws LoginFailedException {
if (!authUsername.equals(username) || !authPassword.equals(password)) {
logger.debug("Tried to login with user/password [{}/{}]", username, password);
throw new LoginFailedException("Incorrect password for user " + authUsername);
}
}
};
authHandleFactory.addFactory(new LoginAuthenticationHandlerFactory(validator));
authHandleFactory.addFactory(new PlainAuthenticationHandlerFactory(validator));
}
public AuthenticationHandler create() {
return authHandleFactory.create();
}
public List<String> getAuthenticationMechanisms() {
return authHandleFactory.getAuthenticationMechanisms();
}
}
}
| |
/*
* Copyright 2000-2016 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.xdebugger;
import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.util.concurrency.FutureResult;
import com.intellij.util.ui.TextTransferable;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.breakpoints.*;
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator;
import com.intellij.xdebugger.frame.*;
import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.intellij.xdebugger.impl.breakpoints.XBreakpointUtil;
import com.intellij.xdebugger.impl.breakpoints.XExpressionImpl;
import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointImpl;
import com.intellij.xdebugger.impl.frame.XStackFrameContainerEx;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
public class XDebuggerTestUtil {
private static final int TIMEOUT = 25000;
private XDebuggerTestUtil() {
}
public static <B extends XBreakpoint<?>> void assertBreakpointValidity(Project project,
VirtualFile file,
int line,
boolean validity,
String errorMessage,
Class<? extends XBreakpointType<B, ?>> breakpointType) {
XLineBreakpointType type = (XLineBreakpointType)XDebuggerUtil.getInstance().findBreakpointType(breakpointType);
XBreakpointManager manager = XDebuggerManager.getInstance(project).getBreakpointManager();
XLineBreakpointImpl breakpoint = (XLineBreakpointImpl)manager.findBreakpointAtLine(type, file, line);
assertNotNull(breakpoint);
assertEquals(validity ? AllIcons.Debugger.Db_verified_breakpoint : AllIcons.Debugger.Db_invalid_breakpoint, breakpoint.getIcon());
assertEquals(errorMessage, breakpoint.getErrorMessage());
}
public static void toggleBreakpoint(Project project, VirtualFile file, int line) {
XDebuggerUtil.getInstance().toggleLineBreakpoint(project, file, line);
}
public static <P extends XBreakpointProperties> XBreakpoint<P> insertBreakpoint(final Project project,
final P properties,
final Class<? extends XBreakpointType<XBreakpoint<P>, P>> typeClass) {
return new WriteAction<XBreakpoint<P>>() {
protected void run(@NotNull final Result<XBreakpoint<P>> result) {
result.setResult(XDebuggerManager.getInstance(project).getBreakpointManager().addBreakpoint(
XBreakpointType.EXTENSION_POINT_NAME.findExtension(typeClass), properties));
}
}.execute().getResultObject();
}
public static void removeBreakpoint(final Project project, final XBreakpoint<?> breakpoint) {
new WriteAction() {
protected void run(@NotNull final Result result) {
XDebuggerManager.getInstance(project).getBreakpointManager().removeBreakpoint(breakpoint);
}
}.execute();
}
public static void assertPosition(XSourcePosition pos, VirtualFile file, int line) throws IOException {
assertNotNull("No current position", pos);
assertEquals(new File(file.getPath()).getCanonicalPath(), new File(pos.getFile().getPath()).getCanonicalPath());
if (line != -1) assertEquals(line, pos.getLine());
}
public static void assertCurrentPosition(XDebugSession session, VirtualFile file, int line) throws IOException {
assertPosition(session.getCurrentPosition(), file, line);
}
public static XExecutionStack getActiveThread(@NotNull XDebugSession session) {
return session.getSuspendContext().getActiveExecutionStack();
}
public static List<XExecutionStack> collectThreads(@NotNull XDebugSession session) throws InterruptedException {
return collectThreadsWithErrors(session).first;
}
public static Pair<List<XExecutionStack>, String> collectThreadsWithErrors(@NotNull XDebugSession session) throws InterruptedException {
XTestExecutionStackContainer container = new XTestExecutionStackContainer();
session.getSuspendContext().computeExecutionStacks(container);
return container.waitFor(TIMEOUT);
}
public static List<XStackFrame> collectFrames(@NotNull XDebugSession session) throws InterruptedException {
return collectFrames(null, session);
}
public static List<XStackFrame> collectFrames(@Nullable XExecutionStack thread, @NotNull XDebugSession session)
throws InterruptedException {
return collectFrames(thread == null ? getActiveThread(session) : thread);
}
public static String getFramePresentation(XStackFrame frame) {
TextTransferable.ColoredStringBuilder builder = new TextTransferable.ColoredStringBuilder();
frame.customizePresentation(builder);
return builder.getBuilder().toString();
}
public static List<XStackFrame> collectFrames(@NotNull XExecutionStack thread) throws InterruptedException {
return collectFrames(thread, TIMEOUT * 2);
}
public static List<XStackFrame> collectFrames(XExecutionStack thread, long timeout) throws InterruptedException {
return collectFramesWithError(thread, timeout).first;
}
public static Pair<List<XStackFrame>, String> collectFramesWithError(XExecutionStack thread, long timeout) throws InterruptedException {
XTestStackFrameContainer container = new XTestStackFrameContainer();
thread.computeStackFrames(0, container);
return container.waitFor(timeout);
}
public static Pair<List<XStackFrame>, XStackFrame> collectFramesWithSelected(@NotNull XDebugSession session, long timeout) throws InterruptedException {
return collectFramesWithSelected(getActiveThread(session), timeout);
}
public static Pair<List<XStackFrame>, XStackFrame> collectFramesWithSelected(XExecutionStack thread, long timeout) throws InterruptedException {
XTestStackFrameContainer container = new XTestStackFrameContainer();
thread.computeStackFrames(0, container);
List<XStackFrame> all = container.waitFor(timeout).first;
return Pair.create(all, container.frameToSelect);
}
public static List<XValue> collectVariables(XStackFrame frame) throws InterruptedException {
XTestCompositeNode container = new XTestCompositeNode();
frame.computeChildren(container);
return container.waitFor(TIMEOUT).first;
}
public static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression) {
return evaluate(session, expression, TIMEOUT);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression) {
return evaluate(session, XExpressionImpl.fromText(expression), TIMEOUT);
}
public static Pair<XValue, String> evaluate(XDebugSession session, String expression, long timeout) {
return evaluate(session, XExpressionImpl.fromText(expression), timeout);
}
private static Pair<XValue, String> evaluate(XDebugSession session, XExpression expression, long timeout) {
XStackFrame frame = session.getCurrentStackFrame();
assertNotNull(frame);
XDebuggerEvaluator evaluator = frame.getEvaluator();
assertNotNull(evaluator);
XTestEvaluationCallback callback = new XTestEvaluationCallback();
evaluator.evaluate(expression, callback, session.getCurrentPosition());
return callback.waitFor(timeout);
}
public static void waitForSwing() throws InterruptedException, InvocationTargetException {
final com.intellij.util.concurrency.Semaphore s = new com.intellij.util.concurrency.Semaphore();
s.down();
ApplicationManager.getApplication().invokeLater(() -> s.up());
s.waitForUnsafe();
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
public void run() {
}
});
}
@NotNull
public static XValue findVar(Collection<XValue> vars, String name) {
StringBuilder names = new StringBuilder();
for (XValue each : vars) {
if (each instanceof XNamedValue) {
String eachName = ((XNamedValue)each).getName();
if (eachName.equals(name)) return each;
if (names.length() > 0) names.append(", ");
names.append(eachName);
}
}
throw new AssertionError("var '" + name + "' not found among " + names);
}
public static XTestValueNode computePresentation(@NotNull XValue value) throws InterruptedException {
return computePresentation(value, TIMEOUT);
}
public static XTestValueNode computePresentation(XValue value, long timeout) throws InterruptedException {
XTestValueNode node = new XTestValueNode();
if (value instanceof XNamedValue) {
node.myName = ((XNamedValue)value).getName();
}
value.computePresentation(node, XValuePlace.TREE);
node.waitFor(timeout);
return node;
}
public static void assertVariable(XValue var,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren) throws InterruptedException {
XTestValueNode node = computePresentation(var);
if (name != null) assertEquals(name, node.myName);
if (type != null) assertEquals(type, node.myType);
if (value != null) assertEquals(value, node.myValue);
if (hasChildren != null) assertEquals(hasChildren, node.myHasChildren);
}
public static void assertVariableValue(XValue var, @Nullable String name, @Nullable String value) throws InterruptedException {
assertVariable(var, name, null, value, null);
}
public static void assertVariableValue(Collection<XValue> vars, @Nullable String name, @Nullable String value)
throws InterruptedException {
assertVariableValue(findVar(vars, name), name, value);
}
public static void assertVariableValueMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable @Language("RegExp") String valuePattern) throws InterruptedException {
assertVariableValueMatches(findVar(vars, name), name, valuePattern);
}
public static void assertVariableValueMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern) throws InterruptedException {
assertVariableValueMatches(findVar(vars, name), name, type, valuePattern);
}
public static void assertVariableValueMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern,
@Nullable Boolean hasChildren) throws InterruptedException {
assertVariableValueMatches(findVar(vars, name), name, type, valuePattern, hasChildren);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable @Language("RegExp") String valuePattern) throws InterruptedException {
assertVariableValueMatches(var, name, null, valuePattern);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern) throws InterruptedException {
assertVariableValueMatches(var, name, type, valuePattern, null);
}
public static void assertVariableValueMatches(@NotNull XValue var,
@Nullable String name,
@Nullable String type,
@Nullable @Language("RegExp") String valuePattern,
@Nullable Boolean hasChildren) throws InterruptedException {
XTestValueNode node = computePresentation(var);
if (name != null) assertEquals(name, node.myName);
if (type != null) assertEquals(type, node.myType);
if (valuePattern != null) {
assertTrue("Expected value: " + valuePattern + " Actual value: " + node.myValue, node.myValue.matches(valuePattern));
}
if (hasChildren != null) assertEquals(hasChildren, node.myHasChildren);
}
public static void assertVariableTypeMatches(@NotNull Collection<XValue> vars,
@Nullable String name,
@Nullable @Language("RegExp") String typePattern) throws InterruptedException {
assertVariableTypeMatches(findVar(vars, name), name, typePattern);
}
public static void assertVariableTypeMatches(@NotNull XValue var,
@Nullable String name,
@Nullable @Language("RegExp") String typePattern) throws InterruptedException {
XTestValueNode node = computePresentation(var);
if (name != null) {
assertEquals(name, node.myName);
}
if (typePattern != null) {
assertTrue("Expected type: " + typePattern + " Actual type: " + node.myType, node.myType.matches(typePattern));
}
}
public static void assertVariableFullValue(@NotNull XValue var,
@Nullable String value) throws Exception {
XTestValueNode node = computePresentation(var);
if (value == null) {
assertNull("full value evaluator should be null", node.myFullValueEvaluator);
}
else {
final FutureResult<String> result = new FutureResult<>();
node.myFullValueEvaluator.startEvaluation(new XFullValueEvaluator.XFullValueEvaluationCallback() {
@Override
public void evaluated(@NotNull String fullValue) {
result.set(fullValue);
}
@Override
public void evaluated(@NotNull String fullValue, @Nullable Font font) {
result.set(fullValue);
}
@Override
public void errorOccurred(@NotNull String errorMessage) {
result.set(errorMessage);
}
@Override
public boolean isObsolete() {
return false;
}
});
assertEquals(value, result.get(TIMEOUT, TimeUnit.MILLISECONDS));
}
}
public static void assertVariableFullValue(Collection<XValue> vars, @Nullable String name, @Nullable String value)
throws Exception {
assertVariableFullValue(findVar(vars, name), value);
}
public static void assertVariables(List<XValue> vars, String... names) throws InterruptedException {
List<String> expectedNames = new ArrayList<>(Arrays.asList(names));
List<String> actualNames = new ArrayList<>();
for (XValue each : vars) {
actualNames.add(computePresentation(each).myName);
}
Collections.sort(actualNames);
Collections.sort(expectedNames);
UsefulTestCase.assertOrderedEquals(actualNames, expectedNames);
}
public static void assertVariablesContain(List<XValue> vars, String... names) throws InterruptedException {
List<String> expectedNames = new ArrayList<>(Arrays.asList(names));
List<String> actualNames = new ArrayList<>();
for (XValue each : vars) {
actualNames.add(computePresentation(each).myName);
}
expectedNames.removeAll(actualNames);
assertTrue("Missing variables:" + StringUtil.join(expectedNames, ", ")
+ "\nAll Variables: " + StringUtil.join(actualNames, ", "),
expectedNames.isEmpty()
);
}
public static void assertSourcePosition(final XValue value, VirtualFile file, int offset) {
final XTestNavigatable n = new XTestNavigatable();
ApplicationManager.getApplication().runReadAction(() -> value.computeSourcePosition(n));
assertNotNull(n.myPosition);
assertEquals(file, n.myPosition.getFile());
assertEquals(offset, n.myPosition.getOffset());
}
public static void assertSourcePosition(final XStackFrame frame, VirtualFile file, int line) {
XSourcePosition position = frame.getSourcePosition();
assertNotNull(position);
assertEquals(file, position.getFile());
assertEquals(line, position.getLine());
}
public static boolean waitFor(Semaphore semaphore, long timeoutInMillis) {
long end = System.currentTimeMillis() + timeoutInMillis;
long remaining = timeoutInMillis;
do {
try {
return semaphore.tryAcquire(remaining, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ignored) {
remaining = end - System.currentTimeMillis();
}
} while (remaining > 0);
return false;
}
public static void assertVariable(Collection<XValue> vars,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren) throws InterruptedException {
assertVariable(findVar(vars, name), name, type, value, hasChildren);
}
@NotNull
public static String getConsoleText(final @NotNull ConsoleViewImpl consoleView) {
new WriteAction() {
protected void run(@NotNull Result result) throws Throwable {
consoleView.flushDeferredText();
}
}.execute();
return consoleView.getEditor().getDocument().getText();
}
public static <T extends XBreakpointType> XBreakpoint addBreakpoint(@NotNull final Project project,
@NotNull final Class<T> exceptionType,
@NotNull final XBreakpointProperties properties) {
final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
XBreakpointType[] types = XBreakpointUtil.getBreakpointTypes();
final Ref<XBreakpoint> breakpoint = Ref.create(null);
for (XBreakpointType type : types) {
if (exceptionType.isInstance(type)) {
final T breakpointType = exceptionType.cast(type);
new WriteAction() {
@Override
protected void run(@NotNull Result result) throws Throwable {
breakpoint.set(breakpointManager.addBreakpoint(breakpointType, properties));
}
}.execute();
break;
}
}
return breakpoint.get();
}
public static void removeAllBreakpoints(@NotNull final Project project) {
final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
XBreakpoint<?>[] breakpoints = getBreakpoints(breakpointManager);
for (final XBreakpoint b : breakpoints) {
new WriteAction() {
@Override
protected void run(@NotNull Result result) throws Throwable {
breakpointManager.removeBreakpoint(b);
}
}.execute();
}
}
public static XBreakpoint<?>[] getBreakpoints(final XBreakpointManager breakpointManager) {
return ApplicationManager.getApplication().runReadAction((Computable<XBreakpoint<?>[]>)breakpointManager::getAllBreakpoints);
}
public static <B extends XBreakpoint<?>>
void setDefaultBreakpointEnabled(@NotNull final Project project, Class<? extends XBreakpointType<B, ?>> bpTypeClass, boolean enabled) {
final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
XBreakpointType<B, ?> bpType = XDebuggerUtil.getInstance().findBreakpointType(bpTypeClass);
XBreakpoint<?> bp = breakpointManager.getDefaultBreakpoint(bpType);
if (bp != null) {
bp.setEnabled(enabled);
}
}
public static void setBreakpointCondition(Project project, int line, final String condition) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
for (XBreakpoint breakpoint : getBreakpoints(breakpointManager)) {
if (breakpoint instanceof XLineBreakpoint) {
final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint;
if (lineBreakpoint.getLine() == line) {
new WriteAction() {
@Override
protected void run(@NotNull Result result) throws Throwable {
lineBreakpoint.setCondition(condition);
}
}.execute();
}
}
}
}
public static void setBreakpointLogExpression(Project project, int line, final String logExpression) {
XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
for (XBreakpoint breakpoint : getBreakpoints(breakpointManager)) {
if (breakpoint instanceof XLineBreakpoint) {
final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint;
if (lineBreakpoint.getLine() == line) {
new WriteAction() {
@Override
protected void run(@NotNull Result result) throws Throwable {
lineBreakpoint.setLogExpression(logExpression);
lineBreakpoint.setLogMessage(true);
}
}.execute();
}
}
}
}
public static void disposeDebugSession(final XDebugSession debugSession) {
new WriteAction() {
protected void run(@NotNull Result result) throws Throwable {
XDebugSessionImpl session = (XDebugSessionImpl)debugSession;
Disposer.dispose(session.getSessionTab());
Disposer.dispose(session.getConsoleView());
}
}.execute();
}
public static void assertVariable(Pair<XValue, String> varAndErrorMessage,
@Nullable String name,
@Nullable String type,
@Nullable String value,
@Nullable Boolean hasChildren) throws InterruptedException {
assertNull(varAndErrorMessage.second);
assertVariable(varAndErrorMessage.first, name, type, value, hasChildren);
}
public static String assertVariableExpression(XValue desc, String expectedExpression) {
String expression = desc.getEvaluationExpression();
assertEquals(expectedExpression, expression);
return expression;
}
public static class XTestExecutionStackContainer extends XTestContainer<XExecutionStack> implements XSuspendContext.XExecutionStackContainer {
@Override
public void errorOccurred(@NotNull String errorMessage) {
setErrorMessage(errorMessage);
}
@Override
public void addExecutionStack(@NotNull List<? extends XExecutionStack> executionStacks, boolean last) {
addChildren(executionStacks, last);
}
}
public static class XTestStackFrameContainer extends XTestContainer<XStackFrame> implements XStackFrameContainerEx {
public volatile XStackFrame frameToSelect;
public void addStackFrames(@NotNull List<? extends XStackFrame> stackFrames, boolean last) {
addChildren(stackFrames, last);
}
@Override
public void addStackFrames(@NotNull List<? extends XStackFrame> stackFrames, @Nullable XStackFrame toSelect, boolean last) {
if (toSelect != null) frameToSelect = toSelect;
addChildren(stackFrames, last);
}
@Override
public void errorOccurred(@NotNull String errorMessage) {
setErrorMessage(errorMessage);
}
}
public static class XTestNavigatable implements XNavigatable {
private XSourcePosition myPosition;
@Override
public void setSourcePosition(@Nullable XSourcePosition sourcePosition) {
myPosition = sourcePosition;
}
public XSourcePosition getPosition() {
return myPosition;
}
}
}
| |
package de.metanome.algorithms.hyfd;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import de.metanome.algorithm_integration.AlgorithmConfigurationException;
import de.metanome.algorithm_integration.AlgorithmExecutionException;
import de.metanome.algorithm_integration.ColumnCombination;
import de.metanome.algorithm_integration.ColumnIdentifier;
import de.metanome.algorithm_integration.algorithm_types.BooleanParameterAlgorithm;
import de.metanome.algorithm_integration.algorithm_types.FunctionalDependencyAlgorithm;
import de.metanome.algorithm_integration.algorithm_types.IntegerParameterAlgorithm;
import de.metanome.algorithm_integration.algorithm_types.RelationalInputParameterAlgorithm;
import de.metanome.algorithm_integration.configuration.ConfigurationRequirement;
import de.metanome.algorithm_integration.configuration.ConfigurationRequirementBoolean;
import de.metanome.algorithm_integration.configuration.ConfigurationRequirementInteger;
import de.metanome.algorithm_integration.configuration.ConfigurationRequirementRelationalInput;
import de.metanome.algorithm_integration.input.InputGenerationException;
import de.metanome.algorithm_integration.input.InputIterationException;
import de.metanome.algorithm_integration.input.RelationalInput;
import de.metanome.algorithm_integration.input.RelationalInputGenerator;
import de.metanome.algorithm_integration.result_receiver.FunctionalDependencyResultReceiver;
import de.metanome.algorithm_integration.results.FunctionalDependency;
import de.metanome.algorithms.hyfd.fdep.FDEP;
import de.metanome.algorithms.hyfd.structures.FDList;
import de.metanome.algorithms.hyfd.structures.FDSet;
import de.metanome.algorithms.hyfd.structures.FDTree;
import de.metanome.algorithms.hyfd.structures.IntegerPair;
import de.metanome.algorithms.hyfd.structures.PLIBuilder;
import de.metanome.algorithms.hyfd.structures.PositionListIndex;
import de.metanome.algorithms.hyfd.utils.Logger;
import de.metanome.algorithms.hyfd.utils.ValueComparator;
import de.uni_potsdam.hpi.utils.CollectionUtils;
import de.uni_potsdam.hpi.utils.FileUtils;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
public class HyFD implements FunctionalDependencyAlgorithm, BooleanParameterAlgorithm, IntegerParameterAlgorithm, RelationalInputParameterAlgorithm {
public enum Identifier {
INPUT_GENERATOR, NULL_EQUALS_NULL, VALIDATE_PARALLEL, ENABLE_MEMORY_GUARDIAN, MAX_DETERMINANT_SIZE, INPUT_ROW_LIMIT
};
private RelationalInputGenerator inputGenerator = null;
private FunctionalDependencyResultReceiver resultReceiver = null;
private ValueComparator valueComparator;
private final MemoryGuardian memoryGuardian = new MemoryGuardian(true);
private boolean validateParallel = true; // The validation is the most costly part in HyFD and it can easily be parallelized
private int maxLhsSize = -1; // The lhss can become numAttributes - 1 large, but usually we are only interested in FDs with lhs < some threshold (otherwise they would not be useful for normalization, key discovery etc.)
private int inputRowLimit = -1; // Maximum number of rows to be read from for analysis; values smaller or equal 0 will cause the algorithm to read all rows
private float efficiencyThreshold = 0.01f;
private String tableName;
private List<String> attributeNames;
private int numAttributes;
@Override
public String getAuthors() {
return "Thorsten Papenbrock";
}
@Override
public String getDescription() {
return "Hybrid Sampling- and Lattice-Traversal-based FD discovery";
}
@Override
public ArrayList<ConfigurationRequirement<?>> getConfigurationRequirements() {
ArrayList<ConfigurationRequirement<?>> configs = new ArrayList<ConfigurationRequirement<?>>(5);
configs.add(new ConfigurationRequirementRelationalInput(HyFD.Identifier.INPUT_GENERATOR.name()));
ConfigurationRequirementBoolean nullEqualsNull = new ConfigurationRequirementBoolean(HyFD.Identifier.NULL_EQUALS_NULL.name());
Boolean[] defaultNullEqualsNull = new Boolean[1];
defaultNullEqualsNull[0] = new Boolean(true);
nullEqualsNull.setDefaultValues(defaultNullEqualsNull);
nullEqualsNull.setRequired(true);
configs.add(nullEqualsNull);
ConfigurationRequirementBoolean validateParallel = new ConfigurationRequirementBoolean(HyFD.Identifier.VALIDATE_PARALLEL.name());
Boolean[] defaultValidateParallel = new Boolean[1];
defaultValidateParallel[0] = new Boolean(this.validateParallel);
validateParallel.setDefaultValues(defaultValidateParallel);
validateParallel.setRequired(true);
configs.add(validateParallel);
ConfigurationRequirementBoolean enableMemoryGuardian = new ConfigurationRequirementBoolean(HyFD.Identifier.ENABLE_MEMORY_GUARDIAN.name());
Boolean[] defaultEnableMemoryGuardian = new Boolean[1];
defaultEnableMemoryGuardian[0] = new Boolean(this.memoryGuardian.isActive());
enableMemoryGuardian.setDefaultValues(defaultEnableMemoryGuardian);
enableMemoryGuardian.setRequired(true);
configs.add(enableMemoryGuardian);
ConfigurationRequirementInteger maxLhsSize = new ConfigurationRequirementInteger(HyFD.Identifier.MAX_DETERMINANT_SIZE.name());
Integer[] defaultMaxLhsSize = new Integer[1];
defaultMaxLhsSize[0] = new Integer(this.maxLhsSize);
maxLhsSize.setDefaultValues(defaultMaxLhsSize);
maxLhsSize.setRequired(false);
configs.add(maxLhsSize);
ConfigurationRequirementInteger inputRowLimit = new ConfigurationRequirementInteger(HyFD.Identifier.INPUT_ROW_LIMIT.name());
Integer[] defaultInputRowLimit = { Integer.valueOf(this.inputRowLimit) };
inputRowLimit.setDefaultValues(defaultInputRowLimit);
inputRowLimit.setRequired(false);
configs.add(inputRowLimit);
return configs;
}
@Override
public void setResultReceiver(FunctionalDependencyResultReceiver resultReceiver) {
this.resultReceiver = resultReceiver;
}
@Override
public void setBooleanConfigurationValue(String identifier, Boolean... values) throws AlgorithmConfigurationException {
if (HyFD.Identifier.NULL_EQUALS_NULL.name().equals(identifier))
this.valueComparator = new ValueComparator(values[0].booleanValue());
else if (HyFD.Identifier.VALIDATE_PARALLEL.name().equals(identifier))
this.validateParallel = values[0].booleanValue();
else if (HyFD.Identifier.ENABLE_MEMORY_GUARDIAN.name().equals(identifier))
this.memoryGuardian.setActive(values[0].booleanValue());
else
this.handleUnknownConfiguration(identifier, CollectionUtils.concat(values, ","));
}
@Override
public void setIntegerConfigurationValue(String identifier, Integer... values) throws AlgorithmConfigurationException {
if (HyFD.Identifier.MAX_DETERMINANT_SIZE.name().equals(identifier))
this.maxLhsSize = values[0].intValue();
else if (HyFD.Identifier.INPUT_ROW_LIMIT.name().equals(identifier))
if (values.length > 0)
this.inputRowLimit = values[0].intValue();
else
this.handleUnknownConfiguration(identifier, CollectionUtils.concat(values, ","));
}
@Override
public void setRelationalInputConfigurationValue(String identifier, RelationalInputGenerator... values) throws AlgorithmConfigurationException {
if (HyFD.Identifier.INPUT_GENERATOR.name().equals(identifier))
this.inputGenerator = values[0];
else
this.handleUnknownConfiguration(identifier, CollectionUtils.concat(values, ","));
}
private void handleUnknownConfiguration(String identifier, String value) throws AlgorithmConfigurationException {
throw new AlgorithmConfigurationException("Unknown configuration: " + identifier + " -> " + value);
}
@Override
public String toString() {
return "HyFD:\r\n\t" +
"inputGenerator: " + ((this.inputGenerator != null) ? this.inputGenerator.toString() : "-") + "\r\n\t" +
"tableName: " + this.tableName + " (" + CollectionUtils.concat(this.attributeNames, ", ") + ")\r\n\t" +
"numAttributes: " + this.numAttributes + "\r\n\t" +
"isNullEqualNull: " + ((this.valueComparator != null) ? String.valueOf(this.valueComparator.isNullEqualNull()) : "-") + ")\r\n\t" +
"maxLhsSize: " + this.maxLhsSize + "\r\n" +
"inputRowLimit: " + this.inputRowLimit + "\r\n" +
"\r\n" +
"Progress log: \r\n" + Logger.getInstance().read();
}
private void initialize(RelationalInput relationalInput) throws AlgorithmExecutionException {
this.tableName = relationalInput.relationName();
this.attributeNames = relationalInput.columnNames();
this.numAttributes = this.attributeNames.size();
if (this.valueComparator == null)
this.valueComparator = new ValueComparator(true);
}
@Override
public void execute() throws AlgorithmExecutionException {
long startTime = System.currentTimeMillis();
if (this.inputGenerator == null)
throw new AlgorithmConfigurationException("No input generator set!");
if (this.resultReceiver == null)
throw new AlgorithmConfigurationException("No result receiver set!");
//this.executeFDEP();
this.executeHyFD();
Logger.getInstance().writeln("Time: " + (System.currentTimeMillis() - startTime) + " ms");
}
private void executeHyFD() throws AlgorithmExecutionException {
// Initialize
Logger.getInstance().writeln("Initializing ...");
RelationalInput relationalInput = this.getInput();
this.initialize(relationalInput);
///////////////////////////////////////////////////////
// Build data structures for sampling and validation //
///////////////////////////////////////////////////////
// Calculate plis
Logger.getInstance().writeln("Reading data and calculating plis ...");
PLIBuilder pliBuilder = new PLIBuilder(this.inputRowLimit);
List<PositionListIndex> plis = pliBuilder.getPLIs(relationalInput, this.numAttributes, this.valueComparator.isNullEqualNull());
this.closeInput(relationalInput);
final int numRecords = pliBuilder.getNumLastRecords();
pliBuilder = null;
if (numRecords == 0) {
ObjectArrayList<ColumnIdentifier> columnIdentifiers = this.buildColumnIdentifiers();
for (int attr = 0; attr < this.numAttributes; attr++)
this.resultReceiver.receiveResult(new FunctionalDependency(new ColumnCombination(), columnIdentifiers.get(attr)));
return;
}
// Sort plis by number of clusters: For searching in the covers and for validation, it is good to have attributes with few non-unique values and many clusters left in the prefix tree
Logger.getInstance().writeln("Sorting plis by number of clusters ...");
Collections.sort(plis, new Comparator<PositionListIndex>() {
@Override
public int compare(PositionListIndex o1, PositionListIndex o2) {
int numClustersInO1 = numRecords - o1.getNumNonUniqueValues() + o1.getClusters().size();
int numClustersInO2 = numRecords - o2.getNumNonUniqueValues() + o2.getClusters().size();
return numClustersInO2 - numClustersInO1;
}
});
// Calculate inverted plis
Logger.getInstance().writeln("Inverting plis ...");
int[][] invertedPlis = this.invertPlis(plis, numRecords);
// Extract the integer representations of all records from the inverted plis
Logger.getInstance().writeln("Extracting integer representations for the records ...");
int[][] compressedRecords = new int[numRecords][];
for (int recordId = 0; recordId < numRecords; recordId++)
compressedRecords[recordId] = this.fetchRecordFrom(recordId, invertedPlis);
invertedPlis = null;
// Initialize the negative cover
FDSet negCover = new FDSet(this.numAttributes, this.maxLhsSize);
// Initialize the positive cover
FDTree posCover = new FDTree(this.numAttributes, this.maxLhsSize);
posCover.addMostGeneralDependencies();
//////////////////////////
// Build the components //
//////////////////////////
// TODO: implement parallel sampling
Sampler sampler = new Sampler(negCover, posCover, compressedRecords, plis, this.efficiencyThreshold, this.valueComparator, this.memoryGuardian);
Inductor inductor = new Inductor(negCover, posCover, this.memoryGuardian);
Validator validator = new Validator(negCover, posCover, numRecords, compressedRecords, plis, this.efficiencyThreshold, this.validateParallel, this.memoryGuardian);
List<IntegerPair> comparisonSuggestions = new ArrayList<>();
do {
FDList newNonFds = sampler.enrichNegativeCover(comparisonSuggestions);
inductor.updatePositiveCover(newNonFds);
comparisonSuggestions = validator.validatePositiveCover();
}
while (comparisonSuggestions != null);
negCover = null;
// Output all valid FDs
Logger.getInstance().writeln("Translating FD-tree into result format ...");
// int numFDs = posCover.writeFunctionalDependencies("HyFD_backup_" + this.tableName + "_results.txt", this.buildColumnIdentifiers(), plis, false);
int numFDs = posCover.addFunctionalDependenciesInto(this.resultReceiver, this.buildColumnIdentifiers(), plis);
Logger.getInstance().writeln("... done! (" + numFDs + " FDs)");
}
@SuppressWarnings("unused")
private void executeFDEP() throws AlgorithmExecutionException {
// Initialize
Logger.getInstance().writeln("Initializing ...");
RelationalInput relationalInput = this.getInput();
this.initialize(relationalInput);
// Load data
Logger.getInstance().writeln("Loading data ...");
ObjectArrayList<List<String>> records = this.loadData(relationalInput);
this.closeInput(relationalInput);
// Create default output if input is empty
if (records.isEmpty()) {
ObjectArrayList<ColumnIdentifier> columnIdentifiers = this.buildColumnIdentifiers();
for (int attr = 0; attr < this.numAttributes; attr++)
this.resultReceiver.receiveResult(new FunctionalDependency(new ColumnCombination(), columnIdentifiers.get(attr)));
return;
}
int numRecords = records.size();
// Calculate plis
Logger.getInstance().writeln("Calculating plis ...");
List<PositionListIndex> plis = PLIBuilder.getPLIs(records, this.numAttributes, this.valueComparator.isNullEqualNull());
records = null; // we proceed with the values in the plis
// Calculate inverted plis
Logger.getInstance().writeln("Inverting plis ...");
int[][] invertedPlis = this.invertPlis(plis, numRecords);
// Extract the integer representations of all records from the inverted plis
Logger.getInstance().writeln("Extracting integer representations for the records ...");
int[][] compressedRecords = new int[numRecords][];
for (int recordId = 0; recordId < numRecords; recordId++)
compressedRecords[recordId] = this.fetchRecordFrom(recordId, invertedPlis);
// Execute fdep
Logger.getInstance().writeln("Executing fdep ...");
FDEP fdep = new FDEP(this.numAttributes, this.valueComparator);
FDTree fds = fdep.execute(compressedRecords);
// Output all valid FDs
Logger.getInstance().writeln("Translating fd-tree into result format ...");
List<FunctionalDependency> result = fds.getFunctionalDependencies(this.buildColumnIdentifiers(), plis);
plis = null;
int numFDs = 0;
for (FunctionalDependency fd : result) {
//Logger.getInstance().writeln(fd);
this.resultReceiver.receiveResult(fd);
numFDs++;
}
Logger.getInstance().writeln("... done! (" + numFDs + " FDs)");
}
private RelationalInput getInput() throws InputGenerationException, AlgorithmConfigurationException {
RelationalInput relationalInput = this.inputGenerator.generateNewCopy();
if (relationalInput == null)
throw new InputGenerationException("Input generation failed!");
return relationalInput;
}
private void closeInput(RelationalInput relationalInput) {
FileUtils.close(relationalInput);
}
private ObjectArrayList<ColumnIdentifier> buildColumnIdentifiers() {
ObjectArrayList<ColumnIdentifier> columnIdentifiers = new ObjectArrayList<ColumnIdentifier>(this.attributeNames.size());
for (String attributeName : this.attributeNames)
columnIdentifiers.add(new ColumnIdentifier(this.tableName, attributeName));
return columnIdentifiers;
}
private ObjectArrayList<List<String>> loadData(RelationalInput relationalInput) throws InputIterationException {
ObjectArrayList<List<String>> records = new ObjectArrayList<List<String>>();
while (relationalInput.hasNext())
records.add(relationalInput.next());
return records;
}
private int[][] invertPlis(List<PositionListIndex> plis, int numRecords) {
int[][] invertedPlis = new int[plis.size()][];
for (int attr = 0; attr < plis.size(); attr++) {
int[] invertedPli = new int[numRecords];
Arrays.fill(invertedPli, -1);
for (int clusterId = 0; clusterId < plis.get(attr).size(); clusterId++) {
for (int recordId : plis.get(attr).getClusters().get(clusterId))
invertedPli[recordId] = clusterId;
}
invertedPlis[attr] = invertedPli;
}
return invertedPlis;
}
private int[] fetchRecordFrom(int recordId, int[][] invertedPlis) {
int[] record = new int[this.numAttributes];
for (int i = 0; i < this.numAttributes; i++)
record[i] = invertedPlis[i][recordId];
return record;
}
}
| |
/*
* 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.intellij.openapi.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.StringInterner;
import com.intellij.util.io.URLUtil;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.text.CharSequenceReader;
import com.intellij.util.text.StringFactory;
import org.jdom.*;
import org.jdom.filter.Filter;
import org.jdom.input.SAXBuilder;
import org.jdom.input.SAXHandler;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import javax.xml.XMLConstants;
import java.io.*;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* @author mike
*/
@SuppressWarnings({"HardCodedStringLiteral"})
public class JDOMUtil {
private static final ThreadLocal<SoftReference<SAXBuilder>> ourSaxBuilder = new ThreadLocal<SoftReference<SAXBuilder>>();
public static final Condition<Attribute> NOT_EMPTY_VALUE_CONDITION = new Condition<Attribute>() {
@Override
public boolean value(Attribute attribute) {
return !StringUtil.isEmpty(attribute.getValue());
}
};
private JDOMUtil() { }
@NotNull
public static List<Element> getChildren(@Nullable Element parent) {
if (parent == null) {
return Collections.emptyList();
}
else {
return parent.getChildren();
}
}
@NotNull
public static List<Element> getChildren(@Nullable Element parent, @NotNull String name) {
if (parent != null) {
return parent.getChildren(name);
}
return Collections.emptyList();
}
@SuppressWarnings("UtilityClassWithoutPrivateConstructor")
private static class LoggerHolder {
private static final Logger ourLogger = Logger.getInstance("#com.intellij.openapi.util.JDOMUtil");
}
private static Logger getLogger() {
return LoggerHolder.ourLogger;
}
public static boolean areElementsEqual(@Nullable Element e1, @Nullable Element e2) {
return areElementsEqual(e1, e2, false);
}
/**
*
* @param ignoreEmptyAttrValues defines if elements like <element foo="bar" skip_it=""/> and <element foo="bar"/> are 'equal'
* @return <code>true</code> if two elements are deep-equals by their content and attributes
*/
public static boolean areElementsEqual(@Nullable Element e1, @Nullable Element e2, boolean ignoreEmptyAttrValues) {
if (e1 == null && e2 == null) return true;
if (e1 == null || e2 == null) return false;
return Comparing.equal(e1.getName(), e2.getName())
&& attListsEqual(e1.getAttributes(), e2.getAttributes(), ignoreEmptyAttrValues)
&& contentListsEqual(e1.getContent(CONTENT_FILTER), e2.getContent(CONTENT_FILTER), ignoreEmptyAttrValues);
}
private static final EmptyTextFilter CONTENT_FILTER = new EmptyTextFilter();
public static int getTreeHash(@NotNull Element root) {
return addToHash(0, root, true);
}
private static int addToHash(int i, @NotNull Element element, boolean skipEmptyText) {
i = addToHash(i, element.getName());
for (Attribute attribute : element.getAttributes()) {
i = addToHash(i, attribute.getName());
i = addToHash(i, attribute.getValue());
}
for (Content child : element.getContent()) {
if (child instanceof Element) {
i = addToHash(i, (Element)child, skipEmptyText);
}
else if (child instanceof Text) {
String text = ((Text)child).getText();
if (!skipEmptyText || !StringUtil.isEmptyOrSpaces(text)) {
i = addToHash(i, text);
}
}
}
return i;
}
private static int addToHash(int i, @NotNull String s) {
return i * 31 + s.hashCode();
}
/**
* @deprecated Use Element.getChildren() directly
*/
@NotNull
@Deprecated
public static Element[] getElements(@NotNull Element m) {
List<Element> list = m.getChildren();
return list.toArray(new Element[list.size()]);
}
public static void internElement(@NotNull Element element, @NotNull StringInterner interner) {
element.setName(interner.intern(element.getName()));
for (Attribute attr : element.getAttributes()) {
attr.setName(interner.intern(attr.getName()));
attr.setValue(interner.intern(attr.getValue()));
}
for (Content o : element.getContent()) {
if (o instanceof Element) {
internElement((Element)o, interner);
}
else if (o instanceof Text) {
((Text)o).setText(interner.intern(o.getValue()));
}
}
}
@NotNull
public static String legalizeText(@NotNull String str) {
return legalizeChars(str).toString();
}
@NotNull
public static CharSequence legalizeChars(@NotNull CharSequence str) {
StringBuilder result = new StringBuilder(str.length());
for (int i = 0, len = str.length(); i < len; i ++) {
appendLegalized(result, str.charAt(i));
}
return result;
}
private static void appendLegalized(@NotNull StringBuilder sb, char each) {
if (each == '<' || each == '>') {
sb.append(each == '<' ? "<" : ">");
}
else if (!Verifier.isXMLCharacter(each)) {
sb.append("0x").append(StringUtil.toUpperCase(Long.toHexString(each)));
}
else {
sb.append(each);
}
}
private static class EmptyTextFilter implements Filter {
@Override
public boolean matches(Object obj) {
return !(obj instanceof Text) || !CharArrayUtil.containsOnlyWhiteSpaces(((Text)obj).getText());
}
}
private static boolean contentListsEqual(final List c1, final List c2, boolean ignoreEmptyAttrValues) {
if (c1 == null && c2 == null) return true;
if (c1 == null || c2 == null) return false;
Iterator l1 = c1.listIterator();
Iterator l2 = c2.listIterator();
while (l1.hasNext() && l2.hasNext()) {
if (!contentsEqual((Content)l1.next(), (Content)l2.next(), ignoreEmptyAttrValues)) {
return false;
}
}
return l1.hasNext() == l2.hasNext();
}
private static boolean contentsEqual(Content c1, Content c2, boolean ignoreEmptyAttrValues) {
if (!(c1 instanceof Element) && !(c2 instanceof Element)) {
return c1.getValue().equals(c2.getValue());
}
return c1 instanceof Element && c2 instanceof Element && areElementsEqual((Element)c1, (Element)c2, ignoreEmptyAttrValues);
}
private static boolean attListsEqual(@NotNull List<Attribute> l1, @NotNull List<Attribute> l2, boolean ignoreEmptyAttrValues) {
if (ignoreEmptyAttrValues) {
l1 = ContainerUtil.filter(l1, NOT_EMPTY_VALUE_CONDITION);
l2 = ContainerUtil.filter(l2, NOT_EMPTY_VALUE_CONDITION);
}
if (l1.size() != l2.size()) return false;
for (int i = 0; i < l1.size(); i++) {
if (!attEqual(l1.get(i), l2.get(i))) return false;
}
return true;
}
private static boolean attEqual(@NotNull Attribute a1, @NotNull Attribute a2) {
return a1.getName().equals(a2.getName()) && a1.getValue().equals(a2.getValue());
}
private static SAXBuilder getSaxBuilder() {
SoftReference<SAXBuilder> reference = ourSaxBuilder.get();
SAXBuilder saxBuilder = com.intellij.reference.SoftReference.dereference(reference);
if (saxBuilder == null) {
saxBuilder = new SAXBuilder() {
@Override
protected void configureParser(XMLReader parser, SAXHandler contentHandler) throws JDOMException {
super.configureParser(parser, contentHandler);
try {
parser.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (Exception ignore) {
}
}
};
saxBuilder.setEntityResolver(new EntityResolver() {
@Override
@NotNull
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(new CharArrayReader(ArrayUtil.EMPTY_CHAR_ARRAY));
}
});
ourSaxBuilder.set(new SoftReference<SAXBuilder>(saxBuilder));
}
return saxBuilder;
}
/**
* @deprecated Use {@link #load(CharSequence)}
*
* Direct usage of element allows to get rid of {@link Document#getRootElement()} because only Element is required in mostly all cases.
*/
@NotNull
@Deprecated
public static Document loadDocument(@NotNull CharSequence seq) throws IOException, JDOMException {
return loadDocument(new CharSequenceReader(seq));
}
public static Element load(@NotNull CharSequence seq) throws IOException, JDOMException {
return load(new CharSequenceReader(seq));
}
@NotNull
private static Document loadDocument(@NotNull Reader reader) throws IOException, JDOMException {
try {
return getSaxBuilder().build(reader);
}
finally {
reader.close();
}
}
@NotNull
public static Document loadDocument(File file) throws JDOMException, IOException {
return loadDocument(new BufferedInputStream(new FileInputStream(file)));
}
@NotNull
public static Element load(@NotNull File file) throws JDOMException, IOException {
return load(new BufferedInputStream(new FileInputStream(file)));
}
@NotNull
public static Document loadDocument(@NotNull InputStream stream) throws JDOMException, IOException {
return loadDocument(new InputStreamReader(stream, CharsetToolkit.UTF8_CHARSET));
}
public static Element load(Reader reader) throws JDOMException, IOException {
return reader == null ? null : loadDocument(reader).detachRootElement();
}
/**
* Consider to use `loadElement` (JdomKt.loadElement from java) due to more efficient whitespace handling (cannot be changed here due to backward compatibility).
*/
@Contract("null -> null; !null -> !null")
public static Element load(InputStream stream) throws JDOMException, IOException {
return stream == null ? null : loadDocument(stream).detachRootElement();
}
@NotNull
public static Document loadDocument(@NotNull Class clazz, String resource) throws JDOMException, IOException {
InputStream stream = clazz.getResourceAsStream(resource);
if (stream == null) {
throw new FileNotFoundException(resource);
}
return loadDocument(stream);
}
@NotNull
public static Document loadDocument(@NotNull URL url) throws JDOMException, IOException {
return loadDocument(URLUtil.openStream(url));
}
@NotNull
public static Document loadResourceDocument(URL url) throws JDOMException, IOException {
return loadDocument(URLUtil.openResourceStream(url));
}
public static void writeDocument(@NotNull Document document, @NotNull String filePath, String lineSeparator) throws IOException {
OutputStream stream = new BufferedOutputStream(new FileOutputStream(filePath));
try {
writeDocument(document, stream, lineSeparator);
}
finally {
stream.close();
}
}
public static void writeDocument(@NotNull Document document, @NotNull File file, String lineSeparator) throws IOException {
write(document, file, lineSeparator);
}
public static void write(@NotNull Parent element, @NotNull File file) throws IOException {
write(element, file, "\n");
}
public static void write(@NotNull Parent element, @NotNull File file, @NotNull String lineSeparator) throws IOException {
FileUtil.createParentDirs(file);
OutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
try {
write(element, stream, lineSeparator);
}
finally {
stream.close();
}
}
public static void writeDocument(@NotNull Document document, @NotNull OutputStream stream, String lineSeparator) throws IOException {
write(document, stream, lineSeparator);
}
public static void write(@NotNull Parent element, @NotNull OutputStream stream, @NotNull String lineSeparator) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(stream, CharsetToolkit.UTF8_CHARSET);
try {
if (element instanceof Document) {
writeDocument((Document)element, writer, lineSeparator);
}
else {
writeElement((Element) element, writer, lineSeparator);
}
}
finally {
writer.close();
}
}
/**
* @deprecated Use {@link #writeDocument(Document, String)} or {@link #writeElement(Element)}}
*/
@NotNull
@Deprecated
public static byte[] printDocument(@NotNull Document document, String lineSeparator) throws IOException {
CharArrayWriter writer = new CharArrayWriter();
writeDocument(document, writer, lineSeparator);
return StringFactory.createShared(writer.toCharArray()).getBytes(CharsetToolkit.UTF8_CHARSET);
}
@NotNull
public static String writeDocument(@NotNull Document document, String lineSeparator) {
try {
final StringWriter writer = new StringWriter();
writeDocument(document, writer, lineSeparator);
return writer.toString();
}
catch (IOException ignored) {
// Can't be
return "";
}
}
@NotNull
public static String write(Parent element, String lineSeparator) {
try {
final StringWriter writer = new StringWriter();
write(element, writer, lineSeparator);
return writer.toString();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void write(Parent element, Writer writer, String lineSeparator) throws IOException {
if (element instanceof Element) {
writeElement((Element) element, writer, lineSeparator);
} else if (element instanceof Document) {
writeDocument((Document) element, writer, lineSeparator);
}
}
public static void writeElement(@NotNull Element element, Writer writer, String lineSeparator) throws IOException {
XMLOutputter xmlOutputter = createOutputter(lineSeparator);
try {
xmlOutputter.output(element, writer);
}
catch (NullPointerException ex) {
getLogger().error(ex);
printDiagnostics(element, "");
}
}
@NotNull
public static String writeElement(@NotNull Element element) {
return writeElement(element, "\n");
}
@NotNull
public static String writeElement(@NotNull Element element, String lineSeparator) {
try {
final StringWriter writer = new StringWriter();
writeElement(element, writer, lineSeparator);
return writer.toString();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@NotNull
public static String writeChildren(@NotNull final Element element, @NotNull final String lineSeparator) throws IOException {
final StringWriter writer = new StringWriter();
for (Element child : element.getChildren()) {
writeElement(child, writer, lineSeparator);
writer.append(lineSeparator);
}
return writer.toString();
}
public static void writeDocument(@NotNull Document document, @NotNull Writer writer, String lineSeparator) throws IOException {
XMLOutputter xmlOutputter = createOutputter(lineSeparator);
try {
xmlOutputter.output(document, writer);
}
catch (NullPointerException ex) {
getLogger().error(ex);
printDiagnostics(document.getRootElement(), "");
}
}
@NotNull
public static XMLOutputter createOutputter(String lineSeparator) {
XMLOutputter xmlOutputter = new MyXMLOutputter();
Format format = Format.getCompactFormat().
setIndent(" ").
setTextMode(Format.TextMode.TRIM).
setEncoding(CharsetToolkit.UTF8).
setOmitEncoding(false).
setOmitDeclaration(false).
setLineSeparator(lineSeparator);
xmlOutputter.setFormat(format);
return xmlOutputter;
}
/**
* Returns null if no escapement necessary.
*/
@Nullable
private static String escapeChar(char c, boolean escapeApostrophes, boolean escapeSpaces, boolean escapeLineEnds) {
switch (c) {
case '\n': return escapeLineEnds ? " " : null;
case '\r': return escapeLineEnds ? " " : null;
case '\t': return escapeLineEnds ? "	" : null;
case ' ' : return escapeSpaces ? "" : null;
case '<': return "<";
case '>': return ">";
case '\"': return """;
case '\'': return escapeApostrophes ? "'": null;
case '&': return "&";
}
return null;
}
@NotNull
public static String escapeText(@NotNull String text) {
return escapeText(text, false, false);
}
@NotNull
public static String escapeText(@NotNull String text, boolean escapeSpaces, boolean escapeLineEnds) {
return escapeText(text, false, escapeSpaces, escapeLineEnds);
}
@NotNull
public static String escapeText(@NotNull String text, boolean escapeApostrophes, boolean escapeSpaces, boolean escapeLineEnds) {
StringBuilder buffer = null;
for (int i = 0; i < text.length(); i++) {
final char ch = text.charAt(i);
final String quotation = escapeChar(ch, escapeApostrophes, escapeSpaces, escapeLineEnds);
if (buffer == null) {
if (quotation != null) {
// An quotation occurred, so we'll have to use StringBuffer
// (allocate room for it plus a few more entities).
buffer = new StringBuilder(text.length() + 20);
// Copy previous skipped characters and fall through
// to pickup current character
buffer.append(text, 0, i);
buffer.append(quotation);
}
}
else if (quotation == null) {
buffer.append(ch);
}
else {
buffer.append(quotation);
}
}
// If there were any entities, return the escaped characters
// that we put in the StringBuffer. Otherwise, just return
// the unmodified input string.
return buffer == null ? text : buffer.toString();
}
public static class MyXMLOutputter extends XMLOutputter {
@Override
@NotNull
public String escapeAttributeEntities(@NotNull String str) {
return escapeText(str, false, true);
}
@Override
@NotNull
public String escapeElementEntities(@NotNull String str) {
return escapeText(str, false, false);
}
}
private static void printDiagnostics(@NotNull Element element, String prefix) {
ElementInfo info = getElementInfo(element);
prefix += "/" + info.name;
if (info.hasNullAttributes) {
//noinspection UseOfSystemOutOrSystemErr
System.err.println(prefix);
}
for (final Element child : element.getChildren()) {
printDiagnostics(child, prefix);
}
}
@NotNull
private static ElementInfo getElementInfo(@NotNull Element element) {
ElementInfo info = new ElementInfo();
StringBuilder buf = new StringBuilder(element.getName());
List attributes = element.getAttributes();
if (attributes != null) {
int length = attributes.size();
if (length > 0) {
buf.append("[");
for (int idx = 0; idx < length; idx++) {
Attribute attr = (Attribute)attributes.get(idx);
if (idx != 0) {
buf.append(";");
}
buf.append(attr.getName());
buf.append("=");
buf.append(attr.getValue());
if (attr.getValue() == null) {
info.hasNullAttributes = true;
}
}
buf.append("]");
}
}
info.name = buf.toString();
return info;
}
public static void updateFileSet(@NotNull File[] oldFiles, @NotNull String[] newFilePaths, @NotNull Document[] newFileDocuments, String lineSeparator)
throws IOException {
getLogger().assertTrue(newFilePaths.length == newFileDocuments.length);
ArrayList<String> writtenFilesPaths = new ArrayList<String>();
// check if files are writable
for (String newFilePath : newFilePaths) {
File file = new File(newFilePath);
if (file.exists() && !file.canWrite()) {
throw new IOException("File \"" + newFilePath + "\" is not writeable");
}
}
for (File file : oldFiles) {
if (file.exists() && !file.canWrite()) {
throw new IOException("File \"" + file.getAbsolutePath() + "\" is not writeable");
}
}
for (int i = 0; i < newFilePaths.length; i++) {
String newFilePath = newFilePaths[i];
writeDocument(newFileDocuments[i], newFilePath, lineSeparator);
writtenFilesPaths.add(newFilePath);
}
// delete files if necessary
outer:
for (File oldFile : oldFiles) {
String oldFilePath = oldFile.getAbsolutePath();
for (final String writtenFilesPath : writtenFilesPaths) {
if (oldFilePath.equals(writtenFilesPath)) {
continue outer;
}
}
boolean result = oldFile.delete();
if (!result) {
throw new IOException("File \"" + oldFilePath + "\" was not deleted");
}
}
}
private static class ElementInfo {
@NotNull public String name = "";
public boolean hasNullAttributes = false;
}
public static String getValue(Object node) {
if (node instanceof Content) {
Content content = (Content)node;
return content.getValue();
}
else if (node instanceof Attribute) {
Attribute attribute = (Attribute)node;
return attribute.getValue();
}
else {
throw new IllegalArgumentException("Wrong node: " + node);
}
}
public static boolean isEmpty(@Nullable Element element) {
return element == null || (element.getAttributes().isEmpty() && element.getContent().isEmpty());
}
public static boolean isEmpty(@Nullable Element element, int attributeCount) {
return element == null || (element.getAttributes().size() == attributeCount && element.getContent().isEmpty());
}
public static void merge(@NotNull Element to, @NotNull Element from) {
for (Iterator<Element> iterator = from.getChildren().iterator(); iterator.hasNext(); ) {
Element configuration = iterator.next();
iterator.remove();
to.addContent(configuration);
}
for (Iterator<Attribute> iterator = from.getAttributes().iterator(); iterator.hasNext(); ) {
Attribute attribute = iterator.next();
iterator.remove();
to.setAttribute(attribute);
}
}
}
| |
/*
* 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.indexer.hadoop;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import org.apache.druid.java.util.common.JodaUtils;
import org.apache.druid.java.util.common.granularity.Granularity;
import org.apache.druid.query.filter.DimFilter;
import org.apache.druid.segment.SegmentUtils;
import org.apache.druid.segment.transform.TransformSpec;
import org.apache.druid.timeline.DataSegment;
import org.joda.time.Interval;
import java.util.List;
import java.util.Objects;
public class DatasourceIngestionSpec
{
private final String dataSource;
private final List<Interval> intervals;
private final List<DataSegment> segments;
private final DimFilter filter;
private final List<String> dimensions;
private final List<String> metrics;
private final boolean ignoreWhenNoSegments;
// Note that the only purpose of the transformSpec field is to hold the value from the overall dataSchema.
// It is not meant to be provided by end users, and will be overwritten.
private final TransformSpec transformSpec;
@JsonCreator
public DatasourceIngestionSpec(
@JsonProperty("dataSource") String dataSource,
@Deprecated @JsonProperty("interval") Interval interval,
@JsonProperty("intervals") List<Interval> intervals,
@JsonProperty("segments") List<DataSegment> segments,
@JsonProperty("filter") DimFilter filter,
@JsonProperty("dimensions") List<String> dimensions,
@JsonProperty("metrics") List<String> metrics,
@JsonProperty("ignoreWhenNoSegments") boolean ignoreWhenNoSegments,
@JsonProperty("transformSpec") TransformSpec transformSpec
)
{
this.dataSource = Preconditions.checkNotNull(dataSource, "null dataSource");
Preconditions.checkArgument(
interval == null || intervals == null,
"please specify intervals only"
);
List<Interval> theIntervals = null;
if (interval != null) {
theIntervals = ImmutableList.of(interval);
} else if (intervals != null && intervals.size() > 0) {
theIntervals = JodaUtils.condenseIntervals(intervals);
}
this.intervals = Preconditions.checkNotNull(theIntervals, "no intervals found");
// note that it is important to have intervals even if user explicitly specifies the list of
// segments, because segment list's min/max boundaries might not align the intended interval
// to read in all cases.
this.segments = segments;
this.filter = filter;
this.dimensions = dimensions;
this.metrics = metrics;
this.ignoreWhenNoSegments = ignoreWhenNoSegments;
this.transformSpec = transformSpec != null ? transformSpec : TransformSpec.NONE;
}
@JsonProperty
public String getDataSource()
{
return dataSource;
}
@JsonProperty
public List<Interval> getIntervals()
{
return intervals;
}
@JsonProperty
public List<DataSegment> getSegments()
{
return segments;
}
@JsonProperty
public DimFilter getFilter()
{
return filter;
}
@JsonProperty
public List<String> getDimensions()
{
return dimensions;
}
@JsonProperty
public List<String> getMetrics()
{
return metrics;
}
@JsonProperty
public boolean isIgnoreWhenNoSegments()
{
return ignoreWhenNoSegments;
}
@JsonProperty
public TransformSpec getTransformSpec()
{
return transformSpec;
}
public DatasourceIngestionSpec withDimensions(List<String> dimensions)
{
return new DatasourceIngestionSpec(
dataSource,
null,
intervals,
segments,
filter,
dimensions,
metrics,
ignoreWhenNoSegments,
transformSpec
);
}
public DatasourceIngestionSpec withMetrics(List<String> metrics)
{
return new DatasourceIngestionSpec(
dataSource,
null,
intervals,
segments,
filter,
dimensions,
metrics,
ignoreWhenNoSegments,
transformSpec
);
}
public DatasourceIngestionSpec withQueryGranularity(Granularity granularity)
{
return new DatasourceIngestionSpec(
dataSource,
null,
intervals,
segments,
filter,
dimensions,
metrics,
ignoreWhenNoSegments,
transformSpec
);
}
public DatasourceIngestionSpec withIgnoreWhenNoSegments(boolean ignoreWhenNoSegments)
{
return new DatasourceIngestionSpec(
dataSource,
null,
intervals,
segments,
filter,
dimensions,
metrics,
ignoreWhenNoSegments,
transformSpec
);
}
public DatasourceIngestionSpec withTransformSpec(TransformSpec transformSpec)
{
return new DatasourceIngestionSpec(
dataSource,
null,
intervals,
segments,
filter,
dimensions,
metrics,
ignoreWhenNoSegments,
transformSpec
);
}
@Override
public boolean equals(final Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final DatasourceIngestionSpec that = (DatasourceIngestionSpec) o;
return ignoreWhenNoSegments == that.ignoreWhenNoSegments &&
Objects.equals(dataSource, that.dataSource) &&
Objects.equals(intervals, that.intervals) &&
Objects.equals(segments, that.segments) &&
Objects.equals(filter, that.filter) &&
Objects.equals(dimensions, that.dimensions) &&
Objects.equals(metrics, that.metrics) &&
Objects.equals(transformSpec, that.transformSpec);
}
@Override
public int hashCode()
{
return Objects.hash(
dataSource,
intervals,
segments,
filter,
dimensions,
metrics,
ignoreWhenNoSegments,
transformSpec
);
}
@Override
public String toString()
{
return "DatasourceIngestionSpec{" +
"dataSource='" + dataSource + '\'' +
", intervals=" + intervals +
", segments=" + SegmentUtils.commaSeparatedIdentifiers(segments) +
", filter=" + filter +
", dimensions=" + dimensions +
", metrics=" + metrics +
", ignoreWhenNoSegments=" + ignoreWhenNoSegments +
", transformSpec=" + transformSpec +
'}';
}
}
| |
/*
* The MIT License
*
* Copyright (c) 2015, CloudBees, Inc.
*
* 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 org.jenkinsci.plugins.docker.commons.fingerprint;
import hudson.BulkChange;
import hudson.model.Fingerprint;
import hudson.model.Run;
import jenkins.model.Jenkins;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jenkins.model.FingerprintFacet;
import org.apache.commons.lang.StringUtils;
/**
* Entry point into fingerprint related functionalities in Docker.
* This class provide basic methods for both images and containers
*/
public class DockerFingerprints {
private static final Logger LOGGER = Logger.getLogger(DockerFingerprints.class.getName());
private DockerFingerprints() {} // no instantiation
/**
* Gets a fingerprint hash for Docker ID (image or container).
* This method calculates image hash without retrieving a fingerprint by
* {@link DockerFingerprints#of(java.lang.String)}, which may be a high-cost call.
*
* @param id Docker ID (image or container).
* Only 64-char full IDs are supported.
* @return 32-char fingerprint hash
* @throws IllegalArgumentException Invalid ID
*/
public static @Nonnull String getFingerprintHash(@Nonnull String id) {
// Remove the "sha256:" prefix, if it exists
if (id.indexOf("sha256:") == 0) {
id = id.substring(7);
}
if (id.length() != 64) {
throw new IllegalArgumentException("Expecting 64-char full image ID, but got " + id);
}
return id.substring(0, 32);
}
/**
* Gets {@link Fingerprint} for a given docker ID.
* @param id Docker ID (image or container). Only 64-char full IDs are supported.
* @return Created fingerprint or null if it is not found
* @throws IOException Fingerprint loading error
*/
public static @CheckForNull Fingerprint of(@Nonnull String id) throws IOException {
return Jenkins.getInstance().getFingerprintMap().get(getFingerprintHash(id));
}
private static @CheckForNull Fingerprint ofNoException(@Nonnull String id) {
try {
return of(id);
} catch (IOException ex) { // The error is not a hazard in CheckForNull logic
LOGGER.log(Level.WARNING, "Cannot retrieve a fingerprint for Docker id="+id, ex);
}
return null;
}
/**
* @deprecated Use {@link #forImage(hudson.model.Run, java.lang.String, java.lang.String)}
*/
public static @Nonnull Fingerprint forImage(@CheckForNull Run<?,?> run, @Nonnull String id) throws IOException {
return forImage(run, id, null);
}
/**
* Get or create a {@link Fingerprint} for the image.
* @param run Origin of the fingerprint (if available)
* @param id Image ID. Only 64-char full IDs are supported.
* @param name Optional name of the image. If null, the image name will be
* constructed using the specified ID.
* @return Fingerprint for the specified ID
* @throws IOException Fingerprint load/save error
* @since TODO
*/
public static @Nonnull Fingerprint forImage(@CheckForNull Run<?,?> run,
@Nonnull String id, @CheckForNull String name) throws IOException {
return forDockerInstance(run, id, name, "Docker image ");
}
/**
* @deprecated Use {@link #forContainer(hudson.model.Run, java.lang.String, java.lang.String)}
*/
@Deprecated
public static @Nonnull Fingerprint forContainer(@CheckForNull Run<?,?> run, @Nonnull String id) throws IOException {
return forContainer(run, id, null);
}
/**
* Get or create a {@link Fingerprint} for the container.
* @param run Origin of the fingerprint (if available)
* @param id Container ID. Only 64-char full IDs are supported.
* @param name Optional name of the container. If null, the container name will be
* constructed using the specified ID.
* @return Fingerprint for the specified ID
* @throws IOException Fingerprint load/save error
* @since TODO
*/
public static @Nonnull Fingerprint forContainer(@CheckForNull Run<?,?> run,
@Nonnull String id, @CheckForNull String name) throws IOException {
return forDockerInstance(run, id, name, "Docker container ");
}
private static @Nonnull Fingerprint forDockerInstance(@CheckForNull Run<?,?> run,
@Nonnull String id, @CheckForNull String name, @Nonnull String prefix) throws IOException {
final Jenkins j = Jenkins.getInstance();
if (j == null) {
throw new IOException("Jenkins instance is not ready");
}
final String imageName = prefix + (StringUtils.isNotBlank(name) ? name : id);
return j.getFingerprintMap().getOrCreate(run, imageName, getFingerprintHash(id));
}
/**
* Retrieves a facet from the {@link Fingerprint}.
* The method suppresses {@link IOException} if a fingerprint loading fails.
* @param <TFacet> Facet type to be retrieved
* @param id Docker item ID. Only 64-char full IDs are supported
* @param facetClass Class to be retrieved
* @return First matching facet. Null may be returned if there is no facet
* or if the loading fails
*/
public static @CheckForNull @SuppressWarnings("unchecked")
<TFacet extends FingerprintFacet> TFacet getFacet
(@Nonnull String id, @Nonnull Class<TFacet> facetClass) {
final Fingerprint fp = ofNoException(id);
return (fp != null) ? getFacet(fp, facetClass) : null;
}
/**
* Retrieves a facet from the {@link Fingerprint}.
* The method suppresses {@link IOException} if a fingerprint loading fails.
* @param <TFacet> Facet type to be retrieved
* @param id Docker item ID. Only 64-char full IDs are supported
* @param facetClass Class to be retrieved
* @return First matching facet. Null may be returned if the loading fails
*/
@SuppressWarnings("unchecked")
public static @Nonnull <TFacet extends FingerprintFacet> Collection<TFacet> getFacets
(@Nonnull String id, @Nonnull Class<TFacet> facetClass) {
final Fingerprint fp = ofNoException(id);
return (fp != null) ? getFacets(fp, facetClass) : Collections.<TFacet>emptySet();
}
//TODO: deprecate and use the core's method when it's available
/**
* Retrieves a facet from the {@link Fingerprint}.
* @param <TFacet> Facet type to be retrieved
* @param fingerprint Fingerprint, which stores facets
* @param facetClass Class to be retrieved
* @return First matching facet.
*/
@SuppressWarnings("unchecked")
public static @CheckForNull <TFacet extends FingerprintFacet> TFacet getFacet
(@Nonnull Fingerprint fingerprint, @Nonnull Class<TFacet> facetClass) {
for ( FingerprintFacet facet : fingerprint.getFacets()) {
if (facetClass.isAssignableFrom(facet.getClass())) {
return (TFacet)facet;
}
}
return null;
}
//TODO: deprecate and use the core's method when it's available
/**
* Retrieves facets from the {@link Fingerprint}.
* @param <TFacet> Facet type to be retrieved
* @param fingerprint Fingerprint, which stores facets
* @param facetClass Facet class to be retrieved
* @return All found facets
*/
public static @Nonnull @SuppressWarnings("unchecked")
<TFacet extends FingerprintFacet> Collection<TFacet> getFacets
(@Nonnull Fingerprint fingerprint, @Nonnull Class<TFacet> facetClass) {
final List<TFacet> res = new LinkedList<TFacet>();
for ( FingerprintFacet facet : fingerprint.getFacets()) {
if (facetClass.isAssignableFrom(facet.getClass())) {
res.add((TFacet)facet);
}
}
return res;
}
/**
* Adds a new {@link ContainerRecord} for the specified image, creating necessary intermediate objects as it goes.
*/
public static void addRunFacet(@Nonnull ContainerRecord record, @Nonnull Run<?,?> run) throws IOException {
String imageId = record.getImageId();
Fingerprint f = forImage(run, imageId);
synchronized (f) {
Collection<FingerprintFacet> facets = f.getFacets();
DockerRunFingerprintFacet runFacet = null;
for (FingerprintFacet facet : facets) {
if (facet instanceof DockerRunFingerprintFacet) {
runFacet = (DockerRunFingerprintFacet) facet;
break;
}
}
BulkChange bc = new BulkChange(f);
try {
if (runFacet == null) {
runFacet = new DockerRunFingerprintFacet(f, System.currentTimeMillis(), imageId);
facets.add(runFacet);
}
runFacet.add(record);
runFacet.addFor(run);
DockerFingerprintAction.addToRun(f, imageId, run);
bc.commit();
} finally {
bc.abort();
}
}
}
/**
* Creates a new {@link DockerAncestorFingerprintFacet} and {@link DockerDescendantFingerprintFacet} and adds a run.
* Or adds to existing facets.
* @param ancestorImageId the ID of the image specified in a {@code FROM} instruction, or null in case of {@code scratch} (i.e., the descendant is a base image)
* @param descendantImageId the ID of the image which was built
* @param run the build in which the image building occurred
*/
public static void addFromFacet(@CheckForNull String ancestorImageId, @Nonnull String descendantImageId, @Nonnull Run<?,?> run) throws IOException {
long timestamp = System.currentTimeMillis();
if (ancestorImageId != null) {
Fingerprint f = forImage(run, ancestorImageId);
synchronized (f) {
Collection<FingerprintFacet> facets = f.getFacets();
DockerDescendantFingerprintFacet descendantFacet = null;
for (FingerprintFacet facet : facets) {
if (facet instanceof DockerDescendantFingerprintFacet) {
descendantFacet = (DockerDescendantFingerprintFacet) facet;
break;
}
}
BulkChange bc = new BulkChange(f);
try {
if (descendantFacet == null) {
descendantFacet = new DockerDescendantFingerprintFacet(f, timestamp, ancestorImageId);
facets.add(descendantFacet);
}
descendantFacet.addDescendantImageId(descendantImageId);
descendantFacet.addFor(run);
DockerFingerprintAction.addToRun(f, ancestorImageId, run);
bc.commit();
} finally {
bc.abort();
}
}
}
Fingerprint f = forImage(run, descendantImageId);
synchronized (f) {
Collection<FingerprintFacet> facets = f.getFacets();
DockerAncestorFingerprintFacet ancestorFacet = null;
for (FingerprintFacet facet : facets) {
if (facet instanceof DockerAncestorFingerprintFacet) {
ancestorFacet = (DockerAncestorFingerprintFacet) facet;
break;
}
}
BulkChange bc = new BulkChange(f);
try {
if (ancestorFacet == null) {
ancestorFacet = new DockerAncestorFingerprintFacet(f, timestamp, descendantImageId);
facets.add(ancestorFacet);
}
if (ancestorImageId != null) {
ancestorFacet.addAncestorImageId(ancestorImageId);
}
ancestorFacet.addFor(run);
DockerFingerprintAction.addToRun(f, descendantImageId, run);
bc.commit();
} finally {
bc.abort();
}
}
}
}
| |
/*
* 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.execution;
import com.facebook.drift.annotations.ThriftConstructor;
import com.facebook.drift.annotations.ThriftField;
import com.facebook.drift.annotations.ThriftStruct;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.net.URI;
import java.util.List;
import java.util.Set;
import static com.facebook.presto.execution.TaskState.PLANNED;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
@ThriftStruct
public class TaskStatus
{
/**
* The first valid version that will be returned for a remote task.
*/
public static final long STARTING_VERSION = 1;
/**
* A value lower than {@link #STARTING_VERSION}. This value can be used to
* create an initial local task that is always older than any remote task.
*/
private static final long MIN_VERSION = 0;
/**
* A value larger than any valid value. This value can be used to create
* a final local task that is always newer than any remote task.
*/
private static final long MAX_VERSION = Long.MAX_VALUE;
private final long taskInstanceIdLeastSignificantBits;
private final long taskInstanceIdMostSignificantBits;
private final long version;
private final TaskState state;
private final URI self;
private final Set<Lifespan> completedDriverGroups;
private final int queuedPartitionedDrivers;
private final int runningPartitionedDrivers;
private final double outputBufferUtilization;
private final boolean outputBufferOverutilized;
private final long physicalWrittenDataSizeInBytes;
private final long memoryReservationInBytes;
private final long systemMemoryReservationInBytes;
private final long peakNodeTotalMemoryReservationInBytes;
private final long fullGcCount;
private final long fullGcTimeInMillis;
private final List<ExecutionFailureInfo> failures;
@JsonCreator
@ThriftConstructor
public TaskStatus(
@JsonProperty("taskInstanceIdLeastSignificantBits") long taskInstanceIdLeastSignificantBits,
@JsonProperty("taskInstanceIdMostSignificantBits") long taskInstanceIdMostSignificantBits,
@JsonProperty("version") long version,
@JsonProperty("state") TaskState state,
@JsonProperty("self") URI self,
@JsonProperty("completedDriverGroups") Set<Lifespan> completedDriverGroups,
@JsonProperty("failures") List<ExecutionFailureInfo> failures,
@JsonProperty("queuedPartitionedDrivers") int queuedPartitionedDrivers,
@JsonProperty("runningPartitionedDrivers") int runningPartitionedDrivers,
@JsonProperty("outputBufferUtilization") double outputBufferUtilization,
@JsonProperty("outputBufferOverutilized") boolean outputBufferOverutilized,
@JsonProperty("physicalWrittenDataSizeInBytes") long physicalWrittenDataSizeInBytes,
@JsonProperty("memoryReservationInBytes") long memoryReservationInBytes,
@JsonProperty("systemMemoryReservationInBytes") long systemMemoryReservationInBytes,
@JsonProperty("peakNodeTotalMemoryReservationInBytes") long peakNodeTotalMemoryReservationInBytes,
@JsonProperty("fullGcCount") long fullGcCount,
@JsonProperty("fullGcTimeInMillis") long fullGcTimeInMillis)
{
this.taskInstanceIdLeastSignificantBits = taskInstanceIdLeastSignificantBits;
this.taskInstanceIdMostSignificantBits = taskInstanceIdMostSignificantBits;
checkState(version >= MIN_VERSION, "version must be >= MIN_VERSION");
this.version = version;
this.state = requireNonNull(state, "state is null");
this.self = requireNonNull(self, "self is null");
this.completedDriverGroups = requireNonNull(completedDriverGroups, "completedDriverGroups is null");
checkArgument(queuedPartitionedDrivers >= 0, "queuedPartitionedDrivers must be positive");
this.queuedPartitionedDrivers = queuedPartitionedDrivers;
checkArgument(runningPartitionedDrivers >= 0, "runningPartitionedDrivers must be positive");
this.runningPartitionedDrivers = runningPartitionedDrivers;
this.outputBufferUtilization = outputBufferUtilization;
this.outputBufferOverutilized = outputBufferOverutilized;
this.physicalWrittenDataSizeInBytes = physicalWrittenDataSizeInBytes;
this.memoryReservationInBytes = memoryReservationInBytes;
this.systemMemoryReservationInBytes = systemMemoryReservationInBytes;
this.peakNodeTotalMemoryReservationInBytes = peakNodeTotalMemoryReservationInBytes;
this.failures = ImmutableList.copyOf(requireNonNull(failures, "failures is null"));
checkArgument(fullGcCount >= 0, "fullGcCount is negative");
this.fullGcCount = fullGcCount;
this.fullGcTimeInMillis = fullGcTimeInMillis;
}
@JsonProperty
@ThriftField(1)
public long getTaskInstanceIdLeastSignificantBits()
{
return taskInstanceIdLeastSignificantBits;
}
@JsonProperty
@ThriftField(2)
public long getTaskInstanceIdMostSignificantBits()
{
return taskInstanceIdMostSignificantBits;
}
@JsonProperty
@ThriftField(3)
public long getVersion()
{
return version;
}
@JsonProperty
@ThriftField(4)
public TaskState getState()
{
return state;
}
@JsonProperty
@ThriftField(5)
public URI getSelf()
{
return self;
}
@JsonProperty
@ThriftField(6)
public Set<Lifespan> getCompletedDriverGroups()
{
return completedDriverGroups;
}
@JsonProperty
@ThriftField(7)
public List<ExecutionFailureInfo> getFailures()
{
return failures;
}
@JsonProperty
@ThriftField(8)
public int getQueuedPartitionedDrivers()
{
return queuedPartitionedDrivers;
}
@JsonProperty
@ThriftField(9)
public int getRunningPartitionedDrivers()
{
return runningPartitionedDrivers;
}
@JsonProperty
@ThriftField(10)
public double getOutputBufferUtilization()
{
return outputBufferUtilization;
}
@JsonProperty
@ThriftField(11)
public boolean isOutputBufferOverutilized()
{
return outputBufferOverutilized;
}
@JsonProperty
@ThriftField(12)
public long getPhysicalWrittenDataSizeInBytes()
{
return physicalWrittenDataSizeInBytes;
}
@JsonProperty
@ThriftField(13)
public long getMemoryReservationInBytes()
{
return memoryReservationInBytes;
}
@JsonProperty
@ThriftField(14)
public long getSystemMemoryReservationInBytes()
{
return systemMemoryReservationInBytes;
}
@JsonProperty
@ThriftField(15)
public long getFullGcCount()
{
return fullGcCount;
}
@JsonProperty
@ThriftField(16)
public long getFullGcTimeInMillis()
{
return fullGcTimeInMillis;
}
@JsonProperty
@ThriftField(17)
public long getPeakNodeTotalMemoryReservationInBytes()
{
return peakNodeTotalMemoryReservationInBytes;
}
@Override
public String toString()
{
return toStringHelper(this)
.add("state", state)
.toString();
}
public static TaskStatus initialTaskStatus(URI location)
{
return new TaskStatus(
0L,
0L,
MIN_VERSION,
PLANNED,
location,
ImmutableSet.of(),
ImmutableList.of(),
0,
0,
0.0,
false,
0,
0,
0,
0,
0,
0);
}
public static TaskStatus failWith(TaskStatus taskStatus, TaskState state, List<ExecutionFailureInfo> exceptions)
{
return new TaskStatus(
taskStatus.getTaskInstanceIdLeastSignificantBits(),
taskStatus.getTaskInstanceIdMostSignificantBits(),
MAX_VERSION,
state,
taskStatus.getSelf(),
taskStatus.getCompletedDriverGroups(),
exceptions,
taskStatus.getQueuedPartitionedDrivers(),
taskStatus.getRunningPartitionedDrivers(),
taskStatus.getOutputBufferUtilization(),
taskStatus.isOutputBufferOverutilized(),
taskStatus.getPhysicalWrittenDataSizeInBytes(),
taskStatus.getMemoryReservationInBytes(),
taskStatus.getSystemMemoryReservationInBytes(),
taskStatus.getPeakNodeTotalMemoryReservationInBytes(),
taskStatus.getFullGcCount(),
taskStatus.getFullGcTimeInMillis());
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.connectparticipant.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/connectparticipant-2018-09-07/StartAttachmentUpload"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartAttachmentUploadRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* Describes the MIME file type of the attachment. For a list of supported file types, see <a
* href="https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits"
* >Feature specifications</a> in the <i>Amazon Connect Administrator Guide</i>.
* </p>
*/
private String contentType;
/**
* <p>
* The size of the attachment in bytes.
* </p>
*/
private Long attachmentSizeInBytes;
/**
* <p>
* A case-sensitive name of the attachment being uploaded.
* </p>
*/
private String attachmentName;
/**
* <p>
* A unique case sensitive identifier to support idempotency of request.
* </p>
*/
private String clientToken;
/**
* <p>
* The authentication token associated with the participant's connection.
* </p>
*/
private String connectionToken;
/**
* <p>
* Describes the MIME file type of the attachment. For a list of supported file types, see <a
* href="https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits"
* >Feature specifications</a> in the <i>Amazon Connect Administrator Guide</i>.
* </p>
*
* @param contentType
* Describes the MIME file type of the attachment. For a list of supported file types, see <a href=
* "https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits"
* >Feature specifications</a> in the <i>Amazon Connect Administrator Guide</i>.
*/
public void setContentType(String contentType) {
this.contentType = contentType;
}
/**
* <p>
* Describes the MIME file type of the attachment. For a list of supported file types, see <a
* href="https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits"
* >Feature specifications</a> in the <i>Amazon Connect Administrator Guide</i>.
* </p>
*
* @return Describes the MIME file type of the attachment. For a list of supported file types, see <a
* href="https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits"
* >Feature specifications</a> in the <i>Amazon Connect Administrator Guide</i>.
*/
public String getContentType() {
return this.contentType;
}
/**
* <p>
* Describes the MIME file type of the attachment. For a list of supported file types, see <a
* href="https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits"
* >Feature specifications</a> in the <i>Amazon Connect Administrator Guide</i>.
* </p>
*
* @param contentType
* Describes the MIME file type of the attachment. For a list of supported file types, see <a href=
* "https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits"
* >Feature specifications</a> in the <i>Amazon Connect Administrator Guide</i>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartAttachmentUploadRequest withContentType(String contentType) {
setContentType(contentType);
return this;
}
/**
* <p>
* The size of the attachment in bytes.
* </p>
*
* @param attachmentSizeInBytes
* The size of the attachment in bytes.
*/
public void setAttachmentSizeInBytes(Long attachmentSizeInBytes) {
this.attachmentSizeInBytes = attachmentSizeInBytes;
}
/**
* <p>
* The size of the attachment in bytes.
* </p>
*
* @return The size of the attachment in bytes.
*/
public Long getAttachmentSizeInBytes() {
return this.attachmentSizeInBytes;
}
/**
* <p>
* The size of the attachment in bytes.
* </p>
*
* @param attachmentSizeInBytes
* The size of the attachment in bytes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartAttachmentUploadRequest withAttachmentSizeInBytes(Long attachmentSizeInBytes) {
setAttachmentSizeInBytes(attachmentSizeInBytes);
return this;
}
/**
* <p>
* A case-sensitive name of the attachment being uploaded.
* </p>
*
* @param attachmentName
* A case-sensitive name of the attachment being uploaded.
*/
public void setAttachmentName(String attachmentName) {
this.attachmentName = attachmentName;
}
/**
* <p>
* A case-sensitive name of the attachment being uploaded.
* </p>
*
* @return A case-sensitive name of the attachment being uploaded.
*/
public String getAttachmentName() {
return this.attachmentName;
}
/**
* <p>
* A case-sensitive name of the attachment being uploaded.
* </p>
*
* @param attachmentName
* A case-sensitive name of the attachment being uploaded.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartAttachmentUploadRequest withAttachmentName(String attachmentName) {
setAttachmentName(attachmentName);
return this;
}
/**
* <p>
* A unique case sensitive identifier to support idempotency of request.
* </p>
*
* @param clientToken
* A unique case sensitive identifier to support idempotency of request.
*/
public void setClientToken(String clientToken) {
this.clientToken = clientToken;
}
/**
* <p>
* A unique case sensitive identifier to support idempotency of request.
* </p>
*
* @return A unique case sensitive identifier to support idempotency of request.
*/
public String getClientToken() {
return this.clientToken;
}
/**
* <p>
* A unique case sensitive identifier to support idempotency of request.
* </p>
*
* @param clientToken
* A unique case sensitive identifier to support idempotency of request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartAttachmentUploadRequest withClientToken(String clientToken) {
setClientToken(clientToken);
return this;
}
/**
* <p>
* The authentication token associated with the participant's connection.
* </p>
*
* @param connectionToken
* The authentication token associated with the participant's connection.
*/
public void setConnectionToken(String connectionToken) {
this.connectionToken = connectionToken;
}
/**
* <p>
* The authentication token associated with the participant's connection.
* </p>
*
* @return The authentication token associated with the participant's connection.
*/
public String getConnectionToken() {
return this.connectionToken;
}
/**
* <p>
* The authentication token associated with the participant's connection.
* </p>
*
* @param connectionToken
* The authentication token associated with the participant's connection.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartAttachmentUploadRequest withConnectionToken(String connectionToken) {
setConnectionToken(connectionToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getContentType() != null)
sb.append("ContentType: ").append(getContentType()).append(",");
if (getAttachmentSizeInBytes() != null)
sb.append("AttachmentSizeInBytes: ").append(getAttachmentSizeInBytes()).append(",");
if (getAttachmentName() != null)
sb.append("AttachmentName: ").append(getAttachmentName()).append(",");
if (getClientToken() != null)
sb.append("ClientToken: ").append(getClientToken()).append(",");
if (getConnectionToken() != null)
sb.append("ConnectionToken: ").append(getConnectionToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof StartAttachmentUploadRequest == false)
return false;
StartAttachmentUploadRequest other = (StartAttachmentUploadRequest) obj;
if (other.getContentType() == null ^ this.getContentType() == null)
return false;
if (other.getContentType() != null && other.getContentType().equals(this.getContentType()) == false)
return false;
if (other.getAttachmentSizeInBytes() == null ^ this.getAttachmentSizeInBytes() == null)
return false;
if (other.getAttachmentSizeInBytes() != null && other.getAttachmentSizeInBytes().equals(this.getAttachmentSizeInBytes()) == false)
return false;
if (other.getAttachmentName() == null ^ this.getAttachmentName() == null)
return false;
if (other.getAttachmentName() != null && other.getAttachmentName().equals(this.getAttachmentName()) == false)
return false;
if (other.getClientToken() == null ^ this.getClientToken() == null)
return false;
if (other.getClientToken() != null && other.getClientToken().equals(this.getClientToken()) == false)
return false;
if (other.getConnectionToken() == null ^ this.getConnectionToken() == null)
return false;
if (other.getConnectionToken() != null && other.getConnectionToken().equals(this.getConnectionToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getContentType() == null) ? 0 : getContentType().hashCode());
hashCode = prime * hashCode + ((getAttachmentSizeInBytes() == null) ? 0 : getAttachmentSizeInBytes().hashCode());
hashCode = prime * hashCode + ((getAttachmentName() == null) ? 0 : getAttachmentName().hashCode());
hashCode = prime * hashCode + ((getClientToken() == null) ? 0 : getClientToken().hashCode());
hashCode = prime * hashCode + ((getConnectionToken() == null) ? 0 : getConnectionToken().hashCode());
return hashCode;
}
@Override
public StartAttachmentUploadRequest clone() {
return (StartAttachmentUploadRequest) super.clone();
}
}
| |
/*
* 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.android.apkmodule;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.targetgraph.TargetGraph;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rulekey.AddsToRuleKey;
import com.facebook.buck.core.util.graph.AbstractBreadthFirstTraversal;
import com.facebook.buck.core.util.graph.DirectedAcyclicGraph;
import com.facebook.buck.core.util.graph.MutableDirectedGraph;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.jvm.java.classes.ClasspathTraversal;
import com.facebook.buck.jvm.java.classes.ClasspathTraverser;
import com.facebook.buck.jvm.java.classes.DefaultClasspathTraverser;
import com.facebook.buck.jvm.java.classes.FileLike;
import com.facebook.buck.rules.query.Query;
import com.facebook.buck.util.MoreSuppliers;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Utility class for grouping sets of targets and their dependencies into APK Modules containing
* their exclusive dependencies. Targets that are dependencies of the root target are included in
* the root. Targets that have dependencies in two are more groups are put the APKModule that
* represents the dependent modules minimal cover based on the declared dependencies given. If the
* minimal cover contains more than one APKModule, the target will belong to a new shared APKModule
* that is a dependency of all APKModules in the minimal cover.
*/
public class APKModuleGraph implements AddsToRuleKey {
public static final String ROOT_APKMODULE_NAME = "dex";
private final TargetGraph targetGraph;
@AddToRuleKey private final BuildTarget target;
@AddToRuleKey
private final Optional<ImmutableMap<String, ImmutableList<BuildTarget>>> suppliedSeedConfigMap;
@AddToRuleKey
private final Optional<ImmutableMap<String, ImmutableList<String>>> appModuleDependencies;
@AddToRuleKey private final Optional<List<BuildTarget>> blacklistedModules;
@AddToRuleKey private final Set<String> modulesWithResources;
private final Optional<Set<BuildTarget>> seedTargets;
private final Map<APKModule, Set<BuildTarget>> buildTargetsMap = new HashMap<>();
private final Set<UndeclaredDependency> undeclaredDependencies = new HashSet<>();
private final Supplier<ImmutableMap<BuildTarget, APKModule>> targetToModuleMapSupplier =
MoreSuppliers.memoize(
() -> {
Builder<BuildTarget, APKModule> mapBuilder = ImmutableMap.builder();
new AbstractBreadthFirstTraversal<APKModule>(getGraph().getNodesWithNoIncomingEdges()) {
@Override
public ImmutableSet<APKModule> visit(APKModule node) {
if (node.equals(rootAPKModuleSupplier.get())) {
return ImmutableSet.of();
}
getBuildTargets(node).forEach(input -> mapBuilder.put(input, node));
return getGraph().getOutgoingNodesFor(node);
}
}.start();
return mapBuilder.build();
});
private final Supplier<APKModule> rootAPKModuleSupplier =
MoreSuppliers.memoize(this::generateRootModule);
private final Supplier<DirectedAcyclicGraph<APKModule>> graphSupplier =
MoreSuppliers.memoize(this::generateGraph);
private final Supplier<DirectedAcyclicGraph<String>> declaredDependencyGraphSupplier =
MoreSuppliers.memoize(this::generateDeclaredDependencyGraph);
private final Supplier<DirectedAcyclicGraph<String>> detectedDepAndDeclaredDepGraphSupplier =
MoreSuppliers.memoize(this::generateDetectedDependencyAndDeclaredDependencyGraph);
private final Supplier<ImmutableSet<APKModule>> modulesSupplier =
MoreSuppliers.memoize(
() -> {
ImmutableSet.Builder<APKModule> moduleBuilder = ImmutableSet.builder();
new AbstractBreadthFirstTraversal<APKModule>(getRootAPKModule()) {
@Override
public Iterable<APKModule> visit(APKModule apkModule) throws RuntimeException {
moduleBuilder.add(apkModule);
return getGraph().getIncomingNodesFor(apkModule);
}
}.start();
return moduleBuilder.build();
});
private final Supplier<ImmutableMultimap<BuildTarget, String>> sharedSeedsSupplier =
MoreSuppliers.memoize(this::generateSharedSeeds);
private final Supplier<Optional<ImmutableMap<String, ImmutableList<BuildTarget>>>>
configMapSupplier = MoreSuppliers.memoize(this::generateSeedConfigMap);
private final Supplier<Optional<ImmutableMap<BuildTarget, String>>> seedTargetMapSupplier =
MoreSuppliers.memoize(this::generateSeedTargetMap);
/**
* Constructor for the {@code APKModule} graph generator object that produces a graph with only a
* root module.
*/
public APKModuleGraph(TargetGraph targetGraph, BuildTarget target) {
this(
Optional.empty(),
Optional.empty(),
Optional.empty(),
ImmutableSet.of(),
targetGraph,
target);
}
/**
* Constructor for the {@code APKModule} graph generator object
*
* @param seedConfigMap A map of names to seed targets to use for creating {@code APKModule}.
* @param appModuleDependencies
* <p>a mapping of declared dependencies between module names. If a APKModule <b>m1</b>
* depends on <b>m2</b>, it implies to buck that in order for <b>m1</b> to be available for
* execution <b>m2</b> must be available for use as well. Because of this, we can say that
* including a buck target in <b>m2</b> effectively includes the buck-target in <b>m2's</b>
* dependent <b>m1</b>. In other words, <b>m2</b> covers <b>m1</b>. Therefore, if a buck
* target is required by both these modules, we can safely place it in the minimal cover which
* is the APKModule <b>m2</b>.
* @param blacklistedModules A list of targets that will NOT be included in any module.
* @param targetGraph The full target graph of the build
* @param target The root target to use to traverse the graph
*/
public APKModuleGraph(
Optional<ImmutableMap<String, ImmutableList<BuildTarget>>> seedConfigMap,
Optional<ImmutableMap<String, ImmutableList<String>>> appModuleDependencies,
Optional<List<BuildTarget>> blacklistedModules,
Set<String> modulesWithResources,
TargetGraph targetGraph,
BuildTarget target) {
this.targetGraph = targetGraph;
this.appModuleDependencies = appModuleDependencies;
this.blacklistedModules = blacklistedModules;
this.modulesWithResources = modulesWithResources;
this.target = target;
this.seedTargets = Optional.empty();
this.suppliedSeedConfigMap = seedConfigMap;
}
/**
* Constructor for the {@code APKModule} graph generator object
*
* @param targetGraph The full target graph of the build
* @param target The root target to use to traverse the graph
* @param seedTargets The set of seed targets to use for creating {@code APKModule}.
*/
public APKModuleGraph(
TargetGraph targetGraph, BuildTarget target, Optional<Set<BuildTarget>> seedTargets) {
this.targetGraph = targetGraph;
this.target = target;
this.seedTargets = seedTargets;
this.suppliedSeedConfigMap = Optional.empty();
this.appModuleDependencies = Optional.empty();
this.blacklistedModules = Optional.empty();
this.modulesWithResources = ImmutableSet.of();
}
public ImmutableSortedMap<APKModule, ImmutableSortedSet<APKModule>> toOutgoingEdgesMap() {
return getAPKModules().stream()
.collect(
ImmutableSortedMap.toImmutableSortedMap(
Ordering.natural(),
module -> module,
module -> ImmutableSortedSet.copyOf(getGraph().getOutgoingNodesFor(module))));
}
/**
* Utility method for flattening a list of queries into the a list of the build targets they
* resolve to.
*
* @param queries list of queries, they are expected to have already been resolved
* @return list of build targets queries resolve to joined together
*/
public static Optional<List<BuildTarget>> extractTargetsFromQueries(
Optional<List<Query>> queries) {
if (!queries.isPresent()) {
return Optional.empty();
}
ImmutableList<BuildTarget> targets =
queries.get().stream()
.map(query -> Optional.ofNullable(query.getResolvedQuery()))
.filter(resolution -> resolution.isPresent())
.flatMap(resolution -> resolution.get().stream())
.collect(ImmutableList.toImmutableList());
return Optional.of(targets);
}
private Optional<ImmutableMap<String, ImmutableList<BuildTarget>>> generateSeedConfigMap() {
if (suppliedSeedConfigMap.isPresent()) {
return suppliedSeedConfigMap;
}
if (!seedTargets.isPresent()) {
return Optional.empty();
}
HashMap<String, ImmutableList<BuildTarget>> seedConfigMapMutable = new HashMap<>();
for (BuildTarget seedTarget : seedTargets.get()) {
String moduleName = generateNameFromTarget(seedTarget);
seedConfigMapMutable.put(moduleName, ImmutableList.of(seedTarget));
}
ImmutableMap<String, ImmutableList<BuildTarget>> seedConfigMapImmutable =
ImmutableMap.copyOf(seedConfigMapMutable);
return Optional.of(seedConfigMapImmutable);
}
private Optional<ImmutableMap<BuildTarget, String>> generateSeedTargetMap() {
if (suppliedSeedConfigMap.isPresent()) {
final Map<BuildTarget, String> seedTargetMap = new HashMap<>();
for (final ImmutableMap.Entry<String, ImmutableList<BuildTarget>> suppliedSeedConfig :
suppliedSeedConfigMap.get().entrySet()) {
for (final BuildTarget seedTarget : suppliedSeedConfig.getValue()) {
seedTargetMap.put(seedTarget, suppliedSeedConfig.getKey());
}
}
return Optional.of(ImmutableMap.copyOf(seedTargetMap));
}
if (!seedTargets.isPresent()) {
return Optional.empty();
}
final Map<BuildTarget, String> seedTargetMap = new HashMap<>();
for (final BuildTarget seedTarget : seedTargets.get()) {
seedTargetMap.put(seedTarget, generateNameFromTarget(seedTarget));
}
return Optional.of(ImmutableMap.copyOf(seedTargetMap));
}
/**
* Lazy generate the graph on first use
*
* @return the DAG representing APKModules and their dependency relationships
*/
public DirectedAcyclicGraph<APKModule> getGraph() {
return graphSupplier.get();
}
/**
* Lazy generate the declared dependency graph.
*
* @return the DAG representing the declared dependency relationship of declared app module
* configurations.
*/
private DirectedAcyclicGraph<String> getDeclaredDependencyGraph() {
return declaredDependencyGraphSupplier.get();
}
/**
* Lazy generate the detected dep and declared dependency graph. Undeclared dependencies are
* detected and automatically added to this DAG.
*
* @return the DAG representing the declared dependency relationship of declared app module
* configurations.
*/
private DirectedAcyclicGraph<String> getDetectedDepAndDeclaredDepGraph() {
return detectedDepAndDeclaredDepGraphSupplier.get();
}
/**
* Get the APKModule representing the core application that is always included in the apk
*
* @return the root APK Module
*/
public APKModule getRootAPKModule() {
return rootAPKModuleSupplier.get();
}
public ImmutableSet<APKModule> getAPKModules() {
return modulesSupplier.get();
}
public Optional<ImmutableMap<String, ImmutableList<BuildTarget>>> getSeedConfigMap() {
verifyNoSharedSeeds();
return configMapSupplier.get();
}
public Optional<ImmutableMap<BuildTarget, String>> getSeedTargetMap() {
return seedTargetMapSupplier.get();
}
/**
* Get the Module that contains the given target
*
* @param target target to serach for in modules
* @return the module that contains the target
*/
public APKModule findModuleForTarget(BuildTarget target) {
APKModule module = targetToModuleMapSupplier.get().get(target);
return (module == null ? rootAPKModuleSupplier.get() : module);
}
/**
* Get the Module that should contain the resources for the given target
*
* @param target target to serach for in modules
* @return the module that contains the target
*/
public APKModule findResourceModuleForTarget(BuildTarget target) {
APKModule module = targetToModuleMapSupplier.get().get(target);
return (module == null || !module.hasResources()) ? rootAPKModuleSupplier.get() : module;
}
public Optional<List<BuildTarget>> getBlacklistedModules() {
return blacklistedModules;
}
/**
* Group the classes in the input jars into a multimap based on the APKModule they belong to
*
* @param apkModuleToJarPathMap the mapping of APKModules to the path for the jar files
* @param translatorFunction function used to translate the class names to obfuscated names
* @param filesystem filesystem representation for resolving paths
* @return The mapping of APKModules to the class names they contain
* @throws IOException
*/
public static ImmutableMultimap<APKModule, String> getAPKModuleToClassesMap(
ImmutableMultimap<APKModule, Path> apkModuleToJarPathMap,
Function<String, String> translatorFunction,
ProjectFilesystem filesystem)
throws IOException {
ImmutableMultimap.Builder<APKModule, String> builder = ImmutableSetMultimap.builder();
if (!apkModuleToJarPathMap.isEmpty()) {
for (APKModule dexStore : apkModuleToJarPathMap.keySet()) {
for (Path jarFilePath : apkModuleToJarPathMap.get(dexStore)) {
ClasspathTraverser classpathTraverser = new DefaultClasspathTraverser();
classpathTraverser.traverse(
new ClasspathTraversal(
ImmutableSet.of(jarFilePath),
filesystem.getRootPath(),
filesystem.getIgnoredPaths()) {
@Override
public void visit(FileLike entry) {
if (!entry.getRelativePath().endsWith(".class")) {
// ignore everything but class files in the jar.
return;
}
String classpath = entry.getRelativePath().replaceAll("\\.class$", "");
if (translatorFunction.apply(classpath) != null) {
builder.put(dexStore, translatorFunction.apply(classpath));
}
}
});
}
}
}
return builder.build();
}
/**
* Generate the graph by identifying root targets, then marking targets with the seeds they are
* reachable with, then consolidating the targets reachable by multiple seeds into shared modules
*
* @return The graph of APKModules with edges representing dependencies between modules
*/
private DirectedAcyclicGraph<APKModule> generateGraph() {
MutableDirectedGraph<APKModule> apkModuleGraph = new MutableDirectedGraph<>();
apkModuleGraph.addNode(rootAPKModuleSupplier.get());
if (getSeedConfigMap().isPresent()) {
Multimap<BuildTarget, String> targetToContainingApkModulesMap =
mapTargetsToContainingModules();
generateSharedModules(apkModuleGraph, targetToContainingApkModulesMap);
// add declared dependencies as well.
Map<String, APKModule> nameToAPKModules = new HashMap<>();
for (APKModule node : apkModuleGraph.getNodes()) {
nameToAPKModules.put(node.getName(), node);
}
final DirectedAcyclicGraph<String> detectedDepAndDeclaredDepGraph =
getDetectedDepAndDeclaredDepGraph();
for (String source : detectedDepAndDeclaredDepGraph.getNodes()) {
for (String sink : detectedDepAndDeclaredDepGraph.getOutgoingNodesFor(source)) {
apkModuleGraph.addEdge(nameToAPKModules.get(source), nameToAPKModules.get(sink));
}
}
}
return new DirectedAcyclicGraph<>(apkModuleGraph);
}
private DirectedAcyclicGraph<String> generateDetectedDependencyAndDeclaredDependencyGraph() {
final DirectedAcyclicGraph<String> declaredDependencies = generateDeclaredDependencyGraph();
final DirectedAcyclicGraph.Builder<String> graph = DirectedAcyclicGraph.serialBuilder();
for (final String node : declaredDependencies.getNodes()) {
graph.addNode(node);
for (final String outgoingNode : declaredDependencies.getOutgoingNodesFor(node)) {
graph.addEdge(node, outgoingNode);
}
}
for (final UndeclaredDependency undeclaredDependency : undeclaredDependencies) {
graph.addEdge(undeclaredDependency.sourceModule, undeclaredDependency.depModule);
}
return graph.build();
}
private DirectedAcyclicGraph<String> generateDeclaredDependencyGraph() {
DirectedAcyclicGraph.Builder<String> declaredDependencyGraph =
DirectedAcyclicGraph.serialBuilder();
if (appModuleDependencies.isPresent()) {
for (Map.Entry<String, ImmutableList<String>> moduleDependencies :
appModuleDependencies.get().entrySet()) {
for (String moduleDep : moduleDependencies.getValue()) {
declaredDependencyGraph.addEdge(moduleDependencies.getKey(), moduleDep);
}
}
}
DirectedAcyclicGraph<String> result = declaredDependencyGraph.build();
verifyNoUnrecognizedModulesInDependencyGraph(result);
return result;
}
private void verifyNoUnrecognizedModulesInDependencyGraph(
DirectedAcyclicGraph<String> dependencyGraph) {
Set<String> configModules =
getSeedConfigMap().isPresent() ? getSeedConfigMap().get().keySet() : new HashSet<>();
Set<String> unrecognizedModules = new HashSet<>(dependencyGraph.getNodes());
unrecognizedModules.removeAll(configModules);
if (!unrecognizedModules.isEmpty()) {
StringBuilder errorString =
new StringBuilder("Unrecognized App Modules in Dependency Graph: ");
for (String module : unrecognizedModules) {
errorString.append(module).append(" ");
}
throw new IllegalStateException(errorString.toString());
}
}
/**
* This walks through the target graph starting from the root target and adds all reachable
* targets that are not seed targets to the root module
*
* @return The root APK Module
*/
private APKModule generateRootModule() {
Set<BuildTarget> rootTargets = new HashSet<>();
if (targetGraph != TargetGraph.EMPTY) {
Set<TargetNode<?>> rootNodes = new HashSet<>();
rootNodes.add(targetGraph.get(target));
if (blacklistedModules.isPresent()) {
for (BuildTarget targetModule : blacklistedModules.get()) {
rootNodes.add(targetGraph.get(targetModule));
rootTargets.add(targetModule);
}
}
new AbstractBreadthFirstTraversal<TargetNode<?>>(rootNodes) {
@Override
public Iterable<TargetNode<?>> visit(TargetNode<?> node) {
ImmutableSet.Builder<TargetNode<?>> depsBuilder = ImmutableSet.builder();
for (BuildTarget depTarget : node.getBuildDeps()) {
if (!isSeedTarget(depTarget)) {
depsBuilder.add(targetGraph.get(depTarget));
rootTargets.add(depTarget);
}
}
return depsBuilder.build();
}
}.start();
}
APKModule rootModule = APKModule.of(ROOT_APKMODULE_NAME, true);
buildTargetsMap.put(rootModule, ImmutableSet.copyOf(rootTargets));
return rootModule;
}
/**
* For each seed target, find its reachable targets and mark them in a multimap as being reachable
* by that module for later sorting into exclusive and shared targets
*
* @return the Multimap containing targets and the seed modules that contain them
*/
private Multimap<BuildTarget, String> mapTargetsToContainingModules() {
final DirectedAcyclicGraph<String> declaredDependencies = getDeclaredDependencyGraph();
final DirectedAcyclicGraph.Builder<String> moduleGraph = DirectedAcyclicGraph.serialBuilder();
Multimap<BuildTarget, String> targetToContainingApkModuleNameMap =
MultimapBuilder.treeKeys().treeSetValues().build();
for (Map.Entry<String, ImmutableList<BuildTarget>> seedConfig :
getSeedConfigMap().get().entrySet()) {
final String seedModuleName = seedConfig.getKey();
for (BuildTarget seedTarget : seedConfig.getValue()) {
final Set<BuildTarget> seedBuildDeps = targetGraph.get(seedTarget).getBuildDeps();
targetToContainingApkModuleNameMap.put(seedTarget, seedModuleName);
new AbstractBreadthFirstTraversal<TargetNode<?>>(targetGraph.get(seedTarget)) {
@Override
public ImmutableSet<TargetNode<?>> visit(TargetNode<?> node) {
ImmutableSet.Builder<TargetNode<?>> depsBuilder = ImmutableSet.builder();
for (final BuildTarget depTarget : node.getBuildDeps()) {
final String depTargetModuleName = getSeedModule(depTarget);
if (depTargetModuleName != null) {
moduleGraph.addNode(depTargetModuleName);
}
if (!isInRootModule(depTarget)) {
if (isSeedTarget(depTarget)) {
if (depTargetModuleName != null
&& depTargetModuleName != seedModuleName
&& seedBuildDeps.contains(depTarget)) {
// Mark depTargetModuleName as a dependency of seedModuleName
moduleGraph.addEdge(seedModuleName, depTargetModuleName);
}
} else {
depsBuilder.add(targetGraph.get(depTarget));
targetToContainingApkModuleNameMap.put(depTarget, seedModuleName);
}
}
}
return depsBuilder.build();
}
}.start();
}
}
undeclaredDependencies.addAll(getUndeclaredDeps(moduleGraph.build(), declaredDependencies));
// Now to generate the minimal covers of APKModules for each set of APKModules that contain
// a buildTarget
Multimap<BuildTarget, String> targetModuleEntriesToRemove =
MultimapBuilder.treeKeys().treeSetValues().build();
for (BuildTarget key : targetToContainingApkModuleNameMap.keySet()) {
Collection<String> modulesForTarget = targetToContainingApkModuleNameMap.get(key);
new AbstractBreadthFirstTraversal<String>(modulesForTarget) {
@Override
public Iterable<String> visit(String moduleName) throws RuntimeException {
Collection<String> dependentModules =
declaredDependencies.getIncomingNodesFor(moduleName);
for (String dependent : dependentModules) {
if (modulesForTarget.contains(dependent)) {
targetModuleEntriesToRemove.put(key, dependent);
}
}
return dependentModules;
}
}.start();
}
for (Map.Entry<BuildTarget, String> entryToRemove : targetModuleEntriesToRemove.entries()) {
targetToContainingApkModuleNameMap.remove(entryToRemove.getKey(), entryToRemove.getValue());
}
return targetToContainingApkModuleNameMap;
}
private Set<UndeclaredDependency> getUndeclaredDeps(
final DirectedAcyclicGraph<String> detectedModuleGraph,
final DirectedAcyclicGraph<String> declaredDeps) {
final Set<UndeclaredDependency> undeclaredDependencies = new HashSet<>();
final Set<String> addedModules = new HashSet<>();
final Queue<String> moduleGraphQueue = new LinkedList<>();
moduleGraphQueue.addAll(detectedModuleGraph.getNodesWithNoIncomingEdges());
addedModules.addAll(detectedModuleGraph.getNodesWithNoIncomingEdges());
while (!moduleGraphQueue.isEmpty()) {
final String currentModule = moduleGraphQueue.poll();
final Set<String> outgoingModuleGraphNodes =
detectedModuleGraph.getOutgoingNodesFor(currentModule);
final Set<String> outgoingDeclaredDepNodes = declaredDeps.getOutgoingNodesFor(currentModule);
final Set<String> undeclaredDepNodes =
Sets.difference(outgoingModuleGraphNodes, outgoingDeclaredDepNodes);
if (!undeclaredDepNodes.isEmpty()) {
for (final String undeclaredDepNode : undeclaredDepNodes) {
if (undeclaredDepNode != null) {
undeclaredDependencies.add(new UndeclaredDependency(currentModule, undeclaredDepNode));
}
}
}
for (final String edgeModule : outgoingModuleGraphNodes) {
if (!addedModules.contains(edgeModule)) {
moduleGraphQueue.add(edgeModule);
addedModules.add(edgeModule);
}
}
}
return undeclaredDependencies;
}
/**
* Loop through each of the targets we visited while generating seed modules: If the are exclusive
* to that module, add them to that module. If they are not exclusive to that module, find or
* create an appropriate shared module and fill out its dependencies
*
* @param apkModuleGraph the current graph we're building
* @param targetToContainingApkModulesMap the targets mapped to the seed targets they are
* reachable from
*/
private void generateSharedModules(
MutableDirectedGraph<APKModule> apkModuleGraph,
Multimap<BuildTarget, String> targetToContainingApkModulesMap) {
// Sort the module-covers of all targets to determine shared module names.
TreeSet<TreeSet<String>> sortedContainingModuleSets =
new TreeSet<>(
new Comparator<TreeSet<String>>() {
@Override
public int compare(TreeSet<String> left, TreeSet<String> right) {
int sizeDiff = left.size() - right.size();
if (sizeDiff != 0) {
return sizeDiff;
}
Iterator<String> leftIter = left.iterator();
Iterator<String> rightIter = right.iterator();
while (leftIter.hasNext()) {
String leftElement = leftIter.next();
String rightElement = rightIter.next();
int stringComparison = leftElement.compareTo(rightElement);
if (stringComparison != 0) {
return stringComparison;
}
}
return 0;
}
});
for (Map.Entry<BuildTarget, Collection<String>> entry :
targetToContainingApkModulesMap.asMap().entrySet()) {
TreeSet<String> containingModuleSet = new TreeSet<>(entry.getValue());
sortedContainingModuleSets.add(containingModuleSet);
}
// build modules based on all entries.
Map<ImmutableSet<String>, APKModule> combinedModuleHashToModuleMap = new HashMap<>();
final Set<String> hashedSharedModuleSet = new HashSet<>();
for (TreeSet<String> moduleCover : sortedContainingModuleSets) {
final List<String> moduleCoverList = new ArrayList<>(moduleCover);
Collections.sort(moduleCoverList);
final String joinedModuleName = String.join("_", moduleCoverList);
String moduleName = moduleCoverList.size() > 1 ? "s_" + joinedModuleName : joinedModuleName;
// there is a hard requirement that module names cannot exceed 50 chars.
if (moduleCoverList.size() > 1 && moduleName.length() > 49) {
moduleName = "s_" + String.valueOf(moduleName.hashCode() & 0x7FFFFFFF);
if (hashedSharedModuleSet.contains(moduleName)) {
throw new RuntimeException(
"Collision while hashing shared module name " + joinedModuleName);
}
hashedSharedModuleSet.add(moduleName);
}
APKModule module = APKModule.of(moduleName, modulesWithResources.contains(moduleName));
combinedModuleHashToModuleMap.put(ImmutableSet.copyOf(moduleCover), module);
}
// add Targets per module;
for (Map.Entry<BuildTarget, Collection<String>> entry :
targetToContainingApkModulesMap.asMap().entrySet()) {
ImmutableSet<String> containingModuleSet = ImmutableSet.copyOf(entry.getValue());
for (Map.Entry<ImmutableSet<String>, APKModule> existingEntry :
combinedModuleHashToModuleMap.entrySet()) {
if (existingEntry.getKey().equals(containingModuleSet)) {
getBuildTargets(existingEntry.getValue()).add(entry.getKey());
break;
}
}
}
// Find the seed modules and add them to the graph
Map<String, APKModule> seedModules = new HashMap<>();
for (Map.Entry<ImmutableSet<String>, APKModule> entry :
combinedModuleHashToModuleMap.entrySet()) {
if (entry.getKey().size() == 1) {
APKModule seed = entry.getValue();
apkModuleGraph.addNode(seed);
seedModules.put(entry.getKey().iterator().next(), seed);
apkModuleGraph.addEdge(seed, rootAPKModuleSupplier.get());
}
}
// Find the shared modules and add them to the graph
for (Map.Entry<ImmutableSet<String>, APKModule> entry :
combinedModuleHashToModuleMap.entrySet()) {
if (entry.getKey().size() > 1) {
APKModule shared = entry.getValue();
apkModuleGraph.addNode(shared);
apkModuleGraph.addEdge(shared, rootAPKModuleSupplier.get());
for (String seedName : entry.getKey()) {
apkModuleGraph.addEdge(seedModules.get(seedName), shared);
}
}
}
}
private boolean isInRootModule(BuildTarget depTarget) {
return getBuildTargets(rootAPKModuleSupplier.get()).contains(depTarget);
}
private boolean isSeedTarget(BuildTarget depTarget) {
if (!getSeedConfigMap().isPresent()) {
return false;
}
return getSeedModule(depTarget) != null;
}
private String getSeedModule(final BuildTarget seedTarget) {
return getSeedTargetMap().get().get(seedTarget);
}
private static String generateNameFromTarget(BuildTarget androidModuleTarget) {
String replacementPattern = "[/\\\\#-]";
String shortName =
androidModuleTarget.getShortNameAndFlavorPostfix().replaceAll(replacementPattern, ".");
String name =
androidModuleTarget
.getCellRelativeBasePath()
.getPath()
.toString()
.replaceAll(replacementPattern, ".");
if (name.endsWith(shortName)) {
// return just the base path, ignoring the target name that is the same as its parent
return name;
} else {
return name.isEmpty() ? shortName : name + "." + shortName;
}
}
private void verifyNoSharedSeeds() {
ImmutableMultimap<BuildTarget, String> sharedSeeds = sharedSeedsSupplier.get();
if (!sharedSeeds.isEmpty()) {
StringBuilder errorMessage = new StringBuilder();
for (BuildTarget seed : sharedSeeds.keySet()) {
errorMessage
.append("BuildTarget: ")
.append(seed)
.append(" is used as seed in multiple modules: ");
for (String module : sharedSeeds.get(seed)) {
errorMessage.append(module).append(' ');
}
errorMessage.append('\n');
}
throw new IllegalArgumentException(errorMessage.toString());
}
}
private ImmutableMultimap<BuildTarget, String> generateSharedSeeds() {
Optional<ImmutableMap<String, ImmutableList<BuildTarget>>> seedConfigMap =
configMapSupplier.get();
HashMultimap<BuildTarget, String> sharedSeedMapBuilder = HashMultimap.create();
if (!seedConfigMap.isPresent()) {
return ImmutableMultimap.copyOf(sharedSeedMapBuilder);
}
// first: invert the seedConfigMap to get BuildTarget -> Seeds
for (Map.Entry<String, ImmutableList<BuildTarget>> entry : seedConfigMap.get().entrySet()) {
for (BuildTarget buildTarget : entry.getValue()) {
sharedSeedMapBuilder.put(buildTarget, entry.getKey());
}
}
// second: remove keys that have only one value.
Set<BuildTarget> nonSharedSeeds = new HashSet<>();
for (BuildTarget buildTarget : sharedSeedMapBuilder.keySet()) {
if (sharedSeedMapBuilder.get(buildTarget).size() <= 1) {
nonSharedSeeds.add(buildTarget);
}
}
for (BuildTarget targetToRemove : nonSharedSeeds) {
sharedSeedMapBuilder.removeAll(targetToRemove);
}
return ImmutableMultimap.copyOf(sharedSeedMapBuilder);
}
public Set<BuildTarget> getBuildTargets(APKModule module) {
return buildTargetsMap.computeIfAbsent(module, (m) -> new HashSet<>());
}
private class UndeclaredDependency {
final String sourceModule;
final String depModule;
public UndeclaredDependency(final String sourceModule, final String depModule) {
this.sourceModule = sourceModule;
this.depModule = depModule;
}
@Override
public String toString() {
return "sourceModule:" + sourceModule + " depModule:" + depModule;
}
}
}
| |
/*
* 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.android;
import static com.facebook.buck.jvm.java.JavaLibraryClasspathProvider.getClasspathDeps;
import com.facebook.buck.android.AndroidBinary.ExopackageMode;
import com.facebook.buck.android.AndroidBinary.PackageType;
import com.facebook.buck.android.ResourcesFilter.ResourceCompressionMode;
import com.facebook.buck.android.aapt.RDotTxtEntry.RType;
import com.facebook.buck.cxx.CxxBuckConfig;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.jvm.java.JavaBuckConfig;
import com.facebook.buck.jvm.java.JavaLibrary;
import com.facebook.buck.jvm.java.JavacFactory;
import com.facebook.buck.jvm.java.JavacOptions;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.CommonDescriptionArg;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.HasDeclaredDeps;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.coercer.BuildConfigFields;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.common.util.concurrent.ListeningExecutorService;
import java.util.EnumSet;
import java.util.Optional;
import org.immutables.value.Value;
public class AndroidInstrumentationApkDescription
implements Description<AndroidInstrumentationApkDescriptionArg> {
private final JavaBuckConfig javaBuckConfig;
private final ProGuardConfig proGuardConfig;
private final JavacOptions javacOptions;
private final ImmutableMap<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform> nativePlatforms;
private final ListeningExecutorService dxExecutorService;
private final CxxBuckConfig cxxBuckConfig;
private final DxConfig dxConfig;
public AndroidInstrumentationApkDescription(
JavaBuckConfig javaBuckConfig,
ProGuardConfig proGuardConfig,
JavacOptions androidJavacOptions,
ImmutableMap<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform> nativePlatforms,
ListeningExecutorService dxExecutorService,
CxxBuckConfig cxxBuckConfig,
DxConfig dxConfig) {
this.javaBuckConfig = javaBuckConfig;
this.proGuardConfig = proGuardConfig;
this.javacOptions = androidJavacOptions;
this.nativePlatforms = nativePlatforms;
this.dxExecutorService = dxExecutorService;
this.cxxBuckConfig = cxxBuckConfig;
this.dxConfig = dxConfig;
}
@Override
public Class<AndroidInstrumentationApkDescriptionArg> getConstructorArgType() {
return AndroidInstrumentationApkDescriptionArg.class;
}
@Override
public BuildRule createBuildRule(
TargetGraph targetGraph,
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
BuildRuleResolver resolver,
CellPathResolver cellRoots,
AndroidInstrumentationApkDescriptionArg args)
throws NoSuchBuildTargetException {
BuildRule installableApk = resolver.getRule(args.getApk());
if (!(installableApk instanceof HasInstallableApk)) {
throw new HumanReadableException(
"In %s, apk='%s' must be an android_binary() or apk_genrule() but was %s().",
buildTarget, installableApk.getFullyQualifiedName(), installableApk.getType());
}
AndroidBinary apkUnderTest =
ApkGenruleDescription.getUnderlyingApk((HasInstallableApk) installableApk);
ImmutableSortedSet<JavaLibrary> rulesToExcludeFromDex =
new ImmutableSortedSet.Builder<>(Ordering.<JavaLibrary>natural())
.addAll(apkUnderTest.getRulesToExcludeFromDex())
.addAll(getClasspathDeps(apkUnderTest.getClasspathDeps()))
.build();
// TODO(natthu): Instrumentation APKs should also exclude native libraries and assets from the
// apk under test.
AndroidPackageableCollection.ResourceDetails resourceDetails =
apkUnderTest.getAndroidPackageableCollection().getResourceDetails();
ImmutableSet<BuildTarget> resourcesToExclude =
ImmutableSet.copyOf(
Iterables.concat(
resourceDetails.getResourcesWithNonEmptyResDir(),
resourceDetails.getResourcesWithEmptyResButNonEmptyAssetsDir()));
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
AndroidBinaryGraphEnhancer graphEnhancer =
new AndroidBinaryGraphEnhancer(
buildTarget,
projectFilesystem,
params,
targetGraph,
resolver,
cellRoots,
AndroidBinary.AaptMode.AAPT1,
ResourceCompressionMode.DISABLED,
FilterResourcesStep.ResourceFilter.EMPTY_FILTER,
/* bannedDuplicateResourceTypes */ EnumSet.noneOf(RType.class),
/* resourceUnionPackage */ Optional.empty(),
/* locales */ ImmutableSet.of(),
args.getManifest(),
PackageType.INSTRUMENTED,
apkUnderTest.getCpuFilters(),
/* shouldBuildStringSourceMap */ false,
/* shouldPreDex */ false,
DexSplitMode.NO_SPLIT,
rulesToExcludeFromDex
.stream()
.map(BuildRule::getBuildTarget)
.collect(MoreCollectors.toImmutableSet()),
resourcesToExclude,
/* skipCrunchPngs */ false,
args.getIncludesVectorDrawables(),
/* noAutoVersionResources */ false,
javaBuckConfig,
JavacFactory.create(ruleFinder, javaBuckConfig, null),
javacOptions,
EnumSet.noneOf(ExopackageMode.class),
/* buildConfigValues */ BuildConfigFields.empty(),
/* buildConfigValuesFile */ Optional.empty(),
/* xzCompressionLevel */ Optional.empty(),
/* trimResourceIds */ false,
/* keepResourcePattern */ Optional.empty(),
nativePlatforms,
/* nativeLibraryMergeMap */ Optional.empty(),
/* nativeLibraryMergeGlue */ Optional.empty(),
/* nativeLibraryMergeCodeGenerator */ Optional.empty(),
/* nativeLibraryProguardConfigGenerator */ Optional.empty(),
Optional.empty(),
AndroidBinary.RelinkerMode.DISABLED,
dxExecutorService,
apkUnderTest.getManifestEntries(),
cxxBuckConfig,
new APKModuleGraph(targetGraph, buildTarget, Optional.empty()),
dxConfig,
/* postFilterResourcesCommands */ Optional.empty());
AndroidGraphEnhancementResult enhancementResult = graphEnhancer.createAdditionalBuildables();
return new AndroidInstrumentationApk(
buildTarget,
projectFilesystem,
params
.withExtraDeps(enhancementResult.getFinalDeps())
.copyAppendingExtraDeps(rulesToExcludeFromDex),
ruleFinder,
proGuardConfig.getProguardJarOverride(),
proGuardConfig.getProguardMaxHeapSize(),
proGuardConfig.getProguardAgentPath(),
apkUnderTest,
rulesToExcludeFromDex,
enhancementResult,
dxExecutorService);
}
@BuckStyleImmutable
@Value.Immutable
interface AbstractAndroidInstrumentationApkDescriptionArg
extends CommonDescriptionArg, HasDeclaredDeps {
SourcePath getManifest();
BuildTarget getApk();
@Value.Default
default boolean getIncludesVectorDrawables() {
return false;
}
}
}
| |
package com.lady.viktoria.lightdrip.services;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import com.lady.viktoria.lightdrip.RealmActions.TransmitterRecord;
import com.lady.viktoria.lightdrip.utils.ConvertHexString;
import com.lady.viktoria.lightdrip.utils.ConvertTxID;
import com.polidea.rxandroidble.RxBleClient;
import com.polidea.rxandroidble.RxBleConnection;
import com.polidea.rxandroidble.RxBleDevice;
import com.polidea.rxandroidble.internal.RxBleLog;
import com.polidea.rxandroidble.utils.ConnectionSharingAdapter;
import net.grandcentrix.tray.AppPreferences;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.subjects.PublishSubject;
import xiaofei.library.hermeseventbus.HermesEventBus;
public class CgmBleService extends Service {
private final static String TAG = CgmBleService.class.getSimpleName();
public final static UUID UUID_BG_MEASUREMENT = UUID.fromString(GattAttributes.HM_RX_TX);
public final static String ACTION_BLE_CONNECTED = "ACTION_BLE_CONNECTED";
public final static String ACTION_BLE_DISCONNECTED = "ACTION_BLE_DISCONNECTED";
public final static String ACTION_BLE_DATA_AVAILABLE = "ACTION_BLE_DATA_AVAILABLE";
public final static String BEACON_SNACKBAR = "BEACON_SNACKBAR";
private RxBleClient rxBleClient;
private RxBleDevice bleDevice;
private AppPreferences mTrayPreferences;
private PublishSubject<Void> disconnectTriggerSubject = PublishSubject.create();
private Observable<RxBleConnection> connectionObservable;
Handler handler;
Subscription writeNotificationSubscription;
Subscription writeCharacteristicSubscription;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
//startForeground(R.string.app_name, new Notification());
HermesEventBus.getDefault().init(this);
handler = new Handler();
// get mac address from selected wixelbridge
mTrayPreferences = new AppPreferences(this);
final String BTDeviceAddress = mTrayPreferences.getString("BT_MAC_Address", "00:00:00:00:00:00");
//init rxBleClient
rxBleClient = RxBleClient.create(this);
bleDevice = rxBleClient.getBleDevice(BTDeviceAddress);
// logging for RxBleClient
RxBleClient.setLogLevel(RxBleLog.INFO);
connectionObservable = bleDevice
.establishConnection(this, true)
//.takeUntil(disconnectTriggerSubject)
.doOnUnsubscribe(this::clearSubscription)
.compose(new ConnectionSharingAdapter());
bleDevice.observeConnectionStateChanges()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onConnectionStateChange);
connect();
return START_STICKY;
}
public void connect() {
if (isConnected()) {
//triggerDisconnect();
} else {
connectionObservable.subscribe(this::onConnectionReceived, this::onConnectionFailure);
}
}
public void writeCharacteristic(final ByteBuffer byteBuffer) {
byte[] bytearray = byteBuffer.array();
if (isConnected()) {
writeCharacteristicSubscription = connectionObservable
.flatMap(rxBleConnection -> rxBleConnection
.writeCharacteristic(UUID_BG_MEASUREMENT, bytearray))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(bytes -> onWriteSuccess(), this::onWriteFailure);
}
}
public void writeNotificationCharacteristic() {
if (isConnected()) {
writeNotificationSubscription = connectionObservable
.flatMap(rxBleConnection -> rxBleConnection.setupNotification(UUID_BG_MEASUREMENT))
.doOnNext(notificationObservable -> runOnUiThread(this::notificationHasBeenSetUp))
.flatMap(notificationObservable -> notificationObservable)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onNotificationReceived, this::onNotificationSetupFailure);
}
}
private void runOnUiThread(Runnable runnable) {
handler.post(runnable);
}
private boolean isConnected() {
return bleDevice.getConnectionState() == RxBleConnection.RxBleConnectionState.CONNECTED;
}
private void clearSubscription() {
updateUI();
}
private void triggerDisconnect() {
disconnectTriggerSubject.onNext(null);
}
private void updateUI() {
// connectButton.setText(isConnected() ? getString(R.string.disconnect) : getString(R.string.connect));
// readButton.setEnabled(isConnected());
// writeButton.setEnabled(isConnected());
// notifyButton.setEnabled(isConnected());
}
private void onConnectionStateChange(RxBleConnection.RxBleConnectionState newState) {
if (newState == RxBleConnection.RxBleConnectionState.CONNECTING) {
Log.v(TAG, "connectionstat CONNECTING");
}
if (newState == RxBleConnection.RxBleConnectionState.DISCONNECTING) {
Log.v(TAG, "connectionstat DISCONNECTING");
}
if (newState == RxBleConnection.RxBleConnectionState.CONNECTED) {
HermesEventBus.getDefault().post(ACTION_BLE_CONNECTED);
writeNotificationCharacteristic();
}
if (newState == RxBleConnection.RxBleConnectionState.DISCONNECTED) {
Log.v(TAG, "connectionstat DISCONNECTED");
HermesEventBus.getDefault().post(ACTION_BLE_DISCONNECTED);
try {
writeNotificationSubscription.unsubscribe();
} catch (Exception e) {
Log.v(TAG, "connectionstat DISCONNECTED " + e.getMessage());
}
}
}
private void onConnectionFailure(Throwable throwable) {
//noinspection ConstantConditions
Log.v(TAG, "Connection Failure");
connect();
}
private void onConnectionReceived(RxBleConnection connection) {
//noinspection ConstantConditions
Log.v(TAG, "Hey, connection has been established!");
}
private void onWriteSuccess() {
//noinspection ConstantConditions
Log.v(TAG, "Write success");
try {
writeCharacteristicSubscription.unsubscribe();
} catch (Exception e) {
Log.v(TAG, "onWriteSuccess " + e.getMessage());
}
}
private void onWriteFailure(Throwable throwable) {
//noinspection ConstantConditions
Log.v(TAG, "Write error: " + throwable);
}
private void onNotificationReceived(byte[] bytes) {
//noinspection ConstantConditions
Log.v(TAG, "Change: " + ConvertHexString.bytesToHex(bytes));
long timestamp = new Date().getTime();
int packatlength = bytes[0];
if (packatlength >= 2) {
if (CheckTransmitterID(bytes, bytes.length)) {
TransmitterRecord.create(bytes, bytes.length, timestamp);
SimpleDateFormat databaseDateTimeFormate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String currentDateandTime = databaseDateTimeFormate.format(timestamp);
mTrayPreferences.put("BLE_LAST_CONNECTED", currentDateandTime);
HermesEventBus.getDefault().post(ACTION_BLE_DATA_AVAILABLE);
} else {
HermesEventBus.getDefault().post(BEACON_SNACKBAR);
}
} else if (packatlength <= 1) {
writeAcknowledgePacket();
}
}
private void onNotificationSetupFailure(Throwable throwable) {
//noinspection ConstantConditions
Log.v(TAG, "Notifications error: " + throwable);
}
private void notificationHasBeenSetUp() {
//noinspection ConstantConditions
Log.v(TAG, "Notifications has been set up");
}
public boolean CheckTransmitterID(byte[] packet, int len) {
int DexSrc;
int TransmitterID;
ByteBuffer tmpBuffer;
final String TxId = mTrayPreferences.getString("Transmitter_Id", "00000");
TransmitterID = ConvertTxID.convertSrc(TxId);
tmpBuffer = ByteBuffer.allocate(len);
tmpBuffer.order(ByteOrder.LITTLE_ENDIAN);
tmpBuffer.put(packet, 0, len);
if (packet[0] == 7) {
Log.i(TAG, "Received Beacon packet.");
HermesEventBus.getDefault().post(BEACON_SNACKBAR);
writeTxIdPacket(TransmitterID);
return false;
} else if (packet[0] >= 21 && packet[1] == 0) {
Log.i(TAG, "Received Data packet");
DexSrc = tmpBuffer.getInt(12);
TransmitterID = ConvertTxID.convertSrc(TxId);
if (Integer.compare(DexSrc, TransmitterID) != 0) {
writeTxIdPacket(TransmitterID);
return false;
} else {
return true;
}
}
return false;
}
private void writeTxIdPacket(int TransmitterID) {
Log.v(TAG, "try to set transmitter ID");
ByteBuffer txidMessage = ByteBuffer.allocate(6);
txidMessage.order(ByteOrder.LITTLE_ENDIAN);
txidMessage.put(0, (byte) 0x06);
txidMessage.put(1, (byte) 0x01);
txidMessage.putInt(2, TransmitterID);
writeCharacteristic(txidMessage);
}
private void writeAcknowledgePacket() {
Log.d(TAG, "Sending Acknowledge Packet, to put wixel to sleep");
ByteBuffer ackMessage = ByteBuffer.allocate(2);
ackMessage.put(0, (byte) 0x02);
ackMessage.put(1, (byte) 0xF0);
writeCharacteristic(ackMessage);
}
@Override
public void onDestroy() {
super.onDestroy();
Intent broadcastIntent = new Intent("com.lady.viktoria.lightdrip.services.RestartCgmBleService");
sendBroadcast(broadcastIntent);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
| |
/*
* Copyright (c) 2016, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.oracle.truffle.llvm.parser.bc.impl.parser.bc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import com.oracle.truffle.llvm.parser.bc.impl.parser.bc.blocks.Block;
import com.oracle.truffle.llvm.parser.bc.impl.parser.bc.records.UserRecordArrayOperand;
import com.oracle.truffle.llvm.parser.bc.impl.parser.bc.records.UserRecordBuilder;
import com.oracle.truffle.llvm.parser.bc.impl.parser.bc.records.UserRecordOperand;
import com.oracle.truffle.llvm.parser.bc.impl.parser.listeners.ParserListener;
import com.oracle.truffle.llvm.parser.bc.impl.parser.util.Pair;
public class Parser {
private static final Operation DEFINE_ABBREV = (parser) -> {
ParserResult result = parser.read(Primitive.ABBREVIATED_RECORD_OPERANDS);
long count = result.getValue();
List<UserRecordOperand> operands = new ArrayList<>();
for (long i = 0; i < count;) {
Pair<ParserResult, UserRecordOperand> pair = UserRecordOperand.parse(result.getParser());
result = pair.getItem1();
UserRecordOperand operand = pair.getItem2();
if (operand instanceof UserRecordArrayOperand) {
pair = UserRecordOperand.parse(result.getParser());
result = pair.getItem1();
operand = pair.getItem2();
operands.add(new UserRecordArrayOperand(operand));
i += 2;
} else {
operands.add(operand);
i++;
}
}
return result.getParser().operation(new UserRecordBuilder(operands));
};
private static final Operation END_BLOCK = Parser::exit;
private static final Operation ENTER_SUBBLOCK = (parser) -> {
ParserResult result = parser.read(Primitive.SUBBLOCK_ID);
long id = result.getValue();
result = result.getParser().read(Primitive.SUBBLOCK_ID_SIZE);
long idsize = result.getValue();
Parser p = result.getParser().alignInt();
result = p.read(Integer.SIZE);
long size = result.getValue();
return result.getParser().enter(id, size, idsize);
};
private static final Operation UNABBREV_RECORD = (parser) -> {
ParserResult result = parser.read(Primitive.UNABBREVIATED_RECORD_ID);
long id = result.getValue();
result = result.getParser().read(Primitive.UNABBREVIATED_RECORD_OPS);
long count = result.getValue();
long[] operands = new long[(int) count];
for (long i = 0; i < count; i++) {
result = result.getParser().read(Primitive.UNABBREVIATED_RECORD_OPERAND);
operands[(int) i] = result.getValue();
}
return result.getParser().handleRecord(id, operands);
};
private static final Operation[] DEFAULT_OPERATIONS = new Operation[]{
END_BLOCK,
ENTER_SUBBLOCK,
DEFINE_ABBREV,
UNABBREV_RECORD
};
private static final String CHAR6 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._";
protected final Bitstream stream;
protected final Block block;
protected final ParserListener listener;
protected final Parser parent;
protected final Operation[][] operations;
protected final long idsize;
protected final long offset;
public Parser(Bitstream stream, ParserListener listener) {
this(Objects.requireNonNull(stream), Objects.requireNonNull(Block.ROOT), Objects.requireNonNull(listener), null, new Operation[][]{DEFAULT_OPERATIONS}, 2, 0);
}
public Parser(Bitstream stream, ParserListener listener, long offset) {
this(Objects.requireNonNull(stream), Objects.requireNonNull(Block.ROOT), Objects.requireNonNull(listener), null, new Operation[][]{DEFAULT_OPERATIONS}, 2, offset);
}
protected Parser(Parser parser) {
this(parser.stream, parser.block, parser.listener, parser.parent, parser.operations, parser.idsize, parser.offset);
}
protected Parser(Bitstream stream, Block block, ParserListener listener, Parser parent, Operation[][] operations, long idsize, long offset) {
this.stream = stream;
this.block = block;
this.listener = listener;
this.parent = parent;
this.operations = operations;
this.idsize = idsize;
this.offset = offset;
}
protected Parser instantiate(@SuppressWarnings("unused") Parser argParser, Bitstream argStream, Block argBlock, ParserListener argListener, Parser argParent, Operation[][] argOperations,
long argIdSize, long argOffset) {
return new Parser(argStream, argBlock, argListener, argParent, argOperations, argIdSize, argOffset);
}
private Parser alignInt() {
long mask = Integer.SIZE - 1;
if ((offset & mask) != 0) {
return offset((offset & ~mask) + Integer.SIZE);
}
return this;
}
public Parser enter(long id, long size, long argIdSize) {
Block subblock = Block.lookup(id);
if (subblock == null) {
// Cannot find block so just skip it
return offset(getOffset() + size * Integer.SIZE);
} else {
return subblock.getParser(instantiate(this, stream, subblock, listener.enter(subblock), this, operations, argIdSize, getOffset()));
}
}
public Parser exit() {
listener.exit();
return getParent().offset(alignInt().getOffset());
}
public long getOffset() {
return offset;
}
public Parser offset(long argOffset) {
return instantiate(this, stream, block, listener, parent, operations, idsize, argOffset);
}
public Operation getOperation(long id) {
return getOperations(block.getId())[(int) id];
}
public Parser operation(Operation operation) {
return operation(block.getId(), operation, false);
}
protected Parser operation(long id, Operation operation, boolean persist) {
Operation[] oldOps = getOperations(id);
Operation[] newOps = Arrays.copyOf(oldOps, oldOps.length + 1);
newOps[oldOps.length] = operation;
Operation[][] ops = Arrays.copyOf(operations, Math.max(((int) id) + 1, operations.length));
ops[(int) id] = newOps;
Parser par = parent;
if (persist) {
par = parent.operation(id, operation, parent.parent != null);
}
return instantiate(this, stream, block, listener, par, ops, idsize, offset);
}
private Operation[] getOperations(long blockid) {
if (blockid < 0 || blockid >= operations.length || operations[(int) blockid] == null) {
return DEFAULT_OPERATIONS;
}
return operations[(int) blockid];
}
public Parser getParent() {
return parent;
}
public Parser handleRecord(long id, long[] operands) {
listener.record(id, operands);
return this;
}
public ParserResult read(long bits) {
long value = stream.read(offset, bits);
return new ParserResult(offset(offset + bits), value);
}
public ParserResult read(Primitive primitive) {
if (primitive.isFixed()) {
return read(primitive.getBits());
} else {
return readVBR(primitive.getBits());
}
}
public ParserResult readChar() {
char value = CHAR6.charAt((int) stream.read(offset, Primitive.CHAR6.getBits()));
return new ParserResult(offset(offset + Primitive.CHAR6.getBits()), value);
}
public ParserResult readId() {
long value = stream.read(offset, idsize);
return new ParserResult(offset(offset + idsize), value);
}
public ParserResult readVBR(long width) {
long value = stream.readVBR(offset, width);
long total = Bitstream.widthVBR(value, width);
return new ParserResult(offset(offset + total), value);
}
}
| |
/*
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 io.rsocket;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.rsocket.core.RSocketConnector;
import io.rsocket.core.RSocketServer;
import io.rsocket.core.Resume;
import io.rsocket.frame.decoder.PayloadDecoder;
import io.rsocket.lease.LeaseStats;
import io.rsocket.lease.Leases;
import io.rsocket.plugins.DuplexConnectionInterceptor;
import io.rsocket.plugins.RSocketInterceptor;
import io.rsocket.plugins.SocketAcceptorInterceptor;
import io.rsocket.resume.ClientResume;
import io.rsocket.resume.ResumableFramesStore;
import io.rsocket.resume.ResumeStrategy;
import io.rsocket.transport.ClientTransport;
import io.rsocket.transport.ServerTransport;
import java.time.Duration;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
/**
* Main entry point to create RSocket clients or servers as follows:
*
* <ul>
* <li>{@link ClientRSocketFactory} to connect as a client. Use {@link #connect()} for a default
* instance.
* <li>{@link ServerRSocketFactory} to start a server. Use {@link #receive()} for a default
* instance.
* </ul>
*
* @deprecated please use {@link RSocketConnector} and {@link RSocketServer}.
*/
@Deprecated
public final class RSocketFactory {
/**
* Create a {@code ClientRSocketFactory} to connect to a remote RSocket endpoint. Internally
* delegates to {@link RSocketConnector}.
*
* @return the {@code ClientRSocketFactory} instance
*/
public static ClientRSocketFactory connect() {
return new ClientRSocketFactory();
}
/**
* Create a {@code ServerRSocketFactory} to accept connections from RSocket clients. Internally
* delegates to {@link RSocketServer}.
*
* @return the {@code ClientRSocketFactory} instance
*/
public static ServerRSocketFactory receive() {
return new ServerRSocketFactory();
}
public interface Start<T extends Closeable> {
Mono<T> start();
}
public interface ClientTransportAcceptor {
Start<RSocket> transport(Supplier<ClientTransport> transport);
default Start<RSocket> transport(ClientTransport transport) {
return transport(() -> transport);
}
}
public interface ServerTransportAcceptor {
ServerTransport.ConnectionAcceptor toConnectionAcceptor();
<T extends Closeable> Start<T> transport(Supplier<ServerTransport<T>> transport);
default <T extends Closeable> Start<T> transport(ServerTransport<T> transport) {
return transport(() -> transport);
}
}
/** Factory to create and configure an RSocket client, and connect to a server. */
public static class ClientRSocketFactory implements ClientTransportAcceptor {
private static final ClientResume CLIENT_RESUME =
new ClientResume(Duration.ofMinutes(2), Unpooled.EMPTY_BUFFER);
private final RSocketConnector connector;
private Duration tickPeriod = Duration.ofSeconds(20);
private Duration ackTimeout = Duration.ofSeconds(30);
private int missedAcks = 3;
private Resume resume;
public ClientRSocketFactory() {
this(RSocketConnector.create());
}
public ClientRSocketFactory(RSocketConnector connector) {
this.connector = connector;
}
/**
* @deprecated this method is deprecated and deliberately has no effect anymore. Right now, in
* order configure the custom {@link ByteBufAllocator} it is recommended to use the
* following setup for Reactor Netty based transport: <br>
* 1. For Client: <br>
* <pre>{@code
* TcpClient.create()
* ...
* .bootstrap(bootstrap -> bootstrap.option(ChannelOption.ALLOCATOR, clientAllocator))
* }</pre>
* <br>
* 2. For server: <br>
* <pre>{@code
* TcpServer.create()
* ...
* .bootstrap(serverBootstrap -> serverBootstrap.childOption(ChannelOption.ALLOCATOR, serverAllocator))
* }</pre>
* Or in case of local transport, to use corresponding factory method {@code
* LocalClientTransport.creat(String, ByteBufAllocator)}
* @param allocator instance of {@link ByteBufAllocator}
* @return this factory instance
*/
public ClientRSocketFactory byteBufAllocator(ByteBufAllocator allocator) {
return this;
}
public ClientRSocketFactory addConnectionPlugin(DuplexConnectionInterceptor interceptor) {
connector.interceptors(registry -> registry.forConnection(interceptor));
return this;
}
/** Deprecated. Use {@link #addRequesterPlugin(RSocketInterceptor)} instead */
@Deprecated
public ClientRSocketFactory addClientPlugin(RSocketInterceptor interceptor) {
return addRequesterPlugin(interceptor);
}
public ClientRSocketFactory addRequesterPlugin(RSocketInterceptor interceptor) {
connector.interceptors(registry -> registry.forRequester(interceptor));
return this;
}
/** Deprecated. Use {@link #addResponderPlugin(RSocketInterceptor)} instead */
@Deprecated
public ClientRSocketFactory addServerPlugin(RSocketInterceptor interceptor) {
return addResponderPlugin(interceptor);
}
public ClientRSocketFactory addResponderPlugin(RSocketInterceptor interceptor) {
connector.interceptors(registry -> registry.forResponder(interceptor));
return this;
}
public ClientRSocketFactory addSocketAcceptorPlugin(SocketAcceptorInterceptor interceptor) {
connector.interceptors(registry -> registry.forSocketAcceptor(interceptor));
return this;
}
/**
* Deprecated without replacement as Keep-Alive is not optional according to spec
*
* @return this ClientRSocketFactory
*/
@Deprecated
public ClientRSocketFactory keepAlive() {
connector.keepAlive(tickPeriod, ackTimeout.plus(tickPeriod.multipliedBy(missedAcks)));
return this;
}
public ClientTransportAcceptor keepAlive(
Duration tickPeriod, Duration ackTimeout, int missedAcks) {
this.tickPeriod = tickPeriod;
this.ackTimeout = ackTimeout;
this.missedAcks = missedAcks;
keepAlive();
return this;
}
public ClientRSocketFactory keepAliveTickPeriod(Duration tickPeriod) {
this.tickPeriod = tickPeriod;
keepAlive();
return this;
}
public ClientRSocketFactory keepAliveAckTimeout(Duration ackTimeout) {
this.ackTimeout = ackTimeout;
keepAlive();
return this;
}
public ClientRSocketFactory keepAliveMissedAcks(int missedAcks) {
this.missedAcks = missedAcks;
keepAlive();
return this;
}
public ClientRSocketFactory mimeType(String metadataMimeType, String dataMimeType) {
connector.metadataMimeType(metadataMimeType);
connector.dataMimeType(dataMimeType);
return this;
}
public ClientRSocketFactory dataMimeType(String dataMimeType) {
connector.dataMimeType(dataMimeType);
return this;
}
public ClientRSocketFactory metadataMimeType(String metadataMimeType) {
connector.metadataMimeType(metadataMimeType);
return this;
}
public ClientRSocketFactory lease(Supplier<Leases<? extends LeaseStats>> supplier) {
connector.lease(supplier);
return this;
}
public ClientRSocketFactory lease() {
connector.lease(Leases::new);
return this;
}
/** @deprecated without a replacement and no longer used. */
@Deprecated
public ClientRSocketFactory singleSubscriberRequester() {
return this;
}
/**
* Enables a reconnectable, shared instance of {@code Mono<RSocket>} so every subscriber will
* observe the same RSocket instance up on connection establishment. <br>
* For example:
*
* <pre>{@code
* Mono<RSocket> sharedRSocketMono =
* RSocketFactory
* .connect()
* .reconnect(Retry.fixedDelay(3, Duration.ofSeconds(1)))
* .transport(transport)
* .start();
*
* RSocket r1 = sharedRSocketMono.block();
* RSocket r2 = sharedRSocketMono.block();
*
* assert r1 == r2;
*
* }</pre>
*
* Apart of the shared behavior, if the connection is lost, the same {@code Mono<RSocket>}
* instance will transparently re-establish the connection for subsequent subscribers.<br>
* For example:
*
* <pre>{@code
* Mono<RSocket> sharedRSocketMono =
* RSocketFactory
* .connect()
* .reconnect(Retry.fixedDelay(3, Duration.ofSeconds(1)))
* .transport(transport)
* .start();
*
* RSocket r1 = sharedRSocketMono.block();
* RSocket r2 = sharedRSocketMono.block();
*
* assert r1 == r2;
*
* r1.dispose()
*
* assert r2.isDisposed()
*
* RSocket r3 = sharedRSocketMono.block();
* RSocket r4 = sharedRSocketMono.block();
*
*
* assert r1 != r3;
* assert r4 == r3;
*
* }</pre>
*
* <b>Note,</b> having reconnect() enabled does not eliminate the need to accompany each
* individual request with the corresponding retry logic. <br>
* For example:
*
* <pre>{@code
* Mono<RSocket> sharedRSocketMono =
* RSocketFactory
* .connect()
* .reconnect(Retry.fixedDelay(3, Duration.ofSeconds(1)))
* .transport(transport)
* .start();
*
* sharedRSocket.flatMap(rSocket -> rSocket.requestResponse(...))
* .retryWhen(ownRetry)
* .subscribe()
*
* }</pre>
*
* @param retrySpec a retry factory applied for {@link Mono#retryWhen(Retry)}
* @return a shared instance of {@code Mono<RSocket>}.
*/
public ClientRSocketFactory reconnect(Retry retrySpec) {
connector.reconnect(retrySpec);
return this;
}
public ClientRSocketFactory resume() {
resume = resume != null ? resume : new Resume();
connector.resume(resume);
return this;
}
public ClientRSocketFactory resumeToken(Supplier<ByteBuf> supplier) {
resume();
resume.token(supplier);
return this;
}
public ClientRSocketFactory resumeStore(
Function<? super ByteBuf, ? extends ResumableFramesStore> storeFactory) {
resume();
resume.storeFactory(storeFactory);
return this;
}
public ClientRSocketFactory resumeSessionDuration(Duration sessionDuration) {
resume();
resume.sessionDuration(sessionDuration);
return this;
}
public ClientRSocketFactory resumeStreamTimeout(Duration streamTimeout) {
resume();
resume.streamTimeout(streamTimeout);
return this;
}
public ClientRSocketFactory resumeStrategy(Supplier<ResumeStrategy> strategy) {
resume();
resume.retry(
Retry.from(
signals -> signals.flatMap(s -> strategy.get().apply(CLIENT_RESUME, s.failure()))));
return this;
}
public ClientRSocketFactory resumeCleanupOnKeepAlive() {
resume();
resume.cleanupStoreOnKeepAlive();
return this;
}
public Start<RSocket> transport(Supplier<ClientTransport> transport) {
return () -> connector.connect(transport);
}
public ClientTransportAcceptor acceptor(Function<RSocket, RSocket> acceptor) {
return acceptor(() -> acceptor);
}
public ClientTransportAcceptor acceptor(Supplier<Function<RSocket, RSocket>> acceptorSupplier) {
return acceptor(
(setup, sendingSocket) -> {
acceptorSupplier.get().apply(sendingSocket);
return Mono.empty();
});
}
public ClientTransportAcceptor acceptor(SocketAcceptor acceptor) {
connector.acceptor(acceptor);
return this;
}
public ClientRSocketFactory fragment(int mtu) {
connector.fragment(mtu);
return this;
}
/**
* @deprecated this handler is deliberately no-ops and is deprecated with no replacement. In
* order to observe errors, it is recommended to add error handler using {@code doOnError}
* on the specific logical stream. In order to observe connection, or RSocket terminal
* errors, it is recommended to hook on {@link Closeable#onClose()} handler.
*/
public ClientRSocketFactory errorConsumer(Consumer<Throwable> errorConsumer) {
return this;
}
public ClientRSocketFactory setupPayload(Payload payload) {
connector.setupPayload(payload);
return this;
}
public ClientRSocketFactory frameDecoder(PayloadDecoder payloadDecoder) {
connector.payloadDecoder(payloadDecoder);
return this;
}
}
/** Factory to create, configure, and start an RSocket server. */
public static class ServerRSocketFactory implements ServerTransportAcceptor {
private final RSocketServer server;
private Resume resume;
public ServerRSocketFactory() {
this(RSocketServer.create());
}
public ServerRSocketFactory(RSocketServer server) {
this.server = server;
}
/**
* @deprecated this method is deprecated and deliberately has no effect anymore. Right now, in
* order configure the custom {@link ByteBufAllocator} it is recommended to use the
* following setup for Reactor Netty based transport: <br>
* 1. For Client: <br>
* <pre>{@code
* TcpClient.create()
* ...
* .bootstrap(bootstrap -> bootstrap.option(ChannelOption.ALLOCATOR, clientAllocator))
* }</pre>
* <br>
* 2. For server: <br>
* <pre>{@code
* TcpServer.create()
* ...
* .bootstrap(serverBootstrap -> serverBootstrap.childOption(ChannelOption.ALLOCATOR, serverAllocator))
* }</pre>
* Or in case of local transport, to use corresponding factory method {@code
* LocalClientTransport.creat(String, ByteBufAllocator)}
* @param allocator instance of {@link ByteBufAllocator}
* @return this factory instance
*/
@Deprecated
public ServerRSocketFactory byteBufAllocator(ByteBufAllocator allocator) {
return this;
}
public ServerRSocketFactory addConnectionPlugin(DuplexConnectionInterceptor interceptor) {
server.interceptors(registry -> registry.forConnection(interceptor));
return this;
}
/** Deprecated. Use {@link #addRequesterPlugin(RSocketInterceptor)} instead */
@Deprecated
public ServerRSocketFactory addClientPlugin(RSocketInterceptor interceptor) {
return addRequesterPlugin(interceptor);
}
public ServerRSocketFactory addRequesterPlugin(RSocketInterceptor interceptor) {
server.interceptors(registry -> registry.forRequester(interceptor));
return this;
}
/** Deprecated. Use {@link #addResponderPlugin(RSocketInterceptor)} instead */
@Deprecated
public ServerRSocketFactory addServerPlugin(RSocketInterceptor interceptor) {
return addResponderPlugin(interceptor);
}
public ServerRSocketFactory addResponderPlugin(RSocketInterceptor interceptor) {
server.interceptors(registry -> registry.forResponder(interceptor));
return this;
}
public ServerRSocketFactory addSocketAcceptorPlugin(SocketAcceptorInterceptor interceptor) {
server.interceptors(registry -> registry.forSocketAcceptor(interceptor));
return this;
}
public ServerTransportAcceptor acceptor(SocketAcceptor acceptor) {
server.acceptor(acceptor);
return this;
}
public ServerRSocketFactory frameDecoder(PayloadDecoder payloadDecoder) {
server.payloadDecoder(payloadDecoder);
return this;
}
public ServerRSocketFactory fragment(int mtu) {
server.fragment(mtu);
return this;
}
/**
* @deprecated this handler is deliberately no-ops and is deprecated with no replacement. In
* order to observe errors, it is recommended to add error handler using {@code doOnError}
* on the specific logical stream. In order to observe connection, or RSocket terminal
* errors, it is recommended to hook on {@link Closeable#onClose()} handler.
*/
public ServerRSocketFactory errorConsumer(Consumer<Throwable> errorConsumer) {
return this;
}
public ServerRSocketFactory lease(Supplier<Leases<?>> supplier) {
server.lease(supplier);
return this;
}
public ServerRSocketFactory lease() {
server.lease(Leases::new);
return this;
}
/** @deprecated without a replacement and no longer used. */
@Deprecated
public ServerRSocketFactory singleSubscriberRequester() {
return this;
}
public ServerRSocketFactory resume() {
resume = resume != null ? resume : new Resume();
server.resume(resume);
return this;
}
public ServerRSocketFactory resumeStore(
Function<? super ByteBuf, ? extends ResumableFramesStore> storeFactory) {
resume();
resume.storeFactory(storeFactory);
return this;
}
public ServerRSocketFactory resumeSessionDuration(Duration sessionDuration) {
resume();
resume.sessionDuration(sessionDuration);
return this;
}
public ServerRSocketFactory resumeStreamTimeout(Duration streamTimeout) {
resume();
resume.streamTimeout(streamTimeout);
return this;
}
public ServerRSocketFactory resumeCleanupOnKeepAlive() {
resume();
resume.cleanupStoreOnKeepAlive();
return this;
}
@Override
public ServerTransport.ConnectionAcceptor toConnectionAcceptor() {
return server.asConnectionAcceptor();
}
@Override
public <T extends Closeable> Start<T> transport(Supplier<ServerTransport<T>> transport) {
return () -> server.bind(transport.get());
}
}
}
| |
/*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.gui.components.ds.api.consistency;
import com.haulmont.cuba.gui.components.HasValue;
import com.haulmont.cuba.gui.components.PickerField;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.security.entity.Group;
import com.haulmont.cuba.security.entity.User;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SuppressWarnings("unchecked")
@Disabled
public class PickerFieldDsTest extends DsApiConsistencyTestCase {
@Test
public void testUnsubscribeWithComponentListener() {
PickerField pickerField = uiComponents.create(PickerField.NAME);
Datasource<User> userDs = getTestUserDatasource();
Group group = metadata.create(Group.class);
group.setName("Test group");
userDs.getItem().setGroup(group);
pickerField.setDatasource(userDs, "group");
// unbind
pickerField.setDatasource(null, null);
Consumer<HasValue.ValueChangeEvent> listener = e -> {
throw new RuntimeException("Value was changed externally");
};
pickerField.addValueChangeListener(listener);
userDs.getItem().setGroup(metadata.create(Group.class));
}
@Test
public void testUnsubscribeWithDsListener() {
PickerField pickerField = uiComponents.create(PickerField.NAME);
Datasource<User> userDs = getTestUserDatasource();
Group group = metadata.create(Group.class);
group.setName("Test group");
userDs.getItem().setGroup(group);
pickerField.setDatasource(userDs, "group");
// unbind
pickerField.setDatasource(null, null);
Datasource.ItemPropertyChangeListener<User> listener = e -> {
throw new RuntimeException("Value was changed externally");
};
userDs.addItemPropertyChangeListener(listener);
pickerField.setValue(null);
}
@Test
public void testValueChangeListener() {
PickerField pickerField = uiComponents.create(PickerField.NAME);
Datasource<User> userDs = getTestUserDatasource();
User user = userDs.getItem();
Group group = metadata.create(Group.class);
group.setName("Test group");
user.setGroup(group);
// datasource before listener
boolean[] valueWasChanged = {false};
Consumer<HasValue.ValueChangeEvent> listener = e -> valueWasChanged[0] = true;
pickerField.addValueChangeListener(listener);
pickerField.setDatasource(userDs, "group");
assertTrue(valueWasChanged[0]);
// reset state
pickerField.setDatasource(null, null);
pickerField.removeValueChangeListener(listener);
valueWasChanged[0] = false;
pickerField.setValue(null);
// listener before datasource
pickerField.addValueChangeListener(listener);
pickerField.setDatasource(userDs, "group");
assertTrue(valueWasChanged[0]);
}
@Test
public void testUnsubscribeSubscribeComponentListener() {
PickerField pickerField = uiComponents.create(PickerField.NAME);
Datasource<User> userDs = getTestUserDatasource();
User user = userDs.getItem();
Group group = metadata.create(Group.class);
group.setName("Test group");
user.setGroup(group);
pickerField.setDatasource(userDs, "group");
// unbind
pickerField.setDatasource(null, null);
// setup
boolean[] valueWasChanged = {false};
Consumer<HasValue.ValueChangeEvent> listener = e -> valueWasChanged[0] = true;
// datasource before listener
pickerField.setDatasource(userDs, "group");
pickerField.addValueChangeListener(listener);
user.setGroup(null);
assertTrue(valueWasChanged[0]);
// reset state
pickerField.setDatasource(null, null);
pickerField.removeValueChangeListener(listener);
valueWasChanged[0] = false;
user.setGroup(metadata.create(Group.class));
// listener before datasource
pickerField.addValueChangeListener(listener);
pickerField.setDatasource(userDs, "group");
assertTrue(valueWasChanged[0]);
}
@Test
public void testUnsubscribeSubscribeDsListener() {
PickerField pickerField = uiComponents.create(PickerField.NAME);
Datasource<User> userDs = getTestUserDatasource();
Group group = metadata.create(Group.class);
group.setName("Test group");
userDs.getItem().setGroup(group);
pickerField.setDatasource(userDs, "group");
// unbind
pickerField.setDatasource(null, null);
// setup
boolean[] valueWasChanged = {false};
Datasource.ItemPropertyChangeListener<User> listener = e -> valueWasChanged[0] = true;
userDs.addItemPropertyChangeListener(listener);
pickerField.setDatasource(userDs, "group");
pickerField.setValue(null);
assertTrue(valueWasChanged[0]);
}
@Test
public void testDatasourceRepeatableAssign() {
PickerField pickerField = uiComponents.create(PickerField.NAME);
pickerField.setDatasource(null, null);
pickerField.setDatasource(null, null);
Datasource<User> userDs1 = getTestUserDatasource();
boolean exceptionWasThrown = false;
try {
pickerField.setDatasource(userDs1, null);
} catch (Exception e) {
exceptionWasThrown = true;
}
assertTrue(exceptionWasThrown);
exceptionWasThrown = false;
try {
pickerField.setDatasource(null, "group");
} catch (Exception e) {
exceptionWasThrown = true;
}
assertTrue(exceptionWasThrown);
pickerField.setDatasource(userDs1, "group");
pickerField.setDatasource(userDs1, "group");
userDs1.getItem().setGroup(metadata.create(Group.class));
pickerField.setDatasource(userDs1, "group");
Datasource<User> userDs2 = getTestUserDatasource();
pickerField.setDatasource(userDs2, "group");
pickerField.setValue(null);
assertNotNull(userDs1.getItem().getGroup());
}
}
| |
/*
* 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.management.internal.cli.functions;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.execute.FunctionContext;
import com.gemstone.gemfire.cache.execute.ResultSender;
import com.gemstone.gemfire.cache.query.Index;
import com.gemstone.gemfire.cache.query.IndexStatistics;
import com.gemstone.gemfire.cache.query.IndexType;
import com.gemstone.gemfire.cache.query.QueryService;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.internal.lang.Filter;
import com.gemstone.gemfire.internal.lang.ObjectUtils;
import com.gemstone.gemfire.internal.util.CollectionUtils;
import com.gemstone.gemfire.management.internal.cli.domain.IndexDetails;
import com.gemstone.gemfire.management.internal.cli.domain.IndexDetails.IndexStatisticsDetails;
import com.gemstone.gemfire.test.junit.categories.UnitTest;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* The ListIndexFunctionJUnitTest class is test suite of test cases testing the contract and functionality of the
* ListIndexFunction GemFire function.
* </p>
* </p>
* @author John Blum
* @see com.gemstone.gemfire.management.internal.cli.functions.ListIndexFunction
* @see org.jmock.Expectations
* @see org.jmock.Mockery
* @see org.jmock.lib.legacy.ClassImposteriser
* @see org.junit.Assert
* @see org.junit.Test
* @since 7.0
*/
@Category(UnitTest.class)
public class ListIndexFunctionJUnitTest {
private AtomicLong mockCounter = new AtomicLong(0l);
private Mockery mockContext;
@Before
public void setup() {
mockContext = new Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
}
@After
public void tearDown() {
mockContext.assertIsSatisfied();
mockContext = null;
}
protected void assertEquals(final IndexDetails expectedIndexDetails, final IndexDetails actualIndexDetails) {
Assert.assertEquals(expectedIndexDetails.getFromClause(), actualIndexDetails.getFromClause());
Assert.assertEquals(expectedIndexDetails.getIndexedExpression(), actualIndexDetails.getIndexedExpression());
Assert.assertEquals(expectedIndexDetails.getIndexName(), actualIndexDetails.getIndexName());
assertEquals(expectedIndexDetails.getIndexStatisticsDetails(), actualIndexDetails.getIndexStatisticsDetails());
Assert.assertEquals(expectedIndexDetails.getIndexType(), actualIndexDetails.getIndexType());
Assert.assertEquals(expectedIndexDetails.getMemberId(), actualIndexDetails.getMemberId());
Assert.assertEquals(expectedIndexDetails.getMemberName(), actualIndexDetails.getMemberName());
Assert.assertEquals(expectedIndexDetails.getProjectionAttributes(), actualIndexDetails.getProjectionAttributes());
Assert.assertEquals(expectedIndexDetails.getRegionName(), actualIndexDetails.getRegionName());
Assert.assertEquals(expectedIndexDetails.getRegionPath(), actualIndexDetails.getRegionPath());
}
protected void assertEquals(final IndexStatisticsDetails expectedIndexStatisticsDetails, final IndexStatisticsDetails actualIndexStatisticsDetails) {
if (expectedIndexStatisticsDetails != null) {
assertNotNull(actualIndexStatisticsDetails);
Assert.assertEquals(expectedIndexStatisticsDetails.getNumberOfKeys(), actualIndexStatisticsDetails
.getNumberOfKeys());
Assert.assertEquals(expectedIndexStatisticsDetails.getNumberOfUpdates(), actualIndexStatisticsDetails
.getNumberOfUpdates());
Assert.assertEquals(expectedIndexStatisticsDetails.getNumberOfValues(), actualIndexStatisticsDetails
.getNumberOfValues());
Assert.assertEquals(expectedIndexStatisticsDetails.getTotalUpdateTime(), actualIndexStatisticsDetails
.getTotalUpdateTime());
Assert.assertEquals(expectedIndexStatisticsDetails.getTotalUses(), actualIndexStatisticsDetails.getTotalUses());
}
else {
assertNull(actualIndexStatisticsDetails);
}
}
protected IndexDetails createIndexDetails(final String memberId,
final String regionPath,
final String indexName,
final IndexType indexType,
final String fromClause,
final String indexedExpression,
final String memberName,
final String projectionAttributes,
final String regionName)
{
final IndexDetails indexDetails = new IndexDetails(memberId, regionPath, indexName);
indexDetails.setFromClause(fromClause);
indexDetails.setIndexedExpression(indexedExpression);
indexDetails.setIndexType(indexType);
indexDetails.setMemberName(memberName);
indexDetails.setProjectionAttributes(projectionAttributes);
indexDetails.setRegionName(regionName);
return indexDetails;
}
protected IndexStatisticsDetails createIndexStatisticsDetails(final Long numberOfKeys,
final Long numberOfUpdates,
final Long numberOfValues,
final Long totalUpdateTime,
final Long totalUses)
{
final IndexStatisticsDetails indexStatisticsDetails = new IndexStatisticsDetails();
indexStatisticsDetails.setNumberOfKeys(numberOfKeys);
indexStatisticsDetails.setNumberOfUpdates(numberOfUpdates);
indexStatisticsDetails.setNumberOfValues(numberOfValues);
indexStatisticsDetails.setTotalUpdateTime(totalUpdateTime);
indexStatisticsDetails.setTotalUses(totalUses);
return indexStatisticsDetails;
}
protected ListIndexFunction createListIndexFunction(final Cache cache) {
return new TestListIndexFunction(cache);
}
protected Index createMockIndex(final IndexDetails indexDetails) {
final Index mockIndex = mockContext.mock(Index.class, "Index " + indexDetails.getIndexName() + " "
+ mockCounter.getAndIncrement());
final Region mockRegion = mockContext.mock(Region.class, "Region " + indexDetails.getRegionPath() + " "
+ mockCounter.getAndIncrement());
mockContext.checking(new Expectations() {{
oneOf(mockIndex).getFromClause();
will(returnValue(indexDetails.getFromClause()));
oneOf(mockIndex).getIndexedExpression();
will(returnValue(indexDetails.getIndexedExpression()));
oneOf(mockIndex).getName();
will(returnValue(indexDetails.getIndexName()));
oneOf(mockIndex).getProjectionAttributes();
will(returnValue(indexDetails.getProjectionAttributes()));
exactly(2).of(mockIndex).getRegion();
will(returnValue(mockRegion));
oneOf(mockIndex).getType();
will(returnValue(getIndexType(indexDetails.getIndexType())));
oneOf(mockRegion).getName();
will(returnValue(indexDetails.getRegionName()));
oneOf(mockRegion).getFullPath();
will(returnValue(indexDetails.getRegionPath()));
}});
if (indexDetails.getIndexStatisticsDetails() != null) {
final IndexStatistics mockIndexStatistics = mockContext.mock(IndexStatistics.class, "IndexStatistics "
+ indexDetails.getIndexName() + " " + mockCounter.getAndIncrement());
mockContext.checking(new Expectations() {{
exactly(2).of(mockIndex).getStatistics();
will(returnValue(mockIndexStatistics));
oneOf(mockIndexStatistics).getNumUpdates();
will(returnValue(indexDetails.getIndexStatisticsDetails().getNumberOfUpdates()));
oneOf(mockIndexStatistics).getNumberOfKeys();
will(returnValue(indexDetails.getIndexStatisticsDetails().getNumberOfKeys()));
oneOf(mockIndexStatistics).getNumberOfValues();
will(returnValue(indexDetails.getIndexStatisticsDetails().getNumberOfValues()));
oneOf(mockIndexStatistics).getTotalUpdateTime();
will(returnValue(indexDetails.getIndexStatisticsDetails().getTotalUpdateTime()));
oneOf(mockIndexStatistics).getTotalUses();
will(returnValue(indexDetails.getIndexStatisticsDetails().getTotalUses()));
}});
}
else {
mockContext.checking(new Expectations() {{
oneOf(mockIndex).getStatistics();
will(returnValue(null));
}});
}
return mockIndex;
}
protected IndexType getIndexType(final IndexDetails.IndexType type) {
switch (type) {
case FUNCTIONAL:
return IndexType.FUNCTIONAL;
case PRIMARY_KEY:
return IndexType.PRIMARY_KEY;
default:
return null;
}
}
@Test
@SuppressWarnings("unchecked")
public void testExecute() throws Throwable {
final String memberId = "mockMemberId";
final String memberName = "mockMemberName";
final Cache mockCache = mockContext.mock(Cache.class, "Cache");
final DistributedSystem mockDistributedSystem = mockContext.mock(DistributedSystem.class, "DistributedSystem");
final DistributedMember mockDistributedMember = mockContext.mock(DistributedMember.class, "DistributedMember");
final IndexDetails indexDetailsOne = createIndexDetails(memberId, "/Employees", "empIdIdx", IndexType.PRIMARY_KEY,
"/Employees", "id", memberName, "id, firstName, lastName", "Employees");
indexDetailsOne.setIndexStatisticsDetails(createIndexStatisticsDetails(10124l, 4096l, 10124l, 1284100l, 280120l));
final IndexDetails indexDetailsTwo = createIndexDetails(memberId, "/Employees", "empGivenNameIdx",
IndexType.FUNCTIONAL, "/Employees", "lastName", memberName, "id, firstName, lastName", "Employees");
final IndexDetails indexDetailsThree = createIndexDetails(memberId, "/Contractors", "empIdIdx",
IndexType.PRIMARY_KEY, "/Contrators", "id", memberName, "id, firstName, lastName", "Contractors");
indexDetailsThree.setIndexStatisticsDetails(createIndexStatisticsDetails(1024l, 256l, 20248l, 768001l, 24480l));
final IndexDetails indexDetailsFour = createIndexDetails(memberId, "/Employees", "empIdIdx", IndexType.FUNCTIONAL,
"/Employees", "emp_id", memberName, "id, surname, givenname", "Employees");
final Set<IndexDetails> expectedIndexDetailsSet = new HashSet<IndexDetails>(3);
expectedIndexDetailsSet.add(indexDetailsOne);
expectedIndexDetailsSet.add(indexDetailsTwo);
expectedIndexDetailsSet.add(indexDetailsThree);
final QueryService mockQueryService = mockContext.mock(QueryService.class, "QueryService");
final FunctionContext mockFunctionContext = mockContext.mock(FunctionContext.class, "FunctionContext");
final TestResultSender testResultSender = new TestResultSender();
mockContext.checking(new Expectations() {{
oneOf(mockCache).getDistributedSystem();
will(returnValue(mockDistributedSystem));
oneOf(mockCache).getQueryService();
will(returnValue(mockQueryService));
oneOf(mockDistributedSystem).getDistributedMember();
will(returnValue(mockDistributedMember));
exactly(4).of(mockDistributedMember).getId();
will(returnValue(memberId));
exactly(4).of(mockDistributedMember).getName();
will(returnValue(memberName));
oneOf(mockQueryService).getIndexes();
will(returnValue(Arrays.asList(createMockIndex(indexDetailsOne), createMockIndex(indexDetailsTwo),
createMockIndex(indexDetailsThree), createMockIndex(indexDetailsFour))));
oneOf(mockFunctionContext).getResultSender();
will(returnValue(testResultSender));
}});
final ListIndexFunction function = createListIndexFunction(mockCache);
function.execute(mockFunctionContext);
final List<?> results = testResultSender.getResults();
assertNotNull(results);
Assert.assertEquals(1, results.size());
final Set<IndexDetails> actualIndexDetailsSet = (Set<IndexDetails>) results.get(0);
assertNotNull(actualIndexDetailsSet);
Assert.assertEquals(expectedIndexDetailsSet.size(), actualIndexDetailsSet.size());
for (final IndexDetails expectedIndexDetails : expectedIndexDetailsSet) {
final IndexDetails actualIndexDetails = CollectionUtils.findBy(actualIndexDetailsSet, new Filter<IndexDetails>() {
@Override public boolean accept(final IndexDetails indexDetails) {
return ObjectUtils.equals(expectedIndexDetails, indexDetails);
}
});
assertNotNull(actualIndexDetails);
assertEquals(expectedIndexDetails, actualIndexDetails);
}
}
@Test
@SuppressWarnings("unchecked")
public void testExecuteWithNoIndexes() throws Throwable {
final Cache mockCache = mockContext.mock(Cache.class, "Cache");
final DistributedSystem mockDistributedSystem = mockContext.mock(DistributedSystem.class, "DistributedSystem");
final DistributedMember mockDistributedMember = mockContext.mock(DistributedMember.class, "DistributedMember");
final QueryService mockQueryService = mockContext.mock(QueryService.class, "QueryService");
final FunctionContext mockFunctionContext = mockContext.mock(FunctionContext.class, "FunctionContext");
final TestResultSender testResultSender = new TestResultSender();
mockContext.checking(new Expectations() {{
oneOf(mockCache).getDistributedSystem();
will(returnValue(mockDistributedSystem));
oneOf(mockCache).getQueryService();
will(returnValue(mockQueryService));
oneOf(mockDistributedSystem).getDistributedMember();
will(returnValue(mockDistributedMember));
oneOf(mockQueryService).getIndexes();
will(returnValue(Collections.emptyList()));
oneOf(mockFunctionContext).getResultSender();
will(returnValue(testResultSender));
}});
final ListIndexFunction function = createListIndexFunction(mockCache);
function.execute(mockFunctionContext);
final List<?> results = testResultSender.getResults();
assertNotNull(results);
Assert.assertEquals(1, results.size());
final Set<IndexDetails> actualIndexDetailsSet = (Set<IndexDetails>) results.get(0);
assertNotNull(actualIndexDetailsSet);
assertTrue(actualIndexDetailsSet.isEmpty());
}
@Test(expected = RuntimeException.class)
public void testExecuteThrowsException() throws Throwable {
final Cache mockCache = mockContext.mock(Cache.class, "Cache");
final DistributedSystem mockDistributedSystem = mockContext.mock(DistributedSystem.class, "DistributedSystem");
final DistributedMember mockDistributedMember = mockContext.mock(DistributedMember.class, "DistributedMember");
final QueryService mockQueryService = mockContext.mock(QueryService.class, "QueryService");
final FunctionContext mockFunctionContext = mockContext.mock(FunctionContext.class, "FunctionContext");
final TestResultSender testResultSender = new TestResultSender();
mockContext.checking(new Expectations() {{
oneOf(mockCache).getDistributedSystem();
will(returnValue(mockDistributedSystem));
oneOf(mockCache).getQueryService();
will(returnValue(mockQueryService));
oneOf(mockDistributedSystem).getDistributedMember();
will(returnValue(mockDistributedMember));
oneOf(mockQueryService).getIndexes();
will(throwException(new RuntimeException("expected")));
oneOf(mockFunctionContext).getResultSender();
will(returnValue(testResultSender));
}});
final ListIndexFunction function = createListIndexFunction(mockCache);
function.execute(mockFunctionContext);
try {
testResultSender.getResults();
}
catch (Throwable t) {
assertTrue(t instanceof RuntimeException);
Assert.assertEquals("expected", t.getMessage());
throw t;
}
}
protected static class TestListIndexFunction extends ListIndexFunction {
private final Cache cache;
protected TestListIndexFunction(final Cache cache) {
assert cache != null : "The Cache cannot be null!";
this.cache = cache;
}
@Override
protected Cache getCache() {
return this.cache;
}
}
protected static class TestResultSender implements ResultSender {
private final List<Object> results = new LinkedList<Object>();
private Throwable t;
protected List<Object> getResults() throws Throwable {
if (t != null) {
throw t;
}
return Collections.unmodifiableList(results);
}
public void lastResult(final Object lastResult) {
results.add(lastResult);
}
public void sendResult(final Object oneResult) {
results.add(oneResult);
}
public void sendException(final Throwable t) {
this.t = t;
}
}
}
| |
package org.cacas.java.gnu.tools;
import java.nio.ByteBuffer;
// http://www.cacas.org/java/gnu/tools/
/****************************************************************************
* Java-based implementation of the unix crypt(3) command
*
* Based upon C source code written by Eric Young, eay@psych.uq.oz.au Java
* conversion by John F. Dumas, jdumas@zgs.com
*
* Found at http://locutus.kingwoodcable.com/jfd/crypt.html Minor optimizations
* by Wes Biggs, wes@cacas.org
*
* Eric's original code is licensed under the BSD license. As this is
* derivative, the same license applies.
*
* Note: Crypt.class is much smaller when compiled with javac -O
****************************************************************************/
public class Crypt {
private Crypt() {} // defined so class can't be instantiated.
private static final int ITERATIONS = 16;
private static final boolean shifts2[] = {
false, false, true, true, true, true, true, true,
false, true, true, true, true, true, true, false
};
private static final int skb[][] = {
{
/* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x00000010, 0x20000000, 0x20000010,
0x00010000, 0x00010010, 0x20010000, 0x20010010,
0x00000800, 0x00000810, 0x20000800, 0x20000810,
0x00010800, 0x00010810, 0x20010800, 0x20010810,
0x00000020, 0x00000030, 0x20000020, 0x20000030,
0x00010020, 0x00010030, 0x20010020, 0x20010030,
0x00000820, 0x00000830, 0x20000820, 0x20000830,
0x00010820, 0x00010830, 0x20010820, 0x20010830,
0x00080000, 0x00080010, 0x20080000, 0x20080010,
0x00090000, 0x00090010, 0x20090000, 0x20090010,
0x00080800, 0x00080810, 0x20080800, 0x20080810,
0x00090800, 0x00090810, 0x20090800, 0x20090810,
0x00080020, 0x00080030, 0x20080020, 0x20080030,
0x00090020, 0x00090030, 0x20090020, 0x20090030,
0x00080820, 0x00080830, 0x20080820, 0x20080830,
0x00090820, 0x00090830, 0x20090820, 0x20090830,
},
{
/* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
0x00000000, 0x02000000, 0x00002000, 0x02002000,
0x00200000, 0x02200000, 0x00202000, 0x02202000,
0x00000004, 0x02000004, 0x00002004, 0x02002004,
0x00200004, 0x02200004, 0x00202004, 0x02202004,
0x00000400, 0x02000400, 0x00002400, 0x02002400,
0x00200400, 0x02200400, 0x00202400, 0x02202400,
0x00000404, 0x02000404, 0x00002404, 0x02002404,
0x00200404, 0x02200404, 0x00202404, 0x02202404,
0x10000000, 0x12000000, 0x10002000, 0x12002000,
0x10200000, 0x12200000, 0x10202000, 0x12202000,
0x10000004, 0x12000004, 0x10002004, 0x12002004,
0x10200004, 0x12200004, 0x10202004, 0x12202004,
0x10000400, 0x12000400, 0x10002400, 0x12002400,
0x10200400, 0x12200400, 0x10202400, 0x12202400,
0x10000404, 0x12000404, 0x10002404, 0x12002404,
0x10200404, 0x12200404, 0x10202404, 0x12202404,
},
{
/* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
0x00000000, 0x00000001, 0x00040000, 0x00040001,
0x01000000, 0x01000001, 0x01040000, 0x01040001,
0x00000002, 0x00000003, 0x00040002, 0x00040003,
0x01000002, 0x01000003, 0x01040002, 0x01040003,
0x00000200, 0x00000201, 0x00040200, 0x00040201,
0x01000200, 0x01000201, 0x01040200, 0x01040201,
0x00000202, 0x00000203, 0x00040202, 0x00040203,
0x01000202, 0x01000203, 0x01040202, 0x01040203,
0x08000000, 0x08000001, 0x08040000, 0x08040001,
0x09000000, 0x09000001, 0x09040000, 0x09040001,
0x08000002, 0x08000003, 0x08040002, 0x08040003,
0x09000002, 0x09000003, 0x09040002, 0x09040003,
0x08000200, 0x08000201, 0x08040200, 0x08040201,
0x09000200, 0x09000201, 0x09040200, 0x09040201,
0x08000202, 0x08000203, 0x08040202, 0x08040203,
0x09000202, 0x09000203, 0x09040202, 0x09040203,
},
{
/* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
0x00000000, 0x00100000, 0x00000100, 0x00100100,
0x00000008, 0x00100008, 0x00000108, 0x00100108,
0x00001000, 0x00101000, 0x00001100, 0x00101100,
0x00001008, 0x00101008, 0x00001108, 0x00101108,
0x04000000, 0x04100000, 0x04000100, 0x04100100,
0x04000008, 0x04100008, 0x04000108, 0x04100108,
0x04001000, 0x04101000, 0x04001100, 0x04101100,
0x04001008, 0x04101008, 0x04001108, 0x04101108,
0x00020000, 0x00120000, 0x00020100, 0x00120100,
0x00020008, 0x00120008, 0x00020108, 0x00120108,
0x00021000, 0x00121000, 0x00021100, 0x00121100,
0x00021008, 0x00121008, 0x00021108, 0x00121108,
0x04020000, 0x04120000, 0x04020100, 0x04120100,
0x04020008, 0x04120008, 0x04020108, 0x04120108,
0x04021000, 0x04121000, 0x04021100, 0x04121100,
0x04021008, 0x04121008, 0x04021108, 0x04121108,
},
{
/* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x10000000, 0x00010000, 0x10010000,
0x00000004, 0x10000004, 0x00010004, 0x10010004,
0x20000000, 0x30000000, 0x20010000, 0x30010000,
0x20000004, 0x30000004, 0x20010004, 0x30010004,
0x00100000, 0x10100000, 0x00110000, 0x10110000,
0x00100004, 0x10100004, 0x00110004, 0x10110004,
0x20100000, 0x30100000, 0x20110000, 0x30110000,
0x20100004, 0x30100004, 0x20110004, 0x30110004,
0x00001000, 0x10001000, 0x00011000, 0x10011000,
0x00001004, 0x10001004, 0x00011004, 0x10011004,
0x20001000, 0x30001000, 0x20011000, 0x30011000,
0x20001004, 0x30001004, 0x20011004, 0x30011004,
0x00101000, 0x10101000, 0x00111000, 0x10111000,
0x00101004, 0x10101004, 0x00111004, 0x10111004,
0x20101000, 0x30101000, 0x20111000, 0x30111000,
0x20101004, 0x30101004, 0x20111004, 0x30111004,
},
{
/* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
0x00000000, 0x08000000, 0x00000008, 0x08000008,
0x00000400, 0x08000400, 0x00000408, 0x08000408,
0x00020000, 0x08020000, 0x00020008, 0x08020008,
0x00020400, 0x08020400, 0x00020408, 0x08020408,
0x00000001, 0x08000001, 0x00000009, 0x08000009,
0x00000401, 0x08000401, 0x00000409, 0x08000409,
0x00020001, 0x08020001, 0x00020009, 0x08020009,
0x00020401, 0x08020401, 0x00020409, 0x08020409,
0x02000000, 0x0A000000, 0x02000008, 0x0A000008,
0x02000400, 0x0A000400, 0x02000408, 0x0A000408,
0x02020000, 0x0A020000, 0x02020008, 0x0A020008,
0x02020400, 0x0A020400, 0x02020408, 0x0A020408,
0x02000001, 0x0A000001, 0x02000009, 0x0A000009,
0x02000401, 0x0A000401, 0x02000409, 0x0A000409,
0x02020001, 0x0A020001, 0x02020009, 0x0A020009,
0x02020401, 0x0A020401, 0x02020409, 0x0A020409,
},
{
/* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
0x00000000, 0x00000100, 0x00080000, 0x00080100,
0x01000000, 0x01000100, 0x01080000, 0x01080100,
0x00000010, 0x00000110, 0x00080010, 0x00080110,
0x01000010, 0x01000110, 0x01080010, 0x01080110,
0x00200000, 0x00200100, 0x00280000, 0x00280100,
0x01200000, 0x01200100, 0x01280000, 0x01280100,
0x00200010, 0x00200110, 0x00280010, 0x00280110,
0x01200010, 0x01200110, 0x01280010, 0x01280110,
0x00000200, 0x00000300, 0x00080200, 0x00080300,
0x01000200, 0x01000300, 0x01080200, 0x01080300,
0x00000210, 0x00000310, 0x00080210, 0x00080310,
0x01000210, 0x01000310, 0x01080210, 0x01080310,
0x00200200, 0x00200300, 0x00280200, 0x00280300,
0x01200200, 0x01200300, 0x01280200, 0x01280300,
0x00200210, 0x00200310, 0x00280210, 0x00280310,
0x01200210, 0x01200310, 0x01280210, 0x01280310,
},
{
/* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
0x00000000, 0x04000000, 0x00040000, 0x04040000,
0x00000002, 0x04000002, 0x00040002, 0x04040002,
0x00002000, 0x04002000, 0x00042000, 0x04042000,
0x00002002, 0x04002002, 0x00042002, 0x04042002,
0x00000020, 0x04000020, 0x00040020, 0x04040020,
0x00000022, 0x04000022, 0x00040022, 0x04040022,
0x00002020, 0x04002020, 0x00042020, 0x04042020,
0x00002022, 0x04002022, 0x00042022, 0x04042022,
0x00000800, 0x04000800, 0x00040800, 0x04040800,
0x00000802, 0x04000802, 0x00040802, 0x04040802,
0x00002800, 0x04002800, 0x00042800, 0x04042800,
0x00002802, 0x04002802, 0x00042802, 0x04042802,
0x00000820, 0x04000820, 0x00040820, 0x04040820,
0x00000822, 0x04000822, 0x00040822, 0x04040822,
0x00002820, 0x04002820, 0x00042820, 0x04042820,
0x00002822, 0x04002822, 0x00042822, 0x04042822,
}
};
private static final int SPtrans[][] = {
{
/* nibble 0 */
0x00820200, 0x00020000, 0x80800000, 0x80820200,
0x00800000, 0x80020200, 0x80020000, 0x80800000,
0x80020200, 0x00820200, 0x00820000, 0x80000200,
0x80800200, 0x00800000, 0x00000000, 0x80020000,
0x00020000, 0x80000000, 0x00800200, 0x00020200,
0x80820200, 0x00820000, 0x80000200, 0x00800200,
0x80000000, 0x00000200, 0x00020200, 0x80820000,
0x00000200, 0x80800200, 0x80820000, 0x00000000,
0x00000000, 0x80820200, 0x00800200, 0x80020000,
0x00820200, 0x00020000, 0x80000200, 0x00800200,
0x80820000, 0x00000200, 0x00020200, 0x80800000,
0x80020200, 0x80000000, 0x80800000, 0x00820000,
0x80820200, 0x00020200, 0x00820000, 0x80800200,
0x00800000, 0x80000200, 0x80020000, 0x00000000,
0x00020000, 0x00800000, 0x80800200, 0x00820200,
0x80000000, 0x80820000, 0x00000200, 0x80020200,
},
{
/* nibble 1 */
0x10042004, 0x00000000, 0x00042000, 0x10040000,
0x10000004, 0x00002004, 0x10002000, 0x00042000,
0x00002000, 0x10040004, 0x00000004, 0x10002000,
0x00040004, 0x10042000, 0x10040000, 0x00000004,
0x00040000, 0x10002004, 0x10040004, 0x00002000,
0x00042004, 0x10000000, 0x00000000, 0x00040004,
0x10002004, 0x00042004, 0x10042000, 0x10000004,
0x10000000, 0x00040000, 0x00002004, 0x10042004,
0x00040004, 0x10042000, 0x10002000, 0x00042004,
0x10042004, 0x00040004, 0x10000004, 0x00000000,
0x10000000, 0x00002004, 0x00040000, 0x10040004,
0x00002000, 0x10000000, 0x00042004, 0x10002004,
0x10042000, 0x00002000, 0x00000000, 0x10000004,
0x00000004, 0x10042004, 0x00042000, 0x10040000,
0x10040004, 0x00040000, 0x00002004, 0x10002000,
0x10002004, 0x00000004, 0x10040000, 0x00042000,
},
{
/* nibble 2 */
0x41000000, 0x01010040, 0x00000040, 0x41000040,
0x40010000, 0x01000000, 0x41000040, 0x00010040,
0x01000040, 0x00010000, 0x01010000, 0x40000000,
0x41010040, 0x40000040, 0x40000000, 0x41010000,
0x00000000, 0x40010000, 0x01010040, 0x00000040,
0x40000040, 0x41010040, 0x00010000, 0x41000000,
0x41010000, 0x01000040, 0x40010040, 0x01010000,
0x00010040, 0x00000000, 0x01000000, 0x40010040,
0x01010040, 0x00000040, 0x40000000, 0x00010000,
0x40000040, 0x40010000, 0x01010000, 0x41000040,
0x00000000, 0x01010040, 0x00010040, 0x41010000,
0x40010000, 0x01000000, 0x41010040, 0x40000000,
0x40010040, 0x41000000, 0x01000000, 0x41010040,
0x00010000, 0x01000040, 0x41000040, 0x00010040,
0x01000040, 0x00000000, 0x41010000, 0x40000040,
0x41000000, 0x40010040, 0x00000040, 0x01010000,
},
{
/* nibble 3 */
0x00100402, 0x04000400, 0x00000002, 0x04100402,
0x00000000, 0x04100000, 0x04000402, 0x00100002,
0x04100400, 0x04000002, 0x04000000, 0x00000402,
0x04000002, 0x00100402, 0x00100000, 0x04000000,
0x04100002, 0x00100400, 0x00000400, 0x00000002,
0x00100400, 0x04000402, 0x04100000, 0x00000400,
0x00000402, 0x00000000, 0x00100002, 0x04100400,
0x04000400, 0x04100002, 0x04100402, 0x00100000,
0x04100002, 0x00000402, 0x00100000, 0x04000002,
0x00100400, 0x04000400, 0x00000002, 0x04100000,
0x04000402, 0x00000000, 0x00000400, 0x00100002,
0x00000000, 0x04100002, 0x04100400, 0x00000400,
0x04000000, 0x04100402, 0x00100402, 0x00100000,
0x04100402, 0x00000002, 0x04000400, 0x00100402,
0x00100002, 0x00100400, 0x04100000, 0x04000402,
0x00000402, 0x04000000, 0x04000002, 0x04100400,
},
{
/* nibble 4 */
0x02000000, 0x00004000, 0x00000100, 0x02004108,
0x02004008, 0x02000100, 0x00004108, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x00004100,
0x02000108, 0x02004008, 0x02004100, 0x00000000,
0x00004100, 0x02000000, 0x00004008, 0x00000108,
0x02000100, 0x00004108, 0x00000000, 0x02000008,
0x00000008, 0x02000108, 0x02004108, 0x00004008,
0x02004000, 0x00000100, 0x00000108, 0x02004100,
0x02004100, 0x02000108, 0x00004008, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x02000100,
0x02000000, 0x00004100, 0x02004108, 0x00000000,
0x00004108, 0x02000000, 0x00000100, 0x00004008,
0x02000108, 0x00000100, 0x00000000, 0x02004108,
0x02004008, 0x02004100, 0x00000108, 0x00004000,
0x00004100, 0x02004008, 0x02000100, 0x00000108,
0x00000008, 0x00004108, 0x02004000, 0x02000008,
},
{
/* nibble 5 */
0x20000010, 0x00080010, 0x00000000, 0x20080800,
0x00080010, 0x00000800, 0x20000810, 0x00080000,
0x00000810, 0x20080810, 0x00080800, 0x20000000,
0x20000800, 0x20000010, 0x20080000, 0x00080810,
0x00080000, 0x20000810, 0x20080010, 0x00000000,
0x00000800, 0x00000010, 0x20080800, 0x20080010,
0x20080810, 0x20080000, 0x20000000, 0x00000810,
0x00000010, 0x00080800, 0x00080810, 0x20000800,
0x00000810, 0x20000000, 0x20000800, 0x00080810,
0x20080800, 0x00080010, 0x00000000, 0x20000800,
0x20000000, 0x00000800, 0x20080010, 0x00080000,
0x00080010, 0x20080810, 0x00080800, 0x00000010,
0x20080810, 0x00080800, 0x00080000, 0x20000810,
0x20000010, 0x20080000, 0x00080810, 0x00000000,
0x00000800, 0x20000010, 0x20000810, 0x20080800,
0x20080000, 0x00000810, 0x00000010, 0x20080010,
},
{
/* nibble 6 */
0x00001000, 0x00000080, 0x00400080, 0x00400001,
0x00401081, 0x00001001, 0x00001080, 0x00000000,
0x00400000, 0x00400081, 0x00000081, 0x00401000,
0x00000001, 0x00401080, 0x00401000, 0x00000081,
0x00400081, 0x00001000, 0x00001001, 0x00401081,
0x00000000, 0x00400080, 0x00400001, 0x00001080,
0x00401001, 0x00001081, 0x00401080, 0x00000001,
0x00001081, 0x00401001, 0x00000080, 0x00400000,
0x00001081, 0x00401000, 0x00401001, 0x00000081,
0x00001000, 0x00000080, 0x00400000, 0x00401001,
0x00400081, 0x00001081, 0x00001080, 0x00000000,
0x00000080, 0x00400001, 0x00000001, 0x00400080,
0x00000000, 0x00400081, 0x00400080, 0x00001080,
0x00000081, 0x00001000, 0x00401081, 0x00400000,
0x00401080, 0x00000001, 0x00001001, 0x00401081,
0x00400001, 0x00401080, 0x00401000, 0x00001001,
},
{
/* nibble 7 */
0x08200020, 0x08208000, 0x00008020, 0x00000000,
0x08008000, 0x00200020, 0x08200000, 0x08208020,
0x00000020, 0x08000000, 0x00208000, 0x00008020,
0x00208020, 0x08008020, 0x08000020, 0x08200000,
0x00008000, 0x00208020, 0x00200020, 0x08008000,
0x08208020, 0x08000020, 0x00000000, 0x00208000,
0x08000000, 0x00200000, 0x08008020, 0x08200020,
0x00200000, 0x00008000, 0x08208000, 0x00000020,
0x00200000, 0x00008000, 0x08000020, 0x08208020,
0x00008020, 0x08000000, 0x00000000, 0x00208000,
0x08200020, 0x08008020, 0x08008000, 0x00200020,
0x08208000, 0x00000020, 0x00200020, 0x08008000,
0x08208020, 0x00200000, 0x08200000, 0x08000020,
0x00208000, 0x00008020, 0x08008020, 0x08200000,
0x00000020, 0x08208000, 0x00208020, 0x00000000,
0x08000000, 0x08200020, 0x00008000, 0x00208020
}
};
private static final int byteToUnsigned(byte b) {
int value = b;
return (value >= 0) ? value : value + 256;
}
private static int fourBytesToInt(byte b[], int offset) {
return byteToUnsigned(b[offset++])
| (byteToUnsigned(b[offset++]) << 8)
| (byteToUnsigned(b[offset++]) << 16)
| (byteToUnsigned(b[offset]) << 24);
}
private static final void intToFourBytes(int iValue, byte b[], int offset) {
b[offset++] = (byte)((iValue) & 0xff);
b[offset++] = (byte)((iValue >>> 8 ) & 0xff);
b[offset++] = (byte)((iValue >>> 16) & 0xff);
b[offset] = (byte)((iValue >>> 24) & 0xff);
}
private static final void PERM_OP(int a, int b, int n, int m, int results[]) {
int t;
t = ((a >>> n) ^ b) & m;
a ^= t << n;
b ^= t;
results[0] = a;
results[1] = b;
}
private static final int HPERM_OP(int a, int n, int m) {
int t;
t = ((a << (16 - n)) ^ a) & m;
a = a ^ t ^ (t >>> (16 - n));
return a;
}
private static int [] des_set_key(byte key[]) {
int schedule[] = new int [ITERATIONS * 2];
int c = fourBytesToInt(key, 0);
int d = fourBytesToInt(key, 4);
int results[] = new int[2];
PERM_OP(d, c, 4, 0x0f0f0f0f, results);
d = results[0]; c = results[1];
c = HPERM_OP(c, -2, 0xcccc0000);
d = HPERM_OP(d, -2, 0xcccc0000);
PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1];
PERM_OP(c, d, 8, 0x00ff00ff, results);
c = results[0]; d = results[1];
PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1];
d = (((d & 0x000000ff) << 16) | (d & 0x0000ff00) |
((d & 0x00ff0000) >>> 16) | ((c & 0xf0000000) >>> 4));
c &= 0x0fffffff;
int s, t;
int j = 0;
for(int i = 0; i < ITERATIONS; i ++) {
if(shifts2[i]) {
c = (c >>> 2) | (c << 26);
d = (d >>> 2) | (d << 26);
} else {
c = (c >>> 1) | (c << 27);
d = (d >>> 1) | (d << 27);
}
c &= 0x0fffffff;
d &= 0x0fffffff;
s = skb[0][ (c ) & 0x3f ]|
skb[1][((c >>> 6) & 0x03) | ((c >>> 7) & 0x3c)]|
skb[2][((c >>> 13) & 0x0f) | ((c >>> 14) & 0x30)]|
skb[3][((c >>> 20) & 0x01) | ((c >>> 21) & 0x06) |
((c >>> 22) & 0x38)];
t = skb[4][ (d ) & 0x3f ]|
skb[5][((d >>> 7) & 0x03) | ((d >>> 8) & 0x3c)]|
skb[6][ (d >>>15) & 0x3f ]|
skb[7][((d >>>21) & 0x0f) | ((d >>> 22) & 0x30)];
schedule[j++] = ((t << 16) | (s & 0x0000ffff)) & 0xffffffff;
s = ((s >>> 16) | (t & 0xffff0000));
s = (s << 4) | (s >>> 28);
schedule[j++] = s & 0xffffffff;
}
return schedule;
}
private static final int D_ENCRYPT(int L, int R, int S, int E0, int E1, int s[]) {
int t, u, v;
v = R ^ (R >>> 16);
u = v & E0;
v = v & E1;
u = (u ^ (u << 16)) ^ R ^ s[S];
t = (v ^ (v << 16)) ^ R ^ s[S + 1];
t = (t >>> 4) | (t << 28);
L ^= SPtrans[1][(t ) & 0x3f] |
SPtrans[3][(t >>> 8) & 0x3f] |
SPtrans[5][(t >>> 16) & 0x3f] |
SPtrans[7][(t >>> 24) & 0x3f] |
SPtrans[0][(u ) & 0x3f] |
SPtrans[2][(u >>> 8) & 0x3f] |
SPtrans[4][(u >>> 16) & 0x3f] |
SPtrans[6][(u >>> 24) & 0x3f];
return L;
}
private static final int [] body(int schedule[], int Eswap0, int Eswap1) {
int left = 0;
int right = 0;
int t = 0;
for (int j = 0; j < 25; j ++) {
for (int i = 0; i < ITERATIONS * 2; i += 4) {
left = D_ENCRYPT(left, right, i, Eswap0, Eswap1, schedule);
right = D_ENCRYPT(right, left, i + 2, Eswap0, Eswap1, schedule);
}
t = left;
left = right;
right = t;
}
t = right;
right = (left >>> 1) | (left << 31);
left = (t >>> 1) | (t << 31);
left &= 0xffffffff;
right &= 0xffffffff;
int results[] = new int[2];
PERM_OP(right, left, 1, 0x55555555, results);
right = results[0]; left = results[1];
PERM_OP(left, right, 8, 0x00ff00ff, results);
left = results[0]; right = results[1];
PERM_OP(right, left, 2, 0x33333333, results);
right = results[0]; left = results[1];
PERM_OP(left, right, 16, 0x0000ffff, results);
left = results[0]; right = results[1];
PERM_OP(right, left, 4, 0x0f0f0f0f, results);
right = results[0]; left = results[1];
int out[] = new int[2];
out[0] = left;
out[1] = right;
return out;
}
public static final String alphabet = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
public static final String crypt(String salt, String original) {
// wwb -- Should do some sanity checks: salt needs to be 2 chars, in alpha.
while(salt.length() < 2)
salt += "A";
char[] buffer = new char [13];
char charZero = salt.charAt(0);
char charOne = salt.charAt(1);
buffer[0] = charZero;
buffer[1] = charOne;
int Eswap0 = alphabet.indexOf(charZero);
int Eswap1 = alphabet.indexOf(charOne) << 4;
byte key[] = new byte[8];
for(int i = 0; i < key.length; i ++)
key[i] = (byte)0;
for(int i = 0; i < key.length && i < original.length(); i ++)
key[i] = (byte) ((original.charAt(i)) << 1);
int schedule[] = des_set_key(key);
int out[] = body(schedule, Eswap0, Eswap1);
byte b[] = new byte[9];
intToFourBytes(out[0], b, 0);
intToFourBytes(out[1], b, 4);
b[8] = 0;
for(int i = 2, y = 0, u = 0x80; i < 13; i ++) {
for(int j = 0, c = 0; j < 6; j ++) {
c <<= 1;
if((b[y] & u) != 0)
c |= 1;
u >>>= 1;
if (u == 0) {
y++;
u = 0x80;
}
buffer[i] = alphabet.charAt(c);
}
}
return new String(buffer);
}
// ----- END OF ORIGINAL CODES / START OF NEW CODES -----
public static final String crypt(byte[] bsalt, byte[] boriginal) {
if (bsalt.length < 2) {
bsalt = new byte[2];
bsalt[0] = bsalt[1] = 'A';
//throw new IllegalArgumentException("salt requires at least 2 characters");
}
char[] buffer = new char[13];
char charZero = (char) bsalt[0];
char charOne = (char) bsalt[1];
buffer[0] = charZero;
buffer[1] = charOne;
int Eswap0 = alphabet.indexOf(charZero);
int Eswap1 = alphabet.indexOf(charOne) << 4;
byte key[] = new byte[8];
for (int i = 0; i < key.length; i++)
key[i] = (byte) 0;
for (int i = 0; i < key.length && i < boriginal.length; i++)
key[i] = (byte) ((boriginal[i]) << 1);
int schedule[] = des_set_key(key);
int out[] = body(schedule, Eswap0, Eswap1);
byte b[] = new byte[9];
intToFourBytes(out[0], b, 0);
intToFourBytes(out[1], b, 4);
b[8] = 0;
for (int i = 2, y = 0, u = 0x80; i < 13; i++) {
for (int j = 0, c = 0; j < 6; j++) {
c <<= 1;
if ((b[y] & u) != 0)
c |= 1;
u >>>= 1;
if (u == 0) {
y++;
u = 0x80;
}
buffer[i] = alphabet.charAt(c);
}
}
return new String(buffer);
}
public static final String crypt(ByteBuffer bsalt, ByteBuffer boriginal) {
return crypt(bsalt.array(), boriginal.array());
}
}
| |
/*
* Copyright 2006 Open Source Applications 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.unitedinternet.cosmo.service.impl;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.SortedSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.unitedinternet.cosmo.calendar.RecurrenceExpander;
import org.unitedinternet.cosmo.dao.ContentDao;
import org.unitedinternet.cosmo.dao.DuplicateItemNameException;
import org.unitedinternet.cosmo.dao.ModelValidationException;
import org.unitedinternet.cosmo.model.CollectionItem;
import org.unitedinternet.cosmo.model.CollectionLockedException;
import org.unitedinternet.cosmo.model.ContentItem;
import org.unitedinternet.cosmo.model.EventStamp;
import org.unitedinternet.cosmo.model.HomeCollectionItem;
import org.unitedinternet.cosmo.model.Item;
import org.unitedinternet.cosmo.model.ModificationUid;
import org.unitedinternet.cosmo.model.NoteItem;
import org.unitedinternet.cosmo.model.NoteOccurrence;
import org.unitedinternet.cosmo.model.Stamp;
import org.unitedinternet.cosmo.model.StampUtils;
import org.unitedinternet.cosmo.model.Ticket;
import org.unitedinternet.cosmo.model.User;
import org.unitedinternet.cosmo.model.filter.ItemFilter;
import org.unitedinternet.cosmo.model.hibernate.ModificationUidImpl;
import org.unitedinternet.cosmo.service.ContentService;
import org.unitedinternet.cosmo.service.lock.LockManager;
import org.unitedinternet.cosmo.service.triage.TriageStatusQueryContext;
import org.unitedinternet.cosmo.service.triage.TriageStatusQueryProcessor;
import org.unitedinternet.cosmo.util.NoteOccurrenceUtil;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.RecurrenceId;
/**
* Standard implementation of <code>ContentService</code>.
*
* @see ContentService
* @see ContentDao
*/
@Service
@Transactional
public class StandardContentService implements ContentService {
private static final Logger LOG = LoggerFactory.getLogger(StandardContentService.class);
private final ContentDao contentDao;
private final LockManager lockManager;
private final TriageStatusQueryProcessor triageStatusQueryProcessor;
private long lockTimeout = 100;
public StandardContentService( @Autowired ContentDao contentDao, @Autowired LockManager lockManager,
@Autowired TriageStatusQueryProcessor triageStatusQueryProcessor) {
super();
this.contentDao = contentDao;
this.lockManager = lockManager;
this.triageStatusQueryProcessor = triageStatusQueryProcessor;
}
// ContentService methods
/**
* Get the root item for a user
*
* @param user
*/
@Transactional(readOnly = true)
public HomeCollectionItem getRootItem(User user, boolean forceReload) {
if (LOG.isDebugEnabled()) {
LOG.debug("Getting root item for {}", user.getUsername());
}
return contentDao.getRootItem(user, forceReload);
}
/**
* Get the root item for a user
*
* @param user
*/
@Transactional(readOnly = true)
public HomeCollectionItem getRootItem(User user) {
if (LOG.isDebugEnabled()) {
LOG.debug("Getting root item for {}", user.getUsername());
}
return contentDao.getRootItem(user);
}
/**
* Searches for an item stamp by item uid. The implementation will hit directly the the DB.
*
* @param internalItemUid item internal uid
* @param clazz stamp type
* @return the item's stamp from the db
*/
@Transactional(readOnly = true)
public <STAMP_TYPE extends Stamp> STAMP_TYPE findStampByInternalItemUid(String internalItemUid, Class<STAMP_TYPE> clazz){
if (LOG.isDebugEnabled()) {
LOG.debug("Finding item with uid {}", internalItemUid);
}
return contentDao.findStampByInternalItemUid(internalItemUid, clazz);
}
/**
* Find an item with the specified uid. If the uid is found, return
* the item found. If the uid represents a recurring NoteItem occurrence
* (parentUid:recurrenceId), return a NoteOccurrence.
*
* @param uid
* uid of item to find
* @return item represented by uid
*/
@Transactional(readOnly = true)
public Item findItemByUid(String uid) {
if (LOG.isDebugEnabled()) {
LOG.debug("Finding item with uid {}", uid);
}
Item item = contentDao.findItemByUid(uid);
// return item if found
if(item!=null) {
return item;
}
// Handle case where uid represents an occurrence of a recurring item.
if(uid.indexOf(ModificationUid.RECURRENCEID_DELIMITER)!=-1) {
ModificationUidImpl modUid;
try {
modUid = new ModificationUidImpl(uid);
} catch (ModelValidationException e) {
// If ModificationUid is invalid, item isn't present
return null;
}
// Find the parent, and then verify that the recurrenceId is a valid occurrence date for the recurring item.
NoteItem parent = (NoteItem) contentDao.findItemByUid(modUid.getParentUid());
if(parent==null) {
return null;
}
else {
return getNoteOccurrence(parent, modUid.getRecurrenceId());
}
}
return null;
}
/**
* Find content item by path. Path is of the format:
* /username/parent1/parent2/itemname.
*/
@Transactional(readOnly = true)
public Item findItemByPath(String path) {
if (LOG.isDebugEnabled()) {
LOG.debug("Finding item at path {}", path);
}
return contentDao.findItemByPath(path);
}
/**
* Find content item by path relative to the identified parent
* item.
*
* @throws NoSuchItemException if a item does not exist at the specified path
*
*/
@Transactional(readOnly = true)
public Item findItemByPath(String path, String parentUid) {
if (LOG.isDebugEnabled()) {
LOG.debug("Finding item at path {} below parent {}", path , parentUid);
}
return contentDao.findItemByPath(path, parentUid);
}
/**
* Find content item's parent by path. Path is of the format:
* /username/parent1/parent2/itemname. In this example,
* the item at /username/parent1/parent2 would be returned.
*/
@Transactional(readOnly = true)
public Item findItemParentByPath(String path) {
if (LOG.isDebugEnabled()) {
LOG.debug("Finding item's parent at path {}", path);
}
return contentDao.findItemParentByPath(path);
}
public void addItemToCollection(Item item, CollectionItem collection) {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding item {} to collection {}",item.getUid(), collection.getUid());
}
contentDao.addItemToCollection(item, collection);
contentDao.updateCollectionTimestamp(collection);
}
/**
* Copy an item to the given path
* @param item item to copy
* @param existingParent existing source collection
* @param targetParent existing destination collection
* @param path path to copy item to
* @param deepCopy true for deep copy, else shallow copy will
* be performed
* @throws org.unitedinternet.cosmo.dao.ItemNotFoundException
* if parent item specified by path does not exist
* @throws org.unitedinternet.cosmo.dao.DuplicateItemNameException
* if path points to an item with the same path
* @throws org.unitedinternet.cosmo.model.CollectionLockedException
* if Item is a ContentItem and destination CollectionItem
* is lockecd.
*/
public void copyItem(Item item, CollectionItem targetParent,
String path, boolean deepCopy) {
// Prevent HomeCollection from being copied
if(item instanceof HomeCollectionItem) {
throw new IllegalArgumentException("cannot copy home collection");
}
Item toItem = findItemByPath(path);
if(toItem!=null) {
throw new DuplicateItemNameException(null, path + " exists");
}
// Handle case of copying ContentItem (need to sync on dest collection)
if(item != null && item instanceof ContentItem) {
// Need to get exclusive lock to destination collection
CollectionItem parent =
(CollectionItem) contentDao.findItemParentByPath(path);
if(parent==null) {
throw new IllegalArgumentException("path must match parent collection");
}
// Verify that destination parent in path matches newParent
if(!parent.equals(targetParent)) {
throw new IllegalArgumentException("targetParent must mach target path");
}
// if we can't get lock, then throw exception
if (!lockManager.lockCollection(parent, lockTimeout)) {
throw new CollectionLockedException(
"unable to obtain collection lock");
}
try {
contentDao.copyItem(item, path, deepCopy);
} finally {
lockManager.unlockCollection(parent);
}
}
else {
// no need to synchronize if not ContentItem
contentDao.copyItem(item, path, deepCopy);
}
}
/**
* Move item from one collection to another
* @param item item to move
* @param oldParent parent to remove item from
* @param newParent parent to add item to
* @throws org.unitedinternet.cosmo.model.CollectionLockedException
* if Item is a ContentItem and source or destination
* CollectionItem is lockecd.
*/
public void moveItem(Item item, CollectionItem oldParent, CollectionItem newParent) {
// Prevent HomeCollection from being moved
if(item instanceof HomeCollectionItem) {
throw new IllegalArgumentException("cannot move home collection");
}
// Only need locking for ContentItem for now
if(item instanceof ContentItem) {
Set<CollectionItem> locks = acquireLocks(newParent, item);
try {
// add item to newParent
contentDao.addItemToCollection(item, newParent);
// remove item from oldParent
contentDao.removeItemFromCollection(item, oldParent);
// update collections involved
for(CollectionItem parent : locks) {
contentDao.updateCollectionTimestamp(parent);
}
} finally {
releaseLocks(locks);
}
} else {
// add item to newParent
contentDao.addItemToCollection(item, newParent);
// remove item from oldParent
contentDao.removeItemFromCollection(item, oldParent);
}
}
/**
* Remove an item.
*
* @param item
* item to remove
* @throws org.unitedinternet.cosmo.model.CollectionLockedException
* if Item is a ContentItem and parent CollectionItem
* is locked
*/
public void removeItem(Item item) {
if (LOG.isDebugEnabled()) {
LOG.debug("Removing item {}", item.getUid());
}
// Let service handle ContentItems (for sync purposes)
if(item instanceof ContentItem) {
removeContent((ContentItem) item);
}
else if(item instanceof CollectionItem) {
removeCollection((CollectionItem) item);
}
else {
contentDao.removeItem(item);
}
}
/**
* Remove an item from a collection. The item will be deleted if
* it belongs to no more collections.
* @param item item to remove from collection
* @param collection item to remove item from
*/
public void removeItemFromCollection(Item item, CollectionItem collection) {
if (LOG.isDebugEnabled()) {
LOG.debug("removing item {} from collection {}", item.getUid(), collection.getUid());
}
contentDao.removeItemFromCollection(item, collection);
contentDao.updateCollectionTimestamp(collection);
}
/**
* Load all children for collection that have been updated since a given
* timestamp. If no timestamp is specified, then return all children.
*
* @param collection
* collection
* @param timestamp
* timestamp
* @return children of collection that have been updated since timestamp, or
* all children if timestamp is null
*/
@Transactional(readOnly = true)
public Set<ContentItem> loadChildren(CollectionItem collection, java.util.Date timestamp) {
return contentDao.loadChildren(collection, timestamp);
}
/**
* Create a new collection.
*
* @param parent
* parent of collection.
* @param collection
* collection to create
* @return newly created collection
*/
public CollectionItem createCollection(CollectionItem parent,
CollectionItem collection) {
if (LOG.isDebugEnabled()) {
LOG.debug("creating collection {} in {}", collection.getName(), parent.getName());
}
return contentDao.createCollection(parent, collection);
}
/**
* Create a new collection.
*
* @param parent
* parent of collection.
* @param collection
* collection to create
* @param children
* collection children
* @return newly created collection
*/
public CollectionItem createCollection(CollectionItem parent,
CollectionItem collection, Set<Item> children) {
if (LOG.isDebugEnabled()) {
LOG.debug("creating collection {} in {}", collection.getName(), parent.getName());
}
// Obtain locks to all collections involved. A collection is involved
// if it is the parent of one of the children. If all children are new
// items, then no locks are obtained.
Set<CollectionItem> locks = acquireLocks(children);
try {
// Create the new collection
collection = contentDao.createCollection(parent, collection);
Set<ContentItem> childrenToUpdate = new LinkedHashSet<ContentItem>();
// Keep track of NoteItem modifications that need to be processed
// after the master NoteItem.
ArrayList<NoteItem> modifications = new ArrayList<NoteItem>();
// Either create or update each item
for (Item item : children) {
if (item instanceof NoteItem) {
NoteItem note = (NoteItem) item;
// If item is a modification and the master note
// hasn't been created, then we need to process
// the master first.
if(note.getModifies()!=null) {
modifications.add(note);
}
else {
childrenToUpdate.add(note);
}
}
}
// add modifications to end of set
for(NoteItem mod: modifications) {
childrenToUpdate.add(mod);
}
// update all children and collection
collection = contentDao.updateCollection(collection, childrenToUpdate);
// update timestamps on all collections involved
for(CollectionItem lockedCollection : locks) {
contentDao.updateCollectionTimestamp(lockedCollection);
}
// update timestamp on new collection
collection = contentDao.updateCollectionTimestamp(collection);
// get latest timestamp
return collection;
} finally {
releaseLocks(locks);
}
}
/**
* Update collection item
*
* @param collection
* collection item to update
* @return updated collection
* @throws org.unitedinternet.cosmo.model.CollectionLockedException
* if CollectionItem is locked
*/
public CollectionItem updateCollection(CollectionItem collection) {
if (! lockManager.lockCollection(collection, lockTimeout)) {
throw new CollectionLockedException("unable to obtain collection lock");
}
try {
return contentDao.updateCollection(collection);
} finally {
lockManager.unlockCollection(collection);
}
}
/**
* Update a collection and set of children. The set of
* children to be updated can include updates to existing
* children, new children, and removed children. A removal
* of a child Item is accomplished by setting Item.isActive
* to false to an existing Item.
*
* The collection is locked at the beginning of the update. Any
* other update that begins before this update has completed, and
* the collection unlocked, will fail immediately with a
* <code>CollectionLockedException</code>.
*
* @param collection
* collection to update
* @param children
* children to update
* @return updated collection
* @throws CollectionLockedException if the collection is
* currently locked for an update.
*/
public CollectionItem updateCollection(CollectionItem collection,
Set<Item> updates) {
if (LOG.isDebugEnabled()) {
LOG.debug("updating collection {}", collection.getUid());
}
// Obtain locks to all collections involved. A collection is involved
// if it is the parent of one of updated items.
Set<CollectionItem> locks = acquireLocks(collection, updates);
try {
Set<ContentItem> childrenToUpdate = new LinkedHashSet<ContentItem>();
// Keep track of NoteItem modifications that need to be processed
// after the master NoteItem.
ArrayList<NoteItem> modifications = new ArrayList<NoteItem>();
// Either create or update each item
for (Item item : updates) {
if (item instanceof NoteItem) {
NoteItem note = (NoteItem) item;
// If item is a modification and the master note
// hasn't been created, then we need to process
// the master first.
if(note.getModifies()!=null) {
modifications.add(note);
}
else {
childrenToUpdate.add(note);
}
}
}
for(NoteItem mod: modifications) {
// Only update modification if master has not been
// deleted because master deletion will take care
// of modification deletion.
if(mod.getModifies().getIsActive()==true) {
childrenToUpdate.add(mod);
}
}
checkDatesForEvents(childrenToUpdate);
collection = contentDao.updateCollection(collection, childrenToUpdate);
// update collections involved
for(CollectionItem lockedCollection : locks) {
lockedCollection = contentDao.updateCollectionTimestamp(lockedCollection);
if(lockedCollection.getUid().equals(collection.getUid())) {
collection = lockedCollection;
}
}
// get latest timestamp
return collection;
} finally {
releaseLocks(locks);
}
}
/**
* Remove collection item
*
* @param collection
* collection item to remove
*/
public void removeCollection(CollectionItem collection) {
if (LOG.isDebugEnabled()) {
LOG.debug("removing collection {}", collection.getUid());
}
// Prevent HomeCollection from being removed (should only be removed when user is removed)
if(collection instanceof HomeCollectionItem) {
throw new IllegalArgumentException("cannot remove home collection");
}
contentDao.removeCollection(collection);
}
/**
* Create new content item. A content item represents a piece of content or
* file.
*
* @param parent
* parent collection of content. If null, content is assumed to
* live in the top-level user collection
* @param content
* content to create
* @return newly created content
* @throws org.unitedinternet.cosmo.model.CollectionLockedException
* if parent CollectionItem is locked
*/
public ContentItem createContent(CollectionItem parent,
ContentItem content) {
if (LOG.isDebugEnabled()) {
LOG.debug("creating content item {} in {}", content.getName(), parent.getName());
}
checkDatesForEvent(content);
// Obtain locks to all collections involved.
Set<CollectionItem> locks = acquireLocks(parent, content);
try {
content = contentDao.createContent(parent, content);
// update collections
for(CollectionItem col : locks) {
contentDao.updateCollectionTimestamp(col);
}
return content;
} finally {
releaseLocks(locks);
}
}
private void checkDatesForEvents(Collection<ContentItem> items){
if(items == null){
return;
}
for(ContentItem item : items){
checkDatesForEvent(item);
}
}
private void checkDatesForEvent(ContentItem item){
if(!(item instanceof NoteItem)){
return;
}
NoteItem noteItem = (NoteItem)item;
Stamp stamp = noteItem.getStamp("event");
if(!(stamp instanceof EventStamp)){
return;
}
EventStamp eventStamp = (EventStamp) stamp;
VEvent masterEvent = eventStamp.getMasterEvent();
checkDatesForComponent(masterEvent);
for(Component component : eventStamp.getExceptions()){
checkDatesForComponent(component);
}
}
private void checkDatesForComponent(Component component){
if(component == null){
return;
}
Property dtStart = component.getProperty(Property.DTSTART);
Property dtEnd = component.getProperty(Property.DTEND);
if( dtStart instanceof DtStart && dtStart.getValue()!= null
&& dtEnd instanceof DtEnd && dtEnd.getValue() != null
&& ((DtStart)dtStart).getDate().compareTo(((DtEnd)dtEnd).getDate()) > 0 ){
throw new IllegalArgumentException("End date [" + dtEnd + " is lower than start date [" + dtStart + "]");
}
}
/**
* Create new content items in a parent collection.
*
* @param parent
* parent collection of content items.
* @param contentItems
* content items to create
* @throws org.unitedinternet.cosmo.model.CollectionLockedException
* if parent CollectionItem is locked
*/
@Override
public void createContentItems(CollectionItem parent,
Set<ContentItem> contentItems) {
if (LOG.isDebugEnabled()) {
LOG.debug("creating content items in {}", parent.getName());
}
checkDatesForEvents(contentItems);
if (! lockManager.lockCollection(parent, lockTimeout)) {
throw new CollectionLockedException("unable to obtain collection lock");
}
try {
for(ContentItem content : contentItems) {
contentDao.createContent(parent, content);
}
contentDao.updateCollectionTimestamp(parent);
} finally {
lockManager.unlockCollection(parent);
}
}
@Override
public void updateCollectionTimestamp(CollectionItem parent) {
if (! lockManager.lockCollection(parent, lockTimeout)) {
throw new CollectionLockedException("unable to obtain collection lock");
}
try {
contentDao.updateCollectionTimestamp(parent);
LOG.debug("collection timestamp updated");
} finally {
lockManager.unlockCollection(parent);
}
}
@Override
public void createBatchContentItems(CollectionItem parent, Set<ContentItem> contentItems) {
if (LOG.isDebugEnabled()) {
LOG.debug("creating content items in {}", parent.getName());
}
checkDatesForEvents(contentItems);
if (! lockManager.lockCollection(parent, lockTimeout)) {
throw new CollectionLockedException("unable to obtain collection lock");
}
try {
contentDao.createBatchContent(parent, contentItems);
} finally {
lockManager.unlockCollection(parent);
}
}
@Override
public void updateBatchContentItems(CollectionItem parent, Set<ContentItem> contentItems) {
if (LOG.isDebugEnabled()) {
LOG.debug("updating content items in {}", parent.getName());
}
checkDatesForEvents(contentItems);
if (! lockManager.lockCollection(parent, lockTimeout)) {
throw new CollectionLockedException("unable to obtain collection lock");
}
try {
contentDao.updateBatchContent(contentItems);
contentDao.updateCollectionTimestamp(parent);
} finally {
lockManager.unlockCollection(parent);
}
}
@Override
public void removeBatchContentItems(CollectionItem parent, Set<ContentItem> contentItems) {
if (LOG.isDebugEnabled()) {
LOG.debug("removing content items in {}", parent.getName());
}
checkDatesForEvents(contentItems);
if (! lockManager.lockCollection(parent, lockTimeout)) {
throw new CollectionLockedException("unable to obtain collection lock");
}
try {
contentDao.removeBatchContent(parent, contentItems);
contentDao.updateCollectionTimestamp(parent);
} finally {
lockManager.unlockCollection(parent);
}
}
/**
* Update content items. This includes creating new items, removing
* existing items, and updating existing items. ContentItem deletion is
* represented by setting ContentItem.isActive to false. ContentItem deletion
* removes item from system, not just from the parent collections.
* ContentItem creation adds the item to the specified parent collections.
*
* @param parent
* parents that new content items will be added to.
* @param contentItems to update
* @throws org.unitedinternet.cosmo.model.CollectionLockedException
* if parent CollectionItem is locked
*/
public void updateContentItems(CollectionItem parent, Set<ContentItem> contentItems) {
if (LOG.isDebugEnabled()) {
LOG.debug("updating content items");
}
checkDatesForEvents(contentItems);
/*
* Obtain locks to all collections involved. A collection is involved if it is the parent of one of updated
* items.
*/
Set<CollectionItem> locks = acquireLocks(contentItems);
try {
for(ContentItem content: contentItems) {
if(content.getCreationDate()==null) {
contentDao.createContent(parent, content);
}
else if(Boolean.FALSE.equals(content.getIsActive())) {
contentDao.removeContent(content);
}
else {
contentDao.updateContent(content);
}
}
// update collections
for(CollectionItem collectionItem : locks) {
contentDao.updateCollectionTimestamp(collectionItem);
}
} finally {
releaseLocks(locks);
}
}
/**
* Update an existing content item.
*
* @param content
* content item to update
* @return updated content item
* @throws org.unitedinternet.cosmo.model.CollectionLockedException
* if parent CollectionItem is locked
*/
public ContentItem updateContent(ContentItem content) {
if (LOG.isDebugEnabled()) {
LOG.debug("updating content item {}", content.getUid());
}
checkDatesForEvent(content);
Set<CollectionItem> locks = acquireLocks(content);
try {
content = contentDao.updateContent(content);
// update collections
for(CollectionItem parent : locks) {
contentDao.updateCollectionTimestamp(parent);
}
return content;
} finally {
releaseLocks(locks);
}
}
/**
* Remove content item
*
* @param content
* content item to remove
* @throws org.unitedinternet.cosmo.model.CollectionLockedException
* if parent CollectionItem is locked
*/
public void removeContent(ContentItem content) {
if (LOG.isDebugEnabled()) {
LOG.debug("removing content item {}", content.getUid());
}
Set<CollectionItem> locks = acquireLocks(content);
try {
contentDao.removeContent(content);
// update collections
for(CollectionItem parent : locks) {
contentDao.updateCollectionTimestamp(parent);
}
} finally {
releaseLocks(locks);
}
}
/**
* Find note items by triage status that belong to a collection.
* @param collection collection
* @param context the query context
* @return set of notes that match the specified triage status label and
* belong to the specified collection
*/
@Transactional(readOnly = true)
public SortedSet<NoteItem> findNotesByTriageStatus(CollectionItem collection,
TriageStatusQueryContext context) {
return triageStatusQueryProcessor.processTriageStatusQuery(collection,
context);
}
/**
* Find note items by triage status that belong to a recurring note series.
* @param note recurring note
* @param context the query context
* @return set of notes that match the specified triage status label and belong
* to the specified recurring note series
*/
@Transactional(readOnly = true)
public SortedSet<NoteItem> findNotesByTriageStatus(NoteItem note,
TriageStatusQueryContext context) {
return triageStatusQueryProcessor.processTriageStatusQuery(note,
context);
}
/**
* find the set of collection items as children of the given collection item.
*
* @param collectionItem parent collection item
* @return set of children collection items or empty list of parent collection has no children
*/
@Transactional(readOnly = true)
public Set<CollectionItem> findCollectionItems(CollectionItem collectionItem) {
return contentDao.findCollectionItems(collectionItem);
}
/**
* Find items by filter.
*
* @param filter
* filter to use in search
* @return set items matching specified
* filter.
*/
@Transactional(readOnly = true)
public Set<Item> findItems(ItemFilter filter) {
return contentDao.findItems(filter);
}
/**
* Creates a ticket on an item.
*
* @param item the item to be ticketed
* @param ticket the ticket to be saved
*/
public void createTicket(Item item,
Ticket ticket) {
if (LOG.isDebugEnabled()) {
LOG.debug("creating ticket on item {}", item.getUid());
}
contentDao.createTicket(item, ticket);
}
/**
* Creates a ticket on an item.
*
* @param path the path of the item to be ticketed
* @param ticket the ticket to be saved
*/
public void createTicket(String path,
Ticket ticket) {
if (LOG.isDebugEnabled()) {
LOG.debug("creating ticket on item at path {}", path);
}
Item item = contentDao.findItemByPath(path);
if (item == null) {
throw new IllegalArgumentException("item not found for path " + path);
}
contentDao.createTicket(item, ticket);
}
/**
* Returns the identified ticket on the given item, or
* <code>null</code> if the ticket does not exists. Tickets are
* inherited, so if the specified item does not have the ticket
* but an ancestor does, it will still be returned.
*
* @param item the ticketed item
* @param key the ticket to return
*/
@Transactional(readOnly = true)
public Ticket getTicket(Item item,
String key) {
if (LOG.isDebugEnabled()) {
LOG.debug("getting ticket {} for item {}", key, item.getUid());
}
return contentDao.getTicket(item, key);
}
/**
* Removes a ticket from an item.
*
* @param item the item to be de-ticketed
* @param ticket the ticket to remove
*/
public void removeTicket(Item item,
Ticket ticket) {
if (LOG.isDebugEnabled()) {
LOG.debug("removing ticket {} on item {}",ticket.getKey(), item.getUid());
}
contentDao.removeTicket(item, ticket);
}
/**
* Removes a ticket from an item.
*
* @param item the item to be de-ticketed
* @param key the key of the ticket to remove
*/
public void removeTicket(Item item,
String key) {
if (LOG.isDebugEnabled()) {
LOG.debug("removing ticket {} on item {}", key, item.getUid());
}
if (item == null) {
throw new IllegalArgumentException("item required");
}
Ticket ticket = contentDao.getTicket(item, key);
if (ticket == null) {
return;
}
contentDao.removeTicket(item, ticket);
}
/**
* Given a set of items, aquire a lock on all parents
*/
private Set<CollectionItem> acquireLocks(Set<? extends Item> children) {
HashSet<CollectionItem> locks = new HashSet<CollectionItem>();
// Get locks for all collections involved
try {
for(Item child : children) {
acquireLocks(locks, child);
}
return locks;
} catch (RuntimeException e) {
releaseLocks(locks);
throw e;
}
}
/**
* Given a collection and a set of items, aquire a lock on the collection and
* all
*/
private Set<CollectionItem> acquireLocks(CollectionItem collection, Set<Item> children) {
HashSet<CollectionItem> locks = new HashSet<CollectionItem>();
// Get locks for all collections involved
try {
if (! lockManager.lockCollection(collection, lockTimeout)) {
throw new CollectionLockedException("unable to obtain collection lock");
}
locks.add(collection);
for(Item child : children) {
acquireLocks(locks, child);
}
return locks;
} catch (RuntimeException e) {
releaseLocks(locks);
throw e;
}
}
private Set<CollectionItem> acquireLocks(CollectionItem collection, Item item) {
HashSet<Item> items = new HashSet<Item>();
items.add(item);
return acquireLocks(collection, items);
}
private Set<CollectionItem> acquireLocks(Item item) {
HashSet<CollectionItem> locks = new HashSet<CollectionItem>();
try {
acquireLocks(locks,item);
return locks;
} catch (RuntimeException e) {
releaseLocks(locks);
throw e;
}
}
private void acquireLocks(Set<CollectionItem> locks, Item item) {
for(CollectionItem parent: item.getParents()) {
if(locks.contains(parent)) {
continue;
}
if (! lockManager.lockCollection(parent, lockTimeout)) {
throw new CollectionLockedException("unable to obtain collection lock");
}
locks.add(parent);
}
/*
* Acquire locks on master item's parents, as an addition/deletion of a modifications item affects all the
* parents of the master item.
*/
if(item instanceof NoteItem) {
NoteItem note = (NoteItem) item;
if(note.getModifies()!=null) {
acquireLocks(locks, note.getModifies());
}
}
}
private void releaseLocks(Set<CollectionItem> locks) {
for(CollectionItem lock : locks) {
lockManager.unlockCollection(lock);
}
}
private NoteOccurrence getNoteOccurrence(NoteItem parent, net.fortuna.ical4j.model.Date recurrenceId) {
EventStamp eventStamp = StampUtils.getEventStamp(parent);
// Parent must be a recurring event
if(eventStamp==null || !eventStamp.isRecurring()) {
return null;
}
RecurrenceId rid = null;
if(eventStamp.getEvent() != null && eventStamp.getEvent().getStartDate() != null){
DtStart startDate = eventStamp.getEvent().getStartDate();
rid = new RecurrenceId();
try {
if(startDate.isUtc()){
rid.setUtc(true);
}else if(startDate.getTimeZone() != null){
rid.setTimeZone(startDate.getTimeZone());
}
rid.setValue(recurrenceId.toString());
} catch (ParseException e) {
rid = null;
}
}
net.fortuna.ical4j.model.Date recurrenceIdToUse = rid == null ? recurrenceId : rid.getDate();
// Verify that occurrence date is valid
RecurrenceExpander expander = new RecurrenceExpander();
if(expander.isOccurrence(eventStamp.getEventCalendar(), recurrenceIdToUse)) {
return NoteOccurrenceUtil.createNoteOccurrence(recurrenceIdToUse, parent);
}
return null;
}
@Override
public void removeItemsFromCollection(CollectionItem collection) {
if(collection instanceof HomeCollectionItem) {
throw new IllegalArgumentException("cannot remove home collection");
}
contentDao.removeItemsFromCollection(collection);
contentDao.updateCollectionTimestamp(collection);
}
}
| |
package com.lonepulse.travisjr.app;
/*
* #%L
* Travis Jr.
* %%
* Copyright (C) 2013 Lonepulse
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.lonepulse.icklebot.activity.IckleActivity;
import com.lonepulse.icklebot.network.NetworkManager;
import com.lonepulse.icklebot.network.NetworkService;
import com.lonepulse.travisjr.R;
import com.lonepulse.travisjr.adapter.NavigationAdapter;
import com.lonepulse.travisjr.pref.SettingsActivity;
import com.lonepulse.travisjr.service.AccountService;
import com.lonepulse.travisjr.service.BasicAccountService;
import com.lonepulse.travisjr.view.NavigationSwipeDetector;
/**
* <p>A custom {@link IckleActivity} which is tailored to setup the {@link ActionBar} and provide support
* for syncing with Travis-CI.</p>
*
* @version 1.3.0
* <br><br>
* @since 1.1.0
* <br><br>
* @author <a href="mailto:lahiru@lonepulse.com">Lahiru Sahan Jayasinghe</a>
*/
public class TravisJrActivity extends IckleActivity {
/**
* <p>The {@link MenuItem} which initiates synchronization.
*/
private MenuItem menuItemSync;
/**
* <p>A custom view which is set on the sync action when
* synchronization begins.
*/
private View actionViewSync;
/**
* <p>A custom view which is set on the sync action when
* synchronization is complete.
*/
private View actionViewComplete;
/**
* <p>A custom view which is set on the sync action when
* a data connection is unavailable.
*/
private View actionViewData;
/**
* <p>This animation is invoked on {@link #actionViewSync}
* when synchronization starts.
*/
private Animation rotate;
/**
* <p>This animation is invoked on {@link #actionViewComplete}
* when synchronization is complete.
*/
private Animation fadeOut;
/**
* <p>The instance of {@link NetworkManager} which will be used
* to detect network state,
*/
private NetworkManager network;
/**
* <p>The IDs of the strings resources which make up the navigation list.
*/
private int[] navigationResourceIds;
/**
* <p>The instance of {@link AccountService} which is used to discover information
* about the current context's user.
*/
private AccountService accountService;
protected MenuItem getMenuItemSync() {
return menuItemSync;
}
protected void setMenuItemSync(MenuItem menuItemSync) {
this.menuItemSync = menuItemSync;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accountService = new BasicAccountService();
network = new NetworkService(this);
actionViewSync = getLayoutInflater().inflate(R.layout.action_view_sync, null);
actionViewComplete = getLayoutInflater().inflate(R.layout.action_view_complete, null);
actionViewData = getLayoutInflater().inflate(R.layout.action_view_data, null);
rotate = AnimationUtils.loadAnimation(this, R.anim.rotate);
actionViewSync.startAnimation(rotate);
fadeOut = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
fadeOut.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {
menuItemSync.setActionView(null);
}
});
Uri uri = getIntent().getData();
if(uri != null) {
onHandleUri(uri);
}
onInitActionBar(getActionBar());
}
/**
* <p>Override this callback to initialize the {@link ActionBar} associated with this {@link Activity}.</p>
*
* @param actionBar
* the {@link ActionBar} intance to be initialized
*
* @since 1.1.0
*/
protected void onInitActionBar(ActionBar actionBar) {
if(actionBar != null) {
View header = getLayoutInflater().inflate(R.layout.action_view_title, null);
((TextView)header.findViewById(R.id.title)).setText(onInitTitle());
((TextView)header.findViewById(R.id.subtitle)).setText(onInitSubtitle());
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(header);
}
}
/**
* <p>Creates a set of {@link ActionBar} navigation items for the given string resource IDs.</p>
*
* <p>This implementation employs {@link ActionBar#NAVIGATION_MODE_LIST}.</p>
*
* @param navigationResourceIds
* the array of String resource IDs for the navigation item titles
*
* @since 1.1.0
*/
protected void addNavigationItems(final int... navigationResourceIds) {
ActionBar actionBar = getActionBar();
if(actionBar != null) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
this.navigationResourceIds = navigationResourceIds;
String[] stringResources = new String[navigationResourceIds.length];
for (int i = 0; i < navigationResourceIds.length; i++) {
stringResources[i] = getString(navigationResourceIds[i]);
}
ArrayAdapter<String> adapter = NavigationAdapter.newInstance(actionBar.getThemedContext(),
R.layout.action_view_title_repo, android.R.id.text1, android.R.layout.simple_spinner_dropdown_item,
accountService.getGitHubUsername(this), stringResources);
actionBar.setListNavigationCallbacks(adapter, new ActionBar.OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
onTabSelected(navigationResourceIds[itemPosition]);
return true;
}
});
}
}
/**
* <p>Enables lateral swiping for {@link ActionBar} navigation tabs by detecting swipe gestures on the
* given target {@link View}.</p>
*
* @param targetViewId
* the compulsory target {@link View} which is to be swiped
*
* @param moreTargetViewIds
* additional IDs of the {@link View}s which can be swiped
*
* @since 1.1.0
*/
protected void enableNavigationSwiping(int targetViewId, int... moreTargetViewIds) {
NavigationSwipeDetector tabSwipeListener = new NavigationSwipeDetector(this);
View main = findViewById(targetViewId);
if(main != null) main.setOnTouchListener(tabSwipeListener);
for (int id : moreTargetViewIds) {
View view = findViewById(id);
if(view != null)
view.setOnTouchListener(tabSwipeListener);
}
}
/**
* <p>Override this callback to take action for a {@link Intent} which was fired in response to a <i>VIEW</i>
* action on a URL from the host <i>travis-ci.org</i></p>
*
* <p><b>Note</b> that this callback will be only be invoked if a {@link Uri} is present in the {@link Intent}
* which started this {@link Activity} (see {@link Activity#getIntent()}) and <b>before</b> the {@link ActionBar}
* is initialized using {@link #onInitActionBar(ActionBar)}.</p>
*
* @param uri
* the {@link Uri} which was received in the {@link Intent} which started this {@link Activity}
*
* @since 1.1.0
*/
protected void onHandleUri(Uri uri) {}
/**
* <p>Override this callback to take action upon <b>selecting</b> an {@link ActionBar.Tab} tab created with
* the String resource ID.</p>
*
* @param stringResourceId
* the String resource ID which was used to created the
* selected {@link ActionBar.Tab}
*
* @since 1.1.0
*/
protected void onTabSelected(int stringResourceId) {}
/**
* <p>Override this callback to take action upon <b>unselecting</b> an {@link ActionBar.Tab} tab created with
* the String resource ID.</p>
*
* @param stringResourceId
* the String resource ID which was used to created the unselected {@link ActionBar.Tab}
*
* @since 1.1.0
*/
protected void onTabUnselected(int stringResourceId) {}
/**
* <p>Override this callback to take action upon <b>reselecting</b> an {@link ActionBar.Tab} tab created with
* the String resource ID.</p>
*
* @param stringResourceId
* the String resource ID which was used to created the reselected {@link ActionBar.Tab}
*
* @since 1.1.0
*/
protected void onTabReselected(int stringResourceId) {}
/**
* <p>Retrieves the String resource ID of the currently selected navigation tab.</p>
*
* @return the String resource ID of the selected {@link ActionBar.Tab}, else {@code 0} if no navigation tabs
* are available
*
* @since 1.1.0
*/
protected int getSelectedTab() {
ActionBar actionBar = getActionBar();
return (actionBar != null && actionBar.getNavigationItemCount() > 0)?
navigationResourceIds[(Integer)actionBar.getSelectedNavigationIndex()] :0;
}
/**
* <p>Override this callback to initialize the activity with a custom title.</p>
*
* @return the title to be set for this activity; defaults to {@link Activity#getTitle()}
*
* @since 1.1.0
*/
protected String onInitTitle() {
return getTitle().toString();
}
/**
* <p>Override this callback to initialize the activity with a custom subtitle.</p>
*
* @return the subtitle to be set for this activity; defaults to the user's GitHub username
*
* @since 1.1.0
*/
protected String onInitSubtitle() {
return accountService.getGitHubUsername(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.basic, menu);
menuItemSync = menu.findItem(R.id.menu_sync);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_sync: {
if(network.isConnected()) {
onSync();
}
else {
runOnUiThread(new Runnable() {
@Override
public void run() {
menuItemSync.setActionView(actionViewData);
actionViewData.startAnimation(fadeOut);
}
});
}
break;
}
case R.id.menu_settings: {
SettingsActivity.start(this);
break;
}
}
return true;
}
/**
* <p>Override this callback to perform synchronization.</p>
*
* @since 1.1.0
*/
protected synchronized void onSync() {
startSyncAnimation();
}
/**
* <p>Invoke this service to set the sync lock and start the default sync animation on the action bar.</p>
*
* @since 1.1.0
*/
protected synchronized void startSyncAnimation() {
if(!isSyncing()) {
getTravisJrApplication().setSyncing(true);
if(menuItemSync != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
menuItemSync.setActionView(actionViewSync);
actionViewSync.startAnimation(rotate);
}
});
}
}
}
/**
* <p>Invoke this service to clear the sync lock and stop the default sync animation on the action bar.</p>
*
* @since 1.1.0
*/
protected synchronized void stopSyncAnimation() {
if(isSyncing()) {
getTravisJrApplication().setSyncing(false);
if(menuItemSync != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
actionViewSync.clearAnimation();
menuItemSync.setActionView(actionViewComplete);
actionViewComplete.startAnimation(fadeOut);
}
});
}
}
}
/**
* <p>Specifies whether a sync operation is currently underway.</p>
*
* @return {@code true} if there is an ongoing sync
*
* @since 1.1.0
*/
protected final boolean isSyncing() {
return getTravisJrApplication().isSyncing();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
ActionBar actionBar = getActionBar();
if(actionBar != null && actionBar.getTabCount() > 1)
outState.putInt(getString(R.string.key_tab), actionBar.getSelectedTab().getPosition());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
ActionBar actionBar = getActionBar();
if(actionBar != null && actionBar.getTabCount() > 1)
actionBar.setSelectedNavigationItem(savedInstanceState.getInt(getString(R.string.key_tab)));
}
/**
* <p>Returns the instance of {@link TravisJr} contract implementation.</p>
*
* @return the single instance of {@link TravisJr}
*
* @since 1.1.0
*/
protected final TravisJr getTravisJrApplication() {
return ((TravisJr)getApplication());
}
}
| |
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.apple.laf;
import java.awt.*;
import java.lang.ref.*;
import java.util.*;
import java.util.concurrent.locks.*;
import apple.laf.JRSUIConstants;
import apple.laf.JRSUIState;
import com.apple.laf.AquaUtils.RecyclableSingleton;
/**
* ImageCache - A fixed pixel count sized cache of Images keyed by arbitrary set of arguments. All images are held with
* SoftReferences so they will be dropped by the GC if heap memory gets tight. When our size hits max pixel count least
* recently requested images are removed first.
*/
final class ImageCache {
// Ordered Map keyed by args hash, ordered by most recent accessed entry.
private final LinkedHashMap<Integer, PixelCountSoftReference> map = new LinkedHashMap<>(16, 0.75f, true);
// Maximum number of pixels to cache, this is used if maxCount
private final int maxPixelCount;
// The current number of pixels stored in the cache
private int currentPixelCount = 0;
// Lock for concurrent access to map
private final ReadWriteLock lock = new ReentrantReadWriteLock();
// Reference queue for tracking lost softreferences to images in the cache
private final ReferenceQueue<Image> referenceQueue = new ReferenceQueue<>();
// Singleton Instance
private static final RecyclableSingleton<ImageCache> instance = new RecyclableSingleton<ImageCache>() {
@Override
protected ImageCache getInstance() {
return new ImageCache();
}
};
static ImageCache getInstance() {
return instance.get();
}
ImageCache(final int maxPixelCount) {
this.maxPixelCount = maxPixelCount;
}
ImageCache() {
this((8 * 1024 * 1024) / 4); // 8Mb of pixels
}
public void flush() {
lock.writeLock().lock();
try {
map.clear();
} finally {
lock.writeLock().unlock();
}
}
public Image getImage(final GraphicsConfiguration config, final int w,
final int h, final int scale,
final JRSUIState state) {
final int hash = hash(config, w, h, scale, state);
final PixelCountSoftReference ref;
lock.readLock().lock();
try {
ref = map.get(hash);
} finally {
lock.readLock().unlock();
}
// check reference has not been lost and the key truly matches,
// in case of false positive hash match
if (ref != null && ref.equals(config, w, h, scale, state)) {
return ref.get();
}
return null;
}
/**
* Sets the cached image for the specified constraints.
*
* @param image The image to store in cache
* @param config The graphics configuration, needed if cached image is a Volatile Image. Used as part of cache key
* @param w The image width, used as part of cache key
* @param h The image height, used as part of cache key
* @param scale The image scale factor, used as part of cache key
* @return true if the image could be cached, false otherwise.
*/
public boolean setImage(final Image image,
final GraphicsConfiguration config, final int w, final int h,
final int scale, final JRSUIState state) {
if (state.is(JRSUIConstants.Animating.YES)) {
return false;
}
final int hash = hash(config, w, h, scale, state);
lock.writeLock().lock();
try {
PixelCountSoftReference ref = map.get(hash);
// check if currently in map
if (ref != null && ref.get() == image) return true;
// clear out old
if (ref != null) {
currentPixelCount -= ref.pixelCount;
map.remove(hash);
}
// add new image to pixel count
final int newPixelCount = image.getWidth(null) * image.getHeight(null);
currentPixelCount += newPixelCount;
// clean out lost references if not enough space
if (currentPixelCount > maxPixelCount) {
while ((ref = (PixelCountSoftReference)referenceQueue.poll()) != null) {
//reference lost
map.remove(ref.hash);
currentPixelCount -= ref.pixelCount;
}
}
// remove old items till there is enough free space
if (currentPixelCount > maxPixelCount) {
final Iterator<Map.Entry<Integer, PixelCountSoftReference>> mapIter = map.entrySet().iterator();
while ((currentPixelCount > maxPixelCount) && mapIter.hasNext()) {
final Map.Entry<Integer, PixelCountSoftReference> entry = mapIter.next();
mapIter.remove();
final Image img = entry.getValue().get();
if (img != null) img.flush();
currentPixelCount -= entry.getValue().pixelCount;
}
}
// finally put new in map
map.put(hash, new PixelCountSoftReference(image, referenceQueue, newPixelCount, hash, config, w, h, scale, state));
return true;
} finally {
lock.writeLock().unlock();
}
}
private static int hash(final GraphicsConfiguration config, final int w,
final int h, final int scale,
final JRSUIState state) {
int hash = config != null ? config.hashCode() : 0;
hash = 31 * hash + w;
hash = 31 * hash + h;
hash = 31 * hash + scale;
hash = 31 * hash + state.hashCode();
return hash;
}
/**
* Extended SoftReference that stores the pixel count even after the image
* is lost.
*/
private static class PixelCountSoftReference extends SoftReference<Image> {
// default access, because access to these fields shouldn't be emulated
// by a synthetic accessor.
final int pixelCount;
final int hash;
// key parts
private final GraphicsConfiguration config;
private final int w;
private final int h;
private final int scale;
private final JRSUIState state;
PixelCountSoftReference(final Image referent,
final ReferenceQueue<? super Image> q, final int pixelCount,
final int hash, final GraphicsConfiguration config, final int w,
final int h, final int scale, final JRSUIState state) {
super(referent, q);
this.pixelCount = pixelCount;
this.hash = hash;
this.config = config;
this.w = w;
this.h = h;
this.scale = scale;
this.state = state;
}
boolean equals(final GraphicsConfiguration config, final int w,
final int h, final int scale, final JRSUIState state) {
return config == this.config && w == this.w && h == this.h
&& scale == this.scale && state.equals(this.state);
}
}
// /** Gets the rendered image for this painter at the requested size, either from cache or create a new one */
// private VolatileImage getImage(GraphicsConfiguration config, JComponent c, int w, int h, Object[] extendedCacheKeys) {
// VolatileImage buffer = (VolatileImage)getImage(config, w, h, this, extendedCacheKeys);
//
// int renderCounter = 0; // to avoid any potential, though unlikely, infinite loop
// do {
// //validate the buffer so we can check for surface loss
// int bufferStatus = VolatileImage.IMAGE_INCOMPATIBLE;
// if (buffer != null) {
// bufferStatus = buffer.validate(config);
// }
//
// //If the buffer status is incompatible or restored, then we need to re-render to the volatile image
// if (bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE || bufferStatus == VolatileImage.IMAGE_RESTORED) {
// // if the buffer isn't the right size, or has lost its contents, then recreate
// if (buffer != null) {
// if (buffer.getWidth() != w || buffer.getHeight() != h || bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE) {
// // clear any resources related to the old back buffer
// buffer.flush();
// buffer = null;
// }
// }
//
// if (buffer == null) {
// // recreate the buffer
// buffer = config.createCompatibleVolatileImage(w, h, Transparency.TRANSLUCENT);
// // put in cache for future
// setImage(buffer, config, w, h, this, extendedCacheKeys);
// }
//
// //create the graphics context with which to paint to the buffer
// Graphics2D bg = buffer.createGraphics();
//
// //clear the background before configuring the graphics
// bg.setComposite(AlphaComposite.Clear);
// bg.fillRect(0, 0, w, h);
// bg.setComposite(AlphaComposite.SrcOver);
// bg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//
// // paint the painter into buffer
// paint0(bg, c, w, h, extendedCacheKeys);
// //close buffer graphics
// bg.dispose();
// }
// } while (buffer.contentsLost() && renderCounter++ < 3);
//
// // check if we failed
// if (renderCounter >= 3) return null;
//
// return buffer;
// }
}
| |
package net.CyanWool.api.utils;
import java.util.Random;
import net.CyanWool.api.world.Location;
import net.CyanWool.api.world.World;
public class Vector {
private static Random random = new Random();
private static double epsilon = 0.000001;
private double x;
private double y;
private double z;
public Vector() {
this.x = 0;
this.y = 0;
this.z = 0;
}
public Vector(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector add(Vector vec) {
x += vec.x;
y += vec.y;
z += vec.z;
return this;
}
public Vector subtract(Vector vec) {
x -= vec.x;
y -= vec.y;
z -= vec.z;
return this;
}
public Vector multiply(Vector vec) {
x *= vec.x;
y *= vec.y;
z *= vec.z;
return this;
}
public Vector divide(Vector vec) {
x /= vec.x;
y /= vec.y;
z /= vec.z;
return this;
}
public Vector copy(Vector vec) {
x = vec.x;
y = vec.y;
z = vec.z;
return this;
}
public double length() {
return Math.sqrt(NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z));
}
public double lengthSquared() {
return NumberConversions.square(x) + NumberConversions.square(y) + NumberConversions.square(z);
}
public double distance(Vector o) {
return Math.sqrt(NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z));
}
public double distanceSquared(Vector o) {
return NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z);
}
public float angle(Vector other) {
double dot = dot(other) / (length() * other.length());
return (float) Math.acos(dot);
}
public Vector midpoint(Vector other) {
x = (x + other.x) / 2;
y = (y + other.y) / 2;
z = (z + other.z) / 2;
return this;
}
public Vector getMidpoint(Vector other) {
double x = (this.x + other.x) / 2;
double y = (this.y + other.y) / 2;
double z = (this.z + other.z) / 2;
return new Vector(x, y, z);
}
public Vector multiply(int m) {
x *= m;
y *= m;
z *= m;
return this;
}
public Vector multiply(double m) {
x *= m;
y *= m;
z *= m;
return this;
}
public Vector multiply(float m) {
x *= m;
y *= m;
z *= m;
return this;
}
public double dot(Vector other) {
return x * other.x + y * other.y + z * other.z;
}
public Vector crossProduct(Vector o) {
double newX = y * o.z - o.y * z;
double newY = z * o.x - o.z * x;
double newZ = x * o.y - o.x * y;
x = newX;
y = newY;
z = newZ;
return this;
}
public Vector normalize() {
double length = length();
x /= length;
y /= length;
z /= length;
return this;
}
public Vector zero() {
x = 0;
y = 0;
z = 0;
return this;
}
public boolean isInAABB(Vector min, Vector max) {
return x >= min.x && x <= max.x && y >= min.y && y <= max.y && z >= min.z && z <= max.z;
}
public boolean isInSphere(Vector origin, double radius) {
return (NumberConversions.square(origin.x - x) + NumberConversions.square(origin.y - y) + NumberConversions.square(origin.z - z)) <= NumberConversions.square(radius);
}
public double getX() {
return x;
}
public int getBlockX() {
return NumberConversions.floor(x);
}
public double getY() {
return y;
}
public int getBlockY() {
return NumberConversions.floor(y);
}
public double getZ() {
return z;
}
public int getBlockZ() {
return NumberConversions.floor(z);
}
public Vector setX(int x) {
this.x = x;
return this;
}
public Vector setX(double x) {
this.x = x;
return this;
}
public Vector setX(float x) {
this.x = x;
return this;
}
public Vector setY(int y) {
this.y = y;
return this;
}
public Vector setY(double y) {
this.y = y;
return this;
}
public Vector setY(float y) {
this.y = y;
return this;
}
public Vector setZ(int z) {
this.z = z;
return this;
}
public Vector setZ(double z) {
this.z = z;
return this;
}
public Vector setZ(float z) {
this.z = z;
return this;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Vector)) {
return false;
}
Vector other = (Vector) obj;
return Math.abs(x - other.x) < epsilon && Math.abs(y - other.y) < epsilon && Math.abs(z - other.z) < epsilon && (this.getClass().equals(obj.getClass()));
}
public Location toLocation(World world) {
return new Location(world, x, y, z);
}
public Location toLocation(World world, float yaw, float pitch) {
return new Location(world, x, y, z, yaw, pitch);
}
public static double getEpsilon() {
return epsilon;
}
public static Vector getMinimum(Vector v1, Vector v2) {
return new Vector(Math.min(v1.x, v2.x), Math.min(v1.y, v2.y), Math.min(v1.z, v2.z));
}
public static Vector getMaximum(Vector v1, Vector v2) {
return new Vector(Math.max(v1.x, v2.x), Math.max(v1.y, v2.y), Math.max(v1.z, v2.z));
}
public static Vector getRandom() {
return new Vector(random.nextDouble(), random.nextDouble(), random.nextDouble());
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.signer.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* The validity period for a signing job.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/signer-2017-08-25/SignatureValidityPeriod" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SignatureValidityPeriod implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The numerical value of the time unit for signature validity.
* </p>
*/
private Integer value;
/**
* <p>
* The time unit for signature validity.
* </p>
*/
private String type;
/**
* <p>
* The numerical value of the time unit for signature validity.
* </p>
*
* @param value
* The numerical value of the time unit for signature validity.
*/
public void setValue(Integer value) {
this.value = value;
}
/**
* <p>
* The numerical value of the time unit for signature validity.
* </p>
*
* @return The numerical value of the time unit for signature validity.
*/
public Integer getValue() {
return this.value;
}
/**
* <p>
* The numerical value of the time unit for signature validity.
* </p>
*
* @param value
* The numerical value of the time unit for signature validity.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SignatureValidityPeriod withValue(Integer value) {
setValue(value);
return this;
}
/**
* <p>
* The time unit for signature validity.
* </p>
*
* @param type
* The time unit for signature validity.
* @see ValidityType
*/
public void setType(String type) {
this.type = type;
}
/**
* <p>
* The time unit for signature validity.
* </p>
*
* @return The time unit for signature validity.
* @see ValidityType
*/
public String getType() {
return this.type;
}
/**
* <p>
* The time unit for signature validity.
* </p>
*
* @param type
* The time unit for signature validity.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ValidityType
*/
public SignatureValidityPeriod withType(String type) {
setType(type);
return this;
}
/**
* <p>
* The time unit for signature validity.
* </p>
*
* @param type
* The time unit for signature validity.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ValidityType
*/
public SignatureValidityPeriod withType(ValidityType type) {
this.type = type.toString();
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getValue() != null)
sb.append("Value: ").append(getValue()).append(",");
if (getType() != null)
sb.append("Type: ").append(getType());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SignatureValidityPeriod == false)
return false;
SignatureValidityPeriod other = (SignatureValidityPeriod) obj;
if (other.getValue() == null ^ this.getValue() == null)
return false;
if (other.getValue() != null && other.getValue().equals(this.getValue()) == false)
return false;
if (other.getType() == null ^ this.getType() == null)
return false;
if (other.getType() != null && other.getType().equals(this.getType()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getValue() == null) ? 0 : getValue().hashCode());
hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode());
return hashCode;
}
@Override
public SignatureValidityPeriod clone() {
try {
return (SignatureValidityPeriod) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.signer.model.transform.SignatureValidityPeriodMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
package org.rabix.bindings.model;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.rabix.bindings.json.JobValuesDeserializer;
import org.rabix.common.helper.CloneHelper;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Job implements Serializable {
/**
*
*/
private static final long serialVersionUID = -202012646416646107L;
public static enum JobStatus {
PENDING,
READY,
STARTED,
ABORTED,
FAILED,
COMPLETED,
RUNNING
}
@JsonProperty("id")
private final UUID id;
@JsonProperty("parentId")
private final UUID parentId;
@JsonProperty("rootId")
private final UUID rootId;
@JsonProperty("name")
private final String name;
@JsonProperty("app")
private final String app;
@JsonProperty("status")
private final JobStatus status;
@JsonProperty("message")
private final String message;
@JsonProperty("config")
private final Map<String, Object> config;
@JsonProperty("inputs")
@JsonDeserialize(using = JobValuesDeserializer.class)
private final Map<String, Object> inputs;
@JsonProperty("outputs")
@JsonDeserialize(using = JobValuesDeserializer.class)
private final Map<String, Object> outputs;
@JsonProperty("resources")
private final Resources resources;
@JsonProperty("visiblePorts")
private Set<String> visiblePorts;
public Job(String app, Map<String, Object> inputs) {
this(null, null, generateId(), null, app, JobStatus.PENDING, null, inputs, null, null, null, null);
}
@JsonCreator
public Job(@JsonProperty("id") UUID id,
@JsonProperty("parentId") UUID parentId,
@JsonProperty("rootId") UUID rootId,
@JsonProperty("name") String name,
@JsonProperty("app") String app,
@JsonProperty("status") JobStatus status,
@JsonProperty("message") String message,
@JsonProperty("inputs") Map<String, Object> inputs,
@JsonProperty("outputs") Map<String, Object> otputs,
@JsonProperty("config") Map<String, Object> config,
@JsonProperty("resources") Resources resources,
@JsonProperty("visiblePorts") Set<String> visiblePorts) {
this.id = id;
this.parentId = parentId;
this.rootId = rootId;
this.name = name;
this.app = app;
this.status = status;
this.message = message;
this.inputs = inputs;
this.outputs = otputs;
this.resources = resources;
this.config = config;
this.visiblePorts = visiblePorts;
}
public static UUID generateId() {
return UUID.randomUUID();
}
public static Job cloneWithId(Job job, UUID id) {
return new Job(id, job.parentId, job.rootId, job.name, job.app, job.status, job.message, job.inputs, job.outputs, job.config, job.resources, job.visiblePorts);
}
public static Job cloneWithName(Job job, String name) {
return new Job(job.id, job.parentId, job.rootId, name, job.app, job.status, job.message, job.inputs, job.outputs, job.config, job.resources, job.visiblePorts);
}
public static Job cloneWithIds(Job job, UUID id, UUID rootId) {
return new Job(id, job.parentId, rootId, job.name, job.app, job.status, job.message, job.inputs, job.outputs, job.config, job.resources, job.visiblePorts);
}
public static Job cloneWithRootId(Job job, UUID rootId) {
return new Job(job.getId(), job.parentId, rootId, job.name, job.app, job.status, job.message, job.inputs, job.outputs, job.config, job.resources, job.visiblePorts);
}
public static Job cloneWithConfig(Job job, Map<String, Object> config) {
return new Job(job.id, job.parentId, job.rootId, job.name, job.app, job.status, job.message, job.inputs, job.outputs, config, job.resources, job.visiblePorts);
}
public static Job cloneWithStatus(Job job, JobStatus status) {
return new Job(job.id, job.parentId, job.rootId, job.name, job.app, status, job.message, job.inputs, job.outputs, job.config, job.resources, job.visiblePorts);
}
public static Job cloneWithMessage(Job job, String message) {
return new Job(job.id, job.parentId, job.rootId, job.name, job.app, job.status, message, job.inputs, job.outputs, job.config, job.resources, job.visiblePorts);
}
public static Job cloneWithInputs(Job job, Map<String, Object> inputs) {
return new Job(job.id, job.parentId, job.rootId, job.name, job.app, job.status, job.message, inputs, job.outputs, job.config, job.resources, job.visiblePorts);
}
public static Job cloneWithOutputs(Job job, Map<String, Object> outputs) {
return new Job(job.id, job.parentId, job.rootId, job.name, job.app, job.status, job.message, job.inputs, outputs, job.config, job.resources, job.visiblePorts);
}
public static Job cloneWithResources(Job job, Resources resources) {
return new Job(job.id, job.parentId, job.rootId, job.name, job.app, job.status, job.message, job.inputs, job.outputs, job.config, resources, job.visiblePorts);
}
public static boolean isFinished(Job job) {
return job.getStatus().equals(JobStatus.COMPLETED)
|| job.getStatus().equals(JobStatus.ABORTED)
|| job.getStatus().equals(JobStatus.FAILED);
}
@JsonIgnore
public boolean isRoot() {
if (id == null) {
return false;
}
return id.equals(rootId);
}
public UUID getId() {
return id;
}
public String getMessage() {
return message;
}
public UUID getParentId() {
return parentId;
}
public UUID getRootId() {
return rootId;
}
public String getName() {
return name;
}
public String getApp() {
return app;
}
public Resources getResources() {
return resources;
}
public Set<String> getVisiblePorts() {
return visiblePorts;
}
@SuppressWarnings("unchecked")
public Map<String, Object> getInputs() {
try {
return (Map<String, Object>) CloneHelper.deepCopy(inputs);
} catch (Exception e) {
throw new RuntimeException("Failed to clone inputs", e);
}
}
@SuppressWarnings("unchecked")
public Map<String, Object> getOutputs() {
try {
return (Map<String, Object>) CloneHelper.deepCopy(outputs);
} catch (Exception e) {
throw new RuntimeException("Failed to clone outputs", e);
}
}
public JobStatus getStatus() {
return status;
}
public Map<String, Object> getConfig() {
return config;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((app == null) ? 0 : app.hashCode());
result = prime * result + ((config == null) ? 0 : config.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((inputs == null) ? 0 : inputs.hashCode());
result = prime * result + ((message == null) ? 0 : message.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((outputs == null) ? 0 : outputs.hashCode());
result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
result = prime * result + ((resources == null) ? 0 : resources.hashCode());
result = prime * result + ((rootId == null) ? 0 : rootId.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((visiblePorts == null) ? 0 : visiblePorts.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Job other = (Job) obj;
if (app == null) {
if (other.app != null)
return false;
} else if (!app.equals(other.app))
return false;
if (config == null) {
if (other.config != null)
return false;
} else if (!config.equals(other.config))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (inputs == null) {
if (other.inputs != null)
return false;
} else if (!inputs.equals(other.inputs))
return false;
if (message == null) {
if (other.message != null)
return false;
} else if (!message.equals(other.message))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (outputs == null) {
if (other.outputs != null)
return false;
} else if (!outputs.equals(other.outputs))
return false;
if (parentId == null) {
if (other.parentId != null)
return false;
} else if (!parentId.equals(other.parentId))
return false;
if (resources == null) {
if (other.resources != null)
return false;
} else if (!resources.equals(other.resources))
return false;
if (rootId == null) {
if (other.rootId != null)
return false;
} else if (!rootId.equals(other.rootId))
return false;
if (status != other.status)
return false;
if (visiblePorts == null) {
if (other.visiblePorts != null)
return false;
} else if (!visiblePorts.equals(other.visiblePorts))
return false;
return true;
}
@Override
public String toString() {
return "Job [id=" + id + ", parentId=" + parentId + ", rootId=" + rootId + ", name=" + name + ", status=" + status + ", message=" + message + ", config=" + config + ", inputs=" + inputs + ", outputs=" + outputs + "]";
}
}
| |
/*
* 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.builder.endpoint.dsl;
import java.util.concurrent.BlockingQueue;
import javax.annotation.Generated;
import org.apache.camel.ExchangePattern;
import org.apache.camel.WaitForTaskToComplete;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;
import org.apache.camel.spi.ExceptionHandler;
/**
* Asynchronously call another endpoint from any Camel Context in the same JVM.
*
* Generated by camel build tools - do NOT edit this file!
*/
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface SedaEndpointBuilderFactory {
/**
* Builder for endpoint consumers for the SEDA component.
*/
public interface SedaEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default AdvancedSedaEndpointConsumerBuilder advanced() {
return (AdvancedSedaEndpointConsumerBuilder) this;
}
/**
* The maximum capacity of the SEDA queue (i.e., the number of messages
* it can hold). Will by default use the defaultSize set on the SEDA
* component.
*
* The option is a: <code>int</code> type.
*
* Default: 1000
* Group: common
*
* @param size the value to set
* @return the dsl builder
*/
default SedaEndpointConsumerBuilder size(int size) {
doSetProperty("size", size);
return this;
}
/**
* The maximum capacity of the SEDA queue (i.e., the number of messages
* it can hold). Will by default use the defaultSize set on the SEDA
* component.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 1000
* Group: common
*
* @param size the value to set
* @return the dsl builder
*/
default SedaEndpointConsumerBuilder size(String size) {
doSetProperty("size", size);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default SedaEndpointConsumerBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default SedaEndpointConsumerBuilder bridgeErrorHandler(
String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Number of concurrent threads processing exchanges.
*
* The option is a: <code>int</code> type.
*
* Default: 1
* Group: consumer
*
* @param concurrentConsumers the value to set
* @return the dsl builder
*/
default SedaEndpointConsumerBuilder concurrentConsumers(
int concurrentConsumers) {
doSetProperty("concurrentConsumers", concurrentConsumers);
return this;
}
/**
* Number of concurrent threads processing exchanges.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 1
* Group: consumer
*
* @param concurrentConsumers the value to set
* @return the dsl builder
*/
default SedaEndpointConsumerBuilder concurrentConsumers(
String concurrentConsumers) {
doSetProperty("concurrentConsumers", concurrentConsumers);
return this;
}
}
/**
* Advanced builder for endpoint consumers for the SEDA component.
*/
public interface AdvancedSedaEndpointConsumerBuilder
extends
EndpointConsumerBuilder {
default SedaEndpointConsumerBuilder basic() {
return (SedaEndpointConsumerBuilder) this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a:
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder exceptionHandler(
ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder exceptionHandler(
String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a:
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder exchangePattern(
ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder exchangePattern(
String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Whether to limit the number of concurrentConsumers to the maximum of
* 500. By default, an exception will be thrown if an endpoint is
* configured with a greater number. You can disable that check by
* turning this option off.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: consumer (advanced)
*
* @param limitConcurrentConsumers the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder limitConcurrentConsumers(
boolean limitConcurrentConsumers) {
doSetProperty("limitConcurrentConsumers", limitConcurrentConsumers);
return this;
}
/**
* Whether to limit the number of concurrentConsumers to the maximum of
* 500. By default, an exception will be thrown if an endpoint is
* configured with a greater number. You can disable that check by
* turning this option off.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: true
* Group: consumer (advanced)
*
* @param limitConcurrentConsumers the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder limitConcurrentConsumers(
String limitConcurrentConsumers) {
doSetProperty("limitConcurrentConsumers", limitConcurrentConsumers);
return this;
}
/**
* Specifies whether multiple consumers are allowed. If enabled, you can
* use SEDA for Publish-Subscribe messaging. That is, you can send a
* message to the SEDA queue and have each consumer receive a copy of
* the message. When enabled, this option should be specified on every
* consumer endpoint.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param multipleConsumers the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder multipleConsumers(
boolean multipleConsumers) {
doSetProperty("multipleConsumers", multipleConsumers);
return this;
}
/**
* Specifies whether multiple consumers are allowed. If enabled, you can
* use SEDA for Publish-Subscribe messaging. That is, you can send a
* message to the SEDA queue and have each consumer receive a copy of
* the message. When enabled, this option should be specified on every
* consumer endpoint.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer (advanced)
*
* @param multipleConsumers the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder multipleConsumers(
String multipleConsumers) {
doSetProperty("multipleConsumers", multipleConsumers);
return this;
}
/**
* The timeout used when polling. When a timeout occurs, the consumer
* can check whether it is allowed to continue running. Setting a lower
* value allows the consumer to react more quickly upon shutdown.
*
* The option is a: <code>int</code> type.
*
* Default: 1000
* Group: consumer (advanced)
*
* @param pollTimeout the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder pollTimeout(int pollTimeout) {
doSetProperty("pollTimeout", pollTimeout);
return this;
}
/**
* The timeout used when polling. When a timeout occurs, the consumer
* can check whether it is allowed to continue running. Setting a lower
* value allows the consumer to react more quickly upon shutdown.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 1000
* Group: consumer (advanced)
*
* @param pollTimeout the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder pollTimeout(
String pollTimeout) {
doSetProperty("pollTimeout", pollTimeout);
return this;
}
/**
* Whether to purge the task queue when stopping the consumer/route.
* This allows to stop faster, as any pending messages on the queue is
* discarded.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param purgeWhenStopping the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder purgeWhenStopping(
boolean purgeWhenStopping) {
doSetProperty("purgeWhenStopping", purgeWhenStopping);
return this;
}
/**
* Whether to purge the task queue when stopping the consumer/route.
* This allows to stop faster, as any pending messages on the queue is
* discarded.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: consumer (advanced)
*
* @param purgeWhenStopping the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder purgeWhenStopping(
String purgeWhenStopping) {
doSetProperty("purgeWhenStopping", purgeWhenStopping);
return this;
}
/**
* Define the queue instance which will be used by the endpoint.
*
* The option is a:
* <code>java.util.concurrent.BlockingQueue</code> type.
*
* Group: advanced
*
* @param queue the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder queue(BlockingQueue queue) {
doSetProperty("queue", queue);
return this;
}
/**
* Define the queue instance which will be used by the endpoint.
*
* The option will be converted to a
* <code>java.util.concurrent.BlockingQueue</code> type.
*
* Group: advanced
*
* @param queue the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointConsumerBuilder queue(String queue) {
doSetProperty("queue", queue);
return this;
}
}
/**
* Builder for endpoint producers for the SEDA component.
*/
public interface SedaEndpointProducerBuilder
extends
EndpointProducerBuilder {
default AdvancedSedaEndpointProducerBuilder advanced() {
return (AdvancedSedaEndpointProducerBuilder) this;
}
/**
* The maximum capacity of the SEDA queue (i.e., the number of messages
* it can hold). Will by default use the defaultSize set on the SEDA
* component.
*
* The option is a: <code>int</code> type.
*
* Default: 1000
* Group: common
*
* @param size the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder size(int size) {
doSetProperty("size", size);
return this;
}
/**
* The maximum capacity of the SEDA queue (i.e., the number of messages
* it can hold). Will by default use the defaultSize set on the SEDA
* component.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 1000
* Group: common
*
* @param size the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder size(String size) {
doSetProperty("size", size);
return this;
}
/**
* Whether a thread that sends messages to a full SEDA queue will block
* until the queue's capacity is no longer exhausted. By default, an
* exception will be thrown stating that the queue is full. By enabling
* this option, the calling thread will instead block and wait until the
* message can be accepted.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param blockWhenFull the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder blockWhenFull(boolean blockWhenFull) {
doSetProperty("blockWhenFull", blockWhenFull);
return this;
}
/**
* Whether a thread that sends messages to a full SEDA queue will block
* until the queue's capacity is no longer exhausted. By default, an
* exception will be thrown stating that the queue is full. By enabling
* this option, the calling thread will instead block and wait until the
* message can be accepted.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param blockWhenFull the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder blockWhenFull(String blockWhenFull) {
doSetProperty("blockWhenFull", blockWhenFull);
return this;
}
/**
* Whether the producer should discard the message (do not add the
* message to the queue), when sending to a queue with no active
* consumers. Only one of the options discardIfNoConsumers and
* failIfNoConsumers can be enabled at the same time.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param discardIfNoConsumers the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder discardIfNoConsumers(
boolean discardIfNoConsumers) {
doSetProperty("discardIfNoConsumers", discardIfNoConsumers);
return this;
}
/**
* Whether the producer should discard the message (do not add the
* message to the queue), when sending to a queue with no active
* consumers. Only one of the options discardIfNoConsumers and
* failIfNoConsumers can be enabled at the same time.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param discardIfNoConsumers the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder discardIfNoConsumers(
String discardIfNoConsumers) {
doSetProperty("discardIfNoConsumers", discardIfNoConsumers);
return this;
}
/**
* Whether a thread that sends messages to a full SEDA queue will be
* discarded. By default, an exception will be thrown stating that the
* queue is full. By enabling this option, the calling thread will give
* up sending and continue, meaning that the message was not sent to the
* SEDA queue.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param discardWhenFull the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder discardWhenFull(
boolean discardWhenFull) {
doSetProperty("discardWhenFull", discardWhenFull);
return this;
}
/**
* Whether a thread that sends messages to a full SEDA queue will be
* discarded. By default, an exception will be thrown stating that the
* queue is full. By enabling this option, the calling thread will give
* up sending and continue, meaning that the message was not sent to the
* SEDA queue.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param discardWhenFull the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder discardWhenFull(
String discardWhenFull) {
doSetProperty("discardWhenFull", discardWhenFull);
return this;
}
/**
* Whether the producer should fail by throwing an exception, when
* sending to a queue with no active consumers. Only one of the options
* discardIfNoConsumers and failIfNoConsumers can be enabled at the same
* time.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param failIfNoConsumers the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder failIfNoConsumers(
boolean failIfNoConsumers) {
doSetProperty("failIfNoConsumers", failIfNoConsumers);
return this;
}
/**
* Whether the producer should fail by throwing an exception, when
* sending to a queue with no active consumers. Only one of the options
* discardIfNoConsumers and failIfNoConsumers can be enabled at the same
* time.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param failIfNoConsumers the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder failIfNoConsumers(
String failIfNoConsumers) {
doSetProperty("failIfNoConsumers", failIfNoConsumers);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code>
* type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder lazyStartProducer(
String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* offerTimeout (in milliseconds) can be added to the block case when
* queue is full. You can disable timeout by using 0 or a negative
* value.
*
* The option is a: <code>long</code> type.
*
* Group: producer
*
* @param offerTimeout the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder offerTimeout(long offerTimeout) {
doSetProperty("offerTimeout", offerTimeout);
return this;
}
/**
* offerTimeout (in milliseconds) can be added to the block case when
* queue is full. You can disable timeout by using 0 or a negative
* value.
*
* The option will be converted to a <code>long</code> type.
*
* Group: producer
*
* @param offerTimeout the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder offerTimeout(String offerTimeout) {
doSetProperty("offerTimeout", offerTimeout);
return this;
}
/**
* Timeout (in milliseconds) before a SEDA producer will stop waiting
* for an asynchronous task to complete. You can disable timeout by
* using 0 or a negative value.
*
* The option is a: <code>long</code> type.
*
* Default: 30000
* Group: producer
*
* @param timeout the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder timeout(long timeout) {
doSetProperty("timeout", timeout);
return this;
}
/**
* Timeout (in milliseconds) before a SEDA producer will stop waiting
* for an asynchronous task to complete. You can disable timeout by
* using 0 or a negative value.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 30000
* Group: producer
*
* @param timeout the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder timeout(String timeout) {
doSetProperty("timeout", timeout);
return this;
}
/**
* Option to specify whether the caller should wait for the async task
* to complete or not before continuing. The following three options are
* supported: Always, Never or IfReplyExpected. The first two values are
* self-explanatory. The last value, IfReplyExpected, will only wait if
* the message is Request Reply based. The default option is
* IfReplyExpected.
*
* The option is a:
* <code>org.apache.camel.WaitForTaskToComplete</code> type.
*
* Default: IfReplyExpected
* Group: producer
*
* @param waitForTaskToComplete the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder waitForTaskToComplete(
WaitForTaskToComplete waitForTaskToComplete) {
doSetProperty("waitForTaskToComplete", waitForTaskToComplete);
return this;
}
/**
* Option to specify whether the caller should wait for the async task
* to complete or not before continuing. The following three options are
* supported: Always, Never or IfReplyExpected. The first two values are
* self-explanatory. The last value, IfReplyExpected, will only wait if
* the message is Request Reply based. The default option is
* IfReplyExpected.
*
* The option will be converted to a
* <code>org.apache.camel.WaitForTaskToComplete</code> type.
*
* Default: IfReplyExpected
* Group: producer
*
* @param waitForTaskToComplete the value to set
* @return the dsl builder
*/
default SedaEndpointProducerBuilder waitForTaskToComplete(
String waitForTaskToComplete) {
doSetProperty("waitForTaskToComplete", waitForTaskToComplete);
return this;
}
}
/**
* Advanced builder for endpoint producers for the SEDA component.
*/
public interface AdvancedSedaEndpointProducerBuilder
extends
EndpointProducerBuilder {
default SedaEndpointProducerBuilder basic() {
return (SedaEndpointProducerBuilder) this;
}
/**
* Define the queue instance which will be used by the endpoint.
*
* The option is a:
* <code>java.util.concurrent.BlockingQueue</code> type.
*
* Group: advanced
*
* @param queue the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointProducerBuilder queue(BlockingQueue queue) {
doSetProperty("queue", queue);
return this;
}
/**
* Define the queue instance which will be used by the endpoint.
*
* The option will be converted to a
* <code>java.util.concurrent.BlockingQueue</code> type.
*
* Group: advanced
*
* @param queue the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointProducerBuilder queue(String queue) {
doSetProperty("queue", queue);
return this;
}
}
/**
* Builder for endpoint for the SEDA component.
*/
public interface SedaEndpointBuilder
extends
SedaEndpointConsumerBuilder,
SedaEndpointProducerBuilder {
default AdvancedSedaEndpointBuilder advanced() {
return (AdvancedSedaEndpointBuilder) this;
}
/**
* The maximum capacity of the SEDA queue (i.e., the number of messages
* it can hold). Will by default use the defaultSize set on the SEDA
* component.
*
* The option is a: <code>int</code> type.
*
* Default: 1000
* Group: common
*
* @param size the value to set
* @return the dsl builder
*/
default SedaEndpointBuilder size(int size) {
doSetProperty("size", size);
return this;
}
/**
* The maximum capacity of the SEDA queue (i.e., the number of messages
* it can hold). Will by default use the defaultSize set on the SEDA
* component.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 1000
* Group: common
*
* @param size the value to set
* @return the dsl builder
*/
default SedaEndpointBuilder size(String size) {
doSetProperty("size", size);
return this;
}
}
/**
* Advanced builder for endpoint for the SEDA component.
*/
public interface AdvancedSedaEndpointBuilder
extends
AdvancedSedaEndpointConsumerBuilder,
AdvancedSedaEndpointProducerBuilder {
default SedaEndpointBuilder basic() {
return (SedaEndpointBuilder) this;
}
/**
* Define the queue instance which will be used by the endpoint.
*
* The option is a:
* <code>java.util.concurrent.BlockingQueue</code> type.
*
* Group: advanced
*
* @param queue the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointBuilder queue(BlockingQueue queue) {
doSetProperty("queue", queue);
return this;
}
/**
* Define the queue instance which will be used by the endpoint.
*
* The option will be converted to a
* <code>java.util.concurrent.BlockingQueue</code> type.
*
* Group: advanced
*
* @param queue the value to set
* @return the dsl builder
*/
default AdvancedSedaEndpointBuilder queue(String queue) {
doSetProperty("queue", queue);
return this;
}
}
public interface SedaBuilders {
/**
* SEDA (camel-seda)
* Asynchronously call another endpoint from any Camel Context in the
* same JVM.
*
* Category: core,endpoint
* Since: 1.1
* Maven coordinates: org.apache.camel:camel-seda
*
* Syntax: <code>seda:name</code>
*
* Path parameter: name (required)
* Name of queue
*
* @param path name
* @return the dsl builder
*/
default SedaEndpointBuilder seda(String path) {
return SedaEndpointBuilderFactory.endpointBuilder("seda", path);
}
/**
* SEDA (camel-seda)
* Asynchronously call another endpoint from any Camel Context in the
* same JVM.
*
* Category: core,endpoint
* Since: 1.1
* Maven coordinates: org.apache.camel:camel-seda
*
* Syntax: <code>seda:name</code>
*
* Path parameter: name (required)
* Name of queue
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path name
* @return the dsl builder
*/
default SedaEndpointBuilder seda(String componentName, String path) {
return SedaEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
static SedaEndpointBuilder endpointBuilder(String componentName, String path) {
class SedaEndpointBuilderImpl extends AbstractEndpointBuilder implements SedaEndpointBuilder, AdvancedSedaEndpointBuilder {
public SedaEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new SedaEndpointBuilderImpl(path);
}
}
| |
/** Notice of modification as required by the LGPL
* This file was modified by Gemstone Systems Inc. on
* $Date$
**/
// $Id: NotificationBus.java,v 1.9 2005/07/17 11:36:40 chrislott Exp $
package com.gemstone.org.jgroups.blocks;
import com.gemstone.org.jgroups.util.GemFireTracer;
import com.gemstone.org.jgroups.*;
import com.gemstone.org.jgroups.util.ExternalStrings;
import com.gemstone.org.jgroups.util.Promise;
import com.gemstone.org.jgroups.util.Util;
import java.io.Serializable;
import java.util.Vector;
/**
* This class provides notification sending and handling capability.
* Producers can send notifications to all registered consumers.
* Provides hooks to implement shared group state, which allows an
* application programmer to maintain a local cache which is replicated
* by all instances. NotificationBus sits on
* top of a channel, however it creates its channel itself, so the
* application programmers do not have to provide their own channel.
*
* @author Bela Ban
*/
public class NotificationBus implements MessageListener, MembershipListener {
final Vector members=new Vector();
JChannel channel=null;
Address local_addr=null;
PullPushAdapter ad=null;
Consumer consumer=null; // only a single consumer allowed
String bus_name="notification_bus";
final Promise get_cache_promise=new Promise();
final Object cache_mutex=new Object();
protected final GemFireTracer log=GemFireTracer.getLog(getClass());
String props=null;
public interface Consumer {
void handleNotification(Serializable n);
/** Called on the coordinator to obtains its cache */
Serializable getCache();
void memberJoined(Address mbr);
void memberLeft(Address mbr);
}
public NotificationBus() throws Exception {
this(null, null);
}
public NotificationBus(String bus_name) throws Exception {
this(bus_name, null);
}
public NotificationBus(String bus_name, String properties) throws Exception {
if(bus_name != null) this.bus_name=bus_name;
if(properties != null) props=properties;
channel=new JChannel(props);
}
public void setConsumer(Consumer c) {
consumer=c;
}
public Address getLocalAddress() {
if(local_addr != null) return local_addr;
if(channel != null)
local_addr=channel.getLocalAddress();
return local_addr;
}
/**
* Returns a reference to the real membership: don't modify.
* If you need to modify, make a copy first !
* @return Vector of Address objects
*/
public Vector getMembership() {
return members;
}
/**
* Answers the Channel.
* Used to operate on the underlying channel directly, e.g. perform operations that are not
* provided using only NotificationBus. Should be used sparingly.
* @return underlying Channel
*/
public Channel getChannel() {
return channel;
}
public boolean isCoordinator() {
Object first_mbr=null;
synchronized(members) {
first_mbr=members.size() > 0 ? members.elementAt(0) : null;
if(first_mbr == null)
return true;
}
if(getLocalAddress() != null)
return getLocalAddress().equals(first_mbr);
return false;
}
public void start() throws Exception {
channel.connect(bus_name);
ad=new PullPushAdapter(channel, this, this);
}
public void stop() {
if(ad != null) {
ad.stop();
ad=null;
}
if(channel != null) {
channel.close(); // disconnects from channel and closes it
channel=null;
}
}
/** Pack the argument in a Info, serialize that one into the message buffer and send the message */
public void sendNotification(Serializable n) {
Message msg=null;
byte[] data=null;
Info info;
try {
if(n == null) return;
info=new Info(Info.NOTIFICATION, n);
data=Util.objectToByteBuffer(info);
msg=new Message(null, null, data);
if(channel == null) {
if(log.isErrorEnabled()) log.error("channel is null. " +
" Won't send notification");
return;
}
channel.send(msg);
}
catch(Throwable ex) {
if(log.isErrorEnabled()) log.error(ExternalStrings.NotificationBus_EXCEPTION_IS__0, ex);
}
}
/**
Determines the coordinator and asks it for its cache. If there is no coordinator (because we are first member),
null will be returned. Used only internally by NotificationBus.
@param timeout Max number of msecs until the call returns
@param max_tries Max number of attempts to fetch the cache from the coordinator
*/
public Serializable getCacheFromCoordinator(long timeout, int max_tries) {
return getCacheFromMember(null, timeout, max_tries);
}
/**
Determines the coordinator and asks it for its cache. If there is no coordinator (because we are first member),
null will be returned. Used only internally by NotificationBus.
@param mbr The address of the member from which to fetch the state. If null, the current coordinator
will be asked for the state
@param timeout Max number of msecs until the call returns - if timeout elapses
null will be returned
@param max_tries Max number of attempts to fetch the cache from the coordinator (will be set to 1 if < 1)
*/
public Serializable getCacheFromMember(Address mbr, long timeout, int max_tries) {
Serializable cache=null;
int num_tries=0;
Info info; // GemStoneAddition =new Info(Info.GET_CACHE_REQ);
Message msg;
Address dst=mbr; // member from which to fetch the cache
long start, stop; // +++ remove
if(max_tries < 1) max_tries=1;
get_cache_promise.reset();
while(num_tries <= max_tries) {
if(mbr == null) { // mbr == null means get cache from coordinator
dst=determineCoordinator();
if(dst == null || dst.equals(getLocalAddress())) { // we are the first member --> empty cache
if(log.isInfoEnabled()) log.info("[" + getLocalAddress() +
"] no coordinator found --> first member (cache is empty)");
return null;
}
}
// +++ remove
if(log.isInfoEnabled()) log.info("[" + getLocalAddress() + "] dst=" + dst +
", timeout=" + timeout + ", max_tries=" + max_tries + ", num_tries=" + num_tries);
info=new Info(Info.GET_CACHE_REQ);
msg=new Message(dst, null, info);
channel.down(new Event(Event.MSG, msg));
start=System.currentTimeMillis();
cache=(Serializable) get_cache_promise.getResult(timeout);
stop=System.currentTimeMillis();
if(cache != null) {
if(log.isInfoEnabled()) log.info("got cache from " +
dst + ": cache is valid (waited " + (stop - start) + " msecs on get_cache_promise)");
return cache;
}
else {
if(log.isErrorEnabled()) log.error("received null cache; retrying (waited " +
(stop - start) + " msecs on get_cache_promise)");
}
try { // GemStoneAddition
Util.sleep(500);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error(ExternalStrings.NotificationBus_THREAD_INTERRUPTED);
// treat as timeout
break;
}
++num_tries;
}
// if(cache == null) GemStoneAddition (can only be null)
if(log.isErrorEnabled()) log.error("[" + getLocalAddress() +
"] cache is null (num_tries=" + num_tries + ')');
return cache;
}
/**
Don't multicast this to all members, just apply it to local consumers.
*/
public void notifyConsumer(Serializable n) {
if(consumer != null && n != null)
consumer.handleNotification(n);
}
/* -------------------------------- Interface MessageListener -------------------------------- */
public void receive(Message msg) {
Info info=null;
Object obj;
if(msg == null || msg.getLength() == 0) return;
try {
obj=msg.getObject();
if(!(obj instanceof Info)) {
if(log.isErrorEnabled()) log.error("expected an instance of Info (received " +
obj.getClass().getName() + ')');
return;
}
info=(Info) obj;
switch(info.type) {
case Info.NOTIFICATION:
notifyConsumer(info.data);
break;
case Info.GET_CACHE_REQ:
handleCacheRequest(msg.getSrc());
break;
case Info.GET_CACHE_RSP:
// +++ remove
if(log.isDebugEnabled()) log.debug("[GET_CACHE_RSP] cache was received from " + msg.getSrc());
get_cache_promise.setResult(info.data);
break;
default:
if(log.isErrorEnabled()) log.error(ExternalStrings.NotificationBus_TYPE__0__UNKNOWN, info.type);
break;
}
}
catch(Throwable ex) {
if(log.isErrorEnabled()) log.error(ExternalStrings.NotificationBus_EXCEPTION_0, ex);
}
}
public byte[] getState() {
return null;
}
public void setState(byte[] state) {
}
/* ----------------------------- End of Interface MessageListener ---------------------------- */
/* ------------------------------- Interface MembershipListener ------------------------------ */
public synchronized void viewAccepted(View new_view) {
Vector joined_mbrs, left_mbrs, tmp;
Object tmp_mbr;
if(new_view == null) return;
tmp=new_view.getMembers();
synchronized(members) {
// get new members
joined_mbrs=new Vector();
for(int i=0; i < tmp.size(); i++) {
tmp_mbr=tmp.elementAt(i);
if(!members.contains(tmp_mbr))
joined_mbrs.addElement(tmp_mbr);
}
// get members that left
left_mbrs=new Vector();
for(int i=0; i < members.size(); i++) {
tmp_mbr=members.elementAt(i);
if(!tmp.contains(tmp_mbr))
left_mbrs.addElement(tmp_mbr);
}
// adjust our own membership
members.removeAllElements();
members.addAll(tmp);
}
if(consumer != null) {
if(joined_mbrs.size() > 0)
for(int i=0; i < joined_mbrs.size(); i++)
consumer.memberJoined((Address) joined_mbrs.elementAt(i));
if(left_mbrs.size() > 0)
for(int i=0; i < left_mbrs.size(); i++)
consumer.memberLeft((Address) left_mbrs.elementAt(i));
}
}
public void suspect(SuspectMember suspected_mbr) {
}
public void block() {
}
public void channelClosing(Channel c, Exception e) {} // GemStoneAddition
/* ----------------------------- End of Interface MembershipListener ------------------------- */
/* ------------------------------------- Private Methods ------------------------------------- */
Address determineCoordinator() {
Vector v=channel != null ? channel.getView().getMembers() : null;
return v != null ? (Address) v.elementAt(0) : null;
}
void handleCacheRequest(Address sender) {
Serializable cache=null;
Message msg;
Info info;
if(sender == null) {
// +++ remove
//
if(log.isErrorEnabled()) log.error(ExternalStrings.NotificationBus_SENDER_IS_NULL);
return;
}
synchronized(cache_mutex) {
cache=getCache(); // get the cache from the consumer
info=new Info(Info.GET_CACHE_RSP, cache);
msg=new Message(sender, null, info);
if(log.isInfoEnabled()) log.info(ExternalStrings.NotificationBus__0__RETURNING_CACHE_TO__1, new Object[] {getLocalAddress(), sender});
channel.down(new Event(Event.MSG, msg));
}
}
public Serializable getCache() {
return consumer != null ? consumer.getCache() : null;
}
/* --------------------------------- End of Private Methods ---------------------------------- */
private static class Info implements Serializable {
private static final long serialVersionUID = -2247826108262348005L;
public final static int NOTIFICATION=1;
public final static int GET_CACHE_REQ=2;
public final static int GET_CACHE_RSP=3;
int type=0;
Serializable data=null; // if type == NOTIFICATION data is notification, if type == GET_CACHE_RSP, data is cache
public Info(int type) {
this.type=type;
}
public Info(int type, Serializable data) {
this.type=type;
this.data=data;
}
@Override // GemStoneAddition
public String toString() {
StringBuffer sb=new StringBuffer();
sb.append("type= ");
if(type == NOTIFICATION)
sb.append("NOTIFICATION");
else if(type == GET_CACHE_REQ)
sb.append("GET_CACHE_REQ");
else if(type == GET_CACHE_RSP)
sb.append("GET_CACHE_RSP");
else
sb.append("<unknown>");
if(data != null) {
if(type == NOTIFICATION)
sb.append(", notification=" + data);
else if(type == GET_CACHE_RSP) sb.append(", cache=" + data);
}
return sb.toString();
}
}
}
| |
package fragment.submissions;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Reassembles a given set of text fragments into their original sequence.
*
* Author: Rushit Shah
*/
public class RushitShah {
private static final String FRAGMENT_DELIMITER = ";";
public static void main(String[] args) throws IOException {
try (BufferedReader in = new BufferedReader(new FileReader(args[0]))) {
in.lines()
.map(RushitShah::reassemble)
.forEach(System.out::println);
}
}
private static String reassemble(final String input) {
if (input == null) {
throw new IllegalArgumentException("Cannot process null input, please ensure input is not null");
}
// Split the input using the delimiter to obtain fragments
final List<String> fragments = new ArrayList<>(Arrays.asList(input.split(FRAGMENT_DELIMITER)));
if (fragments.isEmpty()) {
throw new IllegalArgumentException("Could not get fragments from input provided. Most likely ; has not been used as a delimiter or the input is not fragmented");
}
if (fragments.size() == 1) {
return fragments.get(0);
}
int fragmentVisibilityTracker = 0; // Index tracker used to keep track of which fragments have been looked at in the loop
boolean hasBeenMerged = false; // Flag to check if any text has been merged at any point in the iterations
String text = fragments.get(fragmentVisibilityTracker);
// Loop over all fragments until all have been merged or only "junk" fragments remain
while (!fragments.isEmpty()) {
MatchState biggestMatchLength = null;
int indexToRemove = -1;
// Check all fragments against the first one (or merged text) for the largest match
for (int i = 0; i < fragments.size(); i++) {
final MatchState matchState = computeMatchState(text, fragments.get(i));
if (matchState.canMerge()) {
// If we've found a match, ensure largest as well as remove record index from collection to prevent it being used again
if (biggestMatchLength == null) {
biggestMatchLength = matchState;
indexToRemove = i;
} else if (biggestMatchLength.getMatchLength() < matchState.getMatchLength()) {
biggestMatchLength = matchState;
indexToRemove = i;
}
}
}
if (biggestMatchLength != null && indexToRemove > -1 && biggestMatchLength.getMatchLength() > 1) {
// Remove matching fragments
fragments.remove(indexToRemove);
// Merge into main sentence
text = biggestMatchLength.merge();
hasBeenMerged = true;
} else if (!hasBeenMerged && biggestMatchLength != null && biggestMatchLength.cannotMerge()) {
// We need to track if we've ever merged something in the event that the fragments have no matches
fragmentVisibilityTracker++;
text = fragments.get(fragmentVisibilityTracker);
} else {
// If there are no more matches, exit the loop - the only remaining fragments can be considered "junk"
break;
}
}
return text;
}
private static MatchState computeMatchState(final String leftFragment, final String rightFragment) {
if (leftFragment == null || rightFragment == null) {
// Validation to ensure that we don't operate on null - spec said we were sure to receive at least 2 characters in fragments
throw new IllegalArgumentException("Cannot accept null strings");
}
if (leftFragment.equals(rightFragment)) {
// Do nothing when fragments are equal
return new MatchState(leftFragment, rightFragment, leftFragment.length(), MergePosition.FULLY_CONTAINED, -1);
}
// use specialized version of sliding window - but to edges only
int maximumMatchLengthFound = 0;
int mergeAtIndex = -1;
MergePosition mp = MergePosition.CANT_MERGE;
int rightLength = rightFragment.length();
// Compare first by increasing the window left to right
for (int expandingWindow = 1; expandingWindow <= rightLength; expandingWindow++) {
final String expandingWindowContent = rightFragment.substring(0, expandingWindow);
final boolean leftContainsExpandingWindowContent = leftFragment.contains(expandingWindowContent);
// Check there is a matching string & that the match is bigger than any previously found match (i.e. maximal match)
if (leftContainsExpandingWindowContent && (maximumMatchLengthFound < expandingWindow)) {
if (leftFragment.endsWith(expandingWindowContent)) {
maximumMatchLengthFound = expandingWindow;
mp = MergePosition.MERGE_AT_END;
mergeAtIndex = rightLength - expandingWindow;
} else if (leftFragment.startsWith(expandingWindowContent)) {
maximumMatchLengthFound = expandingWindow;
mp = MergePosition.CANT_MERGE;
mergeAtIndex = -1;
} else if (!(mp == MergePosition.MERGE_AT_BEGINNING || mp == MergePosition.MERGE_AT_END)) {
maximumMatchLengthFound = expandingWindow;
mp = MergePosition.FULLY_CONTAINED;
mergeAtIndex = -1;
}
}
// When at maximum window length, compare by reducing the window left to right
if (expandingWindow == rightLength) {
for (int reducingWindow = 1; reducingWindow < rightLength; reducingWindow++) {
// No need to compare from 0, that has been done already
final String reducingWindowContent = rightFragment.substring(reducingWindow, rightLength);
final boolean leftContainsReducingWindowContent = leftFragment.contains(reducingWindowContent);
if (leftContainsReducingWindowContent && (maximumMatchLengthFound < (rightLength - reducingWindow))) {
maximumMatchLengthFound = (rightLength - reducingWindow);
if (leftFragment.startsWith(reducingWindowContent)) {
maximumMatchLengthFound = (rightLength - reducingWindow);
mp = MergePosition.MERGE_AT_BEGINNING;
mergeAtIndex = rightLength - reducingWindow;
} else if (leftFragment.endsWith(reducingWindowContent)) {
maximumMatchLengthFound = (rightLength - reducingWindow);
mp = MergePosition.CANT_MERGE;
mergeAtIndex = -1;
} else if (!(mp == MergePosition.MERGE_AT_BEGINNING || mp == MergePosition.MERGE_AT_END)) {
maximumMatchLengthFound = (rightLength - reducingWindow);
mp = MergePosition.FULLY_CONTAINED;
mergeAtIndex = -1;
}
}
}
}
}
return new MatchState(leftFragment, rightFragment, maximumMatchLengthFound, mp, mergeAtIndex);
}
private enum MergePosition {
/**
* Describes that merging should prefix to the input.
*/
MERGE_AT_BEGINNING,
/**
* Describes that merging should post-fixed to the input.
*/
MERGE_AT_END,
/**
* Describes that the input already contains the matches
*/
FULLY_CONTAINED,
/**
* Describes input that cannot be merged either because of no matches or center-only matching
*/
CANT_MERGE
}
/*
* Tracks the merging positions and length of the two different inputs.
*/
private static class MatchState {
private final String leftFragment;
private final String rightFragment;
private final int matchLength;
private final MergePosition mergePosition;
private final int mergeIndex;
/**
* Instantiates a new match state with enough information to merge the fragments if required.
*
* @param leftFragment the left fragment
* @param rightFragment the right fragment
* @param matchLength the maximal match length
* @param mergePosition the merge position
* @param mergeIndex the merge index
*/
MatchState(final String leftFragment, final String rightFragment, final int matchLength, final MergePosition mergePosition, final int mergeIndex) {
this.leftFragment = leftFragment;
this.rightFragment = rightFragment;
this.matchLength = matchLength;
this.mergePosition = mergePosition;
this.mergeIndex = mergeIndex;
}
/**
* Gets the maximal match length for the input fragments.
*
* @return the match maximal length
*/
final int getMatchLength() {
return this.matchLength;
}
/**
* Merges the left and right fragments and returns the result. Returns null if the fragments can't be merged.
*
* @return the merged fragments
*/
String merge() {
switch (mergePosition) {
case MERGE_AT_BEGINNING:
if (mergeIndex < 0) {
throw new IllegalStateException("Incorrect internal state (this is a bug) - there shouldn't be an < 0 index for MERGE_AT_BEGINNING");
}
return (rightFragment.substring(0, rightFragment.length() - mergeIndex)) + leftFragment;
case MERGE_AT_END:
if (mergeIndex < 0) {
throw new IllegalStateException("Incorrect internal state (this is a bug) - there shouldn't be an < 0 index for MERGE_AT_END");
}
return leftFragment + (rightFragment.substring(rightFragment.length() - mergeIndex, rightFragment.length()));
case FULLY_CONTAINED:
return leftFragment;
default:
return null;
}
}
/*
* Returns true if and only if the fragments can be merged. This excludes the {@link MergePosition#FULLY_CONTAINED} state.
*
* @return the boolean
*/
boolean canMerge() {
return mergePosition == MergePosition.MERGE_AT_BEGINNING || mergePosition == MergePosition.MERGE_AT_END;
}
/*
* Returns true if and only if the fragments cannot be merged (merge state is CANT_MERGE).
*
* @return the boolean
*/
boolean cannotMerge() {
return mergePosition == MergePosition.CANT_MERGE;
}
}
}
| |
/**
* 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.wildfly.camel.test.digitalocean;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.digitalocean.constants.DigitalOceanHeaders;
import org.apache.camel.component.digitalocean.constants.DigitalOceanOperations;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.PropertiesComponent;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extension.camel.CamelAware;
import com.myjeeva.digitalocean.impl.DigitalOceanClient;
import com.myjeeva.digitalocean.pojo.Account;
import com.myjeeva.digitalocean.pojo.Delete;
import com.myjeeva.digitalocean.pojo.Droplet;
import com.myjeeva.digitalocean.pojo.Image;
import com.myjeeva.digitalocean.pojo.Region;
import com.myjeeva.digitalocean.pojo.Size;
import com.myjeeva.digitalocean.pojo.Tag;
@CamelAware
@RunWith(Arquillian.class)
public class DigitalOceanIntegrationTest {
private static final String DIGITALOCEAN_OAUTH_TOKEN = "DIGITALOCEAN_OAUTH_TOKEN";
private String oauthToken;
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class, "camel-digitalocean-tests.jar");
}
@Before
public void beforeClass () {
oauthToken = System.getenv(DIGITALOCEAN_OAUTH_TOKEN);
Assume.assumeNotNull("OAuth Token required", oauthToken);
}
@AfterClass
public static void afterClass() {
String oauthToken = System.getenv(DIGITALOCEAN_OAUTH_TOKEN);
if (oauthToken != null) {
DigitalOceanClient client = new DigitalOceanClient(oauthToken);
try {
List<Droplet> droplets = client.getAvailableDroplets(1, 10).getDroplets();
for (Droplet droplet : droplets) {
client.deleteDroplet(droplet.getId());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
@Test
public void testGetAccountInfo() throws Exception {
CamelContext camelctx = createCamelContext(oauthToken);
camelctx.addRoutes(createRouteBuilder());
camelctx.start();
try {
MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockResult.expectedMinimumMessageCount(1);
ProducerTemplate producer = camelctx.createProducerTemplate();
Account result = producer.requestBody("direct:getAccountInfo", null, Account.class);
Assert.assertTrue(result.isEmailVerified());
mockResult.assertIsSatisfied();
} finally {
camelctx.close();
}
}
@Test
public void testCreateDroplet() throws Exception {
CamelContext camelctx = createCamelContext(oauthToken);
camelctx.addRoutes(createRouteBuilder());
camelctx.start();
try {
MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockResult.expectedMinimumMessageCount(1);
ProducerTemplate producer = camelctx.createProducerTemplate();
Droplet droplet = producer.requestBody("direct:createDroplet", null, Droplet.class);
mockResult.assertIsSatisfied();
Assert.assertNotNull(droplet.getId());
Assert.assertEquals(droplet.getRegion().getSlug(), "fra1");
Assert.assertEquals(2, droplet.getTags().size());
mockResult.reset();
mockResult.expectedMinimumMessageCount(1);
Droplet resDroplet = producer.requestBodyAndHeader("direct:getDroplet", null, DigitalOceanHeaders.ID, droplet.getId(), Droplet.class);
mockResult.assertIsSatisfied();
Assert.assertEquals(droplet.getId(), resDroplet.getId());
Delete delres = producer.requestBodyAndHeader("direct:deleteDroplet", null, DigitalOceanHeaders.ID, droplet.getId(), Delete.class);
Assert.assertTrue("Droplet deleted", delres.getIsRequestSuccess());
} finally {
camelctx.close();
}
}
@Test
@SuppressWarnings("unchecked")
public void testCreateMultipleDroplets() throws Exception {
CamelContext camelctx = createCamelContext(oauthToken);
camelctx.addRoutes(createRouteBuilder());
camelctx.start();
try {
MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockResult.expectedMinimumMessageCount(1);
ProducerTemplate producer = camelctx.createProducerTemplate();
List<Droplet> createDroplets = producer.requestBody("direct:createMultipleDroplets", null, List.class);
mockResult.assertIsSatisfied();
Assert.assertEquals(2, createDroplets.size());
List<Droplet> getDroplets = producer.requestBody("direct:getDroplets", null, List.class);
Assert.assertTrue("At least as many droplets as created", getDroplets.size() >= 2);
} finally {
camelctx.close();
}
}
@Test
public void testCreateTag() throws Exception {
CamelContext camelctx = createCamelContext(oauthToken);
camelctx.addRoutes(createRouteBuilder());
camelctx.start();
try {
MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockResult.expectedMinimumMessageCount(1);
ProducerTemplate producer = camelctx.createProducerTemplate();
Tag tag = producer.requestBody("direct:createTag", null, Tag.class);
Assert.assertEquals("tag1", tag.getName());
mockResult.assertIsSatisfied();
} finally {
camelctx.close();
}
}
@Test
@SuppressWarnings("unchecked")
public void testGetTags() throws Exception {
CamelContext camelctx = createCamelContext(oauthToken);
camelctx.addRoutes(createRouteBuilder());
camelctx.start();
try {
MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockResult.expectedMinimumMessageCount(1);
ProducerTemplate producer = camelctx.createProducerTemplate();
List<Tag> tags = producer.requestBody("direct:getTags", null, List.class);
Assert.assertEquals("tag1", tags.get(0).getName());
mockResult.assertIsSatisfied();
} finally {
camelctx.close();
}
}
@Test
@SuppressWarnings("unchecked")
public void getImages() throws Exception {
CamelContext camelctx = createCamelContext(oauthToken);
camelctx.addRoutes(createRouteBuilder());
camelctx.start();
try {
MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockResult.expectedMinimumMessageCount(1);
ProducerTemplate producer = camelctx.createProducerTemplate();
List<Image> images = producer.requestBody("direct:getImages", null, List.class);
mockResult.assertIsSatisfied();
Assert.assertNotEquals(1, images.size());
} finally {
camelctx.close();
}
}
@Test
public void getImage() throws Exception {
CamelContext camelctx = createCamelContext(oauthToken);
camelctx.addRoutes(createRouteBuilder());
camelctx.start();
try {
MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockResult.expectedMinimumMessageCount(1);
ProducerTemplate producer = camelctx.createProducerTemplate();
Image image = producer.requestBody("direct:getImage", null, Image.class);
Assert.assertEquals("ubuntu-14-04-x64", image.getSlug());
mockResult.assertIsSatisfied();
} finally {
camelctx.close();
}
}
@Test
@SuppressWarnings("unchecked")
public void getSizes() throws Exception {
CamelContext camelctx = createCamelContext(oauthToken);
camelctx.addRoutes(createRouteBuilder());
camelctx.start();
try {
MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockResult.expectedMinimumMessageCount(1);
ProducerTemplate producer = camelctx.createProducerTemplate();
List<Size> sizes = producer.requestBody("direct:getSizes", null, List.class);
Assert.assertNotEquals(1, sizes.size());
mockResult.assertIsSatisfied();
} finally {
camelctx.close();
}
}
@Test
@SuppressWarnings("unchecked")
public void getRegions() throws Exception {
CamelContext camelctx = createCamelContext(oauthToken);
camelctx.addRoutes(createRouteBuilder());
camelctx.start();
try {
MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockResult.expectedMinimumMessageCount(1);
ProducerTemplate producer = camelctx.createProducerTemplate();
List<Region> regions = producer.requestBody("direct:getRegions", null, List.class);
Assert.assertNotEquals(1, regions.size());
mockResult.assertIsSatisfied();
} finally {
camelctx.close();
}
}
private RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() {
from("direct:getAccountInfo")
.to("digitalocean:account?operation=" + DigitalOceanOperations.get + "&oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:createMultipleDroplets")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.create))
.process(e -> {
Collection<String> names = new ArrayList<String>();
names.add("droplet1");
names.add("droplet2");
e.getIn().setHeader(DigitalOceanHeaders.NAMES, names);
})
.setHeader(DigitalOceanHeaders.REGION, constant("fra1"))
.setHeader(DigitalOceanHeaders.DROPLET_IMAGE, constant("ubuntu-14-04-x64"))
.setHeader(DigitalOceanHeaders.DROPLET_SIZE, constant("512mb"))
.process(e -> {
Collection<String> tags = new ArrayList<String>();
tags.add("tag1");
tags.add("tag2");
e.getIn().setHeader(DigitalOceanHeaders.DROPLET_TAGS, tags);
})
.to("digitalocean://droplets?oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:getTags")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.list))
.to("digitalocean://tags?oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:getImages")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.list))
.to("digitalocean://images?oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:createDroplet")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.create))
.setHeader(DigitalOceanHeaders.NAME, constant("camel-test"))
.setHeader(DigitalOceanHeaders.REGION, constant("fra1"))
.setHeader(DigitalOceanHeaders.DROPLET_IMAGE, constant("ubuntu-14-04-x64"))
.setHeader(DigitalOceanHeaders.DROPLET_SIZE, constant("512mb"))
.process(e -> {
Collection<String> tags = new ArrayList<String>();
tags.add("tag1");
tags.add("tag2");
e.getIn().setHeader(DigitalOceanHeaders.DROPLET_TAGS, tags);
})
.to("digitalocean:droplets?oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:getDroplet")
.to("digitalocean:droplets?operation=get&oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:deleteDroplet")
.to("digitalocean:droplets?operation=delete&oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:createTag")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.create))
.setHeader(DigitalOceanHeaders.NAME, constant("tag1"))
.to("digitalocean://tags?oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:getImage")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.get))
.setHeader(DigitalOceanHeaders.DROPLET_IMAGE, constant("ubuntu-14-04-x64"))
.to("digitalocean://images?oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:getSizes")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.list))
.to("digitalocean://sizes?oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:getRegions")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.list))
.to("digitalocean://regions?oAuthToken={{oAuthToken}}")
.to("mock:result");
from("direct:getDroplets")
.setHeader(DigitalOceanHeaders.OPERATION, constant(DigitalOceanOperations.list))
.to("digitalocean:droplets?oAuthToken={{oAuthToken}}")
.to("mock:result");
}
};
}
private CamelContext createCamelContext(String oauthToken) {
CamelContext camelctx = new DefaultCamelContext();
PropertiesComponent pc = camelctx.getPropertiesComponent();
Properties properties = new Properties();
properties.setProperty("oAuthToken", oauthToken);
pc.setOverrideProperties(properties);
return camelctx;
}
}
| |
package com.heinrichreimersoftware.materialintro.slide;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;
import com.heinrichreimersoftware.materialintro.app.SlideFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class SlideAdapter extends FragmentPagerAdapter {
private List<Slide> data = new ArrayList<>();
private FragmentManager fragmentManager;
public SlideAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
this.fragmentManager = fragmentManager;
data = new ArrayList<>();
}
public SlideAdapter(FragmentManager fragmentManager, @NonNull Collection<? extends Slide> collection) {
super(fragmentManager);
this.fragmentManager = fragmentManager;
data = new ArrayList<>(collection);
}
public void addSlide(int location, Slide object) {
if (!data.contains(object)) {
data.add(location, object);
}
}
public boolean addSlide(Slide object) {
if (data.contains(object)) {
return false;
}
boolean modified = data.add(object);
if (modified) {
notifyDataSetChanged();
}
return modified;
}
public boolean addSlides(int location, @NonNull Collection<? extends Slide> collection) {
boolean modified = false;
int i = 0;
for (Slide slide : collection) {
if (!data.contains(slide)) {
data.add(location + i, slide);
i++;
modified = true;
}
}
if (modified) {
notifyDataSetChanged();
}
return modified;
}
public boolean addSlides(@NonNull Collection<? extends Slide> collection) {
boolean modified = false;
for (Slide slide : collection) {
if (!data.contains(slide)) {
data.add(slide);
modified = true;
}
}
if (modified) {
notifyDataSetChanged();
}
return modified;
}
public boolean clearSlides() {
if (!data.isEmpty()) {
data.clear();
return true;
}
return false;
}
public boolean containsSlide(Object object) {
return object instanceof Slide && data.contains(object);
}
public boolean containsSlides(@NonNull Collection<?> collection) {
return data.containsAll(collection);
}
public Slide getSlide(int location) {
return data.get(location);
}
@Override
public Fragment getItem(int position) {
return data.get(position).getFragment();
}
@Override
public int getItemPosition(Object object) {
if (object instanceof Fragment) {
fragmentManager.beginTransaction()
.detach((Fragment) object)
.attach((Fragment) object)
.commit();
}
return super.getItemPosition(object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = getItem(position);
if (fragment.isAdded()) {
return fragment;
}
Fragment instantiatedFragment = (Fragment) super.instantiateItem(container, position);
Slide slide = data.get(position);
if (slide instanceof RestorableSlide) {
//Load old fragment from fragment manager
((RestorableSlide) slide).setFragment(instantiatedFragment);
data.set(position, slide);
if (instantiatedFragment instanceof SlideFragment)
((SlideFragment) instantiatedFragment).updateNavigation();
}
return instantiatedFragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment) object;
if (fragment == null)
return;
super.destroyItem(container, position, object);
}
@ColorRes
public int getBackground(int position) {
return data.get(position).getBackground();
}
@ColorRes
public int getBackgroundDark(int position) {
return data.get(position).getBackgroundDark();
}
public List<Slide> getSlides() {
return data;
}
@SuppressWarnings("SuspiciousMethodCalls")
public int indexOfSlide(Object object) {
return data.indexOf(object);
}
public boolean isEmpty() {
return data.isEmpty();
}
@Override
public int getCount() {
return data.size();
}
@SuppressWarnings("SuspiciousMethodCalls")
public int lastIndexOfSlide(Object object) {
return data.lastIndexOf(object);
}
public Slide removeSlide(int location) {
return data.remove(location);
}
@SuppressWarnings("SuspiciousMethodCalls")
public boolean removeSlide(Object object) {
int locationToRemove = data.indexOf(object);
if (locationToRemove >= 0) {
data.remove(locationToRemove);
return true;
}
return false;
}
@SuppressWarnings("SuspiciousMethodCalls")
public boolean removeSlides(@NonNull Collection<?> collection) {
boolean modified = false;
for (Object object : collection) {
int locationToRemove = data.indexOf(object);
if (locationToRemove >= 0) {
data.remove(locationToRemove);
modified = true;
}
}
return modified;
}
public boolean retainSlides(@NonNull Collection<?> collection) {
boolean modified = false;
for (int i = data.size() - 1; i >= 0; i--) {
if(!collection.contains(data.get(i))){
data.remove(i);
modified = true;
i--;
}
}
return modified;
}
public Slide setSlide(int location, Slide object) {
if (!data.contains(object)) {
return data.set(location, object);
}
return data.set(location, object);
}
public List<Slide> setSlides(List<? extends Slide> list) {
List<Slide> oldList = new ArrayList<>(data);
data = new ArrayList<>(list);
return oldList;
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
| |
package com.youtube.vitess.vtgate.integration;
import com.google.common.collect.Lists;
import com.google.common.primitives.UnsignedLong;
import com.youtube.vitess.vtgate.BindVariable;
import com.youtube.vitess.vtgate.Exceptions.ConnectionException;
import com.youtube.vitess.vtgate.Exceptions.DatabaseException;
import com.youtube.vitess.vtgate.KeyRange;
import com.youtube.vitess.vtgate.KeyspaceId;
import com.youtube.vitess.vtgate.Query;
import com.youtube.vitess.vtgate.Query.QueryBuilder;
import com.youtube.vitess.vtgate.Row;
import com.youtube.vitess.vtgate.Row.Cell;
import com.youtube.vitess.vtgate.VtGate;
import com.youtube.vitess.vtgate.cursor.Cursor;
import com.youtube.vitess.vtgate.cursor.CursorImpl;
import com.youtube.vitess.vtgate.integration.util.TestEnv;
import com.youtube.vitess.vtgate.integration.util.Util;
import org.apache.commons.codec.binary.Hex;
import org.joda.time.DateTime;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
@RunWith(JUnit4.class)
public class VtGateIT {
public static TestEnv testEnv = getTestEnv();
@BeforeClass
public static void setUpVtGate() throws Exception {
Util.setupTestEnv(testEnv);
}
@AfterClass
public static void tearDownVtGate() throws Exception {
Util.teardownTestEnv(testEnv);
}
@Before
public void createTable() throws Exception {
Util.createTable(testEnv);
}
/**
* Test selects using ExecuteKeyspaceIds
*/
@Test
public void testExecuteKeyspaceIds() throws Exception {
VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
// Ensure empty table
String selectSql = "select * from vtgate_test";
Query allRowsQuery = new QueryBuilder(selectSql, testEnv.keyspace, "master").setKeyspaceIds(
testEnv.getAllKeyspaceIds()).build();
Cursor cursor = vtgate.execute(allRowsQuery);
Assert.assertEquals(CursorImpl.class, cursor.getClass());
Assert.assertEquals(0, cursor.getRowsAffected());
Assert.assertEquals(0, cursor.getLastRowId());
Assert.assertFalse(cursor.hasNext());
vtgate.close();
// Insert 10 rows
Util.insertRows(testEnv, 1000, 10);
vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
cursor = vtgate.execute(allRowsQuery);
Assert.assertEquals(10, cursor.getRowsAffected());
Assert.assertEquals(0, cursor.getLastRowId());
Assert.assertTrue(cursor.hasNext());
// Fetch all rows from the first shard
KeyspaceId firstKid = testEnv.getAllKeyspaceIds().get(0);
Query query =
new QueryBuilder(selectSql, testEnv.keyspace, "master").addKeyspaceId(firstKid).build();
cursor = vtgate.execute(query);
// Check field types and values
Row row = cursor.next();
Cell idCell = row.next();
Assert.assertEquals("id", idCell.getName());
Assert.assertEquals(Long.class, idCell.getType());
Long id = row.getLong(idCell.getName());
Cell nameCell = row.next();
Assert.assertEquals("name", nameCell.getName());
Assert.assertEquals(byte[].class, nameCell.getType());
Assert.assertTrue(
Arrays.equals(("name_" + id.toString()).getBytes(), row.getBytes(nameCell.getName())));
Cell ageCell = row.next();
Assert.assertEquals("age", ageCell.getName());
Assert.assertEquals(Integer.class, ageCell.getType());
Assert.assertEquals(Integer.valueOf(2 * id.intValue()), row.getInt(ageCell.getName()));
vtgate.close();
}
/**
* Test queries are routed to the right shard based on based on keyspace ids
*/
@Test
public void testQueryRouting() throws Exception {
for (String shardName : testEnv.shardKidMap.keySet()) {
Util.insertRowsInShard(testEnv, shardName, 10);
}
VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
String allRowsSql = "select * from vtgate_test";
for (String shardName : testEnv.shardKidMap.keySet()) {
Query shardRows = new QueryBuilder(allRowsSql, testEnv.keyspace, "master").setKeyspaceIds(
testEnv.getKeyspaceIds(shardName)).build();
Cursor cursor = vtgate.execute(shardRows);
Assert.assertEquals(10, cursor.getRowsAffected());
}
vtgate.close();
}
@Test
public void testDateFieldTypes() throws Exception {
DateTime dt = DateTime.now().minusDays(2).withMillisOfSecond(0);
Util.insertRows(testEnv, 10, 1, dt);
VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
Query allRowsQuery = new QueryBuilder("select * from vtgate_test", testEnv.keyspace, "master")
.setKeyspaceIds(testEnv.getAllKeyspaceIds()).build();
Row row = vtgate.execute(allRowsQuery).next();
Assert.assertTrue(dt.equals(row.getDateTime("timestamp_col")));
Assert.assertTrue(dt.equals(row.getDateTime("datetime_col")));
Assert.assertTrue(dt.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0)
.equals(row.getDateTime("date_col")));
Assert.assertTrue(
dt.withYear(1970).withMonthOfYear(1).withDayOfMonth(1).equals(row.getDateTime("time_col")));
vtgate.close();
}
/**
* Test ALL keyrange fetches rows from all shards
*/
@Test
public void testAllKeyRange() throws Exception {
// Insert 10 rows across the shards
Util.insertRows(testEnv, 1000, 10);
VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
String selectSql = "select * from vtgate_test";
Query allRowsQuery =
new QueryBuilder(selectSql, testEnv.keyspace, "master").addKeyRange(KeyRange.ALL).build();
Cursor cursor = vtgate.execute(allRowsQuery);
// Verify all rows returned
Assert.assertEquals(10, cursor.getRowsAffected());
vtgate.close();
}
/**
* Test reads using Keyrange query
*/
@Test
public void testKeyRangeReads() throws Exception {
int rowsPerShard = 10;
// insert rows in each shard using ExecuteKeyspaceIds
for (String shardName : testEnv.shardKidMap.keySet()) {
Util.insertRowsInShard(testEnv, shardName, rowsPerShard);
}
VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
String selectSql = "select * from vtgate_test";
// Check ALL KeyRange query returns rows from both shards
Query allRangeQuery =
new QueryBuilder(selectSql, testEnv.keyspace, "master").addKeyRange(KeyRange.ALL).build();
Cursor cursor = vtgate.execute(allRangeQuery);
Assert.assertEquals(rowsPerShard * 2, cursor.getRowsAffected());
// Check KeyRange query limited to a single shard returns 10 rows each
for (String shardName : testEnv.shardKidMap.keySet()) {
List<KeyspaceId> shardKids = testEnv.getKeyspaceIds(shardName);
KeyspaceId minKid = Collections.min(shardKids);
KeyspaceId maxKid = Collections.max(shardKids);
KeyRange shardKeyRange = new KeyRange(minKid, maxKid);
Query shardRangeQuery = new QueryBuilder(selectSql, testEnv.keyspace, "master").addKeyRange(
shardKeyRange).build();
cursor = vtgate.execute(shardRangeQuery);
Assert.assertEquals(rowsPerShard, cursor.getRowsAffected());
}
// Now make a cross-shard KeyRange and check all rows are returned
Iterator<String> shardNameIter = testEnv.shardKidMap.keySet().iterator();
KeyspaceId kidShard1 = testEnv.getKeyspaceIds(shardNameIter.next()).get(2);
KeyspaceId kidShard2 = testEnv.getKeyspaceIds(shardNameIter.next()).get(2);
KeyRange crossShardKeyrange;
if (kidShard1.compareTo(kidShard2) < 0) {
crossShardKeyrange = new KeyRange(kidShard1, kidShard2);
} else {
crossShardKeyrange = new KeyRange(kidShard2, kidShard1);
}
Query shardRangeQuery = new QueryBuilder(selectSql, testEnv.keyspace, "master").addKeyRange(
crossShardKeyrange).build();
cursor = vtgate.execute(shardRangeQuery);
Assert.assertEquals(rowsPerShard * 2, cursor.getRowsAffected());
vtgate.close();
}
/**
* Test inserts using KeyRange query
*/
@Test
public void testKeyRangeWrites() throws Exception {
Random random = new Random();
VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
vtgate.begin();
String sql = "insert into vtgate_test " + "(id, name, keyspace_id, age) "
+ "values (:id, :name, :keyspace_id, :age)";
int count = 20;
// Insert 20 rows per shard
for (String shardName : testEnv.shardKidMap.keySet()) {
List<KeyspaceId> kids = testEnv.getKeyspaceIds(shardName);
KeyspaceId minKid = Collections.min(kids);
KeyspaceId maxKid = Collections.max(kids);
KeyRange kr = new KeyRange(minKid, maxKid);
for (int i = 0; i < count; i++) {
KeyspaceId kid = kids.get(i % kids.size());
Query query = new QueryBuilder(sql, testEnv.keyspace, "master")
.addBindVar(
BindVariable.forULong("id", UnsignedLong.valueOf("" + Math.abs(random.nextInt()))))
.addBindVar(BindVariable.forString("name", ("name_" + i)))
.addBindVar(BindVariable.forULong("keyspace_id", (UnsignedLong) kid.getId()))
.addBindVar(BindVariable.forNull("age"))
.addKeyRange(kr)
.build();
vtgate.execute(query);
}
}
vtgate.commit();
vtgate.close();
// Check 40 rows exist in total
vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
String selectSql = "select * from vtgate_test";
Query allRowsQuery = new QueryBuilder(selectSql, testEnv.keyspace, "master").setKeyspaceIds(
testEnv.getAllKeyspaceIds()).build();
Cursor cursor = vtgate.execute(allRowsQuery);
Assert.assertEquals(count * 2, cursor.getRowsAffected());
// Check 20 rows exist per shard
for (String shardName : testEnv.shardKidMap.keySet()) {
Query shardRows = new QueryBuilder(selectSql, testEnv.keyspace, "master").setKeyspaceIds(
testEnv.getKeyspaceIds(shardName)).build();
cursor = vtgate.execute(shardRows);
Assert.assertEquals(count, cursor.getRowsAffected());
}
vtgate.close();
}
@Test
public void testSplitQuery() throws Exception {
// Insert 20 rows per shard
for (String shardName : testEnv.shardKidMap.keySet()) {
Util.insertRowsInShard(testEnv, shardName, 20);
}
Util.waitForTablet("rdonly", 40, 3, testEnv);
VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
Map<Query, Long> queries =
vtgate.splitQuery("test_keyspace", "select id,keyspace_id from vtgate_test", 1, "");
vtgate.close();
// Verify 2 splits, one per shard
Assert.assertEquals(2, queries.size());
Set<String> shardsInSplits = new HashSet<>();
for (Query q : queries.keySet()) {
Assert.assertEquals("select id,keyspace_id from vtgate_test", q.getSql());
Assert.assertEquals("test_keyspace", q.getKeyspace());
Assert.assertEquals("rdonly", q.getTabletType());
Assert.assertEquals(0, q.getBindVars().size());
Assert.assertEquals(null, q.getKeyspaceIds());
String start = Hex.encodeHexString(q.getKeyRanges().get(0).get("Start"));
String end = Hex.encodeHexString(q.getKeyRanges().get(0).get("End"));
shardsInSplits.add(start + "-" + end);
}
// Verify the keyrange queries in splits cover the entire keyspace
Assert.assertTrue(shardsInSplits.containsAll(testEnv.shardKidMap.keySet()));
}
@Test
public void testSplitQueryMultipleSplitsPerShard() throws Exception {
int rowCount = 30;
Util.insertRows(testEnv, 1, 30);
List<String> expectedSqls =
Lists.newArrayList("select id, keyspace_id from vtgate_test where id < 10",
"select id, keyspace_id from vtgate_test where id < 11",
"select id, keyspace_id from vtgate_test where id >= 10 and id < 19",
"select id, keyspace_id from vtgate_test where id >= 11 and id < 19",
"select id, keyspace_id from vtgate_test where id >= 19",
"select id, keyspace_id from vtgate_test where id >= 19");
Util.waitForTablet("rdonly", rowCount, 3, testEnv);
VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
int splitCount = 6;
Map<Query, Long> queries =
vtgate.splitQuery("test_keyspace", "select id,keyspace_id from vtgate_test", splitCount, "");
vtgate.close();
// Verify 6 splits, 3 per shard
Assert.assertEquals(splitCount, queries.size());
Set<String> shardsInSplits = new HashSet<>();
for (Query q : queries.keySet()) {
String sql = q.getSql();
Assert.assertTrue(expectedSqls.contains(sql));
expectedSqls.remove(sql);
Assert.assertEquals("test_keyspace", q.getKeyspace());
Assert.assertEquals("rdonly", q.getTabletType());
Assert.assertEquals(0, q.getBindVars().size());
Assert.assertEquals(null, q.getKeyspaceIds());
String start = Hex.encodeHexString(q.getKeyRanges().get(0).get("Start"));
String end = Hex.encodeHexString(q.getKeyRanges().get(0).get("End"));
shardsInSplits.add(start + "-" + end);
}
// Verify the keyrange queries in splits cover the entire keyspace
Assert.assertTrue(shardsInSplits.containsAll(testEnv.shardKidMap.keySet()));
Assert.assertTrue(expectedSqls.size() == 0);
}
@Test
public void testSplitQueryInvalidTable() throws Exception {
VtGate vtgate = VtGate.connect("localhost:" + testEnv.port, 0);
try {
vtgate.splitQuery("test_keyspace", "select id from invalid_table", 1, "");
Assert.fail("failed to raise connection exception");
} catch (ConnectionException e) {
Assert.assertTrue(
e.getMessage().contains("query validation error: can't find table in schema"));
} finally {
vtgate.close();
}
}
/**
* Create env with two shards each having a master and replica
*/
static TestEnv getTestEnv() {
Map<String, List<String>> shardKidMap = new LinkedHashMap<>();
shardKidMap.put("80-",
Lists.newArrayList("9767889778372766922", "9742070682920810358", "10296850775085416642"));
shardKidMap.put("-80",
Lists.newArrayList("527875958493693904", "626750931627689502", "345387386794260318"));
TestEnv env = new TestEnv(shardKidMap, "test_keyspace");
env.addTablet("rdonly", 1);
return env;
}
}
| |
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.plaf.basic;
import sun.swing.DefaultLookup;
import sun.swing.UIAction;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.ActionMapUIResource;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.ComponentInputMapUIResource;
/**
* Button Listener
*
* @author Jeff Dinkins
* @author Arnaud Weber (keyboard UI support)
*/
public class BasicButtonListener implements MouseListener, MouseMotionListener,
FocusListener, ChangeListener, PropertyChangeListener
{
private long lastPressedTimestamp = -1;
private boolean shouldDiscardRelease = false;
/**
* Populates Buttons actions.
*/
static void loadActionMap(LazyActionMap map) {
map.put(new Actions(Actions.PRESS));
map.put(new Actions(Actions.RELEASE));
}
public BasicButtonListener(AbstractButton b) {
}
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if(prop == AbstractButton.MNEMONIC_CHANGED_PROPERTY) {
updateMnemonicBinding((AbstractButton)e.getSource());
}
else if(prop == AbstractButton.CONTENT_AREA_FILLED_CHANGED_PROPERTY) {
checkOpacity((AbstractButton) e.getSource() );
}
else if(prop == AbstractButton.TEXT_CHANGED_PROPERTY ||
"font" == prop || "foreground" == prop) {
AbstractButton b = (AbstractButton) e.getSource();
BasicHTML.updateRenderer(b, b.getText());
}
}
protected void checkOpacity(AbstractButton b) {
b.setOpaque( b.isContentAreaFilled() );
}
/**
* Register default key actions: pressing space to "click" a
* button and registring the keyboard mnemonic (if any).
*/
public void installKeyboardActions(JComponent c) {
AbstractButton b = (AbstractButton)c;
// Update the mnemonic binding.
updateMnemonicBinding(b);
LazyActionMap.installLazyActionMap(c, BasicButtonListener.class,
"Button.actionMap");
InputMap km = getInputMap(JComponent.WHEN_FOCUSED, c);
SwingUtilities.replaceUIInputMap(c, JComponent.WHEN_FOCUSED, km);
}
/**
* Unregister's default key actions
*/
public void uninstallKeyboardActions(JComponent c) {
SwingUtilities.replaceUIInputMap(c, JComponent.
WHEN_IN_FOCUSED_WINDOW, null);
SwingUtilities.replaceUIInputMap(c, JComponent.WHEN_FOCUSED, null);
SwingUtilities.replaceUIActionMap(c, null);
}
/**
* Returns the InputMap for condition <code>condition</code>. Called as
* part of <code>installKeyboardActions</code>.
*/
InputMap getInputMap(int condition, JComponent c) {
if (condition == JComponent.WHEN_FOCUSED) {
BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType(
((AbstractButton)c).getUI(), BasicButtonUI.class);
if (ui != null) {
return (InputMap)DefaultLookup.get(
c, ui, ui.getPropertyPrefix() + "focusInputMap");
}
}
return null;
}
/**
* Resets the binding for the mnemonic in the WHEN_IN_FOCUSED_WINDOW
* UI InputMap.
*/
void updateMnemonicBinding(AbstractButton b) {
int m = b.getMnemonic();
if(m != 0) {
InputMap map = SwingUtilities.getUIInputMap(
b, JComponent.WHEN_IN_FOCUSED_WINDOW);
if (map == null) {
map = new ComponentInputMapUIResource(b);
SwingUtilities.replaceUIInputMap(b,
JComponent.WHEN_IN_FOCUSED_WINDOW, map);
}
map.clear();
map.put(KeyStroke.getKeyStroke(m, InputEvent.ALT_MASK, false),
"pressed");
map.put(KeyStroke.getKeyStroke(m, InputEvent.ALT_MASK, true),
"released");
map.put(KeyStroke.getKeyStroke(m, 0, true), "released");
}
else {
InputMap map = SwingUtilities.getUIInputMap(b, JComponent.
WHEN_IN_FOCUSED_WINDOW);
if (map != null) {
map.clear();
}
}
}
public void stateChanged(ChangeEvent e) {
AbstractButton b = (AbstractButton) e.getSource();
b.repaint();
}
public void focusGained(FocusEvent e) {
AbstractButton b = (AbstractButton) e.getSource();
if (b instanceof JButton && ((JButton)b).isDefaultCapable()) {
JRootPane root = b.getRootPane();
if (root != null) {
BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType(
((AbstractButton)b).getUI(), BasicButtonUI.class);
if (ui != null && DefaultLookup.getBoolean(b, ui,
ui.getPropertyPrefix() +
"defaultButtonFollowsFocus", true)) {
root.putClientProperty("temporaryDefaultButton", b);
root.setDefaultButton((JButton)b);
root.putClientProperty("temporaryDefaultButton", null);
}
}
}
b.repaint();
}
public void focusLost(FocusEvent e) {
AbstractButton b = (AbstractButton) e.getSource();
JRootPane root = b.getRootPane();
if (root != null) {
JButton initialDefault = (JButton)root.getClientProperty("initialDefaultButton");
if (b != initialDefault) {
BasicButtonUI ui = (BasicButtonUI)BasicLookAndFeel.getUIOfType(
((AbstractButton)b).getUI(), BasicButtonUI.class);
if (ui != null && DefaultLookup.getBoolean(b, ui,
ui.getPropertyPrefix() +
"defaultButtonFollowsFocus", true)) {
root.setDefaultButton(initialDefault);
}
}
}
ButtonModel model = b.getModel();
model.setArmed(false);
model.setPressed(false);
b.repaint();
}
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) ) {
AbstractButton b = (AbstractButton) e.getSource();
if(b.contains(e.getX(), e.getY())) {
long multiClickThreshhold = b.getMultiClickThreshhold();
long lastTime = lastPressedTimestamp;
long currentTime = lastPressedTimestamp = e.getWhen();
if (lastTime != -1 && currentTime - lastTime < multiClickThreshhold) {
shouldDiscardRelease = true;
return;
}
ButtonModel model = b.getModel();
if (!model.isEnabled()) {
// Disabled buttons ignore all input...
return;
}
if (!model.isArmed()) {
// button not armed, should be
model.setArmed(true);
}
model.setPressed(true);
if(!b.hasFocus() && b.isRequestFocusEnabled()) {
b.requestFocus();
}
}
}
};
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
// Support for multiClickThreshhold
if (shouldDiscardRelease) {
shouldDiscardRelease = false;
return;
}
AbstractButton b = (AbstractButton) e.getSource();
ButtonModel model = b.getModel();
model.setPressed(false);
model.setArmed(false);
}
};
public void mouseEntered(MouseEvent e) {
AbstractButton b = (AbstractButton) e.getSource();
ButtonModel model = b.getModel();
if (b.isRolloverEnabled() && !SwingUtilities.isLeftMouseButton(e)) {
model.setRollover(true);
}
if (model.isPressed())
model.setArmed(true);
};
public void mouseExited(MouseEvent e) {
AbstractButton b = (AbstractButton) e.getSource();
ButtonModel model = b.getModel();
if(b.isRolloverEnabled()) {
model.setRollover(false);
}
model.setArmed(false);
};
/**
* Actions for Buttons. Two types of action are supported:
* pressed: Moves the button to a pressed state
* released: Disarms the button.
*/
private static class Actions extends UIAction {
private static final String PRESS = "pressed";
private static final String RELEASE = "released";
Actions(String name) {
super(name);
}
public void actionPerformed(ActionEvent e) {
AbstractButton b = (AbstractButton)e.getSource();
String key = getName();
if (key == PRESS) {
ButtonModel model = b.getModel();
model.setArmed(true);
model.setPressed(true);
if(!b.hasFocus()) {
b.requestFocus();
}
}
else if (key == RELEASE) {
ButtonModel model = b.getModel();
model.setPressed(false);
model.setArmed(false);
}
}
public boolean isEnabled(Object sender) {
if(sender != null && (sender instanceof AbstractButton) &&
!((AbstractButton)sender).getModel().isEnabled()) {
return false;
} else {
return true;
}
}
}
}
| |
/*
* Copyright (C) 2008 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.inputmethod.latin;
import com.android.inputmethod.keyboard.Key;
import com.android.inputmethod.keyboard.Keyboard;
import java.util.Arrays;
/**
* A place to store the currently composing word with information such as adjacent key codes as well
*/
public final class WordComposer {
private static final int MAX_WORD_LENGTH = Constants.Dictionary.MAX_WORD_LENGTH;
private static final boolean DBG = LatinImeLogger.sDBG;
public static final int CAPS_MODE_OFF = 0;
// 1 is shift bit, 2 is caps bit, 4 is auto bit but this is just a convention as these bits
// aren't used anywhere in the code
public static final int CAPS_MODE_MANUAL_SHIFTED = 0x1;
public static final int CAPS_MODE_MANUAL_SHIFT_LOCKED = 0x3;
public static final int CAPS_MODE_AUTO_SHIFTED = 0x5;
public static final int CAPS_MODE_AUTO_SHIFT_LOCKED = 0x7;
private int[] mPrimaryKeyCodes;
private final InputPointers mInputPointers = new InputPointers(MAX_WORD_LENGTH);
private final StringBuilder mTypedWord;
private String mAutoCorrection;
private boolean mIsResumed;
private boolean mIsBatchMode;
// A memory of the last rejected batch mode suggestion, if any. This goes like this: the user
// gestures a word, is displeased with the results and hits backspace, then gestures again.
// At the very least we should avoid re-suggesting the same thing, and to do that we memorize
// the rejected suggestion in this variable.
// TODO: this should be done in a comprehensive way by the User History feature instead of
// as an ad-hockery here.
private String mRejectedBatchModeSuggestion;
// Cache these values for performance
private int mCapsCount;
private int mDigitsCount;
private int mCapitalizedMode;
private int mTrailingSingleQuotesCount;
private int mCodePointSize;
private int mCursorPositionWithinWord;
/**
* Whether the user chose to capitalize the first char of the word.
*/
private boolean mIsFirstCharCapitalized;
public WordComposer() {
mPrimaryKeyCodes = new int[MAX_WORD_LENGTH];
mTypedWord = new StringBuilder(MAX_WORD_LENGTH);
mAutoCorrection = null;
mTrailingSingleQuotesCount = 0;
mIsResumed = false;
mIsBatchMode = false;
mCursorPositionWithinWord = 0;
mRejectedBatchModeSuggestion = null;
refreshSize();
}
public WordComposer(final WordComposer source) {
mPrimaryKeyCodes = Arrays.copyOf(source.mPrimaryKeyCodes, source.mPrimaryKeyCodes.length);
mTypedWord = new StringBuilder(source.mTypedWord);
mInputPointers.copy(source.mInputPointers);
mCapsCount = source.mCapsCount;
mDigitsCount = source.mDigitsCount;
mIsFirstCharCapitalized = source.mIsFirstCharCapitalized;
mCapitalizedMode = source.mCapitalizedMode;
mTrailingSingleQuotesCount = source.mTrailingSingleQuotesCount;
mIsResumed = source.mIsResumed;
mIsBatchMode = source.mIsBatchMode;
mCursorPositionWithinWord = source.mCursorPositionWithinWord;
mRejectedBatchModeSuggestion = source.mRejectedBatchModeSuggestion;
refreshSize();
}
/**
* Clear out the keys registered so far.
*/
public void reset() {
mTypedWord.setLength(0);
mAutoCorrection = null;
mCapsCount = 0;
mDigitsCount = 0;
mIsFirstCharCapitalized = false;
mTrailingSingleQuotesCount = 0;
mIsResumed = false;
mIsBatchMode = false;
mCursorPositionWithinWord = 0;
mRejectedBatchModeSuggestion = null;
refreshSize();
}
private final void refreshSize() {
mCodePointSize = mTypedWord.codePointCount(0, mTypedWord.length());
}
/**
* Number of keystrokes in the composing word.
* @return the number of keystrokes
*/
public final int size() {
return mCodePointSize;
}
public final boolean isComposingWord() {
return size() > 0;
}
// TODO: make sure that the index should not exceed MAX_WORD_LENGTH
public int getCodeAt(int index) {
if (index >= MAX_WORD_LENGTH) {
return -1;
}
return mPrimaryKeyCodes[index];
}
public int getCodeBeforeCursor() {
if (mCursorPositionWithinWord < 1 || mCursorPositionWithinWord > mPrimaryKeyCodes.length) {
return Constants.NOT_A_CODE;
}
return mPrimaryKeyCodes[mCursorPositionWithinWord - 1];
}
public InputPointers getInputPointers() {
return mInputPointers;
}
private static boolean isFirstCharCapitalized(final int index, final int codePoint,
final boolean previous) {
if (index == 0) return Character.isUpperCase(codePoint);
return previous && !Character.isUpperCase(codePoint);
}
/**
* Add a new keystroke, with the pressed key's code point with the touch point coordinates.
*/
public void add(final int primaryCode, final int keyX, final int keyY) {
final int newIndex = size();
mTypedWord.appendCodePoint(primaryCode);
refreshSize();
mCursorPositionWithinWord = mCodePointSize;
if (newIndex < MAX_WORD_LENGTH) {
mPrimaryKeyCodes[newIndex] = primaryCode >= Constants.CODE_SPACE
? Character.toLowerCase(primaryCode) : primaryCode;
// In the batch input mode, the {@code mInputPointers} holds batch input points and
// shouldn't be overridden by the "typed key" coordinates
// (See {@link #setBatchInputWord}).
if (!mIsBatchMode) {
// TODO: Set correct pointer id and time
mInputPointers.addPointer(newIndex, keyX, keyY, 0, 0);
}
}
mIsFirstCharCapitalized = isFirstCharCapitalized(
newIndex, primaryCode, mIsFirstCharCapitalized);
if (Character.isUpperCase(primaryCode)) mCapsCount++;
if (Character.isDigit(primaryCode)) mDigitsCount++;
if (Constants.CODE_SINGLE_QUOTE == primaryCode) {
++mTrailingSingleQuotesCount;
} else {
mTrailingSingleQuotesCount = 0;
}
mAutoCorrection = null;
}
public void setCursorPositionWithinWord(final int posWithinWord) {
mCursorPositionWithinWord = posWithinWord;
}
public boolean isCursorFrontOrMiddleOfComposingWord() {
if (DBG && mCursorPositionWithinWord > mCodePointSize) {
throw new RuntimeException("Wrong cursor position : " + mCursorPositionWithinWord
+ "in a word of size " + mCodePointSize);
}
return mCursorPositionWithinWord != mCodePointSize;
}
public void setBatchInputPointers(final InputPointers batchPointers) {
mInputPointers.set(batchPointers);
mIsBatchMode = true;
}
public void setBatchInputWord(final String word) {
reset();
mIsBatchMode = true;
final int length = word.length();
for (int i = 0; i < length; i = Character.offsetByCodePoints(word, i, 1)) {
final int codePoint = Character.codePointAt(word, i);
// We don't want to override the batch input points that are held in mInputPointers
// (See {@link #add(int,int,int)}).
add(codePoint, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
}
/**
* Add a dummy key by retrieving reasonable coordinates
*/
public void addKeyInfo(final int codePoint, final Keyboard keyboard) {
final int x, y;
final Key key;
if (keyboard != null && (key = keyboard.getKey(codePoint)) != null) {
x = key.mX + key.mWidth / 2;
y = key.mY + key.mHeight / 2;
} else {
x = Constants.NOT_A_COORDINATE;
y = Constants.NOT_A_COORDINATE;
}
add(codePoint, x, y);
}
/**
* Set the currently composing word to the one passed as an argument.
* This will register NOT_A_COORDINATE for X and Ys, and use the passed keyboard for proximity.
*/
public void setComposingWord(final CharSequence word, final Keyboard keyboard) {
reset();
final int length = word.length();
for (int i = 0; i < length; i = Character.offsetByCodePoints(word, i, 1)) {
final int codePoint = Character.codePointAt(word, i);
addKeyInfo(codePoint, keyboard);
}
mIsResumed = true;
}
/**
* Delete the last keystroke as a result of hitting backspace.
*/
public void deleteLast() {
final int size = size();
if (size > 0) {
// Note: mTypedWord.length() and mCodes.length differ when there are surrogate pairs
final int stringBuilderLength = mTypedWord.length();
if (stringBuilderLength < size) {
throw new RuntimeException(
"In WordComposer: mCodes and mTypedWords have non-matching lengths");
}
final int lastChar = mTypedWord.codePointBefore(stringBuilderLength);
if (Character.isSupplementaryCodePoint(lastChar)) {
mTypedWord.delete(stringBuilderLength - 2, stringBuilderLength);
} else {
mTypedWord.deleteCharAt(stringBuilderLength - 1);
}
if (Character.isUpperCase(lastChar)) mCapsCount--;
if (Character.isDigit(lastChar)) mDigitsCount--;
refreshSize();
}
// We may have deleted the last one.
if (0 == size()) {
mIsFirstCharCapitalized = false;
}
if (mTrailingSingleQuotesCount > 0) {
--mTrailingSingleQuotesCount;
} else {
int i = mTypedWord.length();
while (i > 0) {
i = mTypedWord.offsetByCodePoints(i, -1);
if (Constants.CODE_SINGLE_QUOTE != mTypedWord.codePointAt(i)) break;
++mTrailingSingleQuotesCount;
}
}
mCursorPositionWithinWord = mCodePointSize;
mAutoCorrection = null;
}
/**
* Returns the word as it was typed, without any correction applied.
* @return the word that was typed so far. Never returns null.
*/
public String getTypedWord() {
return mTypedWord.toString();
}
/**
* Whether or not the user typed a capital letter as the first letter in the word
* @return capitalization preference
*/
public boolean isFirstCharCapitalized() {
return mIsFirstCharCapitalized;
}
public int trailingSingleQuotesCount() {
return mTrailingSingleQuotesCount;
}
/**
* Whether or not all of the user typed chars are upper case
* @return true if all user typed chars are upper case, false otherwise
*/
public boolean isAllUpperCase() {
if (size() <= 1) {
return mCapitalizedMode == CAPS_MODE_AUTO_SHIFT_LOCKED
|| mCapitalizedMode == CAPS_MODE_MANUAL_SHIFT_LOCKED;
} else {
return mCapsCount == size();
}
}
public boolean wasShiftedNoLock() {
return mCapitalizedMode == CAPS_MODE_AUTO_SHIFTED
|| mCapitalizedMode == CAPS_MODE_MANUAL_SHIFTED;
}
/**
* Returns true if more than one character is upper case, otherwise returns false.
*/
public boolean isMostlyCaps() {
return mCapsCount > 1;
}
/**
* Returns true if we have digits in the composing word.
*/
public boolean hasDigits() {
return mDigitsCount > 0;
}
/**
* Saves the caps mode at the start of composing.
*
* WordComposer needs to know about this for several reasons. The first is, we need to know
* after the fact what the reason was, to register the correct form into the user history
* dictionary: if the word was automatically capitalized, we should insert it in all-lower
* case but if it's a manual pressing of shift, then it should be inserted as is.
* Also, batch input needs to know about the current caps mode to display correctly
* capitalized suggestions.
* @param mode the mode at the time of start
*/
public void setCapitalizedModeAtStartComposingTime(final int mode) {
mCapitalizedMode = mode;
}
/**
* Returns whether the word was automatically capitalized.
* @return whether the word was automatically capitalized
*/
public boolean wasAutoCapitalized() {
return mCapitalizedMode == CAPS_MODE_AUTO_SHIFT_LOCKED
|| mCapitalizedMode == CAPS_MODE_AUTO_SHIFTED;
}
/**
* Sets the auto-correction for this word.
*/
public void setAutoCorrection(final String correction) {
mAutoCorrection = correction;
}
/**
* @return the auto-correction for this word, or null if none.
*/
public String getAutoCorrectionOrNull() {
return mAutoCorrection;
}
/**
* @return whether we started composing this word by resuming suggestion on an existing string
*/
public boolean isResumed() {
return mIsResumed;
}
// `type' should be one of the LastComposedWord.COMMIT_TYPE_* constants above.
public LastComposedWord commitWord(final int type, final String committedWord,
final String separatorString, final String prevWord) {
// Note: currently, we come here whenever we commit a word. If it's a MANUAL_PICK
// or a DECIDED_WORD we may cancel the commit later; otherwise, we should deactivate
// the last composed word to ensure this does not happen.
final int[] primaryKeyCodes = mPrimaryKeyCodes;
mPrimaryKeyCodes = new int[MAX_WORD_LENGTH];
final LastComposedWord lastComposedWord = new LastComposedWord(primaryKeyCodes,
mInputPointers, mTypedWord.toString(), committedWord, separatorString,
prevWord, mCapitalizedMode);
mInputPointers.reset();
if (type != LastComposedWord.COMMIT_TYPE_DECIDED_WORD
&& type != LastComposedWord.COMMIT_TYPE_MANUAL_PICK) {
lastComposedWord.deactivate();
}
mCapsCount = 0;
mDigitsCount = 0;
mIsBatchMode = false;
mTypedWord.setLength(0);
mCodePointSize = 0;
mTrailingSingleQuotesCount = 0;
mIsFirstCharCapitalized = false;
mCapitalizedMode = CAPS_MODE_OFF;
refreshSize();
mAutoCorrection = null;
mCursorPositionWithinWord = 0;
mIsResumed = false;
mRejectedBatchModeSuggestion = null;
return lastComposedWord;
}
public void resumeSuggestionOnLastComposedWord(final LastComposedWord lastComposedWord) {
mPrimaryKeyCodes = lastComposedWord.mPrimaryKeyCodes;
mInputPointers.set(lastComposedWord.mInputPointers);
mTypedWord.setLength(0);
mTypedWord.append(lastComposedWord.mTypedWord);
refreshSize();
mCapitalizedMode = lastComposedWord.mCapitalizedMode;
mAutoCorrection = null; // This will be filled by the next call to updateSuggestion.
mCursorPositionWithinWord = mCodePointSize;
mRejectedBatchModeSuggestion = null;
mIsResumed = true;
}
public boolean isBatchMode() {
return mIsBatchMode;
}
public void setRejectedBatchModeSuggestion(final String rejectedSuggestion) {
mRejectedBatchModeSuggestion = rejectedSuggestion;
}
public String getRejectedBatchModeSuggestion() {
return mRejectedBatchModeSuggestion;
}
}
| |
/*
* Copyright 2015 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.comcast.cdn.traffic_control.traffic_router.core.router;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.comcast.cdn.traffic_control.traffic_router.configuration.ConfigurationListener;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.MaxmindGeolocationService;
import org.apache.commons.pool.ObjectPool;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.xbill.DNS.Name;
import org.xbill.DNS.Zone;
import com.comcast.cdn.traffic_control.traffic_router.core.TrafficRouterException;
import com.comcast.cdn.traffic_control.traffic_router.core.cache.Cache;
import com.comcast.cdn.traffic_control.traffic_router.core.cache.CacheLocation;
import com.comcast.cdn.traffic_control.traffic_router.core.cache.CacheRegister;
import com.comcast.cdn.traffic_control.traffic_router.core.cache.InetRecord;
import com.comcast.cdn.traffic_control.traffic_router.core.dns.ZoneManager;
import com.comcast.cdn.traffic_control.traffic_router.core.dns.DNSAccessRecord;
import com.comcast.cdn.traffic_control.traffic_router.core.ds.DeliveryService;
import com.comcast.cdn.traffic_control.traffic_router.core.ds.Dispersion;
import com.comcast.cdn.traffic_control.traffic_router.core.hash.HashFunction;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.FederationRegistry;
import com.comcast.cdn.traffic_control.traffic_router.geolocation.Geolocation;
import com.comcast.cdn.traffic_control.traffic_router.geolocation.GeolocationException;
import com.comcast.cdn.traffic_control.traffic_router.geolocation.GeolocationService;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.NetworkNode;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.NetworkNodeException;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.RegionalGeo;
import com.comcast.cdn.traffic_control.traffic_router.core.request.DNSRequest;
import com.comcast.cdn.traffic_control.traffic_router.core.request.HTTPRequest;
import com.comcast.cdn.traffic_control.traffic_router.core.request.Request;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.ResultType;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.RouteType;
import com.comcast.cdn.traffic_control.traffic_router.core.util.TrafficOpsUtils;
import com.comcast.cdn.traffic_control.traffic_router.core.util.CidrAddress;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.ResultDetails;
public class TrafficRouter {
public static final Logger LOGGER = Logger.getLogger(TrafficRouter.class);
private final CacheRegister cacheRegister;
private final ZoneManager zoneManager;
private final GeolocationService geolocationService;
private final GeolocationService geolocationService6;
private final ObjectPool hashFunctionPool;
private final FederationRegistry federationRegistry;
private final boolean consistentDNSRouting;
private final Random random = new Random(System.nanoTime());
private Set<String> requestHeaders = new HashSet<String>();
private static final Geolocation GEO_ZERO_ZERO = new Geolocation(0,0);
private ApplicationContext applicationContext;
public TrafficRouter(final CacheRegister cr,
final GeolocationService geolocationService,
final GeolocationService geolocationService6,
final ObjectPool hashFunctionPool,
final StatTracker statTracker,
final TrafficOpsUtils trafficOpsUtils,
final FederationRegistry federationRegistry) throws IOException, JSONException, TrafficRouterException {
this.cacheRegister = cr;
this.geolocationService = geolocationService;
this.geolocationService6 = geolocationService6;
this.hashFunctionPool = hashFunctionPool;
this.federationRegistry = federationRegistry;
this.consistentDNSRouting = cr.getConfig().optBoolean("consistent.dns.routing", false); // previous/default behavior
this.zoneManager = new ZoneManager(this, statTracker, trafficOpsUtils);
}
public ZoneManager getZoneManager() {
return zoneManager;
}
/**
* Returns a {@link List} of all of the online {@link Cache}s that support the specified
* {@link DeliveryService}. If no online caches are found to support the specified
* DeliveryService an empty list is returned.
*
* @param ds
* the DeliveryService to check
* @return collection of supported caches
*/
public List<Cache> getSupportingCaches(final List<Cache> caches, final DeliveryService ds) {
for(int i = 0; i < caches.size(); i++) {
final Cache cache = caches.get(i);
boolean isAvailable = true;
if(cache.hasAuthority()) {
isAvailable = cache.isAvailable();
}
if (!isAvailable || !cache.hasDeliveryService(ds.getId())) {
caches.remove(i);
i--;
}
}
return caches;
}
public CacheRegister getCacheRegister() {
return cacheRegister;
}
protected DeliveryService selectDeliveryService(final Request request, final boolean isHttp) {
if(cacheRegister==null) {
LOGGER.warn("no caches yet");
return null;
}
final DeliveryService ds = cacheRegister.getDeliveryService(request, isHttp);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Selected DeliveryService: " + ds);
}
return ds;
}
boolean setState(final JSONObject states) throws UnknownHostException {
setCacheStates(states.optJSONObject("caches"));
setDsStates(states.optJSONObject("deliveryServices"));
return true;
}
private boolean setDsStates(final JSONObject dsStates) {
if(dsStates == null) {
return false;
}
final Map<String, DeliveryService> dsMap = cacheRegister.getDeliveryServices();
for (final String dsName : dsMap.keySet()) {
dsMap.get(dsName).setState(dsStates.optJSONObject(dsName));
}
return true;
}
private boolean setCacheStates(final JSONObject cacheStates) {
if(cacheStates == null) {
return false;
}
final Map<String, Cache> cacheMap = cacheRegister.getCacheMap();
if(cacheMap == null) { return false; }
for (final String cacheName : cacheMap.keySet()) {
final String monitorCacheName = cacheName.replaceFirst("@.*", "");
final JSONObject state = cacheStates.optJSONObject(monitorCacheName);
cacheMap.get(cacheName).setState(state);
}
return true;
}
protected static final String UNABLE_TO_ROUTE_REQUEST = "Unable to route request.";
protected static final String URL_ERR_STR = "Unable to create URL.";
public GeolocationService getGeolocationService() {
return geolocationService;
}
public Geolocation getLocation(final String clientIP) throws GeolocationException {
return clientIP.contains(":") ? geolocationService6.location(clientIP) : geolocationService.location(clientIP);
}
private GeolocationService getGeolocationService(final String geolocationProvider, final String deliveryServiceId) {
if (applicationContext == null) {
LOGGER.error("ApplicationContext not set unable to use custom geolocation service providers");
return null;
}
if (geolocationProvider == null || geolocationProvider.isEmpty()) {
return null;
}
try {
return (GeolocationService) applicationContext.getBean(geolocationProvider);
} catch (Exception e) {
StringBuilder error = new StringBuilder("Failed getting providing class '" + geolocationProvider + "' for geolocation");
if (deliveryServiceId != null && !deliveryServiceId.isEmpty()) {
error = error.append(" for delivery service " + deliveryServiceId);
}
error = error.append(" falling back to " + MaxmindGeolocationService.class.getSimpleName());
LOGGER.error(error);
}
return null;
}
public Geolocation getLocation(final String clientIP, final String geolocationProvider, final String deliveryServiceId) throws GeolocationException {
final GeolocationService customGeolocationService = getGeolocationService(geolocationProvider, deliveryServiceId);
return customGeolocationService != null ? customGeolocationService.location(clientIP) : getLocation(clientIP);
}
public Geolocation getLocation(final String clientIP, final DeliveryService deliveryService) throws GeolocationException {
return getLocation(clientIP, deliveryService.getGeolocationProvider(), deliveryService.getId());
}
/**
* Gets hashFunctionPool.
*
* @return the hashFunctionPool
*/
public ObjectPool getHashFunctionPool() {
return hashFunctionPool;
}
public List<Cache> getCachesByGeo(final Request request, final DeliveryService ds, final Geolocation clientLocation, final Track track) throws GeolocationException {
int locationsTested = 0;
final int locationLimit = ds.getLocationLimit();
final List<CacheLocation> cacheLocations = orderCacheLocations(getCacheRegister().getCacheLocations(null), ds, clientLocation);
for (final CacheLocation location : cacheLocations) {
final List<Cache> caches = selectCache(location, ds);
if (caches != null) {
track.setResultLocation(location.getGeolocation());
if (track.getResultLocation().equals(GEO_ZERO_ZERO)) {
LOGGER.error("Location " + location.getId() + " has Geolocation " + location.getGeolocation());
}
return caches;
}
locationsTested++;
if(locationLimit != 0 && locationsTested >= locationLimit) {
return null;
}
}
return null;
}
protected List<Cache> selectCache(final Request request, final DeliveryService ds, final Track track) throws GeolocationException {
final CacheLocation cacheLocation = getCoverageZoneCache(request.getClientIP(), ds);
List<Cache> caches = selectCachesByCZ(ds, cacheLocation, track);
if (caches != null) {
return caches;
}
if (ds.isCoverageZoneOnly()) {
if (ds.getGeoRedirectUrl() != null) {
//use the NGB redirect
caches = enforceGeoRedirect(track, ds, request, null);
} else {
track.setResult(ResultType.MISS);
track.setResultDetails(ResultDetails.DS_CZ_ONLY);
}
} else {
caches = selectCachesByGeo(request, ds, cacheLocation, track);
}
return caches;
}
public List<Cache> selectCachesByGeo(final Request request, final DeliveryService deliveryService, final CacheLocation cacheLocation, final Track track) throws GeolocationException {
Geolocation clientLocation = null;
try {
clientLocation = getClientLocation(request, deliveryService, cacheLocation, track);
} catch (GeolocationException e) {
LOGGER.warn("Failed looking up Client GeoLocation: " + e.getMessage());
}
if (clientLocation == null) {
if (deliveryService.getGeoRedirectUrl() != null) {
//will use the NGB redirect
LOGGER.debug(String
.format("client is blocked by geolimit, use the NGB redirect url: %s",
deliveryService.getGeoRedirectUrl()));
return enforceGeoRedirect(track, deliveryService, request, track.getClientGeolocation());
} else {
track.setResultDetails(ResultDetails.DS_CLIENT_GEO_UNSUPPORTED);
return null;
}
}
final List<Cache> caches = getCachesByGeo(request, deliveryService, clientLocation, track);
if (caches == null || caches.isEmpty()) {
track.setResultDetails(ResultDetails.GEO_NO_CACHE_FOUND);
}
track.setResult(ResultType.GEO);
return caches;
}
public DNSRouteResult route(final DNSRequest request, final Track track) throws GeolocationException {
track.setRouteType(RouteType.DNS, request.getHostname());
final DeliveryService ds = selectDeliveryService(request, false);
if (ds == null) {
track.setResult(ResultType.STATIC_ROUTE);
track.setResultDetails(ResultDetails.DS_NOT_FOUND);
return null;
}
final DNSRouteResult result = new DNSRouteResult();
if (!ds.isAvailable()) {
result.setAddresses(ds.getFailureDnsResponse(request, track));
return result;
}
final CacheLocation cacheLocation = getCoverageZoneCache(request.getClientIP(), ds);
List<Cache> caches = selectCachesByCZ(ds, cacheLocation, track);
if (caches != null) {
track.setResult(ResultType.CZ);
result.setAddresses(inetRecordsFromCaches(ds, caches, request));
return result;
}
if (ds.isCoverageZoneOnly()) {
track.setResult(ResultType.MISS);
track.setResultDetails(ResultDetails.DS_CZ_ONLY);
result.setAddresses(ds.getFailureDnsResponse(request, track));
return result;
}
try {
final List<InetRecord> inetRecords = federationRegistry.findInetRecords(ds.getId(), CidrAddress.fromString(request.getClientIP()));
if (inetRecords != null && !inetRecords.isEmpty()) {
result.setAddresses(inetRecords);
track.setResult(ResultType.FED);
return result;
}
} catch (NetworkNodeException e) {
LOGGER.error("Bad client address: '" + request.getClientIP() + "'");
}
caches = selectCachesByGeo(request, ds, cacheLocation, track);
if (caches != null) {
track.setResult(ResultType.GEO);
result.setAddresses(inetRecordsFromCaches(ds, caches, request));
} else {
track.setResult(ResultType.MISS);
result.setAddresses(ds.getFailureDnsResponse(request, track));
}
return result;
}
public List<InetRecord> inetRecordsFromCaches(final DeliveryService ds, final List<Cache> caches, final Request request) {
final List<InetRecord> addresses = new ArrayList<InetRecord>();
final int maxDnsIps = ds.getMaxDnsIps();
List<Cache> selectedCaches;
if (maxDnsIps > 0 && isConsistentDNSRouting()) { // only consistent hash if we must
final SortedMap<Double, Cache> cacheMap = consistentHash(caches, request.getHostname());
final Dispersion dispersion = ds.getDispersion();
selectedCaches = dispersion.getCacheList(cacheMap);
} else if (maxDnsIps > 0) {
/*
* We also shuffle in NameServer when adding Records to the Message prior
* to sending it out, as the Records are sorted later when we fill the
* dynamic zone if DNSSEC is enabled. We shuffle here prior to pruning
* for maxDnsIps so that we ensure we are spreading load across all caches
* assigned to this delivery service.
*/
Collections.shuffle(caches, random);
selectedCaches = new ArrayList<Cache>();
for (final Cache cache : caches) {
selectedCaches.add(cache);
if (selectedCaches.size() >= maxDnsIps) {
break;
}
}
} else {
selectedCaches = caches;
}
for (final Cache cache : selectedCaches) {
addresses.addAll(cache.getIpAddresses(ds.getTtls(), zoneManager, ds.isIp6RoutingEnabled()));
}
return addresses;
}
public Geolocation getClientGeolocation(final Request request, final Track track, final DeliveryService deliveryService) throws GeolocationException {
if (track.isClientGeolocationQueried()) {
return track.getClientGeolocation();
}
final Geolocation clientGeolocation = getLocation(request.getClientIP(), deliveryService);
track.setClientGeolocation(clientGeolocation);
track.setClientGeolocationQueried(true);
return clientGeolocation;
}
public Geolocation getClientLocation(final Request request, final DeliveryService ds, final CacheLocation cacheLocation, final Track track) throws GeolocationException {
if (cacheLocation != null) {
return cacheLocation.getGeolocation();
}
final Geolocation clientGeolocation = getClientGeolocation(request, track, ds);
return ds.supportLocation(clientGeolocation, request.getType());
}
public List<Cache> selectCachesByCZ(final DeliveryService ds, final CacheLocation cacheLocation) {
return selectCachesByCZ(ds, cacheLocation, null);
}
private List<Cache> selectCachesByCZ(final DeliveryService ds, final CacheLocation cacheLocation, final Track track) {
if (cacheLocation == null || !ds.isLocationAvailable(cacheLocation)) {
return null;
}
final List<Cache> caches = selectCache(cacheLocation, ds);
if (caches != null && track != null) {
track.setResult(ResultType.CZ);
track.setResultLocation(cacheLocation.getGeolocation());
}
return caches;
}
public HTTPRouteResult route(final HTTPRequest request, final Track track) throws MalformedURLException, GeolocationException {
track.setRouteType(RouteType.HTTP, request.getHostname());
final DeliveryService ds = selectDeliveryService(request, true);
if (ds == null) {
track.setResult(ResultType.DS_MISS);
track.setResultDetails(ResultDetails.DS_NOT_FOUND);
return null;
}
final HTTPRouteResult routeResult = new HTTPRouteResult();
routeResult.setDeliveryService(ds);
if (!ds.isAvailable()) {
routeResult.setUrl(ds.getFailureHttpResponse(request, track));
return routeResult;
}
final List<Cache> caches = selectCache(request, ds, track);
if (caches == null) {
if (track.getResult() == ResultType.GEO_REDIRECT) {
routeResult.setUrl(new URL(ds.getGeoRedirectUrl()));
LOGGER.debug(String.format("NGB redirect to url: %s for request: %s", ds.getGeoRedirectUrl()
, request.getRequestedUrl()));
return routeResult;
}
routeResult.setUrl(ds.getFailureHttpResponse(request, track));
return routeResult;
}
final Dispersion dispersion = ds.getDispersion();
final Cache cache = dispersion.getCache(consistentHash(caches, request.getPath()));
if (ds.isRegionalGeoEnabled()) {
RegionalGeo.enforce(this, request, ds, cache, routeResult, track);
return routeResult;
}
routeResult.setUrl(new URL(ds.createURIString(request, cache)));
return routeResult;
}
protected CacheLocation getCoverageZoneCache(final String ip, final DeliveryService ds) {
NetworkNode nn = null;
try {
nn = NetworkNode.getInstance().getNetwork(ip);
} catch (NetworkNodeException e) {
LOGGER.warn(e);
}
if (nn == null) {
return null;
}
final String locId = nn.getLoc();
final CacheLocation cl = nn.getCacheLocation();
if (cl != null) {
return cl;
}
if (locId == null) {
return null;
}
// find CacheLocation
final Collection<CacheLocation> cacheLocations = getCacheRegister().getCacheLocations();
for (final CacheLocation cl2 : cacheLocations) {
if (cl2.getId().equals(locId)) {
nn.setCacheLocation(cl2);
return cl2;
}
}
/*
* We had a hit in the CZF but the name does not match a known cache location.
* Check whether the CZF entry has a geolocation and use it if so.
*/
if (nn.getGeolocation() == null) {
return null;
}
return getClosestCacheLocation(cacheLocations, ds, nn.getGeolocation());
}
/**
* Utilizes the hashValues stored with each cache to select the cache that
* the specified hash should map to.
*
* @param caches
* the list of caches to choose from
* @param hash
* the hash value for the request
* @return a cache or null if no cache can be found to map to
*/
protected Cache consistentHashOld(final List<Cache> caches,
final String request) {
double hash = 0;
HashFunction hashFunction = null;
try {
hashFunction = (HashFunction) hashFunctionPool.borrowObject();
try {
hash = hashFunction.hash(request);
} catch (final Exception e) {
LOGGER.debug(e.getMessage(), e);
}
hashFunctionPool.returnObject(hashFunction);
} catch (final Exception e) {
LOGGER.debug(e.getMessage(), e);
}
if (hash == 0) {
LOGGER.warn("Problem with hashFunctionPool, request: " + request);
return null;
}
return searchCacheOld(caches, hash);
}
private Cache searchCacheOld(final List<Cache> caches, final double hash) {
Cache minCache = null;
double minHash = Double.MAX_VALUE;
Cache foundCache = null;
double minDiff = Double.MAX_VALUE;
for (final Cache cache : caches) {
for (final double hashValue : cache.getHashValues()) {
if (hashValue < minHash) {
minCache = cache;
minHash = hashValue;
}
final double diff = hashValue - hash;
if ((diff >= 0) && (diff < minDiff)) {
foundCache = cache;
minDiff = diff;
}
}
}
return (foundCache != null) ? foundCache : minCache;
}
/**
* Utilizes the hashValues stored with each cache to select the cache that
* the specified hash should map to.
*
* @param caches
* the list of caches to choose from
* @param request
* the request string from which the hash will be generated
* @return a cache or null if no cache can be found to map to
*/
protected SortedMap<Double, Cache> consistentHash(final List<Cache> caches,
final String request) {
double hash = 0;
HashFunction hashFunction = null;
try {
hashFunction = (HashFunction) hashFunctionPool.borrowObject();
try {
hash = hashFunction.hash(request);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
hashFunctionPool.returnObject(hashFunction);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
if (hash == 0) {
LOGGER.warn("Problem with hashFunctionPool, request: " + request);
return null;
}
final SortedMap<Double, Cache> cacheMap = new TreeMap<Double, Cache>();
for (final Cache cache : caches) {
final double r = cache.getClosestHash(hash);
if (r == 0) {
LOGGER.warn("Error: getClosestHash returned 0: " + cache);
return null;
}
double diff = Math.abs(r - hash);
if (cacheMap.containsKey(diff)) {
LOGGER.warn("Error: cacheMap contains diff " + diff + "; incrementing to avoid collision");
long bits = Double.doubleToLongBits(diff);
while (cacheMap.containsKey(diff)) {
bits++;
diff = Double.longBitsToDouble(bits);
}
}
cacheMap.put(diff, cache);
}
return cacheMap;
}
/**
* Returns a list {@link CacheLocation}s sorted by distance from the client.
* If the client's location could not be determined, then the list is
* unsorted.
*
* @param cacheLocations
* the collection of CacheLocations to order
* @param ds
* @return the ordered list of locations
*/
public List<CacheLocation> orderCacheLocations(final Collection<CacheLocation> cacheLocations, final DeliveryService ds, final Geolocation clientLocation) {
final List<CacheLocation> locations = new ArrayList<CacheLocation>();
for (final CacheLocation cl : cacheLocations) {
if (ds.isLocationAvailable(cl)) {
locations.add(cl);
}
}
Collections.sort(locations, new CacheLocationComparator(clientLocation));
return locations;
}
private CacheLocation getClosestCacheLocation(final Collection<CacheLocation> cacheLocations, final DeliveryService ds, final Geolocation clientLocation) {
final List<CacheLocation> orderedLocations = orderCacheLocations(cacheLocations, ds, clientLocation);
for (CacheLocation cacheLocation : orderedLocations) {
if (!cacheLocation.getCaches().isEmpty()) {
return cacheLocation;
}
}
return null;
}
/**
* Selects a {@link Cache} from the {@link CacheLocation} provided.
*
* @param location
* the caches that will considered
* @param ds
* the delivery service for the request
* @param request
* the request to consider for cache selection
* @return the selected cache or null if none can be found
*/
private List<Cache> selectCache(final CacheLocation location,
final DeliveryService ds) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Trying location: " + location.getId());
}
final List<Cache> caches = getSupportingCaches(location.getCaches(), ds);
if (caches.isEmpty()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No online, supporting caches were found at location: "
+ location.getId());
}
return null;
}
return caches;//consistentHash(caches, request);List<Cache>
}
public Zone getZone(final Name qname, final int qtype, final InetAddress clientAddress, final boolean isDnssecRequest, final DNSAccessRecord.Builder builder) {
return zoneManager.getZone(qname, qtype, clientAddress, isDnssecRequest, builder);
}
public void setRequestHeaders(final Set<String> requestHeaders) {
this.requestHeaders = requestHeaders;
}
public Set<String> getRequestHeaders() {
return requestHeaders;
}
public boolean isConsistentDNSRouting() {
return consistentDNSRouting;
}
private List<Cache> enforceGeoRedirect(final Track track, final DeliveryService ds,
final Request request, final Geolocation queriedClientLocation) {
final String urlType = ds.getGeoRedirectUrlType();
track.setResult(ResultType.GEO_REDIRECT);
try {
if ("NOT_DS_URL".equals(urlType)) {
//redirect url not belongs to this DS, just redirect it
LOGGER.debug("geo redirect url not belongs to ds: " + ds.getGeoRedirectUrl());
return null;
} else if ("DS_URL".equals(urlType)) {
Geolocation clientLocation = queriedClientLocation;
//redirect url belongs to this DS, will try return the caches
if (clientLocation == null) {
LOGGER.debug("clientLocation null, try to query it");
clientLocation = getLocation(request.getClientIP(), ds);
if (clientLocation == null) { clientLocation = ds.getMissLocation(); }
if (clientLocation == null) {
LOGGER.error("cannot find a geo location for the client: " + request.getClientIP());
// particular error was logged in ds.supportLocation
track.setResult(ResultType.MISS);
track.setResultDetails(ResultDetails.DS_CLIENT_GEO_UNSUPPORTED);
return null;
}
}
final List<Cache> caches = getCachesByGeo(request, ds, clientLocation, track);
if (caches == null) {
LOGGER.warn(String.format(
"No Cache found by Geo in NGB redirect"));
track.setResult(ResultType.MISS);
track.setResultDetails(ResultDetails.GEO_NO_CACHE_FOUND);
return null;
}
return caches;
} else {
LOGGER.error("invalid geo redirect url type");
track.setResult(ResultType.MISS);
track.setResultDetails(ResultDetails.GEO_NO_CACHE_FOUND);
return null;
}
} catch (Exception e) {
LOGGER.error("caught Exception when enforceGeoRedirect: " + e);
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
LOGGER.error(sw.toString());
track.setResult(ResultType.ERROR);
return null;
}
}
public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void configurationChanged() {
if (applicationContext == null) {
LOGGER.warn("Application Context not yet ready, skipping calling listeners of configuration change");
return;
}
final Map<String, ConfigurationListener> configurationListenerMap = applicationContext.getBeansOfType(ConfigurationListener.class);
for (ConfigurationListener configurationListener : configurationListenerMap.values()) {
configurationListener.configurationChanged();
}
}
}
| |
/*
* Copyright (c) 2008-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cometd.server;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.server.ConfigurableServerChannel;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.common.JSONContext;
import org.cometd.common.JettyJSONContextClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CustomAdviceTest extends AbstractBayeuxClientServerTest
{
public CustomAdviceTest(String serverTransport)
{
super(serverTransport);
}
@Before
public void prepare() throws Exception
{
startServer(null);
}
@Test
public void testCustomTimeoutViaMessage() throws Exception
{
final CountDownLatch connectLatch = new CountDownLatch(2);
bayeux.getChannel(Channel.META_CONNECT).addListener(new ServerChannel.MessageListener()
{
public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message)
{
connectLatch.countDown();
return true;
}
});
String channelName = "/connect";
final long newTimeout = timeout / 2;
bayeux.createChannelIfAbsent(channelName, new ConfigurableServerChannel.Initializer()
{
public void configureChannel(ConfigurableServerChannel channel)
{
channel.addListener(new ServerChannel.MessageListener()
{
public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message)
{
from.setTimeout(newTimeout);
return true;
}
});
}
});
Request handshake = newBayeuxRequest("[{" +
"\"channel\": \"/meta/handshake\"," +
"\"version\": \"1.0\"," +
"\"minimumVersion\": \"1.0\"," +
"\"supportedConnectionTypes\": [\"long-polling\"]" +
"}]");
ContentResponse response = handshake.send();
Assert.assertEquals(200, response.getStatus());
String clientId = extractClientId(response);
Request connect1 = newBayeuxRequest("[{" +
"\"channel\": \"/meta/connect\"," +
"\"clientId\": \"" + clientId + "\"," +
"\"connectionType\": \"long-polling\"" +
"}]");
response = connect1.send();
Assert.assertEquals(200, response.getStatus());
Request connect2 = newBayeuxRequest("[{" +
"\"channel\": \"/meta/connect\"," +
"\"clientId\": \"" + clientId + "\"," +
"\"connectionType\": \"long-polling\"" +
"}]");
FutureResponseListener futureResponse = new FutureResponseListener(connect2);
connect2.send(futureResponse);
Assert.assertTrue(connectLatch.await(5, TimeUnit.SECONDS));
Request publish = newBayeuxRequest("[{" +
"\"channel\":\"" + channelName + "\"," +
"\"clientId\":\"" + clientId + "\"," +
"\"data\": {}" +
"}]");
response = publish.send();
Assert.assertEquals(200, response.getStatus());
// Wait for the second connect to return
response = futureResponse.get(timeout * 2, TimeUnit.SECONDS);
Assert.assertEquals(200, response.getStatus());
JSONContext.Client jsonContext = new JettyJSONContextClient();
Message.Mutable[] messages = jsonContext.parse(response.getContentAsString());
Message.Mutable connect = messages[0];
Map<String,Object> advice = connect.getAdvice();
Assert.assertNotNull(advice);
Number timeout = (Number)advice.get("timeout");
Assert.assertNotNull(timeout);
Assert.assertEquals(newTimeout, timeout.longValue());
}
@Test
public void testCustomIntervalViaMessage() throws Exception
{
final CountDownLatch connectLatch = new CountDownLatch(2);
bayeux.getChannel(Channel.META_CONNECT).addListener(new ServerChannel.MessageListener()
{
public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message)
{
connectLatch.countDown();
return true;
}
});
String channelName = "/interval";
final long newInterval = 1000;
bayeux.createChannelIfAbsent(channelName, new ConfigurableServerChannel.Initializer()
{
public void configureChannel(ConfigurableServerChannel channel)
{
channel.addListener(new ServerChannel.MessageListener()
{
public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message)
{
from.setInterval(newInterval);
return true;
}
});
}
});
Request handshake = newBayeuxRequest("[{" +
"\"channel\": \"/meta/handshake\"," +
"\"version\": \"1.0\"," +
"\"minimumVersion\": \"1.0\"," +
"\"supportedConnectionTypes\": [\"long-polling\"]" +
"}]");
ContentResponse response = handshake.send();
Assert.assertEquals(200, response.getStatus());
String clientId = extractClientId(response);
Request connect1 = newBayeuxRequest("[{" +
"\"channel\": \"/meta/connect\"," +
"\"clientId\": \"" + clientId + "\"," +
"\"connectionType\": \"long-polling\"" +
"}]");
response = connect1.send();
Assert.assertEquals(200, response.getStatus());
Request connect2 = newBayeuxRequest("[{" +
"\"channel\": \"/meta/connect\"," +
"\"clientId\": \"" + clientId + "\"," +
"\"connectionType\": \"long-polling\"" +
"}]");
FutureResponseListener futureResponse = new FutureResponseListener(connect2);
connect2.send(futureResponse);
Assert.assertTrue(connectLatch.await(5, TimeUnit.SECONDS));
Request publish = newBayeuxRequest("[{" +
"\"channel\":\"" + channelName + "\"," +
"\"clientId\":\"" + clientId + "\"," +
"\"data\": {}" +
"}]");
response = publish.send();
Assert.assertEquals(200, response.getStatus());
// Wait for the second connect to return
response = futureResponse.get(timeout * 2, TimeUnit.SECONDS);
Assert.assertEquals(200, response.getStatus());
JSONContext.Client jsonContext = new JettyJSONContextClient();
Message.Mutable[] messages = jsonContext.parse(response.getContentAsString());
Message.Mutable connect = messages[0];
Map<String,Object> advice = connect.getAdvice();
Assert.assertNotNull(advice);
Number interval = (Number)advice.get("interval");
Assert.assertNotNull(interval);
Assert.assertEquals(newInterval, interval.longValue());
}
@Test
public void testCustomIntervalViaAdvice() throws Exception
{
Request handshake = newBayeuxRequest("[{" +
"\"channel\": \"/meta/handshake\"," +
"\"version\": \"1.0\"," +
"\"minimumVersion\": \"1.0\"," +
"\"supportedConnectionTypes\": [\"long-polling\"]" +
"}]");
ContentResponse response = handshake.send();
Assert.assertEquals(200, response.getStatus());
String clientId = extractClientId(response);
Request connect1 = newBayeuxRequest("[{" +
"\"channel\": \"/meta/connect\"," +
"\"clientId\": \"" + clientId + "\"," +
"\"connectionType\": \"long-polling\"" +
"}]");
response = connect1.send();
Assert.assertEquals(200, response.getStatus());
// The client tells the server that it's going to sleep and won't connect for a while
// The server must adjust to not expire its session
long newInterval = 1000;
Request connect2 = newBayeuxRequest("[{" +
"\"channel\": \"/meta/connect\"," +
"\"clientId\": \"" + clientId + "\"," +
"\"connectionType\": \"long-polling\"," +
"\"advice\":{" +
" \"timeout\": 0," +
" \"interval\": " + newInterval +
"}" +
"}]");
response = connect2.send();
Assert.assertEquals(200, response.getStatus());
JSONContext.Client jsonContext = new JettyJSONContextClient();
Message.Mutable[] messages = jsonContext.parse(response.getContentAsString());
Message.Mutable connect = messages[0];
Map<String,Object> advice = connect.getAdvice();
Assert.assertNotNull(advice);
Number interval = (Number)advice.get("interval");
Assert.assertNotNull(interval);
Assert.assertEquals(newInterval, interval.longValue());
// Verify that the server is aware of the interval and will not expire the session
ServerSessionImpl session = (ServerSessionImpl)bayeux.getSession(clientId);
long expectedMaxInterval = session.getIntervalTimestamp() - System.currentTimeMillis();
Assert.assertTrue(expectedMaxInterval > session.getMaxInterval() + newInterval / 2);
}
}
| |
/*
* 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.util;
import com.google.api.client.http.HttpBackOffIOExceptionHandler;
import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseInterceptor;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.api.client.util.BackOff;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.client.util.NanoClock;
import com.google.api.client.util.Sleeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Implements a request initializer that adds retry handlers to all
* HttpRequests.
*
* <p>This allows chaining through to another HttpRequestInitializer, since
* clients have exactly one HttpRequestInitializer, and Credential is also
* a required HttpRequestInitializer.
*
* <p>Also can take a HttpResponseInterceptor to be applied to the responses.
*/
public class RetryHttpRequestInitializer implements HttpRequestInitializer {
private static final Logger LOG = LoggerFactory.getLogger(RetryHttpRequestInitializer.class);
/**
* Http response codes that should be silently ignored.
*/
private static final Set<Integer> DEFAULT_IGNORED_RESPONSE_CODES = new HashSet<>(
Arrays.asList(307 /* Redirect, handled by the client library */,
308 /* Resume Incomplete, handled by the client library */));
/**
* Http response timeout to use for hanging gets.
*/
private static final int HANGING_GET_TIMEOUT_SEC = 80;
private static class LoggingHttpBackOffIOExceptionHandler
extends HttpBackOffIOExceptionHandler {
public LoggingHttpBackOffIOExceptionHandler(BackOff backOff) {
super(backOff);
}
@Override
public boolean handleIOException(HttpRequest request, boolean supportsRetry)
throws IOException {
boolean willRetry = super.handleIOException(request, supportsRetry);
if (willRetry) {
LOG.debug("Request failed with IOException, will retry: {}", request.getUrl());
} else {
LOG.warn("Request failed with IOException, will NOT retry: {}", request.getUrl());
}
return willRetry;
}
}
private static class LoggingHttpBackoffUnsuccessfulResponseHandler
implements HttpUnsuccessfulResponseHandler {
private final HttpBackOffUnsuccessfulResponseHandler handler;
private final Set<Integer> ignoredResponseCodes;
public LoggingHttpBackoffUnsuccessfulResponseHandler(BackOff backoff,
Sleeper sleeper, Set<Integer> ignoredResponseCodes) {
this.ignoredResponseCodes = ignoredResponseCodes;
handler = new HttpBackOffUnsuccessfulResponseHandler(backoff);
handler.setSleeper(sleeper);
handler.setBackOffRequired(
new HttpBackOffUnsuccessfulResponseHandler.BackOffRequired() {
@Override
public boolean isRequired(HttpResponse response) {
int statusCode = response.getStatusCode();
return (statusCode / 100 == 5) || // 5xx: server error
statusCode == 429; // 429: Too many requests
}
});
}
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response,
boolean supportsRetry) throws IOException {
boolean retry = handler.handleResponse(request, response, supportsRetry);
if (retry) {
LOG.debug("Request failed with code {} will retry: {}",
response.getStatusCode(), request.getUrl());
} else if (!ignoredResponseCodes.contains(response.getStatusCode())) {
LOG.warn("Request failed with code {}, will NOT retry: {}",
response.getStatusCode(), request.getUrl());
}
return retry;
}
}
@Deprecated
private final HttpRequestInitializer chained;
private final HttpResponseInterceptor responseInterceptor; // response Interceptor to use
private final NanoClock nanoClock; // used for testing
private final Sleeper sleeper; // used for testing
private Set<Integer> ignoredResponseCodes = new HashSet<>(DEFAULT_IGNORED_RESPONSE_CODES);
public RetryHttpRequestInitializer() {
this(Collections.<Integer>emptyList());
}
/**
* @param chained a downstream HttpRequestInitializer, which will also be
* applied to HttpRequest initialization. May be null.
*
* @deprecated use {@link #RetryHttpRequestInitializer}.
*/
@Deprecated
public RetryHttpRequestInitializer(@Nullable HttpRequestInitializer chained) {
this(chained, Collections.<Integer>emptyList());
}
/**
* @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged.
*/
public RetryHttpRequestInitializer(Collection<Integer> additionalIgnoredResponseCodes) {
this(additionalIgnoredResponseCodes, null);
}
/**
* @param chained a downstream HttpRequestInitializer, which will also be
* applied to HttpRequest initialization. May be null.
* @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged.
*
* @deprecated use {@link #RetryHttpRequestInitializer(Collection)}.
*/
@Deprecated
public RetryHttpRequestInitializer(@Nullable HttpRequestInitializer chained,
Collection<Integer> additionalIgnoredResponseCodes) {
this(chained, additionalIgnoredResponseCodes, null);
}
/**
* @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged.
* @param responseInterceptor HttpResponseInterceptor to be applied on all requests. May be null.
*/
public RetryHttpRequestInitializer(
Collection<Integer> additionalIgnoredResponseCodes,
@Nullable HttpResponseInterceptor responseInterceptor) {
this(null, NanoClock.SYSTEM, Sleeper.DEFAULT, additionalIgnoredResponseCodes,
responseInterceptor);
}
/**
* @param chained a downstream HttpRequestInitializer, which will also be applied to HttpRequest
* initialization. May be null.
* @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged.
* @param responseInterceptor HttpResponseInterceptor to be applied on all requests. May be null.
*
* @deprecated use {@link #RetryHttpRequestInitializer(Collection, HttpResponseInterceptor)}.
*/
@Deprecated
public RetryHttpRequestInitializer(
@Nullable HttpRequestInitializer chained,
Collection<Integer> additionalIgnoredResponseCodes,
@Nullable HttpResponseInterceptor responseInterceptor) {
this(chained, NanoClock.SYSTEM, Sleeper.DEFAULT, additionalIgnoredResponseCodes,
responseInterceptor);
}
/**
* Visible for testing.
*
* @param chained a downstream HttpRequestInitializer, which will also be
* applied to HttpRequest initialization. May be null.
* @param nanoClock used as a timing source for knowing how much time has elapsed.
* @param sleeper used to sleep between retries.
* @param additionalIgnoredResponseCodes a list of HTTP status codes that should not be logged.
*/
RetryHttpRequestInitializer(@Nullable HttpRequestInitializer chained,
NanoClock nanoClock, Sleeper sleeper, Collection<Integer> additionalIgnoredResponseCodes,
HttpResponseInterceptor responseInterceptor) {
this.chained = chained;
this.nanoClock = nanoClock;
this.sleeper = sleeper;
this.ignoredResponseCodes.addAll(additionalIgnoredResponseCodes);
this.responseInterceptor = responseInterceptor;
}
@Override
public void initialize(HttpRequest request) throws IOException {
if (chained != null) {
chained.initialize(request);
}
// Set a timeout for hanging-gets.
// TODO: Do this exclusively for work requests.
request.setReadTimeout(HANGING_GET_TIMEOUT_SEC * 1000);
// Back off on retryable http errors.
request.setUnsuccessfulResponseHandler(
// A back-off multiplier of 2 raises the maximum request retrying time
// to approximately 5 minutes (keeping other back-off parameters to
// their default values).
new LoggingHttpBackoffUnsuccessfulResponseHandler(
new ExponentialBackOff.Builder().setNanoClock(nanoClock)
.setMultiplier(2).build(),
sleeper, ignoredResponseCodes));
// Retry immediately on IOExceptions.
LoggingHttpBackOffIOExceptionHandler loggingBackoffHandler =
new LoggingHttpBackOffIOExceptionHandler(BackOff.ZERO_BACKOFF);
request.setIOExceptionHandler(loggingBackoffHandler);
// Set response initializer
if (responseInterceptor != null) {
request.setResponseInterceptor(responseInterceptor);
}
}
}
| |
/**
*
* @author greg (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab 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 (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* 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.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.control;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import org.myrobotlab.control.widget.DigitalButton;
import org.myrobotlab.control.widget.EditorPropeller;
import org.myrobotlab.control.widget.JIntegerField;
import org.myrobotlab.image.SerializableImage;
import org.myrobotlab.image.Util;
import org.myrobotlab.serial.SerialDevice;
import org.myrobotlab.service.GUIService;
import org.myrobotlab.service.Propeller;
import org.myrobotlab.service.data.Pin;
/*
* TODO - move menu into PropellerGUI from editor
* - synch up repo with createLabs
* - correct pin state on menu
* - make Communication -> menu -> MRLComm.ino
* - make menu builder
* - auto-load - MRLComm first
* - refresh serial ?
* - message syphone - message pump - stdout stdin pipes process creator etc...
* - all traces start stop at same time
* - 100% on compile & upload
* - arrow changed for upload to "up" duh
* - incoming pin data -> determines state of inactive/active & oscope pin update
*
* - Java console - duh
* - uploader progress - duh
* - error goes to status
* - console info regarding the state & progress of "connecting" to a serialDevice
* - TODO - "errorMessage vs message" warnMessage too - embed in Console logic
*
*/
public class PropellerGUI extends ServiceGUI implements ItemListener, ActionListener, TabControlEventHandler {
public PropellerGUI(final String boundServiceName, final GUIService myService, final JTabbedPane tabs) {
super(boundServiceName, myService, tabs);
self = this;
}
/**
* component array - to access all components by name
*/
public Propeller myPropeller;
public PropellerGUI self;
HashMap<String, Component> components = new HashMap<String, Component>();
static final long serialVersionUID = 1L;
// FIXME - you need a pattern or a new Menu
// A Menu in the PropellerGUI versus the Propeller Editor
private JMenuItem serialRefresh = new JMenuItem("refresh");
private JMenuItem softReset = new JMenuItem("soft reset");
private JMenuItem serialDisconnect = new JMenuItem("disconnect");
JTabbedPane tabs = new JTabbedPane();
/*
* ---------- Pins begin -------------------------
*/
JLayeredPane imageMap;
/*
* ---------- Pins end -------------------------
*/
/*
* ---------- Config begin -------------------------
*/
JIntegerField rawReadMsgLength = new JIntegerField(4);
JCheckBox rawReadMessage = new JCheckBox();
/*
* ---------- Config end -------------------------
*/
/*
* ---------- Oscope begin -------------------------
*/
/**
* array list of graphical pin components built from pinList
*/
ArrayList<PinComponent> pinComponentList = null;
SerializableImage sensorImage = null;
Graphics g = null;
VideoWidget oscope = null;
JPanel oscopePanel = null;
/*
* ---------- Oscope end -------------------------
*/
/*
* ---------- Editor begin -------------------------
*/
// Base propellerIDE;
DigitalButton uploadButton = null;
GridBagConstraints epgc = new GridBagConstraints();
Dimension size = new Dimension(620, 512);
Map<String, String> boardPreferences;
String boardName;
// JCheckBoxMenuItem serialDevice;
SerialMenuListener serialMenuListener = new SerialMenuListener();
/*
* ---------- Editor end -------------------------
*/
/**
* pinList - from Propeller
*/
ArrayList<Pin> pinList = null;
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
display.setLayout(new BorderLayout());
// ---------------- tabs begin ----------------------
tabs.setTabPlacement(JTabbedPane.RIGHT);
getPinPanel();
getOscopePanel();
getEditorPanel();
display.add(tabs, BorderLayout.CENTER);
//tabs.setSelectedIndex(0);
serialRefresh.addActionListener(self);
softReset.addActionListener(self);
serialDisconnect.addActionListener(self);
}
});
}
public void getPinPanel() {
if (myPropeller != null && boardName != null && boardName.contains("Mega")) {
getMegaPanel();
return;
}
getDuemilanovePanel();
}
class SerialMenuListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JRadioButtonMenuItem checkbox = (JRadioButtonMenuItem) e.getSource();
if (checkbox.isSelected()) {
myService.send(boundServiceName, "connect", checkbox.getText(), 57600, 8, 1, 0);
} else {
myService.send(boundServiceName, "disconnect");
}
}
}
/**
* getState is called when the Propeller service changes state information
* FIXME - this method is often called by other threads so gui - updates
* must be done in the swing post method way
*
* @param propeller
*/
public void getState(final Propeller propeller) { // TODO - all getState data
// should be final
SwingUtilities.invokeLater(new Runnable() {
public void run() {
log.info("getState Propeller");
if (propeller != null) {
myPropeller = propeller; // FIXME - super updates registry state
// ?
boardName = "prop1"; // FIXME - class
// member has
// precedence -
// do away with
// properties !
pinList = myPropeller.getPinList();
// update panels based on state change
// TODO - check what state the panels are to see if a
// change is needed
getPinPanel();
getOscopePanel();
editor.serialDeviceMenu.removeAll();
publishMessage(String.format("found %d serial ports", myPropeller.portNames.size()));
for (int i = 0; i < myPropeller.portNames.size(); ++i) {
String portName = myPropeller.portNames.get(i);
publishMessage(String.format(" %s", portName));
JRadioButtonMenuItem serialDevice = new JRadioButtonMenuItem(myPropeller.portNames.get(i));
SerialDevice sd = myPropeller.getSerialDevice();
if (sd != null && sd.getName().equals(portName) && editor.connectButton != null) {
if (sd.isOpen()) {
// FIXME - editor is often == null - race condition :(
editor.connectButton.activate();
serialDevice.setSelected(true);
} else {
editor.connectButton.deactivate();
serialDevice.setSelected(false);
}
} else {
serialDevice.setSelected(false);
}
serialDevice.addActionListener(serialMenuListener);
editor.serialDeviceMenu.add(serialDevice);
// editor.getTextArea().setText(propeller.getSketch());
// if the service has a different sketch update the gui
// TODO - kinder - gentler - ask user if they want the
// update
}
if (!editor.getTextArea().equals(propeller.getSketch())) {
editor.getTextArea().setText(propeller.getSketch());
}
}
// TODO - work on generalizing editor
editor.serialDeviceMenu.add(serialRefresh);
editor.serialDeviceMenu.add(serialDisconnect);
editor.serialDeviceMenu.add(softReset);
String statusString = boardName + " " + myPropeller.getPortName();
editor.setStatus(statusString);
}
});
}
public void setCompilingProgress(Integer percent) {
editor.progress.setValue(percent);
}
public void compilerError(String msg) {
editor.status.setText(msg);
}
public void publishMessage(String msg) {
if (editor != null) {
editor.console.append(msg);
}
}
@Override
public void attachGUI() {
subscribe("publishPin", "publishPin", Pin.class);
subscribe("publishState", "getState", Propeller.class);
subscribe("publishCompilingProgress", "setCompilingProgress", Integer.class);
subscribe("publishMessage", "publishMessage", String.class);
subscribe("compilerError", "compilerError", String.class);
subscribe("getPorts", "getPorts", String.class);
// subscribe("setBoard", "setBoard", String.class);
// myService.send(boundServiceName, "broadcastState");
myService.send(boundServiceName, "publishState");
}
@Override
public void detachGUI() {
unsubscribe("publishPin", "publishPin", Pin.class);
unsubscribe("publishState", "getState", Propeller.class);
unsubscribe("publishCompilingProgress", "setCompilingProgress", Integer.class);
unsubscribe("publishMessage", "publishMessage", String.class);
unsubscribe("compilerError", "compilerError", String.class);
}
@Override
public void itemStateChanged(ItemEvent item) {
{
// called when the button is pressed
JCheckBox cb = (JCheckBox) item.getSource();
// Determine status
boolean isSel = cb.isSelected();
if (isSel) {
myService.send(boundServiceName, "setRawReadMsg", true);
myService.send(boundServiceName, "setReadMsgLength", rawReadMsgLength.getInt());
rawReadMsgLength.setEnabled(false);
} else {
myService.send(boundServiceName, "setRawReadMsg", false);
myService.send(boundServiceName, "setReadMsgLength", rawReadMsgLength.getInt());
rawReadMsgLength.setEnabled(true);
}
}
}
/**
* The guts of the business logic of handling all the graphical components
* and their relations with each other.
*/
@Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
String cmd = e.getActionCommand();
Component c = (Component) e.getSource();
if (o == serialRefresh) {
myService.send(boundServiceName, "getPortNames");
myService.send(boundServiceName, "publishState");
return;
}
if (o == softReset) {
myService.send(boundServiceName, "softReset");
return;
}
if (o == serialDisconnect) {
myService.send(boundServiceName, "disconnect");
return;
}
// buttons
if (DigitalButton.class == o.getClass()) {
DigitalButton b = (DigitalButton) o;
if (uploadButton == c) {
uploadButton.toggle();
return;
}
PinComponent pin = null;
int address = -1;
int value = -1;
if (b.parent != null) {
address = ((PinComponent) b.parent).pinNumber;
pin = ((PinComponent) b.parent);
}
if (b.type == PinComponent.TYPE_ONOFF) {
if ("off".equals(cmd)) {
// now on
value = PinComponent.HIGH;
myService.send(boundServiceName, "digitalWrite", address, value);
b.toggle();
} else {
// now off
value = PinComponent.LOW;
myService.send(boundServiceName, "digitalWrite", address, value);
b.toggle();
}
} else if (b.type == PinComponent.TYPE_INOUT) {
if ("out".equals(cmd)) {
// is now input
value = PinComponent.INPUT;
myService.send(boundServiceName, "pinMode", address, value);
myService.send(boundServiceName, "digitalReadPollStart", address);
b.toggle();
} else if ("in".equals(cmd)) {
// is now output
value = PinComponent.OUTPUT;
myService.send(boundServiceName, "pinMode", address, value);
myService.send(boundServiceName, "digitalReadPollStop", address);
b.toggle();
} else {
log.error(String.format("unknown digital pin cmd %s", cmd));
}
} else if (b.type == PinComponent.TYPE_TRACE || b.type == PinComponent.TYPE_ACTIVEINACTIVE) {
// digital pin
if (!pin.isAnalog) {
if (!pin.inOut.isOn) { // pin is off turn it on
value = PinComponent.INPUT;
myService.send(boundServiceName, "pinMode", address, value);
myService.send(boundServiceName, "digitalReadPollStart", address);
pin.inOut.setOn(); // in
b.setOn();
} else {
value = PinComponent.OUTPUT;
myService.send(boundServiceName, "pinMode", address, value);
myService.send(boundServiceName, "digitalReadPollStop", address);
pin.inOut.setOff();// out
b.setOff();
}
} else {
value = PinComponent.INPUT;
myService.send(boundServiceName, "pinMode", address, value);
// analog pin
if (pin.activeInActive.isOn) {
myService.send(boundServiceName, "analogReadPollingStop", address);
pin.activeInActive.setOff();
pin.trace.setOff();
b.setOff();
} else {
myService.send(boundServiceName, "analogReadPollingStart", address);
pin.activeInActive.setOn();
pin.trace.setOn();
b.setOn();
}
}
} else {
log.error("unknown pin type " + b.type);
}
log.info("DigitalButton");
}
}
public void closeSerialDevice() {
myService.send(boundServiceName, "closeSerialDevice");
}
class TraceData {
Color color = null;
String label;
String controllerName;
int pin;
int data[] = new int[DATA_WIDTH];
int index = 0;
int total = 0;
int max = 0;
int min = 1024; // TODO - user input on min/max
int sum = 0;
int mean = 0;
int traceStart = 0;
}
int DATA_WIDTH = size.width;
int DATA_HEIGHT = size.height;
HashMap<Integer, TraceData> traceData = new HashMap<Integer, TraceData>();
int clearX = 0;
int lastTraceXPos = 0;
public void publishPin(final Pin pin) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (!traceData.containsKey(pin.pin)) {
TraceData td = new TraceData();
float gradient = 1.0f / pinComponentList.size();
Color color = new Color(Color.HSBtoRGB((pin.pin * (gradient)), 0.8f, 0.7f));
td.color = color;
traceData.put(pin.pin, td);
td.index = lastTraceXPos;
}
TraceData t = traceData.get(pin.pin);
t.index++;
lastTraceXPos = t.index;
t.data[t.index] = pin.value;
++t.total;
t.sum += pin.value;
t.mean = t.sum / t.total;
g.setColor(t.color);
if (pin.type == Pin.DIGITAL_VALUE || pin.type == Pin.PWM_VALUE) {
int yoffset = pin.pin * 15 + 35;
int quantum = -10;
g.drawLine(t.index, t.data[t.index - 1] * quantum + yoffset, t.index, pin.value * quantum + yoffset);
} else if (pin.type == Pin.ANALOG_VALUE) {
g.drawLine(t.index, DATA_HEIGHT - t.data[t.index - 1] / 2, t.index, DATA_HEIGHT - pin.value / 2);
} else {
log.error("dont know how to display pin data method");
}
// computer min max and mean
// if different then blank & post to screen
if (pin.value > t.max)
t.max = pin.value;
if (pin.value < t.min)
t.min = pin.value;
if (t.index < DATA_WIDTH - 1) {
clearX = t.index + 1;
} else {
// TODO - when hit marks all startTracePos - cause the
// screen is
// blank - must iterate through all
t.index = 0;
clearScreen();
drawGrid();
g.setColor(Color.BLACK);
g.fillRect(20, t.pin * 15 + 5, 200, 15);
g.setColor(t.color);
g.drawString(String.format("min %d max %d mean %d ", t.min, t.max, t.mean), 20, t.pin * 15 + 20);
t.total = 0;
t.sum = 0;
}
oscope.displayFrame(sensorImage);
}
});
}
public void clearScreen() // TODO - static - put in oscope/image package
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, DATA_WIDTH, DATA_HEIGHT); // TODO - ratio - to expand
// or reduce view
}
public void drawGrid() // TODO - static & put in oscope/image package
{
g.setColor(Color.DARK_GRAY);
g.drawLine(0, DATA_HEIGHT - 25, DATA_WIDTH - 1, DATA_HEIGHT - 25);
g.drawString("50", 10, DATA_HEIGHT - 25);
g.drawLine(0, DATA_HEIGHT - 50, DATA_WIDTH - 1, DATA_HEIGHT - 50);
g.drawString("100", 10, DATA_HEIGHT - 50);
g.drawLine(0, DATA_HEIGHT - 100, DATA_WIDTH - 1, DATA_HEIGHT - 100);
g.drawString("200", 10, DATA_HEIGHT - 100);
g.drawLine(0, DATA_HEIGHT - 200, DATA_WIDTH - 1, DATA_HEIGHT - 200);
g.drawString("400", 10, DATA_HEIGHT - 200);
g.drawLine(0, DATA_HEIGHT - 300, DATA_WIDTH - 1, DATA_HEIGHT - 300);
g.drawString("600", 10, DATA_HEIGHT - 300);
g.drawLine(0, DATA_HEIGHT - 400, DATA_WIDTH - 1, DATA_HEIGHT - 400);
g.drawString("800", 10, DATA_HEIGHT - 400);
}
/**
* Spew the contents of a String object out to a file.
*/
static public void saveFile(String str, File file) throws IOException {
File temp = File.createTempFile(file.getName(), null, file.getParentFile());
// PApplet.saveStrings(temp, new String[] { str }); FIXME
if (file.exists()) {
boolean result = file.delete();
if (!result) {
throw new IOException("Could not remove old version of " + file.getAbsolutePath());
}
}
boolean result = temp.renameTo(file);
if (!result) {
throw new IOException("Could not replace " + file.getAbsolutePath());
}
}
/**
* Get the number of lines in a file by counting the number of newline
* characters inside a String (and adding 1).
*/
static public int countLines(String what) {
int count = 1;
for (char c : what.toCharArray()) {
if (c == '\n')
count++;
}
return count;
}
public void getMegaPanel() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (imageMap != null) {
tabs.remove(imageMap);
}
pinComponentList = new ArrayList<PinComponent>();
imageMap = new JLayeredPane();
imageMap.setPreferredSize(size);
// set correct propeller image
JLabel image = new JLabel();
ImageIcon dPic = Util.getImageIcon("Propeller/mega.200.pins.png");
image.setIcon(dPic);
Dimension s = image.getPreferredSize();
image.setBounds(0, 0, s.width, s.height);
imageMap.add(image, new Integer(1));
for (int i = 0; i < 70; ++i) {
PinComponent p = null;
if (i > 1 && i < 14) { // pwm pins -----------------
p = new PinComponent(myService, boundServiceName, i, true, false, true);
int xOffSet = 0;
if (i > 7)
xOffSet = 18; // skip pin
p.inOut.setBounds(252 - 18 * i - xOffSet, 30, 15, 30);
imageMap.add(p.inOut, new Integer(2));
p.onOff.setBounds(252 - 18 * i - xOffSet, 0, 15, 30);
// p.onOff.getLabel().setUI(new VerticalLabelUI(true));
imageMap.add(p.onOff, new Integer(2));
if (p.isPWM) {
p.pwmSlider.setBounds(252 - 18 * i - xOffSet, 75, 15, 90);
imageMap.add(p.pwmSlider, new Integer(2));
p.data.setBounds(252 - 18 * i - xOffSet, 180, 32, 15);
p.data.setForeground(Color.white);
p.data.setBackground(Color.decode("0x0f7391"));
p.data.setOpaque(true);
imageMap.add(p.data, new Integer(2));
}
} else if (i < 54 && i > 21) {
// digital pin racks
p = new PinComponent(myService, boundServiceName, i, false, false, false);
if (i != 23 && i != 25 && i != 27 && i != 29) {
if ((i % 2 == 0)) {
// first rack of digital pins
p.inOut.setBounds(472, 55 + 9 * (i - 21), 30, 15);
imageMap.add(p.inOut, new Integer(2));
p.onOff.setBounds(502, 55 + 9 * (i - 21), 30, 15);
// p.onOff.getLabel().setUI(new
// VerticalLabelUI(true));
imageMap.add(p.onOff, new Integer(2));
} else {
// second rack of digital pins
p.inOut.setBounds(567, 45 + 9 * (i - 21), 30, 15);
imageMap.add(p.inOut, new Integer(2));
p.onOff.setBounds(597, 45 + 9 * (i - 21), 30, 15);
// p.onOff.getLabel().setUI(new
// VerticalLabelUI(true));
imageMap.add(p.onOff, new Integer(2));
}
}
} else if (i > 53) {
p = new PinComponent(myService, boundServiceName, i, false, true, true);
// analog pins -----------------
int xOffSet = 0;
if (i > 61)
xOffSet = 18; // skip pin
p.activeInActive.setBounds(128 + 18 * (i - 52) + xOffSet, 392, 15, 48);
imageMap.add(p.activeInActive, new Integer(2));
/*
* bag data at the moment - go look at the Oscope
* p.data.setBounds(208 + 18 * (i - 52) + xOffSet, 260,
* 32, 18); p.data.setForeground(Color.white);
* p.data.setBackground(Color.decode("0x0f7391"));
* p.data.setOpaque(true); imageMap.add(p.data, new
* Integer(2));
*/
} else {
p = new PinComponent(myService, boundServiceName, i, false, false, false);
}
// set up the listeners
p.onOff.addActionListener(self);
p.inOut.addActionListener(self);
p.activeInActive.addActionListener(self);
p.trace.addActionListener(self);
// p.inOut2.addActionListener(this);
pinComponentList.add(p);
}
JFrame top = myService.getFrame();
tabs.insertTab("pins", null, imageMap, "pin panel", 0);
GUIService gui = (GUIService) myService;// FIXME - bad bad bad
//TabControl2(TabControlEventHandler handler, JTabbedPane tabs, Container myPanel, String label)
tabs.setTabComponentAt(0, new TabControl2(self, tabs, imageMap, "pins"));
}
});
}
// public
public void getDuemilanovePanel() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (imageMap != null) {
tabs.remove(imageMap);
}
imageMap = new JLayeredPane();
imageMap.setPreferredSize(size);
pinComponentList = new ArrayList<PinComponent>();
// set correct propeller image
JLabel image = new JLabel();
ImageIcon dPic = Util.getImageIcon("Propeller/propeller.duemilanove.200.pins.png");
image.setIcon(dPic);
Dimension s = image.getPreferredSize();
image.setBounds(0, 0, s.width, s.height);
imageMap.add(image, new Integer(1));
for (int i = 0; i < 20; ++i) {
PinComponent p = null;
if (i < 14) {
if (((i == 3) || (i == 5) || (i == 6) || (i == 9) || (i == 10) || (i == 11))) {
p = new PinComponent(myService, boundServiceName, i, true, false, false);
} else {
p = new PinComponent(myService, boundServiceName, i, false, false, false);
}
} else {
p = new PinComponent(myService, boundServiceName, i, false, true, false);
}
// set up the listeners
p.onOff.addActionListener(self);
p.inOut.addActionListener(self);
p.activeInActive.addActionListener(self);
p.trace.addActionListener(self);
// p.inOut2.addActionListener(this);
pinComponentList.add(p);
if (i < 2) {
continue;
}
if (i < 14) { // digital pins -----------------
int yOffSet = 0;
if (i > 7)
yOffSet = 18; // skip pin
p.inOut.setBounds(406, 297 - 18 * i - yOffSet, 30, 15);
imageMap.add(p.inOut, new Integer(2));
p.onOff.setBounds(436, 297 - 18 * i - yOffSet, 30, 15);
// p.onOff.getLabel().setUI(new VerticalLabelUI(true));
imageMap.add(p.onOff, new Integer(2));
if (p.isPWM) {
p.pwmSlider.setBounds(256, 297 - 18 * i - yOffSet, 90, 15);
imageMap.add(p.pwmSlider, new Integer(2));
p.data.setBounds(232, 297 - 18 * i - yOffSet, 32, 15);
p.data.setForeground(Color.white);
p.data.setBackground(Color.decode("0x0f7391"));
p.data.setOpaque(true);
imageMap.add(p.data, new Integer(2));
}
} else {
// analog pins -----------------
p.activeInActive.setBounds(11, 208 - 18 * (14 - i), 48, 15);
imageMap.add(p.activeInActive, new Integer(2));
p.data.setBounds(116, 205 - 18 * (14 - i), 32, 18);
p.data.setForeground(Color.white);
p.data.setBackground(Color.decode("0x0f7391"));
p.data.setOpaque(true);
imageMap.add(p.data, new Integer(2));
}
}
JFrame top = myService.getFrame();
tabs.insertTab("pins", null, imageMap, "pin panel", 0);
GUIService gui = (GUIService) myService;// FIXME - bad bad bad
// ...
// FIXME TabControl2 - tabs.setTabComponentAt(0, new
// TabControl(gui,
// tabs, imageMap, boundServiceName, "pins"));
}
});
}
public void getOscopePanel() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (oscopePanel != null) {
tabs.remove(oscopePanel);
}
// CREATE SERVICE GUI !!!
oscopePanel = new JPanel(new GridBagLayout());
GridBagConstraints opgc = new GridBagConstraints();
JPanel tracePanel = new JPanel(new GridBagLayout());
opgc.fill = GridBagConstraints.HORIZONTAL;
opgc.gridx = 0;
opgc.gridy = 0;
float gradient = 1.0f / pinComponentList.size();
// pinList.size() mega 60 deuo 20
for (int i = 0; i < pinComponentList.size(); ++i) {
PinComponent p = pinComponentList.get(i);
if (!p.isAnalog) { // digital pins -----------------
p.trace.setText("D " + (i));
p.trace.onText = "D " + (i);
p.trace.offText = "D " + (i);
} else {
// analog pins ------------------
p.trace.setText("A " + (i - 14));
p.trace.onText = "A " + (i - 14);
p.trace.offText = "A " + (i - 14);
}
tracePanel.add(p.trace, opgc);
Color hsv = new Color(Color.HSBtoRGB((i * (gradient)), 0.8f, 0.7f));
p.trace.setBackground(hsv);
p.trace.offBGColor = hsv;
++opgc.gridy;
if (opgc.gridy % 20 == 0) {
opgc.gridy = 0;
++opgc.gridx;
}
}
opgc.gridx = 0;
opgc.gridy = 0;
oscope = new VideoWidget(boundServiceName, myService, tabs, false);
oscope.init();
sensorImage = new SerializableImage(new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB), "output");
g = sensorImage.getImage().getGraphics();
oscope.displayFrame(sensorImage);
oscopePanel.add(tracePanel, opgc);
++opgc.gridx;
oscopePanel.add(oscope.display, opgc);
JFrame top = myService.getFrame();
tabs.insertTab("oscope", null, oscopePanel, "oscope panel", 0);
tabs.setTabComponentAt(0, new TabControl2(self, tabs, oscopePanel, "oscope"));
myService.getFrame().pack();
}
});
}
EditorPropeller editor = null;
public void getEditorPanel() {
editor = new EditorPropeller(boundServiceName, myService, tabs);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// if (editorPanel != null) {
// tabs.remove(editorPanel);
// }
// editorPanel = new JPanel(new BorderLayout());
editor.init();
// editorPanel.add(editor.getDisplay());
JFrame top = myService.getFrame();
tabs.insertTab("editor", null, editor.getDisplay(), "editor", 0);
GUIService gui = (GUIService) myService;// FIXME - bad bad bad
// ...
// FIXME TabControl2 - tabs.setTabComponentAt(0, new
// TabControl(gui,
// tabs, editor.getDisplay(), boundServiceName, "editor"));
myService.getFrame().pack();
}
});
}
public void createSerialDeviceMenu(JMenu m) {
for (int i = 0; i < myPropeller.portNames.size(); ++i) {
// m.add(a)
}
}
}
| |
/**
*
*/
package org.jabref.logic.importer.fileformat;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.jabref.logic.importer.Importer;
import org.jabref.logic.importer.ParserResult;
import org.jabref.logic.util.StandardFileType;
import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.FieldName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
*
*/
public class MrDLibImporter extends Importer {
private static final Logger LOGGER = LoggerFactory.getLogger(MrDLibImporter.class);
public ParserResult parserResult;
@Override
public boolean isRecognizedFormat(BufferedReader input) throws IOException {
String recommendationsAsString = convertToString(input);
// check for valid format
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
// No Processing here. Just check for valid xml.
// Later here will be the check against the XML schema.
};
try (InputStream stream = new ByteArrayInputStream(recommendationsAsString.getBytes())) {
saxParser.parse(stream, handler);
} catch (Exception e) {
return false;
}
} catch (ParserConfigurationException | SAXException e) {
return false;
}
return true;
}
@Override
public ParserResult importDatabase(BufferedReader input) throws IOException {
parse(input);
return parserResult;
}
@Override
public String getName() {
return "MrDLibImporter";
}
@Override
public StandardFileType getFileType() {
return StandardFileType.XML;
}
@Override
public String getDescription() {
return "Takes valid xml documents. Parses from MrDLib API a BibEntry";
}
/**
* The SaxParser needs this String. So I convert it here.
* @param Takes a BufferedReader with a reference to the XML document delivered by mdl server.
* @return Returns an String containing the XML file.
* @throws IOException
*/
private String convertToString(BufferedReader input) throws IOException {
String line;
StringBuilder stringBuilder = new StringBuilder();
try {
while ((line = input.readLine()) != null) {
stringBuilder.append(line);
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return stringBuilder.toString();
}
/**
* Small pair-class to ensure the right order of the recommendations.
*/
private class RankedBibEntry {
public BibEntry entry;
public Integer rank;
public RankedBibEntry(BibEntry entry, Integer rank) {
this.rank = rank;
this.entry = entry;
}
}
/**
* Parses the input from the server to a ParserResult
* @param input A BufferedReader with a reference to a string with the servers response
* @throws IOException
*/
private void parse(BufferedReader input) throws IOException {
// The Bibdatabase that gets returned in the ParserResult.
BibDatabase bibDatabase = new BibDatabase();
// The document to parse
String recommendations = convertToString(input);
// The sorted BibEntries gets stored here later
List<BibEntry> bibEntries = new ArrayList<>();
//Parsing the response with a SAX parser
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
MrDlibImporterHandler handler = new MrDlibImporterHandler();
try (InputStream stream = new ByteArrayInputStream(recommendations.getBytes())) {
saxParser.parse(stream, handler);
} catch (SAXException e) {
LOGGER.error(e.getMessage(), e);
}
List<RankedBibEntry> rankedBibEntries = handler.getRankedBibEntries();
rankedBibEntries.sort((RankedBibEntry rankedBibEntry1,
RankedBibEntry rankedBibEntry2) -> rankedBibEntry1.rank.compareTo(rankedBibEntry2.rank));
bibEntries = rankedBibEntries.stream().map(e -> e.entry).collect(Collectors.toList());
} catch (ParserConfigurationException | SAXException e) {
LOGGER.error(e.getMessage(), e);
}
for (BibEntry bibentry : bibEntries) {
bibDatabase.insertEntry(bibentry);
}
parserResult = new ParserResult(bibDatabase);
}
public ParserResult getParserResult() {
return parserResult;
}
/**
* Handler that parses the response from Mr. DLib to BibEntries
*/
private class MrDlibImporterHandler extends DefaultHandler {
// The list ob BibEntries with its associated rank
private final List<RankedBibEntry> rankedBibEntries = new ArrayList<>();
private boolean authors;
private boolean published_in;
private boolean title;
private boolean year;
private boolean snippet;
private boolean rank;
private boolean type;
private String htmlSnippetSingle;
private int htmlSnippetSingleRank = -1;
private BibEntry currentEntry;
public List<RankedBibEntry> getRankedBibEntries() {
return rankedBibEntries;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
switch (qName.toLowerCase(Locale.ROOT)) {
case "related_article":
currentEntry = new BibEntry();
htmlSnippetSingle = null;
htmlSnippetSingleRank = -1;
break;
case "authors":
authors = true;
break;
case "published_in":
published_in = true;
break;
case "title":
title = true;
break;
case "year":
year = true;
break;
case "type":
type = true;
break;
case "suggested_rank":
rank = true;
break;
default:
break;
}
if (qName.equalsIgnoreCase("snippet")
&& attributes.getValue(0).equalsIgnoreCase("html_fully_formatted")) {
snippet = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("related_article")) {
rankedBibEntries.add(new RankedBibEntry(currentEntry, htmlSnippetSingleRank));
currentEntry = new BibEntry();
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (authors) {
currentEntry.setField(FieldName.AUTHOR, new String(ch, start, length));
authors = false;
}
if (published_in) {
currentEntry.setField(FieldName.JOURNAL, new String(ch, start, length));
published_in = false;
}
if (title) {
currentEntry.setField(FieldName.TITLE, new String(ch, start, length));
title = false;
}
if (year) {
currentEntry.setField(FieldName.YEAR, new String(ch, start, length));
year = false;
}
if (rank) {
htmlSnippetSingleRank = Integer.parseInt(new String(ch, start, length));
rank = false;
}
if (snippet) {
currentEntry.setField("html_representation", new String(ch, start, length));
snippet = false;
}
}
}
}
| |
package jfskora;
import com.google.common.collect.MinMaxPriorityQueue;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import java.lang.reflect.Field;
import java.util.AbstractQueue;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;
public class TestPriorityQueue {
static final String msgInit = "start compares= %3d (%3d)";
static final String msgAdd = "add %2s compares= %3d (%3d)";
static final String msgPoll = "poll %2s compares= %3d (%3d)";
static Map<String, List<Long>> runTimes = new HashMap<>();
boolean DEBUG = false;
@Rule
public TestName name = new TestName();
@Test
public void testAllQueues() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
final Long[] counter = new Long[1];
counter[0] = 0L;
Comparator<String> compString = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
counter[0]++;
return o1.compareTo(o2);
}
};
PriorityQueue<String> testPriorityQueue;
PriorityBlockingQueue<String> testPriorityBlockingQueue;
PriorityQueueExtended<String> testPriorityQueueExtended;
MinMaxPriorityQueue<String> testMinMaxPriorityQueue;
runTimes.put(PriorityQueue.class.getName(), new ArrayList<>());
runTimes.put(PriorityBlockingQueue.class.getName(), new ArrayList<>());
runTimes.put(PriorityQueueExtended.class.getName(), new ArrayList<>());
runTimes.put(MinMaxPriorityQueue.class.getName(), new ArrayList<>());
testPriorityQueue = new PriorityQueue<>(20, compString);
testQueue(testPriorityQueue, counter);
testPriorityBlockingQueue = new PriorityBlockingQueue<>(20, compString);
testQueue(testPriorityBlockingQueue, counter);
testPriorityQueueExtended = new PriorityQueueExtended<>(20, compString);
testQueue(testPriorityQueueExtended, counter);
testMinMaxPriorityQueue = MinMaxPriorityQueue.orderedBy(compString).expectedSize(20).create();
testQueue(testMinMaxPriorityQueue, counter);
System.out.println("");
int width = runTimes.keySet().stream().mapToInt(String::length).max().orElse(10);
for (String key : runTimes.keySet()) {
long total = runTimes.get(key).stream().mapToLong(Long::longValue).sum();
long avg = total / runTimes.get(key).size();
System.out.println(String.format("%-" + width + "s %12d %12d", key, total, avg));
}
}
@Ignore
@Test
public void testJavaUtilPriorityQueue() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
final Long[] counter = new Long[1];
counter[0] = 0L;
Comparator<String> compString = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
counter[0]++;
return o1.compareTo(o2);
}
};
PriorityQueue<String> testQueue = new PriorityQueue<>(20, compString);
runTimes.put(testQueue.getClass().getName(), new ArrayList<>());
testQueue(testQueue, counter);
}
@Ignore
@Test
public void testJavaUtilPriorityBlockingQueue() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
final Long[] counter = new Long[1];
counter[0] = 0L;
Comparator<String> compString = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
counter[0]++;
return o1.compareTo(o2);
}
};
PriorityBlockingQueue<String> testQueue = new PriorityBlockingQueue<>(20, compString);
runTimes.put(testQueue.getClass().getName(), new ArrayList<>());
testQueue(testQueue, counter);
}
@Ignore
@Test
public void testPriorityQueueExtended() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
final Long[] counter = new Long[1];
counter[0] = 0L;
Comparator<String> compString = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
counter[0]++;
return o1.compareTo(o2);
}
};
PriorityQueueExtended<String> testQueue = new PriorityQueueExtended<>(20, compString);
runTimes.put(testQueue.getClass().getName(), new ArrayList<>());
testQueue(testQueue, counter);
}
@Ignore
@Test
public void testGuavaMinMaxPriorityQueue() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
final Long[] counter = new Long[1];
counter[0] = 0L;
Comparator<String> compString = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
counter[0]++;
return o1.compareTo(o2);
}
};
MinMaxPriorityQueue<String> testQueue = MinMaxPriorityQueue.orderedBy(compString).expectedSize(20).create();
runTimes.put(testQueue.getClass().getName(), new ArrayList<>());
testQueue(testQueue, counter);
}
private void testQueue(final AbstractQueue<String> tempQueue, final Long[] counter) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
long start = System.nanoTime();
List<String> charStrings = new ArrayList<>();
for (int c = 32; c <= 122; c++) {
charStrings.add(String.valueOf((char)c));
}
modifyQueue("init", null, counter, tempQueue);
String buf = "351762489ABCDEFG";
for (int i = 0; i < buf.length(); i++) {
modifyQueue("add", buf.substring(i, i+1), counter, tempQueue);
}
for (int j = 0; j < 10000; j++) {
for (String s : charStrings) {
tempQueue.add(s);
modifyQueue("add", s, counter, tempQueue);
}
}
while (tempQueue.size() > 0) {
modifyQueue("poll", null, counter, tempQueue);
}
// Class queueKlass = tempQueue.getClass();
// AbstractQueue dupe = (AbstractQueue) queueKlass.newInstance();
// while (tempQueue.size() > 0) {
// dupe.add(tempQueue.poll());
// }
long runtime = System.nanoTime() - start;
System.out.println(tempQueue.getClass().getName() + " took " + runtime + " nanos");
runTimes.get(tempQueue.getClass().getName()).add(runtime);
}
private void modifyQueue(String action, String value, Long[] compares, AbstractQueue<String> tmpQueue) throws NoSuchFieldException, IllegalAccessException {
Long oldCompares = compares[0];
switch (action) {
case "init":
if (DEBUG) {
System.out.print(String.format(msgInit, compares[0] - oldCompares, compares[0]));
}
break;
case "add":
tmpQueue.add(value);
if (DEBUG) {
System.out.print(String.format(msgAdd, value, compares[0] - oldCompares, compares[0]));
}
break;
case "poll":
String poll = tmpQueue.poll();
if (DEBUG) {
System.out.print(String.format(msgPoll, poll, compares[0] - oldCompares, compares[0]));
}
break;
}
if (DEBUG) {
dumpQueue(tmpQueue);
}
}
private void dumpQueue(AbstractQueue<String> tmpQueue) throws NoSuchFieldException, IllegalAccessException {
if (DEBUG) {
System.out.print(" queue= ");
Class klass = tmpQueue.getClass();
Field fieldQueue = klass.getDeclaredField("queue");
fieldQueue.setAccessible(true);
Object[] objects = (Object[]) fieldQueue.get(tmpQueue);
for (Object object : objects) {
if (object != null) {
System.out.print((String) object + " ");
}
}
System.out.println("");
}
}
}
| |
package eu.bcvsolutions.idm.core.workflow.service.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.activiti.engine.FormService;
import org.activiti.engine.TaskService;
import org.activiti.engine.form.AbstractFormType;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.FormType;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.IdentityLinkType;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskInfo;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import eu.bcvsolutions.idm.core.api.domain.CoreResultCode;
import eu.bcvsolutions.idm.core.api.dto.BaseDto;
import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto;
import eu.bcvsolutions.idm.core.api.exception.CoreException;
import eu.bcvsolutions.idm.core.api.exception.ResultCodeException;
import eu.bcvsolutions.idm.core.api.service.ConfigurationService;
import eu.bcvsolutions.idm.core.api.service.LookupService;
import eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission;
import eu.bcvsolutions.idm.core.rest.AbstractBaseDtoService;
import eu.bcvsolutions.idm.core.security.api.domain.BasePermission;
import eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission;
import eu.bcvsolutions.idm.core.security.api.service.SecurityService;
import eu.bcvsolutions.idm.core.workflow.domain.formtype.AbstractComponentFormType;
import eu.bcvsolutions.idm.core.workflow.domain.formtype.DecisionFormType;
import eu.bcvsolutions.idm.core.workflow.domain.formtype.TaskHistoryFormType;
import eu.bcvsolutions.idm.core.workflow.model.dto.DecisionFormTypeDto;
import eu.bcvsolutions.idm.core.workflow.model.dto.FormDataDto;
import eu.bcvsolutions.idm.core.workflow.model.dto.IdentityLinkDto;
import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowFilterDto;
import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowHistoricTaskInstanceDto;
import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowProcessDefinitionDto;
import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowTaskInstanceDto;
import eu.bcvsolutions.idm.core.workflow.service.WorkflowHistoricTaskInstanceService;
import eu.bcvsolutions.idm.core.workflow.service.WorkflowProcessDefinitionService;
import eu.bcvsolutions.idm.core.workflow.service.WorkflowProcessInstanceService;
import eu.bcvsolutions.idm.core.workflow.service.WorkflowTaskDefinitionService;
import eu.bcvsolutions.idm.core.workflow.service.WorkflowTaskInstanceService;
/**
* Default workflow task instance service
*
* @author svandav
* @author Ondrej Husnik
*
*/
@Service
public class DefaultWorkflowTaskInstanceService extends
AbstractBaseDtoService<WorkflowTaskInstanceDto, WorkflowFilterDto> implements WorkflowTaskInstanceService {
@Autowired
private SecurityService securityService;
@Autowired
private TaskService taskService;
@Autowired
private FormService formService;
@Autowired
private LookupService lookupService;
@Autowired
private WorkflowTaskDefinitionService workflowTaskDefinitionService;
@Autowired
private WorkflowProcessDefinitionService workflowProcessDefinitionService;
@Autowired
private WorkflowHistoricTaskInstanceService historicTaskInstanceService;
@Autowired
private ConfigurationService configurationService;
@Override
public Page<WorkflowTaskInstanceDto> find(WorkflowFilterDto filter, Pageable pageable,
BasePermission... permission) {
return internalSearch(filter, pageable, permission);
}
@Override
public void completeTask(String taskId, String decision) {
completeTask(taskId, decision, null);
}
@Override
public void completeTask(String taskId, String decision, Map<String, String> formData) {
completeTask(taskId, decision, null, null);
}
@Override
public void completeTask(String taskId, String decision, Map<String, String> formData,
Map<String, Object> variables) {
BasePermission[] permission = {IdmBasePermission.UPDATE};
this.completeTask(taskId, decision, formData, variables, permission);
}
@Override
public void completeTask(String taskId, String decision, Map<String, String> formData,
Map<String, Object> variables, BasePermission[] permission) {
UUID implementerId = securityService.getCurrentId();
String loggedUser = implementerId.toString();
UUID originalImplementerId = securityService.getOriginalId();
// Check if user can complete this task
if (!canExecute(this.get(taskId, permission), permission)) {
throw new ResultCodeException(CoreResultCode.FORBIDDEN,
"You do not have permission for execute task with ID: %s !", ImmutableMap.of("taskId", taskId));
}
// add original user into task variables
if (originalImplementerId != null && !originalImplementerId.equals(implementerId)) {
if (variables == null) {
variables = new HashMap<>();
}
variables.put(WorkflowProcessInstanceService.ORIGINAL_IMPLEMENTER_IDENTIFIER, originalImplementerId);
}
taskService.setAssignee(taskId, loggedUser);
taskService.setVariables(taskId, variables);
taskService.setVariableLocal(taskId, WorkflowHistoricTaskInstanceService.TASK_COMPLETE_DECISION, decision);
if (variables != null) {
if (variables.containsKey(WorkflowHistoricTaskInstanceService.TASK_COMPLETE_MESSAGE)) {
taskService.setVariableLocal(taskId, WorkflowHistoricTaskInstanceService.TASK_COMPLETE_MESSAGE,
variables.get(WorkflowHistoricTaskInstanceService.TASK_COMPLETE_MESSAGE));
}
}
Map<String, String> properties = new HashMap<>();
properties.put(WorkflowTaskInstanceService.WORKFLOW_DECISION, decision);
if (formData != null) {
properties.putAll(formData);
}
formService.submitTaskFormData(taskId, properties);
}
/**
* Check if user can complete this task
*/
private boolean canExecute(WorkflowTaskInstanceDto task, BasePermission[] permission) {
return permission == null || permission.length == 0 || this.getPermissions(task).contains(IdmBasePermission.EXECUTE.getName());
}
@Override
public Set<String> getPermissions(Serializable id) {
Assert.notNull(id, "Identifier is required.");
if (id instanceof BaseDto) {
BaseDto baseDto = (BaseDto) id;
return this.getPermissions(this.get(baseDto.getId()));
}
return this.getPermissions(this.get(id));
}
@Override
public WorkflowTaskInstanceDto get(Serializable id, WorkflowFilterDto context, BasePermission... permission) {
if (context == null) {
context = new WorkflowFilterDto();
}
context.setId(UUID.fromString(String.valueOf(id)));
List<WorkflowTaskInstanceDto> tasks = internalSearch(context, null, permission).getContent();
if (!tasks.isEmpty()) {
return tasks.get(0);
}
// Current task doesn't exists, we try to find historic task.
WorkflowHistoricTaskInstanceDto historicTask = historicTaskInstanceService.get(String.valueOf(id), context);
if (historicTask != null) {
return historicTask;
}
return null;
}
@Override
public WorkflowTaskInstanceDto get(Serializable id, BasePermission... permission) {
Assert.notNull(id, "Identifier is required.");
return this.get(id, null, permission);
}
@Override
public Set<String> getPermissions(WorkflowTaskInstanceDto dto) {
Assert.notNull(dto, "DTO is required.");
//
final Set<String> permissions = new HashSet<>();
String loggedUserId = securityService.getCurrentId().toString();
// TODO: user with admin permission can execute any tasks.
// Set<GrantedAuthority> defaultAuthorities =
// autorizationPolicyService.getDefaultAuthorities(securityService.getCurrentId());
// defaultAuthorities.contains(CoreGroupPermission.WORKFLOW_TASK_ADMIN);
// If is logged user candidate or assigned, then can execute task.
boolean isCandidate = dto.getIdentityLinks().stream()
.anyMatch(
(identity) -> ((identity.getType().equals(IdentityLinkType.ASSIGNEE)
|| identity.getType().equals(IdentityLinkType.CANDIDATE))
&& identity.getUserId().equals(loggedUserId)));
if (isCandidate) {
permissions.add(IdmBasePermission.EXECUTE.getName());
}
return permissions;
}
@Override
public Page<UUID> findIds(WorkflowFilterDto filter, Pageable pageable, BasePermission... permission) {
Page<WorkflowTaskInstanceDto> page = this.find(filter, pageable, permission);
List<UUID> uuids = page.getContent()
.stream()
.map(task -> UUID.fromString(task.getId()))
.collect(Collectors.toList());
return new PageImpl<>(uuids, page.getPageable(), page.getTotalElements());
}
@Override
public Page<UUID> findIds(Pageable pageable, BasePermission... permission) {
return findIds(new WorkflowFilterDto(), pageable, permission);
}
private WorkflowTaskInstanceDto toResource(TaskInfo task, BasePermission[] permission) {
if (task == null) {
return null;
}
WorkflowTaskInstanceDto dto = new WorkflowTaskInstanceDto();
dto.setId(task.getId());
dto.setName(task.getName());
dto.setProcessDefinitionId(task.getProcessDefinitionId());
dto.setPriority(task.getPriority());
dto.setAssignee(task.getAssignee());
dto.setCreated(task.getCreateTime());
dto.setFormKey(task.getFormKey());
dto.setDescription(task.getDescription());
dto.setProcessInstanceId(task.getProcessInstanceId());
Map<String, Object> taskVariables = task.getTaskLocalVariables();
Map<String, Object> processVariables = task.getProcessVariables();
// Add applicant username to task dto (for easier work)
if (processVariables != null
&& processVariables.containsKey(WorkflowProcessInstanceService.APPLICANT_IDENTIFIER)) {
dto.setApplicant(processVariables.get(WorkflowProcessInstanceService.APPLICANT_IDENTIFIER).toString());
}
dto.setVariables(processVariables);
convertToDtoVariables(dto, taskVariables);
dto.setDefinition(workflowTaskDefinitionService.searchTaskDefinitionById(task.getProcessDefinitionId(),
task.getTaskDefinitionKey()));
if (!Strings.isNullOrEmpty(task.getProcessDefinitionId())) {
WorkflowProcessDefinitionDto processDefinition = workflowProcessDefinitionService
.get(task.getProcessDefinitionId());
if (processDefinition != null) {
dto.setProcessDefinitionKey(processDefinition.getKey());
}
}
TaskFormData taskFormData = formService.getTaskFormData(task.getId());
// Add form data (it means form properties and value from WF)
List<FormProperty> formProperties = taskFormData.getFormProperties();
// Search and add identity links to dto (It means all user
// (assigned/candidates/group) for this task)
List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(task.getId());
if (identityLinks != null) {
List<IdentityLinkDto> identityLinksDtos = new ArrayList<>(identityLinks.size());
identityLinks.forEach((il) -> {
identityLinksDtos.add(toResource(il));
});
dto.getIdentityLinks().addAll(identityLinksDtos);
}
// Check if the logged user can complete this task
boolean canExecute = this.canExecute(dto, permission);
if (formProperties != null && !formProperties.isEmpty()) {
formProperties.forEach((property) -> {
resovleFormProperty(property, dto, canExecute);
});
}
return dto;
}
/**
* Convert form property and add to result dto
*
* @param property
* @param dto
* @param canExecute
*/
@SuppressWarnings("unchecked")
private void resovleFormProperty(FormProperty property, WorkflowTaskInstanceDto dto, boolean canExecute) {
FormType formType = property.getType();
if (formType instanceof DecisionFormType) {
// Decision buttons will be add only if logged user can execute/complete this
// task
if (!canExecute) {
return;
}
DecisionFormTypeDto decisionDto = (DecisionFormTypeDto) ((DecisionFormType) formType)
.convertFormValueToModelValue(property.getValue());
if (decisionDto != null) {
decisionDto.setId(property.getId());
setDecisionReasonRequired(decisionDto);
dto.getDecisions().add(decisionDto);
}
} else if (formType instanceof TaskHistoryFormType) {
WorkflowFilterDto filterDto = new WorkflowFilterDto();
filterDto.setProcessInstanceId(dto.getProcessInstanceId());
List<WorkflowHistoricTaskInstanceDto> tasks = historicTaskInstanceService.find(filterDto, PageRequest.of(0, 50)).getContent();
List<WorkflowHistoricTaskInstanceDto> history = tasks.stream()
.filter(workflowHistoricTaskInstanceDto -> workflowHistoricTaskInstanceDto.getEndTime() != null)
.sorted((o1, o2) -> {
if (o1.getEndTime().before(o2.getEndTime())) {
return -1;
} else if (o1.getEndTime().after(o2.getEndTime())) {
return 1;
}
return 0;
})
.collect(Collectors.toList());
dto.getFormData().add(historyToResource(property, history));
} else if (formType instanceof AbstractFormType) {
// To rest will be add only component form type marked as "exportable to rest".
if (formType instanceof AbstractComponentFormType
&& !((AbstractComponentFormType) formType).isExportableToRest()) {
return;
}
Object values = formType.getInformation("values");
if (values instanceof Map<?, ?>) {
dto.getFormData().add(toResource(property, (Map<String, String>) values));
} else {
dto.getFormData().add(toResource(property, null));
}
}
}
@Override
public void convertToDtoVariables(WorkflowTaskInstanceDto dto, Map<String, Object> taskVariables) {
if (taskVariables != null) {
taskVariables.entrySet().forEach((entry) -> {
Object value = entry.getValue();
dto.getVariables().put(entry.getKey(), value == null ? null : value.toString());
});
}
}
@Override
public Object getProcessVariable(String taskId, String key) {
return taskService.getVariableInstance(taskId, key);
}
@Override
public boolean canReadAllTask(BasePermission... permission) {
// TODO: Implement check on permission (READ, UPDATE ...). Permissions are uses only for skip rights check now!
return permission == null || securityService.isAdmin() || securityService.hasAnyAuthority(CoreGroupPermission.WORKFLOW_TASK_ADMIN);
}
private FormDataDto historyToResource(FormProperty property, List<WorkflowHistoricTaskInstanceDto> history) {
FormDataDto dto = new FormDataDto();
dto.setId(property.getId());
dto.setName(property.getName());
String value;
try {
value = new ObjectMapper().writeValueAsString(history);
} catch (JsonProcessingException e) {
throw new CoreException(e);
}
dto.setValue(value);
dto.setType(property.getType().getName());
dto.setReadable(property.isReadable());
dto.setRequired(property.isRequired());
dto.setWritable(property.isWritable());
return dto;
}
private FormDataDto toResource(FormProperty property, Map<String, String> additionalInformations) {
FormDataDto dto = new FormDataDto();
dto.setId(property.getId());
dto.setName(property.getName());
dto.setValue(property.getValue());
dto.setType(property.getType().getName());
dto.setReadable(property.isReadable());
dto.setRequired(property.isRequired());
dto.setWritable(property.isWritable());
// Add all additional informations (come from form properties - form
// values)
if (additionalInformations != null) {
// extra add tooltip to dto
if (additionalInformations.containsKey(WorkflowTaskInstanceService.FORM_PROPERTY_TOOLTIP_KEY)) {
dto.setTooltip(additionalInformations.get(WorkflowTaskInstanceService.FORM_PROPERTY_TOOLTIP_KEY));
}
// extra add placeholder to dto
if (additionalInformations.containsKey(WorkflowTaskInstanceService.FORM_PROPERTY_PLACEHOLDER_KEY)) {
dto.setPlaceholder(
additionalInformations.get(WorkflowTaskInstanceService.FORM_PROPERTY_PLACEHOLDER_KEY));
}
dto.getAdditionalInformations().putAll(additionalInformations);
}
return dto;
}
private IdentityLinkDto toResource(IdentityLink link) {
if (link == null) {
return null;
}
IdentityLinkDto dto = new IdentityLinkDto();
dto.setGroupId(link.getGroupId());
dto.setType(link.getType());
dto.setUserId(link.getUserId());
return dto;
}
private PageImpl<WorkflowTaskInstanceDto> internalSearch(WorkflowFilterDto filter, Pageable pageable, BasePermission... permission) {
if (pageable == null) {
pageable = PageRequest.of(0, Integer.MAX_VALUE);
}
// if currently logged user can read all task continue
if (!canReadAllTask(permission)) {
// if user can't read all task check filter
if (filter.getCandidateOrAssigned() == null) {
if (Boolean.TRUE == filter.getOnlyInvolved()) {
filter.setCandidateOrAssigned(securityService.getCurrentId().toString());
}
} else {
IdmIdentityDto identity = lookupService.lookupDto(IdmIdentityDto.class, filter.getCandidateOrAssigned());
if (!identity.getId().equals(securityService.getCurrentId())) {
throw new ResultCodeException(CoreResultCode.FORBIDDEN,
"You do not have permission for access to all tasks!");
}
}
// else is filled candidate and it is equals currently logged user
}
String processDefinitionId = filter.getProcessDefinitionId();
Map<String, Object> equalsVariables = filter.getEqualsVariables();
TaskQuery query = taskService.createTaskQuery();
query.active();
query.includeProcessVariables();
if (processDefinitionId != null) {
query.processDefinitionId(processDefinitionId);
}
if (filter.getProcessDefinitionKey() != null) {
query.processDefinitionKey(filter.getProcessDefinitionKey());
}
if (filter.getProcessInstanceId() != null) {
query.processInstanceId(filter.getProcessInstanceId());
}
if (filter.getId() != null) {
query.taskId(filter.getId().toString());
}
if (filter.getCreatedAfter() != null) {
query.taskCreatedAfter(Date.from(filter.getCreatedAfter().toInstant()));
}
if (filter.getCreatedBefore() != null) {
query.taskCreatedBefore(Date.from(filter.getCreatedBefore().toInstant()));
}
if (equalsVariables != null) {
equalsVariables.entrySet().forEach((entry) -> {
query.processVariableValueEquals(entry.getKey(), entry.getValue());
});
}
if (filter.getCandidateOrAssigned() != null) {
BaseDto dto = lookupService.lookupDto(IdmIdentityDto.class, filter.getCandidateOrAssigned());
Assert.notNull(dto, "DTO is required.");
query.taskCandidateOrAssigned(String.valueOf(dto.getId()));
}
if (pageable.getSort() != null) {
pageable.getSort().forEach(order -> {
if (SORT_BY_TASK_CREATED.equals(order.getProperty())) {
// Sort by key
query.orderByTaskCreateTime();
if (order.isAscending()) {
query.asc();
} else {
query.desc();
}
}
});
}
query.orderByTaskCreateTime();
query.desc();
long count = query.count();
List<Task> tasks = query.listPage((pageable.getPageNumber()) * pageable.getPageSize(), pageable.getPageSize());
List<WorkflowTaskInstanceDto> dtos = new ArrayList<>();
if (tasks != null) {
tasks.forEach((task) -> {
dtos.add(toResource(task, permission));
});
}
return new PageImpl<>(dtos, pageable, count);
}
private void setDecisionReasonRequired(DecisionFormTypeDto decisionDto) {
Boolean reasonRequired = decisionDto.isReasonRequired();
if (reasonRequired == null) {
String key = null;
if (WORKFLOW_DECISION_APPROVE.equalsIgnoreCase(decisionDto.getId())) {
key = WorkflowTaskInstanceService.PROPERTY_APPROVE_DECISION_REASON_REQUIRED;
} else if (WORKFLOW_DECISION_DISAPPROVE.equalsIgnoreCase(decisionDto.getId())) {
key = WorkflowTaskInstanceService.PROPERTY_DISAPPROVE_DECISION_REASON_REQUIRED;
}
reasonRequired = key == null ? false : configurationService.getBooleanValue(key, false);
decisionDto.setReasonRequired(reasonRequired);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/common/asset_types.proto
package com.google.ads.googleads.v10.common;
/**
* <pre>
* A Book on Google asset. Used to redirect user to book through Google.
* Book on Google will change the redirect url to book directly through
* Google.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.common.BookOnGoogleAsset}
*/
public final class BookOnGoogleAsset extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v10.common.BookOnGoogleAsset)
BookOnGoogleAssetOrBuilder {
private static final long serialVersionUID = 0L;
// Use BookOnGoogleAsset.newBuilder() to construct.
private BookOnGoogleAsset(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BookOnGoogleAsset() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new BookOnGoogleAsset();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private BookOnGoogleAsset(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
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;
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 {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.common.AssetTypesProto.internal_static_google_ads_googleads_v10_common_BookOnGoogleAsset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.common.AssetTypesProto.internal_static_google_ads_googleads_v10_common_BookOnGoogleAsset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.common.BookOnGoogleAsset.class, com.google.ads.googleads.v10.common.BookOnGoogleAsset.Builder.class);
}
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 {
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
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.v10.common.BookOnGoogleAsset)) {
return super.equals(obj);
}
com.google.ads.googleads.v10.common.BookOnGoogleAsset other = (com.google.ads.googleads.v10.common.BookOnGoogleAsset) obj;
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 = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v10.common.BookOnGoogleAsset parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.common.BookOnGoogleAsset 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.v10.common.BookOnGoogleAsset parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.common.BookOnGoogleAsset 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.v10.common.BookOnGoogleAsset parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.common.BookOnGoogleAsset parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.common.BookOnGoogleAsset parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.common.BookOnGoogleAsset 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.v10.common.BookOnGoogleAsset parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.common.BookOnGoogleAsset 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.v10.common.BookOnGoogleAsset parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.common.BookOnGoogleAsset 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.v10.common.BookOnGoogleAsset 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>
* A Book on Google asset. Used to redirect user to book through Google.
* Book on Google will change the redirect url to book directly through
* Google.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.common.BookOnGoogleAsset}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.common.BookOnGoogleAsset)
com.google.ads.googleads.v10.common.BookOnGoogleAssetOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.common.AssetTypesProto.internal_static_google_ads_googleads_v10_common_BookOnGoogleAsset_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.common.AssetTypesProto.internal_static_google_ads_googleads_v10_common_BookOnGoogleAsset_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.common.BookOnGoogleAsset.class, com.google.ads.googleads.v10.common.BookOnGoogleAsset.Builder.class);
}
// Construct using com.google.ads.googleads.v10.common.BookOnGoogleAsset.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v10.common.AssetTypesProto.internal_static_google_ads_googleads_v10_common_BookOnGoogleAsset_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v10.common.BookOnGoogleAsset getDefaultInstanceForType() {
return com.google.ads.googleads.v10.common.BookOnGoogleAsset.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v10.common.BookOnGoogleAsset build() {
com.google.ads.googleads.v10.common.BookOnGoogleAsset result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v10.common.BookOnGoogleAsset buildPartial() {
com.google.ads.googleads.v10.common.BookOnGoogleAsset result = new com.google.ads.googleads.v10.common.BookOnGoogleAsset(this);
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.v10.common.BookOnGoogleAsset) {
return mergeFrom((com.google.ads.googleads.v10.common.BookOnGoogleAsset)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v10.common.BookOnGoogleAsset other) {
if (other == com.google.ads.googleads.v10.common.BookOnGoogleAsset.getDefaultInstance()) return this;
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.v10.common.BookOnGoogleAsset parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v10.common.BookOnGoogleAsset) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
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.v10.common.BookOnGoogleAsset)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v10.common.BookOnGoogleAsset)
private static final com.google.ads.googleads.v10.common.BookOnGoogleAsset DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v10.common.BookOnGoogleAsset();
}
public static com.google.ads.googleads.v10.common.BookOnGoogleAsset getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BookOnGoogleAsset>
PARSER = new com.google.protobuf.AbstractParser<BookOnGoogleAsset>() {
@java.lang.Override
public BookOnGoogleAsset parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new BookOnGoogleAsset(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<BookOnGoogleAsset> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BookOnGoogleAsset> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v10.common.BookOnGoogleAsset getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
// 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.impala.planner;
import java.util.ArrayList;
import java.util.List;
import org.apache.impala.analysis.SlotDescriptor;
import org.apache.impala.analysis.TupleDescriptor;
import org.apache.impala.catalog.FeTable;
import org.apache.impala.catalog.HdfsFileFormat;
import org.apache.impala.catalog.Type;
import org.apache.impala.common.NotImplementedException;
import org.apache.impala.common.RuntimeEnv;
import org.apache.impala.thrift.TNetworkAddress;
import org.apache.impala.thrift.TQueryOptions;
import org.apache.impala.thrift.TScanRangeSpec;
import org.apache.impala.thrift.TTableStats;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
/**
* Representation of the common elements of all scan nodes.
*/
abstract public class ScanNode extends PlanNode {
// Factor capturing the worst-case deviation from a uniform distribution of scan ranges
// among nodes. The factor of 1.2 means that a particular node may have 20% more
// scan ranges than would have been estimated assuming a uniform distribution.
// Used for HDFS and Kudu Scan node estimations.
protected static final double SCAN_RANGE_SKEW_FACTOR = 1.2;
protected final TupleDescriptor desc_;
// Total number of rows this node is expected to process
protected long inputCardinality_ = -1;
// Scan-range specs. Populated in init().
protected TScanRangeSpec scanRangeSpecs_;
public ScanNode(PlanNodeId id, TupleDescriptor desc, String displayName) {
super(id, desc.getId().asList(), displayName);
desc_ = desc;
}
public TupleDescriptor getTupleDesc() { return desc_; }
/**
* Checks if this scan is supported based on the types of scanned columns and the
* underlying file formats, in particular, whether complex types are supported.
*
* The default implementation throws if this scan would need to materialize a nested
* field or collection. The scan is ok if the table schema contains complex types, as
* long as the query does not reference them.
*
* Subclasses should override this function as appropriate.
*/
protected void checkForSupportedFileFormats() throws NotImplementedException {
Preconditions.checkNotNull(desc_);
Preconditions.checkNotNull(desc_.getTable());
for (SlotDescriptor slotDesc: desc_.getSlots()) {
if (slotDesc.getType().isComplexType() || slotDesc.getColumn() == null) {
Preconditions.checkNotNull(slotDesc.getPath());
throw new NotImplementedException(String.format(
"Scan of table '%s' is not supported because '%s' references a nested " +
"field/collection.\nComplex types are supported for these file formats: %s.",
slotDesc.getPath().toString(), desc_.getAlias(),
Joiner.on(", ").join(HdfsFileFormat.complexTypesFormats())));
}
}
}
/**
* Returns all scan range specs.
*/
public TScanRangeSpec getScanRangeSpecs() {
Preconditions.checkNotNull(scanRangeSpecs_, "Need to call init() first.");
return scanRangeSpecs_;
}
@Override
protected String debugString() {
return Objects.toStringHelper(this)
.add("tid", desc_.getId().asInt())
.add("tblName", desc_.getTable().getFullName())
.add("keyRanges", "")
.addValue(super.debugString())
.toString();
}
/**
* Returns the explain string for table stats to be included into this ScanNode's
* explain string. The prefix is prepended to each returned line for proper formatting
* when the string returned by this method is embedded in a query's explain plan.
*/
protected String getTableStatsExplainString(String prefix) {
StringBuilder output = new StringBuilder();
TTableStats tblStats = desc_.getTable().getTTableStats();
String numRows = String.valueOf(tblStats.num_rows);
if (tblStats.num_rows == -1) numRows = "unavailable";
output.append(prefix + "table: rows=" + numRows);
return output.toString();
}
/**
* Returns the explain string for column stats to be included into this ScanNode's
* explain string. The prefix is prepended to each returned line for proper formatting
* when the string returned by this method is embedded in a query's explain plan.
*/
protected String getColumnStatsExplainString(String prefix) {
StringBuilder output = new StringBuilder();
List<String> columnsMissingStats = new ArrayList<>();
for (SlotDescriptor slot: desc_.getSlots()) {
if (!slot.getStats().hasStats() && slot.getColumn() != null) {
columnsMissingStats.add(slot.getColumn().getName());
}
}
if (columnsMissingStats.isEmpty()) {
output.append(prefix + "columns: all");
} else if (columnsMissingStats.size() == desc_.getSlots().size()) {
output.append(prefix + "columns: unavailable");
} else {
output.append(String.format("%scolumns missing stats: %s", prefix,
Joiner.on(", ").join(columnsMissingStats)));
}
return output.toString();
}
/**
* Combines the explain string for table and column stats.
*/
protected String getStatsExplainString(String prefix) {
StringBuilder output = new StringBuilder(prefix);
output.append("stored statistics:\n");
prefix = prefix + " ";
output.append(getTableStatsExplainString(prefix));
output.append("\n");
output.append(getColumnStatsExplainString(prefix));
return output.toString();
}
/**
* Returns true if the table underlying this scan is missing table stats
* or column stats relevant to this scan node.
*/
public boolean isTableMissingStats() {
return isTableMissingColumnStats() || isTableMissingTableStats();
}
public boolean isTableMissingTableStats() {
return desc_.getTable().getNumRows() == -1;
}
/**
* Returns true if the tuple descriptor references a path with a collection type.
*/
public boolean isAccessingCollectionType() {
for (Type t: desc_.getPath().getMatchedTypes()) {
if (t.isCollectionType()) return true;
}
return false;
}
public boolean isTableMissingColumnStats() {
for (SlotDescriptor slot: desc_.getSlots()) {
if (slot.getColumn() != null && !slot.getStats().hasStats()) return true;
}
return false;
}
/**
* Returns true, if the scanned table is suspected to have corrupt table stats,
* in particular, if the scan is non-empty and 'numRows' is 0 or negative (but not -1).
*/
public boolean hasCorruptTableStats() { return false; }
/**
* Helper function to parse a "host:port" address string into TNetworkAddress
* This is called with ipaddress:port when doing scan range assignment.
*/
protected static TNetworkAddress addressToTNetworkAddress(String address) {
TNetworkAddress result = new TNetworkAddress();
String[] hostPort = address.split(":");
result.hostname = hostPort[0];
result.port = Integer.parseInt(hostPort[1]);
return result;
}
@Override
public long getInputCardinality() {
if (!hasScanConjuncts() && !hasStorageLayerConjuncts() && hasLimit()) {
return getLimit();
}
return inputCardinality_;
}
@Override
protected String getDisplayLabelDetail() {
FeTable table = desc_.getTable();
List<String> path = new ArrayList<>();
path.add(table.getDb().getName());
path.add(table.getName());
Preconditions.checkNotNull(desc_.getPath());
if (desc_.hasExplicitAlias()) {
return desc_.getPath().toString() + " " + desc_.getAlias();
} else {
return desc_.getPath().toString();
}
}
/**
* Helper function that returns the estimated number of scan ranges that would
* be assigned to each host based on the total number of scan ranges.
*/
protected int estimatePerHostScanRanges(long totalNumOfScanRanges) {
return (int) Math.ceil(((double) totalNumOfScanRanges / (double) numNodes_) *
SCAN_RANGE_SKEW_FACTOR);
}
/**
* Helper function that returns the max number of scanner threads that can be
* spawned by a scan node.
*/
protected int computeMaxNumberOfScannerThreads(TQueryOptions queryOptions,
int perHostScanRanges) {
// The non-MT scan node requires at least one scanner thread.
if (queryOptions.getMt_dop() >= 1) {
return 1;
}
int maxScannerThreads = Math.min(perHostScanRanges,
RuntimeEnv.INSTANCE.getNumCores());
// Account for the max scanner threads query option.
if (queryOptions.isSetNum_scanner_threads() &&
queryOptions.getNum_scanner_threads() > 0) {
maxScannerThreads = Math.min(maxScannerThreads,
queryOptions.getNum_scanner_threads());
}
return maxScannerThreads;
}
/**
* Returns true if this node has conjuncts to be evaluated by Impala against the scan
* tuple.
*/
public boolean hasScanConjuncts() { return !getConjuncts().isEmpty(); }
/**
* Returns true if this node has conjuncts to be evaluated by the underlying storage
* engine.
*/
public boolean hasStorageLayerConjuncts() { return false; }
}
| |
/*
* Copyright (c) 2007, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.registry.app;
import org.apache.abdera.protocol.Request;
import org.apache.abdera.protocol.Resolver;
import org.apache.abdera.protocol.server.RequestContext;
import org.apache.abdera.protocol.server.ResponseContext;
import org.apache.abdera.protocol.server.Target;
import org.apache.abdera.protocol.server.TargetType;
import org.apache.abdera.protocol.server.context.EmptyResponseContext;
import org.apache.abdera.protocol.server.impl.SimpleTarget;
import org.apache.abdera.protocol.server.servlet.ServletRequestContext;
import org.apache.axiom.om.util.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.registry.app.targets.ResourceTarget;
import org.wso2.carbon.registry.app.targets.ResponseTarget;
import org.wso2.carbon.registry.core.ActionConstants;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.ResourceImpl;
import org.wso2.carbon.registry.core.config.RegistryContext;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.exceptions.ResourceNotFoundException;
import org.wso2.carbon.registry.core.jdbc.EmbeddedRegistryService;
import org.wso2.carbon.registry.core.secure.AuthorizationFailedException;
import org.wso2.carbon.registry.core.session.CurrentSession;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.registry.core.utils.AuthorizationUtils;
import org.wso2.carbon.registry.core.utils.RegistryUtils;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Class that is capable of resolving requests made via the Atom API, and identify how to process
* them. Some of the target types are provided by Abdera itself, whereas some others are defined.
*/
public class RegistryResolver implements Resolver<Target> {
private static Log log = LogFactory.getLog(RegistryResolver.class);
/**
* The target type for tags.
*/
public static final TargetType TAGS_TYPE = TargetType.get("tags", true);
/**
* The target type for logs.
*/
public static final TargetType LOGS_TYPE = TargetType.get("logs", true);
/**
* The target type for ratings.
*/
public static final TargetType RATINGS_TYPE = TargetType.get("ratings", true);
/**
* The target type for rename operations.
*/
public static final TargetType RENAME_TYPE = TargetType.get("rename", true);
/**
* The target type for copy operations.
*/
public static final TargetType COPY_TYPE = TargetType.get("copy", true);
/**
* The target type for move operations.
*/
public static final TargetType MOVE_TYPE = TargetType.get("move", true);
/**
* The target type for comments.
*/
public static final TargetType COMMENTS_TYPE = TargetType.get("comments", true);
/**
* The target type for tag urls.
*/
public static final TargetType TAG_URL_TYPE = TargetType.get("tagURL", true);
/**
* The target type for associations.
*/
public static final TargetType ASSOCIATIONS_TYPE = TargetType.get("associations", true);
/**
* The target type for restore operations.
*/
public static final TargetType RESTORE_TYPE = TargetType.get("restore", true);
/**
* The target type for aspects.
*/
public static final TargetType ASPECT_TYPE = TargetType.get("aspect", true);
/**
* The target type for versions.
*/
public static final TargetType VERSIONS_TYPE = TargetType.get("versions", true);
/**
* The target type for check points.
*/
public static final TargetType CHECKPOINT_TYPE = TargetType.get("checkpoint", true);
/**
* The target type for queries..
*/
public static final TargetType QUERY_TYPE = TargetType.get("query", true);
/**
* The target type for import requests.
*/
public static final TargetType IMPORT_TYPE = TargetType.get("import", true);
/**
* The target type for delete requests.
*/
public static final TargetType DELETE_TYPE = TargetType.get("delete", true);
/**
* The target type for custom collections.
*/
public static final TargetType COLLECTION_CUSTOM_TYPE = TargetType.get("col-custom", true);
/**
* The target type for dump.
*/
public static final TargetType DUMP_TYPE = TargetType.get("dump", true);
private EmbeddedRegistryService embeddedRegistryService;
private String basePath;
public RegistryResolver(EmbeddedRegistryService embeddedRegistryService, String basePath) {
this.embeddedRegistryService = embeddedRegistryService;
this.basePath = basePath;
}
private static Map<String, TargetType> types;
static {
types = new HashMap<String, TargetType>();
types.put("tags", TAGS_TYPE);
types.put("logs", LOGS_TYPE);
types.put("ratings", RATINGS_TYPE);
types.put("comments", COMMENTS_TYPE);
types.put("rename", RENAME_TYPE);
types.put("copy", COPY_TYPE);
types.put("move", MOVE_TYPE);
types.put("tagURL", TAG_URL_TYPE);
types.put("associations", ASSOCIATIONS_TYPE);
types.put("restore", RESTORE_TYPE);
types.put("versions", VERSIONS_TYPE);
types.put("checkpoint", CHECKPOINT_TYPE);
types.put("query", QUERY_TYPE);
types.put("application/resource-import", IMPORT_TYPE);
types.put("dump", DUMP_TYPE);
}
/**
* Method to identify the response target for the request.
*
* @param request the request.
*
* @return the response target.
*/
public Target resolve(Request request) {
RequestContext context = (RequestContext) request;
final ServletRequestContext requestContext;
if (context instanceof ServletRequestContext) {
requestContext = (ServletRequestContext) request;
} else {
requestContext = null;
}
if (embeddedRegistryService == null) {
if (requestContext != null) {
embeddedRegistryService =
(EmbeddedRegistryService) requestContext.getRequest().getSession()
.getServletContext().getAttribute("registry");
}
if (embeddedRegistryService == null) {
String msg = "Error in retrieving the embedded registry service.";
log.error(msg);
}
}
//TODO (reg-sep)
UserRegistry registry = null;
String uri = context.getUri().toString();
String loggedIn = null;
if (requestContext != null) {
loggedIn = ((ServletRequestContext) request).getRequest().getParameter("loggedIn");
}
if (loggedIn != null) {
String loggedUser =
(String) requestContext.getRequest().getSession().getServletContext()
.getAttribute("logged-user");
try {
registry = embeddedRegistryService.getRegistry(loggedUser);
uri = uri.substring(0, uri.lastIndexOf('?'));
} catch (RegistryException e) {
final StringResponseContext response =
new StringResponseContext("Unauthorized",
HttpURLConnection.HTTP_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
return new ResponseTarget(context, response);
}
}
if (registry == null) {
// Set up secure registry instance
String authorizationString = request.getAuthorization();
if (authorizationString != null) {
// splitting the Authorization string "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
String values[] = authorizationString.split("\\ ");
if (values == null || values.length == 0) {
final StringResponseContext response =
new StringResponseContext("Unauthorized",
HttpURLConnection.HTTP_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
return new ResponseTarget(context, response);
} else if ("Basic".equals(values[0])) {
try {
// Decode username/password
authorizationString = new String(Base64.decode(values[1]));
values = authorizationString.split("\\:");
String userName = values[0];
String password = values[1];
String tenantDomain =
(String) ((ServletRequestContext) request).getRequest().
getAttribute(MultitenantConstants.TENANT_DOMAIN);
int tenantId;
String userNameAlong;
if (tenantDomain == null ||
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
tenantId = getTenantId(userName);
userNameAlong = getUserName(userName);
} else {
tenantId = getTenantIdFromDomain(tenantDomain);
userNameAlong = userName;
}
registry = embeddedRegistryService.getRegistry(userNameAlong,
password, tenantId);
} catch (Exception e) {
final StringResponseContext response =
new StringResponseContext("Unauthorized",
HttpURLConnection.HTTP_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
return new ResponseTarget(context, response);
}
} else {
// TODO - return an ExceptionTarget which contains the authentication problem
// return new ExceptionTarget(400, "Only basic authentication is supported!");
return null;
}
} else {
String tenantDomain = (String) requestContext.getRequest().
getAttribute(MultitenantConstants.TENANT_DOMAIN);
int calledTenantId = MultitenantConstants.SUPER_TENANT_ID;
if (tenantDomain != null &&
!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
if (RegistryContext.getBaseInstance().getRealmService() == null) {
String msg = "Error in getting the tenant manager. " +
"The realm service is not available.";
log.error(msg);
return new ResponseTarget(context, new EmptyResponseContext(400, msg));
}
TenantManager tenantManager =
RegistryContext.getBaseInstance().getRealmService().
getTenantManager();
try {
calledTenantId = tenantManager.getTenantId(tenantDomain);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg =
"Error in converting tenant domain to the id for tenant domain: " +
tenantDomain + ".";
log.error(msg, e);
return new ResponseTarget(context, new EmptyResponseContext(400, msg));
}
try {
if (!tenantManager.isTenantActive(calledTenantId)) {
// the tenant is not active.
String msg =
"The tenant is not active. tenant domain: " + tenantDomain +
".";
log.error(msg);
return new ResponseTarget(context, new EmptyResponseContext(400, msg));
}
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg =
"Error in converting tenant domain to the id for tenant domain: " +
tenantDomain + ".";
log.error(msg, e);
return new ResponseTarget(context, new EmptyResponseContext(400, msg));
}
RegistryContext.getBaseInstance().
getRealmService().getBootstrapRealmConfiguration();
}
String anonUser = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
try {
registry = embeddedRegistryService.getRegistry(anonUser, calledTenantId);
} catch (RegistryException e) {
String msg = "Error in creating the registry.";
log.error(msg, e);
return new ResponseTarget(context, new EmptyResponseContext(400, msg));
}
}
}
// Squirrel this away so the adapter can get it later (after all that work we just did!)
context.setAttribute("userRegistry", registry);
final String method = context.getMethod();
/*
Following code moved further down
try {
uri = URLDecoder.decode(uri, "utf-8");
} catch (UnsupportedEncodingException e) {
log.error(e);
return null;
} */
if (uri.startsWith(RegistryConstants.PATH_SEPARATOR
+ RegistryConstants.REGISTRY_INSTANCE
+ RegistryConstants.PATH_SEPARATOR
+ RegistryConstants.REGISTRY_INSTANCE)) {
//if ROOT war is renamed to 'registry', uri will look like following,
//'/registry/registry/foo/bar'
//Hence,we need to remove the first 'registry'
uri = uri.replaceFirst(RegistryConstants.PATH_SEPARATOR
+ RegistryConstants.REGISTRY_INSTANCE, "");
}
// URI will start with the baseURI, which we need to strip off.
String[] excludeStartArr = {basePath + APPConstants.ATOM,
basePath + APPConstants.RESOURCE, basePath + "/tags"};
if (basePath == null) {
log.error("Base path is null. Aborting the operation.");
final StringResponseContext response =
new StringResponseContext("Internal Server Error",
HttpURLConnection.HTTP_INTERNAL_ERROR);
return new ResponseTarget(context, response);
} else if (!basePath.equals("")) {
for (String excludeStartStr : excludeStartArr) {
// URI will start with the baseURI, which we need to strip off.
if (uri.indexOf(excludeStartStr) > -1 &&
uri.length() > uri.indexOf(excludeStartStr) + basePath.length()) {
uri = uri.substring(uri.indexOf(excludeStartStr) + basePath.length());
break;
}
}
}
if (!uri.startsWith(
RegistryConstants.PATH_SEPARATOR + RegistryConstants.REGISTRY_INSTANCE)) {
uri = uri.substring(uri.indexOf(RegistryConstants.PATH_SEPARATOR));
}
context.setAttribute("pathInfo", uri);
String[] parts = splitPath(uri); // splits with "\;"
boolean hasColon = false;
TargetType type = null;
// Let's just see if this is an import first - in which case we can just send it
// on through.
if (parts.length > 1) {
String discriminator = parts[1];
// If this is a version request, don't do anything special. Otherwise process.
if (discriminator.startsWith("version:")) {
if (parts.length > 2) {
// Make sure this is a restore.
if (parts[2].equals("restore")) {
type = RESTORE_TYPE;
uri = parts[0] + RegistryConstants.URL_SEPARATOR + parts[1];
} else if (parts[2].equals(APPConstants.ASSOCIATIONS)) {
type = ASSOCIATIONS_TYPE;
uri = parts[0] + RegistryConstants.URL_SEPARATOR + parts[1];
} else {
// There's an extra semicolon here somewhere.
return null;
}
}
} else {
// Store the split URL for later
context.setAttribute(APPConstants.PARAMETER_SPLIT_PATH, parts);
int idx = discriminator.indexOf('?');
if (idx > -1) {
discriminator = discriminator.substring(0, idx);
}
String suffix = null;
idx = discriminator.indexOf(':');
if (idx > -1) {
suffix = discriminator.substring(idx + 1, discriminator.length());
discriminator = discriminator.substring(0, idx);
hasColon = true;
}
if (discriminator.startsWith("aspect")) {
type = ASPECT_TYPE;
} else {
type = types.get(discriminator);
}
if (discriminator.equals("tag") && method.equals("DELETE") && hasColon) {
context.setAttribute("tagName", suffix);
type = DELETE_TYPE;
} else if (discriminator.equals("comment") && method.equals("DELETE") && hasColon) {
context.setAttribute("commentId", suffix);
type = DELETE_TYPE;
} else if (discriminator.equals("ratings") && hasColon) {
context.setAttribute("ratingUser", suffix);
type = RATINGS_TYPE;
}
// If we have a discriminator that we don't understand, return a 404
if (type == null) {
return null;
}
// For the rest of this code, we'll want the "raw" resource URI
if (!hasColon || !(type.equals(COMMENTS_TYPE) || type.equals(RATINGS_TYPE) ||
type.equals(TAGS_TYPE))) {
uri = parts[0];
}
if (hasColon && type.equals(TAGS_TYPE)) {
type = null;
}
}
}
int idx = uri.indexOf('?');
if (idx > -1) {
String queryString = uri.substring(idx + 1, uri.length());
context.setAttribute("queryString", queryString);
uri = uri.substring(0, idx);
}
try {
uri = URLDecoder.decode(uri, RegistryConstants.DEFAULT_CHARSET_ENCODING);
} catch (UnsupportedEncodingException e) {
log.error(e);
return null;
}
boolean isMedia = false;
if (uri.startsWith(APPConstants.RESOURCE)) {
uri = uri.substring(APPConstants.RESOURCE.length());
isMedia = true;
} else if (uri.startsWith(APPConstants.ATOM)) {
uri = uri.substring(APPConstants.ATOM.length());
} else if (uri.startsWith("/tags") && (uri.length() == 5 || uri.charAt(5) == '/')) {
return new SimpleTarget(TAG_URL_TYPE, context);
} else {
return null;
}
if (uri.length() == 0) {
uri = "/";
}
// See if we're asking for a paginated collection
String startParam = context.getParameter("start");
String pageLenParam = context.getParameter("pageLen");
int start = (startParam == null) ? -1 : Integer.parseInt(startParam);
int pageLen = (pageLenParam == null) ? -1 : Integer.parseInt(pageLenParam);
Resource resource = null;
if (type != null && type.equals(DUMP_TYPE) &&
method != null && method.equals("POST")) {
// for restoring a dump we don't need to have available resource
// here we will create a fake resource to store the path
resource = new ResourceImpl();
((ResourceImpl) resource).setPath(uri);
} else {
// in a restore, path don't need to exist.
CurrentSession.setUserRealm(registry.getUserRealm());
CurrentSession.setUser(registry.getUserName());
try {
if (!AuthorizationUtils.authorize(RegistryUtils.getAbsolutePath(
registry.getRegistryContext(), uri),
ActionConstants.GET)) {
final StringResponseContext response =
new StringResponseContext("Unauthorized",
HttpURLConnection.HTTP_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
return new ResponseTarget(context, response);
} else if (start > -1 || pageLen > -1) {
resource = registry.get(uri, start, pageLen);
} else {
resource = registry.get(uri);
}
} catch (AuthorizationFailedException e) {
final StringResponseContext response =
new StringResponseContext("Unauthorized",
HttpURLConnection.HTTP_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
return new ResponseTarget(context, response);
} catch (ResourceNotFoundException e) {
// If this is a straight-ahead POST to a non-existent directory, create it?
if (method.equals("POST") && parts.length == 1) {
// Need to create it.
try {
Collection c = registry.newCollection();
registry.put(uri, c);
resource = registry.get(uri);
} catch (RegistryException e1) {
log.error(e1);
return null;
}
}
if (resource == null) {
return null;
}
} catch (RegistryException e) {
return null; // return 404
} finally{
CurrentSession.removeUser();
CurrentSession.removeUserRealm();
}
if (method.equals("GET")) {
// eTag based conditional get
String ifNonMatchValue = context.getHeader("if-none-match");
if (ifNonMatchValue != null) {
String currentETag = Utils.calculateEntityTag(resource);
if (ifNonMatchValue.equals(currentETag)) {
/* the version is not modified */
ResponseContext response = new StringResponseContext("Not Modified",
HttpURLConnection.HTTP_NOT_MODIFIED);
return new ResponseTarget(context, response);
}
}
// date based conditional get
long ifModifiedSinceValue = 0;
Date ifModifiedSince = context.getDateHeader("If-Modified-Since");
if (ifModifiedSince != null) {
ifModifiedSinceValue = ifModifiedSince.getTime();
}
if (ifModifiedSinceValue > 0) {
long lastModifiedValue = resource.getLastModified().getTime();
// convert the time values from milliseconds to seconds
ifModifiedSinceValue /= 1000;
lastModifiedValue /= 1000;
/* condition to check we have latest updates in terms of dates */
if (ifModifiedSinceValue >= lastModifiedValue) {
/* no need to response with data */
ResponseContext response = new StringResponseContext("Not Modified",
HttpURLConnection.HTTP_NOT_MODIFIED);
return new ResponseTarget(context, response);
}
}
}
}
context.setAttribute("MyResolver", this);
if (type == null) {
if (method.equals("DELETE")) {
// Unfortunately, deletions aren't quite handled the way we want them
// in AbstractEntityCollectionProvider, so for now we're using an
// extensionRequest to get it done.
type = DELETE_TYPE;
} else {
if (resource instanceof Collection) {
if (method.equals("HEAD") || method.equals("PUT")) {
// Abdera doesn't handle HEAD or PUT on collections yet. this should
// go away once that's fixed!
type = COLLECTION_CUSTOM_TYPE;
} else {
type = TargetType.TYPE_COLLECTION;
}
} else {
type = isMedia ? TargetType.TYPE_MEDIA : TargetType.TYPE_ENTRY;
}
}
}
return new ResourceTarget(type, context, resource);
}
/**
* This method will split the path into parts around the path separator, returning an array of
* the parts.
*
* @param path URL path
*
* @return String array of the split string
*/
private String[] splitPath(String path) {
return path.split("\\" + RegistryConstants.URL_SEPARATOR);
}
@SuppressWarnings("unused")
public String getBasePath() {
return basePath;
}
public static String getUserName(String userNameWithDomain) throws RegistryException {
int atIndex = userNameWithDomain.indexOf('@');
if (atIndex == -1) {
// no domain in the inserted test
return userNameWithDomain;
}
return userNameWithDomain.substring(atIndex + 1);
}
public static int getTenantId(String userNameWithDomain) throws RegistryException {
int atIndex = userNameWithDomain.indexOf('@');
if (atIndex == -1) {
// no domain
return MultitenantConstants.SUPER_TENANT_ID;
}
String domain = userNameWithDomain.substring(atIndex + 1, userNameWithDomain.length());
return getTenantIdFromDomain(domain);
}
private static int getTenantIdFromDomain(String domain) throws RegistryException {
RegistryContext registryContext = RegistryContext.getBaseInstance();
RealmService realmService = registryContext.getRealmService();
if (realmService == null) {
String msg = "Error in getting the tenant manager. The realm service is not available.";
log.error(msg);
throw new RegistryException(msg);
}
TenantManager tenantManager = realmService.getTenantManager();
try {
return tenantManager.getTenantId(domain);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg = "Error in getting the tenant manager.";
log.error(msg, e);
throw new RegistryException(msg, e);
}
}
}
| |
/*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
import java.util.Iterator;
/**
* See JVMS3, section 4.5.
*
* <p><b>This is NOT part of any API supported by Sun Microsystems. If
* you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class ConstantPool {
public class InvalidIndex extends ConstantPoolException {
InvalidIndex(int index) {
super(index);
}
@Override
public String getMessage() {
// i18n
return "invalid index #" + index;
}
}
public class UnexpectedEntry extends ConstantPoolException {
UnexpectedEntry(int index, int expected_tag, int found_tag) {
super(index);
this.expected_tag = expected_tag;
this.found_tag = found_tag;
}
@Override
public String getMessage() {
// i18n?
return "unexpected entry at #" + index + " -- expected tag " + expected_tag + ", found " + found_tag;
}
public final int expected_tag;
public final int found_tag;
}
public class InvalidEntry extends ConstantPoolException {
InvalidEntry(int index, int tag) {
super(index);
this.tag = tag;
}
@Override
public String getMessage() {
// i18n?
return "unexpected tag at #" + index + ": " + tag;
}
public final int tag;
}
public class EntryNotFound extends ConstantPoolException {
EntryNotFound(Object value) {
super(-1);
this.value = value;
}
@Override
public String getMessage() {
// i18n?
return "value not found: " + value;
}
public final Object value;
}
public static final int CONSTANT_Utf8 = 1;
public static final int CONSTANT_Integer = 3;
public static final int CONSTANT_Float = 4;
public static final int CONSTANT_Long = 5;
public static final int CONSTANT_Double = 6;
public static final int CONSTANT_Class = 7;
public static final int CONSTANT_String = 8;
public static final int CONSTANT_Fieldref = 9;
public static final int CONSTANT_Methodref = 10;
public static final int CONSTANT_InterfaceMethodref = 11;
public static final int CONSTANT_NameAndType = 12;
ConstantPool(ClassReader cr) throws IOException, InvalidEntry {
int count = cr.readUnsignedShort();
pool = new CPInfo[count];
for (int i = 1; i < count; i++) {
int tag = cr.readUnsignedByte();
switch (tag) {
case CONSTANT_Class:
pool[i] = new CONSTANT_Class_info(this, cr);
break;
case CONSTANT_Double:
pool[i] = new CONSTANT_Double_info(cr);
i++;
break;
case CONSTANT_Fieldref:
pool[i] = new CONSTANT_Fieldref_info(this, cr);
break;
case CONSTANT_Float:
pool[i] = new CONSTANT_Float_info(cr);
break;
case CONSTANT_Integer:
pool[i] = new CONSTANT_Integer_info(cr);
break;
case CONSTANT_InterfaceMethodref:
pool[i] = new CONSTANT_InterfaceMethodref_info(this, cr);
break;
case CONSTANT_Long:
pool[i] = new CONSTANT_Long_info(cr);
i++;
break;
case CONSTANT_Methodref:
pool[i] = new CONSTANT_Methodref_info(this, cr);
break;
case CONSTANT_NameAndType:
pool[i] = new CONSTANT_NameAndType_info(this, cr);
break;
case CONSTANT_String:
pool[i] = new CONSTANT_String_info(this, cr);
break;
case CONSTANT_Utf8:
pool[i] = new CONSTANT_Utf8_info(cr);
break;
default:
throw new InvalidEntry(i, tag);
}
}
}
public ConstantPool(CPInfo[] pool) {
this.pool = pool;
}
public int size() {
return pool.length;
}
public CPInfo get(int index) throws InvalidIndex {
if (index <= 0 || index >= pool.length)
throw new InvalidIndex(index);
CPInfo info = pool[index];
if (info == null) {
// this occurs for indices referencing the "second half" of an
// 8 byte constant, such as CONSTANT_Double or CONSTANT_Long
throw new InvalidIndex(index);
}
return pool[index];
}
private CPInfo get(int index, int expected_type) throws InvalidIndex, UnexpectedEntry {
CPInfo info = get(index);
if (info.getTag() != expected_type)
throw new UnexpectedEntry(index, expected_type, info.getTag());
return info;
}
public CONSTANT_Utf8_info getUTF8Info(int index) throws InvalidIndex, UnexpectedEntry {
return ((CONSTANT_Utf8_info) get(index, CONSTANT_Utf8));
}
public CONSTANT_Class_info getClassInfo(int index) throws InvalidIndex, UnexpectedEntry {
return ((CONSTANT_Class_info) get(index, CONSTANT_Class));
}
public CONSTANT_NameAndType_info getNameAndTypeInfo(int index) throws InvalidIndex, UnexpectedEntry {
return ((CONSTANT_NameAndType_info) get(index, CONSTANT_NameAndType));
}
public String getUTF8Value(int index) throws InvalidIndex, UnexpectedEntry {
return getUTF8Info(index).value;
}
public int getUTF8Index(String value) throws EntryNotFound {
for (int i = 1; i < pool.length; i++) {
CPInfo info = pool[i];
if (info instanceof CONSTANT_Utf8_info &&
((CONSTANT_Utf8_info) info).value.equals(value))
return i;
}
throw new EntryNotFound(value);
}
public Iterable<CPInfo> entries() {
return new Iterable<CPInfo>() {
public Iterator<CPInfo> iterator() {
return new Iterator<CPInfo>() {
public boolean hasNext() {
return next < pool.length;
}
public CPInfo next() {
current = pool[next];
switch (current.getTag()) {
case CONSTANT_Double:
case CONSTANT_Long:
next += 2;
break;
default:
next += 1;
}
return current;
}
public void remove() {
throw new UnsupportedOperationException();
}
private CPInfo current;
private int next = 1;
};
}
};
}
private CPInfo[] pool;
public interface Visitor<R,P> {
R visitClass(CONSTANT_Class_info info, P p);
R visitDouble(CONSTANT_Double_info info, P p);
R visitFieldref(CONSTANT_Fieldref_info info, P p);
R visitFloat(CONSTANT_Float_info info, P p);
R visitInteger(CONSTANT_Integer_info info, P p);
R visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info info, P p);
R visitLong(CONSTANT_Long_info info, P p);
R visitNameAndType(CONSTANT_NameAndType_info info, P p);
R visitMethodref(CONSTANT_Methodref_info info, P p);
R visitString(CONSTANT_String_info info, P p);
R visitUtf8(CONSTANT_Utf8_info info, P p);
}
public static abstract class CPInfo {
CPInfo() {
this.cp = null;
}
CPInfo(ConstantPool cp) {
this.cp = cp;
}
public abstract int getTag();
/** The number of slots in the constant pool used by this entry.
* 2 for CONSTANT_Double and CONSTANT_Long; 1 for everything else. */
public int size() {
return 1;
}
public abstract <R,D> R accept(Visitor<R,D> visitor, D data);
protected final ConstantPool cp;
}
public static abstract class CPRefInfo extends CPInfo {
protected CPRefInfo(ConstantPool cp, ClassReader cr, int tag) throws IOException {
super(cp);
this.tag = tag;
class_index = cr.readUnsignedShort();
name_and_type_index = cr.readUnsignedShort();
}
protected CPRefInfo(ConstantPool cp, int tag, int class_index, int name_and_type_index) {
super(cp);
this.tag = tag;
this.class_index = class_index;
this.name_and_type_index = name_and_type_index;
}
public int getTag() {
return tag;
}
public CONSTANT_Class_info getClassInfo() throws ConstantPoolException {
return cp.getClassInfo(class_index);
}
public String getClassName() throws ConstantPoolException {
return cp.getClassInfo(class_index).getName();
}
public CONSTANT_NameAndType_info getNameAndTypeInfo() throws ConstantPoolException {
return cp.getNameAndTypeInfo(name_and_type_index);
}
public final int tag;
public final int class_index;
public final int name_and_type_index;
}
public static class CONSTANT_Class_info extends CPInfo {
CONSTANT_Class_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp);
name_index = cr.readUnsignedShort();
}
public CONSTANT_Class_info(ConstantPool cp, int name_index) {
super(cp);
this.name_index = name_index;
}
public int getTag() {
return CONSTANT_Class;
}
public String getName() throws ConstantPoolException {
return cp.getUTF8Value(name_index);
}
public String getBaseName() throws ConstantPoolException {
String name = getName();
int index = name.indexOf("[L") + 1;
return name.substring(index);
}
public int getDimensionCount() throws ConstantPoolException {
String name = getName();
int count = 0;
while (name.charAt(count) == '[')
count++;
return count;
}
@Override
public String toString() {
return "CONSTANT_Class_info[name_index: " + name_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitClass(this, data);
}
public final int name_index;
}
public static class CONSTANT_Double_info extends CPInfo {
CONSTANT_Double_info(ClassReader cr) throws IOException {
value = cr.readDouble();
}
public CONSTANT_Double_info(double value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Double;
}
@Override
public int size() {
return 2;
}
@Override
public String toString() {
return "CONSTANT_Double_info[value: " + value + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitDouble(this, data);
}
public final double value;
}
public static class CONSTANT_Fieldref_info extends CPRefInfo {
CONSTANT_Fieldref_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp, cr, CONSTANT_Fieldref);
}
public CONSTANT_Fieldref_info(ConstantPool cp, int class_index, int name_and_type_index) {
super(cp, CONSTANT_Fieldref, class_index, name_and_type_index);
}
@Override
public String toString() {
return "CONSTANT_Fieldref_info[class_index: " + class_index + ", name_and_type_index: " + name_and_type_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitFieldref(this, data);
}
}
public static class CONSTANT_Float_info extends CPInfo {
CONSTANT_Float_info(ClassReader cr) throws IOException {
value = cr.readFloat();
}
public CONSTANT_Float_info(float value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Float;
}
@Override
public String toString() {
return "CONSTANT_Float_info[value: " + value + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitFloat(this, data);
}
public final float value;
}
public static class CONSTANT_Integer_info extends CPInfo {
CONSTANT_Integer_info(ClassReader cr) throws IOException {
value = cr.readInt();
}
public CONSTANT_Integer_info(int value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Integer;
}
@Override
public String toString() {
return "CONSTANT_Integer_info[value: " + value + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitInteger(this, data);
}
public final int value;
}
public static class CONSTANT_InterfaceMethodref_info extends CPRefInfo {
CONSTANT_InterfaceMethodref_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp, cr, CONSTANT_InterfaceMethodref);
}
public CONSTANT_InterfaceMethodref_info(ConstantPool cp, int class_index, int name_and_type_index) {
super(cp, CONSTANT_InterfaceMethodref, class_index, name_and_type_index);
}
@Override
public String toString() {
return "CONSTANT_InterfaceMethodref_info[class_index: " + class_index + ", name_and_type_index: " + name_and_type_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitInterfaceMethodref(this, data);
}
}
public static class CONSTANT_Long_info extends CPInfo {
CONSTANT_Long_info(ClassReader cr) throws IOException {
value = cr.readLong();
}
public CONSTANT_Long_info(long value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Long;
}
@Override
public int size() {
return 2;
}
@Override
public String toString() {
return "CONSTANT_Long_info[value: " + value + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitLong(this, data);
}
public final long value;
}
public static class CONSTANT_Methodref_info extends CPRefInfo {
CONSTANT_Methodref_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp, cr, CONSTANT_Methodref);
}
public CONSTANT_Methodref_info(ConstantPool cp, int class_index, int name_and_type_index) {
super(cp, CONSTANT_Methodref, class_index, name_and_type_index);
}
@Override
public String toString() {
return "CONSTANT_Methodref_info[class_index: " + class_index + ", name_and_type_index: " + name_and_type_index + "]";
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitMethodref(this, data);
}
}
public static class CONSTANT_NameAndType_info extends CPInfo {
CONSTANT_NameAndType_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp);
name_index = cr.readUnsignedShort();
type_index = cr.readUnsignedShort();
}
public CONSTANT_NameAndType_info(ConstantPool cp, int name_index, int type_index) {
super(cp);
this.name_index = name_index;
this.type_index = type_index;
}
public int getTag() {
return CONSTANT_NameAndType;
}
public String getName() throws ConstantPoolException {
return cp.getUTF8Value(name_index);
}
public String getType() throws ConstantPoolException {
return cp.getUTF8Value(type_index);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitNameAndType(this, data);
}
@Override
public String toString() {
return "CONSTANT_NameAndType_info[name_index: " + name_index + ", type_index: " + type_index + "]";
}
public final int name_index;
public final int type_index;
}
public static class CONSTANT_String_info extends CPInfo {
CONSTANT_String_info(ConstantPool cp, ClassReader cr) throws IOException {
super(cp);
string_index = cr.readUnsignedShort();
}
public CONSTANT_String_info(ConstantPool cp, int string_index) {
super(cp);
this.string_index = string_index;
}
public int getTag() {
return CONSTANT_String;
}
public String getString() throws ConstantPoolException {
return cp.getUTF8Value(string_index);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitString(this, data);
}
@Override
public String toString() {
return "CONSTANT_String_info[class_index: " + string_index + "]";
}
public final int string_index;
}
public static class CONSTANT_Utf8_info extends CPInfo {
CONSTANT_Utf8_info(ClassReader cr) throws IOException {
value = cr.readUTF();
}
public CONSTANT_Utf8_info(String value) {
this.value = value;
}
public int getTag() {
return CONSTANT_Utf8;
}
@Override
public String toString() {
if (value.length() < 32 && isPrintableAscii(value))
return "CONSTANT_Utf8_info[value: \"" + value + "\"]";
else
return "CONSTANT_Utf8_info[value: (" + value.length() + " chars)]";
}
static boolean isPrintableAscii(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c < 32 || c >= 127)
return false;
}
return true;
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitUtf8(this, data);
}
public final String value;
}
}
| |
/*
* 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.tests.integration.jms.consumer;
import javax.jms.Connection;
import javax.jms.JMSConsumer;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient;
import org.apache.activemq.artemis.api.jms.ActiveMQJMSConstants;
import org.apache.activemq.artemis.api.jms.JMSFactoryType;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger;
import org.apache.activemq.artemis.tests.util.JMSTestBase;
import org.apache.activemq.artemis.utils.ReusableLatch;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class JmsConsumerTest extends JMSTestBase {
private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER;
private static final String Q_NAME = "ConsumerTestQueue";
private static final String T_NAME = "ConsumerTestTopic";
private static final String T2_NAME = "ConsumerTestTopic2";
private javax.jms.Queue jBossQueue;
private javax.jms.Topic topic;
private javax.jms.Topic topic2;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
topic = ActiveMQJMSClient.createTopic(T_NAME);
topic2 = ActiveMQJMSClient.createTopic(T2_NAME);
jmsServer.createQueue(false, JmsConsumerTest.Q_NAME, null, true, JmsConsumerTest.Q_NAME);
jmsServer.createTopic(true, T_NAME, "/topic/" + T_NAME);
jmsServer.createTopic(true, T2_NAME, "/topic/" + T2_NAME);
cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY));
}
@Test
public void testTransactionalSessionRollback() throws Exception {
conn = cf.createConnection();
Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
MessageProducer prod = sess.createProducer(topic);
MessageConsumer cons = sess.createConsumer(topic);
conn.start();
TextMessage msg1 = sess.createTextMessage("m1");
TextMessage msg2 = sess.createTextMessage("m2");
TextMessage msg3 = sess.createTextMessage("m3");
prod.send(msg1);
sess.commit();
prod.send(msg2);
sess.rollback();
prod.send(msg3);
sess.commit();
TextMessage m1 = (TextMessage) cons.receive(2000);
Assert.assertNotNull(m1);
Assert.assertEquals("m1", m1.getText());
TextMessage m2 = (TextMessage) cons.receive(2000);
Assert.assertNotNull(m2);
Assert.assertEquals("m3", m2.getText());
TextMessage m3 = (TextMessage) cons.receive(2000);
Assert.assertNull("m3 should be null", m3);
System.out.println("received m1: " + m1.getText());
System.out.println("received m2: " + m2.getText());
System.out.println("received m3: " + m3);
sess.commit();
}
@Test
public void testPreCommitAcks() throws Exception {
conn = cf.createConnection();
Session session = conn.createSession(false, ActiveMQJMSConstants.PRE_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageProducer producer = session.createProducer(jBossQueue);
MessageConsumer consumer = session.createConsumer(jBossQueue);
int noOfMessages = 100;
for (int i = 0; i < noOfMessages; i++) {
producer.send(session.createTextMessage("m" + i));
}
conn.start();
for (int i = 0; i < noOfMessages; i++) {
Message m = consumer.receive(500);
Assert.assertNotNull(m);
}
SimpleString queueName = new SimpleString(JmsConsumerTest.Q_NAME);
Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
}
@Test
public void testIndividualACK() throws Exception {
Connection conn = cf.createConnection();
Session session = conn.createSession(false, ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageProducer producer = session.createProducer(jBossQueue);
MessageConsumer consumer = session.createConsumer(jBossQueue);
int noOfMessages = 100;
for (int i = 0; i < noOfMessages; i++) {
producer.send(session.createTextMessage("m" + i));
}
conn.start();
// Consume even numbers first
for (int i = 0; i < noOfMessages; i++) {
Message m = consumer.receive(500);
Assert.assertNotNull(m);
if (i % 2 == 0) {
m.acknowledge();
}
}
session.close();
session = conn.createSession(false, ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE);
consumer = session.createConsumer(jBossQueue);
// Consume odd numbers first
for (int i = 0; i < noOfMessages; i++) {
if (i % 2 == 0) {
continue;
}
TextMessage m = (TextMessage) consumer.receive(1000);
Assert.assertNotNull(m);
m.acknowledge();
Assert.assertEquals("m" + i, m.getText());
}
SimpleString queueName = new SimpleString(JmsConsumerTest.Q_NAME);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getDeliveringCount());
Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
conn.close();
}
@Test
public void testIndividualACKMessageConsumer() throws Exception {
Connection conn = cf.createConnection();
Session session = conn.createSession(false, ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageProducer producer = session.createProducer(jBossQueue);
MessageConsumer consumer = session.createConsumer(jBossQueue);
int noOfMessages = 100;
for (int i = 0; i < noOfMessages; i++) {
producer.setPriority(2);
producer.send(session.createTextMessage("m" + i));
}
conn.start();
final AtomicInteger errors = new AtomicInteger(0);
final ReusableLatch latch = new ReusableLatch();
latch.setCount(noOfMessages);
class MessageAckEven implements MessageListener {
int count = 0;
@Override
public void onMessage(Message msg) {
try {
TextMessage txtmsg = (TextMessage) msg;
if (!txtmsg.getText().equals("m" + count)) {
errors.incrementAndGet();
}
if (count % 2 == 0) {
msg.acknowledge();
}
count++;
} catch (Exception e) {
errors.incrementAndGet();
} finally {
latch.countDown();
}
}
}
consumer.setMessageListener(new MessageAckEven());
Assert.assertTrue(latch.await(5000));
session.close();
session = conn.createSession(false, ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE);
consumer = session.createConsumer(jBossQueue);
// Consume odd numbers first
for (int i = 0; i < noOfMessages; i++) {
if (i % 2 == 0) {
continue;
}
TextMessage m = (TextMessage) consumer.receive(1000);
Assert.assertNotNull(m);
m.acknowledge();
Assert.assertEquals("m" + i, m.getText());
}
SimpleString queueName = new SimpleString(JmsConsumerTest.Q_NAME);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getDeliveringCount());
Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
conn.close();
}
@Test
public void testPreCommitAcksSetOnConnectionFactory() throws Exception {
((ActiveMQConnectionFactory) cf).setPreAcknowledge(true);
conn = cf.createConnection();
Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageProducer producer = session.createProducer(jBossQueue);
MessageConsumer consumer = session.createConsumer(jBossQueue);
int noOfMessages = 100;
for (int i = 0; i < noOfMessages; i++) {
producer.send(session.createTextMessage("m" + i));
}
conn.start();
for (int i = 0; i < noOfMessages; i++) {
Message m = consumer.receive(500);
Assert.assertNotNull(m);
}
// Messages should all have been acked since we set pre ack on the cf
SimpleString queueName = new SimpleString(JmsConsumerTest.Q_NAME);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(queueName).getBindable()).getDeliveringCount());
Assert.assertEquals(0, getMessageCount((Queue) server.getPostOffice().getBinding(queueName).getBindable()));
}
@Test
public void testPreCommitAcksWithMessageExpiry() throws Exception {
JmsConsumerTest.log.info("starting test");
conn = cf.createConnection();
Session session = conn.createSession(false, ActiveMQJMSConstants.PRE_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageProducer producer = session.createProducer(jBossQueue);
MessageConsumer consumer = session.createConsumer(jBossQueue);
int noOfMessages = 1000;
for (int i = 0; i < noOfMessages; i++) {
TextMessage textMessage = session.createTextMessage("m" + i);
producer.setTimeToLive(1);
producer.send(textMessage);
}
Thread.sleep(2);
conn.start();
Message m = consumer.receiveNoWait();
Assert.assertNull(m);
// Asserting delivering count is zero is bogus since messages might still be being delivered and expired at this
// point
// which can cause delivering count to flip to 1
}
@Test
public void testPreCommitAcksWithMessageExpirySetOnConnectionFactory() throws Exception {
((ActiveMQConnectionFactory) cf).setPreAcknowledge(true);
conn = cf.createConnection();
Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageProducer producer = session.createProducer(jBossQueue);
MessageConsumer consumer = session.createConsumer(jBossQueue);
int noOfMessages = 1000;
for (int i = 0; i < noOfMessages; i++) {
TextMessage textMessage = session.createTextMessage("m" + i);
producer.setTimeToLive(1);
producer.send(textMessage);
}
Thread.sleep(2);
conn.start();
Message m = consumer.receiveNoWait();
Assert.assertNull(m);
// Asserting delivering count is zero is bogus since messages might still be being delivered and expired at this
// point
// which can cause delivering count to flip to 1
}
@Test
public void testBrowserAndConsumerSimultaneous() throws Exception {
((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0);
conn = cf.createConnection();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageProducer producer = session.createProducer(jBossQueue);
QueueBrowser browser = session.createBrowser(jBossQueue);
Enumeration enumMessages = browser.getEnumeration();
MessageConsumer consumer = session.createConsumer(jBossQueue);
int noOfMessages = 10;
for (int i = 0; i < noOfMessages; i++) {
TextMessage textMessage = session.createTextMessage("m" + i);
textMessage.setIntProperty("i", i);
producer.send(textMessage);
}
conn.start();
for (int i = 0; i < noOfMessages; i++) {
TextMessage msg = (TextMessage) enumMessages.nextElement();
Assert.assertNotNull(msg);
Assert.assertEquals(i, msg.getIntProperty("i"));
conn.start();
TextMessage recvMessage = (TextMessage) consumer.receiveNoWait();
Assert.assertNotNull(recvMessage);
conn.stop();
Assert.assertEquals(i, msg.getIntProperty("i"));
}
Assert.assertNull(consumer.receiveNoWait());
Assert.assertFalse(enumMessages.hasMoreElements());
conn.close();
// Asserting delivering count is zero is bogus since messages might still be being delivered and expired at this
// point
// which can cause delivering count to flip to 1
}
@Test
public void testBrowserAndConsumerSimultaneousDifferentConnections() throws Exception {
((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0);
conn = cf.createConnection();
Connection connConsumer = cf.createConnection();
Session sessionConsumer = connConsumer.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageProducer producer = session.createProducer(jBossQueue);
MessageConsumer consumer = sessionConsumer.createConsumer(jBossQueue);
int noOfMessages = 1000;
for (int i = 0; i < noOfMessages; i++) {
TextMessage textMessage = session.createTextMessage("m" + i);
textMessage.setIntProperty("i", i);
producer.send(textMessage);
}
connConsumer.start();
QueueBrowser browser = session.createBrowser(jBossQueue);
Enumeration enumMessages = browser.getEnumeration();
for (int i = 0; i < noOfMessages; i++) {
TextMessage msg = (TextMessage) enumMessages.nextElement();
Assert.assertNotNull(msg);
Assert.assertEquals(i, msg.getIntProperty("i"));
TextMessage recvMessage = (TextMessage) consumer.receiveNoWait();
Assert.assertNotNull(recvMessage);
Assert.assertEquals(i, msg.getIntProperty("i"));
}
Message m = consumer.receiveNoWait();
Assert.assertFalse(enumMessages.hasMoreElements());
Assert.assertNull(m);
conn.close();
}
@Test
public void testBrowserOnly() throws Exception {
((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0);
conn = cf.createConnection();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageProducer producer = session.createProducer(jBossQueue);
int noOfMessages = 10;
for (int i = 0; i < noOfMessages; i++) {
TextMessage textMessage = session.createTextMessage("m" + i);
textMessage.setIntProperty("i", i);
producer.send(textMessage);
}
QueueBrowser browser = session.createBrowser(jBossQueue);
Enumeration enumMessages = browser.getEnumeration();
for (int i = 0; i < noOfMessages; i++) {
Assert.assertTrue(enumMessages.hasMoreElements());
TextMessage msg = (TextMessage) enumMessages.nextElement();
Assert.assertNotNull(msg);
Assert.assertEquals(i, msg.getIntProperty("i"));
}
Assert.assertFalse(enumMessages.hasMoreElements());
conn.close();
// Asserting delivering count is zero is bogus since messages might still be being delivered and expired at this
// point
// which can cause delivering count to flip to 1
}
@Test
public void testClearExceptionListener() throws Exception {
conn = cf.createConnection();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageConsumer consumer = session.createConsumer(jBossQueue);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(final Message msg) {
}
});
consumer.setMessageListener(null);
consumer.receiveNoWait();
}
@Test
public void testCantReceiveWhenListenerIsSet() throws Exception {
conn = cf.createConnection();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
MessageConsumer consumer = session.createConsumer(jBossQueue);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(final Message msg) {
}
});
try {
consumer.receiveNoWait();
Assert.fail("Should throw exception");
} catch (JMSException e) {
// Ok
}
}
@Test
public void testSharedConsumer() throws Exception {
conn = cf.createConnection();
conn.start();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
topic = ActiveMQJMSClient.createTopic(T_NAME);
MessageConsumer cons = session.createSharedConsumer(topic, "test1");
MessageProducer producer = session.createProducer(topic);
producer.send(session.createTextMessage("test"));
TextMessage txt = (TextMessage) cons.receive(5000);
Assert.assertNotNull(txt);
}
@Test
public void testSharedDurableConsumer() throws Exception {
conn = cf.createConnection();
conn.start();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
topic = ActiveMQJMSClient.createTopic(T_NAME);
MessageConsumer cons = session.createSharedDurableConsumer(topic, "test1");
MessageProducer producer = session.createProducer(topic);
producer.send(session.createTextMessage("test"));
TextMessage txt = (TextMessage) cons.receive(5000);
Assert.assertNotNull(txt);
}
@Test
public void testSharedDurableConsumerWithClientID() throws Exception {
conn = cf.createConnection();
conn.setClientID("C1");
conn.start();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Connection conn2 = cf.createConnection();
conn2.setClientID("C2");
Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
{
Connection conn3 = cf.createConnection();
boolean exception = false;
try {
conn3.setClientID("C2");
} catch (Exception e) {
exception = true;
}
Assert.assertTrue(exception);
conn3.close();
}
topic = ActiveMQJMSClient.createTopic(T_NAME);
MessageConsumer cons = session.createSharedDurableConsumer(topic, "test1");
MessageProducer producer = session.createProducer(topic);
producer.send(session.createTextMessage("test"));
TextMessage txt = (TextMessage) cons.receive(5000);
Assert.assertNotNull(txt);
}
@Test
public void testValidateExceptionsThroughSharedConsumers() throws Exception {
conn = cf.createConnection();
conn.setClientID("C1");
conn.start();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Connection conn2 = cf.createConnection();
conn2.setClientID("C2");
MessageConsumer cons = session.createSharedConsumer(topic, "cons1");
boolean exceptionHappened = false;
try {
MessageConsumer cons2Error = session.createSharedConsumer(topic2, "cons1");
} catch (JMSException e) {
exceptionHappened = true;
}
Assert.assertTrue(exceptionHappened);
MessageProducer producer = session.createProducer(topic2);
// This is durable, different than the one on topic... So it should go through
MessageConsumer cons2 = session.createSharedDurableConsumer(topic2, "cons1");
conn.start();
producer.send(session.createTextMessage("hello!"));
TextMessage msg = (TextMessage) cons2.receive(5000);
Assert.assertNotNull(msg);
exceptionHappened = false;
try {
session.unsubscribe("cons1");
} catch (JMSException e) {
exceptionHappened = true;
}
Assert.assertTrue(exceptionHappened);
cons2.close();
conn.close();
conn2.close();
}
@Test
public void testUnsubscribeDurable() throws Exception {
conn = cf.createConnection();
conn.setClientID("C1");
conn.start();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer cons = session.createSharedDurableConsumer(topic, "c1");
MessageProducer prod = session.createProducer(topic);
for (int i = 0; i < 100; i++) {
prod.send(session.createTextMessage("msg" + i));
}
Assert.assertNotNull(cons.receive(5000));
cons.close();
session.unsubscribe("c1");
cons = session.createSharedDurableConsumer(topic, "c1");
// it should be null since the queue was deleted through unsubscribe
Assert.assertNull(cons.receiveNoWait());
}
@Test
public void testShareDurable() throws Exception {
((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0);
conn = cf.createConnection();
conn.start();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Session session2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer cons = session.createSharedDurableConsumer(topic, "c1");
MessageConsumer cons2 = session2.createSharedDurableConsumer(topic, "c1");
MessageProducer prod = session.createProducer(topic);
for (int i = 0; i < 100; i++) {
prod.send(session.createTextMessage("msg" + i));
}
for (int i = 0; i < 50; i++) {
Message msg = cons.receive(5000);
Assert.assertNotNull(msg);
msg = cons2.receive(5000);
Assert.assertNotNull(msg);
}
Assert.assertNull(cons.receiveNoWait());
Assert.assertNull(cons2.receiveNoWait());
cons.close();
boolean exceptionHappened = false;
try {
session.unsubscribe("c1");
} catch (JMSException e) {
exceptionHappened = true;
}
Assert.assertTrue(exceptionHappened);
cons2.close();
for (int i = 0; i < 100; i++) {
prod.send(session.createTextMessage("msg" + i));
}
session.unsubscribe("c1");
cons = session.createSharedDurableConsumer(topic, "c1");
// it should be null since the queue was deleted through unsubscribe
Assert.assertNull(cons.receiveNoWait());
}
@Test
public void testShareDuraleWithJMSContext() throws Exception {
((ActiveMQConnectionFactory) cf).setConsumerWindowSize(0);
JMSContext conn = cf.createContext(JMSContext.AUTO_ACKNOWLEDGE);
JMSConsumer consumer = conn.createSharedDurableConsumer(topic, "c1");
JMSProducer producer = conn.createProducer();
for (int i = 0; i < 100; i++) {
producer.setProperty("count", i).send(topic, "test" + i);
}
JMSContext conn2 = conn.createContext(JMSContext.AUTO_ACKNOWLEDGE);
JMSConsumer consumer2 = conn2.createSharedDurableConsumer(topic, "c1");
for (int i = 0; i < 50; i++) {
String txt = consumer.receiveBody(String.class, 5000);
System.out.println("TXT:" + txt);
Assert.assertNotNull(txt);
txt = consumer.receiveBody(String.class, 5000);
System.out.println("TXT:" + txt);
Assert.assertNotNull(txt);
}
Assert.assertNull(consumer.receiveNoWait());
Assert.assertNull(consumer2.receiveNoWait());
boolean exceptionHappened = false;
try {
conn.unsubscribe("c1");
} catch (Exception e) {
e.printStackTrace();
exceptionHappened = true;
}
Assert.assertTrue(exceptionHappened);
consumer.close();
consumer2.close();
conn2.close();
conn.unsubscribe("c1");
}
@Test
public void defaultAutoCreatedQueueConfigTest() throws Exception {
final String queueName = "q1";
server.getAddressSettingsRepository()
.addMatch(queueName, new AddressSettings()
.setDefaultMaxConsumers(5)
.setDefaultPurgeOnNoConsumers(true));
Connection connection = cf.createConnection();
Session session = connection.createSession();
session.createConsumer(session.createQueue(queueName));
org.apache.activemq.artemis.core.server.Queue queue = server.locateQueue(SimpleString.toSimpleString(queueName));
assertEquals(5, queue.getMaxConsumers());
assertEquals(true, queue.isPurgeOnNoConsumers());
connection.close();
}
}
| |
/**
* Copyright 2016 Netflix, 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 io.reactivex.subscribers;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.junit.*;
import org.reactivestreams.*;
import io.reactivex.*;
import io.reactivex.exceptions.TestException;
import io.reactivex.internal.subscriptions.*;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
public class SerializedSubscriberTest {
Subscriber<String> observer;
@Before
public void before() {
observer = TestHelper.mockSubscriber();
}
private Subscriber<String> serializedSubscriber(Subscriber<String> o) {
return new SerializedSubscriber<String>(o);
}
@Test
public void testSingleThreadedBasic() {
TestSingleThreadedPublisher onSubscribe = new TestSingleThreadedPublisher("one", "two", "three");
Flowable<String> w = Flowable.unsafeCreate(onSubscribe);
Subscriber<String> aw = serializedSubscriber(observer);
w.subscribe(aw);
onSubscribe.waitToFinish();
verify(observer, times(1)).onNext("one");
verify(observer, times(1)).onNext("two");
verify(observer, times(1)).onNext("three");
verify(observer, never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
// non-deterministic because unsubscribe happens after 'waitToFinish' releases
// so commenting out for now as this is not a critical thing to test here
// verify(s, times(1)).unsubscribe();
}
@Test
public void testMultiThreadedBasic() {
TestMultiThreadedObservable onSubscribe = new TestMultiThreadedObservable("one", "two", "three");
Flowable<String> w = Flowable.unsafeCreate(onSubscribe);
BusySubscriber busySubscriber = new BusySubscriber();
Subscriber<String> aw = serializedSubscriber(busySubscriber);
w.subscribe(aw);
onSubscribe.waitToFinish();
assertEquals(3, busySubscriber.onNextCount.get());
assertFalse(busySubscriber.onError);
assertTrue(busySubscriber.onComplete);
// non-deterministic because unsubscribe happens after 'waitToFinish' releases
// so commenting out for now as this is not a critical thing to test here
// verify(s, times(1)).unsubscribe();
// we can have concurrency ...
assertTrue(onSubscribe.maxConcurrentThreads.get() > 1);
// ... but the onNext execution should be single threaded
assertEquals(1, busySubscriber.maxConcurrentThreads.get());
}
@Test(timeout = 1000)
public void testMultiThreadedWithNPE() throws InterruptedException {
TestMultiThreadedObservable onSubscribe = new TestMultiThreadedObservable("one", "two", "three", null);
Flowable<String> w = Flowable.unsafeCreate(onSubscribe);
BusySubscriber busySubscriber = new BusySubscriber();
Subscriber<String> aw = serializedSubscriber(busySubscriber);
w.subscribe(aw);
onSubscribe.waitToFinish();
busySubscriber.terminalEvent.await();
System.out.println("OnSubscribe maxConcurrentThreads: " + onSubscribe.maxConcurrentThreads.get() + " Subscriber maxConcurrentThreads: " + busySubscriber.maxConcurrentThreads.get());
// we can't know how many onNext calls will occur since they each run on a separate thread
// that depends on thread scheduling so 0, 1, 2 and 3 are all valid options
// assertEquals(3, busySubscriber.onNextCount.get());
assertTrue(busySubscriber.onNextCount.get() < 4);
assertTrue(busySubscriber.onError);
// no onComplete because onError was invoked
assertFalse(busySubscriber.onComplete);
// non-deterministic because unsubscribe happens after 'waitToFinish' releases
// so commenting out for now as this is not a critical thing to test here
//verify(s, times(1)).unsubscribe();
// we can have concurrency ...
assertTrue(onSubscribe.maxConcurrentThreads.get() > 1);
// ... but the onNext execution should be single threaded
assertEquals(1, busySubscriber.maxConcurrentThreads.get());
}
@Test
public void testMultiThreadedWithNPEinMiddle() {
int n = 10;
for (int i = 0; i < n; i++) {
TestMultiThreadedObservable onSubscribe = new TestMultiThreadedObservable("one", "two", "three", null,
"four", "five", "six", "seven", "eight", "nine");
Flowable<String> w = Flowable.unsafeCreate(onSubscribe);
BusySubscriber busySubscriber = new BusySubscriber();
Subscriber<String> aw = serializedSubscriber(busySubscriber);
w.subscribe(aw);
onSubscribe.waitToFinish();
System.out.println("OnSubscribe maxConcurrentThreads: " + onSubscribe.maxConcurrentThreads.get() + " Subscriber maxConcurrentThreads: " + busySubscriber.maxConcurrentThreads.get());
// we can have concurrency ...
assertTrue(onSubscribe.maxConcurrentThreads.get() > 1);
// ... but the onNext execution should be single threaded
assertEquals(1, busySubscriber.maxConcurrentThreads.get());
// this should not be the full number of items since the error should stop it before it completes all 9
System.out.println("onNext count: " + busySubscriber.onNextCount.get());
assertFalse(busySubscriber.onComplete);
assertTrue(busySubscriber.onError);
assertTrue(busySubscriber.onNextCount.get() < 9);
// no onComplete because onError was invoked
// non-deterministic because unsubscribe happens after 'waitToFinish' releases
// so commenting out for now as this is not a critical thing to test here
// verify(s, times(1)).unsubscribe();
}
}
/**
* A non-realistic use case that tries to expose thread-safety issues by throwing lots of out-of-order
* events on many threads.
*/
@Test
public void runOutOfOrderConcurrencyTest() {
ExecutorService tp = Executors.newFixedThreadPool(20);
try {
TestConcurrencySubscriber tw = new TestConcurrencySubscriber();
// we need Synchronized + SafeSubscriber to handle synchronization plus life-cycle
Subscriber<String> w = serializedSubscriber(new SafeSubscriber<String>(tw));
Future<?> f1 = tp.submit(new OnNextThread(w, 12000));
Future<?> f2 = tp.submit(new OnNextThread(w, 5000));
Future<?> f3 = tp.submit(new OnNextThread(w, 75000));
Future<?> f4 = tp.submit(new OnNextThread(w, 13500));
Future<?> f5 = tp.submit(new OnNextThread(w, 22000));
Future<?> f6 = tp.submit(new OnNextThread(w, 15000));
Future<?> f7 = tp.submit(new OnNextThread(w, 7500));
Future<?> f8 = tp.submit(new OnNextThread(w, 23500));
Future<?> f10 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f1, f2, f3, f4));
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// ignore
}
Future<?> f11 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
Future<?> f12 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
Future<?> f13 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
Future<?> f14 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f4, f6, f7));
// // the next 4 onError events should wait on same as f10
Future<?> f15 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
Future<?> f16 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
Future<?> f17 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
Future<?> f18 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onError, f1, f2, f3, f4));
waitOnThreads(f1, f2, f3, f4, f5, f6, f7, f8, f10, f11, f12, f13, f14, f15, f16, f17, f18);
@SuppressWarnings("unused")
int numNextEvents = tw.assertEvents(null); // no check of type since we don't want to test barging results here, just interleaving behavior
// System.out.println("Number of events executed: " + numNextEvents);
} catch (Throwable e) {
fail("Concurrency test failed: " + e.getMessage());
e.printStackTrace();
} finally {
tp.shutdown();
try {
tp.awaitTermination(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Test
public void runConcurrencyTest() {
ExecutorService tp = Executors.newFixedThreadPool(20);
try {
TestConcurrencySubscriber tw = new TestConcurrencySubscriber();
// we need Synchronized + SafeSubscriber to handle synchronization plus life-cycle
Subscriber<String> w = serializedSubscriber(new SafeSubscriber<String>(tw));
w.onSubscribe(new BooleanSubscription());
Future<?> f1 = tp.submit(new OnNextThread(w, 12000));
Future<?> f2 = tp.submit(new OnNextThread(w, 5000));
Future<?> f3 = tp.submit(new OnNextThread(w, 75000));
Future<?> f4 = tp.submit(new OnNextThread(w, 13500));
Future<?> f5 = tp.submit(new OnNextThread(w, 22000));
Future<?> f6 = tp.submit(new OnNextThread(w, 15000));
Future<?> f7 = tp.submit(new OnNextThread(w, 7500));
Future<?> f8 = tp.submit(new OnNextThread(w, 23500));
// 12000 + 5000 + 75000 + 13500 + 22000 + 15000 + 7500 + 23500 = 173500
Future<?> f10 = tp.submit(new CompletionThread(w, TestConcurrencySubscriberEvent.onComplete, f1, f2, f3, f4, f5, f6, f7, f8));
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// ignore
}
waitOnThreads(f1, f2, f3, f4, f5, f6, f7, f8, f10);
int numNextEvents = tw.assertEvents(null); // no check of type since we don't want to test barging results here, just interleaving behavior
assertEquals(173500, numNextEvents);
// System.out.println("Number of events executed: " + numNextEvents);
} catch (Throwable e) {
fail("Concurrency test failed: " + e.getMessage());
e.printStackTrace();
} finally {
tp.shutdown();
try {
tp.awaitTermination(25000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Test that a notification does not get delayed in the queue waiting for the next event to push it through.
*
* @throws InterruptedException if the await is interrupted
*/
@Ignore("this is non-deterministic ... haven't figured out what's wrong with the test yet (benjchristensen: July 2014)")
@Test
public void testNotificationDelay() throws InterruptedException {
ExecutorService tp1 = Executors.newFixedThreadPool(1);
ExecutorService tp2 = Executors.newFixedThreadPool(1);
try {
int n = 10;
for (int i = 0; i < n; i++) {
final CountDownLatch firstOnNext = new CountDownLatch(1);
final CountDownLatch onNextCount = new CountDownLatch(2);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch running = new CountDownLatch(2);
TestSubscriber<String> to = new TestSubscriber<String>(new DefaultSubscriber<String>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String t) {
firstOnNext.countDown();
// force it to take time when delivering so the second one is enqueued
try {
latch.await();
} catch (InterruptedException e) {
}
}
});
Subscriber<String> o = serializedSubscriber(to);
Future<?> f1 = tp1.submit(new OnNextThread(o, 1, onNextCount, running));
Future<?> f2 = tp2.submit(new OnNextThread(o, 1, onNextCount, running));
running.await(); // let one of the OnNextThread actually run before proceeding
firstOnNext.await();
Thread t1 = to.lastThread();
System.out.println("first onNext on thread: " + t1);
latch.countDown();
waitOnThreads(f1, f2);
// not completed yet
assertEquals(2, to.valueCount());
Thread t2 = to.lastThread();
System.out.println("second onNext on thread: " + t2);
assertSame(t1, t2);
System.out.println(to.values());
o.onComplete();
System.out.println(to.values());
}
} finally {
tp1.shutdown();
tp2.shutdown();
}
}
/**
* Demonstrates thread starvation problem.
*
* No solution on this for now. Trade-off in this direction as per https://github.com/ReactiveX/RxJava/issues/998#issuecomment-38959474
* Probably need backpressure for this to work
*
* When using SynchronizedSubscriber we get this output:
*
* p1: 18 p2: 68 => should be close to each other unless we have thread starvation
*
* When using SerializedSubscriber we get:
*
* p1: 1 p2: 2445261 => should be close to each other unless we have thread starvation
*
* This demonstrates how SynchronizedSubscriber balances back and forth better, and blocks emission.
* The real issue in this example is the async buffer-bloat, so we need backpressure.
*
*
* @throws InterruptedException if the await is interrupted
*/
@Ignore("Demonstrates thread starvation problem. Read JavaDoc")
@Test
public void testThreadStarvation() throws InterruptedException {
TestSubscriber<String> to = new TestSubscriber<String>(new DefaultSubscriber<String>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String t) {
// force it to take time when delivering
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
});
final Subscriber<String> o = serializedSubscriber(to);
AtomicInteger p1 = new AtomicInteger();
AtomicInteger p2 = new AtomicInteger();
o.onSubscribe(new BooleanSubscription());
ResourceSubscriber<String> as1 = new ResourceSubscriber<String>() {
@Override
public void onNext(String t) {
o.onNext(t);
}
@Override
public void onError(Throwable t) {
RxJavaPlugins.onError(t);
}
@Override
public void onComplete() {
}
};
ResourceSubscriber<String> as2 = new ResourceSubscriber<String>() {
@Override
public void onNext(String t) {
o.onNext(t);
}
@Override
public void onError(Throwable t) {
RxJavaPlugins.onError(t);
}
@Override
public void onComplete() {
}
};
infinite(p1).subscribe(as1);
infinite(p2).subscribe(as2);
Thread.sleep(100);
System.out.println("p1: " + p1.get() + " p2: " + p2.get() + " => should be close to each other unless we have thread starvation");
assertEquals(p1.get(), p2.get(), 10000); // fairly distributed within 10000 of each other
as1.dispose();
as2.dispose();
}
private static void waitOnThreads(Future<?>... futures) {
for (Future<?> f : futures) {
try {
f.get(20, TimeUnit.SECONDS);
} catch (Throwable e) {
System.err.println("Failed while waiting on future.");
e.printStackTrace();
}
}
}
private static Flowable<String> infinite(final AtomicInteger produced) {
return Flowable.unsafeCreate(new Publisher<String>() {
@Override
public void subscribe(Subscriber<? super String> s) {
BooleanSubscription bs = new BooleanSubscription();
s.onSubscribe(bs);
while (!bs.isCancelled()) {
s.onNext("onNext");
produced.incrementAndGet();
}
}
}).subscribeOn(Schedulers.newThread());
}
/**
* A thread that will pass data to onNext.
*/
public static class OnNextThread implements Runnable {
private final CountDownLatch latch;
private final Subscriber<String> observer;
private final int numStringsToSend;
final AtomicInteger produced;
private final CountDownLatch running;
OnNextThread(Subscriber<String> observer, int numStringsToSend, CountDownLatch latch, CountDownLatch running) {
this(observer, numStringsToSend, new AtomicInteger(), latch, running);
}
OnNextThread(Subscriber<String> observer, int numStringsToSend, AtomicInteger produced) {
this(observer, numStringsToSend, produced, null, null);
}
OnNextThread(Subscriber<String> observer, int numStringsToSend, AtomicInteger produced, CountDownLatch latch, CountDownLatch running) {
this.observer = observer;
this.numStringsToSend = numStringsToSend;
this.produced = produced;
this.latch = latch;
this.running = running;
}
OnNextThread(Subscriber<String> observer, int numStringsToSend) {
this(observer, numStringsToSend, new AtomicInteger());
}
@Override
public void run() {
if (running != null) {
running.countDown();
}
for (int i = 0; i < numStringsToSend; i++) {
observer.onNext(Thread.currentThread().getId() + "-" + i);
if (latch != null) {
latch.countDown();
}
produced.incrementAndGet();
}
}
}
/**
* A thread that will call onError or onNext.
*/
public static class CompletionThread implements Runnable {
private final Subscriber<String> observer;
private final TestConcurrencySubscriberEvent event;
private final Future<?>[] waitOnThese;
CompletionThread(Subscriber<String> Subscriber, TestConcurrencySubscriberEvent event, Future<?>... waitOnThese) {
this.observer = Subscriber;
this.event = event;
this.waitOnThese = waitOnThese;
}
@Override
public void run() {
/* if we have 'waitOnThese' futures, we'll wait on them before proceeding */
if (waitOnThese != null) {
for (Future<?> f : waitOnThese) {
try {
f.get();
} catch (Throwable e) {
System.err.println("Error while waiting on future in CompletionThread");
}
}
}
/* send the event */
if (event == TestConcurrencySubscriberEvent.onError) {
observer.onError(new RuntimeException("mocked exception"));
} else if (event == TestConcurrencySubscriberEvent.onComplete) {
observer.onComplete();
} else {
throw new IllegalArgumentException("Expecting either onError or onComplete");
}
}
}
enum TestConcurrencySubscriberEvent {
onComplete, onError, onNext
}
private static class TestConcurrencySubscriber extends DefaultSubscriber<String> {
/**
* Used to store the order and number of events received.
*/
private final LinkedBlockingQueue<TestConcurrencySubscriberEvent> events = new LinkedBlockingQueue<TestConcurrencySubscriberEvent>();
private final int waitTime;
@SuppressWarnings("unused")
TestConcurrencySubscriber(int waitTimeInNext) {
this.waitTime = waitTimeInNext;
}
TestConcurrencySubscriber() {
this.waitTime = 0;
}
@Override
public void onComplete() {
events.add(TestConcurrencySubscriberEvent.onComplete);
}
@Override
public void onError(Throwable e) {
events.add(TestConcurrencySubscriberEvent.onError);
}
@Override
public void onNext(String args) {
events.add(TestConcurrencySubscriberEvent.onNext);
// do some artificial work to make the thread scheduling/timing vary
int s = 0;
for (int i = 0; i < 20; i++) {
s += s * i;
}
if (waitTime > 0) {
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
// ignore
}
}
}
/**
* Assert the order of events is correct and return the number of onNext executions.
*
* @param expectedEndingEvent the last event
* @return int count of onNext calls
* @throws IllegalStateException
* If order of events was invalid.
*/
public int assertEvents(TestConcurrencySubscriberEvent expectedEndingEvent) throws IllegalStateException {
int nextCount = 0;
boolean finished = false;
for (TestConcurrencySubscriberEvent e : events) {
if (e == TestConcurrencySubscriberEvent.onNext) {
if (finished) {
// already finished, we shouldn't get this again
throw new IllegalStateException("Received onNext but we're already finished.");
}
nextCount++;
} else if (e == TestConcurrencySubscriberEvent.onError) {
if (finished) {
// already finished, we shouldn't get this again
throw new IllegalStateException("Received onError but we're already finished.");
}
if (expectedEndingEvent != null && TestConcurrencySubscriberEvent.onError != expectedEndingEvent) {
throw new IllegalStateException("Received onError ending event but expected " + expectedEndingEvent);
}
finished = true;
} else if (e == TestConcurrencySubscriberEvent.onComplete) {
if (finished) {
// already finished, we shouldn't get this again
throw new IllegalStateException("Received onComplete but we're already finished.");
}
if (expectedEndingEvent != null && TestConcurrencySubscriberEvent.onComplete != expectedEndingEvent) {
throw new IllegalStateException("Received onComplete ending event but expected " + expectedEndingEvent);
}
finished = true;
}
}
return nextCount;
}
}
/**
* This spawns a single thread for the subscribe execution.
*/
static class TestSingleThreadedPublisher implements Publisher<String> {
final String[] values;
private Thread t;
TestSingleThreadedPublisher(final String... values) {
this.values = values;
}
@Override
public void subscribe(final Subscriber<? super String> observer) {
observer.onSubscribe(new BooleanSubscription());
System.out.println("TestSingleThreadedObservable subscribed to ...");
t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("running TestSingleThreadedObservable thread");
for (String s : values) {
System.out.println("TestSingleThreadedObservable onNext: " + s);
observer.onNext(s);
}
observer.onComplete();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
});
System.out.println("starting TestSingleThreadedObservable thread");
t.start();
System.out.println("done starting TestSingleThreadedObservable thread");
}
public void waitToFinish() {
try {
t.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
/**
* This spawns a thread for the subscription, then a separate thread for each onNext call.
*/
static class TestMultiThreadedObservable implements Publisher<String> {
final String[] values;
Thread t;
AtomicInteger threadsRunning = new AtomicInteger();
AtomicInteger maxConcurrentThreads = new AtomicInteger();
ExecutorService threadPool;
TestMultiThreadedObservable(String... values) {
this.values = values;
this.threadPool = Executors.newCachedThreadPool();
}
@Override
public void subscribe(final Subscriber<? super String> observer) {
observer.onSubscribe(new BooleanSubscription());
final NullPointerException npe = new NullPointerException();
System.out.println("TestMultiThreadedObservable subscribed to ...");
t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("running TestMultiThreadedObservable thread");
int j = 0;
for (final String s : values) {
final int fj = ++j;
threadPool.execute(new Runnable() {
@Override
public void run() {
threadsRunning.incrementAndGet();
try {
// perform onNext call
System.out.println("TestMultiThreadedObservable onNext: " + s + " on thread " + Thread.currentThread().getName());
if (s == null) {
// force an error
throw npe;
} else {
// allow the exception to queue up
int sleep = (fj % 3) * 10;
if (sleep != 0) {
Thread.sleep(sleep);
}
}
observer.onNext(s);
// capture 'maxThreads'
int concurrentThreads = threadsRunning.get();
int maxThreads = maxConcurrentThreads.get();
if (concurrentThreads > maxThreads) {
maxConcurrentThreads.compareAndSet(maxThreads, concurrentThreads);
}
} catch (Throwable e) {
observer.onError(e);
} finally {
threadsRunning.decrementAndGet();
}
}
});
}
// we are done spawning threads
threadPool.shutdown();
} catch (Throwable e) {
throw new RuntimeException(e);
}
// wait until all threads are done, then mark it as COMPLETED
try {
// wait for all the threads to finish
if (!threadPool.awaitTermination(5, TimeUnit.SECONDS)) {
System.out.println("Threadpool did not terminate in time.");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
observer.onComplete();
}
});
System.out.println("starting TestMultiThreadedObservable thread");
t.start();
System.out.println("done starting TestMultiThreadedObservable thread");
}
public void waitToFinish() {
try {
t.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
private static class BusySubscriber extends DefaultSubscriber<String> {
volatile boolean onComplete;
volatile boolean onError;
AtomicInteger onNextCount = new AtomicInteger();
AtomicInteger threadsRunning = new AtomicInteger();
AtomicInteger maxConcurrentThreads = new AtomicInteger();
final CountDownLatch terminalEvent = new CountDownLatch(1);
@Override
public void onComplete() {
threadsRunning.incrementAndGet();
try {
onComplete = true;
} finally {
captureMaxThreads();
threadsRunning.decrementAndGet();
terminalEvent.countDown();
}
}
@Override
public void onError(Throwable e) {
System.out.println(">>>>>>>>>>>>>>>>>>>> onError received: " + e);
threadsRunning.incrementAndGet();
try {
onError = true;
} finally {
captureMaxThreads();
threadsRunning.decrementAndGet();
terminalEvent.countDown();
}
}
@Override
public void onNext(String args) {
threadsRunning.incrementAndGet();
try {
onNextCount.incrementAndGet();
try {
// simulate doing something computational
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
// capture 'maxThreads'
captureMaxThreads();
threadsRunning.decrementAndGet();
}
}
protected void captureMaxThreads() {
int concurrentThreads = threadsRunning.get();
int maxThreads = maxConcurrentThreads.get();
if (concurrentThreads > maxThreads) {
maxConcurrentThreads.compareAndSet(maxThreads, concurrentThreads);
if (concurrentThreads > 1) {
new RuntimeException("should not be greater than 1").printStackTrace();
}
}
}
}
@Test
@Ignore("Null values not permitted")
public void testSerializeNull() {
final AtomicReference<Subscriber<Integer>> serial = new AtomicReference<Subscriber<Integer>>();
TestSubscriber<Integer> to = new TestSubscriber<Integer>() {
@Override
public void onNext(Integer t) {
if (t != null && t == 0) {
serial.get().onNext(null);
}
super.onNext(t);
}
};
SerializedSubscriber<Integer> sobs = new SerializedSubscriber<Integer>(to);
serial.set(sobs);
sobs.onNext(0);
to.assertValues(0, null);
}
@Test
@Ignore("Subscribers can't throw")
public void testSerializeAllowsOnError() {
TestSubscriber<Integer> to = new TestSubscriber<Integer>() {
@Override
public void onNext(Integer t) {
throw new TestException();
}
};
SerializedSubscriber<Integer> sobs = new SerializedSubscriber<Integer>(to);
try {
sobs.onNext(0);
} catch (TestException ex) {
sobs.onError(ex);
}
to.assertError(TestException.class);
}
@Test
@Ignore("Null values no longer permitted")
public void testSerializeReentrantNullAndComplete() {
final AtomicReference<Subscriber<Integer>> serial = new AtomicReference<Subscriber<Integer>>();
TestSubscriber<Integer> to = new TestSubscriber<Integer>() {
@Override
public void onNext(Integer t) {
serial.get().onComplete();
throw new TestException();
}
};
SerializedSubscriber<Integer> sobs = new SerializedSubscriber<Integer>(to);
serial.set(sobs);
try {
sobs.onNext(0);
} catch (TestException ex) {
sobs.onError(ex);
}
to.assertError(TestException.class);
to.assertNotComplete();
}
@Test
@Ignore("Subscribers can't throw")
public void testSerializeReentrantNullAndError() {
final AtomicReference<Subscriber<Integer>> serial = new AtomicReference<Subscriber<Integer>>();
TestSubscriber<Integer> to = new TestSubscriber<Integer>() {
@Override
public void onNext(Integer t) {
serial.get().onError(new RuntimeException());
throw new TestException();
}
};
SerializedSubscriber<Integer> sobs = new SerializedSubscriber<Integer>(to);
serial.set(sobs);
try {
sobs.onNext(0);
} catch (TestException ex) {
sobs.onError(ex);
}
to.assertError(TestException.class);
to.assertNotComplete();
}
@Test
@Ignore("Null values no longer permitted")
public void testSerializeDrainPhaseThrows() {
final AtomicReference<Subscriber<Integer>> serial = new AtomicReference<Subscriber<Integer>>();
TestSubscriber<Integer> to = new TestSubscriber<Integer>() {
@Override
public void onNext(Integer t) {
if (t != null && t == 0) {
serial.get().onNext(null);
} else
if (t == null) {
throw new TestException();
}
super.onNext(t);
}
};
SerializedSubscriber<Integer> sobs = new SerializedSubscriber<Integer>(to);
serial.set(sobs);
sobs.onNext(0);
to.assertError(TestException.class);
to.assertNotComplete();
}
@Test
public void testErrorReentry() {
final AtomicReference<Subscriber<Integer>> serial = new AtomicReference<Subscriber<Integer>>();
TestSubscriber<Integer> ts = new TestSubscriber<Integer>() {
@Override
public void onNext(Integer v) {
serial.get().onError(new TestException());
serial.get().onError(new TestException());
super.onNext(v);
}
};
SerializedSubscriber<Integer> sobs = new SerializedSubscriber<Integer>(ts);
sobs.onSubscribe(new BooleanSubscription());
serial.set(sobs);
sobs.onNext(1);
ts.assertValue(1);
ts.assertError(TestException.class);
}
@Test
public void testCompleteReentry() {
final AtomicReference<Subscriber<Integer>> serial = new AtomicReference<Subscriber<Integer>>();
TestSubscriber<Integer> ts = new TestSubscriber<Integer>() {
@Override
public void onNext(Integer v) {
serial.get().onComplete();
serial.get().onComplete();
super.onNext(v);
}
};
SerializedSubscriber<Integer> sobs = new SerializedSubscriber<Integer>(ts);
sobs.onSubscribe(new BooleanSubscription());
serial.set(sobs);
sobs.onNext(1);
ts.assertValue(1);
ts.assertComplete();
ts.assertNoErrors();
}
@Test
public void dispose() {
TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts);
BooleanSubscription d = new BooleanSubscription();
so.onSubscribe(d);
ts.cancel();
assertTrue(d.isCancelled());
}
@Test
public void onCompleteRace() {
for (int i = 0; i < 500; i++) {
TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts);
BooleanSubscription d = new BooleanSubscription();
so.onSubscribe(d);
Runnable r = new Runnable() {
@Override
public void run() {
so.onComplete();
}
};
TestHelper.race(r, r, Schedulers.single());
ts.awaitDone(5, TimeUnit.SECONDS)
.assertResult();
}
}
@Test
public void onNextOnCompleteRace() {
for (int i = 0; i < 500; i++) {
TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts);
BooleanSubscription d = new BooleanSubscription();
so.onSubscribe(d);
Runnable r1 = new Runnable() {
@Override
public void run() {
so.onComplete();
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
so.onNext(1);
}
};
TestHelper.race(r1, r2, Schedulers.single());
ts.awaitDone(5, TimeUnit.SECONDS)
.assertNoErrors()
.assertComplete();
assertTrue(ts.valueCount() <= 1);
}
}
@Test
public void onNextOnErrorRace() {
for (int i = 0; i < 500; i++) {
TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts);
BooleanSubscription d = new BooleanSubscription();
so.onSubscribe(d);
final Throwable ex = new TestException();
Runnable r1 = new Runnable() {
@Override
public void run() {
so.onError(ex);
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
so.onNext(1);
}
};
TestHelper.race(r1, r2, Schedulers.single());
ts.awaitDone(5, TimeUnit.SECONDS)
.assertError(ex)
.assertNotComplete();
assertTrue(ts.valueCount() <= 1);
}
}
@Test
public void onNextOnErrorRaceDelayError() {
for (int i = 0; i < 500; i++) {
TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts, true);
BooleanSubscription d = new BooleanSubscription();
so.onSubscribe(d);
final Throwable ex = new TestException();
Runnable r1 = new Runnable() {
@Override
public void run() {
so.onError(ex);
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
so.onNext(1);
}
};
TestHelper.race(r1, r2, Schedulers.single());
ts.awaitDone(5, TimeUnit.SECONDS)
.assertError(ex)
.assertNotComplete();
assertTrue(ts.valueCount() <= 1);
}
}
@Test
public void startOnce() {
List<Throwable> error = TestHelper.trackPluginErrors();
try {
TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts);
so.onSubscribe(new BooleanSubscription());
BooleanSubscription d = new BooleanSubscription();
so.onSubscribe(d);
assertTrue(d.isCancelled());
TestHelper.assertError(error, 0, IllegalStateException.class, "Subscription already set!");
} finally {
RxJavaPlugins.reset();
}
}
@Test
public void onCompleteOnErrorRace() {
for (int i = 0; i < 500; i++) {
TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
final SerializedSubscriber<Integer> so = new SerializedSubscriber<Integer>(ts);
BooleanSubscription d = new BooleanSubscription();
so.onSubscribe(d);
final Throwable ex = new TestException();
Runnable r1 = new Runnable() {
@Override
public void run() {
so.onError(ex);
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
so.onComplete();
}
};
TestHelper.race(r1, r2, Schedulers.single());
ts.awaitDone(5, TimeUnit.SECONDS);
if (ts.completions() != 0) {
ts.assertResult();
} else {
ts.assertFailure(TestException.class).assertError(ex);
}
}
}
}
| |
/**
* 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.presentation.releases;
import com.francetelecom.clara.cloud.core.service.ManageApplication;
import com.francetelecom.clara.cloud.core.service.ManageApplicationRelease;
import com.francetelecom.clara.cloud.core.service.exception.ObjectNotFoundException;
import com.francetelecom.clara.cloud.coremodel.Application;
import com.francetelecom.clara.cloud.coremodel.ApplicationRelease;
import com.francetelecom.clara.cloud.deployment.logical.service.ManageLogicalDeployment;
import com.francetelecom.clara.cloud.presentation.designer.pages.DesignerHelperPage;
import com.francetelecom.clara.cloud.presentation.designer.panels.DesignerArchitectureMatrixPanel;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* User: wwnl9733
* Date: 25/10/11
* Time: 15:31
*/
public class ReleaseForkSelectPanel extends Panel {
private static final long serialVersionUID = 8165234888427238880L;
private static final Logger logger = LoggerFactory.getLogger(ReleaseForkSelectPanel.class);
@SpringBean
private ManageApplication manageApplication;
@SpringBean
private ManageApplicationRelease manageApplicationRelease;
@SpringBean
private ManageLogicalDeployment manageLogicalDeployment;
private DropDownChoice<ApplicationRelease> releaseSelect;
private DropDownChoice<Application> applicationSelect;
private WebMarkupContainer appContainer;
private WebMarkupContainer releaseContainer;
private WebMarkupContainer appDescriptionContainer;
private Label appDescriptionLabel;
private WebMarkupContainer architectureContainer;
private DesignerHelperPage parentPage;
private DesignerArchitectureMatrixPanel envArchitecturePanel;
public ReleaseForkSelectPanel(String id, DesignerHelperPage parentPage) {
super(id);
this.parentPage = parentPage;
initComponents();
}
private void initComponents() {
initContainers();
//Select appliction choice
ChoiceRenderer<Application> applicationChoice = new ChoiceRenderer<>("label", "uid");
applicationSelect = new DropDownChoice<Application>("appSelect", new Model<Application>(), getApplicationList(), applicationChoice);
applicationSelect.add(new OnChangeAjaxBehavior() {
@Override
protected void onUpdate(AjaxRequestTarget target) {
Application selectedApp = applicationSelect.getModelObject();
boolean isSelected = selectedApp != null;
updateContainerVisibility(isSelected, false, target);
if (isSelected) {
updateReleaseSelect(selectedApp.getUID(), target);
updateAppDescription(selectedApp.getUID(), target);
}
}
});
applicationSelect.setNullValid(true);
appContainer.add(applicationSelect);
//Select Release version choice
ChoiceRenderer<ApplicationRelease> applicationReleaseVersionChoice = new ChoiceRenderer<>("releaseVersion", "uid");
releaseSelect = new DropDownChoice<ApplicationRelease>("releaseSelect", new Model<ApplicationRelease>(), (List) null, applicationReleaseVersionChoice);
releaseSelect.add(new OnChangeAjaxBehavior() {
@Override
protected void onUpdate(AjaxRequestTarget target) {
ApplicationRelease selectedRelease = releaseSelect.getModelObject();
boolean isSelected = selectedRelease != null;
updateMatrixContainerVisibility(isSelected, target);
if (isSelected) {
try {
parentPage.getLogicalDeploymentPersisted(selectedRelease.getUID());
envArchitecturePanel.updateTable();
} catch (ObjectNotFoundException e) {
logger.info("Logical deployment not found for release: " + selectedRelease.getUID(), e);
}
}
}
});
releaseSelect.setNullValid(true);
releaseContainer.add(releaseSelect);
//Description
appDescriptionLabel = new Label("appDescription", "placeholder");
appDescriptionContainer.add(appDescriptionLabel);
//Matrix
envArchitecturePanel = new DesignerArchitectureMatrixPanel("archi", parentPage, true, false);
architectureContainer.add(envArchitecturePanel);
}
private List<Application> getApplicationList() {
return (List<Application>) manageApplication.findAccessibleApplications();
}
private void initContainers() {
appContainer = new WebMarkupContainer("appContainer");
appContainer.setOutputMarkupPlaceholderTag(true);
appContainer.setOutputMarkupId(true);
add(appContainer);
releaseContainer = new WebMarkupContainer("releaseContainer");
releaseContainer.setOutputMarkupPlaceholderTag(true);
releaseContainer.setOutputMarkupId(true);
releaseContainer.setVisible(false);
add(releaseContainer);
appDescriptionContainer = new WebMarkupContainer("appDescriptionContainer");
appDescriptionContainer.setOutputMarkupPlaceholderTag(true);
appDescriptionContainer.setOutputMarkupId(true);
appDescriptionContainer.setVisible(false);
add(appDescriptionContainer);
architectureContainer = new WebMarkupContainer("architectureContainer");
architectureContainer.setOutputMarkupPlaceholderTag(true);
architectureContainer.setOutputMarkupId(true);
architectureContainer.setVisible(false);
add(architectureContainer);
}
private void updateContainerVisibility(boolean isVisible, boolean isReleaseSelected, AjaxRequestTarget target) {
releaseContainer.setVisible(isVisible);
appDescriptionContainer.setVisible(isVisible);
if (!isVisible || isReleaseSelected) {
updateMatrixContainerVisibility(isVisible, target);
}
addContainersToTarget(target);
}
private void addContainersToTarget(AjaxRequestTarget target) {
target.add(releaseContainer);
target.add(appDescriptionContainer);
target.add(architectureContainer);
}
private void updateMatrixContainerVisibility(boolean isVisible, AjaxRequestTarget target) {
architectureContainer.setVisible(isVisible);
addContainersToTarget(target);
}
private void updateReleaseSelect(String appUid, AjaxRequestTarget target) {
List<ApplicationRelease> releaseList = null;
releaseSelect.setChoices(releaseList);
updateMatrixContainerVisibility(false, target);
try {
releaseList = manageApplicationRelease.findApplicationReleasesByAppUID(appUid);
releaseSelect.setChoices(releaseList);
} catch (ObjectNotFoundException e) {
logger.info("Application not found with AppId: " + appUid, e);
}
addContainersToTarget(target);
}
private void updateAppDescription(String appUid, AjaxRequestTarget target){
try {
String description = manageApplication.findApplicationByUID(appUid).getDescription();
appDescriptionLabel.setDefaultModelObject(description == null ? getString("portal.release.creation.fork.app.description.empty") : description);
} catch (ObjectNotFoundException e) {
logger.info("Application not found for application uid: " + appUid, e);
}
addContainersToTarget(target);
}
public ApplicationRelease getRelease() {
return releaseSelect.getModelObject();
}
}
| |
/*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.model.token;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xdi.oxauth.model.common.AccessToken;
import org.xdi.oxauth.model.common.AuthorizationGrantType;
import org.xdi.oxauth.model.common.IdToken;
import org.xdi.oxauth.model.common.RefreshToken;
import org.xdi.oxauth.model.util.Util;
/**
* @author Javier Rojas Blum Date: 05.22.2012
*/
public class PersistentJwt {
private final static Logger log = LoggerFactory.getLogger(PersistentJwt.class);
private String userId;
private String clientId;
private AuthorizationGrantType authorizationGrantType;
private Date authenticationTime;
private List<String> scopes;
private List<AccessToken> accessTokens;
private List<RefreshToken> refreshTokens;
private AccessToken longLivedAccessToken;
private IdToken idToken;
public PersistentJwt() {
}
public PersistentJwt(String jwt) {
try {
load(jwt);
} catch (JSONException e) {
log.error(e.getMessage(), e);
}
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public AuthorizationGrantType getAuthorizationGrantType() {
return authorizationGrantType;
}
public void setAuthorizationGrantType(AuthorizationGrantType authorizationGrantType) {
this.authorizationGrantType = authorizationGrantType;
}
public Date getAuthenticationTime() {
return authenticationTime;
}
public List<String> getScopes() {
return scopes;
}
public void setScopes(List<String> scopes) {
this.scopes = scopes;
}
public void setAuthenticationTime(Date authenticationTime) {
this.authenticationTime = authenticationTime;
}
public List<AccessToken> getAccessTokens() {
return accessTokens;
}
public void setAccessTokens(List<AccessToken> accessTokens) {
this.accessTokens = accessTokens;
}
public List<RefreshToken> getRefreshTokens() {
return refreshTokens;
}
public void setRefreshTokens(List<RefreshToken> refreshTokens) {
this.refreshTokens = refreshTokens;
}
public AccessToken getLongLivedAccessToken() {
return longLivedAccessToken;
}
public void setLongLivedAccessToken(AccessToken longLivedAccessToken) {
this.longLivedAccessToken = longLivedAccessToken;
}
public IdToken getIdToken() {
return idToken;
}
public void setIdToken(IdToken idToken) {
this.idToken = idToken;
}
@Override
public String toString() {
JSONObject jsonObject = new JSONObject();
try {
if (StringUtils.isNotBlank(userId)) {
jsonObject.put("user_id", userId);
}
if (StringUtils.isNotBlank(clientId)) {
jsonObject.put("client_id", clientId);
}
if (authorizationGrantType != null) {
jsonObject.put("authorization_grant_type", authorizationGrantType);
}
if (authenticationTime != null) {
jsonObject.put("authentication_time", authenticationTime.getTime());
}
if (scopes != null) {
JSONArray scopesJsonArray = new JSONArray();
for (String scope : scopes) {
scopesJsonArray.put(scope);
}
jsonObject.put("scopes", scopesJsonArray);
}
if (accessTokens != null) {
JSONArray accessTokensJsonArray = new JSONArray();
for (AccessToken accessToken : accessTokens) {
JSONObject accessTokenJsonObject = new JSONObject();
if (accessToken.getCode() != null && !accessToken.getCode().isEmpty()) {
accessTokenJsonObject.put("code", accessToken.getCode());
}
if (accessToken.getCreationDate() != null) {
accessTokenJsonObject.put("creation_date", accessToken.getCreationDate().getTime());
}
if (accessToken.getExpirationDate() != null) {
accessTokenJsonObject.put("expiration_date", accessToken.getExpirationDate().getTime());
}
accessTokensJsonArray.put(accessTokenJsonObject);
}
jsonObject.put("access_tokens", accessTokensJsonArray);
}
if (refreshTokens != null) {
JSONArray refreshTokensJsonArray = new JSONArray();
for (RefreshToken refreshToken : refreshTokens) {
JSONObject refreshTokenJsonObject = new JSONObject();
if (refreshToken.getCode() != null && !refreshToken.getCode().isEmpty()) {
refreshTokenJsonObject.put("code", refreshToken.getCode());
}
if (refreshToken.getCreationDate() != null) {
refreshTokenJsonObject.put("creation_date", refreshToken.getCreationDate().getTime());
}
if (refreshToken.getExpirationDate() != null) {
refreshTokenJsonObject.put("expiration_date", refreshToken.getExpirationDate().getTime());
}
}
jsonObject.put("refresh_tokens", refreshTokensJsonArray);
}
if (longLivedAccessToken != null) {
JSONObject longLivedAccessTokenJsonObject = new JSONObject();
if (longLivedAccessToken.getCode() != null && !longLivedAccessToken.getCode().isEmpty()) {
longLivedAccessTokenJsonObject.put("code", longLivedAccessToken.getCode());
}
if (longLivedAccessToken.getCreationDate() != null) {
longLivedAccessTokenJsonObject.put("creation_date", longLivedAccessToken.getCreationDate().getTime());
}
if (longLivedAccessToken.getExpirationDate() != null) {
longLivedAccessTokenJsonObject.put("expiration_date", longLivedAccessToken.getExpirationDate().getTime());
}
jsonObject.put("long_lived_access_token", longLivedAccessTokenJsonObject);
}
if (idToken != null) {
JSONObject idTokenJsonObject = new JSONObject();
if (idToken.getCode() != null && !idToken.getCode().isEmpty()) {
idTokenJsonObject.put("code", idToken.getCode());
}
if (idToken.getCreationDate() != null) {
idTokenJsonObject.put("creation_date", idToken.getCreationDate().getTime());
}
if (idToken.getExpirationDate() != null) {
idTokenJsonObject.put("expiration_date", idToken.getExpirationDate().getTime());
}
jsonObject.put("id_token", idTokenJsonObject);
}
} catch (JSONException e) {
log.error(e.getMessage(), e);
}
return jsonObject.toString();
}
private boolean load(String jwt) throws JSONException {
boolean result = false;
JSONObject jsonObject = new JSONObject(jwt);
if (jsonObject.has("user_id")) {
userId = jsonObject.getString("user_id");
}
if (jsonObject.has("client_id")) {
clientId = jsonObject.getString("client_id");
}
if (jsonObject.has("authorization_grant_type")) {
authorizationGrantType = AuthorizationGrantType.fromString(jsonObject.getString("authorization_grant_type"));
}
if (jsonObject.has("authentication_time")) {
authenticationTime = new Date(jsonObject.getLong("authentication_time"));
}
if (jsonObject.has("scopes")) {
JSONArray jsonArray = jsonObject.getJSONArray("scopes");
scopes = Util.asList(jsonArray);
}
if (jsonObject.has("access_tokens")) {
JSONArray accessTokensJsonArray = jsonObject.getJSONArray("access_tokens");
accessTokens = new ArrayList<AccessToken>();
for (int i = 0; i < accessTokensJsonArray.length(); i++) {
JSONObject accessTokenJsonObject = accessTokensJsonArray.getJSONObject(i);
if (accessTokenJsonObject.has("code")
&& accessTokenJsonObject.has("creation_date")
&& accessTokenJsonObject.has("expiration_date")) {
String tokenCode = accessTokenJsonObject.getString("code");
Date creationDate = new Date(accessTokenJsonObject.getLong("creation_date"));
Date expirationDate = new Date(accessTokenJsonObject.getLong("expiration_date"));
AccessToken accessToken = new AccessToken(tokenCode, creationDate, expirationDate);
accessTokens.add(accessToken);
}
}
}
if (jsonObject.has("refresh_tokens")) {
JSONArray refreshTokensJsonArray = jsonObject.getJSONArray("refresh_tokens");
refreshTokens = new ArrayList<RefreshToken>();
for (int i = 0; i < refreshTokensJsonArray.length(); i++) {
JSONObject refreshTokenJsonObject = refreshTokensJsonArray.getJSONObject(i);
if (refreshTokenJsonObject.has("code")
&& refreshTokenJsonObject.has("creation_date")
&& refreshTokenJsonObject.has("expiration_date")) {
String tokenCode = refreshTokenJsonObject.getString("code");
Date creationDate = new Date(refreshTokenJsonObject.getLong("creation_date"));
Date expirationDate = new Date(refreshTokenJsonObject.getLong("expiration_date"));
RefreshToken refreshToken = new RefreshToken(tokenCode, creationDate, expirationDate);
refreshTokens.add(refreshToken);
}
}
}
if (jsonObject.has("long_lived_access_token")) {
JSONObject longLivedAccessTokenJsonObject = jsonObject.getJSONObject("long_lived_access_token");
if (longLivedAccessTokenJsonObject.has("code")
&& longLivedAccessTokenJsonObject.has("creation_date")
&& longLivedAccessTokenJsonObject.has("expiration_date")) {
String tokenCode = longLivedAccessTokenJsonObject.getString("code");
Date creationDate = new Date(longLivedAccessTokenJsonObject.getLong("creation_date"));
Date expirationDate = new Date(longLivedAccessTokenJsonObject.getLong("expiration_date"));
longLivedAccessToken = new AccessToken(tokenCode, creationDate, expirationDate);
}
}
if (jsonObject.has("id_token")) {
JSONObject idTokenJsonObject = jsonObject.getJSONObject("id_token");
if (idTokenJsonObject.has("code")
&& idTokenJsonObject.has("creation_date")
&& idTokenJsonObject.has("expiration_date")) {
String tokenCode = idTokenJsonObject.getString("code");
Date creationDate = new Date(idTokenJsonObject.getLong("creation_date"));
Date expirationDate = new Date(idTokenJsonObject.getLong("expiration_date"));
idToken = new IdToken(tokenCode, creationDate, expirationDate);
}
}
return result;
}
}
| |
/*
* 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.zeppelin.livy;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.zeppelin.interpreter.Interpreter;
import org.apache.zeppelin.interpreter.InterpreterContext;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterResult;
import org.apache.zeppelin.interpreter.InterpreterResultMessage;
import org.apache.zeppelin.interpreter.InterpreterUtils;
import org.apache.zeppelin.interpreter.LazyOpenInterpreter;
import org.apache.zeppelin.interpreter.WrappedInterpreter;
import org.apache.zeppelin.interpreter.thrift.InterpreterCompletion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.kerberos.client.KerberosRestTemplate;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
/**
* Base class for livy interpreters.
*/
public abstract class BaseLivyInterpreter extends Interpreter {
protected static final Logger LOGGER = LoggerFactory.getLogger(BaseLivyInterpreter.class);
private static Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static String SESSION_NOT_FOUND_PATTERN = "\"Session '\\d+' not found.\"";
protected volatile SessionInfo sessionInfo;
private String livyURL;
private int sessionCreationTimeout;
private int pullStatusInterval;
protected boolean displayAppInfo;
protected LivyVersion livyVersion;
private RestTemplate restTemplate;
private Map<String, String> customHeaders = new HashMap<>();
// delegate to sharedInterpreter when it is available
protected LivySharedInterpreter sharedInterpreter;
Set<Object> paragraphsToCancel = Collections.newSetFromMap(
new ConcurrentHashMap<Object, Boolean>());
private ConcurrentHashMap<String, Integer> paragraphId2StmtProgressMap =
new ConcurrentHashMap<>();
public BaseLivyInterpreter(Properties property) {
super(property);
this.livyURL = property.getProperty("zeppelin.livy.url");
this.displayAppInfo = Boolean.parseBoolean(
property.getProperty("zeppelin.livy.displayAppInfo", "true"));
this.sessionCreationTimeout = Integer.parseInt(
property.getProperty("zeppelin.livy.session.create_timeout", 120 + ""));
this.pullStatusInterval = Integer.parseInt(
property.getProperty("zeppelin.livy.pull_status.interval.millis", 1000 + ""));
this.restTemplate = createRestTemplate();
if (!StringUtils.isBlank(property.getProperty("zeppelin.livy.http.headers"))) {
String[] headers = property.getProperty("zeppelin.livy.http.headers").split(";");
for (String header : headers) {
String[] splits = header.split(":", -1);
if (splits.length != 2) {
throw new RuntimeException("Invalid format of http headers: " + header +
", valid http header format is HEADER_NAME:HEADER_VALUE");
}
customHeaders.put(splits[0].trim(), envSubstitute(splits[1].trim()));
}
}
}
private String envSubstitute(String value) {
String newValue = new String(value);
Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
Matcher matcher = pattern.matcher(value);
while (matcher.find()) {
String env = matcher.group(1);
newValue = newValue.replace("${" + env + "}", System.getenv(env));
}
return newValue;
}
// only for testing
Map<String, String> getCustomHeaders() {
return customHeaders;
}
public abstract String getSessionKind();
@Override
public void open() throws InterpreterException {
try {
this.livyVersion = getLivyVersion();
if (this.livyVersion.isSharedSupported()) {
sharedInterpreter = getLivySharedInterpreter();
}
if (sharedInterpreter == null || !sharedInterpreter.isSupported()) {
initLivySession();
}
} catch (LivyException e) {
String msg = "Fail to create session, please check livy interpreter log and " +
"livy server log";
throw new RuntimeException(msg, e);
}
}
protected LivySharedInterpreter getLivySharedInterpreter() throws InterpreterException {
LazyOpenInterpreter lazy = null;
LivySharedInterpreter sharedInterpreter = null;
Interpreter p = getInterpreterInTheSameSessionByClassName(
LivySharedInterpreter.class.getName());
while (p instanceof WrappedInterpreter) {
if (p instanceof LazyOpenInterpreter) {
lazy = (LazyOpenInterpreter) p;
}
p = ((WrappedInterpreter) p).getInnerInterpreter();
}
sharedInterpreter = (LivySharedInterpreter) p;
if (lazy != null) {
lazy.open();
}
return sharedInterpreter;
}
@Override
public void close() {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
sharedInterpreter.close();
return;
}
if (sessionInfo != null) {
closeSession(sessionInfo.id);
// reset sessionInfo to null so that we won't close it twice.
sessionInfo = null;
}
}
protected void initLivySession() throws LivyException {
this.sessionInfo = createSession(getUserName(), getSessionKind());
if (displayAppInfo) {
if (sessionInfo.appId == null) {
// livy 0.2 don't return appId and sparkUiUrl in response so that we need to get it
// explicitly by ourselves.
sessionInfo.appId = extractAppId();
}
if (sessionInfo.appInfo == null ||
StringUtils.isEmpty(sessionInfo.appInfo.get("sparkUiUrl"))) {
sessionInfo.webUIAddress = extractWebUIAddress();
} else {
sessionInfo.webUIAddress = sessionInfo.appInfo.get("sparkUiUrl");
}
LOGGER.info("Create livy session successfully with sessionId: {}, appId: {}, webUI: {}",
sessionInfo.id, sessionInfo.appId, sessionInfo.webUIAddress);
} else {
LOGGER.info("Create livy session successfully with sessionId: {}", this.sessionInfo.id);
}
}
protected abstract String extractAppId() throws LivyException;
protected abstract String extractWebUIAddress() throws LivyException;
public SessionInfo getSessionInfo() {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
return sharedInterpreter.getSessionInfo();
}
return sessionInfo;
}
public String getCodeType() {
if (getSessionKind().equalsIgnoreCase("pyspark3")) {
return "pyspark";
}
return getSessionKind();
}
@Override
public InterpreterResult interpret(String st, InterpreterContext context) {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
return sharedInterpreter.interpret(st, getCodeType(), context);
}
if (StringUtils.isEmpty(st)) {
return new InterpreterResult(InterpreterResult.Code.SUCCESS, "");
}
try {
return interpret(st, null, context.getParagraphId(), this.displayAppInfo, true);
} catch (LivyException e) {
LOGGER.error("Fail to interpret:" + st, e);
return new InterpreterResult(InterpreterResult.Code.ERROR,
InterpreterUtils.getMostRelevantMessage(e));
}
}
@Override
public List<InterpreterCompletion> completion(String buf, int cursor,
InterpreterContext interpreterContext) {
List<InterpreterCompletion> candidates = Collections.emptyList();
try {
candidates = callCompletion(new CompletionRequest(buf, getSessionKind(), cursor));
} catch (SessionNotFoundException e) {
LOGGER.warn("Livy session {} is expired. Will return empty list of candidates.",
sessionInfo.id);
} catch (LivyException le) {
logger.error("Failed to call code completions. Will return empty list of candidates", le);
}
return candidates;
}
private List<InterpreterCompletion> callCompletion(CompletionRequest req) throws LivyException {
List<InterpreterCompletion> candidates = new ArrayList<>();
try {
CompletionResponse resp = CompletionResponse.fromJson(
callRestAPI("/sessions/" + sessionInfo.id + "/completion", "POST", req.toJson()));
for (String candidate : resp.candidates) {
candidates.add(new InterpreterCompletion(candidate, candidate, StringUtils.EMPTY));
}
} catch (APINotFoundException e) {
logger.debug("completion api seems not to be available. (available from livy 0.5)", e);
}
return candidates;
}
@Override
public void cancel(InterpreterContext context) {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
sharedInterpreter.cancel(context);
return;
}
paragraphsToCancel.add(context.getParagraphId());
LOGGER.info("Added paragraph " + context.getParagraphId() + " for cancellation.");
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
@Override
public int getProgress(InterpreterContext context) {
if (sharedInterpreter != null && sharedInterpreter.isSupported()) {
return sharedInterpreter.getProgress(context);
}
if (livyVersion.isGetProgressSupported()) {
String paraId = context.getParagraphId();
Integer progress = paragraphId2StmtProgressMap.get(paraId);
return progress == null ? 0 : progress;
}
return 0;
}
private SessionInfo createSession(String user, String kind)
throws LivyException {
try {
Map<String, String> conf = new HashMap<>();
for (Map.Entry<Object, Object> entry : getProperties().entrySet()) {
if (entry.getKey().toString().startsWith("livy.spark.") &&
!entry.getValue().toString().isEmpty())
conf.put(entry.getKey().toString().substring(5), entry.getValue().toString());
}
CreateSessionRequest request = new CreateSessionRequest(kind,
user == null || user.equals("anonymous") ? null : user, conf);
SessionInfo sessionInfo = SessionInfo.fromJson(
callRestAPI("/sessions", "POST", request.toJson()));
long start = System.currentTimeMillis();
// pull the session status until it is idle or timeout
while (!sessionInfo.isReady()) {
if ((System.currentTimeMillis() - start) / 1000 > sessionCreationTimeout) {
String msg = "The creation of session " + sessionInfo.id + " is timeout within "
+ sessionCreationTimeout + " seconds, appId: " + sessionInfo.appId
+ ", log: " + sessionInfo.log;
throw new LivyException(msg);
}
Thread.sleep(pullStatusInterval);
sessionInfo = getSessionInfo(sessionInfo.id);
LOGGER.info("Session {} is in state {}, appId {}", sessionInfo.id, sessionInfo.state,
sessionInfo.appId);
if (sessionInfo.isFinished()) {
String msg = "Session " + sessionInfo.id + " is finished, appId: " + sessionInfo.appId
+ ", log: " + sessionInfo.log;
throw new LivyException(msg);
}
}
return sessionInfo;
} catch (Exception e) {
LOGGER.error("Error when creating livy session for user " + user, e);
throw new LivyException(e);
}
}
private SessionInfo getSessionInfo(int sessionId) throws LivyException {
return SessionInfo.fromJson(callRestAPI("/sessions/" + sessionId, "GET"));
}
public InterpreterResult interpret(String code,
String paragraphId,
boolean displayAppInfo,
boolean appendSessionExpired) throws LivyException {
return interpret(code, sharedInterpreter.isSupported() ? getSessionKind() : null,
paragraphId, displayAppInfo, appendSessionExpired);
}
public InterpreterResult interpret(String code,
String codeType,
String paragraphId,
boolean displayAppInfo,
boolean appendSessionExpired) throws LivyException {
StatementInfo stmtInfo = null;
boolean sessionExpired = false;
try {
try {
stmtInfo = executeStatement(new ExecuteRequest(code, codeType));
} catch (SessionNotFoundException e) {
LOGGER.warn("Livy session {} is expired, new session will be created.", sessionInfo.id);
sessionExpired = true;
// we don't want to create multiple sessions because it is possible to have multiple thread
// to call this method, like LivySparkSQLInterpreter which use ParallelScheduler. So we need
// to check session status again in this sync block
synchronized (this) {
if (isSessionExpired()) {
initLivySession();
}
}
stmtInfo = executeStatement(new ExecuteRequest(code, codeType));
}
// pull the statement status
while (!stmtInfo.isAvailable()) {
if (paragraphId != null && paragraphsToCancel.contains(paragraphId)) {
cancel(stmtInfo.id, paragraphId);
return new InterpreterResult(InterpreterResult.Code.ERROR, "Job is cancelled");
}
try {
Thread.sleep(pullStatusInterval);
} catch (InterruptedException e) {
LOGGER.error("InterruptedException when pulling statement status.", e);
throw new LivyException(e);
}
stmtInfo = getStatementInfo(stmtInfo.id);
if (paragraphId != null) {
paragraphId2StmtProgressMap.put(paragraphId, (int) (stmtInfo.progress * 100));
}
}
if (appendSessionExpired) {
return appendSessionExpire(getResultFromStatementInfo(stmtInfo, displayAppInfo),
sessionExpired);
} else {
return getResultFromStatementInfo(stmtInfo, displayAppInfo);
}
} finally {
if (paragraphId != null) {
paragraphId2StmtProgressMap.remove(paragraphId);
paragraphsToCancel.remove(paragraphId);
}
}
}
private void cancel(int id, String paragraphId) {
if (livyVersion.isCancelSupported()) {
try {
LOGGER.info("Cancelling statement " + id);
cancelStatement(id);
} catch (LivyException e) {
LOGGER.error("Fail to cancel statement " + id + " for paragraph " + paragraphId, e);
}
finally {
paragraphsToCancel.remove(paragraphId);
}
} else {
LOGGER.warn("cancel is not supported for this version of livy: " + livyVersion);
paragraphsToCancel.clear();
}
}
protected LivyVersion getLivyVersion() throws LivyException {
return new LivyVersion((LivyVersionResponse.fromJson(callRestAPI("/version", "GET")).version));
}
private boolean isSessionExpired() throws LivyException {
try {
getSessionInfo(sessionInfo.id);
return false;
} catch (SessionNotFoundException e) {
return true;
} catch (LivyException e) {
throw e;
}
}
private InterpreterResult appendSessionExpire(InterpreterResult result, boolean sessionExpired) {
if (sessionExpired) {
InterpreterResult result2 = new InterpreterResult(result.code());
result2.add(InterpreterResult.Type.HTML,
"<font color=\"red\">Previous livy session is expired, new livy session is created. " +
"Paragraphs that depend on this paragraph need to be re-executed!</font>");
for (InterpreterResultMessage message : result.message()) {
result2.add(message.getType(), message.getData());
}
return result2;
} else {
return result;
}
}
private InterpreterResult getResultFromStatementInfo(StatementInfo stmtInfo,
boolean displayAppInfo) {
if (stmtInfo.output != null && stmtInfo.output.isError()) {
InterpreterResult result = new InterpreterResult(InterpreterResult.Code.ERROR);
StringBuilder sb = new StringBuilder();
sb.append(stmtInfo.output.evalue);
// in case evalue doesn't have newline char
if (!stmtInfo.output.evalue.contains("\n"))
sb.append("\n");
if (stmtInfo.output.traceback != null) {
sb.append(StringUtils.join(stmtInfo.output.traceback));
}
result.add(sb.toString());
return result;
} else if (stmtInfo.isCancelled()) {
// corner case, output might be null if it is cancelled.
return new InterpreterResult(InterpreterResult.Code.ERROR, "Job is cancelled");
} else if (stmtInfo.output == null) {
// This case should never happen, just in case
return new InterpreterResult(InterpreterResult.Code.ERROR, "Empty output");
} else {
//TODO(zjffdu) support other types of data (like json, image and etc)
String result = stmtInfo.output.data.plain_text;
// check table magic result first
if (stmtInfo.output.data.application_livy_table_json != null) {
StringBuilder outputBuilder = new StringBuilder();
boolean notFirstColumn = false;
for (Map header : stmtInfo.output.data.application_livy_table_json.headers) {
if (notFirstColumn) {
outputBuilder.append("\t");
}
outputBuilder.append(header.get("name"));
notFirstColumn = true;
}
outputBuilder.append("\n");
for (List<Object> row : stmtInfo.output.data.application_livy_table_json.records) {
outputBuilder.append(StringUtils.join(row, "\t"));
outputBuilder.append("\n");
}
return new InterpreterResult(InterpreterResult.Code.SUCCESS,
InterpreterResult.Type.TABLE, outputBuilder.toString());
} else if (stmtInfo.output.data.image_png != null) {
return new InterpreterResult(InterpreterResult.Code.SUCCESS,
InterpreterResult.Type.IMG, (String) stmtInfo.output.data.image_png);
} else if (result != null) {
result = result.trim();
if (result.startsWith("<link")
|| result.startsWith("<script")
|| result.startsWith("<style")
|| result.startsWith("<div")) {
result = "%html " + result;
}
}
if (displayAppInfo) {
InterpreterResult interpreterResult = new InterpreterResult(InterpreterResult.Code.SUCCESS);
interpreterResult.add(result);
String appInfoHtml = "<hr/>Spark Application Id: " + sessionInfo.appId + "<br/>"
+ "Spark WebUI: <a href=\"" + sessionInfo.webUIAddress + "\">"
+ sessionInfo.webUIAddress + "</a>";
interpreterResult.add(InterpreterResult.Type.HTML, appInfoHtml);
return interpreterResult;
} else {
return new InterpreterResult(InterpreterResult.Code.SUCCESS, result);
}
}
}
private StatementInfo executeStatement(ExecuteRequest executeRequest)
throws LivyException {
return StatementInfo.fromJson(callRestAPI("/sessions/" + sessionInfo.id + "/statements", "POST",
executeRequest.toJson()));
}
private StatementInfo getStatementInfo(int statementId)
throws LivyException {
return StatementInfo.fromJson(
callRestAPI("/sessions/" + sessionInfo.id + "/statements/" + statementId, "GET"));
}
private void cancelStatement(int statementId) throws LivyException {
callRestAPI("/sessions/" + sessionInfo.id + "/statements/" + statementId + "/cancel", "POST");
}
private RestTemplate createRestTemplate() {
String keytabLocation = getProperty("zeppelin.livy.keytab");
String principal = getProperty("zeppelin.livy.principal");
boolean isSpnegoEnabled = StringUtils.isNotEmpty(keytabLocation) &&
StringUtils.isNotEmpty(principal);
HttpClient httpClient = null;
if (livyURL.startsWith("https:")) {
String keystoreFile = getProperty("zeppelin.livy.ssl.trustStore");
String password = getProperty("zeppelin.livy.ssl.trustStorePassword");
if (StringUtils.isBlank(keystoreFile)) {
throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
}
if (StringUtils.isBlank(password)) {
throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " +
"for livy ssl");
}
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(keystoreFile);
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(new FileInputStream(keystoreFile), password.toCharArray());
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(trustStore)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(csf);
RequestConfig reqConfig = new RequestConfig() {
@Override
public boolean isAuthenticationEnabled() {
return true;
}
};
httpClientBuilder.setDefaultRequestConfig(reqConfig);
Credentials credentials = new Credentials() {
@Override
public String getPassword() {
return null;
}
@Override
public Principal getUserPrincipal() {
return null;
}
};
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, credentials);
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
if (isSpnegoEnabled) {
Registry<AuthSchemeProvider> authSchemeProviderRegistry =
RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
.build();
httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeProviderRegistry);
}
httpClient = httpClientBuilder.build();
} catch (Exception e) {
throw new RuntimeException("Failed to create SSL HttpClient", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
LOGGER.error("Failed to close keystore file", e);
}
}
}
}
if (isSpnegoEnabled) {
if (httpClient == null) {
return new KerberosRestTemplate(keytabLocation, principal);
} else {
return new KerberosRestTemplate(keytabLocation, principal, httpClient);
}
}
if (httpClient == null) {
return new RestTemplate();
} else {
return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
}
}
private String callRestAPI(String targetURL, String method) throws LivyException {
return callRestAPI(targetURL, method, "");
}
private String callRestAPI(String targetURL, String method, String jsonData)
throws LivyException {
targetURL = livyURL + targetURL;
LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.add("X-Requested-By", "zeppelin");
for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
ResponseEntity<String> response = null;
try {
if (method.equals("POST")) {
HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
} else if (method.equals("GET")) {
HttpEntity<String> entity = new HttpEntity<>(headers);
response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
} else if (method.equals("DELETE")) {
HttpEntity<String> entity = new HttpEntity<>(headers);
response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
}
} catch (HttpClientErrorException e) {
response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
LOGGER.error(String.format("Error with %s StatusCode: %s",
response.getStatusCode().value(), e.getResponseBodyAsString()));
} catch (RestClientException e) {
// Exception happens when kerberos is enabled.
if (e.getCause() instanceof HttpClientErrorException) {
HttpClientErrorException cause = (HttpClientErrorException) e.getCause();
if (cause.getResponseBodyAsString().matches(SESSION_NOT_FOUND_PATTERN)) {
throw new SessionNotFoundException(cause.getResponseBodyAsString());
}
throw new LivyException(cause.getResponseBodyAsString() + "\n"
+ ExceptionUtils.getFullStackTrace(ExceptionUtils.getRootCause(e)));
}
if (e instanceof HttpServerErrorException) {
HttpServerErrorException errorException = (HttpServerErrorException) e;
String errorResponse = errorException.getResponseBodyAsString();
if (errorResponse.contains("Session is in state dead")) {
throw new LivyException("%html <font color=\"red\">Livy session is dead somehow, " +
"please check log to see why it is dead, and then restart livy interpreter</font>");
}
throw new LivyException(errorResponse, e);
}
throw new LivyException(e);
}
if (response == null) {
throw new LivyException("No http response returned");
}
LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(),
response.getBody());
if (response.getStatusCode().value() == 200
|| response.getStatusCode().value() == 201) {
return response.getBody();
} else if (response.getStatusCode().value() == 404) {
if (response.getBody().matches(SESSION_NOT_FOUND_PATTERN)) {
throw new SessionNotFoundException(response.getBody());
} else {
throw new APINotFoundException("No rest api found for " + targetURL +
", " + response.getStatusCode());
}
} else {
String responseString = response.getBody();
if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
return responseString;
}
throw new LivyException(String.format("Error with %s StatusCode: %s",
response.getStatusCode().value(), responseString));
}
}
private void closeSession(int sessionId) {
try {
callRestAPI("/sessions/" + sessionId, "DELETE");
} catch (Exception e) {
LOGGER.error(String.format("Error closing session for user with session ID: %s",
sessionId), e);
}
}
/*
* We create these POJO here to accommodate livy 0.3 which is not released yet. livy rest api has
* some changes from version to version. So we create these POJO in zeppelin side to accommodate
* incompatibility between versions. Later, when livy become more stable, we could just depend on
* livy client jar.
*/
private static class CreateSessionRequest {
public final String kind;
@SerializedName("proxyUser")
public final String user;
public final Map<String, String> conf;
public CreateSessionRequest(String kind, String user, Map<String, String> conf) {
this.kind = kind;
this.user = user;
this.conf = conf;
}
public String toJson() {
return gson.toJson(this);
}
}
/**
*
*/
public static class SessionInfo {
public final int id;
public String appId;
public String webUIAddress;
public final String owner;
public final String proxyUser;
public final String state;
public final String kind;
public final Map<String, String> appInfo;
public final List<String> log;
public SessionInfo(int id, String appId, String owner, String proxyUser, String state,
String kind, Map<String, String> appInfo, List<String> log) {
this.id = id;
this.appId = appId;
this.owner = owner;
this.proxyUser = proxyUser;
this.state = state;
this.kind = kind;
this.appInfo = appInfo;
this.log = log;
}
public boolean isReady() {
return state.equals("idle");
}
public boolean isFinished() {
return state.equals("error") || state.equals("dead") || state.equals("success");
}
public static SessionInfo fromJson(String json) {
return gson.fromJson(json, SessionInfo.class);
}
}
static class ExecuteRequest {
public final String code;
public final String kind;
public ExecuteRequest(String code, String kind) {
this.code = code;
this.kind = kind;
}
public String toJson() {
return gson.toJson(this);
}
}
private static class StatementInfo {
public Integer id;
public String state;
public double progress;
public StatementOutput output;
public StatementInfo() {
}
public static StatementInfo fromJson(String json) {
String right_json = "";
try {
gson.fromJson(json, StatementInfo.class);
right_json = json;
} catch (Exception e) {
if (json.contains("\"traceback\":{}")) {
LOGGER.debug("traceback type mismatch, replacing the mismatching part ");
right_json = json.replace("\"traceback\":{}", "\"traceback\":[]");
LOGGER.debug("new json string is {}", right_json);
}
}
return gson.fromJson(right_json, StatementInfo.class);
}
public boolean isAvailable() {
return state.equals("available") || state.equals("cancelled");
}
public boolean isCancelled() {
return state.equals("cancelled");
}
private static class StatementOutput {
public String status;
public String execution_count;
public Data data;
public String ename;
public String evalue;
public String[] traceback;
public TableMagic tableMagic;
public boolean isError() {
return status.equals("error");
}
public String toJson() {
return gson.toJson(this);
}
private static class Data {
@SerializedName("text/plain")
public String plain_text;
@SerializedName("image/png")
public String image_png;
@SerializedName("application/json")
public String application_json;
@SerializedName("application/vnd.livy.table.v1+json")
public TableMagic application_livy_table_json;
}
private static class TableMagic {
@SerializedName("headers")
List<Map> headers;
@SerializedName("data")
List<List> records;
}
}
}
static class CompletionRequest {
public final String code;
public final String kind;
public final int cursor;
public CompletionRequest(String code, String kind, int cursor) {
this.code = code;
this.kind = kind;
this.cursor = cursor;
}
public String toJson() {
return gson.toJson(this);
}
}
static class CompletionResponse {
public final String[] candidates;
public CompletionResponse(String[] candidates) {
this.candidates = candidates;
}
public static CompletionResponse fromJson(String json) {
return gson.fromJson(json, CompletionResponse.class);
}
}
private static class LivyVersionResponse {
public String url;
public String branch;
public String revision;
public String version;
public String date;
public String user;
public static LivyVersionResponse fromJson(String json) {
return gson.fromJson(json, LivyVersionResponse.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.camel.language.simple;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.camel.CamelAuthorizationException;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Expression;
import org.apache.camel.ExpressionIllegalSyntaxException;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.LanguageTestSupport;
import org.apache.camel.Predicate;
import org.apache.camel.component.bean.MethodNotFoundException;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.language.bean.RuntimeBeanExpressionException;
import org.apache.camel.language.simple.types.SimpleIllegalSyntaxException;
import org.apache.camel.language.simple.types.SimpleParserException;
import org.apache.camel.spi.Language;
/**
* @version
*/
public class SimpleTest extends LanguageTestSupport {
@Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry jndi = super.createRegistry();
jndi.bind("myAnimal", new Animal("Donkey", 17));
return jndi;
}
public void testSimpleExpressionOrPredicate() throws Exception {
Predicate predicate = SimpleLanguage.predicate("${header.bar} == 123");
assertTrue(predicate.matches(exchange));
predicate = SimpleLanguage.predicate("${header.bar} == 124");
assertFalse(predicate.matches(exchange));
Expression expression = SimpleLanguage.expression("${body}");
assertEquals("<hello id='m123'>world!</hello>", expression.evaluate(exchange, String.class));
expression = SimpleLanguage.simple("${body}");
assertEquals("<hello id='m123'>world!</hello>", expression.evaluate(exchange, String.class));
expression = SimpleLanguage.simple("${body}", String.class);
assertEquals("<hello id='m123'>world!</hello>", expression.evaluate(exchange, String.class));
expression = SimpleLanguage.simple("${header.bar} == 123", boolean.class);
assertEquals(Boolean.TRUE, expression.evaluate(exchange, Object.class));
expression = SimpleLanguage.simple("${header.bar} == 124", boolean.class);
assertEquals(Boolean.FALSE, expression.evaluate(exchange, Object.class));
expression = SimpleLanguage.simple("${header.bar} == 123", Boolean.class);
assertEquals(Boolean.TRUE, expression.evaluate(exchange, Object.class));
expression = SimpleLanguage.simple("${header.bar} == 124", Boolean.class);
assertEquals(Boolean.FALSE, expression.evaluate(exchange, Object.class));
}
public void testResultType() throws Exception {
assertEquals(123, SimpleLanguage.simple("${header.bar}", int.class).evaluate(exchange, Object.class));
assertEquals("123", SimpleLanguage.simple("${header.bar}", String.class).evaluate(exchange, Object.class));
// should not be possible
assertEquals(null, SimpleLanguage.simple("${header.bar}", Date.class).evaluate(exchange, Object.class));
assertEquals(null, SimpleLanguage.simple("${header.unknown}", String.class).evaluate(exchange, Object.class));
}
public void testRefExpression() throws Exception {
assertExpressionResultInstanceOf("ref:myAnimal", Animal.class);
assertExpressionResultInstanceOf("${ref:myAnimal}", Animal.class);
assertExpression("ref:myAnimal", "Donkey");
assertExpression("${ref:myAnimal}", "Donkey");
assertExpression("ref:unknown", null);
assertExpression("${ref:unknown}", null);
assertExpression("Hello ${ref:myAnimal}", "Hello Donkey");
assertExpression("Hello ${ref:unknown}", "Hello ");
}
public void testConstantExpression() throws Exception {
assertExpression("Hello World", "Hello World");
}
public void testNull() throws Exception {
assertNull(SimpleLanguage.simple("${null}").evaluate(exchange, Object.class));
}
public void testEmptyExpression() throws Exception {
assertExpression("", "");
assertExpression(" ", " ");
try {
assertExpression(null, null);
fail("Should have thrown exception");
} catch (IllegalArgumentException e) {
assertEquals("expression must be specified", e.getMessage());
}
assertPredicate("", false);
assertPredicate(" ", false);
try {
assertPredicate(null, false);
fail("Should have thrown exception");
} catch (IllegalArgumentException e) {
assertEquals("expression must be specified", e.getMessage());
}
}
public void testBodyExpression() throws Exception {
Expression exp = SimpleLanguage.simple("${body}");
assertNotNull(exp);
}
public void testBodyExpressionUsingAlternativeStartToken() throws Exception {
Expression exp = SimpleLanguage.simple("$simple{body}");
assertNotNull(exp);
}
public void testBodyExpressionNotStringType() throws Exception {
exchange.getIn().setBody(123);
Expression exp = SimpleLanguage.simple("${body}");
assertNotNull(exp);
Object val = exp.evaluate(exchange, Object.class);
assertIsInstanceOf(Integer.class, val);
assertEquals(123, val);
}
public void testSimpleExpressions() throws Exception {
assertExpression("exchangeId", exchange.getExchangeId());
assertExpression("id", exchange.getIn().getMessageId());
assertExpression("body", "<hello id='m123'>world!</hello>");
assertExpression("in.body", "<hello id='m123'>world!</hello>");
assertExpression("in.header.foo", "abc");
assertExpression("in.headers.foo", "abc");
assertExpression("header.foo", "abc");
assertExpression("headers.foo", "abc");
assertExpression("routeId", exchange.getFromRouteId());
exchange.setFromRouteId("myRouteId");
assertExpression("routeId", "myRouteId");
}
public void testTrimSimpleExpressions() throws Exception {
assertExpression(" \texchangeId\n".trim(), exchange.getExchangeId());
assertExpression("\nid\r".trim(), exchange.getIn().getMessageId());
assertExpression("\t\r body".trim(), "<hello id='m123'>world!</hello>");
assertExpression("\nin.body\r".trim(), "<hello id='m123'>world!</hello>");
}
public void testSimpleThreadName() throws Exception {
String name = Thread.currentThread().getName();
assertExpression("threadName", name);
assertExpression("The name is ${threadName}", "The name is " + name);
}
public void testSimpleOutExpressions() throws Exception {
exchange.getOut().setBody("Bye World");
exchange.getOut().setHeader("quote", "Camel rocks");
assertExpression("out.body", "Bye World");
assertExpression("out.header.quote", "Camel rocks");
assertExpression("out.headers.quote", "Camel rocks");
}
public void testSimplePropertyExpressions() throws Exception {
exchange.setProperty("medal", "gold");
assertExpression("property.medal", "gold");
}
public void testSimpleSystemPropertyExpressions() throws Exception {
System.setProperty("who", "I was here");
assertExpression("sys.who", "I was here");
}
public void testSimpleSystemEnvironmentExpressions() throws Exception {
String path = System.getenv("PATH");
if (path != null) {
assertExpression("sysenv.PATH", path);
}
}
public void testSimpleCamelId() throws Exception {
assertExpression("camelId", context.getName());
}
public void testOGNLBodyListAndMap() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("cool", "Camel rocks");
map.put("dude", "Hey dude");
map.put("code", 4321);
List<Map<String, Object>> lines = new ArrayList<Map<String, Object>>();
lines.add(map);
exchange.getIn().setBody(lines);
assertExpression("${in.body[0][cool]}", "Camel rocks");
assertExpression("${body[0][cool]}", "Camel rocks");
assertExpression("${in.body[0][code]}", 4321);
assertExpression("${body[0][code]}", 4321);
}
public void testOGNLCallReplace() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("cool", "Camel rocks");
map.put("dude", "Hey dude");
exchange.getIn().setHeaders(map);
assertExpression("${headers.cool.replaceAll(\"rocks\", \"is so cool\")}", "Camel is so cool");
}
public void testOGNLBodyListAndMapAndMethod() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("camel", new OrderLine(123, "Camel in Action"));
map.put("amq", new OrderLine(456, "ActiveMQ in Action"));
List<Map<String, Object>> lines = new ArrayList<Map<String, Object>>();
lines.add(map);
exchange.getIn().setBody(lines);
assertExpression("${in.body[0][camel].id}", 123);
assertExpression("${in.body[0][camel].name}", "Camel in Action");
assertExpression("${in.body[0][camel].getId}", 123);
assertExpression("${in.body[0][camel].getName}", "Camel in Action");
assertExpression("${body[0][camel].id}", 123);
assertExpression("${body[0][camel].name}", "Camel in Action");
assertExpression("${body[0][camel].getId}", 123);
assertExpression("${body[0][camel].getName}", "Camel in Action");
}
public void testOGNLPropertyList() throws Exception {
List<String> lines = new ArrayList<String>();
lines.add("Camel in Action");
lines.add("ActiveMQ in Action");
exchange.setProperty("wicket", lines);
assertExpression("${property.wicket[0]}", "Camel in Action");
assertExpression("${property.wicket[1]}", "ActiveMQ in Action");
try {
assertExpression("${property.wicket[2]}", "");
fail("Should have thrown an exception");
} catch (Exception e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertEquals("Index: 2, Size: 2", cause.getMessage());
}
assertExpression("${property.unknown[cool]}", null);
}
public void testOGNLPropertyLinesList() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
exchange.setProperty("wicket", lines);
assertExpression("${property.wicket[0].getId}", 123);
assertExpression("${property.wicket[1].getName}", "ActiveMQ in Action");
try {
assertExpression("${property.wicket[2]}", "");
fail("Should have thrown an exception");
} catch (Exception e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertEquals("Index: 2, Size: 2", cause.getMessage());
}
assertExpression("${property.unknown[cool]}", null);
}
public void testOGNLPropertyMap() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("cool", "Camel rocks");
map.put("dude", "Hey dude");
map.put("code", 4321);
exchange.setProperty("wicket", map);
assertExpression("${property.wicket[cool]}", "Camel rocks");
assertExpression("${property.wicket[dude]}", "Hey dude");
assertExpression("${property.wicket[unknown]}", null);
assertExpression("${property.wicket[code]}", 4321);
// no header named unknown
assertExpression("${property?.unknown[cool]}", null);
assertExpression("${property.unknown[cool]}", null);
}
public void testOGNLPropertyMapWithDot() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("this.code", "This code");
exchange.setProperty("wicket", map);
assertExpression("${property.wicket[this.code]}", "This code");
}
public void testOGNLPropertyMapNotMap() throws Exception {
try {
assertExpression("${property.foobar[bar]}", null);
fail("Should have thrown an exception");
} catch (RuntimeBeanExpressionException e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertEquals("Key: bar not found in bean: cba of type: java.lang.String using OGNL path [[bar]]", cause.getMessage());
}
}
public void testOGNLPropertyMapIllegalSyntax() throws Exception {
try {
assertExpression("${property.foobar[bar}", null);
fail("Should have thrown an exception");
} catch (ExpressionIllegalSyntaxException e) {
assertTrue(e.getMessage().startsWith("Valid syntax: ${property.OGNL} was: property.foobar[bar at location 0"));
}
}
public void testOGNLHeaderEmptyTest() throws Exception {
exchange.getIn().setHeader("beer", "");
assertPredicate("${header.beer} == ''", true);
assertPredicate("${header.beer} == \"\"", true);
assertPredicate("${header.beer} == ' '", false);
assertPredicate("${header.beer} == \" \"", false);
exchange.getIn().setHeader("beer", " ");
assertPredicate("${header.beer} == ''", false);
assertPredicate("${header.beer} == \"\"", false);
assertPredicate("${header.beer} == ' '", true);
assertPredicate("${header.beer} == \" \"", true);
assertPredicate("${header.beer.toString().trim()} == ''", true);
assertPredicate("${header.beer.toString().trim()} == \"\"", true);
exchange.getIn().setHeader("beer", " ");
assertPredicate("${header.beer.trim()} == ''", true);
assertPredicate("${header.beer.trim()} == \"\"", true);
}
public void testDateExpressions() throws Exception {
Calendar cal = Calendar.getInstance();
cal.set(1974, Calendar.APRIL, 20);
exchange.getIn().setHeader("birthday", cal.getTime());
assertExpression("date:header.birthday:yyyyMMdd", "19740420");
try {
assertExpression("date:yyyyMMdd", "19740420");
fail("Should thrown an exception");
} catch (SimpleParserException e) {
assertEquals("Valid syntax: ${date:command:pattern} was: date:yyyyMMdd", e.getMessage());
}
}
public void testDateAndTimeExpressions() throws Exception {
Calendar cal = Calendar.getInstance();
cal.set(1974, Calendar.APRIL, 20, 8, 55, 47);
cal.set(Calendar.MILLISECOND, 123);
exchange.getIn().setHeader("birthday", cal.getTime());
assertExpression("date:header.birthday:yyyy-MM-dd'T'HH:mm:ss:SSS", "1974-04-20T08:55:47:123");
}
public void testLanguagesInContext() throws Exception {
// evaluate so we know there is 1 language in the context
assertExpression("id", exchange.getIn().getMessageId());
assertEquals(1, context.getLanguageNames().size());
assertEquals("simple", context.getLanguageNames().get(0));
}
public void testComplexExpressions() throws Exception {
assertExpression("hey ${in.header.foo}", "hey abc");
assertExpression("hey ${in.header.foo}!", "hey abc!");
assertExpression("hey ${in.header.foo}-${in.header.foo}!", "hey abc-abc!");
assertExpression("hey ${in.header.foo}${in.header.foo}", "hey abcabc");
assertExpression("${in.header.foo}${in.header.foo}", "abcabc");
assertExpression("${in.header.foo}", "abc");
assertExpression("${in.header.foo}!", "abc!");
}
public void testComplexExpressionsUsingAlternativeStartToken() throws Exception {
assertExpression("hey $simple{in.header.foo}", "hey abc");
assertExpression("hey $simple{in.header.foo}!", "hey abc!");
assertExpression("hey $simple{in.header.foo}-$simple{in.header.foo}!", "hey abc-abc!");
assertExpression("hey $simple{in.header.foo}$simple{in.header.foo}", "hey abcabc");
assertExpression("$simple{in.header.foo}$simple{in.header.foo}", "abcabc");
assertExpression("$simple{in.header.foo}", "abc");
assertExpression("$simple{in.header.foo}!", "abc!");
}
public void testInvalidComplexExpression() throws Exception {
try {
assertExpression("hey ${foo", "bad expression!");
fail("Should have thrown an exception!");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(8, e.getIndex());
}
}
public void testPredicates() throws Exception {
assertPredicate("body");
assertPredicate("header.foo");
assertPredicate("header.madeUpHeader", false);
}
public void testExceptionMessage() throws Exception {
exchange.setException(new IllegalArgumentException("Just testing"));
assertExpression("exception.message", "Just testing");
assertExpression("Hello ${exception.message} World", "Hello Just testing World");
}
public void testExceptionStacktrace() throws Exception {
exchange.setException(new IllegalArgumentException("Just testing"));
String out = SimpleLanguage.simple("exception.stacktrace").evaluate(exchange, String.class);
assertNotNull(out);
assertTrue(out.startsWith("java.lang.IllegalArgumentException: Just testing"));
assertTrue(out.contains("at org.apache.camel.language."));
}
public void testException() throws Exception {
exchange.setException(new IllegalArgumentException("Just testing"));
Exception out = SimpleLanguage.simple("exception").evaluate(exchange, Exception.class);
assertNotNull(out);
assertIsInstanceOf(IllegalArgumentException.class, out);
assertEquals("Just testing", out.getMessage());
}
public void testBodyAs() throws Exception {
assertExpression("${bodyAs(String)}", "<hello id='m123'>world!</hello>");
assertExpression("${bodyAs('String')}", "<hello id='m123'>world!</hello>");
exchange.getIn().setBody(null);
assertExpression("${bodyAs('String')}", null);
exchange.getIn().setBody(456);
assertExpression("${bodyAs(Integer)}", 456);
assertExpression("${bodyAs(int)}", 456);
assertExpression("${bodyAs('int')}", 456);
try {
assertExpression("${bodyAs(XXX)}", 456);
fail("Should have thrown an exception");
} catch (CamelExecutionException e) {
assertIsInstanceOf(ClassNotFoundException.class, e.getCause());
}
}
public void testMandatoryBodyAs() throws Exception {
assertExpression("${mandatoryBodyAs(String)}", "<hello id='m123'>world!</hello>");
assertExpression("${mandatoryBodyAs('String')}", "<hello id='m123'>world!</hello>");
exchange.getIn().setBody(null);
try {
assertExpression("${mandatoryBodyAs('String')}", "");
fail("Should have thrown exception");
} catch (CamelExecutionException e) {
assertIsInstanceOf(InvalidPayloadException.class, e.getCause());
}
exchange.getIn().setBody(456);
assertExpression("${mandatoryBodyAs(Integer)}", 456);
assertExpression("${mandatoryBodyAs(int)}", 456);
assertExpression("${mandatoryBodyAs('int')}", 456);
try {
assertExpression("${mandatoryBodyAs(XXX)}", 456);
fail("Should have thrown an exception");
} catch (CamelExecutionException e) {
assertIsInstanceOf(ClassNotFoundException.class, e.getCause());
}
}
public void testHeaderEmptyBody() throws Exception {
// set an empty body
exchange.getIn().setBody(null);
assertExpression("header.foo", "abc");
assertExpression("headers.foo", "abc");
assertExpression("in.header.foo", "abc");
assertExpression("in.headers.foo", "abc");
assertExpression("${header.foo}", "abc");
assertExpression("${headers.foo}", "abc");
assertExpression("${in.header.foo}", "abc");
assertExpression("${in.headers.foo}", "abc");
}
public void testHeadersWithBracket() throws Exception {
assertExpression("headers[foo]", "abc");
assertExpression("${headers[foo]}", "abc");
assertExpression("${in.headers[foo]}", "abc");
}
public void testIsInstanceOfEmptyBody() throws Exception {
// set an empty body
exchange.getIn().setBody(null);
try {
assertPredicate("${body} is null", false);
fail("Should have thrown an exception");
} catch (SimpleIllegalSyntaxException e) {
assertEquals(11, e.getIndex());
}
}
public void testHeaders() throws Exception {
Map<String, Object> headers = exchange.getIn().getHeaders();
assertEquals(2, headers.size());
assertExpression("headers", headers);
assertExpression("${headers}", headers);
assertExpression("in.headers", headers);
assertExpression("${in.headers}", headers);
}
public void testHeaderKeyWithSpace() throws Exception {
Map<String, Object> headers = exchange.getIn().getHeaders();
headers.put("some key", "Some Value");
assertEquals(3, headers.size());
assertExpression("${headerAs(foo,String)}", "abc");
assertExpression("${headerAs(some key,String)}", "Some Value");
assertExpression("${headerAs('some key',String)}", "Some Value");
assertExpression("${header[foo]}", "abc");
assertExpression("${header[some key]}", "Some Value");
assertExpression("${header['some key']}", "Some Value");
assertExpression("${headers[foo]}", "abc");
assertExpression("${headers[some key]}", "Some Value");
assertExpression("${headers['some key']}", "Some Value");
}
public void testHeaderAs() throws Exception {
assertExpression("${headerAs(foo,String)}", "abc");
assertExpression("${headerAs(bar,int)}", 123);
assertExpression("${headerAs(bar, int)}", 123);
assertExpression("${headerAs('bar', int)}", 123);
assertExpression("${headerAs('bar','int')}", 123);
assertExpression("${headerAs('bar','Integer')}", 123);
assertExpression("${headerAs('bar',\"int\")}", 123);
assertExpression("${headerAs(bar,String)}", "123");
assertExpression("${headerAs(unknown,String)}", null);
try {
assertExpression("${headerAs(unknown String)}", null);
fail("Should have thrown an exception");
} catch (ExpressionIllegalSyntaxException e) {
assertTrue(e.getMessage().startsWith("Valid syntax: ${headerAs(key, type)} was: headerAs(unknown String)"));
}
try {
assertExpression("${headerAs(bar,XXX)}", 123);
fail("Should have thrown an exception");
} catch (CamelExecutionException e) {
assertIsInstanceOf(ClassNotFoundException.class, e.getCause());
}
}
public void testIllegalSyntax() throws Exception {
try {
assertExpression("hey ${xxx} how are you?", "");
fail("Should have thrown an exception");
} catch (ExpressionIllegalSyntaxException e) {
assertTrue(e.getMessage().startsWith("Unknown function: xxx at location 4"));
}
try {
assertExpression("${xxx}", "");
fail("Should have thrown an exception");
} catch (ExpressionIllegalSyntaxException e) {
assertTrue(e.getMessage().startsWith("Unknown function: xxx at location 0"));
}
try {
assertExpression("${bodyAs(xxx}", "");
fail("Should have thrown an exception");
} catch (ExpressionIllegalSyntaxException e) {
assertTrue(e.getMessage().startsWith("Valid syntax: ${bodyAs(type)} was: bodyAs(xxx"));
}
}
public void testOGNLHeaderList() throws Exception {
List<String> lines = new ArrayList<String>();
lines.add("Camel in Action");
lines.add("ActiveMQ in Action");
exchange.getIn().setHeader("wicket", lines);
assertExpression("${header.wicket[0]}", "Camel in Action");
assertExpression("${header.wicket[1]}", "ActiveMQ in Action");
try {
assertExpression("${header.wicket[2]}", "");
fail("Should have thrown an exception");
} catch (Exception e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertEquals("Index: 2, Size: 2", cause.getMessage());
}
assertExpression("${header.unknown[cool]}", null);
}
public void testOGNLHeaderLinesList() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
exchange.getIn().setHeader("wicket", lines);
assertExpression("${header.wicket[0].getId}", 123);
assertExpression("${header.wicket[1].getName}", "ActiveMQ in Action");
try {
assertExpression("${header.wicket[2]}", "");
fail("Should have thrown an exception");
} catch (Exception e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertEquals("Index: 2, Size: 2", cause.getMessage());
}
assertExpression("${header.unknown[cool]}", null);
}
public void testOGNLHeaderMap() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("cool", "Camel rocks");
map.put("dude", "Hey dude");
map.put("code", 4321);
exchange.getIn().setHeader("wicket", map);
assertExpression("${header.wicket[cool]}", "Camel rocks");
assertExpression("${header.wicket[dude]}", "Hey dude");
assertExpression("${header.wicket[unknown]}", null);
assertExpression("${header.wicket[code]}", 4321);
// no header named unknown
assertExpression("${header?.unknown[cool]}", null);
assertExpression("${header.unknown[cool]}", null);
}
public void testOGNLHeaderMapWithDot() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("this.code", "This code");
exchange.getIn().setHeader("wicket", map);
assertExpression("${header.wicket[this.code]}", "This code");
}
public void testOGNLHeaderMapNotMap() throws Exception {
try {
assertExpression("${header.foo[bar]}", null);
fail("Should have thrown an exception");
} catch (RuntimeBeanExpressionException e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertEquals("Key: bar not found in bean: abc of type: java.lang.String using OGNL path [[bar]]", cause.getMessage());
}
}
public void testOGNLHeaderMapIllegalSyntax() throws Exception {
try {
assertExpression("${header.foo[bar}", null);
fail("Should have thrown an exception");
} catch (ExpressionIllegalSyntaxException e) {
assertTrue(e.getMessage().startsWith("Valid syntax: ${header.name[key]} was: header.foo[bar"));
}
}
public void testBodyOGNLAsMap() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("foo", "Camel");
map.put("bar", 6);
exchange.getIn().setBody(map);
assertExpression("${in.body[foo]}", "Camel");
assertExpression("${in.body[bar]}", 6);
}
public void testBodyOGNLAsMapWithDot() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("foo.bar", "Camel");
exchange.getIn().setBody(map);
assertExpression("${in.body[foo.bar]}", "Camel");
}
public void testBodyOGNLAsMapShorthand() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("foo", "Camel");
map.put("bar", 6);
exchange.getIn().setBody(map);
assertExpression("${body[foo]}", "Camel");
assertExpression("${body[bar]}", 6);
}
public void testBodyOGNLSimple() throws Exception {
Animal camel = new Animal("Camel", 6);
exchange.getIn().setBody(camel);
assertExpression("${in.body.getName}", "Camel");
assertExpression("${in.body.getAge}", 6);
}
public void testExceptionOGNLSimple() throws Exception {
exchange.getIn().setHeader(Exchange.AUTHENTICATION_FAILURE_POLICY_ID, "myPolicy");
exchange.setProperty(Exchange.EXCEPTION_CAUGHT, new CamelAuthorizationException("The camel authorization exception", exchange));
assertExpression("${exception.getPolicyId}", "myPolicy");
}
public void testBodyOGNLSimpleShorthand() throws Exception {
Animal camel = new Animal("Camel", 6);
exchange.getIn().setBody(camel);
assertExpression("${in.body.name}", "Camel");
assertExpression("${in.body.age}", 6);
}
public void testBodyOGNLSimpleOperator() throws Exception {
Animal tiger = new Animal("Tony the Tiger", 13);
Animal camel = new Animal("Camel", 6);
camel.setFriend(tiger);
exchange.getIn().setBody(camel);
assertPredicate("${in.body.getName} contains 'Camel'", true);
assertPredicate("${in.body.getName} contains 'Tiger'", false);
assertPredicate("${in.body.getAge} < 10", true);
assertPredicate("${in.body.getAge} > 10", false);
assertPredicate("${in.body.getAge} <= '6'", true);
assertPredicate("${in.body.getAge} > '6'", false);
assertPredicate("${in.body.getAge} < ${body.getFriend.getAge}", true);
assertPredicate("${in.body.getFriend.isDangerous} == true", true);
}
public void testBodyOGNLSimpleOperatorShorthand() throws Exception {
Animal tiger = new Animal("Tony the Tiger", 13);
Animal camel = new Animal("Camel", 6);
camel.setFriend(tiger);
exchange.getIn().setBody(camel);
assertPredicate("${in.body.name} contains 'Camel'", true);
assertPredicate("${in.body.name} contains 'Tiger'", false);
assertPredicate("${in.body.age} < 10", true);
assertPredicate("${in.body.age} > 10", false);
assertPredicate("${in.body.age} <= '6'", true);
assertPredicate("${in.body.age} > '6'", false);
assertPredicate("${in.body.age} < ${body.friend.age}", true);
assertPredicate("${in.body.friend.dangerous} == true", true);
}
public void testBodyOGNLNested() throws Exception {
Animal tiger = new Animal("Tony the Tiger", 13);
Animal camel = new Animal("Camel", 6);
camel.setFriend(tiger);
exchange.getIn().setBody(camel);
assertExpression("${in.body.getName}", "Camel");
assertExpression("${in.body.getAge}", 6);
assertExpression("${in.body.getFriend.getName}", "Tony the Tiger");
assertExpression("${in.body.getFriend.getAge}", "13");
}
public void testBodyOGNLNestedShorthand() throws Exception {
Animal tiger = new Animal("Tony the Tiger", 13);
Animal camel = new Animal("Camel", 6);
camel.setFriend(tiger);
exchange.getIn().setBody(camel);
assertExpression("${in.body.name}", "Camel");
assertExpression("${in.body.age}", 6);
assertExpression("${in.body.friend.name}", "Tony the Tiger");
assertExpression("${in.body.friend.age}", "13");
}
public void testBodyOGNLOrderList() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
Order order = new Order(lines);
exchange.getIn().setBody(order);
assertExpression("${in.body.getLines[0].getId}", 123);
assertExpression("${in.body.getLines[0].getName}", "Camel in Action");
assertExpression("${in.body.getLines[1].getId}", 456);
assertExpression("${in.body.getLines[1].getName}", "ActiveMQ in Action");
assertExpression("${in.body.getLines[last].getId}", 456);
assertExpression("${in.body.getLines[last].getName}", "ActiveMQ in Action");
assertExpression("${in.body.getLines[last-1].getId}", 123);
assertExpression("${in.body.getLines[last-1].getName}", "Camel in Action");
}
public void testBodyOGNLOrderListShorthand() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
Order order = new Order(lines);
exchange.getIn().setBody(order);
assertExpression("${in.body.lines[0].id}", 123);
assertExpression("${in.body.lines[0].name}", "Camel in Action");
assertExpression("${in.body.lines[1].id}", 456);
assertExpression("${in.body.lines[1].name}", "ActiveMQ in Action");
assertExpression("${in.body.lines[last].id}", 456);
assertExpression("${in.body.lines[last].name}", "ActiveMQ in Action");
assertExpression("${in.body.lines[last-1].id}", 123);
assertExpression("${in.body.lines[last-1].name}", "Camel in Action");
assertExpression("${in.body.lines.size}", 2);
}
public void testBodyOGNLListMap() throws Exception {
List<Map<String, String>> grid = new ArrayList<Map<String, String>>();
Map<String, String> cells = new LinkedHashMap<String, String>();
cells.put("ABC", "123");
cells.put("DEF", "456");
grid.add(cells);
Map<String, String> cells2 = new LinkedHashMap<String, String>();
cells2.put("HIJ", "789");
grid.add(cells2);
exchange.getIn().setBody(grid);
assertExpression("${in.body[0][ABC]}", "123");
assertExpression("${in.body[0][DEF]}", "456");
assertExpression("${in.body[0]['ABC']}", "123");
assertExpression("${in.body[0]['DEF']}", "456");
assertExpression("${in.body[1][HIJ]}", "789");
assertExpression("${in.body[1]['HIJ']}", "789");
}
public void testBodyOGNLList() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
exchange.getIn().setBody(lines);
assertExpression("${in.body[0].getId}", 123);
assertExpression("${in.body[0].getName}", "Camel in Action");
assertExpression("${in.body[1].getId}", 456);
assertExpression("${in.body[1].getName}", "ActiveMQ in Action");
}
public void testBodyOGNLListShorthand() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
exchange.getIn().setBody(lines);
assertExpression("${in.body[0].id}", 123);
assertExpression("${in.body[0].name}", "Camel in Action");
assertExpression("${in.body[1].id}", 456);
assertExpression("${in.body[1].name}", "ActiveMQ in Action");
}
public void testBodyOGNLArray() throws Exception {
OrderLine[] lines = new OrderLine[2];
lines[0] = new OrderLine(123, "Camel in Action");
lines[1] = new OrderLine(456, "ActiveMQ in Action");
exchange.getIn().setBody(lines);
assertExpression("${in.body[0].getId}", 123);
assertExpression("${in.body[0].getName}", "Camel in Action");
assertExpression("${in.body[1].getId}", 456);
assertExpression("${in.body[1].getName}", "ActiveMQ in Action");
}
public void testBodyOGNLArrayShorthand() throws Exception {
OrderLine[] lines = new OrderLine[2];
lines[0] = new OrderLine(123, "Camel in Action");
lines[1] = new OrderLine(456, "ActiveMQ in Action");
exchange.getIn().setBody(lines);
assertExpression("${in.body[0].id}", 123);
assertExpression("${in.body[0].name}", "Camel in Action");
assertExpression("${in.body[1].id}", 456);
assertExpression("${in.body[1].name}", "ActiveMQ in Action");
}
public void testBodyOGNLOrderListOutOfBounds() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
Order order = new Order(lines);
exchange.getIn().setBody(order);
try {
assertExpression("${in.body.getLines[3].getId}", 123);
fail("Should have thrown an exception");
} catch (RuntimeBeanExpressionException e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertTrue(cause.getMessage().startsWith("Index: 3, Size: 2 out of bounds with List from bean"));
}
try {
assertExpression("${in.body.getLines[last-2].getId}", 123);
fail("Should have thrown an exception");
} catch (RuntimeBeanExpressionException e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertTrue(cause.getMessage().startsWith("Index: -1, Size: 2 out of bounds with List from bean"));
}
try {
assertExpression("${in.body.getLines[last - XXX].getId}", 123);
fail("Should have thrown an exception");
} catch (RuntimeBeanExpressionException e) {
ExpressionIllegalSyntaxException cause = assertIsInstanceOf(ExpressionIllegalSyntaxException.class, e.getCause());
assertEquals("last - XXX", cause.getExpression());
}
}
public void testBodyOGNLOrderListOutOfBoundsShorthand() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
Order order = new Order(lines);
exchange.getIn().setBody(order);
try {
assertExpression("${in.body.lines[3].id}", 123);
fail("Should have thrown an exception");
} catch (RuntimeBeanExpressionException e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertTrue(cause.getMessage().startsWith("Index: 3, Size: 2 out of bounds with List from bean"));
}
try {
assertExpression("${in.body.lines[last - 2].id}", 123);
fail("Should have thrown an exception");
} catch (RuntimeBeanExpressionException e) {
IndexOutOfBoundsException cause = assertIsInstanceOf(IndexOutOfBoundsException.class, e.getCause());
assertTrue(cause.getMessage().startsWith("Index: -1, Size: 2 out of bounds with List from bean"));
}
try {
assertExpression("${in.body.lines[last - XXX].id}", 123);
fail("Should have thrown an exception");
} catch (RuntimeBeanExpressionException e) {
ExpressionIllegalSyntaxException cause = assertIsInstanceOf(ExpressionIllegalSyntaxException.class, e.getCause());
assertEquals("last - XXX", cause.getExpression());
}
}
public void testBodyOGNLOrderListOutOfBoundsWithNullSafe() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
Order order = new Order(lines);
exchange.getIn().setBody(order);
assertExpression("${in.body?.getLines[3].getId}", null);
}
public void testBodyOGNLOrderListOutOfBoundsWithNullSafeShorthand() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
Order order = new Order(lines);
exchange.getIn().setBody(order);
assertExpression("${in.body?.lines[3].id}", null);
}
public void testBodyOGNLOrderListNoMethodNameWithNullSafe() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
Order order = new Order(lines);
exchange.getIn().setBody(order);
try {
assertExpression("${in.body.getLines[0]?.getRating}", "");
fail("Should have thrown exception");
} catch (RuntimeBeanExpressionException e) {
MethodNotFoundException cause = assertIsInstanceOf(MethodNotFoundException.class, e.getCause().getCause());
assertEquals("getRating", cause.getMethodName());
}
}
public void testBodyOGNLOrderListNoMethodNameWithNullSafeShorthand() throws Exception {
List<OrderLine> lines = new ArrayList<OrderLine>();
lines.add(new OrderLine(123, "Camel in Action"));
lines.add(new OrderLine(456, "ActiveMQ in Action"));
Order order = new Order(lines);
exchange.getIn().setBody(order);
try {
assertExpression("${in.body.lines[0]?.rating}", "");
fail("Should have thrown exception");
} catch (RuntimeBeanExpressionException e) {
MethodNotFoundException cause = assertIsInstanceOf(MethodNotFoundException.class, e.getCause().getCause());
assertEquals("rating", cause.getMethodName());
}
}
public void testBodyOGNLNullSafeToAvoidNPE() throws Exception {
Animal tiger = new Animal("Tony the Tiger", 13);
Animal camel = new Animal("Camel", 6);
camel.setFriend(tiger);
exchange.getIn().setBody(camel);
assertExpression("${in.body.getName}", "Camel");
assertExpression("${in.body.getAge}", 6);
assertExpression("${in.body.getFriend.getName}", "Tony the Tiger");
assertExpression("${in.body.getFriend.getAge}", "13");
// using null safe to avoid the NPE
assertExpression("${in.body.getFriend?.getFriend.getName}", null);
try {
// without null safe we get an NPE
assertExpression("${in.body.getFriend.getFriend.getName}", "");
fail("Should have thrown exception");
} catch (RuntimeBeanExpressionException e) {
assertEquals("Failed to invoke method: .getFriend.getFriend.getName on null due to: java.lang.NullPointerException", e.getMessage());
assertIsInstanceOf(NullPointerException.class, e.getCause());
}
}
public void testBodyOGNLNullSafeToAvoidNPEShorthand() throws Exception {
Animal tiger = new Animal("Tony the Tiger", 13);
Animal camel = new Animal("Camel", 6);
camel.setFriend(tiger);
exchange.getIn().setBody(camel);
assertExpression("${in.body.name}", "Camel");
assertExpression("${in.body.age}", 6);
// just to mix it a bit
assertExpression("${in.body.friend.getName}", "Tony the Tiger");
assertExpression("${in.body.getFriend.age}", "13");
// using null safe to avoid the NPE
assertExpression("${in.body.friend?.friend.name}", null);
try {
// without null safe we get an NPE
assertExpression("${in.body.friend.friend.name}", "");
fail("Should have thrown exception");
} catch (RuntimeBeanExpressionException e) {
assertEquals("Failed to invoke method: .friend.friend.name on null due to: java.lang.NullPointerException", e.getMessage());
assertIsInstanceOf(NullPointerException.class, e.getCause());
}
}
public void testBodyOGNLReentrant() throws Exception {
Animal camel = new Animal("Camel", 6);
Animal tiger = new Animal("Tony the Tiger", 13);
Animal elephant = new Animal("Big Ella", 48);
camel.setFriend(tiger);
tiger.setFriend(elephant);
elephant.setFriend(camel);
exchange.getIn().setBody(camel);
assertExpression("${body.getFriend.getFriend.getFriend.getName}", "Camel");
assertExpression("${body.getFriend.getFriend.getFriend.getFriend.getName}", "Tony the Tiger");
assertExpression("${body.getFriend.getFriend.getFriend.getFriend.getFriend.getName}", "Big Ella");
}
public void testBodyOGNLReentrantShorthand() throws Exception {
Animal camel = new Animal("Camel", 6);
Animal tiger = new Animal("Tony the Tiger", 13);
Animal elephant = new Animal("Big Ella", 48);
camel.setFriend(tiger);
tiger.setFriend(elephant);
elephant.setFriend(camel);
exchange.getIn().setBody(camel);
assertExpression("${body.friend.friend.friend.name}", "Camel");
assertExpression("${body.friend.friend.friend.friend.name}", "Tony the Tiger");
assertExpression("${body.friend.friend.friend.friend.friend.name}", "Big Ella");
}
public void testBodyOGNLBoolean() throws Exception {
Animal tiger = new Animal("Tony the Tiger", 13);
exchange.getIn().setBody(tiger);
assertExpression("${body.isDangerous}", "true");
assertExpression("${body.dangerous}", "true");
Animal camel = new Animal("Camel", 6);
exchange.getIn().setBody(camel);
assertExpression("${body.isDangerous}", "false");
assertExpression("${body.dangerous}", "false");
}
public void testBodyOgnlOnString() throws Exception {
exchange.getIn().setBody("Camel");
assertExpression("${body.substring(2)}", "mel");
assertExpression("${body.substring(2, 4)}", "me");
assertExpression("${body.length()}", 5);
assertExpression("${body.toUpperCase()}", "CAMEL");
assertExpression("${body.toUpperCase()}", "CAMEL");
assertExpression("${body.toUpperCase().substring(2)}", "MEL");
assertExpression("${body.toLowerCase().length()}", 5);
}
public void testBodyOgnlOnStringWithOgnlParams() throws Exception {
exchange.getIn().setBody("Camel");
exchange.getIn().setHeader("max", 4);
exchange.getIn().setHeader("min", 2);
assertExpression("${body.substring(${header.min}, ${header.max})}", "me");
}
public void testHeaderOgnlOnStringWithOgnlParams() throws Exception {
exchange.getIn().setBody(null);
exchange.getIn().setHeader("name", "Camel");
exchange.getIn().setHeader("max", 4);
exchange.getIn().setHeader("min", 2);
assertExpression("${header.name.substring(${header.min}, ${header.max})}", "me");
}
public void testCamelContextStartRoute() throws Exception {
exchange.getIn().setBody(null);
assertExpression("${camelContext.startRoute('foo')}", null);
}
public void testBodyOgnlReplace() throws Exception {
exchange.getIn().setBody("Kamel is a cool Kamel");
assertExpression("${body.replace(\"Kamel\", \"Camel\")}", "Camel is a cool Camel");
}
public void testBodyOgnlReplaceEscapedChar() throws Exception {
exchange.getIn().setBody("foo$bar$baz");
assertExpression("${body.replace('$', '-')}", "foo-bar-baz");
}
public void testBodyOgnlReplaceEscapedBackslashChar() throws Exception {
exchange.getIn().setBody("foo\\bar\\baz");
assertExpression("${body.replace('\\', '\\\\')}", "foo\\\\bar\\\\baz");
}
public void testBodyOgnlReplaceFirst() throws Exception {
exchange.getIn().setBody("http:camel.apache.org");
assertExpression("${body.replaceFirst('http:', 'http4:')}", "http4:camel.apache.org");
assertExpression("${body.replaceFirst('http:', '')}", "camel.apache.org");
assertExpression("${body.replaceFirst('http:', ' ')}", " camel.apache.org");
assertExpression("${body.replaceFirst('http:', ' ')}", " camel.apache.org");
assertExpression("${body.replaceFirst('http:',' ')}", " camel.apache.org");
}
public void testBodyOgnlReplaceSingleQuoteInDouble() throws Exception {
exchange.getIn().setBody("Hello O'Conner");
assertExpression("${body.replace(\"O'C\", \"OC\")}", "Hello OConner");
assertExpression("${body.replace(\"O'C\", \"O C\")}", "Hello O Conner");
assertExpression("${body.replace(\"O'C\", \"O-C\")}", "Hello O-Conner");
assertExpression("${body.replace(\"O'C\", \"O''C\")}", "Hello O''Conner");
assertExpression("${body.replace(\"O'C\", \"O\n'C\")}", "Hello O\n'Conner");
}
public void testBodyOgnlSpaces() throws Exception {
exchange.getIn().setBody("Hello World");
// no quotes, which is discouraged to use
assertExpression("${body.compareTo(Hello World)}", 0);
assertExpression("${body.compareTo('Hello World')}", 0);
assertExpression("${body.compareTo(${body})}", 0);
assertExpression("${body.compareTo('foo')}", "Hello World".compareTo("foo"));
assertExpression("${body.compareTo( 'Hello World' )}", 0);
assertExpression("${body.compareTo( ${body} )}", 0);
assertExpression("${body.compareTo( 'foo' )}", "Hello World".compareTo("foo"));
}
public void testClassSimpleName() throws Exception {
Animal tiger = new Animal("Tony the Tiger", 13);
exchange.getIn().setBody(tiger);
assertExpression("${body.getClass().getSimpleName()}", "Animal");
assertExpression("${body.getClass.getSimpleName}", "Animal");
assertExpression("${body.class.simpleName}", "Animal");
}
public void testExceptionClassSimpleName() throws Exception {
Animal tiger = new Animal("Tony the Tiger", 13);
exchange.getIn().setBody(tiger);
Exception cause = new IllegalArgumentException("Forced");
exchange.setException(cause);
assertExpression("${exception.getClass().getSimpleName()}", "IllegalArgumentException");
assertExpression("${exception.getClass.getSimpleName}", "IllegalArgumentException");
assertExpression("${exception.class.simpleName}", "IllegalArgumentException");
}
public void testSlashBeforeHeader() throws Exception {
assertExpression("foo/${header.foo}", "foo/abc");
assertExpression("foo\\${header.foo}", "foo\\abc");
}
public void testJSonLike() throws Exception {
exchange.getIn().setBody("Something");
assertExpression("{\n\"data\": \"${body}\"\n}", "{\n\"data\": \"Something\"\n}");
}
public void testFunctionEnds() throws Exception {
exchange.getIn().setBody("Something");
assertExpression("{{", "{{");
assertExpression("}}", "}}");
assertExpression("{{}}", "{{}}");
assertExpression("{{foo}}", "{{foo}}");
assertExpression("{{${body}}}", "{{Something}}");
assertExpression("{{${body}-${body}}}", "{{Something-Something}}");
}
public void testEscape() throws Exception {
exchange.getIn().setBody("Something");
// slash foo
assertExpression("\\foo", "\\foo");
assertExpression("\\n${body}", "\nSomething");
assertExpression("\\t${body}", "\tSomething");
assertExpression("\\r${body}", "\rSomething");
assertExpression("\\n\\r${body}", "\n\rSomething");
assertExpression("\\n${body}\\n", "\nSomething\n");
assertExpression("\\t${body}\\t", "\tSomething\t");
assertExpression("\\r${body}\\r", "\rSomething\r");
assertExpression("\\n\\r${body}\\n\\r", "\n\rSomething\n\r");
assertExpression("$${body}", "$Something");
}
public void testCamelContextOGNL() throws Exception {
assertExpression("${camelContext.getName()}", context.getName());
assertExpression("${camelContext.version}", context.getVersion());
}
public void testTypeConstant() throws Exception {
assertExpression("${type:org.apache.camel.Exchange.FILE_NAME}", Exchange.FILE_NAME);
assertExpression("${type:org.apache.camel.ExchangePattern.InOut}", ExchangePattern.InOut);
// non existing fields
assertExpression("${type:org.apache.camel.ExchangePattern.}", null);
assertExpression("${type:org.apache.camel.ExchangePattern.UNKNOWN}", null);
}
public void testStringArrayLength() throws Exception {
exchange.getIn().setBody(new String[]{"foo", "bar"});
assertExpression("${body[0]}", "foo");
assertExpression("${body[1]}", "bar");
assertExpression("${body.length}", 2);
exchange.getIn().setBody(new String[]{"foo", "bar", "beer"});
assertExpression("${body.length}", 3);
}
public void testSimpleMapBoolean() throws Exception {
Map map = new HashMap();
exchange.getIn().setBody(map);
map.put("isCredit", true);
assertPredicate("${body[isCredit]} == true", true);
assertPredicate("${body[isCredit]} == false", false);
assertPredicate("${body['isCredit']} == true", true);
assertPredicate("${body['isCredit']} == false", false);
// wrong case
assertPredicate("${body['IsCredit']} == true", false);
map.put("isCredit", false);
assertPredicate("${body[isCredit]} == true", false);
assertPredicate("${body[isCredit]} == false", true);
assertPredicate("${body['isCredit']} == true", false);
assertPredicate("${body['isCredit']} == false", true);
}
protected String getLanguageName() {
return "simple";
}
protected void assertExpressionResultInstanceOf(String expressionText, Class<?> expectedType) {
Language language = assertResolveLanguage(getLanguageName());
Expression expression = language.createExpression(expressionText);
assertNotNull("Cannot assert type when no type is provided", expectedType);
assertNotNull("No Expression could be created for text: " + expressionText + " language: " + language, expression);
Object answer = expression.evaluate(exchange, Object.class);
assertIsInstanceOf(expectedType, answer);
}
public static final class Animal {
private String name;
private int age;
private Animal friend;
private Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Animal getFriend() {
return friend;
}
public void setFriend(Animal friend) {
this.friend = friend;
}
public boolean isDangerous() {
return name.contains("Tiger");
}
@Override
public String toString() {
return name;
}
}
public static final class Order {
private List<OrderLine> lines;
public Order(List<OrderLine> lines) {
this.lines = lines;
}
public List<OrderLine> getLines() {
return lines;
}
public void setLines(List<OrderLine> lines) {
this.lines = lines;
}
}
public static final class OrderLine {
private int id;
private String name;
public OrderLine(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
}
| |
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.bitcoinj.core;
import com.google.common.base.Stopwatch;
import com.google.common.collect.*;
import com.google.common.net.*;
import com.google.common.util.concurrent.*;
import org.bitcoinj.core.listeners.*;
import org.bitcoinj.net.discovery.*;
import org.bitcoinj.testing.*;
import org.bitcoinj.utils.*;
import org.junit.*;
import org.junit.runner.*;
import org.junit.runners.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static org.bitcoinj.core.Coin.*;
import static org.junit.Assert.*;
// TX announcement and broadcast is tested in TransactionBroadcastTest.
@RunWith(value = Parameterized.class)
public class PeerGroupTest extends TestWithPeerGroup {
private static final int BLOCK_HEIGHT_GENESIS = 0;
private BlockingQueue<Peer> connectedPeers;
private BlockingQueue<Peer> disconnectedPeers;
private AbstractPeerEventListener listener;
private Map<Peer, AtomicInteger> peerToMessageCount;
@Parameterized.Parameters
public static Collection<ClientType[]> parameters() {
return Arrays.asList(new ClientType[] {ClientType.NIO_CLIENT_MANAGER},
new ClientType[] {ClientType.BLOCKING_CLIENT_MANAGER});
}
public PeerGroupTest(ClientType clientType) {
super(clientType);
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
peerToMessageCount = new HashMap<Peer, AtomicInteger>();
connectedPeers = new LinkedBlockingQueue<Peer>();
disconnectedPeers = new LinkedBlockingQueue<Peer>();
listener = new AbstractPeerEventListener() {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
connectedPeers.add(peer);
}
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
disconnectedPeers.add(peer);
}
@Override
public Message onPreMessageReceived(Peer peer, Message m) {
AtomicInteger messageCount = peerToMessageCount.get(peer);
if (messageCount == null) {
messageCount = new AtomicInteger(0);
peerToMessageCount.put(peer, messageCount);
}
messageCount.incrementAndGet();
// Just pass the message right through for further processing.
return m;
}
};
}
@Override
@After
public void tearDown() {
super.tearDown();
}
@Test
public void listener() throws Exception {
peerGroup.start();
peerGroup.addConnectionEventListener(listener);
peerGroup.addDataEventListener(listener);
// Create a couple of peers.
InboundMessageQueuer p1 = connectPeer(1);
InboundMessageQueuer p2 = connectPeer(2);
connectedPeers.take();
connectedPeers.take();
pingAndWait(p1);
pingAndWait(p2);
Threading.waitForUserCode();
assertEquals(0, disconnectedPeers.size());
p1.close();
disconnectedPeers.take();
assertEquals(0, disconnectedPeers.size());
p2.close();
disconnectedPeers.take();
assertEquals(0, disconnectedPeers.size());
assertTrue(peerGroup.removeConnectionEventListener(listener));
assertFalse(peerGroup.removeConnectionEventListener(listener));
assertTrue(peerGroup.removeDataEventListener(listener));
assertFalse(peerGroup.removeDataEventListener(listener));
}
@Test
public void peerDiscoveryPolling() throws InterruptedException {
// Check that if peer discovery fails, we keep trying until we have some nodes to talk with.
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean result = new AtomicBoolean();
peerGroup.addPeerDiscovery(new PeerDiscovery() {
@Override
public InetSocketAddress[] getPeers(long services, long unused, TimeUnit unused2) throws PeerDiscoveryException {
if (!result.getAndSet(true)) {
// Pretend we are not connected to the internet.
throw new PeerDiscoveryException("test failure");
} else {
// Return a bogus address.
latch.countDown();
return new InetSocketAddress[]{new InetSocketAddress("localhost", 1)};
}
}
@Override
public void shutdown() {
}
});
peerGroup.start();
latch.await();
// Check that we did indeed throw an exception. If we got here it means we threw and then PeerGroup tried
// again a bit later.
assertTrue(result.get());
}
// Utility method to create a PeerDiscovery with a certain number of addresses.
private PeerDiscovery createPeerDiscovery(int nrOfAddressesWanted, int port) {
final InetSocketAddress[] addresses = new InetSocketAddress[nrOfAddressesWanted];
for (int addressNr = 0; addressNr < nrOfAddressesWanted; addressNr++) {
// make each address unique by using the counter to increment the port.
addresses[addressNr] = new InetSocketAddress("localhost", port + addressNr);
}
return new PeerDiscovery() {
public InetSocketAddress[] getPeers(long services, long unused, TimeUnit unused2) throws PeerDiscoveryException {
return addresses;
}
public void shutdown() {
}
};
}
@Test
public void multiplePeerDiscovery() throws InterruptedException {
peerGroup.setMaxPeersToDiscoverCount(98);
peerGroup.addPeerDiscovery(createPeerDiscovery(1, 0));
peerGroup.addPeerDiscovery(createPeerDiscovery(2, 100));
peerGroup.addPeerDiscovery(createPeerDiscovery(96, 200));
peerGroup.addPeerDiscovery(createPeerDiscovery(3, 300));
peerGroup.addPeerDiscovery(createPeerDiscovery(1, 400));
peerGroup.addConnectionEventListener(new AbstractPeerConnectionEventListener() {
@Override
public void onPeersDiscovered(Set<PeerAddress> peerAddresses) {
assertEquals(99, peerAddresses.size());
}
});
peerGroup.start();
}
@Test
public void receiveTxBroadcast() throws Exception {
// Check that when we receive transactions on all our peers, we do the right thing.
peerGroup.start();
// Create a couple of peers.
InboundMessageQueuer p1 = connectPeer(1);
InboundMessageQueuer p2 = connectPeer(2);
// Check the peer accessors.
assertEquals(2, peerGroup.numConnectedPeers());
Set<Peer> tmp = new HashSet<Peer>(peerGroup.getConnectedPeers());
Set<Peer> expectedPeers = new HashSet<Peer>();
expectedPeers.add(peerOf(p1));
expectedPeers.add(peerOf(p2));
assertEquals(tmp, expectedPeers);
Coin value = COIN;
Transaction t1 = FakeTxBuilder.createFakeTx(params, value, address);
InventoryMessage inv = new InventoryMessage(params);
inv.addTransaction(t1);
// Note: we start with p2 here to verify that transactions are downloaded from whichever peer announces first
// which does not have to be the same as the download peer (which is really the "block download peer").
inbound(p2, inv);
assertTrue(outbound(p2) instanceof GetDataMessage);
inbound(p1, inv);
assertNull(outbound(p1)); // Only one peer is used to download.
inbound(p2, t1);
assertNull(outbound(p1));
// Asks for dependency.
GetDataMessage getdata = (GetDataMessage) outbound(p2);
assertNotNull(getdata);
inbound(p2, new NotFoundMessage(params, getdata.getItems()));
pingAndWait(p2);
assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
}
@Test
public void receiveTxBroadcastOnAddedWallet() throws Exception {
// Check that when we receive transactions on all our peers, we do the right thing.
peerGroup.start();
// Create a peer.
InboundMessageQueuer p1 = connectPeer(1);
Wallet wallet2 = new Wallet(params);
ECKey key2 = wallet2.freshReceiveKey();
Address address2 = key2.toAddress(params);
peerGroup.addWallet(wallet2);
blockChain.addWallet(wallet2);
assertEquals(BloomFilter.class, waitForOutbound(p1).getClass());
assertEquals(MemoryPoolMessage.class, waitForOutbound(p1).getClass());
Coin value = COIN;
Transaction t1 = FakeTxBuilder.createFakeTx(params, value, address2);
InventoryMessage inv = new InventoryMessage(params);
inv.addTransaction(t1);
inbound(p1, inv);
assertTrue(outbound(p1) instanceof GetDataMessage);
inbound(p1, t1);
// Asks for dependency.
GetDataMessage getdata = (GetDataMessage) outbound(p1);
assertNotNull(getdata);
inbound(p1, new NotFoundMessage(params, getdata.getItems()));
pingAndWait(p1);
assertEquals(value, wallet2.getBalance(Wallet.BalanceType.ESTIMATED));
}
@Test
public void singleDownloadPeer1() throws Exception {
// Check that we don't attempt to retrieve blocks on multiple peers.
peerGroup.start();
// Create a couple of peers.
InboundMessageQueuer p1 = connectPeer(1);
InboundMessageQueuer p2 = connectPeer(2);
assertEquals(2, peerGroup.numConnectedPeers());
// Set up a little block chain. We heard about b1 but not b2 (it is pending download). b3 is solved whilst we
// are downloading the chain.
Block b1 = FakeTxBuilder.createFakeBlock(blockStore, BLOCK_HEIGHT_GENESIS).block;
blockChain.add(b1);
Block b2 = FakeTxBuilder.makeSolvedTestBlock(b1);
Block b3 = FakeTxBuilder.makeSolvedTestBlock(b2);
// Peer 1 and 2 receives an inv advertising a newly solved block.
InventoryMessage inv = new InventoryMessage(params);
inv.addBlock(b3);
// Only peer 1 tries to download it.
inbound(p1, inv);
pingAndWait(p1);
assertTrue(outbound(p1) instanceof GetDataMessage);
assertNull(outbound(p2));
// Peer 1 goes away, peer 2 becomes the download peer and thus queries the remote mempool.
final SettableFuture<Void> p1CloseFuture = SettableFuture.create();
peerOf(p1).addConnectionEventListener(new AbstractPeerConnectionEventListener() {
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
p1CloseFuture.set(null);
}
});
closePeer(peerOf(p1));
p1CloseFuture.get();
// Peer 2 fetches it next time it hears an inv (should it fetch immediately?).
inbound(p2, inv);
assertTrue(outbound(p2) instanceof GetDataMessage);
}
@Test
public void singleDownloadPeer2() throws Exception {
// Check that we don't attempt multiple simultaneous block chain downloads, when adding a new peer in the
// middle of an existing chain download.
// Create a couple of peers.
peerGroup.start();
// Create a couple of peers.
InboundMessageQueuer p1 = connectPeer(1);
// Set up a little block chain.
Block b1 = FakeTxBuilder.createFakeBlock(blockStore, BLOCK_HEIGHT_GENESIS).block;
Block b2 = FakeTxBuilder.makeSolvedTestBlock(b1);
Block b3 = FakeTxBuilder.makeSolvedTestBlock(b2);
// Expect a zero hash getblocks on p1. This is how the process starts.
peerGroup.startBlockChainDownload(new AbstractPeerDataEventListener() {
});
GetBlocksMessage getblocks = (GetBlocksMessage) outbound(p1);
assertEquals(Sha256Hash.ZERO_HASH, getblocks.getStopHash());
// We give back an inv with some blocks in it.
InventoryMessage inv = new InventoryMessage(params);
inv.addBlock(b1);
inv.addBlock(b2);
inv.addBlock(b3);
inbound(p1, inv);
assertTrue(outbound(p1) instanceof GetDataMessage);
// We hand back the first block.
inbound(p1, b1);
// Now we successfully connect to another peer. There should be no messages sent.
InboundMessageQueuer p2 = connectPeer(2);
Message message = outbound(p2);
assertNull(message == null ? "" : message.toString(), message);
}
@Test
public void transactionConfidence() throws Exception {
// Checks that we correctly count how many peers broadcast a transaction, so we can establish some measure of
// its trustworthyness assuming an untampered with internet connection.
peerGroup.start();
final Transaction[] event = new Transaction[1];
final TransactionConfidence[] confEvent = new TransactionConfidence[1];
peerGroup.addOnTransactionBroadcastListener(Threading.SAME_THREAD, new OnTransactionBroadcastListener() {
@Override
public void onTransaction(Peer peer, Transaction t) {
event[0] = t;
}
});
InboundMessageQueuer p1 = connectPeer(1);
InboundMessageQueuer p2 = connectPeer(2);
InboundMessageQueuer p3 = connectPeer(3);
Transaction tx = FakeTxBuilder.createFakeTx(params, valueOf(20, 0), address);
InventoryMessage inv = new InventoryMessage(params);
inv.addTransaction(tx);
// Peer 2 advertises the tx but does not receive it yet.
inbound(p2, inv);
assertTrue(outbound(p2) instanceof GetDataMessage);
assertEquals(1, tx.getConfidence().numBroadcastPeers());
assertNull(event[0]);
// Peer 1 advertises the tx, we don't do anything as it's already been requested.
inbound(p1, inv);
assertNull(outbound(p1));
// Peer 2 gets sent the tx and requests the dependency.
inbound(p2, tx);
assertTrue(outbound(p2) instanceof GetDataMessage);
tx = event[0]; // We want to use the canonical copy delivered by the PeerGroup from now on.
assertNotNull(tx);
event[0] = null;
// Peer 1 (the download peer) advertises the tx, we download it.
inbound(p1, inv); // returns getdata
inbound(p1, tx); // returns nothing after a queue drain.
// Two peers saw this tx hash.
assertEquals(2, tx.getConfidence().numBroadcastPeers());
assertTrue(tx.getConfidence().wasBroadcastBy(peerOf(p1).getAddress()));
assertTrue(tx.getConfidence().wasBroadcastBy(peerOf(p2).getAddress()));
tx.getConfidence().addEventListener(new TransactionConfidence.Listener() {
@Override
public void onConfidenceChanged(TransactionConfidence confidence, TransactionConfidence.Listener.ChangeReason reason) {
confEvent[0] = confidence;
}
});
// A straggler reports in.
inbound(p3, inv);
pingAndWait(p3);
Threading.waitForUserCode();
assertEquals(tx.getHash(), confEvent[0].getTransactionHash());
assertEquals(3, tx.getConfidence().numBroadcastPeers());
assertTrue(tx.getConfidence().wasBroadcastBy(peerOf(p3).getAddress()));
}
@Test
public void testWalletCatchupTime() throws Exception {
// Check the fast catchup time was initialized to something around the current runtime minus a week.
// The wallet was already added to the peer in setup.
final int WEEK = 86400 * 7;
final long now = Utils.currentTimeSeconds();
peerGroup.start();
assertTrue(peerGroup.getFastCatchupTimeSecs() > now - WEEK - 10000);
Wallet w2 = new Wallet(params);
ECKey key1 = new ECKey();
key1.setCreationTimeSeconds(now - 86400); // One day ago.
w2.importKey(key1);
peerGroup.addWallet(w2);
peerGroup.waitForJobQueue();
assertEquals(peerGroup.getFastCatchupTimeSecs(), now - 86400 - WEEK);
// Adding a key to the wallet should update the fast catchup time, but asynchronously and in the background
// due to the need to avoid complicated lock inversions.
ECKey key2 = new ECKey();
key2.setCreationTimeSeconds(now - 100000);
w2.importKey(key2);
peerGroup.waitForJobQueue();
assertEquals(peerGroup.getFastCatchupTimeSecs(), now - WEEK - 100000);
}
@Test
public void noPings() throws Exception {
peerGroup.start();
peerGroup.setPingIntervalMsec(0);
VersionMessage versionMessage = new VersionMessage(params, 2);
versionMessage.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion();
versionMessage.localServices = VersionMessage.NODE_NETWORK;
connectPeer(1, versionMessage);
peerGroup.waitForPeers(1).get();
assertFalse(peerGroup.getConnectedPeers().get(0).getLastPingTime() < Long.MAX_VALUE);
}
@Test
public void pings() throws Exception {
peerGroup.start();
peerGroup.setPingIntervalMsec(100);
VersionMessage versionMessage = new VersionMessage(params, 2);
versionMessage.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion();
versionMessage.localServices = VersionMessage.NODE_NETWORK;
InboundMessageQueuer p1 = connectPeer(1, versionMessage);
Ping ping = (Ping) waitForOutbound(p1);
inbound(p1, new Pong(ping.getNonce()));
pingAndWait(p1);
assertTrue(peerGroup.getConnectedPeers().get(0).getLastPingTime() < Long.MAX_VALUE);
// The call to outbound should block until a ping arrives.
ping = (Ping) waitForOutbound(p1);
inbound(p1, new Pong(ping.getNonce()));
assertTrue(peerGroup.getConnectedPeers().get(0).getLastPingTime() < Long.MAX_VALUE);
}
@Test
public void downloadPeerSelection() throws Exception {
peerGroup.start();
VersionMessage versionMessage2 = new VersionMessage(params, 2);
versionMessage2.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion();
versionMessage2.localServices = VersionMessage.NODE_NETWORK;
VersionMessage versionMessage3 = new VersionMessage(params, 3);
versionMessage3.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion();
versionMessage3.localServices = VersionMessage.NODE_NETWORK;
assertNull(peerGroup.getDownloadPeer());
Peer a = connectPeer(1, versionMessage2).peer;
assertEquals(2, peerGroup.getMostCommonChainHeight());
assertEquals(a, peerGroup.getDownloadPeer());
connectPeer(2, versionMessage2);
assertEquals(2, peerGroup.getMostCommonChainHeight());
assertEquals(a, peerGroup.getDownloadPeer()); // No change.
Peer c = connectPeer(3, versionMessage3).peer;
assertEquals(2, peerGroup.getMostCommonChainHeight());
assertEquals(a, peerGroup.getDownloadPeer()); // No change yet.
connectPeer(4, versionMessage3);
assertEquals(3, peerGroup.getMostCommonChainHeight());
assertEquals(a, peerGroup.getDownloadPeer()); // Still no change.
// New peer with a higher protocol version but same chain height.
// TODO: When PeerGroup.selectDownloadPeer.PREFERRED_VERSION is not equal to vMinRequiredProtocolVersion,
// reenable this test
/*VersionMessage versionMessage4 = new VersionMessage(params, 3);
versionMessage4.clientVersion = 100000;
versionMessage4.localServices = VersionMessage.NODE_NETWORK;
InboundMessageQueuer d = connectPeer(5, versionMessage4);
assertEquals(d.peer, peerGroup.getDownloadPeer());*/
}
@Test
public void peerTimeoutTest() throws Exception {
final int timeout = 100;
peerGroup.start();
peerGroup.setConnectTimeoutMillis(timeout);
final SettableFuture<Void> peerConnectedFuture = SettableFuture.create();
final SettableFuture<Void> peerDisconnectedFuture = SettableFuture.create();
peerGroup.addConnectionEventListener(Threading.SAME_THREAD, new AbstractPeerConnectionEventListener() {
@Override
public void onPeerConnected(Peer peer, int peerCount) {
peerConnectedFuture.set(null);
}
@Override
public void onPeerDisconnected(Peer peer, int peerCount) {
peerDisconnectedFuture.set(null);
}
});
// connect to peer but don't do handshake
final Stopwatch watch = Stopwatch.createStarted(); // before connection so we don't get elapsed < timeout
connectPeerWithoutVersionExchange(0);
// wait for disconnect (plus a bit more, in case test server is overloaded)
try {
peerDisconnectedFuture.get(timeout + 200, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
// the checks below suffice for this case too
}
// check things after disconnect
watch.stop();
assertFalse(peerConnectedFuture.isDone()); // should never have connected
assertTrue(watch.elapsed(TimeUnit.MILLISECONDS) >= timeout); // should not disconnect before timeout
assertTrue(peerDisconnectedFuture.isDone()); // but should disconnect eventually
}
@Test
@Ignore("disabled for now as this test is too flaky")
public void peerPriority() throws Exception {
final List<InetSocketAddress> addresses = Lists.newArrayList(
new InetSocketAddress("localhost", 2000),
new InetSocketAddress("localhost", 2001),
new InetSocketAddress("localhost", 2002)
);
peerGroup.addConnectionEventListener(listener);
peerGroup.addDataEventListener(listener);
peerGroup.addPeerDiscovery(new PeerDiscovery() {
@Override
public InetSocketAddress[] getPeers(long services, long unused, TimeUnit unused2) throws PeerDiscoveryException {
return addresses.toArray(new InetSocketAddress[addresses.size()]);
}
@Override
public void shutdown() {
}
});
peerGroup.setMaxConnections(3);
Utils.setMockSleep(true);
blockJobs = true;
jobBlocks.release(2); // startup + first peer discovery
peerGroup.start();
jobBlocks.release(3); // One for each peer.
handleConnectToPeer(0);
handleConnectToPeer(1);
handleConnectToPeer(2);
connectedPeers.take();
connectedPeers.take();
connectedPeers.take();
addresses.clear();
addresses.addAll(Lists.newArrayList(new InetSocketAddress("localhost", 2003)));
stopPeerServer(2);
assertEquals(2002, disconnectedPeers.take().getAddress().getPort()); // peer died
// discovers, connects to new peer
jobBlocks.release(1);
handleConnectToPeer(3);
assertEquals(2003, connectedPeers.take().getAddress().getPort());
stopPeerServer(1);
assertEquals(2001, disconnectedPeers.take().getAddress().getPort()); // peer died
// Alternates trying two offline peers
jobBlocks.release(10);
assertEquals(2001, disconnectedPeers.take().getAddress().getPort());
assertEquals(2002, disconnectedPeers.take().getAddress().getPort());
assertEquals(2001, disconnectedPeers.take().getAddress().getPort());
assertEquals(2002, disconnectedPeers.take().getAddress().getPort());
assertEquals(2001, disconnectedPeers.take().getAddress().getPort());
// Peer 2 comes online
startPeerServer(2);
jobBlocks.release(1);
handleConnectToPeer(2);
assertEquals(2002, connectedPeers.take().getAddress().getPort());
jobBlocks.release(6);
stopPeerServer(2);
assertEquals(2002, disconnectedPeers.take().getAddress().getPort()); // peer died
// Peer 2 is tried before peer 1, since it has a lower backoff due to recent success
assertEquals(2002, disconnectedPeers.take().getAddress().getPort());
assertEquals(2001, disconnectedPeers.take().getAddress().getPort());
}
@Test
public void testBloomOnP2Pubkey() throws Exception {
// Cover bug 513. When a relevant transaction with a p2pubkey output is found, the Bloom filter should be
// recalculated to include that transaction hash but not re-broadcast as the remote nodes should have followed
// the same procedure. However a new node that's connected should get the fresh filter.
peerGroup.start();
final ECKey key = wallet.currentReceiveKey();
// Create a couple of peers.
InboundMessageQueuer p1 = connectPeer(1);
InboundMessageQueuer p2 = connectPeer(2);
// Create a pay to pubkey tx.
Transaction tx = FakeTxBuilder.createFakeTx(params, COIN, key);
Transaction tx2 = new Transaction(params);
tx2.addInput(tx.getOutput(0));
TransactionOutPoint outpoint = tx2.getInput(0).getOutpoint();
assertTrue(p1.lastReceivedFilter.contains(key.getPubKey()));
assertFalse(p1.lastReceivedFilter.contains(tx.getHash().getBytes()));
inbound(p1, tx);
// p1 requests dep resolution, p2 is quiet.
assertTrue(outbound(p1) instanceof GetDataMessage);
final Sha256Hash dephash = tx.getInput(0).getOutpoint().getHash();
final InventoryItem inv = new InventoryItem(InventoryItem.Type.Transaction, dephash);
inbound(p1, new NotFoundMessage(params, ImmutableList.of(inv)));
assertNull(outbound(p1));
assertNull(outbound(p2));
peerGroup.waitForJobQueue();
// Now we connect p3 and there is a new bloom filter sent, that DOES match the relevant outpoint.
InboundMessageQueuer p3 = connectPeer(3);
assertTrue(p3.lastReceivedFilter.contains(key.getPubKey()));
assertTrue(p3.lastReceivedFilter.contains(outpoint.bitcoinSerialize()));
}
@Test
public void testBloomResendOnNewKey() throws Exception {
// Check that when we add a new key to the wallet, the Bloom filter is re-calculated and re-sent but only once
// we exceed the lookahead threshold.
wallet.setKeyChainGroupLookaheadSize(5);
wallet.setKeyChainGroupLookaheadThreshold(4);
peerGroup.start();
// Create a couple of peers.
InboundMessageQueuer p1 = connectPeer(1);
InboundMessageQueuer p2 = connectPeer(2);
peerGroup.waitForJobQueue();
BloomFilter f1 = p1.lastReceivedFilter;
ECKey key = null;
// We have to run ahead of the lookahead zone for this test. There should only be one bloom filter recalc.
for (int i = 0; i < wallet.getKeyChainGroupLookaheadSize() + wallet.getKeyChainGroupLookaheadThreshold() + 1; i++) {
key = wallet.freshReceiveKey();
}
peerGroup.waitForJobQueue();
BloomFilter bf, f2 = null;
while ((bf = (BloomFilter) outbound(p1)) != null) {
assertEquals(MemoryPoolMessage.class, outbound(p1).getClass());
f2 = bf;
}
assertNotNull(key);
assertNotNull(f2);
assertNull(outbound(p1));
// Check the last filter received.
assertNotEquals(f1, f2);
assertTrue(f2.contains(key.getPubKey()));
assertTrue(f2.contains(key.getPubKeyHash()));
assertFalse(f1.contains(key.getPubKey()));
assertFalse(f1.contains(key.getPubKeyHash()));
}
@Test
public void waitForNumPeers1() throws Exception {
ListenableFuture<List<Peer>> future = peerGroup.waitForPeers(3);
peerGroup.start();
assertFalse(future.isDone());
connectPeer(1);
assertFalse(future.isDone());
connectPeer(2);
assertFalse(future.isDone());
assertTrue(peerGroup.waitForPeers(2).isDone()); // Immediate completion.
connectPeer(3);
future.get();
assertTrue(future.isDone());
}
@Test
public void waitForPeersOfVersion() throws Exception {
final int baseVer = peerGroup.getMinRequiredProtocolVersion() + 3000;
final int newVer = baseVer + 1000;
ListenableFuture<List<Peer>> future = peerGroup.waitForPeersOfVersion(2, newVer);
VersionMessage ver1 = new VersionMessage(params, 10);
ver1.clientVersion = baseVer;
ver1.localServices = VersionMessage.NODE_NETWORK;
VersionMessage ver2 = new VersionMessage(params, 10);
ver2.clientVersion = newVer;
ver2.localServices = VersionMessage.NODE_NETWORK;
peerGroup.start();
assertFalse(future.isDone());
connectPeer(1, ver1);
assertFalse(future.isDone());
connectPeer(2, ver2);
assertFalse(future.isDone());
assertTrue(peerGroup.waitForPeersOfVersion(1, newVer).isDone()); // Immediate completion.
connectPeer(3, ver2);
future.get();
assertTrue(future.isDone());
}
@Test
public void waitForPeersWithServiceFlags() throws Exception {
ListenableFuture<List<Peer>> future = peerGroup.waitForPeersWithServiceMask(2, 3);
VersionMessage ver1 = new VersionMessage(params, 10);
ver1.clientVersion = 70000;
ver1.localServices = VersionMessage.NODE_NETWORK;
VersionMessage ver2 = new VersionMessage(params, 10);
ver2.clientVersion = 70000;
ver2.localServices = VersionMessage.NODE_NETWORK | 2;
peerGroup.start();
assertFalse(future.isDone());
connectPeer(1, ver1);
assertTrue(peerGroup.findPeersWithServiceMask(3).isEmpty());
assertFalse(future.isDone());
connectPeer(2, ver2);
assertFalse(future.isDone());
assertEquals(1, peerGroup.findPeersWithServiceMask(3).size());
assertTrue(peerGroup.waitForPeersWithServiceMask(1, 0x3).isDone()); // Immediate completion.
connectPeer(3, ver2);
future.get();
assertTrue(future.isDone());
peerGroup.stop();
}
@Test
public void preferLocalPeer() throws IOException {
// Because we are using the same port (8333 or 18333) that is used by Bitcoin Core
// We have to consider 2 cases:
// 1. Test are executed on the same machine that is running a full node
// 2. Test are executed without any full node running locally
// We have to avoid to connecting to real and external services in unit tests
// So we skip this test in case we have already something running on port params.getPort()
// Check that if we have a localhost port 8333 or 18333 then it's used instead of the p2p network.
ServerSocket local = null;
try {
local = new ServerSocket(params.getPort(), 100, InetAddresses.forString("127.0.0.1"));
}
catch(BindException e) { // Port already in use, skipping this test.
return;
}
try {
peerGroup.setUseLocalhostPeerWhenPossible(true);
peerGroup.start();
local.accept().close(); // Probe connect
local.accept(); // Real connect
// If we get here it used the local peer. Check no others are in use.
assertEquals(1, peerGroup.getMaxConnections());
assertEquals(PeerAddress.localhost(params), peerGroup.getPendingPeers().get(0).getAddress());
} finally {
local.close();
}
}
private <T extends Message> T assertNextMessageIs(InboundMessageQueuer q, Class<T> klass) throws Exception {
Message outbound = waitForOutbound(q);
assertEquals(klass, outbound.getClass());
return (T) outbound;
}
@Test
public void autoRescanOnKeyExhaustion() throws Exception {
// Check that if the last key that was inserted into the bloom filter is seen in some requested blocks,
// that the exhausting block is discarded, a new filter is calculated and sent, and then the download resumes.
final int NUM_KEYS = 9;
// First, grab a load of keys from the wallet, and then recreate it so it forgets that those keys were issued.
Wallet shadow = Wallet.fromSeed(wallet.getParams(), wallet.getKeyChainSeed());
List<ECKey> keys = new ArrayList<ECKey>(NUM_KEYS);
for (int i = 0; i < NUM_KEYS; i++) {
keys.add(shadow.freshReceiveKey());
}
// Reduce the number of keys we need to work with to speed up this test.
wallet.setKeyChainGroupLookaheadSize(4);
wallet.setKeyChainGroupLookaheadThreshold(2);
peerGroup.start();
InboundMessageQueuer p1 = connectPeer(1);
assertTrue(p1.lastReceivedFilter.contains(keys.get(1).getPubKey()));
assertTrue(p1.lastReceivedFilter.contains(keys.get(5).getPubKeyHash()));
assertFalse(p1.lastReceivedFilter.contains(keys.get(keys.size() - 1).getPubKey()));
peerGroup.startBlockChainDownload(null);
assertNextMessageIs(p1, GetBlocksMessage.class);
// Make some transactions and blocks that send money to the wallet thus using up all the keys.
List<Block> blocks = Lists.newArrayList();
Coin expectedBalance = Coin.ZERO;
Block prev = blockStore.getChainHead().getHeader();
for (ECKey key1 : keys) {
Address addr = key1.toAddress(params);
Block next = FakeTxBuilder.makeSolvedTestBlock(prev, FakeTxBuilder.createFakeTx(params, Coin.FIFTY_COINS, addr));
expectedBalance = expectedBalance.add(next.getTransactions().get(2).getOutput(0).getValue());
blocks.add(next);
prev = next;
}
// Send the chain that doesn't have all the transactions in it. The blocks after the exhaustion point should all
// be ignored.
int epoch = wallet.keyChainGroup.getCombinedKeyLookaheadEpochs();
BloomFilter filter = new BloomFilter(params, p1.lastReceivedFilter.bitcoinSerialize());
filterAndSend(p1, blocks, filter);
Block exhaustionPoint = blocks.get(3);
pingAndWait(p1);
assertNotEquals(epoch, wallet.keyChainGroup.getCombinedKeyLookaheadEpochs());
// 4th block was end of the lookahead zone and thus was discarded, so we got 3 blocks worth of money (50 each).
assertEquals(Coin.FIFTY_COINS.multiply(3), wallet.getBalance());
assertEquals(exhaustionPoint.getPrevBlockHash(), blockChain.getChainHead().getHeader().getHash());
// Await the new filter.
peerGroup.waitForJobQueue();
BloomFilter newFilter = assertNextMessageIs(p1, BloomFilter.class);
assertNotEquals(filter, newFilter);
assertNextMessageIs(p1, MemoryPoolMessage.class);
Ping ping = assertNextMessageIs(p1, Ping.class);
inbound(p1, new Pong(ping.getNonce()));
// Await restart of the chain download.
GetDataMessage getdata = assertNextMessageIs(p1, GetDataMessage.class);
assertEquals(exhaustionPoint.getHash(), getdata.getHashOf(0));
assertEquals(InventoryItem.Type.FilteredBlock, getdata.getItems().get(0).type);
List<Block> newBlocks = blocks.subList(3, blocks.size());
filterAndSend(p1, newBlocks, newFilter);
assertNextMessageIs(p1, Ping.class);
// It happened again.
peerGroup.waitForJobQueue();
newFilter = assertNextMessageIs(p1, BloomFilter.class);
assertNextMessageIs(p1, MemoryPoolMessage.class);
inbound(p1, new Pong(assertNextMessageIs(p1, Ping.class).getNonce()));
assertNextMessageIs(p1, GetDataMessage.class);
newBlocks = blocks.subList(6, blocks.size());
filterAndSend(p1, newBlocks, newFilter);
// Send a non-tx message so the peer knows the filtered block is over and force processing.
inbound(p1, new Ping());
pingAndWait(p1);
assertEquals(expectedBalance, wallet.getBalance());
assertEquals(blocks.get(blocks.size() - 1).getHash(), blockChain.getChainHead().getHeader().getHash());
}
private void filterAndSend(InboundMessageQueuer p1, List<Block> blocks, BloomFilter filter) {
for (Block block : blocks) {
FilteredBlock fb = filter.applyAndUpdate(block);
inbound(p1, fb);
for (Transaction tx : fb.getAssociatedTransactions().values())
inbound(p1, tx);
}
}
}
| |
/*
* 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.geo;
import org.elasticsearch.Version;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.GeoValidationMethod;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.InternalSettingsPlugin;
import org.elasticsearch.test.VersionUtils;
import java.util.Arrays;
import java.util.Collection;
import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.geoBoundingBoxQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.equalTo;
public class GeoBoundingBoxIT extends ESIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Arrays.asList(InternalSettingsPlugin.class); // uses index.version.created
}
public void testSimpleBoundingBoxTest() throws Exception {
Version version = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0,
Version.CURRENT);
Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type1")
.startObject("properties").startObject("location").field("type", "geo_point");
xContentBuilder.endObject().endObject().endObject().endObject();
assertAcked(prepareCreate("test").setSettings(settings).addMapping("type1", xContentBuilder));
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
.field("name", "New York")
.startObject("location").field("lat", 40.7143528).field("lon", -74.0059731).endObject()
.endObject()).execute().actionGet();
// to NY: 5.286 km
client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject()
.field("name", "Times Square")
.startObject("location").field("lat", 40.759011).field("lon", -73.9844722).endObject()
.endObject()).execute().actionGet();
// to NY: 0.4621 km
client().prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject()
.field("name", "Tribeca")
.startObject("location").field("lat", 40.718266).field("lon", -74.007819).endObject()
.endObject()).execute().actionGet();
// to NY: 1.055 km
client().prepareIndex("test", "type1", "4").setSource(jsonBuilder().startObject()
.field("name", "Wall Street")
.startObject("location").field("lat", 40.7051157).field("lon", -74.0088305).endObject()
.endObject()).execute().actionGet();
// to NY: 1.258 km
client().prepareIndex("test", "type1", "5").setSource(jsonBuilder().startObject()
.field("name", "Soho")
.startObject("location").field("lat", 40.7247222).field("lon", -74).endObject()
.endObject()).execute().actionGet();
// to NY: 2.029 km
client().prepareIndex("test", "type1", "6").setSource(jsonBuilder().startObject()
.field("name", "Greenwich Village")
.startObject("location").field("lat", 40.731033).field("lon", -73.9962255).endObject()
.endObject()).execute().actionGet();
// to NY: 8.572 km
client().prepareIndex("test", "type1", "7").setSource(jsonBuilder().startObject()
.field("name", "Brooklyn")
.startObject("location").field("lat", 40.65).field("lon", -73.95).endObject()
.endObject()).execute().actionGet();
client().admin().indices().prepareRefresh().execute().actionGet();
SearchResponse searchResponse = client().prepareSearch() // from NY
.setQuery(geoBoundingBoxQuery("location").setCorners(40.73, -74.1, 40.717, -73.99))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
assertThat(searchResponse.getHits().getHits().length, equalTo(2));
for (SearchHit hit : searchResponse.getHits()) {
assertThat(hit.getId(), anyOf(equalTo("1"), equalTo("3"), equalTo("5")));
}
searchResponse = client().prepareSearch() // from NY
.setQuery(geoBoundingBoxQuery("location").setCorners(40.73, -74.1, 40.717, -73.99).type("indexed"))
.execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
assertThat(searchResponse.getHits().getHits().length, equalTo(2));
for (SearchHit hit : searchResponse.getHits()) {
assertThat(hit.getId(), anyOf(equalTo("1"), equalTo("3"), equalTo("5")));
}
}
public void testLimit2BoundingBox() throws Exception {
Version version = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0,
Version.CURRENT);
Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type1")
.startObject("properties").startObject("location").field("type", "geo_point");
xContentBuilder.endObject().endObject().endObject().endObject();
assertAcked(prepareCreate("test").setSettings(settings).addMapping("type1", xContentBuilder));
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
.field("userid", 880)
.field("title", "Place in Stockholm")
.startObject("location").field("lat", 59.328355000000002).field("lon", 18.036842).endObject()
.endObject())
.setRefreshPolicy(IMMEDIATE)
.get();
client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject()
.field("userid", 534)
.field("title", "Place in Montreal")
.startObject("location").field("lat", 45.509526999999999).field("lon", -73.570986000000005).endObject()
.endObject())
.setRefreshPolicy(IMMEDIATE)
.get();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(
boolQuery().must(termQuery("userid", 880)).filter(
geoBoundingBoxQuery("location").setCorners(74.579421999999994, 143.5, -66.668903999999998, 113.96875))
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
searchResponse = client().prepareSearch()
.setQuery(
boolQuery().must(termQuery("userid", 880)).filter(
geoBoundingBoxQuery("location").setCorners(74.579421999999994, 143.5, -66.668903999999998, 113.96875).type("indexed"))
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
searchResponse = client().prepareSearch()
.setQuery(
boolQuery().must(termQuery("userid", 534)).filter(
geoBoundingBoxQuery("location").setCorners(74.579421999999994, 143.5, -66.668903999999998, 113.96875))
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
searchResponse = client().prepareSearch()
.setQuery(
boolQuery().must(termQuery("userid", 534)).filter(
geoBoundingBoxQuery("location").setCorners(74.579421999999994, 143.5, -66.668903999999998, 113.96875).type("indexed"))
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
}
public void testCompleteLonRange() throws Exception {
Version version = VersionUtils.randomVersionBetween(random(), Version.V_5_0_0,
Version.CURRENT);
Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, version).build();
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject().startObject("type1")
.startObject("properties").startObject("location").field("type", "geo_point");
xContentBuilder.endObject().endObject().endObject().endObject();
assertAcked(prepareCreate("test").setSettings(settings).addMapping("type1", xContentBuilder));
ensureGreen();
client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject()
.field("userid", 880)
.field("title", "Place in Stockholm")
.startObject("location").field("lat", 59.328355000000002).field("lon", 18.036842).endObject()
.endObject())
.setRefreshPolicy(IMMEDIATE)
.get();
client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject()
.field("userid", 534)
.field("title", "Place in Montreal")
.startObject("location").field("lat", 45.509526999999999).field("lon", -73.570986000000005).endObject()
.endObject())
.setRefreshPolicy(IMMEDIATE)
.get();
SearchResponse searchResponse = client().prepareSearch()
.setQuery(
geoBoundingBoxQuery("location").setValidationMethod(GeoValidationMethod.COERCE).setCorners(50, -180, -50, 180)
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
searchResponse = client().prepareSearch()
.setQuery(
geoBoundingBoxQuery("location").setValidationMethod(GeoValidationMethod.COERCE).setCorners(50, -180, -50, 180).type("indexed")
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
searchResponse = client().prepareSearch()
.setQuery(
geoBoundingBoxQuery("location").setValidationMethod(GeoValidationMethod.COERCE).setCorners(90, -180, -90, 180)
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
searchResponse = client().prepareSearch()
.setQuery(
geoBoundingBoxQuery("location").setValidationMethod(GeoValidationMethod.COERCE).setCorners(90, -180, -90, 180).type("indexed")
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
searchResponse = client().prepareSearch()
.setQuery(
geoBoundingBoxQuery("location").setValidationMethod(GeoValidationMethod.COERCE).setCorners(50, 0, -50, 360)
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
searchResponse = client().prepareSearch()
.setQuery(
geoBoundingBoxQuery("location").setValidationMethod(GeoValidationMethod.COERCE).setCorners(50, 0, -50, 360).type("indexed")
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(1L));
searchResponse = client().prepareSearch()
.setQuery(
geoBoundingBoxQuery("location").setValidationMethod(GeoValidationMethod.COERCE).setCorners(90, 0, -90, 360)
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
searchResponse = client().prepareSearch()
.setQuery(
geoBoundingBoxQuery("location").setValidationMethod(GeoValidationMethod.COERCE).setCorners(90, 0, -90, 360).type("indexed")
).execute().actionGet();
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.