gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.common.trace;
import static com.navercorp.pinpoint.common.trace.HistogramSchema.*;
import static com.navercorp.pinpoint.common.trace.ServiceTypeProperty.*;
/**
*
*
* <h3>Pinpoint Internal (~ 999)</h3>
*
* <table>
* <tr><td>-1</td><td>UNDEFINED</td></tr>
* <tr><td>1</td><td>UNKNOWN</td></tr>
* <tr><td>2</td><td>USER</td></tr>
* <tr><td>3</td><td>UNKNOWN_GROUP</td></tr>
* <tr><td>5</td><td>TEST</td></tr>
* <tr><td>7</td><td>COLLECTOR</td></tr>
* <tr><td>100</td><td>ASYNC</td></tr>
* </table>
*
*
* <h3>Server (1000 ~ 1899)</h3>
*
* <table>
* <tr><td>1000</td><td>STAND_ALONE</td></tr>
* <tr><td>1005</td><td>TEST_STAND_ALONE</td></tr>
* <tr><td>1010</td><td>TOMCAT</td></tr>
* <tr><td>1011</td><td>TOMCAT_METHOD</td></tr>
* <tr><td>1020</td><td><i>RESERVED</i></td></tr>
* <tr><td>1021</td><td><i>RESERVED</i></td></tr>
* <tr><td>1030</td><td>JETTY</td></tr>
* <tr><td>1031</td><td>JETTY_METHOD</td></tr>
* <tr><td>1100</td><td>THRIFT_SERVER</td></tr>
* <tr><td>1101</td><td>THRIFT_SERVER_INTERNAL</td></tr>
* </table>
*
* <h3>Server Sandbox (1900 ~ 1999)</h3>
*
*
* <h3>Library (2000 ~ 8999)</h3>
* <table>
* <tr><td>2050</td><td>UNKNOWN_DB</td></tr>
* <tr><td>2051</td><td>UNKNOWN_DB_EXECUTE_QUERY</td></tr>
* <tr><td>2100</td><td>MYSQL</td></tr>
* <tr><td>2101</td><td>MYSQL_EXECUTE_QUERY</td></tr>
* <tr><td>2200</td><td>MSSQL</td></tr>
* <tr><td>2201</td><td>MSSQL_EXECUTE_QUERY</td></tr>
* <tr><td>2300</td><td>ORACLE</td></tr>
* <tr><td>2301</td><td>ORACLE_EXECUTE_QUERY</td></tr>
* <tr><td>2400</td><td>CUBRID</td></tr>
* <tr><td>2401</td><td>CUBRID_EXECUTE_QUERY</td></tr>
* <tr><td>5000</td><td>INTERNAL_METHOD</td></tr>
* <tr><td>5010</td><td>GSON</td></tr>
* <tr><td>5011</td><td>JACKSON</td></tr>
* <tr><td>5012</td><td>JSON-LIB</td></tr>
* <tr><td>5050</td><td>SPRING</td></tr>
* <tr><td>5051</td><td>SPRING_MVC</td></tr>
* <tr><td>5061</td><td><i>RESERVED</i></td></tr>
* <tr><td>5071</td><td>SPRING_BEAN</td></tr>
* <tr><td>5500</td><td>IBATIS</td></tr>
* <tr><td>5501</td><td>IBATIS-SPRING</td></tr>
* <tr><td>5510</td><td>MYBATIS</td></tr>
* <tr><td>6050</td><td>DBCP</td></tr>
* <tr><td>7010</td><td>USER_INCLUDE</td></tr>
* <tr><td>8050</td><td>MEMCACHED</td></tr>
* <tr><td>8051</td><td>MEMCACHED_FUTURE_GET</td></tr>
* <tr><td>8100</td><td>ARCUS</td></tr>
* <tr><td>8101</td><td>ARCUS_FUTURE_GET</td></tr>
* <tr><td>8102</td><td>ARCUS_EHCACHE_FUTURE_GET</td></tr>
* <tr><td>8103</td><td>ARCUS_INTERNAL</td></tr>
* <tr><td>8200</td><td>REDIS</td></tr>
* <tr><td>8250</td><td><i>RESERVED</i></td></tr>
* <tr><td>8251</td><td><i>RESERVED</i></td></tr>
* </table>
*
*
* <h3>RPC (9000 ~ 9899)</h3>
* <table>
* <tr><td>9050</td><td>HTTP_CLIENT_3</td></tr>
* <tr><td>9051</td><td>HTTP_CLIENT_3_INTERNAL</td></tr>
* <tr><td>9052</td><td>HTTP_CLIENT_4</td></tr>
* <tr><td>9053</td><td>HTTP_CLIENT_4_INTERNAL</td></tr>
* <tr><td>9054</td><td>GOOGLE_HTTP_CLIENT_INTERNAL</td></tr>
* <tr><td>9055</td><td>JDK_HTTPURLCONNECTOR</td></tr>
* <tr><td>9056</td><td>ASYNC_HTTP_CLIENT</td></tr>
* <tr><td>9057</td><td>ASYNC_HTTP_CLIENT_INTERNAL</td></tr>
* <tr><td>9058</td><td>OK_HTTP_CLIENT</td></tr>
* <tr><td>9059</td><td>OK_HTTP_CLIENT_INTERNAL</td></tr>
* <tr><td>9060</td><td><i>RESERVED</i></td></tr>
* <tr><td>9070</td><td><i>RESERVED</i></td></tr>
* <tr><td>9100</td><td>THRIFT_CLIENT</td></tr>
* <tr><td>9101</td><td>THRIFT_CLIENT_INTERNAL</td></tr>
* </table>
*
* <h3>RPC Sandbox (9900 ~ 9999)</h3>
*
* <h3>Library Sandbox (10000 ~ 10999)</h3>
*
* <tr><td></td><td></td></tr>
*
* @author emeroad
* @author netspider
* @author Jongho Moon
*/
public class ServiceType {
private final short code;
private final String name;
private final String desc;
private final boolean terminal;
// FIXME record statistics of only rpc call currently. so is it all right to chane into isRecordRpc()
private final boolean recordStatistics;
// whether or not print out api including destinationId
private final boolean includeDestinationId;
private final HistogramSchema histogramSchema;
public static ServiceType of(int code, String name, HistogramSchema histogramSchema, ServiceTypeProperty... properties) {
return of(code, name, name, histogramSchema, properties);
}
public static ServiceType of(int code, String name, String desc, HistogramSchema histogramSchema, ServiceTypeProperty... properties) {
return new ServiceType(code, name, desc, histogramSchema, properties);
}
public ServiceType(int code, String name, String desc, HistogramSchema histogramSchema, ServiceTypeProperty... properties) {
// code must be a short value but constructors accept int to make declaring ServiceType values more cleaner by removing casting to short.
if (code > Short.MAX_VALUE || code < Short.MIN_VALUE) {
throw new IllegalArgumentException("code must be a short value");
}
checkSupportHistogramSchema(code, histogramSchema);
this.code = (short)code;
this.name = name;
this.desc = desc;
this.histogramSchema = histogramSchema;
boolean terminal = false;
boolean recordStatistics = false;
boolean includeDestinationId = false;
for (ServiceTypeProperty property : properties) {
switch (property) {
case TERMINAL:
terminal = true;
break;
case RECORD_STATISTICS:
recordStatistics = true;
break;
case INCLUDE_DESTINATION_ID:
includeDestinationId = true;
break;
default:
throw new IllegalStateException("Unknown ServiceTypeProperty:" + property);
}
}
this.terminal = terminal;
this.recordStatistics = recordStatistics;
this.includeDestinationId = includeDestinationId;
}
private void checkSupportHistogramSchema(int code, HistogramSchema histogramSchema) {
if (!isWas((short)code)) {
return;
}
if (histogramSchema != HistogramSchema.NORMAL_SCHEMA) {
throw new IllegalArgumentException("Server ServiceType only support HistogramSchema.NORMAL_SCHEMA. code:" + code);
}
}
public boolean isInternalMethod() {
return this == INTERNAL_METHOD;
}
public boolean isRpcClient() {
return ServiceTypeCategory.RPC.contains(code);
}
// FIXME record statistics of only rpc call currently. so is it all right to chane into isRecordRpc()
public boolean isRecordStatistics() {
return recordStatistics;
}
public boolean isUnknown() {
return this == ServiceType.UNKNOWN; // || this == ServiceType.UNKNOWN_CLOUD;
}
// return true when the service type is USER or can not be identified
public boolean isUser() {
return this == ServiceType.USER;
}
public String getName() {
return name;
}
public short getCode() {
return code;
}
public String getDesc() {
return desc;
}
public boolean isTerminal() {
return terminal;
}
public boolean isIncludeDestinationId() {
return includeDestinationId;
}
public HistogramSchema getHistogramSchema() {
return histogramSchema;
}
public boolean isWas() {
return isWas(this.code);
}
@Override
public String toString() {
return desc;
}
@Override
public int hashCode() {
// ServiceType's hashCode method is not used as they are put into IntHashMap (see ServiceTypeRegistry)
// which uses ServiceType code as key. It shouldn't really matter what this method returns.
final int prime = 31;
int result = 1;
result = prime * result + code;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ServiceType other = (ServiceType) obj;
if (code != other.code) {
return false;
}
if (desc == null) {
if (other.desc != null) {
return false;
}
} else if (!desc.equals(other.desc)) {
return false;
}
if (histogramSchema == null) {
if (other.histogramSchema != null) {
return false;
}
} else if (!histogramSchema.equals(other.histogramSchema)) {
return false;
}
if (includeDestinationId != other.includeDestinationId) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (recordStatistics != other.recordStatistics) {
return false;
}
if (terminal != other.terminal) {
return false;
}
return true;
}
public static boolean isWas(final short code) {
return ServiceTypeCategory.SERVER.contains(code);
}
// Undefined Service Code
public static final ServiceType UNDEFINED = of(-1, "UNDEFINED", NORMAL_SCHEMA, TERMINAL);
// Callee node that agent hasn't been installed
public static final ServiceType UNKNOWN = of(1, "UNKNOWN", NORMAL_SCHEMA, RECORD_STATISTICS);
// UserUNDEFINED
public static final ServiceType USER = of(2, "USER", NORMAL_SCHEMA, RECORD_STATISTICS);
// Group of UNKNOWN, used only for UI
public static final ServiceType UNKNOWN_GROUP = of(3, "UNKNOWN_GROUP", NORMAL_SCHEMA, RECORD_STATISTICS);
// Group of TEST, used for running tests
public static final ServiceType TEST = of(5, "TEST", NORMAL_SCHEMA);
public static final ServiceType COLLECTOR = of(7, "COLLECTOR", NORMAL_SCHEMA);
public static final ServiceType ASYNC = of(100, "ASYNC", NORMAL_SCHEMA);
// Java applications, WAS
public static final ServiceType STAND_ALONE = of(1000, "STAND_ALONE", NORMAL_SCHEMA, RECORD_STATISTICS);
public static final ServiceType TEST_STAND_ALONE = of(1005, "TEST_STAND_ALONE", NORMAL_SCHEMA, RECORD_STATISTICS);
/**
* Database shown only as xxx_EXECUTE_QUERY at the statistics info section in the server map
*/
// DB 2000
public static final ServiceType UNKNOWN_DB = of(2050, "UNKNOWN_DB", NORMAL_SCHEMA, TERMINAL, INCLUDE_DESTINATION_ID);
public static final ServiceType UNKNOWN_DB_EXECUTE_QUERY = of(2051, "UNKNOWN_DB_EXECUTE_QUERY", "UNKNOWN_DB", NORMAL_SCHEMA, TERMINAL, RECORD_STATISTICS, INCLUDE_DESTINATION_ID);
// Internal method
// FIXME it's not clear to put internal method here. but do that for now.
public static final ServiceType INTERNAL_METHOD = of(5000, "INTERNAL_METHOD", NORMAL_SCHEMA);
// Spring framework
public static final ServiceType SPRING = of(5050, "SPRING", NORMAL_SCHEMA);
// public static final ServiceType SPRING_MVC = of(5051, "SPRING_MVC", "SPRING", NORMAL_SCHEMA);
// FIXME replaced with IBATIS_SPRING (5501) under IBatis Plugin - kept for backwards compatibility
public static final ServiceType SPRING_ORM_IBATIS = of(5061, "SPRING_ORM_IBATIS", "SPRING", NORMAL_SCHEMA);
// FIXME need to define how to handle spring related codes
// public static final ServiceType SPRING_BEAN = of(5071, "SPRING_BEAN", "SPRING_BEAN", NORMAL_SCHEMA);
}
| |
package com.bullhornsdk.data.model.entity.core.onboarding365.forms;
import com.bullhornsdk.data.model.entity.core.standard.Candidate;
import com.bullhornsdk.data.model.entity.core.type.*;
import com.bullhornsdk.data.model.entity.customfields.CustomFieldsH;
import com.bullhornsdk.data.util.ReadOnly;
import com.fasterxml.jackson.annotation.*;
import org.joda.time.DateTime;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.util.Objects;
/**
* Created by dhuber 27-Oct-21
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonRootName(value = "data")
@JsonPropertyOrder({"id", "candidate", "customDate1", "customDate2", "customDate3", "customDate4", "customDate5",
"customInt1", "customInt2", "customInt3", "customInt4", "customInt5", "customMoney1", "customMoney2", "customMoney3", "customMoney4", "customMoney5",
"customText1", "customText2", "customText3","customText4", "customText5","customText6", "customText7", "customText8", "customText9", "customText10",
"dateAdded", "dateLastModified", "isDeleted", "isExempt", "localAdditionalWithholdingsAmount", "localExemptions", "localFilingStatus", "localTaxCode", "localTaxStateID"})
public class LocalTaxForm extends CustomFieldsH implements QueryEntity, CreateEntity, UpdateEntity, DateLastModifiedEntity, SoftDeleteEntity {
private Integer id;
private Candidate candidate;
private DateTime dateAdded;
private DateTime dateLastModified;
private Boolean isDeleted;
private Boolean isExempt;
private BigDecimal localAdditionalWithholdingsAmount;
private Integer localExemptions;
@JsonIgnore
@Size(max = 10)
private String localFilingStatus;
@JsonIgnore
@Size(max = 1000)
private String localTaxCode;
private Integer localTaxStateID;
public LocalTaxForm() {
}
public LocalTaxForm(Integer id) {
this.id = id;
}
@Override
@JsonProperty("id")
public Integer getId() {
return id;
}
@ReadOnly
@Override
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
@JsonProperty("candidate")
public Candidate getCandidate() {
return candidate;
}
@JsonProperty("candidate")
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
}
@JsonProperty("dateAdded")
public DateTime getDateAdded() {
return dateAdded;
}
@JsonProperty("dateAdded")
public void setDateAdded(DateTime dateAdded) {
this.dateAdded = dateAdded;
}
@JsonProperty("dateLastModified")
public DateTime getDateLastModified() {
return dateLastModified;
}
@JsonProperty("dateLastModified")
public void setDateLastModified(DateTime dateLastModified) {
this.dateLastModified = dateLastModified;
}
@JsonProperty("isDeleted")
public Boolean getIsDeleted() {
return isDeleted;
}
@JsonProperty("isDeleted")
public void setIsDeleted(Boolean deleted) {
isDeleted = deleted;
}
@JsonProperty("isExempt")
public Boolean getExempt() {
return isExempt;
}
@JsonProperty("isExempt")
public void setExempt(Boolean exempt) {
isExempt = exempt;
}
@JsonProperty("localAdditionalWithholdingsAmount")
public BigDecimal getLocalAdditionalWithholdingsAmount() {
return localAdditionalWithholdingsAmount;
}
@JsonProperty("localAdditionalWithholdingsAmount")
public void setLocalAdditionalWithholdingsAmount(BigDecimal localAdditionalWithholdingsAmount) {
this.localAdditionalWithholdingsAmount = localAdditionalWithholdingsAmount;
}
@JsonProperty("localExemptions")
public Integer getLocalExemptions() {
return localExemptions;
}
@JsonProperty("localExemptions")
public void setLocalExemptions(Integer localExemptions) {
this.localExemptions = localExemptions;
}
@JsonProperty("localFilingStatus")
public String getLocalFilingStatus() {
return localFilingStatus;
}
@JsonIgnore
public void setLocalFilingStatus(String localFilingStatus) {
this.localFilingStatus = localFilingStatus;
}
@JsonProperty("localTaxCode")
public String getLocalTaxCode() {
return localTaxCode;
}
@JsonIgnore
public void setLocalTaxCode(String localTaxCode) {
this.localTaxCode = localTaxCode;
}
@JsonProperty("localTaxStateID")
public Integer getLocalTaxStateID() {
return localTaxStateID;
}
@JsonProperty("localTaxStateID")
public void setLocalTaxStateID(Integer localTaxStateID) {
this.localTaxStateID = localTaxStateID;
}
@Override
public String toString() {
return "LocalTaxForm{" +
"id=" + id +
", candidate=" + candidate +
", dateAdded=" + dateAdded +
", dateLastModified=" + dateLastModified +
", isDeleted=" + isDeleted +
", isExempt=" + isExempt +
", localAdditionalWithholdingsAmount=" + localAdditionalWithholdingsAmount +
", localExemptions=" + localExemptions +
", localFilingStatus='" + localFilingStatus + '\'' +
", localTaxCode='" + localTaxCode + '\'' +
", localTaxStateID=" + localTaxStateID +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
LocalTaxForm that = (LocalTaxForm) o;
return Objects.equals(id, that.id) &&
Objects.equals(candidate, that.candidate) &&
Objects.equals(dateAdded, that.dateAdded) &&
Objects.equals(dateLastModified, that.dateLastModified) &&
Objects.equals(isDeleted, that.isDeleted) &&
Objects.equals(isExempt, that.isExempt) &&
Objects.equals(localAdditionalWithholdingsAmount, that.localAdditionalWithholdingsAmount) &&
Objects.equals(localExemptions, that.localExemptions) &&
Objects.equals(localFilingStatus, that.localFilingStatus) &&
Objects.equals(localTaxCode, that.localTaxCode) &&
Objects.equals(localTaxStateID, that.localTaxStateID);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), id, candidate, dateAdded, dateLastModified, isDeleted, isExempt, localAdditionalWithholdingsAmount, localExemptions, localFilingStatus, localTaxCode, localTaxStateID);
}
}
| |
/*
* Copyright (C) 2016 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.wallpaperbackup;
import android.app.WallpaperManager;
import android.app.backup.BackupAgent;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
import android.app.backup.FullBackupDataOutput;
import android.content.Context;
import android.graphics.Rect;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.os.UserHandle;
import android.system.Os;
import android.util.Slog;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class WallpaperBackupAgent extends BackupAgent {
private static final String TAG = "WallpaperBackup";
private static final boolean DEBUG = false;
// NB: must be kept in sync with WallpaperManagerService but has no
// compile-time visibility.
// Target filenames within the system's wallpaper directory
static final String WALLPAPER = "wallpaper_orig";
static final String WALLPAPER_INFO = "wallpaper_info.xml";
// Names of our local-data stage files/links
static final String IMAGE_STAGE = "wallpaper-stage";
static final String INFO_STAGE = "wallpaper-info-stage";
static final String EMPTY_SENTINEL = "empty";
private File mWallpaperInfo; // wallpaper metadata file
private File mWallpaperFile; // primary wallpaper image file
private WallpaperManager mWm;
@Override
public void onCreate() {
if (DEBUG) {
Slog.v(TAG, "onCreate()");
}
File wallpaperDir = Environment.getUserSystemDirectory(UserHandle.USER_SYSTEM);
mWallpaperInfo = new File(wallpaperDir, WALLPAPER_INFO);
mWallpaperFile = new File(wallpaperDir, WALLPAPER);
mWm = (WallpaperManager) getSystemService(Context.WALLPAPER_SERVICE);
}
@Override
public void onFullBackup(FullBackupDataOutput data) throws IOException {
// To avoid data duplication and disk churn, use links as the stage.
final File filesDir = getFilesDir();
final File infoStage = new File(filesDir, INFO_STAGE);
final File imageStage = new File (filesDir, IMAGE_STAGE);
final File empty = new File (filesDir, EMPTY_SENTINEL);
try {
// We always back up this 'empty' file to ensure that the absence of
// storable wallpaper imagery still produces a non-empty backup data
// stream, otherwise it'd simply be ignored in preflight.
FileOutputStream touch = new FileOutputStream(empty);
touch.close();
fullBackupFile(empty, data);
// only back up the wallpaper if we've been told it's allowed
if (mWm.isWallpaperBackupEligible()) {
if (DEBUG) {
Slog.v(TAG, "Wallpaper is backup-eligible; linking & writing");
}
// In case of prior muddled state
infoStage.delete();
imageStage.delete();
Os.link(mWallpaperInfo.getCanonicalPath(), infoStage.getCanonicalPath());
fullBackupFile(infoStage, data);
Os.link(mWallpaperFile.getCanonicalPath(), imageStage.getCanonicalPath());
fullBackupFile(imageStage, data);
} else {
if (DEBUG) {
Slog.v(TAG, "Wallpaper not backup-eligible; writing no data");
}
}
} catch (Exception e) {
Slog.e(TAG, "Unable to back up wallpaper: " + e.getMessage());
} finally {
if (DEBUG) {
Slog.v(TAG, "Removing backup stage links");
}
infoStage.delete();
imageStage.delete();
}
}
// We use the default onRestoreFile() implementation that will recreate our stage files,
// then post-process in onRestoreFinished() to apply the new wallpaper.
@Override
public void onRestoreFinished() {
if (DEBUG) {
Slog.v(TAG, "onRestoreFinished()");
}
final File infoStage = new File(getFilesDir(), INFO_STAGE);
final File imageStage = new File (getFilesDir(), IMAGE_STAGE);
try {
// It is valid for the imagery to be absent; it means that we were not permitted
// to back up the original image on the source device.
if (imageStage.exists()) {
if (DEBUG) {
Slog.v(TAG, "Got restored wallpaper; applying");
}
// Parse the restored info file to find the crop hint. Note that this currently
// relies on a priori knowledge of the wallpaper info file schema.
Rect cropHint = parseCropHint(infoStage);
if (cropHint != null) {
if (DEBUG) {
Slog.v(TAG, "Restored crop hint " + cropHint + "; now writing data");
}
WallpaperManager wm = getSystemService(WallpaperManager.class);
try (FileInputStream in = new FileInputStream(imageStage)) {
wm.setStream(in, cropHint, true, WallpaperManager.FLAG_SYSTEM);
} finally {} // auto-closes 'in'
}
}
} catch (Exception e) {
Slog.e(TAG, "Unable to restore wallpaper: " + e.getMessage());
} finally {
if (DEBUG) {
Slog.v(TAG, "Removing restore stage files");
}
infoStage.delete();
imageStage.delete();
}
}
private Rect parseCropHint(File wallpaperInfo) {
Rect cropHint = new Rect();
try (FileInputStream stream = new FileInputStream(wallpaperInfo)) {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(stream, StandardCharsets.UTF_8.name());
int type;
do {
type = parser.next();
if (type == XmlPullParser.START_TAG) {
String tag = parser.getName();
if ("wp".equals(tag)) {
cropHint.left = getAttributeInt(parser, "cropLeft", 0);
cropHint.top = getAttributeInt(parser, "cropTop", 0);
cropHint.right = getAttributeInt(parser, "cropRight", 0);
cropHint.bottom = getAttributeInt(parser, "cropBottom", 0);
}
}
} while (type != XmlPullParser.END_DOCUMENT);
} catch (Exception e) {
// Whoops; can't process the info file at all. Report failure.
Slog.w(TAG, "Failed to parse restored metadata: " + e.getMessage());
return null;
}
return cropHint;
}
private int getAttributeInt(XmlPullParser parser, String name, int defValue) {
final String value = parser.getAttributeValue(null, name);
return (value == null) ? defValue : Integer.parseInt(value);
}
//
// Key/value API: abstract, therefore required; but not used
//
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
ParcelFileDescriptor newState) throws IOException {
// Intentionally blank
}
@Override
public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState)
throws IOException {
// Intentionally blank
}
}
| |
/*
* Copyright 2016-present Open Networking 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.onosproject.tetopology.management.impl;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.onlab.packet.Ip4Address;
import org.onosproject.tetopology.management.api.DefaultNetwork;
import org.onosproject.tetopology.management.api.KeyId;
import org.onosproject.tetopology.management.api.Network;
import org.onosproject.tetopology.management.api.TeTopology;
import org.onosproject.tetopology.management.api.TeTopologyId;
import org.onosproject.tetopology.management.api.TeTopologyKey;
import org.onosproject.tetopology.management.api.link.DefaultNetworkLink;
import org.onosproject.tetopology.management.api.link.NetworkLink;
import org.onosproject.tetopology.management.api.link.NetworkLinkKey;
import org.onosproject.tetopology.management.api.link.TeLink;
import org.onosproject.tetopology.management.api.link.TeLinkTpGlobalKey;
import org.onosproject.tetopology.management.api.link.TeLinkTpKey;
import org.onosproject.tetopology.management.api.node.DefaultNetworkNode;
import org.onosproject.tetopology.management.api.node.DefaultTerminationPoint;
import org.onosproject.tetopology.management.api.node.NetworkNode;
import org.onosproject.tetopology.management.api.node.NetworkNodeKey;
import org.onosproject.tetopology.management.api.node.NodeTpKey;
import org.onosproject.tetopology.management.api.node.TeNode;
import org.onosproject.tetopology.management.api.node.TeNodeKey;
import org.onosproject.tetopology.management.api.node.TerminationPoint;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* TE Topology Manager utility functions.
*/
public final class TeMgrUtil {
private static final String TENODE_ID = "teNodeId/";
private static final String TELINK_ID = "/teLinkId/";
private static final String PROVIDER_ID = "providerId/";
private static final String CLIENT_ID = "/clientId/";
private static final String TOPOLOGY_ID = "/topologyId/";
// no instantiation
private TeMgrUtil() {
}
/**
* Returns the network link id for a TE link local key.
*
* @param key TE link local key
* @return value of network link id
*/
public static KeyId toNetworkLinkId(TeLinkTpKey key) {
return KeyId.keyId(new StringBuilder()
.append(TENODE_ID)
.append(Ip4Address.valueOf((int) key.teNodeId()).toString())
.append(TELINK_ID)
.append(key.teLinkTpId()).toString());
}
/**
* Returns the network id for a TE topology id.
*
* @param teTopologyId TE topology id
* @return value of network id
*/
public static KeyId toNetworkId(TeTopologyId teTopologyId) {
return KeyId.keyId(new StringBuilder()
.append(PROVIDER_ID)
.append(teTopologyId.providerId())
.append(CLIENT_ID)
.append(teTopologyId.clientId())
.append(TOPOLOGY_ID)
.append(teTopologyId.topologyId()).toString());
}
/**
* Returns the network id for a TE topology key.
*
* @param teTopologyKey TE topology key
* @return value of network id
*/
public static KeyId toNetworkId(TeTopologyKey teTopologyKey) {
return KeyId.keyId(new StringBuilder()
.append(PROVIDER_ID)
.append(teTopologyKey.providerId())
.append(CLIENT_ID)
.append(teTopologyKey.clientId())
.append(TOPOLOGY_ID)
.append(teTopologyKey.topologyId()).toString());
}
/**
* Returns the network node key for a TE node global key.
*
* @param teNodeKey TE node global key
* @return value of network node key
*/
public static NetworkNodeKey networkNodeKey(TeNodeKey teNodeKey) {
return new NetworkNodeKey(toNetworkId(teNodeKey.teTopologyKey()),
KeyId.keyId(Ip4Address
.valueOf((int) teNodeKey.teNodeId())
.toString()));
}
/**
* Returns the network link key for a TE link global key.
*
* @param teLinkKey TE link global key
* @return value of network link key
*/
public static NetworkLinkKey networkLinkKey(TeLinkTpGlobalKey teLinkKey) {
return new NetworkLinkKey(toNetworkId(teLinkKey.teTopologyKey()),
toNetworkLinkId(teLinkKey.teLinkTpKey()));
}
/**
* Returns the TE topology id for a TE topology.
*
* @param teTopology an instance of TE topology
* @return value of TE topology id
*/
public static TeTopologyId teTopologyId(TeTopology teTopology) {
return new TeTopologyId(teTopology.teTopologyId().providerId(),
teTopology.teTopologyId().clientId(),
teTopology.teTopologyIdStringValue());
}
/**
* Returns a default instance of termination point for a TE termination point id.
*
* @param teTpId TE termination point id
* @return an instance of termination point
*/
private static TerminationPoint tpBuilder(long teTpId) {
return new DefaultTerminationPoint(KeyId.keyId(Long.toString(teTpId)), null, teTpId);
}
/**
* Returns an instance of network node for a TE node.
*
* @param id value of the network node id
* @param teNode value of TE node
* @return an instance of network node
*/
public static NetworkNode nodeBuilder(KeyId id, TeNode teNode) {
List<NetworkNodeKey> supportingNodeIds = null;
if (teNode.supportingTeNodeId() != null) {
supportingNodeIds = Lists.newArrayList(networkNodeKey(teNode.supportingTeNodeId()));
}
Map<KeyId, TerminationPoint> tps = Maps.newConcurrentMap();
for (Long teTpid : teNode.teTerminationPointIds()) {
tps.put(KeyId.keyId(Long.toString(teTpid)), tpBuilder(teTpid));
}
return new DefaultNetworkNode(id, supportingNodeIds, teNode, tps);
}
/**
* Returns the network node termination point key for a TE link end point key.
*
* @param teLinkKey TE link end point key
* @return value of network node termination point key
*/
public static NodeTpKey nodeTpKey(TeLinkTpKey teLinkKey) {
return new NodeTpKey(KeyId.keyId(Ip4Address
.valueOf((int) teLinkKey.teNodeId()).toString()),
KeyId.keyId(Long.toString(teLinkKey.teLinkTpId())));
}
/**
* Returns an instance of network link for a TE link.
*
* @param id value of the network link id
* @param teLink value of TE link
* @return an instance of network link
*/
public static NetworkLink linkBuilder(KeyId id, TeLink teLink) {
NodeTpKey source = nodeTpKey(teLink.teLinkKey());
NodeTpKey destination = null;
if (teLink.peerTeLinkKey() != null) {
destination = nodeTpKey(teLink.peerTeLinkKey());
}
List<NetworkLinkKey> supportingLinkIds = null;
if (teLink.supportingTeLinkId() != null) {
supportingLinkIds = Lists.newArrayList(networkLinkKey(teLink.supportingTeLinkId()));
}
return new DefaultNetworkLink(id, source, destination, supportingLinkIds, teLink);
}
/**
* Returns an instance of network for a TE topology.
*
* @param teTopology value of TE topology
* @return an instance of network
*/
public static Network networkBuilder(TeTopology teTopology) {
KeyId networkId = TeMgrUtil.toNetworkId(teTopology.teTopologyId());
TeTopologyId topologyId = teTopologyId(teTopology);
Map<KeyId, NetworkNode> nodes = null;
if (MapUtils.isNotEmpty(teTopology.teNodes())) {
nodes = Maps.newHashMap();
for (TeNode tenode : teTopology.teNodes().values()) {
KeyId key = KeyId.keyId(Ip4Address
.valueOf((int) tenode.teNodeId()).toString());
nodes.put(key, nodeBuilder(key, tenode));
}
}
Map<KeyId, NetworkLink> links = null;
if (MapUtils.isNotEmpty(teTopology.teLinks())) {
links = Maps.newHashMap();
for (TeLink telink : teTopology.teLinks().values()) {
KeyId key = toNetworkLinkId(telink.teLinkKey());
links.put(key, linkBuilder(key, telink));
}
}
return new DefaultNetwork(networkId, null, nodes, links,
topologyId, false, teTopology.ownerId(),
teTopology.optimization());
}
}
| |
package net.ontrack.backend.dao.jdbc;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import net.ontrack.backend.BuildAlreadyExistsException;
import net.ontrack.backend.cache.Caches;
import net.ontrack.backend.dao.BuildDao;
import net.ontrack.backend.dao.PromotionLevelDao;
import net.ontrack.backend.dao.ValidationStampDao;
import net.ontrack.backend.dao.model.TBuild;
import net.ontrack.backend.dao.model.TPromotionLevel;
import net.ontrack.backend.dao.model.TValidationStamp;
import net.ontrack.backend.db.SQL;
import net.ontrack.core.model.*;
import net.ontrack.dao.AbstractJdbcDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import static java.lang.String.format;
@Component
public class BuildJdbcDao extends AbstractJdbcDao implements BuildDao {
private final RowMapper<TBuild> buildRowMapper = new RowMapper<TBuild>() {
@Override
public TBuild mapRow(ResultSet rs, int rowNum) throws SQLException {
return new TBuild(
rs.getInt("id"),
rs.getInt("branch"),
rs.getString("name"),
rs.getString("description")
);
}
};
private final ValidationStampDao validationStampDao;
private final PromotionLevelDao promotionLevelDao;
@Autowired
public BuildJdbcDao(DataSource dataSource, ValidationStampDao validationStampDao, PromotionLevelDao promotionLevelDao) {
super(dataSource);
this.validationStampDao = validationStampDao;
this.promotionLevelDao = promotionLevelDao;
}
@Override
@Transactional(readOnly = true)
@Cacheable(Caches.BUILD)
public TBuild getById(int id) {
return getNamedParameterJdbcTemplate().queryForObject(
SQL.BUILD,
params("id", id),
buildRowMapper
);
}
@Override
@Transactional(readOnly = true)
public TBuild findLastByBranch(int branch) {
return getFirstItem(
SQL.BUILD_LAST_BY_BRANCH,
params("branch", branch),
buildRowMapper
);
}
@Override
@Transactional(readOnly = true)
public Collection<TBuild> findByName(String name) {
return getNamedParameterJdbcTemplate().query(
SQL.BUILD_BY_NAME,
params("name", name),
buildRowMapper
);
}
@Override
@Transactional(readOnly = true)
public Integer findByBrandAndName(int branchId, String buildName) {
return getFirstItem(
SQL.BUILD_BY_BRANCH_AND_NAME,
params("branch", branchId).addValue("name", buildName),
Integer.class
);
}
@Override
@Transactional(readOnly = true)
public Integer findBuildAfterUsingNumericForm(int branchId, String buildName) {
return getFirstItem(
SQL.BUILD_BY_BRANCH_AND_NUMERIC_NAME,
params("branch", branchId).addValue("name", buildName),
Integer.class
);
}
@Override
@Transactional
public Ack delete(int buildId) {
return Ack.one(
getNamedParameterJdbcTemplate().update(
SQL.BUILD_DELETE,
params("id", buildId)
)
);
}
@Override
@Transactional
@CacheEvict(value = Caches.BUILD, key = "#buildId")
public Ack updateBuild(int buildId, String name, String description) {
try {
return Ack.one(
getNamedParameterJdbcTemplate().update(
SQL.BUILD_UPDATE,
params("id", buildId).addValue("name", name).addValue("description", description)
)
);
} catch (DuplicateKeyException ex) {
throw new BuildAlreadyExistsException(name);
}
}
@Override
@Transactional(readOnly = true)
public List<TBuild> findByBranch(int branch, int offset, int count) {
return getNamedParameterJdbcTemplate().query(
SQL.BUILD_LIST,
params("branch", branch).addValue("offset", offset).addValue("count", count),
buildRowMapper);
}
@Override
@Transactional(readOnly = true)
public List<TBuild> query(int branch, BuildFilter filter) {
// "Last build per promotion" overrides all other filters
if (filter.isForEachPromotionLevel()) {
return queryLastBuildForEachPromotionLevel(branch, filter);
}
// Query root
StringBuilder sql = new StringBuilder("SELECT DISTINCT(B.ID) FROM BUILD B" +
" LEFT JOIN PROMOTED_RUN PR ON PR.BUILD = B.ID" +
" LEFT JOIN PROMOTION_LEVEL PL ON PL.ID = PR.PROMOTION_LEVEL" +
" LEFT JOIN (" +
" SELECT R.BUILD, R.VALIDATION_STAMP, VRS.STATUS " +
" FROM VALIDATION_RUN R" +
" INNER JOIN VALIDATION_RUN_STATUS VRS ON VRS.ID = (SELECT ID FROM VALIDATION_RUN_STATUS WHERE VALIDATION_RUN = R.ID ORDER BY ID DESC LIMIT 1)" +
" AND R.RUN_ORDER = (SELECT MAX(RUN_ORDER) FROM VALIDATION_RUN WHERE BUILD = R.BUILD AND VALIDATION_STAMP = R.VALIDATION_STAMP)" +
" ) S ON S.BUILD = B.ID" +
" LEFT JOIN PROPERTIES PP ON PP.BUILD = B.ID" +
" WHERE B.BRANCH = :branch");
MapSqlParameterSource params = new MapSqlParameterSource("branch", branch);
Integer sinceBuildId = null;
// Since last promotion level
String sincePromotionLevel = filter.getSincePromotionLevel();
if (StringUtils.isNotBlank(sincePromotionLevel)) {
// Gets the promotion level ID
int promotionLevelId = promotionLevelDao.getByBranchAndName(branch, sincePromotionLevel).getId();
// Gets the last build having this promotion level
TBuild build = findLastBuildWithPromotionLevel(promotionLevelId);
if (build != null) {
sinceBuildId = build.getId();
}
}
// With promotion level
String withPromotionLevel = filter.getWithPromotionLevel();
if (StringUtils.isNotBlank(withPromotionLevel)) {
sql.append(" AND PL.NAME = :withPromotionLevel");
params.addValue("withPromotionLevel", withPromotionLevel);
}
// Since validation stamp
List<BuildValidationStampFilter> sinceValidationStamps = filter.getSinceValidationStamps();
if (sinceValidationStamps != null && !sinceValidationStamps.isEmpty()) {
for (BuildValidationStampFilter sinceValidationStamp : sinceValidationStamps) {
// Gets the validation stamp ID
int validationStampId = validationStampDao.getByBranchAndName(branch, sinceValidationStamp.getValidationStamp()).getId();
// Gets the last build having this validation stamp and the status
TBuild build = findLastBuildWithValidationStamp(validationStampId, sinceValidationStamp.getStatuses());
if (build != null) {
if (sinceBuildId == null) {
sinceBuildId = build.getId();
} else {
sinceBuildId = Math.min(sinceBuildId.intValue(), build.getId());
}
}
}
}
// With validation stamp
List<BuildValidationStampFilter> withValidationStamps = filter.getWithValidationStamps();
if (withValidationStamps != null && !withValidationStamps.isEmpty()) {
sql.append(" AND (");
int index = 0;
for (BuildValidationStampFilter stamp : withValidationStamps) {
if (index > 0) {
sql.append(" OR ");
}
TValidationStamp tstamp = validationStampDao.getByBranchAndName(branch, stamp.getValidationStamp());
sql.append(format("(S.VALIDATION_STAMP = :validationStamp%d", index));
params.addValue(format("validationStamp%d", index), tstamp.getId());
// Status criteria
Set<Status> statuses = stamp.getStatuses();
if (statuses != null && !statuses.isEmpty()) {
sql.append(format(" AND S.STATUS IN (%s)", getStatusesForSQLInClause(statuses)));
}
// OK for this validation stamp
sql.append(")");
index++;
}
sql.append(")");
}
// Since build?
if (sinceBuildId != null) {
sql.append(" AND B.ID >= :sinceBuildId");
params.addValue("sinceBuildId", sinceBuildId);
}
// Properties
PropertyValue withProperty = filter.getWithProperty();
if (withProperty != null) {
sql.append(" AND PP.EXTENSION = :propertyExtension AND PP.NAME = :propertyName");
params.addValue("propertyExtension", withProperty.getExtension());
params.addValue("propertyName", withProperty.getName());
String withPropertyValue = withProperty.getValue();
if (StringUtils.isNotBlank(withPropertyValue)) {
sql.append(" AND PP.VALUE REGEXP :propertyValue");
params.addValue("propertyValue", withPropertyValue);
}
}
// Ordering
sql.append(" ORDER BY B.ID DESC");
// Limit
sql.append(" LIMIT :limit");
params.addValue("limit", filter.getLimit());
// List of builds
return Lists.transform(
getNamedParameterJdbcTemplate().queryForList(
sql.toString(),
params,
Integer.class),
new Function<Integer, TBuild>() {
@Override
public TBuild apply(Integer id) {
return getById(id);
}
}
);
}
protected List<TBuild> queryLastBuildForEachPromotionLevel(int branch, BuildFilter filter) {
List<TBuild> builds = new ArrayList<>();
// List of promotion levels
List<TPromotionLevel> promotionLevels = promotionLevelDao.findByBranch(branch);
for (TPromotionLevel promotionLevel : promotionLevels) {
// Last build with promotion level
TBuild build = findLastBuildWithPromotionLevel(promotionLevel.getId());
if (build != null) {
builds.add(build);
}
}
// Sorts by build ID
Collections.sort(
builds,
new Comparator<TBuild>() {
@Override
public int compare(TBuild o1, TBuild o2) {
return o2.getId() - o1.getId();
}
}
);
// OK
return builds;
}
@Override
public TBuild findLastBuildWithValidationStamp(int validationStamp, Set<Status> statuses) {
StringBuilder sql = new StringBuilder(
"SELECT VR.BUILD FROM VALIDATION_RUN_STATUS VRS\n" +
"INNER JOIN VALIDATION_RUN VR ON VR.ID = VRS.VALIDATION_RUN\n" +
"WHERE VR.VALIDATION_STAMP = :validationStamp\n"
);
// Status criteria
if (statuses != null && !statuses.isEmpty()) {
sql.append(format("AND VRS.STATUS IN (%s)\n", getStatusesForSQLInClause(statuses)));
}
// Order & limit
sql.append("ORDER BY VR.BUILD DESC LIMIT 1\n");
// Parameters
MapSqlParameterSource params = params("validationStamp", validationStamp);
// Build ID
Integer buildId = getFirstItem(
sql.toString(),
params,
Integer.class
);
// OK
if (buildId != null) {
return getById(buildId);
} else {
return null;
}
}
@Override
public TBuild findLastBuildWithPromotionLevel(int promotionLevel) {
Integer buildId = getFirstItem(
SQL.BUILD_LAST_FOR_PROMOTION_LEVEL,
params("promotionLevel", promotionLevel),
Integer.class
);
if (buildId != null) {
return getById(buildId);
} else {
return null;
}
}
@Override
@Transactional
public int createBuild(int branch, String name, String description) {
try {
return dbCreate(
SQL.BUILD_CREATE,
params("branch", branch)
.addValue("name", name)
.addValue("description", description)
);
} catch (DuplicateKeyException ex) {
throw new BuildAlreadyExistsException(name);
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.IOException;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.LocalDirAllocator;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.MRConfig;
/**
* Manipulate the working area for the transient store for maps and reduces.
*
* This class is used by map and reduce tasks to identify the directories that
* they need to write to/read from for intermediate files. The callers of
* these methods are from child space and see mapreduce.cluster.local.dir as
* taskTracker/jobCache/jobId/attemptId
* This class should not be used from TaskTracker space.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public class MapOutputFile {
private JobConf conf;
static final String REDUCE_INPUT_FILE_FORMAT_STRING = "%s/map_%d.out";
public MapOutputFile() {
}
private LocalDirAllocator lDirAlloc =
new LocalDirAllocator(MRConfig.LOCAL_DIR);
/**
* Return the path to local map output file created earlier
*
* @return path
* @throws IOException
*/
public Path getOutputFile()
throws IOException {
return lDirAlloc.getLocalPathToRead(TaskTracker.OUTPUT + Path.SEPARATOR
+ "file.out", conf);
}
/**
* Create a local map output file name.
*
* @param size the size of the file
* @return path
* @throws IOException
*/
public Path getOutputFileForWrite(long size)
throws IOException {
return lDirAlloc.getLocalPathForWrite(TaskTracker.OUTPUT + Path.SEPARATOR
+ "file.out", size, conf);
}
/**
* Return the path to a local map output index file created earlier
*
* @return path
* @throws IOException
*/
public Path getOutputIndexFile()
throws IOException {
return lDirAlloc.getLocalPathToRead(TaskTracker.OUTPUT + Path.SEPARATOR
+ "file.out.index", conf);
}
/**
* Create a local map output index file name.
*
* @param size the size of the file
* @return path
* @throws IOException
*/
public Path getOutputIndexFileForWrite(long size)
throws IOException {
return lDirAlloc.getLocalPathForWrite(TaskTracker.OUTPUT + Path.SEPARATOR
+ "file.out.index", size, conf);
}
/**
* Return a local map spill file created earlier.
*
* @param spillNumber the number
* @return path
* @throws IOException
*/
public Path getSpillFile(int spillNumber)
throws IOException {
return lDirAlloc.getLocalPathToRead(TaskTracker.OUTPUT + "/spill"
+ spillNumber + ".out", conf);
}
/**
* Create a local map spill file name.
*
* @param spillNumber the number
* @param size the size of the file
* @return path
* @throws IOException
*/
public Path getSpillFileForWrite(int spillNumber, long size)
throws IOException {
return lDirAlloc.getLocalPathForWrite(TaskTracker.OUTPUT + "/spill"
+ spillNumber + ".out", size, conf);
}
/**
* Return a local map spill index file created earlier
*
* @param spillNumber the number
* @return path
* @throws IOException
*/
public Path getSpillIndexFile(int spillNumber)
throws IOException {
return lDirAlloc.getLocalPathToRead(TaskTracker.OUTPUT + "/spill"
+ spillNumber + ".out.index", conf);
}
/**
* Create a local map spill index file name.
*
* @param spillNumber the number
* @param size the size of the file
* @return path
* @throws IOException
*/
public Path getSpillIndexFileForWrite(int spillNumber, long size)
throws IOException {
return lDirAlloc.getLocalPathForWrite(TaskTracker.OUTPUT + "/spill"
+ spillNumber + ".out.index", size, conf);
}
/**
* Return a local reduce input file created earlier
*
* @param mapId a map task id
* @return path
* @throws IOException
*/
public Path getInputFile(int mapId)
throws IOException {
return lDirAlloc.getLocalPathToRead(String.format(
REDUCE_INPUT_FILE_FORMAT_STRING, TaskTracker.OUTPUT, Integer
.valueOf(mapId)), conf);
}
/**
* Create a local reduce input file name.
*
* @param mapId a map task id
* @param size the size of the file
* @return path
* @throws IOException
*/
public Path getInputFileForWrite(org.apache.hadoop.mapreduce.TaskID mapId,
long size)
throws IOException {
return lDirAlloc.getLocalPathForWrite(String.format(
REDUCE_INPUT_FILE_FORMAT_STRING, TaskTracker.OUTPUT, mapId.getId()),
size, conf);
}
/** Removes all of the files related to a task. */
public void removeAll()
throws IOException {
conf.deleteLocalFiles(TaskTracker.OUTPUT);
}
public void setConf(Configuration conf) {
if (conf instanceof JobConf) {
this.conf = (JobConf) conf;
} else {
this.conf = new JobConf(conf);
}
}
}
| |
/**
* 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.journal;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger;
import org.apache.activemq.artemis.tests.util.UnitTestCase;
import org.apache.activemq.artemis.core.journal.EncodingSupport;
import org.apache.activemq.artemis.core.journal.IOCompletion;
import org.apache.activemq.artemis.core.journal.Journal;
import org.apache.activemq.artemis.core.journal.LoaderCallback;
import org.apache.activemq.artemis.core.journal.PreparedTransactionInfo;
import org.apache.activemq.artemis.core.journal.RecordInfo;
import org.apache.activemq.artemis.core.journal.SequentialFileFactory;
import org.apache.activemq.artemis.core.journal.impl.AIOSequentialFileFactory;
import org.apache.activemq.artemis.core.journal.impl.JournalImpl;
import org.apache.activemq.artemis.utils.DataConstants;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class JournalPerfTuneTest extends UnitTestCase
{
private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER;
private Journal journal;
static final class LoaderCB implements LoaderCallback
{
public void addPreparedTransaction(PreparedTransactionInfo preparedTransaction)
{
// no-op
}
public void addRecord(RecordInfo info)
{
// no-op
}
public void deleteRecord(long id)
{
// no-op
}
public void updateRecord(RecordInfo info)
{
// no-op
}
public void failedTransaction(long transactionID, List<RecordInfo> records, List<RecordInfo> recordsToDelete)
{
// no-op
}
}
@Override
@Before
public void setUp() throws Exception
{
super.setUp();
final int fileSize = 1024 * 1024 * 10;
final int minFiles = 10;
final int compactMinFiles = 20;
final int compactPercentage = 30;
final String filePrefix = "data";
final String extension = "amq";
final int maxIO = 500;
final String journalDir = getTestDir();
final int bufferSize = 490 * 1024;
final int bufferTimeout = (int)(1000000000d / 2000);
final boolean logRates = true;
super.recreateDirectory(journalDir);
SequentialFileFactory fileFactory = new AIOSequentialFileFactory(journalDir, bufferSize, bufferTimeout, logRates);
journal = new JournalImpl(fileSize,
minFiles,
compactMinFiles,
compactPercentage,
fileFactory,
filePrefix,
extension,
maxIO);
addActiveMQComponent(journal);
journal.start();
journal.load(new LoaderCB());
}
static final class TestCallback implements IOCompletion
{
private final CountDownLatch latch;
TestCallback(final int counts)
{
this.latch = new CountDownLatch(counts);
}
public void await() throws Exception
{
waitForLatch(latch);
}
public void storeLineUp()
{
}
public void done()
{
latch.countDown();
log.info(latch.getCount());
}
public void onError(int errorCode, String errorMessage)
{
}
}
@Test
public void test1() throws Exception
{
final int itersPerThread = 10000000;
final int numThreads = 1;
this.callback = new TestCallback(2 * itersPerThread * numThreads);
Worker[] workers = new Worker[numThreads];
for (int i = 0; i < numThreads; i++)
{
workers[i] = new Worker(itersPerThread);
workers[i].start();
}
for (int i = 0; i < numThreads; i++)
{
workers[i].join();
}
callback.await();
}
private final AtomicLong idGen = new AtomicLong(0);
private TestCallback callback;
class Worker extends Thread
{
final int iters;
Worker(final int iters)
{
this.iters = iters;
}
@Override
public void run()
{
try
{
Record record = new Record(new byte[1024]);
for (int i = 0; i < iters; i++)
{
long id = idGen.getAndIncrement();
journal.appendAddRecord(id, (byte)0, record, true, callback);
journal.appendDeleteRecord(id, true, callback);
// log.info("did " + i);
}
}
catch (Exception e)
{
log.error("Failed", e);
}
}
}
static class Record implements EncodingSupport
{
private byte[] bytes;
Record(byte[] bytes)
{
this.bytes = bytes;
}
public void decode(ActiveMQBuffer buffer)
{
int length = buffer.readInt();
bytes = new byte[length];
buffer.readBytes(bytes);
}
public void encode(ActiveMQBuffer buffer)
{
buffer.writeInt(bytes.length);
buffer.writeBytes(bytes);
}
public int getEncodeSize()
{
return DataConstants.SIZE_INT + bytes.length;
}
}
}
| |
/*
* Copyright 2015 LG CNS.
*
* 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 scouter.client.views;
import java.util.HashMap;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.WorkbenchPage;
import org.eclipse.ui.part.ViewPart;
import scouter.client.Images;
import scouter.client.model.AgentDataProxy;
import scouter.client.model.DetachedManager;
import scouter.client.model.RefreshThread;
import scouter.client.model.RefreshThread.Refreshable;
import scouter.client.util.ChartUtil;
import scouter.client.util.ColorUtil;
import scouter.client.util.ExUtil;
import scouter.client.util.ImageUtil;
import scouter.client.util.ScouterUtil;
import scouter.client.util.SortUtil;
import scouter.client.util.UIUtil;
import scouter.client.util.UIUtil.ViewWithTable;
import scouter.lang.pack.MapPack;
import scouter.lang.value.ListValue;
import scouter.util.CastUtil;
import scouter.util.FormatUtil;
import scouter.util.StringUtil;
public class ObjectThreadListView extends ViewPart implements Refreshable, ViewWithTable{
public static final String ID = ObjectThreadListView.class.getName();
private Table table = null;
public int objHash;
public int serverId;
Action actAutoRefresh, actFilter;
protected RefreshThread thread = null;
Display display = null;
boolean refresh = false;
boolean asc;
int col_idx;
boolean isNum;
public HashMap<Long, Long> prevCpuMap = new HashMap<Long, Long>();
public void createPartControl(Composite parent) {
display = getSite().getShell().getDisplay();
parent.setLayout(ChartUtil.gridlayout(1));
Composite area2 = new Composite(parent, SWT.NONE);
area2.setLayout(ChartUtil.gridlayout(1));
area2.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
table = build(area2);
table.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
table.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F5) {
reload();
}
}
});
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
TableItem[] item = table.getSelection();
if (item == null || item.length == 0)
return;
long threadId = CastUtil.clong(item[0].getText(0));
try {
IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
ObjectThreadDetailView view = (ObjectThreadDetailView) win.getActivePage().showView(ObjectThreadDetailView.ID, serverId + "&" + objHash, IWorkbenchPage.VIEW_ACTIVATE);
view.setInput(threadId);
} catch (Exception d) {
}
}
});
IToolBarManager man = getViewSite().getActionBars().getToolBarManager();
man.add(new Action("reload", ImageUtil.getImageDescriptor(Images.refresh)) {
public void run() {
reload();
}
});
man.add(new Separator());
actAutoRefresh = new Action("Auto Refresh in 5 sec.", IAction.AS_CHECK_BOX){
public void run(){
if(actAutoRefresh.isChecked())
reload();
}
};
actAutoRefresh.setImageDescriptor(ImageUtil.getImageDescriptor(Images.refresh_auto));
man.add(actAutoRefresh);
}
public void setInput(int objHash, int serverId) {
this.objHash = objHash;
this.serverId = serverId;
reload();
if (thread == null) {
thread = new RefreshThread(this, 5000);
thread.start();
}
thread.setName(this.toString() + " - " + "objHash:"+objHash+", serverId:"+serverId);
}
public void reload() {
if (table == null)
return;
ExUtil.asyncRun(new Runnable() {
public void run() {
final MapPack mpack = AgentDataProxy.getThreadList(objHash, serverId);
if(mpack == null){
refresh = true;
return;
}else{
refresh = false;
}
ExUtil.exec(table, new Runnable() {
public void run() {
TableItem[] tItem = table.getItems();
ListValue idLv = mpack.getList("id");
ListValue nameLv = mpack.getList("name");
ListValue statLv = mpack.getList("stat");
ListValue cpuLv = mpack.getList("cpu");
ListValue txidLv = mpack.getList("txid");
ListValue elapsedLv = mpack.getList("elapsed");
ListValue serviceLv = mpack.getList("service");
int rows = idLv == null ? 0 : idLv.size();
for (int i = 0; i < rows; i++) {
TableItem t = null;
if(tItem != null && tItem.length > 0 && i < tItem.length && tItem[i] != null){
t = tItem[i];
}else{
t = new TableItem(table, SWT.NONE, i);
}
long threadId = idLv.getLong(i);
long cputime = cpuLv.getLong(i);
long delta = 0;
Long prevCpu = prevCpuMap.get(threadId);
if (prevCpu != null) {
delta = cputime - prevCpu.longValue();
}
prevCpuMap.put(threadId, cputime);
String[] datas = new String[] {
FormatUtil.print(threadId, "000"), //
CastUtil.cString(nameLv.get(i)),//
CastUtil.cString(statLv.get(i)),//
FormatUtil.print(cputime, "#,##0"),//
FormatUtil.print(delta, "#,##0"),//
CastUtil.cString(txidLv.get(i)),//
FormatUtil.print(elapsedLv.get(i), "#,##0"),//
CastUtil.cString(serviceLv.get(i)),//
};
for(int inx = 0 ; inx < datas.length ; inx++){
datas[inx] = StringUtil.trimToEmpty(datas[inx]);
}
t.setText(datas);
}
sortTable();
}
});
}
});
}
public void setColor(TableItem t) {
if (StringUtil.isNotEmpty(t.getText(7))) {
int time = CastUtil.cint(StringUtil.strip(t.getText(6), ","));
if (time > 8000) {
t.setForeground(ColorUtil.getInstance().getColor(SWT.COLOR_RED));
} else if (time > 3000) {
t.setForeground(ColorUtil.getInstance().getColor(SWT.COLOR_MAGENTA));
} else {
t.setForeground(ColorUtil.getInstance().getColor(SWT.COLOR_BLUE));
}
} else {
t.setForeground(ColorUtil.getInstance().getColor(SWT.COLOR_BLACK));
}
}
private Table build(Composite parent) {
final Table table = new Table(parent, SWT.BORDER | SWT.WRAP | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn[] cols = new TableColumn[8];
cols[0] = UIUtil.create(table, SWT.CENTER, "No", cols.length, 0, true, 40, this);
cols[1] = UIUtil.create(table, SWT.LEFT, "Name", cols.length, 1, false, 250, this);
cols[2] = UIUtil.create(table, SWT.CENTER, "Stat", cols.length, 2, false, 100, this);
cols[3] = UIUtil.create(table, SWT.RIGHT, "Cpu", cols.length, 3, true, 60, this);
cols[4] = UIUtil.create(table, SWT.RIGHT, "\u0394 Cpu", cols.length, 4, true, 60, this);
cols[5] = UIUtil.create(table, SWT.LEFT, "Txid", cols.length, 5, false, 70, this);
cols[6] = UIUtil.create(table, SWT.RIGHT, "Elapsed", cols.length, 6, true, 60, this);
cols[7] = UIUtil.create(table, SWT.LEFT, "Service Name", cols.length, 7, false, 200, this);
return table;
}
public void setSortCriteria(boolean asc, int col_idx, boolean isNum) {
this.asc = asc;
this.col_idx = col_idx;
this.isNum = isNum;
}
public void setTableItem(TableItem t) {
setColor(t);
}
public void setFocus() {
ScouterUtil.detachView(this);
}
@Override
public void dispose() {
super.dispose();
if(thread != null && thread.isAlive()){
thread.shutdown();
thread = null;
}
}
public void refresh() {
if(refresh || actAutoRefresh.isChecked()){
reload();
}
}
public void sortTable(){
int col_count = table.getColumnCount();
TableItem[] items = table.getItems();
if (isNum) {
new SortUtil(asc).sort_num(items, col_idx, col_count);
} else {
new SortUtil(asc).sort_str(items, col_idx, col_count);
}
for (int i = 0; i < items.length; i++) {
setColor(items[i]);
}
}
}
| |
package org.apache.maven.plugin.assembly.archive.task;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.model.Model;
import org.apache.maven.plugin.assembly.archive.ArchiveCreationException;
import org.apache.maven.plugin.assembly.archive.task.testutils.MockAndControlForAddFileSetsTask;
import org.apache.maven.plugin.assembly.format.AssemblyFormattingException;
import org.apache.maven.plugin.assembly.model.FileSet;
import org.apache.maven.plugin.assembly.testutils.MockManager;
import org.apache.maven.plugin.assembly.testutils.TestFileManager;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import junit.framework.TestCase;
public class AddFileSetsTaskTest
extends TestCase
{
private MockManager mockManager;
private TestFileManager fileManager;
private MockAndControlForAddFileSetsTask macTask;
@Override
public void setUp()
{
mockManager = new MockManager();
fileManager = new TestFileManager( "add-fileset.test.", "" );
macTask = new MockAndControlForAddFileSetsTask( mockManager, fileManager );
}
@Override
public void tearDown() throws IOException
{
fileManager.cleanUp();
}
public void testGetFileSetDirectory_ShouldReturnAbsoluteSourceDir()
throws ArchiveCreationException, AssemblyFormattingException
{
final File dir = fileManager.createTempDir();
final FileSet fs = new FileSet();
fs.setDirectory( dir.getAbsolutePath() );
final File result = new AddFileSetsTask( new ArrayList<FileSet>() ).getFileSetDirectory( fs, null, null );
assertEquals( dir.getAbsolutePath(), result.getAbsolutePath() );
}
public void testGetFileSetDirectory_ShouldReturnBasedir()
throws ArchiveCreationException, AssemblyFormattingException
{
final File dir = fileManager.createTempDir();
final FileSet fs = new FileSet();
final File result = new AddFileSetsTask( new ArrayList<FileSet>() ).getFileSetDirectory( fs, dir, null );
assertEquals( dir.getAbsolutePath(), result.getAbsolutePath() );
}
public void testGetFileSetDirectory_ShouldReturnDirFromBasedirAndSourceDir()
throws ArchiveCreationException, AssemblyFormattingException
{
final File dir = fileManager.createTempDir();
final String srcPath = "source";
final File srcDir = new File( dir, srcPath );
final FileSet fs = new FileSet();
fs.setDirectory( srcPath );
final File result = new AddFileSetsTask( new ArrayList<FileSet>() ).getFileSetDirectory( fs, dir, null );
assertEquals( srcDir.getAbsolutePath(), result.getAbsolutePath() );
}
public void testGetFileSetDirectory_ShouldReturnDirFromArchiveBasedirAndSourceDir()
throws ArchiveCreationException, AssemblyFormattingException
{
final File dir = fileManager.createTempDir();
final String srcPath = "source";
final File srcDir = new File( dir, srcPath );
final FileSet fs = new FileSet();
fs.setDirectory( srcPath );
final File result = new AddFileSetsTask( new ArrayList<FileSet>() ).getFileSetDirectory( fs, null, dir );
assertEquals( srcDir.getAbsolutePath(), result.getAbsolutePath() );
}
public void testAddFileSet_ShouldAddDirectory() throws ArchiveCreationException, AssemblyFormattingException
{
final FileSet fs = new FileSet();
final String dirname = "dir";
fs.setDirectory( dirname );
fs.setOutputDirectory( "dir2" );
// ensure this exists, so the directory addition will proceed.
final File srcDir = new File( macTask.archiveBaseDir, dirname );
srcDir.mkdirs();
final int[] modes = { -1, -1, -1, -1 };
macTask.expectAdditionOfSingleFileSet( null, null, null, true, modes, 1, true, false );
macTask.expectGetProject( null );
final MavenProject project = new MavenProject( new Model() );
mockManager.replayAll();
final AddFileSetsTask task = new AddFileSetsTask( new ArrayList<FileSet>() );
task.setLogger( new ConsoleLogger( Logger.LEVEL_DEBUG, "test" ) );
task.setProject( project );
task.addFileSet( fs, macTask.archiver, macTask.configSource, macTask.archiveBaseDir );
mockManager.verifyAll();
}
public void testAddFileSet_ShouldAddDirectoryUsingSourceDirNameForDestDir()
throws ArchiveCreationException, AssemblyFormattingException
{
final FileSet fs = new FileSet();
final String dirname = "dir";
fs.setDirectory( dirname );
final File archiveBaseDir = fileManager.createTempDir();
// ensure this exists, so the directory addition will proceed.
final File srcDir = new File( archiveBaseDir, dirname );
srcDir.mkdirs();
final int[] modes = { -1, -1, -1, -1 };
macTask.expectAdditionOfSingleFileSet( null, null, null, true, modes, 1, true, false );
macTask.expectGetProject( null );
final MavenProject project = new MavenProject( new Model() );
mockManager.replayAll();
final AddFileSetsTask task = new AddFileSetsTask( new ArrayList<FileSet>() );
task.setLogger( new ConsoleLogger( Logger.LEVEL_DEBUG, "test" ) );
task.setProject( project );
task.addFileSet( fs, macTask.archiver, macTask.configSource, archiveBaseDir );
mockManager.verifyAll();
}
public void testAddFileSet_ShouldNotAddDirectoryWhenSourceDirNonExistent()
throws ArchiveCreationException, AssemblyFormattingException
{
final FileSet fs = new FileSet();
final String dirname = "dir";
fs.setDirectory( dirname );
final File archiveBaseDir = fileManager.createTempDir();
macTask.expectGetFinalName( "finalName" );
macTask.expectGetProject( null );
macTask.archiver.getOverrideDirectoryMode();
macTask.archiverCtl.setReturnValue( -1 );
macTask.archiver.getOverrideFileMode();
macTask.archiverCtl.setReturnValue( -1 );
final MavenProject project = new MavenProject( new Model() );
mockManager.replayAll();
final AddFileSetsTask task = new AddFileSetsTask( new ArrayList<FileSet>() );
task.setLogger( new ConsoleLogger( Logger.LEVEL_DEBUG, "test" ) );
task.setProject( project );
task.addFileSet( fs, macTask.archiver, macTask.configSource, archiveBaseDir );
mockManager.verifyAll();
}
public void testExecute_ShouldThrowExceptionIfArchiveBasedirProvidedIsNonExistent()
throws AssemblyFormattingException
{
macTask.archiveBaseDir.delete();
macTask.expectGetArchiveBaseDirectory();
mockManager.replayAll();
final AddFileSetsTask task = new AddFileSetsTask( new ArrayList<FileSet>() );
try
{
task.execute( macTask.archiver, macTask.configSource );
fail( "Should throw exception due to non-existent archiveBasedir location that was provided." );
}
catch ( final ArchiveCreationException e )
{
// should do this, because it cannot use the provide archiveBasedir.
}
mockManager.verifyAll();
}
public void testExecute_ShouldThrowExceptionIfArchiveBasedirProvidedIsNotADirectory()
throws AssemblyFormattingException, IOException
{
final File archiveBaseDir = fileManager.createTempFile();
macTask.archiveBaseDir = archiveBaseDir;
macTask.expectGetArchiveBaseDirectory();
mockManager.replayAll();
final AddFileSetsTask task = new AddFileSetsTask( new ArrayList<FileSet>() );
try
{
task.execute( macTask.archiver, macTask.configSource );
fail( "Should throw exception due to non-directory archiveBasedir location that was provided." );
}
catch ( final ArchiveCreationException e )
{
// should do this, because it cannot use the provide archiveBasedir.
}
mockManager.verifyAll();
}
}
| |
/*
* Copyright 2022 The Hekate Project
*
* The Hekate Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.hekate.cluster.internal.gossip;
import io.hekate.cluster.ClusterAddress;
import io.hekate.cluster.ClusterNode;
import io.hekate.util.format.ToString;
import java.net.InetSocketAddress;
public abstract class GossipProtocol {
public enum Type {
LONG_TERM_CONNECT,
GOSSIP_UPDATE,
GOSSIP_UPDATE_DIGEST,
JOIN_REQUEST,
JOIN_ACCEPT,
JOIN_REJECT,
HEARTBEAT_REQUEST,
HEARTBEAT_REPLY
}
public abstract static class GossipMessage extends GossipProtocol {
private final ClusterAddress to;
public GossipMessage(ClusterAddress from, ClusterAddress to) {
super(from);
this.to = to;
}
public ClusterAddress to() {
return to;
}
@Override
public InetSocketAddress toAddress() {
return to.socket();
}
}
public static class LongTermConnect extends GossipMessage {
public LongTermConnect(ClusterAddress from, ClusterAddress to) {
super(from, to);
}
@Override
public Type type() {
return Type.LONG_TERM_CONNECT;
}
}
public static class HeartbeatReply extends GossipMessage {
public HeartbeatReply(ClusterAddress from, ClusterAddress to) {
super(from, to);
}
@Override
public Type type() {
return Type.HEARTBEAT_REPLY;
}
}
public static class HeartbeatRequest extends GossipMessage {
public HeartbeatRequest(ClusterAddress from, ClusterAddress to) {
super(from, to);
}
@Override
public Type type() {
return Type.HEARTBEAT_REQUEST;
}
}
public abstract static class JoinReply extends GossipMessage {
public JoinReply(ClusterAddress from, ClusterAddress to) {
super(from, to);
}
public abstract boolean isAccept();
public abstract JoinAccept asAccept();
public abstract JoinReject asReject();
}
public static class JoinAccept extends JoinReply {
private final Gossip gossip;
public JoinAccept(ClusterAddress from, ClusterAddress to, Gossip gossip) {
super(from, to);
this.gossip = gossip;
}
public Gossip gossip() {
return gossip;
}
@Override
public boolean isAccept() {
return true;
}
@Override
public JoinAccept asAccept() {
return this;
}
@Override
public JoinReject asReject() {
throw new UnsupportedOperationException(getClass().getSimpleName()
+ " can't be used as " + JoinReject.class.getSimpleName());
}
@Override
public Type type() {
return Type.JOIN_ACCEPT;
}
}
public static class JoinReject extends JoinReply {
public enum RejectType {
TEMPORARY,
PERMANENT,
FATAL,
CONFLICT
}
private final RejectType rejectType;
private final InetSocketAddress rejectedAddress;
private final String reason;
public JoinReject(ClusterAddress from, ClusterAddress to, InetSocketAddress rejectedAddress, RejectType rejectType,
String reason) {
super(from, to);
this.rejectedAddress = rejectedAddress;
this.rejectType = rejectType;
this.reason = reason;
}
public static JoinReject permanent(ClusterAddress from, ClusterAddress to, InetSocketAddress rejectedAddress) {
return new JoinReject(from, to, rejectedAddress, RejectType.PERMANENT, null);
}
public static JoinReject retryLater(ClusterAddress from, ClusterAddress to, InetSocketAddress rejectedAddress) {
return new JoinReject(from, to, rejectedAddress, RejectType.TEMPORARY, null);
}
public static JoinReject fatal(ClusterAddress from, ClusterAddress to, InetSocketAddress rejectedAddress, String reason) {
return new JoinReject(from, to, rejectedAddress, RejectType.FATAL, reason);
}
public static JoinReject conflict(ClusterAddress from, ClusterAddress to, InetSocketAddress rejectedAddress) {
return new JoinReject(from, to, rejectedAddress, RejectType.CONFLICT, null);
}
public RejectType rejectType() {
return rejectType;
}
public String reason() {
return reason;
}
public InetSocketAddress rejectedAddress() {
return rejectedAddress;
}
@Override
public boolean isAccept() {
return false;
}
@Override
public JoinAccept asAccept() {
throw new UnsupportedOperationException(getClass().getSimpleName()
+ " can't be used as " + JoinAccept.class.getSimpleName());
}
@Override
public JoinReject asReject() {
return this;
}
@Override
public Type type() {
return Type.JOIN_REJECT;
}
}
public static class JoinRequest extends GossipProtocol {
private final ClusterNode fromNode;
private final InetSocketAddress to;
private final String namespace;
public JoinRequest(ClusterNode from, String namespace, InetSocketAddress to) {
super(from.address());
this.namespace = namespace;
this.fromNode = from;
this.to = to;
}
public ClusterNode fromNode() {
return fromNode;
}
public String namespace() {
return namespace;
}
@Override
public InetSocketAddress toAddress() {
return to;
}
@Override
public Type type() {
return Type.JOIN_REQUEST;
}
}
public abstract static class UpdateBase extends GossipMessage {
public UpdateBase(ClusterAddress from, ClusterAddress to) {
super(from, to);
}
public abstract GossipBase gossipBase();
public abstract Update asUpdate();
}
public static class Update extends UpdateBase {
private final Gossip gossip;
public Update(ClusterAddress from, ClusterAddress to, Gossip gossip) {
super(from, to);
this.gossip = gossip;
}
public Gossip gossip() {
return gossip;
}
@Override
public GossipBase gossipBase() {
return gossip;
}
@Override
public Update asUpdate() {
return this;
}
@Override
public Type type() {
return Type.GOSSIP_UPDATE;
}
}
public static class UpdateDigest extends UpdateBase {
private final GossipDigest digest;
public UpdateDigest(ClusterAddress from, ClusterAddress to, GossipDigest digest) {
super(from, to);
this.digest = digest;
}
public GossipDigest digest() {
return digest;
}
@Override
public GossipBase gossipBase() {
return digest;
}
@Override
public Update asUpdate() {
return null;
}
@Override
public Type type() {
return Type.GOSSIP_UPDATE_DIGEST;
}
}
private final ClusterAddress from;
public GossipProtocol(ClusterAddress from) {
this.from = from;
}
public abstract Type type();
public abstract InetSocketAddress toAddress();
public ClusterAddress from() {
return from;
}
@Override
public String toString() {
return ToString.format(this);
}
}
| |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// 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: 2015.08.07 at 06:17:52 PM CEST
//
package org.w3._1998.math.mathml;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import java.math.BigInteger;
import java.util.ArrayList;
/**
* <p>Java class for declare.type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="declare.type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <group ref="{http://www.w3.org/1998/Math/MathML}declare.content" maxOccurs="unbounded"/>
* <attGroup ref="{http://www.w3.org/1998/Math/MathML}declare.attlist"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "declare.type", propOrder = {
"cnsAndCisAndCsymbols"
})
@XmlRootElement(name = "declare")
public class Declare {
@XmlElementRefs({
@XmlElementRef(name = "menclose", namespace = "http://www.w3.org/1998/Math/MathML", type = Menclose.class, required = false),
@XmlElementRef(name = "interval", namespace = "http://www.w3.org/1998/Math/MathML", type = Interval.class, required = false),
@XmlElementRef(name = "tan", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "piecewise", namespace = "http://www.w3.org/1998/Math/MathML", type = Piecewise.class, required = false),
@XmlElementRef(name = "ceiling", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "factorof", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "mover", namespace = "http://www.w3.org/1998/Math/MathML", type = Mover.class, required = false),
@XmlElementRef(name = "arcsin", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "msubsup", namespace = "http://www.w3.org/1998/Math/MathML", type = Msubsup.class, required = false),
@XmlElementRef(name = "variance", namespace = "http://www.w3.org/1998/Math/MathML", type = Variance.class, required = false),
@XmlElementRef(name = "product", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "mtext", namespace = "http://www.w3.org/1998/Math/MathML", type = Mtext.class, required = false),
@XmlElementRef(name = "mode", namespace = "http://www.w3.org/1998/Math/MathML", type = Mode.class, required = false),
@XmlElementRef(name = "power", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "divergence", namespace = "http://www.w3.org/1998/Math/MathML", type = Divergence.class, required = false),
@XmlElementRef(name = "matrix", namespace = "http://www.w3.org/1998/Math/MathML", type = Matrix.class, required = false),
@XmlElementRef(name = "logbase", namespace = "http://www.w3.org/1998/Math/MathML", type = Logbase.class, required = false),
@XmlElementRef(name = "degree", namespace = "http://www.w3.org/1998/Math/MathML", type = Degree.class, required = false),
@XmlElementRef(name = "outerproduct", namespace = "http://www.w3.org/1998/Math/MathML", type = Outerproduct.class, required = false),
@XmlElementRef(name = "mfenced", namespace = "http://www.w3.org/1998/Math/MathML", type = Mfenced.class, required = false),
@XmlElementRef(name = "prsubset", namespace = "http://www.w3.org/1998/Math/MathML", type = Prsubset.class, required = false),
@XmlElementRef(name = "msup", namespace = "http://www.w3.org/1998/Math/MathML", type = Msup.class, required = false),
@XmlElementRef(name = "mphantom", namespace = "http://www.w3.org/1998/Math/MathML", type = Mphantom.class, required = false),
@XmlElementRef(name = "grad", namespace = "http://www.w3.org/1998/Math/MathML", type = Grad.class, required = false),
@XmlElementRef(name = "vectorproduct", namespace = "http://www.w3.org/1998/Math/MathML", type = Vectorproduct.class, required = false),
@XmlElementRef(name = "plus", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "emptyset", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "notprsubset", namespace = "http://www.w3.org/1998/Math/MathML", type = Notprsubset.class, required = false),
@XmlElementRef(name = "card", namespace = "http://www.w3.org/1998/Math/MathML", type = Card.class, required = false),
@XmlElementRef(name = "mstyle", namespace = "http://www.w3.org/1998/Math/MathML", type = Mstyle.class, required = false),
@XmlElementRef(name = "bvar", namespace = "http://www.w3.org/1998/Math/MathML", type = Bvar.class, required = false),
@XmlElementRef(name = "cos", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "min", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "partialdiff", namespace = "http://www.w3.org/1998/Math/MathML", type = Partialdiff.class, required = false),
@XmlElementRef(name = "real", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "msub", namespace = "http://www.w3.org/1998/Math/MathML", type = Msub.class, required = false),
@XmlElementRef(name = "lcm", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "mroot", namespace = "http://www.w3.org/1998/Math/MathML", type = Mroot.class, required = false),
@XmlElementRef(name = "domainofapplication", namespace = "http://www.w3.org/1998/Math/MathML", type = Domainofapplication.class, required = false),
@XmlElementRef(name = "laplacian", namespace = "http://www.w3.org/1998/Math/MathML", type = Laplacian.class, required = false),
@XmlElementRef(name = "or", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "declare", namespace = "http://www.w3.org/1998/Math/MathML", type = Declare.class, required = false),
@XmlElementRef(name = "leq", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "cartesianproduct", namespace = "http://www.w3.org/1998/Math/MathML", type = Cartesianproduct.class, required = false),
@XmlElementRef(name = "cot", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "arcsec", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "csc", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "gt", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "approx", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "exponentiale", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "union", namespace = "http://www.w3.org/1998/Math/MathML", type = Union.class, required = false),
@XmlElementRef(name = "image", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "exp", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "arcsinh", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "rationals", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "in", namespace = "http://www.w3.org/1998/Math/MathML", type = In.class, required = false),
@XmlElementRef(name = "tanh", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "divide", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "condition", namespace = "http://www.w3.org/1998/Math/MathML", type = Condition.class, required = false),
@XmlElementRef(name = "arccsch", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "mn", namespace = "http://www.w3.org/1998/Math/MathML", type = Mn.class, required = false),
@XmlElementRef(name = "arctanh", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "uplimit", namespace = "http://www.w3.org/1998/Math/MathML", type = Uplimit.class, required = false),
@XmlElementRef(name = "naturalnumbers", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "notsubset", namespace = "http://www.w3.org/1998/Math/MathML", type = Notsubset.class, required = false),
@XmlElementRef(name = "intersect", namespace = "http://www.w3.org/1998/Math/MathML", type = Intersect.class, required = false),
@XmlElementRef(name = "imaginaryi", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "eq", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "cn", namespace = "http://www.w3.org/1998/Math/MathML", type = Cn.class, required = false),
@XmlElementRef(name = "minus", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "true", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ci", namespace = "http://www.w3.org/1998/Math/MathML", type = Ci.class, required = false),
@XmlElementRef(name = "arg", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "lowlimit", namespace = "http://www.w3.org/1998/Math/MathML", type = Lowlimit.class, required = false),
@XmlElementRef(name = "pi", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ident", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "mtable", namespace = "http://www.w3.org/1998/Math/MathML", type = Mtable.class, required = false),
@XmlElementRef(name = "domain", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "malignmark", namespace = "http://www.w3.org/1998/Math/MathML", type = Malignmark.class, required = false),
@XmlElementRef(name = "sum", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "apply", namespace = "http://www.w3.org/1998/Math/MathML", type = Apply.class, required = false),
@XmlElementRef(name = "mpadded", namespace = "http://www.w3.org/1998/Math/MathML", type = Mpadded.class, required = false),
@XmlElementRef(name = "sec", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "mo", namespace = "http://www.w3.org/1998/Math/MathML", type = Mo.class, required = false),
@XmlElementRef(name = "momentabout", namespace = "http://www.w3.org/1998/Math/MathML", type = Momentabout.class, required = false),
@XmlElementRef(name = "and", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "arctan", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "root", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "subset", namespace = "http://www.w3.org/1998/Math/MathML", type = Subset.class, required = false),
@XmlElementRef(name = "notin", namespace = "http://www.w3.org/1998/Math/MathML", type = Notin.class, required = false),
@XmlElementRef(name = "coth", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "csch", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "maction", namespace = "http://www.w3.org/1998/Math/MathML", type = Maction.class, required = false),
@XmlElementRef(name = "tendsto", namespace = "http://www.w3.org/1998/Math/MathML", type = Tendsto.class, required = false),
@XmlElementRef(name = "reals", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "false", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "scalarproduct", namespace = "http://www.w3.org/1998/Math/MathML", type = Scalarproduct.class, required = false),
@XmlElementRef(name = "inverse", namespace = "http://www.w3.org/1998/Math/MathML", type = Inverse.class, required = false),
@XmlElementRef(name = "integers", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "neq", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "infinity", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "lt", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "eulergamma", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "times", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "notanumber", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "munder", namespace = "http://www.w3.org/1998/Math/MathML", type = Munder.class, required = false),
@XmlElementRef(name = "arccosh", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "arccos", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "forall", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "int", namespace = "http://www.w3.org/1998/Math/MathML", type = Int.class, required = false),
@XmlElementRef(name = "codomain", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "setdiff", namespace = "http://www.w3.org/1998/Math/MathML", type = Setdiff.class, required = false),
@XmlElementRef(name = "sinh", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "transpose", namespace = "http://www.w3.org/1998/Math/MathML", type = Transpose.class, required = false),
@XmlElementRef(name = "semantics", namespace = "http://www.w3.org/1998/Math/MathML", type = Semantics.class, required = false),
@XmlElementRef(name = "selector", namespace = "http://www.w3.org/1998/Math/MathML", type = Selector.class, required = false),
@XmlElementRef(name = "sdev", namespace = "http://www.w3.org/1998/Math/MathML", type = Sdev.class, required = false),
@XmlElementRef(name = "arccot", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "mi", namespace = "http://www.w3.org/1998/Math/MathML", type = Mi.class, required = false),
@XmlElementRef(name = "implies", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "rem", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "csymbol", namespace = "http://www.w3.org/1998/Math/MathML", type = Csymbol.class, required = false),
@XmlElementRef(name = "complexes", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ln", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "limit", namespace = "http://www.w3.org/1998/Math/MathML", type = Limit.class, required = false),
@XmlElementRef(name = "sech", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "equivalent", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "maligngroup", namespace = "http://www.w3.org/1998/Math/MathML", type = Maligngroup.class, required = false),
@XmlElementRef(name = "arccoth", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "xor", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "lambda", namespace = "http://www.w3.org/1998/Math/MathML", type = Lambda.class, required = false),
@XmlElementRef(name = "exists", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "vector", namespace = "http://www.w3.org/1998/Math/MathML", type = Vector.class, required = false),
@XmlElementRef(name = "list", namespace = "http://www.w3.org/1998/Math/MathML", type = org.w3._1998.math.mathml.List.class, required = false),
@XmlElementRef(name = "cosh", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "curl", namespace = "http://www.w3.org/1998/Math/MathML", type = Curl.class, required = false),
@XmlElementRef(name = "msqrt", namespace = "http://www.w3.org/1998/Math/MathML", type = Msqrt.class, required = false),
@XmlElementRef(name = "abs", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "sin", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "geq", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "mfrac", namespace = "http://www.w3.org/1998/Math/MathML", type = Mfrac.class, required = false),
@XmlElementRef(name = "moment", namespace = "http://www.w3.org/1998/Math/MathML", type = Moment.class, required = false),
@XmlElementRef(name = "max", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "mmultiscripts", namespace = "http://www.w3.org/1998/Math/MathML", type = Mmultiscripts.class, required = false),
@XmlElementRef(name = "quotient", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "gcd", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "ms", namespace = "http://www.w3.org/1998/Math/MathML", type = Ms.class, required = false),
@XmlElementRef(name = "imaginary", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "munderover", namespace = "http://www.w3.org/1998/Math/MathML", type = Munderover.class, required = false),
@XmlElementRef(name = "mean", namespace = "http://www.w3.org/1998/Math/MathML", type = Mean.class, required = false),
@XmlElementRef(name = "compose", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "set", namespace = "http://www.w3.org/1998/Math/MathML", type = Set.class, required = false),
@XmlElementRef(name = "mspace", namespace = "http://www.w3.org/1998/Math/MathML", type = Mspace.class, required = false),
@XmlElementRef(name = "mrow", namespace = "http://www.w3.org/1998/Math/MathML", type = Mrow.class, required = false),
@XmlElementRef(name = "median", namespace = "http://www.w3.org/1998/Math/MathML", type = Median.class, required = false),
@XmlElementRef(name = "primes", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "log", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "floor", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "arccsc", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "determinant", namespace = "http://www.w3.org/1998/Math/MathML", type = Determinant.class, required = false),
@XmlElementRef(name = "not", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "diff", namespace = "http://www.w3.org/1998/Math/MathML", type = Diff.class, required = false),
@XmlElementRef(name = "arcsech", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "conjugate", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false),
@XmlElementRef(name = "merror", namespace = "http://www.w3.org/1998/Math/MathML", type = Merror.class, required = false),
@XmlElementRef(name = "factorial", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class, required = false)
})
protected java.util.List<Object> cnsAndCisAndCsymbols;
@XmlAttribute(name = "type")
protected String type;
@XmlAttribute(name = "scope")
protected String scope;
@XmlAttribute(name = "nargs")
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger nargs;
@XmlAttribute(name = "occurrence")
protected String occurrence;
@XmlAttribute(name = "encoding")
protected String encoding;
@XmlAttribute(name = "definitionURL")
@XmlSchemaType(name = "anyURI")
protected String definitionURL;
/**
* Gets the value of the cnsAndCisAndCsymbols 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 cnsAndCisAndCsymbols property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCnsAndCisAndCsymbols().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Menclose }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Interval }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Piecewise }
* {@link JAXBElement }{@code <}{@link RelationsType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Mover }
* {@link Variance }
* {@link Msubsup }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Mode }
* {@link Mtext }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Matrix }
* {@link Divergence }
* {@link Logbase }
* {@link Outerproduct }
* {@link Degree }
* {@link Mfenced }
* {@link Prsubset }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Vectorproduct }
* {@link Grad }
* {@link Mphantom }
* {@link Msup }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link Card }
* {@link Notprsubset }
* {@link Mstyle }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Bvar }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Partialdiff }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Msub }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Domainofapplication }
* {@link Mroot }
* {@link Laplacian }
* {@link JAXBElement }{@code <}{@link LogicType }{@code >}
* {@link JAXBElement }{@code <}{@link RelationsType }{@code >}
* {@link Declare }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Cartesianproduct }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link RelationsType }{@code >}
* {@link JAXBElement }{@code <}{@link RelationsType }{@code >}
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link Union }
* {@link JAXBElement }{@code <}{@link FunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link In }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Condition }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Mn }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Uplimit }
* {@link Notsubset }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link Intersect }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link JAXBElement }{@code <}{@link RelationsType }{@code >}
* {@link Cn }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link Ci }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Lowlimit }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link JAXBElement }{@code <}{@link FunctionsType }{@code >}
* {@link Mtable }
* {@link JAXBElement }{@code <}{@link FunctionsType }{@code >}
* {@link Malignmark }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Apply }
* {@link Mpadded }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Mo }
* {@link Momentabout }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Subset }
* {@link Notin }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Maction }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link Tendsto }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link Scalarproduct }
* {@link JAXBElement }{@code <}{@link RelationsType }{@code >}
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link Inverse }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link JAXBElement }{@code <}{@link RelationsType }{@code >}
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Munder }
* {@link JAXBElement }{@code <}{@link LogicType }{@code >}
* {@link Int }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Setdiff }
* {@link JAXBElement }{@code <}{@link FunctionsType }{@code >}
* {@link Transpose }
* {@link Semantics }
* {@link Selector }
* {@link Sdev }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link LogicType }{@code >}
* {@link Mi }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Csymbol }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Limit }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link RelationsType }{@code >}
* {@link JAXBElement }{@code <}{@link LogicType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Maligngroup }
* {@link JAXBElement }{@code <}{@link LogicType }{@code >}
* {@link Lambda }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link org.w3._1998.math.mathml.List }
* {@link Vector }
* {@link Curl }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Msqrt }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link RelationsType }{@code >}
* {@link Mfrac }
* {@link Moment }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Mmultiscripts }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Ms }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link Munderover }
* {@link JAXBElement }{@code <}{@link FunctionsType }{@code >}
* {@link Mean }
* {@link Set }
* {@link Mspace }
* {@link Mrow }
* {@link JAXBElement }{@code <}{@link ConstantType }{@code >}
* {@link Median }
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Determinant }
* {@link JAXBElement }{@code <}{@link LogicType }{@code >}
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
* {@link JAXBElement }{@code <}{@link ElementaryFunctionsType }{@code >}
* {@link Diff }
* {@link Merror }
* {@link JAXBElement }{@code <}{@link ArithType }{@code >}
*
*
*/
public java.util.List<Object> getCnsAndCisAndCsymbols() {
if (cnsAndCisAndCsymbols == null) {
cnsAndCisAndCsymbols = new ArrayList<>();
}
return this.cnsAndCisAndCsymbols;
}
/**
* 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 scope property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getScope() {
return scope;
}
/**
* Sets the value of the scope property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setScope(String value) {
this.scope = value;
}
/**
* Gets the value of the nargs property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNargs() {
return nargs;
}
/**
* Sets the value of the nargs property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNargs(BigInteger value) {
this.nargs = value;
}
/**
* Gets the value of the occurrence property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOccurrence() {
return occurrence;
}
/**
* Sets the value of the occurrence property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOccurrence(String value) {
this.occurrence = value;
}
/**
* Gets the value of the encoding property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEncoding() {
return encoding;
}
/**
* Sets the value of the encoding property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEncoding(String value) {
this.encoding = value;
}
/**
* Gets the value of the definitionURL property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefinitionURL() {
return definitionURL;
}
/**
* Sets the value of the definitionURL property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefinitionURL(String value) {
this.definitionURL = value;
}
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.committed;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.DefaultTreeExpander;
import com.intellij.ide.TreeExpander;
import com.intellij.ide.actions.ContextHelpAction;
import com.intellij.ide.ui.SplitterProportionsDataImpl;
import com.intellij.ide.util.treeView.TreeState;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.progress.util.BackgroundTaskUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.SplitterProportionsData;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsActions;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.changes.issueLinks.TreeLinkMouseListener;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.ui.*;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.ui.treeStructure.actions.CollapseAllAction;
import com.intellij.ui.treeStructure.actions.ExpandAllAction;
import com.intellij.util.containers.LinkedMultiMap;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.messages.Topic;
import com.intellij.util.ui.StatusText;
import com.intellij.util.ui.tree.TreeUtil;
import com.intellij.util.ui.tree.WideSelectionTreeUI;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.TreeUI;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.List;
import java.util.*;
import static com.intellij.openapi.keymap.KeymapUtil.getActiveKeymapShortcuts;
import static com.intellij.openapi.vcs.changes.ChangesUtil.getFiles;
import static com.intellij.openapi.vcs.changes.ChangesUtil.getNavigatableArray;
import static com.intellij.util.WaitForProgressToShow.runOrInvokeLaterAboveProgress;
/**
* @author yole
*/
public class CommittedChangesTreeBrowser extends JPanel implements TypeSafeDataProvider, Disposable, DecoratorManager {
private static final Border RIGHT_BORDER = IdeBorderFactory.createBorder(SideBorder.TOP | SideBorder.LEFT);
private final Project myProject;
@NotNull private final ChangesBrowserTree myChangesTree;
private final MyRepositoryChangesViewer myDetailsView;
private List<CommittedChangeList> myChangeLists;
private List<CommittedChangeList> mySelectedChangeLists;
@NotNull private ChangeListGroupingStrategy myGroupingStrategy = new DateChangeListGroupingStrategy();
private final CompositeChangeListFilteringStrategy myFilteringStrategy = new CompositeChangeListFilteringStrategy();
private final JPanel myLeftPanel;
private final FilterChangeListener myFilterChangeListener = new FilterChangeListener();
private final SplitterProportionsData mySplitterProportionsData = new SplitterProportionsDataImpl();
private final CopyProvider myCopyProvider;
private final TreeExpander myTreeExpander;
private String myHelpId;
public static final Topic<CommittedChangesReloadListener> ITEMS_RELOADED =
new Topic<>("ITEMS_RELOADED", CommittedChangesReloadListener.class);
private final List<CommittedChangeListDecorator> myDecorators;
@NonNls public static final String ourHelpId = "reference.changesToolWindow.incoming";
private WiseSplitter myInnerSplitter;
private final MessageBusConnection myConnection;
private TreeState myState;
public CommittedChangesTreeBrowser(final Project project, final List<CommittedChangeList> changeLists) {
super(new BorderLayout());
myProject = project;
myDecorators = new LinkedList<>();
myChangeLists = new ArrayList<>(changeLists);
myChangesTree = new ChangesBrowserTree();
myChangesTree.setRootVisible(false);
myChangesTree.setShowsRootHandles(true);
myChangesTree.setCellRenderer(new CommittedChangeListRenderer(project, myDecorators));
TreeUtil.expandAll(myChangesTree);
myChangesTree.setExpandableItemsEnabled(false);
myDetailsView = new MyRepositoryChangesViewer(project);
myChangesTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
updateBySelectionChange();
}
});
myChangesTree.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
myChangesTree.invalidateNodeSizes();
}
});
final TreeLinkMouseListener linkMouseListener = new TreeLinkMouseListener(new CommittedChangeListRenderer(project, myDecorators));
linkMouseListener.installOn(myChangesTree);
myLeftPanel = new JPanel(new BorderLayout());
initSplitters();
updateBySelectionChange();
Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
CustomShortcutSet quickdocShortcuts = new CustomShortcutSet(keymap.getShortcuts(IdeActions.ACTION_QUICK_JAVADOC));
EmptyAction.registerWithShortcutSet("CommittedChanges.Details", quickdocShortcuts, this);
myCopyProvider = new TreeCopyProvider(myChangesTree);
myTreeExpander = new DefaultTreeExpander(myChangesTree);
myDetailsView.addToolbarAction(ActionManager.getInstance().getAction("Vcs.ShowTabbedFileHistory"));
myHelpId = ourHelpId;
myDetailsView.getDiffAction().registerCustomShortcutSet(myDetailsView.getDiffAction().getShortcutSet(), myChangesTree);
myConnection = myProject.getMessageBus().connect();
myConnection.subscribe(ITEMS_RELOADED, new CommittedChangesReloadListener() {
@Override
public void itemsReloaded() {
}
@Override
public void emptyRefresh() {
updateGrouping();
}
});
}
private void initSplitters() {
final Splitter filterSplitter = new Splitter(false, 0.5f);
filterSplitter.setSecondComponent(ScrollPaneFactory.createScrollPane(myChangesTree));
myLeftPanel.add(filterSplitter, BorderLayout.CENTER);
final Splitter mainSplitter = new Splitter(false, 0.7f);
mainSplitter.setFirstComponent(myLeftPanel);
mainSplitter.setSecondComponent(myDetailsView);
add(mainSplitter, BorderLayout.CENTER);
myInnerSplitter = new WiseSplitter(() -> {
filterSplitter.doLayout();
updateModel();
}, filterSplitter);
Disposer.register(this, myInnerSplitter);
mySplitterProportionsData.externalizeFromDimensionService("CommittedChanges.SplitterProportions");
mySplitterProportionsData.restoreSplitterProportions(this);
}
public void addFilter(final ChangeListFilteringStrategy strategy) {
myFilteringStrategy.addStrategy(strategy.getKey(), strategy);
strategy.addChangeListener(myFilterChangeListener);
}
private void updateGrouping() {
if (myGroupingStrategy.changedSinceApply()) {
ApplicationManager.getApplication().invokeLater(() -> updateModel(), ModalityState.NON_MODAL);
}
}
private TreeModel buildTreeModel(final List<CommittedChangeList> filteredChangeLists) {
DefaultMutableTreeNode root = new DefaultMutableTreeNode();
DefaultTreeModel model = new DefaultTreeModel(root);
Collections.sort(filteredChangeLists, myGroupingStrategy.getComparator());
myGroupingStrategy.beforeStart();
DefaultMutableTreeNode lastGroupNode = null;
String lastGroupName = null;
for(CommittedChangeList list: filteredChangeLists) {
String groupName = StringUtil.notNullize(myGroupingStrategy.getGroupName(list));
if (!Comparing.equal(groupName, lastGroupName)) {
lastGroupName = groupName;
lastGroupNode = new DefaultMutableTreeNode(lastGroupName);
root.add(lastGroupNode);
}
assert lastGroupNode != null;
lastGroupNode.add(new DefaultMutableTreeNode(list));
}
return model;
}
public void setHelpId(final String helpId) {
myHelpId = helpId;
}
public StatusText getEmptyText() {
return myChangesTree.getEmptyText();
}
public void setToolBar(JComponent toolBar) {
myLeftPanel.add(toolBar, BorderLayout.NORTH);
myDetailsView.syncSizeWithToolbar(toolBar);
}
@Override
public void dispose() {
myConnection.disconnect();
mySplitterProportionsData.saveSplitterProportions(this);
mySplitterProportionsData.externalizeToDimensionService("CommittedChanges.SplitterProportions");
}
public void setItems(@NotNull List<CommittedChangeList> items, final CommittedChangesBrowserUseCase useCase) {
myDetailsView.setUseCase(useCase);
myChangeLists = new ArrayList<>(items);
myFilteringStrategy.setFilterBase(items);
BackgroundTaskUtil.syncPublisher(myProject, ITEMS_RELOADED).itemsReloaded();
updateModel();
}
private void updateModel() {
TreeState state = TreeState.createOn(myChangesTree, (DefaultMutableTreeNode)myChangesTree.getModel().getRoot());
final List<CommittedChangeList> filteredChangeLists = myFilteringStrategy.filterChangeLists(myChangeLists);
myChangesTree.setModel(buildTreeModel(filteredChangeLists));
state.applyTo(myChangesTree);
TreeUtil.expandAll(myChangesTree);
}
public void setGroupingStrategy(@NotNull ChangeListGroupingStrategy strategy) {
myGroupingStrategy = strategy;
updateModel();
}
@NotNull
public ChangeListGroupingStrategy getGroupingStrategy() {
return myGroupingStrategy;
}
private void updateBySelectionChange() {
List<CommittedChangeList> selection = new ArrayList<>();
final TreePath[] selectionPaths = myChangesTree.getSelectionPaths();
if (selectionPaths != null) {
for(TreePath path: selectionPaths) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
if (node.getUserObject() instanceof CommittedChangeList) {
selection.add((CommittedChangeList) node.getUserObject());
}
}
}
if (!selection.equals(mySelectedChangeLists)) {
mySelectedChangeLists = selection;
myDetailsView.setChangesToDisplay(collectChanges(mySelectedChangeLists, false));
}
}
@NotNull
public static List<Change> collectChanges(final List<? extends CommittedChangeList> selectedChangeLists, final boolean withMovedTrees) {
Collections.sort(selectedChangeLists, CommittedChangeListByDateComparator.ASCENDING);
List<Change> changes = new ArrayList<>();
for (CommittedChangeList cl : selectedChangeLists) {
changes.addAll(withMovedTrees ? cl.getChangesWithMovedTrees() : cl.getChanges());
}
return zipChanges(changes);
}
/**
* Zips changes by removing duplicates (changes in the same file) and compounding the diff.
* <b>NB:</b> changes must be given in the time-ascending order, i.e the first change in the list should be the oldest one.
*/
@NotNull
public static List<Change> zipChanges(@NotNull List<? extends Change> changes) {
// TODO: further improvements needed
// We may want to process collisions more consistent
// Possible solution: avoid creating duplicate entries for the same FilePath. No changes in the output should have same beforePath or afterPath.
// We may take earliest and latest revisions for each file.
//
// The main problem would be to keep existing movements in non-conflicting cases (where input changes are taken from linear sequence of commits)
// case1: "a -> b; b -> c" - file renamed twice in the same revision (as source and as target)
// case2: "a -> b" "b -> c" - file renamed twice in consequent commits
// case3: "a -> b; b -> a" - files swapped vs "a -> b" "b -> a" - file rename canceled
// case4: "delete a" "b -> a" "modify a"
// ...
// but return "good enough" result for input with conflicting changes
// case1: "new a", "new a"
// case2: "a -> b", "new b"
// ...
//
// getting "actually good" results is impossible without knowledge of commits topology.
// key - after path (nullable)
LinkedMultiMap<FilePath, Change> map = new LinkedMultiMap<>();
for (Change change : changes) {
ContentRevision bRev = change.getBeforeRevision();
ContentRevision aRev = change.getAfterRevision();
FilePath bPath = bRev != null ? bRev.getFile() : null;
FilePath aPath = aRev != null ? aRev.getFile() : null;
if (bRev == null) {
map.putValue(aPath, change);
continue;
}
Collection<Change> bucket = map.get(bPath);
if (bucket.isEmpty()) {
map.putValue(aPath, change);
continue;
}
Change oldChange = bucket.iterator().next();
bucket.remove(oldChange);
ContentRevision oldRevision = oldChange.getBeforeRevision();
if (oldRevision != null || aRev != null) {
map.putValue(aPath, new Change(oldRevision, aRev));
}
}
// put deletions into appropriate place in list
Collection<Change> deleted = map.remove(null);
if (deleted != null) {
for (Change change : deleted) {
//noinspection ConstantConditions
map.putValue(change.getBeforeRevision().getFile(), change);
}
}
return new ArrayList<>(map.values());
}
private List<CommittedChangeList> getSelectedChangeLists() {
return TreeUtil.collectSelectedObjectsOfType(myChangesTree, CommittedChangeList.class);
}
public void setTableContextMenu(final ActionGroup group, final List<AnAction> auxiliaryActions) {
DefaultActionGroup menuGroup = new DefaultActionGroup();
menuGroup.add(group);
for (AnAction action : auxiliaryActions) {
menuGroup.add(action);
}
menuGroup.add(ActionManager.getInstance().getAction(VcsActions.ACTION_COPY_REVISION_NUMBER));
PopupHandler.installPopupHandler(myChangesTree, menuGroup, ActionPlaces.UNKNOWN, ActionManager.getInstance());
}
@Override
public void removeFilteringStrategy(final CommittedChangesFilterKey key) {
final ChangeListFilteringStrategy strategy = myFilteringStrategy.removeStrategy(key);
if (strategy != null) {
strategy.removeChangeListener(myFilterChangeListener);
}
myInnerSplitter.remove(key);
}
@Override
public boolean setFilteringStrategy(final ChangeListFilteringStrategy filteringStrategy) {
if (myInnerSplitter.canAdd()) {
filteringStrategy.addChangeListener(myFilterChangeListener);
final CommittedChangesFilterKey key = filteringStrategy.getKey();
myFilteringStrategy.addStrategy(key, filteringStrategy);
myFilteringStrategy.setFilterBase(myChangeLists);
final JComponent filterUI = filteringStrategy.getFilterUI();
if (filterUI != null) {
myInnerSplitter.add(key, filterUI);
}
return true;
}
return false;
}
public ActionToolbar createGroupFilterToolbar(final Project project, final ActionGroup leadGroup, @Nullable final ActionGroup tailGroup,
final List<AnAction> extra) {
DefaultActionGroup toolbarGroup = new DefaultActionGroup();
toolbarGroup.add(leadGroup);
toolbarGroup.addSeparator();
toolbarGroup.add(new SelectFilteringAction(project, this));
toolbarGroup.add(new SelectGroupingAction(project, this));
final ExpandAllAction expandAllAction = new ExpandAllAction(myChangesTree);
final CollapseAllAction collapseAllAction = new CollapseAllAction(myChangesTree);
expandAllAction.registerCustomShortcutSet(getActiveKeymapShortcuts(IdeActions.ACTION_EXPAND_ALL), myChangesTree);
collapseAllAction.registerCustomShortcutSet(getActiveKeymapShortcuts(IdeActions.ACTION_COLLAPSE_ALL), myChangesTree);
toolbarGroup.add(expandAllAction);
toolbarGroup.add(collapseAllAction);
toolbarGroup.add(ActionManager.getInstance().getAction(VcsActions.ACTION_COPY_REVISION_NUMBER));
toolbarGroup.add(new ContextHelpAction(myHelpId));
if (tailGroup != null) {
toolbarGroup.add(tailGroup);
}
for (AnAction anAction : extra) {
toolbarGroup.add(anAction);
}
return ActionManager.getInstance().createActionToolbar("CommittedChangesTree", toolbarGroup, true);
}
@Override
public void calcData(@NotNull DataKey key, @NotNull DataSink sink) {
if (key.equals(VcsDataKeys.CHANGES)) {
final Collection<Change> changes = collectChanges(getSelectedChangeLists(), false);
sink.put(VcsDataKeys.CHANGES, changes.toArray(new Change[0]));
} else if (key.equals(VcsDataKeys.HAVE_SELECTED_CHANGES)) {
final int count = myChangesTree.getSelectionCount();
sink.put(VcsDataKeys.HAVE_SELECTED_CHANGES, count > 0);
}
else if (key.equals(VcsDataKeys.CHANGES_WITH_MOVED_CHILDREN)) {
final Collection<Change> changes = collectChanges(getSelectedChangeLists(), true);
sink.put(VcsDataKeys.CHANGES_WITH_MOVED_CHILDREN, changes.toArray(new Change[0]));
}
else if (key.equals(VcsDataKeys.CHANGE_LISTS)) {
final List<CommittedChangeList> lists = getSelectedChangeLists();
if (!lists.isEmpty()) {
sink.put(VcsDataKeys.CHANGE_LISTS, lists.toArray(new CommittedChangeList[0]));
}
}
else if (key.equals(CommonDataKeys.NAVIGATABLE_ARRAY)) {
Collection<Change> changes = collectChanges(getSelectedChangeLists(), false);
sink.put(CommonDataKeys.NAVIGATABLE_ARRAY, getNavigatableArray(myProject, getFiles(changes.stream())));
}
else if (key.equals(PlatformDataKeys.HELP_ID)) {
sink.put(PlatformDataKeys.HELP_ID, myHelpId);
} else if (VcsDataKeys.SELECTED_CHANGES_IN_DETAILS.equals(key)) {
final List<Change> selectedChanges = myDetailsView.getSelectedChanges();
sink.put(VcsDataKeys.SELECTED_CHANGES_IN_DETAILS, selectedChanges.toArray(new Change[0]));
}
}
public TreeExpander getTreeExpander() {
return myTreeExpander;
}
@Override
public void repaintTree() {
myChangesTree.revalidate();
myChangesTree.repaint();
}
@Override
public void install(final CommittedChangeListDecorator decorator) {
myDecorators.add(decorator);
repaintTree();
}
@Override
public void remove(final CommittedChangeListDecorator decorator) {
myDecorators.remove(decorator);
repaintTree();
}
@Override
public void reportLoadedLists(final CommittedChangeListsListener listener) {
List<CommittedChangeList> lists = new ArrayList<>(myChangeLists);
ApplicationManager.getApplication().executeOnPooledThread(() -> {
listener.onBeforeStartReport();
for (CommittedChangeList list : lists) {
listener.report(list);
}
listener.onAfterEndReport();
});
}
// for appendable view
public void reset() {
myChangeLists.clear();
myFilteringStrategy.resetFilterBase();
myState = TreeState.createOn(myChangesTree, (DefaultMutableTreeNode)myChangesTree.getModel().getRoot());
updateModel();
}
public void append(final List<CommittedChangeList> list) {
final TreeState state = myChangeLists.isEmpty() && myState != null ? myState :
TreeState.createOn(myChangesTree, (DefaultMutableTreeNode)myChangesTree.getModel().getRoot());
state.setScrollToSelection(false);
myChangeLists.addAll(list);
myFilteringStrategy.appendFilterBase(list);
myChangesTree.setModel(buildTreeModel(myFilteringStrategy.filterChangeLists(myChangeLists)));
state.applyTo(myChangesTree, myChangesTree.getModel().getRoot());
TreeUtil.expandAll(myChangesTree);
BackgroundTaskUtil.syncPublisher(myProject, ITEMS_RELOADED).itemsReloaded();
}
public static class MoreLauncher implements Runnable {
private final Project myProject;
private final CommittedChangeList myList;
MoreLauncher(final Project project, final CommittedChangeList list) {
myProject = project;
myList = list;
}
@Override
public void run() {
ChangeListDetailsAction.showDetailsPopup(myProject, myList);
}
}
private class FilterChangeListener implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
if (ApplicationManager.getApplication().isDispatchThread()) {
updateModel();
} else {
ApplicationManager.getApplication().invokeLater(() -> updateModel());
}
}
}
private class ChangesBrowserTree extends Tree implements TypeSafeDataProvider {
ChangesBrowserTree() {
super(buildTreeModel(myFilteringStrategy.filterChangeLists(myChangeLists)));
}
@Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
@Override
public void calcData(@NotNull final DataKey key, @NotNull final DataSink sink) {
if (key.equals(PlatformDataKeys.COPY_PROVIDER)) {
sink.put(PlatformDataKeys.COPY_PROVIDER, myCopyProvider);
}
else if (key.equals(PlatformDataKeys.TREE_EXPANDER)) {
sink.put(PlatformDataKeys.TREE_EXPANDER, myTreeExpander);
} else {
final String name = key.getName();
if (VcsDataKeys.SELECTED_CHANGES.is(name) || VcsDataKeys.CHANGE_LEAD_SELECTION.is(name) ||
CommittedChangesBrowserUseCase.DATA_KEY.is(name)) {
final Object data = myDetailsView.getData(name);
if (data != null) {
sink.put(key, data);
}
}
}
}
public void invalidateNodeSizes() {
TreeUI ui = getUI();
if (ui instanceof WideSelectionTreeUI) {
((WideSelectionTreeUI)ui).invalidateNodeSizes();
}
repaint();
}
}
public interface CommittedChangesReloadListener {
void itemsReloaded();
void emptyRefresh();
}
public void setLoading(final boolean value) {
runOrInvokeLaterAboveProgress(() -> myChangesTree.setPaintBusy(value), ModalityState.NON_MODAL, myProject);
}
private static class MyRepositoryChangesViewer extends CommittedChangesBrowser {
private final JComponent myHeaderPanel = new JPanel();
MyRepositoryChangesViewer(Project project) {
super(project);
}
@Nullable
@Override
protected JComponent createHeaderPanel() {
return myHeaderPanel;
}
@NotNull
@Override
protected Border createViewerBorder() {
return RIGHT_BORDER;
}
public void syncSizeWithToolbar(@NotNull JComponent toolbar) {
myHeaderPanel.setPreferredSize(new Dimension(0, toolbar.getPreferredSize().height));
}
}
}
| |
/*
* Copyright 2006-2021 Prowide
*
* 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.prowidesoftware.swift.model.mt.mt7xx;
import com.prowidesoftware.Generated;
import java.io.Serializable;
import org.apache.commons.lang3.StringUtils;
import com.prowidesoftware.swift.model.*;
import com.prowidesoftware.swift.model.field.*;
import com.prowidesoftware.swift.model.mt.AbstractMT;
import com.prowidesoftware.swift.utils.Lib;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
/**
* MT 792 - Request for Cancellation.
*
* <p>
* SWIFT MT792 (ISO 15022) message structure:
*
<div class="scheme"><ul>
<li class="field">Field 20 (M)</li>
<li class="field">Field 21 (M)</li>
<li class="field">Field 11 S (M)</li>
<li class="field">Field 79 (O)</li>
</ul></div>
*
* <p>
* This source code is specific to release <strong>SRU 2021</strong>
* <p>
* For additional resources check <a href="https://www.prowidesoftware.com/resources">https://www.prowidesoftware.com/resources</a>
*/
@Generated
public class MT792 extends AbstractMT implements Serializable {
/**
* Constant identifying the SRU to which this class belongs to.
*/
public static final int SRU = 2021;
private static final long serialVersionUID = 1L;
private static final transient java.util.logging.Logger log = java.util.logging.Logger.getLogger(MT792.class.getName());
/**
* Constant for MT name, this is part of the classname, after MT.
*/
public static final String NAME = "792";
/**
* Creates an MT792 initialized with the parameter SwiftMessage.
* @param m swift message with the MT792 content
*/
public MT792(final SwiftMessage m) {
super(m);
sanityCheck(m);
}
/**
* Creates an MT792 initialized with the parameter MtSwiftMessage.
* @param m swift message with the MT792 content, the parameter can not be null
* @see #MT792(String)
*/
public MT792(final MtSwiftMessage m) {
this(m.message());
}
/**
* Creates an MT792 initialized with the parameter MtSwiftMessage.
*
* @param m swift message with the MT792 content
* @return the created object or null if the parameter is null
* @see #MT792(String)
* @since 7.7
*/
public static MT792 parse(final MtSwiftMessage m) {
if (m == null) {
return null;
}
return new MT792(m);
}
/**
* Creates and initializes a new MT792 input message setting TEST BICS as sender and receiver.
* All mandatory header attributes are completed with default values.
*
* @since 7.6
*/
public MT792() {
this(BIC.TEST8, BIC.TEST8);
}
/**
* Creates and initializes a new MT792 input message from sender to receiver.
* All mandatory header attributes are completed with default values.
* In particular the sender and receiver addresses will be filled with proper default LT identifier
* and branch codes if not provided,
*
* @param sender the sender address as a bic8, bic11 or full logical terminal consisting of 12 characters
* @param receiver the receiver address as a bic8, bic11 or full logical terminal consisting of 12 characters
* @since 7.7
*/
public MT792(final String sender, final String receiver) {
super(792, sender, receiver);
}
/**
* Creates a new MT792 by parsing a String with the message content in its swift FIN format.
* If the fin parameter is null or the message cannot be parsed, the internal message object
* will be initialized (blocks will be created) but empty.
* If the string contains multiple messages, only the first one will be parsed.
*
* @param fin a string with the MT message in its FIN swift format
* @since 7.7
*/
public MT792(final String fin) {
super();
if (fin != null) {
final SwiftMessage parsed = read(fin);
if (parsed != null) {
super.m = parsed;
sanityCheck(parsed);
}
}
}
private void sanityCheck(final SwiftMessage param) {
if (param.isServiceMessage()) {
log.warning("Creating an MT792 object from FIN content with a Service Message. Check if the MT792 you are intended to read is prepended with and ACK.");
} else if (!StringUtils.equals(param.getType(), "792")) {
log.warning("Creating an MT792 object from FIN content with message type "+param.getType());
}
}
/**
* Creates a new MT792 by parsing a String with the message content in its swift FIN format.
* If the fin parameter cannot be parsed, the returned MT792 will have its internal message object
* initialized (blocks will be created) but empty.
* If the string contains multiple messages, only the first one will be parsed.
*
* @param fin a string with the MT message in its FIN swift format. <em>fin may be null in which case this method returns null</em>
* @return a new instance of MT792 or null if fin is null
* @since 7.7
*/
public static MT792 parse(final String fin) {
if (fin == null) {
return null;
}
return new MT792(fin);
}
/**
* Creates a new MT792 by parsing a input stream with the message content in its swift FIN format, using "UTF-8" as encoding.
* If the message content is null or cannot be parsed, the internal message object
* will be initialized (blocks will be created) but empty.
* If the stream contains multiple messages, only the first one will be parsed.
*
* @param stream an input stream in UTF-8 encoding with the MT message in its FIN swift format.
* @throws IOException if the stream data cannot be read
* @since 7.7
*/
public MT792(final InputStream stream) throws IOException {
this(Lib.readStream(stream));
}
/**
* Creates a new MT792 by parsing a input stream with the message content in its swift FIN format, using "UTF-8" as encoding.
* If the stream contains multiple messages, only the first one will be parsed.
*
* @param stream an input stream in UTF-8 encoding with the MT message in its FIN swift format.
* @return a new instance of MT792 or null if stream is null or the message cannot be parsed
* @throws IOException if the stream data cannot be read
* @since 7.7
*/
public static MT792 parse(final InputStream stream) throws IOException {
if (stream == null) {
return null;
}
return new MT792(stream);
}
/**
* Creates a new MT792 by parsing a file with the message content in its swift FIN format.
* If the file content is null or cannot be parsed as a message, the internal message object
* will be initialized (blocks will be created) but empty.
* If the file contains multiple messages, only the first one will be parsed.
*
* @param file a file with the MT message in its FIN swift format.
* @throws IOException if the file content cannot be read
* @since 7.7
*/
public MT792(final File file) throws IOException {
this(Lib.readFile(file));
}
/**
* Creates a new MT792 by parsing a file with the message content in its swift FIN format.
* If the file contains multiple messages, only the first one will be parsed.
*
* @param file a file with the MT message in its FIN swift format.
* @return a new instance of MT792 or null if; file is null, does not exist, can't be read, is not a file or the message cannot be parsed
* @throws IOException if the file content cannot be read
* @since 7.7
*/
public static MT792 parse(final File file) throws IOException {
if (file == null) {
return null;
}
return new MT792(file);
}
/**
* Returns this MT number.
* @return the message type number of this MT
* @since 6.4
*/
@Override
public String getMessageType() {
return "792";
}
/**
* Add all tags from block to the end of the block4.
*
* @param block to append
* @return this object to allow method chaining
* @since 7.6
*/
@Override
public MT792 append(final SwiftTagListBlock block) {
super.append(block);
return this;
}
/**
* Add all tags to the end of the block4.
*
* @param tags to append
* @return this object to allow method chaining
* @since 7.6
*/
@Override
public MT792 append(final Tag... tags) {
super.append(tags);
return this;
}
/**
* Add all the fields to the end of the block4.
*
* @param fields to append
* @return this object to allow method chaining
* @since 7.6
*/
@Override
public MT792 append(final Field... fields) {
super.append(fields);
return this;
}
/**
* Creates an MT792 messages from its JSON representation.
* <p>
* For generic conversion of JSON into the corresponding MT instance
* see {@link AbstractMT#fromJson(String)}
*
* @param json a JSON representation of an MT792 message
* @return a new instance of MT792
* @since 7.10.3
*/
public static MT792 fromJson(final String json) {
return (MT792) AbstractMT.fromJson(json);
}
/**
* Iterates through block4 fields and return the first one whose name matches 20,
* or null if none is found.
* The first occurrence of field 20 at MT792 is expected to be the only one.
*
* @return a Field20 object or null if the field is not found
* @see SwiftTagListBlock#getTagByName(String)
* @throws IllegalStateException if SwiftMessage object is not initialized
*/
public Field20 getField20() {
final Tag t = tag("20");
if (t != null) {
return new Field20(t.getValue());
} else {
return null;
}
}
/**
* Iterates through block4 fields and return the first one whose name matches 21,
* or null if none is found.
* The first occurrence of field 21 at MT792 is expected to be the only one.
*
* @return a Field21 object or null if the field is not found
* @see SwiftTagListBlock#getTagByName(String)
* @throws IllegalStateException if SwiftMessage object is not initialized
*/
public Field21 getField21() {
final Tag t = tag("21");
if (t != null) {
return new Field21(t.getValue());
} else {
return null;
}
}
/**
* Iterates through block4 fields and return the first one whose name matches 11S,
* or null if none is found.
* The first occurrence of field 11S at MT792 is expected to be the only one.
*
* @return a Field11S object or null if the field is not found
* @see SwiftTagListBlock#getTagByName(String)
* @throws IllegalStateException if SwiftMessage object is not initialized
*/
public Field11S getField11S() {
final Tag t = tag("11S");
if (t != null) {
return new Field11S(t.getValue());
} else {
return null;
}
}
/**
* Iterates through block4 fields and return the first one whose name matches 79,
* or null if none is found.
* The first occurrence of field 79 at MT792 is expected to be the only one.
*
* @return a Field79 object or null if the field is not found
* @see SwiftTagListBlock#getTagByName(String)
* @throws IllegalStateException if SwiftMessage object is not initialized
*/
public Field79 getField79() {
final Tag t = tag("79");
if (t != null) {
return new Field79(t.getValue());
} else {
return null;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.connect.runtime.rest.resources;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.ws.rs.core.HttpHeaders;
import org.apache.kafka.common.config.Config;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.config.ConfigDef.Recommender;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.common.config.ConfigDef.Width;
import org.apache.kafka.common.config.ConfigValue;
import org.apache.kafka.connect.connector.Connector;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.runtime.AbstractHerder;
import org.apache.kafka.connect.runtime.ConnectorConfig;
import org.apache.kafka.connect.runtime.Herder;
import org.apache.kafka.connect.runtime.TestSinkConnector;
import org.apache.kafka.connect.runtime.TestSourceConnector;
import org.apache.kafka.connect.runtime.WorkerConfig;
import org.apache.kafka.connect.runtime.isolation.PluginClassLoader;
import org.apache.kafka.connect.runtime.isolation.PluginDesc;
import org.apache.kafka.connect.runtime.isolation.Plugins;
import org.apache.kafka.connect.runtime.rest.RestClient;
import org.apache.kafka.connect.runtime.rest.entities.ConfigInfo;
import org.apache.kafka.connect.runtime.rest.entities.ConfigInfos;
import org.apache.kafka.connect.runtime.rest.entities.ConfigKeyInfo;
import org.apache.kafka.connect.runtime.rest.entities.ConfigValueInfo;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorPluginInfo;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorType;
import org.apache.kafka.connect.sink.SinkConnector;
import org.apache.kafka.connect.source.SourceConnector;
import org.apache.kafka.connect.tools.MockConnector;
import org.apache.kafka.connect.tools.MockSinkConnector;
import org.apache.kafka.connect.tools.MockSourceConnector;
import org.apache.kafka.connect.tools.SchemaSourceConnector;
import org.apache.kafka.connect.tools.VerifiableSinkConnector;
import org.apache.kafka.connect.tools.VerifiableSourceConnector;
import org.apache.kafka.connect.util.Callback;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.ws.rs.BadRequestException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
@RunWith(PowerMockRunner.class)
@PrepareForTest(RestClient.class)
@PowerMockIgnore("javax.management.*")
public class ConnectorPluginsResourceTest {
private static Map<String, String> props;
private static Map<String, String> partialProps = new HashMap<>();
static {
partialProps.put("name", "test");
partialProps.put("test.string.config", "testString");
partialProps.put("test.int.config", "1");
partialProps.put("test.list.config", "a,b");
props = new HashMap<>(partialProps);
props.put("connector.class", ConnectorPluginsResourceTestConnector.class.getSimpleName());
props.put("plugin.path", null);
}
private static final ConfigInfos CONFIG_INFOS;
private static final ConfigInfos PARTIAL_CONFIG_INFOS;
private static final int ERROR_COUNT = 0;
private static final int PARTIAL_CONFIG_ERROR_COUNT = 1;
private static final Set<PluginDesc<Connector>> CONNECTOR_PLUGINS = new TreeSet<>();
static {
List<ConfigInfo> configs = new LinkedList<>();
List<ConfigInfo> partialConfigs = new LinkedList<>();
ConfigDef connectorConfigDef = ConnectorConfig.configDef();
List<ConfigValue> connectorConfigValues = connectorConfigDef.validate(props);
List<ConfigValue> partialConnectorConfigValues = connectorConfigDef.validate(partialProps);
ConfigInfos result = AbstractHerder.generateResult(ConnectorPluginsResourceTestConnector.class.getName(), connectorConfigDef.configKeys(), connectorConfigValues, Collections.emptyList());
ConfigInfos partialResult = AbstractHerder.generateResult(ConnectorPluginsResourceTestConnector.class.getName(), connectorConfigDef.configKeys(), partialConnectorConfigValues, Collections.emptyList());
configs.addAll(result.values());
partialConfigs.addAll(partialResult.values());
ConfigKeyInfo configKeyInfo = new ConfigKeyInfo("test.string.config", "STRING", true, null, "HIGH", "Test configuration for string type.", null, -1, "NONE", "test.string.config", Collections.emptyList());
ConfigValueInfo configValueInfo = new ConfigValueInfo("test.string.config", "testString", Collections.emptyList(), Collections.emptyList(), true);
ConfigInfo configInfo = new ConfigInfo(configKeyInfo, configValueInfo);
configs.add(configInfo);
partialConfigs.add(configInfo);
configKeyInfo = new ConfigKeyInfo("test.int.config", "INT", true, null, "MEDIUM", "Test configuration for integer type.", "Test", 1, "MEDIUM", "test.int.config", Collections.emptyList());
configValueInfo = new ConfigValueInfo("test.int.config", "1", asList("1", "2", "3"), Collections.emptyList(), true);
configInfo = new ConfigInfo(configKeyInfo, configValueInfo);
configs.add(configInfo);
partialConfigs.add(configInfo);
configKeyInfo = new ConfigKeyInfo("test.string.config.default", "STRING", false, "", "LOW", "Test configuration with default value.", null, -1, "NONE", "test.string.config.default", Collections.emptyList());
configValueInfo = new ConfigValueInfo("test.string.config.default", "", Collections.emptyList(), Collections.emptyList(), true);
configInfo = new ConfigInfo(configKeyInfo, configValueInfo);
configs.add(configInfo);
partialConfigs.add(configInfo);
configKeyInfo = new ConfigKeyInfo("test.list.config", "LIST", true, null, "HIGH", "Test configuration for list type.", "Test", 2, "LONG", "test.list.config", Collections.emptyList());
configValueInfo = new ConfigValueInfo("test.list.config", "a,b", asList("a", "b", "c"), Collections.emptyList(), true);
configInfo = new ConfigInfo(configKeyInfo, configValueInfo);
configs.add(configInfo);
partialConfigs.add(configInfo);
CONFIG_INFOS = new ConfigInfos(ConnectorPluginsResourceTestConnector.class.getName(), ERROR_COUNT, Collections.singletonList("Test"), configs);
PARTIAL_CONFIG_INFOS = new ConfigInfos(ConnectorPluginsResourceTestConnector.class.getName(), PARTIAL_CONFIG_ERROR_COUNT, Collections.singletonList("Test"), partialConfigs);
List<Class<? extends Connector>> abstractConnectorClasses = asList(
Connector.class,
SourceConnector.class,
SinkConnector.class
);
List<Class<? extends Connector>> connectorClasses = asList(
VerifiableSourceConnector.class,
VerifiableSinkConnector.class,
MockSourceConnector.class,
MockSinkConnector.class,
MockConnector.class,
SchemaSourceConnector.class,
ConnectorPluginsResourceTestConnector.class
);
try {
for (Class<? extends Connector> klass : abstractConnectorClasses) {
@SuppressWarnings("unchecked")
MockConnectorPluginDesc pluginDesc = new MockConnectorPluginDesc(klass, "0.0.0");
CONNECTOR_PLUGINS.add(pluginDesc);
}
for (Class<? extends Connector> klass : connectorClasses) {
@SuppressWarnings("unchecked")
MockConnectorPluginDesc pluginDesc = new MockConnectorPluginDesc(klass);
CONNECTOR_PLUGINS.add(pluginDesc);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Mock
private Herder herder;
@Mock
private Plugins plugins;
private ConnectorPluginsResource connectorPluginsResource;
@Before
public void setUp() throws Exception {
PowerMock.mockStatic(RestClient.class,
RestClient.class.getMethod("httpRequest", String.class, String.class, HttpHeaders.class, Object.class, TypeReference.class, WorkerConfig.class));
plugins = PowerMock.createMock(Plugins.class);
herder = PowerMock.createMock(AbstractHerder.class);
connectorPluginsResource = new ConnectorPluginsResource(herder);
}
private void expectPlugins() {
EasyMock.expect(herder.plugins()).andReturn(plugins);
EasyMock.expect(plugins.connectors()).andReturn(CONNECTOR_PLUGINS);
PowerMock.replayAll();
}
@Test
public void testValidateConfigWithSingleErrorDueToMissingConnectorClassname() throws Throwable {
Capture<Callback<ConfigInfos>> configInfosCallback = EasyMock.newCapture();
herder.validateConnectorConfig(EasyMock.eq(partialProps), EasyMock.capture(configInfosCallback), EasyMock.anyBoolean());
PowerMock.expectLastCall().andAnswer((IAnswer<Void>) () -> {
ConfigDef connectorConfigDef = ConnectorConfig.configDef();
List<ConfigValue> connectorConfigValues = connectorConfigDef.validate(partialProps);
Connector connector = new ConnectorPluginsResourceTestConnector();
Config config = connector.validate(partialProps);
ConfigDef configDef = connector.config();
Map<String, ConfigDef.ConfigKey> configKeys = configDef.configKeys();
List<ConfigValue> configValues = config.configValues();
Map<String, ConfigDef.ConfigKey> resultConfigKeys = new HashMap<>(configKeys);
resultConfigKeys.putAll(connectorConfigDef.configKeys());
configValues.addAll(connectorConfigValues);
ConfigInfos configInfos = AbstractHerder.generateResult(
ConnectorPluginsResourceTestConnector.class.getName(),
resultConfigKeys,
configValues,
Collections.singletonList("Test")
);
configInfosCallback.getValue().onCompletion(null, configInfos);
return null;
});
PowerMock.replayAll();
// This call to validateConfigs does not throw a BadRequestException because we've mocked
// validateConnectorConfig.
ConfigInfos configInfos = connectorPluginsResource.validateConfigs(
ConnectorPluginsResourceTestConnector.class.getSimpleName(),
partialProps
);
assertEquals(PARTIAL_CONFIG_INFOS.name(), configInfos.name());
assertEquals(PARTIAL_CONFIG_INFOS.errorCount(), configInfos.errorCount());
assertEquals(PARTIAL_CONFIG_INFOS.groups(), configInfos.groups());
assertEquals(
new HashSet<>(PARTIAL_CONFIG_INFOS.values()),
new HashSet<>(configInfos.values())
);
PowerMock.verifyAll();
}
@Test
public void testValidateConfigWithSimpleName() throws Throwable {
Capture<Callback<ConfigInfos>> configInfosCallback = EasyMock.newCapture();
herder.validateConnectorConfig(EasyMock.eq(props), EasyMock.capture(configInfosCallback), EasyMock.anyBoolean());
PowerMock.expectLastCall().andAnswer((IAnswer<ConfigInfos>) () -> {
ConfigDef connectorConfigDef = ConnectorConfig.configDef();
List<ConfigValue> connectorConfigValues = connectorConfigDef.validate(props);
Connector connector = new ConnectorPluginsResourceTestConnector();
Config config = connector.validate(props);
ConfigDef configDef = connector.config();
Map<String, ConfigDef.ConfigKey> configKeys = configDef.configKeys();
List<ConfigValue> configValues = config.configValues();
Map<String, ConfigDef.ConfigKey> resultConfigKeys = new HashMap<>(configKeys);
resultConfigKeys.putAll(connectorConfigDef.configKeys());
configValues.addAll(connectorConfigValues);
ConfigInfos configInfos = AbstractHerder.generateResult(
ConnectorPluginsResourceTestConnector.class.getName(),
resultConfigKeys,
configValues,
Collections.singletonList("Test")
);
configInfosCallback.getValue().onCompletion(null, configInfos);
return null;
});
PowerMock.replayAll();
// make a request to connector-plugins resource using just the simple class name.
ConfigInfos configInfos = connectorPluginsResource.validateConfigs(
ConnectorPluginsResourceTestConnector.class.getSimpleName(),
props
);
assertEquals(CONFIG_INFOS.name(), configInfos.name());
assertEquals(0, configInfos.errorCount());
assertEquals(CONFIG_INFOS.groups(), configInfos.groups());
assertEquals(new HashSet<>(CONFIG_INFOS.values()), new HashSet<>(configInfos.values()));
PowerMock.verifyAll();
}
@Test
public void testValidateConfigWithAlias() throws Throwable {
Capture<Callback<ConfigInfos>> configInfosCallback = EasyMock.newCapture();
herder.validateConnectorConfig(EasyMock.eq(props), EasyMock.capture(configInfosCallback), EasyMock.anyBoolean());
PowerMock.expectLastCall().andAnswer((IAnswer<ConfigInfos>) () -> {
ConfigDef connectorConfigDef = ConnectorConfig.configDef();
List<ConfigValue> connectorConfigValues = connectorConfigDef.validate(props);
Connector connector = new ConnectorPluginsResourceTestConnector();
Config config = connector.validate(props);
ConfigDef configDef = connector.config();
Map<String, ConfigDef.ConfigKey> configKeys = configDef.configKeys();
List<ConfigValue> configValues = config.configValues();
Map<String, ConfigDef.ConfigKey> resultConfigKeys = new HashMap<>(configKeys);
resultConfigKeys.putAll(connectorConfigDef.configKeys());
configValues.addAll(connectorConfigValues);
ConfigInfos configInfos = AbstractHerder.generateResult(
ConnectorPluginsResourceTestConnector.class.getName(),
resultConfigKeys,
configValues,
Collections.singletonList("Test")
);
configInfosCallback.getValue().onCompletion(null, configInfos);
return null;
});
PowerMock.replayAll();
// make a request to connector-plugins resource using a valid alias.
ConfigInfos configInfos = connectorPluginsResource.validateConfigs(
"ConnectorPluginsResourceTest",
props
);
assertEquals(CONFIG_INFOS.name(), configInfos.name());
assertEquals(0, configInfos.errorCount());
assertEquals(CONFIG_INFOS.groups(), configInfos.groups());
assertEquals(new HashSet<>(CONFIG_INFOS.values()), new HashSet<>(configInfos.values()));
PowerMock.verifyAll();
}
@Test
public void testValidateConfigWithNonExistentName() {
// make a request to connector-plugins resource using a non-loaded connector with the same
// simple name but different package.
String customClassname = "com.custom.package."
+ ConnectorPluginsResourceTestConnector.class.getSimpleName();
assertThrows(BadRequestException.class, () -> connectorPluginsResource.validateConfigs(customClassname, props));
}
@Test
public void testValidateConfigWithNonExistentAlias() {
assertThrows(BadRequestException.class, () -> connectorPluginsResource.validateConfigs("ConnectorPluginsTest", props));
}
@Test
public void testListConnectorPlugins() throws Exception {
expectPlugins();
Set<ConnectorPluginInfo> connectorPlugins = new HashSet<>(connectorPluginsResource.listConnectorPlugins());
assertFalse(connectorPlugins.contains(newInfo(Connector.class, "0.0")));
assertFalse(connectorPlugins.contains(newInfo(SourceConnector.class, "0.0")));
assertFalse(connectorPlugins.contains(newInfo(SinkConnector.class, "0.0")));
assertFalse(connectorPlugins.contains(newInfo(VerifiableSourceConnector.class)));
assertFalse(connectorPlugins.contains(newInfo(VerifiableSinkConnector.class)));
assertFalse(connectorPlugins.contains(newInfo(MockSourceConnector.class)));
assertFalse(connectorPlugins.contains(newInfo(MockSinkConnector.class)));
assertFalse(connectorPlugins.contains(newInfo(MockConnector.class)));
assertFalse(connectorPlugins.contains(newInfo(SchemaSourceConnector.class)));
assertTrue(connectorPlugins.contains(newInfo(ConnectorPluginsResourceTestConnector.class)));
PowerMock.verifyAll();
}
@Test
public void testConnectorPluginsIncludesTypeAndVersionInformation() throws Exception {
expectPlugins();
ConnectorPluginInfo sinkInfo = newInfo(TestSinkConnector.class);
ConnectorPluginInfo sourceInfo =
newInfo(TestSourceConnector.class);
ConnectorPluginInfo unknownInfo =
newInfo(ConnectorPluginsResourceTestConnector.class);
assertEquals(ConnectorType.SINK, sinkInfo.type());
assertEquals(ConnectorType.SOURCE, sourceInfo.type());
assertEquals(ConnectorType.UNKNOWN, unknownInfo.type());
assertEquals(TestSinkConnector.VERSION, sinkInfo.version());
assertEquals(TestSourceConnector.VERSION, sourceInfo.version());
final ObjectMapper objectMapper = new ObjectMapper();
String serializedSink = objectMapper.writeValueAsString(ConnectorType.SINK);
String serializedSource = objectMapper.writeValueAsString(ConnectorType.SOURCE);
String serializedUnknown = objectMapper.writeValueAsString(ConnectorType.UNKNOWN);
assertTrue(serializedSink.contains("sink"));
assertTrue(serializedSource.contains("source"));
assertTrue(serializedUnknown.contains("unknown"));
assertEquals(
ConnectorType.SINK,
objectMapper.readValue(serializedSink, ConnectorType.class)
);
assertEquals(
ConnectorType.SOURCE,
objectMapper.readValue(serializedSource, ConnectorType.class)
);
assertEquals(
ConnectorType.UNKNOWN,
objectMapper.readValue(serializedUnknown, ConnectorType.class)
);
}
protected static ConnectorPluginInfo newInfo(Class<? extends Connector> klass, String version)
throws Exception {
return new ConnectorPluginInfo(new MockConnectorPluginDesc(klass, version));
}
protected static ConnectorPluginInfo newInfo(Class<? extends Connector> klass)
throws Exception {
return new ConnectorPluginInfo(new MockConnectorPluginDesc(klass));
}
public static class MockPluginClassLoader extends PluginClassLoader {
public MockPluginClassLoader(URL pluginLocation, URL[] urls, ClassLoader parent) {
super(pluginLocation, urls, parent);
}
public MockPluginClassLoader(URL pluginLocation, URL[] urls) {
super(pluginLocation, urls);
}
@Override
public String location() {
return "/tmp/mockpath";
}
}
public static class MockConnectorPluginDesc extends PluginDesc<Connector> {
public MockConnectorPluginDesc(Class<? extends Connector> klass, String version) {
super(klass, version, new MockPluginClassLoader(null, new URL[0]));
}
public MockConnectorPluginDesc(Class<? extends Connector> klass) throws Exception {
super(
klass,
klass.getConstructor().newInstance().version(),
new MockPluginClassLoader(null, new URL[0])
);
}
}
/* Name here needs to be unique as we are testing the aliasing mechanism */
public static class ConnectorPluginsResourceTestConnector extends Connector {
private static final String TEST_STRING_CONFIG = "test.string.config";
private static final String TEST_INT_CONFIG = "test.int.config";
private static final String TEST_STRING_CONFIG_DEFAULT = "test.string.config.default";
private static final String TEST_LIST_CONFIG = "test.list.config";
private static final String GROUP = "Test";
private static final ConfigDef CONFIG_DEF = new ConfigDef()
.define(TEST_STRING_CONFIG, Type.STRING, Importance.HIGH, "Test configuration for string type.")
.define(TEST_INT_CONFIG, Type.INT, Importance.MEDIUM, "Test configuration for integer type.", GROUP, 1, Width.MEDIUM, TEST_INT_CONFIG, new IntegerRecommender())
.define(TEST_STRING_CONFIG_DEFAULT, Type.STRING, "", Importance.LOW, "Test configuration with default value.")
.define(TEST_LIST_CONFIG, Type.LIST, Importance.HIGH, "Test configuration for list type.", GROUP, 2, Width.LONG, TEST_LIST_CONFIG, new ListRecommender());
@Override
public String version() {
return "1.0";
}
@Override
public void start(Map<String, String> props) {
}
@Override
public Class<? extends Task> taskClass() {
return null;
}
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
return null;
}
@Override
public void stop() {
}
@Override
public ConfigDef config() {
return CONFIG_DEF;
}
}
private static class IntegerRecommender implements Recommender {
@Override
public List<Object> validValues(String name, Map<String, Object> parsedConfig) {
return asList(1, 2, 3);
}
@Override
public boolean visible(String name, Map<String, Object> parsedConfig) {
return true;
}
}
private static class ListRecommender implements Recommender {
@Override
public List<Object> validValues(String name, Map<String, Object> parsedConfig) {
return asList("a", "b", "c");
}
@Override
public boolean visible(String name, Map<String, Object> parsedConfig) {
return true;
}
}
}
| |
/*
* 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.cache;
import com.facebook.presto.hive.HiveFileContext;
import com.facebook.presto.hive.HiveFileInfo;
import com.facebook.presto.hive.filesystem.ExtendedFileSystem;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.CreateFlag;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileChecksum;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.fs.FsStatus;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.XAttrSetFlag;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.util.Progressable;
import java.io.IOException;
import java.net.URI;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import static java.util.Objects.requireNonNull;
public abstract class CachingFileSystem
extends ExtendedFileSystem
{
protected final ExtendedFileSystem dataTier;
protected final URI uri;
public CachingFileSystem(ExtendedFileSystem dataTier, URI uri)
{
this.dataTier = requireNonNull(dataTier, "dataTier is null");
this.uri = requireNonNull(uri, "uri is null");
}
public ExtendedFileSystem getDataTier()
{
return dataTier;
}
@Override
public String getScheme()
{
return dataTier.getScheme();
}
@Override
public URI getUri()
{
return uri;
}
@Override
public void initialize(URI uri, Configuration configuration)
throws IOException
{
dataTier.initialize(uri, configuration);
}
@Override
public Configuration getConf()
{
return dataTier.getConf();
}
@Override
public Path getWorkingDirectory()
{
return dataTier.getWorkingDirectory();
}
@Override
public void setWorkingDirectory(Path workingDirectory)
{
dataTier.setWorkingDirectory(workingDirectory);
}
@Override
public long getDefaultBlockSize()
{
return dataTier.getDefaultBlockSize();
}
@Override
public long getDefaultBlockSize(Path path)
{
return dataTier.getDefaultBlockSize(path);
}
@Override
public short getDefaultReplication()
{
return dataTier.getDefaultReplication();
}
@Override
public short getDefaultReplication(Path path)
{
return dataTier.getDefaultReplication(path);
}
@Override
public Path getHomeDirectory()
{
return dataTier.getHomeDirectory();
}
@Override
public BlockLocation[] getFileBlockLocations(FileStatus fileStatus, long offset, long length)
throws IOException
{
return dataTier.getFileBlockLocations(fileStatus, offset, length);
}
@Override
public BlockLocation[] getFileBlockLocations(Path path, long offset, long length)
throws IOException
{
return dataTier.getFileBlockLocations(path, offset, length);
}
@Override
public void setVerifyChecksum(boolean verifyChecksum)
{
dataTier.setVerifyChecksum(verifyChecksum);
}
@Override
public FSDataInputStream open(Path path, int bufferSize)
throws IOException
{
return dataTier.open(path, bufferSize);
}
// HiveFileContext contains caching info, which must be used while overriding this method.
@Override
public abstract FSDataInputStream openFile(Path path, HiveFileContext hiveFileContext)
throws Exception;
@Override
public FSDataOutputStream append(Path path, int bufferSize, Progressable progressable)
throws IOException
{
return dataTier.append(path, bufferSize, progressable);
}
@Override
public FSDataOutputStream create(
Path path,
FsPermission permission,
boolean overwrite,
int bufferSize,
short replication,
long blockSize,
Progressable progressable)
throws IOException
{
return dataTier.create(path, permission, overwrite, bufferSize, replication, blockSize, progressable);
}
@Override
public FSDataOutputStream create(
Path path,
FsPermission permission,
EnumSet<CreateFlag> createFlags,
int bufferSize,
short replication,
long blockSize,
Progressable progressable,
Options.ChecksumOpt checksumOption)
throws IOException
{
return dataTier.create(path, permission, createFlags, bufferSize, replication, blockSize, progressable, checksumOption);
}
@Override
public boolean setReplication(Path path, short replication)
throws IOException
{
return dataTier.setReplication(path, replication);
}
@Override
public void concat(Path targetPath, Path[] sourcePaths)
throws IOException
{
dataTier.concat(targetPath, sourcePaths);
}
@Override
public boolean rename(Path source, Path destination)
throws IOException
{
return dataTier.rename(source, destination);
}
@Override
public boolean truncate(Path path, long length)
throws IOException
{
return dataTier.truncate(path, length);
}
@Override
public boolean delete(Path path, boolean recursive)
throws IOException
{
return dataTier.delete(path, recursive);
}
@Override
public ContentSummary getContentSummary(Path path)
throws IOException
{
return dataTier.getContentSummary(path);
}
@Override
public RemoteIterator<LocatedFileStatus> listLocatedStatus(Path path)
throws IOException
{
return dataTier.listLocatedStatus(path);
}
@Override
public FileStatus[] listStatus(Path path)
throws IOException
{
return dataTier.listStatus(path);
}
@Override
public RemoteIterator<FileStatus> listStatusIterator(Path path)
throws IOException
{
return dataTier.listStatusIterator(path);
}
@Override
public boolean mkdirs(Path path, FsPermission permission)
throws IOException
{
return dataTier.mkdirs(path, permission);
}
@Override
public void close()
throws IOException
{
dataTier.close();
}
@Override
public FsStatus getStatus(Path path)
throws IOException
{
return dataTier.getStatus(path);
}
@Override
public RemoteIterator<Path> listCorruptFileBlocks(Path path)
throws IOException
{
return dataTier.listCorruptFileBlocks(path);
}
@Override
public FsServerDefaults getServerDefaults()
throws IOException
{
return dataTier.getServerDefaults();
}
@Override
public FileStatus getFileStatus(Path path)
throws IOException
{
return dataTier.getFileStatus(path);
}
@Override
public void createSymlink(Path target, Path link, boolean createParent)
throws IOException
{
dataTier.createSymlink(target, link, createParent);
}
@Override
public boolean supportsSymlinks()
{
return dataTier.supportsSymlinks();
}
@Override
public FileStatus getFileLinkStatus(Path path)
throws IOException
{
return dataTier.getFileLinkStatus(path);
}
@Override
public Path getLinkTarget(Path path)
throws IOException
{
return dataTier.getLinkTarget(path);
}
@Override
public FileChecksum getFileChecksum(Path path)
throws IOException
{
return dataTier.getFileChecksum(path);
}
@Override
public FileChecksum getFileChecksum(Path path, long length)
throws IOException
{
return dataTier.getFileChecksum(path, length);
}
@Override
public void setPermission(Path path, FsPermission permission)
throws IOException
{
dataTier.setPermission(path, permission);
}
@Override
public void setOwner(Path path, String user, String group)
throws IOException
{
dataTier.setOwner(path, user, group);
}
@Override
public void setTimes(Path path, long modificationTime, long accessTime)
throws IOException
{
dataTier.setTimes(path, modificationTime, accessTime);
}
@Override
public Token<?> getDelegationToken(String renewer)
throws IOException
{
return dataTier.getDelegationToken(renewer);
}
@Override
public String getCanonicalServiceName()
{
return dataTier.getCanonicalServiceName();
}
@Override
public Path createSnapshot(Path path, String snapshotName)
throws IOException
{
return dataTier.createSnapshot(path, snapshotName);
}
@Override
public void renameSnapshot(Path path, String snapshotOldName, String snapshotNewName)
throws IOException
{
dataTier.renameSnapshot(path, snapshotOldName, snapshotNewName);
}
@Override
public void deleteSnapshot(Path snapshotDirectory, String snapshotName)
throws IOException
{
dataTier.deleteSnapshot(snapshotDirectory, snapshotName);
}
@Override
public void modifyAclEntries(Path path, List<AclEntry> aclEntries)
throws IOException
{
dataTier.modifyAclEntries(path, aclEntries);
}
@Override
public void removeAclEntries(Path path, List<AclEntry> aclEntries)
throws IOException
{
dataTier.removeAclEntries(path, aclEntries);
}
@Override
public void removeDefaultAcl(Path path)
throws IOException
{
dataTier.removeDefaultAcl(path);
}
@Override
public void removeAcl(Path path)
throws IOException
{
dataTier.removeAcl(path);
}
@Override
public void setAcl(Path path, List<AclEntry> aclEntries)
throws IOException
{
dataTier.setAcl(path, aclEntries);
}
@Override
public AclStatus getAclStatus(Path path)
throws IOException
{
return dataTier.getAclStatus(path);
}
@Override
public void setXAttr(Path path, String name, byte[] value, EnumSet<XAttrSetFlag> xAttrSetFlags)
throws IOException
{
dataTier.setXAttr(path, name, value, xAttrSetFlags);
}
@Override
public byte[] getXAttr(Path path, String name)
throws IOException
{
return dataTier.getXAttr(path, name);
}
@Override
public Map<String, byte[]> getXAttrs(Path path)
throws IOException
{
return dataTier.getXAttrs(path);
}
@Override
public Map<String, byte[]> getXAttrs(Path path, List<String> names)
throws IOException
{
return dataTier.getXAttrs(path, names);
}
@Override
public List<String> listXAttrs(Path path)
throws IOException
{
return dataTier.listXAttrs(path);
}
@Override
public void removeXAttr(Path path, String name)
throws IOException
{
dataTier.removeXAttr(path, name);
}
@Override
public void access(Path path, FsAction mode)
throws IOException
{
dataTier.access(path, mode);
}
@Override
public Token<?>[] addDelegationTokens(String renewer, Credentials credentials)
throws IOException
{
return dataTier.addDelegationTokens(renewer, credentials);
}
@Override
public Path makeQualified(Path path)
{
return dataTier.makeQualified(path);
}
@Override
public RemoteIterator<LocatedFileStatus> listDirectory(Path path)
throws IOException
{
return dataTier.listDirectory(path);
}
@Override
public RemoteIterator<HiveFileInfo> listFiles(Path path)
throws IOException
{
return dataTier.listFiles(path);
}
@Override
public ListenableFuture<Void> renameFileAsync(Path source, Path destination)
throws IOException
{
return dataTier.renameFileAsync(source, destination);
}
}
| |
/*L
* Copyright Washington University in St. Louis
* Copyright SemanticBits
* Copyright Persistent Systems
* Copyright Krishagni
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catissue-advanced-query/LICENSE.txt for details.
*/
package edu.wustl.query.util.querysuite;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.util.QueryParams;
import edu.wustl.common.util.XMLPropertyHandler;
import edu.wustl.common.util.global.CommonServiceLocator;
import edu.wustl.common.util.global.QuerySessionData;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.dao.JDBCDAO;
import edu.wustl.dao.daofactory.DAOConfigFactory;
import edu.wustl.dao.daofactory.IDAOFactory;
import edu.wustl.dao.exception.DAOException;
import edu.wustl.dao.query.generator.ColumnValueBean;
import edu.wustl.query.executor.AbstractQueryExecutor;
import edu.wustl.query.util.global.AQConstants;
import edu.wustl.query.util.global.Utility;
import edu.wustl.security.exception.SMException;
/**
* Utility class for SQL related operations required for Query.
*
* @author santhoshkumar_c
*
*/
final public class QueryModuleSqlUtil {
private QueryModuleSqlUtil() {
}
/**
* Executes the query and returns the results.
*
* @param selectSql
* SQL to be executed
* @param sessionData
* sessionData
* @param querySessionData
* @return list of results
* @throws ClassNotFoundException
* @throws DAOException
* @throws SMException
*/
public static List<List<String>> executeQuery(
final SessionDataBean sessionData,
final QuerySessionData querySessionData)
throws ClassNotFoundException, DAOException, SMException {
List<List<String>> dataList = new ArrayList<List<String>>();
QueryParams queryParams = new QueryParams();
queryParams.setQuery(querySessionData.getSql());
queryParams.setSessionDataBean(sessionData);
queryParams.setStartIndex(-1);
queryParams.setSecureToExecute(querySessionData.isSecureExecute());
queryParams.setHasConditionOnIdentifiedField(querySessionData
.isHasConditionOnIdentifiedField());
queryParams.setQueryResultObjectDataMap(querySessionData
.getQueryResultObjectDataMap());
queryParams.setNoOfRecords(querySessionData.getRecordsPerPage());
AbstractQueryExecutor queryExecutor = Utility.getQueryExecutor();
dataList = queryExecutor.getQueryResultList(queryParams).getResult();
return dataList;
}
/**
* Creates a view in database for advance query.
*
* @param tableName
* name of the table to be deleted before creating new one.
* @param createTableSql
* SQL to create table
* @param sessionData
* session data.
* @throws DAOException
* DAOException
*/
public static void executeCreateTable(final String tableName,
final String createTableSql, QueryDetails queryDetailsObj)
throws DAOException {
String appName = CommonServiceLocator.getInstance().getAppName();
IDAOFactory daoFactory = DAOConfigFactory.getInstance().getDAOFactory(
appName);
JDBCDAO jdbcDao = daoFactory.getJDBCDAO();
try {
String tablespace = XMLPropertyHandler
.getValue(AQConstants.TABLESPACE);
if (tablespace.length() != 0) {
tablespace = "TABLESPACE " + tablespace;
}
jdbcDao.openSession(queryDetailsObj.getSessionData());
String createViewQuery = createTableSql;
while (createViewQuery.contains("(select")) {//check for inner select query
int startIndex = createViewQuery.indexOf("(select");
int lastIndex = createViewQuery.indexOf(")");
while (lastIndex < startIndex) {//indices for inner select query
lastIndex = createViewQuery.indexOf(")", lastIndex + 1);
}
//substring for creating inner view from inner select query
String innerViewQuery = createViewQuery.substring(startIndex, lastIndex + 1);
String innerViewName = ("VIEW" + (new Random().nextInt(1000)));//inner view name
String innerView = "CREATE OR REPLACE VIEW "+ innerViewName + " " + tablespace + " " + " AS "+ innerViewQuery;
//inner view create query
jdbcDao.executeUpdate(innerView);//creating inner view
/**
* Replacing the inner select query substring with the created inner view
*/
createViewQuery = createViewQuery.replace(innerViewQuery,innerViewName);
}
//creating a final view with inner views
String advViewQuery = "CREATE OR REPLACE VIEW " + tableName + " "+ tablespace + " " + " AS " + createViewQuery;
executeInsertQuery(queryDetailsObj, jdbcDao, advViewQuery);
} catch (DAOException e) {
Logger.out.error(e);
throw e;
} finally {
jdbcDao.closeSession();
}
}
/**
* @param queryDetailsObj
* queryDetailsObj
* @param jdbcDao
* jdbcDao
* @param insertSql
* insert query
* @throws DAOException
* DAOException
*/
private static void executeInsertQuery(QueryDetails queryDetailsObj,
JDBCDAO jdbcDao, String insertSql) throws DAOException {
int cnt =0;
String value;
/**
* removing binding variables by putting variables name in where clause
*/
while (insertSql.contains("?")) {
value = "'"+queryDetailsObj.getColumnValueBean().get(cnt++).getColumnName()+"'";
insertSql=insertSql.replaceFirst("\\?", value);//modifying sql for inserting variables in where clause
}
jdbcDao.executeUpdate(insertSql);
jdbcDao.commit();
}
/**
* @param createTableSql
* query
* @return newSql
*/
private static String modifySqlForCreateTable(String createTableSql) {
String whereClause = "";
if (createTableSql.indexOf("where") == -1) {
whereClause = "WHERE";
} else {
whereClause = "where";
}
String newSql = createTableSql.substring(0, createTableSql
.lastIndexOf(whereClause) + 6);
return newSql;
}
/**
* @param tableName
* @param columnNameIndexMap
* @return
*/
public static String getSQLForRootNode(final String tableName,
Map<String, String> columnNameIndexMap) {
String columnNames = columnNameIndexMap.get(AQConstants.COLUMN_NAMES);
String indexStr = columnNameIndexMap.get(AQConstants.INDEX);
int index = -1;
if (indexStr != null && !AQConstants.NULL.equals(indexStr)) {
index = Integer.valueOf(indexStr);
}
String idColumnName = columnNames;
if (columnNames.indexOf(',') != -1) {
idColumnName = columnNames.substring(0, columnNames.indexOf(','));
}
StringBuffer selectSql = new StringBuffer(80);
selectSql.append("select distinct ").append(columnNames).append(
" from ").append(tableName).append(" where ").append(
idColumnName).append(" is not null");
selectSql = selectSql.append(AQConstants.NODE_SEPARATOR).append(index);
return selectSql.toString();
}
/**
* Method to get count for the given SQL query
*
* @param sql
* original SQL for which count is required
* @param queryDetailsObj
* object of QueryDetails
* @return count integer value of count
* @throws DAOException
* @throws ClassNotFoundException
* @throws SMException
*/
public static int getCountForQuery(final String sql,
QueryDetails queryDetailsObj) throws DAOException,
ClassNotFoundException, SMException {
int count = 0;
List<List<String>> dataList = null;
String appName = CommonServiceLocator.getInstance().getAppName();
IDAOFactory daoFactory = DAOConfigFactory.getInstance().getDAOFactory(
appName);
JDBCDAO jdbcDao = daoFactory.getJDBCDAO();
try {
String countSql = "Select count(*) from (" + sql + ") alias";
QueryParams queryParams = new QueryParams();
SessionDataBean sessionData = queryDetailsObj.getSessionData();
queryParams.setQuery(countSql);
queryParams.setSessionDataBean(sessionData);
queryParams.setStartIndex(-1);
queryParams.setSecureToExecute(true);
queryParams.setHasConditionOnIdentifiedField(false);
queryParams.setQueryResultObjectDataMap(null);
queryParams.setNoOfRecords(200);
jdbcDao.openSession(queryDetailsObj.getSessionData());
AbstractQueryExecutor queryExecutor = Utility.getQueryExecutor();
dataList = queryExecutor.getQueryResultList(queryParams)
.getResult();
jdbcDao.commit();
} finally {
jdbcDao.closeSession();
}
if (dataList != null) {
List<String> countList = (List<String>) dataList.get(0);
count = Integer.valueOf(countList.get(0));
}
return count;
}
/**
*
* @param columnName
* @param newColumnValue
* @param auditEventId
* @throws DAOException
* @throws SQLException
* @throws SQLException
*/
public static void updateAuditQueryDetails(String columnName,
String newColumnValue, long auditEventId) throws DAOException,
SQLException {
String tableName = "catissue_audit_event_query_log";
String appName = CommonServiceLocator.getInstance().getAppName();
IDAOFactory daoFactory = DAOConfigFactory.getInstance().getDAOFactory(
appName);
JDBCDAO jdbcDao = daoFactory.getJDBCDAO();
jdbcDao.openSession(null);
ResultSet resultSet = jdbcDao.getQueryResultSet("select * from "
+ tableName + " where 1=0");
ResultSetMetaData metaData;
try {
metaData = resultSet.getMetaData();
LinkedList<LinkedList<ColumnValueBean>> beanList = populateBeanList(
columnName, newColumnValue, auditEventId, metaData);
executeUpdateQuery(columnName, tableName, jdbcDao, beanList);
} catch (DAOException e) {
Logger.out.error("Error while updating query auditing details :\n"
+ e);
throw e;
} catch (SQLException e1) {
Logger.out.error("Error while updating query auditing details :\n"
+ e1);
throw e1;
} finally {
jdbcDao.closeSession();
resultSet.close();
}
}
/**
* @param columnName
* columnName
* @param tableName
* tableName
* @param jdbcDao
* jdbcDao
* @param beanList
* beanList
* @throws DAOException
* DAOException
*/
private static void executeUpdateQuery(String columnName, String tableName,
JDBCDAO jdbcDao, LinkedList<LinkedList<ColumnValueBean>> beanList)
throws DAOException {
String updateSql = AQConstants.UPDATE + " " + tableName + " "
+ AQConstants.SET + " " + columnName + " = ?" + " "
+ AQConstants.WHERE + " " + AQConstants.AUDIT_EVENT_ID + "= ?";
jdbcDao.executeUpdate(updateSql, beanList);
jdbcDao.commit();
}
/**
* @param columnName
* columnName
* @param newColumnValue
* newColumnValue
* @param auditEventId
* auditEventId
* @param metaData
* metaData
* @return metaData
* @throws SQLException
* SQLException
*/
private static LinkedList<LinkedList<ColumnValueBean>> populateBeanList(
String columnName, String newColumnValue, long auditEventId,
ResultSetMetaData metaData) throws SQLException {
int columnType = getColumnType(columnName, metaData);
String value = getValueForDBType(newColumnValue, columnType);
LinkedList<ColumnValueBean> columnValueBean = new LinkedList<ColumnValueBean>();
ColumnValueBean bean = new ColumnValueBean("value", value);
columnValueBean.add(bean);
bean = new ColumnValueBean("auditEventId", Long.valueOf(auditEventId));
columnValueBean.add(bean);
LinkedList<LinkedList<ColumnValueBean>> beanList = new LinkedList<LinkedList<ColumnValueBean>>();
beanList.add(columnValueBean);
return beanList;
}
/**
* @param columnName
* columnName
* @param metaData
* metaData
* @return columnType
* @throws SQLException
* SQLException
*/
private static int getColumnType(String columnName,
ResultSetMetaData metaData) throws SQLException {
int columnType = 0;
int columnCount = metaData.getColumnCount();
for (int counter = 1; counter <= columnCount; counter++) {
String columnNameInTable = metaData.getColumnName(counter);
if (columnNameInTable.equalsIgnoreCase(columnName)) {
columnType = metaData.getColumnType(counter);
break;
}
}
return columnType;
}
/**
* Returns the value specific to data base type.
*
* @param newColumnValue
* value to be converted
* @param columnType
* type of the column.
* @return String value
*/
private static String getValueForDBType(String newColumnValue,
int columnType) {
String value = "";
switch (columnType) {
case Types.VARCHAR:
value = newColumnValue;
break;
case Types.BIGINT:
case Types.BIT:
case Types.TINYINT:
case Types.NUMERIC:
default:
value = newColumnValue;
break;
}
return value;
}
}
| |
package org.apache.hadoop.mapred;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.hadoop.http.HtmlQuoting;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.mapred.JSPUtil.JobWithViewAccessCheck;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.util.*;
public final class jobfailures_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final long serialVersionUID = 1L;
private void printFailedAttempts(JspWriter out,
JobTracker tracker,
TaskInProgress tip,
TaskStatus.State failState) throws IOException {
TaskStatus[] statuses = tip.getTaskStatuses();
TaskID tipId = tip.getTIPId();
for(int i=0; i < statuses.length; ++i) {
TaskStatus.State taskState = statuses[i].getRunState();
if ((failState == null && (taskState == TaskStatus.State.FAILED ||
taskState == TaskStatus.State.KILLED)) || taskState == failState) {
String taskTrackerName = statuses[i].getTaskTracker();
TaskTrackerStatus taskTracker = tracker.getTaskTrackerStatus(taskTrackerName);
out.print("<tr><td>" + statuses[i].getTaskID() +
"</td><td><a href=\"taskdetails.jsp?tipid=" + tipId + "\">" +
tipId + "</a></td>");
if (taskTracker == null) {
out.print("<td>" + taskTrackerName + "</td>");
} else {
out.print("<td><a href=\"http://" + taskTracker.getHost() + ":" +
taskTracker.getHttpPort() + "\">" + taskTracker.getHost() +
"</a></td>");
}
out.print("<td>" + taskState + "</td>");
out.print("<td><pre>");
String[] failures =
tracker.getTaskDiagnostics(statuses[i].getTaskID());
if (failures == null) {
out.print(" ");
} else {
for(int j = 0 ; j < failures.length ; j++){
out.print(HtmlQuoting.quoteHtmlChars(failures[j]));
if (j < (failures.length - 1)) {
out.print("\n-------\n");
}
}
}
out.print("</pre></td>");
out.print("<td>");
String taskLogUrl = null;
if (taskTracker != null) {
taskLogUrl = TaskLogServlet.getTaskLogUrl(taskTracker.getHost(),
String.valueOf(taskTracker.getHttpPort()),
statuses[i].getTaskID().toString());
}
if (taskLogUrl != null) {
String tailFourKBUrl = taskLogUrl + "&start=-4097";
String tailEightKBUrl = taskLogUrl + "&start=-8193";
String entireLogUrl = taskLogUrl;
out.print("<a href=\"" + tailFourKBUrl + "\">Last 4KB</a><br/>");
out.print("<a href=\"" + tailEightKBUrl + "\">Last 8KB</a><br/>");
out.print("<a href=\"" + entireLogUrl + "\">All</a><br/>");
} else {
out.print("n/a"); // task tracker was lost
}
out.print("</td>");
out.print("</tr>\n");
}
}
}
private void printFailures(JspWriter out,
JobTracker tracker,
JobInProgress job,
String kind,
String cause)
throws IOException, InterruptedException, ServletException {
boolean includeMap = false;
boolean includeReduce = false;
if (kind == null) {
includeMap = true;
includeReduce = true;
} else if ("map".equals(kind)) {
includeMap = true;
} else if ("reduce".equals(kind)) {
includeReduce = true;
} else if ("all".equals(kind)) {
includeMap = true;
includeReduce = true;
} else {
out.print("<b>Kind " + kind +
" not supported.</b><br>\n");
return;
}
TaskStatus.State state = null;
try {
if (cause != null) {
state = TaskStatus.State.valueOf(cause.toUpperCase());
if (state != TaskStatus.State.FAILED && state != TaskStatus.State.KILLED) {
out.print("<b>Cause '" + cause +
"' is not an 'unsuccessful' state.</b><br>\n");
return;
}
}
} catch (IllegalArgumentException e) {
out.print("<b>Cause '" + cause + "' not supported.</b><br>\n");
return;
}
out.print("<table border=2 cellpadding=\"5\" cellspacing=\"2\">");
out.print("<tr><th>Attempt</th><th>Task</th><th>Machine</th><th>State</th>" +
"<th>Error</th><th>Logs</th></tr>\n");
if (includeMap) {
TaskInProgress[] tips = job.getTasks(TaskType.MAP);
for(int i=0; i < tips.length; ++i) {
printFailedAttempts(out, tracker, tips[i], state);
}
}
if (includeReduce) {
TaskInProgress[] tips = job.getTasks(TaskType.REDUCE);
for(int i=0; i < tips.length; ++i) {
printFailedAttempts(out, tracker, tips[i], state);
}
}
out.print("</table>\n");
}
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.Vector _jspx_dependants;
private org.apache.jasper.runtime.ResourceInjector _jspx_resourceInjector;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write('\n');
out.write('\n');
out.write('\n');
out.write('\n');
JobTracker tracker = (JobTracker) application.getAttribute("job.tracker");
String trackerName =
StringUtils.simpleHostname(tracker.getJobTrackerMachine());
out.write('\n');
out.write('\n');
out.write('\n');
String jobId = request.getParameter("jobid");
if (jobId == null) {
out.println("<h2>Missing 'jobid'!</h2>");
return;
}
JobID jobIdObj = JobID.forName(jobId);
JobWithViewAccessCheck myJob = JSPUtil.checkAccessAndGetJob(
tracker, jobIdObj, request, response);
if (!myJob.isViewJobAllowed()) {
return; // user is not authorized to view this job
}
JobInProgress job = myJob.getJob();
if (job == null) {
out.print("<b>Job " + jobId + " not found.</b><br>\n");
return;
}
String kind = request.getParameter("kind");
String cause = request.getParameter("cause");
out.write("\n\n<!DOCTYPE html>\n<html>\n<title>Hadoop ");
out.print(jobId);
out.write(" failures on ");
out.print(trackerName);
out.write("</title>\n<body>\n<h1>Hadoop <a href=\"jobdetails.jsp?jobid=");
out.print(jobId);
out.write('"');
out.write('>');
out.print(jobId);
out.write("</a>\nfailures on <a href=\"jobtracker.jsp\">");
out.print(trackerName);
out.write("</a></h1>\n\n");
printFailures(out, tracker, job, kind, cause);
out.write("\n\n<hr>\n<a href=\"jobtracker.jsp\">Go back to JobTracker</a><br>\n");
out.println(ServletUtil.htmlFooter());
out.write('\n');
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| |
package com.lades.sihv.model;
// Generated 25/09/2018 14:47:05 by Hibernate Tools 4.3.1
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* SisUrinarioMamaria generated by hbm2java
*/
@Entity
@Table(name="sisUrinarioMamaria"
,catalog="bd_sihv"
)
public class SisUrinarioMamaria implements java.io.Serializable {
private SisUrinarioMamariaId id;
private VetConsultation vetConsultation;
private String ingestHidrica;
private String ingestHidricaEvolu;
private String estadoUrina;
private String urina;
private String urinaAspecto;
private String urinaEvolu;
private String ultimoCio;
private String prenhez;
private String prenhezDescricao;
private String ultimoParto;
private String secreVagiPeni;
private String secreVagiPeniTipo;
private String secreVagiPeniEvolu;
private String castrado;
private String sistemaAfetado;
public SisUrinarioMamaria() {
}
public SisUrinarioMamaria(SisUrinarioMamariaId id, VetConsultation vetConsultation, String ingestHidrica, String estadoUrina, String urina, String prenhez, String secreVagiPeni, String castrado, String sistemaAfetado) {
this.id = id;
this.vetConsultation = vetConsultation;
this.ingestHidrica = ingestHidrica;
this.estadoUrina = estadoUrina;
this.urina = urina;
this.prenhez = prenhez;
this.secreVagiPeni = secreVagiPeni;
this.castrado = castrado;
this.sistemaAfetado = sistemaAfetado;
}
public SisUrinarioMamaria(SisUrinarioMamariaId id, VetConsultation vetConsultation, String ingestHidrica, String ingestHidricaEvolu, String estadoUrina, String urina, String urinaAspecto, String urinaEvolu, String ultimoCio, String prenhez, String prenhezDescricao, String ultimoParto, String secreVagiPeni, String secreVagiPeniTipo, String secreVagiPeniEvolu, String castrado, String sistemaAfetado) {
this.id = id;
this.vetConsultation = vetConsultation;
this.ingestHidrica = ingestHidrica;
this.ingestHidricaEvolu = ingestHidricaEvolu;
this.estadoUrina = estadoUrina;
this.urina = urina;
this.urinaAspecto = urinaAspecto;
this.urinaEvolu = urinaEvolu;
this.ultimoCio = ultimoCio;
this.prenhez = prenhez;
this.prenhezDescricao = prenhezDescricao;
this.ultimoParto = ultimoParto;
this.secreVagiPeni = secreVagiPeni;
this.secreVagiPeniTipo = secreVagiPeniTipo;
this.secreVagiPeniEvolu = secreVagiPeniEvolu;
this.castrado = castrado;
this.sistemaAfetado = sistemaAfetado;
}
@EmbeddedId
@AttributeOverrides( {
@AttributeOverride(name="pkSisUrinarioMamaria", column=@Column(name="PK_sisUrinarioMamaria", nullable=false) ),
@AttributeOverride(name="vetConsultationPkVetConsultation", column=@Column(name="vetConsultation_PK_vetConsultation", nullable=false) ) } )
public SisUrinarioMamariaId getId() {
return this.id;
}
public void setId(SisUrinarioMamariaId id) {
this.id = id;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="vetConsultation_PK_vetConsultation", nullable=false, insertable=false, updatable=false)
public VetConsultation getVetConsultation() {
return this.vetConsultation;
}
public void setVetConsultation(VetConsultation vetConsultation) {
this.vetConsultation = vetConsultation;
}
@Column(name="ingestHidrica", nullable=false, length=28)
public String getIngestHidrica() {
return this.ingestHidrica;
}
public void setIngestHidrica(String ingestHidrica) {
this.ingestHidrica = ingestHidrica;
}
@Column(name="ingestHidricaEvolu", length=254)
public String getIngestHidricaEvolu() {
return this.ingestHidricaEvolu;
}
public void setIngestHidricaEvolu(String ingestHidricaEvolu) {
this.ingestHidricaEvolu = ingestHidricaEvolu;
}
@Column(name="estadoUrina", nullable=false, length=15)
public String getEstadoUrina() {
return this.estadoUrina;
}
public void setEstadoUrina(String estadoUrina) {
this.estadoUrina = estadoUrina;
}
@Column(name="urina", nullable=false, length=53)
public String getUrina() {
return this.urina;
}
public void setUrina(String urina) {
this.urina = urina;
}
@Column(name="urinaAspecto", length=254)
public String getUrinaAspecto() {
return this.urinaAspecto;
}
public void setUrinaAspecto(String urinaAspecto) {
this.urinaAspecto = urinaAspecto;
}
@Column(name="urinaEvolu", length=254)
public String getUrinaEvolu() {
return this.urinaEvolu;
}
public void setUrinaEvolu(String urinaEvolu) {
this.urinaEvolu = urinaEvolu;
}
@Column(name="ultimoCio", length=254)
public String getUltimoCio() {
return this.ultimoCio;
}
public void setUltimoCio(String ultimoCio) {
this.ultimoCio = ultimoCio;
}
@Column(name="prenhez", nullable=false, length=66)
public String getPrenhez() {
return this.prenhez;
}
public void setPrenhez(String prenhez) {
this.prenhez = prenhez;
}
@Column(name="prenhezDescricao", length=254)
public String getPrenhezDescricao() {
return this.prenhezDescricao;
}
public void setPrenhezDescricao(String prenhezDescricao) {
this.prenhezDescricao = prenhezDescricao;
}
@Column(name="ultimoParto", length=254)
public String getUltimoParto() {
return this.ultimoParto;
}
public void setUltimoParto(String ultimoParto) {
this.ultimoParto = ultimoParto;
}
@Column(name="secreVagiPeni", nullable=false, length=7)
public String getSecreVagiPeni() {
return this.secreVagiPeni;
}
public void setSecreVagiPeni(String secreVagiPeni) {
this.secreVagiPeni = secreVagiPeni;
}
@Column(name="secreVagiPeniTipo", length=100)
public String getSecreVagiPeniTipo() {
return this.secreVagiPeniTipo;
}
public void setSecreVagiPeniTipo(String secreVagiPeniTipo) {
this.secreVagiPeniTipo = secreVagiPeniTipo;
}
@Column(name="secreVagiPeniEvolu", length=254)
public String getSecreVagiPeniEvolu() {
return this.secreVagiPeniEvolu;
}
public void setSecreVagiPeniEvolu(String secreVagiPeniEvolu) {
this.secreVagiPeniEvolu = secreVagiPeniEvolu;
}
@Column(name="castrado", nullable=false, length=7)
public String getCastrado() {
return this.castrado;
}
public void setCastrado(String castrado) {
this.castrado = castrado;
}
@Column(name="sistemaAfetado", nullable=false, length=7)
public String getSistemaAfetado() {
return this.sistemaAfetado;
}
public void setSistemaAfetado(String sistemaAfetado) {
this.sistemaAfetado = sistemaAfetado;
}
}
| |
package jalse.entities;
import static jalse.entities.Entities.getTypeAncestry;
import static jalse.entities.Entities.isSubtype;
import static jalse.tags.Tags.getRootContainer;
import static jalse.tags.Tags.getTreeDepth;
import static jalse.tags.Tags.getTreeMember;
import static jalse.tags.Tags.setCreated;
import static jalse.tags.Tags.setOriginContainer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;
import jalse.actions.Action;
import jalse.actions.ActionContext;
import jalse.actions.ActionEngine;
import jalse.actions.DefaultActionScheduler;
import jalse.actions.SchedulableActionContext;
import jalse.attributes.AttributeContainer;
import jalse.attributes.AttributeListener;
import jalse.attributes.DefaultAttributeContainer;
import jalse.attributes.NamedAttributeType;
import jalse.misc.AbstractIdentifiable;
import jalse.misc.ListenerSet;
import jalse.tags.Created;
import jalse.tags.OriginContainer;
import jalse.tags.RootContainer;
import jalse.tags.Tag;
import jalse.tags.TagTypeSet;
import jalse.tags.TreeDepth;
import jalse.tags.TreeMember;
/**
* A simple yet fully featured {@link Entity} implementation.<br>
* <br>
* This entity can be marked as alive ({@link #markAsAlive()}) or dead ({@link #markAsDead()}).
*
* @author Elliot Ford
*
* @see DefaultEntityFactory
* @see DefaultEntityContainer
* @see DefaultAttributeContainer
* @see DefaultActionScheduler
* @see TagTypeSet
*
*/
public class DefaultEntity extends AbstractIdentifiable implements Entity {
/**
* Parent entity container.
*/
protected EntityContainer container;
/**
* Child entities.
*/
protected final DefaultEntityContainer entities;
/**
* Associated attributes.
*/
protected final DefaultAttributeContainer attributes;
/**
* Self action scheduler.
*/
protected final DefaultActionScheduler<Entity> scheduler;
/**
* Current state information.
*/
protected final TagTypeSet tags;
private final ListenerSet<EntityTypeListener> listeners;
private final Set<Class<? extends Entity>> types;
private final AtomicBoolean alive;
private final Lock read;
private final Lock write;
/**
* Creates a new default entity instance.
*
* @param id
* Entity ID.
* @param factory
* Entity factory for creating/killing child entities.
* @param container
* Parent entity container.
*/
protected DefaultEntity(final UUID id, final EntityFactory factory, final EntityContainer container) {
super(id);
this.container = container;
entities = new DefaultEntityContainer(factory, this);
attributes = new DefaultAttributeContainer(this);
tags = new TagTypeSet();
scheduler = new DefaultActionScheduler<>(this);
listeners = new ListenerSet<>(EntityTypeListener.class);
types = new HashSet<>();
alive = new AtomicBoolean();
final ReadWriteLock rwLock = new ReentrantReadWriteLock();
read = rwLock.readLock();
write = rwLock.writeLock();
}
@Override
public <T> boolean addAttributeListener(final NamedAttributeType<T> namedType,
final AttributeListener<T> listener) {
return attributes.addAttributeListener(namedType, listener);
}
/**
* Adds tree based tags for when a non-null container is set.
*
* @see RootContainer
* @see TreeDepth
*/
protected void addContainerTags() {
// Only add root if we aren't it
final RootContainer rc = getRootContainer(container);
if (rc != null) {
tags.add(rc);
}
final TreeDepth parentDepth = getTreeDepth(container);
tags.add(parentDepth != null ? parentDepth.increment() : TreeDepth.ROOT);
}
@Override
public boolean addEntityListener(final EntityListener listener) {
return entities.addEntityListener(listener);
}
@Override
public boolean addEntityTypeListener(final EntityTypeListener listener) {
Objects.requireNonNull(listener);
write.lock();
try {
return listeners.add(listener);
} finally {
write.unlock();
}
}
/**
* Adds the default tags.
*
* @see Created
* @see OriginContainer
* @see #addContainerTags()
*/
protected void addTags() {
setCreated(tags);
setOriginContainer(tags, container);
addContainerTags();
}
protected void addTreeMember() {
/*
* Ensure this is called before read: If this was added after creating an entity the
* listener could try and read this tag and it might not be up to date.
*/
tags.add(getTreeMember(this));
}
@Override
public void cancelAllScheduledForActor() {
scheduler.cancelAllScheduledForActor();
}
private void checkAlive() {
if (!isAlive()) {
throw new IllegalStateException(String.format("Entity %s is no longer alive", id));
}
}
@Override
public <T> void fireAttributeChanged(final NamedAttributeType<T> namedType) {
attributes.fireAttributeChanged(namedType);
}
@Override
public <T> T getAttribute(final NamedAttributeType<T> namedType) {
return attributes.getAttribute(namedType);
}
@Override
public int getAttributeCount() {
return attributes.getAttributeCount();
}
@Override
public <T> Set<? extends AttributeListener<T>> getAttributeListeners(final NamedAttributeType<T> namedType) {
return attributes.getAttributeListeners(namedType);
}
@Override
public Set<NamedAttributeType<?>> getAttributeListenerTypes() {
return attributes.getAttributeListenerTypes();
}
@Override
public Set<NamedAttributeType<?>> getAttributeTypes() {
return attributes.getAttributeTypes();
}
@Override
public EntityContainer getContainer() {
return isAlive() ? container : null;
}
/**
* Gets the associated action engine.
*
* @return Optional containing the engine or else empty optional if there is no engine
* associated.
*/
protected ActionEngine getEngine() {
return scheduler.getEngine();
}
@Override
public Entity getEntity(final UUID id) {
return entities.getEntity(id);
}
@Override
public int getEntityCount() {
return entities.getEntityCount();
}
@Override
public Set<UUID> getEntityIDs() {
return entities.getEntityIDs();
}
@Override
public Set<? extends EntityListener> getEntityListeners() {
return entities.getEntityListeners();
}
@Override
public Set<? extends EntityTypeListener> getEntityTypeListeners() {
read.lock();
try {
return new HashSet<>(listeners);
} finally {
read.unlock();
}
}
@Override
public <T extends Tag> Set<T> getTagsOfType(final Class<T> type) {
addTreeMember();
return tags.getOfType(type);
}
@Override
public boolean isAlive() {
return alive.get();
}
@Override
public boolean isMarkedAsType(final Class<? extends Entity> type) {
read.lock();
try {
return types.contains(type);
} finally {
read.unlock();
}
}
@Override
public boolean kill() {
return container.killEntity(id);
}
@Override
public void killEntities() {
entities.killEntities();
}
@Override
public boolean killEntity(final UUID id) {
return entities.killEntity(id);
}
/**
* Marks the entity as alive.
*
* @return Whether the core was alive.
* @see #addTags()
*/
protected boolean markAsAlive() {
addTags();
return alive.getAndSet(true);
}
/**
* Marks the entity as dead.
*
* @return Whether the core was alive.
*
* @see #removeContainerTags()
*/
protected boolean markAsDead() {
removeContainerTags();
return alive.getAndSet(false);
}
@Override
public boolean markAsType(final Class<? extends Entity> type) {
Objects.requireNonNull(type);
write.lock();
try {
// Add target type
if (!types.add(type)) {
return false;
}
// Add missing ancestors
final Set<Class<? extends Entity>> addedAncestors = new HashSet<>();
for (final Class<? extends Entity> at : getTypeAncestry(type)) {
if (types.add(at)) {
// Missing ancestor
addedAncestors.add(at);
}
}
// Trigger change
listeners.getProxy().entityMarkedAsType(new EntityTypeEvent(this, type, addedAncestors));
return true;
} finally {
write.unlock();
}
}
@Override
public SchedulableActionContext<Entity> newContextForActor(final Action<Entity> action) {
checkAlive();
return scheduler.newContextForActor(action);
}
@Override
public Entity newEntity(final UUID id, final AttributeContainer sourceContainer) {
checkAlive();
return entities.newEntity(id, sourceContainer);
}
@Override
public <T extends Entity> T newEntity(final UUID id, final Class<T> type,
final AttributeContainer sourceContainer) {
checkAlive();
return entities.newEntity(id, type, sourceContainer);
}
@Override
public boolean receiveEntity(final Entity e) {
return entities.receiveEntity(e);
}
@Override
public <T> T removeAttribute(final NamedAttributeType<T> namedType) {
return attributes.removeAttribute(namedType);
}
@Override
public <T> boolean removeAttributeListener(final NamedAttributeType<T> namedType,
final AttributeListener<T> listener) {
return attributes.removeAttributeListener(namedType, listener);
}
@Override
public void removeAttributeListeners() {
attributes.removeAttributeListeners();
}
@Override
public <T> void removeAttributeListeners(final NamedAttributeType<T> namedType) {
attributes.removeAttributeListeners(namedType);
}
@Override
public void removeAttributes() {
attributes.removeAttributes();
}
/**
* Removes tree based tags for when a null container is set.
*
* @see TreeMember
* @see RootContainer
* @see TreeDepth
*/
protected void removeContainerTags() {
tags.removeOfType(TreeMember.class);
tags.removeOfType(RootContainer.class);
tags.removeOfType(TreeDepth.class);
}
@Override
public boolean removeEntityListener(final EntityListener listener) {
return entities.removeEntityListener(listener);
}
@Override
public void removeEntityListeners() {
entities.removeEntityListeners();
}
@Override
public boolean removeEntityTypeListener(final EntityTypeListener listener) {
Objects.requireNonNull(listener);
write.lock();
try {
return listeners.remove(listener);
} finally {
write.unlock();
}
}
@Override
public void removeEntityTypeListeners() {
write.lock();
try {
listeners.clear();
} finally {
write.unlock();
}
}
@Override
public ActionContext<Entity> scheduleForActor(final Action<Entity> action, final long initialDelay,
final long period, final TimeUnit unit) {
checkAlive();
return scheduler.scheduleForActor(action, initialDelay, period, unit);
}
@Override
public <T> T setAttribute(final NamedAttributeType<T> namedType, final T attr) {
return attributes.setAttribute(namedType, attr);
}
/**
* Sets the parent container for the entity.
*
* @param container
* New parent container (can be null);
*/
protected void setContainer(final EntityContainer container) {
if (!Objects.equals(this.container, container)) {
this.container = container;
if (!isAlive()) {
return;
}
// Fix container based tags
if (container == null) {
removeContainerTags();
} else {
addContainerTags();
}
}
}
/**
* Associates an engine to the entity for scheduling actions.
*
* @param engine
* Engine to set.
*/
protected void setEngine(final ActionEngine engine) {
scheduler.setEngine(engine);
}
@Override
public Stream<?> streamAttributes() {
return attributes.streamAttributes();
}
@Override
public Stream<Entity> streamEntities() {
return entities.streamEntities();
}
@Override
public Stream<Class<? extends Entity>> streamMarkedAsTypes() {
read.lock();
try {
return new ArrayList<>(types).stream();
} finally {
read.unlock();
}
}
@Override
public Stream<Tag> streamTags() {
addTreeMember();
return tags.stream();
}
@Override
public boolean transfer(final EntityContainer destination) {
return container.transferEntity(id, destination);
}
@Override
public boolean transferEntity(final UUID id, final EntityContainer destination) {
return entities.transferEntity(id, destination);
}
@Override
public void unmarkAsAllTypes() {
write.lock();
try {
new ArrayList<>(types).forEach(this::unmarkAsType);
} finally {
write.unlock();
}
}
@Override
public boolean unmarkAsType(final Class<? extends Entity> type) {
Objects.requireNonNull(type);
write.lock();
try {
// Remove target type
if (!types.remove(type)) {
return false;
}
// Remove descendants
final Set<Class<? extends Entity>> removedDescendants = new HashSet<>();
final Iterator<Class<? extends Entity>> it = types.iterator();
while (it.hasNext()) {
final Class<? extends Entity> dt = it.next();
if (isSubtype(dt, type)) {
// Removed descendant
removedDescendants.add(dt);
it.remove();
}
}
// Trigger change
listeners.getProxy().entityUnmarkedAsType(new EntityTypeEvent(this, type, removedDescendants));
return true;
} finally {
write.unlock();
}
}
}
| |
/*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.uikit;
import apple.NSObject;
import apple.coregraphics.struct.CGPoint;
import apple.coregraphics.struct.CGSize;
import apple.foundation.NSArray;
import apple.foundation.NSDictionary;
import apple.foundation.NSIndexPath;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.ByValue;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;
@Generated
@Library("UIKit")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class UICollectionViewLayoutInvalidationContext extends NSObject {
static {
NatJ.register();
}
@Generated
protected UICollectionViewLayoutInvalidationContext(Pointer peer) {
super(peer);
}
@Generated
@Selector("accessInstanceVariablesDirectly")
public static native boolean accessInstanceVariablesDirectly();
@Generated
@Owned
@Selector("alloc")
public static native UICollectionViewLayoutInvalidationContext alloc();
@Owned
@Generated
@Selector("allocWithZone:")
public static native UICollectionViewLayoutInvalidationContext allocWithZone(VoidPtr zone);
@Generated
@Selector("automaticallyNotifiesObserversForKey:")
public static native boolean automaticallyNotifiesObserversForKey(String key);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:")
public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
@Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
@Mapped(ObjCObjectMapper.class) Object anArgument);
@Generated
@Selector("classFallbacksForKeyedArchiver")
public static native NSArray<String> classFallbacksForKeyedArchiver();
@Generated
@Selector("classForKeyedUnarchiver")
public static native Class classForKeyedUnarchiver();
@Generated
@Selector("debugDescription")
public static native String debugDescription_static();
@Generated
@Selector("description")
public static native String description_static();
@Generated
@Selector("hash")
@NUInt
public static native long hash_static();
@Generated
@Selector("instanceMethodForSelector:")
@FunctionPtr(name = "call_instanceMethodForSelector_ret")
public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);
@Generated
@Selector("instanceMethodSignatureForSelector:")
public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);
@Generated
@Selector("instancesRespondToSelector:")
public static native boolean instancesRespondToSelector(SEL aSelector);
@Generated
@Selector("isSubclassOfClass:")
public static native boolean isSubclassOfClass(Class aClass);
@Generated
@Selector("keyPathsForValuesAffectingValueForKey:")
public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);
@Generated
@Owned
@Selector("new")
public static native UICollectionViewLayoutInvalidationContext new_objc();
@Generated
@Selector("resolveClassMethod:")
public static native boolean resolveClassMethod(SEL sel);
@Generated
@Selector("resolveInstanceMethod:")
public static native boolean resolveInstanceMethod(SEL sel);
@Generated
@Selector("setVersion:")
public static native void setVersion_static(@NInt long aVersion);
@Generated
@Selector("superclass")
public static native Class superclass_static();
@Generated
@Selector("version")
@NInt
public static native long version_static();
/**
* delta to be applied to the collection view's current contentOffset - default is CGPointZero
*/
@Generated
@Selector("contentOffsetAdjustment")
@ByValue
public native CGPoint contentOffsetAdjustment();
/**
* delta to be applied to the current content size - default is CGSizeZero
*/
@Generated
@Selector("contentSizeAdjustment")
@ByValue
public native CGSize contentSizeAdjustment();
@Generated
@Selector("init")
public native UICollectionViewLayoutInvalidationContext init();
@Generated
@Selector("interactiveMovementTarget")
@ByValue
public native CGPoint interactiveMovementTarget();
/**
* if YES, the layout should requery section and item counts from the collection view - set to YES when the collection view is sent -reloadData and when items are inserted or deleted
*/
@Generated
@Selector("invalidateDataSourceCounts")
public native boolean invalidateDataSourceCounts();
@Generated
@Selector("invalidateDecorationElementsOfKind:atIndexPaths:")
public native void invalidateDecorationElementsOfKindAtIndexPaths(String elementKind,
NSArray<? extends NSIndexPath> indexPaths);
/**
* set to YES when invalidation occurs because the collection view is sent -reloadData
*/
@Generated
@Selector("invalidateEverything")
public native boolean invalidateEverything();
@Generated
@Selector("invalidateItemsAtIndexPaths:")
public native void invalidateItemsAtIndexPaths(NSArray<? extends NSIndexPath> indexPaths);
@Generated
@Selector("invalidateSupplementaryElementsOfKind:atIndexPaths:")
public native void invalidateSupplementaryElementsOfKindAtIndexPaths(String elementKind,
NSArray<? extends NSIndexPath> indexPaths);
/**
* keys are element kind strings - values are NSArrays of NSIndexPaths
*/
@Generated
@Selector("invalidatedDecorationIndexPaths")
public native NSDictionary<String, ? extends NSArray<? extends NSIndexPath>> invalidatedDecorationIndexPaths();
@Generated
@Selector("invalidatedItemIndexPaths")
public native NSArray<? extends NSIndexPath> invalidatedItemIndexPaths();
/**
* keys are element kind strings - values are NSArrays of NSIndexPaths
*/
@Generated
@Selector("invalidatedSupplementaryIndexPaths")
public native NSDictionary<String, ? extends NSArray<? extends NSIndexPath>> invalidatedSupplementaryIndexPaths();
/**
* index paths of moving items prior to the invalidation
*/
@Generated
@Selector("previousIndexPathsForInteractivelyMovingItems")
public native NSArray<? extends NSIndexPath> previousIndexPathsForInteractivelyMovingItems();
/**
* delta to be applied to the collection view's current contentOffset - default is CGPointZero
*/
@Generated
@Selector("setContentOffsetAdjustment:")
public native void setContentOffsetAdjustment(@ByValue CGPoint value);
/**
* delta to be applied to the current content size - default is CGSizeZero
*/
@Generated
@Selector("setContentSizeAdjustment:")
public native void setContentSizeAdjustment(@ByValue CGSize value);
/**
* index paths of moved items following the invalidation
*/
@Generated
@Selector("targetIndexPathsForInteractivelyMovingItems")
public native NSArray<? extends NSIndexPath> targetIndexPathsForInteractivelyMovingItems();
}
| |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.platform;
import com.intellij.facet.ui.FacetEditorValidator;
import com.intellij.facet.ui.FacetValidatorsManager;
import com.intellij.facet.ui.ValidationResult;
import com.intellij.ide.GeneralSettings;
import com.intellij.ide.ui.ListCellRendererWrapper;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComponentWithBrowseButton;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.DocumentAdapter;
import com.intellij.util.SystemProperties;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
/**
* @author yole
*/
public class NewDirectoryProjectDialog extends DialogWrapper {
private JTextField myProjectNameTextField;
private TextFieldWithBrowseButton myLocationField;
private JPanel myRootPane;
private JComboBox myProjectTypeComboBox;
private JPanel myProjectTypePanel;
private JLabel myLocationLabel;
private String myBaseDir;
private boolean myModifyingLocation = false;
private boolean myModifyingProjectName = false;
private static final Object EMPTY_PROJECT_GENERATOR = new Object();
protected NewDirectoryProjectDialog(Project project) {
super(project, true);
setTitle("Create New Project");
init();
myLocationLabel.setLabelFor(myLocationField.getChildComponent());
myBaseDir = getBaseDir();
File projectName = FileUtil.findSequentNonexistentFile(new File(myBaseDir), "untitled", "");
myLocationField.setText(projectName.toString());
myProjectNameTextField.setText(projectName.getName());
FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false);
ComponentWithBrowseButton.BrowseFolderActionListener<JTextField> listener =
new ComponentWithBrowseButton.BrowseFolderActionListener<JTextField>("Select Location for Project Directory", "", myLocationField,
project,
descriptor,
TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT) {
protected void onFileChoosen(VirtualFile chosenFile) {
super.onFileChoosen(chosenFile);
myBaseDir = chosenFile.getPath();
myLocationField.setText(new File(chosenFile.getPath(), myProjectNameTextField.getText()).toString());
}
};
myLocationField.addActionListener(listener);
myLocationField.getTextField().getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
myModifyingLocation = true;
String path = myLocationField.getText().trim();
if (path.endsWith(File.separator)) {
path = path.substring(0, path.length() - File.separator.length());
}
int ind = path.lastIndexOf(File.separator);
if (ind != -1) {
String projectName = path.substring(ind + 1, path.length());
if (!myProjectNameTextField.getText().trim().isEmpty()) {
myBaseDir = path.substring(0, ind);
}
if (!projectName.equals(myProjectNameTextField.getText())) {
if (!myModifyingProjectName) {
myProjectNameTextField.setText(projectName);
}
}
}
myModifyingLocation = false;
}
});
myProjectNameTextField.getDocument().addDocumentListener(new DocumentAdapter() {
protected void textChanged(final DocumentEvent e) {
if (!myModifyingLocation) {
myModifyingProjectName = true;
File f = new File(myBaseDir);
myLocationField.setText(new File(f, myProjectNameTextField.getText()).getPath());
myModifyingProjectName = false;
}
}
});
myProjectNameTextField.selectAll();
final DirectoryProjectGenerator[] generators = Extensions.getExtensions(DirectoryProjectGenerator.EP_NAME);
if (generators.length == 0) {
myProjectTypePanel.setVisible(false);
}
else {
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement(EMPTY_PROJECT_GENERATOR);
for (DirectoryProjectGenerator generator : generators) {
model.addElement(generator);
}
myProjectTypeComboBox.setModel(model);
myProjectTypeComboBox.setRenderer(new ListCellRendererWrapper(myProjectTypeComboBox.getRenderer()) {
@Override
public void customize(final JList list, final Object value, final int index, final boolean selected, final boolean cellHasFocus) {
if (value == null) return;
if (value == EMPTY_PROJECT_GENERATOR) {
setText("Empty project");
}
else {
setText(((DirectoryProjectGenerator)value).getName());
}
}
});
}
registerValidators(new FacetValidatorsManager() {
public void registerValidator(FacetEditorValidator validator, JComponent... componentsToWatch) {
}
public void validate() {
checkValid();
}
});
}
private void checkValid() {
String projectName = myProjectNameTextField.getText();
if (projectName.trim().isEmpty()) {
setOKActionEnabled(false);
setErrorText("Project name can't be empty");
return;
}
DirectoryProjectGenerator generator = getProjectGenerator();
if (generator != null) {
String baseDirPath = myLocationField.getTextField().getText();
ValidationResult validationResult = generator.validate(baseDirPath);
if (!validationResult.isOk()) {
setOKActionEnabled(false);
setErrorText(validationResult.getErrorMessage());
return;
}
}
setOKActionEnabled(true);
setErrorText(null);
}
private void registerValidators(final FacetValidatorsManager validatorsManager) {
validateOnTextChange(validatorsManager, myLocationField.getTextField());
validateOnSelectionChange(validatorsManager, myProjectTypeComboBox);
}
private static void validateOnSelectionChange(final FacetValidatorsManager validatorsManager, final JComboBox projectNameTextField) {
projectNameTextField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
validatorsManager.validate();
}
});
}
private static void validateOnTextChange(final FacetValidatorsManager validatorsManager, final JTextField textField) {
textField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
validatorsManager.validate();
}
});
}
public static String getBaseDir() {
final String lastProjectLocation = GeneralSettings.getInstance().getLastProjectLocation();
if (lastProjectLocation != null) {
return lastProjectLocation.replace('/', File.separatorChar);
}
final String userHome = SystemProperties.getUserHome();
//noinspection HardCodedStringLiteral
return userHome.replace('/', File.separatorChar) + File.separator + ApplicationNamesInfo.getInstance().getLowercaseProductName() +
"Projects";
}
protected JComponent createCenterPanel() {
return myRootPane;
}
public String getNewProjectLocation() {
return myLocationField.getText();
}
public String getNewProjectName() {
return myProjectNameTextField.getText();
}
@Nullable
public DirectoryProjectGenerator getProjectGenerator() {
final Object selItem = myProjectTypeComboBox.getSelectedItem();
if (selItem == EMPTY_PROJECT_GENERATOR) return null;
return (DirectoryProjectGenerator)selItem;
}
public JComponent getPreferredFocusedComponent() {
return myProjectNameTextField;
}
@Override
protected String getHelpId() {
return "create_new_project_dialog";
}
}
| |
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2011 BiGCaT Bioinformatics
//
// 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.pathvisio.cytoscape.superpathways;
import java.awt.Color;
import java.io.File;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.bridgedb.BridgeDb;
import org.bridgedb.DataSource;
import org.bridgedb.IDMapper;
import org.bridgedb.IDMapperException;
import org.bridgedb.Xref;
import org.bridgedb.bio.Organism;
import org.pathvisio.core.debug.Logger;
import org.pathvisio.core.model.ConverterException;
import org.pathvisio.core.model.ObjectType;
import org.pathvisio.core.model.Pathway;
import org.pathvisio.core.model.PathwayElement;
import org.pathvisio.core.preferences.GlobalPreference;
import org.pathvisio.wikipathways.webservice.WSPathway;
import org.wikipathways.client.WikiPathwaysClient;
import cytoscape.CyEdge;
import cytoscape.CyNetwork;
import cytoscape.CyNode;
import cytoscape.Cytoscape;
import cytoscape.data.CyAttributes;
import cytoscape.data.Semantics;
import cytoscape.layout.CyLayoutAlgorithm;
import cytoscape.layout.CyLayouts;
import cytoscape.layout.LayoutProperties;
import cytoscape.layout.Tunable;
public class CommonNodeView {
// List<String> selectedPwsNameId;
List<String> mSelectedPwsID;
List<String> mSelectedPwsNameID;
SuperpathwaysClient mClient;
Map<Xref, Xref> nodePairByTranslation;
List<String> colorPool;
protected boolean interrupted; // to enable cancel of the network merge
static String dbLocation = GlobalPreference.getDataDir().toString()
+ "/gene databases/";
public CommonNodeView(List<String> pwId, List<String> pwNameID, SuperpathwaysClient c) {
mSelectedPwsID = pwId;
mClient = c;
mSelectedPwsNameID=pwNameID;
nodePairByTranslation = new HashMap<Xref, Xref>();
interrupted = false;
}
public void interrupt() {
interrupted = true;
}
public List<String> getColorPool() {
return colorPool;
}
public Map<Xref, Xref> getNodePairByTranslation() {
return nodePairByTranslation;
}
public commonNodePathwayPair findCommonNode(String pw1ID, String pw1NameID, String pw2ID, String pw2NameID) throws ClassNotFoundException, IDMapperException {
commonNodePathwayPair cnPwPair = new commonNodePathwayPair();
int commonNode = 0;
// Create a client to the WikiPathways web service
WikiPathwaysClient client = mClient.getStub();
// Download these two pathways from WikiPathways by passing their id
WSPathway wsPathway1 = new WSPathway();
WSPathway wsPathway2 = new WSPathway();
try {
wsPathway1 = client.getPathway(pw1ID);
wsPathway2 = client.getPathway(pw2ID);
} catch (RemoteException e) {
Logger.log.error(
"Unable to get the pathway due to the RemoteException", e);
} catch (ConverterException e) {
Logger.log.error(
"Unable to get the pathway due to the ConverterException",
e);
}
// Create two corresponding pathway objects
Pathway pathway1 = new Pathway();
Pathway pathway2 = new Pathway();
try {
pathway1 = WikiPathwaysClient.toPathway(wsPathway1);
pathway2 = WikiPathwaysClient.toPathway(wsPathway2);
} catch (ConverterException e) {
Logger.log.error(
"Unable to get the pathway due to the RemoteException", e);
}
List<Xref> XrefListPw1 = new ArrayList<Xref>();
List<Xref> XrefListPw2 = new ArrayList<Xref>();
List<String> XrefListCommonNode = new ArrayList<String>();
// create the list of Xref for the pathway1: XrefListPw1
System.out.println("Xref info of one pathway: " + pw1ID);
for (PathwayElement pw1Elm : pathway1.getDataObjects()) {
// Only take elements with type DATANODE (genes, proteins,
// metabolites)
if (pw1Elm.getObjectType() == ObjectType.DATANODE) {
String id = pw1Elm.getGeneID();
DataSource ds = pw1Elm.getDataSource();
if (!checkString(id) || ds == null) {
continue; // Skip empty id/codes
}
// System.out.println("before translation: ");
// System.out.println(pw1Elm.getXref().toString());
XrefListPw1.add(pw1Elm.getXref());
}
}
// deternmine which database to be loaded according to the species of
// pathway2
Organism organism = Organism.fromLatinName(pathway2.getMappInfo()
.getOrganism());
// System.out.println("The organism for pathway2 is " + organism);
IDMapper gdb = mClient.getPlugin().getIDMapper(organism);
// create the list of Xref for the pathway2: XrefListPw2
System.out.println("Xref info of the other pathway: " + pw2ID);
for (PathwayElement pw2Elm : pathway2.getDataObjects()) {
if (pw2Elm.getObjectType() == ObjectType.DATANODE) {
if (interrupted)
return null;
boolean isMapped = false;
String id = pw2Elm.getGeneID();
DataSource ds = pw2Elm.getDataSource();
if (!checkString(id) || ds == null)
continue; // Skip empty
// id/codes
// System.out.println(pw2Elm.getXref().toString());
XrefListPw2.add(pw2Elm.getXref());
for (int k = 0; k < XrefListPw1.size(); k++) {
try {
Set<Xref> xrefs2 = gdb.mapID(pw2Elm.getXref());
if (xrefs2.contains(XrefListPw1.get(k))) {
isMapped = true;
System.out.println(pw2Elm.getXref().toString()
+ "======" + XrefListPw1.get(k).toString());
// this map is for later use--when merging pathways
nodePairByTranslation.put(pw2Elm.getXref(),
XrefListPw1.get(k));
}
} catch (IDMapperException e) {
Logger.log
.error(
"Problem while getting the all the Xrefs for the pathwayElement of pw2!",
e);
System.out
.println("Problem while getting the all the Xrefs for the pathwayElement of pw2!");
break;
}
}
if ((XrefListPw1.contains(pw2Elm.getXref().toString()) || isMapped)
&& !XrefListCommonNode.contains(pw2Elm.getXref()
.toString())) {
// maybe need to change later!!
commonNode = commonNode + 1;
XrefListCommonNode.add(pw2Elm.getXref().toString());
}
}
}
// the following code is for printing out the common nodes returned by
// the code
System.out.println("The common node: ");
for (int k = 0; k < XrefListCommonNode.size(); k++) {
System.out.println(XrefListCommonNode.get(k));
}
cnPwPair.pathway1NameID = pw1NameID;
cnPwPair.pathway2NameID = pw2NameID;
cnPwPair.commonNodeNumber = commonNode;
cnPwPair.geneIDListOfCommonNode = XrefListCommonNode;
return cnPwPair;
}
public List<commonNodePathwayPair> findCommonNodeForPathwaysGroup() throws ClassNotFoundException, IDMapperException {
List<commonNodePathwayPair> commonNodeInfoPwGroup = new ArrayList<commonNodePathwayPair>();
System.out.println("For Databases: " + dbLocation);
Object[] arrayOfSelectedPwsId = mSelectedPwsID.toArray();
Object[] arrayOfSelectedPwsNameId = mSelectedPwsNameID.toArray();
int len = arrayOfSelectedPwsId.length;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (interrupted)
return null;
commonNodeInfoPwGroup.add(findCommonNode(
(String) arrayOfSelectedPwsId[i], (String) arrayOfSelectedPwsNameId[i],
(String) arrayOfSelectedPwsId[j], (String) arrayOfSelectedPwsNameId[j]));
}
}
return commonNodeInfoPwGroup;
}
public Map<String, Color> drawCommonNodeView() throws ClassNotFoundException, IDMapperException {
if (interrupted)
return null;
Map<String, Color> pwNameToColor=new HashMap<String, Color>();
colorPool = new ArrayList<String>();
String[] shapePool = { "Diamond", "Hexagon", "Parallelogram",
"Round Rectange", "Rectangle", "Ellipse", "Triangle", "Octagon" };
List<commonNodePathwayPair> cnInfoPwGroup = findCommonNodeForPathwaysGroup();
CyNetwork cyNetwork = Cytoscape
.createNetwork("Common Node View", false);
CyAttributes nodeAtts = Cytoscape.getNodeAttributes();
CyAttributes edgeAtts = Cytoscape.getEdgeAttributes();
if (interrupted)
return null;
CyNode[] groupPwsIcons = new CyNode[mSelectedPwsID.size()];
for (int i = 0; i < mSelectedPwsID.size(); i++) {
groupPwsIcons[i] = Cytoscape.getCyNode(mSelectedPwsNameID.get(i), true);
cyNetwork.addNode(groupPwsIcons[i]);
nodeAtts.setAttribute(mSelectedPwsNameID.get(i), "node.fontSize", "10");
}
if (interrupted)
return null;
CyEdge[] groupEdges = new CyEdge[cnInfoPwGroup.size()];
int[] commonNodeNumber = new int[cnInfoPwGroup.size()];
int numberOfEdges = 0;
for (int j = 0; j < cnInfoPwGroup.size(); j++) {
commonNodePathwayPair temp = cnInfoPwGroup.get(j);
if (temp.commonNodeNumber != 0) {
CyNode n1 = Cytoscape.getCyNode(temp.pathway1NameID, false);
CyNode n2 = Cytoscape.getCyNode(temp.pathway2NameID, false);
groupEdges[numberOfEdges] = Cytoscape.getCyEdge(n1, n2, Semantics.INTERACTION, "pp", true);
commonNodeNumber[numberOfEdges] = temp.commonNodeNumber;
cyNetwork.addEdge(groupEdges[numberOfEdges]);
edgeAtts.setAttribute(groupEdges[numberOfEdges].getIdentifier(), "weight", commonNodeNumber[numberOfEdges]);
numberOfEdges++;
}
}
int numberOfSelectedPws = mSelectedPwsID.size();
double division1 = 360 / numberOfSelectedPws;
double division2 = 50 / numberOfSelectedPws;
for (int i = 0; i < mSelectedPwsID.size(); i++) {
// String temp=getRandomColorInString();
//use hsv and convert it to rgb
double h2=i*division1;
double s2=i*division2;
double v2=i*division2;
int h=Double.valueOf(h2).intValue();
int s=Double.valueOf(s2).intValue();
int v=Double.valueOf(v2).intValue();
System.out.println("value of h "+ h);
RGB tempRGB=hsvToRgb(h, 100, 100);
String temp=String.valueOf(Double.valueOf(tempRGB.r).intValue())+", "+String.valueOf(Double.valueOf(tempRGB.g).intValue())+", "+String.valueOf(Double.valueOf(tempRGB.b).intValue());
System.out.println("after conversion hsv to rgb"+ temp);
nodeAtts.setAttribute(groupPwsIcons[i].getIdentifier(),
"node.fillColor", temp);
//this part is for storing the info <pwName, corresponding color> into the pwNameToColor
String pwNameID=mSelectedPwsNameID.get(i);
int index2 = pwNameID.lastIndexOf("(");
String pwName = pwNameID.substring(0, index2);
System.out.println(Double.valueOf(tempRGB.r).intValue()+";"+Double.valueOf(tempRGB.g).intValue()+";"+Double.valueOf(tempRGB.b).intValue());
Color result=new Color(Double.valueOf(tempRGB.r).intValue(), Double.valueOf(tempRGB.g).intValue(),Double.valueOf(tempRGB.b).intValue());
pwNameToColor.put(pwName,result);
colorPool.add(temp);
nodeAtts.setAttribute(groupPwsIcons[i].getIdentifier(),
"node.shape", shapePool[i % shapePool.length]);
// re-use shapes from the shapePool when the number of
// selected Pws is larger than 8
}
for (int j = 0; j < numberOfEdges; j++) {
edgeAtts.setAttribute(groupEdges[j].getIdentifier(), "edge.label",
String.valueOf(commonNodeNumber[j]));
}
// display the common node view
Cytoscape.createNetworkView(cyNetwork, "Common Node View");
//the following code is for set the edge-weighted spring embedded layout (weight=the number of shared nodes)
CyLayoutAlgorithm alg = CyLayouts.getLayout("force-directed");
LayoutProperties props = alg.getSettings();
Tunable weightAttribute = props.get("edge_attribute");
weightAttribute.setValue("weight");
alg.updateSettings();
Cytoscape.getCurrentNetworkView().applyLayout(alg);
return pwNameToColor;
}
private static boolean checkString(String string) {
return string != null && string.length() > 0;
}
/*
* public static Color getRandomColor() { Random numGen = new Random();
* return new Color(numGen.nextInt(256), numGen.nextInt(256),
* numGen.nextInt(256)); }
*/
public static String getRandomColorInString() {
Random numGen = new Random();
return new String(numGen.nextInt(256) + ", " + numGen.nextInt(256)
+ ", " + numGen.nextInt(256));
}
public static RGB hsvToRgb(int h, int s, int v) {
RGB result = new RGB();
int i;
double f, p, q, t;
// Make sure our arguments stay in-range
h = Math.max(0, Math.min(360, h));
s = Math.max(0, Math.min(100, s));
v = Math.max(0, Math.min(100, v));
// We accept saturation and value arguments from 0 to 100 because that's
// how Photoshop represents those values. Internally, however, the
// saturation and value are calculated from a range of 0 to 1. We make
// That conversion here.
double s2 = (double)s / 100;
double v2 = (double)v / 100;
if (s2 == 0) {
// Achromatic (grey)
result.r = Math.round(v2 * 255);
result.g = Math.round(v2 * 255);
result.b = Math.round(v2 * 255);
return result;
}
double h2 = (double)h / 60; // sector 0 to 5
double i2 = Math.floor(h2);
i = Double.valueOf(i2).intValue();
f = h2 - i; // factorial part of h
p = v2 * (1 - s2);
q = v2 * (1 - s2 * f);
t = v2 * (1 - s2 * (1 - f));
switch (i) {
case 0:
result.r = v2;
result.g = t;
result.b = p;
break;
case 1:
result.r = q;
result.g = v2;
result.b = p;
break;
case 2:
result.r = p;
result.g = v2;
result.b = t;
break;
case 3:
result.r = p;
result.g = q;
result.b = v2;
break;
case 4:
result.r = t;
result.g = p;
result.b = v2;
break;
default: // case 5:
result.r = v2;
result.g = p;
result.b = q;
}
result.r = Math.round(result.r * 255);
result.g = Math.round(result.g * 255);
result.b = Math.round(result.b * 255);
return result;
}
public static class commonNodePathwayPair {
public String pathway1NameID;
public String pathway2NameID;
public int commonNodeNumber;
public List<String> geneIDListOfCommonNode = null;
}
public static class RGB {
public double r;
public double g;
public double b;
}
}
| |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.firestore.v1;
import com.google.api.core.BetaApi;
import com.google.firestore.v1.BatchGetDocumentsRequest;
import com.google.firestore.v1.BatchGetDocumentsResponse;
import com.google.firestore.v1.BeginTransactionRequest;
import com.google.firestore.v1.BeginTransactionResponse;
import com.google.firestore.v1.CommitRequest;
import com.google.firestore.v1.CommitResponse;
import com.google.firestore.v1.CreateDocumentRequest;
import com.google.firestore.v1.DeleteDocumentRequest;
import com.google.firestore.v1.Document;
import com.google.firestore.v1.FirestoreGrpc.FirestoreImplBase;
import com.google.firestore.v1.GetDocumentRequest;
import com.google.firestore.v1.ListCollectionIdsRequest;
import com.google.firestore.v1.ListCollectionIdsResponse;
import com.google.firestore.v1.ListDocumentsRequest;
import com.google.firestore.v1.ListDocumentsResponse;
import com.google.firestore.v1.ListenRequest;
import com.google.firestore.v1.ListenResponse;
import com.google.firestore.v1.RollbackRequest;
import com.google.firestore.v1.RunQueryRequest;
import com.google.firestore.v1.RunQueryResponse;
import com.google.firestore.v1.UpdateDocumentRequest;
import com.google.firestore.v1.WriteRequest;
import com.google.firestore.v1.WriteResponse;
import com.google.protobuf.Empty;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
@javax.annotation.Generated("by GAPIC")
@BetaApi
public class MockFirestoreImpl extends FirestoreImplBase {
private ArrayList<GeneratedMessageV3> requests;
private Queue<Object> responses;
public MockFirestoreImpl() {
requests = new ArrayList<>();
responses = new LinkedList<>();
}
public List<GeneratedMessageV3> getRequests() {
return requests;
}
public void addResponse(GeneratedMessageV3 response) {
responses.add(response);
}
public void setResponses(List<GeneratedMessageV3> responses) {
this.responses = new LinkedList<Object>(responses);
}
public void addException(Exception exception) {
responses.add(exception);
}
public void reset() {
requests = new ArrayList<>();
responses = new LinkedList<>();
}
@Override
public void getDocument(GetDocumentRequest request, StreamObserver<Document> responseObserver) {
Object response = responses.remove();
if (response instanceof Document) {
requests.add(request);
responseObserver.onNext((Document) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void listDocuments(
ListDocumentsRequest request, StreamObserver<ListDocumentsResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof ListDocumentsResponse) {
requests.add(request);
responseObserver.onNext((ListDocumentsResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void createDocument(
CreateDocumentRequest request, StreamObserver<Document> responseObserver) {
Object response = responses.remove();
if (response instanceof Document) {
requests.add(request);
responseObserver.onNext((Document) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void updateDocument(
UpdateDocumentRequest request, StreamObserver<Document> responseObserver) {
Object response = responses.remove();
if (response instanceof Document) {
requests.add(request);
responseObserver.onNext((Document) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void deleteDocument(
DeleteDocumentRequest request, StreamObserver<Empty> responseObserver) {
Object response = responses.remove();
if (response instanceof Empty) {
requests.add(request);
responseObserver.onNext((Empty) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void batchGetDocuments(
BatchGetDocumentsRequest request,
StreamObserver<BatchGetDocumentsResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof BatchGetDocumentsResponse) {
requests.add(request);
responseObserver.onNext((BatchGetDocumentsResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void beginTransaction(
BeginTransactionRequest request, StreamObserver<BeginTransactionResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof BeginTransactionResponse) {
requests.add(request);
responseObserver.onNext((BeginTransactionResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void commit(CommitRequest request, StreamObserver<CommitResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof CommitResponse) {
requests.add(request);
responseObserver.onNext((CommitResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void rollback(RollbackRequest request, StreamObserver<Empty> responseObserver) {
Object response = responses.remove();
if (response instanceof Empty) {
requests.add(request);
responseObserver.onNext((Empty) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void runQuery(RunQueryRequest request, StreamObserver<RunQueryResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof RunQueryResponse) {
requests.add(request);
responseObserver.onNext((RunQueryResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public StreamObserver<WriteRequest> write(final StreamObserver<WriteResponse> responseObserver) {
final Object response = responses.remove();
StreamObserver<WriteRequest> requestObserver =
new StreamObserver<WriteRequest>() {
@Override
public void onNext(WriteRequest value) {
if (response instanceof WriteResponse) {
responseObserver.onNext((WriteResponse) response);
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void onError(Throwable t) {
responseObserver.onError(t);
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
};
return requestObserver;
}
@Override
public StreamObserver<ListenRequest> listen(
final StreamObserver<ListenResponse> responseObserver) {
final Object response = responses.remove();
StreamObserver<ListenRequest> requestObserver =
new StreamObserver<ListenRequest>() {
@Override
public void onNext(ListenRequest value) {
if (response instanceof ListenResponse) {
responseObserver.onNext((ListenResponse) response);
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
@Override
public void onError(Throwable t) {
responseObserver.onError(t);
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
};
return requestObserver;
}
@Override
public void listCollectionIds(
ListCollectionIdsRequest request,
StreamObserver<ListCollectionIdsResponse> responseObserver) {
Object response = responses.remove();
if (response instanceof ListCollectionIdsResponse) {
requests.add(request);
responseObserver.onNext((ListCollectionIdsResponse) response);
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError((Exception) response);
} else {
responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
}
}
}
| |
/*
* 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.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.milo.client.MiloClientComponent;
/**
* Connect to OPC UA servers using the binary protocol for acquiring telemetry
* data.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface MiloClientComponentBuilderFactory {
/**
* OPC UA Client (camel-milo)
* Connect to OPC UA servers using the binary protocol for acquiring
* telemetry data.
*
* Category: iot
* Since: 2.19
* Maven coordinates: org.apache.camel:camel-milo
*
* @return the dsl builder
*/
static MiloClientComponentBuilder miloClient() {
return new MiloClientComponentBuilderImpl();
}
/**
* Builder for the OPC UA Client component.
*/
interface MiloClientComponentBuilder
extends
ComponentBuilder<MiloClientComponent> {
/**
* A virtual client id to force the creation of a new connection
* instance.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param clientId the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder clientId(java.lang.String clientId) {
doSetProperty("clientId", clientId);
return this;
}
/**
* All default options for client configurations.
*
* The option is a:
* <code>org.apache.camel.component.milo.client.MiloClientConfiguration</code> type.
*
* Group: common
*
* @param configuration the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder configuration(
org.apache.camel.component.milo.client.MiloClientConfiguration configuration) {
doSetProperty("configuration", configuration);
return this;
}
/**
* A suffix for endpoint URI when discovering.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param discoveryEndpointSuffix the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder discoveryEndpointSuffix(
java.lang.String discoveryEndpointSuffix) {
doSetProperty("discoveryEndpointSuffix", discoveryEndpointSuffix);
return this;
}
/**
* An alternative discovery URI.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param discoveryEndpointUri the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder discoveryEndpointUri(
java.lang.String discoveryEndpointUri) {
doSetProperty("discoveryEndpointUri", discoveryEndpointUri);
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 MiloClientComponentBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
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 MiloClientComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder autowiredEnabled(
boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* A set of allowed security policy URIs. Default is to accept all and
* use the highest.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: client
*
* @param allowedSecurityPolicies the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder allowedSecurityPolicies(
java.lang.String allowedSecurityPolicies) {
doSetProperty("allowedSecurityPolicies", allowedSecurityPolicies);
return this;
}
/**
* The application name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: Apache Camel adapter for Eclipse Milo
* Group: client
*
* @param applicationName the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder applicationName(
java.lang.String applicationName) {
doSetProperty("applicationName", applicationName);
return this;
}
/**
* The application URI.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: http://camel.apache.org/EclipseMilo/Client
* Group: client
*
* @param applicationUri the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder applicationUri(
java.lang.String applicationUri) {
doSetProperty("applicationUri", applicationUri);
return this;
}
/**
* Channel lifetime in milliseconds.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: client
*
* @param channelLifetime the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder channelLifetime(
java.lang.Long channelLifetime) {
doSetProperty("channelLifetime", channelLifetime);
return this;
}
/**
* The name of the key in the keystore file.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: client
*
* @param keyAlias the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder keyAlias(java.lang.String keyAlias) {
doSetProperty("keyAlias", keyAlias);
return this;
}
/**
* The key password.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: client
*
* @param keyPassword the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder keyPassword(
java.lang.String keyPassword) {
doSetProperty("keyPassword", keyPassword);
return this;
}
/**
* The keystore password.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: client
*
* @param keyStorePassword the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder keyStorePassword(
java.lang.String keyStorePassword) {
doSetProperty("keyStorePassword", keyStorePassword);
return this;
}
/**
* The key store type.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: client
*
* @param keyStoreType the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder keyStoreType(
java.lang.String keyStoreType) {
doSetProperty("keyStoreType", keyStoreType);
return this;
}
/**
* The URL where the key should be loaded from.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: client
*
* @param keyStoreUrl the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder keyStoreUrl(
java.lang.String keyStoreUrl) {
doSetProperty("keyStoreUrl", keyStoreUrl);
return this;
}
/**
* The maximum number of pending publish requests.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: client
*
* @param maxPendingPublishRequests the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder maxPendingPublishRequests(
java.lang.Long maxPendingPublishRequests) {
doSetProperty("maxPendingPublishRequests", maxPendingPublishRequests);
return this;
}
/**
* The maximum number of bytes a response message may have.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: client
*
* @param maxResponseMessageSize the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder maxResponseMessageSize(
java.lang.Long maxResponseMessageSize) {
doSetProperty("maxResponseMessageSize", maxResponseMessageSize);
return this;
}
/**
* Instance for managing client connections.
*
* The option is a:
* <code>org.apache.camel.component.milo.client.MiloClientConnectionManager</code> type.
*
* Group: client
*
* @param miloClientConnectionManager the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder miloClientConnectionManager(
org.apache.camel.component.milo.client.MiloClientConnectionManager miloClientConnectionManager) {
doSetProperty("miloClientConnectionManager", miloClientConnectionManager);
return this;
}
/**
* Override the server reported endpoint host with the host from the
* endpoint URI.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: client
*
* @param overrideHost the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder overrideHost(boolean overrideHost) {
doSetProperty("overrideHost", overrideHost);
return this;
}
/**
* The product URI.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: http://camel.apache.org/EclipseMilo
* Group: client
*
* @param productUri the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder productUri(
java.lang.String productUri) {
doSetProperty("productUri", productUri);
return this;
}
/**
* The requested publishing interval in milliseconds.
*
* The option is a: <code>java.lang.Double</code> type.
*
* Default: 1_000.0
* Group: client
*
* @param requestedPublishingInterval the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder requestedPublishingInterval(
java.lang.Double requestedPublishingInterval) {
doSetProperty("requestedPublishingInterval", requestedPublishingInterval);
return this;
}
/**
* Request timeout in milliseconds.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: client
*
* @param requestTimeout the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder requestTimeout(
java.lang.Long requestTimeout) {
doSetProperty("requestTimeout", requestTimeout);
return this;
}
/**
* Session name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: client
*
* @param sessionName the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder sessionName(
java.lang.String sessionName) {
doSetProperty("sessionName", sessionName);
return this;
}
/**
* Session timeout in milliseconds.
*
* The option is a: <code>java.lang.Long</code> type.
*
* Group: client
*
* @param sessionTimeout the value to set
* @return the dsl builder
*/
default MiloClientComponentBuilder sessionTimeout(
java.lang.Long sessionTimeout) {
doSetProperty("sessionTimeout", sessionTimeout);
return this;
}
}
class MiloClientComponentBuilderImpl
extends
AbstractComponentBuilder<MiloClientComponent>
implements
MiloClientComponentBuilder {
@Override
protected MiloClientComponent buildConcreteComponent() {
return new MiloClientComponent();
}
private org.apache.camel.component.milo.client.MiloClientConfiguration getOrCreateConfiguration(
org.apache.camel.component.milo.client.MiloClientComponent component) {
if (component.getConfiguration() == null) {
component.setConfiguration(new org.apache.camel.component.milo.client.MiloClientConfiguration());
}
return component.getConfiguration();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "clientId": getOrCreateConfiguration((MiloClientComponent) component).setClientId((java.lang.String) value); return true;
case "configuration": ((MiloClientComponent) component).setConfiguration((org.apache.camel.component.milo.client.MiloClientConfiguration) value); return true;
case "discoveryEndpointSuffix": getOrCreateConfiguration((MiloClientComponent) component).setDiscoveryEndpointSuffix((java.lang.String) value); return true;
case "discoveryEndpointUri": getOrCreateConfiguration((MiloClientComponent) component).setDiscoveryEndpointUri((java.lang.String) value); return true;
case "bridgeErrorHandler": ((MiloClientComponent) component).setBridgeErrorHandler((boolean) value); return true;
case "lazyStartProducer": ((MiloClientComponent) component).setLazyStartProducer((boolean) value); return true;
case "autowiredEnabled": ((MiloClientComponent) component).setAutowiredEnabled((boolean) value); return true;
case "allowedSecurityPolicies": getOrCreateConfiguration((MiloClientComponent) component).setAllowedSecurityPolicies((java.lang.String) value); return true;
case "applicationName": getOrCreateConfiguration((MiloClientComponent) component).setApplicationName((java.lang.String) value); return true;
case "applicationUri": getOrCreateConfiguration((MiloClientComponent) component).setApplicationUri((java.lang.String) value); return true;
case "channelLifetime": getOrCreateConfiguration((MiloClientComponent) component).setChannelLifetime((java.lang.Long) value); return true;
case "keyAlias": getOrCreateConfiguration((MiloClientComponent) component).setKeyAlias((java.lang.String) value); return true;
case "keyPassword": getOrCreateConfiguration((MiloClientComponent) component).setKeyPassword((java.lang.String) value); return true;
case "keyStorePassword": getOrCreateConfiguration((MiloClientComponent) component).setKeyStorePassword((java.lang.String) value); return true;
case "keyStoreType": getOrCreateConfiguration((MiloClientComponent) component).setKeyStoreType((java.lang.String) value); return true;
case "keyStoreUrl": getOrCreateConfiguration((MiloClientComponent) component).setKeyStoreUrl((java.lang.String) value); return true;
case "maxPendingPublishRequests": getOrCreateConfiguration((MiloClientComponent) component).setMaxPendingPublishRequests((java.lang.Long) value); return true;
case "maxResponseMessageSize": getOrCreateConfiguration((MiloClientComponent) component).setMaxResponseMessageSize((java.lang.Long) value); return true;
case "miloClientConnectionManager": ((MiloClientComponent) component).setMiloClientConnectionManager((org.apache.camel.component.milo.client.MiloClientConnectionManager) value); return true;
case "overrideHost": getOrCreateConfiguration((MiloClientComponent) component).setOverrideHost((boolean) value); return true;
case "productUri": getOrCreateConfiguration((MiloClientComponent) component).setProductUri((java.lang.String) value); return true;
case "requestedPublishingInterval": getOrCreateConfiguration((MiloClientComponent) component).setRequestedPublishingInterval((java.lang.Double) value); return true;
case "requestTimeout": getOrCreateConfiguration((MiloClientComponent) component).setRequestTimeout((java.lang.Long) value); return true;
case "sessionName": getOrCreateConfiguration((MiloClientComponent) component).setSessionName((java.lang.String) value); return true;
case "sessionTimeout": getOrCreateConfiguration((MiloClientComponent) component).setSessionTimeout((java.lang.Long) value); return true;
default: return false;
}
}
}
}
| |
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.schemaorg.core;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.schemaorg.SchemaOrgTypeImpl;
import com.google.schemaorg.ValueType;
import com.google.schemaorg.core.datatype.Date;
import com.google.schemaorg.core.datatype.Text;
import com.google.schemaorg.core.datatype.URL;
import com.google.schemaorg.goog.GoogConstants;
import com.google.schemaorg.goog.PopularityScoreSpecification;
/** Implementation of {@link GardenStore}. */
public class GardenStoreImpl extends StoreImpl implements GardenStore {
private static final ImmutableSet<String> PROPERTY_SET = initializePropertySet();
private static ImmutableSet<String> initializePropertySet() {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
builder.add(CoreConstants.PROPERTY_ADDITIONAL_PROPERTY);
builder.add(CoreConstants.PROPERTY_ADDITIONAL_TYPE);
builder.add(CoreConstants.PROPERTY_ADDRESS);
builder.add(CoreConstants.PROPERTY_AGGREGATE_RATING);
builder.add(CoreConstants.PROPERTY_ALTERNATE_NAME);
builder.add(CoreConstants.PROPERTY_ALUMNI);
builder.add(CoreConstants.PROPERTY_AREA_SERVED);
builder.add(CoreConstants.PROPERTY_AWARD);
builder.add(CoreConstants.PROPERTY_AWARDS);
builder.add(CoreConstants.PROPERTY_BRANCH_CODE);
builder.add(CoreConstants.PROPERTY_BRANCH_OF);
builder.add(CoreConstants.PROPERTY_BRAND);
builder.add(CoreConstants.PROPERTY_CONTACT_POINT);
builder.add(CoreConstants.PROPERTY_CONTACT_POINTS);
builder.add(CoreConstants.PROPERTY_CONTAINED_IN);
builder.add(CoreConstants.PROPERTY_CONTAINED_IN_PLACE);
builder.add(CoreConstants.PROPERTY_CONTAINS_PLACE);
builder.add(CoreConstants.PROPERTY_CURRENCIES_ACCEPTED);
builder.add(CoreConstants.PROPERTY_DEPARTMENT);
builder.add(CoreConstants.PROPERTY_DESCRIPTION);
builder.add(CoreConstants.PROPERTY_DISSOLUTION_DATE);
builder.add(CoreConstants.PROPERTY_DUNS);
builder.add(CoreConstants.PROPERTY_EMAIL);
builder.add(CoreConstants.PROPERTY_EMPLOYEE);
builder.add(CoreConstants.PROPERTY_EMPLOYEES);
builder.add(CoreConstants.PROPERTY_EVENT);
builder.add(CoreConstants.PROPERTY_EVENTS);
builder.add(CoreConstants.PROPERTY_FAX_NUMBER);
builder.add(CoreConstants.PROPERTY_FOUNDER);
builder.add(CoreConstants.PROPERTY_FOUNDERS);
builder.add(CoreConstants.PROPERTY_FOUNDING_DATE);
builder.add(CoreConstants.PROPERTY_FOUNDING_LOCATION);
builder.add(CoreConstants.PROPERTY_GEO);
builder.add(CoreConstants.PROPERTY_GLOBAL_LOCATION_NUMBER);
builder.add(CoreConstants.PROPERTY_HAS_MAP);
builder.add(CoreConstants.PROPERTY_HAS_OFFER_CATALOG);
builder.add(CoreConstants.PROPERTY_HAS_POS);
builder.add(CoreConstants.PROPERTY_IMAGE);
builder.add(CoreConstants.PROPERTY_ISIC_V4);
builder.add(CoreConstants.PROPERTY_LEGAL_NAME);
builder.add(CoreConstants.PROPERTY_LOCATION);
builder.add(CoreConstants.PROPERTY_LOGO);
builder.add(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE);
builder.add(CoreConstants.PROPERTY_MAKES_OFFER);
builder.add(CoreConstants.PROPERTY_MAP);
builder.add(CoreConstants.PROPERTY_MAPS);
builder.add(CoreConstants.PROPERTY_MEMBER);
builder.add(CoreConstants.PROPERTY_MEMBER_OF);
builder.add(CoreConstants.PROPERTY_MEMBERS);
builder.add(CoreConstants.PROPERTY_NAICS);
builder.add(CoreConstants.PROPERTY_NAME);
builder.add(CoreConstants.PROPERTY_NUMBER_OF_EMPLOYEES);
builder.add(CoreConstants.PROPERTY_OPENING_HOURS);
builder.add(CoreConstants.PROPERTY_OPENING_HOURS_SPECIFICATION);
builder.add(CoreConstants.PROPERTY_OWNS);
builder.add(CoreConstants.PROPERTY_PARENT_ORGANIZATION);
builder.add(CoreConstants.PROPERTY_PAYMENT_ACCEPTED);
builder.add(CoreConstants.PROPERTY_PHOTO);
builder.add(CoreConstants.PROPERTY_PHOTOS);
builder.add(CoreConstants.PROPERTY_POTENTIAL_ACTION);
builder.add(CoreConstants.PROPERTY_PRICE_RANGE);
builder.add(CoreConstants.PROPERTY_REVIEW);
builder.add(CoreConstants.PROPERTY_REVIEWS);
builder.add(CoreConstants.PROPERTY_SAME_AS);
builder.add(CoreConstants.PROPERTY_SEEKS);
builder.add(CoreConstants.PROPERTY_SERVICE_AREA);
builder.add(CoreConstants.PROPERTY_SUB_ORGANIZATION);
builder.add(CoreConstants.PROPERTY_TAX_ID);
builder.add(CoreConstants.PROPERTY_TELEPHONE);
builder.add(CoreConstants.PROPERTY_URL);
builder.add(CoreConstants.PROPERTY_VAT_ID);
builder.add(GoogConstants.PROPERTY_DETAILED_DESCRIPTION);
builder.add(GoogConstants.PROPERTY_POPULARITY_SCORE);
return builder.build();
}
static final class BuilderImpl extends SchemaOrgTypeImpl.BuilderImpl<GardenStore.Builder>
implements GardenStore.Builder {
@Override
public GardenStore.Builder addAdditionalProperty(PropertyValue value) {
return addProperty(CoreConstants.PROPERTY_ADDITIONAL_PROPERTY, value);
}
@Override
public GardenStore.Builder addAdditionalProperty(PropertyValue.Builder value) {
return addProperty(CoreConstants.PROPERTY_ADDITIONAL_PROPERTY, value.build());
}
@Override
public GardenStore.Builder addAdditionalProperty(String value) {
return addProperty(CoreConstants.PROPERTY_ADDITIONAL_PROPERTY, Text.of(value));
}
@Override
public GardenStore.Builder addAdditionalType(URL value) {
return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, value);
}
@Override
public GardenStore.Builder addAdditionalType(String value) {
return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, Text.of(value));
}
@Override
public GardenStore.Builder addAddress(PostalAddress value) {
return addProperty(CoreConstants.PROPERTY_ADDRESS, value);
}
@Override
public GardenStore.Builder addAddress(PostalAddress.Builder value) {
return addProperty(CoreConstants.PROPERTY_ADDRESS, value.build());
}
@Override
public GardenStore.Builder addAddress(Text value) {
return addProperty(CoreConstants.PROPERTY_ADDRESS, value);
}
@Override
public GardenStore.Builder addAddress(String value) {
return addProperty(CoreConstants.PROPERTY_ADDRESS, Text.of(value));
}
@Override
public GardenStore.Builder addAggregateRating(AggregateRating value) {
return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value);
}
@Override
public GardenStore.Builder addAggregateRating(AggregateRating.Builder value) {
return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value.build());
}
@Override
public GardenStore.Builder addAggregateRating(String value) {
return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, Text.of(value));
}
@Override
public GardenStore.Builder addAlternateName(Text value) {
return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, value);
}
@Override
public GardenStore.Builder addAlternateName(String value) {
return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, Text.of(value));
}
@Override
public GardenStore.Builder addAlumni(Person value) {
return addProperty(CoreConstants.PROPERTY_ALUMNI, value);
}
@Override
public GardenStore.Builder addAlumni(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_ALUMNI, value.build());
}
@Override
public GardenStore.Builder addAlumni(String value) {
return addProperty(CoreConstants.PROPERTY_ALUMNI, Text.of(value));
}
@Override
public GardenStore.Builder addAreaServed(AdministrativeArea value) {
return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value);
}
@Override
public GardenStore.Builder addAreaServed(AdministrativeArea.Builder value) {
return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value.build());
}
@Override
public GardenStore.Builder addAreaServed(GeoShape value) {
return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value);
}
@Override
public GardenStore.Builder addAreaServed(GeoShape.Builder value) {
return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value.build());
}
@Override
public GardenStore.Builder addAreaServed(Place value) {
return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value);
}
@Override
public GardenStore.Builder addAreaServed(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value.build());
}
@Override
public GardenStore.Builder addAreaServed(Text value) {
return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value);
}
@Override
public GardenStore.Builder addAreaServed(String value) {
return addProperty(CoreConstants.PROPERTY_AREA_SERVED, Text.of(value));
}
@Override
public GardenStore.Builder addAward(Text value) {
return addProperty(CoreConstants.PROPERTY_AWARD, value);
}
@Override
public GardenStore.Builder addAward(String value) {
return addProperty(CoreConstants.PROPERTY_AWARD, Text.of(value));
}
@Override
public GardenStore.Builder addAwards(Text value) {
return addProperty(CoreConstants.PROPERTY_AWARDS, value);
}
@Override
public GardenStore.Builder addAwards(String value) {
return addProperty(CoreConstants.PROPERTY_AWARDS, Text.of(value));
}
@Override
public GardenStore.Builder addBranchCode(Text value) {
return addProperty(CoreConstants.PROPERTY_BRANCH_CODE, value);
}
@Override
public GardenStore.Builder addBranchCode(String value) {
return addProperty(CoreConstants.PROPERTY_BRANCH_CODE, Text.of(value));
}
@Override
public GardenStore.Builder addBranchOf(Organization value) {
return addProperty(CoreConstants.PROPERTY_BRANCH_OF, value);
}
@Override
public GardenStore.Builder addBranchOf(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_BRANCH_OF, value.build());
}
@Override
public GardenStore.Builder addBranchOf(String value) {
return addProperty(CoreConstants.PROPERTY_BRANCH_OF, Text.of(value));
}
@Override
public GardenStore.Builder addBrand(Brand value) {
return addProperty(CoreConstants.PROPERTY_BRAND, value);
}
@Override
public GardenStore.Builder addBrand(Brand.Builder value) {
return addProperty(CoreConstants.PROPERTY_BRAND, value.build());
}
@Override
public GardenStore.Builder addBrand(Organization value) {
return addProperty(CoreConstants.PROPERTY_BRAND, value);
}
@Override
public GardenStore.Builder addBrand(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_BRAND, value.build());
}
@Override
public GardenStore.Builder addBrand(String value) {
return addProperty(CoreConstants.PROPERTY_BRAND, Text.of(value));
}
@Override
public GardenStore.Builder addContactPoint(ContactPoint value) {
return addProperty(CoreConstants.PROPERTY_CONTACT_POINT, value);
}
@Override
public GardenStore.Builder addContactPoint(ContactPoint.Builder value) {
return addProperty(CoreConstants.PROPERTY_CONTACT_POINT, value.build());
}
@Override
public GardenStore.Builder addContactPoint(String value) {
return addProperty(CoreConstants.PROPERTY_CONTACT_POINT, Text.of(value));
}
@Override
public GardenStore.Builder addContactPoints(ContactPoint value) {
return addProperty(CoreConstants.PROPERTY_CONTACT_POINTS, value);
}
@Override
public GardenStore.Builder addContactPoints(ContactPoint.Builder value) {
return addProperty(CoreConstants.PROPERTY_CONTACT_POINTS, value.build());
}
@Override
public GardenStore.Builder addContactPoints(String value) {
return addProperty(CoreConstants.PROPERTY_CONTACT_POINTS, Text.of(value));
}
@Override
public GardenStore.Builder addContainedIn(Place value) {
return addProperty(CoreConstants.PROPERTY_CONTAINED_IN, value);
}
@Override
public GardenStore.Builder addContainedIn(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_CONTAINED_IN, value.build());
}
@Override
public GardenStore.Builder addContainedIn(String value) {
return addProperty(CoreConstants.PROPERTY_CONTAINED_IN, Text.of(value));
}
@Override
public GardenStore.Builder addContainedInPlace(Place value) {
return addProperty(CoreConstants.PROPERTY_CONTAINED_IN_PLACE, value);
}
@Override
public GardenStore.Builder addContainedInPlace(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_CONTAINED_IN_PLACE, value.build());
}
@Override
public GardenStore.Builder addContainedInPlace(String value) {
return addProperty(CoreConstants.PROPERTY_CONTAINED_IN_PLACE, Text.of(value));
}
@Override
public GardenStore.Builder addContainsPlace(Place value) {
return addProperty(CoreConstants.PROPERTY_CONTAINS_PLACE, value);
}
@Override
public GardenStore.Builder addContainsPlace(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_CONTAINS_PLACE, value.build());
}
@Override
public GardenStore.Builder addContainsPlace(String value) {
return addProperty(CoreConstants.PROPERTY_CONTAINS_PLACE, Text.of(value));
}
@Override
public GardenStore.Builder addCurrenciesAccepted(Text value) {
return addProperty(CoreConstants.PROPERTY_CURRENCIES_ACCEPTED, value);
}
@Override
public GardenStore.Builder addCurrenciesAccepted(String value) {
return addProperty(CoreConstants.PROPERTY_CURRENCIES_ACCEPTED, Text.of(value));
}
@Override
public GardenStore.Builder addDepartment(Organization value) {
return addProperty(CoreConstants.PROPERTY_DEPARTMENT, value);
}
@Override
public GardenStore.Builder addDepartment(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_DEPARTMENT, value.build());
}
@Override
public GardenStore.Builder addDepartment(String value) {
return addProperty(CoreConstants.PROPERTY_DEPARTMENT, Text.of(value));
}
@Override
public GardenStore.Builder addDescription(Text value) {
return addProperty(CoreConstants.PROPERTY_DESCRIPTION, value);
}
@Override
public GardenStore.Builder addDescription(String value) {
return addProperty(CoreConstants.PROPERTY_DESCRIPTION, Text.of(value));
}
@Override
public GardenStore.Builder addDissolutionDate(Date value) {
return addProperty(CoreConstants.PROPERTY_DISSOLUTION_DATE, value);
}
@Override
public GardenStore.Builder addDissolutionDate(String value) {
return addProperty(CoreConstants.PROPERTY_DISSOLUTION_DATE, Text.of(value));
}
@Override
public GardenStore.Builder addDuns(Text value) {
return addProperty(CoreConstants.PROPERTY_DUNS, value);
}
@Override
public GardenStore.Builder addDuns(String value) {
return addProperty(CoreConstants.PROPERTY_DUNS, Text.of(value));
}
@Override
public GardenStore.Builder addEmail(Text value) {
return addProperty(CoreConstants.PROPERTY_EMAIL, value);
}
@Override
public GardenStore.Builder addEmail(String value) {
return addProperty(CoreConstants.PROPERTY_EMAIL, Text.of(value));
}
@Override
public GardenStore.Builder addEmployee(Person value) {
return addProperty(CoreConstants.PROPERTY_EMPLOYEE, value);
}
@Override
public GardenStore.Builder addEmployee(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_EMPLOYEE, value.build());
}
@Override
public GardenStore.Builder addEmployee(String value) {
return addProperty(CoreConstants.PROPERTY_EMPLOYEE, Text.of(value));
}
@Override
public GardenStore.Builder addEmployees(Person value) {
return addProperty(CoreConstants.PROPERTY_EMPLOYEES, value);
}
@Override
public GardenStore.Builder addEmployees(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_EMPLOYEES, value.build());
}
@Override
public GardenStore.Builder addEmployees(String value) {
return addProperty(CoreConstants.PROPERTY_EMPLOYEES, Text.of(value));
}
@Override
public GardenStore.Builder addEvent(Event value) {
return addProperty(CoreConstants.PROPERTY_EVENT, value);
}
@Override
public GardenStore.Builder addEvent(Event.Builder value) {
return addProperty(CoreConstants.PROPERTY_EVENT, value.build());
}
@Override
public GardenStore.Builder addEvent(String value) {
return addProperty(CoreConstants.PROPERTY_EVENT, Text.of(value));
}
@Override
public GardenStore.Builder addEvents(Event value) {
return addProperty(CoreConstants.PROPERTY_EVENTS, value);
}
@Override
public GardenStore.Builder addEvents(Event.Builder value) {
return addProperty(CoreConstants.PROPERTY_EVENTS, value.build());
}
@Override
public GardenStore.Builder addEvents(String value) {
return addProperty(CoreConstants.PROPERTY_EVENTS, Text.of(value));
}
@Override
public GardenStore.Builder addFaxNumber(Text value) {
return addProperty(CoreConstants.PROPERTY_FAX_NUMBER, value);
}
@Override
public GardenStore.Builder addFaxNumber(String value) {
return addProperty(CoreConstants.PROPERTY_FAX_NUMBER, Text.of(value));
}
@Override
public GardenStore.Builder addFounder(Person value) {
return addProperty(CoreConstants.PROPERTY_FOUNDER, value);
}
@Override
public GardenStore.Builder addFounder(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_FOUNDER, value.build());
}
@Override
public GardenStore.Builder addFounder(String value) {
return addProperty(CoreConstants.PROPERTY_FOUNDER, Text.of(value));
}
@Override
public GardenStore.Builder addFounders(Person value) {
return addProperty(CoreConstants.PROPERTY_FOUNDERS, value);
}
@Override
public GardenStore.Builder addFounders(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_FOUNDERS, value.build());
}
@Override
public GardenStore.Builder addFounders(String value) {
return addProperty(CoreConstants.PROPERTY_FOUNDERS, Text.of(value));
}
@Override
public GardenStore.Builder addFoundingDate(Date value) {
return addProperty(CoreConstants.PROPERTY_FOUNDING_DATE, value);
}
@Override
public GardenStore.Builder addFoundingDate(String value) {
return addProperty(CoreConstants.PROPERTY_FOUNDING_DATE, Text.of(value));
}
@Override
public GardenStore.Builder addFoundingLocation(Place value) {
return addProperty(CoreConstants.PROPERTY_FOUNDING_LOCATION, value);
}
@Override
public GardenStore.Builder addFoundingLocation(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_FOUNDING_LOCATION, value.build());
}
@Override
public GardenStore.Builder addFoundingLocation(String value) {
return addProperty(CoreConstants.PROPERTY_FOUNDING_LOCATION, Text.of(value));
}
@Override
public GardenStore.Builder addGeo(GeoCoordinates value) {
return addProperty(CoreConstants.PROPERTY_GEO, value);
}
@Override
public GardenStore.Builder addGeo(GeoCoordinates.Builder value) {
return addProperty(CoreConstants.PROPERTY_GEO, value.build());
}
@Override
public GardenStore.Builder addGeo(GeoShape value) {
return addProperty(CoreConstants.PROPERTY_GEO, value);
}
@Override
public GardenStore.Builder addGeo(GeoShape.Builder value) {
return addProperty(CoreConstants.PROPERTY_GEO, value.build());
}
@Override
public GardenStore.Builder addGeo(String value) {
return addProperty(CoreConstants.PROPERTY_GEO, Text.of(value));
}
@Override
public GardenStore.Builder addGlobalLocationNumber(Text value) {
return addProperty(CoreConstants.PROPERTY_GLOBAL_LOCATION_NUMBER, value);
}
@Override
public GardenStore.Builder addGlobalLocationNumber(String value) {
return addProperty(CoreConstants.PROPERTY_GLOBAL_LOCATION_NUMBER, Text.of(value));
}
@Override
public GardenStore.Builder addHasMap(Map value) {
return addProperty(CoreConstants.PROPERTY_HAS_MAP, value);
}
@Override
public GardenStore.Builder addHasMap(Map.Builder value) {
return addProperty(CoreConstants.PROPERTY_HAS_MAP, value.build());
}
@Override
public GardenStore.Builder addHasMap(URL value) {
return addProperty(CoreConstants.PROPERTY_HAS_MAP, value);
}
@Override
public GardenStore.Builder addHasMap(String value) {
return addProperty(CoreConstants.PROPERTY_HAS_MAP, Text.of(value));
}
@Override
public GardenStore.Builder addHasOfferCatalog(OfferCatalog value) {
return addProperty(CoreConstants.PROPERTY_HAS_OFFER_CATALOG, value);
}
@Override
public GardenStore.Builder addHasOfferCatalog(OfferCatalog.Builder value) {
return addProperty(CoreConstants.PROPERTY_HAS_OFFER_CATALOG, value.build());
}
@Override
public GardenStore.Builder addHasOfferCatalog(String value) {
return addProperty(CoreConstants.PROPERTY_HAS_OFFER_CATALOG, Text.of(value));
}
@Override
public GardenStore.Builder addHasPOS(Place value) {
return addProperty(CoreConstants.PROPERTY_HAS_POS, value);
}
@Override
public GardenStore.Builder addHasPOS(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_HAS_POS, value.build());
}
@Override
public GardenStore.Builder addHasPOS(String value) {
return addProperty(CoreConstants.PROPERTY_HAS_POS, Text.of(value));
}
@Override
public GardenStore.Builder addImage(ImageObject value) {
return addProperty(CoreConstants.PROPERTY_IMAGE, value);
}
@Override
public GardenStore.Builder addImage(ImageObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_IMAGE, value.build());
}
@Override
public GardenStore.Builder addImage(URL value) {
return addProperty(CoreConstants.PROPERTY_IMAGE, value);
}
@Override
public GardenStore.Builder addImage(String value) {
return addProperty(CoreConstants.PROPERTY_IMAGE, Text.of(value));
}
@Override
public GardenStore.Builder addIsicV4(Text value) {
return addProperty(CoreConstants.PROPERTY_ISIC_V4, value);
}
@Override
public GardenStore.Builder addIsicV4(String value) {
return addProperty(CoreConstants.PROPERTY_ISIC_V4, Text.of(value));
}
@Override
public GardenStore.Builder addLegalName(Text value) {
return addProperty(CoreConstants.PROPERTY_LEGAL_NAME, value);
}
@Override
public GardenStore.Builder addLegalName(String value) {
return addProperty(CoreConstants.PROPERTY_LEGAL_NAME, Text.of(value));
}
@Override
public GardenStore.Builder addLocation(Place value) {
return addProperty(CoreConstants.PROPERTY_LOCATION, value);
}
@Override
public GardenStore.Builder addLocation(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_LOCATION, value.build());
}
@Override
public GardenStore.Builder addLocation(PostalAddress value) {
return addProperty(CoreConstants.PROPERTY_LOCATION, value);
}
@Override
public GardenStore.Builder addLocation(PostalAddress.Builder value) {
return addProperty(CoreConstants.PROPERTY_LOCATION, value.build());
}
@Override
public GardenStore.Builder addLocation(Text value) {
return addProperty(CoreConstants.PROPERTY_LOCATION, value);
}
@Override
public GardenStore.Builder addLocation(String value) {
return addProperty(CoreConstants.PROPERTY_LOCATION, Text.of(value));
}
@Override
public GardenStore.Builder addLogo(ImageObject value) {
return addProperty(CoreConstants.PROPERTY_LOGO, value);
}
@Override
public GardenStore.Builder addLogo(ImageObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_LOGO, value.build());
}
@Override
public GardenStore.Builder addLogo(URL value) {
return addProperty(CoreConstants.PROPERTY_LOGO, value);
}
@Override
public GardenStore.Builder addLogo(String value) {
return addProperty(CoreConstants.PROPERTY_LOGO, Text.of(value));
}
@Override
public GardenStore.Builder addMainEntityOfPage(CreativeWork value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value);
}
@Override
public GardenStore.Builder addMainEntityOfPage(CreativeWork.Builder value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value.build());
}
@Override
public GardenStore.Builder addMainEntityOfPage(URL value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value);
}
@Override
public GardenStore.Builder addMainEntityOfPage(String value) {
return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, Text.of(value));
}
@Override
public GardenStore.Builder addMakesOffer(Offer value) {
return addProperty(CoreConstants.PROPERTY_MAKES_OFFER, value);
}
@Override
public GardenStore.Builder addMakesOffer(Offer.Builder value) {
return addProperty(CoreConstants.PROPERTY_MAKES_OFFER, value.build());
}
@Override
public GardenStore.Builder addMakesOffer(String value) {
return addProperty(CoreConstants.PROPERTY_MAKES_OFFER, Text.of(value));
}
@Override
public GardenStore.Builder addMap(URL value) {
return addProperty(CoreConstants.PROPERTY_MAP, value);
}
@Override
public GardenStore.Builder addMap(String value) {
return addProperty(CoreConstants.PROPERTY_MAP, Text.of(value));
}
@Override
public GardenStore.Builder addMaps(URL value) {
return addProperty(CoreConstants.PROPERTY_MAPS, value);
}
@Override
public GardenStore.Builder addMaps(String value) {
return addProperty(CoreConstants.PROPERTY_MAPS, Text.of(value));
}
@Override
public GardenStore.Builder addMember(Organization value) {
return addProperty(CoreConstants.PROPERTY_MEMBER, value);
}
@Override
public GardenStore.Builder addMember(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_MEMBER, value.build());
}
@Override
public GardenStore.Builder addMember(Person value) {
return addProperty(CoreConstants.PROPERTY_MEMBER, value);
}
@Override
public GardenStore.Builder addMember(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_MEMBER, value.build());
}
@Override
public GardenStore.Builder addMember(String value) {
return addProperty(CoreConstants.PROPERTY_MEMBER, Text.of(value));
}
@Override
public GardenStore.Builder addMemberOf(Organization value) {
return addProperty(CoreConstants.PROPERTY_MEMBER_OF, value);
}
@Override
public GardenStore.Builder addMemberOf(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_MEMBER_OF, value.build());
}
@Override
public GardenStore.Builder addMemberOf(ProgramMembership value) {
return addProperty(CoreConstants.PROPERTY_MEMBER_OF, value);
}
@Override
public GardenStore.Builder addMemberOf(ProgramMembership.Builder value) {
return addProperty(CoreConstants.PROPERTY_MEMBER_OF, value.build());
}
@Override
public GardenStore.Builder addMemberOf(String value) {
return addProperty(CoreConstants.PROPERTY_MEMBER_OF, Text.of(value));
}
@Override
public GardenStore.Builder addMembers(Organization value) {
return addProperty(CoreConstants.PROPERTY_MEMBERS, value);
}
@Override
public GardenStore.Builder addMembers(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_MEMBERS, value.build());
}
@Override
public GardenStore.Builder addMembers(Person value) {
return addProperty(CoreConstants.PROPERTY_MEMBERS, value);
}
@Override
public GardenStore.Builder addMembers(Person.Builder value) {
return addProperty(CoreConstants.PROPERTY_MEMBERS, value.build());
}
@Override
public GardenStore.Builder addMembers(String value) {
return addProperty(CoreConstants.PROPERTY_MEMBERS, Text.of(value));
}
@Override
public GardenStore.Builder addNaics(Text value) {
return addProperty(CoreConstants.PROPERTY_NAICS, value);
}
@Override
public GardenStore.Builder addNaics(String value) {
return addProperty(CoreConstants.PROPERTY_NAICS, Text.of(value));
}
@Override
public GardenStore.Builder addName(Text value) {
return addProperty(CoreConstants.PROPERTY_NAME, value);
}
@Override
public GardenStore.Builder addName(String value) {
return addProperty(CoreConstants.PROPERTY_NAME, Text.of(value));
}
@Override
public GardenStore.Builder addNumberOfEmployees(QuantitativeValue value) {
return addProperty(CoreConstants.PROPERTY_NUMBER_OF_EMPLOYEES, value);
}
@Override
public GardenStore.Builder addNumberOfEmployees(QuantitativeValue.Builder value) {
return addProperty(CoreConstants.PROPERTY_NUMBER_OF_EMPLOYEES, value.build());
}
@Override
public GardenStore.Builder addNumberOfEmployees(String value) {
return addProperty(CoreConstants.PROPERTY_NUMBER_OF_EMPLOYEES, Text.of(value));
}
@Override
public GardenStore.Builder addOpeningHours(Text value) {
return addProperty(CoreConstants.PROPERTY_OPENING_HOURS, value);
}
@Override
public GardenStore.Builder addOpeningHours(String value) {
return addProperty(CoreConstants.PROPERTY_OPENING_HOURS, Text.of(value));
}
@Override
public GardenStore.Builder addOpeningHoursSpecification(OpeningHoursSpecification value) {
return addProperty(CoreConstants.PROPERTY_OPENING_HOURS_SPECIFICATION, value);
}
@Override
public GardenStore.Builder addOpeningHoursSpecification(
OpeningHoursSpecification.Builder value) {
return addProperty(CoreConstants.PROPERTY_OPENING_HOURS_SPECIFICATION, value.build());
}
@Override
public GardenStore.Builder addOpeningHoursSpecification(String value) {
return addProperty(CoreConstants.PROPERTY_OPENING_HOURS_SPECIFICATION, Text.of(value));
}
@Override
public GardenStore.Builder addOwns(OwnershipInfo value) {
return addProperty(CoreConstants.PROPERTY_OWNS, value);
}
@Override
public GardenStore.Builder addOwns(OwnershipInfo.Builder value) {
return addProperty(CoreConstants.PROPERTY_OWNS, value.build());
}
@Override
public GardenStore.Builder addOwns(Product value) {
return addProperty(CoreConstants.PROPERTY_OWNS, value);
}
@Override
public GardenStore.Builder addOwns(Product.Builder value) {
return addProperty(CoreConstants.PROPERTY_OWNS, value.build());
}
@Override
public GardenStore.Builder addOwns(String value) {
return addProperty(CoreConstants.PROPERTY_OWNS, Text.of(value));
}
@Override
public GardenStore.Builder addParentOrganization(Organization value) {
return addProperty(CoreConstants.PROPERTY_PARENT_ORGANIZATION, value);
}
@Override
public GardenStore.Builder addParentOrganization(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_PARENT_ORGANIZATION, value.build());
}
@Override
public GardenStore.Builder addParentOrganization(String value) {
return addProperty(CoreConstants.PROPERTY_PARENT_ORGANIZATION, Text.of(value));
}
@Override
public GardenStore.Builder addPaymentAccepted(Text value) {
return addProperty(CoreConstants.PROPERTY_PAYMENT_ACCEPTED, value);
}
@Override
public GardenStore.Builder addPaymentAccepted(String value) {
return addProperty(CoreConstants.PROPERTY_PAYMENT_ACCEPTED, Text.of(value));
}
@Override
public GardenStore.Builder addPhoto(ImageObject value) {
return addProperty(CoreConstants.PROPERTY_PHOTO, value);
}
@Override
public GardenStore.Builder addPhoto(ImageObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_PHOTO, value.build());
}
@Override
public GardenStore.Builder addPhoto(Photograph value) {
return addProperty(CoreConstants.PROPERTY_PHOTO, value);
}
@Override
public GardenStore.Builder addPhoto(Photograph.Builder value) {
return addProperty(CoreConstants.PROPERTY_PHOTO, value.build());
}
@Override
public GardenStore.Builder addPhoto(String value) {
return addProperty(CoreConstants.PROPERTY_PHOTO, Text.of(value));
}
@Override
public GardenStore.Builder addPhotos(ImageObject value) {
return addProperty(CoreConstants.PROPERTY_PHOTOS, value);
}
@Override
public GardenStore.Builder addPhotos(ImageObject.Builder value) {
return addProperty(CoreConstants.PROPERTY_PHOTOS, value.build());
}
@Override
public GardenStore.Builder addPhotos(Photograph value) {
return addProperty(CoreConstants.PROPERTY_PHOTOS, value);
}
@Override
public GardenStore.Builder addPhotos(Photograph.Builder value) {
return addProperty(CoreConstants.PROPERTY_PHOTOS, value.build());
}
@Override
public GardenStore.Builder addPhotos(String value) {
return addProperty(CoreConstants.PROPERTY_PHOTOS, Text.of(value));
}
@Override
public GardenStore.Builder addPotentialAction(Action value) {
return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value);
}
@Override
public GardenStore.Builder addPotentialAction(Action.Builder value) {
return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value.build());
}
@Override
public GardenStore.Builder addPotentialAction(String value) {
return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, Text.of(value));
}
@Override
public GardenStore.Builder addPriceRange(Text value) {
return addProperty(CoreConstants.PROPERTY_PRICE_RANGE, value);
}
@Override
public GardenStore.Builder addPriceRange(String value) {
return addProperty(CoreConstants.PROPERTY_PRICE_RANGE, Text.of(value));
}
@Override
public GardenStore.Builder addReview(Review value) {
return addProperty(CoreConstants.PROPERTY_REVIEW, value);
}
@Override
public GardenStore.Builder addReview(Review.Builder value) {
return addProperty(CoreConstants.PROPERTY_REVIEW, value.build());
}
@Override
public GardenStore.Builder addReview(String value) {
return addProperty(CoreConstants.PROPERTY_REVIEW, Text.of(value));
}
@Override
public GardenStore.Builder addReviews(Review value) {
return addProperty(CoreConstants.PROPERTY_REVIEWS, value);
}
@Override
public GardenStore.Builder addReviews(Review.Builder value) {
return addProperty(CoreConstants.PROPERTY_REVIEWS, value.build());
}
@Override
public GardenStore.Builder addReviews(String value) {
return addProperty(CoreConstants.PROPERTY_REVIEWS, Text.of(value));
}
@Override
public GardenStore.Builder addSameAs(URL value) {
return addProperty(CoreConstants.PROPERTY_SAME_AS, value);
}
@Override
public GardenStore.Builder addSameAs(String value) {
return addProperty(CoreConstants.PROPERTY_SAME_AS, Text.of(value));
}
@Override
public GardenStore.Builder addSeeks(Demand value) {
return addProperty(CoreConstants.PROPERTY_SEEKS, value);
}
@Override
public GardenStore.Builder addSeeks(Demand.Builder value) {
return addProperty(CoreConstants.PROPERTY_SEEKS, value.build());
}
@Override
public GardenStore.Builder addSeeks(String value) {
return addProperty(CoreConstants.PROPERTY_SEEKS, Text.of(value));
}
@Override
public GardenStore.Builder addServiceArea(AdministrativeArea value) {
return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value);
}
@Override
public GardenStore.Builder addServiceArea(AdministrativeArea.Builder value) {
return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value.build());
}
@Override
public GardenStore.Builder addServiceArea(GeoShape value) {
return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value);
}
@Override
public GardenStore.Builder addServiceArea(GeoShape.Builder value) {
return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value.build());
}
@Override
public GardenStore.Builder addServiceArea(Place value) {
return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value);
}
@Override
public GardenStore.Builder addServiceArea(Place.Builder value) {
return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value.build());
}
@Override
public GardenStore.Builder addServiceArea(String value) {
return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, Text.of(value));
}
@Override
public GardenStore.Builder addSubOrganization(Organization value) {
return addProperty(CoreConstants.PROPERTY_SUB_ORGANIZATION, value);
}
@Override
public GardenStore.Builder addSubOrganization(Organization.Builder value) {
return addProperty(CoreConstants.PROPERTY_SUB_ORGANIZATION, value.build());
}
@Override
public GardenStore.Builder addSubOrganization(String value) {
return addProperty(CoreConstants.PROPERTY_SUB_ORGANIZATION, Text.of(value));
}
@Override
public GardenStore.Builder addTaxID(Text value) {
return addProperty(CoreConstants.PROPERTY_TAX_ID, value);
}
@Override
public GardenStore.Builder addTaxID(String value) {
return addProperty(CoreConstants.PROPERTY_TAX_ID, Text.of(value));
}
@Override
public GardenStore.Builder addTelephone(Text value) {
return addProperty(CoreConstants.PROPERTY_TELEPHONE, value);
}
@Override
public GardenStore.Builder addTelephone(String value) {
return addProperty(CoreConstants.PROPERTY_TELEPHONE, Text.of(value));
}
@Override
public GardenStore.Builder addUrl(URL value) {
return addProperty(CoreConstants.PROPERTY_URL, value);
}
@Override
public GardenStore.Builder addUrl(String value) {
return addProperty(CoreConstants.PROPERTY_URL, Text.of(value));
}
@Override
public GardenStore.Builder addVatID(Text value) {
return addProperty(CoreConstants.PROPERTY_VAT_ID, value);
}
@Override
public GardenStore.Builder addVatID(String value) {
return addProperty(CoreConstants.PROPERTY_VAT_ID, Text.of(value));
}
@Override
public GardenStore.Builder addDetailedDescription(Article value) {
return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value);
}
@Override
public GardenStore.Builder addDetailedDescription(Article.Builder value) {
return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value.build());
}
@Override
public GardenStore.Builder addDetailedDescription(String value) {
return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, Text.of(value));
}
@Override
public GardenStore.Builder addPopularityScore(PopularityScoreSpecification value) {
return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value);
}
@Override
public GardenStore.Builder addPopularityScore(PopularityScoreSpecification.Builder value) {
return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value.build());
}
@Override
public GardenStore.Builder addPopularityScore(String value) {
return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, Text.of(value));
}
@Override
public GardenStore build() {
return new GardenStoreImpl(properties, reverseMap);
}
}
public GardenStoreImpl(
Multimap<String, ValueType> properties, Multimap<String, Thing> reverseMap) {
super(properties, reverseMap);
}
@Override
public String getFullTypeName() {
return CoreConstants.TYPE_GARDEN_STORE;
}
@Override
public boolean includesProperty(String property) {
return PROPERTY_SET.contains(CoreConstants.NAMESPACE + property)
|| PROPERTY_SET.contains(GoogConstants.NAMESPACE + property)
|| PROPERTY_SET.contains(property);
}
}
| |
/*
*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*
*/
package org.elasticsearch.xpack.core.security.authz.privilege;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesAction;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotAction;
import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsAction;
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusAction;
import org.elasticsearch.action.admin.cluster.state.ClusterStateAction;
import org.elasticsearch.common.Strings;
import org.elasticsearch.xpack.core.ilm.action.GetLifecycleAction;
import org.elasticsearch.xpack.core.ilm.action.GetStatusAction;
import org.elasticsearch.xpack.core.ilm.action.StartILMAction;
import org.elasticsearch.xpack.core.ilm.action.StopILMAction;
import org.elasticsearch.xpack.core.security.action.DelegatePkiAuthenticationAction;
import org.elasticsearch.xpack.core.security.action.GrantApiKeyAction;
import org.elasticsearch.xpack.core.security.action.token.InvalidateTokenAction;
import org.elasticsearch.xpack.core.security.action.token.RefreshTokenAction;
import org.elasticsearch.xpack.core.security.action.user.HasPrivilegesAction;
import org.elasticsearch.xpack.core.slm.action.GetSnapshotLifecycleAction;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Translates cluster privilege names into concrete implementations
*/
public class ClusterPrivilegeResolver {
private static final Logger logger = LogManager.getLogger(ClusterPrivilegeResolver.class);
// shared automatons
private static final Set<String> ALL_SECURITY_PATTERN = Set.of("cluster:admin/xpack/security/*");
private static final Set<String> MANAGE_SAML_PATTERN = Set.of("cluster:admin/xpack/security/saml/*",
InvalidateTokenAction.NAME, RefreshTokenAction.NAME);
private static final Set<String> MANAGE_OIDC_PATTERN = Set.of("cluster:admin/xpack/security/oidc/*");
private static final Set<String> MANAGE_TOKEN_PATTERN = Set.of("cluster:admin/xpack/security/token/*");
private static final Set<String> MANAGE_API_KEY_PATTERN = Set.of("cluster:admin/xpack/security/api_key/*");
private static final Set<String> GRANT_API_KEY_PATTERN = Set.of(GrantApiKeyAction.NAME + "*");
private static final Set<String> MONITOR_PATTERN = Set.of("cluster:monitor/*");
private static final Set<String> MONITOR_ML_PATTERN = Set.of("cluster:monitor/xpack/ml/*");
private static final Set<String> MONITOR_TRANSFORM_PATTERN = Set.of("cluster:monitor/data_frame/*", "cluster:monitor/transform/*");
private static final Set<String> MONITOR_WATCHER_PATTERN = Set.of("cluster:monitor/xpack/watcher/*");
private static final Set<String> MONITOR_ROLLUP_PATTERN = Set.of("cluster:monitor/xpack/rollup/*");
private static final Set<String> ALL_CLUSTER_PATTERN = Set.of("cluster:*", "indices:admin/template/*", "indices:admin/index_template/*",
"indices:admin/data_stream/*");
private static final Set<String> MANAGE_ML_PATTERN = Set.of("cluster:admin/xpack/ml/*", "cluster:monitor/xpack/ml/*");
private static final Set<String> MANAGE_TRANSFORM_PATTERN = Set.of("cluster:admin/data_frame/*", "cluster:monitor/data_frame/*",
"cluster:monitor/transform/*", "cluster:admin/transform/*");
private static final Set<String> MANAGE_WATCHER_PATTERN = Set.of("cluster:admin/xpack/watcher/*", "cluster:monitor/xpack/watcher/*");
private static final Set<String> TRANSPORT_CLIENT_PATTERN = Set.of("cluster:monitor/nodes/liveness", "cluster:monitor/state");
private static final Set<String> MANAGE_IDX_TEMPLATE_PATTERN = Set.of("indices:admin/template/*", "indices:admin/index_template/*",
"cluster:admin/component_template/*");
private static final Set<String> MANAGE_INGEST_PIPELINE_PATTERN = Set.of("cluster:admin/ingest/pipeline/*");
private static final Set<String> MANAGE_ROLLUP_PATTERN = Set.of("cluster:admin/xpack/rollup/*", "cluster:monitor/xpack/rollup/*");
private static final Set<String> MANAGE_CCR_PATTERN =
Set.of("cluster:admin/xpack/ccr/*", ClusterStateAction.NAME, HasPrivilegesAction.NAME);
private static final Set<String> CREATE_SNAPSHOT_PATTERN = Set.of(CreateSnapshotAction.NAME, SnapshotsStatusAction.NAME + "*",
GetSnapshotsAction.NAME, SnapshotsStatusAction.NAME, GetRepositoriesAction.NAME);
private static final Set<String> MONITOR_SNAPSHOT_PATTERN = Set.of(SnapshotsStatusAction.NAME + "*", GetSnapshotsAction.NAME,
SnapshotsStatusAction.NAME, GetRepositoriesAction.NAME);
private static final Set<String> READ_CCR_PATTERN = Set.of(ClusterStateAction.NAME, HasPrivilegesAction.NAME);
private static final Set<String> MANAGE_ILM_PATTERN = Set.of("cluster:admin/ilm/*");
private static final Set<String> READ_ILM_PATTERN = Set.of(GetLifecycleAction.NAME, GetStatusAction.NAME);
private static final Set<String> MANAGE_SLM_PATTERN =
Set.of("cluster:admin/slm/*", StartILMAction.NAME, StopILMAction.NAME, GetStatusAction.NAME);
private static final Set<String> READ_SLM_PATTERN = Set.of(GetSnapshotLifecycleAction.NAME, GetStatusAction.NAME);
private static final Set<String> MANAGE_ENRICH_AUTOMATON = Set.of("cluster:admin/xpack/enrich/*");
public static final NamedClusterPrivilege NONE = new ActionClusterPrivilege("none", Set.of(), Set.of());
public static final NamedClusterPrivilege ALL = new ActionClusterPrivilege("all", ALL_CLUSTER_PATTERN);
public static final NamedClusterPrivilege MONITOR = new ActionClusterPrivilege("monitor", MONITOR_PATTERN);
public static final NamedClusterPrivilege MONITOR_ML = new ActionClusterPrivilege("monitor_ml", MONITOR_ML_PATTERN);
public static final NamedClusterPrivilege MONITOR_TRANSFORM_DEPRECATED =
new ActionClusterPrivilege("monitor_data_frame_transforms", MONITOR_TRANSFORM_PATTERN);
public static final NamedClusterPrivilege MONITOR_TRANSFORM =
new ActionClusterPrivilege("monitor_transform", MONITOR_TRANSFORM_PATTERN);
public static final NamedClusterPrivilege MONITOR_WATCHER = new ActionClusterPrivilege("monitor_watcher", MONITOR_WATCHER_PATTERN);
public static final NamedClusterPrivilege MONITOR_ROLLUP = new ActionClusterPrivilege("monitor_rollup", MONITOR_ROLLUP_PATTERN);
public static final NamedClusterPrivilege MANAGE = new ActionClusterPrivilege("manage", ALL_CLUSTER_PATTERN, ALL_SECURITY_PATTERN);
public static final NamedClusterPrivilege MANAGE_ML = new ActionClusterPrivilege("manage_ml", MANAGE_ML_PATTERN);
public static final NamedClusterPrivilege MANAGE_TRANSFORM_DEPRECATED =
new ActionClusterPrivilege("manage_data_frame_transforms", MANAGE_TRANSFORM_PATTERN);
public static final NamedClusterPrivilege MANAGE_TRANSFORM =
new ActionClusterPrivilege("manage_transform", MANAGE_TRANSFORM_PATTERN);
public static final NamedClusterPrivilege MANAGE_TOKEN = new ActionClusterPrivilege("manage_token", MANAGE_TOKEN_PATTERN);
public static final NamedClusterPrivilege MANAGE_WATCHER = new ActionClusterPrivilege("manage_watcher", MANAGE_WATCHER_PATTERN);
public static final NamedClusterPrivilege MANAGE_ROLLUP = new ActionClusterPrivilege("manage_rollup", MANAGE_ROLLUP_PATTERN);
public static final NamedClusterPrivilege MANAGE_IDX_TEMPLATES =
new ActionClusterPrivilege("manage_index_templates", MANAGE_IDX_TEMPLATE_PATTERN);
public static final NamedClusterPrivilege MANAGE_INGEST_PIPELINES =
new ActionClusterPrivilege("manage_ingest_pipelines", MANAGE_INGEST_PIPELINE_PATTERN);
public static final NamedClusterPrivilege TRANSPORT_CLIENT = new ActionClusterPrivilege("transport_client",
TRANSPORT_CLIENT_PATTERN);
public static final NamedClusterPrivilege MANAGE_SECURITY = new ActionClusterPrivilege("manage_security", ALL_SECURITY_PATTERN,
Set.of(DelegatePkiAuthenticationAction.NAME));
public static final NamedClusterPrivilege MANAGE_SAML = new ActionClusterPrivilege("manage_saml", MANAGE_SAML_PATTERN);
public static final NamedClusterPrivilege MANAGE_OIDC = new ActionClusterPrivilege("manage_oidc", MANAGE_OIDC_PATTERN);
public static final NamedClusterPrivilege MANAGE_API_KEY = new ActionClusterPrivilege("manage_api_key", MANAGE_API_KEY_PATTERN);
public static final NamedClusterPrivilege GRANT_API_KEY = new ActionClusterPrivilege("grant_api_key", GRANT_API_KEY_PATTERN);
public static final NamedClusterPrivilege MANAGE_PIPELINE = new ActionClusterPrivilege("manage_pipeline", Set.of("cluster:admin" +
"/ingest/pipeline/*"));
public static final NamedClusterPrivilege MANAGE_AUTOSCALING = new ActionClusterPrivilege(
"manage_autoscaling",
Set.of("cluster:admin/autoscaling/*")
);
public static final NamedClusterPrivilege MANAGE_CCR = new ActionClusterPrivilege("manage_ccr", MANAGE_CCR_PATTERN);
public static final NamedClusterPrivilege READ_CCR = new ActionClusterPrivilege("read_ccr", READ_CCR_PATTERN);
public static final NamedClusterPrivilege CREATE_SNAPSHOT = new ActionClusterPrivilege("create_snapshot", CREATE_SNAPSHOT_PATTERN);
public static final NamedClusterPrivilege MONITOR_SNAPSHOT = new ActionClusterPrivilege("monitor_snapshot", MONITOR_SNAPSHOT_PATTERN);
public static final NamedClusterPrivilege MANAGE_ILM = new ActionClusterPrivilege("manage_ilm", MANAGE_ILM_PATTERN);
public static final NamedClusterPrivilege READ_ILM = new ActionClusterPrivilege("read_ilm", READ_ILM_PATTERN);
public static final NamedClusterPrivilege MANAGE_SLM = new ActionClusterPrivilege("manage_slm", MANAGE_SLM_PATTERN);
public static final NamedClusterPrivilege READ_SLM = new ActionClusterPrivilege("read_slm", READ_SLM_PATTERN);
public static final NamedClusterPrivilege DELEGATE_PKI = new ActionClusterPrivilege("delegate_pki",
Set.of(DelegatePkiAuthenticationAction.NAME, InvalidateTokenAction.NAME));
public static final NamedClusterPrivilege MANAGE_OWN_API_KEY = ManageOwnApiKeyClusterPrivilege.INSTANCE;
public static final NamedClusterPrivilege MANAGE_ENRICH = new ActionClusterPrivilege("manage_enrich", MANAGE_ENRICH_AUTOMATON);
private static final Map<String, NamedClusterPrivilege> VALUES = Stream.of(
NONE,
ALL,
MONITOR,
MONITOR_ML,
MONITOR_TRANSFORM_DEPRECATED,
MONITOR_TRANSFORM,
MONITOR_WATCHER,
MONITOR_ROLLUP,
MANAGE,
MANAGE_ML,
MANAGE_TRANSFORM_DEPRECATED,
MANAGE_TRANSFORM,
MANAGE_TOKEN,
MANAGE_WATCHER,
MANAGE_IDX_TEMPLATES,
MANAGE_INGEST_PIPELINES,
TRANSPORT_CLIENT,
MANAGE_SECURITY,
MANAGE_SAML,
MANAGE_OIDC,
MANAGE_API_KEY,
GRANT_API_KEY,
MANAGE_PIPELINE,
MANAGE_ROLLUP,
MANAGE_AUTOSCALING,
MANAGE_CCR,
READ_CCR,
CREATE_SNAPSHOT,
MONITOR_SNAPSHOT,
MANAGE_ILM,
READ_ILM,
MANAGE_SLM,
READ_SLM,
DELEGATE_PKI,
MANAGE_OWN_API_KEY,
MANAGE_ENRICH).collect(Collectors.toUnmodifiableMap(NamedClusterPrivilege::name, Function.identity()));
/**
* Resolves a {@link NamedClusterPrivilege} from a given name if it exists.
* If the name is a cluster action, then it converts the name to pattern and creates a {@link ActionClusterPrivilege}
*
* @param name either {@link ClusterPrivilegeResolver#names()} or cluster action {@link #isClusterAction(String)}
* @return instance of {@link NamedClusterPrivilege}
*/
public static NamedClusterPrivilege resolve(String name) {
name = Objects.requireNonNull(name).toLowerCase(Locale.ROOT);
if (isClusterAction(name)) {
return new ActionClusterPrivilege(name, Set.of(actionToPattern(name)));
}
final NamedClusterPrivilege fixedPrivilege = VALUES.get(name);
if (fixedPrivilege != null) {
return fixedPrivilege;
}
String errorMessage = "unknown cluster privilege [" + name + "]. a privilege must be either " +
"one of the predefined cluster privilege names [" +
Strings.collectionToCommaDelimitedString(VALUES.keySet()) + "] or a pattern over one of the available " +
"cluster actions";
logger.debug(errorMessage);
throw new IllegalArgumentException(errorMessage);
}
public static Set<String> names() {
return Collections.unmodifiableSet(VALUES.keySet());
}
public static boolean isClusterAction(String actionName) {
return actionName.startsWith("cluster:") ||
actionName.startsWith("indices:admin/template/") ||
// todo: hack until we implement security of data_streams
actionName.startsWith("indices:admin/data_stream/") ||
actionName.startsWith("indices:admin/index_template/");
}
private static String actionToPattern(String text) {
return text + "*";
}
}
| |
/*
* Copyright (C) 2011 JFrog Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jfrog.hudson.util;
import com.google.common.collect.Lists;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import hudson.FilePath;
import hudson.Util;
import hudson.model.*;
import hudson.slaves.SlaveComputer;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.jfrog.build.api.BuildInfoConfigProperties;
import org.jfrog.build.api.BuildInfoFields;
import org.jfrog.build.api.BuildRetention;
import org.jfrog.build.api.util.NullLog;
import org.jfrog.build.extractor.clientConfiguration.ArtifactoryClientConfiguration;
import org.jfrog.build.extractor.clientConfiguration.ClientProperties;
import org.jfrog.build.extractor.clientConfiguration.IncludeExcludePatterns;
import org.jfrog.hudson.ArtifactoryServer;
import org.jfrog.hudson.DeployerOverrider;
import org.jfrog.hudson.ServerDetails;
import org.jfrog.hudson.action.ActionableHelper;
import org.jfrog.hudson.release.ReleaseAction;
import org.jfrog.hudson.util.plugins.MultiConfigurationUtils;
import org.jfrog.hudson.util.publisher.PublisherContext;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* @author Tomer Cohen
*/
public class ExtractorUtils {
/**
* Flag to indicate whether an external extractor was used, and the work doesn't need to be done from inside
* Jenkins.
*/
public static final String EXTRACTOR_USED = "extractor.used";
private ExtractorUtils() {
// utility class
throw new IllegalAccessError();
}
/**
* Get the VCS revision from the Jenkins build environment. The search will one of "SVN_REVISION", "GIT_COMMIT",
* "P4_CHANGELIST" in the environment.
*
* @param env Th Jenkins build environment.
* @return The vcs revision for supported VCS
*/
public static String getVcsRevision(Map<String, String> env) {
String revision = env.get("SVN_REVISION");
if (StringUtils.isBlank(revision)) {
revision = env.get("GIT_COMMIT");
}
if (StringUtils.isBlank(revision)) {
revision = env.get("P4_CHANGELIST");
}
return revision;
}
/**
* Get the VCS url from the Jenkins build environment. The search will one of "SVN_REVISION", "GIT_COMMIT",
* "P4_CHANGELIST" in the environment.
*
* @param env Th Jenkins build environment.
* @return The vcs url for supported VCS
*/
public static String getVcsUrl(Map<String, String> env) {
String url = env.get("SVN_URL");
if (StringUtils.isBlank(url)) {
url = publicGitUrl(env.get("GIT_URL"));
}
if (StringUtils.isBlank(url)) {
url = env.get("P4PORT");
}
return url;
}
/*
* Git publish the repository credentials in the Url,
* this method will discard it.
*/
private static String publicGitUrl(String gitUrl) {
if (gitUrl != null && gitUrl.contains("https://") && gitUrl.contains("@")) {
StringBuilder sb = new StringBuilder(gitUrl);
int start = sb.indexOf("https://");
int end = sb.indexOf("@") + 1;
sb = sb.replace(start, end, StringUtils.EMPTY);
return "https://" + sb.toString();
}
return gitUrl;
}
/**
* Add build info properties that will be read by an external extractor. All properties are then saved into a {@code
* buildinfo.properties} into a temporary location. The location is then put into an environment variable {@link
* BuildInfoConfigProperties#PROP_PROPS_FILE} for the extractor to read.
*
* @param env A map of the environment variables that are to be persisted into the buildinfo.properties
* file. NOTE: nothing should be added to the env in this method
* @param build The build from which to get build/project related information from (e.g build name and
* build number).
* @param listener
* @param publisherContext A context for publisher settings
* @param resolverContext A context for resolver settings
*/
public static ArtifactoryClientConfiguration addBuilderInfoArguments(Map<String, String> env, AbstractBuild build,
BuildListener listener, PublisherContext publisherContext, ResolverContext resolverContext)
throws IOException, InterruptedException {
ArtifactoryClientConfiguration configuration = new ArtifactoryClientConfiguration(new NullLog());
addBuildRootIfNeeded(build, configuration);
if (publisherContext != null) {
setPublisherInfo(env, build, publisherContext, configuration);
// setProxy(publisherContext.getArtifactoryServer(), configuration);
}
if (resolverContext != null) {
if (publisherContext != null)
setResolverInfo(configuration, build, resolverContext, publisherContext.getDeployerOverrider(), env);
else
setResolverInfo(configuration, build, resolverContext, null, env);
// setProxy(resolverContext.getServer(), configuration);
}
if ((Jenkins.getInstance().getPlugin("jira") != null) && (publisherContext != null) &&
publisherContext.isEnableIssueTrackerIntegration()) {
new IssuesTrackerHelper(build, listener, publisherContext.isAggregateBuildIssues(),
publisherContext.getAggregationBuildStatus()).setIssueTrackerInfo(configuration);
}
IncludesExcludes envVarsPatterns = new IncludesExcludes("", "");
if (publisherContext != null && publisherContext.getEnvVarsPatterns() != null) {
envVarsPatterns = publisherContext.getEnvVarsPatterns();
}
addEnvVars(env, build, configuration, envVarsPatterns);
persistConfiguration(build, configuration, env);
return configuration;
}
private static void setProxy(ArtifactoryServer server, ArtifactoryClientConfiguration configuration) {
// TODO: distinguish between resolving bypass and deployment bypass
if (!server.isBypassProxy() && Jenkins.getInstance().proxy != null) {
configuration.proxy.setHost(Jenkins.getInstance().proxy.name);
configuration.proxy.setPort(Jenkins.getInstance().proxy.port);
configuration.proxy.setUsername(Jenkins.getInstance().proxy.getUserName());
configuration.proxy.setPassword(Jenkins.getInstance().proxy.getPassword());
}
}
private static void setResolverInfo(ArtifactoryClientConfiguration configuration, AbstractBuild build, ResolverContext context,
DeployerOverrider deployerOverrider, Map<String, String> env) {
configuration.setTimeout(context.getServer().getTimeout());
configuration.resolver.setContextUrl(context.getServer().getUrl());
String inputDownloadReleaseKey = context.getServerDetails().getResolveReleaseRepository().getRepoKey();
String inputDownloadSnapshotKey = context.getServerDetails().getResolveSnapshotRepository().getRepoKey();
// These input variables might be a variable that should be replaced with it's value
replaceRepositoryInputForValues(configuration, build, inputDownloadReleaseKey, inputDownloadSnapshotKey, env);
Credentials preferredResolver = CredentialResolver.getPreferredResolver(context.getResolverOverrider(),
deployerOverrider, context.getServer());
if (StringUtils.isNotBlank(preferredResolver.getUsername())) {
configuration.resolver.setUsername(preferredResolver.getUsername());
configuration.resolver.setPassword(preferredResolver.getPassword());
}
}
/*
* If necessary, replace the input for the configured repositories to their values
* under the current environment. We are not allowing for the input or the value to be empty.
*/
private static void replaceRepositoryInputForValues(ArtifactoryClientConfiguration configuration, AbstractBuild build,
String resolverReleaseInput, String resolverSnapshotInput, Map<String, String> env) {
if (StringUtils.isBlank(resolverReleaseInput) || StringUtils.isBlank(resolverSnapshotInput)) {
build.setResult(Result.FAILURE);
throw new IllegalStateException("Input for resolve repositories cannot be empty.");
}
String resolveReleaseRepo = Util.replaceMacro(resolverReleaseInput, env);
String resolveSnapshotRepo = Util.replaceMacro(resolverSnapshotInput, env);
if (StringUtils.isBlank(resolveReleaseRepo) || StringUtils.isBlank(resolveSnapshotRepo)) {
build.setResult(Result.FAILURE);
throw new IllegalStateException("Resolver repository variable cannot be replaces with empty value.");
}
configuration.resolver.setDownloadSnapshotRepoKey(resolveSnapshotRepo);
configuration.resolver.setRepoKey(resolveReleaseRepo);
}
/**
* Set all the parameters relevant for publishing artifacts and build info
*/
private static void setPublisherInfo(Map<String, String> env, AbstractBuild build,
PublisherContext context, ArtifactoryClientConfiguration configuration) {
configuration.setActivateRecorder(Boolean.TRUE);
String buildName = BuildUniqueIdentifierHelper.getBuildName(build);
configuration.info.setBuildName(buildName);
configuration.publisher.addMatrixParam("build.name", buildName);
String buildNumber = BuildUniqueIdentifierHelper.getBuildNumber(build);
configuration.info.setBuildNumber(buildNumber);
configuration.publisher.addMatrixParam("build.number", buildNumber);
Date buildStartDate = build.getTimestamp().getTime();
configuration.info.setBuildStarted(buildStartDate.getTime());
configuration.info.setBuildTimestamp(String.valueOf(build.getStartTimeInMillis()));
configuration.publisher.addMatrixParam("build.timestamp", String.valueOf(build.getStartTimeInMillis()));
String vcsRevision = getVcsRevision(env);
if (StringUtils.isNotBlank(vcsRevision)) {
configuration.info.setVcsRevision(vcsRevision);
configuration.publisher.addMatrixParam(BuildInfoFields.VCS_REVISION, vcsRevision);
}
String vcsUrl = getVcsUrl(env);
if (StringUtils.isNotBlank(vcsUrl)) {
configuration.info.setVcsUrl(vcsUrl);
}
if (StringUtils.isNotBlank(context.getArtifactsPattern())) {
configuration.publisher.setIvyArtifactPattern(context.getArtifactsPattern());
}
if (StringUtils.isNotBlank(context.getIvyPattern())) {
configuration.publisher.setIvyPattern(context.getIvyPattern());
}
configuration.publisher.setM2Compatible(context.isMaven2Compatible());
String buildUrl = ActionableHelper.getBuildUrl(build);
if (StringUtils.isNotBlank(buildUrl)) {
configuration.info.setBuildUrl(buildUrl);
}
String userName = null;
Cause.UpstreamCause parent = ActionableHelper.getUpstreamCause(build);
if (parent != null) {
String parentProject = sanitizeBuildName(parent.getUpstreamProject());
configuration.info.setParentBuildName(parentProject);
configuration.publisher.addMatrixParam(BuildInfoFields.BUILD_PARENT_NAME, parentProject);
String parentBuildNumber = parent.getUpstreamBuild() + "";
configuration.info.setParentBuildNumber(parentBuildNumber);
configuration.publisher.addMatrixParam(BuildInfoFields.BUILD_PARENT_NUMBER, parentBuildNumber);
userName = "auto";
}
userName = ActionableHelper.getUserCausePrincipal(build, userName);
configuration.info.setPrincipal(userName);
configuration.info.setAgentName("Jenkins");
configuration.info.setAgentVersion(build.getHudsonVersion());
ArtifactoryServer artifactoryServer = context.getArtifactoryServer();
Credentials preferredDeployer =
CredentialResolver.getPreferredDeployer(context.getDeployerOverrider(), artifactoryServer);
if (StringUtils.isNotBlank(preferredDeployer.getUsername())) {
configuration.publisher.setUsername(preferredDeployer.getUsername());
configuration.publisher.setPassword(preferredDeployer.getPassword());
}
configuration.setTimeout(artifactoryServer.getTimeout());
configuration.publisher.setContextUrl(artifactoryServer.getUrl());
ServerDetails serverDetails = context.getServerDetails();
if (serverDetails != null) {
String inputRepKey = serverDetails.getDeployReleaseRepositoryKey();
String repoKEy = Util.replaceMacro(inputRepKey, env);
configuration.publisher.setRepoKey(repoKEy);
String inputSnapshotRepKey = serverDetails.getDeploySnapshotRepositoryKey();
String snapshotRepoKey = Util.replaceMacro(inputSnapshotRepKey, env);
configuration.publisher.setSnapshotRepoKey(snapshotRepoKey);
}
configuration.info.licenseControl.setRunChecks(context.isRunChecks());
configuration.info.licenseControl.setIncludePublishedArtifacts(context.isIncludePublishArtifacts());
configuration.info.licenseControl.setAutoDiscover(context.isLicenseAutoDiscovery());
if (context.isRunChecks()) {
if (StringUtils.isNotBlank(context.getViolationRecipients())) {
configuration.info.licenseControl.setViolationRecipients(context.getViolationRecipients());
}
if (StringUtils.isNotBlank(context.getScopes())) {
configuration.info.licenseControl.setScopes(context.getScopes());
}
}
configuration.info.blackDuckProperties.setRunChecks(context.isBlackDuckRunChecks());
configuration.info.blackDuckProperties.setAppName(context.getBlackDuckAppName());
configuration.info.blackDuckProperties.setAppVersion(context.getBlackDuckAppVersion());
configuration.info.blackDuckProperties.setReportRecipients(context.getBlackDuckReportRecipients());
configuration.info.blackDuckProperties.setScopes(context.getBlackDuckScopes());
configuration.info.blackDuckProperties.setIncludePublishedArtifacts(context.isBlackDuckIncludePublishedArtifacts());
configuration.info.blackDuckProperties.setAutoCreateMissingComponentRequests(context.isAutoCreateMissingComponentRequests());
configuration.info.blackDuckProperties.setAutoDiscardStaleComponentRequests(context.isAutoDiscardStaleComponentRequests());
if (context.isDiscardOldBuilds()) {
BuildRetention buildRetention = BuildRetentionFactory.createBuildRetention(build, context.isDiscardBuildArtifacts());
if (buildRetention.getCount() > -1) {
configuration.info.setBuildRetentionCount(buildRetention.getCount());
}
if (buildRetention.getMinimumBuildDate() != null) {
long days = daysBetween(buildRetention.getMinimumBuildDate(), new Date());
configuration.info.setBuildRetentionMinimumDate(String.valueOf(days));
}
configuration.info.setDeleteBuildArtifacts(context.isDiscardBuildArtifacts());
configuration.info.setBuildNumbersNotToDelete(getBuildNumbersNotToBeDeletedAsString(build));
}
configuration.publisher.setPublishArtifacts(context.isDeployArtifacts());
configuration.publisher.setEvenUnstable(context.isEvenIfUnstable());
configuration.publisher.setIvy(context.isDeployIvy());
configuration.publisher.setMaven(context.isDeployMaven());
IncludesExcludes deploymentPatterns = context.getIncludesExcludes();
if (deploymentPatterns != null) {
String includePatterns = deploymentPatterns.getIncludePatterns();
if (StringUtils.isNotBlank(includePatterns)) {
configuration.publisher.setIncludePatterns(includePatterns);
}
String excludePatterns = deploymentPatterns.getExcludePatterns();
if (StringUtils.isNotBlank(excludePatterns)) {
configuration.publisher.setExcludePatterns(excludePatterns);
}
}
ReleaseAction releaseAction = ActionableHelper.getLatestAction(build, ReleaseAction.class);
if (releaseAction != null) {
configuration.info.setReleaseEnabled(true);
String comment = releaseAction.getStagingComment();
if (StringUtils.isNotBlank(comment)) {
configuration.info.setReleaseComment(comment);
}
}
configuration.publisher.setFilterExcludedArtifactsFromBuild(context.isFilterExcludedArtifactsFromBuild());
configuration.publisher.setPublishBuildInfo(!context.isSkipBuildInfoDeploy());
configuration.publisher.setRecordAllDependencies(context.isRecordAllDependencies());
configuration.setIncludeEnvVars(context.isIncludeEnvVars());
IncludesExcludes envVarsPatterns = context.getEnvVarsPatterns();
if (envVarsPatterns != null) {
configuration.setEnvVarsIncludePatterns(envVarsPatterns.getIncludePatterns());
configuration.setEnvVarsExcludePatterns(envVarsPatterns.getExcludePatterns());
}
addMatrixParams(context, configuration.publisher, env);
}
// Naive implementation of the difference in days between two dates
private static long daysBetween(Date date1, Date date2) {
long diff;
if (date2.after(date1)) {
diff = date2.getTime() - date1.getTime();
} else {
diff = date1.getTime() - date2.getTime();
}
return diff / (24 * 60 * 60 * 1000);
}
/**
* Replaces occurrences of '/' with ' :: ' if exist
*/
public static String sanitizeBuildName(String buildName) {
return StringUtils.replace(buildName, "/", " :: ");
}
/**
* Get the list of build numbers that are to be kept forever.
*/
public static List<String> getBuildNumbersNotToBeDeleted(AbstractBuild build) {
List<String> notToDelete = Lists.newArrayList();
List<? extends Run<?, ?>> builds = build.getProject().getBuilds();
for (Run<?, ?> run : builds) {
if (run.isKeepLog()) {
notToDelete.add(String.valueOf(run.getNumber()));
}
}
return notToDelete;
}
private static String getBuildNumbersNotToBeDeletedAsString(AbstractBuild build) {
StringBuilder builder = new StringBuilder();
List<String> notToBeDeleted = getBuildNumbersNotToBeDeleted(build);
for (String notToDelete : notToBeDeleted) {
builder.append(notToDelete).append(",");
}
return builder.toString();
}
public static void addBuildRootIfNeeded(AbstractBuild build, ArtifactoryClientConfiguration configuration)
throws UnsupportedEncodingException {
AbstractBuild<?, ?> rootBuild = BuildUniqueIdentifierHelper.getRootBuild(build);
if (rootBuild != null) {
String identifier = BuildUniqueIdentifierHelper.getUpstreamIdentifier(rootBuild);
configuration.info.setBuildRoot(identifier);
}
}
public static void persistConfiguration(AbstractBuild build, ArtifactoryClientConfiguration configuration,
Map<String, String> env) throws IOException, InterruptedException {
FilePath propertiesFile = build.getWorkspace().createTextTempFile("buildInfo", ".properties", "", false);
configuration.setPropertiesFile(propertiesFile.getRemote());
env.put("BUILDINFO_PROPFILE", propertiesFile.getRemote());
env.put(BuildInfoConfigProperties.PROP_PROPS_FILE, propertiesFile.getRemote());
// Jenkins prefixes env variables with 'env' but we need it clean..
System.setProperty(BuildInfoConfigProperties.PROP_PROPS_FILE, propertiesFile.getRemote());
if (!(Computer.currentComputer() instanceof SlaveComputer)) {
configuration.persistToPropertiesFile();
} else {
try {
Properties properties = new Properties();
properties.putAll(configuration.getAllRootConfig());
properties.putAll(configuration.getAllProperties());
File tempFile = File.createTempFile("buildInfo", ".properties");
FileOutputStream stream = new FileOutputStream(tempFile);
try {
properties.store(stream, "");
} finally {
Closeables.closeQuietly(stream);
}
propertiesFile.copyFrom(tempFile.toURI().toURL());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private static void addMatrixParams(PublisherContext context,
ArtifactoryClientConfiguration.PublisherHandler publisher,
Map<String, String> env) {
String matrixParams = context.getMatrixParams();
if (StringUtils.isBlank(matrixParams)) {
return;
}
String[] keyValuePairs = StringUtils.split(matrixParams, "; ");
if (keyValuePairs == null) {
return;
}
for (String keyValuePair : keyValuePairs) {
String[] split = StringUtils.split(keyValuePair, "=");
if (split.length == 2) {
String value = Util.replaceMacro(split[1], env);
publisher.addMatrixParam(split[0], value);
}
}
}
private static void addEnvVars(Map<String, String> env, AbstractBuild<?, ?> build,
ArtifactoryClientConfiguration configuration, IncludesExcludes envVarsPatterns) {
IncludeExcludePatterns patterns = new IncludeExcludePatterns(envVarsPatterns.getIncludePatterns(),
envVarsPatterns.getExcludePatterns());
// Add only the jenkins specific environment variables
MapDifference<String, String> envDifference = Maps.difference(env, System.getenv());
Map<String, String> filteredEnvDifference = envDifference.entriesOnlyOnLeft();
configuration.info.addBuildVariables(filteredEnvDifference, patterns);
// Add Jenkins build variables
Map<String, String> buildVariables = build.getBuildVariables();
MapDifference<String, String> buildVarDifference = Maps.difference(buildVariables, System.getenv());
Map<String, String> filteredBuildVarDifferences = buildVarDifference.entriesOnlyOnLeft();
configuration.info.addBuildVariables(filteredBuildVarDifferences, patterns);
// Write all the deploy (matrix params) properties.
configuration.fillFromProperties(buildVariables, patterns);
for (Map.Entry<String, String> entry : buildVariables.entrySet()) {
if (entry.getKey().startsWith(ClientProperties.PROP_DEPLOY_PARAM_PROP_PREFIX)) {
configuration.publisher.addMatrixParam(entry.getKey(), entry.getValue());
}
}
MultiConfigurationUtils.addMatrixCombination(build, configuration);
}
}
| |
/*
* Copyright 2000-2013 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.util;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.light.LightElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiSearchScopeUtil;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.HashSet;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Set;
/**
* @author anna
* Date: 05-Oct-2009
*/
public class RefactoringConflictsUtil {
private RefactoringConflictsUtil() { }
public static void analyzeAccessibilityConflicts(@NotNull Set<PsiMember> membersToMove,
@NotNull PsiClass targetClass,
@NotNull MultiMap<PsiElement, String> conflicts,
@Nullable String newVisibility) {
analyzeAccessibilityConflicts(membersToMove, targetClass, conflicts, newVisibility, targetClass, null);
}
public static void analyzeAccessibilityConflicts(@NotNull Set<PsiMember> membersToMove,
@Nullable PsiClass targetClass,
@NotNull MultiMap<PsiElement, String> conflicts,
@Nullable String newVisibility,
@NotNull PsiElement context,
@Nullable Set<PsiMethod> abstractMethods) {
if (VisibilityUtil.ESCALATE_VISIBILITY.equals(newVisibility)) { //Still need to check for access object
newVisibility = PsiModifier.PUBLIC;
}
for (PsiMember member : membersToMove) {
checkUsedElements(member, member, membersToMove, abstractMethods, targetClass, context, conflicts);
checkAccessibilityConflicts(member, newVisibility, targetClass, membersToMove, conflicts);
}
}
public static void checkAccessibilityConflicts(@NotNull PsiMember member,
@PsiModifier.ModifierConstant @Nullable String newVisibility,
@Nullable PsiClass targetClass,
@NotNull Set<? extends PsiMember> membersToMove,
@NotNull MultiMap<PsiElement, String> conflicts) {
PsiModifierList modifierListCopy = member.getModifierList();
if (modifierListCopy != null) {
modifierListCopy = (PsiModifierList)modifierListCopy.copy();
final PsiClass containingClass = member.getContainingClass();
if (containingClass != null && containingClass.isInterface()) {
VisibilityUtil.setVisibility(modifierListCopy, PsiModifier.PUBLIC);
}
}
if (newVisibility != null && modifierListCopy != null) {
try {
VisibilityUtil.setVisibility(modifierListCopy, newVisibility);
}
catch (IncorrectOperationException ignore) { } // do nothing and hope for the best
}
checkAccessibilityConflicts(member, modifierListCopy, targetClass, membersToMove, conflicts);
}
public static void checkAccessibilityConflicts(@NotNull PsiMember member,
@Nullable PsiModifierList modifierListCopy,
@Nullable PsiClass targetClass,
@NotNull Set<? extends PsiMember> membersToMove,
@NotNull MultiMap<PsiElement, String> conflicts) {
for (PsiReference psiReference : ReferencesSearch.search(member)) {
checkAccessibilityConflicts(psiReference, member, modifierListCopy, targetClass, membersToMove, conflicts);
}
}
public static void checkAccessibilityConflicts(@NotNull PsiReference reference,
@NotNull PsiMember member,
@Nullable PsiModifierList modifierListCopy,
@Nullable PsiClass targetClass,
@NotNull Set<? extends PsiMember> membersToMove,
@NotNull MultiMap<PsiElement, String> conflicts) {
JavaPsiFacade manager = JavaPsiFacade.getInstance(member.getProject());
PsiElement ref = reference.getElement();
if (!RefactoringHierarchyUtil.willBeInTargetClass(ref, membersToMove, targetClass, false)) {
// check for target class accessibility
if (targetClass != null && !manager.getResolveHelper().isAccessible(targetClass, targetClass.getModifierList(), ref, null, null)) {
String message = RefactoringBundle.message("0.is.1.and.will.not.be.accessible.from.2.in.the.target.class",
RefactoringUIUtil.getDescription(targetClass, true),
VisibilityUtil.getVisibilityStringToDisplay(targetClass),
RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(ref), true));
message = CommonRefactoringUtil.capitalize(message);
conflicts.putValue(targetClass, message);
}
// check for member accessibility
else if (!manager.getResolveHelper().isAccessible(member, modifierListCopy, ref, targetClass, null)) {
String message = RefactoringBundle.message("0.is.1.and.will.not.be.accessible.from.2.in.the.target.class",
RefactoringUIUtil.getDescription(member, true),
VisibilityUtil.toPresentableText(VisibilityUtil.getVisibilityModifier(modifierListCopy)),
RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(ref), true));
message = CommonRefactoringUtil.capitalize(message);
conflicts.putValue(member, message);
}
}
}
public static void checkUsedElements(PsiMember member,
PsiElement scope,
@NotNull Set<PsiMember> membersToMove,
@Nullable Set<PsiMethod> abstractMethods,
@Nullable PsiClass targetClass,
@NotNull PsiElement context,
MultiMap<PsiElement, String> conflicts) {
final Set<PsiMember> moving = new HashSet<PsiMember>(membersToMove);
if (abstractMethods != null) {
moving.addAll(abstractMethods);
}
if (scope instanceof PsiReferenceExpression) {
PsiReferenceExpression refExpr = (PsiReferenceExpression)scope;
PsiElement refElement = refExpr.resolve();
if (refElement instanceof PsiMember) {
if (!RefactoringHierarchyUtil.willBeInTargetClass(refElement, moving, targetClass, false)) {
PsiExpression qualifier = refExpr.getQualifierExpression();
PsiClass accessClass = (PsiClass)(qualifier != null ? PsiUtil.getAccessObjectClass(qualifier).getElement() : null);
checkAccessibility((PsiMember)refElement, context, accessClass, member, conflicts);
}
}
}
else if (scope instanceof PsiNewExpression) {
final PsiNewExpression newExpression = (PsiNewExpression)scope;
final PsiAnonymousClass anonymousClass = newExpression.getAnonymousClass();
if (anonymousClass != null) {
if (!RefactoringHierarchyUtil.willBeInTargetClass(anonymousClass, moving, targetClass, false)) {
checkAccessibility(anonymousClass, context, anonymousClass, member, conflicts);
}
}
else {
final PsiMethod refElement = newExpression.resolveConstructor();
if (refElement != null) {
if (!RefactoringHierarchyUtil.willBeInTargetClass(refElement, moving, targetClass, false)) {
checkAccessibility(refElement, context, null, member, conflicts);
}
}
}
}
else if (scope instanceof PsiJavaCodeReferenceElement) {
PsiJavaCodeReferenceElement refExpr = (PsiJavaCodeReferenceElement)scope;
PsiElement refElement = refExpr.resolve();
if (refElement instanceof PsiMember) {
if (!RefactoringHierarchyUtil.willBeInTargetClass(refElement, moving, targetClass, false)) {
checkAccessibility((PsiMember)refElement, context, null, member, conflicts);
}
}
}
for (PsiElement child : scope.getChildren()) {
if (child instanceof PsiWhiteSpace || child instanceof PsiComment) continue;
checkUsedElements(member, child, membersToMove, abstractMethods, targetClass, context, conflicts);
}
}
public static void checkAccessibility(PsiMember refMember,
@NotNull PsiElement newContext,
@Nullable PsiClass accessClass,
PsiMember member,
MultiMap<PsiElement, String> conflicts) {
if (!PsiUtil.isAccessible(refMember, newContext, accessClass)) {
String message = RefactoringBundle.message("0.is.1.and.will.not.be.accessible.from.2.in.the.target.class",
RefactoringUIUtil.getDescription(refMember, true),
VisibilityUtil.getVisibilityStringToDisplay(refMember),
RefactoringUIUtil.getDescription(member, false));
message = CommonRefactoringUtil.capitalize(message);
conflicts.putValue(refMember, message);
}
else if (newContext instanceof PsiClass && refMember instanceof PsiField && refMember.getContainingClass() == member.getContainingClass()) {
final PsiField fieldInSubClass = ((PsiClass)newContext).findFieldByName(refMember.getName(), false);
if (fieldInSubClass != null && fieldInSubClass != refMember) {
conflicts.putValue(refMember, CommonRefactoringUtil.capitalize(RefactoringUIUtil.getDescription(fieldInSubClass, true) +
" would hide " + RefactoringUIUtil.getDescription(refMember, true) +
" which is used by moved " + RefactoringUIUtil.getDescription(member, false)));
}
}
}
public static void analyzeModuleConflicts(final Project project,
final Collection<? extends PsiElement> scopes,
final UsageInfo[] usages,
final PsiElement target,
final MultiMap<PsiElement,String> conflicts) {
if (scopes == null) return;
final VirtualFile vFile = PsiUtilCore.getVirtualFile(target);
if (vFile == null) return;
analyzeModuleConflicts(project, scopes, usages, vFile, conflicts);
}
public static void analyzeModuleConflicts(final Project project,
final Collection<? extends PsiElement> scopes,
final UsageInfo[] usages,
final VirtualFile vFile,
final MultiMap<PsiElement, String> conflicts) {
if (scopes == null) return;
for (final PsiElement scope : scopes) {
if (scope instanceof PsiPackage) return;
}
final Module targetModule = ModuleUtil.findModuleForFile(vFile, project);
if (targetModule == null) return;
final GlobalSearchScope resolveScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(targetModule);
final HashSet<PsiElement> reported = new HashSet<PsiElement>();
for (final PsiElement scope : scopes) {
scope.accept(new JavaRecursiveElementVisitor() {
@Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
super.visitReferenceElement(reference);
final PsiElement resolved = reference.resolve();
if (resolved != null &&
!reported.contains(resolved) &&
!CommonRefactoringUtil.isAncestor(resolved, scopes) &&
!PsiSearchScopeUtil.isInScope(resolveScope, resolved) &&
!(resolved instanceof LightElement)) {
final String scopeDescription = RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(reference), true);
final String message = RefactoringBundle.message("0.referenced.in.1.will.not.be.accessible.in.module.2",
RefactoringUIUtil.getDescription(resolved, true),
scopeDescription,
CommonRefactoringUtil.htmlEmphasize(targetModule.getName()));
conflicts.putValue(resolved, CommonRefactoringUtil.capitalize(message));
reported.add(resolved);
}
}
});
}
boolean isInTestSources = ModuleRootManager.getInstance(targetModule).getFileIndex().isInTestSourceContent(vFile);
NextUsage:
for (UsageInfo usage : usages) {
final PsiElement element = usage.getElement();
if (element != null && PsiTreeUtil.getParentOfType(element, PsiImportStatement.class, false) == null) {
for (PsiElement scope : scopes) {
if (PsiTreeUtil.isAncestor(scope, element, false)) continue NextUsage;
}
final GlobalSearchScope resolveScope1 = element.getResolveScope();
if (!resolveScope1.isSearchInModuleContent(targetModule, isInTestSources)) {
final PsiFile usageFile = element.getContainingFile();
PsiElement container;
if (usageFile instanceof PsiJavaFile) {
container = ConflictsUtil.getContainer(element);
}
else {
container = usageFile;
}
final String scopeDescription = RefactoringUIUtil.getDescription(container, true);
final VirtualFile usageVFile = usageFile.getVirtualFile();
if (usageVFile != null) {
Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(usageVFile);
if (module != null) {
final String message;
final PsiElement referencedElement;
if (usage instanceof MoveRenameUsageInfo) {
referencedElement = ((MoveRenameUsageInfo)usage).getReferencedElement();
}
else {
referencedElement = usage.getElement();
}
assert referencedElement != null : usage;
if (module == targetModule && isInTestSources) {
message = RefactoringBundle.message("0.referenced.in.1.will.not.be.accessible.from.production.of.module.2",
RefactoringUIUtil.getDescription(referencedElement, true),
scopeDescription,
CommonRefactoringUtil.htmlEmphasize(module.getName()));
}
else {
message = RefactoringBundle.message("0.referenced.in.1.will.not.be.accessible.from.module.2",
RefactoringUIUtil.getDescription(referencedElement, true),
scopeDescription,
CommonRefactoringUtil.htmlEmphasize(module.getName()));
}
conflicts.putValue(referencedElement, CommonRefactoringUtil.capitalize(message));
}
}
}
}
}
}
}
| |
/*
* 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.openjpa.azure.jdbc;
import java.util.Date;
import org.apache.openjpa.kernel.Filters;
import org.apache.openjpa.kernel.StoreQuery;
import org.apache.openjpa.kernel.exps.QueryExpressions;
import org.apache.openjpa.kernel.exps.Value;
import org.apache.openjpa.lib.rop.ResultObjectProvider;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.util.InternalException;
public class AzureUniqueResultObjectProvider implements ResultObjectProvider {
private static final Localizer _loc = Localizer.forPackage(AzureUniqueResultObjectProvider.class);
private static final String COUNT = "Count";
private static final String MAX = "Max";
private static final String MIN = "AzureMin";
private static final String SUM = "Sum";
protected final ResultObjectProvider[] _rops;
private final StoreQuery _query;
private final QueryExpressions[] _exps;
protected Object _single;
protected boolean _opened;
public AzureUniqueResultObjectProvider(
final ResultObjectProvider[] rops, final StoreQuery query, final QueryExpressions[] exps) {
_rops = rops;
_query = query;
_exps = exps;
}
public boolean absolute(int pos)
throws Exception {
return false;
}
public void close()
throws Exception {
_opened = false;
for (ResultObjectProvider rop : _rops) {
rop.close();
}
}
public Object getResultObject()
throws Exception {
if (!_opened) {
throw new InternalException(_loc.get("not-open"));
}
return _single;
}
public void handleCheckedException(Exception e) {
_rops[0].handleCheckedException(e);
}
@Override
public boolean next()
throws Exception {
if (!_opened) {
open();
}
if (_single != null) {
return false;
}
Value[] values = _exps[0].projections;
Object[] single = new Object[values.length];
for (int i = 0; i < values.length; i++) {
Value v = values[i];
boolean isAggregate = v.isAggregate();
String op = v.getClass().getSimpleName();
for (ResultObjectProvider rop : _rops) {
if (rop.next()) {
Object[] row = (Object[]) rop.getResultObject();
if (isAggregate) {
if (COUNT.equals(op)) {
single[i] = count(single[i], row[i]);
} else if (MAX.equals(op)) {
single[i] = max(single[i], row[i]);
} else if (MIN.equals(op)) {
single[i] = min(single[i], row[i]);
} else if (SUM.equals(op)) {
single[i] = sum(single[i], row[i]);
} else {
throw new UnsupportedOperationException(_loc.get("aggregate-unsupported", op).toString());
}
} else {
single[i] = row[i];
}
single[i] = Filters.convert(single[i], v.getType());
}
}
}
_single = single;
return true;
}
protected Object count(Object current, Object other) {
if (current == null) {
return other;
}
if (other == null) {
return current;
}
return ((Number) current).longValue() + ((Number) other).longValue();
}
protected Object max(Object current, Object other) {
if (current == null) {
return other;
}
if (other == null) {
return current;
}
if (current instanceof Number) {
return Math.max(((Number) current).doubleValue(),
((Number) other).doubleValue());
}
if (current instanceof String) {
return ((String) current).compareTo((String) other) > 0 ? current : other;
}
if (current instanceof Date) {
return ((Date) current).compareTo((Date) other) > 0 ? current : other;
}
if (current instanceof Character) {
return ((Character) current).compareTo((Character) other) > 0 ? current : other;
}
throw new UnsupportedOperationException(_loc.get("aggregate-unsupported-on-type",
"MAX()", (current == null ? other : current).getClass().getName()).toString());
}
protected Object min(Object current, Object other) {
if (current == null) {
return other;
}
if (other == null) {
return current;
}
if (current instanceof Number) {
return Math.min(((Number) current).doubleValue(), ((Number) other).doubleValue());
}
if (current instanceof String) {
return ((String) current).compareTo((String) other) < 0 ? current : other;
}
if (current instanceof Date) {
return ((Date) current).compareTo((Date) other) < 0 ? current : other;
}
if (current instanceof Character) {
return ((Character) current).compareTo((Character) other) < 0 ? current : other;
}
throw new UnsupportedOperationException(_loc.get("aggregate-unsupported-on-type",
"MIN()", (current == null ? other : current).getClass().getName()).toString());
}
protected Object sum(Object current, Object other) {
if (current == null) {
return other;
}
if (other == null) {
return current;
}
if (current instanceof Number) {
return (((Number) current).doubleValue()
+ ((Number) other).doubleValue());
}
throw new UnsupportedOperationException(_loc.get("aggregate-unsupported-on-type",
"SUM()", (current == null ? other : current).getClass().getName()).toString());
}
public void open()
throws Exception {
for (ResultObjectProvider rop : _rops) {
rop.open();
}
_opened = true;
}
public void reset()
throws Exception {
_single = null;
for (ResultObjectProvider rop : _rops) {
rop.reset();
}
}
public int size()
throws Exception {
return 1;
}
public boolean supportsRandomAccess() {
return false;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.service;
import com.google.common.collect.Multimap;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.registry.client.binding.RegistryPathUtils;
import org.apache.hadoop.registry.client.binding.RegistryUtils;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainersRequest;
import org.apache.hadoop.yarn.api.records.*;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.apache.hadoop.yarn.service.api.records.Component;
import org.apache.hadoop.yarn.service.api.records.ComponentState;
import org.apache.hadoop.yarn.service.api.records.Configuration;
import org.apache.hadoop.yarn.service.api.records.Container;
import org.apache.hadoop.yarn.service.api.records.PlacementConstraint;
import org.apache.hadoop.yarn.service.api.records.PlacementPolicy;
import org.apache.hadoop.yarn.service.api.records.PlacementScope;
import org.apache.hadoop.yarn.service.api.records.PlacementType;
import org.apache.hadoop.yarn.service.api.records.Service;
import org.apache.hadoop.yarn.service.api.records.ServiceState;
import org.apache.hadoop.yarn.service.client.ServiceClient;
import org.apache.hadoop.yarn.service.conf.YarnServiceConstants;
import org.apache.hadoop.yarn.service.utils.ServiceApiUtil;
import org.apache.hadoop.yarn.service.utils.SliderFileSystem;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeoutException;
import static org.apache.hadoop.yarn.api.records.YarnApplicationState.FINISHED;
import static org.apache.hadoop.yarn.service.conf.YarnServiceConf.*;
import static org.apache.hadoop.yarn.service.exceptions.LauncherExitCodes.EXIT_COMMAND_ARGUMENT_ERROR;
import static org.apache.hadoop.yarn.service.exceptions.LauncherExitCodes.EXIT_NOT_FOUND;
/**
* End to end tests to test deploying services with MiniYarnCluster and a in-JVM
* ZK testing cluster.
*/
public class TestYarnNativeServices extends ServiceTestUtils {
private static final Logger LOG =
LoggerFactory.getLogger(TestYarnNativeServices.class);
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
@Before
public void setup() throws Exception {
File tmpYarnDir = new File("target", "tmp");
FileUtils.deleteQuietly(tmpYarnDir);
}
@After
public void tearDown() throws IOException {
shutdown();
}
// End-to-end test to use ServiceClient to deploy a service.
// 1. Create a service with 2 components, each of which has 2 containers
// 2. Flex up each component to 3 containers and check the component instance names
// 3. Flex down each component to 1 container and check the component instance names
// 4. Flex up each component to 2 containers and check the component instance names
// 5. Stop the service
// 6. Destroy the service
@Test (timeout = 200000)
public void testCreateFlexStopDestroyService() throws Exception {
setupInternal(NUM_NMS);
ServiceClient client = createClient(getConf());
Service exampleApp = createExampleApplication();
client.actionCreate(exampleApp);
SliderFileSystem fileSystem = new SliderFileSystem(getConf());
Path appDir = fileSystem.buildClusterDirPath(exampleApp.getName());
// check app.json is persisted.
Assert.assertTrue(
getFS().exists(new Path(appDir, exampleApp.getName() + ".json")));
waitForServiceToBeStable(client, exampleApp);
// Flex two components, each from 2 container to 3 containers.
flexComponents(client, exampleApp, 3L);
// wait for flex to be completed, increase from 2 to 3 containers.
waitForServiceToBeStable(client, exampleApp);
// check all instances name for each component are in sequential order.
checkCompInstancesInOrder(client, exampleApp);
// flex down to 1
flexComponents(client, exampleApp, 1L);
waitForServiceToBeStable(client, exampleApp);
checkCompInstancesInOrder(client, exampleApp);
// check component dir and registry are cleaned up.
// flex up again to 2
flexComponents(client, exampleApp, 2L);
waitForServiceToBeStable(client, exampleApp);
checkCompInstancesInOrder(client, exampleApp);
// stop the service
LOG.info("Stop the service");
client.actionStop(exampleApp.getName(), true);
ApplicationReport report = client.getYarnClient()
.getApplicationReport(ApplicationId.fromString(exampleApp.getId()));
// AM unregisters with RM successfully
Assert.assertEquals(FINISHED, report.getYarnApplicationState());
Assert.assertEquals(FinalApplicationStatus.ENDED,
report.getFinalApplicationStatus());
String serviceZKPath = RegistryUtils.servicePath(RegistryUtils
.currentUser(), YarnServiceConstants.APP_TYPE, exampleApp.getName());
Assert.assertFalse("Registry ZK service path still exists after stop",
getCuratorService().zkPathExists(serviceZKPath));
LOG.info("Destroy the service");
// destroy the service and check the app dir is deleted from fs.
Assert.assertEquals(0, client.actionDestroy(exampleApp.getName()));
// check the service dir on hdfs (in this case, local fs) are deleted.
Assert.assertFalse(getFS().exists(appDir));
// check that destroying again does not succeed
Assert.assertEquals(EXIT_NOT_FOUND, client.actionDestroy(exampleApp.getName()));
}
// Save a service without starting it and ensure that stop does not NPE and
// that service can be successfully destroyed
@Test (timeout = 200000)
public void testStopDestroySavedService() throws Exception {
setupInternal(NUM_NMS);
ServiceClient client = createClient(getConf());
Service exampleApp = createExampleApplication();
client.actionBuild(exampleApp);
Assert.assertEquals(EXIT_COMMAND_ARGUMENT_ERROR, client.actionStop(
exampleApp.getName()));
Assert.assertEquals(0, client.actionDestroy(exampleApp.getName()));
}
// Create compa with 2 containers
// Create compb with 2 containers which depends on compa
// Create compc with 2 containers which depends on compb
// Check containers for compa started before containers for compb before
// containers for compc
@Test (timeout = 200000)
public void testComponentStartOrder() throws Exception {
setupInternal(NUM_NMS);
ServiceClient client = createClient(getConf());
Service exampleApp = new Service();
exampleApp.setName("teststartorder");
exampleApp.setVersion("v1");
exampleApp.addComponent(createComponent("compa", 2, "sleep 1000"));
// Let compb depend on compa
Component compb = createComponent("compb", 2, "sleep 1000");
compb.setDependencies(Collections.singletonList("compa"));
exampleApp.addComponent(compb);
// Let compc depend on compb
Component compc = createComponent("compc", 2, "sleep 1000");
compc.setDependencies(Collections.singletonList("compb"));
exampleApp.addComponent(compc);
client.actionCreate(exampleApp);
waitForServiceToBeStable(client, exampleApp);
// check that containers for compa are launched before containers for compb
checkContainerLaunchDependencies(client, exampleApp, "compa", "compb",
"compc");
client.actionStop(exampleApp.getName(), true);
client.actionDestroy(exampleApp.getName());
}
@Test(timeout = 200000)
public void testCreateServiceSameNameDifferentUser() throws Exception {
String sameAppName = "same-name";
String userA = "usera";
String userB = "userb";
setupInternal(NUM_NMS);
ServiceClient client = createClient(getConf());
String origBasePath = getConf().get(YARN_SERVICE_BASE_PATH);
Service userAApp = new Service();
userAApp.setName(sameAppName);
userAApp.setVersion("v1");
userAApp.addComponent(createComponent("comp", 1, "sleep 1000"));
Service userBApp = new Service();
userBApp.setName(sameAppName);
userBApp.setVersion("v1");
userBApp.addComponent(createComponent("comp", 1, "sleep 1000"));
File userABasePath = null, userBBasePath = null;
try {
userABasePath = new File(origBasePath, userA);
userABasePath.mkdirs();
getConf().set(YARN_SERVICE_BASE_PATH, userABasePath.getAbsolutePath());
client.actionCreate(userAApp);
waitForServiceToBeStarted(client, userAApp);
userBBasePath = new File(origBasePath, userB);
userBBasePath.mkdirs();
getConf().set(YARN_SERVICE_BASE_PATH, userBBasePath.getAbsolutePath());
client.actionBuild(userBApp);
} catch (Exception e) {
Assert
.fail("Exception should not be thrown - " + e.getLocalizedMessage());
} finally {
if (userABasePath != null) {
getConf().set(YARN_SERVICE_BASE_PATH, userABasePath.getAbsolutePath());
client.actionStop(sameAppName, true);
client.actionDestroy(sameAppName);
}
if (userBBasePath != null) {
getConf().set(YARN_SERVICE_BASE_PATH, userBBasePath.getAbsolutePath());
client.actionDestroy(sameAppName);
}
}
// Need to extend this test to validate that different users can create
// apps of exact same name. So far only create followed by build is tested.
// Need to test create followed by create.
}
@Test(timeout = 200000)
public void testCreateServiceSameNameSameUser() throws Exception {
String sameAppName = "same-name";
String user = UserGroupInformation.getCurrentUser().getUserName();
System.setProperty("user.name", user);
setupInternal(NUM_NMS);
ServiceClient client = createClient(getConf());
Service appA = new Service();
appA.setName(sameAppName);
appA.setVersion("v1");
appA.addComponent(createComponent("comp", 1, "sleep 1000"));
Service appB = new Service();
appB.setName(sameAppName);
appB.setVersion("v1");
appB.addComponent(createComponent("comp", 1, "sleep 1000"));
try {
client.actionBuild(appA);
client.actionBuild(appB);
} catch (Exception e) {
String expectedMsg = "Service Instance dir already exists:";
if (e.getLocalizedMessage() != null) {
Assert.assertThat(e.getLocalizedMessage(),
CoreMatchers.containsString(expectedMsg));
} else {
Assert.fail("Message cannot be null. It has to say - " + expectedMsg);
}
} finally {
// cleanup
client.actionDestroy(sameAppName);
}
try {
client.actionCreate(appA);
waitForServiceToBeStarted(client, appA);
client.actionCreate(appB);
waitForServiceToBeStarted(client, appB);
} catch (Exception e) {
String expectedMsg = "Failed to create service " + sameAppName
+ ", because it already exists.";
if (e.getLocalizedMessage() != null) {
Assert.assertThat(e.getLocalizedMessage(),
CoreMatchers.containsString(expectedMsg));
} else {
Assert.fail("Message cannot be null. It has to say - " + expectedMsg);
}
} finally {
// cleanup
client.actionStop(sameAppName, true);
client.actionDestroy(sameAppName);
}
}
// Test to verify recovery of SeviceMaster after RM is restarted.
// 1. Create an example service.
// 2. Restart RM.
// 3. Fail the application attempt.
// 4. Verify ServiceMaster recovers.
@Test(timeout = 200000)
public void testRecoverComponentsAfterRMRestart() throws Exception {
YarnConfiguration conf = new YarnConfiguration();
conf.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true);
conf.setBoolean(
YarnConfiguration.RM_WORK_PRESERVING_RECOVERY_ENABLED, true);
conf.setLong(YarnConfiguration.NM_RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_MS,
500L);
conf.setBoolean(YarnConfiguration.YARN_MINICLUSTER_FIXED_PORTS, true);
conf.setBoolean(YarnConfiguration.YARN_MINICLUSTER_USE_RPC, true);
setConf(conf);
setupInternal(NUM_NMS);
ServiceClient client = createClient(getConf());
Service exampleApp = createExampleApplication();
client.actionCreate(exampleApp);
Multimap<String, String> containersBeforeFailure =
waitForAllCompToBeReady(client, exampleApp);
LOG.info("Restart the resource manager");
getYarnCluster().restartResourceManager(
getYarnCluster().getActiveRMIndex());
GenericTestUtils.waitFor(() ->
getYarnCluster().getResourceManager().getServiceState() ==
org.apache.hadoop.service.Service.STATE.STARTED, 2000, 200000);
Assert.assertTrue("node managers connected",
getYarnCluster().waitForNodeManagersToConnect(5000));
ApplicationId exampleAppId = ApplicationId.fromString(exampleApp.getId());
ApplicationAttemptId applicationAttemptId = client.getYarnClient()
.getApplicationReport(exampleAppId).getCurrentApplicationAttemptId();
LOG.info("Fail the application attempt {}", applicationAttemptId);
client.getYarnClient().failApplicationAttempt(applicationAttemptId);
//wait until attempt 2 is running
GenericTestUtils.waitFor(() -> {
try {
ApplicationReport ar = client.getYarnClient()
.getApplicationReport(exampleAppId);
return ar.getCurrentApplicationAttemptId().getAttemptId() == 2 &&
ar.getYarnApplicationState() == YarnApplicationState.RUNNING;
} catch (YarnException | IOException e) {
throw new RuntimeException("while waiting", e);
}
}, 2000, 200000);
Multimap<String, String> containersAfterFailure = waitForAllCompToBeReady(
client, exampleApp);
Assert.assertEquals("component container affected by restart",
containersBeforeFailure, containersAfterFailure);
LOG.info("Stop/destroy service {}", exampleApp);
client.actionStop(exampleApp.getName(), true);
client.actionDestroy(exampleApp.getName());
}
@Test(timeout = 200000)
public void testUpgrade() throws Exception {
setupInternal(NUM_NMS);
getConf().setBoolean(YARN_SERVICE_UPGRADE_ENABLED, true);
ServiceClient client = createClient(getConf());
Service service = createExampleApplication();
client.actionCreate(service);
waitForServiceToBeStable(client, service);
// upgrade the service
Component component = service.getComponents().iterator().next();
service.setState(ServiceState.UPGRADING);
service.setVersion("v2");
component.getConfiguration().getEnv().put("key1", "val1");
client.initiateUpgrade(service);
// wait for service to be in upgrade state
waitForServiceToBeInState(client, service, ServiceState.UPGRADING);
SliderFileSystem fs = new SliderFileSystem(getConf());
Service fromFs = ServiceApiUtil.loadServiceUpgrade(fs,
service.getName(), service.getVersion());
Assert.assertEquals(service.getName(), fromFs.getName());
Assert.assertEquals(service.getVersion(), fromFs.getVersion());
// upgrade containers
Service liveService = client.getStatus(service.getName());
client.actionUpgrade(service,
liveService.getComponent(component.getName()).getContainers());
waitForAllCompToBeReady(client, service);
// finalize the upgrade
client.actionStart(service.getName());
waitForServiceToBeStable(client, service);
Service active = client.getStatus(service.getName());
Assert.assertEquals("component not stable", ComponentState.STABLE,
active.getComponent(component.getName()).getState());
Assert.assertEquals("comp does not have new env", "val1",
active.getComponent(component.getName()).getConfiguration()
.getEnv("key1"));
LOG.info("Stop/destroy service {}", service);
client.actionStop(service.getName(), true);
client.actionDestroy(service.getName());
}
@Test(timeout = 200000)
public void testExpressUpgrade() throws Exception {
setupInternal(NUM_NMS);
getConf().setBoolean(YARN_SERVICE_UPGRADE_ENABLED, true);
ServiceClient client = createClient(getConf());
Service service = createExampleApplication();
client.actionCreate(service);
waitForServiceToBeStable(client, service);
// upgrade the service
Component component = service.getComponents().iterator().next();
service.setState(ServiceState.EXPRESS_UPGRADING);
service.setVersion("v2");
component.getConfiguration().getEnv().put("key1", "val1");
Component component2 = service.getComponent("compb");
component2.getConfiguration().getEnv().put("key2", "val2");
client.actionUpgradeExpress(service);
// wait for upgrade to complete
waitForServiceToBeStable(client, service);
Service active = client.getStatus(service.getName());
Assert.assertEquals("component not stable", ComponentState.STABLE,
active.getComponent(component.getName()).getState());
Assert.assertEquals("compa does not have new env", "val1",
active.getComponent(component.getName()).getConfiguration()
.getEnv("key1"));
Assert.assertEquals("compb does not have new env", "val2",
active.getComponent(component2.getName()).getConfiguration()
.getEnv("key2"));
LOG.info("Stop/destroy service {}", service);
client.actionStop(service.getName(), true);
client.actionDestroy(service.getName());
}
// Test to verify ANTI_AFFINITY placement policy
// 1. Start mini cluster with 3 NMs and scheduler placement-constraint handler
// 2. Create an example service with 3 containers
// 3. Verify no more than 1 container comes up in each of the 3 NMs
// 4. Flex the component to 4 containers
// 5. Verify that the 4th container does not even get allocated since there
// are only 3 NMs
@Test (timeout = 200000)
public void testCreateServiceWithPlacementPolicy() throws Exception {
// We need to enable scheduler placement-constraint at the cluster level to
// let apps use placement policies.
YarnConfiguration conf = new YarnConfiguration();
conf.set(YarnConfiguration.RM_PLACEMENT_CONSTRAINTS_HANDLER,
YarnConfiguration.SCHEDULER_RM_PLACEMENT_CONSTRAINTS_HANDLER);
setConf(conf);
setupInternal(3);
ServiceClient client = createClient(getConf());
Service exampleApp = new Service();
exampleApp.setName("example-app");
exampleApp.setVersion("v1");
Component comp = createComponent("compa", 3L, "sleep 1000");
PlacementPolicy pp = new PlacementPolicy();
PlacementConstraint pc = new PlacementConstraint();
pc.setName("CA1");
pc.setTargetTags(Collections.singletonList("compa"));
pc.setScope(PlacementScope.NODE);
pc.setType(PlacementType.ANTI_AFFINITY);
pp.setConstraints(Collections.singletonList(pc));
comp.setPlacementPolicy(pp);
exampleApp.addComponent(comp);
client.actionCreate(exampleApp);
waitForServiceToBeStable(client, exampleApp);
// Check service is stable and all 3 containers are running
Service service = client.getStatus(exampleApp.getName());
Component component = service.getComponent("compa");
Assert.assertEquals("Service state should be STABLE", ServiceState.STABLE,
service.getState());
Assert.assertEquals("3 containers are expected to be running", 3,
component.getContainers().size());
// Prepare a map of non-AM containers for later lookup
Set<String> nonAMContainerIdSet = new HashSet<>();
for (Container cont : component.getContainers()) {
nonAMContainerIdSet.add(cont.getId());
}
// Verify that no more than 1 non-AM container came up on each of the 3 NMs
Set<String> hosts = new HashSet<>();
ApplicationReport report = client.getYarnClient()
.getApplicationReport(ApplicationId.fromString(exampleApp.getId()));
GetContainersRequest req = GetContainersRequest
.newInstance(report.getCurrentApplicationAttemptId());
ResourceManager rm = getYarnCluster().getResourceManager();
for (ContainerReport contReport : rm.getClientRMService().getContainers(req)
.getContainerList()) {
if (!nonAMContainerIdSet
.contains(contReport.getContainerId().toString())) {
continue;
}
if (hosts.contains(contReport.getNodeHttpAddress())) {
Assert.fail("Container " + contReport.getContainerId()
+ " came up in the same host as another container.");
} else {
hosts.add(contReport.getNodeHttpAddress());
}
}
// Flex compa up to 5, which is more containers than the no of NMs
Map<String, Long> compCounts = new HashMap<>();
compCounts.put("compa", 5L);
exampleApp.getComponent("compa").setNumberOfContainers(5L);
client.flexByRestService(exampleApp.getName(), compCounts);
try {
// 10 secs is enough for the container to be started. The down side of
// this test is that it has to wait that long. Setting a higher wait time
// will add to the total time taken by tests to run.
waitForServiceToBeStable(client, exampleApp, 10000);
Assert.fail("Service should not be in a stable state. It should throw "
+ "a timeout exception.");
} catch (Exception e) {
// Check that service state is not STABLE and only 3 containers are
// running and the fourth one should not get allocated.
service = client.getStatus(exampleApp.getName());
component = service.getComponent("compa");
Assert.assertNotEquals("Service state should not be STABLE",
ServiceState.STABLE, service.getState());
Assert.assertEquals("Component state should be FLEXING",
ComponentState.FLEXING, component.getState());
Assert.assertEquals("3 containers are expected to be running", 3,
component.getContainers().size());
}
// Flex compa down to 4 now, which is still more containers than the no of
// NMs. This tests the usecase that flex down does not kill any of the
// currently running containers since the required number of containers are
// still higher than the currently running number of containers. However,
// component state will still be FLEXING and service state not STABLE.
compCounts = new HashMap<>();
compCounts.put("compa", 4L);
exampleApp.getComponent("compa").setNumberOfContainers(4L);
client.flexByRestService(exampleApp.getName(), compCounts);
try {
// 10 secs is enough for the container to be started. The down side of
// this test is that it has to wait that long. Setting a higher wait time
// will add to the total time taken by tests to run.
waitForServiceToBeStable(client, exampleApp, 10000);
Assert.fail("Service should not be in a stable state. It should throw "
+ "a timeout exception.");
} catch (Exception e) {
// Check that service state is not STABLE and only 3 containers are
// running and the fourth one should not get allocated.
service = client.getStatus(exampleApp.getName());
component = service.getComponent("compa");
Assert.assertNotEquals("Service state should not be STABLE",
ServiceState.STABLE, service.getState());
Assert.assertEquals("Component state should be FLEXING",
ComponentState.FLEXING, component.getState());
Assert.assertEquals("3 containers are expected to be running", 3,
component.getContainers().size());
}
// Finally flex compa down to 3, which is exactly the number of containers
// currently running. This will bring the component and service states to
// STABLE.
compCounts = new HashMap<>();
compCounts.put("compa", 3L);
exampleApp.getComponent("compa").setNumberOfContainers(3L);
client.flexByRestService(exampleApp.getName(), compCounts);
waitForServiceToBeStable(client, exampleApp);
LOG.info("Stop/destroy service {}", exampleApp);
client.actionStop(exampleApp.getName(), true);
client.actionDestroy(exampleApp.getName());
}
@Test(timeout = 200000)
public void testAMSigtermDoesNotKillApplication() throws Exception {
runAMSignalTest(SignalContainerCommand.GRACEFUL_SHUTDOWN);
}
@Test(timeout = 200000)
public void testAMSigkillDoesNotKillApplication() throws Exception {
runAMSignalTest(SignalContainerCommand.FORCEFUL_SHUTDOWN);
}
public void runAMSignalTest(SignalContainerCommand signal) throws Exception {
setupInternal(NUM_NMS);
ServiceClient client = createClient(getConf());
Service exampleApp = createExampleApplication();
client.actionCreate(exampleApp);
waitForServiceToBeStable(client, exampleApp);
Service appStatus1 = client.getStatus(exampleApp.getName());
ApplicationId exampleAppId = ApplicationId.fromString(appStatus1.getId());
YarnClient yarnClient = createYarnClient(getConf());
ApplicationReport applicationReport = yarnClient.getApplicationReport(
exampleAppId);
ApplicationAttemptId firstAttemptId = applicationReport
.getCurrentApplicationAttemptId();
ApplicationAttemptReport attemptReport = yarnClient
.getApplicationAttemptReport(firstAttemptId);
// the AM should not perform a graceful shutdown since the operation was not
// initiated through the service client
yarnClient.signalToContainer(attemptReport.getAMContainerId(), signal);
GenericTestUtils.waitFor(() -> {
try {
ApplicationReport ar = client.getYarnClient()
.getApplicationReport(exampleAppId);
YarnApplicationState state = ar.getYarnApplicationState();
Assert.assertTrue(state == YarnApplicationState.RUNNING ||
state == YarnApplicationState.ACCEPTED);
if (state != YarnApplicationState.RUNNING) {
return false;
}
if (ar.getCurrentApplicationAttemptId() == null ||
ar.getCurrentApplicationAttemptId().equals(firstAttemptId)) {
return false;
}
Service appStatus2 = client.getStatus(exampleApp.getName());
if (appStatus2.getState() != ServiceState.STABLE) {
return false;
}
Assert.assertEquals(getSortedContainerIds(appStatus1).toString(),
getSortedContainerIds(appStatus2).toString());
return true;
} catch (YarnException | IOException e) {
throw new RuntimeException("while waiting", e);
}
}, 2000, 200000);
}
private static List<String> getSortedContainerIds(Service s) {
List<String> containerIds = new ArrayList<>();
for (Component component : s.getComponents()) {
for (Container container : component.getContainers()) {
containerIds.add(container.getId());
}
}
Collections.sort(containerIds);
return containerIds;
}
// Test to verify component health threshold monitor. It uses anti-affinity
// placement policy to make it easier to simulate container failure by
// allocating more containers than the no of NMs.
// 1. Start mini cluster with 3 NMs and scheduler placement-constraint handler
// 2. Create an example service of 3 containers with anti-affinity placement
// policy and health threshold = 65%, window = 3 secs, init-delay = 0 secs,
// poll-frequency = 1 secs
// 3. Flex the component to 4 containers. This makes health = 75%, so based on
// threshold the service will continue to run beyond the window of 3 secs.
// 4. Flex the component to 5 containers. This makes health = 60%, so based on
// threshold the service will be stopped after the window of 3 secs.
@Test (timeout = 200000)
public void testComponentHealthThresholdMonitor() throws Exception {
// We need to enable scheduler placement-constraint at the cluster level to
// let apps use placement policies.
YarnConfiguration conf = new YarnConfiguration();
conf.set(YarnConfiguration.RM_PLACEMENT_CONSTRAINTS_HANDLER,
YarnConfiguration.SCHEDULER_RM_PLACEMENT_CONSTRAINTS_HANDLER);
setConf(conf);
setupInternal(3);
ServiceClient client = createClient(getConf());
Service exampleApp = new Service();
exampleApp.setName("example-app");
exampleApp.setVersion("v1");
Component comp = createComponent("compa", 3L, "sleep 1000");
PlacementPolicy pp = new PlacementPolicy();
PlacementConstraint pc = new PlacementConstraint();
pc.setName("CA1");
pc.setTargetTags(Collections.singletonList("compa"));
pc.setScope(PlacementScope.NODE);
pc.setType(PlacementType.ANTI_AFFINITY);
pp.setConstraints(Collections.singletonList(pc));
comp.setPlacementPolicy(pp);
Configuration config = new Configuration();
config.setProperty(CONTAINER_HEALTH_THRESHOLD_PERCENT, "65");
config.setProperty(CONTAINER_HEALTH_THRESHOLD_WINDOW_SEC, "3");
config.setProperty(CONTAINER_HEALTH_THRESHOLD_INIT_DELAY_SEC, "0");
config.setProperty(CONTAINER_HEALTH_THRESHOLD_POLL_FREQUENCY_SEC, "1");
config.setProperty(DEFAULT_READINESS_CHECK_ENABLED, "false");
comp.setConfiguration(config);
exampleApp.addComponent(comp);
// Make sure AM does not come up after service is killed for this test
Configuration serviceConfig = new Configuration();
serviceConfig.setProperty(AM_RESTART_MAX, "1");
exampleApp.setConfiguration(serviceConfig);
client.actionCreate(exampleApp);
waitForServiceToBeStable(client, exampleApp);
// Check service is stable and all 3 containers are running
Service service = client.getStatus(exampleApp.getName());
Component component = service.getComponent("compa");
Assert.assertEquals("Service state should be STABLE", ServiceState.STABLE,
service.getState());
Assert.assertEquals("3 containers are expected to be running", 3,
component.getContainers().size());
// Flex compa up to 4 - will make health 75% (3 out of 4 running), but still
// above threshold of 65%, so service will continue to run.
Map<String, Long> compCounts = new HashMap<>();
compCounts.put("compa", 4L);
exampleApp.getComponent("compa").setNumberOfContainers(4L);
client.flexByRestService(exampleApp.getName(), compCounts);
try {
// Wait for 6 secs (window 3 secs + 1 for next poll + 2 for buffer). Since
// the service will never go to stable state (because of anti-affinity the
// 4th container will never be allocated) it will timeout. However, after
// the timeout the service should continue to run since health is 75%
// which is above the threshold of 65%.
waitForServiceToBeStable(client, exampleApp, 6000);
Assert.fail("Service should not be in a stable state. It should throw "
+ "a timeout exception.");
} catch (Exception e) {
// Check that service state is STARTED and only 3 containers are running
service = client.getStatus(exampleApp.getName());
component = service.getComponent("compa");
Assert.assertEquals("Service state should be STARTED",
ServiceState.STARTED, service.getState());
Assert.assertEquals("Component state should be FLEXING",
ComponentState.FLEXING, component.getState());
Assert.assertEquals("3 containers are expected to be running", 3,
component.getContainers().size());
}
// Flex compa up to 5 - will make health 60% (3 out of 5 running), so
// service will stop since it is below threshold of 65%.
compCounts.put("compa", 5L);
exampleApp.getComponent("compa").setNumberOfContainers(5L);
client.flexByRestService(exampleApp.getName(), compCounts);
try {
// Wait for 14 secs (window 3 secs + 1 for next poll + 2 for buffer + 5
// secs of service wait before shutting down + 3 secs app cleanup so that
// API returns that service is in FAILED state). Note, because of
// anti-affinity the 4th and 5th container will never be allocated.
waitForServiceToBeInState(client, exampleApp, ServiceState.FAILED,
14000);
} catch (Exception e) {
Assert.fail("Should not have thrown exception");
}
LOG.info("Destroy service {}", exampleApp);
client.actionDestroy(exampleApp.getName());
}
// Check containers launched are in dependency order
// Get all containers into a list and sort based on container launch time e.g.
// compa-c1, compa-c2, compb-c1, compb-c2;
// check that the container's launch time are align with the dependencies.
private void checkContainerLaunchDependencies(ServiceClient client,
Service exampleApp, String... compOrder)
throws IOException, YarnException {
Service retrievedApp = client.getStatus(exampleApp.getName());
List<Container> containerList = new ArrayList<>();
for (Component component : retrievedApp.getComponents()) {
containerList.addAll(component.getContainers());
}
// sort based on launchTime
containerList
.sort((o1, o2) -> o1.getLaunchTime().compareTo(o2.getLaunchTime()));
LOG.info("containerList: " + containerList);
// check the containers are in the dependency order.
int index = 0;
for (String comp : compOrder) {
long num = retrievedApp.getComponent(comp).getNumberOfContainers();
for (int i = 0; i < num; i++) {
String compInstanceName = containerList.get(index).getComponentInstanceName();
String compName =
compInstanceName.substring(0, compInstanceName.lastIndexOf('-'));
Assert.assertEquals(comp, compName);
index++;
}
}
}
private Map<String, Long> flexComponents(ServiceClient client,
Service exampleApp, long count) throws YarnException, IOException {
Map<String, Long> compCounts = new HashMap<>();
compCounts.put("compa", count);
compCounts.put("compb", count);
// flex will update the persisted conf to reflect latest number of containers.
exampleApp.getComponent("compa").setNumberOfContainers(count);
exampleApp.getComponent("compb").setNumberOfContainers(count);
client.flexByRestService(exampleApp.getName(), compCounts);
return compCounts;
}
// Check each component's comp instances name are in sequential order.
// E.g. If there are two instances compA-1 and compA-2
// When flex up to 4 instances, it should be compA-1 , compA-2, compA-3, compA-4
// When flex down to 3 instances, it should be compA-1 , compA-2, compA-3.
private void checkCompInstancesInOrder(ServiceClient client,
Service exampleApp) throws IOException, YarnException,
TimeoutException, InterruptedException {
Service service = client.getStatus(exampleApp.getName());
for (Component comp : service.getComponents()) {
checkEachCompInstancesInOrder(comp, exampleApp.getName());
}
}
private void checkEachCompInstancesInOrder(Component component, String
serviceName) throws TimeoutException, InterruptedException {
long expectedNumInstances = component.getNumberOfContainers();
Assert.assertEquals(expectedNumInstances, component.getContainers().size());
TreeSet<String> instances = new TreeSet<>();
for (Container container : component.getContainers()) {
instances.add(container.getComponentInstanceName());
String componentZKPath = RegistryUtils.componentPath(RegistryUtils
.currentUser(), YarnServiceConstants.APP_TYPE, serviceName,
RegistryPathUtils.encodeYarnID(container.getId()));
GenericTestUtils.waitFor(() -> {
try {
return getCuratorService().zkPathExists(componentZKPath);
} catch (IOException e) {
return false;
}
}, 1000, 60000);
}
int i = 0;
for (String s : instances) {
Assert.assertEquals(component.getName() + "-" + i, s);
i++;
}
}
}
| |
/*
* 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.transforms.reflect;
import static com.google.common.base.Preconditions.checkState;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.schemas.FieldAccessDescriptor;
import org.apache.beam.sdk.state.State;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.state.Timer;
import org.apache.beam.sdk.state.TimerSpec;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.DoFn.MultiOutputReceiver;
import org.apache.beam.sdk.transforms.DoFn.OutputReceiver;
import org.apache.beam.sdk.transforms.DoFn.StateId;
import org.apache.beam.sdk.transforms.DoFn.TimerId;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.FieldAccessDeclaration;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.Parameter;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.Parameter.RestrictionTrackerParameter;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.Parameter.StateParameter;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.Parameter.TimerParameter;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.Parameter.WindowParameter;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.StateDeclaration;
import org.apache.beam.sdk.transforms.reflect.DoFnSignature.TimerDeclaration;
import org.apache.beam.sdk.transforms.splittabledofn.HasDefaultTracker;
import org.apache.beam.sdk.transforms.splittabledofn.RestrictionTracker;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.util.common.ReflectHelpers;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.apache.beam.sdk.values.TypeParameter;
import org.joda.time.Instant;
/** Utilities for working with {@link DoFnSignature}. See {@link #getSignature}. */
public class DoFnSignatures {
private DoFnSignatures() {}
private static final Map<Class<?>, DoFnSignature> signatureCache = new LinkedHashMap<>();
private static final ImmutableList<Class<? extends Parameter>>
ALLOWED_NON_SPLITTABLE_PROCESS_ELEMENT_PARAMETERS =
ImmutableList.of(
Parameter.ProcessContextParameter.class,
Parameter.ElementParameter.class,
Parameter.RowParameter.class,
Parameter.TimestampParameter.class,
Parameter.OutputReceiverParameter.class,
Parameter.TaggedOutputReceiverParameter.class,
Parameter.WindowParameter.class,
Parameter.PaneInfoParameter.class,
Parameter.PipelineOptionsParameter.class,
Parameter.TimerParameter.class,
Parameter.StateParameter.class);
private static final ImmutableList<Class<? extends Parameter>>
ALLOWED_SPLITTABLE_PROCESS_ELEMENT_PARAMETERS =
ImmutableList.of(
Parameter.PipelineOptionsParameter.class,
Parameter.ElementParameter.class,
Parameter.RowParameter.class,
Parameter.TimestampParameter.class,
Parameter.OutputReceiverParameter.class,
Parameter.TaggedOutputReceiverParameter.class,
Parameter.ProcessContextParameter.class,
Parameter.RestrictionTrackerParameter.class);
private static final ImmutableList<Class<? extends Parameter>> ALLOWED_ON_TIMER_PARAMETERS =
ImmutableList.of(
Parameter.OnTimerContextParameter.class,
Parameter.TimestampParameter.class,
Parameter.TimeDomainParameter.class,
Parameter.WindowParameter.class,
Parameter.PipelineOptionsParameter.class,
Parameter.OutputReceiverParameter.class,
Parameter.TaggedOutputReceiverParameter.class,
Parameter.TimerParameter.class,
Parameter.StateParameter.class);
private static final Collection<Class<? extends Parameter>>
ALLOWED_ON_WINDOW_EXPIRATION_PARAMETERS =
ImmutableList.of(
Parameter.WindowParameter.class,
Parameter.PipelineOptionsParameter.class,
Parameter.OutputReceiverParameter.class,
Parameter.TaggedOutputReceiverParameter.class,
Parameter.StateParameter.class);
/** @return the {@link DoFnSignature} for the given {@link DoFn} instance. */
public static <FnT extends DoFn<?, ?>> DoFnSignature signatureForDoFn(FnT fn) {
return getSignature(fn.getClass());
}
/** @return the {@link DoFnSignature} for the given {@link DoFn} subclass. */
public static synchronized <FnT extends DoFn<?, ?>> DoFnSignature getSignature(Class<FnT> fn) {
return signatureCache.computeIfAbsent(fn, k -> parseSignature(fn));
}
/**
* The context for a {@link DoFn} class, for use in analysis.
*
* <p>It contains much of the information that eventually becomes part of the {@link
* DoFnSignature}, but in an intermediate state.
*/
@VisibleForTesting
static class FnAnalysisContext {
private final Map<String, StateDeclaration> stateDeclarations = new HashMap<>();
private final Map<String, TimerDeclaration> timerDeclarations = new HashMap<>();
private final Map<String, FieldAccessDeclaration> fieldAccessDeclarations = new HashMap<>();
private FnAnalysisContext() {}
/** Create an empty context, with no declarations. */
public static FnAnalysisContext create() {
return new FnAnalysisContext();
}
/** State parameters declared in this context, keyed by {@link StateId}. Unmodifiable. */
public Map<String, StateDeclaration> getStateDeclarations() {
return Collections.unmodifiableMap(stateDeclarations);
}
/** Timer parameters declared in this context, keyed by {@link TimerId}. Unmodifiable. */
public Map<String, TimerDeclaration> getTimerDeclarations() {
return Collections.unmodifiableMap(timerDeclarations);
}
/** Field access declaration declared in this context. */
@Nullable
public Map<String, FieldAccessDeclaration> getFieldAccessDeclarations() {
return fieldAccessDeclarations;
}
public void addStateDeclaration(StateDeclaration decl) {
stateDeclarations.put(decl.id(), decl);
}
public void addStateDeclarations(Iterable<StateDeclaration> decls) {
for (StateDeclaration decl : decls) {
addStateDeclaration(decl);
}
}
public void addTimerDeclaration(TimerDeclaration decl) {
timerDeclarations.put(decl.id(), decl);
}
public void addTimerDeclarations(Iterable<TimerDeclaration> decls) {
for (TimerDeclaration decl : decls) {
addTimerDeclaration(decl);
}
}
public void addFieldAccessDeclaration(FieldAccessDeclaration decl) {
fieldAccessDeclarations.put(decl.id(), decl);
}
public void addFieldAccessDeclarations(Iterable<FieldAccessDeclaration> decls) {
for (FieldAccessDeclaration decl : decls) {
addFieldAccessDeclaration(decl);
}
}
}
/**
* The context of analysis within a particular method.
*
* <p>It contains much of the information that eventually becomes part of the {@link
* DoFnSignature.MethodWithExtraParameters}, but in an intermediate state.
*/
private static class MethodAnalysisContext {
private final Map<String, StateParameter> stateParameters = new HashMap<>();
private final Map<String, TimerParameter> timerParameters = new HashMap<>();
private final List<Parameter> extraParameters = new ArrayList<>();
@Nullable private TypeDescriptor<? extends BoundedWindow> windowT;
private MethodAnalysisContext() {}
/** Indicates whether a {@link RestrictionTrackerParameter} is known in this context. */
public boolean hasRestrictionTrackerParameter() {
return extraParameters
.stream()
.anyMatch(Predicates.instanceOf(RestrictionTrackerParameter.class)::apply);
}
/** Indicates whether a {@link WindowParameter} is known in this context. */
public boolean hasWindowParameter() {
return extraParameters.stream().anyMatch(Predicates.instanceOf(WindowParameter.class)::apply);
}
/** Indicates whether a {@link Parameter.PipelineOptionsParameter} is known in this context. */
public boolean hasPipelineOptionsParamter() {
return extraParameters
.stream()
.anyMatch(Predicates.instanceOf(Parameter.PipelineOptionsParameter.class)::apply);
}
/** The window type, if any, used by this method. */
@Nullable
public TypeDescriptor<? extends BoundedWindow> getWindowType() {
return windowT;
}
/** State parameters declared in this context, keyed by {@link StateId}. */
public Map<String, StateParameter> getStateParameters() {
return Collections.unmodifiableMap(stateParameters);
}
/** Timer parameters declared in this context, keyed by {@link TimerId}. */
public Map<String, TimerParameter> getTimerParameters() {
return Collections.unmodifiableMap(timerParameters);
}
/** Extra parameters in their entirety. Unmodifiable. */
public List<Parameter> getExtraParameters() {
return Collections.unmodifiableList(extraParameters);
}
/**
* Returns an {@link MethodAnalysisContext} like this one but including the provided {@link
* StateParameter}.
*/
public void addParameter(Parameter param) {
extraParameters.add(param);
if (param instanceof StateParameter) {
StateParameter stateParameter = (StateParameter) param;
stateParameters.put(stateParameter.referent().id(), stateParameter);
}
if (param instanceof TimerParameter) {
TimerParameter timerParameter = (TimerParameter) param;
timerParameters.put(timerParameter.referent().id(), timerParameter);
}
}
/** Create an empty context, with no declarations. */
public static MethodAnalysisContext create() {
return new MethodAnalysisContext();
}
}
@AutoValue
abstract static class ParameterDescription {
public abstract Method getMethod();
public abstract int getIndex();
public abstract TypeDescriptor<?> getType();
public abstract List<Annotation> getAnnotations();
public static ParameterDescription of(
Method method, int index, TypeDescriptor<?> type, List<Annotation> annotations) {
return new AutoValue_DoFnSignatures_ParameterDescription(method, index, type, annotations);
}
public static ParameterDescription of(
Method method, int index, TypeDescriptor<?> type, Annotation[] annotations) {
return new AutoValue_DoFnSignatures_ParameterDescription(
method, index, type, Arrays.asList(annotations));
}
}
/** Analyzes a given {@link DoFn} class and extracts its {@link DoFnSignature}. */
private static DoFnSignature parseSignature(Class<? extends DoFn<?, ?>> fnClass) {
DoFnSignature.Builder signatureBuilder = DoFnSignature.builder();
ErrorReporter errors = new ErrorReporter(null, fnClass.getName());
errors.checkArgument(DoFn.class.isAssignableFrom(fnClass), "Must be subtype of DoFn");
signatureBuilder.setFnClass(fnClass);
TypeDescriptor<? extends DoFn<?, ?>> fnT = TypeDescriptor.of(fnClass);
// Extract the input and output type, and whether the fn is bounded.
TypeDescriptor<?> inputT = null;
TypeDescriptor<?> outputT = null;
for (TypeDescriptor<?> supertype : fnT.getTypes()) {
if (!supertype.getRawType().equals(DoFn.class)) {
continue;
}
Type[] args = ((ParameterizedType) supertype.getType()).getActualTypeArguments();
inputT = TypeDescriptor.of(args[0]);
outputT = TypeDescriptor.of(args[1]);
}
errors.checkNotNull(inputT, "Unable to determine input type");
// Find the state and timer declarations in advance of validating
// method parameter lists
FnAnalysisContext fnContext = FnAnalysisContext.create();
fnContext.addStateDeclarations(analyzeStateDeclarations(errors, fnClass).values());
fnContext.addTimerDeclarations(analyzeTimerDeclarations(errors, fnClass).values());
fnContext.addFieldAccessDeclarations(analyzeFieldAccessDeclaration(errors, fnClass).values());
Method processElementMethod =
findAnnotatedMethod(errors, DoFn.ProcessElement.class, fnClass, true);
Method startBundleMethod = findAnnotatedMethod(errors, DoFn.StartBundle.class, fnClass, false);
Method finishBundleMethod =
findAnnotatedMethod(errors, DoFn.FinishBundle.class, fnClass, false);
Method setupMethod = findAnnotatedMethod(errors, DoFn.Setup.class, fnClass, false);
Method teardownMethod = findAnnotatedMethod(errors, DoFn.Teardown.class, fnClass, false);
Method onWindowExpirationMethod =
findAnnotatedMethod(errors, DoFn.OnWindowExpiration.class, fnClass, false);
Method getInitialRestrictionMethod =
findAnnotatedMethod(errors, DoFn.GetInitialRestriction.class, fnClass, false);
Method splitRestrictionMethod =
findAnnotatedMethod(errors, DoFn.SplitRestriction.class, fnClass, false);
Method getRestrictionCoderMethod =
findAnnotatedMethod(errors, DoFn.GetRestrictionCoder.class, fnClass, false);
Method newTrackerMethod = findAnnotatedMethod(errors, DoFn.NewTracker.class, fnClass, false);
Collection<Method> onTimerMethods =
declaredMethodsWithAnnotation(DoFn.OnTimer.class, fnClass, DoFn.class);
HashMap<String, DoFnSignature.OnTimerMethod> onTimerMethodMap =
Maps.newHashMapWithExpectedSize(onTimerMethods.size());
for (Method onTimerMethod : onTimerMethods) {
String id = onTimerMethod.getAnnotation(DoFn.OnTimer.class).value();
errors.checkArgument(
fnContext.getTimerDeclarations().containsKey(id),
"Callback %s is for undeclared timer %s",
onTimerMethod,
id);
TimerDeclaration timerDecl = fnContext.getTimerDeclarations().get(id);
errors.checkArgument(
timerDecl.field().getDeclaringClass().equals(onTimerMethod.getDeclaringClass()),
"Callback %s is for timer %s declared in a different class %s."
+ " Timer callbacks must be declared in the same lexical scope as their timer",
onTimerMethod,
id,
timerDecl.field().getDeclaringClass().getCanonicalName());
onTimerMethodMap.put(
id, analyzeOnTimerMethod(errors, fnT, onTimerMethod, id, inputT, outputT, fnContext));
}
signatureBuilder.setOnTimerMethods(onTimerMethodMap);
// Check the converse - that all timers have a callback. This could be relaxed to only
// those timers used in methods, once method parameter lists support timers.
for (TimerDeclaration decl : fnContext.getTimerDeclarations().values()) {
errors.checkArgument(
onTimerMethodMap.containsKey(decl.id()),
"No callback registered via %s for timer %s",
DoFn.OnTimer.class.getSimpleName(),
decl.id());
}
ErrorReporter processElementErrors =
errors.forMethod(DoFn.ProcessElement.class, processElementMethod);
DoFnSignature.ProcessElementMethod processElement =
analyzeProcessElementMethod(
processElementErrors, fnT, processElementMethod, inputT, outputT, fnContext);
signatureBuilder.setProcessElement(processElement);
if (startBundleMethod != null) {
ErrorReporter startBundleErrors = errors.forMethod(DoFn.StartBundle.class, startBundleMethod);
signatureBuilder.setStartBundle(
analyzeStartBundleMethod(startBundleErrors, fnT, startBundleMethod, inputT, outputT));
}
if (finishBundleMethod != null) {
ErrorReporter finishBundleErrors =
errors.forMethod(DoFn.FinishBundle.class, finishBundleMethod);
signatureBuilder.setFinishBundle(
analyzeFinishBundleMethod(finishBundleErrors, fnT, finishBundleMethod, inputT, outputT));
}
if (setupMethod != null) {
signatureBuilder.setSetup(
analyzeLifecycleMethod(errors.forMethod(DoFn.Setup.class, setupMethod), setupMethod));
}
if (teardownMethod != null) {
signatureBuilder.setTeardown(
analyzeLifecycleMethod(
errors.forMethod(DoFn.Teardown.class, teardownMethod), teardownMethod));
}
if (onWindowExpirationMethod != null) {
signatureBuilder.setOnWindowExpiration(
analyzeOnWindowExpirationMethod(
errors, fnT, onWindowExpirationMethod, inputT, outputT, fnContext));
}
ErrorReporter getInitialRestrictionErrors;
if (getInitialRestrictionMethod != null) {
getInitialRestrictionErrors =
errors.forMethod(DoFn.GetInitialRestriction.class, getInitialRestrictionMethod);
signatureBuilder.setGetInitialRestriction(
analyzeGetInitialRestrictionMethod(
getInitialRestrictionErrors, fnT, getInitialRestrictionMethod, inputT));
}
if (splitRestrictionMethod != null) {
ErrorReporter splitRestrictionErrors =
errors.forMethod(DoFn.SplitRestriction.class, splitRestrictionMethod);
signatureBuilder.setSplitRestriction(
analyzeSplitRestrictionMethod(
splitRestrictionErrors, fnT, splitRestrictionMethod, inputT));
}
if (getRestrictionCoderMethod != null) {
ErrorReporter getRestrictionCoderErrors =
errors.forMethod(DoFn.GetRestrictionCoder.class, getRestrictionCoderMethod);
signatureBuilder.setGetRestrictionCoder(
analyzeGetRestrictionCoderMethod(
getRestrictionCoderErrors, fnT, getRestrictionCoderMethod));
}
if (newTrackerMethod != null) {
ErrorReporter newTrackerErrors = errors.forMethod(DoFn.NewTracker.class, newTrackerMethod);
signatureBuilder.setNewTracker(
analyzeNewTrackerMethod(newTrackerErrors, fnT, newTrackerMethod));
}
signatureBuilder.setIsBoundedPerElement(inferBoundedness(fnT, processElement, errors));
signatureBuilder.setStateDeclarations(fnContext.getStateDeclarations());
signatureBuilder.setTimerDeclarations(fnContext.getTimerDeclarations());
signatureBuilder.setFieldAccessDeclarations(fnContext.getFieldAccessDeclarations());
DoFnSignature signature = signatureBuilder.build();
// Additional validation for splittable DoFn's.
if (processElement.isSplittable()) {
verifySplittableMethods(signature, errors);
} else {
verifyUnsplittableMethods(errors, signature);
}
return signature;
}
/**
* Infers the boundedness of the {@link DoFn.ProcessElement} method (whether or not it performs a
* bounded amount of work per element) using the following criteria:
*
* <ol>
* <li>If the {@link DoFn} is not splittable, then it is bounded, it must not be annotated as
* {@link DoFn.BoundedPerElement} or {@link DoFn.UnboundedPerElement}, and {@link
* DoFn.ProcessElement} must return {@code void}.
* <li>If the {@link DoFn} (or any of its supertypes) is annotated as {@link
* DoFn.BoundedPerElement} or {@link DoFn.UnboundedPerElement}, use that. Only one of these
* must be specified.
* <li>If {@link DoFn.ProcessElement} returns {@link DoFn.ProcessContinuation}, assume it is
* unbounded. Otherwise (if it returns {@code void}), assume it is bounded.
* <li>If {@link DoFn.ProcessElement} returns {@code void}, but the {@link DoFn} is annotated
* {@link DoFn.UnboundedPerElement}, this is an error.
* </ol>
*/
private static PCollection.IsBounded inferBoundedness(
TypeDescriptor<? extends DoFn> fnT,
DoFnSignature.ProcessElementMethod processElement,
ErrorReporter errors) {
PCollection.IsBounded isBounded = null;
for (TypeDescriptor<?> supertype : fnT.getTypes()) {
if (supertype.getRawType().isAnnotationPresent(DoFn.BoundedPerElement.class)
|| supertype.getRawType().isAnnotationPresent(DoFn.UnboundedPerElement.class)) {
errors.checkArgument(
isBounded == null,
"Both @%s and @%s specified",
DoFn.BoundedPerElement.class.getSimpleName(),
DoFn.UnboundedPerElement.class.getSimpleName());
isBounded =
supertype.getRawType().isAnnotationPresent(DoFn.BoundedPerElement.class)
? PCollection.IsBounded.BOUNDED
: PCollection.IsBounded.UNBOUNDED;
}
}
if (processElement.isSplittable()) {
if (isBounded == null) {
isBounded =
processElement.hasReturnValue()
? PCollection.IsBounded.UNBOUNDED
: PCollection.IsBounded.BOUNDED;
}
} else {
errors.checkArgument(
isBounded == null,
"Non-splittable, but annotated as @"
+ ((isBounded == PCollection.IsBounded.BOUNDED)
? DoFn.BoundedPerElement.class.getSimpleName()
: DoFn.UnboundedPerElement.class.getSimpleName()));
checkState(!processElement.hasReturnValue(), "Should have been inferred splittable");
isBounded = PCollection.IsBounded.BOUNDED;
}
return isBounded;
}
/**
* Verifies properties related to methods of splittable {@link DoFn}:
*
* <ul>
* <li>Must declare the required {@link DoFn.GetInitialRestriction} and {@link DoFn.NewTracker}
* methods.
* <li>Types of restrictions and trackers must match exactly between {@link
* DoFn.ProcessElement}, {@link DoFn.GetInitialRestriction}, {@link DoFn.NewTracker}, {@link
* DoFn.GetRestrictionCoder}, {@link DoFn.SplitRestriction}.
* </ul>
*/
private static void verifySplittableMethods(DoFnSignature signature, ErrorReporter errors) {
DoFnSignature.ProcessElementMethod processElement = signature.processElement();
DoFnSignature.GetInitialRestrictionMethod getInitialRestriction =
signature.getInitialRestriction();
DoFnSignature.NewTrackerMethod newTracker = signature.newTracker();
DoFnSignature.GetRestrictionCoderMethod getRestrictionCoder = signature.getRestrictionCoder();
DoFnSignature.SplitRestrictionMethod splitRestriction = signature.splitRestriction();
ErrorReporter processElementErrors =
errors.forMethod(DoFn.ProcessElement.class, processElement.targetMethod());
final TypeDescriptor<?> trackerT;
final String originOfTrackerT;
List<String> missingRequiredMethods = new ArrayList<>();
if (getInitialRestriction == null) {
missingRequiredMethods.add("@" + DoFn.GetInitialRestriction.class.getSimpleName());
}
if (newTracker == null) {
if (getInitialRestriction != null
&& getInitialRestriction
.restrictionT()
.isSubtypeOf(TypeDescriptor.of(HasDefaultTracker.class))) {
trackerT =
getInitialRestriction
.restrictionT()
.resolveType(HasDefaultTracker.class.getTypeParameters()[1]);
originOfTrackerT =
String.format(
"restriction type %s of @%s method %s",
formatType(getInitialRestriction.restrictionT()),
DoFn.GetInitialRestriction.class.getSimpleName(),
format(getInitialRestriction.targetMethod()));
} else {
missingRequiredMethods.add("@" + DoFn.NewTracker.class.getSimpleName());
trackerT = null;
originOfTrackerT = null;
}
} else {
trackerT = newTracker.trackerT();
originOfTrackerT =
String.format(
"%s method %s",
DoFn.NewTracker.class.getSimpleName(), format(newTracker.targetMethod()));
ErrorReporter getInitialRestrictionErrors =
errors.forMethod(DoFn.GetInitialRestriction.class, getInitialRestriction.targetMethod());
TypeDescriptor<?> restrictionT = getInitialRestriction.restrictionT();
getInitialRestrictionErrors.checkArgument(
restrictionT.equals(newTracker.restrictionT()),
"Uses restriction type %s, but @%s method %s uses restriction type %s",
formatType(restrictionT),
DoFn.NewTracker.class.getSimpleName(),
format(newTracker.targetMethod()),
formatType(newTracker.restrictionT()));
}
if (!missingRequiredMethods.isEmpty()) {
processElementErrors.throwIllegalArgument(
"Splittable, but does not define the following required methods: %s",
missingRequiredMethods);
}
ErrorReporter getInitialRestrictionErrors =
errors.forMethod(DoFn.GetInitialRestriction.class, getInitialRestriction.targetMethod());
TypeDescriptor<?> restrictionT = getInitialRestriction.restrictionT();
processElementErrors.checkArgument(
processElement.trackerT().equals(trackerT),
"Has tracker type %s, but the DoFn's tracker type was inferred as %s from %s",
formatType(processElement.trackerT()),
trackerT,
originOfTrackerT);
if (getRestrictionCoder != null) {
getInitialRestrictionErrors.checkArgument(
getRestrictionCoder.coderT().isSubtypeOf(coderTypeOf(restrictionT)),
"Uses restriction type %s, but @%s method %s returns %s "
+ "which is not a subtype of %s",
formatType(restrictionT),
DoFn.GetRestrictionCoder.class.getSimpleName(),
format(getRestrictionCoder.targetMethod()),
formatType(getRestrictionCoder.coderT()),
formatType(coderTypeOf(restrictionT)));
}
if (splitRestriction != null) {
getInitialRestrictionErrors.checkArgument(
splitRestriction.restrictionT().equals(restrictionT),
"Uses restriction type %s, but @%s method %s uses restriction type %s",
formatType(restrictionT),
DoFn.SplitRestriction.class.getSimpleName(),
format(splitRestriction.targetMethod()),
formatType(splitRestriction.restrictionT()));
}
}
/**
* Verifies that a non-splittable {@link DoFn} does not declare any methods that only make sense
* for splittable {@link DoFn}: {@link DoFn.GetInitialRestriction}, {@link DoFn.SplitRestriction},
* {@link DoFn.NewTracker}, {@link DoFn.GetRestrictionCoder}.
*/
private static void verifyUnsplittableMethods(ErrorReporter errors, DoFnSignature signature) {
List<String> forbiddenMethods = new ArrayList<>();
if (signature.getInitialRestriction() != null) {
forbiddenMethods.add("@" + DoFn.GetInitialRestriction.class.getSimpleName());
}
if (signature.splitRestriction() != null) {
forbiddenMethods.add("@" + DoFn.SplitRestriction.class.getSimpleName());
}
if (signature.newTracker() != null) {
forbiddenMethods.add("@" + DoFn.NewTracker.class.getSimpleName());
}
if (signature.getRestrictionCoder() != null) {
forbiddenMethods.add("@" + DoFn.GetRestrictionCoder.class.getSimpleName());
}
errors.checkArgument(
forbiddenMethods.isEmpty(), "Non-splittable, but defines methods: %s", forbiddenMethods);
}
/**
* Generates a {@link TypeDescriptor} for {@code DoFn<InputT, OutputT>.ProcessContext} given
* {@code InputT} and {@code OutputT}.
*/
private static <InputT, OutputT>
TypeDescriptor<DoFn<InputT, OutputT>.ProcessContext> doFnProcessContextTypeOf(
TypeDescriptor<InputT> inputT, TypeDescriptor<OutputT> outputT) {
return new TypeDescriptor<DoFn<InputT, OutputT>.ProcessContext>() {}.where(
new TypeParameter<InputT>() {}, inputT)
.where(new TypeParameter<OutputT>() {}, outputT);
}
/**
* Generates a {@link TypeDescriptor} for {@code DoFn<InputT, OutputT>.StartBundleContext} given
* {@code InputT} and {@code OutputT}.
*/
private static <InputT, OutputT>
TypeDescriptor<DoFn<InputT, OutputT>.StartBundleContext> doFnStartBundleContextTypeOf(
TypeDescriptor<InputT> inputT, TypeDescriptor<OutputT> outputT) {
return new TypeDescriptor<DoFn<InputT, OutputT>.StartBundleContext>() {}.where(
new TypeParameter<InputT>() {}, inputT)
.where(new TypeParameter<OutputT>() {}, outputT);
}
/**
* Generates a {@link TypeDescriptor} for {@code DoFn<InputT, OutputT>.FinishBundleContext} given
* {@code InputT} and {@code OutputT}.
*/
private static <InputT, OutputT>
TypeDescriptor<DoFn<InputT, OutputT>.FinishBundleContext> doFnFinishBundleContextTypeOf(
TypeDescriptor<InputT> inputT, TypeDescriptor<OutputT> outputT) {
return new TypeDescriptor<DoFn<InputT, OutputT>.FinishBundleContext>() {}.where(
new TypeParameter<InputT>() {}, inputT)
.where(new TypeParameter<OutputT>() {}, outputT);
}
/**
* Generates a {@link TypeDescriptor} for {@code DoFn<InputT, OutputT>.Context} given {@code
* InputT} and {@code OutputT}.
*/
private static <InputT, OutputT>
TypeDescriptor<DoFn<InputT, OutputT>.OnTimerContext> doFnOnTimerContextTypeOf(
TypeDescriptor<InputT> inputT, TypeDescriptor<OutputT> outputT) {
return new TypeDescriptor<DoFn<InputT, OutputT>.OnTimerContext>() {}.where(
new TypeParameter<InputT>() {}, inputT)
.where(new TypeParameter<OutputT>() {}, outputT);
}
@VisibleForTesting
static DoFnSignature.OnTimerMethod analyzeOnTimerMethod(
ErrorReporter errors,
TypeDescriptor<? extends DoFn<?, ?>> fnClass,
Method m,
String timerId,
TypeDescriptor<?> inputT,
TypeDescriptor<?> outputT,
FnAnalysisContext fnContext) {
errors.checkArgument(void.class.equals(m.getReturnType()), "Must return void");
Type[] params = m.getGenericParameterTypes();
MethodAnalysisContext methodContext = MethodAnalysisContext.create();
boolean requiresStableInput = m.isAnnotationPresent(DoFn.RequiresStableInput.class);
@Nullable TypeDescriptor<? extends BoundedWindow> windowT = getWindowType(fnClass, m);
List<DoFnSignature.Parameter> extraParameters = new ArrayList<>();
ErrorReporter onTimerErrors = errors.forMethod(DoFn.OnTimer.class, m);
for (int i = 0; i < params.length; ++i) {
Parameter parameter =
analyzeExtraParameter(
onTimerErrors,
fnContext,
methodContext,
fnClass,
ParameterDescription.of(
m,
i,
fnClass.resolveType(params[i]),
Arrays.asList(m.getParameterAnnotations()[i])),
inputT,
outputT);
checkParameterOneOf(errors, parameter, ALLOWED_ON_TIMER_PARAMETERS);
extraParameters.add(parameter);
}
return DoFnSignature.OnTimerMethod.create(
m, timerId, requiresStableInput, windowT, extraParameters);
}
@VisibleForTesting
static DoFnSignature.OnWindowExpirationMethod analyzeOnWindowExpirationMethod(
ErrorReporter errors,
TypeDescriptor<? extends DoFn<?, ?>> fnClass,
Method m,
TypeDescriptor<?> inputT,
TypeDescriptor<?> outputT,
FnAnalysisContext fnContext) {
errors.checkArgument(void.class.equals(m.getReturnType()), "Must return void");
Type[] params = m.getGenericParameterTypes();
MethodAnalysisContext methodContext = MethodAnalysisContext.create();
boolean requiresStableInput = m.isAnnotationPresent(DoFn.RequiresStableInput.class);
@Nullable TypeDescriptor<? extends BoundedWindow> windowT = getWindowType(fnClass, m);
List<DoFnSignature.Parameter> extraParameters = new ArrayList<>();
ErrorReporter onWindowExpirationErrors = errors.forMethod(DoFn.OnWindowExpiration.class, m);
for (int i = 0; i < params.length; ++i) {
Parameter parameter =
analyzeExtraParameter(
onWindowExpirationErrors,
fnContext,
methodContext,
fnClass,
ParameterDescription.of(
m,
i,
fnClass.resolveType(params[i]),
Arrays.asList(m.getParameterAnnotations()[i])),
inputT,
outputT);
checkParameterOneOf(errors, parameter, ALLOWED_ON_WINDOW_EXPIRATION_PARAMETERS);
extraParameters.add(parameter);
}
return DoFnSignature.OnWindowExpirationMethod.create(
m, requiresStableInput, windowT, extraParameters);
}
@VisibleForTesting
static DoFnSignature.ProcessElementMethod analyzeProcessElementMethod(
ErrorReporter errors,
TypeDescriptor<? extends DoFn<?, ?>> fnClass,
Method m,
TypeDescriptor<?> inputT,
TypeDescriptor<?> outputT,
FnAnalysisContext fnContext) {
errors.checkArgument(
void.class.equals(m.getReturnType())
|| DoFn.ProcessContinuation.class.equals(m.getReturnType()),
"Must return void or %s",
DoFn.ProcessContinuation.class.getSimpleName());
MethodAnalysisContext methodContext = MethodAnalysisContext.create();
boolean requiresStableInput = m.isAnnotationPresent(DoFn.RequiresStableInput.class);
Type[] params = m.getGenericParameterTypes();
TypeDescriptor<?> trackerT = getTrackerType(fnClass, m);
TypeDescriptor<? extends BoundedWindow> windowT = getWindowType(fnClass, m);
for (int i = 0; i < params.length; ++i) {
Parameter extraParam =
analyzeExtraParameter(
errors.forMethod(DoFn.ProcessElement.class, m),
fnContext,
methodContext,
fnClass,
ParameterDescription.of(
m,
i,
fnClass.resolveType(params[i]),
Arrays.asList(m.getParameterAnnotations()[i])),
inputT,
outputT);
methodContext.addParameter(extraParam);
}
// The allowed parameters depend on whether this DoFn is splittable
if (methodContext.hasRestrictionTrackerParameter()) {
for (Parameter parameter : methodContext.getExtraParameters()) {
checkParameterOneOf(errors, parameter, ALLOWED_SPLITTABLE_PROCESS_ELEMENT_PARAMETERS);
}
} else {
for (Parameter parameter : methodContext.getExtraParameters()) {
checkParameterOneOf(errors, parameter, ALLOWED_NON_SPLITTABLE_PROCESS_ELEMENT_PARAMETERS);
}
}
return DoFnSignature.ProcessElementMethod.create(
m,
methodContext.getExtraParameters(),
requiresStableInput,
trackerT,
windowT,
DoFn.ProcessContinuation.class.equals(m.getReturnType()));
}
private static void checkParameterOneOf(
ErrorReporter errors,
Parameter parameter,
Collection<Class<? extends Parameter>> allowedParameterClasses) {
for (Class<? extends Parameter> paramClass : allowedParameterClasses) {
if (paramClass.isAssignableFrom(parameter.getClass())) {
return;
}
}
// If we get here, none matched
errors.throwIllegalArgument("Illegal parameter type: %s", parameter);
}
private static Parameter analyzeExtraParameter(
ErrorReporter methodErrors,
FnAnalysisContext fnContext,
MethodAnalysisContext methodContext,
TypeDescriptor<? extends DoFn<?, ?>> fnClass,
ParameterDescription param,
TypeDescriptor<?> inputT,
TypeDescriptor<?> outputT) {
TypeDescriptor<?> expectedProcessContextT = doFnProcessContextTypeOf(inputT, outputT);
TypeDescriptor<?> expectedOnTimerContextT = doFnOnTimerContextTypeOf(inputT, outputT);
TypeDescriptor<?> paramT = param.getType();
Class<?> rawType = paramT.getRawType();
ErrorReporter paramErrors = methodErrors.forParameter(param);
if (hasElementAnnotation(param.getAnnotations())) {
if (paramT.equals(TypeDescriptor.of(Row.class)) && !paramT.equals(inputT)) {
// a null id means that there is no registered FieldAccessDescriptor, so we should default
// to all fields. If the input type of the DoFn is already Row, then no need to do
// anything special.
return Parameter.rowParameter(null);
} else {
methodErrors.checkArgument(
paramT.equals(inputT), "@Element argument must have type %s", inputT);
return Parameter.elementParameter(paramT);
}
} else if (hasTimestampAnnotation(param.getAnnotations())) {
methodErrors.checkArgument(
rawType.equals(Instant.class),
"@Timestamp argument must have type org.joda.time.Instant.");
return Parameter.timestampParameter();
} else if (rawType.equals(TimeDomain.class)) {
return Parameter.timeDomainParameter();
} else if (rawType.equals(PaneInfo.class)) {
return Parameter.paneInfoParameter();
} else if (rawType.equals(DoFn.ProcessContext.class)) {
paramErrors.checkArgument(
paramT.equals(expectedProcessContextT),
"ProcessContext argument must have type %s",
formatType(expectedProcessContextT));
return Parameter.processContext();
} else if (rawType.equals(DoFn.OnTimerContext.class)) {
paramErrors.checkArgument(
paramT.equals(expectedOnTimerContextT),
"OnTimerContext argument must have type %s",
formatType(expectedOnTimerContextT));
return Parameter.onTimerContext();
} else if (BoundedWindow.class.isAssignableFrom(rawType)) {
methodErrors.checkArgument(
!methodContext.hasWindowParameter(),
"Multiple %s parameters",
BoundedWindow.class.getSimpleName());
return Parameter.boundedWindow((TypeDescriptor<? extends BoundedWindow>) paramT);
} else if (rawType.equals(OutputReceiver.class)) {
// It's a schema row receiver if it's an OutputReceiver<Row> _and_ the output type is not
// already Row.
boolean schemaRowReceiver =
paramT.equals(outputReceiverTypeOf(TypeDescriptor.of(Row.class)))
&& !outputT.equals(TypeDescriptor.of(Row.class));
if (!schemaRowReceiver) {
TypeDescriptor<?> expectedReceiverT = outputReceiverTypeOf(outputT);
paramErrors.checkArgument(
paramT.equals(expectedReceiverT),
"OutputReceiver should be parameterized by %s",
outputT);
}
return Parameter.outputReceiverParameter(schemaRowReceiver);
} else if (rawType.equals(MultiOutputReceiver.class)) {
return Parameter.taggedOutputReceiverParameter();
} else if (PipelineOptions.class.equals(rawType)) {
methodErrors.checkArgument(
!methodContext.hasPipelineOptionsParamter(),
"Multiple %s parameters",
PipelineOptions.class.getSimpleName());
return Parameter.pipelineOptions();
} else if (RestrictionTracker.class.isAssignableFrom(rawType)) {
methodErrors.checkArgument(
!methodContext.hasRestrictionTrackerParameter(),
"Multiple %s parameters",
RestrictionTracker.class.getSimpleName());
return Parameter.restrictionTracker(paramT);
} else if (rawType.equals(Timer.class)) {
// m.getParameters() is not available until Java 8
String id = getTimerId(param.getAnnotations());
paramErrors.checkArgument(
id != null,
"%s missing %s annotation",
Timer.class.getSimpleName(),
TimerId.class.getSimpleName());
paramErrors.checkArgument(
!methodContext.getTimerParameters().containsKey(id),
"duplicate %s: \"%s\"",
TimerId.class.getSimpleName(),
id);
TimerDeclaration timerDecl = fnContext.getTimerDeclarations().get(id);
paramErrors.checkArgument(
timerDecl != null,
"reference to undeclared %s: \"%s\"",
TimerId.class.getSimpleName(),
id);
paramErrors.checkArgument(
timerDecl.field().getDeclaringClass().equals(param.getMethod().getDeclaringClass()),
"%s %s declared in a different class %s."
+ " Timers may be referenced only in the lexical scope where they are declared.",
TimerId.class.getSimpleName(),
id,
timerDecl.field().getDeclaringClass().getName());
return Parameter.timerParameter(timerDecl);
} else if (State.class.isAssignableFrom(rawType)) {
// m.getParameters() is not available until Java 8
String id = getStateId(param.getAnnotations());
paramErrors.checkArgument(
id != null, "missing %s annotation", DoFn.StateId.class.getSimpleName());
paramErrors.checkArgument(
!methodContext.getStateParameters().containsKey(id),
"duplicate %s: \"%s\"",
DoFn.StateId.class.getSimpleName(),
id);
// By static typing this is already a well-formed State subclass
TypeDescriptor<? extends State> stateType = (TypeDescriptor<? extends State>) param.getType();
StateDeclaration stateDecl = fnContext.getStateDeclarations().get(id);
paramErrors.checkArgument(
stateDecl != null,
"reference to undeclared %s: \"%s\"",
DoFn.StateId.class.getSimpleName(),
id);
paramErrors.checkArgument(
stateDecl.stateType().isSubtypeOf(stateType),
"data type of reference to %s %s must be a supertype of %s",
StateId.class.getSimpleName(),
id,
formatType(stateDecl.stateType()));
paramErrors.checkArgument(
stateDecl.field().getDeclaringClass().equals(param.getMethod().getDeclaringClass()),
"%s %s declared in a different class %s."
+ " State may be referenced only in the class where it is declared.",
StateId.class.getSimpleName(),
id,
stateDecl.field().getDeclaringClass().getName());
return Parameter.stateParameter(stateDecl);
} else if (rawType.equals(Row.class)) {
String id = getFieldAccessId(param.getAnnotations());
paramErrors.checkArgument(
id != null, "missing %s annotation", DoFn.FieldAccess.class.getSimpleName());
FieldAccessDeclaration fieldAccessDeclaration =
fnContext.getFieldAccessDeclarations().get(id);
paramErrors.checkArgument(
fieldAccessDeclaration != null, "No FieldAccessDescriptor defined.");
return Parameter.rowParameter(id);
} else {
List<String> allowedParamTypes =
Arrays.asList(
formatType(new TypeDescriptor<BoundedWindow>() {}),
formatType(new TypeDescriptor<RestrictionTracker<?, ?>>() {}));
paramErrors.throwIllegalArgument(
"%s is not a valid context parameter. Should be one of %s",
formatType(paramT), allowedParamTypes);
// Unreachable
return null;
}
}
@Nullable
private static String getTimerId(List<Annotation> annotations) {
DoFn.TimerId stateId = findFirstOfType(annotations, DoFn.TimerId.class);
return stateId != null ? stateId.value() : null;
}
@Nullable
private static String getStateId(List<Annotation> annotations) {
DoFn.StateId stateId = findFirstOfType(annotations, DoFn.StateId.class);
return stateId != null ? stateId.value() : null;
}
@Nullable
private static String getFieldAccessId(List<Annotation> annotations) {
DoFn.FieldAccess access = findFirstOfType(annotations, DoFn.FieldAccess.class);
return access != null ? access.value() : null;
}
@Nullable
static <T> T findFirstOfType(List<Annotation> annotations, Class<T> clazz) {
Optional<Annotation> annotation =
annotations.stream().filter(a -> a.annotationType().equals(clazz)).findFirst();
return annotation.isPresent() ? (T) annotation.get() : null;
}
private static boolean hasElementAnnotation(List<Annotation> annotations) {
for (Annotation anno : annotations) {
if (anno.annotationType().equals(DoFn.Element.class)) {
return true;
}
}
return false;
}
private static boolean hasTimestampAnnotation(List<Annotation> annotations) {
for (Annotation anno : annotations) {
if (anno.annotationType().equals(DoFn.Timestamp.class)) {
return true;
}
}
return false;
}
@Nullable
private static TypeDescriptor<?> getTrackerType(TypeDescriptor<?> fnClass, Method method) {
Type[] params = method.getGenericParameterTypes();
for (Type param : params) {
TypeDescriptor<?> paramT = fnClass.resolveType(param);
if (RestrictionTracker.class.isAssignableFrom(paramT.getRawType())) {
return paramT;
}
}
return null;
}
@Nullable
private static TypeDescriptor<? extends BoundedWindow> getWindowType(
TypeDescriptor<?> fnClass, Method method) {
Type[] params = method.getGenericParameterTypes();
for (Type param : params) {
TypeDescriptor<?> paramT = fnClass.resolveType(param);
if (BoundedWindow.class.isAssignableFrom(paramT.getRawType())) {
return (TypeDescriptor<? extends BoundedWindow>) paramT;
}
}
return null;
}
@VisibleForTesting
static DoFnSignature.BundleMethod analyzeStartBundleMethod(
ErrorReporter errors,
TypeDescriptor<? extends DoFn<?, ?>> fnT,
Method m,
TypeDescriptor<?> inputT,
TypeDescriptor<?> outputT) {
errors.checkArgument(void.class.equals(m.getReturnType()), "Must return void");
TypeDescriptor<?> expectedContextT = doFnStartBundleContextTypeOf(inputT, outputT);
Type[] params = m.getGenericParameterTypes();
errors.checkArgument(
params.length == 0
|| (params.length == 1 && fnT.resolveType(params[0]).equals(expectedContextT)),
"Must take a single argument of type %s",
formatType(expectedContextT));
return DoFnSignature.BundleMethod.create(m);
}
@VisibleForTesting
static DoFnSignature.BundleMethod analyzeFinishBundleMethod(
ErrorReporter errors,
TypeDescriptor<? extends DoFn<?, ?>> fnT,
Method m,
TypeDescriptor<?> inputT,
TypeDescriptor<?> outputT) {
errors.checkArgument(void.class.equals(m.getReturnType()), "Must return void");
TypeDescriptor<?> expectedContextT = doFnFinishBundleContextTypeOf(inputT, outputT);
Type[] params = m.getGenericParameterTypes();
errors.checkArgument(
params.length == 0
|| (params.length == 1 && fnT.resolveType(params[0]).equals(expectedContextT)),
"Must take a single argument of type %s",
formatType(expectedContextT));
return DoFnSignature.BundleMethod.create(m);
}
private static DoFnSignature.LifecycleMethod analyzeLifecycleMethod(
ErrorReporter errors, Method m) {
errors.checkArgument(void.class.equals(m.getReturnType()), "Must return void");
errors.checkArgument(m.getGenericParameterTypes().length == 0, "Must take zero arguments");
return DoFnSignature.LifecycleMethod.create(m);
}
@VisibleForTesting
static DoFnSignature.GetInitialRestrictionMethod analyzeGetInitialRestrictionMethod(
ErrorReporter errors,
TypeDescriptor<? extends DoFn> fnT,
Method m,
TypeDescriptor<?> inputT) {
// Method is of the form:
// @GetInitialRestriction
// RestrictionT getInitialRestriction(InputT element);
Type[] params = m.getGenericParameterTypes();
errors.checkArgument(
params.length == 1 && fnT.resolveType(params[0]).equals(inputT),
"Must take a single argument of type %s",
formatType(inputT));
return DoFnSignature.GetInitialRestrictionMethod.create(
m, fnT.resolveType(m.getGenericReturnType()));
}
/**
* Generates a {@link TypeDescriptor} for {@code DoFn.OutputReceiver<OutputT>} given {@code
* OutputT}.
*/
private static <OutputT> TypeDescriptor<DoFn.OutputReceiver<OutputT>> outputReceiverTypeOf(
TypeDescriptor<OutputT> outputT) {
return new TypeDescriptor<DoFn.OutputReceiver<OutputT>>() {}.where(
new TypeParameter<OutputT>() {}, outputT);
}
@VisibleForTesting
static DoFnSignature.SplitRestrictionMethod analyzeSplitRestrictionMethod(
ErrorReporter errors,
TypeDescriptor<? extends DoFn> fnT,
Method m,
TypeDescriptor<?> inputT) {
// Method is of the form:
// @SplitRestriction
// void splitRestriction(InputT element, RestrictionT restriction);
errors.checkArgument(void.class.equals(m.getReturnType()), "Must return void");
Type[] params = m.getGenericParameterTypes();
errors.checkArgument(params.length == 3, "Must have exactly 3 arguments");
errors.checkArgument(
fnT.resolveType(params[0]).equals(inputT),
"First argument must be the element type %s",
formatType(inputT));
TypeDescriptor<?> restrictionT = fnT.resolveType(params[1]);
TypeDescriptor<?> receiverT = fnT.resolveType(params[2]);
TypeDescriptor<?> expectedReceiverT = outputReceiverTypeOf(restrictionT);
errors.checkArgument(
receiverT.equals(expectedReceiverT),
"Third argument must be %s, but is %s",
formatType(expectedReceiverT),
formatType(receiverT));
return DoFnSignature.SplitRestrictionMethod.create(m, restrictionT);
}
private static ImmutableMap<String, TimerDeclaration> analyzeTimerDeclarations(
ErrorReporter errors, Class<?> fnClazz) {
Map<String, DoFnSignature.TimerDeclaration> declarations = new HashMap<>();
for (Field field : declaredFieldsWithAnnotation(DoFn.TimerId.class, fnClazz, DoFn.class)) {
// TimerSpec fields may generally be private, but will be accessed via the signature
field.setAccessible(true);
String id = field.getAnnotation(DoFn.TimerId.class).value();
validateTimerField(errors, declarations, id, field);
declarations.put(id, DoFnSignature.TimerDeclaration.create(id, field));
}
return ImmutableMap.copyOf(declarations);
}
/**
* Returns successfully if the field is valid, otherwise throws an exception via its {@link
* ErrorReporter} parameter describing validation failures for the timer declaration.
*/
private static void validateTimerField(
ErrorReporter errors, Map<String, TimerDeclaration> declarations, String id, Field field) {
if (declarations.containsKey(id)) {
errors.throwIllegalArgument(
"Duplicate %s \"%s\", used on both of [%s] and [%s]",
DoFn.TimerId.class.getSimpleName(),
id,
field.toString(),
declarations.get(id).field().toString());
}
Class<?> timerSpecRawType = field.getType();
if (!(timerSpecRawType.equals(TimerSpec.class))) {
errors.throwIllegalArgument(
"%s annotation on non-%s field [%s]",
DoFn.TimerId.class.getSimpleName(), TimerSpec.class.getSimpleName(), field.toString());
}
if (!Modifier.isFinal(field.getModifiers())) {
errors.throwIllegalArgument(
"Non-final field %s annotated with %s. Timer declarations must be final.",
field.toString(), DoFn.TimerId.class.getSimpleName());
}
}
/** Generates a {@link TypeDescriptor} for {@code Coder<T>} given {@code T}. */
private static <T> TypeDescriptor<Coder<T>> coderTypeOf(TypeDescriptor<T> elementT) {
return new TypeDescriptor<Coder<T>>() {}.where(new TypeParameter<T>() {}, elementT);
}
@VisibleForTesting
static DoFnSignature.GetRestrictionCoderMethod analyzeGetRestrictionCoderMethod(
ErrorReporter errors, TypeDescriptor<? extends DoFn> fnT, Method m) {
errors.checkArgument(m.getParameterTypes().length == 0, "Must have zero arguments");
TypeDescriptor<?> resT = fnT.resolveType(m.getGenericReturnType());
errors.checkArgument(
resT.isSubtypeOf(TypeDescriptor.of(Coder.class)),
"Must return a Coder, but returns %s",
formatType(resT));
return DoFnSignature.GetRestrictionCoderMethod.create(m, resT);
}
/**
* Generates a {@link TypeDescriptor} for {@code RestrictionTracker<RestrictionT>} given {@code
* RestrictionT}.
*/
private static <RestrictionT>
TypeDescriptor<RestrictionTracker<RestrictionT, ?>> restrictionTrackerTypeOf(
TypeDescriptor<RestrictionT> restrictionT) {
return new TypeDescriptor<RestrictionTracker<RestrictionT, ?>>() {}.where(
new TypeParameter<RestrictionT>() {}, restrictionT);
}
@VisibleForTesting
static DoFnSignature.NewTrackerMethod analyzeNewTrackerMethod(
ErrorReporter errors, TypeDescriptor<? extends DoFn> fnT, Method m) {
// Method is of the form:
// @NewTracker
// TrackerT newTracker(RestrictionT restriction);
Type[] params = m.getGenericParameterTypes();
errors.checkArgument(params.length == 1, "Must have a single argument");
TypeDescriptor<?> restrictionT = fnT.resolveType(params[0]);
TypeDescriptor<?> trackerT = fnT.resolveType(m.getGenericReturnType());
TypeDescriptor<?> expectedTrackerT = restrictionTrackerTypeOf(restrictionT);
errors.checkArgument(
trackerT.isSubtypeOf(expectedTrackerT),
"Returns %s, but must return a subtype of %s",
formatType(trackerT),
formatType(expectedTrackerT));
return DoFnSignature.NewTrackerMethod.create(m, restrictionT, trackerT);
}
private static Collection<Method> declaredMethodsWithAnnotation(
Class<? extends Annotation> anno, Class<?> startClass, Class<?> stopClass) {
return declaredMembersWithAnnotation(anno, startClass, stopClass, GET_METHODS);
}
private static Collection<Field> declaredFieldsWithAnnotation(
Class<? extends Annotation> anno, Class<?> startClass, Class<?> stopClass) {
return declaredMembersWithAnnotation(anno, startClass, stopClass, GET_FIELDS);
}
private interface MemberGetter<MemberT> {
MemberT[] getMembers(Class<?> clazz);
}
private static final MemberGetter<Method> GET_METHODS = Class::getDeclaredMethods;
private static final MemberGetter<Field> GET_FIELDS = Class::getDeclaredFields;
private static <MemberT extends AnnotatedElement>
Collection<MemberT> declaredMembersWithAnnotation(
Class<? extends Annotation> anno,
Class<?> startClass,
Class<?> stopClass,
MemberGetter<MemberT> getter) {
Collection<MemberT> matches = new ArrayList<>();
Class<?> clazz = startClass;
LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<>();
// First, find all declared methods on the startClass and parents (up to stopClass)
while (clazz != null && !clazz.equals(stopClass)) {
for (MemberT member : getter.getMembers(clazz)) {
if (member.isAnnotationPresent(anno)) {
matches.add(member);
}
}
// Add all interfaces, including transitive
for (TypeDescriptor<?> iface : TypeDescriptor.of(clazz).getInterfaces()) {
interfaces.add(iface.getRawType());
}
clazz = clazz.getSuperclass();
}
// Now, iterate over all the discovered interfaces
for (Class<?> iface : interfaces) {
for (MemberT member : getter.getMembers(iface)) {
if (member.isAnnotationPresent(anno)) {
matches.add(member);
}
}
}
return matches;
}
private static Map<String, DoFnSignature.FieldAccessDeclaration> analyzeFieldAccessDeclaration(
ErrorReporter errors, Class<?> fnClazz) {
Map<String, FieldAccessDeclaration> fieldAccessDeclarations = new HashMap<>();
for (Field field : declaredFieldsWithAnnotation(DoFn.FieldAccess.class, fnClazz, DoFn.class)) {
field.setAccessible(true);
DoFn.FieldAccess fieldAccessAnnotation = field.getAnnotation(DoFn.FieldAccess.class);
if (!Modifier.isFinal(field.getModifiers())) {
errors.throwIllegalArgument(
"Non-final field %s annotated with %s. Field access declarations must be final.",
field.toString(), DoFn.FieldAccess.class.getSimpleName());
continue;
}
Class<?> fieldAccessRawType = field.getType();
if (!fieldAccessRawType.equals(FieldAccessDescriptor.class)) {
errors.throwIllegalArgument(
"Field %s annotated with %s, but the value was not of type %s",
field.toString(),
DoFn.FieldAccess.class.getSimpleName(),
FieldAccessDescriptor.class.getSimpleName());
}
fieldAccessDeclarations.put(
fieldAccessAnnotation.value(),
FieldAccessDeclaration.create(fieldAccessAnnotation.value(), field));
}
return fieldAccessDeclarations;
}
private static Map<String, DoFnSignature.StateDeclaration> analyzeStateDeclarations(
ErrorReporter errors, Class<?> fnClazz) {
Map<String, DoFnSignature.StateDeclaration> declarations = new HashMap<>();
for (Field field : declaredFieldsWithAnnotation(DoFn.StateId.class, fnClazz, DoFn.class)) {
// StateSpec fields may generally be private, but will be accessed via the signature
field.setAccessible(true);
String id = field.getAnnotation(DoFn.StateId.class).value();
if (declarations.containsKey(id)) {
errors.throwIllegalArgument(
"Duplicate %s \"%s\", used on both of [%s] and [%s]",
DoFn.StateId.class.getSimpleName(),
id,
field.toString(),
declarations.get(id).field().toString());
continue;
}
Class<?> stateSpecRawType = field.getType();
if (!(TypeDescriptor.of(stateSpecRawType).isSubtypeOf(TypeDescriptor.of(StateSpec.class)))) {
errors.throwIllegalArgument(
"%s annotation on non-%s field [%s] that has class %s",
DoFn.StateId.class.getSimpleName(),
StateSpec.class.getSimpleName(),
field.toString(),
stateSpecRawType.getName());
continue;
}
if (!Modifier.isFinal(field.getModifiers())) {
errors.throwIllegalArgument(
"Non-final field %s annotated with %s. State declarations must be final.",
field.toString(), DoFn.StateId.class.getSimpleName());
continue;
}
Type stateSpecType = field.getGenericType();
// A type descriptor for whatever type the @StateId-annotated class has, which
// must be some subtype of StateSpec
TypeDescriptor<? extends StateSpec<?>> stateSpecSubclassTypeDescriptor =
(TypeDescriptor) TypeDescriptor.of(stateSpecType);
// A type descriptor for StateSpec, with the generic type parameters filled
// in according to the specialization of the subclass (or just straight params)
TypeDescriptor<StateSpec<?>> stateSpecTypeDescriptor =
(TypeDescriptor) stateSpecSubclassTypeDescriptor.getSupertype(StateSpec.class);
// The type of the state, which may still have free type variables from the
// context
Type unresolvedStateType =
((ParameterizedType) stateSpecTypeDescriptor.getType()).getActualTypeArguments()[0];
// By static typing this is already a well-formed State subclass
TypeDescriptor<? extends State> stateType =
(TypeDescriptor<? extends State>)
TypeDescriptor.of(fnClazz).resolveType(unresolvedStateType);
declarations.put(id, DoFnSignature.StateDeclaration.create(id, field, stateType));
}
return ImmutableMap.copyOf(declarations);
}
@Nullable
private static Method findAnnotatedMethod(
ErrorReporter errors, Class<? extends Annotation> anno, Class<?> fnClazz, boolean required) {
Collection<Method> matches = declaredMethodsWithAnnotation(anno, fnClazz, DoFn.class);
if (matches.isEmpty()) {
errors.checkArgument(!required, "No method annotated with @%s found", anno.getSimpleName());
return null;
}
// If we have at least one match, then either it should be the only match
// or it should be an extension of the other matches (which came from parent
// classes).
Method first = matches.iterator().next();
for (Method other : matches) {
errors.checkArgument(
first.getName().equals(other.getName())
&& Arrays.equals(first.getParameterTypes(), other.getParameterTypes()),
"Found multiple methods annotated with @%s. [%s] and [%s]",
anno.getSimpleName(),
format(first),
format(other));
}
ErrorReporter methodErrors = errors.forMethod(anno, first);
// We need to be able to call it. We require it is public.
methodErrors.checkArgument((first.getModifiers() & Modifier.PUBLIC) != 0, "Must be public");
// And make sure its not static.
methodErrors.checkArgument((first.getModifiers() & Modifier.STATIC) == 0, "Must not be static");
return first;
}
private static String format(Method method) {
return ReflectHelpers.METHOD_FORMATTER.apply(method);
}
private static String formatType(TypeDescriptor<?> t) {
return ReflectHelpers.TYPE_SIMPLE_DESCRIPTION.apply(t.getType());
}
static class ErrorReporter {
private final String label;
ErrorReporter(@Nullable ErrorReporter root, String label) {
this.label = (root == null) ? label : String.format("%s, %s", root.label, label);
}
ErrorReporter forMethod(Class<? extends Annotation> annotation, Method method) {
return new ErrorReporter(
this,
String.format(
"@%s %s",
annotation.getSimpleName(), (method == null) ? "(absent)" : format(method)));
}
ErrorReporter forParameter(ParameterDescription param) {
return new ErrorReporter(
this,
String.format(
"parameter of type %s at index %s", formatType(param.getType()), param.getIndex()));
}
void throwIllegalArgument(String message, Object... args) {
throw new IllegalArgumentException(label + ": " + String.format(message, args));
}
public void checkArgument(boolean condition, String message, Object... args) {
if (!condition) {
throwIllegalArgument(message, args);
}
}
public void checkNotNull(Object value, String message, Object... args) {
if (value == null) {
throwIllegalArgument(message, args);
}
}
}
public static StateSpec<?> getStateSpecOrThrow(
StateDeclaration stateDeclaration, DoFn<?, ?> target) {
try {
Object fieldValue = stateDeclaration.field().get(target);
checkState(
fieldValue instanceof StateSpec,
"Malformed %s class %s: state declaration field %s does not have type %s.",
DoFn.class.getSimpleName(),
target.getClass().getName(),
stateDeclaration.field().getName(),
StateSpec.class);
return (StateSpec<?>) stateDeclaration.field().get(target);
} catch (IllegalAccessException exc) {
throw new RuntimeException(
String.format(
"Malformed %s class %s: state declaration field %s is not accessible.",
DoFn.class.getSimpleName(),
target.getClass().getName(),
stateDeclaration.field().getName()));
}
}
public static TimerSpec getTimerSpecOrThrow(
TimerDeclaration timerDeclaration, DoFn<?, ?> target) {
try {
Object fieldValue = timerDeclaration.field().get(target);
checkState(
fieldValue instanceof TimerSpec,
"Malformed %s class %s: timer declaration field %s does not have type %s.",
DoFn.class.getSimpleName(),
target.getClass().getName(),
timerDeclaration.field().getName(),
TimerSpec.class);
return (TimerSpec) timerDeclaration.field().get(target);
} catch (IllegalAccessException exc) {
throw new RuntimeException(
String.format(
"Malformed %s class %s: timer declaration field %s is not accessible.",
DoFn.class.getSimpleName(),
target.getClass().getName(),
timerDeclaration.field().getName()));
}
}
}
| |
package com.untamedears.JukeAlert.manager;
import static com.untamedears.JukeAlert.util.Utility.setDebugging;
import org.bukkit.configuration.file.FileConfiguration;
import com.untamedears.JukeAlert.JukeAlert;
public class ConfigManager
{
private JukeAlert plugin;
private String username;
private String host;
private String password;
private String database;
private String prefix;
private int port;
private int defaultCuboidSize;
private int logsPerPage;
private int daysFromLastAdminVisitForLoggedSnitchCulling;
private int daysFromLastAdminVisitForNonLoggedSnitchCulling;
private boolean snitchEntryCullingEnabled;
private boolean allowTriggeringLevers;
private int maxEntryCount;
private int minEntryLifetimeDays;
private int maxEntryLifetimeDays;
private boolean snitchCullingEnabled;
private int maxSnitchLifetimeDays;
private Double maxAlertDistanceAll = null;
private Double maxAlertDistanceNs = null;
private int maxPlayerAlertCount;
private boolean taxReinforcementPerAlert;
private int alertRateLimit;
private boolean enableInvisibility;
private boolean toggleRestartCheckGroup;
private boolean displayOwnerOnBreak;
private boolean softDelete;
private boolean multipleWorldSupport = false;
private boolean broadcastAllServers;
private FileConfiguration config;
public ConfigManager()
{
this.plugin = JukeAlert.getInstance();
this.config = plugin.getConfig();
plugin.saveDefaultConfig();
plugin.reloadConfig();
this.config = plugin.getConfig();
this.load();
}
/**
* Load configuration
*/
private void load()
{
username = config.getString("mysql.username");
host = config.getString("mysql.host");
password = config.getString("mysql.password");
database = config.getString("mysql.database");
prefix = config.getString("mysql.prefix");
port = config.getInt("mysql.port");
setDefaultCuboidSize(config.getInt("settings.defaultCuboidSize"));
logsPerPage = config.getInt("settings.logsPerPage");
daysFromLastAdminVisitForLoggedSnitchCulling = config.getInt("settings.daysFromLastAdminVisitForLoggedSnitchCulling");
daysFromLastAdminVisitForNonLoggedSnitchCulling = config.getInt("settings.daysFromLastAdminVisitForNonLoggedSnitchCulling");
allowTriggeringLevers = config.getBoolean("settings.allowTriggeringLevers",false);
setDebugging(config.getBoolean("settings.debugging"));
if (config.isDouble("settings.max_alert_distance")) {
maxAlertDistanceAll = config.getDouble("settings.max_alert_distance");
}
if (config.isDouble("settings.max_alert_distance_ns")) {
maxAlertDistanceNs = config.getDouble("settings.max_alert_distance_ns");
}
maxPlayerAlertCount = config.getInt("settings.max_player_alert_count", Integer.MAX_VALUE);
taxReinforcementPerAlert = config.getBoolean("settings.tax_reinforcement_per_alert");
snitchEntryCullingEnabled = config.getBoolean("entryculling.enabled", true);
maxEntryCount = config.getInt("entryculling.maxcount", 200);
minEntryLifetimeDays = config.getInt("entryculling.minlifetime", 1);
maxEntryLifetimeDays = config.getInt("entryculling.maxlifetime", 8);
snitchCullingEnabled = config.getBoolean("snitchculling.enabled", false);
maxSnitchLifetimeDays = config.getInt("snitchculling.maxlifetime", 21);
alertRateLimit = config.getInt("settings.alertratelimit", 70);
enableInvisibility = config.getBoolean("settings.enableinvisiblity", false);
toggleRestartCheckGroup = config.getBoolean("settings.togglerestartgroupcheck", false);
displayOwnerOnBreak = config.getBoolean("settings.displayOwnerOnSnitchBreak", true);
softDelete = config.getBoolean("settings.softDelete", true);
multipleWorldSupport = config.getBoolean("settings.multipleWorldSupport", false);
broadcastAllServers = config.getBoolean("mercury.broadcastallservers", false);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public int getDefaultCuboidSize() {
return defaultCuboidSize;
}
public void setDefaultCuboidSize(int defaultCuboidSize) {
this.defaultCuboidSize = defaultCuboidSize;
}
public int getLogsPerPage() {
return logsPerPage;
}
public int getDaysFromLastAdminVisitForNonLoggedSnitchCulling() {
return daysFromLastAdminVisitForNonLoggedSnitchCulling;
}
public int getDaysFromLastAdminVisitForLoggedSnitchCulling() {
return daysFromLastAdminVisitForLoggedSnitchCulling;
}
public Boolean getAllowTriggeringLevers() {
return allowTriggeringLevers;
}
public void setLogsPerPage(int logsPerPage) {
this.logsPerPage = logsPerPage;
}
public boolean getSnitchEntryCullingEnabled() {
return snitchEntryCullingEnabled;
}
public int getMaxSnitchEntryCount() {
return maxEntryCount;
}
public int getMinSnitchEntryLifetime() {
return minEntryLifetimeDays;
}
public int getMaxSnitchEntryLifetime() {
return maxEntryLifetimeDays;
}
public boolean getSnitchCullingEnabled() {
return snitchCullingEnabled;
}
public int getMaxSnitchLifetime() {
return maxSnitchLifetimeDays;
}
public Double getMaxAlertDistanceAll() {
return maxAlertDistanceAll;
}
public Double getMaxAlertDistanceNs() {
return maxAlertDistanceNs;
}
public int getMaxPlayerAlertCount() {
return maxPlayerAlertCount;
}
public boolean getTaxReinforcementPerAlert() {
return taxReinforcementPerAlert;
}
public int getAlertRateLimit() {
return alertRateLimit;
}
public boolean getInvisibilityEnabled(){
return enableInvisibility;
}
public boolean isDisplayOwnerOnBreak() {
return displayOwnerOnBreak;
}
public boolean isSoftDelete() {
return softDelete;
}
public boolean getMultipleWorldSupport() {
return multipleWorldSupport;
}
public boolean getToggleRestartCheckGroup(){
return toggleRestartCheckGroup;
}
public boolean getBroadcastAllServers() {
return broadcastAllServers;
}
}
| |
/*
* 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.tinkerpop.gremlin.server.op;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;
import org.apache.tinkerpop.gremlin.driver.MessageSerializer;
import org.apache.tinkerpop.gremlin.driver.Tokens;
import org.apache.tinkerpop.gremlin.driver.message.RequestMessage;
import org.apache.tinkerpop.gremlin.driver.message.ResponseMessage;
import org.apache.tinkerpop.gremlin.driver.message.ResponseStatusCode;
import org.apache.tinkerpop.gremlin.driver.ser.MessageTextSerializer;
import org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor;
import org.apache.tinkerpop.gremlin.groovy.jsr223.customizer.TimedInterruptTimeoutException;
import org.apache.tinkerpop.gremlin.server.GraphManager;
import org.apache.tinkerpop.gremlin.server.handler.Frame;
import org.apache.tinkerpop.gremlin.server.handler.GremlinResponseFrameEncoder;
import org.apache.tinkerpop.gremlin.server.handler.StateKey;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.server.Context;
import org.apache.tinkerpop.gremlin.server.GremlinServer;
import org.apache.tinkerpop.gremlin.server.OpProcessor;
import org.apache.tinkerpop.gremlin.server.Settings;
import org.apache.tinkerpop.gremlin.server.util.MetricManager;
import org.apache.tinkerpop.gremlin.util.function.ThrowingConsumer;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import static com.codahale.metrics.MetricRegistry.name;
/**
* A base {@link org.apache.tinkerpop.gremlin.server.OpProcessor} implementation that helps with operations that deal
* with script evaluation functions.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public abstract class AbstractEvalOpProcessor implements OpProcessor {
private static final Logger logger = LoggerFactory.getLogger(AbstractEvalOpProcessor.class);
public static final Timer evalOpTimer = MetricManager.INSTANCE.getTimer(name(GremlinServer.class, "op", "eval"));
/**
* Captures the "error" count as a reportable metric for Gremlin Server.
*
* @deprecated As of release 3.1.1-incubating, not replaced. Direct usage is discouraged with sub-classes as
* error counts are captured more globally for error messages written down the pipeline to
* {@link GremlinResponseFrameEncoder}.
*/
@Deprecated
static final Meter errorMeter = MetricManager.INSTANCE.getMeter(name(GremlinServer.class, "errors"));
/**
* Regex for validating that binding variables.
*/
protected static final Pattern validBindingName = Pattern.compile("[a-zA-Z$_][a-zA-Z0-9$_]*");
/**
* This may or may not be the full set of invalid binding keys. It is dependent on the static imports made to
* Gremlin Server. This should get rid of the worst offenders though and provide a good message back to the
* calling client.
* <p/>
* Use of {@code toUpperCase()} on the accessor values of {@link T} solves an issue where the {@code ScriptEngine}
* ignores private scope on {@link T} and imports static fields.
*/
private static final List<String> invalidBindingsKeys = Arrays.asList(
T.id.getAccessor(), T.key.getAccessor(),
T.label.getAccessor(), T.value.getAccessor(),
T.id.getAccessor().toUpperCase(), T.key.getAccessor().toUpperCase(),
T.label.getAccessor().toUpperCase(), T.value.getAccessor().toUpperCase());
private static final String invalidBindingKeysJoined = String.join(",", invalidBindingsKeys);
protected final boolean manageTransactions;
protected AbstractEvalOpProcessor(final boolean manageTransactions) {
this.manageTransactions = manageTransactions;
}
/**
* Provides an operation for evaluating a Gremlin script.
*/
public abstract ThrowingConsumer<Context> getEvalOp();
/**
* A sub-class may have additional "ops" that it will service. Calls to {@link #select(Context)} that are not
* handled will be passed to this method to see if the sub-class can service the requested op code.
*/
public abstract Optional<ThrowingConsumer<Context>> selectOther(final RequestMessage requestMessage) throws OpProcessorException;
@Override
public ThrowingConsumer<Context> select(final Context ctx) throws OpProcessorException {
final RequestMessage message = ctx.getRequestMessage();
logger.debug("Selecting processor for RequestMessage {}", message);
final ThrowingConsumer<Context> op;
switch (message.getOp()) {
case Tokens.OPS_EVAL:
op = validateEvalMessage(message).orElse(getEvalOp());
break;
case Tokens.OPS_INVALID:
final String msgInvalid = String.format("Message could not be parsed. Check the format of the request. [%s]", message);
throw new OpProcessorException(msgInvalid, ResponseMessage.build(message).code(ResponseStatusCode.REQUEST_ERROR_MALFORMED_REQUEST).statusMessage(msgInvalid).create());
default:
op = selectOther(message).orElseThrow(() -> {
final String msgDefault = String.format("Message with op code [%s] is not recognized.", message.getOp());
return new OpProcessorException(msgDefault, ResponseMessage.build(message).code(ResponseStatusCode.REQUEST_ERROR_MALFORMED_REQUEST).statusMessage(msgDefault).create());
});
}
return op;
}
protected Optional<ThrowingConsumer<Context>> validateEvalMessage(final RequestMessage message) throws OpProcessorException {
if (!message.optionalArgs(Tokens.ARGS_GREMLIN).isPresent()) {
final String msg = String.format("A message with an [%s] op code requires a [%s] argument.", Tokens.OPS_EVAL, Tokens.ARGS_GREMLIN);
throw new OpProcessorException(msg, ResponseMessage.build(message).code(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS).statusMessage(msg).create());
}
if (message.optionalArgs(Tokens.ARGS_BINDINGS).isPresent()) {
final Map bindings = (Map) message.getArgs().get(Tokens.ARGS_BINDINGS);
if (bindings.keySet().stream().anyMatch(k -> null == k || !(k instanceof String))) {
final String msg = String.format("The [%s] message is using one or more invalid binding keys - they must be of type String and cannot be null", Tokens.OPS_EVAL);
throw new OpProcessorException(msg, ResponseMessage.build(message).code(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS).statusMessage(msg).create());
}
if (bindings.keySet().stream().anyMatch(invalidBindingsKeys::contains)) {
final String msg = String.format("The [%s] message is using at least one of the invalid binding key of [%s]. It conflicts with standard static imports to Gremlin Server.", Tokens.OPS_EVAL, invalidBindingKeysJoined);
throw new OpProcessorException(msg, ResponseMessage.build(message).code(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS).statusMessage(msg).create());
}
}
return Optional.empty();
}
/**
* A generalized implementation of the "eval" operation. It handles script evaluation and iteration of results
* so as to write {@link ResponseMessage} objects down the Netty pipeline. It also handles script timeouts,
* iteration timeouts, metrics and building bindings. Note that result iteration is delegated to the
* {@link #handleIterator} method, so those extending this class could override that method for better control
* over result iteration.
*
* @param context The current Gremlin Server {@link Context}
* @param gremlinExecutorSupplier A function that returns the {@link GremlinExecutor} to use in executing the
* script evaluation.
* @param bindingsSupplier A function that returns the {@link Bindings} to provide to the
* {@link GremlinExecutor#eval} method.
*/
protected void evalOpInternal(final Context context, final Supplier<GremlinExecutor> gremlinExecutorSupplier,
final BindingSupplier bindingsSupplier) throws OpProcessorException {
final Timer.Context timerContext = evalOpTimer.time();
final ChannelHandlerContext ctx = context.getChannelHandlerContext();
final RequestMessage msg = context.getRequestMessage();
final GremlinExecutor gremlinExecutor = gremlinExecutorSupplier.get();
final Settings settings = context.getSettings();
final Map<String, Object> args = msg.getArgs();
final String script = (String) args.get(Tokens.ARGS_GREMLIN);
final String language = args.containsKey(Tokens.ARGS_LANGUAGE) ? (String) args.get(Tokens.ARGS_LANGUAGE) : null;
final Bindings bindings = new SimpleBindings();
// sessionless requests are always transaction managed, but in-session requests are configurable.
final boolean managedTransactionsForRequest = manageTransactions ?
true : (Boolean) args.getOrDefault(Tokens.ARGS_MANAGE_TRANSACTION, false);
final GremlinExecutor.LifeCycle lifeCycle = GremlinExecutor.LifeCycle.build()
.beforeEval(b -> {
try {
b.putAll(bindingsSupplier.get());
} catch (OpProcessorException ope) {
// this should bubble up in the GremlinExecutor properly as the RuntimeException will be
// unwrapped and the root cause thrown
throw new RuntimeException(ope);
}
})
.withResult(o -> {
final Iterator itty = IteratorUtils.asIterator(o);
logger.debug("Preparing to iterate results from - {} - in thread [{}]", msg, Thread.currentThread().getName());
try {
handleIterator(context, itty);
} catch (TimeoutException ex) {
final String errorMessage = String.format("Response iteration exceeded the configured threshold for request [%s] - %s", msg, ex.getMessage());
logger.warn(errorMessage);
ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT).statusMessage(errorMessage).create());
if (managedTransactionsForRequest) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement);
} catch (Exception ex) {
logger.warn(String.format("Exception processing a script on request [%s].", msg), ex);
ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR).statusMessage(ex.getMessage()).create());
if (managedTransactionsForRequest) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement);
}
}).create();
final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(script, language, bindings, lifeCycle);
evalFuture.handle((v, t) -> {
timerContext.stop();
if (t != null) {
if (t instanceof OpProcessorException) {
ctx.writeAndFlush(((OpProcessorException) t).getResponseMessage());
} else if (t instanceof TimedInterruptTimeoutException) {
// occurs when the TimedInterruptCustomizerProvider is in play
final String errorMessage = String.format("A timeout occurred within the script during evaluation of [%s] - consider increasing the limit given to TimedInterruptCustomizerProvider", msg);
logger.warn(errorMessage);
ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT).statusMessage("Timeout during script evaluation triggered by TimedInterruptCustomizerProvider").create());
} else if (t instanceof TimeoutException) {
final String errorMessage = String.format("Response evaluation exceeded the configured threshold for request [%s] - %s", msg, t.getMessage());
logger.warn(errorMessage, t);
ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_TIMEOUT).statusMessage(t.getMessage()).create());
} else {
logger.warn(String.format("Exception processing a script on request [%s].", msg), t);
ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION).statusMessage(t.getMessage()).create());
}
}
return null;
});
}
/**
* Called by {@link #evalOpInternal} when iterating a result set. Implementers should respect the
* {@link Settings#serializedResponseTimeout} configuration and break the serialization process if
* it begins to take too long to do so, throwing a {@link java.util.concurrent.TimeoutException} in such
* cases.
*
* @param context The Gremlin Server {@link Context} object containing settings, request message, etc.
* @param itty The result to iterator
* @throws TimeoutException if the time taken to serialize the entire result set exceeds the allowable time.
*/
protected void handleIterator(final Context context, final Iterator itty) throws TimeoutException, InterruptedException {
final ChannelHandlerContext ctx = context.getChannelHandlerContext();
final RequestMessage msg = context.getRequestMessage();
final Settings settings = context.getSettings();
final MessageSerializer serializer = ctx.channel().attr(StateKey.SERIALIZER).get();
final boolean useBinary = ctx.channel().attr(StateKey.USE_BINARY).get();
boolean warnOnce = false;
// sessionless requests are always transaction managed, but in-session requests are configurable.
final boolean managedTransactionsForRequest = manageTransactions ?
true : (Boolean) msg.getArgs().getOrDefault(Tokens.ARGS_MANAGE_TRANSACTION, false);
// we have an empty iterator - happens on stuff like: g.V().iterate()
if (!itty.hasNext()) {
// as there is nothing left to iterate if we are transaction managed then we should execute a
// commit here before we send back a NO_CONTENT which implies success
if (managedTransactionsForRequest) attemptCommit(msg, context.getGraphManager(), settings.strictTransactionManagement);
ctx.writeAndFlush(ResponseMessage.build(msg)
.code(ResponseStatusCode.NO_CONTENT)
.create());
return;
}
// timer for the total serialization time
final StopWatch stopWatch = new StopWatch();
stopWatch.start();
// the batch size can be overridden by the request
final int resultIterationBatchSize = (Integer) msg.optionalArgs(Tokens.ARGS_BATCH_SIZE)
.orElse(settings.resultIterationBatchSize);
List<Object> aggregate = new ArrayList<>(resultIterationBatchSize);
// use an external control to manage the loop as opposed to just checking hasNext() in the while. this
// prevent situations where auto transactions create a new transaction after calls to commit() withing
// the loop on calls to hasNext().
boolean hasMore = itty.hasNext();
while (hasMore) {
if (Thread.interrupted()) throw new InterruptedException();
// have to check the aggregate size because it is possible that the channel is not writeable (below)
// so iterating next() if the message is not written and flushed would bump the aggregate size beyond
// the expected resultIterationBatchSize. Total serialization time for the response remains in
// effect so if the client is "slow" it may simply timeout.
if (aggregate.size() < resultIterationBatchSize) aggregate.add(itty.next());
// send back a page of results if batch size is met or if it's the end of the results being iterated.
// also check writeability of the channel to prevent OOME for slow clients.
if (ctx.channel().isWritable()) {
if (aggregate.size() == resultIterationBatchSize || !itty.hasNext()) {
final ResponseStatusCode code = itty.hasNext() ? ResponseStatusCode.PARTIAL_CONTENT : ResponseStatusCode.SUCCESS;
// serialize here because in sessionless requests the serialization must occur in the same
// thread as the eval. as eval occurs in the GremlinExecutor there's no way to get back to the
// thread that processed the eval of the script so, we have to push serialization down into that
Frame frame;
try {
frame = makeFrame(ctx, msg, serializer, useBinary, aggregate, code);
} catch (Exception ex) {
// exception is handled in makeFrame() - serialization error gets written back to driver
// at that point
if (manageTransactions) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement);
break;
}
// only need to reset the aggregation list if there's more stuff to write
if (itty.hasNext())
aggregate = new ArrayList<>(resultIterationBatchSize);
else {
// iteration and serialization are both complete which means this finished successfully. note that
// errors internal to script eval or timeout will rollback given GremlinServer's global configurations.
// local errors will get rolledback below because the exceptions aren't thrown in those cases to be
// caught by the GremlinExecutor for global rollback logic. this only needs to be committed if
// there are no more items to iterate and serialization is complete
if (managedTransactionsForRequest) attemptCommit(msg, context.getGraphManager(), settings.strictTransactionManagement);
// exit the result iteration loop as there are no more results left. using this external control
// because of the above commit. some graphs may open a new transaction on the call to
// hasNext()
hasMore = false;
}
// the flush is called after the commit has potentially occurred. in this way, if a commit was
// required then it will be 100% complete before the client receives it. the "frame" at this point
// should have completely detached objects from the transaction (i.e. serialization has occurred)
// so a new one should not be opened on the flush down the netty pipeline
ctx.writeAndFlush(frame);
}
} else {
// don't keep triggering this warning over and over again for the same request
if (!warnOnce) {
logger.warn("Pausing response writing as writeBufferHighWaterMark exceeded on {} - writing will continue once client has caught up", msg);
warnOnce = true;
}
// since the client is lagging we can hold here for a period of time for the client to catch up.
// this isn't blocking the IO thread - just a worker.
TimeUnit.MILLISECONDS.sleep(10);
}
stopWatch.split();
if (stopWatch.getSplitTime() > settings.serializedResponseTimeout) {
final String timeoutMsg = String.format("Serialization of the entire response exceeded the 'serializeResponseTimeout' setting %s",
warnOnce ? "[Gremlin Server paused writes to client as messages were not being consumed quickly enough]" : "");
throw new TimeoutException(timeoutMsg.trim());
}
stopWatch.unsplit();
}
stopWatch.stop();
}
private static Frame makeFrame(final ChannelHandlerContext ctx, final RequestMessage msg,
final MessageSerializer serializer, final boolean useBinary, List<Object> aggregate,
final ResponseStatusCode code) throws Exception {
try {
if (useBinary) {
return new Frame(serializer.serializeResponseAsBinary(ResponseMessage.build(msg)
.code(code)
.result(aggregate).create(), ctx.alloc()));
} else {
// the expectation is that the GremlinTextRequestDecoder will have placed a MessageTextSerializer
// instance on the channel.
final MessageTextSerializer textSerializer = (MessageTextSerializer) serializer;
return new Frame(textSerializer.serializeResponseAsString(ResponseMessage.build(msg)
.code(code)
.result(aggregate).create()));
}
} catch (Exception ex) {
logger.warn("The result [{}] in the request {} could not be serialized and returned.", aggregate, msg.getRequestId(), ex);
final String errorMessage = String.format("Error during serialization: %s",
ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage());
final ResponseMessage error = ResponseMessage.build(msg.getRequestId())
.statusMessage(errorMessage)
.code(ResponseStatusCode.SERVER_ERROR_SERIALIZATION).create();
ctx.writeAndFlush(error);
throw ex;
}
}
private static void attemptCommit(final RequestMessage msg, final GraphManager graphManager, final boolean strict) {
if (strict) {
// assumes that validations will already have been performed in extending classes - they are performed
// in StandardOpProcessor when getting bindings right now
final boolean hasRebindings = msg.getArgs().containsKey(Tokens.ARGS_REBINDINGS);
final String rebindingOrAliasParameter = hasRebindings ? Tokens.ARGS_REBINDINGS : Tokens.ARGS_ALIASES;
final Map<String, String> aliases = (Map<String, String>) msg.getArgs().get(rebindingOrAliasParameter);
graphManager.commit(new HashSet<>(aliases.values()));
} else {
graphManager.commitAll();
}
}
private static void attemptRollback(final RequestMessage msg, final GraphManager graphManager, final boolean strict) {
if (strict) {
// assumes that validations will already have been performed in extending classes - they are performed
// in StandardOpProcessor when getting bindings right now
final boolean hasRebindings = msg.getArgs().containsKey(Tokens.ARGS_REBINDINGS);
final String rebindingOrAliasParameter = hasRebindings ? Tokens.ARGS_REBINDINGS : Tokens.ARGS_ALIASES;
final Map<String, String> aliases = (Map<String, String>) msg.getArgs().get(rebindingOrAliasParameter);
graphManager.rollback(new HashSet<>(aliases.values()));
} else {
graphManager.rollbackAll();
}
}
@FunctionalInterface
public interface BindingSupplier {
public Bindings get() throws OpProcessorException;
}
}
| |
/*
* 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.
*/
/*
* This is not the original file distributed by the Apache Software Foundation
* It has been modified by the Hipparchus project
*/
package org.hipparchus.stat.descriptive;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Locale;
import org.hipparchus.UnitTestUtils;
import org.hipparchus.exception.MathIllegalArgumentException;
import org.hipparchus.stat.descriptive.moment.GeometricMean;
import org.hipparchus.stat.descriptive.moment.Mean;
import org.hipparchus.stat.descriptive.moment.Variance;
import org.hipparchus.stat.descriptive.rank.Max;
import org.hipparchus.stat.descriptive.rank.Min;
import org.hipparchus.stat.descriptive.summary.Sum;
import org.hipparchus.stat.descriptive.summary.SumOfSquares;
import org.hipparchus.util.FastMath;
import org.hipparchus.util.Precision;
import org.junit.Test;
/**
* Test cases for the {@link DescriptiveStatistics} class.
*/
public class DescriptiveStatisticsTest {
private final double[] testArray = new double[] { 1, 2, 2, 3 };
private final double one = 1;
private final float twoF = 2;
private final long twoL = 2;
private final int three = 3;
private final double mean = 2;
private final double sumSq = 18;
private final double sum = 8;
private final double var = 0.666666666666666666667;
private final double popVar = 0.5;
private final double std = FastMath.sqrt(var);
private final double n = 4;
private final double min = 1;
private final double max = 3;
private final double tolerance = 10E-15;
protected DescriptiveStatistics createDescriptiveStatistics() {
return new DescriptiveStatistics();
}
/** test stats */
@Test
public void testStats() {
DescriptiveStatistics u = createDescriptiveStatistics();
assertEquals("total count", 0, u.getN(), tolerance);
u.addValue(one);
u.addValue(twoF);
u.addValue(twoL);
u.addValue(three);
assertEquals("N", n, u.getN(), tolerance);
assertEquals("sum", sum, u.getSum(), tolerance);
assertEquals("sumsq", sumSq, u.getSumOfSquares(), tolerance);
assertEquals("var", var, u.getVariance(), tolerance);
assertEquals("population var", popVar, u.getPopulationVariance(), tolerance);
assertEquals("std", std, u.getStandardDeviation(), tolerance);
assertEquals("mean", mean, u.getMean(), tolerance);
assertEquals("min", min, u.getMin(), tolerance);
assertEquals("max", max, u.getMax(), tolerance);
u.clear();
assertEquals("total count", 0, u.getN(), tolerance);
}
@Test
public void testConsume() {
DescriptiveStatistics u = createDescriptiveStatistics();
assertEquals("total count", 0, u.getN(), tolerance);
Arrays.stream(testArray)
.forEach(u);
assertEquals("N", n, u.getN(), tolerance);
assertEquals("sum", sum, u.getSum(), tolerance);
assertEquals("sumsq", sumSq, u.getSumOfSquares(), tolerance);
assertEquals("var", var, u.getVariance(), tolerance);
assertEquals("population var", popVar, u.getPopulationVariance(), tolerance);
assertEquals("std", std, u.getStandardDeviation(), tolerance);
assertEquals("mean", mean, u.getMean(), tolerance);
assertEquals("min", min, u.getMin(), tolerance);
assertEquals("max", max, u.getMax(), tolerance);
u.clear();
assertEquals("total count", 0, u.getN(), tolerance);
}
@Test
public void testCopy() {
DescriptiveStatistics stats = createDescriptiveStatistics();
stats.addValue(1);
stats.addValue(3);
assertEquals(2, stats.getMean(), 1E-10);
DescriptiveStatistics copy = stats.copy();
assertEquals(2, copy.getMean(), 1E-10);
}
@Test
public void testWindowSize() {
DescriptiveStatistics stats = createDescriptiveStatistics();
stats.setWindowSize(300);
for (int i = 0; i < 100; ++i) {
stats.addValue(i + 1);
}
int refSum = (100 * 101) / 2;
assertEquals(refSum / 100.0, stats.getMean(), 1E-10);
assertEquals(300, stats.getWindowSize());
try {
stats.setWindowSize(-3);
fail("an exception should have been thrown");
} catch (MathIllegalArgumentException iae) {
// expected
}
assertEquals(300, stats.getWindowSize());
stats.setWindowSize(50);
assertEquals(50, stats.getWindowSize());
int refSum2 = refSum - (50 * 51) / 2;
assertEquals(refSum2 / 50.0, stats.getMean(), 1E-10);
}
@Test
public void testGetValues() {
DescriptiveStatistics stats = createDescriptiveStatistics();
for (int i = 100; i > 0; --i) {
stats.addValue(i);
}
int refSum = (100 * 101) / 2;
assertEquals(refSum / 100.0, stats.getMean(), 1E-10);
double[] v = stats.getValues();
for (int i = 0; i < v.length; ++i) {
assertEquals(100.0 - i, v[i], 1.0e-10);
}
double[] s = stats.getSortedValues();
for (int i = 0; i < s.length; ++i) {
assertEquals(i + 1.0, s[i], 1.0e-10);
}
assertEquals(12.0, stats.getElement(88), 1.0e-10);
}
@Test
public void testQuadraticMean() {
final double[] values = { 1.2, 3.4, 5.6, 7.89 };
final DescriptiveStatistics stats = new DescriptiveStatistics(values);
final int len = values.length;
double expected = 0;
for (int i = 0; i < len; i++) {
final double v = values[i];
expected += v * v / len;
}
expected = Math.sqrt(expected);
assertEquals(expected, stats.getQuadraticMean(), Math.ulp(expected));
}
@Test
public void testToString() {
DescriptiveStatistics stats = createDescriptiveStatistics();
stats.addValue(1);
stats.addValue(2);
stats.addValue(3);
Locale d = Locale.getDefault();
Locale.setDefault(Locale.US);
assertEquals("DescriptiveStatistics:\n" +
"n: 3\n" +
"min: 1.0\n" +
"max: 3.0\n" +
"mean: 2.0\n" +
"std dev: 1.0\n" +
"median: 2.0\n" +
"skewness: 0.0\n" +
"kurtosis: NaN\n", stats.toString());
Locale.setDefault(d);
}
@Test
public void testPercentile() {
DescriptiveStatistics stats = createDescriptiveStatistics();
stats.addValue(1);
stats.addValue(2);
stats.addValue(3);
assertEquals(2, stats.getPercentile(50.0), 1E-10);
}
@Test
public void test20090720() {
DescriptiveStatistics descriptiveStatistics = new DescriptiveStatistics(100);
for (int i = 0; i < 161; i++) {
descriptiveStatistics.addValue(1.2);
}
descriptiveStatistics.clear();
descriptiveStatistics.addValue(1.2);
assertEquals(1, descriptiveStatistics.getN());
}
@Test
public void testRemoval() {
final DescriptiveStatistics dstat = createDescriptiveStatistics();
checkRemoval(dstat, 1, 6.0, 0.0, Double.NaN);
checkRemoval(dstat, 3, 5.0, 3.0, 4.5);
checkRemoval(dstat, 6, 3.5, 2.5, 3.0);
checkRemoval(dstat, 9, 3.5, 2.5, 3.0);
checkRemoval(dstat, DescriptiveStatistics.INFINITE_WINDOW, 3.5, 2.5, 3.0);
}
@Test
public void testSummaryConsistency() {
final int windowSize = 5;
final DescriptiveStatistics dstats = new DescriptiveStatistics(windowSize);
final StreamingStatistics sstats = new StreamingStatistics();
final double tol = 1E-12;
for (int i = 0; i < 20; i++) {
dstats.addValue(i);
sstats.clear();
double[] values = dstats.getValues();
for (int j = 0; j < values.length; j++) {
sstats.addValue(values[j]);
}
UnitTestUtils.assertEquals(dstats.getMean(), sstats.getMean(), tol);
UnitTestUtils.assertEquals(new Mean().evaluate(values), dstats.getMean(), tol);
UnitTestUtils.assertEquals(dstats.getMax(), sstats.getMax(), tol);
UnitTestUtils.assertEquals(new Max().evaluate(values), dstats.getMax(), tol);
UnitTestUtils.assertEquals(dstats.getGeometricMean(), sstats.getGeometricMean(), tol);
UnitTestUtils.assertEquals(new GeometricMean().evaluate(values), dstats.getGeometricMean(), tol);
UnitTestUtils.assertEquals(dstats.getMin(), sstats.getMin(), tol);
UnitTestUtils.assertEquals(new Min().evaluate(values), dstats.getMin(), tol);
UnitTestUtils.assertEquals(dstats.getStandardDeviation(), sstats.getStandardDeviation(), tol);
UnitTestUtils.assertEquals(dstats.getVariance(), sstats.getVariance(), tol);
UnitTestUtils.assertEquals(new Variance().evaluate(values), dstats.getVariance(), tol);
UnitTestUtils.assertEquals(dstats.getSum(), sstats.getSum(), tol);
UnitTestUtils.assertEquals(new Sum().evaluate(values), dstats.getSum(), tol);
UnitTestUtils.assertEquals(dstats.getSumOfSquares(), sstats.getSumOfSquares(), tol);
UnitTestUtils.assertEquals(new SumOfSquares().evaluate(values), dstats.getSumOfSquares(), tol);
UnitTestUtils.assertEquals(dstats.getPopulationVariance(), sstats.getPopulationVariance(), tol);
UnitTestUtils.assertEquals(new Variance(false).evaluate(values), dstats.getPopulationVariance(), tol);
}
}
@Test
public void testMath1129(){
final double[] data = new double[] {
-0.012086732064244697,
-0.24975668704012527,
0.5706168483164684,
-0.322111769955327,
0.24166759508327315,
Double.NaN,
0.16698443218942854,
-0.10427763937565114,
-0.15595963093172435,
-0.028075857595882995,
-0.24137994506058857,
0.47543170476574426,
-0.07495595384947631,
0.37445697625436497,
-0.09944199541668033
};
final DescriptiveStatistics ds = new DescriptiveStatistics(data);
final double t = ds.getPercentile(75);
final double o = ds.getPercentile(25);
final double iqr = t - o;
// System.out.println(String.format("25th percentile %s 75th percentile %s", o, t));
assertTrue(iqr >= 0);
}
public void checkRemoval(DescriptiveStatistics dstat, int wsize,
double mean1, double mean2, double mean3) {
dstat.setWindowSize(wsize);
dstat.clear();
for (int i = 1 ; i <= 6 ; ++i) {
dstat.addValue(i);
}
assertTrue(Precision.equalsIncludingNaN(mean1, dstat.getMean()));
dstat.replaceMostRecentValue(0);
assertTrue(Precision.equalsIncludingNaN(mean2, dstat.getMean()));
dstat.removeMostRecentValue();
assertTrue(Precision.equalsIncludingNaN(mean3, dstat.getMean()));
}
}
| |
/*
* 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.google.cloud.dataflow.examples.complete;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableReference;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import com.google.api.services.datastore.DatastoreV1.Entity;
import com.google.api.services.datastore.DatastoreV1.Key;
import com.google.api.services.datastore.DatastoreV1.Value;
import com.google.api.services.datastore.client.DatastoreHelper;
import com.google.cloud.dataflow.examples.common.DataflowExampleUtils;
import com.google.cloud.dataflow.examples.common.ExampleBigQueryTableOptions;
import com.google.cloud.dataflow.examples.common.ExamplePubsubTopicOptions;
import com.google.cloud.dataflow.sdk.Pipeline;
import com.google.cloud.dataflow.sdk.PipelineResult;
import com.google.cloud.dataflow.sdk.coders.AvroCoder;
import com.google.cloud.dataflow.sdk.coders.DefaultCoder;
import com.google.cloud.dataflow.sdk.io.BigQueryIO;
import com.google.cloud.dataflow.sdk.io.DatastoreIO;
import com.google.cloud.dataflow.sdk.io.PubsubIO;
import com.google.cloud.dataflow.sdk.io.TextIO;
import com.google.cloud.dataflow.sdk.options.Default;
import com.google.cloud.dataflow.sdk.options.Description;
import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
import com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner;
import com.google.cloud.dataflow.sdk.transforms.Count;
import com.google.cloud.dataflow.sdk.transforms.DoFn;
import com.google.cloud.dataflow.sdk.transforms.Filter;
import com.google.cloud.dataflow.sdk.transforms.Flatten;
import com.google.cloud.dataflow.sdk.transforms.PTransform;
import com.google.cloud.dataflow.sdk.transforms.ParDo;
import com.google.cloud.dataflow.sdk.transforms.Partition;
import com.google.cloud.dataflow.sdk.transforms.Partition.PartitionFn;
import com.google.cloud.dataflow.sdk.transforms.SerializableFunction;
import com.google.cloud.dataflow.sdk.transforms.Top;
import com.google.cloud.dataflow.sdk.transforms.windowing.GlobalWindows;
import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows;
import com.google.cloud.dataflow.sdk.transforms.windowing.Window;
import com.google.cloud.dataflow.sdk.transforms.windowing.WindowFn;
import com.google.cloud.dataflow.sdk.values.KV;
import com.google.cloud.dataflow.sdk.values.PBegin;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.cloud.dataflow.sdk.values.PCollectionList;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import org.joda.time.Duration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* An example that computes the most popular hash tags
* for every prefix, which can be used for auto-completion.
*
* <p>Concepts: Using the same pipeline in both streaming and batch, combiners,
* composite transforms.
*
* <p>To execute this pipeline using the Dataflow service in batch mode,
* specify pipeline configuration:
* <pre>{@code
* --project=YOUR_PROJECT_ID
* --stagingLocation=gs://YOUR_STAGING_DIRECTORY
* --runner=DataflowPipelineRunner
* --inputFile=gs://path/to/input*.txt
* }</pre>
*
* <p>To execute this pipeline using the Dataflow service in streaming mode,
* specify pipeline configuration:
* <pre>{@code
* --project=YOUR_PROJECT_ID
* --stagingLocation=gs://YOUR_STAGING_DIRECTORY
* --runner=DataflowPipelineRunner
* --inputFile=gs://YOUR_INPUT_DIRECTORY/*.txt
* --streaming
* }</pre>
*
* <p>This will update the datastore every 10 seconds based on the last
* 30 minutes of data received.
*/
public class AutoComplete {
/**
* A PTransform that takes as input a list of tokens and returns
* the most common tokens per prefix.
*/
public static class ComputeTopCompletions
extends PTransform<PCollection<String>, PCollection<KV<String, List<CompletionCandidate>>>> {
private final int candidatesPerPrefix;
private final boolean recursive;
protected ComputeTopCompletions(int candidatesPerPrefix, boolean recursive) {
this.candidatesPerPrefix = candidatesPerPrefix;
this.recursive = recursive;
}
public static ComputeTopCompletions top(int candidatesPerPrefix, boolean recursive) {
return new ComputeTopCompletions(candidatesPerPrefix, recursive);
}
@Override
public PCollection<KV<String, List<CompletionCandidate>>> apply(PCollection<String> input) {
PCollection<CompletionCandidate> candidates = input
// First count how often each token appears.
.apply(new Count.PerElement<String>())
// Map the KV outputs of Count into our own CompletionCandiate class.
.apply(ParDo.named("CreateCompletionCandidates").of(
new DoFn<KV<String, Long>, CompletionCandidate>() {
@Override
public void processElement(ProcessContext c) {
c.output(new CompletionCandidate(c.element().getKey(), c.element().getValue()));
}
}));
// Compute the top via either a flat or recursive algorithm.
if (recursive) {
return candidates
.apply(new ComputeTopRecursive(candidatesPerPrefix, 1))
.apply(Flatten.<KV<String, List<CompletionCandidate>>>pCollections());
} else {
return candidates
.apply(new ComputeTopFlat(candidatesPerPrefix, 1));
}
}
}
/**
* Lower latency, but more expensive.
*/
private static class ComputeTopFlat
extends PTransform<PCollection<CompletionCandidate>,
PCollection<KV<String, List<CompletionCandidate>>>> {
private final int candidatesPerPrefix;
private final int minPrefix;
public ComputeTopFlat(int candidatesPerPrefix, int minPrefix) {
this.candidatesPerPrefix = candidatesPerPrefix;
this.minPrefix = minPrefix;
}
@Override
public PCollection<KV<String, List<CompletionCandidate>>> apply(
PCollection<CompletionCandidate> input) {
return input
// For each completion candidate, map it to all prefixes.
.apply(ParDo.of(new AllPrefixes(minPrefix)))
// Find and return the top candiates for each prefix.
.apply(Top.<String, CompletionCandidate>largestPerKey(candidatesPerPrefix)
.withHotKeyFanout(new HotKeyFanout()));
}
private static class HotKeyFanout implements SerializableFunction<String, Integer> {
@Override
public Integer apply(String input) {
return (int) Math.pow(4, 5 - input.length());
}
}
}
/**
* Cheaper but higher latency.
*
* <p>Returns two PCollections, the first is top prefixes of size greater
* than minPrefix, and the second is top prefixes of size exactly
* minPrefix.
*/
private static class ComputeTopRecursive
extends PTransform<PCollection<CompletionCandidate>,
PCollectionList<KV<String, List<CompletionCandidate>>>> {
private final int candidatesPerPrefix;
private final int minPrefix;
public ComputeTopRecursive(int candidatesPerPrefix, int minPrefix) {
this.candidatesPerPrefix = candidatesPerPrefix;
this.minPrefix = minPrefix;
}
private class KeySizePartitionFn implements PartitionFn<KV<String, List<CompletionCandidate>>> {
@Override
public int partitionFor(KV<String, List<CompletionCandidate>> elem, int numPartitions) {
return elem.getKey().length() > minPrefix ? 0 : 1;
}
}
private static class FlattenTops
extends DoFn<KV<String, List<CompletionCandidate>>, CompletionCandidate> {
@Override
public void processElement(ProcessContext c) {
for (CompletionCandidate cc : c.element().getValue()) {
c.output(cc);
}
}
}
@Override
public PCollectionList<KV<String, List<CompletionCandidate>>> apply(
PCollection<CompletionCandidate> input) {
if (minPrefix > 10) {
// Base case, partitioning to return the output in the expected format.
return input
.apply(new ComputeTopFlat(candidatesPerPrefix, minPrefix))
.apply(Partition.of(2, new KeySizePartitionFn()));
} else {
// If a candidate is in the top N for prefix a...b, it must also be in the top
// N for a...bX for every X, which is typlically a much smaller set to consider.
// First, compute the top candidate for prefixes of size at least minPrefix + 1.
PCollectionList<KV<String, List<CompletionCandidate>>> larger = input
.apply(new ComputeTopRecursive(candidatesPerPrefix, minPrefix + 1));
// Consider the top candidates for each prefix of length minPrefix + 1...
PCollection<KV<String, List<CompletionCandidate>>> small =
PCollectionList
.of(larger.get(1).apply(ParDo.of(new FlattenTops())))
// ...together with those (previously excluded) candidates of length
// exactly minPrefix...
.and(input.apply(Filter.byPredicate(
new SerializableFunction<CompletionCandidate, Boolean>() {
@Override
public Boolean apply(CompletionCandidate c) {
return c.getValue().length() == minPrefix;
}
})))
.apply("FlattenSmall", Flatten.<CompletionCandidate>pCollections())
// ...set the key to be the minPrefix-length prefix...
.apply(ParDo.of(new AllPrefixes(minPrefix, minPrefix)))
// ...and (re)apply the Top operator to all of them together.
.apply(Top.<String, CompletionCandidate>largestPerKey(candidatesPerPrefix));
PCollection<KV<String, List<CompletionCandidate>>> flattenLarger = larger
.apply("FlattenLarge", Flatten.<KV<String, List<CompletionCandidate>>>pCollections());
return PCollectionList.of(flattenLarger).and(small);
}
}
}
/**
* A DoFn that keys each candidate by all its prefixes.
*/
private static class AllPrefixes
extends DoFn<CompletionCandidate, KV<String, CompletionCandidate>> {
private final int minPrefix;
private final int maxPrefix;
public AllPrefixes(int minPrefix) {
this(minPrefix, Integer.MAX_VALUE);
}
public AllPrefixes(int minPrefix, int maxPrefix) {
this.minPrefix = minPrefix;
this.maxPrefix = maxPrefix;
}
@Override
public void processElement(ProcessContext c) {
String word = c.element().value;
for (int i = minPrefix; i <= Math.min(word.length(), maxPrefix); i++) {
c.output(KV.of(word.substring(0, i), c.element()));
}
}
}
/**
* Class used to store tag-count pairs.
*/
@DefaultCoder(AvroCoder.class)
static class CompletionCandidate implements Comparable<CompletionCandidate> {
private long count;
private String value;
public CompletionCandidate(String value, long count) {
this.value = value;
this.count = count;
}
public long getCount() {
return count;
}
public String getValue() {
return value;
}
// Empty constructor required for Avro decoding.
public CompletionCandidate() {}
@Override
public int compareTo(CompletionCandidate o) {
if (this.count < o.count) {
return -1;
} else if (this.count == o.count) {
return this.value.compareTo(o.value);
} else {
return 1;
}
}
@Override
public boolean equals(Object other) {
if (other instanceof CompletionCandidate) {
CompletionCandidate that = (CompletionCandidate) other;
return this.count == that.count && this.value.equals(that.value);
} else {
return false;
}
}
@Override
public int hashCode() {
return Long.valueOf(count).hashCode() ^ value.hashCode();
}
@Override
public String toString() {
return "CompletionCandidate[" + value + ", " + count + "]";
}
}
/**
* Takes as input a set of strings, and emits each #hashtag found therein.
*/
static class ExtractHashtags extends DoFn<String, String> {
@Override
public void processElement(ProcessContext c) {
Matcher m = Pattern.compile("#\\S+").matcher(c.element());
while (m.find()) {
c.output(m.group().substring(1));
}
}
}
static class FormatForBigquery extends DoFn<KV<String, List<CompletionCandidate>>, TableRow> {
@Override
public void processElement(ProcessContext c) {
List<TableRow> completions = new ArrayList<>();
for (CompletionCandidate cc : c.element().getValue()) {
completions.add(new TableRow()
.set("count", cc.getCount())
.set("tag", cc.getValue()));
}
TableRow row = new TableRow()
.set("prefix", c.element().getKey())
.set("tags", completions);
c.output(row);
}
/**
* Defines the BigQuery schema used for the output.
*/
static TableSchema getSchema() {
List<TableFieldSchema> tagFields = new ArrayList<>();
tagFields.add(new TableFieldSchema().setName("count").setType("INTEGER"));
tagFields.add(new TableFieldSchema().setName("tag").setType("STRING"));
List<TableFieldSchema> fields = new ArrayList<>();
fields.add(new TableFieldSchema().setName("prefix").setType("STRING"));
fields.add(new TableFieldSchema()
.setName("tags").setType("RECORD").setMode("REPEATED").setFields(tagFields));
return new TableSchema().setFields(fields);
}
}
/**
* Takes as input a the top candidates per prefix, and emits an entity
* suitable for writing to Datastore.
*/
static class FormatForDatastore extends DoFn<KV<String, List<CompletionCandidate>>, Entity> {
private String kind;
public FormatForDatastore(String kind) {
this.kind = kind;
}
@Override
public void processElement(ProcessContext c) {
Entity.Builder entityBuilder = Entity.newBuilder();
Key key = DatastoreHelper.makeKey(kind, c.element().getKey()).build();
entityBuilder.setKey(key);
List<Value> candidates = new ArrayList<>();
for (CompletionCandidate tag : c.element().getValue()) {
Entity.Builder tagEntity = Entity.newBuilder();
tagEntity.addProperty(
DatastoreHelper.makeProperty("tag", DatastoreHelper.makeValue(tag.value)));
tagEntity.addProperty(
DatastoreHelper.makeProperty("count", DatastoreHelper.makeValue(tag.count)));
candidates.add(DatastoreHelper.makeValue(tagEntity).setIndexed(false).build());
}
entityBuilder.addProperty(
DatastoreHelper.makeProperty("candidates", DatastoreHelper.makeValue(candidates)));
c.output(entityBuilder.build());
}
}
/**
* Options supported by this class.
*
* <p>Inherits standard Dataflow configuration options.
*/
private static interface Options extends ExamplePubsubTopicOptions, ExampleBigQueryTableOptions {
@Description("Input text file")
String getInputFile();
void setInputFile(String value);
@Description("Whether to use the recursive algorithm")
@Default.Boolean(true)
Boolean getRecursive();
void setRecursive(Boolean value);
@Description("Dataset entity kind")
@Default.String("autocomplete-demo")
String getKind();
void setKind(String value);
@Description("Whether output to BigQuery")
@Default.Boolean(true)
Boolean getOutputToBigQuery();
void setOutputToBigQuery(Boolean value);
@Description("Whether output to Datastore")
@Default.Boolean(false)
Boolean getOutputToDatastore();
void setOutputToDatastore(Boolean value);
@Description("Datastore output dataset ID, defaults to project ID")
String getOutputDataset();
void setOutputDataset(String value);
}
public static void main(String[] args) throws IOException {
Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
if (options.isStreaming()) {
// In order to cancel the pipelines automatically,
// {@literal DataflowPipelineRunner} is forced to be used.
options.setRunner(DataflowPipelineRunner.class);
}
options.setBigQuerySchema(FormatForBigquery.getSchema());
DataflowExampleUtils dataflowUtils = new DataflowExampleUtils(options);
// We support running the same pipeline in either
// batch or windowed streaming mode.
PTransform<? super PBegin, PCollection<String>> readSource;
WindowFn<Object, ?> windowFn;
if (options.isStreaming()) {
Preconditions.checkArgument(
!options.getOutputToDatastore(), "DatastoreIO is not supported in streaming.");
dataflowUtils.setupPubsub();
readSource = PubsubIO.Read.topic(options.getPubsubTopic());
windowFn = SlidingWindows.of(Duration.standardMinutes(30)).every(Duration.standardSeconds(5));
} else {
readSource = TextIO.Read.from(options.getInputFile());
windowFn = new GlobalWindows();
}
// Create the pipeline.
Pipeline p = Pipeline.create(options);
PCollection<KV<String, List<CompletionCandidate>>> toWrite = p
.apply(readSource)
.apply(ParDo.of(new ExtractHashtags()))
.apply(Window.<String>into(windowFn))
.apply(ComputeTopCompletions.top(10, options.getRecursive()));
if (options.getOutputToDatastore()) {
toWrite
.apply(ParDo.named("FormatForDatastore").of(new FormatForDatastore(options.getKind())))
.apply(DatastoreIO.writeTo(MoreObjects.firstNonNull(
options.getOutputDataset(), options.getProject())));
}
if (options.getOutputToBigQuery()) {
dataflowUtils.setupBigQueryTable();
TableReference tableRef = new TableReference();
tableRef.setProjectId(options.getProject());
tableRef.setDatasetId(options.getBigQueryDataset());
tableRef.setTableId(options.getBigQueryTable());
toWrite
.apply(ParDo.of(new FormatForBigquery()))
.apply(BigQueryIO.Write
.to(tableRef)
.withSchema(FormatForBigquery.getSchema())
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE));
}
// Run the pipeline.
PipelineResult result = p.run();
if (options.isStreaming() && !options.getInputFile().isEmpty()) {
// Inject the data into the Pub/Sub topic with a Dataflow batch pipeline.
dataflowUtils.runInjectorPipeline(options.getInputFile(), options.getPubsubTopic());
}
// dataflowUtils will try to cancel the pipeline and the injector before the program exists.
dataflowUtils.waitToFinish(result);
}
}
| |
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.fixedincome;
import java.io.Serializable;
import java.util.Map;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.DerivedProperty;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBean;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import org.threeten.bp.LocalDate;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.CurrencyAmount;
/**
* Container for the relevant details for pricing a fixed swap leg, with the entries
* <p>
* <li>Start accrual date</li>
* <li>End accrual date</li>
* <li>Payment time</li>
* <li>Payment year fraction</li>
* <li>Payment amount (non discounted)</li>
* <li>Discount factor</li>
* <li>Notional</li>
* <li>Rate</li>
* <li>Discounted payment amount</li>
* <p>
* There is an entry for each coupon in a fixed leg.
* @deprecated Use FixedLegCashFlows
*/
@Deprecated
@BeanDefinition
public class FixedSwapLegDetails extends DirectBean implements Serializable {
/**
* The start accrual dates label.
*/
public static final String START_ACCRUAL_DATES = "Start Accrual Date";
/**
* The end accrual dates label.
*/
public static final String END_ACCRUAL_DATES = "End Accrual Date";
/**
* The payment time label.
*/
public static final String PAYMENT_TIME = "Payment Time";
/**
* The payment year fraction label.
*/
public static final String PAYMENT_YEAR_FRACTION = "Payment Year Fraction";
/**
* The payment amount label.
*/
public static final String PAYMENT_AMOUNT = "Payment Amount";
/**
* The discount factor label.
*/
public static final String DISCOUNT_FACTOR = "Discount Factor";
/**
* The notional label.
*/
public static final String NOTIONAL = "Notional";
/**
* The fixed rate label.
*/
public static final String FIXED_RATE = "Fixed Rate";
/**
* The discounted payment amount
*/
public static final String DISCOUNTED_PAYMENT_AMOUNT = "Discounted Payment Amount";
/** Serialization version */
private static final long serialVersionUID = 1L;
/**
* An array of accrual start dates.
*/
@PropertyDefinition(validate = "notNull")
private LocalDate[] _accrualStart;
/**
* An array of accrual end dates.
*/
@PropertyDefinition(validate = "notNull")
private LocalDate[] _accrualEnd;
/**
* An array of discount factors for the payments.
*/
@PropertyDefinition(validate = "notNull")
private double[] _discountFactors;
/**
* An array of payment times.
*/
@PropertyDefinition(validate = "notNull")
private double[] _paymentTimes;
/**
* An array of payment year fractions.
*/
@PropertyDefinition(validate = "notNull")
private double[] _paymentFractions;
/**
* An array of payment amounts.
*/
@PropertyDefinition(validate = "notNull")
private CurrencyAmount[] _paymentAmounts;
/**
* An array of notionals.
*/
@PropertyDefinition(validate = "notNull")
private CurrencyAmount[] _notionals;
/**
* An array of fixed rates.
*/
@PropertyDefinition(validate = "notNull")
private Double[] _fixedRates;
/**
* For the builder.
*/
/* package */FixedSwapLegDetails() {
super();
}
/**
* All arrays must be the same length.
* @param startAccrualDates The start accrual dates, not null
* @param endAccrualDates The end accrual dates, not null
* @param paymentTimes The payment times, not null
* @param paymentFractions The payment year fractions, not null
* @param discountFactors The discount factors, not null
* @param paymentAmounts The payment amounts, not null
* @param notionals The notionals, not null
* @param fixedRates The fixed rates, not null
*/
public FixedSwapLegDetails(final LocalDate[] startAccrualDates, final LocalDate[] endAccrualDates,
final double[] discountFactors, final double[] paymentTimes, final double[] paymentFractions,
final CurrencyAmount[] paymentAmounts, final CurrencyAmount[] notionals, final Double[] fixedRates) {
setAccrualStart(startAccrualDates);
setAccrualEnd(endAccrualDates);
setDiscountFactors(discountFactors);
setPaymentTimes(paymentTimes);
setPaymentFractions(paymentFractions);
setPaymentAmounts(paymentAmounts);
setNotionals(notionals);
setFixedRates(fixedRates);
final int n = startAccrualDates.length;
ArgumentChecker.isTrue(n == endAccrualDates.length, "Must have same number of start and end accrual dates");
ArgumentChecker.isTrue(n == discountFactors.length, "Must have same number of start accrual dates and discount factors");
ArgumentChecker.isTrue(n == paymentTimes.length, "Must have same number of start accrual dates and payment times");
ArgumentChecker.isTrue(n == paymentFractions.length, "Must have same number of start accrual dates and payment year fractions");
ArgumentChecker.isTrue(n == paymentAmounts.length, "Must have same number of start accrual dates and payment amounts");
ArgumentChecker.isTrue(n == notionals.length, "Must have same number of start accrual dates and notionals");
ArgumentChecker.isTrue(n == fixedRates.length, "Must have same number of start accrual dates and fixed rates");
}
/**
* Gets the number of cash-flows.
* @return the number of cash-flows
*/
@DerivedProperty
public int getNumberOfCashFlows() {
return getAccrualStart().length;
}
/**
* Gets the discounted payment amounts.
* @return the discounted cashflows
*/
@DerivedProperty
public CurrencyAmount[] getDiscountedPaymentAmounts() {
final CurrencyAmount[] cashflows = new CurrencyAmount[getNumberOfCashFlows()];
for (int i = 0; i < getNumberOfCashFlows(); i++) {
final CurrencyAmount payment = getPaymentAmounts()[i];
if (payment == null) {
continue;
}
final double df = getDiscountFactors()[i];
cashflows[i] = CurrencyAmount.of(payment.getCurrency(), payment.getAmount() * df);
}
return cashflows;
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code FixedSwapLegDetails}.
* @return the meta-bean, not null
*/
public static FixedSwapLegDetails.Meta meta() {
return FixedSwapLegDetails.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(FixedSwapLegDetails.Meta.INSTANCE);
}
@Override
public FixedSwapLegDetails.Meta metaBean() {
return FixedSwapLegDetails.Meta.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets an array of accrual start dates.
* @return the value of the property, not null
*/
public LocalDate[] getAccrualStart() {
return _accrualStart;
}
/**
* Sets an array of accrual start dates.
* @param accrualStart the new value of the property, not null
*/
public void setAccrualStart(LocalDate[] accrualStart) {
JodaBeanUtils.notNull(accrualStart, "accrualStart");
this._accrualStart = accrualStart;
}
/**
* Gets the the {@code accrualStart} property.
* @return the property, not null
*/
public final Property<LocalDate[]> accrualStart() {
return metaBean().accrualStart().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets an array of accrual end dates.
* @return the value of the property, not null
*/
public LocalDate[] getAccrualEnd() {
return _accrualEnd;
}
/**
* Sets an array of accrual end dates.
* @param accrualEnd the new value of the property, not null
*/
public void setAccrualEnd(LocalDate[] accrualEnd) {
JodaBeanUtils.notNull(accrualEnd, "accrualEnd");
this._accrualEnd = accrualEnd;
}
/**
* Gets the the {@code accrualEnd} property.
* @return the property, not null
*/
public final Property<LocalDate[]> accrualEnd() {
return metaBean().accrualEnd().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets an array of discount factors for the payments.
* @return the value of the property, not null
*/
public double[] getDiscountFactors() {
return _discountFactors;
}
/**
* Sets an array of discount factors for the payments.
* @param discountFactors the new value of the property, not null
*/
public void setDiscountFactors(double[] discountFactors) {
JodaBeanUtils.notNull(discountFactors, "discountFactors");
this._discountFactors = discountFactors;
}
/**
* Gets the the {@code discountFactors} property.
* @return the property, not null
*/
public final Property<double[]> discountFactors() {
return metaBean().discountFactors().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets an array of payment times.
* @return the value of the property, not null
*/
public double[] getPaymentTimes() {
return _paymentTimes;
}
/**
* Sets an array of payment times.
* @param paymentTimes the new value of the property, not null
*/
public void setPaymentTimes(double[] paymentTimes) {
JodaBeanUtils.notNull(paymentTimes, "paymentTimes");
this._paymentTimes = paymentTimes;
}
/**
* Gets the the {@code paymentTimes} property.
* @return the property, not null
*/
public final Property<double[]> paymentTimes() {
return metaBean().paymentTimes().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets an array of payment year fractions.
* @return the value of the property, not null
*/
public double[] getPaymentFractions() {
return _paymentFractions;
}
/**
* Sets an array of payment year fractions.
* @param paymentFractions the new value of the property, not null
*/
public void setPaymentFractions(double[] paymentFractions) {
JodaBeanUtils.notNull(paymentFractions, "paymentFractions");
this._paymentFractions = paymentFractions;
}
/**
* Gets the the {@code paymentFractions} property.
* @return the property, not null
*/
public final Property<double[]> paymentFractions() {
return metaBean().paymentFractions().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets an array of payment amounts.
* @return the value of the property, not null
*/
public CurrencyAmount[] getPaymentAmounts() {
return _paymentAmounts;
}
/**
* Sets an array of payment amounts.
* @param paymentAmounts the new value of the property, not null
*/
public void setPaymentAmounts(CurrencyAmount[] paymentAmounts) {
JodaBeanUtils.notNull(paymentAmounts, "paymentAmounts");
this._paymentAmounts = paymentAmounts;
}
/**
* Gets the the {@code paymentAmounts} property.
* @return the property, not null
*/
public final Property<CurrencyAmount[]> paymentAmounts() {
return metaBean().paymentAmounts().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets an array of notionals.
* @return the value of the property, not null
*/
public CurrencyAmount[] getNotionals() {
return _notionals;
}
/**
* Sets an array of notionals.
* @param notionals the new value of the property, not null
*/
public void setNotionals(CurrencyAmount[] notionals) {
JodaBeanUtils.notNull(notionals, "notionals");
this._notionals = notionals;
}
/**
* Gets the the {@code notionals} property.
* @return the property, not null
*/
public final Property<CurrencyAmount[]> notionals() {
return metaBean().notionals().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets an array of fixed rates.
* @return the value of the property, not null
*/
public Double[] getFixedRates() {
return _fixedRates;
}
/**
* Sets an array of fixed rates.
* @param fixedRates the new value of the property, not null
*/
public void setFixedRates(Double[] fixedRates) {
JodaBeanUtils.notNull(fixedRates, "fixedRates");
this._fixedRates = fixedRates;
}
/**
* Gets the the {@code fixedRates} property.
* @return the property, not null
*/
public final Property<Double[]> fixedRates() {
return metaBean().fixedRates().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the the {@code numberOfCashFlows} property.
* @return the property, not null
*/
public final Property<Integer> numberOfCashFlows() {
return metaBean().numberOfCashFlows().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the the {@code discountedPaymentAmounts} property.
* @return the property, not null
*/
public final Property<CurrencyAmount[]> discountedPaymentAmounts() {
return metaBean().discountedPaymentAmounts().createProperty(this);
}
//-----------------------------------------------------------------------
@Override
public FixedSwapLegDetails clone() {
return JodaBeanUtils.cloneAlways(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
FixedSwapLegDetails other = (FixedSwapLegDetails) obj;
return JodaBeanUtils.equal(getAccrualStart(), other.getAccrualStart()) &&
JodaBeanUtils.equal(getAccrualEnd(), other.getAccrualEnd()) &&
JodaBeanUtils.equal(getDiscountFactors(), other.getDiscountFactors()) &&
JodaBeanUtils.equal(getPaymentTimes(), other.getPaymentTimes()) &&
JodaBeanUtils.equal(getPaymentFractions(), other.getPaymentFractions()) &&
JodaBeanUtils.equal(getPaymentAmounts(), other.getPaymentAmounts()) &&
JodaBeanUtils.equal(getNotionals(), other.getNotionals()) &&
JodaBeanUtils.equal(getFixedRates(), other.getFixedRates());
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(getAccrualStart());
hash = hash * 31 + JodaBeanUtils.hashCode(getAccrualEnd());
hash = hash * 31 + JodaBeanUtils.hashCode(getDiscountFactors());
hash = hash * 31 + JodaBeanUtils.hashCode(getPaymentTimes());
hash = hash * 31 + JodaBeanUtils.hashCode(getPaymentFractions());
hash = hash * 31 + JodaBeanUtils.hashCode(getPaymentAmounts());
hash = hash * 31 + JodaBeanUtils.hashCode(getNotionals());
hash = hash * 31 + JodaBeanUtils.hashCode(getFixedRates());
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(352);
buf.append("FixedSwapLegDetails{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
protected void toString(StringBuilder buf) {
buf.append("accrualStart").append('=').append(JodaBeanUtils.toString(getAccrualStart())).append(',').append(' ');
buf.append("accrualEnd").append('=').append(JodaBeanUtils.toString(getAccrualEnd())).append(',').append(' ');
buf.append("discountFactors").append('=').append(JodaBeanUtils.toString(getDiscountFactors())).append(',').append(' ');
buf.append("paymentTimes").append('=').append(JodaBeanUtils.toString(getPaymentTimes())).append(',').append(' ');
buf.append("paymentFractions").append('=').append(JodaBeanUtils.toString(getPaymentFractions())).append(',').append(' ');
buf.append("paymentAmounts").append('=').append(JodaBeanUtils.toString(getPaymentAmounts())).append(',').append(' ');
buf.append("notionals").append('=').append(JodaBeanUtils.toString(getNotionals())).append(',').append(' ');
buf.append("fixedRates").append('=').append(JodaBeanUtils.toString(getFixedRates())).append(',').append(' ');
buf.append("numberOfCashFlows").append('=').append(JodaBeanUtils.toString(getNumberOfCashFlows())).append(',').append(' ');
buf.append("discountedPaymentAmounts").append('=').append(JodaBeanUtils.toString(getDiscountedPaymentAmounts())).append(',').append(' ');
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code FixedSwapLegDetails}.
*/
public static class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code accrualStart} property.
*/
private final MetaProperty<LocalDate[]> _accrualStart = DirectMetaProperty.ofReadWrite(
this, "accrualStart", FixedSwapLegDetails.class, LocalDate[].class);
/**
* The meta-property for the {@code accrualEnd} property.
*/
private final MetaProperty<LocalDate[]> _accrualEnd = DirectMetaProperty.ofReadWrite(
this, "accrualEnd", FixedSwapLegDetails.class, LocalDate[].class);
/**
* The meta-property for the {@code discountFactors} property.
*/
private final MetaProperty<double[]> _discountFactors = DirectMetaProperty.ofReadWrite(
this, "discountFactors", FixedSwapLegDetails.class, double[].class);
/**
* The meta-property for the {@code paymentTimes} property.
*/
private final MetaProperty<double[]> _paymentTimes = DirectMetaProperty.ofReadWrite(
this, "paymentTimes", FixedSwapLegDetails.class, double[].class);
/**
* The meta-property for the {@code paymentFractions} property.
*/
private final MetaProperty<double[]> _paymentFractions = DirectMetaProperty.ofReadWrite(
this, "paymentFractions", FixedSwapLegDetails.class, double[].class);
/**
* The meta-property for the {@code paymentAmounts} property.
*/
private final MetaProperty<CurrencyAmount[]> _paymentAmounts = DirectMetaProperty.ofReadWrite(
this, "paymentAmounts", FixedSwapLegDetails.class, CurrencyAmount[].class);
/**
* The meta-property for the {@code notionals} property.
*/
private final MetaProperty<CurrencyAmount[]> _notionals = DirectMetaProperty.ofReadWrite(
this, "notionals", FixedSwapLegDetails.class, CurrencyAmount[].class);
/**
* The meta-property for the {@code fixedRates} property.
*/
private final MetaProperty<Double[]> _fixedRates = DirectMetaProperty.ofReadWrite(
this, "fixedRates", FixedSwapLegDetails.class, Double[].class);
/**
* The meta-property for the {@code numberOfCashFlows} property.
*/
private final MetaProperty<Integer> _numberOfCashFlows = DirectMetaProperty.ofDerived(
this, "numberOfCashFlows", FixedSwapLegDetails.class, Integer.TYPE);
/**
* The meta-property for the {@code discountedPaymentAmounts} property.
*/
private final MetaProperty<CurrencyAmount[]> _discountedPaymentAmounts = DirectMetaProperty.ofDerived(
this, "discountedPaymentAmounts", FixedSwapLegDetails.class, CurrencyAmount[].class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"accrualStart",
"accrualEnd",
"discountFactors",
"paymentTimes",
"paymentFractions",
"paymentAmounts",
"notionals",
"fixedRates",
"numberOfCashFlows",
"discountedPaymentAmounts");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case 1071260659: // accrualStart
return _accrualStart;
case 1846909100: // accrualEnd
return _accrualEnd;
case -91613053: // discountFactors
return _discountFactors;
case -507430688: // paymentTimes
return _paymentTimes;
case 1206997835: // paymentFractions
return _paymentFractions;
case -1875448267: // paymentAmounts
return _paymentAmounts;
case 1910080819: // notionals
return _notionals;
case 1695350911: // fixedRates
return _fixedRates;
case -338982286: // numberOfCashFlows
return _numberOfCashFlows;
case 178231285: // discountedPaymentAmounts
return _discountedPaymentAmounts;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends FixedSwapLegDetails> builder() {
return new DirectBeanBuilder<FixedSwapLegDetails>(new FixedSwapLegDetails());
}
@Override
public Class<? extends FixedSwapLegDetails> beanType() {
return FixedSwapLegDetails.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code accrualStart} property.
* @return the meta-property, not null
*/
public final MetaProperty<LocalDate[]> accrualStart() {
return _accrualStart;
}
/**
* The meta-property for the {@code accrualEnd} property.
* @return the meta-property, not null
*/
public final MetaProperty<LocalDate[]> accrualEnd() {
return _accrualEnd;
}
/**
* The meta-property for the {@code discountFactors} property.
* @return the meta-property, not null
*/
public final MetaProperty<double[]> discountFactors() {
return _discountFactors;
}
/**
* The meta-property for the {@code paymentTimes} property.
* @return the meta-property, not null
*/
public final MetaProperty<double[]> paymentTimes() {
return _paymentTimes;
}
/**
* The meta-property for the {@code paymentFractions} property.
* @return the meta-property, not null
*/
public final MetaProperty<double[]> paymentFractions() {
return _paymentFractions;
}
/**
* The meta-property for the {@code paymentAmounts} property.
* @return the meta-property, not null
*/
public final MetaProperty<CurrencyAmount[]> paymentAmounts() {
return _paymentAmounts;
}
/**
* The meta-property for the {@code notionals} property.
* @return the meta-property, not null
*/
public final MetaProperty<CurrencyAmount[]> notionals() {
return _notionals;
}
/**
* The meta-property for the {@code fixedRates} property.
* @return the meta-property, not null
*/
public final MetaProperty<Double[]> fixedRates() {
return _fixedRates;
}
/**
* The meta-property for the {@code numberOfCashFlows} property.
* @return the meta-property, not null
*/
public final MetaProperty<Integer> numberOfCashFlows() {
return _numberOfCashFlows;
}
/**
* The meta-property for the {@code discountedPaymentAmounts} property.
* @return the meta-property, not null
*/
public final MetaProperty<CurrencyAmount[]> discountedPaymentAmounts() {
return _discountedPaymentAmounts;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case 1071260659: // accrualStart
return ((FixedSwapLegDetails) bean).getAccrualStart();
case 1846909100: // accrualEnd
return ((FixedSwapLegDetails) bean).getAccrualEnd();
case -91613053: // discountFactors
return ((FixedSwapLegDetails) bean).getDiscountFactors();
case -507430688: // paymentTimes
return ((FixedSwapLegDetails) bean).getPaymentTimes();
case 1206997835: // paymentFractions
return ((FixedSwapLegDetails) bean).getPaymentFractions();
case -1875448267: // paymentAmounts
return ((FixedSwapLegDetails) bean).getPaymentAmounts();
case 1910080819: // notionals
return ((FixedSwapLegDetails) bean).getNotionals();
case 1695350911: // fixedRates
return ((FixedSwapLegDetails) bean).getFixedRates();
case -338982286: // numberOfCashFlows
return ((FixedSwapLegDetails) bean).getNumberOfCashFlows();
case 178231285: // discountedPaymentAmounts
return ((FixedSwapLegDetails) bean).getDiscountedPaymentAmounts();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
switch (propertyName.hashCode()) {
case 1071260659: // accrualStart
((FixedSwapLegDetails) bean).setAccrualStart((LocalDate[]) newValue);
return;
case 1846909100: // accrualEnd
((FixedSwapLegDetails) bean).setAccrualEnd((LocalDate[]) newValue);
return;
case -91613053: // discountFactors
((FixedSwapLegDetails) bean).setDiscountFactors((double[]) newValue);
return;
case -507430688: // paymentTimes
((FixedSwapLegDetails) bean).setPaymentTimes((double[]) newValue);
return;
case 1206997835: // paymentFractions
((FixedSwapLegDetails) bean).setPaymentFractions((double[]) newValue);
return;
case -1875448267: // paymentAmounts
((FixedSwapLegDetails) bean).setPaymentAmounts((CurrencyAmount[]) newValue);
return;
case 1910080819: // notionals
((FixedSwapLegDetails) bean).setNotionals((CurrencyAmount[]) newValue);
return;
case 1695350911: // fixedRates
((FixedSwapLegDetails) bean).setFixedRates((Double[]) newValue);
return;
case -338982286: // numberOfCashFlows
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: numberOfCashFlows");
case 178231285: // discountedPaymentAmounts
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: discountedPaymentAmounts");
}
super.propertySet(bean, propertyName, newValue, quiet);
}
@Override
protected void validate(Bean bean) {
JodaBeanUtils.notNull(((FixedSwapLegDetails) bean)._accrualStart, "accrualStart");
JodaBeanUtils.notNull(((FixedSwapLegDetails) bean)._accrualEnd, "accrualEnd");
JodaBeanUtils.notNull(((FixedSwapLegDetails) bean)._discountFactors, "discountFactors");
JodaBeanUtils.notNull(((FixedSwapLegDetails) bean)._paymentTimes, "paymentTimes");
JodaBeanUtils.notNull(((FixedSwapLegDetails) bean)._paymentFractions, "paymentFractions");
JodaBeanUtils.notNull(((FixedSwapLegDetails) bean)._paymentAmounts, "paymentAmounts");
JodaBeanUtils.notNull(((FixedSwapLegDetails) bean)._notionals, "notionals");
JodaBeanUtils.notNull(((FixedSwapLegDetails) bean)._fixedRates, "fixedRates");
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| |
/*******************************************************************************
* Copyright 2013 EMBL-EBI
*
* 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 net.sf.cram;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.zip.GZIPInputStream;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileReader;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMProgramRecord;
import htsjdk.samtools.SAMReadGroupRecord;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SAMSequenceRecord;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import htsjdk.samtools.seekablestream.SeekableFileStream;
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.samtools.util.IOUtil;
import htsjdk.samtools.util.Log;
import net.sf.cram.CramTools.LevelConverter;
import net.sf.cram.CramTools.ValidationStringencyConverter;
import net.sf.cram.FixBAMFileHeader.MD5MismatchError;
import net.sf.cram.common.Utils;
import net.sf.cram.index.BAMQueryFilteringIterator;
import net.sf.cram.index.CramIndex;
import net.sf.cram.ref.ReferenceSource;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
public class Merge {
public static final String COMMAND = "merge";
public static void usage(JCommander jc) {
StringBuilder sb = new StringBuilder();
sb.append("\n");
jc.usage(sb);
System.out.println("Version " + Merge.class.getPackage().getImplementationVersion());
System.out.println(sb.toString());
}
public static void main(String[] args) throws IOException {
Params params = new Params();
JCommander jc = new JCommander(params);
jc.parse(args);
Log.setGlobalLogLevel(params.logLevel);
if (args.length == 0 || params.help) {
usage(jc);
System.exit(1);
}
if (params.reference == null) {
System.out.println("A reference fasta file is required.");
System.exit(1);
}
if (params.files == null || params.files.isEmpty()) {
System.out.println("At least one CRAM or BAM file is required.");
System.exit(1);
}
ReferenceSource referenceSource = null;
if (params.reference != null) {
System.setProperty("reference", params.reference.getAbsolutePath());
referenceSource = new ReferenceSource(params.reference);
} else {
String prop = System.getProperty("reference");
if (prop != null)
referenceSource = new ReferenceSource(new File(prop));
}
AlignmentSliceQuery query = params.region == null ? null : new AlignmentSliceQuery(params.region);
List<RecordSource> list = readFiles(params.files, params.reference, query, params.validationLevel);
StringBuffer mergeComment = new StringBuffer("Merged from:");
for (RecordSource source : list) {
mergeComment.append(" ").append(source.path);
}
resolveCollisions(list);
SAMFileHeader header = mergeHeaders(list);
header.setSortOrder(SAMFileHeader.SortOrder.coordinate);
FixBAMFileHeader fix = new FixBAMFileHeader(referenceSource);
fix.setConfirmMD5(true);
fix.setInjectURI(true);
fix.setIgnoreMD5Mismatch(false);
try {
fix.fixSequences(header.getSequenceDictionary().getSequences());
} catch (MD5MismatchError e) {
e.printStackTrace();
System.exit(1);
}
fix.addCramtoolsPG(header);
header.addComment(mergeComment.toString());
SAMFileWriter writer = null;
if (params.outFile != null)
if (!params.samFormat)
writer = new SAMFileWriterFactory().makeBAMWriter(header, true, params.outFile);
else
writer = new SAMFileWriterFactory().makeSAMWriter(header, true, params.outFile);
else if (!params.samFormat) {
// hack to write BAM format to stdout:
File file = File.createTempFile("bam", null);
file.deleteOnExit();
SAMFileWriter bamWriter = new SAMFileWriterFactory().makeBAMWriter(header, true, System.out);
writer = bamWriter;
}
else {
writer = Utils.createSAMTextWriter(null, System.out, header, params.printSAMHeader);
}
MergedIterator mergedIterator = new MergedIterator(list, header);
while (mergedIterator.hasNext()) {
SAMRecord record = mergedIterator.next();
writer.addAlignment(record);
}
mergedIterator.close();
for (RecordSource source : list)
source.close();
writer.close();
}
private static List<RecordSource> readFiles(List<File> files, File refFile,
AlignmentSliceQuery query, ValidationStringency ValidationStringency) throws IOException {
List<RecordSource> sources = new ArrayList<Merge.RecordSource>(files.size());
SAMFileReader.setDefaultValidationStringency(ValidationStringency);
for (File file : files) {
IOUtil.assertFileIsReadable(file);
RecordSource source = new RecordSource();
sources.add(source);
source.id = file.getName();
source.path = file.getAbsolutePath();
File index = new File(file.getAbsolutePath() + ".bai");
if (index.exists()) {
SAMFileReader reader = new SAMFileReader(file, index);
source.reader = reader;
if (query == null)
source.it = reader.iterator();
else
source.it = reader.query(query.sequence, query.start, query.end, true);
} else {
index = new File(file.getAbsolutePath() + ".crai");
if (index.exists()) {
SAMFileReader reader = new SAMFileReader(file);
source.reader = reader;
if (query == null)
source.it = reader.iterator();
else {
SeekableFileStream is = new SeekableFileStream(file);
FileInputStream fis = new FileInputStream(index);
GZIPInputStream gis = new GZIPInputStream(new BufferedInputStream(fis));
BufferedInputStream bis = new BufferedInputStream(gis);
List<CramIndex.Entry> full = CramIndex.readIndex(gis);
List<CramIndex.Entry> entries = new LinkedList<CramIndex.Entry>();
SAMSequenceRecord sequence = reader.getFileHeader().getSequence(query.sequence);
if (sequence == null)
throw new RuntimeException("Sequence not found: " + query.sequence);
entries.addAll(CramIndex.find(full, sequence.getSequenceIndex(), query.start, query.end
- query.start));
bis.close();
SamInputResource sir = SamInputResource.of(is);
final SamReader samReader = SamReaderFactory.make().referenceSequence(refFile).open(sir);
is.seek(entries.get(0).containerStartOffset);
BAMQueryFilteringIterator bit = new BAMQueryFilteringIterator(samReader.iterator(), query.sequence, query.start,
query.end, BAMQueryFilteringIterator.QueryType.CONTAINED, reader.getFileHeader());
source.it = bit;
}
} else {
SAMFileReader reader = new SAMFileReader(file);
source.reader = reader;
source.it = reader.iterator();
}
}
}
return sources;
}
private static List<String> resolveCollisions(List<RecordSource> list) {
ArrayList<String> result = new ArrayList<String>(list.size());
// count list entries:
Map<String, Integer> idCountMap = new TreeMap<String, Integer>();
for (RecordSource source : list) {
if (idCountMap.containsKey(source.id)) {
idCountMap.put(source.id, idCountMap.get(source.id).intValue() + 1);
} else
idCountMap.put(source.id, 1);
}
// update entries with their number of occurrence except for singletons:
for (int i = list.size() - 1; i >= 0; i--) {
RecordSource source = list.get(i);
int count = idCountMap.get(source.id);
if (count > 1) {
list.get(i).id = source.id + String.valueOf(count);
idCountMap.put(source.id, --count);
}
}
return result;
}
private static class RecordSource {
private String path;
private String id;
private CloseableIterator<SAMRecord> it;
private SAMFileReader reader;
public RecordSource() {
}
public RecordSource(String id, SAMRecordIterator it) {
this.id = id;
this.it = it;
}
public void close() {
if (it != null)
it.close();
if (reader != null)
reader.close();
}
}
private static SAMFileHeader mergeHeaders(List<RecordSource> sources) {
SAMFileHeader header = new SAMFileHeader();
for (RecordSource source : sources) {
SAMFileHeader h = source.reader.getFileHeader();
for (SAMSequenceRecord seq : h.getSequenceDictionary().getSequences()) {
if (header.getSequenceDictionary().getSequence(seq.getSequenceName()) == null)
header.addSequence(seq);
}
for (SAMProgramRecord pro : h.getProgramRecords()) {
if (header.getProgramRecord(pro.getProgramGroupId()) == null)
header.addProgramRecord(pro);
}
for (String comment : h.getComments())
header.addComment(comment);
for (SAMReadGroupRecord rg : h.getReadGroups()) {
if (header.getReadGroup(rg.getReadGroupId()) == null)
header.addReadGroup(rg);
}
}
return header;
}
private static class MergedIterator implements SAMRecordIterator {
private static String delim = ".";
private RecordSource[] sources;
private SAMRecord[] records;
private SAMRecord next;
private SAMFileHeader header;
public MergedIterator(List<RecordSource> list, SAMFileHeader header) {
this.header = header;
sources = list.toArray(new RecordSource[list.size()]);
records = new SAMRecord[list.size()];
for (int i = 0; i < records.length; i++) {
if (sources[i].it.hasNext())
records[i] = sources[i].it.next();
}
advance();
}
@Override
public void close() {
if (sources != null)
for (RecordSource source : sources)
if (source != null)
source.close();
records = null;
next = null;
}
@Override
public boolean hasNext() {
return next != null;
}
private void advance() {
int candidateIndex = getIndexOfMinAlignment();
if (candidateIndex < 0) {
next = null;
} else {
next = records[candidateIndex];
SAMSequenceRecord sequence = header.getSequence(next.getReferenceName());
next.setHeader(header);
next.setReferenceIndex(sequence.getSequenceIndex());
next.setReadName(sources[candidateIndex].id + delim + next.getReadName());
if (next.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) {
next.setMateAlignmentStart(SAMRecord.NO_ALIGNMENT_START);
} else {
SAMSequenceRecord mateSequence = header.getSequence(next.getMateReferenceName());
next.setMateReferenceIndex(mateSequence.getSequenceIndex());
}
if (sources[candidateIndex].it.hasNext())
records[candidateIndex] = sources[candidateIndex].it.next();
else
records[candidateIndex] = null;
}
}
@Override
public SAMRecord next() {
if (next == null)
return null;
SAMRecord result = next;
advance();
return result;
}
@Override
public void remove() {
throw new RuntimeException("Unsupported operation.");
}
@Override
public SAMRecordIterator assertSorted(SAMFileHeader.SortOrder sortOrder) {
// TODO Auto-generated method stub
return null;
}
private int getIndexOfMinAlignment() {
if (records == null || records.length == 0)
return -1;
int min = Integer.MAX_VALUE;
int index = -1;
for (int i = 0; i < records.length; i++) {
if (records[i] == null)
continue;
int start = records[i].getAlignmentStart();
if (start > 0 && start < min) {
min = start;
index = i;
}
}
return index;
}
}
@Parameters(commandDescription = "Tool to merge CRAM or BAM files. ")
static class Params {
@Parameter(names = { "-l", "--log-level" }, description = "Change log level: DEBUG, INFO, WARNING, ERROR.", converter = LevelConverter.class)
Log.LogLevel logLevel = Log.LogLevel.ERROR;
@Parameter(names = { "-v", "--validation-level" }, description = "Change validation stringency level: STRICT, LENIENT, SILENT.", converter = ValidationStringencyConverter.class)
ValidationStringency validationLevel = ValidationStringency.DEFAULT_STRINGENCY;
@Parameter(names = { "--reference-fasta-file", "-R" }, converter = FileConverter.class, description = "Path to the reference fasta file, it must be uncompressed and indexed (use 'samtools faidx' for example).")
File reference;
@Parameter(names = { "--output-file" }, converter = FileConverter.class, description = "Path to the output BAM file. Omit for stdout.")
File outFile;
@Parameter(names = { "--sam-format" }, description = "Output in SAM rather than BAM format.")
boolean samFormat = false;
@Parameter(names = { "--sam-header" }, description = "Print SAM file header when output format is text SAM.")
boolean printSAMHeader = false;
@Parameter(names = { "--region", "-r" }, description = "Alignment slice specification, for example: chr1:65000-100000.")
String region;
@Parameter(names = { "-h", "--help" }, description = "Print help and quit")
boolean help = false;
@Parameter(converter = FileConverter.class, description = "The paths to the CRAM or BAM files to uncompress. ")
List<File> files;
}
}
| |
/*
* Copyright (C) 2008 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.primitives;
public class IntsTest_gwt extends com.google.gwt.junit.client.GWTTestCase {
@Override public String getModuleName() {
return "com.google.common.primitives.testModule";
}
public void testAsListEmpty() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testAsListEmpty();
}
public void testAsList_isAView() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testAsList_isAView();
}
public void testAsList_subList_toArray_roundTrip() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testAsList_subList_toArray_roundTrip();
}
public void testAsList_toArray_roundTrip() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testAsList_toArray_roundTrip();
}
public void testByteArrayRoundTrips() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testByteArrayRoundTrips();
}
public void testCheckedCast() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testCheckedCast();
}
public void testCompare() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testCompare();
}
public void testConcat() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testConcat();
}
public void testConstrainToRange() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testConstrainToRange();
}
public void testContains() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testContains();
}
public void testEnsureCapacity() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testEnsureCapacity();
}
public void testEnsureCapacity_fail() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testEnsureCapacity_fail();
}
public void testFromByteArray() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testFromByteArray();
}
public void testFromByteArrayFails() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testFromByteArrayFails();
}
public void testFromBytes() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testFromBytes();
}
public void testHashCode() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testHashCode();
}
public void testIndexOf() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testIndexOf();
}
public void testIndexOf_arrayTarget() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testIndexOf_arrayTarget();
}
public void testJoin() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testJoin();
}
public void testLastIndexOf() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testLastIndexOf();
}
public void testLexicographicalComparator() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testLexicographicalComparator();
}
public void testMax() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testMax();
}
public void testMax_noArgs() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testMax_noArgs();
}
public void testMin() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testMin();
}
public void testMin_noArgs() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testMin_noArgs();
}
public void testReverse() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testReverse();
}
public void testReverseIndexed() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testReverseIndexed();
}
public void testSaturatedCast() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testSaturatedCast();
}
public void testSortDescending() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testSortDescending();
}
public void testSortDescendingIndexed() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testSortDescendingIndexed();
}
public void testStringConverter_convert() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testStringConverter_convert();
}
public void testStringConverter_convertError() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testStringConverter_convertError();
}
public void testStringConverter_nullConversions() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testStringConverter_nullConversions();
}
public void testStringConverter_reverse() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testStringConverter_reverse();
}
public void testToArray() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testToArray();
}
public void testToArray_threadSafe() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testToArray_threadSafe();
}
public void testToArray_withConversion() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testToArray_withConversion();
}
public void testToArray_withNull() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testToArray_withNull();
}
public void testToByteArray() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testToByteArray();
}
public void testTryParse() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testTryParse();
}
public void testTryParse_radix() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testTryParse_radix();
}
public void testTryParse_radixTooBig() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testTryParse_radixTooBig();
}
public void testTryParse_radixTooSmall() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testTryParse_radixTooSmall();
}
public void testTryParse_withNullGwt() throws Exception {
com.google.common.primitives.IntsTest testCase = new com.google.common.primitives.IntsTest();
testCase.testTryParse_withNullGwt();
}
}
| |
package com.github.ppamorim.bound;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import com.github.ppamorim.bound.utils.ColorUtil;
import com.github.ppamorim.bound.utils.ViewUtil;
public class RippleDrawable extends Drawable implements Animatable, OnTouchListener {
private boolean mRunning = false;
private Paint mShaderPaint;
private Paint mFillPaint;
private Mask mMask;
private RadialGradient mInShader;
private RadialGradient mOutShader;
private Matrix mMatrix;
private int mAlpha = 255;
private Drawable mBackgroundDrawable;
private RectF mBackgroundBounds;
private Path mBackground;
private int mBackgroundAnimDuration;
private int mBackgroundColor;
private float mBackgroundAlphaPercent;
private PointF mRipplePoint;
private float mRippleRadius;
private int mRippleType;
private int mMaxRippleRadius;
private int mRippleAnimDuration;
private int mRippleColor;
private float mRippleAlphaPercent;
private int mDelayClickType;
private Interpolator mInInterpolator;
private Interpolator mOutInterpolator;
private long mStartTime;
private int mState = STATE_OUT;
public static final int DELAY_CLICK_NONE = 0;
public static final int DELAY_CLICK_UNTIL_RELEASE = 1;
public static final int DELAY_CLICK_AFTER_RELEASE = 2;
private static final int STATE_OUT = 0;
private static final int STATE_PRESS = 1;
private static final int STATE_HOVER = 2;
private static final int STATE_RELEASE_ON_HOLD = 3;
private static final int STATE_RELEASE = 4;
private static final int TYPE_TOUCH_MATCH_VIEW = -1;
private static final int TYPE_TOUCH = 0;
private static final int TYPE_WAVE = 1;
private static final float[] GRADIENT_STOPS = new float[]{0f, 0.99f, 1f};
private static final float GRADIENT_RADIUS = 16;
private RippleDrawable(Drawable backgroundDrawable, int backgroundAnimDuration, int backgroundColor, int rippleType, int delayClickType, int maxRippleRadius, int rippleAnimDuration, int rippleColor, Interpolator inInterpolator, Interpolator outInterpolator, int type, int topLeftCornerRadius, int topRightCornerRadius, int bottomRightCornerRadius, int bottomLeftCornerRadius, int left, int top, int right, int bottom){
setBackgroundDrawable(backgroundDrawable);
mBackgroundAnimDuration = backgroundAnimDuration;
mBackgroundColor = backgroundColor;
mRippleType = rippleType;
setDelayClickType(delayClickType);
mMaxRippleRadius = maxRippleRadius;
mRippleAnimDuration = rippleAnimDuration;
mRippleColor = rippleColor;
if(mRippleType == TYPE_TOUCH && mMaxRippleRadius <= 0)
mRippleType = TYPE_TOUCH_MATCH_VIEW;
mInInterpolator = inInterpolator;
mOutInterpolator = outInterpolator;
setMask(type, topLeftCornerRadius, topRightCornerRadius, bottomRightCornerRadius, bottomLeftCornerRadius, left, top, right, bottom);
mFillPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mFillPaint.setStyle(Paint.Style.FILL);
mShaderPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mShaderPaint.setStyle(Paint.Style.FILL);
mBackground = new Path();
mBackgroundBounds = new RectF();
mRipplePoint = new PointF();
mMatrix = new Matrix();
mInShader = new RadialGradient(0, 0, GRADIENT_RADIUS, new int[]{
mRippleColor, mRippleColor, 0}, GRADIENT_STOPS, Shader.TileMode.CLAMP);
if(mRippleType == TYPE_WAVE)
mOutShader = new RadialGradient(0, 0, GRADIENT_RADIUS, new int[]{0, ColorUtil.getColor(
mRippleColor, 0f), mRippleColor}, GRADIENT_STOPS, Shader.TileMode.CLAMP);
}
public void setBackgroundDrawable(Drawable backgroundDrawable){
mBackgroundDrawable = backgroundDrawable;
if(mBackgroundDrawable != null)
mBackgroundDrawable.setBounds(getBounds());
}
public int getDelayClickType(){
return mDelayClickType;
}
public void setDelayClickType(int type){
mDelayClickType = type;
}
public void setMask(int type, int topLeftCornerRadius, int topRightCornerRadius, int bottomRightCornerRadius, int bottomLeftCornerRadius, int left, int top, int right, int bottom){
mMask = new Mask(type, topLeftCornerRadius, topRightCornerRadius, bottomRightCornerRadius, bottomLeftCornerRadius, left, top, right, bottom);
}
@Override
public void setAlpha(int alpha) {
mAlpha = alpha;
}
@Override
public void setColorFilter(ColorFilter filter) {
mFillPaint.setColorFilter(filter);
mShaderPaint.setColorFilter(filter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
public long getClickDelayTime(){
switch (mDelayClickType){
case DELAY_CLICK_NONE:
return -1;
case DELAY_CLICK_UNTIL_RELEASE:
if(mState == STATE_RELEASE_ON_HOLD)
return Math.max(mBackgroundAnimDuration, mRippleAnimDuration) - (SystemClock.uptimeMillis() - mStartTime);
break;
case DELAY_CLICK_AFTER_RELEASE:
if(mState == STATE_RELEASE_ON_HOLD)
return 2 * Math.max(mBackgroundAnimDuration, mRippleAnimDuration) - (SystemClock.uptimeMillis() - mStartTime);
else if(mState == STATE_RELEASE)
return Math.max(mBackgroundAnimDuration, mRippleAnimDuration) - (SystemClock.uptimeMillis() - mStartTime);
break;
}
return -1;
}
private void setRippleState(int state){
if(mState != state){
mState = state;
if(mState != STATE_OUT){
if(mState != STATE_HOVER)
start();
else
stop();
}
else
stop();
}
}
private boolean setRippleEffect(float x, float y, float radius){
if(mRipplePoint.x != x || mRipplePoint.y != y || mRippleRadius != radius){
mRipplePoint.set(x, y);
mRippleRadius = radius;
radius = mRippleRadius / GRADIENT_RADIUS;
mMatrix.reset();
mMatrix.postTranslate(x, y);
mMatrix.postScale(radius, radius, x, y);
mInShader.setLocalMatrix(mMatrix);
if(mOutShader != null)
mOutShader.setLocalMatrix(mMatrix);
return true;
}
return false;
}
@Override
protected void onBoundsChange(Rect bounds) {
if(mBackgroundDrawable != null)
mBackgroundDrawable.setBounds(bounds);
mBackgroundBounds.set(bounds.left + mMask.left, bounds.top + mMask.top, bounds.right - mMask.right, bounds.bottom - mMask.bottom);
mBackground.reset();
switch (mMask.type) {
case Mask.TYPE_OVAL:
mBackground.addOval(mBackgroundBounds, Direction.CW);
break;
case Mask.TYPE_RECTANGLE:
mBackground.addRoundRect(mBackgroundBounds, mMask.cornerRadius, Direction.CW);
break;
}
}
@Override
public boolean isStateful() {
return mBackgroundDrawable != null && mBackgroundDrawable.isStateful();
}
@Override
protected boolean onStateChange(int[] state) {
return mBackgroundDrawable != null && mBackgroundDrawable.setState(state);
}
@Override
public void draw(Canvas canvas) {
if(mBackgroundDrawable != null)
mBackgroundDrawable.draw(canvas);
switch (mRippleType) {
case TYPE_TOUCH:
case TYPE_TOUCH_MATCH_VIEW:
drawTouch(canvas);
break;
case TYPE_WAVE:
drawWave(canvas);
break;
}
}
private void drawTouch(Canvas canvas){
if(mState != STATE_OUT){
if(mBackgroundAlphaPercent > 0){
mFillPaint.setColor(mBackgroundColor);
mFillPaint.setAlpha(Math.round(mAlpha * mBackgroundAlphaPercent));
canvas.drawPath(mBackground, mFillPaint);
}
if(mRippleRadius > 0 && mRippleAlphaPercent > 0){
mShaderPaint.setAlpha(Math.round(mAlpha * mRippleAlphaPercent));
mShaderPaint.setShader(mInShader);
canvas.drawPath(mBackground, mShaderPaint);
}
}
}
private void drawWave(Canvas canvas){
if(mState != STATE_OUT){
if(mState == STATE_RELEASE){
if(mRippleRadius == 0){
mFillPaint.setColor(mRippleColor);
canvas.drawPath(mBackground, mFillPaint);
}
else{
mShaderPaint.setShader(mOutShader);
canvas.drawPath(mBackground, mShaderPaint);
}
}
else if(mRippleRadius > 0){
mShaderPaint.setShader(mInShader);
canvas.drawPath(mBackground, mShaderPaint);
}
}
}
private int getMaxRippleRadius(float x, float y){
float x1 = x < mBackgroundBounds.centerX() ? mBackgroundBounds.right : mBackgroundBounds.left;
float y1 = y < mBackgroundBounds.centerY() ? mBackgroundBounds.bottom : mBackgroundBounds.top;
return (int)Math.round(Math.sqrt(Math.pow(x1 - x, 2) + Math.pow(y1 - y, 2)));
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
if(mState == STATE_OUT || mState == STATE_RELEASE){
if(mRippleType == TYPE_WAVE || mRippleType == TYPE_TOUCH_MATCH_VIEW)
mMaxRippleRadius = getMaxRippleRadius(event.getX(), event.getY());
setRippleEffect(event.getX(), event.getY(), 0);
setRippleState(STATE_PRESS);
}
else if(mRippleType == TYPE_TOUCH){
if(setRippleEffect(event.getX(), event.getY(), mRippleRadius))
invalidateSelf();
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if(mState != STATE_OUT){
if(mState == STATE_HOVER){
if(mRippleType == TYPE_WAVE || mRippleType == TYPE_TOUCH_MATCH_VIEW)
setRippleEffect(mRipplePoint.x, mRipplePoint.y, 0);
setRippleState(STATE_RELEASE);
}
else
setRippleState(STATE_RELEASE_ON_HOLD);
}
break;
}
return true;
}
//Animation: based on http://cyrilmottier.com/2012/11/27/actionbar-on-the-move/
public void cancel(){
setRippleState(STATE_OUT);
}
private void resetAnimation(){
mStartTime = SystemClock.uptimeMillis();
}
@Override
public void start() {
if(isRunning())
return;
resetAnimation();
scheduleSelf(mUpdater, SystemClock.uptimeMillis() + ViewUtil.FRAME_DURATION);
invalidateSelf();
}
@Override
public void stop() {
if(!isRunning())
return;
mRunning = false;
unscheduleSelf(mUpdater);
invalidateSelf();
}
@Override
public boolean isRunning() {
return mRunning;
}
@Override
public void scheduleSelf(Runnable what, long when) {
mRunning = true;
super.scheduleSelf(what, when);
}
private final Runnable mUpdater = new Runnable() {
@Override
public void run() {
switch (mRippleType) {
case TYPE_TOUCH:
case TYPE_TOUCH_MATCH_VIEW:
updateTouch();
break;
case TYPE_WAVE:
updateWave();
break;
}
}
};
private void updateTouch(){
if(mState != STATE_RELEASE){
float backgroundProgress = Math.min(1f, (float)(SystemClock.uptimeMillis() - mStartTime) / mBackgroundAnimDuration);
mBackgroundAlphaPercent = mInInterpolator.getInterpolation(backgroundProgress) * Color.alpha(mBackgroundColor) / 255f;
float touchProgress = Math.min(1f, (float)(SystemClock.uptimeMillis() - mStartTime) / mRippleAnimDuration);
mRippleAlphaPercent = mInInterpolator.getInterpolation(touchProgress);
setRippleEffect(mRipplePoint.x, mRipplePoint.y, mMaxRippleRadius * mInInterpolator.getInterpolation(touchProgress));
if(backgroundProgress == 1f && touchProgress == 1f){
mStartTime = SystemClock.uptimeMillis();
setRippleState(mState == STATE_PRESS ? STATE_HOVER : STATE_RELEASE);
}
}
else{
float backgroundProgress = Math.min(1f, (float)(SystemClock.uptimeMillis() - mStartTime) / mBackgroundAnimDuration);
mBackgroundAlphaPercent = (1f - mOutInterpolator.getInterpolation(backgroundProgress)) * Color.alpha(mBackgroundColor) / 255f;
float touchProgress = Math.min(1f, (float)(SystemClock.uptimeMillis() - mStartTime) / mRippleAnimDuration);
mRippleAlphaPercent = 1f - mOutInterpolator.getInterpolation(touchProgress);
setRippleEffect(mRipplePoint.x, mRipplePoint.y, mMaxRippleRadius * (1f + 0.5f * mOutInterpolator.getInterpolation(touchProgress)));
if(backgroundProgress == 1f && touchProgress == 1f)
setRippleState(STATE_OUT);
}
if(isRunning())
scheduleSelf(mUpdater, SystemClock.uptimeMillis() + ViewUtil.FRAME_DURATION);
invalidateSelf();
}
private void updateWave(){
float progress = Math.min(1f, (float)(SystemClock.uptimeMillis() - mStartTime) / mRippleAnimDuration);
if(mState != STATE_RELEASE){
setRippleEffect(mRipplePoint.x, mRipplePoint.y, mMaxRippleRadius * mInInterpolator.getInterpolation(progress));
if(progress == 1f){
mStartTime = SystemClock.uptimeMillis();
if(mState == STATE_PRESS)
setRippleState(STATE_HOVER);
else{
setRippleEffect(mRipplePoint.x, mRipplePoint.y, 0);
setRippleState(STATE_RELEASE);
}
}
}
else{
setRippleEffect(mRipplePoint.x, mRipplePoint.y, mMaxRippleRadius * mOutInterpolator.getInterpolation(progress));
if(progress == 1f)
setRippleState(STATE_OUT);
}
if(isRunning())
scheduleSelf(mUpdater, SystemClock.uptimeMillis() + ViewUtil.FRAME_DURATION);
invalidateSelf();
}
public static class Mask{
public static final int TYPE_RECTANGLE = 0;
public static final int TYPE_OVAL = 1;
final int type;
final float[] cornerRadius = new float[8];
final int left;
final int top;
final int right;
final int bottom;
public Mask(int type, int topLeftCornerRadius, int topRightCornerRadius, int bottomRightCornerRadius, int bottomLeftCornerRadius, int left, int top, int right, int bottom){
this.type = type;
cornerRadius[0] = topLeftCornerRadius;
cornerRadius[1] = topLeftCornerRadius;
cornerRadius[2] = topRightCornerRadius;
cornerRadius[3] = topRightCornerRadius;
cornerRadius[4] = bottomRightCornerRadius;
cornerRadius[5] = bottomRightCornerRadius;
cornerRadius[6] = bottomLeftCornerRadius;
cornerRadius[7] = bottomLeftCornerRadius;
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
}
public static class Builder{
private Drawable mBackgroundDrawable;
private int mBackgroundAnimDuration = 200;
private int mBackgroundColor;
private int mRippleType;
private int mMaxRippleRadius;
private int mRippleAnimDuration = 400;
private int mRippleColor;
private int mDelayClickType;
private Interpolator mInInterpolator;
private Interpolator mOutInterpolator;
private int mMaskType;
private int mMaskTopLeftCornerRadius;
private int mMaskTopRightCornerRadius;
private int mMaskBottomLeftCornerRadius;
private int mMaskBottomRightCornerRadius;
private int mMaskLeft;
private int mMaskTop;
private int mMaskRight;
private int mMaskBottom;
public Builder(){}
public Builder(Context context, int defStyleRes){
this(context, null, 0, defStyleRes);
}
public Builder(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RippleDrawable, defStyleAttr, defStyleRes);
int type, resId;
backgroundColor(a.getColor(R.styleable.RippleDrawable_rd_backgroundColor, 0));
backgroundAnimDuration(a.getInteger(R.styleable.RippleDrawable_rd_backgroundAnimDuration, context.getResources().getInteger(android.R.integer.config_mediumAnimTime)));
rippleType(a.getInteger(R.styleable.RippleDrawable_rd_rippleType, RippleDrawable.TYPE_TOUCH));
delayClickType(a.getInteger(R.styleable.RippleDrawable_rd_delayClick, RippleDrawable.DELAY_CLICK_NONE));
type = ViewUtil.getType(a, R.styleable.RippleDrawable_rd_maxRippleRadius);
if(type >= TypedValue.TYPE_FIRST_INT && type <= TypedValue.TYPE_LAST_INT)
maxRippleRadius(a.getInteger(R.styleable.RippleDrawable_rd_maxRippleRadius, -1));
else
maxRippleRadius(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_maxRippleRadius, ViewUtil.dpToPx(context, 48)));
rippleColor(a.getColor(R.styleable.RippleDrawable_rd_rippleColor, ViewUtil.colorControlHighlight(context, 0)));
rippleAnimDuration(a.getInteger(R.styleable.RippleDrawable_rd_rippleAnimDuration, context.getResources().getInteger(android.R.integer.config_mediumAnimTime)));
if((resId = a.getResourceId(R.styleable.RippleDrawable_rd_inInterpolator, 0)) != 0)
inInterpolator(AnimationUtils.loadInterpolator(context, resId));
if((resId = a.getResourceId(R.styleable.RippleDrawable_rd_outInterpolator, 0)) != 0)
outInterpolator(AnimationUtils.loadInterpolator(context, resId));
maskType(a.getInteger(R.styleable.RippleDrawable_rd_maskType, Mask.TYPE_RECTANGLE));
cornerRadius(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_cornerRadius, 0));
topLeftCornerRadius(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_topLeftCornerRadius, mMaskTopLeftCornerRadius));
topRightCornerRadius(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_topRightCornerRadius, mMaskTopRightCornerRadius));
bottomRightCornerRadius(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_bottomRightCornerRadius, mMaskBottomRightCornerRadius));
bottomLeftCornerRadius(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_bottomLeftCornerRadius, mMaskBottomLeftCornerRadius));
padding(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_padding, 0));
left(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_leftPadding, mMaskLeft));
right(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_rightPadding, mMaskRight));
top(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_topPadding, mMaskTop));
bottom(a.getDimensionPixelSize(R.styleable.RippleDrawable_rd_bottomPadding, mMaskBottom));
a.recycle();
}
public RippleDrawable build(){
if(mInInterpolator == null)
mInInterpolator = new AccelerateInterpolator();
if(mOutInterpolator == null)
mOutInterpolator = new DecelerateInterpolator();
return new RippleDrawable(mBackgroundDrawable, mBackgroundAnimDuration, mBackgroundColor, mRippleType, mDelayClickType, mMaxRippleRadius, mRippleAnimDuration, mRippleColor, mInInterpolator, mOutInterpolator, mMaskType, mMaskTopLeftCornerRadius, mMaskTopRightCornerRadius, mMaskBottomRightCornerRadius, mMaskBottomLeftCornerRadius, mMaskLeft, mMaskTop, mMaskRight, mMaskBottom);
}
public Builder backgroundDrawable(Drawable drawable){
mBackgroundDrawable = drawable;
return this;
}
public Builder backgroundAnimDuration(int duration){
mBackgroundAnimDuration = duration;
return this;
}
public Builder backgroundColor(int color){
mBackgroundColor = color;
return this;
}
public Builder rippleType(int type){
mRippleType = type;
return this;
}
public Builder delayClickType(int type){
mDelayClickType = type;
return this;
}
public Builder maxRippleRadius(int radius){
mMaxRippleRadius = radius;
return this;
}
public Builder rippleAnimDuration(int duration){
mRippleAnimDuration = duration;
return this;
}
public Builder rippleColor(int color){
mRippleColor = color;
return this;
}
public Builder inInterpolator(Interpolator interpolator){
mInInterpolator = interpolator;
return this;
}
public Builder outInterpolator(Interpolator interpolator){
mOutInterpolator = interpolator;
return this;
}
public Builder maskType(int type){
mMaskType = type;
return this;
}
public Builder cornerRadius(int radius){
mMaskTopLeftCornerRadius = radius;
mMaskTopRightCornerRadius = radius;
mMaskBottomLeftCornerRadius = radius;
mMaskBottomRightCornerRadius = radius;
return this;
}
public Builder topLeftCornerRadius(int radius){
mMaskTopLeftCornerRadius = radius;
return this;
}
public Builder topRightCornerRadius(int radius){
mMaskTopRightCornerRadius = radius;
return this;
}
public Builder bottomLeftCornerRadius(int radius){
mMaskBottomLeftCornerRadius = radius;
return this;
}
public Builder bottomRightCornerRadius(int radius){
mMaskBottomRightCornerRadius = radius;
return this;
}
public Builder padding(int padding){
mMaskLeft = padding;
mMaskTop = padding;
mMaskRight = padding;
mMaskBottom = padding;
return this;
}
public Builder left(int padding){
mMaskLeft = padding;
return this;
}
public Builder top(int padding){
mMaskTop = padding;
return this;
}
public Builder right(int padding){
mMaskRight = padding;
return this;
}
public Builder bottom(int padding){
mMaskBottom = padding;
return this;
}
}
}
| |
/*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.serialization.serializer.record.string;
import java.io.IOException;
import java.io.StringWriter;
import java.text.ParseException;
import java.util.*;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.common.parser.OStringParser;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OUserObject2RecordHandler;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.record.*;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.fetch.OFetchHelper;
import com.orientechnologies.orient.core.fetch.OFetchPlan;
import com.orientechnologies.orient.core.fetch.json.OJSONFetchContext;
import com.orientechnologies.orient.core.fetch.json.OJSONFetchListener;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordStringable;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentHelper;
import com.orientechnologies.orient.core.record.impl.ODocumentInternal;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.serialization.OBase64Utils;
import com.orientechnologies.orient.core.serialization.serializer.OJSONWriter;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.util.ODateHelper;
@SuppressWarnings("serial")
public class ORecordSerializerJSON extends ORecordSerializerStringAbstract {
public static final String NAME = "json";
public static final ORecordSerializerJSON INSTANCE = new ORecordSerializerJSON();
public static final String ATTRIBUTE_FIELD_TYPES = "@fieldTypes";
public static final char[] PARAMETER_SEPARATOR = new char[] { ':', ',' };
public static final int INITIAL_SIZE = 5000;
private static final Long MAX_INT = (long) Integer.MAX_VALUE;
private static final Long MIN_INT = (long) Integer.MIN_VALUE;
private static final Double MAX_FLOAT = (double) Float.MAX_VALUE;
private static final Double MIN_FLOAT = (double) Float.MIN_VALUE;
private interface CollectionItemVisitor {
void visitItem(Object item);
}
public class FormatSettings {
public boolean includeVer;
public boolean includeType;
public boolean includeId;
public boolean includeClazz;
public boolean attribSameRow;
public boolean alwaysFetchEmbeddedDocuments;
public int indentLevel;
public String fetchPlan = null;
public boolean keepTypes = true;
public boolean dateAsLong = false;
public boolean prettyPrint = false;
public FormatSettings(final String iFormat) {
if (iFormat == null) {
includeType = true;
includeVer = true;
includeId = true;
includeClazz = true;
attribSameRow = true;
indentLevel = 1;
fetchPlan = "";
keepTypes = true;
alwaysFetchEmbeddedDocuments = true;
} else {
includeType = false;
includeVer = false;
includeId = false;
includeClazz = false;
attribSameRow = false;
alwaysFetchEmbeddedDocuments = false;
indentLevel = 1;
keepTypes = false;
if (iFormat != null && !iFormat.isEmpty()) {
final String[] format = iFormat.split(",");
for (String f : format)
if (f.equals("type"))
includeType = true;
else if (f.equals("rid"))
includeId = true;
else if (f.equals("version"))
includeVer = true;
else if (f.equals("class"))
includeClazz = true;
else if (f.equals("attribSameRow"))
attribSameRow = true;
else if (f.startsWith("indent"))
indentLevel = Integer.parseInt(f.substring(f.indexOf(':') + 1));
else if (f.startsWith("fetchPlan"))
fetchPlan = f.substring(f.indexOf(':') + 1);
else if (f.startsWith("keepTypes"))
keepTypes = true;
else if (f.startsWith("alwaysFetchEmbedded"))
alwaysFetchEmbeddedDocuments = true;
else if (f.startsWith("dateAsLong"))
dateAsLong = true;
else if (f.startsWith("prettyPrint"))
prettyPrint = true;
else if (f.startsWith("graph") || f.startsWith("shallow"))
// SUPPORTED IN OTHER PARTS
;
else
throw new IllegalArgumentException("Unrecognized JSON formatting option: " + f);
}
}
}
}
@Override
public int getCurrentVersion() {
return 0;
}
@Override
public int getMinSupportedVersion() {
return 0;
}
public ORecord fromString(String iSource, ORecord iRecord, final String[] iFields, boolean needReload) {
return fromString(iSource, iRecord, iFields, null, needReload);
}
@Override
public ORecord fromString(String iSource, ORecord iRecord, final String[] iFields) {
return fromString(iSource, iRecord, iFields, null, false);
}
public ORecord fromString(String iSource, ORecord iRecord, final String[] iFields, final String iOptions, boolean needReload) {
iSource = unwrapSource(iSource);
boolean noMap = false;
if (iOptions != null) {
final String[] format = iOptions.split(",");
for (String f : format)
if (f.equalsIgnoreCase("noMap"))
noMap = true;
}
if (iRecord != null)
// RESET ALL THE FIELDS
iRecord.clear();
final List<String> fields = OStringSerializerHelper.smartSplit(iSource, PARAMETER_SEPARATOR, 0, -1, true, true, false, false,
' ', '\n', '\r', '\t');
if (fields.size() % 2 != 0)
throw new OSerializationException("Error on unmarshalling JSON content: wrong format \"" + iSource
+ "\". Use <field> : <value>");
Map<String, Character> fieldTypes = null;
if (fields != null && fields.size() > 0) {
// SEARCH FOR FIELD TYPES IF ANY
for (int i = 0; i < fields.size(); i += 2) {
final String fieldName = OStringSerializerHelper.getStringContent(fields.get(i));
final String fieldValue = fields.get(i + 1);
final String fieldValueAsString = OStringSerializerHelper.getStringContent(fieldValue);
if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) {
fieldTypes = loadFieldTypes(fieldTypes, fieldValueAsString);
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) {
if (iRecord == null || ORecordInternal.getRecordType(iRecord) != fieldValueAsString.charAt(0)) {
// CREATE THE RIGHT RECORD INSTANCE
iRecord = Orient.instance().getRecordFactoryManager().newInstance((byte) fieldValueAsString.charAt(0));
}
} else if (needReload && fieldName.equals(ODocumentHelper.ATTRIBUTE_RID) && iRecord instanceof ODocument) {
if (fieldValue != null && fieldValue.length() > 0) {
ORecord localRecord = ODatabaseRecordThreadLocal.INSTANCE.get().load(new ORecordId(fieldValueAsString));
if (localRecord != null)
iRecord = localRecord;
}
} else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_CLASS) && iRecord instanceof ODocument) {
((ODocument) iRecord).setClassNameIfExists("null".equals(fieldValueAsString) ? null : fieldValueAsString);
}
}
if (iRecord == null)
iRecord = new ODocument();
try {
int recordVersion = 0;
long timestamp = 0L;
long macAddress = 0L;
for (int i = 0; i < fields.size(); i += 2) {
final String fieldName = OStringSerializerHelper.getStringContent(fields.get(i));
final String fieldValue = fields.get(i + 1);
final String fieldValueAsString = OStringSerializerHelper.getStringContent(fieldValue);
// RECORD ATTRIBUTES
if (fieldName.equals(ODocumentHelper.ATTRIBUTE_RID))
ORecordInternal.setIdentity(iRecord, new ORecordId(fieldValueAsString));
else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION))
iRecord.getRecordVersion().setCounter(Integer.parseInt(fieldValue));
else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) {
continue;
} else if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) {
continue;
} else if (fieldName.equals("value") && !(iRecord instanceof ODocument)) {
// RECORD VALUE(S)
if ("null".equals(fieldValue))
iRecord.fromStream(new byte[] {});
else if (iRecord instanceof ORecordBytes) {
// BYTES
iRecord.fromStream(OBase64Utils.decode(fieldValueAsString));
} else if (iRecord instanceof ORecordStringable) {
((ORecordStringable) iRecord).value(fieldValueAsString);
} else
throw new IllegalArgumentException("unsupported type of record");
} else if (iRecord instanceof ODocument) {
final ODocument doc = ((ODocument) iRecord);
// DETERMINE THE TYPE FROM THE SCHEMA
OType type = determineType(doc, fieldName);
final Object v = getValue(doc, fieldName, fieldValue, fieldValueAsString, type, null, fieldTypes, noMap, iOptions);
if (v != null)
if (v instanceof Collection<?> && !((Collection<?>) v).isEmpty()) {
if (v instanceof ORecordLazyMultiValue)
((ORecordLazyMultiValue) v).setAutoConvertToRecord(false);
// CHECK IF THE COLLECTION IS EMBEDDED
if (type == null) {
// TRY TO UNDERSTAND BY FIRST ITEM
Object first = ((Collection<?>) v).iterator().next();
if (first != null && first instanceof ORecord && !((ORecord) first).getIdentity().isValid())
type = v instanceof Set<?> ? OType.EMBEDDEDSET : OType.EMBEDDEDLIST;
}
if (type != null) {
// TREAT IT AS EMBEDDED
doc.field(fieldName, v, type);
continue;
}
} else if (v instanceof Map<?, ?> && !((Map<?, ?>) v).isEmpty()) {
// CHECK IF THE MAP IS EMBEDDED
Object first = ((Map<?, ?>) v).values().iterator().next();
if (first != null && first instanceof ORecord && !((ORecord) first).getIdentity().isValid()) {
doc.field(fieldName, v, OType.EMBEDDEDMAP);
continue;
}
} else if (v instanceof ODocument && type != null && type.isLink()) {
String className = ((ODocument) v).getClassName();
if (className != null && className.length() > 0)
((ODocument) v).save();
}
if (type == null && fieldTypes != null && fieldTypes.containsKey(fieldName))
type = ORecordSerializerStringAbstract.getType(fieldValue, fieldTypes.get(fieldName));
if (v instanceof OTrackedSet<?>) {
if (OMultiValue.getFirstValue((Set<?>) v) instanceof OIdentifiable)
type = OType.LINKSET;
} else if (v instanceof OTrackedList<?>) {
if (OMultiValue.getFirstValue((List<?>) v) instanceof OIdentifiable)
type = OType.LINKLIST;
}
if (type != null)
doc.field(fieldName, v, type);
else
doc.field(fieldName, v);
}
}
} catch (Exception e) {
if (iRecord.getIdentity().isValid())
throw new OSerializationException("Error on unmarshalling JSON content for record " + iRecord.getIdentity(), e);
else
throw new OSerializationException("Error on unmarshalling JSON content for record: " + iSource, e);
}
}
return iRecord;
}
@Override
public StringBuilder toString(final ORecord iRecord, final StringBuilder iOutput, final String iFormat,
final OUserObject2RecordHandler iObjHandler, final Map<ODocument, Boolean> iMarshalledRecords, boolean iOnlyDelta,
boolean autoDetectCollectionType) {
try {
final StringWriter buffer = new StringWriter(INITIAL_SIZE);
final OJSONWriter json = new OJSONWriter(buffer, iFormat);
final FormatSettings settings = new FormatSettings(iFormat);
json.beginObject();
OJSONFetchContext context = new OJSONFetchContext(json, settings);
context.writeSignature(json, iRecord);
if (iRecord instanceof ODocument) {
final OFetchPlan fp = OFetchHelper.buildFetchPlan(settings.fetchPlan);
OFetchHelper.fetch(iRecord, null, fp, new OJSONFetchListener(), context, iFormat);
} else if (iRecord instanceof ORecordStringable) {
// STRINGABLE
final ORecordStringable record = (ORecordStringable) iRecord;
json.writeAttribute(settings.indentLevel + 1, true, "value", record.value());
} else if (iRecord instanceof ORecordBytes) {
// BYTES
final ORecordBytes record = (ORecordBytes) iRecord;
json.writeAttribute(settings.indentLevel + 1, true, "value", OBase64Utils.encodeBytes(record.toStream()));
} else
throw new OSerializationException("Error on marshalling record of type '" + iRecord.getClass()
+ "' to JSON. The record type cannot be exported to JSON");
json.endObject(0, true);
iOutput.append(buffer);
return iOutput;
} catch (IOException e) {
throw new OSerializationException("Error on marshalling of record to JSON", e);
}
}
@Override
public String toString() {
return NAME;
}
private OType determineType(ODocument doc, String fieldName) {
OType type = null;
final OClass cls = ODocumentInternal.getImmutableSchemaClass(doc);
if (cls != null) {
final OProperty prop = cls.getProperty(fieldName);
if (prop != null)
type = prop.getType();
}
return type;
}
private Map<String, Character> loadFieldTypes(Map<String, Character> fieldTypes, String fieldValueAsString) {
// LOAD THE FIELD TYPE MAP
final String[] fieldTypesParts = fieldValueAsString.split(",");
if (fieldTypesParts.length > 0) {
fieldTypes = new HashMap<String, Character>();
String[] part;
for (String f : fieldTypesParts) {
part = f.split("=");
if (part.length == 2)
fieldTypes.put(part[0], part[1].charAt(0));
}
}
return fieldTypes;
}
private String unwrapSource(String iSource) {
if (iSource == null)
throw new OSerializationException("Error on unmarshalling JSON content: content is null");
iSource = iSource.trim();
if (!iSource.startsWith("{") || !iSource.endsWith("}"))
throw new OSerializationException("Error on unmarshalling JSON content '" + iSource + "': content must be between { }");
iSource = iSource.substring(1, iSource.length() - 1).trim();
return iSource;
}
@SuppressWarnings("unchecked")
private Object getValue(final ODocument iRecord, String iFieldName, String iFieldValue, String iFieldValueAsString, OType iType,
OType iLinkedType, final Map<String, Character> iFieldTypes, final boolean iNoMap, final String iOptions) {
if (iFieldValue.equals("null"))
return null;
if (iFieldName != null && ODocumentInternal.getImmutableSchemaClass(iRecord) != null) {
final OProperty p = ODocumentInternal.getImmutableSchemaClass(iRecord).getProperty(iFieldName);
if (p != null) {
iType = p.getType();
iLinkedType = p.getLinkedType();
}
}
if (iType == null && iFieldTypes != null && iFieldTypes.containsKey(iFieldName))
iType = ORecordSerializerStringAbstract.getType(iFieldValue, iFieldTypes.get(iFieldName));
if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) {
return getValueAsObjectOrMap(iRecord, iFieldValue, iType, iLinkedType, iFieldTypes, iNoMap, iOptions);
} else if (iFieldValue.startsWith("[") && iFieldValue.endsWith("]")) {
return getValueAsCollection(iRecord, iFieldValue, iType, iLinkedType, iFieldTypes, iNoMap, iOptions);
}
if (iType == null)
// TRY TO DETERMINE THE CONTAINED TYPE from THE FIRST VALUE
if (iFieldValue.charAt(0) != '\"' && iFieldValue.charAt(0) != '\'') {
if (iFieldValue.equalsIgnoreCase("false") || iFieldValue.equalsIgnoreCase("true"))
iType = OType.BOOLEAN;
else {
Character c = null;
if (iFieldTypes != null) {
c = iFieldTypes.get(iFieldName);
if (c != null)
iType = ORecordSerializerStringAbstract.getType(iFieldValue + c);
}
if (c == null && !iFieldValue.isEmpty()) {
// TRY TO AUTODETERMINE THE BEST TYPE
if (iFieldValue.charAt(0) == ORID.PREFIX && iFieldValue.contains(":"))
iType = OType.LINK;
else if (OStringSerializerHelper.contains(iFieldValue, '.')) {
// DECIMAL FORMAT: DETERMINE IF DOUBLE OR FLOAT
final Double v = new Double(OStringSerializerHelper.getStringContent(iFieldValue));
if (canBeTrunkedToFloat(v))
return v.floatValue();
else
return v;
} else {
final Long v = new Long(OStringSerializerHelper.getStringContent(iFieldValue));
// INTEGER FORMAT: DETERMINE IF DOUBLE OR FLOAT
if (canBeTrunkedToInt(v))
return v.intValue();
else
return v;
}
}
}
} else if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}"))
iType = OType.EMBEDDED;
else {
if (iFieldValueAsString.length() >= 4 && iFieldValueAsString.charAt(0) == ORID.PREFIX && iFieldValueAsString.contains(":")) {
// IS IT A LINK?
final List<String> parts = OStringSerializerHelper.split(iFieldValueAsString, 1, -1, ':');
if (parts.size() == 2)
try {
Short.parseShort(parts.get(0));
// YES, IT'S A LINK
if (parts.get(1).matches("\\d+")) {
iType = OType.LINK;
}
} catch (Exception ignored) {
}
}
if (iFieldTypes != null) {
Character c = iFieldTypes.get(iFieldName);
if (c != null)
iType = ORecordSerializerStringAbstract.getType(iFieldValueAsString, c);
}
if (iType == null)
iType = OType.STRING;
}
if (iType != null)
switch (iType) {
case STRING:
return decodeJSON(iFieldValueAsString);
case LINK:
final int pos = iFieldValueAsString.indexOf('@');
if (pos > -1)
// CREATE DOCUMENT
return new ODocument(iFieldValueAsString.substring(1, pos), new ORecordId(iFieldValueAsString.substring(pos + 1)));
else {
// CREATE SIMPLE RID
return new ORecordId(iFieldValueAsString);
}
case EMBEDDED:
return fromString(iFieldValueAsString);
case DATE:
if (iFieldValueAsString == null || iFieldValueAsString.equals(""))
return null;
try {
// TRY TO PARSE AS LONG
return Long.parseLong(iFieldValueAsString);
} catch (NumberFormatException e) {
try {
// TRY TO PARSE AS DATE
return ODateHelper.getDateFormatInstance().parseObject(iFieldValueAsString);
} catch (ParseException ex) {
throw new OSerializationException("Unable to unmarshall date (format=" + ODateHelper.getDateFormat() + ") : "
+ iFieldValueAsString, e);
}
}
case DATETIME:
if (iFieldValueAsString == null || iFieldValueAsString.equals(""))
return null;
try {
// TRY TO PARSE AS LONG
return Long.parseLong(iFieldValueAsString);
} catch (NumberFormatException e) {
try {
// TRY TO PARSE AS DATETIME
return ODateHelper.getDateTimeFormatInstance().parseObject(iFieldValueAsString);
} catch (ParseException ex) {
throw new OSerializationException("Unable to unmarshall datetime (format=" + ODateHelper.getDateTimeFormat() + ") : "
+ iFieldValueAsString, e);
}
}
case BINARY:
return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValueAsString);
default:
return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValue);
}
return iFieldValueAsString;
}
private boolean canBeTrunkedToInt(Long v) {
return (v > 0) ? v.compareTo(MAX_INT) <= 0 : v.compareTo(MIN_INT) >= 0;
}
private boolean canBeTrunkedToFloat(Double v) {
// TODO not really correct check. Small numbers with high precision will be trunked while they shouldn't be
return (v > 0) ? v.compareTo(MAX_FLOAT) <= 0 : v.compareTo(MIN_FLOAT) >= 0;
}
/**
* OBJECT OR MAP. CHECK THE TYPE ATTRIBUTE TO KNOW IT.
*/
private Object getValueAsObjectOrMap(ODocument iRecord, String iFieldValue, OType iType, OType iLinkedType,
Map<String, Character> iFieldTypes, boolean iNoMap, String iOptions) {
final String[] fields = OStringParser.getWords(iFieldValue.substring(1, iFieldValue.length() - 1), ":,", true);
if (fields == null || fields.length == 0)
if (iNoMap) {
ODocument res = new ODocument();
ODocumentInternal.addOwner(res, iRecord);
return res;
} else
return new HashMap<String, Object>();
if (iNoMap || hasTypeField(fields)) {
return getValueAsRecord(iRecord, iFieldValue, iType, iOptions, fields);
} else {
return getValueAsMap(iRecord, iFieldValue, iLinkedType, iFieldTypes, false, iOptions, fields);
}
}
private Object getValueAsMap(ODocument iRecord, String iFieldValue, OType iLinkedType, Map<String, Character> iFieldTypes,
boolean iNoMap, String iOptions, String[] fields) {
if (fields.length % 2 == 1)
throw new OSerializationException("Bad JSON format on map. Expected pairs of field:value but received '" + iFieldValue + "'");
final Map<String, Object> embeddedMap = new LinkedHashMap<String, Object>();
for (int i = 0; i < fields.length; i += 2) {
String iFieldName = fields[i];
if (iFieldName.length() >= 2)
iFieldName = iFieldName.substring(1, iFieldName.length() - 1);
iFieldValue = fields[i + 1];
final String valueAsString = OStringSerializerHelper.getStringContent(iFieldValue);
embeddedMap.put(iFieldName,
getValue(iRecord, null, iFieldValue, valueAsString, iLinkedType, null, iFieldTypes, iNoMap, iOptions));
}
return embeddedMap;
}
private Object getValueAsRecord(ODocument iRecord, String iFieldValue, OType iType, String iOptions, String[] fields) {
ORID rid = new ORecordId(OStringSerializerHelper.getStringContent(getFieldValue("@rid", fields)));
boolean shouldReload = rid.isTemporary();
final ODocument recordInternal = (ODocument) fromString(iFieldValue, new ODocument(), null, iOptions, shouldReload);
if (shouldBeDeserializedAsEmbedded(recordInternal, iType))
ODocumentInternal.addOwner(recordInternal, iRecord);
else {
ODatabaseDocument database = ODatabaseRecordThreadLocal.INSTANCE.get();
if (rid.isPersistent() && database != null) {
ODocument documentToMerge = database.load(rid);
documentToMerge.merge(recordInternal, false, false);
return documentToMerge;
}
}
return recordInternal;
}
private Object getValueAsCollection(ODocument iRecord, String iFieldValue, OType iType, OType iLinkedType,
Map<String, Character> iFieldTypes, boolean iNoMap, String iOptions) {
// remove square brackets
iFieldValue = iFieldValue.substring(1, iFieldValue.length() - 1);
if (iType == OType.LINKBAG) {
final ORidBag bag = new ORidBag();
parseCollection(iRecord, iFieldValue, iType, OType.LINK, iFieldTypes, iNoMap, iOptions, new CollectionItemVisitor() {
@Override
public void visitItem(Object item) {
bag.add((OIdentifiable) item);
}
});
return bag;
} else if (iType == OType.LINKSET) {
return getValueAsLinkedCollection(new ORecordLazySet(iRecord), iRecord, iFieldValue, iType, iLinkedType, iFieldTypes, iNoMap,
iOptions);
} else if (iType == OType.LINKLIST) {
return getValueAsLinkedCollection(new ORecordLazyList(iRecord), iRecord, iFieldValue, iType, iLinkedType, iFieldTypes,
iNoMap, iOptions);
} else if (iType == OType.EMBEDDEDSET) {
return getValueAsEmbeddedCollection(new OTrackedSet<Object>(iRecord), iRecord, iFieldValue, iType, iLinkedType, iFieldTypes,
iNoMap, iOptions);
} else {
return getValueAsEmbeddedCollection(new OTrackedList<Object>(iRecord), iRecord, iFieldValue, iType, iLinkedType, iFieldTypes,
iNoMap, iOptions);
}
}
private Object getValueAsLinkedCollection(final Collection<OIdentifiable> collection, ODocument iRecord, String iFieldValue,
OType iType, OType iLinkedType, Map<String, Character> iFieldTypes, boolean iNoMap, String iOptions) {
parseCollection(iRecord, iFieldValue, iType, iLinkedType, iFieldTypes, iNoMap, iOptions, new CollectionItemVisitor() {
@Override
public void visitItem(Object item) {
collection.add((OIdentifiable) item);
}
});
return collection;
}
private Object getValueAsEmbeddedCollection(final Collection<Object> collection, ODocument iRecord, String iFieldValue,
OType iType, OType iLinkedType, Map<String, Character> iFieldTypes, boolean iNoMap, String iOptions) {
parseCollection(iRecord, iFieldValue, iType, iLinkedType, iFieldTypes, iNoMap, iOptions, new CollectionItemVisitor() {
@Override
public void visitItem(Object item) {
collection.add(item);
}
});
return collection;
}
private void parseCollection(ODocument iRecord, String iFieldValue, OType iType, OType iLinkedType,
Map<String, Character> iFieldTypes, boolean iNoMap, String iOptions, CollectionItemVisitor visitor) {
if (!iFieldValue.isEmpty()) {
for (String item : OStringSerializerHelper.smartSplit(iFieldValue, ',')) {
final String itemValue = item.trim();
if (itemValue.length() == 0)
continue;
final Object collectionItem = getValue(iRecord, null, itemValue, OStringSerializerHelper.getStringContent(itemValue),
iLinkedType, null, iFieldTypes, iNoMap, iOptions);
// TODO redundant in some cases, owner is already added by getValue in some cases
if (shouldBeDeserializedAsEmbedded(collectionItem, iType))
ODocumentInternal.addOwner((ODocument) collectionItem, iRecord);
if (collectionItem instanceof String && ((String) collectionItem).length() == 0)
continue;
visitor.visitItem(collectionItem);
}
}
}
private boolean shouldBeDeserializedAsEmbedded(Object record, OType iType) {
return record instanceof ODocument && !((ODocument) record).getIdentity().isTemporary()
&& !((ODocument) record).getIdentity().isPersistent() && (iType == null || !iType.isLink());
}
private String decodeJSON(String iFieldValueAsString) {
if (iFieldValueAsString == null) {
return null;
}
StringBuilder builder = new StringBuilder(iFieldValueAsString.length());
boolean quoting = false;
for (char c : iFieldValueAsString.toCharArray()) {
if (quoting) {
if (c != '\\' && c != '\"' && c != '/') {
builder.append('\\');
}
builder.append(c);
quoting = false;
} else {
if (c == '\\') {
quoting = true;
} else {
builder.append(c);
}
}
}
return builder.toString();
}
private boolean hasTypeField(final String[] fields) {
return hasField("@type", fields);
}
/**
* Checks if given collection of fields contain field with specified name.
*
* @param field
* to find
* @param fields
* collection of fields where search
* @return true if collection contain specified field, false otherwise.
*/
private boolean hasField(final String field, final String[] fields) {
return getFieldValue(field, fields) != null;
}
private String getFieldValue(final String field, final String[] fields) {
String doubleQuotes = "\"" + field + "\"";
String singleQuotes = "'" + field + "'";
for (int i = 0; i < fields.length; i = i + 2) {
if (fields[i].equals(doubleQuotes) || fields[i].equals(singleQuotes)) {
return fields[i + 1];
}
}
return null;
}
}
| |
package org.votesmart.classes;
import org.votesmart.api.*;
import org.votesmart.data.CandidateList;
/**
* <pre>
* Candidates Class
*
* * - Required
* * - Multiple rows
*
* Candidates.getByOfficeState()
* This method grabs a list of candidates according to office and state representation.
* Input: officeId*, stateId(default: 'NA'), electionYear(default: >= current year), stageId
* Output: {@link CandidateList}
*
* Candidates.getByOfficeTypeState()
* This method grabs a list of candidates according to office type and state representation.
* Input: officeTypeId*, stateId(default: 'NA'), electionYear(default: >= current year), stageId
* Output: {@link CandidateList}
*
* Candidates.getByLastname()
* This method grabs a list of candidates according to a lastname match.
* Input: lastName*, electionYear(default: >= current year), stageId
* Output: {@link CandidateList}
*
* Candidates.getByLevenshtein()
* This method grabs a list of candidates according to a fuzzy lastname match.
* Input: lastName*, electionYear(default: >= current year), stageId
* Output: {@link CandidateList}
*
* Candidates.getByElection()
* This method grabs a list of candidates according to the election they are running in.
* Input: electionId*, stageId
* Output: {@link CandidateList}
*
* Candidates.getByDistrict()
* This method grabs a list of candidates according to the district they represent.
* Input: districtId*, electionYear(default: >= current year), stageId
* Output: {@link CandidateList}
*
* Candidates.getByZip()
* This method grabs a list of candidates according to the zip code they represent.
* Input: zip5*, electionYear(default: >= current year), zip4(default: NULL), stageId
* Output: {@link CandidateList}
*
* ========= EXAMPLE USAGE =============
*
* CandidatesClass candidatesClass = new CandidatesClass();
*
* // Candidates for last office, for state
* CandidateList candidates = candidatesClass.getByOfficeState(office.officeId, state.stateId);
*
* // Candidates for last office, for state
* candidates = candidatesClass.getByOfficeTypeState(officeType.officeTypeId, state.stateId);
*</pre>
*/
public class CandidatesClass extends ClassesBase {
/**
* Constructor for testing purposes.
*
* @param api
*/
public CandidatesClass(VoteSmartAPI api) {
super(api);
}
/**
* Default Constructor
*/
public CandidatesClass() throws VoteSmartException {
super();
}
/**
* This method grabs a list of candidates according to office and state representation.
*
* @param officeId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByOfficeState(String officeId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByOfficeState", new ArgMap("officeId", officeId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to office and state representation.
*
* @param officeId
* @param stateId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByOfficeState(String officeId, String stateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByOfficeState", new ArgMap("officeId", officeId, "stateId", stateId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to office and state representation.
*
* @param officeId
* @param stateId
* @param electionYear
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByOfficeState(String officeId, String stateId, String electionYear) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByOfficeState", new ArgMap("officeId", officeId, "stateId", stateId, "electionYear", electionYear), CandidateList.class );
}
/**
* This method grabs a list of candidates according to office and state representation.
*
* @param officeId
* @param stateId
* @param electionYear
* @param stageId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByOfficeState(String officeId, String stateId, String electionYear, String stageId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByOfficeState", new ArgMap("officeId", officeId, "stateId", stateId, "electionYear", electionYear, "stageId", stageId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to office type and state representation.
*
* @param officeTypeId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByOfficeTypeState(String officeTypeId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByOfficeTypeState", new ArgMap("officeTypeId", officeTypeId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to office type and state representation.
*
* @param officeTypeId
* @param stateId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByOfficeTypeState(String officeTypeId, String stateId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByOfficeTypeState", new ArgMap("officeTypeId", officeTypeId, "stateId", stateId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to office type and state representation.
*
* @param officeTypeId
* @param stateId
* @param electionYear
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByOfficeTypeState(String officeTypeId, String stateId, String electionYear) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByOfficeTypeState", new ArgMap("officeTypeId", officeTypeId, "stateId", stateId, "electionYear", electionYear), CandidateList.class );
}
/**
* This method grabs a list of candidates according to office type and state representation.
*
* @param officeTypeId
* @param stateId
* @param electionYear
* @param stageId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByOfficeTypeState(String officeTypeId, String stateId, String electionYear, String stageId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByOfficeTypeState", new ArgMap("officeTypeId", officeTypeId, "stateId", stateId, "electionYear", electionYear, "stageId", stageId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to a lastname match.
*
* @param lastName
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByLastname(String lastName) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByLastname", new ArgMap("lastName", lastName), CandidateList.class );
}
/**
* This method grabs a list of candidates according to a lastname match.
*
* @param lastName
* @param electionYear
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByLastname(String lastName, String electionYear) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByLastname", new ArgMap("lastName", lastName, "electionYear", electionYear), CandidateList.class );
}
/**
* This method grabs a list of candidates according to a lastname match.
*
* @param lastName
* @param electionYear
* @param stageId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByLastname(String lastName, String electionYear, String stageId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByLastname", new ArgMap("lastName", lastName, "electionYear", electionYear, "stageId", stageId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to a fuzzy lastname match.
*
* @param lastName
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByLevenshtein(String lastName) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByLevenshtein", new ArgMap("lastName", lastName), CandidateList.class );
}
/**
* This method grabs a list of candidates according to a fuzzy lastname match.
*
* @param lastName
* @param electionYear
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByLevenshtein(String lastName, String electionYear) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByLevenshtein", new ArgMap("lastName", lastName, "electionYear", electionYear), CandidateList.class );
}
/**
* This method grabs a list of candidates according to a fuzzy lastname match.
*
* @param lastName
* @param electionYear
* @param stageId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByLevenshtein(String lastName, String electionYear, String stageId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByLevenshtein", new ArgMap("lastName", lastName, "electionYear", electionYear, "stageId", stageId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to a fuzzy lastname match.
*
* @param electionId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByElection(String electionId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByElection", new ArgMap("electionId", electionId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to a fuzzy lastname match.
*
* @param electionId
* @param stageId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByElection(String electionId, String stageId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByElection", new ArgMap("electionId", electionId, "stageId", stageId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to the district they represent.
*
* @param districtId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByDistrict(String districtId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByDistrict", new ArgMap("districtId", districtId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to the district they represent.
*
* @param districtId
* @param electionYear
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByDistrict(String districtId, String electionYear) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByDistrict", new ArgMap("districtId", districtId, "electionYear", electionYear), CandidateList.class );
}
/**
* This method grabs a list of candidates according to the district they represent.
*
* @param districtId
* @param electionYear
* @param stageId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByDistrict(String districtId, String electionYear, String stageId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByDistrict", new ArgMap("districtId", districtId, "electionYear", electionYear, "stageId", stageId), CandidateList.class );
}
/**
* This method grabs a list of candidates according to the district they represent.
*
* @param zip5
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByZip(String zip5) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByZip", new ArgMap("zip5", zip5), CandidateList.class );
}
/**
* This method grabs a list of candidates according to the district they represent.
*
* @param zip5
* @param electionYear
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByZip(String zip5, String electionYear) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByZip", new ArgMap("zip5", zip5, "electionYear", electionYear), CandidateList.class );
}
/**
* This method grabs a list of candidates according to the district they represent.
*
* @param zip5
* @param electionYear
* @param zip4
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByZip(String zip5, String electionYear, String zip4) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByZip", new ArgMap("zip5", zip5, "electionYear", electionYear, "zip4", zip4), CandidateList.class );
}
/**
* This method grabs a list of candidates according to the district they represent.
*
* @param zip5
* @param electionYear
* @param zip4
* @param stageId
* @return {@link CandidateList}: list of detailed candidate information.
*/
public CandidateList getByZip(String zip5, String electionYear, String zip4, String stageId) throws VoteSmartException, VoteSmartErrorException {
return api.query("Candidates.getByZip", new ArgMap("zip5", zip5, "electionYear", electionYear, "zip4", zip4, "stageId", stageId), CandidateList.class );
}
}
| |
package de.codesourcery.jasm16.ide.ui.views;
/**
* Copyright 2012 Tobias Gierke <tobias.gierke@code-sourcery.de>
*
* 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.
*/
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import de.codesourcery.jasm16.Address;
import de.codesourcery.jasm16.emulator.EmulationListener;
import de.codesourcery.jasm16.emulator.IEmulator;
import de.codesourcery.jasm16.emulator.IEmulator.EmulationSpeed;
import de.codesourcery.jasm16.ide.ui.utils.UIUtils;
import de.codesourcery.jasm16.ide.ui.viewcontainers.DebuggingPerspective;
import de.codesourcery.jasm16.ide.ui.viewcontainers.IViewContainer;
public class EmulatorControllerView extends AbstractView
{
public static final String VIEW_ID = "emulator-controller-view";
private static final AtomicBoolean showDialog = new AtomicBoolean(false);
// @GuardedBy( showDialog )
private static DialogHelper worker = null;
private static final AtomicLong LISTENER_REGISTRATION_COUNT = new AtomicLong(0);
private JPanel panel;
private final JButton singleStepButton = new JButton("Step");
private final JButton stepReturnButton = new JButton("Step return");
private final JButton skipButton = new JButton("Skip");
private final JButton runButton = new JButton("Run");
private final JButton stopButton = new JButton("Stop");
private final JButton resetButton = new JButton("Reset");
private JCheckBox runAtRealSpeed;
private final DebuggingPerspective perspective;
private IEmulator emulator;
private final MyEmulationListener listener;
private final class DialogHelper
{
private final AtomicReference<JFrame> dialog = new AtomicReference<JFrame>();
private final IViewContainer parent;
public DialogHelper()
{
parent = getViewContainer();
if ( parent == null ) {
throw new IllegalStateException("NULL parent ?");
}
}
public void showDialog()
{
UIUtils.invokeLater( new Runnable() {
@Override
public void run()
{
System.out.println("Creating dialog (EDT="+SwingUtilities.isEventDispatchThread()+")");
final JFrame tmp = UIUtils.createMessageFrame( "Calibrating emulation speed" , "Please wait, benchmarking your system...");
tmp.setVisible( true );
parent.setBlockAllUserInput( true );
dialog.set(tmp);
}
});
}
public void closeDialog()
{
UIUtils.invokeLater( new Runnable()
{
@Override
public void run()
{
System.out.println("Disposing dialog (EDT="+SwingUtilities.isEventDispatchThread()+")");
while( dialog.get() == null ) {}
dialog.get().dispose();
parent.setBlockAllUserInput( false );
}
});
}
}
protected final class MyEmulationListener extends EmulationListener
{
// this view may be visible in multiple instances (and thus this register may be registered more than once), this flag
// is used to make sure only exactly one of the listeners responds to beforeCalibration() / afterCalibration() messages
private final boolean isFirstListener;
public MyEmulationListener(boolean isFirstListener) {
this.isFirstListener = isFirstListener;
}
public void beforeCalibration(IEmulator emulator)
{
if ( ! isFirstListener ) {
return;
}
synchronized( showDialog )
{
if ( showDialog.compareAndSet(false,true) && worker == null )
{
worker = new DialogHelper();
worker.showDialog();
}
}
}
public void afterCalibration(IEmulator emulator)
{
if ( ! isFirstListener ) {
return;
}
synchronized( showDialog )
{
if ( showDialog.compareAndSet(true,false) && worker != null )
{
worker.closeDialog();
worker = null;
}
}
}
public void onEmulationSpeedChange(EmulationSpeed oldSpeed, EmulationSpeed newSpeed) {
if ( runAtRealSpeed != null ) {
runAtRealSpeed.setSelected( newSpeed == EmulationSpeed.REAL_SPEED );
}
}
public void afterMemoryLoad(IEmulator emulator, Address startAddress, int lengthInBytes) {
updateButtonStates(false);
}
@Override
public void afterReset(IEmulator emulator)
{
updateButtonStates( false );
}
@Override
protected void beforeContinuousExecutionHook() {
updateButtonStates( true );
}
@Override
public void onStopHook(IEmulator emulator, Address previousPC, Throwable emulationError) {
updateButtonStates( false );
}
};
// helper interface for invoking IEmulator methods from a non-EDT thread
protected abstract class Invoker implements Runnable
{
public abstract void invoke(IEmulator emulator);
@Override
public final void run()
{
invoke(emulator);
}
}
public EmulatorControllerView(DebuggingPerspective perspective, IEmulator emulator) {
if ( perspective == null ) {
throw new IllegalArgumentException("perspective must not be null");
}
this.perspective = perspective;
this.emulator = emulator;
listener = new MyEmulationListener( LISTENER_REGISTRATION_COUNT.incrementAndGet() == 1 );
emulator.addEmulationListener( listener );
}
private void updateButtonStates(final boolean emulatorRunningContinously) {
final Runnable runnable = new Runnable() {
@Override
public void run()
{
skipButton.setEnabled( ! emulatorRunningContinously );
singleStepButton.setEnabled( ! emulatorRunningContinously );
runButton.setEnabled( ! emulatorRunningContinously );
stopButton.setEnabled( emulatorRunningContinously );
if ( emulatorRunningContinously ) {
stepReturnButton.setEnabled( false );
} else {
stepReturnButton.setEnabled( true );
}
resetButton.setEnabled( true );
}
};
UIUtils.invokeLater( runnable );
}
@Override
public void refreshDisplay()
{
}
@Override
public void disposeHook()
{
if ( this.emulator != null )
{
this.emulator.removeEmulationListener( listener );
this.emulator = null;
}
}
protected JPanel createPanel()
{
// setup top panel
final JPanel buttonBar = new JPanel();
buttonBar.setLayout( new GridBagLayout() );
int x = 0;
// =========== "SINGLE STEP" button ============
singleStepButton.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
executeAsynchronously( new Invoker() {
@Override
public void invoke(IEmulator emulator)
{
emulator.executeOneInstruction();
updateButtonStates( false );
}
});
}
});
GridBagConstraints cnstrs = constraints( x++ , 0 , false , true , GridBagConstraints.NONE );
buttonBar.add( singleStepButton , cnstrs );
// =========== "STEP RETURN" button ============
stepReturnButton.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
executeAsynchronously( new Invoker() {
@Override
public void invoke(IEmulator emulator)
{
if ( emulator.canStepReturn() ) {
emulator.stepReturn();
} else {
emulator.executeOneInstruction();
}
}
});
}
});
cnstrs = constraints( x++ , 0 , false , true , GridBagConstraints.NONE );
buttonBar.add( stepReturnButton , cnstrs );
// =========== "Skip" button ============
skipButton.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
executeAsynchronously( new Invoker() {
@Override
public void invoke(IEmulator emulator)
{
emulator.skipCurrentInstruction();
}
});
}
});
cnstrs = constraints( x++ , 0 , false , true , GridBagConstraints.NONE );
buttonBar.add( skipButton , cnstrs );
// =========== "RUN" button ============
runButton.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
executeAsynchronously( new Invoker() {
@Override
public void invoke(IEmulator emulator)
{
emulator.start();
}
});
}
});
cnstrs = constraints( x++ , 0 , false , true , GridBagConstraints.NONE );
buttonBar.add( runButton , cnstrs );
// =========== "STOP" button ============
stopButton.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
executeAsynchronously( new Invoker() {
@Override
public void invoke(IEmulator emulator)
{
emulator.stop();
}
});
}
});
cnstrs = constraints( x++ , 0 , false , true , GridBagConstraints.NONE );
buttonBar.add( stopButton , cnstrs );
// =========== "RESET" button ============
resetButton.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
executeAsynchronously( new Invoker() {
@Override
public void invoke(IEmulator emulator)
{
perspective.resetEmulator();
}
});
}
});
cnstrs = constraints( x++ , 0 , false , true , GridBagConstraints.NONE );
buttonBar.add( resetButton , cnstrs );
// =========== "Run at full speed" checkbox ============
runAtRealSpeed = new JCheckBox("Run at real speed",emulator.getEmulationSpeed() == IEmulator.EmulationSpeed.REAL_SPEED);
runAtRealSpeed.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
final boolean isSelected = runAtRealSpeed.isSelected();
executeAsynchronously( new Invoker() {
@Override
public void invoke(IEmulator emulator)
{
if ( isSelected )
{
emulator.setEmulationSpeed( IEmulator.EmulationSpeed.REAL_SPEED );
} else {
emulator.setEmulationSpeed( isSelected ? EmulationSpeed.REAL_SPEED : EmulationSpeed.MAX_SPEED );
}
}} );
}
});
cnstrs = constraints( x++ , 0 , true , true , GridBagConstraints.NONE );
buttonBar.add( runAtRealSpeed , cnstrs );
updateButtonStates( false );
return buttonBar;
}
@Override
protected JPanel getPanel() {
if ( panel == null ) {
panel = createPanel();
}
return panel;
}
@Override
public String getTitle() {
return "Emulator control";
}
@Override
public String getID() {
return VIEW_ID;
}
}
| |
// 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 com.thoughtworks.selenium;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.openqa.selenium.net.Urls;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
/**
* Sends commands and retrieves results via HTTP.
*
* @author Ben Griffiths, Jez Humble
* @deprecated The RC interface will be removed in Selenium 3.0. Please migrate to using WebDriver.
*/
@Deprecated
public class HttpCommandProcessor implements CommandProcessor {
private String pathToServlet;
private String browserStartCommand;
private String browserURL;
private String sessionId;
private String extensionJs;
private String rcServerLocation;
/**
* Specifies a server host/port, a command to launch the browser, and a starting URL for the
* browser.
*
* @param serverHost - the host name on which the Selenium Server resides
* @param serverPort - the port on which the Selenium Server is listening
* @param browserStartCommand - the command string used to launch the browser, e.g. "*firefox" or
* "c:\\program files\\internet explorer\\iexplore.exe"
* @param browserURL - the starting URL including just a domain name. We'll start the browser
* pointing at the Selenium resources on this URL,
*/
public HttpCommandProcessor(String serverHost, int serverPort, String browserStartCommand,
String browserURL) {
rcServerLocation = serverHost +
":" + Integer.toString(serverPort);
this.pathToServlet = "http://" + rcServerLocation + "/selenium-server/driver/";
this.browserStartCommand = browserStartCommand;
this.browserURL = browserURL;
this.extensionJs = "";
}
/**
* Specifies the URL to the CommandBridge servlet, a command to launch the browser, and a starting
* URL for the browser.
*
* @param pathToServlet - the URL of the Selenium Server Driver, e.g.
* "http://localhost:4444/selenium-server/driver/" (don't forget the final slash!)
* @param browserStartCommand - the command string used to launch the browser, e.g. "*firefox" or
* "c:\\program files\\internet explorer\\iexplore.exe"
* @param browserURL - the starting URL including just a domain name. We'll start the browser
* pointing at the Selenium resources on this URL,
*/
public HttpCommandProcessor(String pathToServlet, String browserStartCommand, String browserURL) {
this.pathToServlet = pathToServlet;
this.browserStartCommand = browserStartCommand;
this.browserURL = browserURL;
this.extensionJs = "";
}
public String getRemoteControlServerLocation() {
return rcServerLocation;
}
public String doCommand(String commandName, String[] args) {
DefaultRemoteCommand command = new DefaultRemoteCommand(commandName, args);
String result = executeCommandOnServlet(command.getCommandURLString());
if (result == null) {
throw new NullPointerException("Selenium Bug! result must not be null");
}
if (!result.startsWith("OK")) {
return throwAssertionFailureExceptionOrError(result);
}
return result;
}
protected String throwAssertionFailureExceptionOrError(String message) {
throw new SeleniumException(message);
}
/** Sends the specified command string to the bridge servlet */
public String executeCommandOnServlet(String command) {
try {
return getCommandResponseAsString(command);
} catch (IOException e) {
if (e instanceof ConnectException) {
throw new SeleniumException(e.getMessage(), e);
}
e.printStackTrace();
throw new UnsupportedOperationException("Catch body broken: IOException from " + command +
" -> " + e, e);
}
}
private String stringContentsOfInputStream(Reader rdr) throws IOException {
StringBuffer sb = new StringBuffer();
int c;
try {
while ((c = rdr.read()) != -1) {
sb.append((char) c);
}
return sb.toString();
} finally {
rdr.close();
}
}
// for testing
protected HttpURLConnection getHttpUrlConnection(URL urlForServlet) throws IOException {
return (HttpURLConnection) urlForServlet.openConnection();
}
// for testing
protected Writer getOutputStreamWriter(HttpURLConnection conn) throws IOException {
return new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), Charsets.UTF_8));
}
// for testing
protected Reader getInputStreamReader(HttpURLConnection conn) throws IOException {
return new InputStreamReader(conn.getInputStream(), "UTF-8");
}
// for testing
protected int getResponseCode(HttpURLConnection conn) throws IOException {
return conn.getResponseCode();
}
protected String getCommandResponseAsString(String command) throws IOException {
String responseString = null;
int responsecode = HttpURLConnection.HTTP_MOVED_PERM;
HttpURLConnection uc = null;
Writer wr = null;
Reader rdr = null;
while (responsecode == HttpURLConnection.HTTP_MOVED_PERM) {
URL result = new URL(pathToServlet);
String body = buildCommandBody(command);
try {
uc = getHttpUrlConnection(result);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
uc.setInstanceFollowRedirects(false);
uc.setDoOutput(true);
wr = getOutputStreamWriter(uc);
wr.write(body);
wr.flush();
responsecode = getResponseCode(uc);
if (responsecode == HttpURLConnection.HTTP_MOVED_PERM) {
pathToServlet = uc.getHeaderField("Location");
} else if (responsecode != HttpURLConnection.HTTP_OK) {
throwAssertionFailureExceptionOrError(uc.getResponseMessage());
} else {
rdr = getInputStreamReader(uc);
responseString = stringContentsOfInputStream(rdr);
}
} finally {
closeResources(uc, wr, rdr);
}
}
return responseString;
}
protected void closeResources(HttpURLConnection conn, Writer wr, Reader rdr) {
try {
if (null != wr) {
wr.close();
}
} catch (IOException ioe) {
// ignore
}
try {
if (null != rdr) {
rdr.close();
}
} catch (IOException ioe) {
// ignore
}
if (null != conn) {
conn.disconnect();
}
}
private String buildCommandBody(String command) {
StringBuffer sb = new StringBuffer();
sb.append(command);
if (sessionId != null) {
sb.append("&sessionId=");
sb.append(Urls.urlEncode(sessionId));
}
return sb.toString();
}
/**
* This should be invoked before start().
*
* @param extensionJs the extra extension Javascript to include in this browser session.
*/
public void setExtensionJs(String extensionJs) {
this.extensionJs = extensionJs;
}
public void start() {
String result = getString("getNewBrowserSession",
new String[] {browserStartCommand, browserURL, extensionJs});
setSessionInProgress(result);
}
public void start(String optionsString) {
String result = getString("getNewBrowserSession",
new String[] {browserStartCommand, browserURL,
extensionJs, optionsString});
setSessionInProgress(result);
}
/**
* Wraps the version of start() that takes a String parameter, sending it the result of calling
* toString() on optionsObject, which will likely be a BrowserConfigurationOptions instance.
*
* @param optionsObject start options
*/
public void start(Object optionsObject) {
start(optionsObject.toString());
}
protected void setSessionInProgress(String result) {
sessionId = result;
}
public void stop() {
if (hasSessionInProgress()) {
doCommand("testComplete", null);
}
setSessionInProgress(null);
}
public boolean hasSessionInProgress() {
return null != sessionId;
}
public String getString(String commandName, String[] args) {
String result = doCommand(commandName, args);
if (result.length() >= "OK,".length()) {
return result.substring("OK,".length());
}
System.err.println("WARNING: getString(" + commandName + ") saw a bad result " + result);
return "";
}
public String[] getStringArray(String commandName, String[] args) {
String result = getString(commandName, args);
return parseCSV(result);
}
/**
* Convert backslash-escaped comma-delimited string into String array. As described in SRC-CDP
* spec section 5.2.1.2, these strings are comma-delimited, but commas can be escaped with a
* backslash "\". Backslashes can also be escaped as a double-backslash.
*
* @param input the unparsed string, e.g. "veni\, vidi\, vici,c:\\foo\\bar,c:\\I came\, I
* \\saw\\\, I conquered"
* @return the string array resulting from parsing this string
*/
public static String[] parseCSV(String input) {
List<String> output = Lists.newArrayList();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case ',':
output.add(sb.toString());
sb = new StringBuffer();
continue;
case '\\':
i++;
c = input.charAt(i);
// fall through to:
default:
sb.append(c);
}
}
output.add(sb.toString());
return output.toArray(new String[output.size()]);
}
public Number getNumber(String commandName, String[] args) {
String result = getString(commandName, args);
Number n;
try {
n = NumberFormat.getInstance().parse(result);
} catch (ParseException e) {
throw new RuntimeException(e);
}
if (n instanceof Long && n.intValue() == n.longValue()) {
// SRC-315 we should return Integers if possible
return Integer.valueOf(n.intValue());
}
return n;
}
public Number[] getNumberArray(String commandName, String[] args) {
String[] result = getStringArray(commandName, args);
Number[] n = new Number[result.length];
for (int i = 0; i < result.length; i++) {
try {
n[i] = NumberFormat.getInstance().parse(result[i]);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
return n;
}
public boolean getBoolean(String commandName, String[] args) {
String result = getString(commandName, args);
boolean b;
if ("true".equals(result)) {
b = true;
return b;
}
if ("false".equals(result)) {
b = false;
return b;
}
throw new RuntimeException("result was neither 'true' nor 'false': " + result);
}
public boolean[] getBooleanArray(String commandName, String[] args) {
String[] result = getStringArray(commandName, args);
boolean[] b = new boolean[result.length];
for (int i = 0; i < result.length; i++) {
if ("true".equals(result[i])) {
b[i] = true;
continue;
}
if ("false".equals(result[i])) {
b[i] = false;
continue;
}
throw new RuntimeException("result was neither 'true' nor 'false': " +
Arrays.toString(result));
}
return b;
}
}
| |
/*
* Copyright 2012 GitHub 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.gh4a.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.appcompat.graphics.drawable.DrawableWrapper;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.caverock.androidsvg.SVG;
import com.gh4a.R;
import com.gh4a.ServiceFactory;
import com.gh4a.fragment.SettingsFragment;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pl.droidsonroids.gif.GifDrawable;
public class HttpImageGetter {
private static class GifCallback implements Drawable.Callback {
private final List<WeakReference<TextView>> mViewRefs;
private final Handler mHandler = new Handler();
public GifCallback(List<WeakReference<TextView>> viewRefs) {
mViewRefs = viewRefs;
}
@Override
public void invalidateDrawable(@NonNull Drawable drawable) {
for (WeakReference<TextView> ref : mViewRefs) {
TextView view = ref.get();
if (view != null) {
view.invalidate();
// make sure the TextView's display list is regenerated
boolean enabled = view.isEnabled();
view.setEnabled(!enabled);
view.setEnabled(enabled);
}
}
}
@Override
public void scheduleDrawable(@NonNull Drawable drawable,
@NonNull Runnable runnable, long when) {
mHandler.postAtTime(runnable, when);
}
@Override
public void unscheduleDrawable(@NonNull Drawable drawable, @NonNull Runnable runnable) {
mHandler.removeCallbacks(runnable);
}
}
private static class GifInfo {
final WeakReference<GifDrawable> mDrawable;
final GifCallback mCallback;
public GifInfo(GifDrawable d, List<WeakReference<TextView>> viewRefs) {
mCallback = new GifCallback(viewRefs);
mDrawable = new WeakReference<>(d);
d.setCallback(mCallback);
}
public void destroy() {
GifDrawable drawable = mDrawable.get();
if (drawable != null) {
drawable.setCallback(null);
drawable.stop();
drawable.recycle();
}
}
}
// interface just used for tracking purposes
private static class LoadedBitmapDrawable extends BitmapDrawable {
public LoadedBitmapDrawable(Resources res, Bitmap bitmap) {
super(res, bitmap);
}
}
private static class PlaceholderDrawable extends DrawableWrapper implements Runnable {
private final String mUrl;
private final ObjectInfo mInfo;
private Drawable mLoadedImage;
public PlaceholderDrawable(String url, ObjectInfo info, Drawable placeholder) {
super(placeholder);
setBounds(0, 0, placeholder.getIntrinsicWidth(), placeholder.getIntrinsicHeight());
mUrl = url;
mInfo = info;
}
public String getUrl() {
return mUrl;
}
public void addLoadedImage(Drawable image, Handler handler) {
synchronized (this) {
mLoadedImage = image;
handler.post(this);
}
}
@Override
public void run() {
setWrappedDrawable(mLoadedImage);
setBounds(0, 0, mLoadedImage.getIntrinsicWidth(), mLoadedImage.getIntrinsicHeight());
mInfo.invalidateViewsForNewDrawable();
}
}
private class ObjectInfo implements ImageGetter {
private final ArrayList<WeakReference<TextView>> mViewRefs = new ArrayList<>();
private final List<GifInfo> mGifs = new ArrayList<>();
private final List<WeakReference<Bitmap>> mBitmaps = new ArrayList<>();
private CharSequence mHtml;
private ImageGetterAsyncTask mTask;
private boolean mHasStartedImageLoad;
private boolean mResumed = true;
void bind(TextView view, String html) {
addView(view);
if (mHtml == null) {
encode(view.getContext(), html);
}
apply(mHtml);
if (!mHasStartedImageLoad) {
ImageSpan[] spans = getImageSpans();
if (spans.length > 0) {
ArrayList<PlaceholderDrawable> imagesToLoad = new ArrayList<>();
for (ImageSpan span : spans) {
Drawable d = span.getDrawable();
if (d instanceof PlaceholderDrawable) {
imagesToLoad.add((PlaceholderDrawable) d);
}
}
mTask = new ImageGetterAsyncTask(HttpImageGetter.this, this);
mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
imagesToLoad.toArray(new PlaceholderDrawable[0]));
}
mHasStartedImageLoad = true;
}
}
void unbind(TextView view) {
removeView(view);
}
void encode(Context context, String html) {
CharSequence encoded = HtmlUtils.encode(context, html, this);
synchronized (this) {
mHtml = encoded;
}
}
void onImageLoadDone() {
discardLoadedImages();
for (ImageSpan span : getImageSpans()) {
Drawable d = span.getDrawable();
if (d instanceof PlaceholderDrawable) {
PlaceholderDrawable phd = (PlaceholderDrawable) d;
d = phd.getWrappedDrawable();
}
if (d instanceof GifDrawable) {
GifDrawable gd = (GifDrawable) d;
if (mResumed) {
gd.start();
}
mGifs.add(new GifInfo(gd, mViewRefs));
} else if (d instanceof LoadedBitmapDrawable) {
BitmapDrawable bd = (BitmapDrawable) d;
mBitmaps.add(new WeakReference<>(bd.getBitmap()));
}
}
}
void invalidateViewsForNewDrawable() {
for (int i = 0; i < mViewRefs.size(); i++) {
TextView view = mViewRefs.get(i).get();
if (view != null) {
view.setText(view.getText());
}
}
}
void setResumed(boolean resumed) {
mResumed = resumed;
for (GifInfo info : mGifs) {
GifDrawable drawable = info.mDrawable.get();
if (drawable == null) {
continue;
}
if (resumed) {
drawable.start();
} else {
drawable.stop();
}
}
}
@NonNull
private ImageSpan[] getImageSpans() {
if (TextUtils.isEmpty(mHtml)) {
return new ImageSpan[0];
}
Spanned spanned = (Spanned) mHtml;
return spanned.getSpans(0, spanned.length(), ImageSpan.class);
}
private void discardLoadedImages() {
for (WeakReference<Bitmap> ref : mBitmaps) {
Bitmap bitmap = ref.get();
if (bitmap != null) {
bitmap.recycle();
}
}
mBitmaps.clear();
for (GifInfo info : mGifs) {
info.destroy();
}
mGifs.clear();
mHasStartedImageLoad = false;
}
void clearHtmlCache() {
if (mTask != null) {
mTask.cancel(true);
mTask = null;
}
mHtml = null;
mHasStartedImageLoad = false;
}
private void apply(CharSequence text) {
int visibility = TextUtils.isEmpty(text) ? View.GONE : View.VISIBLE;
for (int i = 0; i < mViewRefs.size(); i++) {
TextView view = mViewRefs.get(i).get();
if (view != null) {
view.setText(text);
view.setVisibility(visibility);
}
}
}
private void addView(TextView view) {
boolean alreadyPresent = false;
for (int i = 0; i < mViewRefs.size(); i++) {
TextView existing = mViewRefs.get(i).get();
if (existing == null) {
mViewRefs.remove(i);
} else if (existing == view) {
alreadyPresent = true;
}
}
if (!alreadyPresent) {
mViewRefs.add(new WeakReference<>(view));
}
}
private void removeView(TextView view) {
for (int i = 0; i < mViewRefs.size(); i++) {
TextView existing = mViewRefs.get(i).get();
if (existing == null || existing == view) {
mViewRefs.remove(i);
}
}
}
@Override
public Drawable getDrawable(String source) {
return new PlaceholderDrawable(source, this, mLoadingDrawable);
}
}
private final Handler mHandler = new Handler();
private final Map<Object, ObjectInfo> mObjectInfos = new HashMap<>();
private final Drawable mLoadingDrawable;
private final Drawable mErrorDrawable;
private final OkHttpClient mClient;
private final Context mContext;
private final File mCacheDir;
private final int mWidth;
private final int mHeight;
private boolean mDestroyed;
public HttpImageGetter(Context context) {
mContext = context;
mCacheDir = context.getCacheDir();
mClient = ServiceFactory.getImageHttpClient();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
final Point size = new Point();
wm.getDefaultDisplay().getSize(size);
mWidth = size.x;
mHeight = size.y;
mLoadingDrawable = ContextCompat.getDrawable(context, R.drawable.image_loading);
mLoadingDrawable.setBounds(0, 0,
mLoadingDrawable.getIntrinsicWidth(), mLoadingDrawable.getIntrinsicHeight());
mErrorDrawable = ContextCompat.getDrawable(context, R.drawable.content_picture);
mErrorDrawable.setBounds(0, 0,
mErrorDrawable.getIntrinsicWidth(), mErrorDrawable.getIntrinsicHeight());
}
public void pause() {
for (ObjectInfo info : mObjectInfos.values()) {
info.setResumed(false);
}
}
public void resume() {
for (ObjectInfo info : mObjectInfos.values()) {
info.setResumed(true);
}
}
public void clearHtmlCache() {
for (ObjectInfo info : mObjectInfos.values()) {
info.clearHtmlCache();
}
}
public void destroy() {
for (ObjectInfo info : mObjectInfos.values()) {
info.discardLoadedImages();
}
mObjectInfos.clear();
mDestroyed = true;
}
public void encode(final Context context, final Object id, final String html) {
findOrCreateInfo(id).encode(context, html);
}
public void bind(final TextView view, final String html, final Object id) {
unbind(view);
findOrCreateInfo(id).bind(view, html);
}
private void unbind(final TextView view) {
for (ObjectInfo info : mObjectInfos.values()) {
info.unbind(view);
}
}
private ObjectInfo findOrCreateInfo(Object id) {
ObjectInfo info = mObjectInfos.get(id);
if (info == null) {
info = new ObjectInfo();
mObjectInfos.put(id, info);
}
return info;
}
private static class ImageGetterAsyncTask extends AsyncTask<PlaceholderDrawable, Void, Void> {
private final HttpImageGetter mImageGetter;
private final ObjectInfo mInfo;
public ImageGetterAsyncTask(HttpImageGetter getter, ObjectInfo info) {
mImageGetter = getter;
mInfo = info;
}
@Override
protected Void doInBackground(PlaceholderDrawable... params) {
for (PlaceholderDrawable placeholder : params) {
Drawable drawable = mImageGetter.loadImageForUrl(placeholder.getUrl());
if (drawable != null) {
placeholder.addLoadedImage(drawable, mImageGetter.mHandler);
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (!isCancelled()) {
mInfo.onImageLoadDone();
}
}
}
private Drawable loadImageForUrl(String source) {
HttpUrl url = source != null ? HttpUrl.parse(source) : null;
Bitmap bitmap = null;
if (!mDestroyed && url != null) {
File output = null;
InputStream is = null;
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = mClient.newCall(request).execute()) {
is = response.body().byteStream();
if (is != null) {
MediaType mediaType = response.body().contentType();
String mime = mediaType != null ? mediaType.toString() : null;
if (mime == null) {
mime = URLConnection.guessContentTypeFromName(source);
}
if (mime == null) {
mime = URLConnection.guessContentTypeFromStream(is);
}
if (mime != null && mime.startsWith("image/svg")) {
bitmap = renderSvgToBitmap(mContext.getResources(), is, mWidth, mHeight);
} else {
boolean isGif = mime != null && mime.startsWith("image/gif");
if (!isGif || canLoadGif()) {
output = File.createTempFile("image", ".tmp", mCacheDir);
if (FileUtils.save(output, is)) {
if (isGif) {
GifDrawable d = new GifDrawable(output);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
} else {
bitmap = getBitmap(output, mWidth, mHeight);
}
}
}
}
}
} catch (IOException e) {
// fall through to showing the error bitmap
} finally {
if (output != null) {
output.delete();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
// ignored
}
}
}
}
synchronized (this) {
if (mDestroyed && bitmap != null) {
bitmap.recycle();
bitmap = null;
}
}
if (bitmap == null) {
return mErrorDrawable;
}
BitmapDrawable drawable = new LoadedBitmapDrawable(mContext.getResources(), bitmap);
drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
return drawable;
}
private boolean canLoadGif() {
SharedPreferences prefs = mContext.getSharedPreferences(SettingsFragment.PREF_NAME,
Context.MODE_PRIVATE);
int mode = prefs.getInt(SettingsFragment.KEY_GIF_LOADING, 1);
switch (mode) {
case 1: // load via Wifi
return !DownloadUtils.downloadNeedsWarning(mContext);
case 2: // always load
return true;
default:
return false;
}
}
private static Bitmap getBitmap(final File image, int width, int height) {
final BitmapFactory.Options options = new BitmapFactory.Options();
RandomAccessFile file = null;
try {
file = new RandomAccessFile(image.getAbsolutePath(), "r");
FileDescriptor fd = file.getFD();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fd, null, options);
int scale = 1;
while (options.outWidth >= width || options.outHeight >= height) {
options.outWidth /= 2;
options.outHeight /= 2;
scale *= 2;
}
options.inJustDecodeBounds = false;
options.inDither = false;
options.inSampleSize = scale;
return BitmapFactory.decodeFileDescriptor(fd, null, options);
} catch (IOException e) {
return null;
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// ignored
}
}
}
}
private static Bitmap renderSvgToBitmap(Resources res, InputStream is,
int maxWidth, int maxHeight) {
try {
SVG svg = SVG.getFromInputStream(is);
if (svg != null) {
svg.setRenderDPI(DisplayMetrics.DENSITY_DEFAULT);
Float density = res.getDisplayMetrics().density;
int docWidth = (int) (svg.getDocumentWidth() * density);
int docHeight = (int) (svg.getDocumentHeight() * density);
if (docWidth < 0 || docHeight < 0) {
float aspectRatio = svg.getDocumentAspectRatio();
if (aspectRatio > 0) {
float heightForAspect = (float) maxWidth / aspectRatio;
float widthForAspect = (float) maxHeight * aspectRatio;
if (widthForAspect < heightForAspect) {
docWidth = Math.round(widthForAspect);
docHeight = maxHeight;
} else {
docWidth = maxWidth;
docHeight = Math.round(heightForAspect);
}
} else {
docWidth = maxWidth;
docHeight = maxHeight;
}
// we didn't take density into account anymore when calculating docWidth
// and docHeight, so don't scale with it and just let the renderer
// figure out the scaling
density = null;
}
while (docWidth >= maxWidth || docHeight >= maxHeight) {
docWidth /= 2;
docHeight /= 2;
if (density != null) {
density /= 2;
}
}
Bitmap bitmap = Bitmap.createBitmap(docWidth, docHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
if (density != null) {
canvas.scale(density, density);
}
svg.renderToCanvas(canvas);
return bitmap;
}
} catch (Exception e) {
// fall through
}
return null;
}
}
| |
/**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.market.curve;
import java.io.Serializable;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import org.joda.beans.Bean;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.google.common.collect.ImmutableMap;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.index.Index;
/**
* A group of curves.
* <p>
* This is used to hold a group of related curves, typically forming a logical set.
* It is often used to hold the results of a curve calibration.
*/
@BeanDefinition
public final class CurveGroup
implements ImmutableBean, Serializable {
/**
* The name of the curve group.
*/
@PropertyDefinition(validate = "notNull")
private final CurveGroupName name;
/**
* The discount curves in the group, keyed by currency.
*/
@PropertyDefinition(validate = "notNull")
private final ImmutableMap<Currency, Curve> discountCurves;
/**
* The forward curves in the group, keyed by index.
*/
@PropertyDefinition(validate = "notNull", builderType = "Map<? extends Index, Curve>")
private final ImmutableMap<Index, Curve> forwardCurves;
//-------------------------------------------------------------------------
/**
* Returns a curve group containing the specified curves.
*
* @param name the name of the curve group
* @param discountCurves the discount curves, keyed by currency
* @param forwardCurves the forward curves, keyed by index
* @return a curve group containing the specified curves
*/
public static CurveGroup of(CurveGroupName name, Map<Currency, Curve> discountCurves, Map<Index, Curve> forwardCurves) {
return new CurveGroup(name, discountCurves, forwardCurves);
}
//-------------------------------------------------------------------------
/**
* Returns the discount curve for the currency if there is one in the group.
*
* @param currency the currency for which a discount curve is required
* @return the discount curve for the currency if there is one in the group
*/
public Optional<Curve> getDiscountCurve(Currency currency) {
return Optional.ofNullable(discountCurves.get(currency));
}
/**
* Returns the forward curve for the index if there is one in the group.
*
* @param index the index for which a forward curve is required
* @return the forward curve for the index if there is one in the group
*/
public Optional<Curve> getForwardCurve(Index index) {
return Optional.ofNullable(forwardCurves.get(index));
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code CurveGroup}.
* @return the meta-bean, not null
*/
public static CurveGroup.Meta meta() {
return CurveGroup.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(CurveGroup.Meta.INSTANCE);
}
/**
* The serialization version id.
*/
private static final long serialVersionUID = 1L;
/**
* Returns a builder used to create an instance of the bean.
* @return the builder, not null
*/
public static CurveGroup.Builder builder() {
return new CurveGroup.Builder();
}
private CurveGroup(
CurveGroupName name,
Map<Currency, Curve> discountCurves,
Map<? extends Index, Curve> forwardCurves) {
JodaBeanUtils.notNull(name, "name");
JodaBeanUtils.notNull(discountCurves, "discountCurves");
JodaBeanUtils.notNull(forwardCurves, "forwardCurves");
this.name = name;
this.discountCurves = ImmutableMap.copyOf(discountCurves);
this.forwardCurves = ImmutableMap.copyOf(forwardCurves);
}
@Override
public CurveGroup.Meta metaBean() {
return CurveGroup.Meta.INSTANCE;
}
@Override
public <R> Property<R> property(String propertyName) {
return metaBean().<R>metaProperty(propertyName).createProperty(this);
}
@Override
public Set<String> propertyNames() {
return metaBean().metaPropertyMap().keySet();
}
//-----------------------------------------------------------------------
/**
* Gets the name of the curve group.
* @return the value of the property, not null
*/
public CurveGroupName getName() {
return name;
}
//-----------------------------------------------------------------------
/**
* Gets the discount curves in the group, keyed by currency.
* @return the value of the property, not null
*/
public ImmutableMap<Currency, Curve> getDiscountCurves() {
return discountCurves;
}
//-----------------------------------------------------------------------
/**
* Gets the forward curves in the group, keyed by index.
* @return the value of the property, not null
*/
public ImmutableMap<Index, Curve> getForwardCurves() {
return forwardCurves;
}
//-----------------------------------------------------------------------
/**
* Returns a builder that allows this bean to be mutated.
* @return the mutable builder, not null
*/
public Builder toBuilder() {
return new Builder(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
CurveGroup other = (CurveGroup) obj;
return JodaBeanUtils.equal(getName(), other.getName()) &&
JodaBeanUtils.equal(getDiscountCurves(), other.getDiscountCurves()) &&
JodaBeanUtils.equal(getForwardCurves(), other.getForwardCurves());
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(getName());
hash = hash * 31 + JodaBeanUtils.hashCode(getDiscountCurves());
hash = hash * 31 + JodaBeanUtils.hashCode(getForwardCurves());
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(128);
buf.append("CurveGroup{");
buf.append("name").append('=').append(getName()).append(',').append(' ');
buf.append("discountCurves").append('=').append(getDiscountCurves()).append(',').append(' ');
buf.append("forwardCurves").append('=').append(JodaBeanUtils.toString(getForwardCurves()));
buf.append('}');
return buf.toString();
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code CurveGroup}.
*/
public static final class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code name} property.
*/
private final MetaProperty<CurveGroupName> name = DirectMetaProperty.ofImmutable(
this, "name", CurveGroup.class, CurveGroupName.class);
/**
* The meta-property for the {@code discountCurves} property.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
private final MetaProperty<ImmutableMap<Currency, Curve>> discountCurves = DirectMetaProperty.ofImmutable(
this, "discountCurves", CurveGroup.class, (Class) ImmutableMap.class);
/**
* The meta-property for the {@code forwardCurves} property.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
private final MetaProperty<ImmutableMap<Index, Curve>> forwardCurves = DirectMetaProperty.ofImmutable(
this, "forwardCurves", CurveGroup.class, (Class) ImmutableMap.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"name",
"discountCurves",
"forwardCurves");
/**
* Restricted constructor.
*/
private Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case 3373707: // name
return name;
case -624113147: // discountCurves
return discountCurves;
case -850086775: // forwardCurves
return forwardCurves;
}
return super.metaPropertyGet(propertyName);
}
@Override
public CurveGroup.Builder builder() {
return new CurveGroup.Builder();
}
@Override
public Class<? extends CurveGroup> beanType() {
return CurveGroup.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code name} property.
* @return the meta-property, not null
*/
public MetaProperty<CurveGroupName> name() {
return name;
}
/**
* The meta-property for the {@code discountCurves} property.
* @return the meta-property, not null
*/
public MetaProperty<ImmutableMap<Currency, Curve>> discountCurves() {
return discountCurves;
}
/**
* The meta-property for the {@code forwardCurves} property.
* @return the meta-property, not null
*/
public MetaProperty<ImmutableMap<Index, Curve>> forwardCurves() {
return forwardCurves;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case 3373707: // name
return ((CurveGroup) bean).getName();
case -624113147: // discountCurves
return ((CurveGroup) bean).getDiscountCurves();
case -850086775: // forwardCurves
return ((CurveGroup) bean).getForwardCurves();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
//-----------------------------------------------------------------------
/**
* The bean-builder for {@code CurveGroup}.
*/
public static final class Builder extends DirectFieldsBeanBuilder<CurveGroup> {
private CurveGroupName name;
private Map<Currency, Curve> discountCurves = ImmutableMap.of();
private Map<? extends Index, Curve> forwardCurves = ImmutableMap.of();
/**
* Restricted constructor.
*/
private Builder() {
}
/**
* Restricted copy constructor.
* @param beanToCopy the bean to copy from, not null
*/
private Builder(CurveGroup beanToCopy) {
this.name = beanToCopy.getName();
this.discountCurves = beanToCopy.getDiscountCurves();
this.forwardCurves = beanToCopy.getForwardCurves();
}
//-----------------------------------------------------------------------
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case 3373707: // name
return name;
case -624113147: // discountCurves
return discountCurves;
case -850086775: // forwardCurves
return forwardCurves;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@SuppressWarnings("unchecked")
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case 3373707: // name
this.name = (CurveGroupName) newValue;
break;
case -624113147: // discountCurves
this.discountCurves = (Map<Currency, Curve>) newValue;
break;
case -850086775: // forwardCurves
this.forwardCurves = (Map<? extends Index, Curve>) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public Builder setString(String propertyName, String value) {
setString(meta().metaProperty(propertyName), value);
return this;
}
@Override
public Builder setString(MetaProperty<?> property, String value) {
super.setString(property, value);
return this;
}
@Override
public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
super.setAll(propertyValueMap);
return this;
}
@Override
public CurveGroup build() {
return new CurveGroup(
name,
discountCurves,
forwardCurves);
}
//-----------------------------------------------------------------------
/**
* Sets the name of the curve group.
* @param name the new value, not null
* @return this, for chaining, not null
*/
public Builder name(CurveGroupName name) {
JodaBeanUtils.notNull(name, "name");
this.name = name;
return this;
}
/**
* Sets the discount curves in the group, keyed by currency.
* @param discountCurves the new value, not null
* @return this, for chaining, not null
*/
public Builder discountCurves(Map<Currency, Curve> discountCurves) {
JodaBeanUtils.notNull(discountCurves, "discountCurves");
this.discountCurves = discountCurves;
return this;
}
/**
* Sets the forward curves in the group, keyed by index.
* @param forwardCurves the new value, not null
* @return this, for chaining, not null
*/
public Builder forwardCurves(Map<? extends Index, Curve> forwardCurves) {
JodaBeanUtils.notNull(forwardCurves, "forwardCurves");
this.forwardCurves = forwardCurves;
return this;
}
//-----------------------------------------------------------------------
@Override
public String toString() {
StringBuilder buf = new StringBuilder(128);
buf.append("CurveGroup.Builder{");
buf.append("name").append('=').append(JodaBeanUtils.toString(name)).append(',').append(' ');
buf.append("discountCurves").append('=').append(JodaBeanUtils.toString(discountCurves)).append(',').append(' ');
buf.append("forwardCurves").append('=').append(JodaBeanUtils.toString(forwardCurves));
buf.append('}');
return buf.toString();
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| |
package org.holoeverywhere.drawable;
import java.io.IOException;
import org.holoeverywhere.R;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.view.View;
public class LayerDrawable extends Drawable implements Drawable.Callback {
static class ChildDrawable {
public Drawable mDrawable;
public int mId;
public int mInsetL, mInsetT, mInsetR, mInsetB;
}
static class LayerState extends ConstantState {
private boolean mCanConstantState;
int mChangingConfigurations;
private boolean mCheckedConstantState;
ChildDrawable[] mChildren;
int mChildrenChangingConfigurations;
private boolean mHaveOpacity = false;
private boolean mHaveStateful = false;
int mNum;
private int mOpacity;
private boolean mStateful;
LayerState(LayerState orig, LayerDrawable owner, Resources res) {
if (orig != null) {
final ChildDrawable[] origChildDrawable = orig.mChildren;
final int N = orig.mNum;
mNum = N;
mChildren = new ChildDrawable[N];
mChangingConfigurations = orig.mChangingConfigurations;
mChildrenChangingConfigurations = orig.mChildrenChangingConfigurations;
for (int i = 0; i < N; i++) {
final ChildDrawable r = mChildren[i] = new ChildDrawable();
final ChildDrawable or = origChildDrawable[i];
if (res != null) {
r.mDrawable = or.mDrawable.getConstantState().newDrawable(res);
} else {
r.mDrawable = or.mDrawable.getConstantState().newDrawable();
}
r.mDrawable.setCallback(owner);
r.mInsetL = or.mInsetL;
r.mInsetT = or.mInsetT;
r.mInsetR = or.mInsetR;
r.mInsetB = or.mInsetB;
r.mId = or.mId;
}
mHaveOpacity = orig.mHaveOpacity;
mOpacity = orig.mOpacity;
mHaveStateful = orig.mHaveStateful;
mStateful = orig.mStateful;
mCheckedConstantState = mCanConstantState = true;
} else {
mNum = 0;
mChildren = null;
}
}
public boolean canConstantState() {
if (!mCheckedConstantState && mChildren != null) {
mCanConstantState = true;
final int N = mNum;
for (int i = 0; i < N; i++) {
if (mChildren[i].mDrawable.getConstantState() == null) {
mCanConstantState = false;
break;
}
}
mCheckedConstantState = true;
}
return mCanConstantState;
}
@Override
public int getChangingConfigurations() {
return mChangingConfigurations;
}
public final int getOpacity() {
if (mHaveOpacity) {
return mOpacity;
}
final int N = mNum;
int op = N > 0 ? mChildren[0].mDrawable.getOpacity() : PixelFormat.TRANSPARENT;
for (int i = 1; i < N; i++) {
op = Drawable.resolveOpacity(op, mChildren[i].mDrawable.getOpacity());
}
mOpacity = op;
mHaveOpacity = true;
return op;
}
public final boolean isStateful() {
if (mHaveStateful) {
return mStateful;
}
boolean stateful = false;
final int N = mNum;
for (int i = 0; i < N; i++) {
if (mChildren[i].mDrawable.isStateful()) {
stateful = true;
break;
}
}
mStateful = stateful;
mHaveStateful = true;
return stateful;
}
@Override
public Drawable newDrawable() {
return new LayerDrawable(this, null);
}
@Override
public Drawable newDrawable(Resources res) {
return new LayerDrawable(this, res);
}
}
LayerState mLayerState;
private boolean mMutated;
private int mOpacityOverride = PixelFormat.UNKNOWN;
private int[] mPaddingB;
private int[] mPaddingL;
private int[] mPaddingR;
private int[] mPaddingT;
private final Rect mTmpRect = new Rect();
LayerDrawable() {
this((LayerState) null, null);
}
public LayerDrawable(Drawable[] layers) {
this(layers, null);
}
LayerDrawable(Drawable[] layers, LayerState state) {
this(state, null);
int length = layers.length;
ChildDrawable[] r = new ChildDrawable[length];
for (int i = 0; i < length; i++) {
r[i] = new ChildDrawable();
r[i].mDrawable = layers[i];
layers[i].setCallback(this);
mLayerState.mChildrenChangingConfigurations |= layers[i].getChangingConfigurations();
}
mLayerState.mNum = length;
mLayerState.mChildren = r;
ensurePadding();
}
LayerDrawable(LayerState state, Resources res) {
LayerState as = createConstantState(state, res);
mLayerState = as;
if (as.mNum > 0) {
ensurePadding();
}
}
private void addLayer(Drawable layer, int id, int left, int top, int right, int bottom) {
final LayerState st = mLayerState;
int N = st.mChildren != null ? st.mChildren.length : 0;
int i = st.mNum;
if (i >= N) {
ChildDrawable[] nu = new ChildDrawable[N + 10];
if (i > 0) {
System.arraycopy(st.mChildren, 0, nu, 0, i);
}
st.mChildren = nu;
}
mLayerState.mChildrenChangingConfigurations |= layer.getChangingConfigurations();
ChildDrawable childDrawable = new ChildDrawable();
st.mChildren[i] = childDrawable;
childDrawable.mId = id;
childDrawable.mDrawable = layer;
childDrawable.mInsetL = left;
childDrawable.mInsetT = top;
childDrawable.mInsetR = right;
childDrawable.mInsetB = bottom;
st.mNum++;
layer.setCallback(this);
}
LayerState createConstantState(LayerState state, Resources res) {
return new LayerState(state, this, res);
}
@Override
public void draw(Canvas canvas) {
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
for (int i = 0; i < N; i++) {
array[i].mDrawable.draw(canvas);
}
}
private void ensurePadding() {
final int N = mLayerState.mNum;
if (mPaddingL != null && mPaddingL.length >= N) {
return;
}
mPaddingL = new int[N];
mPaddingT = new int[N];
mPaddingR = new int[N];
mPaddingB = new int[N];
}
public Drawable findDrawableByLayerId(int id) {
final ChildDrawable[] layers = mLayerState.mChildren;
for (int i = mLayerState.mNum - 1; i >= 0; i--) {
if (layers[i].mId == id) {
return layers[i].mDrawable;
}
}
return null;
}
@Override
public Callback getCallback() {
if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
return super.getCallback();
} else {
return null;
}
}
@Override
public int getChangingConfigurations() {
return super.getChangingConfigurations()
| mLayerState.mChangingConfigurations
| mLayerState.mChildrenChangingConfigurations;
}
@Override
public ConstantState getConstantState() {
if (mLayerState.canConstantState()) {
mLayerState.mChangingConfigurations = getChangingConfigurations();
return mLayerState;
}
return null;
}
public Drawable getDrawable(int index) {
return mLayerState.mChildren[index].mDrawable;
}
public int getId(int index) {
return mLayerState.mChildren[index].mId;
}
@Override
public int getIntrinsicHeight() {
int height = -1;
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
int padT = 0, padB = 0;
for (int i = 0; i < N; i++) {
final ChildDrawable r = array[i];
int h = r.mDrawable.getIntrinsicHeight() + r.mInsetT + r.mInsetB + +padT + padB;
if (h > height) {
height = h;
}
padT += mPaddingT[i];
padB += mPaddingB[i];
}
return height;
}
@Override
public int getIntrinsicWidth() {
int width = -1;
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
int padL = 0, padR = 0;
for (int i = 0; i < N; i++) {
final ChildDrawable r = array[i];
int w = r.mDrawable.getIntrinsicWidth()
+ r.mInsetL + r.mInsetR + padL + padR;
if (w > width) {
width = w;
}
padL += mPaddingL[i];
padR += mPaddingR[i];
}
return width;
}
public int getNumberOfLayers() {
return mLayerState.mNum;
}
@Override
public int getOpacity() {
if (mOpacityOverride != PixelFormat.UNKNOWN) {
return mOpacityOverride;
}
return mLayerState.getOpacity();
}
@Override
public boolean getPadding(Rect padding) {
padding.left = 0;
padding.top = 0;
padding.right = 0;
padding.bottom = 0;
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
for (int i = 0; i < N; i++) {
reapplyPadding(i, array[i]);
padding.left += mPaddingL[i];
padding.top += mPaddingT[i];
padding.right += mPaddingR[i];
padding.bottom += mPaddingB[i];
}
return true;
}
@Override
public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs)
throws XmlPullParserException, IOException {
super.inflate(r, parser, attrs);
int type;
TypedArray a = r.obtainAttributes(attrs, R.styleable.LayerDrawable);
mOpacityOverride = a.getInt(R.styleable.LayerDrawable_android_opacity,
PixelFormat.UNKNOWN);
a.recycle();
final int innerDepth = parser.getDepth() + 1;
int depth;
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) {
if (type != XmlPullParser.START_TAG) {
continue;
}
if (depth > innerDepth || !parser.getName().equals("item")) {
continue;
}
a = r.obtainAttributes(attrs, R.styleable.LayerDrawableItem);
int left = a.getDimensionPixelOffset(R.styleable.LayerDrawableItem_android_left, 0);
int top = a.getDimensionPixelOffset(R.styleable.LayerDrawableItem_android_top, 0);
int right = a.getDimensionPixelOffset(R.styleable.LayerDrawableItem_android_right, 0);
int bottom = a.getDimensionPixelOffset(R.styleable.LayerDrawableItem_android_bottom, 0);
int drawableRes = a.getResourceId(R.styleable.LayerDrawableItem_android_drawable, 0);
int id = a.getResourceId(R.styleable.LayerDrawableItem_android_id, View.NO_ID);
a.recycle();
Drawable dr;
if (drawableRes != 0) {
dr = DrawableCompat.getDrawable(r, drawableRes);
} else {
while ((type = parser.next()) == XmlPullParser.TEXT) {
}
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException(parser.getPositionDescription()
+ ": <item> tag requires a 'drawable' attribute or "
+ "child tag defining a drawable");
}
dr = DrawableCompat.createFromXmlInner(r, parser, attrs);
}
addLayer(dr, id, left, top, right, bottom);
}
ensurePadding();
onStateChange(getState());
}
@Override
public void invalidateDrawable(Drawable who) {
final Callback callback = getCallback();
if (callback != null) {
callback.invalidateDrawable(this);
}
}
@Override
public boolean isStateful() {
return mLayerState.isStateful();
}
@Override
public Drawable mutate() {
if (!mMutated && super.mutate() == this) {
if (!mLayerState.canConstantState()) {
throw new IllegalStateException("One or more children of this LayerDrawable does " +
"not have constant state; this drawable cannot be mutated.");
}
mLayerState = new LayerState(mLayerState, this, null);
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
for (int i = 0; i < N; i++) {
array[i].mDrawable.mutate();
}
mMutated = true;
}
return this;
}
@Override
protected void onBoundsChange(Rect bounds) {
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
int padL = 0, padT = 0, padR = 0, padB = 0;
for (int i = 0; i < N; i++) {
final ChildDrawable r = array[i];
r.mDrawable.setBounds(bounds.left + r.mInsetL + padL,
bounds.top + r.mInsetT + padT,
bounds.right - r.mInsetR - padR,
bounds.bottom - r.mInsetB - padB);
padL += mPaddingL[i];
padR += mPaddingR[i];
padT += mPaddingT[i];
padB += mPaddingB[i];
}
}
@Override
protected boolean onLevelChange(int level) {
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
boolean paddingChanged = false;
boolean changed = false;
for (int i = 0; i < N; i++) {
final ChildDrawable r = array[i];
if (r.mDrawable.setLevel(level)) {
changed = true;
}
if (reapplyPadding(i, r)) {
paddingChanged = true;
}
}
if (paddingChanged) {
onBoundsChange(getBounds());
}
return changed;
}
@Override
protected boolean onStateChange(int[] state) {
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
boolean paddingChanged = false;
boolean changed = false;
for (int i = 0; i < N; i++) {
final ChildDrawable r = array[i];
if (r.mDrawable.setState(state)) {
changed = true;
}
if (reapplyPadding(i, r)) {
paddingChanged = true;
}
}
if (paddingChanged) {
onBoundsChange(getBounds());
}
if (changed) {
invalidateSelf();
}
return changed;
}
private boolean reapplyPadding(int i, ChildDrawable r) {
final Rect rect = mTmpRect;
r.mDrawable.getPadding(rect);
if (rect.left != mPaddingL[i] || rect.top != mPaddingT[i] ||
rect.right != mPaddingR[i] || rect.bottom != mPaddingB[i]) {
mPaddingL[i] = rect.left;
mPaddingT[i] = rect.top;
mPaddingR[i] = rect.right;
mPaddingB[i] = rect.bottom;
return true;
}
return false;
}
@Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
final Callback callback = getCallback();
if (callback != null) {
callback.scheduleDrawable(this, what, when);
}
}
@Override
public void setAlpha(int alpha) {
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
for (int i = 0; i < N; i++) {
array[i].mDrawable.setAlpha(alpha);
}
}
@Override
public void setColorFilter(ColorFilter cf) {
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
for (int i = 0; i < N; i++) {
array[i].mDrawable.setColorFilter(cf);
}
}
@Override
public void setDither(boolean dither) {
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
for (int i = 0; i < N; i++) {
array[i].mDrawable.setDither(dither);
}
}
public boolean setDrawableByLayerId(int id, Drawable drawable) {
final ChildDrawable[] layers = mLayerState.mChildren;
for (int i = mLayerState.mNum - 1; i >= 0; i--) {
if (layers[i].mId == id) {
if (layers[i].mDrawable != null) {
if (drawable != null) {
Rect bounds = layers[i].mDrawable.getBounds();
drawable.setBounds(bounds);
}
layers[i].mDrawable.setCallback(null);
}
if (drawable != null) {
drawable.setCallback(this);
}
layers[i].mDrawable = drawable;
return true;
}
}
return false;
}
public void setId(int index, int id) {
mLayerState.mChildren[index].mId = id;
}
public void setLayerInset(int index, int l, int t, int r, int b) {
ChildDrawable childDrawable = mLayerState.mChildren[index];
childDrawable.mInsetL = l;
childDrawable.mInsetT = t;
childDrawable.mInsetR = r;
childDrawable.mInsetB = b;
}
public void setOpacity(int opacity) {
mOpacityOverride = opacity;
}
@Override
public boolean setVisible(boolean visible, boolean restart) {
boolean changed = super.setVisible(visible, restart);
final ChildDrawable[] array = mLayerState.mChildren;
final int N = mLayerState.mNum;
for (int i = 0; i < N; i++) {
array[i].mDrawable.setVisible(visible, restart);
}
return changed;
}
@Override
public void unscheduleDrawable(Drawable who, Runnable what) {
final Callback callback = getCallback();
if (callback != null) {
callback.unscheduleDrawable(this, what);
}
}
}
| |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.protocols.ssl;
import org.xnio.BufferAllocator;
import org.xnio.ByteBufferSlicePool;
import org.xnio.ChannelListener;
import org.xnio.ChannelListeners;
import org.xnio.FutureResult;
import org.xnio.IoFuture;
import org.xnio.IoUtils;
import org.xnio.Option;
import org.xnio.OptionMap;
import org.xnio.Pool;
import org.xnio.StreamConnection;
import org.xnio.Xnio;
import org.xnio.XnioExecutor;
import org.xnio.XnioIoThread;
import org.xnio.XnioWorker;
import org.xnio.channels.AcceptingChannel;
import org.xnio.channels.AssembledConnectedSslStreamChannel;
import org.xnio.channels.BoundChannel;
import org.xnio.channels.ConnectedSslStreamChannel;
import org.xnio.channels.ConnectedStreamChannel;
import org.xnio.ssl.JsseSslUtils;
import org.xnio.ssl.JsseXnioSsl;
import org.xnio.ssl.SslConnection;
import org.xnio.ssl.XnioSsl;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.concurrent.TimeUnit;
import static org.xnio.IoUtils.safeClose;
/**
* @author Stuart Douglas
*/
public class UndertowXnioSsl extends XnioSsl {
private static final Pool<ByteBuffer> DEFAULT_BUFFER_POOL = new ByteBufferSlicePool(BufferAllocator.DIRECT_BYTE_BUFFER_ALLOCATOR, 17 * 1024, 17 * 1024 * 128);
private final Pool<ByteBuffer> bufferPool;
private volatile SSLContext sslContext;
/**
* Construct a new instance.
*
* @param xnio the XNIO instance to associate with
* @param optionMap the options for this provider
* @throws java.security.NoSuchProviderException if the given SSL provider is not found
* @throws java.security.NoSuchAlgorithmException if the given SSL algorithm is not supported
* @throws java.security.KeyManagementException if the SSL context could not be initialized
*/
public UndertowXnioSsl(final Xnio xnio, final OptionMap optionMap) throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
this(xnio, optionMap, DEFAULT_BUFFER_POOL, JsseSslUtils.createSSLContext(optionMap));
}
/**
* Construct a new instance.
* @param xnio the XNIO instance to associate with
* @param optionMap the options for this provider
* @param sslContext the SSL context to use for this instance
*/
public UndertowXnioSsl(final Xnio xnio, final OptionMap optionMap, final SSLContext sslContext) {
this(xnio, optionMap, DEFAULT_BUFFER_POOL, sslContext);
}
/**
* Construct a new instance.
*
* @param xnio the XNIO instance to associate with
* @param optionMap the options for this provider
* @param bufferPool
* @throws java.security.NoSuchProviderException if the given SSL provider is not found
* @throws java.security.NoSuchAlgorithmException if the given SSL algorithm is not supported
* @throws java.security.KeyManagementException if the SSL context could not be initialized
*/
public UndertowXnioSsl(final Xnio xnio, final OptionMap optionMap, Pool<ByteBuffer> bufferPool) throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
this(xnio, optionMap, bufferPool, JsseSslUtils.createSSLContext(optionMap));
}
/**
* Construct a new instance.
* @param xnio the XNIO instance to associate with
* @param optionMap the options for this provider
* @param bufferPool
* @param sslContext the SSL context to use for this instance
*/
public UndertowXnioSsl(final Xnio xnio, final OptionMap optionMap, Pool<ByteBuffer> bufferPool, final SSLContext sslContext) {
super(xnio, sslContext, optionMap);
this.bufferPool = bufferPool;
this.sslContext = sslContext;
}
/**
* Get the JSSE SSL context for this provider instance.
*
* @return the SSL context
*/
@SuppressWarnings("unused")
public SSLContext getSslContext() {
return sslContext;
}
/**
* Get the SSL engine for a given connection.
*
* @return the SSL engine
*/
public static SSLEngine getSslEngine(SslConnection connection) {
if (connection instanceof UndertowSslConnection) {
return ((UndertowSslConnection) connection).getSSLEngine();
} else {
return JsseXnioSsl.getSslEngine(connection);
}
}
@SuppressWarnings("deprecation")
public IoFuture<ConnectedSslStreamChannel> connectSsl(final XnioWorker worker, final InetSocketAddress bindAddress, final InetSocketAddress destination, final ChannelListener<? super ConnectedSslStreamChannel> openListener, final ChannelListener<? super BoundChannel> bindListener, final OptionMap optionMap) {
final FutureResult<ConnectedSslStreamChannel> futureResult = new FutureResult<>(IoUtils.directExecutor());
final IoFuture<SslConnection> futureSslConnection = openSslConnection(worker, bindAddress, destination, new ChannelListener<SslConnection>() {
public void handleEvent(final SslConnection sslConnection) {
final ConnectedSslStreamChannel assembledChannel = new AssembledConnectedSslStreamChannel(sslConnection, sslConnection.getSourceChannel(), sslConnection.getSinkChannel());
if (!futureResult.setResult(assembledChannel)) {
safeClose(assembledChannel);
} else {
ChannelListeners.invokeChannelListener(assembledChannel, openListener);
}
}
}, bindListener, optionMap).addNotifier(new IoFuture.HandlingNotifier<SslConnection, FutureResult<ConnectedSslStreamChannel>>() {
public void handleCancelled(final FutureResult<ConnectedSslStreamChannel> result) {
result.setCancelled();
}
public void handleFailed(final IOException exception, final FutureResult<ConnectedSslStreamChannel> result) {
result.setException(exception);
}
}, futureResult);
futureResult.getIoFuture().addNotifier(new IoFuture.HandlingNotifier<ConnectedStreamChannel, IoFuture<SslConnection>>() {
public void handleCancelled(final IoFuture<SslConnection> result) {
result.cancel();
}
}, futureSslConnection);
futureResult.addCancelHandler(futureSslConnection);
return futureResult.getIoFuture();
}
public IoFuture<SslConnection> openSslConnection(final XnioWorker worker, final InetSocketAddress bindAddress, final InetSocketAddress destination, final ChannelListener<? super SslConnection> openListener, final ChannelListener<? super BoundChannel> bindListener, final OptionMap optionMap) {
final FutureResult<SslConnection> futureResult = new FutureResult<>(worker);
final IoFuture<StreamConnection> connection = worker.openStreamConnection(bindAddress, destination, new StreamConnectionChannelListener(optionMap, destination, futureResult, openListener), bindListener, optionMap);
return setupSslConnection(futureResult, connection);
}
@Override
public IoFuture<SslConnection> openSslConnection(final XnioIoThread ioThread, final InetSocketAddress bindAddress, final InetSocketAddress destination, final ChannelListener<? super SslConnection> openListener, final ChannelListener<? super BoundChannel> bindListener, final OptionMap optionMap) {
final FutureResult<SslConnection> futureResult = new FutureResult<>(ioThread);
final IoFuture<StreamConnection> connection = ioThread.openStreamConnection(bindAddress, destination, new StreamConnectionChannelListener(optionMap, destination, futureResult, openListener), bindListener, optionMap);
return setupSslConnection(futureResult, connection);
}
public SslConnection wrapExistingConnection(StreamConnection connection, OptionMap optionMap) {
return new UndertowSslConnection(connection, JsseSslUtils.createSSLEngine(sslContext, optionMap, (InetSocketAddress) connection.getPeerAddress()), bufferPool);
}
private IoFuture<SslConnection> setupSslConnection(FutureResult<SslConnection> futureResult, IoFuture<StreamConnection> connection) {
connection.addNotifier(new IoFuture.HandlingNotifier<StreamConnection, FutureResult<SslConnection>>() {
public void handleCancelled(final FutureResult<SslConnection> attachment) {
attachment.setCancelled();
}
public void handleFailed(final IOException exception, final FutureResult<SslConnection> attachment) {
attachment.setException(exception);
}
}, futureResult);
futureResult.addCancelHandler(connection);
return futureResult.getIoFuture();
}
@SuppressWarnings("deprecation")
public AcceptingChannel<ConnectedSslStreamChannel> createSslTcpServer(final XnioWorker worker, final InetSocketAddress bindAddress, final ChannelListener<? super AcceptingChannel<ConnectedSslStreamChannel>> acceptListener, final OptionMap optionMap) throws IOException {
final AcceptingChannel<SslConnection> server = createSslConnectionServer(worker, bindAddress, null, optionMap);
final AcceptingChannel<ConnectedSslStreamChannel> acceptingChannel = new AcceptingChannel<ConnectedSslStreamChannel>() {
public ConnectedSslStreamChannel accept() throws IOException {
final SslConnection connection = server.accept();
return connection == null ? null : new AssembledConnectedSslStreamChannel(connection, connection.getSourceChannel(), connection.getSinkChannel());
}
public ChannelListener.Setter<? extends AcceptingChannel<ConnectedSslStreamChannel>> getAcceptSetter() {
return ChannelListeners.getDelegatingSetter(server.getAcceptSetter(), this);
}
public ChannelListener.Setter<? extends AcceptingChannel<ConnectedSslStreamChannel>> getCloseSetter() {
return ChannelListeners.getDelegatingSetter(server.getCloseSetter(), this);
}
public SocketAddress getLocalAddress() {
return server.getLocalAddress();
}
public <A extends SocketAddress> A getLocalAddress(final Class<A> type) {
return server.getLocalAddress(type);
}
public void suspendAccepts() {
server.suspendAccepts();
}
public void resumeAccepts() {
server.resumeAccepts();
}
public boolean isAcceptResumed() {
return server.isAcceptResumed();
}
public void wakeupAccepts() {
server.wakeupAccepts();
}
public void awaitAcceptable() throws IOException {
server.awaitAcceptable();
}
public void awaitAcceptable(final long time, final TimeUnit timeUnit) throws IOException {
server.awaitAcceptable(time, timeUnit);
}
public XnioWorker getWorker() {
return server.getWorker();
}
@Deprecated
public XnioExecutor getAcceptThread() {
return server.getAcceptThread();
}
public XnioIoThread getIoThread() {
return server.getIoThread();
}
public void close() throws IOException {
server.close();
}
public boolean isOpen() {
return server.isOpen();
}
public boolean supportsOption(final Option<?> option) {
return server.supportsOption(option);
}
public <T> T getOption(final Option<T> option) throws IOException {
return server.getOption(option);
}
public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException {
return server.setOption(option, value);
}
};
acceptingChannel.getAcceptSetter().set(acceptListener);
return acceptingChannel;
}
/**
* Updates the SSLContext that is in use. All new connections will use this new context, however established connections
* will not be affected.
*
* @param context The new context
*/
public void updateSSLContext(SSLContext context) {
this.sslContext = context;
}
public AcceptingChannel<SslConnection> createSslConnectionServer(final XnioWorker worker, final InetSocketAddress bindAddress, final ChannelListener<? super AcceptingChannel<SslConnection>> acceptListener, final OptionMap optionMap) throws IOException {
final UndertowAcceptingSslChannel server = new UndertowAcceptingSslChannel(this, worker.createStreamConnectionServer(bindAddress, null, optionMap), optionMap, bufferPool, false);
if (acceptListener != null) server.getAcceptSetter().set(acceptListener);
return server;
}
private class StreamConnectionChannelListener implements ChannelListener<StreamConnection> {
private final OptionMap optionMap;
private final InetSocketAddress destination;
private final FutureResult<SslConnection> futureResult;
private final ChannelListener<? super SslConnection> openListener;
public StreamConnectionChannelListener(OptionMap optionMap, InetSocketAddress destination, FutureResult<SslConnection> futureResult, ChannelListener<? super SslConnection> openListener) {
this.optionMap = optionMap;
this.destination = destination;
this.futureResult = futureResult;
this.openListener = openListener;
}
public void handleEvent(final StreamConnection connection) {
final SslConnection wrappedConnection = new UndertowSslConnection(connection, JsseSslUtils.createSSLEngine(sslContext, optionMap, destination), bufferPool);
if (! futureResult.setResult(wrappedConnection)) {
IoUtils.safeClose(connection);
} else {
ChannelListeners.invokeChannelListener(wrappedConnection, openListener);
}
}
}
}
| |
package io.indexr.tool;
import com.google.common.base.Preconditions;
import org.apache.commons.io.IOUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import io.indexr.io.ByteBufferReader;
import io.indexr.plugin.Plugins;
import io.indexr.segment.Column;
import io.indexr.segment.InfoSegment;
import io.indexr.segment.SegmentManager;
import io.indexr.segment.SegmentMode;
import io.indexr.segment.SegmentSchema;
import io.indexr.segment.pack.DataPackNode;
import io.indexr.segment.rt.RTSGroupInfo;
import io.indexr.segment.storage.StorageSegment;
import io.indexr.segment.storage.itg.IntegratedColumn;
import io.indexr.segment.storage.itg.IntegratedSegment;
import io.indexr.server.FileSegmentManager;
import io.indexr.server.IndexRConfig;
import io.indexr.server.SegmentHelper;
import io.indexr.server.ServerHelper;
import io.indexr.server.TableSchema;
import io.indexr.server.ZkTableManager;
import io.indexr.server.rt.RealtimeConfig;
import io.indexr.server.rt.RealtimeSegmentPool;
import io.indexr.server.rt2his.HiveHelper;
import io.indexr.util.GenericCompression;
import io.indexr.util.JsonUtil;
import io.indexr.util.RuntimeUtil;
import io.indexr.util.Strings;
import io.indexr.util.Try;
public class Tools {
private static final Logger logger = LoggerFactory.getLogger(Tools.class);
static {
RealtimeConfig.loadSubtypes();
}
private static class MyOptions {
@Option(name = "-h", usage = "print this help. \nUsage: -cmd <cmd> [-option ...]")
boolean help;
@Option(name = "-cmd", metaVar = "<cmd>", usage = "the command." +
"\n=====================================" +
"\nlisttb - list all tables." +
"\nsettb - add or update table. [-t, -c]" +
"\nrmtb - remove table. [-t]" +
"\ndctb - describe table. [-t] " +
"\nlisths - list all historical segments. [-t]" +
"\nlistrs - list all realtime segments. [-t, -v]" +
"\nrmseg - remove segments. [-t, -s]" +
"\ndchs - describ historical segments. [-t, -s, -v]" +
"\nstoprt - stop realtime. [-host, -port]" +
"\nstartrt - start realtime. [-host, -port]" +
"\nstopnode - stop indexr node. [-host, -port]" +
"\nlistnode - list all running nodes." +
"\nnodertt - list all realtime tables on host. [-host]" +
"\nrttnode - list all hosts the realtime table exists. [-t]" +
"\naddrtt - add realtime table to hosts. [-t, -host]" +
"\nrmrtt - remove realtime table from hosts. [-t, -host]" +
"\nnotifysu - notify segment update. [-t]" +
"\nhivesql - get the hive table creation sql. Specify the partition column of hive table by -column <columnName>. [-t, -c, -column, -hivetb]" +
"\nupmode - update table segment mode. [-t, -mode]" +
"\nmergefrag - merge fragments of table. [-t]" +
"\n=====================================")
String cmd;
@Option(name = "-v", usage = "verbose or not")
boolean verbose = false;
@Option(name = "-t", metaVar = "<tableName>", usage = "table name(s), splited by `,`")
String table;
@Option(name = "-s", metaVar = "<segmentName>", usage = "segment name(s), splited by `,`")
String segment;
@Option(name = "-c", metaVar = "<schemaPath>", usage = "the path of table schema")
String schemapath;
@Option(name = "-col", metaVar = "<columnName>", usage = "the column name, splited by `,`")
String columnName;
@Option(name = "-hivetb", metaVar = "<hiveTableName>", usage = "the hive table name")
String hiveTable;
@Option(name = "-host", metaVar = "<host>", usage = "host of node(s), splited by `,`")
String host;
@Option(name = "-port", metaVar = "<port>", usage = "control port of node")
int port = 9235;
@Option(name = "-mode", metaVar = "<mode>", usage = "segment mode")
String mode = SegmentMode.DEFAULT.name();
}
public static void main(String[] args) throws Exception {
// Hack, make jvm init the static fields.
RealtimeConfig.loadSubtypes();
MyOptions options = new MyOptions();
CmdLineParser parser = RuntimeUtil.parseArgs(args, options);
if (options.help) {
parser.printUsage(System.out);
return;
}
Plugins.loadPlugins();
IndexRConfig config = new IndexRConfig();
boolean ok = false;
try {
ok = runTool(options, config);
} catch (Exception e) {
logger.error("", e);
} finally {
IOUtils.closeQuietly(config);
}
if (ok) {
System.exit(0);
} else {
System.exit(1);
}
}
private static boolean runTool(MyOptions options, IndexRConfig config) throws Exception {
if (Strings.isEmpty(options.cmd)) {
System.out.println("Please specify -cmd");
return false;
}
switch (options.cmd.toLowerCase()) {
case "listtb":
return listTable(options, config);
case "settb":
return setTable(options, config);
case "rmtb":
return removeTables(options, config);
case "dctb":
return describeTables(options, config);
case "lisths":
return listHisSegs(options, config);
case "listrs":
return listRTSegs(options, config);
case "dchs":
return describeHisSeg(options, config);
case "rmseg":
return removeSegments(options, config);
case "stoprt":
return stopRealtime(options, config);
case "startrt":
return startRealtime(options, config);
case "stopnode":
return stopNode(options, config);
case "listnode":
return listNode(options, config);
case "nodertt":
return nodeRTT(options, config);
case "rttnode":
return rttNode(options, config);
case "addrtt":
return addRTT(options, config);
case "rmrtt":
return removeRTT(options, config);
case "notifysu":
return notifySegmentUpdate(options, config);
case "hivesql":
return hiveCreateSql(options, config);
case "upmode":
return updateMode(options, config);
case "mergefrag":
return mergeFragments(options, config);
default:
System.out.println("Illegal cmd: " + options.cmd);
return false;
}
}
private static boolean listTable(MyOptions options, IndexRConfig config) throws Exception {
ZkTableManager tm = new ZkTableManager(config.getZkClient());
Set<String> tables = tm.allTableNames();
if (tables == null) {
return true;
}
List<String> list = new ArrayList<>(tables);
list.sort(String::compareTo);
list.forEach(System.out::println);
return true;
}
private static boolean setTable(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
Preconditions.checkState(!Strings.isEmpty(options.schemapath), "Please specify schema path! -c <path>");
String[] tableNames = options.table.split(",");
Preconditions.checkState(tableNames.length == 1, "Can only add one table one time!");
TableSchema schema = JsonUtil.loadConfig(Paths.get(options.schemapath), TableSchema.class);
//RealtimeConfig rtConfig = schema.realtimeConfig;
//if (rtConfig != null) {
// String error = RealtimeHelper.validateSetting(schema.schema.getColumns(), rtConfig.dims, rtConfig.metrics, rtConfig.grouping);
// if (error != null) {
// System.out.println(error);
// return false;
// }
//}
ZkTableManager tm = new ZkTableManager(config.getZkClient());
tm.set(options.table, schema);
System.out.println("OK");
return true;
}
private static boolean removeTables(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
String[] tableNames = options.table.split(",");
ZkTableManager tm = new ZkTableManager(config.getZkClient());
for (String name : tableNames) {
tm.remove(name.trim());
}
System.out.println("OK");
return true;
}
private static boolean describeTables(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
String[] tableNames = options.table.split(",");
ZkTableManager tm = new ZkTableManager(config.getZkClient());
for (String name : tableNames) {
String schema = JsonUtil.toJson(tm.getTableSchema(name));
System.out.printf("%s:\n%s\n", name, schema);
}
return true;
}
private static boolean listHisSegs(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
String[] tableNames = options.table.split(",");
Preconditions.checkState(tableNames.length == 1, "Only one table name are supported!");
ZkTableManager zkTableManager = new ZkTableManager(config.getZkClient());
TableSchema schema = zkTableManager.getTableSchema(options.table);
SegmentManager tm = new FileSegmentManager(
options.table,
config.getFileSystem(),
IndexRConfig.segmentRootPath(config.getDataRoot(), options.table, schema.location));
List<String> names = tm.allSegmentNames();
if (names == null) {
return true;
}
List<String> list = new ArrayList<String>(names);
list.sort(String::compareTo);
list.forEach(System.out::println);
return true;
}
private static boolean listRTSegs(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
String delcarePath = IndexRConfig.zkRTTablePath(options.table);
CuratorFramework zkClient = config.getZkClient();
List<String> hosts = zkClient.getChildren().forPath(delcarePath);
for (String host : hosts) {
byte[] bytes = Try.on(() -> zkClient.getData().forPath(delcarePath + "/" + host), 1, logger);
if (bytes == null) {
continue;
}
RealtimeSegmentPool.HostSegmentInfo hostInfo = JsonUtil.fromJson(GenericCompression.decomress(bytes), RealtimeSegmentPool.HostSegmentInfo.class);
if (hostInfo == null) {
continue;
}
List<RTSGroupInfo> rtsegs = new ArrayList<>(hostInfo.rtsGroupInfos);
if (!rtsegs.isEmpty()) {
rtsegs.sort((a, b) -> a.name().compareTo(b.name()));
for (RTSGroupInfo info : rtsegs) {
System.out.println(info.name() + ":\n----------");
System.out.println("host: " + host);
System.out.println("rowCount: " + info.rowCount());
System.out.println("version: " + info.version());
System.out.println("mode: " + info.mode());
if (options.verbose) {
System.out.println("schema:\n" + JsonUtil.toJson(info.schema()));
System.out.println("columnNodes:\n" + JsonUtil.toJson(info.columnNodes));
}
System.out.println();
}
}
}
return true;
}
private static boolean describeHisSeg(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
Preconditions.checkState(!Strings.isEmpty(options.segment), "Please specify segment name! -s <name>");
ZkTableManager zkTableManager = new ZkTableManager(config.getZkClient());
TableSchema tableSchema = zkTableManager.getTableSchema(options.table);
Path segmentRootPath = IndexRConfig.segmentRootPath(config.getDataRoot(), options.table, tableSchema.location);
String[] segNames = options.segment.split(",");
for (String segName : segNames) {
segName = segName.trim();
Path path = new Path(segmentRootPath, segName);
FileSystem fileSystem = config.getFileSystem();
FileStatus fileStatus = fileSystem.getFileStatus(path);
if (fileStatus == null) {
System.out.printf("%s is not exists!\n", segName);
continue;
}
int blockCount = fileSystem.getFileBlockLocations(fileStatus, 0, fileStatus.getLen()).length;
ByteBufferReader.Opener readerOpener = ByteBufferReader.Opener.create(
fileSystem,
path,
fileStatus.getLen(),
blockCount);
IntegratedSegment.Fd fd = IntegratedSegment.Fd.create(segName, readerOpener);
if (fd == null) {
System.out.printf("%s is not a legal segment!\n", segName);
continue;
}
try (StorageSegment segment = fd.open()) {
InfoSegment infoSegment = fd.info();
SegmentSchema schema = infoSegment.schema();
long rowCount = infoSegment.rowCount();
System.out.println(segName + ":\n----------");
System.out.println("rowCount: " + rowCount);
System.out.println("size: " + fileStatus.getLen());
System.out.println("version: " + segment.version());
System.out.println("mode: " + segment.mode());
if (options.verbose) {
System.out.println("schema:\n" + JsonUtil.toJson(schema));
System.out.println("sectionInfo:\n" + JsonUtil.toJson(fd.sectionInfo()));
System.out.println("columnInfo:");
for (int colId = 0; colId < schema.getColumns().size(); colId++) {
Column column = segment.column(colId);
long dpnSize = 0;
long indexSize = 0;
long extIndexSize = 0;
long outerIndexSize = ((IntegratedColumn) column).outerIndexSize();
long dataSize = 0;
for (int packId = 0; packId < column.packCount(); packId++) {
DataPackNode dpn = column.dpn(packId);
dpnSize += segment.mode().versionAdapter.dpnSize(segment.version(), segment.mode());
indexSize += dpn.indexSize();
extIndexSize += dpn.extIndexSize();
dataSize += dpn.packSize();
}
System.out.printf(" %s: dpn: %s, index: %s, extIndex: %s, outerIndex: %s, data: %s, dict(0th): %s\n", column.name(), dpnSize, indexSize, extIndexSize, outerIndexSize, dataSize, column.dpn(0).isDictEncoded());
}
}
System.out.println();
}
}
return true;
}
private static boolean removeSegments(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
String[] tableNames = options.table.split(",");
Preconditions.checkState(tableNames.length == 1, "Only one table name are supported!");
Preconditions.checkState(options.segment != null, "Please specify segment name! -s <name>");
ZkTableManager zkTableManager = new ZkTableManager(config.getZkClient());
TableSchema schema = zkTableManager.getTableSchema(options.table);
SegmentManager tm = new FileSegmentManager(
options.table,
config.getFileSystem(),
IndexRConfig.segmentRootPath(config.getDataRoot(), options.table, schema.location));
String[] names = options.segment.split(",");
for (String name : names) {
tm.remove(name.trim());
}
System.out.println("OK");
return true;
}
private static boolean stopRealtime(MyOptions options, IndexRConfig config) throws Exception {
String host = options.host == null ? InetAddress.getLocalHost().getHostName() : options.host;
int port = options.port == 0 ? config.getControlPort() : options.port;
if (options.table == null) {
sendCommand(host, port, "cmd=stoprt");
} else {
HttpParams params = new BasicHttpParams();
sendCommand(host, port, "cmd=stoprt&table=" + options.table);
}
return true;
}
private static boolean startRealtime(MyOptions options, IndexRConfig config) throws Exception {
String host = options.host == null ? InetAddress.getLocalHost().getHostName() : options.host;
int port = options.port == 0 ? config.getControlPort() : options.port;
if (options.table == null) {
sendCommand(host, port, "cmd=startrt");
} else {
sendCommand(host, port, "cmd=startrt&table=" + options.table);
}
return true;
}
private static boolean stopNode(MyOptions options, IndexRConfig config) throws Exception {
String host = options.host == null ? InetAddress.getLocalHost().getHostName() : options.host;
int port = options.port == 0 ? config.getControlPort() : options.port;
sendCommand(host, port, "cmd=stopnode");
return true;
}
private static boolean listNode(MyOptions options, IndexRConfig config) throws Exception {
List<String> hosts = ServerHelper.validHosts(config.getZkClient());
hosts.sort(String::compareTo);
hosts.forEach(System.out::println);
return true;
}
private static boolean nodeRTT(MyOptions options, IndexRConfig config) throws Exception {
CuratorFramework zkClient = config.getZkClient();
List<String> hosts;
if (Strings.isEmpty(options.host)) {
hosts = ServerHelper.validHosts(zkClient);
hosts.sort(String::compareTo);
} else {
hosts = Collections.singletonList(options.host);
}
for (String host : hosts) {
System.out.println(host + ":\n-----------");
List<String> tables = ServerHelper.getHostRTTables(zkClient, host);
tables.sort(String::compareTo);
tables.forEach(System.out::println);
System.out.println();
}
return true;
}
private static boolean rttNode(MyOptions options, IndexRConfig config) throws Exception {
CuratorFramework zkClient = config.getZkClient();
List<String> tables;
if (Strings.isEmpty(options.table)) {
ZkTableManager tm = new ZkTableManager(zkClient);
Set<String> tbs = tm.allTableNames();
if (tbs == null) {
return true;
}
tables = new ArrayList<>(tbs);
tables.sort(String::compareTo);
} else {
tables = Collections.singletonList(options.table);
}
for (String table : tables) {
System.out.println(table + ":\n-----------");
List<String> hosts = ServerHelper.getRTTableHosts(zkClient, table);
hosts.sort(String::compareTo);
hosts.forEach(System.out::println);
System.out.println();
}
return true;
}
private static boolean addRTT(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
Preconditions.checkState(!Strings.isEmpty(options.host), "Please specify host! -host <host>");
List<String> hosts = Arrays.asList(options.host.split(","));
ServerHelper.addRTTableToHosts(config.getZkClient(), options.table, hosts);
System.out.println("OK");
return true;
}
private static boolean removeRTT(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
Preconditions.checkState(!Strings.isEmpty(options.host), "Please specify host! -host <host>");
List<String> hosts = Arrays.asList(options.host.split(","));
ServerHelper.removeRTTableFromHosts(config.getZkClient(), options.table, hosts);
System.out.println("OK");
return true;
}
private static void sendCommand(String host, int port, String params) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
String url = String.format("http://%s:%d/control?%s", host, port, params);
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
System.out.println("OK");
} else {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
System.out.println(IOUtils.toString(new InputStreamReader(instream)));
} catch (RuntimeException ex) {
instream.close();
}
} else {
System.out.println("FAIL");
}
}
} finally {
httpclient.getConnectionManager().shutdown();
}
}
private static boolean notifySegmentUpdate(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
ZkTableManager tm = new ZkTableManager(config.getZkClient());
Preconditions.checkState(tm.getTableSchema(options.table) != null, "Table [%s] not exists!", options.table);
TableSchema schema = tm.getTableSchema(options.table);
SegmentHelper.notifyUpdate(
config.getFileSystem(),
IndexRConfig.segmentRootPath(config.getDataRoot(), options.table, schema.location));
System.out.println("OK");
return true;
}
private static boolean hiveCreateSql(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
Preconditions.checkState(!Strings.isEmpty(options.columnName), "Please specify hive table partition column by -col <columnName>");
TableSchema schema;
if (!Strings.isEmpty(options.schemapath)) {
schema = JsonUtil.loadConfig(Paths.get(options.schemapath), TableSchema.class);
} else {
ZkTableManager tm = new ZkTableManager(config.getZkClient());
schema = tm.getTableSchema(options.table);
}
if (schema == null) {
System.out.println("Table schema not found. Neither specified by -c, nor found in system.");
return false;
}
String createSql = HiveHelper.getHiveTableCreateSql(
Strings.isEmpty(options.hiveTable) ? options.table : options.hiveTable,
true,
schema.schema,
schema.mode,
schema.aggSchema,
IndexRConfig.segmentRootPath(config.getDataRoot(), options.table, schema.location).toString(),
options.columnName
);
if (!createSql.trim().endsWith(";")) {
createSql += ";";
}
System.out.println(createSql);
return true;
}
private static boolean updateMode(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
Preconditions.checkState(!Strings.isEmpty(options.mode), "Please specify segment mode by -mode <mode>");
SegmentMode newMode = SegmentMode.fromName(options.mode);
String[] tables = options.table.trim().split(",");
for (String table : tables) {
table = table.trim();
ZkTableManager tm = new ZkTableManager(config.getZkClient());
TableSchema schema = tm.getTableSchema(table);
if (schema == null) {
System.out.printf("Table [%s] schema not found in system.\n", table);
return false;
}
schema.setMode(newMode);
schema.realtimeConfig.setMode(newMode);
tm.set(table, schema);
}
return true;
}
private static boolean mergeFragments(MyOptions options, IndexRConfig config) throws Exception {
Preconditions.checkState(!Strings.isEmpty(options.table), "Please specify table name! -t <name>");
FragmentMerger.mergeTable(options.table, config);
return true;
}
}
| |
package gigaherz.nattrees;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLeaves;
import net.minecraft.block.IGrowable;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.ColorizerFoliage;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeColorHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
import java.util.Random;
public class BlockBranch
extends Block
implements IGrowable
{
public static int getMetaFromProperties(int thickness, boolean leaves)
{
if (leaves)
thickness |= 8;
return thickness;
}
public static final PropertyDirection FACING = PropertyDirection.create("facing");
public static final PropertyBool HAS_LEAVES = PropertyBool.create("has_leaves");
public static final PropertyInteger THICKNESS = PropertyInteger.create("thickness", 0, 7);
public final Variant variant;
public BlockBranch(Material materialIn, Variant variant, String unlocName)
{
super(materialIn);
this.variant = variant;
this.setDefaultState(this.blockState.getBaseState()
.withProperty(FACING, EnumFacing.DOWN)
.withProperty(HAS_LEAVES, false)
.withProperty(THICKNESS, 0));
this.setCreativeTab(CreativeTabs.tabDecorations);
this.setLightOpacity(1);
this.setHardness(4);
this.setStepSound(SoundType.WOOD);
this.setUnlocalizedName(unlocName);
}
@Override
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(THICKNESS, meta & 7).withProperty(HAS_LEAVES, (meta & 8) > 0);
}
@Override
public int getMetaFromState(IBlockState state)
{
int i = state.getValue(THICKNESS);
if (state.getValue(HAS_LEAVES))
i |= 8;
return i;
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
{
int thickness = state.getValue(THICKNESS);
EnumFacing face = getPreferredConnectionSide(worldIn, pos, thickness);
state = state.withProperty(FACING, face);
return state;
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, FACING, HAS_LEAVES, THICKNESS);
}
@SideOnly(Side.CLIENT)
public int getBlockColor(IBlockState state)
{
return ColorizerFoliage.getFoliageColor(0.5D, 1.0D);
}
@SideOnly(Side.CLIENT)
public int getRenderColor(IBlockState state)
{
switch (variant)
{
case BIRCH:
return ColorizerFoliage.getFoliageColorBirch();
case SPRUCE:
return ColorizerFoliage.getFoliageColorPine();
}
return ColorizerFoliage.getFoliageColorBasic();
}
@Override
@SideOnly(Side.CLIENT)
public BlockRenderLayer getBlockLayer()
{
return BlockRenderLayer.CUTOUT_MIPPED;
}
@Override
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
@Override
public boolean isFullCube(IBlockState state)
{
return false;
}
@Override
public boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
return true;
}
@Override
public float getBlockHardness(IBlockState state, World worldIn, BlockPos pos)
{
return this.blockHardness * (getThickness(worldIn, pos) + 1) / 8.0f;
}
@Override
public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, EnumFacing side)
{
BlockPos npos = pos.offset(side.getOpposite());
Block block = worldIn.getBlockState(npos).getBlock();
if (block instanceof BlockBranch)
{
return block == this;
}
if (side != EnumFacing.UP)
return false;
if (block != Blocks.dirt && block != Blocks.grass)
return false;
return worldIn.isSideSolid(npos, side, true);
}
@Override
public boolean canPlaceBlockAt(World worldIn, BlockPos pos)
{
for (EnumFacing facing : EnumFacing.values())
{
if (canPlaceBlockOnSide(worldIn, pos, facing))
{
return true;
}
}
return false;
}
protected EnumFacing getPreferredConnectionSide(IBlockAccess worldIn, BlockPos pos, int thickness)
{
EnumFacing face = EnumFacing.DOWN;
int preference = -1;
int pref;
pref = this.getConnectionValue(worldIn, pos, EnumFacing.DOWN, thickness * 2 + 1);
if (pref > preference)
{
face = EnumFacing.DOWN;
preference = pref;
}
pref = this.getConnectionValue(worldIn, pos, EnumFacing.UP, thickness * 2 + 1);
if (pref > preference)
{
face = EnumFacing.UP;
preference = pref;
}
pref = this.getConnectionValue(worldIn, pos, EnumFacing.WEST, thickness * 2 + 1);
if (pref > preference)
{
face = EnumFacing.WEST;
preference = pref;
}
pref = this.getConnectionValue(worldIn, pos, EnumFacing.EAST, thickness * 2 + 1);
if (pref > preference)
{
face = EnumFacing.EAST;
preference = pref;
}
pref = this.getConnectionValue(worldIn, pos, EnumFacing.NORTH, thickness * 2 + 1);
if (pref > preference)
{
face = EnumFacing.NORTH;
preference = pref;
}
pref = this.getConnectionValue(worldIn, pos, EnumFacing.SOUTH, thickness * 2 + 1);
if (pref > preference)
{
face = EnumFacing.SOUTH;
preference = pref;
}
if (preference < thickness * 2)
return EnumFacing.DOWN;
return face;
}
private int getConnectionValue(IBlockAccess worldIn, BlockPos thisPos, EnumFacing facing, int sideValue)
{
BlockPos pos = thisPos.offset(facing);
IBlockState state = worldIn.getBlockState(pos);
Block block = state.getBlock();
if (block == Blocks.barrier)
return -1;
if (block instanceof BlockBranch)
{
if (block.getUnlocalizedName().equals(getUnlocalizedName()))
return ((BlockBranch) block).getThickness(worldIn, pos) * 2;
else return -1;
}
if (block.isSideSolid(state, worldIn, pos, facing.getOpposite()))
return sideValue;
return -1;
}
@Override
public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
{
int thickness = meta & 7;
boolean hasLeaves = (meta & 8) != 0;
return this.getDefaultState()
.withProperty(THICKNESS, thickness)
.withProperty(HAS_LEAVES, hasLeaves);
}
@Override
public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos)
{
return getBB(pos.getX(), pos.getY(), pos.getZ(), state);
}
@Override
public AxisAlignedBB getCollisionBoundingBox(IBlockState state, World world, BlockPos pos)
{
return getBB(pos.getX(), pos.getY(), pos.getZ(), state);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos)
{
return getBB(0, 0, 0, state);
}
@Override
public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB mask, List<AxisAlignedBB> list, Entity p_185477_6_)
{
AxisAlignedBB aabb = getBB(pos.getX(), pos.getY(), pos.getZ(), state);
if (aabb != null && mask.intersectsWith(aabb))
{
list.add(aabb);
}
}
public AxisAlignedBB getBB(int x, int y, int z, IBlockState state)
{
boolean hasLeaves = state.getValue(HAS_LEAVES);
float west, down, north, east, up, south;
if (hasLeaves)
{
west = down = north = 0;
east = up = south = 1;
}
else
{
//EnumFacing facing = state.getValue(FACING);
int thickness = state.getValue(THICKNESS);
float width = (thickness + 1) * 2 / 16.0f;
north = (1 - width) / 2;
south = 1 - north;
west = (1 - width) / 2;
east = 1 - west;
down = (1 - width) / 2;
up = 1 - down;
/*if (facing == EnumFacing.DOWN)
down = 0;
else if (facing == EnumFacing.UP)
up = 1;
else if (facing == EnumFacing.WEST)
west = 0;
else if (facing == EnumFacing.EAST)
east = 1;
else if (facing == EnumFacing.NORTH)
north = 0;
else if (facing == EnumFacing.SOUTH)
south = 1;*/
}
return new AxisAlignedBB(
x+west, y+down, z+north,
x+east, y+up, z+south);
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ)
{
boolean hasLeaves = state.getValue(HAS_LEAVES);
ItemStack stack = playerIn.getHeldItem(hand);
if (stack != null && stack.stackSize > 0 && stack.getItem().getToolClasses(stack).contains("sword"))
{
if (hasLeaves)
{
worldIn.setBlockState(pos, state.withProperty(HAS_LEAVES, false));
// TODO: pretend break leaf block
// BlockLeaves.dropBlockAsItem
}
}
if (canHaveLeaves(worldIn, pos, state))
{
if (stack != null && stack.stackSize > 0 && stack.getItem() instanceof ItemBlock)
{
ItemBlock ib = (ItemBlock) stack.getItem();
if (ib.getBlock() instanceof BlockLeaves && !stack.hasTagCompound())
{
stack.stackSize--;
worldIn.setBlockState(pos, state.withProperty(HAS_LEAVES, true));
return true;
}
}
}
return false;
}
private boolean canHaveLeaves(World worldIn, BlockPos pos, IBlockState state)
{
if (state == null)
state = worldIn.getBlockState(pos);
return variant.canHaveLeaves() && state.getValue(THICKNESS) < 7;
}
public int getThickness(IBlockAccess worldIn, BlockPos pos)
{
IBlockState state = worldIn.getBlockState(pos);
if (state.getBlock() != this)
return 0;
return state.getValue(THICKNESS);
}
public boolean getHasLeaves(World worldIn, BlockPos pos)
{
IBlockState state = worldIn.getBlockState(pos);
return state.getValue(HAS_LEAVES);
}
@Override
public boolean canGrow(World worldIn, BlockPos pos, IBlockState state, boolean isClient)
{
return state.getValue(THICKNESS) < 7;
}
@Override
public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, IBlockState state)
{
return state.getValue(THICKNESS) < 7;
}
@Override
public void grow(World worldIn, Random rand, BlockPos pos, IBlockState state)
{
int thickness = state.getValue(THICKNESS);
worldIn.setBlockState(pos, state.withProperty(THICKNESS, thickness + 1));
}
public enum Variant implements IStringSerializable
{
OAK("oak"),
BIRCH("birch"),
SPRUCE("spruce"),
JUNGLE("jungle"),
DARK_OAK("dark_oak"),
ACACIA("acacia");
// TODO: CACTUS?
private final String name;
private final boolean canHaveLeaves;
Variant(String name)
{
this.name = name;
this.canHaveLeaves = true;
}
// For future use with CACTUS and such
Variant(String name, boolean canHaveLeaves)
{
this.name = name;
this.canHaveLeaves = canHaveLeaves;
}
@Override
public String toString()
{
return name;
}
@Override
public String getName()
{
return name;
}
public boolean canHaveLeaves()
{
return canHaveLeaves;
}
}
}
| |
package com.example.lovetalk.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVUser;
import com.example.lovetalk.DemoApplication;
import com.example.lovetalk.R;
import com.example.lovetalk.activity.ChatActivity;
import com.example.lovetalk.chat.entity.Msg;
import com.example.lovetalk.chat.entity.RoomType;
import com.example.lovetalk.service.UserService;
import com.example.lovetalk.util.EmotionUtils;
import com.example.lovetalk.util.PathUtils;
import com.example.lovetalk.util.PhotoUtil;
import com.example.lovetalk.util.TimeUtils;
import com.example.lovetalk.view.PlayButton;
import com.example.lovetalk.view.ViewHolder;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.io.File;
import java.util.List;
public class ChatMsgAdapter extends BaseListAdapter<Msg> {
int msgViewTypes = 8;
public static interface MsgViewType {
int COME_TEXT = 0;
int TO_TEXT = 1;
int COME_IMAGE = 2;
int TO_IMAGE = 3;
int COME_AUDIO = 4;
int TO_AUDIO = 5;
int COME_LOCATION = 6;
int TO_LOCATION = 7;
}
ChatActivity chatActivity;
public ChatMsgAdapter(ChatActivity chatActivity, List<Msg> datas) {
super(chatActivity, datas);
this.chatActivity = chatActivity;
}
public int getItemPosById(String objectId) {
for (int i = 0; i < getCount(); i++) {
Msg itemMsg = datas.get(i);
if (itemMsg.getObjectId().equals(objectId)) {
return i;
}
}
return -1;
}
public Msg getItem(String objectId) {
for (Msg msg : datas) {
if (msg.getObjectId().equals(objectId)) {
return msg;
}
}
return null;
}
public int getItemViewType(int position) {
Msg entity = datas.get(position);
boolean comeMsg = entity.isComeMessage();
Msg.Type type = entity.getType();
switch (type) {
case Text:
return comeMsg ? MsgViewType.COME_TEXT : MsgViewType.TO_TEXT;
case Image:
return comeMsg ? MsgViewType.COME_IMAGE : MsgViewType.TO_IMAGE;
case Audio:
return comeMsg ? MsgViewType.COME_AUDIO : MsgViewType.TO_AUDIO;
case Location:
return comeMsg ? MsgViewType.COME_LOCATION : MsgViewType.TO_LOCATION;
}
throw new IllegalStateException("position's type is wrong");
}
public int getViewTypeCount() {
return msgViewTypes;
}
public View getView(int position, View conView, ViewGroup parent) {
Msg msg = datas.get(position);
int itemViewType = getItemViewType(position);
boolean isComMsg = msg.isComeMessage();
if (conView == null) {
conView = createViewByType(itemViewType);
}
TextView sendTimeView = ViewHolder.findViewById(conView, R.id.sendTimeView);
TextView contentView = ViewHolder.findViewById(conView, R.id.textContent);
ImageView imageView = ViewHolder.findViewById(conView, R.id.imageView);
ImageView avatarView = ViewHolder.findViewById(conView, R.id.avatar);
PlayButton playBtn = ViewHolder.findViewById(conView, R.id.playBtn);
TextView locationView = ViewHolder.findViewById(conView, R.id.locationView);
View statusSendFailed = ViewHolder.findViewById(conView, R.id.status_send_failed);
View statusSendSucceed = ViewHolder.findViewById(conView, R.id.status_send_succeed);
View statusSendStart = ViewHolder.findViewById(conView, R.id.status_send_start);
// timestamp
if (position == 0 || TimeUtils.haveTimeGap(datas.get(position - 1).getTimestamp(),
msg.getTimestamp())) {
sendTimeView.setVisibility(View.VISIBLE);
sendTimeView.setText(TimeUtils.millisecs2DateString(msg.getTimestamp()));
} else {
sendTimeView.setVisibility(View.GONE);
}
String fromPeerId = msg.getFromPeerId();
AVUser user = DemoApplication.lookupUser(fromPeerId);
if (user == null) {
throw new RuntimeException("cannot find user");
}
UserService.displayAvatar(getAvatarUrl(user), avatarView);
Msg.Type type = msg.getType();
if (type == Msg.Type.Text) {
contentView.setText(EmotionUtils.replace(ctx, msg.getContent()));
} else if (type == Msg.Type.Image) {
String localPath = PathUtils.getChatFileDir() + msg.getObjectId();
String url = msg.getContent();
displayImageByUri(imageView, localPath, url);
setImageOnClickListener(localPath, url, imageView);
} else if (type == Msg.Type.Audio) {
initPlayBtn(msg, playBtn);
} else if (type == Msg.Type.Location) {
setLocationView(msg, locationView);
}
if (isComMsg == false) {
hideStatusViews(statusSendStart, statusSendFailed, statusSendSucceed);
setSendFailedBtnListener(statusSendFailed, msg);
switch (msg.getStatus()) {
case SendFailed:
statusSendFailed.setVisibility(View.VISIBLE);
break;
case SendSucceed:
statusSendSucceed.setVisibility(View.VISIBLE);
break;
case SendStart:
statusSendStart.setVisibility(View.VISIBLE);
break;
}
}
return conView;
}
public String getAvatarUrl(AVUser user) {
AVFile avatar = user.getAVFile("avatar");
if (avatar != null) {
return avatar.getUrl();
} else {
return null;
}
}
private void setSendFailedBtnListener(View statusSendFailed, final Msg msg) {
statusSendFailed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chatActivity.resendMsg(msg);
}
});
}
private void hideStatusViews(View statusSendStart, View statusSendFailed, View statusSendSucceed) {
statusSendFailed.setVisibility(View.GONE);
statusSendStart.setVisibility(View.GONE);
statusSendSucceed.setVisibility(View.GONE);
}
public void setLocationView(Msg msg, TextView locationView) {
try {
String content = msg.getContent();
if (content != null && !content.equals("")) {
String[] parts = content.split("&");
String address = parts[0];
final String latitude = parts[1];
final String longtitude = parts[2];
locationView.setText(address);
locationView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Intent intent = new Intent(ctx, LocationActivity.class);
// intent.putExtra("type", "scan");
// intent.putExtra("latitude", Double.parseDouble(latitude));
// intent.putExtra("longtitude", Double.parseDouble(longtitude));
// ctx.startActivity(intent);
}
});
}
} catch (Exception e) {
}
}
private void initPlayBtn(Msg msg, PlayButton playBtn) {
playBtn.setPath(msg.getAudioPath());
}
private void setImageOnClickListener(final String path, final String url, ImageView imageView) {
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Intent intent = new Intent(ctx, ImageBrowerActivity.class);
// intent.putExtra("path", path);
// intent.putExtra("url", url);
// ctx.startActivity(intent);
}
});
}
public static void displayImageByUri(ImageView imageView,
String localPath, String url) {
File file = new File(localPath);
ImageLoader imageLoader = UserService.imageLoader;
if (file.exists()) {
imageLoader.displayImage("file://" + localPath, imageView, PhotoUtil.normalImageOptions);
} else {
imageLoader.displayImage(url, imageView, PhotoUtil.normalImageOptions);
}
}
public View createViewByType(int itemViewType) {
int[] types = new int[]{MsgViewType.COME_TEXT, MsgViewType.TO_TEXT,
MsgViewType.COME_IMAGE, MsgViewType.TO_IMAGE, MsgViewType.COME_AUDIO,
MsgViewType.TO_AUDIO, MsgViewType.COME_LOCATION, MsgViewType.TO_LOCATION};
int[] layoutIds = new int[]{
R.layout.chat_item_msg_text_left,
R.layout.chat_item_msg_text_right,
R.layout.chat_item_msg_image_left,
R.layout.chat_item_msg_image_right,
R.layout.chat_item_msg_audio_left,
R.layout.chat_item_msg_audio_right,
R.layout.chat_item_msg_location_left,
R.layout.chat_item_msg_location_right};
int i;
for (i = 0; i < types.length; i++) {
if (itemViewType == types[i]) {
break;
}
}
return inflater.inflate(layoutIds[i], null);
}
}
| |
/**
* The MIT License (MIT)
*
* Copyright (c) 2011-2016 Incapture Technologies LLC
*
* 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 rapture.kernel;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import rapture.common.CallingContext;
import rapture.common.LockHandle;
import rapture.common.RaptureApplicationDefinition;
import rapture.common.RaptureApplicationDefinitionStorage;
import rapture.common.RaptureApplicationInstance;
import rapture.common.RaptureApplicationInstancePathBuilder;
import rapture.common.RaptureApplicationInstanceStorage;
import rapture.common.RaptureInstanceCapabilities;
import rapture.common.RaptureInstanceCapabilitiesStorage;
import rapture.common.RaptureLibraryDefinition;
import rapture.common.RaptureLibraryDefinitionStorage;
import rapture.common.RapturePipelineTask;
import rapture.common.RaptureRunnerConfig;
import rapture.common.RaptureRunnerConfigStorage;
import rapture.common.RaptureRunnerInstanceStatus;
import rapture.common.RaptureRunnerStatus;
import rapture.common.RaptureRunnerStatusStorage;
import rapture.common.RaptureServerGroup;
import rapture.common.RaptureServerGroupStorage;
import rapture.common.RaptureURI;
import rapture.common.Scheme;
import rapture.common.api.RunnerApi;
import rapture.common.exception.RaptureExceptionFactory;
import rapture.common.impl.jackson.JacksonUtil;
import rapture.common.impl.jackson.JsonContent;
import rapture.common.mime.custom.MimeRunnerNotification;
import rapture.common.model.RaptureApplicationStatus;
import rapture.common.model.RaptureApplicationStatusStep;
import rapture.common.model.RaptureApplicationStatusStorage;
import rapture.common.pipeline.PipelineConstants;
import rapture.kernel.pipeline.TaskSubmitter;
import rapture.repo.RepoVisitor;
import rapture.util.IDGenerator;
/**
* Runner is all about RaptureRunner config
*
* @author amkimian
*/
public class RunnerApiImpl extends KernelBase implements RunnerApi {
public static final String RAPTUREAPPLICATIONSTATUS = "RaptureApplicationStatus";
private static final String RUNNER_STATUS_LOCK = "runnerStatus-%s";
private static Logger logger = Logger.getLogger(RunnerApiImpl.class);
public RunnerApiImpl(Kernel raptureKernel) {
super(raptureKernel);
}
@Override
public RaptureServerGroup createServerGroup(CallingContext context, String name, String description) {
RaptureServerGroup newGroup = new RaptureServerGroup();
newGroup.setLibraries(new HashSet<String>());
newGroup.setName(name);
newGroup.setDescription(description);
Set<String> inclusions = new HashSet<String>();
inclusions.add("*");
newGroup.setInclusions(inclusions);
newGroup.setExclusions(new HashSet<String>());
RaptureServerGroupStorage.add(newGroup, context.getUser(), "Create server group");
return newGroup;
}
@Override
public void deleteServerGroup(CallingContext context, String name) {
RaptureServerGroupStorage.deleteByFields(name, context.getUser(), "Remove server group");
}
@Override
public RaptureServerGroup addGroupInclusion(CallingContext context, String name, String inclusion) {
RaptureServerGroup group = getServerGroup(context, name);
if (group.getInclusions().contains("*")) {
group.getInclusions().remove("*");
}
group.getInclusions().add(inclusion);
RaptureServerGroupStorage.add(group, context.getUser(), "Add group inclusion");
return group;
}
@Override
public RaptureServerGroup removeGroupInclusion(CallingContext context, String name, String inclusion) {
RaptureServerGroup group = getServerGroup(context, name);
Set<String> inclusions = group.getInclusions();
inclusions.remove(inclusion);
if (inclusions.isEmpty()) {
inclusions.add("*");
}
RaptureServerGroupStorage.add(group, context.getUser(), "Remove group inclusion");
return group;
}
@Override
public RaptureServerGroup addGroupExclusion(CallingContext context, String name, String exclusion) {
RaptureServerGroup group = getServerGroup(context, name);
group.getExclusions().add(exclusion);
RaptureServerGroupStorage.add(group, context.getUser(), "Add group exclusion");
return group;
}
@Override
public RaptureServerGroup removeGroupExclusion(CallingContext context, String name, String exclusion) {
RaptureServerGroup group = getServerGroup(context, name);
group.getExclusions().remove(exclusion);
RaptureServerGroupStorage.add(group, context.getUser(), "Remove group exclusion");
return group;
}
@Override
public RaptureServerGroup addLibraryToGroup(CallingContext context, String serverGroup, String libraryName) {
RaptureServerGroup group = getServerGroup(context, serverGroup);
group.getLibraries().add(libraryName);
RaptureServerGroupStorage.add(group, context.getUser(), "Add library to group");
return group;
}
@Override
public RaptureServerGroup removeLibraryFromGroup(CallingContext context, String serverGroup, String libraryName) {
RaptureServerGroup group = getServerGroup(context, serverGroup);
if (group.getLibraries().contains(libraryName)) {
group.getLibraries().remove(libraryName);
RaptureServerGroupStorage.add(group, context.getUser(), "Remove library from group");
}
return group;
}
@Override
public RaptureServerGroup removeGroupEntry(CallingContext context, String name, String entry) {
RaptureServerGroup group = getServerGroup(context, name);
group.getInclusions().remove(entry);
group.getExclusions().remove(entry);
RaptureServerGroupStorage.add(group, context.getUser(), "Remove group entry");
return group;
}
@Override
public RaptureApplicationDefinition createApplicationDefinition(CallingContext context, String name, String ver, String description) {
RaptureApplicationDefinition rad = new RaptureApplicationDefinition();
rad.setName(name);
rad.setDescription(description);
rad.setVersion(ver);
RaptureApplicationDefinitionStorage.add(rad, context.getUser(), "Create app definition");
return rad;
}
@Override
public RaptureLibraryDefinition createLibraryDefinition(CallingContext context, String name, String ver, String description) {
RaptureLibraryDefinition rld = new RaptureLibraryDefinition();
rld.setName(name);
rld.setDescription(description);
rld.setVersion(ver);
RaptureLibraryDefinitionStorage.add(rld, context.getUser(), "Create library definition");
return rld;
}
@Override
public void deleteApplicationDefinition(CallingContext context, String name) {
RaptureApplicationDefinitionStorage.deleteByFields(name, context.getUser(), "Remove application definition");
}
@Override
public void deleteLibraryDefinition(CallingContext context, String name) {
RaptureLibraryDefinitionStorage.deleteByFields(name, context.getUser(), "Remove library definition");
}
@Override
public RaptureApplicationDefinition updateApplicationVersion(CallingContext context, String name, String ver) {
RaptureApplicationDefinition rad = retrieveApplicationDefinition(context, name);
rad.setVersion(ver);
RaptureApplicationDefinitionStorage.add(rad, context.getUser(), "Update application version");
return rad;
}
@Override
public RaptureLibraryDefinition updateLibraryVersion(CallingContext context, String name, String ver) {
RaptureLibraryDefinition rld = retrieveLibraryDefinition(context, name);
rld.setVersion(ver);
RaptureLibraryDefinitionStorage.add(rld, context.getUser(), "Update library version");
return rld;
}
@Override
public RaptureApplicationInstance createApplicationInstance(CallingContext context, String name, String description, String serverGroup, String appName,
String timeRange, int retryCount, String parameters, String apiUser) {
RaptureApplicationInstance rai = new RaptureApplicationInstance();
rai.setName(name);
rai.setDescription(description);
rai.setAppName(appName);
rai.setRetryCount(retryCount);
if (parameters.trim().isEmpty()) {
rai.setParameters("");
} else {
rai.setParameters(parameters);
}
rai.setTimeRangeSpecification(timeRange);
rai.setServerGroup(serverGroup);
if (apiUser.trim().isEmpty()) {
rai.setApiUser("");
} else {
rai.setApiUser(apiUser);
}
RaptureApplicationInstanceStorage.add(rai, context.getUser(), "Create app instance");
notifyRunner(context);
return rai;
}
@Override
public void deleteApplicationInstance(CallingContext context, String name, String serverGroup) {
RaptureApplicationInstanceStorage.deleteByFields(serverGroup, name, context.getUser(), "Remove application instance");
notifyRunner(context);
}
private List<RaptureServerGroup> getServerGroupInstances(CallingContext context) {
return RaptureServerGroupStorage.readAll();
}
private List<RaptureApplicationInstance> getApplicationInstancesForServerGroup(CallingContext context, String serverGroup) {
final List<RaptureApplicationInstance> ret = new ArrayList<RaptureApplicationInstance>();
String prefix = new RaptureApplicationInstancePathBuilder().serverGroup(serverGroup).buildStorageLocation().getDocPath() + "/";
getConfigRepo().visitAll(prefix, null, new RepoVisitor() {
@Override
public boolean visit(String name, JsonContent content, boolean isFolder) {
if (!isFolder) {
ret.add(JacksonUtil.objectFromJson(content.getContent(), RaptureApplicationInstance.class));
}
return true;
}
});
return ret;
}
@Override
public List<RaptureApplicationInstance> getApplicationsForServer(CallingContext context, String serverName) {
// Given a server, determine the groups it belongs to, and return the
// ApplicationInstances within
// those groups
List<RaptureServerGroup> serverGroups = getServerGroupInstances(context);
List<RaptureApplicationInstance> ret = new ArrayList<RaptureApplicationInstance>();
for (RaptureServerGroup serverGroup : serverGroups) {
boolean thisIncluded = false;
if (serverGroup.getInclusions().contains("*")) {
thisIncluded = true;
} else if (serverGroup.getInclusions().contains(serverName)) {
thisIncluded = true;
}
if (serverGroup.getExclusions().contains(serverName)) {
thisIncluded = false;
}
if (thisIncluded) {
ret.addAll(getApplicationInstancesForServerGroup(context, serverGroup.getName()));
}
}
return ret;
}
@Override
public RaptureApplicationDefinition getApplicationDefinition(CallingContext context, String name) {
return RaptureApplicationDefinitionStorage.readByFields(name);
}
private RaptureApplicationDefinition retrieveApplicationDefinition(CallingContext context, String name) {
return RaptureApplicationDefinitionStorage.readByFields(name);
}
@Override
public RaptureLibraryDefinition getLibraryDefinition(CallingContext context, String name) {
return RaptureLibraryDefinitionStorage.readByFields(name);
}
private RaptureLibraryDefinition retrieveLibraryDefinition(CallingContext context, String name) {
return RaptureLibraryDefinitionStorage.readByFields(name);
}
@Override
public void setRunnerConfig(CallingContext context, String name, String value) {
RaptureRunnerConfig config = getRunnerConfig(context);
if (config == null) {
config = new RaptureRunnerConfig();
config.setConfig(new HashMap<String, String>());
}
config.getConfig().put(name, value);
RaptureRunnerConfigStorage.add(config, context.getUser(), "Set runner config");
}
@Override
public void deleteRunnerConfig(CallingContext context, String name) {
RaptureRunnerConfig config = getRunnerConfig(context);
if (config != null) {
config.getConfig().remove(name);
RaptureRunnerConfigStorage.add(config, context.getUser(), "Remove runner config");
}
}
@Override
public RaptureRunnerConfig getRunnerConfig(CallingContext context) {
RaptureRunnerConfig config = RaptureRunnerConfigStorage.readByFields();
if (config == null) {
config = new RaptureRunnerConfig();
config.setConfig(new HashMap<String, String>());
}
return config;
}
@Override
public void recordRunnerStatus(CallingContext context, String serverName, String serverGroup, String instanceName, String appName, String status) {
String lockName = getRunnerStatusLockName(serverName);
logger.debug("Trying to acquire lock: Updating status for " + instanceName + " running on server " + serverName);
LockHandle lockHandle = acquireLock(context, lockName);
if (lockHandle != null) {
try {
logger.debug("Updating status for " + instanceName + " running on server " + serverName);
RaptureRunnerStatus runnerStatus = getRunnerStatus(context, serverName);
if (runnerStatus == null) {
logger.info("No status recorded, creating new");
runnerStatus = new RaptureRunnerStatus();
runnerStatus.setStatusByInstanceName(new HashMap<String, RaptureRunnerInstanceStatus>());
runnerStatus.setServerName(serverName);
}
RaptureRunnerInstanceStatus instanceStatus = new RaptureRunnerInstanceStatus();
if (runnerStatus.getStatusByInstanceName().containsKey(instanceName)) {
logger.debug("Information for this instance already existing");
instanceStatus = runnerStatus.getStatusByInstanceName().get(instanceName);
// If we are marking this as stopped, or failed, reset the
// needs
// restart flag
if (!status.equals("RUNNING")) {
instanceStatus.setNeedsRestart(false);
}
} else {
logger.debug("Newly seen application instance");
instanceStatus.setAppInstance(instanceName);
instanceStatus.setServerGroup(serverGroup);
instanceStatus.setAppName(appName);
}
instanceStatus.setStatus(status);
instanceStatus.setLastSeen(new Date());
logger.debug("Recording update to instance status, before " + runnerStatus.getStatusByInstanceName().keySet().size());
runnerStatus.getStatusByInstanceName().put(instanceName, instanceStatus);
logger.debug("Recording update to instance status, after " + runnerStatus.getStatusByInstanceName().keySet().size());
RaptureRunnerStatusStorage.add(runnerStatus, context.getUser(), "Record runner status");
} finally {
logger.debug("Done updating status for " + instanceName + " running on server " + serverName);
releaseLock(context, lockName, lockHandle);
}
} else {
logger.error(String.format("Unable to acquire lock %s, so unable to record runner status", lockName));
}
}
@Override
public void recordInstanceCapabilities(CallingContext context, String serverName, String instanceName, Map<String, Object> capabilities) {
RaptureInstanceCapabilities ric = new RaptureInstanceCapabilities();
ric.setInstanceName(instanceName);
ric.setServer(serverName);
ric.setCapabilities(capabilities);
RaptureInstanceCapabilitiesStorage.add(ric, context.getUser(), "Setting capabilities");
}
@Override
public Map<String, RaptureInstanceCapabilities> getCapabilities(CallingContext context, String serverName, List<String> instanceNames) {
Map<String, RaptureInstanceCapabilities> nameToRic = new HashMap<String, RaptureInstanceCapabilities>();
for (String name : instanceNames) {
RaptureInstanceCapabilities ric = RaptureInstanceCapabilitiesStorage.readByFields(serverName, name);
if (ric == null) {
ric = new RaptureInstanceCapabilities();
ric.setInstanceName(name);
}
nameToRic.put(name, ric);
}
return nameToRic;
}
private String getRunnerStatusLockName(String serverName) {
return String.format(RUNNER_STATUS_LOCK, serverName);
}
private LockHandle acquireLock(CallingContext context, String lockName) {
RaptureURI providerURI = Kernel.getLock().getTrusted().getKernelManagerUri();
return Kernel.getLock().acquireLock(context, providerURI.toString(), lockName, 30, 5);
}
private void releaseLock(CallingContext context, String lockName, LockHandle lockHandle) {
RaptureURI providerURI = Kernel.getLock().getTrusted().getKernelManagerUri();
Kernel.getLock().releaseLock(context, providerURI.toString(), lockName, lockHandle);
}
@Override
public List<String> getRunnerServers(CallingContext context) {
final List<String> ret = new ArrayList<String>();
List<RaptureRunnerStatus> statuses = RaptureRunnerStatusStorage.readAll();
for (RaptureRunnerStatus status : statuses) {
ret.add(status.getServerName());
}
return ret;
}
@Override
public RaptureRunnerStatus getRunnerStatus(CallingContext context, String serverName) {
RaptureRunnerStatus runnerStatus = RaptureRunnerStatusStorage.readByFields(serverName);
if (runnerStatus == null) {
logger.info("No status found, returning default");
runnerStatus = new RaptureRunnerStatus();
runnerStatus.setStatusByInstanceName(new HashMap<String, RaptureRunnerInstanceStatus>());
runnerStatus.setServerName(serverName);
}
return runnerStatus;
}
@Override
public RaptureServerGroup getServerGroup(CallingContext context, String name) {
return RaptureServerGroupStorage.readByFields(name);
}
@Override
public RaptureApplicationInstance getApplicationInstance(CallingContext context, String name, String serverGroup) {
return RaptureApplicationInstanceStorage.readByFields(serverGroup, name);
}
public RaptureApplicationInstance createOneShot(CallingContext context, String appName, String serverGroup, String parameters, String apiUser) {
logger.warn("RunnerApi.createOneShot is deprecated. Please change your code to use runApplication");
RaptureApplicationInstance rai = new RaptureApplicationInstance();
String instanceId = IDGenerator.getUUID(5);
rai.setName(appName + "-" + instanceId);
rai.setDescription("One shot for " + appName);
rai.setAppName(appName);
rai.setRetryCount(3);
rai.setLastStateChange(new Date());
if (parameters.trim().isEmpty()) {
rai.setParameters("");
} else {
rai.setParameters(parameters);
}
rai.setTimeRangeSpecification("* *");
rai.setServerGroup(serverGroup);
if (apiUser.trim().isEmpty()) {
rai.setApiUser("");
} else {
rai.setApiUser(apiUser);
}
rai.setOneShot(true);
RaptureApplicationInstanceStorage.add(rai, context.getUser(), "Create one shot");
notifyRunner(context);
return rai;
}
private void notifyRunner(CallingContext context) {
MimeRunnerNotification mime = new MimeRunnerNotification();
// notify all runners, since we may have multiple runners connected to
// same network
TaskSubmitter.submitBroadcastToCategory(context, mime, MimeRunnerNotification.getMimeType(), PipelineConstants.CATEGORY_RUNNER);
}
public RaptureApplicationInstance updateOneShot(CallingContext context, String appName, String serverGroup, String status, Boolean finished) {
logger.warn("RunnerApi.updateOneShot is deprecated. Please change your code to use runApplication");
RaptureApplicationInstance inst = getApplicationInstance(context, appName, serverGroup);
if (inst.getOneShot()) {
inst.setStatus(status);
inst.setFinished(finished);
inst.setLastStateChange(new Date());
RaptureApplicationInstanceStorage.add(inst, context.getUser(), "Update one shot");
notifyRunner(context);
} else {
throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Instance is not a one-shot instance");
}
return inst;
}
public Boolean lockOneShot(CallingContext context, String name, String serverGroup, String myServer) {
logger.warn("RunnerApi.lockOneShot is deprecated. Please change your code to use runApplication");
RaptureApplicationInstance instance = getApplicationInstance(context, name, serverGroup);
if (instance.getLockedBy() != null) {
if (instance.getLockedBy().equals(myServer)) {
return true;
} else {
return false;
}
}
instance.setLockedBy(myServer);
RaptureApplicationInstanceStorage.add(instance, context.getUser(), "Lock one shot");
notifyRunner(context);
instance = getApplicationInstance(context, name, serverGroup);
if (instance.getLockedBy().equals(myServer)) {
return true;
}
return false;
}
@Override
public List<String> getApplicationsForServerGroup(CallingContext context, String serverGroup) {
final List<String> ret = new ArrayList<String>();
final String prefix = new RaptureApplicationInstancePathBuilder().serverGroup(serverGroup).buildStorageLocation().getDocPath() + "/";
getConfigRepo().visitAll(prefix, null, new RepoVisitor() {
@Override
public boolean visit(String name, JsonContent content, boolean isFolder) {
if (!isFolder) {
ret.add(name.substring(prefix.length()));
}
return true;
}
});
return ret;
}
/**
* Remove old status records from this, then save if anything changed
*/
@Override
public void cleanRunnerStatus(CallingContext context, int ageInMinutes) {
List<String> runnerServers = getRunnerServers(context);
for (String serverName : runnerServers) {
String lockName = getRunnerStatusLockName(serverName);
LockHandle lockHandle = acquireLock(context, lockName);
if (lockHandle != null) {
try {
logger.debug("Cleaning data on server " + serverName);
RaptureRunnerStatus status = getRunnerStatus(context, serverName);
List<String> toRemove = new ArrayList<String>();
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, ageInMinutes * -1);
for (Map.Entry<String, RaptureRunnerInstanceStatus> entry : status.getStatusByInstanceName().entrySet()) {
Calendar entryDate = Calendar.getInstance();
entryDate.setTime(entry.getValue().getLastSeen());
if (entryDate.before(now)) {
toRemove.add(entry.getKey());
}
}
if (!toRemove.isEmpty()) {
for (String instance : toRemove) {
status.getStatusByInstanceName().remove(instance);
}
if (!status.getStatusByInstanceName().isEmpty()) {
RaptureRunnerStatusStorage.add(status, context.getUser(), "Clear runner status");
} else {
RaptureRunnerStatusStorage.deleteByFields(serverName, context.getUser(), "Clear runner status");
}
}
} finally {
logger.debug("Done cleaning data on server " + serverName);
releaseLock(context, lockName, lockHandle);
}
} else {
logger.info(String.format("Unable to acquire lock %s, so unable to clean runner status for server %s this time", lockName, serverName));
}
}
}
@Override
public void updateStatus(CallingContext context, String name, String serverGroup, String myServer, String status, Boolean finished) {
RaptureApplicationInstance instance = getApplicationInstance(context, name, serverGroup);
if (instance.getLockedBy() != null && instance.getLockedBy().equals(myServer)) {
instance.setStatus(status);
instance.setFinished(finished);
RaptureApplicationInstanceStorage.add(instance, context.getUser(), "Update status");
notifyRunner(context);
}
}
@Override
public void markForRestart(CallingContext context, String serverName, String name) {
String lockName = getRunnerStatusLockName(serverName);
LockHandle lockHandle = acquireLock(context, lockName);
if (lockHandle != null) {
try {
logger.debug("Setting restart request for " + name + " running on server " + serverName);
RaptureRunnerStatus runnerStatus = getRunnerStatus(context, serverName);
if (runnerStatus == null) {
logger.debug("No status recorded, nothing to do");
return;
}
if (runnerStatus.getStatusByInstanceName().containsKey(name)) {
logger.info("Setting restart flag");
runnerStatus.getStatusByInstanceName().get(name).setNeedsRestart(true);
RaptureRunnerStatusStorage.add(runnerStatus, context.getUser(), "Mark for restart");
}
} finally {
logger.debug("Done setting restart request for " + name + " running on server " + serverName);
releaseLock(context, lockName, lockHandle);
}
} else {
logger.info(String.format("Unable to acquire lock %s, so unable to mark %s on server %s for restart this time", lockName, name, serverName));
}
}
@Override
public RaptureApplicationStatus runCustomApplication(CallingContext context, String appName, String queueName, Map<String, String> parameterInput,
Map<String, String> parameterOutput, String customApplicationPath) {
RaptureApplicationStatus status = new RaptureApplicationStatus();
status.setAppName(appName);
status.setInstanceId(IDGenerator.getUUID());
status.setInputConfig(parameterInput);
status.setOutputConfig(parameterOutput);
status.setStatus(RaptureApplicationStatusStep.INITIATED);
status.setOverrideApplicationPath(customApplicationPath);
return lowerInitiateApp(context, status);
}
@Override
public RaptureApplicationStatus runApplication(CallingContext context, String appName, String queueName, Map<String, String> parameterInput,
Map<String, String> parameterOutput) {
RaptureApplicationStatus status = new RaptureApplicationStatus();
status.setAppName(appName);
status.setInstanceId(IDGenerator.getUUID());
status.setInputConfig(parameterInput);
status.setOutputConfig(parameterOutput);
status.setStatus(RaptureApplicationStatusStep.INITIATED);
return lowerInitiateApp(context, status);
}
private RaptureApplicationStatus lowerInitiateApp(CallingContext context, RaptureApplicationStatus status) {
Date now = new Date();
String yyyymmdd = new SimpleDateFormat("yyyyMMdd").format(now);
status.setTheDate(yyyymmdd);
RaptureApplicationStatusStorage.add(status, context.getUser(), "New application creation");
RapturePipelineTask pTask = new RapturePipelineTask();
pTask.setPriority(1);
List<String> categoryList = new LinkedList<String>();
categoryList.add(PipelineConstants.CATEGORY_APPMANAGER);
pTask.setCategoryList(categoryList);
pTask.initTask();
pTask.addMimeObject(status);
pTask.setContentType(RAPTUREAPPLICATIONSTATUS);
// Check that queue is valid?
Kernel.getPipeline().publishMessageToCategory(context, pTask);
return status;
}
@Override
public RaptureApplicationStatus getApplicationStatus(CallingContext context, String applicationStatusURI) {
RaptureURI parsedURI = new RaptureURI(applicationStatusURI, Scheme.APPSTATUS);
return RaptureApplicationStatusStorage.readByAddress(parsedURI);
}
@Override
public List<String> getApplicationStatusDates(CallingContext context) {
final Set<String> dates = new HashSet<String>();
RaptureApplicationStatusStorage.visitAll(new RepoVisitor() {
@Override
public boolean visit(String name, JsonContent content, boolean isFolder) {
RaptureApplicationStatus status = RaptureApplicationStatusStorage.readFromJson(content);
dates.add(status.getTheDate());
return true;
}
});
return new ArrayList<String>(dates);
}
@Override
public List<RaptureApplicationStatus> getApplicationStatuses(CallingContext context, String date) {
return RaptureApplicationStatusStorage.readAll(date);
}
@Override
public RaptureApplicationStatus changeApplicationStatus(CallingContext context, String applicationStatusURI, RaptureApplicationStatusStep statusCode,
String message) {
RaptureApplicationStatus status = getApplicationStatus(context, applicationStatusURI);
if (status != null) {
status.setStatus(statusCode);
status.setLastMessage(message);
if (status.getMessages() == null) {
status.setMessages(new ArrayList<String>());
}
status.getMessages().add(message);
RaptureApplicationStatusStorage.add(status, context.getUser(), "Updated status");
}
return null;
}
@Override
public void recordStatusMessages(CallingContext context, String applicationStatusURI, List<String> messages) {
RaptureApplicationStatus status = getApplicationStatus(context, applicationStatusURI);
if (status != null) {
if (status.getMessages() == null) {
status.setMessages(new ArrayList<String>());
}
status.getMessages().addAll(messages);
RaptureApplicationStatusStorage.add(status, context.getUser(), "Updated from std out");
}
}
@Override
public RaptureApplicationStatus terminateApplication(CallingContext context, String applicationStatusURI, String reasonMessage) {
// Put such a message on the general "broadcast" queue to all interested
// parties, who would potentially reach back to update the status
// Depending on the state...
logger.info("terminateApplication not implemented");
return null;
}
@Override
public void archiveApplicationStatuses(CallingContext context) {
// Remove old and boring app statuses.
logger.info("archiveApplicationStatuses not implemented");
}
@Override
public List<RaptureServerGroup> getAllServerGroups(CallingContext context) {
return RaptureServerGroupStorage.readAll();
}
@Override
public List<RaptureApplicationDefinition> getAllApplicationDefinitions(CallingContext context) {
return RaptureApplicationDefinitionStorage.readAll();
}
@Override
public List<RaptureLibraryDefinition> getAllLibraryDefinitions(CallingContext context) {
return RaptureLibraryDefinitionStorage.readAll();
}
@Override
public List<RaptureApplicationInstance> getAllApplicationInstances(CallingContext context) {
return RaptureApplicationInstanceStorage.readAll();
}
}
| |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.features.v2015_12_01.implementation;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.POST;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in Features.
*/
public class FeaturesInner {
/** The Retrofit service to perform REST calls. */
private FeaturesService service;
/** The service client containing this operation class. */
private FeatureClientImpl client;
/**
* Initializes an instance of FeaturesInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public FeaturesInner(Retrofit retrofit, FeatureClientImpl client) {
this.service = retrofit.create(FeaturesService.class);
this.client = client;
}
/**
* The interface defining all the services for Features to be
* used by Retrofit to perform actually REST calls.
*/
interface FeaturesService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.features.v2015_12_01.Features list" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.Features/features")
Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.features.v2015_12_01.Features list1" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features")
Observable<Response<ResponseBody>> list1(@Path("resourceProviderNamespace") String resourceProviderNamespace, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.features.v2015_12_01.Features get" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}")
Observable<Response<ResponseBody>> get(@Path("resourceProviderNamespace") String resourceProviderNamespace, @Path("featureName") String featureName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.features.v2015_12_01.Features register" })
@POST("subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/register")
Observable<Response<ResponseBody>> register(@Path("resourceProviderNamespace") String resourceProviderNamespace, @Path("featureName") String featureName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.features.v2015_12_01.Features unregister" })
@POST("subscriptions/{subscriptionId}/providers/Microsoft.Features/providers/{resourceProviderNamespace}/features/{featureName}/unregister")
Observable<Response<ResponseBody>> unregister(@Path("resourceProviderNamespace") String resourceProviderNamespace, @Path("featureName") String featureName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.features.v2015_12_01.Features listNext" })
@GET
Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.features.v2015_12_01.Features list1Next" })
@GET
Observable<Response<ResponseBody>> list1Next(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<FeatureResultInner> object if successful.
*/
public PagedList<FeatureResultInner> list() {
ServiceResponse<Page<FeatureResultInner>> response = listSinglePageAsync().toBlocking().single();
return new PagedList<FeatureResultInner>(response.body()) {
@Override
public Page<FeatureResultInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<FeatureResultInner>> listAsync(final ListOperationCallback<FeatureResultInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listSinglePageAsync(),
new Func1<String, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<FeatureResultInner> object
*/
public Observable<Page<FeatureResultInner>> listAsync() {
return listWithServiceResponseAsync()
.map(new Func1<ServiceResponse<Page<FeatureResultInner>>, Page<FeatureResultInner>>() {
@Override
public Page<FeatureResultInner> call(ServiceResponse<Page<FeatureResultInner>> response) {
return response.body();
}
});
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<FeatureResultInner> object
*/
public Observable<ServiceResponse<Page<FeatureResultInner>>> listWithServiceResponseAsync() {
return listSinglePageAsync()
.concatMap(new Func1<ServiceResponse<Page<FeatureResultInner>>, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(ServiceResponse<Page<FeatureResultInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<FeatureResultInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<FeatureResultInner>>> listSinglePageAsync() {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.list(this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<FeatureResultInner>> result = listDelegate(response);
return Observable.just(new ServiceResponse<Page<FeatureResultInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<FeatureResultInner>> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<FeatureResultInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<FeatureResultInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<FeatureResultInner> object if successful.
*/
public PagedList<FeatureResultInner> list1(final String resourceProviderNamespace) {
ServiceResponse<Page<FeatureResultInner>> response = list1SinglePageAsync(resourceProviderNamespace).toBlocking().single();
return new PagedList<FeatureResultInner>(response.body()) {
@Override
public Page<FeatureResultInner> nextPage(String nextPageLink) {
return list1NextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<FeatureResultInner>> list1Async(final String resourceProviderNamespace, final ListOperationCallback<FeatureResultInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
list1SinglePageAsync(resourceProviderNamespace),
new Func1<String, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(String nextPageLink) {
return list1NextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<FeatureResultInner> object
*/
public Observable<Page<FeatureResultInner>> list1Async(final String resourceProviderNamespace) {
return list1WithServiceResponseAsync(resourceProviderNamespace)
.map(new Func1<ServiceResponse<Page<FeatureResultInner>>, Page<FeatureResultInner>>() {
@Override
public Page<FeatureResultInner> call(ServiceResponse<Page<FeatureResultInner>> response) {
return response.body();
}
});
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<FeatureResultInner> object
*/
public Observable<ServiceResponse<Page<FeatureResultInner>>> list1WithServiceResponseAsync(final String resourceProviderNamespace) {
return list1SinglePageAsync(resourceProviderNamespace)
.concatMap(new Func1<ServiceResponse<Page<FeatureResultInner>>, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(ServiceResponse<Page<FeatureResultInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(list1NextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
ServiceResponse<PageImpl<FeatureResultInner>> * @param resourceProviderNamespace The namespace of the resource provider for getting features.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<FeatureResultInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<FeatureResultInner>>> list1SinglePageAsync(final String resourceProviderNamespace) {
if (resourceProviderNamespace == null) {
throw new IllegalArgumentException("Parameter resourceProviderNamespace is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.list1(resourceProviderNamespace, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<FeatureResultInner>> result = list1Delegate(response);
return Observable.just(new ServiceResponse<Page<FeatureResultInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<FeatureResultInner>> list1Delegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<FeatureResultInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<FeatureResultInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets the preview feature with the specified name.
*
* @param resourceProviderNamespace The resource provider namespace for the feature.
* @param featureName The name of the feature to get.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the FeatureResultInner object if successful.
*/
public FeatureResultInner get(String resourceProviderNamespace, String featureName) {
return getWithServiceResponseAsync(resourceProviderNamespace, featureName).toBlocking().single().body();
}
/**
* Gets the preview feature with the specified name.
*
* @param resourceProviderNamespace The resource provider namespace for the feature.
* @param featureName The name of the feature to get.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<FeatureResultInner> getAsync(String resourceProviderNamespace, String featureName, final ServiceCallback<FeatureResultInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceProviderNamespace, featureName), serviceCallback);
}
/**
* Gets the preview feature with the specified name.
*
* @param resourceProviderNamespace The resource provider namespace for the feature.
* @param featureName The name of the feature to get.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the FeatureResultInner object
*/
public Observable<FeatureResultInner> getAsync(String resourceProviderNamespace, String featureName) {
return getWithServiceResponseAsync(resourceProviderNamespace, featureName).map(new Func1<ServiceResponse<FeatureResultInner>, FeatureResultInner>() {
@Override
public FeatureResultInner call(ServiceResponse<FeatureResultInner> response) {
return response.body();
}
});
}
/**
* Gets the preview feature with the specified name.
*
* @param resourceProviderNamespace The resource provider namespace for the feature.
* @param featureName The name of the feature to get.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the FeatureResultInner object
*/
public Observable<ServiceResponse<FeatureResultInner>> getWithServiceResponseAsync(String resourceProviderNamespace, String featureName) {
if (resourceProviderNamespace == null) {
throw new IllegalArgumentException("Parameter resourceProviderNamespace is required and cannot be null.");
}
if (featureName == null) {
throw new IllegalArgumentException("Parameter featureName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.get(resourceProviderNamespace, featureName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<FeatureResultInner>>>() {
@Override
public Observable<ServiceResponse<FeatureResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<FeatureResultInner> clientResponse = getDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<FeatureResultInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<FeatureResultInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<FeatureResultInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Registers the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to register.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the FeatureResultInner object if successful.
*/
public FeatureResultInner register(String resourceProviderNamespace, String featureName) {
return registerWithServiceResponseAsync(resourceProviderNamespace, featureName).toBlocking().single().body();
}
/**
* Registers the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to register.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<FeatureResultInner> registerAsync(String resourceProviderNamespace, String featureName, final ServiceCallback<FeatureResultInner> serviceCallback) {
return ServiceFuture.fromResponse(registerWithServiceResponseAsync(resourceProviderNamespace, featureName), serviceCallback);
}
/**
* Registers the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to register.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the FeatureResultInner object
*/
public Observable<FeatureResultInner> registerAsync(String resourceProviderNamespace, String featureName) {
return registerWithServiceResponseAsync(resourceProviderNamespace, featureName).map(new Func1<ServiceResponse<FeatureResultInner>, FeatureResultInner>() {
@Override
public FeatureResultInner call(ServiceResponse<FeatureResultInner> response) {
return response.body();
}
});
}
/**
* Registers the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to register.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the FeatureResultInner object
*/
public Observable<ServiceResponse<FeatureResultInner>> registerWithServiceResponseAsync(String resourceProviderNamespace, String featureName) {
if (resourceProviderNamespace == null) {
throw new IllegalArgumentException("Parameter resourceProviderNamespace is required and cannot be null.");
}
if (featureName == null) {
throw new IllegalArgumentException("Parameter featureName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.register(resourceProviderNamespace, featureName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<FeatureResultInner>>>() {
@Override
public Observable<ServiceResponse<FeatureResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<FeatureResultInner> clientResponse = registerDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<FeatureResultInner> registerDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<FeatureResultInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<FeatureResultInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Unregisters the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to unregister.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the FeatureResultInner object if successful.
*/
public FeatureResultInner unregister(String resourceProviderNamespace, String featureName) {
return unregisterWithServiceResponseAsync(resourceProviderNamespace, featureName).toBlocking().single().body();
}
/**
* Unregisters the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to unregister.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<FeatureResultInner> unregisterAsync(String resourceProviderNamespace, String featureName, final ServiceCallback<FeatureResultInner> serviceCallback) {
return ServiceFuture.fromResponse(unregisterWithServiceResponseAsync(resourceProviderNamespace, featureName), serviceCallback);
}
/**
* Unregisters the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to unregister.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the FeatureResultInner object
*/
public Observable<FeatureResultInner> unregisterAsync(String resourceProviderNamespace, String featureName) {
return unregisterWithServiceResponseAsync(resourceProviderNamespace, featureName).map(new Func1<ServiceResponse<FeatureResultInner>, FeatureResultInner>() {
@Override
public FeatureResultInner call(ServiceResponse<FeatureResultInner> response) {
return response.body();
}
});
}
/**
* Unregisters the preview feature for the subscription.
*
* @param resourceProviderNamespace The namespace of the resource provider.
* @param featureName The name of the feature to unregister.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the FeatureResultInner object
*/
public Observable<ServiceResponse<FeatureResultInner>> unregisterWithServiceResponseAsync(String resourceProviderNamespace, String featureName) {
if (resourceProviderNamespace == null) {
throw new IllegalArgumentException("Parameter resourceProviderNamespace is required and cannot be null.");
}
if (featureName == null) {
throw new IllegalArgumentException("Parameter featureName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.unregister(resourceProviderNamespace, featureName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<FeatureResultInner>>>() {
@Override
public Observable<ServiceResponse<FeatureResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<FeatureResultInner> clientResponse = unregisterDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<FeatureResultInner> unregisterDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<FeatureResultInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<FeatureResultInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<FeatureResultInner> object if successful.
*/
public PagedList<FeatureResultInner> listNext(final String nextPageLink) {
ServiceResponse<Page<FeatureResultInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<FeatureResultInner>(response.body()) {
@Override
public Page<FeatureResultInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<FeatureResultInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<FeatureResultInner>> serviceFuture, final ListOperationCallback<FeatureResultInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<FeatureResultInner> object
*/
public Observable<Page<FeatureResultInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<FeatureResultInner>>, Page<FeatureResultInner>>() {
@Override
public Page<FeatureResultInner> call(ServiceResponse<Page<FeatureResultInner>> response) {
return response.body();
}
});
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<FeatureResultInner> object
*/
public Observable<ServiceResponse<Page<FeatureResultInner>>> listNextWithServiceResponseAsync(final String nextPageLink) {
return listNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<FeatureResultInner>>, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(ServiceResponse<Page<FeatureResultInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all the preview features that are available through AFEC for the subscription.
*
ServiceResponse<PageImpl<FeatureResultInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<FeatureResultInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<FeatureResultInner>>> listNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<FeatureResultInner>> result = listNextDelegate(response);
return Observable.just(new ServiceResponse<Page<FeatureResultInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<FeatureResultInner>> listNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<FeatureResultInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<FeatureResultInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<FeatureResultInner> object if successful.
*/
public PagedList<FeatureResultInner> list1Next(final String nextPageLink) {
ServiceResponse<Page<FeatureResultInner>> response = list1NextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<FeatureResultInner>(response.body()) {
@Override
public Page<FeatureResultInner> nextPage(String nextPageLink) {
return list1NextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<FeatureResultInner>> list1NextAsync(final String nextPageLink, final ServiceFuture<List<FeatureResultInner>> serviceFuture, final ListOperationCallback<FeatureResultInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
list1NextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(String nextPageLink) {
return list1NextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<FeatureResultInner> object
*/
public Observable<Page<FeatureResultInner>> list1NextAsync(final String nextPageLink) {
return list1NextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<FeatureResultInner>>, Page<FeatureResultInner>>() {
@Override
public Page<FeatureResultInner> call(ServiceResponse<Page<FeatureResultInner>> response) {
return response.body();
}
});
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<FeatureResultInner> object
*/
public Observable<ServiceResponse<Page<FeatureResultInner>>> list1NextWithServiceResponseAsync(final String nextPageLink) {
return list1NextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<FeatureResultInner>>, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(ServiceResponse<Page<FeatureResultInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(list1NextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all the preview features in a provider namespace that are available through AFEC for the subscription.
*
ServiceResponse<PageImpl<FeatureResultInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<FeatureResultInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<FeatureResultInner>>> list1NextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.list1Next(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<FeatureResultInner>>>>() {
@Override
public Observable<ServiceResponse<Page<FeatureResultInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<FeatureResultInner>> result = list1NextDelegate(response);
return Observable.just(new ServiceResponse<Page<FeatureResultInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<FeatureResultInner>> list1NextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<FeatureResultInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<FeatureResultInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.data.input.orc;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.druid.data.input.InputRow;
import io.druid.data.input.MapBasedInputRow;
import io.druid.data.input.impl.InputRowParser;
import io.druid.data.input.impl.ParseSpec;
import io.druid.data.input.impl.TimestampSpec;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.ql.io.orc.OrcSerde;
import org.apache.hadoop.hive.ql.io.orc.OrcStruct;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.joda.time.DateTime;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class OrcHadoopInputRowParser implements InputRowParser<OrcStruct>
{
private final ParseSpec parseSpec;
private String typeString;
private final List<String> dimensions;
private StructObjectInspector oip;
private final OrcSerde serde;
@JsonCreator
public OrcHadoopInputRowParser(
@JsonProperty("parseSpec") ParseSpec parseSpec,
@JsonProperty("typeString") String typeString
)
{
this.parseSpec = parseSpec;
this.typeString = typeString;
this.dimensions = parseSpec.getDimensionsSpec().getDimensionNames();
this.serde = new OrcSerde();
initialize();
}
@SuppressWarnings("ArgumentParameterSwap")
@Override
public InputRow parse(OrcStruct input)
{
Map<String, Object> map = Maps.newHashMap();
List<? extends StructField> fields = oip.getAllStructFieldRefs();
for (StructField field: fields) {
ObjectInspector objectInspector = field.getFieldObjectInspector();
switch(objectInspector.getCategory()) {
case PRIMITIVE:
PrimitiveObjectInspector primitiveObjectInspector = (PrimitiveObjectInspector)objectInspector;
map.put(field.getFieldName(),
primitiveObjectInspector.getPrimitiveJavaObject(oip.getStructFieldData(input, field)));
break;
case LIST: // array case - only 1-depth array supported yet
ListObjectInspector listObjectInspector = (ListObjectInspector)objectInspector;
map.put(field.getFieldName(),
getListObject(listObjectInspector, oip.getStructFieldData(input, field)));
break;
default:
break;
}
}
TimestampSpec timestampSpec = parseSpec.getTimestampSpec();
DateTime dateTime = timestampSpec.extractTimestamp(map);
return new MapBasedInputRow(dateTime, dimensions, map);
}
private void initialize()
{
if (typeString == null) {
typeString = typeStringFromParseSpec(parseSpec);
}
TypeInfo typeInfo = TypeInfoUtils.getTypeInfoFromTypeString(typeString);
Preconditions.checkArgument(typeInfo instanceof StructTypeInfo,
String.format("typeString should be struct type but not [%s]", typeString));
Properties table = getTablePropertiesFromStructTypeInfo((StructTypeInfo)typeInfo);
serde.initialize(new Configuration(), table);
try {
oip = (StructObjectInspector) serde.getObjectInspector();
} catch (SerDeException e) {
e.printStackTrace();
}
}
private List getListObject(ListObjectInspector listObjectInspector, Object listObject)
{
List objectList = listObjectInspector.getList(listObject);
List list = null;
ObjectInspector child = listObjectInspector.getListElementObjectInspector();
switch(child.getCategory()) {
case PRIMITIVE:
final PrimitiveObjectInspector primitiveObjectInspector = (PrimitiveObjectInspector)child;
list = Lists.transform(objectList, new Function() {
@Nullable
@Override
public Object apply(@Nullable Object input) {
return primitiveObjectInspector.getPrimitiveJavaObject(input);
}
});
break;
default:
break;
}
return list;
}
@Override
@JsonProperty
public ParseSpec getParseSpec()
{
return parseSpec;
}
@JsonProperty
public String getTypeString()
{
return typeString;
}
@Override
public InputRowParser withParseSpec(ParseSpec parseSpec)
{
return new OrcHadoopInputRowParser(parseSpec, typeString);
}
public InputRowParser withTypeString(String typeString)
{
return new OrcHadoopInputRowParser(parseSpec, typeString);
}
public static String typeStringFromParseSpec(ParseSpec parseSpec)
{
StringBuilder builder = new StringBuilder("struct<");
builder.append(parseSpec.getTimestampSpec().getTimestampColumn()).append(":string");
if (parseSpec.getDimensionsSpec().getDimensionNames().size() > 0) {
builder.append(",");
builder.append(StringUtils.join(parseSpec.getDimensionsSpec().getDimensionNames(), ":string,")).append(":string");
}
builder.append(">");
return builder.toString();
}
public static Properties getTablePropertiesFromStructTypeInfo(StructTypeInfo structTypeInfo)
{
Properties table = new Properties();
table.setProperty("columns", StringUtils.join(structTypeInfo.getAllStructFieldNames(), ","));
table.setProperty("columns.types", StringUtils.join(
Lists.transform(structTypeInfo.getAllStructFieldTypeInfos(),
new Function<TypeInfo, String>() {
@Nullable
@Override
public String apply(@Nullable TypeInfo typeInfo) {
return typeInfo.getTypeName();
}
}),
","
));
return table;
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof OrcHadoopInputRowParser)) {
return false;
}
OrcHadoopInputRowParser other = (OrcHadoopInputRowParser)o;
if (!parseSpec.equals(other.parseSpec)) {
return false;
}
if (!typeString.equals(other.typeString)) {
return false;
}
return true;
}
}
| |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide;
import com.intellij.ide.plugins.DynamicPluginListener;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.presentation.Presentation;
import com.intellij.ide.presentation.PresentationProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.util.ClassExtension;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.NullableLazyValue;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ConcurrentFactoryMap;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
public final class TypePresentationServiceImpl extends TypePresentationService {
private static final ExtensionPointName<TypeIconEP> TYPE_ICON_EP_NAME = new ExtensionPointName<>("com.intellij.typeIcon");
private static final ExtensionPointName<PresentationProvider<?>> PROVIDER_EP = new ExtensionPointName<>("com.intellij.presentationProvider");
private static final ClassExtension<PresentationProvider<?>> PROVIDERS = new ClassExtension<>(PROVIDER_EP.getName());
@Nullable
@Override
public Icon getIcon(@NotNull Object o) {
return getIcon(o.getClass(), o);
}
@Nullable
@Override
public Icon getTypeIcon(Class type) {
return getIcon(type, null);
}
private @Nullable Icon getIcon(Class<?> type, Object o) {
return findFirst(type, template -> template.getIcon(o, 0));
}
@Override
public @NotNull String getTypePresentableName(Class type) {
String typeName = findFirst(type, template -> template.getTypeName());
return typeName != null ? typeName : getDefaultTypeName(type);
}
@Nullable
@Override
public String getTypeName(@NotNull Object o) {
return findFirst(o.getClass(), template -> template.getTypeName(o));
}
@Nullable
@Override
public String getObjectName(@NotNull Object o) {
return findFirst(o.getClass(), template -> template.getName(o));
}
@Nullable
private <T> T findFirst(Class<?> clazz, @NotNull Function<? super PresentationTemplate, ? extends T> f) {
Set<PresentationTemplate> templates = mySuperClasses.get(clazz);
for (PresentationTemplate template : templates) {
T result = f.apply(template);
if (result != null) {
return result;
}
}
return null;
}
public TypePresentationServiceImpl() {
for (TypeIconEP ep : TYPE_ICON_EP_NAME.getExtensionList()) {
myIcons.put(ep.className, ep.lazyIcon);
}
TYPE_ICON_EP_NAME.addExtensionPointListener(new ExtensionPointListener<>() {
@Override
public void extensionAdded(@NotNull TypeIconEP extension, @NotNull PluginDescriptor pluginDescriptor) {
myIcons.put(extension.className, extension.lazyIcon);
}
@Override
public void extensionRemoved(@NotNull TypeIconEP extension, @NotNull PluginDescriptor pluginDescriptor) {
myIcons.remove(extension.className);
}
}, null);
for (TypeNameEP ep : TypeNameEP.EP_NAME.getExtensionList()) {
myNames.put(ep.className, ep.getTypeName());
}
TypeNameEP.EP_NAME.addExtensionPointListener(new ExtensionPointListener<>() {
@Override
public void extensionAdded(@NotNull TypeNameEP extension, @NotNull PluginDescriptor pluginDescriptor) {
myNames.put(extension.className, extension.getTypeName());
}
@Override
public void extensionRemoved(@NotNull TypeNameEP extension, @NotNull PluginDescriptor pluginDescriptor) {
myNames.remove(extension.className);
}
}, null);
ApplicationManager.getApplication().getMessageBus().connect().subscribe(DynamicPluginListener.TOPIC, new DynamicPluginListener() {
@Override
public void beforePluginUnload(@NotNull IdeaPluginDescriptor pluginDescriptor, boolean isUpdate) {
mySuperClasses.clear();
}
});
}
private @Nullable PresentationTemplate createPresentationTemplate(Class<?> type) {
Presentation presentation = type.getAnnotation(Presentation.class);
if (presentation != null) {
return new AnnotationBasedTemplate(presentation, type);
}
PresentationProvider<?> provider = PROVIDERS.forClass(type);
if (provider != null) {
return new ProviderBasedTemplate(provider);
}
NullableLazyValue<Icon> icon = myIcons.get(type.getName());
NullableLazyValue<String> typeName = myNames.get(type.getName());
if (icon == null && typeName == null) {
return null;
}
return new PresentationTemplate() {
@Nullable
@Override
public Icon getIcon(Object o, int flags) {
return icon == null ? null : icon.getValue();
}
@Nullable
@Override
public String getName(Object o) {
return null;
}
@Nullable
@Override
public String getTypeName() {
return typeName == null ? null : typeName.getValue();
}
@Nullable
@Override
public String getTypeName(Object o) {
return getTypeName();
}
};
}
private final Map<String, NullableLazyValue<Icon>> myIcons = new HashMap<>();
private final Map<String, NullableLazyValue<String>> myNames = new HashMap<>();
private final Map<Class<?>, Set<PresentationTemplate>> mySuperClasses = ConcurrentFactoryMap.createMap(key -> {
Set<PresentationTemplate> templates = new LinkedHashSet<>();
walkSupers(key, new LinkedHashSet<>(), templates);
return templates;
});
private void walkSupers(Class<?> aClass, Set<? super Class<?>> classes, Set<? super PresentationTemplate> templates) {
if (!classes.add(aClass)) {
return;
}
ContainerUtil.addIfNotNull(templates, createPresentationTemplate(aClass));
Class<?> superClass = aClass.getSuperclass();
if (superClass != null) {
walkSupers(superClass, classes, templates);
}
for (Class<?> intf : aClass.getInterfaces()) {
walkSupers(intf, classes, templates);
}
}
public static class ProviderBasedTemplate implements PresentationTemplate {
private final PresentationProvider myProvider;
public ProviderBasedTemplate(PresentationProvider<?> provider) {
myProvider = provider;
}
@Nullable
@Override
public Icon getIcon(Object o, int flags) {
//noinspection unchecked
return myProvider instanceof PresentationTemplate ? ((PresentationTemplate)myProvider).getIcon(o, flags) : myProvider.getIcon(o);
}
@Nullable
@Override
public String getName(Object o) {
//noinspection unchecked
return myProvider.getName(o);
}
@Nullable
@Override
public String getTypeName() {
return myProvider instanceof PresentationTemplate ? ((PresentationTemplate)myProvider).getTypeName() : null;
}
@Nullable
@Override
public String getTypeName(Object o) {
//noinspection unchecked
return myProvider.getTypeName(o);
}
}
public static class PresentationTemplateImpl extends ProviderBasedTemplate {
public PresentationTemplateImpl(Presentation presentation, Class<?> aClass) {
super(new AnnotationBasedTemplate(presentation, aClass));
}
}
@SuppressWarnings("unchecked")
private static final class AnnotationBasedTemplate extends PresentationProvider<Object> implements PresentationTemplate {
private final Presentation myPresentation;
private final Class<?> myClass;
AnnotationBasedTemplate(Presentation presentation, Class<?> aClass) {
myPresentation = presentation;
myClass = aClass;
}
@Nullable
@Override
public Icon getIcon(Object o) {
return getIcon(o, 0);
}
@Nullable
@Override
public Icon getIcon(Object o, int flags) {
if (o == null) {
return myIcon.getValue();
}
PresentationProvider provider = myPresentationProvider.getValue();
if (provider == null) {
return myIcon.getValue();
}
else {
Icon icon = provider.getIcon(o);
return icon == null ? myIcon.getValue() : icon;
}
}
@Nullable
@Override
public String getTypeName() {
return StringUtil.isEmpty(myPresentation.typeName()) ? null : myPresentation.typeName();
}
@Nullable
@Override
public String getTypeName(Object o) {
PresentationProvider provider = myPresentationProvider.getValue();
if (provider != null) {
String typeName = provider.getTypeName(o);
if (typeName != null) return typeName;
}
//noinspection HardCodedStringLiteral
return getTypeName();
}
@Nullable
@Override
public String getName(Object o) {
PresentationProvider namer = myPresentationProvider.getValue();
return namer == null ? null : namer.getName(o);
}
private final NullableLazyValue<Icon> myIcon = new NullableLazyValue<>() {
@Override
protected Icon compute() {
if (myPresentation.icon().isEmpty()) {
return null;
}
return IconLoader.getIcon(myPresentation.icon(), myClass);
}
};
private final NullableLazyValue<PresentationProvider<?>> myPresentationProvider = new NullableLazyValue<>() {
@Override
protected PresentationProvider<?> compute() {
Class<? extends PresentationProvider> aClass = myPresentation.provider();
try {
return aClass == PresentationProvider.class ? null : aClass.getDeclaredConstructor().newInstance();
}
catch (Exception e) {
return null;
}
}
};
}
interface PresentationTemplate {
@Nullable
Icon getIcon(Object o, int flags);
@Nullable
String getName(Object o);
@Nullable
String getTypeName();
@Nullable
String getTypeName(Object o);
}
}
| |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.autofill_assistant.user_data;
import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import org.chromium.chrome.autofill_assistant.R;
import org.chromium.chrome.browser.autofill.PersonalDataManager;
import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile;
import org.chromium.chrome.browser.autofill.PersonalDataManager.CreditCard;
import org.chromium.chrome.browser.autofill.settings.CardEditor;
import org.chromium.chrome.browser.autofill_assistant.user_data.AssistantCollectUserDataModel.PaymentInstrumentModel;
import org.chromium.chrome.browser.payments.AutofillAddress;
import org.chromium.chrome.browser.payments.AutofillPaymentInstrument;
import java.util.List;
/**
* The payment method section of the Autofill Assistant payment request.
*/
public class AssistantPaymentMethodSection
extends AssistantCollectUserDataSection<PaymentInstrumentModel> {
private CardEditor mEditor;
private boolean mIgnorePaymentMethodsChangeNotifications;
AssistantPaymentMethodSection(Context context, ViewGroup parent) {
super(context, parent, R.layout.autofill_assistant_payment_method_summary,
R.layout.autofill_assistant_payment_method_full,
context.getResources().getDimensionPixelSize(
R.dimen.autofill_assistant_payment_request_payment_method_title_padding),
context.getString(R.string.payments_add_card),
context.getString(R.string.payments_add_card));
setTitle(context.getString(R.string.payments_method_of_payment_label));
}
public void setEditor(CardEditor editor) {
mEditor = editor;
if (mEditor == null) {
return;
}
for (PaymentInstrumentModel item : getItems()) {
AutofillProfile profile = item.mOption.getBillingProfile();
if (profile != null) {
addAutocompleteInformationToEditor(new AutofillAddress(mContext, profile));
}
}
}
@Override
protected void createOrEditItem(@Nullable PaymentInstrumentModel oldItem) {
if (mEditor == null) {
return;
}
mEditor.edit(oldItem == null ? null : oldItem.mOption, paymentInstrument -> {
assert (paymentInstrument != null && paymentInstrument.isComplete());
mIgnorePaymentMethodsChangeNotifications = true;
addOrUpdateItem(new PaymentInstrumentModel(paymentInstrument), /* select= */ true,
/* notify= */ true);
mIgnorePaymentMethodsChangeNotifications = false;
}, cancel -> {});
}
@Override
protected void updateFullView(View fullView, PaymentInstrumentModel model) {
if (model == null) {
return;
}
updateView(fullView, model);
TextView cardNameView = fullView.findViewById(R.id.credit_card_name);
cardNameView.setText(model.mOption.getCard().getName());
hideIfEmpty(cardNameView);
TextView errorView = fullView.findViewById(R.id.incomplete_error);
if (model.mErrors.isEmpty()) {
errorView.setText("");
errorView.setVisibility(View.GONE);
} else {
errorView.setText(TextUtils.join("\n", model.mErrors));
errorView.setVisibility(View.VISIBLE);
}
}
@Override
protected void updateSummaryView(View summaryView, PaymentInstrumentModel model) {
if (model == null) {
return;
}
updateView(summaryView, model);
TextView errorView = summaryView.findViewById(R.id.incomplete_error);
errorView.setVisibility(model.mErrors.isEmpty() ? View.GONE : View.VISIBLE);
}
private void updateView(View view, PaymentInstrumentModel model) {
AutofillPaymentInstrument method = model.mOption;
ImageView cardIssuerImageView = view.findViewById(R.id.credit_card_issuer_icon);
try {
cardIssuerImageView.setImageDrawable(
view.getContext().getDrawable(method.getCard().getIssuerIconDrawableId()));
} catch (Resources.NotFoundException e) {
cardIssuerImageView.setImageDrawable(null);
}
// By default, the obfuscated number contains the issuer (e.g., 'Visa'). This is needlessly
// verbose, so we strip it away. See |PersonalDataManagerTest::testAddAndEditCreditCards|
// for explanation of "\u0020...\u2060".
String obfuscatedNumber = method.getCard().getObfuscatedNumber();
int beginningOfObfuscatedNumber =
Math.max(obfuscatedNumber.indexOf("\u0020\u202A\u2022\u2060"), 0);
obfuscatedNumber = obfuscatedNumber.substring(beginningOfObfuscatedNumber);
TextView cardNumberView = view.findViewById(R.id.credit_card_number);
cardNumberView.setText(obfuscatedNumber);
hideIfEmpty(cardNumberView);
TextView cardExpirationView = view.findViewById(R.id.credit_card_expiration);
cardExpirationView.setText(method.getCard().getFormattedExpirationDate(view.getContext()));
hideIfEmpty(cardExpirationView);
}
@Override
protected boolean canEditOption(PaymentInstrumentModel model) {
return true;
}
@Override
protected @DrawableRes int getEditButtonDrawable(PaymentInstrumentModel model) {
return R.drawable.ic_edit_24dp;
}
@Override
protected String getEditButtonContentDescription(PaymentInstrumentModel model) {
return mContext.getString(R.string.autofill_edit_credit_card);
}
@Override
protected boolean areEqual(
@Nullable PaymentInstrumentModel modelA, @Nullable PaymentInstrumentModel modelB) {
if (modelA == null || modelB == null) {
return modelA == modelB;
}
AutofillPaymentInstrument optionA = modelA.mOption;
AutofillPaymentInstrument optionB = modelB.mOption;
if (TextUtils.equals(optionA.getIdentifier(), optionB.getIdentifier())) {
return true;
}
return areEqualCards(optionA.getCard(), optionB.getCard())
&& areEqualBillingProfiles(
optionA.getBillingProfile(), optionB.getBillingProfile());
}
private boolean areEqualCards(CreditCard cardA, CreditCard cardB) {
// TODO(crbug.com/806868): Implement better check for the case where PDM is disabled, we
// won't have IDs.
return TextUtils.equals(cardA.getGUID(), cardB.getGUID());
}
private boolean areEqualBillingProfiles(
@Nullable AutofillProfile profileA, @Nullable AutofillProfile profileB) {
if (profileA == null || profileB == null) {
return profileA == profileB;
}
// TODO(crbug.com/806868): Implement better check for the case where PDM is disabled, we
// won't have IDs.
return TextUtils.equals(profileA.getGUID(), profileB.getGUID());
}
void onAddressesChanged(List<AutofillAddress> addresses) {
// TODO(crbug.com/806868): replace suggested billing addresses (remove if necessary).
for (AutofillAddress address : addresses) {
addAutocompleteInformationToEditor(address);
}
}
/**
* The set of available payment methods has changed externally. This will rebuild the UI with
* the new/changed set of payment methods, while keeping the selected item if possible.
*/
void onAvailablePaymentMethodsChanged(List<PaymentInstrumentModel> paymentMethods) {
if (mIgnorePaymentMethodsChangeNotifications) {
return;
}
int selectedMethodIndex = -1;
if (mSelectedOption != null) {
for (int i = 0; i < paymentMethods.size(); ++i) {
if (areEqual(paymentMethods.get(i), mSelectedOption)) {
selectedMethodIndex = i;
break;
}
}
}
// Replace current set of items, keep selection if possible.
setItems(paymentMethods, selectedMethodIndex);
}
private void addAutocompleteInformationToEditor(AutofillAddress address) {
if (mEditor == null) {
return;
}
if (address.getProfile().getLabel() == null) {
address.getProfile().setLabel(
PersonalDataManager.getInstance().getBillingAddressLabelForPaymentRequest(
address.getProfile()));
}
mEditor.updateBillingAddressIfComplete(address);
}
}
| |
/*
* Copyright (C) 2014 The Android Open Source Project
* Copyright (C) 2017 Vyacheslav Shmakin
*
* 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 ru.shmakinv.android.widget.customizableactionbardrawertoggle;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.StringRes;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
/**
* This class provides a handy way to tie together the functionality of
* {@link android.support.v4.widget.DrawerLayout} and the framework <code>ActionBar</code> to
* implement the recommended design for navigation drawers.
* <p>
* <p>To use <code>ActionBarDrawerToggle</code>, create one in your Activity and call through
* to the following methods corresponding to your Activity callbacks:</p>
* <p>
* <ul>
* <li>{@link android.app.Activity#onConfigurationChanged(android.content.res.Configuration)
* onConfigurationChanged}
* <li>{@link android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
* onOptionsItemSelected}</li>
* </ul>
* <p>
* <p>Call {@link #syncState(Bundle savedInstanceState)} from your <code>Activity</code>'s
* {@link android.app.Activity#onPostCreate(android.os.Bundle) onPostCreate} to synchronize the
* indicator with the state of the linked DrawerLayout after <code>onRestoreInstanceState</code>
* has occurred.</p>
* <p>
* <p><code>ActionBarDrawerToggle</code> can be used directly as a
* {@link android.support.v4.widget.DrawerLayout.DrawerListener}, or if you are already providing
* your own listener, call through to each of the listener methods from your own.</p>
* <p>
* <p>
* You can customize the the animated toggle by defining the
* {android.support.v7.appcompat.R.styleable#DrawerArrowToggle drawerArrowStyle} in your
* ActionBar theme.
*/
public class ActionBarDrawerToggle implements DrawerLayout.DrawerListener {
/**
* Allows an implementing Activity to return an {@link ActionBarDrawerToggle.Delegate} to use
* with ActionBarDrawerToggle.
*/
public interface DelegateProvider {
/**
* @return Delegate to use for ActionBarDrawableToggles, or null if the Activity
* does not wish to override the default behavior.
*/
@Nullable
Delegate getDrawerToggleDelegate();
}
public interface Delegate {
/**
* Set the Action Bar's up indicator drawable and content description.
*
* @param upDrawable - Drawable to set as up indicator
* @param contentDescRes - Content description to set
*/
void setActionBarUpIndicator(Drawable upDrawable, @StringRes int contentDescRes);
/**
* Set the Action Bar's up indicator content description.
*
* @param contentDescRes - Content description to set
*/
void setActionBarDescription(@StringRes int contentDescRes);
/**
* Returns the drawable to be set as up button when DrawerToggle is disabled
*/
Drawable getThemeUpIndicator();
/**
* Returns the context of ActionBar
*/
Context getActionBarThemedContext();
/**
* Returns whether navigation icon is visible or not.
* Used to print warning messages in case developer forgets to set displayHomeAsUp to true
*/
boolean isNavigationVisible();
}
private static final String KEY_DRAWER_POSITION = "LastDrawerPositionInstance";
private static final String KEY_INTERPOLATOR_DURATION = "InterpolatorDurationInstance";
private static final String KEY_ROTATE_DIRECTION = "RotateDirectionBackInstance";
private static final String KEY_AUTO_RESET_ROTATE_DIRECTION = "AutoResetRotateDirectionInstance";
private static final String TAG = "ActionBarDrawerToggle";
private static final String MESSAGE_NAV_ICON_NOT_VISIBLE = "DrawerToggle may not show up " +
"because NavigationIcon is not visible. You may need to call actionbar.setDisplayHomeAsUpEnabled(true);";
private static final float SLIDER_START_POSITION = 0.0F;
private static final float SLIDER_END_POSITION = 1.0F;
private final Delegate mActivityImpl;
private final DrawerLayout mDrawerLayout;
private DrawerArrowDrawableCompat mSlider;
private Drawable mHomeAsUpIndicator;
private boolean mDrawerIndicatorEnabled = true;
private boolean mDrawerSlideAnimationEnabled = true;
private boolean mHasCustomUpIndicator;
@StringRes
private final int mOpenDrawerContentDescRes;
@StringRes
private final int mCloseDrawerContentDescRes;
// used in toolbar mode when DrawerToggle is disabled
private ToolbarNavigationClickListener mToolbarNavigationClickListener;
// If developer does not set displayHomeAsUp, DrawerToggle won't show up.
// DrawerToggle logs a warning if this case is detected
private boolean mWarnedForDisplayHomeAsUp = false;
private TimeInterpolator mInterpolator = new MaterialInterpolator();
private int mInterpolatorDuration = 400;
private boolean mRotateDirectionBack = false;
private boolean mAutoResetRotateDirection = true;
/**
* Construct a new ActionBarDrawerToggle.
* <p>
* <p>The given {@link Activity} will be linked to the specified {@link DrawerLayout} and
* its Actionbar's Up button will be set to a custom drawable.
* <p>This drawable shows a Hamburger icon when drawer is closed and an arrow when drawer
* is open. It animates between these two states as the drawer opens.</p>
* <p>
* <p>String resources must be provided to describe the open/close drawer actions for
* accessibility services.</p>
*
* @param activity The Activity hosting the drawer. Should have an ActionBar.
* @param drawerLayout The DrawerLayout to link to the given Activity's ActionBar
* @param openDrawerContentDescRes A String resource to describe the "open drawer" action
* for accessibility
* @param closeDrawerContentDescRes A String resource to describe the "close drawer" action
* for accessibility
*/
public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout,
@StringRes int openDrawerContentDescRes,
@StringRes int closeDrawerContentDescRes) {
this(activity, null, drawerLayout, null, openDrawerContentDescRes,
closeDrawerContentDescRes);
}
/**
* Construct a new ActionBarDrawerToggle with a Toolbar.
* <p>
* The given {@link Activity} will be linked to the specified {@link DrawerLayout} and
* the Toolbar's navigation icon will be set to a custom drawable. Using this constructor
* will set Toolbar's navigation click listener to toggle the drawer when it is clicked.
* <p>
* This drawable shows a Hamburger icon when drawer is closed and an arrow when drawer
* is open. It animates between these two states as the drawer opens.
* <p>
* String resources must be provided to describe the open/close drawer actions for
* accessibility services.
* <p>
* Please use {@link #ActionBarDrawerToggle(Activity, DrawerLayout, int, int)} if you are
* setting the Toolbar as the ActionBar of your activity.
*
* @param activity The Activity hosting the drawer.
* @param toolbar The toolbar to use if you have an independent Toolbar.
* @param drawerLayout The DrawerLayout to link to the given Activity's ActionBar
* @param openDrawerContentDescRes A String resource to describe the "open drawer" action
* for accessibility
* @param closeDrawerContentDescRes A String resource to describe the "close drawer" action
* for accessibility
*/
public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout,
Toolbar toolbar, @StringRes int openDrawerContentDescRes,
@StringRes int closeDrawerContentDescRes) {
this(activity, toolbar, drawerLayout, null, openDrawerContentDescRes,
closeDrawerContentDescRes);
}
/**
* In the future, we can make this constructor public if we want to let developers customize
* the
* animation.
*/
public ActionBarDrawerToggle(Activity activity, Toolbar toolbar, DrawerLayout drawerLayout,
DrawerArrowDrawableCompat slider, @StringRes int openDrawerContentDescRes,
@StringRes int closeDrawerContentDescRes) {
if (toolbar != null) {
mActivityImpl = new ToolbarCompatDelegate(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDrawerIndicatorEnabled) {
toggle();
} else if (mToolbarNavigationClickListener != null) {
mToolbarNavigationClickListener.onClick(v);
}
}
});
} else if (activity instanceof DelegateProvider) { // Allow the Activity to provide an impl
mActivityImpl = ((DelegateProvider) activity).getDrawerToggleDelegate();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mActivityImpl = new JellybeanMr2Delegate(activity);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
mActivityImpl = new IcsDelegate(activity);
} else {
mActivityImpl = new DummyDelegate(activity);
}
mDrawerLayout = drawerLayout;
mOpenDrawerContentDescRes = openDrawerContentDescRes;
mCloseDrawerContentDescRes = closeDrawerContentDescRes;
if (slider == null && mActivityImpl != null) {
mSlider = new DrawerArrowDrawableCompat(mActivityImpl.getActionBarThemedContext());
} else {
mSlider = slider;
}
mHomeAsUpIndicator = getThemeUpIndicator();
}
/**
* Synchronize the state of the drawer indicator/affordance with the linked DrawerLayout.
* <p>
* <p>This should be called from your <code>Activity</code>'s
* {@link Activity#onPostCreate(android.os.Bundle) onPostCreate} method to synchronize after
* the DrawerLayout's instance state has been restored, and any other time when the state
* may have diverged in such a way that the ActionBarDrawerToggle was not notified.
* (For example, if you stop forwarding appropriate drawer events for a period of time.)</p>
*/
public void syncState(@Nullable Bundle savedInstanceState) {
float position = SLIDER_START_POSITION;
if (savedInstanceState != null) {
position = (float) savedInstanceState.getInt(KEY_DRAWER_POSITION);
mInterpolatorDuration = savedInstanceState.getInt(KEY_INTERPOLATOR_DURATION);
mRotateDirectionBack = savedInstanceState.getBoolean(KEY_ROTATE_DIRECTION);
mAutoResetRotateDirection = savedInstanceState.getBoolean(KEY_AUTO_RESET_ROTATE_DIRECTION);
}
this.mSlider.setPosition(position, DrawerImageState.TOGGLE_DRAWER_DEFAULT);
if (this.mDrawerIndicatorEnabled) {
this.setActionBarUpIndicator(mSlider,
mDrawerLayout.isDrawerOpen(GravityCompat.START) ?
mCloseDrawerContentDescRes : mOpenDrawerContentDescRes);
}
}
public void onSavedInstanceState(Bundle bundle) {
bundle.putInt(KEY_DRAWER_POSITION, Math.round(mSlider.getPosition()));
bundle.putInt(KEY_INTERPOLATOR_DURATION, mInterpolatorDuration);
bundle.putBoolean(KEY_ROTATE_DIRECTION, mRotateDirectionBack);
bundle.putBoolean(KEY_AUTO_RESET_ROTATE_DIRECTION, mAutoResetRotateDirection);
}
/**
* This method should always be called by your <code>Activity</code>'s
* {@link Activity#onConfigurationChanged(android.content.res.Configuration)
* onConfigurationChanged}
* method.
*
* @param newConfig The new configuration
*/
public void onConfigurationChanged(Configuration newConfig) {
// Reload drawables that can change with configuration
if (!mHasCustomUpIndicator) {
mHomeAsUpIndicator = getThemeUpIndicator();
}
syncState(null);
}
/**
* This method should be called by your <code>Activity</code>'s
* {@link Activity#onOptionsItemSelected(android.view.MenuItem) onOptionsItemSelected} method.
* If it returns true, your <code>onOptionsItemSelected</code> method should return true and
* skip further processing.
*
* @param item the MenuItem instance representing the selected menu item
* @return true if the event was handled and further processing should not occur
*/
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home && mDrawerIndicatorEnabled) {
toggle();
return true;
}
return false;
}
private void toggle() {
int drawerLockMode = mDrawerLayout.getDrawerLockMode(GravityCompat.START);
if (mDrawerLayout.isDrawerVisible(GravityCompat.START)
&& (drawerLockMode != DrawerLayout.LOCK_MODE_LOCKED_OPEN)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else if (drawerLockMode != DrawerLayout.LOCK_MODE_LOCKED_CLOSED) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
}
public boolean isRotateDirectionBack() {
return mRotateDirectionBack;
}
public void setRotateDirectionBack(boolean rotateDirectionBack) {
this.mRotateDirectionBack = rotateDirectionBack;
}
public boolean isAutoResetRotateDirection() {
return mAutoResetRotateDirection;
}
public void setAutoResetRotateDirection(boolean autoResetRotateDirection) {
this.mAutoResetRotateDirection = autoResetRotateDirection;
}
public TimeInterpolator getInterpolator() {
return this.mInterpolator;
}
public void setInterpolator(TimeInterpolator interpolator) {
this.mInterpolator = interpolator;
}
public int getInterpolatorDuration() {
return mInterpolatorDuration;
}
public void setInterpolatorDuration(int interpolatorDuration) {
this.mInterpolatorDuration = interpolatorDuration;
}
/**
* Set the up indicator to display when the drawer indicator is not
* enabled.
* <p>
* If you pass <code>null</code> to this method, the default drawable from
* the theme will be used.
*
* @param indicator A drawable to use for the up indicator, or null to use
* the theme's default
* @see #setDrawerIndicatorEnabled(boolean)
*/
public void setHomeAsUpIndicator(Drawable indicator) {
if (indicator == null) {
mHomeAsUpIndicator = getThemeUpIndicator();
mHasCustomUpIndicator = false;
} else {
mHomeAsUpIndicator = indicator;
mHasCustomUpIndicator = true;
}
if (!mDrawerIndicatorEnabled) {
setActionBarUpIndicator(mHomeAsUpIndicator, 0);
}
}
/**
* Set the up indicator to display when the drawer indicator is not
* enabled.
* <p>
* If you pass 0 to this method, the default drawable from the theme will
* be used.
*
* @param resId Resource ID of a drawable to use for the up indicator, or 0
* to use the theme's default
* @see #setDrawerIndicatorEnabled(boolean)
*/
public void setHomeAsUpIndicator(int resId) {
Drawable indicator = null;
if (resId != 0) {
indicator = mDrawerLayout.getResources().getDrawable(resId);
}
setHomeAsUpIndicator(indicator);
}
/**
* @return true if the enhanced drawer indicator is enabled, false otherwise
* @see #setDrawerIndicatorEnabled(boolean)
*/
public boolean isDrawerIndicatorEnabled() {
return mDrawerIndicatorEnabled;
}
/**
* Enable or disable the drawer indicator. The indicator defaults to enabled.
* <p>
* <p>When the indicator is disabled, the <code>ActionBar</code> will revert to displaying
* the home-as-up indicator provided by the <code>Activity</code>'s theme in the
* <code>android.R.attr.homeAsUpIndicator</code> attribute instead of the animated
* drawer glyph.</p>
*
* @param enable true to enable, false to disable
*/
public void setDrawerIndicatorEnabled(boolean enable) {
if (enable != mDrawerIndicatorEnabled) {
if (enable) {
setActionBarUpIndicator(
mSlider,
mDrawerLayout.isDrawerOpen(GravityCompat.START)
? mCloseDrawerContentDescRes
: mOpenDrawerContentDescRes);
} else {
setActionBarUpIndicator(mHomeAsUpIndicator, 0);
}
mDrawerIndicatorEnabled = enable;
}
}
/**
* @return DrawerArrowDrawable that is currently shown by the ActionBarDrawerToggle.
*/
@NonNull
public DrawerArrowDrawableCompat getDrawerArrowDrawable() {
return mSlider;
}
/**
* Sets the DrawerArrowDrawableCompat that should be shown by this ActionBarDrawerToggle.
*
* @param drawable DrawerArrowDrawableCompat that should be shown by this ActionBarDrawerToggle
*/
public void setDrawerArrowDrawable(@NonNull DrawerArrowDrawableCompat drawable) {
mSlider = drawable;
syncState(null);
}
public void toggleIndicator(final boolean backDirection) {
this.mRotateDirectionBack = backDirection;
this.mAutoResetRotateDirection = true;
float position = Math.round(this.mSlider.getPosition());
float start, end;
if (position == SLIDER_START_POSITION) {
start = SLIDER_START_POSITION;
end = SLIDER_END_POSITION;
} else {
start = SLIDER_END_POSITION;
end = SLIDER_START_POSITION;
}
animateDrawer(start, end);
}
public void animateDrawer(final float start, final float end) {
final ValueAnimator anim = ValueAnimator.ofFloat(start, end);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float slideOffset = (Float) valueAnimator.getAnimatedValue();
setPosition(slideOffset);
if (slideOffset == end) {
anim.removeAllListeners();
}
}
});
anim.setInterpolator(mInterpolator);
// You can change this duration to more closely match that of the default animation.
anim.setDuration(mInterpolatorDuration);
anim.start();
}
/**
* Specifies whether the drawer arrow should animate when the drawer position changes.
*
* @param enabled if this is {@code true} then the animation will run, else it will be skipped
*/
public void setDrawerSlideAnimationEnabled(boolean enabled) {
mDrawerSlideAnimationEnabled = enabled;
if (!enabled) {
setPosition(SLIDER_START_POSITION);
}
}
/**
* @return whether the drawer slide animation is enabled
*/
public boolean isDrawerSlideAnimationEnabled() {
return mDrawerSlideAnimationEnabled;
}
/**
* {@link DrawerLayout.DrawerListener} callback method. If you do not use your
* ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call
* through to this method from your own listener object.
*
* @param drawerView The child view that was moved
* @param slideOffset The new offset of this drawer within its range, from 0-1
*/
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
setPosition(mDrawerSlideAnimationEnabled ? slideOffset : SLIDER_START_POSITION);
}
/**
* SLIDER_END_POSITION, DrawerImageState.TOGGLE_DRAWER_DEFAULT
* {@link DrawerLayout.DrawerListener} callback method. If you do not use your
* ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call
* through to this method from your own listener object.
*
* @param drawerView Drawer view that is now open
*/
@Override
public void onDrawerOpened(View drawerView) {
setPosition(SLIDER_END_POSITION);
if (mDrawerIndicatorEnabled) {
setActionBarDescription(mCloseDrawerContentDescRes);
}
}
/**
* {@link DrawerLayout.DrawerListener} callback method. If you do not use your
* ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call
* through to this method from your own listener object.
*
* @param drawerView Drawer view that is now closed
*/
@Override
public void onDrawerClosed(View drawerView) {
setPosition(SLIDER_START_POSITION);
if (mDrawerIndicatorEnabled) {
setActionBarDescription(mOpenDrawerContentDescRes);
}
}
/**
* {@link DrawerLayout.DrawerListener} callback method. If you do not use your
* ActionBarDrawerToggle instance directly as your DrawerLayout's listener, you should call
* through to this method from your own listener object.
*
* @param newState The new drawer motion state
*/
@Override
public void onDrawerStateChanged(int newState) {
}
/**
* Returns the fallback listener for Navigation icon click events.
*
* @return The click listener which receives Navigation click events from Toolbar when
* drawer indicator is disabled.
* @see #setToolbarNavigationClickListener(ToolbarNavigationClickListener)
* @see #setDrawerIndicatorEnabled(boolean)
* @see #isDrawerIndicatorEnabled()
*/
public ToolbarNavigationClickListener getToolbarNavigationClickListener() {
return mToolbarNavigationClickListener;
}
/**
* When DrawerToggle is constructed with a Toolbar, it sets the click listener on
* the Navigation icon. If you want to listen for clicks on the Navigation icon when
* DrawerToggle is disabled ({@link #setDrawerIndicatorEnabled(boolean)}, you should call this
* method with your listener and DrawerToggle will forward click events to that listener
* when drawer indicator is disabled.
*
* @see #setDrawerIndicatorEnabled(boolean)
*/
public void setToolbarNavigationClickListener(ToolbarNavigationClickListener onClickListener) {
mToolbarNavigationClickListener = onClickListener;
}
void setActionBarUpIndicator(Drawable upDrawable, int contentDescRes) {
if (!mWarnedForDisplayHomeAsUp && !mActivityImpl.isNavigationVisible()) {
Log.w(TAG, MESSAGE_NAV_ICON_NOT_VISIBLE);
mWarnedForDisplayHomeAsUp = true;
}
mActivityImpl.setActionBarUpIndicator(upDrawable, contentDescRes);
}
void setActionBarDescription(int contentDescRes) {
mActivityImpl.setActionBarDescription(contentDescRes);
}
Drawable getThemeUpIndicator() {
return mActivityImpl.getThemeUpIndicator();
}
private void setPosition(float slideOffset) {
float position = Math.min(SLIDER_END_POSITION, Math.max(SLIDER_START_POSITION, slideOffset));
int mirrored = DrawerImageState.TOGGLE_DRAWER_DEFAULT;
if (mRotateDirectionBack) {
mirrored = DrawerImageState.TOGGLE_DRAWER_MIRRORED;
} else {
if (position == SLIDER_START_POSITION) {
mirrored = DrawerImageState.TOGGLE_DRAWER_NORMAL;
} else if (position == SLIDER_END_POSITION) {
mirrored = DrawerImageState.TOGGLE_DRAWER_MIRRORED;
}
}
this.mSlider.setPosition(position, mirrored);
if (mAutoResetRotateDirection && mRotateDirectionBack && position == SLIDER_END_POSITION) {
mRotateDirectionBack = !mRotateDirectionBack;
}
}
/**
* Delegate if SDK version is between ICS and JBMR2
*/
@RequiresApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private static class IcsDelegate implements Delegate {
final Activity mActivity;
ActionBarDrawerToggleHoneycomb.SetIndicatorInfo mSetIndicatorInfo;
IcsDelegate(Activity activity) {
mActivity = activity;
}
@Override
public Drawable getThemeUpIndicator() {
return ActionBarDrawerToggleHoneycomb.getThemeUpIndicator(mActivity);
}
@Override
public Context getActionBarThemedContext() {
final ActionBar actionBar = mActivity.getActionBar();
final Context context;
if (actionBar != null) {
context = actionBar.getThemedContext();
} else {
context = mActivity;
}
return context;
}
@Override
public boolean isNavigationVisible() {
final ActionBar actionBar = mActivity.getActionBar();
return actionBar != null
&& (actionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0;
}
@Override
public void setActionBarUpIndicator(Drawable themeImage, int contentDescRes) {
final ActionBar actionBar = mActivity.getActionBar();
if (actionBar != null) {
actionBar.setDisplayShowHomeEnabled(true);
mSetIndicatorInfo = ActionBarDrawerToggleHoneycomb.setActionBarUpIndicator(
mSetIndicatorInfo,
mActivity,
themeImage,
contentDescRes);
actionBar.setDisplayShowHomeEnabled(false);
}
}
@Override
public void setActionBarDescription(int contentDescRes) {
mSetIndicatorInfo = ActionBarDrawerToggleHoneycomb.setActionBarDescription(
mSetIndicatorInfo, mActivity, contentDescRes);
}
}
/**
* Delegate if SDK version is JB MR2 or newer
*/
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static class JellybeanMr2Delegate implements Delegate {
final Activity mActivity;
JellybeanMr2Delegate(Activity activity) {
mActivity = activity;
}
@Override
public Drawable getThemeUpIndicator() {
final TypedArray a = getActionBarThemedContext().obtainStyledAttributes(null,
new int[]{android.R.attr.homeAsUpIndicator}, android.R.attr.actionBarStyle, 0);
final Drawable result = a.getDrawable(0);
a.recycle();
return result;
}
@Override
public Context getActionBarThemedContext() {
final ActionBar actionBar = mActivity.getActionBar();
final Context context;
if (actionBar != null) {
context = actionBar.getThemedContext();
} else {
context = mActivity;
}
return context;
}
@Override
public boolean isNavigationVisible() {
final ActionBar actionBar = mActivity.getActionBar();
return actionBar != null &&
(actionBar.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0;
}
@Override
public void setActionBarUpIndicator(Drawable drawable, int contentDescRes) {
final ActionBar actionBar = mActivity.getActionBar();
if (actionBar != null) {
actionBar.setHomeAsUpIndicator(drawable);
actionBar.setHomeActionContentDescription(contentDescRes);
}
}
@Override
public void setActionBarDescription(int contentDescRes) {
final ActionBar actionBar = mActivity.getActionBar();
if (actionBar != null) {
actionBar.setHomeActionContentDescription(contentDescRes);
}
}
}
/**
* Used when DrawerToggle is initialized with a Toolbar
*/
static class ToolbarCompatDelegate implements Delegate {
final Toolbar mToolbar;
final Drawable mDefaultUpIndicator;
final CharSequence mDefaultContentDescription;
ToolbarCompatDelegate(Toolbar toolbar) {
mToolbar = toolbar;
mDefaultUpIndicator = toolbar.getNavigationIcon();
mDefaultContentDescription = toolbar.getNavigationContentDescription();
}
@Override
public void setActionBarUpIndicator(Drawable upDrawable, @StringRes int contentDescRes) {
mToolbar.setNavigationIcon(upDrawable);
setActionBarDescription(contentDescRes);
}
@Override
public void setActionBarDescription(@StringRes int contentDescRes) {
if (contentDescRes == 0) {
mToolbar.setNavigationContentDescription(mDefaultContentDescription);
} else {
mToolbar.setNavigationContentDescription(contentDescRes);
}
}
@Override
public Drawable getThemeUpIndicator() {
return mDefaultUpIndicator;
}
@Override
public Context getActionBarThemedContext() {
return mToolbar.getContext();
}
@Override
public boolean isNavigationVisible() {
return true;
}
}
/**
* Fallback delegate
*/
static class DummyDelegate implements Delegate {
final Activity mActivity;
DummyDelegate(Activity activity) {
mActivity = activity;
}
@Override
public void setActionBarUpIndicator(Drawable upDrawable, @StringRes int contentDescRes) {
}
@Override
public void setActionBarDescription(@StringRes int contentDescRes) {
}
@Override
public Drawable getThemeUpIndicator() {
return null;
}
@Override
public Context getActionBarThemedContext() {
return mActivity;
}
@Override
public boolean isNavigationVisible() {
return true;
}
}
}
| |
package jops;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class Gui implements Listener {
private static final String FA_LOAD = "\uf15b";
private static final String FA_EJECT = "\uf052";
private static final String FA_STOP = "\uf04d";
private static final String FA_PLAY = "\uf04b";
private Model model;
private JLabel state = new JLabel("EJECTED");
private JLabel name = new JLabel("<No connection>");
private JLabel duration = new JLabel("--");
private JLabel position = new JLabel("--");
private JFrame frame;
private JSlider seeker = new JSlider();
private JLabel songAlbum = new JLabel("--");
private JLabel songArtist = new JLabel("--");
private JLabel songTitle = new JLabel("--");
private JButton playButton = new JButton("Play");
private JButton stopButton = new JButton("Stop");
private JButton ejctButton = new JButton("Eject");
private JButton loadButton = new JButton("Load");
private Font fontAwesome = null;
public Gui(Model inModel) {
this.model = inModel;
this.model.registerListener(this);
}
public void start() {
System.out.println("Showing GUI");
javax.swing.SwingUtilities.invokeLater(() -> createAndShowGui());
}
private void createAndShowGui() {
setLookAndFeel();
try (InputStream is = this.getClass().getResourceAsStream(
"FontAwesome.ttf")) {
this.fontAwesome = Font.createFont(Font.TRUETYPE_FONT, is)
.deriveFont(Font.PLAIN, 24);
} catch (FontFormatException | IOException e) {
// Ignore - things should fall back to text labels if fontAwesome
// is null.
}
this.frame = new JFrame();
JPanel controlPanel = initControlPanel();
JPanel positionPanel = initPositionPanel();
JPanel metadataPanel = initMetadataPanel();
this.state.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
this.frame.getContentPane().add(controlPanel, BorderLayout.PAGE_END);
this.frame.getContentPane().add(this.name, BorderLayout.PAGE_START);
this.frame.getContentPane().add(this.state, BorderLayout.LINE_START);
this.frame.getContentPane().add(metadataPanel, BorderLayout.CENTER);
this.frame.getContentPane().add(positionPanel, BorderLayout.LINE_END);
// Set up player for the initial ejected state.
handleEject();
this.frame.pack();
this.frame.setVisible(true);
}
private JPanel initControlPanel() {
JPanel controlPanel = new JPanel();
controlPanel
.setLayout(new BoxLayout(controlPanel, BoxLayout.PAGE_AXIS));
controlPanel.add(this.seeker);
initSeeker();
JPanel buttonPanel = initButtonPanel();
controlPanel.add(buttonPanel);
return controlPanel;
}
private JPanel initButtonPanel() {
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(this.playButton);
buttonPanel.add(this.stopButton);
buttonPanel.add(this.ejctButton);
buttonPanel.add(this.loadButton);
initButtons();
return buttonPanel;
}
private JPanel initPositionPanel() {
JPanel positionPanel = new JPanel();
positionPanel.setLayout(new BoxLayout(positionPanel,
BoxLayout.PAGE_AXIS));
positionPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
positionPanel.add(this.duration);
positionPanel.add(this.position);
return positionPanel;
}
private JPanel initMetadataPanel() {
JPanel metadataPanel = new JPanel();
metadataPanel.setLayout(new BoxLayout(metadataPanel,
BoxLayout.PAGE_AXIS));
metadataPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLoweredBevelBorder(),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
metadataPanel.add(this.songTitle);
metadataPanel.add(this.songArtist);
metadataPanel.add(this.songAlbum);
return metadataPanel;
}
private void initButtons() {
this.playButton.addActionListener((e) -> {
this.model.play();
});
this.stopButton.addActionListener((e) -> {
this.model.stop();
});
this.ejctButton.addActionListener((e) -> {
this.model.eject();
});
this.loadButton.addActionListener((e) -> {
loadFile();
});
setFontAwesomeIcon(this.playButton, FA_PLAY);
setFontAwesomeIcon(this.stopButton, FA_STOP);
setFontAwesomeIcon(this.ejctButton, FA_EJECT);
setFontAwesomeIcon(this.loadButton, FA_LOAD);
}
private void setFontAwesomeIcon(JButton component, String icon) {
if (this.fontAwesome != null) {
component.setFont(this.fontAwesome);
component.setText(icon);
}
}
private void setFontAwesomeIcon(JLabel component, String icon) {
if (this.fontAwesome != null) {
component.setFont(this.fontAwesome);
component.setText(icon);
}
}
private void initSeeker() {
this.seeker.setEnabled(false);
this.seeker.addChangeListener((e) -> {
if (!this.seeker.getValueIsAdjusting()) {
// This change may have happened as part of a position update
// from the player, in which case the new duration will be the
// same as that in the model. Ignore this case.
if (this.seeker.getValue() != this.model.time()) {
this.model.seek(this.seeker.getValue());
}
}
});
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// Use default look and feel
}
}
private void loadFile() {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this.frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
this.model.load(fc.getSelectedFile());
}
}
@Override
public void setName(String inName) {
this.name.setText(inName);
}
@Override
public void setState(State to) {
this.state.setText(to.toString());
switch (to) {
case EJECTED:
handleEject();
break;
case PLAYING:
handlePlay();
break;
case STOPPED:
handleStop();
break;
default:
break;
}
}
private void handleEject() {
clearMetadata();
this.seeker.setEnabled(false);
this.stopButton.setEnabled(false);
this.playButton.setEnabled(false);
this.ejctButton.setEnabled(false);
setFontAwesomeIcon(this.state, FA_EJECT);
this.state.setForeground(Color.BLUE);
}
private void handlePlay() {
this.seeker.setEnabled(true);
this.stopButton.setEnabled(true);
this.playButton.setEnabled(false);
this.ejctButton.setEnabled(true);
setFontAwesomeIcon(this.state, FA_PLAY);
this.state.setForeground(Color.GREEN);
}
private void handleStop() {
this.seeker.setEnabled(true);
this.stopButton.setEnabled(false);
this.playButton.setEnabled(true);
this.ejctButton.setEnabled(true);
setFontAwesomeIcon(this.state, FA_STOP);
this.state.setForeground(Color.RED);
}
@Override
public void setTime(long micros) {
this.position.setText(formatTime(micros));
// Only update the seek bar if it isn't being used.
if (!this.seeker.getValueIsAdjusting()) {
this.seeker.setValue((int) micros);
}
}
private static String formatTime(long micros) {
Duration dur = Duration.ofNanos(micros * 1000);
long hours = dur.toHours();
long mins = dur.minusHours(hours).toMinutes();
long secs = dur.minusHours(hours).minusMinutes(mins).getSeconds();
return String.format("%d:%02d:%02d", Long.valueOf(hours),
Long.valueOf(mins), Long.valueOf(secs));
}
@Override
public void setTotalDuration(long micros) {
this.duration.setText(formatTime(micros));
this.seeker.setMaximum((int) micros);
}
@Override
public void loadFailed() {
clearMetadata();
setSongTitle("(Load Failed)");
}
private void clearMetadata() {
setSongAlbum("No Album");
setSongArtist("No Artist");
setSongTitle("No Title");
this.duration.setText("0:00:00");
this.position.setText("0:00:00");
this.seeker.setValue(0);
this.seeker.setMaximum(0);
}
@Override
public void setSongAlbum(String album) {
this.songAlbum.setText(album);
}
@Override
public void setSongArtist(String artist) {
this.songArtist.setText(artist);
}
@Override
public void setSongTitle(String title) {
this.songTitle.setText(title);
}
}
| |
/*
* Copyright (c) 2013 Hudson.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Hudson - initial API and implementation and/or initial documentation
*/
package org.jvnet.hudson.test;
import hudson.AbortException;
import hudson.maven.MavenEmbedder;
import hudson.maven.MavenEmbedderException;
import hudson.maven.MavenRequest;
import hudson.model.TaskListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import java.io.PrintStream;
import java.util.StringTokenizer;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.cli.MavenLoggerManager;
import org.codehaus.plexus.logging.console.ConsoleLogger;
/**
* Just enough of MavenUtil from legacy-maven to fix test harness bug
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=403703
*
* TODO Move class back to Hudson?
*
* @author Bob Foster
*/
public class MavenUtil {
/**
* Create MavenRequest given only a TaskListener. Used by HudsonTestCase.
*
* @param listener
* @return MavenRequest
* @throws MavenEmbedderException
* @throws IOException
*/
public static MavenRequest createMavenRequest(TaskListener listener) throws MavenEmbedderException, IOException {
Properties systemProperties = new Properties();
MavenRequest mavenRequest = new MavenRequest();
// make sure ~/.m2 exists to avoid http://www.nabble.com/BUG-Report-tf3401736.html
File m2Home = new File(MavenEmbedder.userHome, ".m2");
m2Home.mkdirs();
if(!m2Home.exists())
throw new AbortException("Failed to create "+m2Home);
mavenRequest.setUserSettingsFile( new File( m2Home, "settings.xml" ).getAbsolutePath() );
mavenRequest.setGlobalSettingsFile( new File( "conf/settings.xml" ).getAbsolutePath() );
mavenRequest.setUpdateSnapshots(false);
// TODO olamy check this sould be userProperties
mavenRequest.setSystemProperties(systemProperties);
EmbedderLoggerImpl logger =
new EmbedderLoggerImpl( listener, debugMavenEmbedder ? org.codehaus.plexus.logging.Logger.LEVEL_DEBUG
: org.codehaus.plexus.logging.Logger.LEVEL_INFO );
mavenRequest.setMavenLoggerManager( logger );
ClassLoader mavenEmbedderClassLoader = new MaskingClassLoader( MavenUtil.class.getClassLoader() );
{// are we loading the right components.xml? (and not from Maven that's running Jetty, if we are running in "mvn hudson-dev:run" or "mvn hpi:run"?
Enumeration<URL> e = mavenEmbedderClassLoader.getResources("META-INF/plexus/components.xml");
while (e.hasMoreElements()) {
URL url = e.nextElement();
LOGGER.fine("components.xml from "+url);
}
}
mavenRequest.setProcessPlugins( false );
mavenRequest.setResolveDependencies( false );
mavenRequest.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 );
return mavenRequest;
}
/**
* {@link MavenEmbedderLogger} implementation that
* sends output to {@link TaskListener}.
*
* @author Kohsuke Kawaguchi
*/
private static final class EmbedderLoggerImpl extends MavenLoggerManager {
private final PrintStream logger;
public EmbedderLoggerImpl(TaskListener listener, int threshold) {
super(new ConsoleLogger( threshold, "hudson-logger" ));
logger = listener.getLogger();
}
private void print(String message, Throwable throwable, int threshold, String prefix) {
if (getThreshold() <= threshold) {
StringTokenizer tokens = new StringTokenizer(message,"\n");
while(tokens.hasMoreTokens()) {
logger.print(prefix);
logger.println(tokens.nextToken());
}
if (throwable!=null)
throwable.printStackTrace(logger);
}
}
public void debug(String message, Throwable throwable) {
print(message, throwable, org.codehaus.plexus.logging.Logger.LEVEL_DEBUG, "[DEBUG] ");
}
public void info(String message, Throwable throwable) {
print(message, throwable, org.codehaus.plexus.logging.Logger.LEVEL_INFO, "[INFO ] ");
}
public void warn(String message, Throwable throwable) {
print(message, throwable, org.codehaus.plexus.logging.Logger.LEVEL_WARN, "[WARN ] ");
}
public void error(String message, Throwable throwable) {
print(message, throwable, org.codehaus.plexus.logging.Logger.LEVEL_ERROR, "[ERROR] ");
}
public void fatalError(String message, Throwable throwable) {
print(message, throwable, org.codehaus.plexus.logging.Logger.LEVEL_FATAL, "[FATAL] ");
}
}
/**
* When we run in Jetty during development, embedded Maven will end up
* seeing some of the Maven class visible through Jetty, and this confuses it.
*
* <p>
* Specifically, embedded Maven will find all the component descriptors
* visible through Jetty, yet when it comes to loading classes, classworlds
* still load classes from local realms created inside embedder.
*
* <p>
* This classloader prevents this issue by hiding the component descriptor
* visible through Jetty.
*/
private static final class MaskingClassLoader extends ClassLoader {
public MaskingClassLoader(ClassLoader parent) {
super(parent);
}
public Enumeration<URL> getResources(String name) throws IOException {
final Enumeration<URL> e = super.getResources(name);
return new Enumeration<URL>() {
URL next;
public boolean hasMoreElements() {
fetch();
return next!=null;
}
public URL nextElement() {
fetch();
URL r = next;
next = null;
return r;
}
private void fetch() {
while(next==null && e.hasMoreElements()) {
next = e.nextElement();
if(shouldBeIgnored(next))
next = null;
}
}
private boolean shouldBeIgnored(URL url) {
String s = url.toExternalForm();
if(s.contains("maven-plugin-tools-api"))
return true;
// because RemoteClassLoader mangles the path, we can't check for plexus/components.xml,
// which would have otherwise made the test cheaper.
if(s.endsWith("components.xml")) {
BufferedReader r=null;
try {
// is this designated for interception purpose? If so, don't load them in the MavenEmbedder
// earlier I tried to use a marker file in the same directory, but that won't work
r = new BufferedReader(new InputStreamReader(url.openStream()));
for (int i=0; i<2; i++) {
String l = r.readLine();
if(l!=null && l.contains("MAVEN-INTERCEPTION-TO-BE-MASKED"))
return true;
}
} catch (IOException _) {
// let whoever requesting this resource re-discover an error and report it
} finally {
IOUtils.closeQuietly(r);
}
}
return false;
}
};
}
}
/**
* If set to true, maximize the logging level of Maven embedder.
*/
public static boolean debugMavenEmbedder = Boolean.getBoolean( "debugMavenEmbedder" );
private static final Logger LOGGER = Logger.getLogger(MavenUtil.class.getName());
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.webapp;
import static org.apache.hadoop.yarn.util.StringHelper.join;
import static org.apache.hadoop.yarn.webapp.YarnWebParams.APP_STATE;
import static org.apache.hadoop.yarn.webapp.YarnWebParams.APP_START_TIME_BEGIN;
import static org.apache.hadoop.yarn.webapp.YarnWebParams.APP_START_TIME_END;
import static org.apache.hadoop.yarn.webapp.YarnWebParams.APPS_NUM;
import static org.apache.hadoop.yarn.webapp.view.JQueryUI.C_PROGRESSBAR;
import static org.apache.hadoop.yarn.webapp.view.JQueryUI.C_PROGRESSBAR_VALUE;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.Collection;
import java.util.EnumSet;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.math.LongRange;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.yarn.api.ApplicationBaseProtocol;
import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsRequest;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.webapp.dao.AppInfo;
import org.apache.hadoop.yarn.webapp.BadRequestException;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TABLE;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TBODY;
import org.apache.hadoop.yarn.webapp.view.HtmlBlock;
import com.google.inject.Inject;
public class AppsBlock extends HtmlBlock {
private static final Log LOG = LogFactory.getLog(AppsBlock.class);
protected ApplicationBaseProtocol appBaseProt;
protected EnumSet<YarnApplicationState> reqAppStates;
protected UserGroupInformation callerUGI;
protected Collection<ApplicationReport> appReports;
@Inject
protected AppsBlock(ApplicationBaseProtocol appBaseProt, ViewContext ctx) {
super(ctx);
this.appBaseProt = appBaseProt;
}
protected void fetchData() throws YarnException, IOException,
InterruptedException {
reqAppStates = EnumSet.noneOf(YarnApplicationState.class);
String reqStateString = $(APP_STATE);
if (reqStateString != null && !reqStateString.isEmpty()) {
String[] appStateStrings = reqStateString.split(",");
for (String stateString : appStateStrings) {
reqAppStates.add(YarnApplicationState.valueOf(stateString.trim()));
}
}
callerUGI = getCallerUGI();
final GetApplicationsRequest request =
GetApplicationsRequest.newInstance(reqAppStates);
String appsNumStr = $(APPS_NUM);
if (appsNumStr != null && !appsNumStr.isEmpty()) {
long appsNum = Long.parseLong(appsNumStr);
request.setLimit(appsNum);
}
String appStartedTimeBegainStr = $(APP_START_TIME_BEGIN);
long appStartedTimeBegain = 0;
if (appStartedTimeBegainStr != null && !appStartedTimeBegainStr.isEmpty()) {
appStartedTimeBegain = Long.parseLong(appStartedTimeBegainStr);
if (appStartedTimeBegain < 0) {
throw new BadRequestException(
"app.started-time.begin must be greater than 0");
}
}
String appStartedTimeEndStr = $(APP_START_TIME_END);
long appStartedTimeEnd = Long.MAX_VALUE;
if (appStartedTimeEndStr != null && !appStartedTimeEndStr.isEmpty()) {
appStartedTimeEnd = Long.parseLong(appStartedTimeEndStr);
if (appStartedTimeEnd < 0) {
throw new BadRequestException(
"app.started-time.end must be greater than 0");
}
}
if (appStartedTimeBegain > appStartedTimeEnd) {
throw new BadRequestException(
"app.started-time.end must be greater than app.started-time.begin");
}
request.setStartRange(
new LongRange(appStartedTimeBegain, appStartedTimeEnd));
if (callerUGI == null) {
appReports = appBaseProt.getApplications(request).getApplicationList();
} else {
appReports =
callerUGI
.doAs(new PrivilegedExceptionAction<Collection<ApplicationReport>>() {
@Override
public Collection<ApplicationReport> run() throws Exception {
return appBaseProt.getApplications(request)
.getApplicationList();
}
});
}
}
@Override
public void render(Block html) {
setTitle("Applications");
try {
fetchData();
}
catch( Exception e) {
String message = "Failed to read the applications.";
LOG.error(message, e);
html.p()._(message)._();
return;
}
renderData(html);
}
protected void renderData(Block html) {
TBODY<TABLE<Hamlet>> tbody =
html.table("#apps").thead().tr().th(".id", "ID").th(".user", "User")
.th(".name", "Name").th(".type", "Application Type")
.th(".queue", "Queue").th(".priority", "Application Priority")
.th(".starttime", "StartTime").th(".finishtime", "FinishTime")
.th(".state", "State").th(".finalstatus", "FinalStatus")
.th(".progress", "Progress").th(".ui", "Tracking UI")._()._().tbody();
StringBuilder appsTableData = new StringBuilder("[\n");
for (ApplicationReport appReport : appReports) {
// TODO: remove the following condition. It is still here because
// the history side implementation of ApplicationBaseProtocol
// hasn't filtering capability (YARN-1819).
if (!reqAppStates.isEmpty()
&& !reqAppStates.contains(appReport.getYarnApplicationState())) {
continue;
}
AppInfo app = new AppInfo(appReport);
String percent = StringUtils.format("%.1f", app.getProgress());
appsTableData
.append("[\"<a href='")
.append(url("app", app.getAppId()))
.append("'>")
.append(app.getAppId())
.append("</a>\",\"")
.append(
StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app
.getUser())))
.append("\",\"")
.append(
StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app
.getName())))
.append("\",\"")
.append(
StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app
.getType())))
.append("\",\"")
.append(
StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(app
.getQueue()))).append("\",\"").append(String
.valueOf(app.getPriority()))
.append("\",\"").append(app.getStartedTime())
.append("\",\"").append(app.getFinishedTime())
.append("\",\"")
.append(app.getAppState() == null ? UNAVAILABLE : app.getAppState())
.append("\",\"")
.append(app.getFinalAppStatus())
.append("\",\"")
// Progress bar
.append("<br title='").append(percent).append("'> <div class='")
.append(C_PROGRESSBAR).append("' title='").append(join(percent, '%'))
.append("'> ").append("<div class='").append(C_PROGRESSBAR_VALUE)
.append("' style='").append(join("width:", percent, '%'))
.append("'> </div> </div>").append("\",\"<a ");
String trackingURL =
app.getTrackingUrl() == null
|| app.getTrackingUrl().equals(UNAVAILABLE) ? null : app
.getTrackingUrl();
String trackingUI =
app.getTrackingUrl() == null || app.getTrackingUrl().equals(UNAVAILABLE)
? "Unassigned"
: app.getAppState() == YarnApplicationState.FINISHED
|| app.getAppState() == YarnApplicationState.FAILED
|| app.getAppState() == YarnApplicationState.KILLED
? "History" : "ApplicationMaster";
appsTableData.append(trackingURL == null ? "#" : "href='" + trackingURL)
.append("'>").append(trackingUI).append("</a>\"],\n");
}
if (appsTableData.charAt(appsTableData.length() - 2) == ',') {
appsTableData.delete(appsTableData.length() - 2,
appsTableData.length() - 1);
}
appsTableData.append("]");
html.script().$type("text/javascript")
._("var appsTableData=" + appsTableData)._();
tbody._()._();
}
}
| |
/*
* The MIT License
*
* Copyright 2015 Jesse Glick.
*
* 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 jenkins.tasks;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.console.ConsoleLogFilter;
import hudson.console.LineTransformationOutputStream;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.JDK;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.scm.ChangeLogParser;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.RetentionStrategy;
import hudson.slaves.SlaveComputer;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Shell;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.Locale;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Assume;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.jvnet.hudson.test.BuildWatcher;
import org.jvnet.hudson.test.CaptureEnvironmentBuilder;
import org.jvnet.hudson.test.FailureBuilder;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestBuilder;
import org.jvnet.hudson.test.TestExtension;
public class SimpleBuildWrapperTest {
@ClassRule public static BuildWatcher buildWatcher = new BuildWatcher();
@Rule public JenkinsRule r = new JenkinsRule();
@Rule public TemporaryFolder tmp = new TemporaryFolder();
@Test public void envOverride() throws Exception {
FreeStyleProject p = r.createFreeStyleProject();
p.getBuildWrappersList().add(new WrapperWithEnvOverride());
CaptureEnvironmentBuilder captureEnvironment = new CaptureEnvironmentBuilder();
p.getBuildersList().add(captureEnvironment);
FreeStyleBuild b = r.buildAndAssertSuccess(p);
String path = captureEnvironment.getEnvVars().get("PATH");
assertTrue(path, path.startsWith(b.getWorkspace().child("bin").getRemote() + File.pathSeparatorChar));
}
public static class WrapperWithEnvOverride extends SimpleBuildWrapper {
@Override public void setUp(Context context, Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException {
assertNotNull(initialEnvironment.get("PATH"));
context.env("PATH+STUFF", workspace.child("bin").getRemote());
}
@TestExtension("envOverride") public static class DescriptorImpl extends BuildWrapperDescriptor {
@Override public boolean isApplicable(AbstractProject<?,?> item) {
return true;
}
}
}
@Test public void envOverrideExpand() throws Exception {
Assume.assumeFalse(Functions.isWindows());
FreeStyleProject p = r.createFreeStyleProject();
p.getBuildWrappersList().add(new WrapperWithEnvOverrideExpand());
SpecialEnvSlave slave = new SpecialEnvSlave(tmp.getRoot(), r.createComputerLauncher(null));
r.jenkins.addNode(slave);
p.setAssignedNode(slave);
JDK jdk = new JDK("test", "/opt/jdk");
r.jenkins.getJDKs().add(jdk);
p.setJDK(jdk);
CaptureEnvironmentBuilder captureEnvironment = new CaptureEnvironmentBuilder();
p.getBuildersList().add(captureEnvironment);
p.getBuildersList().add(new Shell("echo effective PATH=$PATH"));
FreeStyleBuild b = r.buildAndAssertSuccess(p);
String expected = "/home/jenkins/extra/bin:/opt/jdk/bin:/usr/bin:/bin";
assertEquals(expected, captureEnvironment.getEnvVars().get("PATH"));
// TODO why is /opt/jdk/bin added twice? In CommandInterpreter.perform, envVars right before Launcher.launch is correct, but this somehow sneaks in.
r.assertLogContains("effective PATH=/opt/jdk/bin:" + expected, b);
}
public static class WrapperWithEnvOverrideExpand extends SimpleBuildWrapper {
@Override public void setUp(Context context, Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException {
assertEquals("/opt/jdk/bin:/usr/bin:/bin", initialEnvironment.get("PATH"));
assertEquals("/home/jenkins", initialEnvironment.get("HOME"));
context.env("EXTRA", "${HOME}/extra");
context.env("PATH+EXTRA", "${EXTRA}/bin");
}
@TestExtension("envOverrideExpand") public static class DescriptorImpl extends BuildWrapperDescriptor {
@Override public boolean isApplicable(AbstractProject<?,?> item) {
return true;
}
}
}
private static class SpecialEnvSlave extends Slave {
SpecialEnvSlave(File remoteFS, ComputerLauncher launcher) throws Descriptor.FormException, IOException {
super("special", "SpecialEnvSlave", remoteFS.getAbsolutePath(), 1, Mode.NORMAL, "", launcher, RetentionStrategy.NOOP, Collections.emptyList());
}
@Override public Computer createComputer() {
return new SpecialEnvComputer(this);
}
}
private static class SpecialEnvComputer extends SlaveComputer {
SpecialEnvComputer(SpecialEnvSlave slave) {
super(slave);
}
@Override public EnvVars getEnvironment() throws IOException, InterruptedException {
EnvVars env = super.getEnvironment();
env.put("PATH", "/usr/bin:/bin");
env.put("HOME", "/home/jenkins");
return env;
}
}
@Test public void disposer() throws Exception {
FreeStyleProject p = r.createFreeStyleProject();
p.getBuildWrappersList().add(new WrapperWithDisposer());
FreeStyleBuild b = r.buildAndAssertSuccess(p);
r.assertLogContains("ran DisposerImpl #1", b);
r.assertLogNotContains("ran DisposerImpl #2", b);
}
public static class WrapperWithDisposer extends SimpleBuildWrapper {
@Override public void setUp(Context context, Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException {
context.setDisposer(new DisposerImpl());
}
private static final class DisposerImpl extends Disposer {
private static final long serialVersionUID = 1;
private int tearDownCount = 0;
@Override public void tearDown(Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
listener.getLogger().println("ran DisposerImpl #" + (++tearDownCount));
}
}
@TestExtension({ "disposer", "failedJobWithInterruptedDisposer" }) public static class DescriptorImpl extends BuildWrapperDescriptor {
@Override public boolean isApplicable(AbstractProject<?,?> item) {
return true;
}
}
}
@Test public void disposerForPreCheckoutWrapper() throws Exception {
FreeStyleProject p = r.createFreeStyleProject();
p.getBuildWrappersList().add(new PreCheckoutWrapperWithDisposer());
FreeStyleBuild b = r.buildAndAssertSuccess(p);
r.assertLogContains("ran DisposerImpl #1", b);
r.assertLogNotContains("ran DisposerImpl #2", b);
}
@Issue("JENKINS-43889")
@Test public void disposerForPreCheckoutWrapperWithScmError() throws Exception {
FreeStyleProject p = r.createFreeStyleProject();
p.setScm(new FailingSCM());
p.getBuildWrappersList().add(new PreCheckoutWrapperWithDisposer());
FreeStyleBuild b = r.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0));
r.assertLogContains("ran DisposerImpl #1", b);
r.assertLogNotContains("ran DisposerImpl #2", b);
}
public static class PreCheckoutWrapperWithDisposer extends WrapperWithDisposer {
@Override
protected boolean runPreCheckout() {
return true;
}
@TestExtension({ "disposerForPreCheckoutWrapper", "disposerForPreCheckoutWrapperWithScmError" }) public static class DescriptorImpl extends BuildWrapperDescriptor {
@Override public boolean isApplicable(AbstractProject<?,?> item) {
return true;
}
}
}
public static class FailingSCM extends SCM {
@Override
public void checkout(Run<?, ?> build, Launcher launcher, FilePath workspace, TaskListener listener, File changelogFile, SCMRevisionState baseline) throws IOException, InterruptedException {
throw new RuntimeException("SCM failed");
}
@Override
public ChangeLogParser createChangeLogParser() {
return null;
}
}
@Test public void failedJobWithInterruptedDisposer() throws Exception {
FreeStyleProject p = r.createFreeStyleProject();
p.getBuildersList().add(new FailureBuilder());
p.getBuildWrappersList().add(new WrapperWithDisposer());
p.getBuildWrappersList().add(new InterruptedDisposerWrapper());
// build is ABORTED because of InterruptedException during tearDown (trumps the FAILURE result)
FreeStyleBuild b = r.assertBuildStatus(Result.ABORTED, p.scheduleBuild2(0));
r.assertLogContains("tearDown InterruptedDisposerImpl", b);
r.assertLogContains("ran DisposerImpl", b); // ran despite earlier InterruptedException
}
public static class InterruptedDisposerWrapper extends SimpleBuildWrapper {
@Override public void setUp(Context context, Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException {
context.setDisposer(new InterruptedDisposerImpl());
}
private static final class InterruptedDisposerImpl extends Disposer {
private static final long serialVersionUID = 1;
@Override public void tearDown(Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
listener.getLogger().println("tearDown InterruptedDisposerImpl");
throw new InterruptedException("interrupted in InterruptedDisposerImpl");
}
}
@TestExtension("failedJobWithInterruptedDisposer") public static class DescriptorImpl extends BuildWrapperDescriptor {
@Override public boolean isApplicable(AbstractProject<?,?> item) {
return true;
}
}
}
@Issue("JENKINS-27392")
@Test public void loggerDecorator() throws Exception {
FreeStyleProject p = r.createFreeStyleProject();
p.getBuildWrappersList().add(new WrapperWithLogger());
p.getBuildersList().add(new TestBuilder() {
@Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
listener.getLogger().println("sending a message");
return true;
}
});
r.assertLogContains("SENDING A MESSAGE", r.buildAndAssertSuccess(p));
}
public static class WrapperWithLogger extends SimpleBuildWrapper {
@Override public void setUp(Context context, Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException {}
@Override public ConsoleLogFilter createLoggerDecorator(Run<?,?> build) {
return new UpcaseFilter();
}
private static class UpcaseFilter extends ConsoleLogFilter implements Serializable {
private static final long serialVersionUID = 1;
@SuppressWarnings("rawtypes") // inherited
@Override public OutputStream decorateLogger(AbstractBuild _ignore, OutputStream logger) throws IOException, InterruptedException {
return new LineTransformationOutputStream.Delegating(logger) {
@Override protected void eol(byte[] b, int len) throws IOException {
out.write(new String(b, 0, len).toUpperCase(Locale.ROOT).getBytes());
}
};
}
}
@TestExtension("loggerDecorator") public static class DescriptorImpl extends BuildWrapperDescriptor {
@Override public boolean isApplicable(AbstractProject<?,?> item) {
return true;
}
}
}
}
| |
package com.perforce.p4java.impl.mapbased.server.cmd;
import static com.perforce.p4java.server.CmdSpec.BRANCHES;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.expectThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Executable;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import com.google.common.collect.Lists;
import com.perforce.p4java.AbstractP4JavaUnitTest;
import com.perforce.p4java.core.IBranchSpec;
import com.perforce.p4java.core.IBranchSpecSummary;
import com.perforce.p4java.exception.AccessException;
import com.perforce.p4java.exception.ConnectionException;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.exception.RequestException;
import com.perforce.p4java.impl.mapbased.MapKeys;
import com.perforce.p4java.impl.mapbased.rpc.OneShotServerImpl;
import com.perforce.p4java.option.server.GetBranchSpecsOptions;
import com.perforce.p4java.tests.UnitTestGivenThatWillThrowException;
/**
* @author Sean Shou
* @since 21/09/2016
*/
@RunWith(JUnitPlatform.class)
public class BranchesDelegatorTest extends AbstractP4JavaUnitTest {
private static BranchesDelegator branchesDelegator;
private Map<String, Object> resultMap;
private List<Map<String, Object>> resultMaps;
private IBranchSpec mockBranchSpec;
private IBranchSpecSummary mockBranchSpecSummary;
@BeforeEach
public void beforeEach() {
server = mock(OneShotServerImpl.class);
branchesDelegator = new BranchesDelegator(server);
resultMap = mock(Map.class);
resultMaps = Lists.newArrayList(resultMap);
// server = mock(Server.class);
mockBranchSpec = mock(IBranchSpec.class);
}
/**
* Check that a null result map results in an empty list.
* @throws P4JavaException
*/
@Test
public void testNullServerResponse()
throws P4JavaException {
// given
when(server.execMapCmdList(eq(BRANCHES.toString()), any(String[].class), eq(null)))
.thenReturn(null);
// when
List<IBranchSpecSummary> branchSpecs = branchesDelegator
.getBranchSpecs(mock(GetBranchSpecsOptions.class));
// then
assertThat(branchSpecs.size(), is(0));
}
/**
* Check that a result map from a server gets converted into an IBranchSpec list.
* @throws P4JavaException thrown by the delegate
*/
@Test
public void testNormalServerResponse()
throws P4JavaException {
// When the server is given a branches command, return a single map
when(server.execMapCmdList(eq(BRANCHES.toString()), any(String[].class), eq(null)))
.thenReturn(resultMaps);
when(resultMap.get(MapKeys.ACCESS_KEY)).thenReturn("0");
when(resultMap.get(MapKeys.UPDATE_KEY)).thenReturn("0");
// when
List<IBranchSpecSummary> branchSpecs = branchesDelegator
.getBranchSpecs(new GetBranchSpecsOptions());
// then
assertThat(branchSpecs.size(), is(1));
}
/**
* Test that a ConnectionException thrown by the underlying server implementation is passed
* back up the chain.
* @throws P4JavaException thrown by the delegate
*/
@Test
public void testServerConnectionException()
throws P4JavaException {
checkExceptionFilter(ConnectionException.class, ConnectionException.class);
}
/**
* Test that a AccessException thrown by the underlying server implementation is passed
* back up the chain.
* @throws P4JavaException thrown by the delegate
*/
@Test
public void testAccessExceptiong()
throws P4JavaException {
checkExceptionFilter(AccessException.class, AccessException.class);
}
/**
* Test that a RequestException thrown by the underlying server implementation is passed
* back up the chain.
* @throws P4JavaException thrown by the delegate
*/
@Test
public void testRequestException()
throws P4JavaException {
checkExceptionFilter(RequestException.class, RequestException.class);
}
/**
* Test that a P4JavaException thrown by the underlying server implementation is passed
* back up the chain as a RequestException.
* @throws P4JavaException thrown by the delegate
*/
@Test
public void testP4JavaException()
throws P4JavaException {
checkExceptionFilter(P4JavaException.class, RequestException.class);
}
/**
* Test that the result list from a filtered branches command contains the data from a
* defined server response.
* TODO: Add tests that exercise the actual filtering; e.g. no more than max
* @throws P4JavaException
*/
@Test
public void testFilteredResultList()
throws P4JavaException {
final String knownName="testKnownName";
final String knownDescription="testKnownSummaryDescription";
// given
when(server.getServerVersion()).thenReturn(20161);
when(server.execMapCmdList(eq(BRANCHES.toString()), any(String[].class), eq(null)))
.thenReturn(resultMaps);
// use predictable data
when(resultMap.get(MapKeys.BRANCH_LC_KEY)).thenReturn(knownName);
when(resultMap.get(MapKeys.DESCRIPTION_KEY)).thenReturn(knownDescription);
when(resultMap.get(MapKeys.ACCESS_KEY)).thenReturn("0");
when(resultMap.get(MapKeys.UPDATE_KEY)).thenReturn("0");
// when
List<IBranchSpecSummary> branchSpecs = branchesDelegator.getBranchSpecs(
"seans",
"myFilter",
10);
// then
assertEquals(1, branchSpecs.size());
assertEquals(knownName, branchSpecs.get(0).getName());
assertEquals(knownDescription, branchSpecs.get(0).getDescription());
}
/**
* Test that when a server is less than 2005.1, a request exception will be thrown if a user
* name filter is provided to the branches command.
* @throws P4JavaException when supported version is too low
*/
@Test
public void testUserNameFilterSupportMinVersion()
throws P4JavaException {
// given
when(server.getServerVersion()).thenReturn(20051);
// doCallRealMethod().when(server).checkMinSupportedPerforceVersion(any(String.class),
// any(int.class), any(String.class), eq("branch"));
// then
expectThrows(RequestException.class,
() -> branchesDelegator.getBranchSpecs("sean", "Date_Modified>453470485", 10));
}
/**
* Test that when a servers is less than 2006.1, a request exception will be thrown if a
* max results filter is provided to the branches command.
* @throws P4JavaException when supported version is too low
*/
@Test
public void testMaxResultsFilterSupportMinVersion()
throws P4JavaException {
// given
when(server.getServerVersion()).thenReturn(20051);
// doCallRealMethod().when(server).checkMinSupportedPerforceVersion(any(String.class),
// any(int.class), any(String.class), eq("branch"));
// then
expectThrows(RequestException.class,
() -> branchesDelegator.getBranchSpecs(EMPTY, "Date_Modified>453470485", 10));
}
/**
* Test that when the server is less than 2008.2, a request exception will be thrown if
* a query filter is provided to the branches command.
* @throws P4JavaException when supported version is too low
*/
@Test
public void testQueryFilterSupportMinVersion()
throws P4JavaException {
// given
when(server.getServerVersion()).thenReturn(20071);
// doCallRealMethod().when(server).checkMinSupportedPerforceVersion(any(String.class),
// any(int.class), any(String.class), eq("branch"));
// then
expectThrows(RequestException.class,
() -> branchesDelegator.getBranchSpecs(EMPTY, "Date_Modified>453470485", -1));
}
/**
* Wrap the exception handling in the delegator such that we get the correct exception
* propagation for the given expectations.
* @param thrownException The exception thrown by the lower tier
* @param expectedThrows The exception after it has been processed by the delegator
* @throws P4JavaException the parent exception type
*/
private void checkExceptionFilter(
Class<? extends P4JavaException> thrownException,
Class<? extends P4JavaException> expectedThrows) throws P4JavaException {
Executable executable = () -> branchesDelegator.getBranchSpecs("seans", "myFilter", 10);
UnitTestGivenThatWillThrowException unitTestGiven = (originalException) -> {
when(server.getServerVersion()).thenReturn(20161);
when(server.execMapCmdList(eq(BRANCHES.toString()), any(String[].class), eq(null)))
.thenThrow(originalException);
};
testIfGivenExceptionWasThrown(thrownException, expectedThrows, executable, unitTestGiven);
}
}
| |
package com.plined.liftlog;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.CursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.plined.liftlog.LiftLogDBMaster.RoutineExerciseCursor;
public class RoutineFactoryFragment extends ListFragment {
//Stores the routine we're currently managing.
private Routine mRoutine;
private int mRoutineId;
private static String TAG = "RoutineFactoryFragment";
private RoutineExerciseCursorAdapter mAdapter;
private LiftLogDBAPI mDbHelper;
private View mHeaderView;
//Key used in our bundle to store the routine's ID
public static String ROUTINE_ID = "com.perryb.liftlog.routinefactoryfragment.routine_id";
public static String ROUTINE_EXERCISE_ID = "com.perryb.liftlog.routinefactoryfragment.routine_exercise_id";
/*
* Request codes
*/
private static int REQUEST_EDIT_ROUTINE_NAME = 2;
private static int REQUEST_ADD_EXERCISE = 3;
private static int REQUEST_SET_INSTRUCTION = 4;
private static int REQUEST_DELETE_EXERCISE = 5;
private static int REQUEST_RENAME_EXERCISE = 6;
/*
* Result codes.
*/
private static int RESULT_EDIT_ROUTINE = 2;
private static int RESULT_ADD_EXERCISE = 3;
private static int RESULT_SET_INSTRUCTION = 4;
private static int RESULT_DELETE_EXERCISE = 5;
private static int RESULT_RENAME_EXERCISE = 6;
/*
* Dialog tags
*/
private static String DIALOG_TAG_EDIT_NAME = "editroutinename";
private static String DIALOG_TAG_ADD_EXERCISE = "addexercise";
public static RoutineFactoryFragment newInstance(int routineId) {
//Create our bundle
Bundle args = new Bundle();
//Put the routine's ID in
args.putInt(ROUTINE_ID, routineId);
//Create our routine fragment
RoutineFactoryFragment toLaunch = new RoutineFactoryFragment();
//Attach our bundle
toLaunch.setArguments(args);
return toLaunch;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get a reference to our DB manager
mDbHelper = LiftLogDBAPI.get(getActivity());
//Assign our ID
mRoutineId = getRoutineArg(getArguments());
//Set this so we'll get callbacks when menu items are hit.
setHasOptionsMenu(true);
getRoutineFromDb();
}
/*
* Gets our routine from the Db based on the mRoutineId we have set.
*/
public void getRoutineFromDb() {
//Get our routine object
mRoutine = mDbHelper.getRoutineById(mRoutineId);
//Make sure our routine is non-null
if (mRoutine == null) {
throw new RuntimeException("Routine with id " + mRoutineId + " was null after retrieval.");
}
}
/*
* Right now all of the listview initialization stuff happens in onStart().
*/
@Override
public void onStart() {
super.onStart();
RoutineExerciseCursor insCursor = (RoutineExerciseCursor) new RoutineExerciseCursorLoader(getActivity()).loadCursor();
mAdapter = new RoutineExerciseCursorAdapter(getActivity(), insCursor);
setListAdapter(mAdapter);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
//Inflate the context menu
getActivity().getMenuInflater().inflate(R.menu.routine_factory_item_context, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
//Figure out if they hit the delete button
switch(item.getItemId()) {
case R.id.menu_item_delete_routine_exercise: {
//Trying to delete.
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
//Figure out which we're trying to delete
RoutineExerciseCursorAdapter adapter = (RoutineExerciseCursorAdapter)getListAdapter();
RoutineExerciseCursor rotExCursor = (RoutineExerciseCursor) adapter.getItem(position-1);
RoutineExercise rotEx = rotExCursor.getRoutineExercise();
//Launch a delete confirm dialog.
//Create the fragment. We'll attach our current routine ID with it so it knows what to edit.
ConfirmDeleteRotEx fragToUse = ConfirmDeleteRotEx.newInstance(rotEx.getId());
//Launch this fragment.
launchDialogFragmentTarget(fragToUse, "deleterotexconfirm", REQUEST_DELETE_EXERCISE);
return true;
}
case R.id.menu_item_rename_routine_exercise: {
//Trying to rename exercise.
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
//Figure out which we're trying to rename.
RoutineExerciseCursorAdapter adapter = (RoutineExerciseCursorAdapter)getListAdapter();
RoutineExerciseCursor rotExCursor = (RoutineExerciseCursor) adapter.getItem(position-1);
RoutineExercise rotEx = rotExCursor.getRoutineExercise();
//Launch a rename dialog.
//Create the fragment. We'll attach the exercise super id so w eknow what to edit.
RenameExerciseDialog fragToUse = RenameExerciseDialog.newInstance(rotEx.getExerciseSuper());
//Launch this fragment.
launchDialogFragmentTarget(fragToUse, "renameexercise", REQUEST_RENAME_EXERCISE);
return true;
}
default:
return super.onContextItemSelected(item);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_routine_factory, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
RoutineExerciseCursor rotCursor;
switch(item.getItemId()) {
case R.id.menu_item_expand:
//They hit the expand collapsae button
//Get our current rotCursor
rotCursor = (RoutineExerciseCursor) mAdapter.getCursor();
rotCursor.moveToFirst();
//Iterate over it and set everyone's expanded state to false
while (!rotCursor.isAfterLast()) {
rotCursor.getRoutineExercise().setExpanded(true);
}
//Update our data
mAdapter.reloadData();
return true;
case R.id.menu_item_collapse:
//They hit the collapsae button
//Get our current rotCursor
rotCursor = (RoutineExerciseCursor) mAdapter.getCursor();
rotCursor.moveToFirst();
//Iterate over it and set everyone's expanded state to true
while (!rotCursor.isAfterLast()) {
rotCursor.getRoutineExercise().setExpanded(false);
}
//Update our data
mAdapter.reloadData();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
//Add the header to the listview
mHeaderView = getActivity().getLayoutInflater().inflate(R.layout.t_routine_factory_header, null);
getListView().addHeaderView(mHeaderView);
configureHeaderView();
//Make sure our listview doesn't show selections
getListView().setSelector(android.R.color.transparent);
super.onActivityCreated(savedInstanceState);
}
/*
* Populates the text fields of the header view, and sets up its on click listeners.
*/
public void configureHeaderView() {
//Set up our textviews
configureHeaderTextView();
//Set up our header onclick listeners
configureHeaderOnClick();
}
private void configureHeaderTextView() {
//Populate textviews in both rows.
LinearLayout topRow = (LinearLayout) mHeaderView.findViewById(R.id.t_routine_factory_header_name);
configureLabelRow(topRow, "Name", mRoutine.getName());
LinearLayout bottomRow = (LinearLayout) mHeaderView.findViewById(R.id.t_routine_factory_header_lastUsed);
configureLabelRow(bottomRow, "Last Used", Utilities.formatDate(mRoutine.getLastUsed()));
}
private void configureHeaderOnClick() {
//Set an onclick listener on the name modification dialog box.
View nameLayout = mHeaderView.findViewById(R.id.t_routine_factory_header_name);
nameLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment toShow = NameEditDialog.newInstance(mRoutineId);
launchDialogFragmentTarget(toShow, DIALOG_TAG_EDIT_NAME, REQUEST_EDIT_ROUTINE_NAME);
}
});
//Set an onclick listener on the exercise add dialog box.
View exerciseLayout = mHeaderView.findViewById(R.id.t_routine_factory_header_addExercise);
exerciseLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment toShow = AddExerciseDialog.newInstance(mRoutineId);
launchDialogFragmentTarget(toShow, DIALOG_TAG_ADD_EXERCISE, REQUEST_ADD_EXERCISE);
}
});
}
/*
* Configures a row of entries in our header.
*/
public void configureLabelRow(LinearLayout layoutRoot, String leftLabel, String rightLabel) {
TextView leftTv = (TextView) layoutRoot.findViewById(R.id.t_workout_instance_header_element_leftText);
leftTv.setText(leftLabel);
TextView rightTv = (TextView) layoutRoot.findViewById(R.id.t_workout_instance_header_element_rightText);
rightTv.setText(rightLabel);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
v.setBackgroundResource(R.color.newTempBg);
//Make our listview context menu sensitive
ListView listView = (ListView) v.findViewById(android.R.id.list);
registerForContextMenu(listView);
//Set our divider to be non-existent
listView.setDividerHeight(0);
return v;
}
/*
* Pulls the routine_id from our fragment bundle and returns it.
* Returns -1 for the routineID if there were no arguments included.
*/
private int getRoutineArg(Bundle fragArguments) {
if (fragArguments == null) {
//No routine ID provided.
return -1;
}
int rotId = fragArguments.getInt(ROUTINE_ID);
return rotId;
}
/*
* Creates and launches a dialog fragment. This is used in cases where we don't want to set it as our target.
*/
protected void launchDialogFragment(DialogFragment dialogToShow, String dialogTag) {
//Get our fragment manager
FragmentManager fm = getActivity().getSupportFragmentManager();
//Show it.
dialogToShow.show(fm, dialogTag);
}
/*
* Creates and launches a dialog fragment. This is used in cases where we do want our current
* fragment to be targeted.
*/
protected void launchDialogFragmentTarget(DialogFragment dialogToShow, String dialogTag, int targetRequest) {
dialogToShow.setTargetFragment(this, targetRequest);
launchDialogFragment(dialogToShow, dialogTag);
}
/*
* Processes returns from our dialogs.
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EDIT_ROUTINE_NAME) {
//Routine name has been updated. Update our routine info.
getRoutineFromDb();
//Reconfigure our header
configureHeaderTextView();
} else if (requestCode == REQUEST_ADD_EXERCISE) {
//Exercise has been added. Notify that our data set has changed.
mAdapter.reloadData();
} else if (requestCode == REQUEST_SET_INSTRUCTION) {
//An instruction has been set on one of our routine exercises. Update our data set.
mAdapter.reloadData();
} else if (requestCode == REQUEST_DELETE_EXERCISE) {
//Exercise has been removed from routine, reload data.
mAdapter.reloadData();
} else if (requestCode == REQUEST_RENAME_EXERCISE) {
//Exercise has been renamaed. Reload data.
mAdapter.reloadData();
}
else {
//Unexpected code returned.
throw new RuntimeException("Received unexpected request and/or result code. Request code is " + requestCode + " result code is " + resultCode);
}
}
/*
* Adds an onclick listener to our name so when it's clicked we're able to edit the name of our routine.
*
* viewToListen is the View to add the onclick listener to.
*/
private void addNameOnClickListener(View viewToListen) {
//Add the onclick listener to our view
viewToListen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*
* Create and launch our name dialog editing box.
*/
//Create the fragment. We'll attach our current routine ID with it so it knows what to edit.
NameSelectionDialog fragToUse = NameEditDialog.newInstance(mRoutine.getId());
//Launch this fragment.
launchDialogFragmentTarget(fragToUse, "editroutinename", REQUEST_EDIT_ROUTINE_NAME);
}
});
}
public static class InstructionEditDialog extends NameSelectionDialog {
RoutineExercise mRoutineExercise;
public static InstructionEditDialog newInstance(int routineExerciseId) {
Bundle args = new Bundle();
args.putInt(ROUTINE_EXERCISE_ID, routineExerciseId);
InstructionEditDialog fragment = new InstructionEditDialog();
fragment.setArguments(args);
return fragment;
}
public String getDialogTitle() {
return "Exercise Instructions";
}
public void negativeCallback() {
}
public boolean positiveCallback() {
//Get our instruction text
EditText routineEditText = (EditText) mInflatedLayout.findViewById(R.id.fragment_new_routine_name_edit_text);
String enteredText = routineEditText.getText().toString();
//Put it into our routine
mRoutineExercise.setInstruction(enteredText);
//Call onactivity result so it can reload our data
getTargetFragment().onActivityResult(REQUEST_SET_INSTRUCTION, RESULT_SET_INSTRUCTION, null);
return true;
}
public String getPositiveText() {
return "Save";
}
public View preCreateDialog(LayoutInflater inflater) {
View v = super.inflateLayout(inflater, R.layout.dialog_new_routine, null);
//Set the instruction, and our edit text hint to nothing.
populateTexts("Enter your instructions for this exercise", "");
//Get our routineexercise object
int rotExId = getArguments().getInt(ROUTINE_EXERCISE_ID);
mRoutineExercise = LiftLogDBAPI.get(getActivity()).getRoutineExerciseById(rotExId);
//Populate the edit text with our existing instruction text
setExistingText();
return v;
}
/*
* Populates our edit text with the existing routine name.
*/
private void setExistingText() {
//Get our edit text
EditText nameBox = (EditText) mInflatedLayout.findViewById(R.id.fragment_new_routine_name_edit_text);
//Set its text to the routine name.
nameBox.setText(mRoutineExercise.getInstruction());
//Set our text box to be left aligned.
nameBox.setGravity(Gravity.LEFT);
//Put our edit text cursor at the end of our string
nameBox.setSelection(nameBox.getText().length());
}
}
public static class NameEditDialog extends NameSelectionDialog {
public static NameSelectionDialog newInstance(int routineId) {
Bundle args = new Bundle();
args.putInt(ROUTINE_ID, routineId);
NameSelectionDialog fragment = new NameEditDialog();
fragment.setArguments(args);
return fragment;
}
public String getDialogTitle() {
return "Edit Routine Name";
}
public void negativeCallback() {
}
public boolean positiveCallback() {
//Get our routine name
EditText routineEditText = (EditText) mInflatedLayout.findViewById(R.id.fragment_new_routine_name_edit_text);
String enteredText = routineEditText.getText().toString();
//Trim off leading and trailing whitespaces
enteredText = enteredText.trim();
//Make sure it's long enough
if (!isLongEnough(enteredText, MIN_ROUTINE_NAME_LENGTH)) {
showErrorText("Your routine name can't be empty.");
return false;
}
//Check if it's the same as our existing routine name. That'll happen when they
//open the edit name box, then press ok. Let's just return true in that case without actually
//modifying our routine's name.
if (enteredText.equals(mRoutine.getName())) {
//Name is unchanged.
return true;
}
//Make sure the name isn't in use
if (!routineNameAvailable(enteredText)) {
showErrorText("That routine name is already in use.");
return false;
}
//Update the routine's name
updateRoutineName(enteredText);
return true;
}
public String getPositiveText() {
return "Edit Routine";
}
/*
* Updates our mRoutine with its new name, then updates
* it in the database.
*/
private void updateRoutineName(String newName) {
//Change the name in mroutine
mRoutine.setName(newName);
//Tell teh hosting fragment we're done
getTargetFragment().onActivityResult(REQUEST_EDIT_ROUTINE_NAME, RESULT_EDIT_ROUTINE, null);
}
public View preCreateDialog(LayoutInflater inflater) {
View v = super.inflateLayout(inflater, R.layout.dialog_new_routine, null);
//Set the instruction, and our edit text hint to nothing.
populateTexts("Choose a new routine name", "");
//Grab our routine into our member var
getRoutine();
//Populate the edit text with our existing routine name.
setExistingName();
return v;
}
/*
* Populates our edit text with the existing routine name.
*/
private void setExistingName() {
//Get our edit text
EditText nameBox = (EditText) mInflatedLayout.findViewById(R.id.fragment_new_routine_name_edit_text);
//Set its text to the routine name.
nameBox.setText(mRoutine.getName());
//Put our edit text cursor at the end of our string
nameBox.setSelection(nameBox.getText().length());
}
}
public static class AddExerciseDialog extends NameSelectionDialog {
public static AddExerciseDialog newInstance(int routineId) {
Bundle args = new Bundle();
args.putInt(ROUTINE_ID, routineId);
AddExerciseDialog fragment = new AddExerciseDialog();
fragment.setArguments(args);
return fragment;
}
public String getDialogTitle() {
return "Add Exercise";
}
public void negativeCallback() {
}
public boolean positiveCallback() {
//Get our edit text string
String enteredText = getEditTextString();
//Trim the text
enteredText = enteredText.trim();
//Make sure it's at least one character long
if (!isLongEnough(enteredText, 1)) {
showErrorText("The exercise name can't be empty.");
return false;
}
//Get the exercise object for this exercise.
Exercise nameCheck = getDBManager().getExerciseByName(enteredText, false);
//Check if the exercise doesn't exist in our DB yet.
if (nameCheck == null) {
//The exercise we want to add isn't an exercise that exists. Add it.
createExercise(enteredText);
} else {
//Name check isn't null. So the exercise exists already. If the name differs
//change it in the DB so all future instances get the new casing.
if (!nameCheck.getName().equals(enteredText)) {
//Casing idffers. Update it.
nameCheck.setName(enteredText);
nameCheck.update();
}
}
//Get the exercise object. We can be case sensitive now as it should exactly match our entry.
Exercise toAdd = getDBManager().getExerciseByName(enteredText, false);
//Make sure it's not null. Shouldn't be under any circumstance.
if (toAdd == null) {
throw new RuntimeException("Created an exercise and inserted it into the database, but immediately after" +
"insertion the exercise can't be retrieved. Exercise name is " + enteredText);
}
//See if this exercise is in our routine already
if (exerciseInRoutine(toAdd)) {
//Print the error text.
showErrorText("The exercise '" + toAdd.getName() + "' is already in this routine.");
return false;
}
//Exercise isn't in our routine, add it.
RoutineExercise newRoutineExercise = new RoutineExercise(getActivity().getApplicationContext(), toAdd.getId(), mRoutine.getId(), 1, 1, null, true);
//Insert the new routine exercise.
newRoutineExercise.insert();
//Call our parent so it knows to update.
getTargetFragment().onActivityResult(REQUEST_ADD_EXERCISE, RESULT_ADD_EXERCISE, null);
return true;
}
/*
* Checks whether the provided exercise is already in our routine.
*/
private boolean exerciseInRoutine(Exercise toAdd) {
//Grab all of our routineexercises
ArrayList<RoutineExercise> rotExArray = getDBManager().getRoutineExercises(mRoutine.getId());
for (RoutineExercise rotEx : rotExArray) {
//check if the exercise is in our routine already
if (rotEx.getExerciseSuper() == toAdd.getId()) {
//Exercise is in our routine already.
return true;
}
}
//Exercise isn't in our routine.
return false;
}
/*
* Creates the exercise and inserts it into the DB.
*/
private void createExercise(String exerciseName) {
new Exercise(getActivity(), exerciseName).insert();
}
public View preCreateDialog(LayoutInflater inflater) {
View v = super.inflateLayout(inflater, R.layout.dialog_add_exercise, null);
//Set the instruction, and our edit text hint to nothing.
populateTexts("Enter the name of the exercise you wish to add.", "Exercise Name");
//Get all exercises
String[] exerciseNames = LiftLogDBAPI.get(getActivity()).getAllExercisesNames();
ArrayAdapter<String> exAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, exerciseNames);
AutoCompleteTextView textView = (AutoCompleteTextView) v.findViewById(R.id.fragment_new_routine_name_edit_text);
textView.setAdapter(exAdapter);
//Grab our routine into our member var
getRoutine();
return v;
}
}
public static class RenameExerciseDialog extends NameSelectionDialog {
private static final String EXERCISE_ID = "com.plined.liftlog.routinefactoryfragment.renameexercisedialog.exerciseid";
private Exercise mExercise;
public static RenameExerciseDialog newInstance(int exerciseId) {
Bundle args = new Bundle();
args.putInt(EXERCISE_ID, exerciseId);
RenameExerciseDialog fragment = new RenameExerciseDialog();
fragment.setArguments(args);
return fragment;
}
public String getDialogTitle() {
return "Rename Exercise";
}
public void negativeCallback() {
}
public boolean positiveCallback() {
//Get our edit text string
String enteredText = getEditTextString();
//Trim the text
enteredText = enteredText.trim();
//Check if we're just recasing the name, or using the same name.
if (enteredText.toLowerCase().equals(mExercise.getName().toLowerCase())) {
//Updat eit and return. No need to check itf it's in use.
mExercise.setName(enteredText);
mExercise.update();
return true;
}
//Make sure it's at least one character long
if (!isLongEnough(enteredText, 1)) {
showErrorText("The exercise name can't be empty.");
return false;
}
//Make sure the name isn't in use
if (LiftLogDBAPI.get(getActivity()).isExNameUsed(enteredText, false)) {
//An exercise already exists with this name.
showErrorText("Exercise name is already in use.");
return false;
}
//Update our name
mExercise.setName(enteredText);
mExercise.update();
//Call our parent so it knows to update.
getTargetFragment().onActivityResult(REQUEST_RENAME_EXERCISE, RESULT_RENAME_EXERCISE, null);
return true;
}
public View preCreateDialog(LayoutInflater inflater) {
View v = super.inflateLayout(inflater, R.layout.dialog_new_routine, null);
//Set the instruction, and our edit text hint to nothing.
populateTexts("Enter an updated name for this exercise", "");
//Get the exercise
mExercise = getExercise();
//Populate the initial name of the exercise with the current name
setExistingName();
return v;
}
/*
* Gets the exercise referred to in our arguments. Throws runtimeexception
* if the exercise doesn't exist.
*/
private Exercise getExercise() {
//Get the argument
int exerciseId = getArguments().getInt(EXERCISE_ID, -1);
//Get the exercise
Exercise toRet = LiftLogDBAPI.get(getActivity()).getExerciseById(exerciseId);
if (toRet == null) {
throw new RuntimeException("Attempting to retrieve an exercise that does not exist. Exercise id is " + exerciseId);
}
return toRet;
}
/*
* Populates our edit text with the existing routine name.
*/
private void setExistingName() {
//Get our edit text
EditText nameBox = (EditText) mInflatedLayout.findViewById(R.id.fragment_new_routine_name_edit_text);
//Set its text to the routine name.
nameBox.setText(mExercise.getName());
//Put our edit text cursor at the end of our string
nameBox.setSelection(nameBox.getText().length());
}
}
private class RoutineExerciseCursorLoader extends SQLiteCursorLoader {
public RoutineExerciseCursorLoader(Context context) {
super(context);
}
@Override
protected Cursor loadCursor() {
//Query the list of runs
return LiftLogDBAPI.get(getContext()).getRoutineExercisesCursor(mRoutineId);
}
}
private class RoutineExerciseCursorAdapter extends CursorAdapter {
private RoutineExerciseCursor mRotExCursor;
//ID of image to use in image view button when expanded
private int EXPANDED_TRUE_IMG_ID = R.drawable.ic_menu_rotate;
private int EXPANDED_FALSE_IMG_ID = R.drawable.ic_menu_more;
public RoutineExerciseCursorAdapter(Context context, RoutineExerciseCursor cursor) {
super(context, cursor, 0);
mRotExCursor = cursor;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//Use a layout inflater to get a row view
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.t_routine_factory_container, parent, false);
}
public void reloadData() {
changeCursor(new RoutineExerciseCursorLoader(getActivity()).loadCursor());
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
//Get the run for the current row
RoutineExercise rotEx = ((RoutineExerciseCursor)cursor).getRoutineExercise();
wireTitle(view, rotEx);
setVisibility(view, rotEx);
wirePositionText(view.findViewById(R.id.t_routine_factory_container_position), rotEx);
wireSetText(view.findViewById(R.id.t_routine_factory_container_sets), rotEx);
wireInstructionText((TextView) view.findViewById(R.id.t_routine_factory_container_instructions_body), rotEx);
wireListeners(view, rotEx);
}
/*
* Sets the text body of our instruction text (if there is any). Hides the text
* body portion if there's no instruction text.
*/
private void wireInstructionText(TextView instructionTv, RoutineExercise rotEx) {
if (rotEx.getInstruction() != null && rotEx.getInstruction().length() > 0) {
//There's an instruction.
//Populate it
instructionTv.setText(rotEx.getInstruction());
//Make sure it's visible
instructionTv.setVisibility(View.VISIBLE);
} else {
//There's no instruction. Make the body gone.
instructionTv.setVisibility(View.GONE);
}
}
/*
* Populates the position text labels (left and right)
*/
private void wirePositionText(View rotExView, RoutineExercise rotEx) {
setLabels(rotExView, "Position", rotEx.getPosition()+"");
}
/*
* Populates the position text labels (left and right)
*/
private void wireSetText(View rotExView, RoutineExercise rotEx) {
setLabels(rotExView, "Sets", rotEx.getNumSets()+"");
}
/*
* Sets label with the provided values. Both set and position can use this.
*/
private void setLabels(View relativeRoot, String leftLabel, String rightLabel) {
//Get a reference to our left label
TextView leftTv = (TextView) relativeRoot.findViewById(R.id.t_routine_factory_bodyrow_leftText);
leftTv.setText(leftLabel);
//Get a reference to our right label.
TextView rightTv = (TextView) relativeRoot.findViewById(R.id.t_routine_factory_bodyrow_right_text);
rightTv.setText(rightLabel);
}
/*
* Sets the visibility of the body and divider based on the value in our routine exercise.
*/
private void setVisibility(View rotExView, RoutineExercise rotEx) {
//Get the two views we need to manipulate
View bodyView = rotExView.findViewById(R.id.t_routine_factory_container_lay_body);
//Get the iamge view of the expand button
ImageView expandButton = (ImageView) rotExView.findViewById(R.id.t_routine_factory_container_header_expand);
if (rotEx.isExpanded()) {
//It should be visible.
bodyView.setVisibility(View.VISIBLE);
//Set our imageView
expandButton.setImageResource(EXPANDED_TRUE_IMG_ID);
} else {
//It should be invisible.
bodyView.setVisibility(View.GONE);
//Set our imageView
expandButton.setImageResource(EXPANDED_FALSE_IMG_ID);
}
}
/*
* Adds onclick listeners for all four of the image views.
*/
private void wireListeners(View view, RoutineExercise rotEx) {
//Get references to our relative layouts holding the labels.
View positionRel = view.findViewById(R.id.t_routine_factory_container_position);
View setRel = view.findViewById(R.id.t_routine_factory_container_sets);
/*
* Get position image views
*/
//Get the two image views from mit
ImageView posMinus = (ImageView) positionRel.findViewById(R.id.t_routine_factory_bodyrow_right_minus);
ImageView posPlus = (ImageView) positionRel.findViewById(R.id.t_routine_factory_bodyrow_right_plus);
/*
* Get set image views
*/
//Set view box holds the right side box that ocntains the 2 IV and 1 TV
ImageView setMinus = (ImageView) setRel.findViewById(R.id.t_routine_factory_bodyrow_right_minus);
ImageView setPlus = (ImageView) setRel.findViewById(R.id.t_routine_factory_bodyrow_right_plus);
/*
* Get teh expanded image view
*/
ImageView setExpanded = (ImageView) view.findViewById(R.id.t_routine_factory_container_header_expand);
/*
* Get the entire body that contains the instructions component. We'll make all of it an onclick listener.
*/
View instructionBox = view.findViewById(R.id.t_routine_factory_container_lay_instructions);
//Construct our onclick listener object
ExerciseClickWrapper clickWrapper = new ExerciseClickWrapper(rotEx, setMinus, setPlus, posMinus, posPlus, setExpanded, instructionBox);
//Add it as our listener for every single one
registerOnClickListener(posMinus, clickWrapper);
registerOnClickListener(posPlus, clickWrapper);
registerOnClickListener(setMinus, clickWrapper);
registerOnClickListener(setPlus, clickWrapper);
registerOnClickListener(setExpanded, clickWrapper);
registerOnClickListener(instructionBox, clickWrapper);
}
private void registerOnClickListener(View toListen, ExerciseClickWrapper clickWrapper) {
toListen.setOnClickListener(clickWrapper);
}
/*
* Wires up the exercise title.
*/
private void wireTitle(View rotExView, RoutineExercise rotEx) {
//Get the name of the exercise that corresponds to this routineexercise.
Exercise parentExercise = mDbHelper.getRotExSuperEx(rotEx);
//Get the title text view.
TextView exTitleTv = (TextView) rotExView.findViewById(R.id.t_routine_factory_container_header_name);
//Set the title text view to our exercise. Basing name on whether it's expanded or not.
if (rotEx.isExpanded()) {
//We're expanded, don't include detialsa bout the number of sets.
exTitleTv.setText(parentExercise.getName());
} else {
//Not expanded. Add detailsa bout set count.
String setTerm; //Holds the pluralization of our set.
if (rotEx.getNumSets() == 1) {
setTerm = "set";
} else {
setTerm = "sets";
}
exTitleTv.setText(rotEx.getNumSets() + " " + setTerm + ": " + parentExercise.getName());
}
}
}
public static class ConfirmDeleteRotEx extends ConfirmationDialog {
View mInflatedLayout;
private static final String FRAGMENT_ROUTINE_EXERCISE_ID = "com.plined.liftlog.confirmdeleterotex.fragmentroutineid";
public static ConfirmDeleteRotEx newInstance(int routineExerciseId) {
Bundle args = new Bundle();
args.putInt(FRAGMENT_ROUTINE_EXERCISE_ID, routineExerciseId);
ConfirmDeleteRotEx fragment = new ConfirmDeleteRotEx();
fragment.setArguments(args);
return fragment;
}
public String getDialogTitle() {
return "Remove Exercise";
}
public void negativeCallback() {
}
public boolean positiveCallback() {
//Get the id of the routine exercise to delete
int idToDel = getRoutineExerciseId();
//get the associated routine exercise
RoutineExercise toDel = LiftLogDBAPI.get(getActivity()).getRoutineExerciseById(idToDel);
if (toDel == null) {
throw new RuntimeException("Attempting to delete routine exercise, but its result is null. ID is " + idToDel);
}
//Delete it
toDel.delete();
//Call onactivityresult so it knows to update.
getTargetFragment().onActivityResult(getTargetRequestCode(), RESULT_DELETE_EXERCISE, null);
return true;
}
/*
* Returns the routine ID passed to this confirm dialog.
*/
private int getRoutineExerciseId() {
//Get our arguments
Bundle args = getArguments();
//Parse out the routine ID
int rotId = args.getInt(FRAGMENT_ROUTINE_EXERCISE_ID, -1);
//Check that we got a rotid
if (rotId == -1) {
//Didn't get ar otId
throw new RuntimeException("Attempting to delete a routine exercise with routine exercise ID -1.");
}
//Return it
return rotId;
}
public String getPositiveText() {
return "Yes";
}
public String getNegativeText() {
return "No";
}
public View preCreateDialog(LayoutInflater inflater) {
mInflatedLayout = super.inflateLayout(inflater, R.layout.dialog_confirm, null);
//Popuilate our text boxes.
setConfirmTopText("Are you sure you want to remove the selected exercise from this routine?");
setConfirmBottomText(null);
return mInflatedLayout;
}
}
public class ExerciseClickWrapper implements View.OnClickListener {
RoutineExercise mRoutineExercise;
ImageView mSetMinus;
ImageView mSetPlus;
ImageView mPositionMinus;
ImageView mPositionPlus;
ImageView mSetVisibility;
View mInstructionBox;
public ExerciseClickWrapper(RoutineExercise routine, ImageView setMin, ImageView setPlu, ImageView posMin, ImageView posPlu, ImageView setVisibility, View instructionBox) {
mRoutineExercise = routine;
mSetMinus = setMin;
mSetPlus = setPlu;
mPositionMinus = posMin;
mPositionPlus = posPlu;
mSetVisibility = setVisibility;
mInstructionBox = instructionBox;
}
@Override
public void onClick(View v) {
//Figure out which imageview was clicked
if (v == mSetMinus) {
mRoutineExercise.decrementSetCount();
} else if (v == mSetPlus) {
mRoutineExercise.incrementSetCount();
} else if (v == mPositionMinus) {
mRoutineExercise.decrementPosition();
} else if (v == mPositionPlus) {
mRoutineExercise.incrementPosition();
} else if (v == mSetVisibility) {
//Reverse the expanded state
mRoutineExercise.setExpanded(!mRoutineExercise.isExpanded());
//Reload our data
} else if (v == mInstructionBox) {
//Got an onclick listener on the instruction box.
showInstructionDialog();
}
else {
throw new RuntimeException("Had an onclick event from an unexpected source.");
}
//Force our adapter to update with new data.
mAdapter.reloadData();
}
/*
* Launches an instruction dialog box.
*/
private void showInstructionDialog() {
//Create the fragment. We'll attach our current routine ID with it so it knows what to edit.
InstructionEditDialog fragToUse = InstructionEditDialog.newInstance(mRoutineExercise.getId());
//Launch this fragment.
launchDialogFragmentTarget(fragToUse, "editsetinstruction", REQUEST_SET_INSTRUCTION);
}
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.heneryh.aquanotes.ui;
import com.heneryh.aquanotes.R;
import com.heneryh.aquanotes.provider.AquaNotesDbContract;
import com.heneryh.aquanotes.util.ActivityHelper;
import com.heneryh.aquanotes.util.AnalyticsUtils;
import com.heneryh.aquanotes.util.BitmapUtils;
import com.heneryh.aquanotes.util.FractionalTouchDelegate;
import com.heneryh.aquanotes.util.NotifyingAsyncQueryHandler;
import com.heneryh.aquanotes.util.ParserUtils;
import com.heneryh.aquanotes.util.UIUtils;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
/**
* A fragment that shows detail information for a sandbox company, including company name,
* description, product description, logo, etc.
*/
public class VendorDetailFragment extends Fragment implements
NotifyingAsyncQueryHandler.AsyncQueryListener,
CompoundButton.OnCheckedChangeListener {
private static final String TAG = "VendorDetailFragment";
private Uri mVendorUri;
private String mTrackId;
private ViewGroup mRootView;
private TextView mName;
private CompoundButton mStarred;
private ImageView mLogo;
private TextView mUrl;
private TextView mDesc;
private TextView mProductDesc;
private String mNameString;
private NotifyingAsyncQueryHandler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
mVendorUri = intent.getData();
if (mVendorUri== null) {
return;
}
setHasOptionsMenu(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mVendorUri == null) {
return;
}
// Start background query to load vendor details
mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this);
mHandler.startQuery(mVendorUri, VendorsQuery.PROJECTION);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_vendor_detail, null);
mName = (TextView) mRootView.findViewById(R.id.vendor_name);
mStarred = (CompoundButton) mRootView.findViewById(R.id.star_button);
mStarred.setFocusable(true);
mStarred.setClickable(true);
// Larger target triggers star toggle
final View starParent = mRootView.findViewById(R.id.header_vendor);
FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f));
mLogo = (ImageView) mRootView.findViewById(R.id.vendor_logo);
mUrl = (TextView) mRootView.findViewById(R.id.vendor_url);
mDesc = (TextView) mRootView.findViewById(R.id.vendor_desc);
mProductDesc = (TextView) mRootView.findViewById(R.id.vendor_product_desc);
return mRootView;
}
/**
* Build a {@link android.view.View} to be used as a tab indicator, setting the requested string resource as
* its label.
*
* @return View
*/
private View buildIndicator(int textRes) {
final TextView indicator = (TextView) getActivity().getLayoutInflater()
.inflate(R.layout.tab_indicator,
(ViewGroup) mRootView.findViewById(android.R.id.tabs), false);
indicator.setText(textRes);
return indicator;
}
/**
* {@inheritDoc}
*/
public void onQueryComplete(int token, Object cookie, Cursor cursor) {
if (getActivity() == null) {
return;
}
try {
if (!cursor.moveToFirst()) {
return;
}
mNameString = cursor.getString(VendorsQuery.NAME);
mName.setText(mNameString);
// Unregister around setting checked state to avoid triggering
// listener since change isn't user generated.
mStarred.setOnCheckedChangeListener(null);
mStarred.setChecked(cursor.getInt(VendorsQuery.STARRED) != 0);
mStarred.setOnCheckedChangeListener(this);
// Start background fetch to load vendor logo
final String logoUrl = cursor.getString(VendorsQuery.LOGO_URL);
if (!TextUtils.isEmpty(logoUrl)) {
BitmapUtils.fetchImage(getActivity(), logoUrl, null, null,
new BitmapUtils.OnFetchCompleteListener() {
public void onFetchComplete(Object cookie, Bitmap result) {
if (result == null) {
mLogo.setVisibility(View.GONE);
} else {
mLogo.setVisibility(View.VISIBLE);
mLogo.setImageBitmap(result);
}
}
});
}
mUrl.setText(cursor.getString(VendorsQuery.URL));
mDesc.setText(cursor.getString(VendorsQuery.DESC));
mProductDesc.setText(cursor.getString(VendorsQuery.PRODUCT_DESC));
mTrackId = cursor.getString(VendorsQuery.TRACK_ID);
// Assign track details when found
// TODO: handle vendors not attached to track
ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper();
activityHelper.setActionBarTitle(cursor.getString(VendorsQuery.TRACK_NAME));
activityHelper.setActionBarColor(cursor.getInt(VendorsQuery.TRACK_COLOR));
AnalyticsUtils.getInstance(getActivity()).trackPageView(
"/Sandbox/Vendors/" + mNameString);
} finally {
cursor.close();
}
}
/**
* Handle toggling of starred checkbox.
*/
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final ContentValues values = new ContentValues();
values.put(AquaNotesDbContract.Vendors.VENDOR_STARRED, isChecked ? 1 : 0);
mHandler.startUpdate(mVendorUri, values);
AnalyticsUtils.getInstance(getActivity()).trackEvent(
"Sandbox", isChecked ? "Starred" : "Unstarred", mNameString, 0);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.map_menu_items, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_map) {
// The room ID for the sandbox, in the map, is just the track ID
final Intent intent = new Intent(getActivity().getApplicationContext(),
UIUtils.getMapActivityClass(getActivity()));
intent.putExtra(MapFragment.EXTRA_ROOM,
ParserUtils.translateTrackIdAliasInverse(mTrackId));
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* {@link com.heneryh.aquanotes.provider.AquaNotesDbContract.Vendors} query parameters.
*/
private interface VendorsQuery {
String[] PROJECTION = {
AquaNotesDbContract.Vendors.VENDOR_NAME,
AquaNotesDbContract.Vendors.VENDOR_LOCATION,
AquaNotesDbContract.Vendors.VENDOR_DESC,
AquaNotesDbContract.Vendors.VENDOR_URL,
AquaNotesDbContract.Vendors.VENDOR_PRODUCT_DESC,
AquaNotesDbContract.Vendors.VENDOR_LOGO_URL,
AquaNotesDbContract.Vendors.VENDOR_STARRED,
AquaNotesDbContract.Vendors.TRACK_ID,
AquaNotesDbContract.Tracks.TRACK_NAME,
AquaNotesDbContract.Tracks.TRACK_COLOR,
};
int NAME = 0;
int LOCATION = 1;
int DESC = 2;
int URL = 3;
int PRODUCT_DESC = 4;
int LOGO_URL = 5;
int STARRED = 6;
int TRACK_ID = 7;
int TRACK_NAME = 8;
int TRACK_COLOR = 9;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.segment.filter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import it.unimi.dsi.fastutil.ints.IntIterable;
import it.unimi.dsi.fastutil.ints.IntIterator;
import org.apache.druid.collections.bitmap.ImmutableBitmap;
import org.apache.druid.common.config.NullHandling;
import org.apache.druid.query.BitmapResultFactory;
import org.apache.druid.query.extraction.ExtractionFn;
import org.apache.druid.query.filter.BitmapIndexSelector;
import org.apache.druid.query.filter.Filter;
import org.apache.druid.query.filter.FilterTuning;
import org.apache.druid.query.filter.LikeDimFilter;
import org.apache.druid.query.filter.ValueMatcher;
import org.apache.druid.query.filter.vector.VectorValueMatcher;
import org.apache.druid.query.filter.vector.VectorValueMatcherColumnProcessorFactory;
import org.apache.druid.segment.ColumnSelector;
import org.apache.druid.segment.ColumnSelectorFactory;
import org.apache.druid.segment.DimensionHandlerUtils;
import org.apache.druid.segment.column.BitmapIndex;
import org.apache.druid.segment.data.CloseableIndexed;
import org.apache.druid.segment.data.Indexed;
import org.apache.druid.segment.vector.VectorColumnSelectorFactory;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.NoSuchElementException;
import java.util.Set;
public class LikeFilter implements Filter
{
private final String dimension;
private final ExtractionFn extractionFn;
private final LikeDimFilter.LikeMatcher likeMatcher;
private final FilterTuning filterTuning;
public LikeFilter(
final String dimension,
final ExtractionFn extractionFn,
final LikeDimFilter.LikeMatcher likeMatcher,
final FilterTuning filterTuning
)
{
this.dimension = dimension;
this.extractionFn = extractionFn;
this.likeMatcher = likeMatcher;
this.filterTuning = filterTuning;
}
@Override
public <T> T getBitmapResult(BitmapIndexSelector selector, BitmapResultFactory<T> bitmapResultFactory)
{
return bitmapResultFactory.unionDimensionValueBitmaps(getBitmapIterable(selector));
}
@Override
public double estimateSelectivity(BitmapIndexSelector selector)
{
return Filters.estimateSelectivity(getBitmapIterable(selector).iterator(), selector.getNumRows());
}
@Override
public ValueMatcher makeMatcher(ColumnSelectorFactory factory)
{
return Filters.makeValueMatcher(factory, dimension, likeMatcher.predicateFactory(extractionFn));
}
@Override
public VectorValueMatcher makeVectorMatcher(final VectorColumnSelectorFactory factory)
{
return DimensionHandlerUtils.makeVectorProcessor(
dimension,
VectorValueMatcherColumnProcessorFactory.instance(),
factory
).makeMatcher(likeMatcher.predicateFactory(extractionFn));
}
@Override
public boolean canVectorizeMatcher()
{
return true;
}
@Override
public Set<String> getRequiredColumns()
{
return ImmutableSet.of(dimension);
}
@Override
public boolean supportsBitmapIndex(BitmapIndexSelector selector)
{
return selector.getBitmapIndex(dimension) != null;
}
@Override
public boolean shouldUseBitmapIndex(BitmapIndexSelector selector)
{
return Filters.shouldUseBitmapIndex(this, selector, filterTuning);
}
@Override
public boolean supportsSelectivityEstimation(ColumnSelector columnSelector, BitmapIndexSelector indexSelector)
{
return Filters.supportsSelectivityEstimation(this, dimension, columnSelector, indexSelector);
}
private Iterable<ImmutableBitmap> getBitmapIterable(final BitmapIndexSelector selector)
{
if (isSimpleEquals()) {
// Verify that dimension equals prefix.
return ImmutableList.of(
selector.getBitmapIndex(
dimension,
NullHandling.emptyToNullIfNeeded(likeMatcher.getPrefix())
)
);
} else if (isSimplePrefix()) {
// Verify that dimension startsWith prefix, and is accepted by likeMatcher.matchesSuffixOnly.
final BitmapIndex bitmapIndex = selector.getBitmapIndex(dimension);
if (bitmapIndex == null) {
// Treat this as a column full of nulls
return ImmutableList.of(likeMatcher.matches(null) ? Filters.allTrue(selector) : Filters.allFalse(selector));
}
// search for start, end indexes in the bitmaps; then include all matching bitmaps between those points
try (final CloseableIndexed<String> dimValues = selector.getDimensionValues(dimension)) {
// Union bitmaps for all matching dimension values in range.
// Use lazy iterator to allow unioning bitmaps one by one and avoid materializing all of them at once.
return Filters.bitmapsFromIndexes(getDimValueIndexIterableForPrefixMatch(bitmapIndex, dimValues), bitmapIndex);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
} else {
// fallback
return Filters.matchPredicateNoUnion(
dimension,
selector,
likeMatcher.predicateFactory(extractionFn).makeStringPredicate()
);
}
}
/**
* Returns true if this filter is a simple equals filter: dimension = 'value' with no extractionFn.
*/
private boolean isSimpleEquals()
{
return extractionFn == null && likeMatcher.getSuffixMatch() == LikeDimFilter.LikeMatcher.SuffixMatch.MATCH_EMPTY;
}
/**
* Returns true if this filter is a simple prefix filter: dimension startsWith 'value' with no extractionFn.
*/
private boolean isSimplePrefix()
{
return extractionFn == null && !likeMatcher.getPrefix().isEmpty();
}
private IntIterable getDimValueIndexIterableForPrefixMatch(
final BitmapIndex bitmapIndex,
final Indexed<String> dimValues
)
{
final String lower = NullHandling.nullToEmptyIfNeeded(likeMatcher.getPrefix());
final String upper = NullHandling.nullToEmptyIfNeeded(likeMatcher.getPrefix()) + Character.MAX_VALUE;
final int startIndex; // inclusive
final int endIndex; // exclusive
if (lower == null) {
// For Null values
startIndex = bitmapIndex.getIndex(null);
endIndex = startIndex + 1;
} else {
final int lowerFound = bitmapIndex.getIndex(lower);
startIndex = lowerFound >= 0 ? lowerFound : -(lowerFound + 1);
final int upperFound = bitmapIndex.getIndex(upper);
endIndex = upperFound >= 0 ? upperFound + 1 : -(upperFound + 1);
}
return new IntIterable()
{
@Override
public IntIterator iterator()
{
return new IntIterator()
{
int currIndex = startIndex;
int found;
{
found = findNext();
}
private int findNext()
{
while (currIndex < endIndex && !likeMatcher.matchesSuffixOnly(dimValues, currIndex)) {
currIndex++;
}
if (currIndex < endIndex) {
return currIndex++;
} else {
return -1;
}
}
@Override
public boolean hasNext()
{
return found != -1;
}
@Override
public int nextInt()
{
int cur = found;
if (cur == -1) {
throw new NoSuchElementException();
}
found = findNext();
return cur;
}
};
}
};
}
}
| |
/*
* Copyright 2018 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 androidx.mediarouter.app;
import android.app.Dialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.ProgressBar;
import androidx.annotation.IntDef;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.mediarouter.R;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
final class MediaRouterThemeHelper {
private static final float MIN_CONTRAST = 3.0f;
@IntDef({COLOR_DARK_ON_LIGHT_BACKGROUND, COLOR_WHITE_ON_DARK_BACKGROUND})
@Retention(RetentionPolicy.SOURCE)
private @interface ControllerColorType {}
static final int COLOR_DARK_ON_LIGHT_BACKGROUND = 0xDE000000; /* Opacity of 87% */
static final int COLOR_WHITE_ON_DARK_BACKGROUND = Color.WHITE;
private static final int COLOR_DARK_ON_LIGHT_BACKGROUND_RES_ID =
R.color.mr_dynamic_dialog_icon_light;
private MediaRouterThemeHelper() {
}
static Drawable getMuteButtonDrawableIcon(Context context) {
return getIconByDrawableId(context, R.drawable.mr_cast_mute_button);
}
static Drawable getCheckBoxDrawableIcon(Context context) {
return getIconByDrawableId(context, R.drawable.mr_cast_checkbox);
}
static Drawable getDefaultDrawableIcon(Context context) {
return getIconByAttrId(context, R.attr.mediaRouteDefaultIconDrawable);
}
static Drawable getTvDrawableIcon(Context context) {
return getIconByAttrId(context, R.attr.mediaRouteTvIconDrawable);
}
static Drawable getSpeakerDrawableIcon(Context context) {
return getIconByAttrId(context, R.attr.mediaRouteSpeakerIconDrawable);
}
static Drawable getSpeakerGroupDrawableIcon(Context context) {
return getIconByAttrId(context, R.attr.mediaRouteSpeakerGroupIconDrawable);
}
private static Drawable getIconByDrawableId(Context context, int drawableId) {
Drawable icon = AppCompatResources.getDrawable(context, drawableId);
icon = DrawableCompat.wrap(icon);
if (isLightTheme(context)) {
int tintColor = ContextCompat.getColor(context, COLOR_DARK_ON_LIGHT_BACKGROUND_RES_ID);
DrawableCompat.setTint(icon, tintColor);
}
return icon;
}
private static Drawable getIconByAttrId(Context context, int attrId) {
TypedArray styledAttributes = context.obtainStyledAttributes(new int[] { attrId });
Drawable icon = AppCompatResources.getDrawable(context,
styledAttributes.getResourceId(0, 0));
icon = DrawableCompat.wrap(icon);
// Since Chooser(Controller)Dialog and DevicePicker(Cast)Dialog is using same shape but
// different color icon for LightTheme, change color of the icon for the latter.
if (isLightTheme(context)) {
int tintColor = ContextCompat.getColor(context, COLOR_DARK_ON_LIGHT_BACKGROUND_RES_ID);
DrawableCompat.setTint(icon, tintColor);
}
styledAttributes.recycle();
return icon;
}
static Context createThemedButtonContext(Context context) {
// Apply base Media Router theme.
context = new ContextThemeWrapper(context, getRouterThemeId(context));
// Apply custom Media Router theme.
int style = getThemeResource(context, R.attr.mediaRouteTheme);
if (style != 0) {
context = new ContextThemeWrapper(context, style);
}
return context;
}
/*
* The following two methods are to be used in conjunction. They should be used to prepare
* the context and theme for a super class constructor (the latter method relies on the
* former method to properly prepare the context):
* super(context = createThemedDialogContext(context, theme),
* createThemedDialogStyle(context));
*
* It will apply theme in the following order (style lookups will be done in reverse):
* 1) Current theme
* 2) Supplied theme
* 3) Base Media Router theme
* 4) Custom Media Router theme, if provided
*/
static Context createThemedDialogContext(Context context, int theme, boolean alertDialog) {
// 1) Current theme is already applied to the context
// 2) If no theme is supplied, look it up from the context (dialogTheme/alertDialogTheme)
if (theme == 0) {
theme = getThemeResource(context, !alertDialog
? androidx.appcompat.R.attr.dialogTheme
: androidx.appcompat.R.attr.alertDialogTheme);
}
// Apply it
context = new ContextThemeWrapper(context, theme);
// 3) If a custom Media Router theme is provided then apply the base theme
if (getThemeResource(context, R.attr.mediaRouteTheme) != 0) {
context = new ContextThemeWrapper(context, getRouterThemeId(context));
}
return context;
}
// This method should be used in conjunction with the previous method.
static int createThemedDialogStyle(Context context) {
// 4) Apply the custom Media Router theme
int theme = getThemeResource(context, R.attr.mediaRouteTheme);
if (theme == 0) {
// 3) No custom MediaRouther theme was provided so apply the base theme instead
theme = getRouterThemeId(context);
}
return theme;
}
// END. Previous two methods should be used in conjunction.
static int getThemeResource(Context context, int attr) {
TypedValue value = new TypedValue();
return context.getTheme().resolveAttribute(attr, value, true) ? value.resourceId : 0;
}
static float getDisabledAlpha(Context context) {
TypedValue value = new TypedValue();
return context.getTheme().resolveAttribute(android.R.attr.disabledAlpha, value, true)
? value.getFloat() : 0.5f;
}
static @ControllerColorType int getControllerColor(Context context, int style) {
int primaryColor = getThemeColor(context, style,
androidx.appcompat.R.attr.colorPrimary);
if (ColorUtils.calculateContrast(COLOR_WHITE_ON_DARK_BACKGROUND, primaryColor)
>= MIN_CONTRAST) {
return COLOR_WHITE_ON_DARK_BACKGROUND;
}
return COLOR_DARK_ON_LIGHT_BACKGROUND;
}
static int getButtonTextColor(Context context) {
int primaryColor = getThemeColor(context, 0,
androidx.appcompat.R.attr.colorPrimary);
int backgroundColor = getThemeColor(context, 0, android.R.attr.colorBackground);
if (ColorUtils.calculateContrast(primaryColor, backgroundColor) < MIN_CONTRAST) {
// Default to colorAccent if the contrast ratio is low.
return getThemeColor(context, 0, androidx.appcompat.R.attr.colorAccent);
}
return primaryColor;
}
static TypedArray getStyledAttributes(Context context) {
TypedArray styledAttributes = context.obtainStyledAttributes(new int[] {
R.attr.mediaRouteDefaultIconDrawable,
R.attr.mediaRouteTvIconDrawable,
R.attr.mediaRouteSpeakerIconDrawable,
R.attr.mediaRouteSpeakerGroupIconDrawable});
return styledAttributes;
}
static void setDialogBackgroundColor(Context context, Dialog dialog) {
View dialogView = dialog.getWindow().getDecorView();
int backgroundColor = ContextCompat.getColor(context, isLightTheme(context)
? R.color.mr_dynamic_dialog_background_light
: R.color.mr_dynamic_dialog_background_dark);
dialogView.setBackgroundColor(backgroundColor);
}
static void setMediaControlsBackgroundColor(
Context context, View mainControls, View groupControls, boolean hasGroup) {
int primaryColor = getThemeColor(context, 0,
androidx.appcompat.R.attr.colorPrimary);
int primaryDarkColor = getThemeColor(context, 0,
androidx.appcompat.R.attr.colorPrimaryDark);
if (hasGroup && getControllerColor(context, 0) == COLOR_DARK_ON_LIGHT_BACKGROUND) {
// Instead of showing dark controls in a possibly dark (i.e. the primary dark), model
// the white dialog and use the primary color for the group controls.
primaryDarkColor = primaryColor;
primaryColor = Color.WHITE;
}
mainControls.setBackgroundColor(primaryColor);
groupControls.setBackgroundColor(primaryDarkColor);
// Also store the background colors to the view tags. They are used in
// setVolumeSliderColor() below.
mainControls.setTag(primaryColor);
groupControls.setTag(primaryDarkColor);
}
/**
* This method is used by MediaRouteControllerDialog to set color of the volume slider
* appropriate for the color of controller and backgroundView.
*/
static void setVolumeSliderColor(
Context context, MediaRouteVolumeSlider volumeSlider, View backgroundView) {
int controllerColor = getControllerColor(context, 0);
if (Color.alpha(controllerColor) != 0xFF) {
// Composite with the background in order not to show the underlying progress bar
// through the thumb.
int backgroundColor = (int) backgroundView.getTag();
controllerColor = ColorUtils.compositeColors(controllerColor, backgroundColor);
}
volumeSlider.setColor(controllerColor);
}
/**
* This method is used by MediaRouteDynamicControllerDialog to set color of the volume slider
* according to current theme.
*/
static void setVolumeSliderColor(Context context, MediaRouteVolumeSlider volumeSlider) {
int progressAndThumbColor, backgroundColor;
if (isLightTheme(context)) {
progressAndThumbColor = ContextCompat.getColor(context,
R.color.mr_cast_progressbar_progress_and_thumb_light);
backgroundColor = ContextCompat.getColor(context,
R.color.mr_cast_progressbar_background_light);
} else {
progressAndThumbColor = ContextCompat.getColor(context,
R.color.mr_cast_progressbar_progress_and_thumb_dark);
backgroundColor = ContextCompat.getColor(context,
R.color.mr_cast_progressbar_background_dark);
}
volumeSlider.setColor(progressAndThumbColor, backgroundColor);
}
static void setIndeterminateProgressBarColor(Context context, ProgressBar progressBar) {
if (!progressBar.isIndeterminate()) {
return;
}
int progressColor = ContextCompat.getColor(context, isLightTheme(context)
? R.color.mr_cast_progressbar_progress_and_thumb_light :
R.color.mr_cast_progressbar_progress_and_thumb_dark);
progressBar.getIndeterminateDrawable().setColorFilter(progressColor,
PorterDuff.Mode.SRC_IN);
}
private static boolean isLightTheme(Context context) {
TypedValue value = new TypedValue();
return context.getTheme().resolveAttribute(androidx.appcompat.R.attr.isLightTheme,
value, true) && value.data != 0;
}
private static int getThemeColor(Context context, int style, int attr) {
if (style != 0) {
int[] attrs = { attr };
TypedArray ta = context.obtainStyledAttributes(style, attrs);
int color = ta.getColor(0, 0);
ta.recycle();
if (color != 0) {
return color;
}
}
TypedValue value = new TypedValue();
context.getTheme().resolveAttribute(attr, value, true);
if (value.resourceId != 0) {
return context.getResources().getColor(value.resourceId);
}
return value.data;
}
private static int getRouterThemeId(Context context) {
int themeId;
if (isLightTheme(context)) {
if (getControllerColor(context, 0) == COLOR_DARK_ON_LIGHT_BACKGROUND) {
themeId = R.style.Theme_MediaRouter_Light;
} else {
themeId = R.style.Theme_MediaRouter_Light_DarkControlPanel;
}
} else {
if (getControllerColor(context, 0) == COLOR_DARK_ON_LIGHT_BACKGROUND) {
themeId = R.style.Theme_MediaRouter_LightControlPanel;
} else {
themeId = R.style.Theme_MediaRouter;
}
}
return themeId;
}
}
| |
/*
Copyright 2013 Nationale-Nederlanden
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nl.nn.adapterframework.jms;
import java.io.IOException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.util.ClassUtils;
import nl.nn.adapterframework.util.CredentialFactory;
import nl.nn.adapterframework.util.LogUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
/**
* Provides all JNDI functions and is meant to act as a base class.
*
* <p><b>Configuration:</b>
* <table border="1">
* <tr><th>attributes</th><th>description</th><th>default</th></tr>
* <tr><td>classname</td><td>nl.nn.adapterframework.jms.JNDIBase</td><td> </td></tr>
* <tr><td>{@link #setProviderURL(String) providerURL}</td><td> </td><td> </td></tr>
* <tr><td>{@link #setInitialContextFactoryName(String) initialContextFactoryName}</td><td>class to use as initial context factory</td><td> </td></tr>
* <tr><td>{@link #setAuthentication(String) authentication}</td><td>maps to the field Context.SECURITY_AUTHENTICATION</td><td> </td></tr>
* <tr><td>{@link #setPrincipal(String) principal}</td><td>username to connect to context, maps to Context.SECURITY_PRINCIPAL</td><td> </td></tr>
* <tr><td>{@link #setCredentials(String) credentials}</td><td>username to connect to context, maps to Context.SECURITY_CREDENTIALS</td><td> </td></tr>
* <tr><td>{@link #setJndiAuthAlias(String) jndiAuthAlias}</td><td>Authentication alias, may be used to override principal and credential-settings</td><td> </td></tr>
* <tr><td>{@link #setUrlPkgPrefixes(String) urlPkgPrefixes}</td><td>maps to the field Context.URL_PKG_PREFIXES</td><td> </td></tr>
* <tr><td>{@link #setSecurityProtocol(String) securityProtocol}</td><td>maps to the field Context.SECURITY_PROTOCOL</td><td> </td></tr>
* </table>
* </p>
* <br/>
* @version $Id$
* @author Johan Verrips IOS
*/
public class JNDIBase {
protected Logger log = LogUtil.getLogger(this);
// JNDI
private String providerURL = null;
private String initialContextFactoryName = null;
private String authentication = null;
private String principal = null;
private String credentials = null;
private String jndiAuthAlias = null;
private String jmsRealmName = null;
private String urlPkgPrefixes = null;
private String securityProtocol = null;
private String jndiContextPrefix = "";
private String jndiProperties = null;
private Context context = null;
public void closeContext() throws javax.naming.NamingException {
if (null != context) {
log.debug("closing JNDI-context");
context.close();
context = null;
}
}
protected Hashtable getJndiEnv() throws NamingException {
Properties jndiEnv = new Properties();
if (StringUtils.isNotEmpty(getJndiProperties())) {
URL url = ClassUtils.getResourceURL(this, getJndiProperties());
if (url==null) {
throw new NamingException("cannot find jndiProperties from ["+getJndiProperties()+"]");
}
try {
jndiEnv.load(url.openStream());
} catch (IOException e) {
throw new NamingException("cannot load jndiProperties ["+getJndiProperties()+"] from url ["+url.toString()+"]");
}
}
if (getInitialContextFactoryName() != null)
jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactoryName());
if (getProviderURL() != null)
jndiEnv.put(Context.PROVIDER_URL, getProviderURL());
if (getAuthentication() != null)
jndiEnv.put(Context.SECURITY_AUTHENTICATION, getAuthentication());
if (getPrincipal() != null || getCredentials() != null || getJndiAuthAlias()!=null) {
CredentialFactory jndiCf = new CredentialFactory(getJndiAuthAlias(), getPrincipal(), getCredentials());
if (StringUtils.isNotEmpty(jndiCf.getUsername()))
jndiEnv.put(Context.SECURITY_PRINCIPAL, jndiCf.getUsername());
if (StringUtils.isNotEmpty(jndiCf.getPassword()))
jndiEnv.put(Context.SECURITY_CREDENTIALS, jndiCf.getPassword());
}
if (getUrlPkgPrefixes() != null)
jndiEnv.put(Context.URL_PKG_PREFIXES, getUrlPkgPrefixes());
if (getSecurityProtocol() != null)
jndiEnv.put(Context.SECURITY_PROTOCOL, getSecurityProtocol());
if (log.isDebugEnabled()) {
for(Iterator it=jndiEnv.keySet().iterator(); it.hasNext();) {
String key=(String) it.next();
String value=jndiEnv.getProperty(key);
log.debug("jndiEnv ["+key+"] = ["+value+"]");
}
}
return jndiEnv;
}
/**
* Gets the Context<br/>
* When InitialContextFactory and ProviderURL are set, these are used
* to get the <code>Context</code>. Otherwise the the InitialContext is
* retrieved without parameters.<br/>
* <b>Notice:</b> you can set the parameters on the commandline with <br/>
* java -Djava.naming.factory.initial= xxx -Djava.naming.provider.url=xxx
* <br/><br/>
*
* @return The context value
* @exception javax.naming.NamingException Description of the Exception
*/
public Context getContext() throws NamingException {
if (null == context) {
Hashtable jndiEnv = getJndiEnv();
if (jndiEnv.size()>0) {
log.debug("creating initial JNDI-context using specified environment");
context = (Context) new InitialContext(jndiEnv);
} else {
log.debug("creating initial JNDI-context");
context = (Context) new InitialContext();
}
}
return context;
}
public String getCredentials() {
return credentials;
}
/**
* Gets the initialContextFactoryName
*
* @return The initialContextFactoryName value
*/
public String getInitialContextFactoryName() {
return initialContextFactoryName;
}
/**
* Gets the providerURL
*
* @return The providerURL value
*/
public String getProviderURL() {
return providerURL;
}
public String getSecurityProtocol() {
return securityProtocol;
}
public java.lang.String getUrlPkgPrefixes() {
return urlPkgPrefixes;
}
public void setAuthentication(java.lang.String newAuthentication) {
authentication = newAuthentication;
}
public void setCredentials(java.lang.String newCredentials) {
credentials = newCredentials;
}
/**
* Sets the initialContextFactoryName
*
* @param value The new initialContextFactoryName value
*/
public void setInitialContextFactoryName(String value) {
initialContextFactoryName = value;
}
/**
* Sets the providerURL
*
* @param value The new providerURL value
*/
public void setProviderURL(String value) {
providerURL = value;
}
public void setSecurityProtocol(String securityProtocol) {
this.securityProtocol = securityProtocol;
}
/**
* Setter for <code>Context.URL_PKG_PREFIXES</code><br/>
* Creation date: (03-04-2003 8:50:36)
* @param newUrlPkgPrefixes java.lang.String
*/
public void setUrlPkgPrefixes(java.lang.String newUrlPkgPrefixes) {
urlPkgPrefixes = newUrlPkgPrefixes;
}
public String toString() {
ToStringBuilder ts = new ToStringBuilder(this);
ts.append("context", context);
ts.append("authentication", authentication);
ts.append("credentials", credentials);
ts.append("providerURL", providerURL);
ts.append("urlPkgPrefixes", urlPkgPrefixes);
ts.append("securityProtocol", securityProtocol);
ts.append("initialContextFactoryName", initialContextFactoryName);
return ts.toString();
}
/**
* loads JNDI (and other) properties from a JmsRealm
* @see JmsRealm
*/
public void setJmsRealm(String jmsRealmName) {
try {
JmsRealm.copyRealm(this,jmsRealmName);
this.jmsRealmName = jmsRealmName;
} catch (ConfigurationException e) {
log.warn("cannot copy data from realm",e);
}
}
public String getJmsRealName() {
return this.jmsRealmName;
}
public String getAuthentication() {
return authentication;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String string) {
principal = string;
}
public void setJndiAuthAlias(String string) {
jndiAuthAlias = string;
}
public String getJndiAuthAlias() {
return jndiAuthAlias;
}
public void setJndiContextPrefix(String string) {
jndiContextPrefix = string;
}
public String getJndiContextPrefix() {
return jndiContextPrefix;
}
public String getJndiProperties() {
return jndiProperties;
}
public void setJndiProperties(String jndiProperties) {
this.jndiProperties = jndiProperties;
}
}
| |
package bzh.medek.server.rest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import bzh.medek.server.conf.Conf;
import bzh.medek.server.json.JsonLang;
import bzh.medek.server.json.JsonSimpleResponse;
import bzh.medek.server.json.movie.JsonMovie;
import bzh.medek.server.json.movie.JsonMyMovie;
import bzh.medek.server.persistence.dao.MovieDAO;
import bzh.medek.server.persistence.dao.StorygenreDAO;
import bzh.medek.server.persistence.dao.SupportDAO;
import bzh.medek.server.persistence.dao.UserDAO;
import bzh.medek.server.persistence.dao.UsermovieDAO;
import bzh.medek.server.persistence.entities.Lang;
import bzh.medek.server.persistence.entities.Movie;
import bzh.medek.server.persistence.entities.Movieartist;
import bzh.medek.server.persistence.entities.Usermovie;
import bzh.medek.server.persistence.entities.UsermoviePK;
import bzh.medek.server.utils.Constants;
@Stateless
@ApplicationPath("/services")
@Path(value = "/movies")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MovieService extends Application {
private static final Logger LOGGER = Logger.getLogger(MovieService.class);
@Inject
MovieDAO movieDao;
@Inject
SupportDAO supportDAO;
@Inject
StorygenreDAO storygenreDAO;
@Inject
Conf conf;
@Inject
UsermovieDAO usermovieDAO;
@Inject
UserDAO userDAO;
public MovieService () {
}
/**
* GET /movies : retrieve all movies
*
* @return
*/
@GET
public List<JsonMovie> getAllWithParams(@Context HttpServletRequest request,
@QueryParam("from") int from, @QueryParam("limit") int limit,
@QueryParam("orderBy") String orderBy, @QueryParam("orderDir") String orderDir) {
List<Movie> movies = movieDao.getMoviesForList(from, limit, orderBy, orderDir);
LOGGER.info("find "+movies.size()+" movies in the database");
ArrayList<JsonMovie> lm = new ArrayList<JsonMovie>();
String artistName = "";
Integer artistId = 0;
for (Movie m : movies) {
if (!m.getMovieartists().isEmpty()) {
artistName = m.getMovieartists().get(0).getArtistBean()
.getName()
+ " "
+ m.getMovieartists().get(0).getArtistBean()
.getFirstname();
artistId = m.getMovieartists().get(0).getArtistBean().getId();
} else {
artistName = "";
artistId = 0;
}
Usermovie mym = usermovieDAO.getUsermovie(m.getId(), request.getHeader(Constants.HTTP_HEADER_TOKEN));
lm.add(new JsonMovie(m.getId(), m.getTitle(), m.getDescription(),
m.getReleasedate(), m.getCover(), m.getSupportBean().getName(), m.getSupportBean().getId(),
m.getStorygenre().getName(), m.getStorygenre().getId(), m.getLength(), m.getIscollector(),
artistName, artistId, "", null, "", null, new ArrayList<JsonLang>(), new ArrayList<JsonLang>(),
(mym!=null)?true:false, (mym!=null)?mym.getRating():0));
}
return lm;
}
/**
* GET /movies/user : retrieve movie for one user
*
* @param id - user ID
* @return
*/
@GET
@Path(value = "user")
public List<JsonMovie> getAllWithParams(@Context HttpServletRequest request,
@QueryParam("from") int from, @QueryParam("limit") int limit,
@QueryParam("orderBy") String orderBy, @QueryParam("orderDir") String orderDir,
@QueryParam("userId") Integer userId) {
List<JsonMovie> movies = movieDao.getUserMovies(from, limit, orderBy, orderDir, userId);
LOGGER.info("find "+movies.size()+" movies in the database");
String artistName = "";
Integer artistId = 0;
List<Movieartist> martists = null;
for (JsonMovie m : movies) {
martists = movieDao.getMovieArtists(m.getId());
if (!martists.isEmpty()) {
artistName = martists.get(0).getArtistBean()
.getName()
+ " "
+ martists.get(0).getArtistBean()
.getFirstname();
artistId = martists.get(0).getArtistBean().getId();
} else {
artistName = "";
artistId = 0;
}
m.setRealisator(artistName);
m.setRealisatorId(artistId);
}
return movies;
}
/**
* GET /movies/{id} : retrieve one movie
*
* @param id
* @return
*/
@GET
@Path(value = "/{id}")
public JsonMovie getOne(@PathParam(value = "id") Integer id) {
JsonMovie jm = movieDao.getJsonMovie(id);
LOGGER.info("find "+jm.getTitle()+" movie in the database");
Movie m = movieDao.getMovie(id);
List<JsonLang> ll = new ArrayList<JsonLang>();
for (Lang l:m.getLangs2()) {
ll.add(new JsonLang(l.getId(), l.getName()));
}
jm.setLangs(ll);
List<JsonLang> ls = new ArrayList<JsonLang>();
for (Lang l:m.getLangs1()) {
ls.add(new JsonLang(l.getId(), l.getName()));
}
jm.setSubtitles(ls);
return jm;
}
/**
* POST /movies : create / update one movie
*
* @param id
* @return
*/
@POST
public JsonMovie createUpdateOne(JsonMovie movie) {
JsonMovie jmovie = movie;
if (movie.getId() == null) {
Movie m = new Movie();
m.setTitle(movie.getTitle());
m.setDescription(movie.getDescription());
m.setReleasedate(movie.getReleaseDate());
m.setLength(movie.getLength());
m.setIscollector(movie.getIsCollector());
m.setSupportBean(supportDAO.getSupport(movie.getSupportId()));
m.setStorygenre(storygenreDAO.getStorygenre(movie.getGenreId()));
movieDao.saveMovie(m);
jmovie.setId(m.getId());
} else {
Movie m = movieDao.getMovie(movie.getId());
m.setTitle(movie.getTitle());
m.setDescription(movie.getDescription());
m.setReleasedate(movie.getReleaseDate());
m.setLength(movie.getLength());
m.setIscollector(movie.getIsCollector());
m.setSupportBean(supportDAO.getSupport(movie.getSupportId()));
m.setStorygenre(storygenreDAO.getStorygenre(movie.getGenreId()));
movieDao.updateMovie(m);
}
return jmovie;
}
/**
* POST : upload new cover for movie
*
* @param newcover
* @return
*/
@POST
@Path("{id}/coverupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadAttach(@PathParam("id") Integer id, MultipartFormDataInput newcover) {
Map<String, List<InputPart>> uploadForm = newcover.getFormDataMap();
// Get file data to save
List<InputPart> inputParts = uploadForm.get("file");
String filename = null;
for (InputPart inputPart : inputParts) {
// convert the uploaded file to inputstream and write it to disk
InputStream inputStream = null;
OutputStream out = null;
try {
inputStream = inputPart.getBody(InputStream.class, null);
List<String> contDisp = inputPart.getHeaders().get("Content-Disposition");
for (String cd : contDisp) {
if (cd.contains("filename")) {
filename = "cover.jpg";
LOGGER.info("FILENAME : " + filename);
}
}
String path = conf.getMovieFS() + id + "/";
File pathtest = new File(path);
if (!pathtest.exists()) {
if (!pathtest.mkdirs()) {
LOGGER.error("While saving cover : "
+ "unable to create repository tmp dir => " + path);
}
}
File up = new File(path + filename);
if (!up.createNewFile()) {
if (up.exists()) {
up.delete();
if (!up.createNewFile()) {
LOGGER.error("While saving cover : " + "unable to overwrite existing file => "
+ up.getAbsolutePath());
}
} else {
LOGGER.error("While saving cover : " + "unable to create new file => "
+ up.getAbsolutePath());
}
}
out = new FileOutputStream(up);
int read = 0;
byte[] bytes = new byte[2048];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
} catch (IOException e) {
LOGGER.error("While saving cover : ", e);
return Response.ok(new JsonSimpleResponse(false), MediaType.APPLICATION_JSON).build();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
LOGGER.error("While saving cover - closing inputstream : ", e);
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
LOGGER.error("While saving cover - closing outputstream : ", e);
}
}
}
}
return Response.ok(new JsonSimpleResponse(true), MediaType.APPLICATION_JSON).build();
}
/**
* POST /addtocollec : add movie to user's collection
*
* @return
*/
@POST
@Path("addtocollec")
public Response addToCollection(JsonMyMovie movie) {
Usermovie um = new Usermovie();
UsermoviePK umid = new UsermoviePK();
umid.setMovie(movie.getMovieId().intValue());
umid.setUser(movie.getUserId().intValue());
um.setId(umid);
um.setMovieBean(movieDao.getMovie(movie.getMovieId()));
um.setUserBean(userDAO.getUser(movie.getUserId()));
um.setComment(movie.getComment());
um.setRating(movie.getRating());
usermovieDAO.saveUsermovie(um);
return Response.ok(new JsonSimpleResponse(true),
MediaType.APPLICATION_JSON).build();
}
/**
* POST /removefromcollec : remove movie from user's collection
*
* @return
*/
@POST
@Path("removefromcollec")
public Response removeFromCollection(JsonMyMovie movie) {
Usermovie um = new Usermovie();
UsermoviePK umid = new UsermoviePK();
umid.setMovie(movie.getMovieId().intValue());
umid.setUser(movie.getUserId().intValue());
um.setId(umid);
um.setMovieBean(movieDao.getMovie(movie.getMovieId()));
um.setUserBean(userDAO.getUser(movie.getUserId()));
um.setComment(movie.getComment());
um.setRating(movie.getRating());
usermovieDAO.removeUsermovie(um);
return Response.ok(new JsonSimpleResponse(true),
MediaType.APPLICATION_JSON).build();
}
}
| |
/*
* 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.jena.rdf.model.impl;
import java.util.*;
import org.apache.jena.enhanced.* ;
import org.apache.jena.graph.* ;
import org.apache.jena.rdf.model.* ;
import org.apache.jena.shared.* ;
import org.apache.jena.vocabulary.RDF ;
/** An internal class not normally of interest to application developers.
* A base class on which the other containers are built.
*/
public class ContainerImpl extends ResourceImpl
implements Container, ContainerI {
static NodeIteratorFactory iteratorFactory;
static {
iteratorFactory = new ContNodeIteratorFactoryImpl();
}
/** Creates new ContainerImpl */
public ContainerImpl( ModelCom model ) {
super(model);
}
public ContainerImpl( String uri, ModelCom model ){
super(uri, model);
}
public ContainerImpl(Resource r, ModelCom model) {
super(r.asNode(), model);
}
public ContainerImpl(Node n, EnhGraph g) {
super(n,g);
}
protected ContainerImpl( Resource r )
{ this( r, (ModelCom) r.getModel() ); }
private boolean is( Resource r ) {
return hasProperty(RDF.type, r);
}
@Override
public boolean isAlt() {
return is(RDF.Alt);
}
@Override
public boolean isBag() {
return is(RDF.Bag);
}
@Override
public boolean isSeq() {
return is(RDF.Seq);
}
@Override
public Container add(RDFNode n) {
int i = size();
addProperty(RDF.li(i+1), n);
return this;
}
@Override
public Container add(boolean o) {
return add( getModel().createTypedLiteral( o ) );
}
@Override
public Container add(long o) {
return add( getModel().createTypedLiteral( o ) );
}
@Override
public Container add(char o) {
return add( getModel().createTypedLiteral( o ) );
}
@Override
public Container add( float o ) {
return add( getModel().createTypedLiteral( o ) );
}
@Override
public Container add(double o) {
return add( getModel().createTypedLiteral( o ) );
}
@Override
public Container add(Object o) {
return add( getModel().createTypedLiteral( o ) );
}
@Override
public Container add(String o) {
return add( o, "" );
}
@Override
public Container add(String o, String l) {
return add( literal( o, l ) );
}
@Override
public boolean contains(RDFNode n) {
return containerContains( n );
}
@Override
public boolean contains(boolean o) {
return contains( getModel().createTypedLiteral( o ) );
}
@Override
public boolean contains(long o) {
return contains( getModel().createTypedLiteral( o ) );
}
@Override
public boolean contains(char o) {
return contains( getModel().createTypedLiteral( o ) );
}
@Override
public boolean contains(float o) {
return contains( getModel().createTypedLiteral( o ) );
}
@Override
public boolean contains(double o) {
return contains( getModel().createTypedLiteral( o ) );
}
@Override
public boolean contains(Object o) {
return contains( getModel().createTypedLiteral( o ) );
}
@Override
public boolean contains(String o) {
return contains( o, "" );
}
@Override
public boolean contains( String o, String l ) {
return contains( literal( o, l ) );
}
private Literal literal( String s, String lang )
{ return new LiteralImpl( NodeFactory.createLiteral( s, lang ), getModelCom() ); }
@Override
public NodeIterator iterator()
{ return listContainerMembers( iteratorFactory ); }
@Override
public int size()
{
int result = 0;
StmtIterator iter = listProperties();
while (iter.hasNext())
if (iter.nextStatement().getPredicate().getOrdinal() != 0) result += 1;
iter.close();
return result;
}
@Override
public Container remove(Statement s) {
int size = size();
Statement last = null;
if (s.getPredicate().getOrdinal() == size) { // if last
getModel().remove(s);
} else {
last = getModel().getRequiredProperty(this, RDF.li(size));
s.changeObject(last.getObject());
getModel().remove(last);
}
if (size() != (size -1))
throw new AssertionFailureException( "container size" );
return this;
}
@Override
public Container remove(int index, RDFNode object) {
remove(getModel().createStatement(this, RDF.li(index), object));
return this;
}
/**
Answer an iterator over the members of this container.
@param f the factory for constructing the final iterator
@return the member iterator
*/
public NodeIterator listContainerMembers( NodeIteratorFactory f )
{
StmtIterator iter = listProperties();
Vector<Statement> result = new Vector<>();
int maxOrdinal = 0;
while (iter.hasNext()) {
Statement stmt = iter.nextStatement();
int ordinal = stmt.getPredicate().getOrdinal();
if (ordinal != 0) {
if (ordinal > maxOrdinal) {
maxOrdinal = ordinal;
result.setSize(ordinal);
}
result.setElementAt(stmt, ordinal-1);
}
}
iter.close();
return f.createIterator( result.iterator(), result, this );
}
public int containerIndexOf( RDFNode n ) {
int result = 0;
StmtIterator iter = listProperties();
while (iter.hasNext()) {
Statement stmt = iter.nextStatement();
int ordinal = stmt.getPredicate().getOrdinal();
if (ordinal != 0 && n.equals( stmt.getObject() )) {
result = ordinal;
break;
}
}
iter.close();
return result;
}
public boolean containerContains( RDFNode n)
{ return containerIndexOf( n ) != 0; }
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.network;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.StreamMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQBytesMessage;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQMapMessage;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQStreamMessage;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.util.Wait;
import org.apache.activemq.xbean.BrokerFactoryBean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class CompressionOverNetworkTest {
protected static final int RECEIVE_TIMEOUT_MILLS = 10000;
protected static final int MESSAGE_COUNT = 10;
private static final Logger LOG = LoggerFactory.getLogger(CompressionOverNetworkTest.class);
protected AbstractApplicationContext context;
protected Connection localConnection;
protected Connection remoteConnection;
protected BrokerService localBroker;
protected BrokerService remoteBroker;
protected Session localSession;
protected Session remoteSession;
protected ActiveMQDestination included;
@Test
public void testCompressedOverCompressedNetwork() throws Exception {
ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection;
localAmqConnection.setUseCompression(true);
MessageConsumer consumer1 = remoteSession.createConsumer(included);
MessageProducer producer = localSession.createProducer(included);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
waitForConsumerRegistration(localBroker, 1, included);
StringBuilder payload = new StringBuilder("test-");
for (int i = 0; i < 100; ++i) {
payload.append(UUID.randomUUID().toString());
}
Message test = localSession.createTextMessage(payload.toString());
producer.send(test);
Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
assertNotNull(msg);
ActiveMQTextMessage message = (ActiveMQTextMessage) msg;
assertTrue(message.isCompressed());
assertEquals(payload.toString(), message.getText());
}
@Test
public void testTextMessageCompression() throws Exception {
MessageConsumer consumer1 = remoteSession.createConsumer(included);
MessageProducer producer = localSession.createProducer(included);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
waitForConsumerRegistration(localBroker, 1, included);
StringBuilder payload = new StringBuilder("test-");
for (int i = 0; i < 100; ++i) {
payload.append(UUID.randomUUID().toString());
}
Message test = localSession.createTextMessage(payload.toString());
producer.send(test);
Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
assertNotNull(msg);
ActiveMQTextMessage message = (ActiveMQTextMessage) msg;
assertTrue(message.isCompressed());
assertEquals(payload.toString(), message.getText());
}
@Test
public void testBytesMessageCompression() throws Exception {
MessageConsumer consumer1 = remoteSession.createConsumer(included);
MessageProducer producer = localSession.createProducer(included);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
waitForConsumerRegistration(localBroker, 1, included);
StringBuilder payload = new StringBuilder("test-");
for (int i = 0; i < 100; ++i) {
payload.append(UUID.randomUUID().toString());
}
byte[] bytes = payload.toString().getBytes(StandardCharsets.UTF_8);
BytesMessage test = localSession.createBytesMessage();
test.writeBytes(bytes);
producer.send(test);
Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
assertNotNull(msg);
ActiveMQBytesMessage message = (ActiveMQBytesMessage) msg;
assertTrue(message.isCompressed());
assertTrue(message.getContent().getLength() < bytes.length);
byte[] result = new byte[bytes.length];
assertEquals(bytes.length, message.readBytes(result));
assertEquals(-1, message.readBytes(result));
for (int i = 0; i < bytes.length; ++i) {
assertEquals(bytes[i], result[i]);
}
}
@Test
public void testStreamMessageCompression() throws Exception {
MessageConsumer consumer1 = remoteSession.createConsumer(included);
MessageProducer producer = localSession.createProducer(included);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
waitForConsumerRegistration(localBroker, 1, included);
StreamMessage test = localSession.createStreamMessage();
for (int i = 0; i < 100; ++i) {
test.writeString("test string: " + i);
}
producer.send(test);
Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
assertNotNull(msg);
ActiveMQStreamMessage message = (ActiveMQStreamMessage) msg;
assertTrue(message.isCompressed());
for (int i = 0; i < 100; ++i) {
assertEquals("test string: " + i, message.readString());
}
}
@Test
public void testMapMessageCompression() throws Exception {
MessageConsumer consumer1 = remoteSession.createConsumer(included);
MessageProducer producer = localSession.createProducer(included);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
waitForConsumerRegistration(localBroker, 1, included);
MapMessage test = localSession.createMapMessage();
for (int i = 0; i < 100; ++i) {
test.setString(Integer.toString(i), "test string: " + i);
}
producer.send(test);
Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
assertNotNull(msg);
ActiveMQMapMessage message = (ActiveMQMapMessage) msg;
assertTrue(message.isCompressed());
for (int i = 0; i < 100; ++i) {
assertEquals("test string: " + i, message.getString(Integer.toString(i)));
}
}
@Test
public void testObjectMessageCompression() throws Exception {
MessageConsumer consumer1 = remoteSession.createConsumer(included);
MessageProducer producer = localSession.createProducer(included);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
waitForConsumerRegistration(localBroker, 1, included);
StringBuilder payload = new StringBuilder("test-");
for (int i = 0; i < 100; ++i) {
payload.append(UUID.randomUUID().toString());
}
Message test = localSession.createObjectMessage(payload.toString());
producer.send(test);
Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
assertNotNull(msg);
ActiveMQObjectMessage message = (ActiveMQObjectMessage) msg;
assertTrue(message.isCompressed());
assertEquals(payload.toString(), message.getObject());
}
private void waitForConsumerRegistration(final BrokerService brokerService,
final int min,
final ActiveMQDestination destination) throws Exception {
assertTrue("Internal bridge consumers registered in time", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
Object[] bridges = brokerService.getNetworkConnectors().get(0).bridges.values().toArray();
if (bridges.length > 0) {
LOG.info(brokerService + " bridges " + Arrays.toString(bridges));
DemandForwardingBridgeSupport demandForwardingBridgeSupport = (DemandForwardingBridgeSupport) bridges[0];
ConcurrentMap<ConsumerId, DemandSubscription> forwardingBridges = demandForwardingBridgeSupport.getLocalSubscriptionMap();
LOG.info(brokerService + " bridge " + demandForwardingBridgeSupport + ", localSubs: " + forwardingBridges);
if (!forwardingBridges.isEmpty()) {
for (DemandSubscription demandSubscription : forwardingBridges.values()) {
if (demandSubscription.getLocalInfo().getDestination().equals(destination)) {
LOG.info(brokerService + " DemandSubscription " + demandSubscription + ", size: " + demandSubscription.size());
return demandSubscription.size() >= min;
}
}
}
}
return false;
}
}));
}
@Before
public void setUp() throws Exception {
doSetUp(true);
}
@After
public void tearDown() throws Exception {
doTearDown();
}
protected void doTearDown() throws Exception {
localConnection.close();
remoteConnection.close();
localBroker.stop();
remoteBroker.stop();
}
protected void doSetUp(boolean deleteAllMessages) throws Exception {
localBroker = createLocalBroker();
localBroker.setDeleteAllMessagesOnStartup(deleteAllMessages);
localBroker.start();
localBroker.waitUntilStarted();
remoteBroker = createRemoteBroker();
remoteBroker.setDeleteAllMessagesOnStartup(deleteAllMessages);
remoteBroker.start();
remoteBroker.waitUntilStarted();
URI localURI = localBroker.getVmConnectorURI();
ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory(localURI);
fac.setAlwaysSyncSend(true);
fac.setDispatchAsync(false);
localConnection = fac.createConnection();
localConnection.setClientID("clientId");
localConnection.start();
URI remoteURI = remoteBroker.getVmConnectorURI();
fac = new ActiveMQConnectionFactory(remoteURI);
remoteConnection = fac.createConnection();
remoteConnection.setClientID("clientId");
remoteConnection.start();
included = new ActiveMQTopic("include.test.bar");
localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
protected String getRemoteBrokerURI() {
return "org/apache/activemq/network/remoteBroker.xml";
}
protected String getLocalBrokerURI() {
return "org/apache/activemq/network/localBroker.xml";
}
protected BrokerService createBroker(String uri) throws Exception {
Resource resource = new ClassPathResource(uri);
BrokerFactoryBean factory = new BrokerFactoryBean(resource);
resource = new ClassPathResource(uri);
factory = new BrokerFactoryBean(resource);
factory.afterPropertiesSet();
BrokerService result = factory.getBroker();
for (NetworkConnector connector : result.getNetworkConnectors()) {
connector.setUseCompression(true);
}
return result;
}
protected BrokerService createLocalBroker() throws Exception {
return createBroker(getLocalBrokerURI());
}
protected BrokerService createRemoteBroker() throws Exception {
return createBroker(getRemoteBrokerURI());
}
}
| |
// This file was generated by Mendix Business Modeler.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package myfirstmodule.proxies;
import com.mendix.core.Core;
import com.mendix.core.CoreException;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.systemwideinterfaces.core.IMendixIdentifier;
import com.mendix.systemwideinterfaces.core.IMendixObject;
/**
*
*/
public class TransientIncidentPivotTableCell
{
private final IMendixObject transientIncidentPivotTableCellMendixObject;
private final IContext context;
/**
* Internal name of this entity
*/
public static final String entityName = "MyFirstModule.TransientIncidentPivotTableCell";
/**
* Enum describing members of this entity
*/
public enum MemberNames
{
categoryNumber("categoryNumber"),
categoryName("categoryName"),
carrierNumber("carrierNumber"),
carrierName("carrierName"),
TransientIncidentPivotTableCell_TransientIncidentPivotTableParameters("MyFirstModule.TransientIncidentPivotTableCell_TransientIncidentPivotTableParameters");
private String metaName;
MemberNames(String s)
{
metaName = s;
}
@Override
public String toString()
{
return metaName;
}
}
public TransientIncidentPivotTableCell(IContext context)
{
this(context, Core.instantiate(context, "MyFirstModule.TransientIncidentPivotTableCell"));
}
protected TransientIncidentPivotTableCell(IContext context, IMendixObject transientIncidentPivotTableCellMendixObject)
{
if (transientIncidentPivotTableCellMendixObject == null)
throw new IllegalArgumentException("The given object cannot be null.");
if (!Core.isSubClassOf("MyFirstModule.TransientIncidentPivotTableCell", transientIncidentPivotTableCellMendixObject.getType()))
throw new IllegalArgumentException("The given object is not a MyFirstModule.TransientIncidentPivotTableCell");
this.transientIncidentPivotTableCellMendixObject = transientIncidentPivotTableCellMendixObject;
this.context = context;
}
/**
* @deprecated Use 'TransientIncidentPivotTableCell.load(IContext, IMendixIdentifier)' instead.
*/
@Deprecated
public static myfirstmodule.proxies.TransientIncidentPivotTableCell initialize(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException
{
return myfirstmodule.proxies.TransientIncidentPivotTableCell.load(context, mendixIdentifier);
}
/**
* Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called.
* The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.getSudoContext() can be used to obtain sudo access).
*/
public static myfirstmodule.proxies.TransientIncidentPivotTableCell initialize(IContext context, IMendixObject mendixObject)
{
return new myfirstmodule.proxies.TransientIncidentPivotTableCell(context, mendixObject);
}
public static myfirstmodule.proxies.TransientIncidentPivotTableCell load(IContext context, IMendixIdentifier mendixIdentifier) throws CoreException
{
IMendixObject mendixObject = Core.retrieveId(context, mendixIdentifier);
return myfirstmodule.proxies.TransientIncidentPivotTableCell.initialize(context, mendixObject);
}
/**
* Commit the changes made on this proxy object.
*/
public final void commit() throws CoreException
{
Core.commit(context, getMendixObject());
}
/**
* Commit the changes made on this proxy object using the specified context.
*/
public final void commit(IContext context) throws CoreException
{
Core.commit(context, getMendixObject());
}
/**
* Delete the object.
*/
public final void delete()
{
Core.delete(context, getMendixObject());
}
/**
* Delete the object using the specified context.
*/
public final void delete(IContext context)
{
Core.delete(context, getMendixObject());
}
/**
* @return value of categoryNumber
*/
public final Long getcategoryNumber()
{
return getcategoryNumber(getContext());
}
/**
* @param context
* @return value of categoryNumber
*/
public final Long getcategoryNumber(IContext context)
{
return (Long) getMendixObject().getValue(context, MemberNames.categoryNumber.toString());
}
/**
* Set value of categoryNumber
* @param categorynumber
*/
public final void setcategoryNumber(Long categorynumber)
{
setcategoryNumber(getContext(), categorynumber);
}
/**
* Set value of categoryNumber
* @param context
* @param categorynumber
*/
public final void setcategoryNumber(IContext context, Long categorynumber)
{
getMendixObject().setValue(context, MemberNames.categoryNumber.toString(), categorynumber);
}
/**
* @return value of categoryName
*/
public final String getcategoryName()
{
return getcategoryName(getContext());
}
/**
* @param context
* @return value of categoryName
*/
public final String getcategoryName(IContext context)
{
return (String) getMendixObject().getValue(context, MemberNames.categoryName.toString());
}
/**
* Set value of categoryName
* @param categoryname
*/
public final void setcategoryName(String categoryname)
{
setcategoryName(getContext(), categoryname);
}
/**
* Set value of categoryName
* @param context
* @param categoryname
*/
public final void setcategoryName(IContext context, String categoryname)
{
getMendixObject().setValue(context, MemberNames.categoryName.toString(), categoryname);
}
/**
* @return value of carrierNumber
*/
public final Long getcarrierNumber()
{
return getcarrierNumber(getContext());
}
/**
* @param context
* @return value of carrierNumber
*/
public final Long getcarrierNumber(IContext context)
{
return (Long) getMendixObject().getValue(context, MemberNames.carrierNumber.toString());
}
/**
* Set value of carrierNumber
* @param carriernumber
*/
public final void setcarrierNumber(Long carriernumber)
{
setcarrierNumber(getContext(), carriernumber);
}
/**
* Set value of carrierNumber
* @param context
* @param carriernumber
*/
public final void setcarrierNumber(IContext context, Long carriernumber)
{
getMendixObject().setValue(context, MemberNames.carrierNumber.toString(), carriernumber);
}
/**
* @return value of carrierName
*/
public final String getcarrierName()
{
return getcarrierName(getContext());
}
/**
* @param context
* @return value of carrierName
*/
public final String getcarrierName(IContext context)
{
return (String) getMendixObject().getValue(context, MemberNames.carrierName.toString());
}
/**
* Set value of carrierName
* @param carriername
*/
public final void setcarrierName(String carriername)
{
setcarrierName(getContext(), carriername);
}
/**
* Set value of carrierName
* @param context
* @param carriername
*/
public final void setcarrierName(IContext context, String carriername)
{
getMendixObject().setValue(context, MemberNames.carrierName.toString(), carriername);
}
/**
* @return value of TransientIncidentPivotTableCell_TransientIncidentPivotTableParameters
*/
public final myfirstmodule.proxies.TransientIncidentPivotTableParameters getTransientIncidentPivotTableCell_TransientIncidentPivotTableParameters() throws CoreException
{
return getTransientIncidentPivotTableCell_TransientIncidentPivotTableParameters(getContext());
}
/**
* @param context
* @return value of TransientIncidentPivotTableCell_TransientIncidentPivotTableParameters
*/
public final myfirstmodule.proxies.TransientIncidentPivotTableParameters getTransientIncidentPivotTableCell_TransientIncidentPivotTableParameters(IContext context) throws CoreException
{
myfirstmodule.proxies.TransientIncidentPivotTableParameters result = null;
IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.TransientIncidentPivotTableCell_TransientIncidentPivotTableParameters.toString());
if (identifier != null)
result = myfirstmodule.proxies.TransientIncidentPivotTableParameters.load(context, identifier);
return result;
}
/**
* Set value of TransientIncidentPivotTableCell_TransientIncidentPivotTableParameters
* @param transientincidentpivottablecell_transientincidentpivottableparameters
*/
public final void setTransientIncidentPivotTableCell_TransientIncidentPivotTableParameters(myfirstmodule.proxies.TransientIncidentPivotTableParameters transientincidentpivottablecell_transientincidentpivottableparameters)
{
setTransientIncidentPivotTableCell_TransientIncidentPivotTableParameters(getContext(), transientincidentpivottablecell_transientincidentpivottableparameters);
}
/**
* Set value of TransientIncidentPivotTableCell_TransientIncidentPivotTableParameters
* @param context
* @param transientincidentpivottablecell_transientincidentpivottableparameters
*/
public final void setTransientIncidentPivotTableCell_TransientIncidentPivotTableParameters(IContext context, myfirstmodule.proxies.TransientIncidentPivotTableParameters transientincidentpivottablecell_transientincidentpivottableparameters)
{
if (transientincidentpivottablecell_transientincidentpivottableparameters == null)
getMendixObject().setValue(context, MemberNames.TransientIncidentPivotTableCell_TransientIncidentPivotTableParameters.toString(), null);
else
getMendixObject().setValue(context, MemberNames.TransientIncidentPivotTableCell_TransientIncidentPivotTableParameters.toString(), transientincidentpivottablecell_transientincidentpivottableparameters.getMendixObject().getId());
}
/**
* @return the IMendixObject instance of this proxy for use in the Core interface.
*/
public final IMendixObject getMendixObject()
{
return transientIncidentPivotTableCellMendixObject;
}
/**
* @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization.
*/
public final IContext getContext()
{
return context;
}
@Override
public boolean equals(Object obj)
{
if (obj == this)
return true;
if (obj != null && getClass().equals(obj.getClass()))
{
final myfirstmodule.proxies.TransientIncidentPivotTableCell that = (myfirstmodule.proxies.TransientIncidentPivotTableCell) obj;
return getMendixObject().equals(that.getMendixObject());
}
return false;
}
@Override
public int hashCode()
{
return getMendixObject().hashCode();
}
/**
* @return String name of this class
*/
public static String getType()
{
return "MyFirstModule.TransientIncidentPivotTableCell";
}
/**
* @return String GUID from this object, format: ID_0000000000
* @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object.
*/
@Deprecated
public String getGUID()
{
return "ID_" + getMendixObject().getId().toLong();
}
}
| |
/*
* 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.solr.handler;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.UnaryOperator;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.common.util.Utils;
import org.apache.solr.handler.loader.JsonLoader;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.update.AddUpdateCommand;
import org.apache.solr.update.CommitUpdateCommand;
import org.apache.solr.update.DeleteUpdateCommand;
import org.apache.solr.update.processor.BufferingRequestProcessor;
import org.junit.BeforeClass;
import org.junit.Test;
public class JsonLoaderTest extends SolrTestCaseJ4 {
@BeforeClass
public static void beforeTests() throws Exception {
initCore("solrconfig.xml", "schema.xml");
}
static String input =
json(
"{\n"
+ "\n"
+ "'add': {\n"
+ " 'doc': {\n"
+ " 'bool': true,\n"
+ " 'f0': 'v0',\n"
+ " 'array': [ 'aaa', 'bbb' ]\n"
+ " }\n"
+ "},\n"
+ "'add': {\n"
+ " 'commitWithin': 1234,\n"
+ " 'overwrite': false,\n"
+ " 'boost': 3.45,\n"
+ " 'doc': {\n"
+ " 'f1': 'v1',\n"
+ " 'f1': 'v2',\n"
+ " 'f2': null\n"
+ " }\n"
+ "},\n"
+ "\n"
+ "'commit': {},\n"
+ "'optimize': { 'waitSearcher':false, 'openSearcher':false },\n"
+ "\n"
+ "'delete': { 'id':'ID' },\n"
+ "'delete': { 'id':'ID', 'commitWithin':500 },\n"
+ "'delete': { 'query':'QUERY' },\n"
+ "'delete': { 'query':'QUERY', 'commitWithin':500 },\n"
+ "'rollback': {}\n"
+ "\n"
+ "}\n"
+ "");
public void testParsing() throws Exception {
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(input), p);
assertEquals(2, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
assertEquals(
"SolrInputDocument(fields: [bool=true, f0=v0, array=[aaa, bbb]])", add.solrDoc.toString());
//
add = p.addCommands.get(1);
assertEquals("SolrInputDocument(fields: [f1=[v1, v2], f2=null])", add.solrDoc.toString());
assertFalse(add.overwrite);
// parse the commit commands
assertEquals(2, p.commitCommands.size());
CommitUpdateCommand commit = p.commitCommands.get(0);
assertFalse(commit.optimize);
assertTrue(commit.waitSearcher);
assertTrue(commit.openSearcher);
commit = p.commitCommands.get(1);
assertTrue(commit.optimize);
assertFalse(commit.waitSearcher);
assertFalse(commit.openSearcher);
// DELETE COMMANDS
assertEquals(4, p.deleteCommands.size());
DeleteUpdateCommand delete = p.deleteCommands.get(0);
assertEquals(delete.id, "ID");
assertNull(delete.query);
assertEquals(delete.commitWithin, -1);
delete = p.deleteCommands.get(1);
assertEquals(delete.id, "ID");
assertNull(delete.query);
assertEquals(delete.commitWithin, 500);
delete = p.deleteCommands.get(2);
assertNull(delete.id);
assertEquals(delete.query, "QUERY");
assertEquals(delete.commitWithin, -1);
delete = p.deleteCommands.get(3);
assertNull(delete.id);
assertEquals(delete.query, "QUERY");
assertEquals(delete.commitWithin, 500);
// ROLLBACK COMMANDS
assertEquals(1, p.rollbackCommands.size());
req.close();
}
public void testSimpleFormat() throws Exception {
String str = "[{'id':'1'},{'id':'2'}]".replace('\'', '"');
SolrQueryRequest req = req("commitWithin", "100", "overwrite", "false");
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(2, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument d = add.solrDoc;
SolrInputField f = d.getField("id");
assertEquals("1", f.getValue());
assertEquals(add.commitWithin, 100);
assertFalse(add.overwrite);
add = p.addCommands.get(1);
d = add.solrDoc;
f = d.getField("id");
assertEquals("2", f.getValue());
assertEquals(add.commitWithin, 100);
assertFalse(add.overwrite);
req.close();
}
@Test
public void testInvalidJsonProducesBadRequestSolrException() throws Exception {
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
String invalidJsonString = "}{";
SolrException ex =
expectThrows(
SolrException.class,
() -> {
loader.load(req(), rsp, new ContentStreamBase.StringStream(invalidJsonString), p);
});
assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
assertTrue(ex.getMessage().contains("Cannot parse"));
assertTrue(ex.getMessage().contains("JSON"));
}
public void testSimpleFormatInAdd() throws Exception {
String str = "{'add':[{'id':'1'},{'id':'2'}]}".replace('\'', '"');
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(2, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument d = add.solrDoc;
SolrInputField f = d.getField("id");
assertEquals("1", f.getValue());
assertEquals(add.commitWithin, -1);
assertTrue(add.overwrite);
add = p.addCommands.get(1);
d = add.solrDoc;
f = d.getField("id");
assertEquals("2", f.getValue());
assertEquals(add.commitWithin, -1);
assertTrue(add.overwrite);
req.close();
}
public void testFieldValueOrdering() throws Exception {
final String pre = "{'add':[{'id':'1',";
final String post = "},{'id':'2'}]}";
// list
checkFieldValueOrdering((pre + "'f':[45,67,89]" + post).replace('\'', '"'));
// dup fieldname keys
checkFieldValueOrdering((pre + "'f':45,'f':67,'f':89" + post).replace('\'', '"'));
}
private void checkFieldValueOrdering(String rawJson) throws Exception {
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(rawJson), p);
assertEquals(2, p.addCommands.size());
SolrInputDocument d = p.addCommands.get(0).solrDoc;
assertEquals(2, d.getFieldNames().size());
assertEquals("1", d.getFieldValue("id"));
assertArrayEquals(new Object[] {45L, 67L, 89L}, d.getFieldValues("f").toArray());
d = p.addCommands.get(1).solrDoc;
assertEquals(1, d.getFieldNames().size());
assertEquals("2", d.getFieldValue("id"));
req.close();
}
public void testMultipleDocsWithoutArray() throws Exception {
String doc = "\n" + "\n" + "{\"f1\": 1111 }\n" + "\n" + "{\"f1\": 2222 }\n";
SolrQueryRequest req = req("srcField", "_src_");
req.getContext().put("path", "/update/json/docs");
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(doc), p);
assertEquals(2, p.addCommands.size());
}
public void testJsonDocFormat() throws Exception {
String doc;
SolrQueryRequest req;
SolrQueryResponse rsp;
BufferingRequestProcessor p;
JsonLoader loader;
doc =
"\n"
+ "\n"
+ "{\"bool\": true,\n"
+ " \"f0\": \"v0\",\n"
+ " \"f2\": {\n"
+ " \t \"boost\": 2.3,\n"
+ " \t \"value\": \"test\"\n"
+ " \t },\n"
+ "\"array\": [ \"aaa\", \"bbb\" ],\n"
+ "\"boosted\": {\n"
+ " \t \"boost\": 6.7,\n"
+ " \t \"value\": [ \"aaa\", \"bbb\" ]\n"
+ " \t }\n"
+ " }\n"
+ "\n"
+ "\n"
+ " {\"f1\": \"v1\",\n"
+ " \"f2\": \"v2\",\n"
+ " \"f3\": null\n"
+ " }\n";
req = req("srcField", "_src_");
req.getContext().put("path", "/update/json/docs");
rsp = new SolrQueryResponse();
p = new BufferingRequestProcessor(null);
loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(doc), p);
assertEquals(2, p.addCommands.size());
String content = (String) p.addCommands.get(0).solrDoc.getFieldValue("_src_");
assertNotNull(content);
Map<?, ?> obj = (Map<?, ?>) Utils.fromJSONString(content);
assertEquals(Boolean.TRUE, obj.get("bool"));
assertEquals("v0", obj.get("f0"));
assertNotNull(obj.get("f0"));
assertNotNull(obj.get("array"));
assertNotNull(obj.get("boosted"));
content = (String) p.addCommands.get(1).solrDoc.getFieldValue("_src_");
assertNotNull(content);
obj = (Map<?, ?>) Utils.fromJSONString(content);
assertEquals("v1", obj.get("f1"));
assertEquals("v2", obj.get("f2"));
assertTrue(obj.containsKey("f3"));
// TODO new test method
doc = "[{'id':'1'},{'id':'2'}]".replace('\'', '"');
req = req("srcField", "_src_");
req.getContext().put("path", "/update/json/docs");
rsp = new SolrQueryResponse();
p = new BufferingRequestProcessor(null);
loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(doc), p);
assertEquals(2, p.addCommands.size());
content = (String) p.addCommands.get(0).solrDoc.getFieldValue("_src_");
assertNotNull(content);
obj = (Map) Utils.fromJSONString(content);
assertEquals("1", obj.get("id"));
content = (String) p.addCommands.get(1).solrDoc.getFieldValue("_src_");
assertNotNull(content);
obj = (Map) Utils.fromJSONString(content);
assertEquals("2", obj.get("id"));
// TODO new test method
String json = "{a:{" + "b:[{c:c1, e:e1},{c:c2, e :e2, d:{p:q}}]," + "x:y" + "}}";
req = req("split", "/|/a/b");
req.getContext().put("path", "/update/json/docs");
rsp = new SolrQueryResponse();
p = new BufferingRequestProcessor(null);
loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(json), p);
assertEquals(1, p.addCommands.size());
assertEquals(
"SolrInputDocument(fields: ["
+ "b=["
+ "SolrInputDocument(fields: [c=c1, e=e1]), "
+ "SolrInputDocument(fields: [c=c2, e=e2, d.p=q])], "
+ "a.x=y"
+ "])",
p.addCommands.get(0).solrDoc.toString());
}
private static final String PARENT_TWO_CHILDREN_JSON =
"{\n"
+ " \"id\": \"1\",\n"
+ " \"name\": \"i am the parent\",\n"
+ " \"cat\": \"parent\",\n"
+ " \"children\": [\n"
+ " {\n"
+ " \"id\": \"1.1\",\n"
+ " \"name\": \"i am the 1st child\",\n"
+ " \"cat\": \"child\"\n"
+ " },\n"
+ " {\n"
+ " \"id\": \"1.2\",\n"
+ " \"name\": \"i am the 2nd child\",\n"
+ " \"cat\": \"child\",\n"
+ " \"test_s\": \"test-new-label\",\n"
+ " \"grandchildren\": [\n"
+ " {\n"
+ " \"id\": \"1.2.1\",\n"
+ " \"name\": \"i am the grandchild\",\n"
+ " \"cat\": \"grandchild\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ "}";
private static final String[] PARENT_TWO_CHILDREN_PARAMS =
new String[] {
"split",
"/|/children|/children/grandchildren",
"f",
"$FQN:/**",
"f",
"id:/children/id",
"f",
"/name",
"f",
"/children/name",
"f",
"cat:/children/cat",
"f",
"id:/children/grandchildren/id",
"f",
"name:/children/grandchildren/name",
"f",
"cat:/children/grandchildren/cat"
};
@Test
public void testFewParentsJsonDoc() throws Exception {
String json = PARENT_TWO_CHILDREN_JSON;
SolrQueryRequest req;
SolrQueryResponse rsp;
BufferingRequestProcessor p;
JsonLoader loader; // multichild test case
final boolean array = random().nextBoolean();
StringBuilder b = new StringBuilder();
if (array) {
b.append("[");
}
final int passes = atLeast(2);
for (int i = 1; i <= passes; i++) {
b.append(json.replace("1", "" + i));
if (array) {
b.append(i < passes ? "," : "]");
}
}
req = req(PARENT_TWO_CHILDREN_PARAMS);
req.getContext().put("path", "/update/json/docs");
rsp = new SolrQueryResponse();
p = new BufferingRequestProcessor(null);
loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(b.toString()), p);
for (int i = 1; i <= passes; i++) {
final int ii = i;
UnaryOperator<String> s = (v) -> v.replace("1", "" + ii);
final SolrInputDocument parent = p.addCommands.get(i - 1).solrDoc;
assertOnlyValue(s.apply("1"), parent, "id");
assertOnlyValue("i am the parent", parent, "name");
assertOnlyValue("parent", parent, "cat");
@SuppressWarnings({"unchecked"})
List<SolrInputDocument> childDocs1 = (List) ((parent.getField("children")).getValue());
assertEquals(2, childDocs1.size());
{
final SolrInputDocument child1 = childDocs1.get(0);
assertOnlyValue(s.apply("1.1"), child1, "id");
assertOnlyValue(s.apply("i am the 1st child"), child1, "name");
assertOnlyValue("child", child1, "cat");
}
{
final SolrInputDocument child2 = childDocs1.get(1);
assertOnlyValue(s.apply("1.2"), child2, "id");
assertOnlyValue("i am the 2nd child", child2, "name");
assertOnlyValue("test-new-label", child2, "test_s");
assertOnlyValue("child", child2, "cat");
@SuppressWarnings({"unchecked"})
List<SolrInputDocument> childDocs2 = (List) ((child2.getField("grandchildren")).getValue());
assertEquals(1, childDocs2.size());
final SolrInputDocument grandChild = childDocs2.get(0);
assertOnlyValue(s.apply("1.2.1"), grandChild, "id");
assertOnlyValue("i am the grandchild", grandChild, "name");
assertOnlyValue("grandchild", grandChild, "cat");
}
}
}
private static void assertOnlyValue(String expected, SolrInputDocument doc, String field) {
assertEquals(Collections.singletonList(expected), doc.getFieldValues(field));
}
public void testAtomicUpdateFieldValue() throws Exception {
String str = "[{'id':'1', 'val_s':{'add':'foo'}}]".replace('\'', '"');
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
assertEquals(add.commitWithin, -1);
assertEquals(add.overwrite, true);
assertEquals("SolrInputDocument(fields: [id=1, val_s={add=foo}])", add.solrDoc.toString());
req.close();
}
@Test
public void testNullValues() throws Exception {
updateJ(
json("[{'id':'10','foo_s':null,'foo2_s':['hi',null,'there']}]"), params("commit", "true"));
assertJQ(
req("q", "id:10", "fl", "foo_s,foo2_s"), "/response/docs/[0]=={'foo2_s':['hi','there']}");
}
@Test
public void testBooleanValuesInAdd() throws Exception {
String str = "{'add':[{'id':'1','b1':true,'b2':false,'b3':[false,true]}]}".replace('\'', '"');
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument d = add.solrDoc;
SolrInputField f = d.getField("b1");
assertEquals(Boolean.TRUE, f.getValue());
f = d.getField("b2");
assertEquals(Boolean.FALSE, f.getValue());
f = d.getField("b3");
assertEquals(2, ((List) f.getValue()).size());
assertEquals(Boolean.FALSE, ((List) f.getValue()).get(0));
assertEquals(Boolean.TRUE, ((List) f.getValue()).get(1));
req.close();
}
@Test
public void testIntegerValuesInAdd() throws Exception {
String str = "{'add':[{'id':'1','i1':256,'i2':-5123456789,'i3':[0,1]}]}".replace('\'', '"');
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument d = add.solrDoc;
SolrInputField f = d.getField("i1");
assertEquals(256L, f.getValue());
f = d.getField("i2");
assertEquals(-5123456789L, f.getValue());
f = d.getField("i3");
assertEquals(2, ((List) f.getValue()).size());
assertEquals(0L, ((List) f.getValue()).get(0));
assertEquals(1L, ((List) f.getValue()).get(1));
req.close();
}
@Test
public void testDecimalValuesInAdd() throws Exception {
String str =
"{'add':[{'id':'1','d1':256.78,'d2':-5123456789.0,'d3':0.0,'d3':1.0,'d4':1.7E-10}]}"
.replace('\'', '"');
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument d = add.solrDoc;
SolrInputField f = d.getField("d1");
assertEquals(256.78, f.getValue());
f = d.getField("d2");
assertEquals(-5123456789.0, f.getValue());
f = d.getField("d3");
assertEquals(2, ((List) f.getValue()).size());
assertTrue(((List) f.getValue()).contains(0.0));
assertTrue(((List) f.getValue()).contains(1.0));
f = d.getField("d4");
assertEquals(1.7E-10, f.getValue());
req.close();
}
@Test
public void testBigDecimalValuesInAdd() throws Exception {
String str =
("{'add':[{'id':'1','bd1':0.12345678901234567890123456789012345,"
+ "'bd2':12345678901234567890.12345678901234567890,'bd3':0.012345678901234567890123456789012345,"
+ "'bd3':123456789012345678900.012345678901234567890}]}")
.replace('\'', '"');
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument d = add.solrDoc;
SolrInputField f = d.getField("bd1");
assertTrue(f.getValue() instanceof String);
assertEquals("0.12345678901234567890123456789012345", f.getValue());
f = d.getField("bd2");
assertTrue(f.getValue() instanceof String);
assertEquals("12345678901234567890.12345678901234567890", f.getValue());
f = d.getField("bd3");
assertEquals(2, ((List) f.getValue()).size());
assertTrue(((List) f.getValue()).contains("0.012345678901234567890123456789012345"));
assertTrue(((List) f.getValue()).contains("123456789012345678900.012345678901234567890"));
req.close();
}
@Test
public void testBigIntegerValuesInAdd() throws Exception {
String str =
("{'add':[{'id':'1','bi1':123456789012345678901,'bi2':1098765432109876543210,"
+ "'bi3':[1234567890123456789012,10987654321098765432109]}]}")
.replace('\'', '"');
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument d = add.solrDoc;
SolrInputField f = d.getField("bi1");
assertTrue(f.getValue() instanceof String);
assertEquals("123456789012345678901", f.getValue());
f = d.getField("bi2");
assertTrue(f.getValue() instanceof String);
assertEquals("1098765432109876543210", f.getValue());
f = d.getField("bi3");
assertEquals(2, ((List) f.getValue()).size());
assertTrue(((List) f.getValue()).contains("1234567890123456789012"));
assertTrue(((List) f.getValue()).contains("10987654321098765432109"));
req.close();
}
@Test
public void testAddNonStringValues() throws Exception {
// BigInteger and BigDecimal should be typed as strings, since there is no direct support for
// them
updateJ(
json(
"[{'id':'1','boolean_b':false,'long_l':19,'double_d':18.6,'big_integer_s':12345678901234567890,"
+ " 'big_decimal_s':0.1234567890123456789012345}]"),
params("commit", "true"));
assertJQ(
req("q", "id:1", "fl", "boolean_b,long_l,double_d,big_integer_s,big_decimal_s"),
"/response/docs/[0]=={'boolean_b':[false],'long_l':[19],'double_d':[18.6],"
+ "'big_integer_s':['12345678901234567890'],"
+ "'big_decimal_s':['0.1234567890123456789012345']}]}");
}
@Test
public void testAddBigIntegerValueToTrieField() throws Exception {
// Adding a BigInteger to a long field should fail
// BigInteger.longValue() returns only the low-order 64 bits.
ignoreException("big_integer_t");
SolrException ex =
expectThrows(
SolrException.class,
() -> {
updateJ(json("[{'id':'1','big_integer_tl':12345678901234567890}]"), null);
});
assertTrue(ex.getCause() instanceof NumberFormatException);
// Adding a BigInteger to an integer field should fail
// BigInteger.intValue() returns only the low-order 32 bits.
ex =
expectThrows(
SolrException.class,
() -> {
updateJ(json("[{'id':'1','big_integer_ti':12345678901234567890}]"), null);
});
assertTrue(ex.getCause() instanceof NumberFormatException);
unIgnoreException("big_integer_t");
}
@Test
public void testAddBigDecimalValueToTrieField() throws Exception {
// Adding a BigDecimal to a double field should succeed by reducing precision
updateJ(
json("[{'id':'1','big_decimal_td':100000000000000000000000000001234567890.0987654321}]"),
params("commit", "true"));
assertJQ(
req("q", "id:1", "fl", "big_decimal_td"),
"/response/docs/[0]=={'big_decimal_td':[1.0E38]}");
// Adding a BigDecimal to a float field should succeed by reducing precision
updateJ(
json("[{'id':'2','big_decimal_tf':100000000000000000000000000001234567890.0987654321}]"),
params("commit", "true"));
assertJQ(
req("q", "id:2", "fl", "big_decimal_tf"),
"/response/docs/[0]=={'big_decimal_tf':[1.0E38]}");
}
// The delete syntax was both extended for simplification in 4.0
@Test
public void testDeleteSyntax() throws Exception {
String str =
"{'delete':10"
+ "\n ,'delete':'20'"
+ "\n ,'delete':['30','40']"
+ "\n ,'delete':{'id':50, '_version_':12345}"
+ "\n ,'delete':[{'id':60, '_version_':67890}, {'id':70, '_version_':77777}, {'query':'id:80', '_version_':88888}]"
+ "\n ,'delete':{'id':90, '_route_':'shard1', '_version_':88888}"
+ "\n}\n";
str = str.replace('\'', '"');
SolrQueryRequest req = req();
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
// DELETE COMMANDS
assertEquals(9, p.deleteCommands.size());
DeleteUpdateCommand delete = p.deleteCommands.get(0);
assertEquals(delete.id, "10");
assertEquals(delete.query, null);
assertEquals(delete.commitWithin, -1);
delete = p.deleteCommands.get(1);
assertEquals(delete.id, "20");
assertEquals(delete.query, null);
assertEquals(delete.commitWithin, -1);
delete = p.deleteCommands.get(2);
assertEquals(delete.id, "30");
assertEquals(delete.query, null);
assertEquals(delete.commitWithin, -1);
delete = p.deleteCommands.get(3);
assertEquals(delete.id, "40");
assertEquals(delete.query, null);
assertEquals(delete.commitWithin, -1);
delete = p.deleteCommands.get(4);
assertEquals(delete.id, "50");
assertEquals(delete.query, null);
assertEquals(delete.getVersion(), 12345L);
delete = p.deleteCommands.get(5);
assertEquals(delete.id, "60");
assertEquals(delete.query, null);
assertEquals(delete.getVersion(), 67890L);
delete = p.deleteCommands.get(6);
assertEquals(delete.id, "70");
assertEquals(delete.query, null);
assertEquals(delete.getVersion(), 77777L);
delete = p.deleteCommands.get(7);
assertEquals(delete.id, null);
assertEquals(delete.query, "id:80");
assertEquals(delete.getVersion(), 88888L);
delete = p.deleteCommands.get(8);
assertEquals(delete.id, "90");
assertEquals(delete.query, null);
assertEquals(delete.getRoute(), "shard1");
assertEquals(delete.getVersion(), 88888L);
req.close();
}
private static final String SIMPLE_ANON_CHILD_DOCS_JSON =
"{\n"
+ " \"add\": {\n"
+ " \"doc\": {\n"
+ " \"id\": \"1\",\n"
+ " \"_childDocuments_\": [\n"
+ " {\n"
+ " \"id\": \"2\"\n"
+ " },\n"
+ " {\n"
+ " \"id\": \"3\",\n"
+ " \"foo_i\": [666,777]\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}";
@Test
public void testSimpleAnonymousChildDocs() throws Exception {
checkTwoAnonymousChildDocs(SIMPLE_ANON_CHILD_DOCS_JSON, true);
}
@Test
public void testSimpleChildDocs() throws Exception {
checkTwoAnonymousChildDocs(SIMPLE_ANON_CHILD_DOCS_JSON, false);
}
private static final String DUP_KEYS_ANON_CHILD_DOCS_JSON =
"{\n"
+ " \"add\": {\n"
+ " \"doc\": {\n"
+ " \"_childDocuments_\": [\n"
+ " {\n"
+ " \"id\": \"2\"\n"
+ " }\n"
+ " ],\n"
+ " \"id\": \"1\",\n"
+ " \"_childDocuments_\": [\n"
+ " {\n"
+ " \"id\": \"3\",\n"
+ " \"foo_i\": 666,\n"
+ " \"foo_i\": 777\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}";
@Test
public void testDupKeysAnonymousChildDocs() throws Exception {
checkTwoAnonymousChildDocs(DUP_KEYS_ANON_CHILD_DOCS_JSON, true);
}
@Test
public void testDupKeysChildDocs() throws Exception {
checkTwoAnonymousChildDocs(DUP_KEYS_ANON_CHILD_DOCS_JSON, false);
}
@Test
public void testChildDocWithoutId() throws Exception {
final String json = DUP_KEYS_ANON_CHILD_DOCS_JSON.replace("\"id\": \"3\",\n", "");
assert !json.equals(DUP_KEYS_ANON_CHILD_DOCS_JSON);
checkTwoAnonymousChildDocs(json, false);
}
// rawJsonStr has "_childDocuments_" key. if anonChildDocs then we want to test with something
// else.
private void checkTwoAnonymousChildDocs(String rawJsonStr, boolean anonChildDocs)
throws Exception {
if (!anonChildDocs) {
rawJsonStr = rawJsonStr.replaceAll("_childDocuments_", "childLabel");
}
SolrQueryRequest req = req("commit", "true");
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(rawJsonStr), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument d = add.solrDoc;
SolrInputField f = d.getField("id");
assertEquals("1", f.getValue());
SolrInputDocument cd;
if (anonChildDocs) {
cd = d.getChildDocuments().get(0);
} else {
cd = (SolrInputDocument) (d.getField("childLabel")).getFirstValue();
}
SolrInputField cf = cd.getField("id");
assertEquals("2", cf.getValue());
if (anonChildDocs) {
cd = d.getChildDocuments().get(1);
} else {
cd = (SolrInputDocument) ((List) (d.getField("childLabel")).getValue()).get(1);
}
cf = cd.getField("id");
if (rawJsonStr.contains("\"3\"")) {
assertEquals("3", cf.getValue());
} else { // ID 3 was removed previously to test we don't need an ID to have a child doc
assertNull("child doc should have no ID", cf);
}
cf = cd.getField("foo_i");
assertEquals(2, cf.getValueCount());
assertEquals(new Object[] {666L, 777L}, cf.getValues().toArray());
req.close();
}
@Test
public void testEmptyAnonymousChildDocs() throws Exception {
String str =
"{\n"
+ " \"add\": {\n"
+ " \"doc\": {\n"
+ " \"id\": \"1\",\n"
+ " \"_childDocuments_\": []\n"
+ " }\n"
+ " }\n"
+ "}";
SolrQueryRequest req = req("commit", "true");
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument d = add.solrDoc;
SolrInputField f = d.getField("id");
assertEquals("1", f.getValue());
List<SolrInputDocument> cd = d.getChildDocuments();
assertNull(cd);
req.close();
}
@Test
public void testAnonymousGrandChildDocs() throws Exception {
String str =
"{\n"
+ " \"add\": {\n"
+ " \"doc\": {\n"
+ " \"id\": \"1\",\n"
+ " \"_childDocuments_\": [\n"
+ " {\n"
+ " \"id\": \"2\",\n"
+ " \"_childDocuments_\": [\n"
+ " {\n"
+ " \"id\": \"4\",\n"
+ " \"foo_s\": \"Baz\"\n"
+ " }\n"
+ " ],\n"
+ " \"foo_s\": \"Yaz\"\n"
+ " },\n"
+ " {\n"
+ " \"id\": \"3\",\n"
+ " \"foo_s\": \"Bar\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}";
SolrQueryRequest req = req("commit", "true");
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument one = add.solrDoc;
assertEquals("1", one.getFieldValue("id"));
SolrInputDocument two = one.getChildDocuments().get(0);
assertEquals("2", two.getFieldValue("id"));
assertEquals("Yaz", two.getFieldValue("foo_s"));
SolrInputDocument four = two.getChildDocuments().get(0);
assertEquals("4", four.getFieldValue("id"));
assertEquals("Baz", four.getFieldValue("foo_s"));
SolrInputDocument three = one.getChildDocuments().get(1);
assertEquals("3", three.getFieldValue("id"));
assertEquals("Bar", three.getFieldValue("foo_s"));
req.close();
}
@Test
public void testChildDocs() throws Exception {
String str =
"{\n"
+ " \"add\": {\n"
+ " \"doc\": {\n"
+ " \"id\": \"1\",\n"
+ " \"children\": [\n"
+ " {\n"
+ " \"id\": \"2\",\n"
+ " \"foo_s\": \"Yaz\"\n"
+ " },\n"
+ " {\n"
+ " \"id\": \"3\",\n"
+ " \"foo_s\": \"Bar\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}";
SolrQueryRequest req = req("commit", "true");
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument one = add.solrDoc;
assertEquals("1", one.getFieldValue("id"));
@SuppressWarnings({"unchecked"})
List<SolrInputDocument> children = (List) one.getFieldValues("children");
SolrInputDocument two = children.get(0);
assertEquals("2", two.getFieldValue("id"));
assertEquals("Yaz", two.getFieldValue("foo_s"));
SolrInputDocument three = children.get(1);
assertEquals("3", three.getFieldValue("id"));
assertEquals("Bar", three.getFieldValue("foo_s"));
req.close();
}
@Test
public void testSingleRelationalChildDoc() throws Exception {
String str =
"{\n"
+ " \"add\": {\n"
+ " \"doc\": {\n"
+ " \"id\": \"1\",\n"
+ " \"child1\": \n"
+ " {\n"
+ " \"id\": \"2\",\n"
+ " \"foo_s\": \"Yaz\"\n"
+ " },\n"
+ " }\n"
+ " }\n"
+ "}";
SolrQueryRequest req = req("commit", "true");
SolrQueryResponse rsp = new SolrQueryResponse();
BufferingRequestProcessor p = new BufferingRequestProcessor(null);
JsonLoader loader = new JsonLoader();
loader.load(req, rsp, new ContentStreamBase.StringStream(str), p);
assertEquals(1, p.addCommands.size());
AddUpdateCommand add = p.addCommands.get(0);
SolrInputDocument one = add.solrDoc;
assertEquals("1", one.getFieldValue("id"));
assertTrue(one.keySet().contains("child1"));
SolrInputDocument two = (SolrInputDocument) one.getField("child1").getValue();
assertEquals("2", two.getFieldValue("id"));
assertEquals("Yaz", two.getFieldValue("foo_s"));
req.close();
}
@Test
public void JSONLoader_denseVector_shouldIndexCorrectly() throws Exception {
updateJ(json("[{'id':'888','vector':[1.8,2.8,3.8,4.8]}]"), params("commit", "true"));
assertJQ(
req("q", "id:888", "fl", "vector"), "/response/docs/[0]=={'vector':[1.8,2.8,3.8,4.8]}");
}
}
| |
/*
* Copyright 2014-2019 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.licensemanager.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/license-manager-2018-08-01/CreateLicenseConfiguration"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateLicenseConfigurationRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* Name of the license configuration.
* </p>
*/
private String name;
/**
* <p>
* Human-friendly description of the license configuration.
* </p>
*/
private String description;
/**
* <p>
* Dimension to use to track the license inventory.
* </p>
*/
private String licenseCountingType;
/**
* <p>
* Number of licenses managed by the license configuration.
* </p>
*/
private Long licenseCount;
/**
* <p>
* Flag indicating whether hard or soft license enforcement is used. Exceeding a hard limit results in the blocked
* deployment of new instances.
* </p>
*/
private Boolean licenseCountHardLimit;
/**
* <p>
* Array of configured License Manager rules.
* </p>
*/
private java.util.List<String> licenseRules;
/**
* <p>
* The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified
* tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been
* created, see CreateTags .
* </p>
* <p/>
*/
private java.util.List<Tag> tags;
/**
* <p>
* Name of the license configuration.
* </p>
*
* @param name
* Name of the license configuration.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* Name of the license configuration.
* </p>
*
* @return Name of the license configuration.
*/
public String getName() {
return this.name;
}
/**
* <p>
* Name of the license configuration.
* </p>
*
* @param name
* Name of the license configuration.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateLicenseConfigurationRequest withName(String name) {
setName(name);
return this;
}
/**
* <p>
* Human-friendly description of the license configuration.
* </p>
*
* @param description
* Human-friendly description of the license configuration.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* Human-friendly description of the license configuration.
* </p>
*
* @return Human-friendly description of the license configuration.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* Human-friendly description of the license configuration.
* </p>
*
* @param description
* Human-friendly description of the license configuration.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateLicenseConfigurationRequest withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* Dimension to use to track the license inventory.
* </p>
*
* @param licenseCountingType
* Dimension to use to track the license inventory.
* @see LicenseCountingType
*/
public void setLicenseCountingType(String licenseCountingType) {
this.licenseCountingType = licenseCountingType;
}
/**
* <p>
* Dimension to use to track the license inventory.
* </p>
*
* @return Dimension to use to track the license inventory.
* @see LicenseCountingType
*/
public String getLicenseCountingType() {
return this.licenseCountingType;
}
/**
* <p>
* Dimension to use to track the license inventory.
* </p>
*
* @param licenseCountingType
* Dimension to use to track the license inventory.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LicenseCountingType
*/
public CreateLicenseConfigurationRequest withLicenseCountingType(String licenseCountingType) {
setLicenseCountingType(licenseCountingType);
return this;
}
/**
* <p>
* Dimension to use to track the license inventory.
* </p>
*
* @param licenseCountingType
* Dimension to use to track the license inventory.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LicenseCountingType
*/
public CreateLicenseConfigurationRequest withLicenseCountingType(LicenseCountingType licenseCountingType) {
this.licenseCountingType = licenseCountingType.toString();
return this;
}
/**
* <p>
* Number of licenses managed by the license configuration.
* </p>
*
* @param licenseCount
* Number of licenses managed by the license configuration.
*/
public void setLicenseCount(Long licenseCount) {
this.licenseCount = licenseCount;
}
/**
* <p>
* Number of licenses managed by the license configuration.
* </p>
*
* @return Number of licenses managed by the license configuration.
*/
public Long getLicenseCount() {
return this.licenseCount;
}
/**
* <p>
* Number of licenses managed by the license configuration.
* </p>
*
* @param licenseCount
* Number of licenses managed by the license configuration.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateLicenseConfigurationRequest withLicenseCount(Long licenseCount) {
setLicenseCount(licenseCount);
return this;
}
/**
* <p>
* Flag indicating whether hard or soft license enforcement is used. Exceeding a hard limit results in the blocked
* deployment of new instances.
* </p>
*
* @param licenseCountHardLimit
* Flag indicating whether hard or soft license enforcement is used. Exceeding a hard limit results in the
* blocked deployment of new instances.
*/
public void setLicenseCountHardLimit(Boolean licenseCountHardLimit) {
this.licenseCountHardLimit = licenseCountHardLimit;
}
/**
* <p>
* Flag indicating whether hard or soft license enforcement is used. Exceeding a hard limit results in the blocked
* deployment of new instances.
* </p>
*
* @return Flag indicating whether hard or soft license enforcement is used. Exceeding a hard limit results in the
* blocked deployment of new instances.
*/
public Boolean getLicenseCountHardLimit() {
return this.licenseCountHardLimit;
}
/**
* <p>
* Flag indicating whether hard or soft license enforcement is used. Exceeding a hard limit results in the blocked
* deployment of new instances.
* </p>
*
* @param licenseCountHardLimit
* Flag indicating whether hard or soft license enforcement is used. Exceeding a hard limit results in the
* blocked deployment of new instances.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateLicenseConfigurationRequest withLicenseCountHardLimit(Boolean licenseCountHardLimit) {
setLicenseCountHardLimit(licenseCountHardLimit);
return this;
}
/**
* <p>
* Flag indicating whether hard or soft license enforcement is used. Exceeding a hard limit results in the blocked
* deployment of new instances.
* </p>
*
* @return Flag indicating whether hard or soft license enforcement is used. Exceeding a hard limit results in the
* blocked deployment of new instances.
*/
public Boolean isLicenseCountHardLimit() {
return this.licenseCountHardLimit;
}
/**
* <p>
* Array of configured License Manager rules.
* </p>
*
* @return Array of configured License Manager rules.
*/
public java.util.List<String> getLicenseRules() {
return licenseRules;
}
/**
* <p>
* Array of configured License Manager rules.
* </p>
*
* @param licenseRules
* Array of configured License Manager rules.
*/
public void setLicenseRules(java.util.Collection<String> licenseRules) {
if (licenseRules == null) {
this.licenseRules = null;
return;
}
this.licenseRules = new java.util.ArrayList<String>(licenseRules);
}
/**
* <p>
* Array of configured License Manager rules.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setLicenseRules(java.util.Collection)} or {@link #withLicenseRules(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param licenseRules
* Array of configured License Manager rules.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateLicenseConfigurationRequest withLicenseRules(String... licenseRules) {
if (this.licenseRules == null) {
setLicenseRules(new java.util.ArrayList<String>(licenseRules.length));
}
for (String ele : licenseRules) {
this.licenseRules.add(ele);
}
return this;
}
/**
* <p>
* Array of configured License Manager rules.
* </p>
*
* @param licenseRules
* Array of configured License Manager rules.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateLicenseConfigurationRequest withLicenseRules(java.util.Collection<String> licenseRules) {
setLicenseRules(licenseRules);
return this;
}
/**
* <p>
* The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified
* tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been
* created, see CreateTags .
* </p>
* <p/>
*
* @return The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The
* specified tags are applied to all instances or volumes that are created during launch. To tag a resource
* after it has been created, see CreateTags .
* </p>
*/
public java.util.List<Tag> getTags() {
return tags;
}
/**
* <p>
* The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified
* tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been
* created, see CreateTags .
* </p>
* <p/>
*
* @param tags
* The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The
* specified tags are applied to all instances or volumes that are created during launch. To tag a resource
* after it has been created, see CreateTags .
* </p>
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new java.util.ArrayList<Tag>(tags);
}
/**
* <p>
* The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified
* tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been
* created, see CreateTags .
* </p>
* <p/>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The
* specified tags are applied to all instances or volumes that are created during launch. To tag a resource
* after it has been created, see CreateTags .</p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateLicenseConfigurationRequest withTags(Tag... tags) {
if (this.tags == null) {
setTags(new java.util.ArrayList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The specified
* tags are applied to all instances or volumes that are created during launch. To tag a resource after it has been
* created, see CreateTags .
* </p>
* <p/>
*
* @param tags
* The tags to apply to the resources during launch. You can only tag instances and volumes on launch. The
* specified tags are applied to all instances or volumes that are created during launch. To tag a resource
* after it has been created, see CreateTags .
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateLicenseConfigurationRequest withTags(java.util.Collection<Tag> tags) {
setTags(tags);
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 (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getLicenseCountingType() != null)
sb.append("LicenseCountingType: ").append(getLicenseCountingType()).append(",");
if (getLicenseCount() != null)
sb.append("LicenseCount: ").append(getLicenseCount()).append(",");
if (getLicenseCountHardLimit() != null)
sb.append("LicenseCountHardLimit: ").append(getLicenseCountHardLimit()).append(",");
if (getLicenseRules() != null)
sb.append("LicenseRules: ").append(getLicenseRules()).append(",");
if (getTags() != null)
sb.append("Tags: ").append(getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateLicenseConfigurationRequest == false)
return false;
CreateLicenseConfigurationRequest other = (CreateLicenseConfigurationRequest) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getLicenseCountingType() == null ^ this.getLicenseCountingType() == null)
return false;
if (other.getLicenseCountingType() != null && other.getLicenseCountingType().equals(this.getLicenseCountingType()) == false)
return false;
if (other.getLicenseCount() == null ^ this.getLicenseCount() == null)
return false;
if (other.getLicenseCount() != null && other.getLicenseCount().equals(this.getLicenseCount()) == false)
return false;
if (other.getLicenseCountHardLimit() == null ^ this.getLicenseCountHardLimit() == null)
return false;
if (other.getLicenseCountHardLimit() != null && other.getLicenseCountHardLimit().equals(this.getLicenseCountHardLimit()) == false)
return false;
if (other.getLicenseRules() == null ^ this.getLicenseRules() == null)
return false;
if (other.getLicenseRules() != null && other.getLicenseRules().equals(this.getLicenseRules()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getLicenseCountingType() == null) ? 0 : getLicenseCountingType().hashCode());
hashCode = prime * hashCode + ((getLicenseCount() == null) ? 0 : getLicenseCount().hashCode());
hashCode = prime * hashCode + ((getLicenseCountHardLimit() == null) ? 0 : getLicenseCountHardLimit().hashCode());
hashCode = prime * hashCode + ((getLicenseRules() == null) ? 0 : getLicenseRules().hashCode());
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public CreateLicenseConfigurationRequest clone() {
return (CreateLicenseConfigurationRequest) super.clone();
}
}
| |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.spongepowered.common.world;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.MemoryDataContainer;
import org.spongepowered.api.entity.living.player.gamemode.GameMode;
import org.spongepowered.api.entity.living.player.gamemode.GameModes;
import org.spongepowered.api.world.DimensionType;
import org.spongepowered.api.world.DimensionTypes;
import org.spongepowered.api.world.GeneratorType;
import org.spongepowered.api.world.GeneratorTypes;
import org.spongepowered.api.world.TeleporterAgent;
import org.spongepowered.api.world.WorldCreationSettings;
import org.spongepowered.api.world.gen.WorldGeneratorModifier;
import org.spongepowered.api.world.storage.WorldProperties;
import org.spongepowered.common.interfaces.world.IMixinWorldSettings;
import org.spongepowered.common.registry.type.world.GeneratorModifierRegistryModule;
import java.util.Random;
public class SpongeWorldCreationSettingsBuilder implements WorldCreationSettings.Builder {
private String name;
private long seed;
private GameMode gameMode;
private GeneratorType generatorType;
private DimensionType dimensionType;
private boolean mapFeaturesEnabled;
private boolean hardcore;
private boolean worldEnabled;
private boolean loadOnStartup;
private boolean keepSpawnLoaded;
private boolean generateSpawnOnLoad;
private boolean isMod;
private boolean pvpEnabled;
private int dimensionId; // internal use only
private DataContainer generatorSettings;
private ImmutableList<WorldGeneratorModifier> generatorModifiers;
public SpongeWorldCreationSettingsBuilder() {
reset();
}
public SpongeWorldCreationSettingsBuilder(WorldCreationSettings settings) {
this.name = settings.getWorldName();
this.seed = settings.getSeed();
this.gameMode = settings.getGameMode();
this.generatorType = settings.getGeneratorType();
this.generatorModifiers = ImmutableList.copyOf(settings.getGeneratorModifiers());
this.dimensionType = settings.getDimensionType();
this.mapFeaturesEnabled = settings.usesMapFeatures();
this.hardcore = settings.isHardcore();
this.worldEnabled = settings.isEnabled();
this.loadOnStartup = settings.loadOnStartup();
this.keepSpawnLoaded = settings.doesKeepSpawnLoaded();
this.generateSpawnOnLoad = settings.doesGenerateSpawnOnLoad();
this.pvpEnabled = settings.isPVPEnabled();
}
public SpongeWorldCreationSettingsBuilder(WorldProperties properties) {
this.name = properties.getWorldName();
this.seed = properties.getSeed();
this.gameMode = properties.getGameMode();
this.generatorType = properties.getGeneratorType();
this.generatorModifiers = ImmutableList.copyOf(properties.getGeneratorModifiers());
this.dimensionType = properties.getDimensionType();
this.mapFeaturesEnabled = properties.usesMapFeatures();
this.hardcore = properties.isHardcore();
this.worldEnabled = properties.isEnabled();
this.loadOnStartup = properties.loadOnStartup();
this.keepSpawnLoaded = properties.doesKeepSpawnLoaded();
this.generateSpawnOnLoad = properties.doesGenerateSpawnOnLoad();
this.pvpEnabled = properties.isPVPEnabled();
}
@Override
public SpongeWorldCreationSettingsBuilder fill(WorldCreationSettings settings) {
checkNotNull(settings);
this.name = settings.getWorldName();
this.seed = settings.getSeed();
this.gameMode = settings.getGameMode();
this.generatorType = settings.getGeneratorType();
this.dimensionType = settings.getDimensionType();
this.mapFeaturesEnabled = settings.usesMapFeatures();
this.hardcore = settings.isHardcore();
this.worldEnabled = settings.isEnabled();
this.loadOnStartup = settings.loadOnStartup();
this.keepSpawnLoaded = settings.doesKeepSpawnLoaded();
this.generateSpawnOnLoad = settings.doesGenerateSpawnOnLoad();
this.pvpEnabled = settings.isPVPEnabled();
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder fill(WorldProperties properties) {
checkNotNull(properties);
this.name = properties.getWorldName();
this.seed = properties.getSeed();
this.gameMode = properties.getGameMode();
this.generatorType = properties.getGeneratorType();
this.dimensionType = properties.getDimensionType();
this.mapFeaturesEnabled = properties.usesMapFeatures();
this.hardcore = properties.isHardcore();
this.worldEnabled = properties.isEnabled();
this.loadOnStartup = properties.loadOnStartup();
this.keepSpawnLoaded = properties.doesKeepSpawnLoaded();
this.generateSpawnOnLoad = properties.doesGenerateSpawnOnLoad();
this.pvpEnabled = properties.isPVPEnabled();
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder name(String name) {
this.name = name;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder seed(long seed) {
this.seed = seed;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder gameMode(GameMode gameMode) {
this.gameMode = gameMode;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder generator(GeneratorType type) {
this.generatorType = type;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder dimension(DimensionType type) {
this.dimensionType = type;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder usesMapFeatures(boolean enabled) {
this.mapFeaturesEnabled = enabled;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder hardcore(boolean enabled) {
this.hardcore = enabled;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder enabled(boolean state) {
this.worldEnabled = state;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder loadsOnStartup(boolean state) {
this.loadOnStartup = state;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder keepsSpawnLoaded(boolean state) {
this.keepSpawnLoaded = state;
return this;
}
@Override
public WorldCreationSettings.Builder generateSpawnOnLoad(boolean state) {
this.generateSpawnOnLoad = state;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder generatorSettings(DataContainer settings) {
this.generatorSettings = settings;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder generatorModifiers(WorldGeneratorModifier... modifiers) {
ImmutableList<WorldGeneratorModifier> defensiveCopy = ImmutableList.copyOf(modifiers);
GeneratorModifierRegistryModule.getInstance().checkAllRegistered(defensiveCopy);
this.generatorModifiers = defensiveCopy;
return this;
}
public SpongeWorldCreationSettingsBuilder dimensionId(int id) {
this.dimensionId = id;
return this;
}
public SpongeWorldCreationSettingsBuilder isMod(boolean flag) {
this.isMod = flag;
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder teleporterAgent(TeleporterAgent agent) {
// TODO
return null;
}
@Override
public SpongeWorldCreationSettingsBuilder pvp(boolean enabled) {
this.pvpEnabled = enabled;
return this;
}
@Override
public WorldCreationSettings.Builder from(WorldCreationSettings value) {
this.name = value.getWorldName();
this.seed = value.getSeed();
this.gameMode = value.getGameMode();
this.generatorType = value.getGeneratorType();
this.dimensionType = value.getDimensionType();
this.mapFeaturesEnabled = value.usesMapFeatures();
this.hardcore = value.isHardcore();
this.worldEnabled = value.isEnabled();
this.loadOnStartup = value.loadOnStartup();
this.keepSpawnLoaded = value.doesKeepSpawnLoaded();
this.generateSpawnOnLoad = value.doesGenerateSpawnOnLoad();
this.generatorSettings = value.getGeneratorSettings().copy();
this.generatorModifiers = ImmutableList.copyOf(value.getGeneratorModifiers());
this.dimensionId = ((IMixinWorldSettings) value).getDimensionId();
this.isMod = ((IMixinWorldSettings) value).getIsMod();
this.pvpEnabled = value.isPVPEnabled();
return this;
}
@Override
public SpongeWorldCreationSettingsBuilder reset() {
this.name = null;
this.seed = new Random().nextLong();
this.gameMode = GameModes.SURVIVAL;
this.generatorType = GeneratorTypes.DEFAULT;
this.dimensionType = DimensionTypes.OVERWORLD;
this.mapFeaturesEnabled = true;
this.hardcore = false;
this.worldEnabled = true;
this.loadOnStartup = true;
this.keepSpawnLoaded = true;
this.generateSpawnOnLoad = true;
this.generatorSettings = new MemoryDataContainer();
this.generatorModifiers = ImmutableList.of();
this.dimensionId = 0;
this.isMod = false;
this.pvpEnabled = true;
return this;
}
@Override
public WorldCreationSettings build() {
checkNotNull(name, "Building the settings to make a world requires a non-null name!");
final WorldSettings settings =
new WorldSettings(this.seed, (WorldSettings.GameType) (Object) this.gameMode, this.mapFeaturesEnabled, this.hardcore,
(WorldType) this.generatorType);
((IMixinWorldSettings) (Object) settings).setActualWorldName(this.name);
((IMixinWorldSettings) (Object) settings).setDimensionType(this.dimensionType);
((IMixinWorldSettings) (Object) settings).setGeneratorSettings(this.generatorSettings);
((IMixinWorldSettings) (Object) settings).setGeneratorModifiers(this.generatorModifiers);
((IMixinWorldSettings) (Object) settings).setEnabled(this.worldEnabled);
((IMixinWorldSettings) (Object) settings).setKeepSpawnLoaded(this.keepSpawnLoaded);
((IMixinWorldSettings) (Object) settings).setGenerateSpawnOnLoad(this.generateSpawnOnLoad);
((IMixinWorldSettings) (Object) settings).setLoadOnStartup(this.loadOnStartup);
if (this.dimensionId != 0) {
((IMixinWorldSettings) (Object) settings).setDimensionId(this.dimensionId);
((IMixinWorldSettings) (Object) settings).setIsMod(this.isMod);
}
((IMixinWorldSettings) (Object) settings).setPVPEnabled(this.pvpEnabled);
((IMixinWorldSettings) (Object) settings).fromBuilder(true);
return (WorldCreationSettings) (Object) settings;
}
}
| |
/*
* 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.indexing.overlord;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.druid.indexer.TaskState;
import org.apache.druid.indexer.TaskStatus;
import org.apache.druid.indexing.common.SegmentLoaderFactory;
import org.apache.druid.indexing.common.SingleFileTaskReportFileWriter;
import org.apache.druid.indexing.common.TaskToolbox;
import org.apache.druid.indexing.common.TaskToolboxFactory;
import org.apache.druid.indexing.common.TestUtils;
import org.apache.druid.indexing.common.actions.TaskActionClient;
import org.apache.druid.indexing.common.actions.TaskActionClientFactory;
import org.apache.druid.indexing.common.config.TaskConfig;
import org.apache.druid.indexing.common.task.AbstractTask;
import org.apache.druid.indexing.common.task.NoopTask;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
import org.apache.druid.segment.join.NoopJoinableFactory;
import org.apache.druid.segment.loading.NoopDataSegmentArchiver;
import org.apache.druid.segment.loading.NoopDataSegmentKiller;
import org.apache.druid.segment.loading.NoopDataSegmentMover;
import org.apache.druid.segment.loading.NoopDataSegmentPusher;
import org.apache.druid.server.DruidNode;
import org.apache.druid.server.coordination.NoopDataSegmentAnnouncer;
import org.apache.druid.server.initialization.ServerConfig;
import org.apache.druid.server.metrics.NoopServiceEmitter;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class SingleTaskBackgroundRunnerTest
{
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private SingleTaskBackgroundRunner runner;
@Before
public void setup() throws IOException
{
final TestUtils utils = new TestUtils();
final DruidNode node = new DruidNode("testServer", "testHost", false, 1000, null, true, false);
final TaskConfig taskConfig = new TaskConfig(
temporaryFolder.newFile().toString(),
null,
null,
50000,
null,
true,
null,
null,
null
);
final ServiceEmitter emitter = new NoopServiceEmitter();
final TaskToolboxFactory toolboxFactory = new TaskToolboxFactory(
taskConfig,
null,
EasyMock.createMock(TaskActionClientFactory.class),
emitter,
new NoopDataSegmentPusher(),
new NoopDataSegmentKiller(),
new NoopDataSegmentMover(),
new NoopDataSegmentArchiver(),
new NoopDataSegmentAnnouncer(),
null,
null,
null,
null,
NoopJoinableFactory.INSTANCE,
null,
new SegmentLoaderFactory(null, utils.getTestObjectMapper()),
utils.getTestObjectMapper(),
utils.getTestIndexIO(),
null,
null,
null,
utils.getTestIndexMergerV9(),
null,
node,
null,
null,
new SingleFileTaskReportFileWriter(new File("fake")),
null
);
runner = new SingleTaskBackgroundRunner(
toolboxFactory,
taskConfig,
emitter,
node,
new ServerConfig()
);
}
@After
public void teardown()
{
runner.stop();
}
@Test
public void testRun() throws ExecutionException, InterruptedException
{
Assert.assertEquals(
TaskState.SUCCESS,
runner.run(new NoopTask(null, null, null, 500L, 0, null, null, null)).get().getStatusCode()
);
}
@Test
public void testStop() throws ExecutionException, InterruptedException, TimeoutException
{
final ListenableFuture<TaskStatus> future = runner.run(
new NoopTask(null, null, null, Long.MAX_VALUE, 0, null, null, null) // infinite task
);
runner.stop();
Assert.assertEquals(
TaskState.FAILED,
future.get(1000, TimeUnit.MILLISECONDS).getStatusCode()
);
}
@Test
public void testStopWithRestorableTask() throws InterruptedException, ExecutionException, TimeoutException
{
final BooleanHolder holder = new BooleanHolder();
final ListenableFuture<TaskStatus> future = runner.run(
new RestorableTask(holder)
);
runner.stop();
Assert.assertEquals(
TaskState.SUCCESS,
future.get(1000, TimeUnit.MILLISECONDS).getStatusCode()
);
Assert.assertTrue(holder.get());
}
private static class RestorableTask extends AbstractTask
{
private final BooleanHolder gracefullyStopped;
RestorableTask(BooleanHolder gracefullyStopped)
{
super("testId", "testDataSource", Collections.emptyMap());
this.gracefullyStopped = gracefullyStopped;
}
@Override
public String getType()
{
return "restorable";
}
@Override
public boolean isReady(TaskActionClient taskActionClient)
{
return true;
}
@Override
public TaskStatus run(TaskToolbox toolbox)
{
return TaskStatus.success(getId());
}
@Override
public boolean canRestore()
{
return true;
}
@Override
public void stopGracefully(TaskConfig taskConfig)
{
gracefullyStopped.set();
}
}
private static class BooleanHolder
{
private boolean value;
void set()
{
this.value = true;
}
boolean get()
{
return value;
}
}
}
| |
/*
* Copyright 2010-2015 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.cloudwatch;
import org.w3c.dom.*;
import java.net.*;
import java.util.*;
import java.util.Map.Entry;
import org.apache.commons.logging.*;
import com.amazonaws.*;
import com.amazonaws.auth.*;
import com.amazonaws.handlers.*;
import com.amazonaws.http.*;
import com.amazonaws.internal.*;
import com.amazonaws.metrics.*;
import com.amazonaws.regions.*;
import com.amazonaws.transform.*;
import com.amazonaws.util.*;
import com.amazonaws.util.AWSRequestMetrics.Field;
import com.amazonaws.services.cloudwatch.model.*;
import com.amazonaws.services.cloudwatch.model.transform.*;
/**
* Client for accessing CloudWatch. All service calls made using this client are
* blocking, and will not return until the service call completes.
* <p>
* <p>
* This is the <i>Amazon CloudWatch API Reference</i>. This guide provides
* detailed information about Amazon CloudWatch actions, data types, parameters,
* and errors. For detailed information about Amazon CloudWatch features and
* their associated API calls, go to the <a href=
* "http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide"
* >Amazon CloudWatch Developer Guide</a>.
* </p>
* <p>
* Amazon CloudWatch is a web service that enables you to publish, monitor, and
* manage various metrics, as well as configure alarm actions based on data from
* metrics. For more information about this product go to <a
* href="http://aws.amazon.com/cloudwatch">http://aws.amazon.com/cloudwatch</a>.
* </p>
* <p>
* Use the following links to get started using the <i>Amazon CloudWatch API
* Reference</i>:
* </p>
* <ul>
* <li><a href=
* "http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_Operations.html"
* >Actions</a>: An alphabetical list of all Amazon CloudWatch actions.</li>
* <li><a href=
* "http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_Types.html"
* >Data Types</a>: An alphabetical list of all Amazon CloudWatch data types.</li>
* <li><a href=
* "http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/CommonParameters.html"
* >Common Parameters</a>: Parameters that all Query actions can use.</li>
* <li><a href=
* "http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/CommonErrors.html"
* >Common Errors</a>: Client and server errors that all actions can return.</li>
* <li><a href=
* "http://docs.amazonwebservices.com/general/latest/gr/index.html?rande.html"
* >Regions and Endpoints</a>: Itemized regions and endpoints for all AWS
* products.</li>
* <li><a
* href="http://monitoring.amazonaws.com/doc/2010-08-01/CloudWatch.wsdl">WSDL
* Location</a>: http://monitoring.amazonaws.com/doc/2010-08-01/CloudWatch.wsdl</li>
* </ul>
*/
public class AmazonCloudWatchClient extends AmazonWebServiceClient implements
AmazonCloudWatch {
/** Provider for AWS credentials. */
private AWSCredentialsProvider awsCredentialsProvider;
private static final Log log = LogFactory.getLog(AmazonCloudWatch.class);
/** Default signing name for the service. */
private static final String DEFAULT_SIGNING_NAME = "monitoring";
/** The region metadata service name for computing region endpoints. */
private static final String DEFAULT_ENDPOINT_PREFIX = "monitoring";
/**
* List of exception unmarshallers for all CloudWatch exceptions.
*/
protected final List<Unmarshaller<AmazonServiceException, Node>> exceptionUnmarshallers = new ArrayList<Unmarshaller<AmazonServiceException, Node>>();
/**
* Constructs a new client to invoke service methods on CloudWatch. A
* credentials provider chain will be used that searches for credentials in
* this order:
* <ul>
* <li>Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY</li>
* <li>Java System Properties - aws.accessKeyId and aws.secretKey</li>
* <li>Instance profile credentials delivered through the Amazon EC2
* metadata service</li>
* </ul>
*
* <p>
* All service calls made using this new client object are blocking, and
* will not return until the service call completes.
*
* @see DefaultAWSCredentialsProviderChain
*/
public AmazonCloudWatchClient() {
this(new DefaultAWSCredentialsProviderChain(),
com.amazonaws.PredefinedClientConfigurations.defaultConfig());
}
/**
* Constructs a new client to invoke service methods on CloudWatch. A
* credentials provider chain will be used that searches for credentials in
* this order:
* <ul>
* <li>Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY</li>
* <li>Java System Properties - aws.accessKeyId and aws.secretKey</li>
* <li>Instance profile credentials delivered through the Amazon EC2
* metadata service</li>
* </ul>
*
* <p>
* All service calls made using this new client object are blocking, and
* will not return until the service call completes.
*
* @param clientConfiguration
* The client configuration options controlling how this client
* connects to CloudWatch (ex: proxy settings, retry counts, etc.).
*
* @see DefaultAWSCredentialsProviderChain
*/
public AmazonCloudWatchClient(ClientConfiguration clientConfiguration) {
this(new DefaultAWSCredentialsProviderChain(), clientConfiguration);
}
/**
* Constructs a new client to invoke service methods on CloudWatch using the
* specified AWS account credentials.
*
* <p>
* All service calls made using this new client object are blocking, and
* will not return until the service call completes.
*
* @param awsCredentials
* The AWS credentials (access key ID and secret key) to use when
* authenticating with AWS services.
*/
public AmazonCloudWatchClient(AWSCredentials awsCredentials) {
this(awsCredentials, com.amazonaws.PredefinedClientConfigurations
.defaultConfig());
}
/**
* Constructs a new client to invoke service methods on CloudWatch using the
* specified AWS account credentials and client configuration options.
*
* <p>
* All service calls made using this new client object are blocking, and
* will not return until the service call completes.
*
* @param awsCredentials
* The AWS credentials (access key ID and secret key) to use when
* authenticating with AWS services.
* @param clientConfiguration
* The client configuration options controlling how this client
* connects to CloudWatch (ex: proxy settings, retry counts, etc.).
*/
public AmazonCloudWatchClient(AWSCredentials awsCredentials,
ClientConfiguration clientConfiguration) {
super(clientConfiguration);
this.awsCredentialsProvider = new StaticCredentialsProvider(
awsCredentials);
init();
}
/**
* Constructs a new client to invoke service methods on CloudWatch using the
* specified AWS account credentials provider.
*
* <p>
* All service calls made using this new client object are blocking, and
* will not return until the service call completes.
*
* @param awsCredentialsProvider
* The AWS credentials provider which will provide credentials to
* authenticate requests with AWS services.
*/
public AmazonCloudWatchClient(AWSCredentialsProvider awsCredentialsProvider) {
this(awsCredentialsProvider,
com.amazonaws.PredefinedClientConfigurations.defaultConfig());
}
/**
* Constructs a new client to invoke service methods on CloudWatch using the
* specified AWS account credentials provider and client configuration
* options.
*
* <p>
* All service calls made using this new client object are blocking, and
* will not return until the service call completes.
*
* @param awsCredentialsProvider
* The AWS credentials provider which will provide credentials to
* authenticate requests with AWS services.
* @param clientConfiguration
* The client configuration options controlling how this client
* connects to CloudWatch (ex: proxy settings, retry counts, etc.).
*/
public AmazonCloudWatchClient(
AWSCredentialsProvider awsCredentialsProvider,
ClientConfiguration clientConfiguration) {
this(awsCredentialsProvider, clientConfiguration, null);
}
/**
* Constructs a new client to invoke service methods on CloudWatch using the
* specified AWS account credentials provider, client configuration options,
* and request metric collector.
*
* <p>
* All service calls made using this new client object are blocking, and
* will not return until the service call completes.
*
* @param awsCredentialsProvider
* The AWS credentials provider which will provide credentials to
* authenticate requests with AWS services.
* @param clientConfiguration
* The client configuration options controlling how this client
* connects to CloudWatch (ex: proxy settings, retry counts, etc.).
* @param requestMetricCollector
* optional request metric collector
*/
public AmazonCloudWatchClient(
AWSCredentialsProvider awsCredentialsProvider,
ClientConfiguration clientConfiguration,
RequestMetricCollector requestMetricCollector) {
super(clientConfiguration, requestMetricCollector);
this.awsCredentialsProvider = awsCredentialsProvider;
init();
}
private void init() {
exceptionUnmarshallers.add(new InvalidNextTokenExceptionUnmarshaller());
exceptionUnmarshallers.add(new InvalidFormatExceptionUnmarshaller());
exceptionUnmarshallers.add(new LimitExceededExceptionUnmarshaller());
exceptionUnmarshallers
.add(new MissingRequiredParameterExceptionUnmarshaller());
exceptionUnmarshallers.add(new InternalServiceExceptionUnmarshaller());
exceptionUnmarshallers
.add(new InvalidParameterValueExceptionUnmarshaller());
exceptionUnmarshallers.add(new ResourceNotFoundExceptionUnmarshaller());
exceptionUnmarshallers
.add(new InvalidParameterCombinationExceptionUnmarshaller());
exceptionUnmarshallers.add(new StandardErrorUnmarshaller());
// calling this.setEndPoint(...) will also modify the signer accordingly
this.setEndpoint("https://monitoring.us-east-1.amazonaws.com");
setServiceNameIntern(DEFAULT_SIGNING_NAME);
setEndpointPrefix(DEFAULT_ENDPOINT_PREFIX);
HandlerChainFactory chainFactory = new HandlerChainFactory();
requestHandler2s
.addAll(chainFactory
.newRequestHandlerChain("/com/amazonaws/services/cloudwatch/request.handlers"));
requestHandler2s
.addAll(chainFactory
.newRequestHandler2Chain("/com/amazonaws/services/cloudwatch/request.handler2s"));
}
/**
* <p>
* Deletes all specified alarms. In the event of an error, no alarms are
* deleted.
* </p>
*
* @param deleteAlarmsRequest
* @throws ResourceNotFoundException
* The named resource does not exist.
*/
@Override
public void deleteAlarms(DeleteAlarmsRequest deleteAlarmsRequest) {
ExecutionContext executionContext = createExecutionContext(deleteAlarmsRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DeleteAlarmsRequest> request = null;
Response<Void> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DeleteAlarmsRequestMarshaller()
.marshall(deleteAlarmsRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<Void> responseHandler = new StaxResponseHandler<Void>(
null);
invoke(request, responseHandler, executionContext);
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Retrieves history for the specified alarm. Filter alarms by date range or
* item type. If an alarm name is not specified, Amazon CloudWatch returns
* histories for all of the owner's alarms.
* </p>
* <note> Amazon CloudWatch retains the history of an alarm for two weeks,
* whether or not you delete the alarm. </note>
*
* @param describeAlarmHistoryRequest
* @return Result of the DescribeAlarmHistory operation returned by the
* service.
* @throws InvalidNextTokenException
* The next token specified is invalid.
*/
@Override
public DescribeAlarmHistoryResult describeAlarmHistory(
DescribeAlarmHistoryRequest describeAlarmHistoryRequest) {
ExecutionContext executionContext = createExecutionContext(describeAlarmHistoryRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DescribeAlarmHistoryRequest> request = null;
Response<DescribeAlarmHistoryResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DescribeAlarmHistoryRequestMarshaller()
.marshall(describeAlarmHistoryRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<DescribeAlarmHistoryResult> responseHandler = new StaxResponseHandler<DescribeAlarmHistoryResult>(
new DescribeAlarmHistoryResultStaxUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
@Override
public DescribeAlarmHistoryResult describeAlarmHistory() {
return describeAlarmHistory(new DescribeAlarmHistoryRequest());
}
/**
* <p>
* Retrieves alarms with the specified names. If no name is specified, all
* alarms for the user are returned. Alarms can be retrieved by using only a
* prefix for the alarm name, the alarm state, or a prefix for any action.
* </p>
*
* @param describeAlarmsRequest
* @return Result of the DescribeAlarms operation returned by the service.
* @throws InvalidNextTokenException
* The next token specified is invalid.
*/
@Override
public DescribeAlarmsResult describeAlarms(
DescribeAlarmsRequest describeAlarmsRequest) {
ExecutionContext executionContext = createExecutionContext(describeAlarmsRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DescribeAlarmsRequest> request = null;
Response<DescribeAlarmsResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DescribeAlarmsRequestMarshaller()
.marshall(describeAlarmsRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<DescribeAlarmsResult> responseHandler = new StaxResponseHandler<DescribeAlarmsResult>(
new DescribeAlarmsResultStaxUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
@Override
public DescribeAlarmsResult describeAlarms() {
return describeAlarms(new DescribeAlarmsRequest());
}
/**
* <p>
* Retrieves all alarms for a single metric. Specify a statistic, period, or
* unit to filter the set of alarms further.
* </p>
*
* @param describeAlarmsForMetricRequest
* @return Result of the DescribeAlarmsForMetric operation returned by the
* service.
*/
@Override
public DescribeAlarmsForMetricResult describeAlarmsForMetric(
DescribeAlarmsForMetricRequest describeAlarmsForMetricRequest) {
ExecutionContext executionContext = createExecutionContext(describeAlarmsForMetricRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DescribeAlarmsForMetricRequest> request = null;
Response<DescribeAlarmsForMetricResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DescribeAlarmsForMetricRequestMarshaller()
.marshall(describeAlarmsForMetricRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<DescribeAlarmsForMetricResult> responseHandler = new StaxResponseHandler<DescribeAlarmsForMetricResult>(
new DescribeAlarmsForMetricResultStaxUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Disables actions for the specified alarms. When an alarm's actions are
* disabled the alarm's state may change, but none of the alarm's actions
* will execute.
* </p>
*
* @param disableAlarmActionsRequest
*/
@Override
public void disableAlarmActions(
DisableAlarmActionsRequest disableAlarmActionsRequest) {
ExecutionContext executionContext = createExecutionContext(disableAlarmActionsRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DisableAlarmActionsRequest> request = null;
Response<Void> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DisableAlarmActionsRequestMarshaller()
.marshall(disableAlarmActionsRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<Void> responseHandler = new StaxResponseHandler<Void>(
null);
invoke(request, responseHandler, executionContext);
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Enables actions for the specified alarms.
* </p>
*
* @param enableAlarmActionsRequest
*/
@Override
public void enableAlarmActions(
EnableAlarmActionsRequest enableAlarmActionsRequest) {
ExecutionContext executionContext = createExecutionContext(enableAlarmActionsRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<EnableAlarmActionsRequest> request = null;
Response<Void> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new EnableAlarmActionsRequestMarshaller()
.marshall(enableAlarmActionsRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<Void> responseHandler = new StaxResponseHandler<Void>(
null);
invoke(request, responseHandler, executionContext);
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Gets statistics for the specified metric.
* </p>
* <note> The maximum number of data points returned from a single
* <code>GetMetricStatistics</code> request is 1,440. If a request is made
* that generates more than 1,440 data points, Amazon CloudWatch returns an
* error. In such a case, alter the request by narrowing the specified time
* range or increasing the specified period. Alternatively, make multiple
* requests across adjacent time ranges. </note>
* <p>
* Amazon CloudWatch aggregates data points based on the length of the
* <code>period</code> that you specify. For example, if you request
* statistics with a one-minute granularity, Amazon CloudWatch aggregates
* data points with time stamps that fall within the same one-minute period.
* In such a case, the data points queried can greatly outnumber the data
* points returned.
* </p>
* <note> The maximum number of data points that can be queried is 50,850;
* whereas the maximum number of data points returned is 1,440. </note>
* <p>
* The following examples show various statistics allowed by the data point
* query maximum of 50,850 when you call <code>GetMetricStatistics</code> on
* Amazon EC2 instances with detailed (one-minute) monitoring enabled:
* </p>
* <ul>
* <li>Statistics for up to 400 instances for a span of one hour</li>
* <li>Statistics for up to 35 instances over a span of 24 hours</li>
* <li>Statistics for up to 2 instances over a span of 2 weeks</li>
* </ul>
*
* @param getMetricStatisticsRequest
* @return Result of the GetMetricStatistics operation returned by the
* service.
* @throws InvalidParameterValueException
* Bad or out-of-range value was supplied for the input parameter.
* @throws MissingRequiredParameterException
* An input parameter that is mandatory for processing the request
* is not supplied.
* @throws InvalidParameterCombinationException
* Parameters that must not be used together were used together.
* @throws InternalServiceException
* Indicates that the request processing has failed due to some
* unknown error, exception, or failure.
*/
@Override
public GetMetricStatisticsResult getMetricStatistics(
GetMetricStatisticsRequest getMetricStatisticsRequest) {
ExecutionContext executionContext = createExecutionContext(getMetricStatisticsRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<GetMetricStatisticsRequest> request = null;
Response<GetMetricStatisticsResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new GetMetricStatisticsRequestMarshaller()
.marshall(getMetricStatisticsRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<GetMetricStatisticsResult> responseHandler = new StaxResponseHandler<GetMetricStatisticsResult>(
new GetMetricStatisticsResultStaxUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Returns a list of valid metrics stored for the AWS account owner.
* Returned metrics can be used with <code>GetMetricStatistics</code> to
* obtain statistical data for a given metric.
* </p>
* <note> Up to 500 results are returned for any one call. To retrieve
* further results, use returned <code>NextToken</code> values with
* subsequent <code>ListMetrics</code> operations. </note> <note> If you
* create a metric with the <a>PutMetricData</a> action, allow up to fifteen
* minutes for the metric to appear in calls to the <code>ListMetrics</code>
* action. </note>
*
* @param listMetricsRequest
* @return Result of the ListMetrics operation returned by the service.
* @throws InternalServiceException
* Indicates that the request processing has failed due to some
* unknown error, exception, or failure.
* @throws InvalidParameterValueException
* Bad or out-of-range value was supplied for the input parameter.
*/
@Override
public ListMetricsResult listMetrics(ListMetricsRequest listMetricsRequest) {
ExecutionContext executionContext = createExecutionContext(listMetricsRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<ListMetricsRequest> request = null;
Response<ListMetricsResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new ListMetricsRequestMarshaller()
.marshall(listMetricsRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<ListMetricsResult> responseHandler = new StaxResponseHandler<ListMetricsResult>(
new ListMetricsResultStaxUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
@Override
public ListMetricsResult listMetrics() {
return listMetrics(new ListMetricsRequest());
}
/**
* <p>
* Creates or updates an alarm and associates it with the specified Amazon
* CloudWatch metric. Optionally, this operation can associate one or more
* Amazon Simple Notification Service resources with the alarm.
* </p>
* <p>
* When this operation creates an alarm, the alarm state is immediately set
* to <code>INSUFFICIENT_DATA</code>. The alarm is evaluated and its
* <code>StateValue</code> is set appropriately. Any actions associated with
* the <code>StateValue</code> is then executed.
* </p>
* <note> When updating an existing alarm, its <code>StateValue</code> is
* left unchanged. </note>
*
* @param putMetricAlarmRequest
* @throws LimitExceededException
* The quota for alarms for this customer has already been reached.
*/
@Override
public void putMetricAlarm(PutMetricAlarmRequest putMetricAlarmRequest) {
ExecutionContext executionContext = createExecutionContext(putMetricAlarmRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<PutMetricAlarmRequest> request = null;
Response<Void> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new PutMetricAlarmRequestMarshaller()
.marshall(putMetricAlarmRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<Void> responseHandler = new StaxResponseHandler<Void>(
null);
invoke(request, responseHandler, executionContext);
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch
* associates the data points with the specified metric. If the specified
* metric does not exist, Amazon CloudWatch creates the metric.
* </p>
* <note> If you create a metric with the <code>PutMetricData</code> action,
* allow up to fifteen minutes for the metric to appear in calls to the
* <a>ListMetrics</a> action. </note>
* <p>
* The size of a <function>PutMetricData</function> request is limited to 8
* KB for HTTP GET requests and 40 KB for HTTP POST requests.
* </p>
* <important> Although the <code>Value</code> parameter accepts numbers of
* type <code>Double</code>, Amazon CloudWatch truncates values with very
* large exponents. Values with base-10 exponents greater than 126 (1 x
* 10^126) are truncated. Likewise, values with base-10 exponents less than
* -130 (1 x 10^-130) are also truncated. </important>
*
* @param putMetricDataRequest
* @throws InvalidParameterValueException
* Bad or out-of-range value was supplied for the input parameter.
* @throws MissingRequiredParameterException
* An input parameter that is mandatory for processing the request
* is not supplied.
* @throws InvalidParameterCombinationException
* Parameters that must not be used together were used together.
* @throws InternalServiceException
* Indicates that the request processing has failed due to some
* unknown error, exception, or failure.
*/
@Override
public void putMetricData(PutMetricDataRequest putMetricDataRequest) {
ExecutionContext executionContext = createExecutionContext(putMetricDataRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<PutMetricDataRequest> request = null;
Response<Void> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new PutMetricDataRequestMarshaller()
.marshall(putMetricDataRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<Void> responseHandler = new StaxResponseHandler<Void>(
null);
invoke(request, responseHandler, executionContext);
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Temporarily sets the state of an alarm. When the updated
* <code>StateValue</code> differs from the previous value, the action
* configured for the appropriate state is invoked. This is not a permanent
* change. The next periodic alarm check (in about a minute) will set the
* alarm to its actual state.
* </p>
*
* @param setAlarmStateRequest
* @throws ResourceNotFoundException
* The named resource does not exist.
* @throws InvalidFormatException
* Data was not syntactically valid JSON.
*/
@Override
public void setAlarmState(SetAlarmStateRequest setAlarmStateRequest) {
ExecutionContext executionContext = createExecutionContext(setAlarmStateRequest);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<SetAlarmStateRequest> request = null;
Response<Void> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new SetAlarmStateRequestMarshaller()
.marshall(setAlarmStateRequest);
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
StaxResponseHandler<Void> responseHandler = new StaxResponseHandler<Void>(
null);
invoke(request, responseHandler, executionContext);
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* Returns additional metadata for a previously executed successful,
* request, typically used for debugging issues where a service isn't acting
* as expected. This data isn't considered part of the result data returned
* by an operation, so it's available through this separate, diagnostic
* interface.
* <p>
* Response metadata is only cached for a limited period of time, so if you
* need to access this extra diagnostic information for an executed request,
* you should use this method to retrieve it as soon as possible after
* executing the request.
*
* @param request
* The originally executed request
*
* @return The response metadata for the specified request, or null if none
* is available.
*/
public ResponseMetadata getCachedResponseMetadata(
AmazonWebServiceRequest request) {
return client.getResponseMetadataForRequest(request);
}
private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(
Request<Y> request,
HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext) {
request.setEndpoint(endpoint);
request.setTimeOffset(timeOffset);
AWSRequestMetrics awsRequestMetrics = executionContext
.getAwsRequestMetrics();
AWSCredentials credentials;
awsRequestMetrics.startEvent(Field.CredentialsRequestTime);
try {
credentials = awsCredentialsProvider.getCredentials();
} finally {
awsRequestMetrics.endEvent(Field.CredentialsRequestTime);
}
AmazonWebServiceRequest originalRequest = request.getOriginalRequest();
if (originalRequest != null
&& originalRequest.getRequestCredentials() != null) {
credentials = originalRequest.getRequestCredentials();
}
executionContext.setCredentials(credentials);
DefaultErrorResponseHandler errorResponseHandler = new DefaultErrorResponseHandler(
exceptionUnmarshallers);
return client.execute(request, responseHandler, errorResponseHandler,
executionContext);
}
}
| |
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
/*******************************************************************************
* Product of NIST/ITL Advanced Networking Technologies Division (ANTD). *
******************************************************************************/
package gov.nist.javax.sip.stack;
import gov.nist.core.CommonLogger;
import gov.nist.core.LogWriter;
import gov.nist.core.ServerLogger;
import gov.nist.core.StackLogger;
import gov.nist.javax.sip.LogRecord;
import gov.nist.javax.sip.header.CallID;
import gov.nist.javax.sip.message.SIPMessage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import javax.sip.SipStack;
import javax.sip.header.TimeStampHeader;
/**
* Log file wrapper class. Log messages into the message trace file and also write the log into
* the debug file if needed. This class keeps an XML formatted trace around for later access via
* RMI. The trace can be viewed with a trace viewer (see tools.traceviewerapp).
*
* @version 1.2 $Revision: 1.42 $ $Date: 2010-12-15 11:43:02 $
*
* @author M. Ranganathan <br/>
*
*
*/
public class ServerLog implements ServerLogger {
private boolean logContent;
protected StackLogger stackLogger;
/**
* Name of the log file in which the trace is written out (default is null)
*/
private String logFileName;
/**
* Print writer that is used to write out the log file.
*/
private PrintWriter printWriter;
/**
* Set auxililary information to log with this trace.
*/
private String auxInfo;
private String description;
private String stackIpAddress;
private SIPTransactionStack sipStack;
private Properties configurationProperties;
public ServerLog() {
// Debug log file. Whatever gets logged by us also makes its way into debug log.
}
private void setProperties(Properties configurationProperties) {
this.configurationProperties = configurationProperties;
// Set a descriptive name for the message trace logger.
this.description = configurationProperties.getProperty("javax.sip.STACK_NAME");
this.stackIpAddress = configurationProperties.getProperty("javax.sip.IP_ADDRESS");
this.logFileName = configurationProperties.getProperty("gov.nist.javax.sip.SERVER_LOG");
String logLevel = configurationProperties.getProperty("gov.nist.javax.sip.TRACE_LEVEL");
String logContent = configurationProperties
.getProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT");
this.logContent = (logContent != null && logContent.equals("true"));
if (logLevel != null) {
if (logLevel.equals("LOG4J")) {
CommonLogger.useLegacyLogger = false;
} else {
try {
int ll;
if (logLevel.equals("DEBUG")) {
ll = TRACE_DEBUG;
} else if (logLevel.equals("INFO")) {
ll = TRACE_MESSAGES;
} else if (logLevel.equals("ERROR")) {
ll = TRACE_EXCEPTION;
} else if (logLevel.equals("NONE") || logLevel.equals("OFF")) {
ll = TRACE_NONE;
} else {
ll = Integer.parseInt(logLevel);
}
this.setTraceLevel(ll);
} catch (NumberFormatException ex) {
System.out.println("ServerLog: WARNING Bad integer " + logLevel);
System.out.println("logging dislabled ");
this.setTraceLevel(0);
}
}
}
checkLogFile();
}
public void setStackIpAddress(String ipAddress) {
this.stackIpAddress = ipAddress;
}
// public static boolean isWebTesterCatchException=false;
// public static String webTesterLogFile=null;
/**
* default trace level
*/
protected int traceLevel = TRACE_MESSAGES;
public synchronized void closeLogFile() {
if (printWriter != null) {
printWriter.close();
printWriter = null;
}
}
public void checkLogFile() {
if (logFileName == null || traceLevel < TRACE_MESSAGES) {
// Dont create a log file if tracing is
// disabled.
return;
}
try {
File logFile = new File(logFileName);
if (!logFile.exists()) {
logFile.createNewFile();
printWriter = null;
}
// Append buffer to the end of the file unless otherwise specified
// by the user.
if (printWriter == null) {
boolean overwrite = Boolean.valueOf(
configurationProperties.getProperty(
"gov.nist.javax.sip.SERVER_LOG_OVERWRITE"));
FileWriter fw = new FileWriter(logFileName, !overwrite);
printWriter = new PrintWriter(fw, true);
printWriter.println("<!-- "
+ "Use the Trace Viewer in src/tools/tracesviewer to"
+ " view this trace \n"
+ "Here are the stack configuration properties \n"
+ "javax.sip.IP_ADDRESS= "
+ configurationProperties.getProperty("javax.sip.IP_ADDRESS") + "\n"
+ "javax.sip.STACK_NAME= "
+ configurationProperties.getProperty("javax.sip.STACK_NAME") + "\n"
+ "javax.sip.ROUTER_PATH= "
+ configurationProperties.getProperty("javax.sip.ROUTER_PATH") + "\n"
+ "javax.sip.OUTBOUND_PROXY= "
+ configurationProperties.getProperty("javax.sip.OUTBOUND_PROXY") + "\n"
+ "-->");
printWriter.println("<description\n logDescription=\"" + description
+ "\"\n name=\""
+ configurationProperties.getProperty("javax.sip.STACK_NAME")
+ "\"\n auxInfo=\"" + auxInfo + "\"/>\n ");
if (auxInfo != null) {
if (sipStack.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
stackLogger
.logDebug("Here are the stack configuration properties \n"
+ "javax.sip.IP_ADDRESS= "
+ configurationProperties
.getProperty("javax.sip.IP_ADDRESS")
+ "\n"
+ "javax.sip.ROUTER_PATH= "
+ configurationProperties
.getProperty("javax.sip.ROUTER_PATH")
+ "\n"
+ "javax.sip.OUTBOUND_PROXY= "
+ configurationProperties
.getProperty("javax.sip.OUTBOUND_PROXY")
+ "\n"
+ "gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS= "
+ configurationProperties
.getProperty("gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS")
+ "\n"
+ "gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS= "
+ configurationProperties
.getProperty("gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS")
+ "\n"
+ "gov.nist.javax.sip.REENTRANT_LISTENER= "
+ configurationProperties
.getProperty("gov.nist.javax.sip.REENTRANT_LISTENER")
+ "gov.nist.javax.sip.THREAD_POOL_SIZE= "
+ configurationProperties
.getProperty("gov.nist.javax.sip.THREAD_POOL_SIZE")
+ "\n");
stackLogger.logDebug(" ]]> ");
stackLogger.logDebug("</debug>");
stackLogger.logDebug("<description\n logDescription=\"" + description
+ "\"\n name=\"" + stackIpAddress + "\"\n auxInfo=\"" + auxInfo
+ "\"/>\n ");
stackLogger.logDebug("<debug>");
stackLogger.logDebug("<![CDATA[ ");
}
} else {
if (sipStack.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
stackLogger.logDebug("Here are the stack configuration properties \n"
+ configurationProperties + "\n");
stackLogger.logDebug(" ]]>");
stackLogger.logDebug("</debug>");
stackLogger.logDebug("<description\n logDescription=\"" + description
+ "\"\n name=\"" + stackIpAddress + "\" />\n");
stackLogger.logDebug("<debug>");
stackLogger.logDebug("<![CDATA[ ");
}
}
}
} catch (IOException ex) {
}
}
/**
* Global check for whether to log or not. To minimize the time return false here.
*
* @return true -- if logging is globally enabled and false otherwise.
*
*/
public boolean needsLogging() {
return logFileName != null;
}
/**
* Set the log file name
*
* @param name is the name of the log file to set.
*/
public void setLogFileName(String name) {
logFileName = name;
}
/**
* return the name of the log file.
*/
public String getLogFileName() {
return logFileName;
}
/**
* Log a message into the log file.
*
* @param message message to log into the log file.
*/
private void logMessage(String message) {
// String tname = Thread.currentThread().getName();
checkLogFile();
String logInfo = message;
if (printWriter != null) {
printWriter.println(logInfo);
}
if (sipStack.isLoggingEnabled()) {
stackLogger.logInfo(logInfo);
}
}
private void logMessage(String message, String from, String to, boolean sender,
String callId, String firstLine, String status, String tid, long time,
long timestampVal) {
LogRecord log = this.sipStack.logRecordFactory.createLogRecord(message, from, to, time,
sender, firstLine, tid, callId, timestampVal);
if (log != null)
logMessage(log.toString());
}
/**
* Log a message into the log directory.
*
* @param message a SIPMessage to log
* @param from from header of the message to log into the log directory
* @param to to header of the message to log into the log directory
* @param sender is the server the sender
* @param time is the time to associate with the message.
*/
public void logMessage(SIPMessage message, String from, String to, boolean sender, long time) {
checkLogFile();
if (message.getFirstLine() == null)
return;
CallID cid = (CallID) message.getCallId();
String callId = null;
if (cid != null)
callId = cid.getCallId();
String firstLine = message.getFirstLine().trim();
String inputText = (logContent ? message.encode() : message.encodeMessage(new StringBuilder()).toString());
String tid = message.getTransactionId();
TimeStampHeader tsHdr = (TimeStampHeader) message.getHeader(TimeStampHeader.NAME);
long tsval = tsHdr == null ? 0 : tsHdr.getTime();
logMessage(inputText, from, to, sender, callId, firstLine, null, tid, time, tsval);
}
/**
* Log a message into the log directory.
*
* @param message a SIPMessage to log
* @param from from header of the message to log into the log directory
* @param to to header of the message to log into the log directory
* @param status the status to log.
* @param sender is the server the sender or receiver (true if sender).
* @param time is the reception time.
*/
public void logMessage(SIPMessage message, String from, String to, String status,
boolean sender, long time) {
checkLogFile();
CallID cid = (CallID) message.getCallId();
String callId = null;
if (cid != null)
callId = cid.getCallId();
String firstLine = message.getFirstLine().trim();
String encoded = (logContent ? message.encode() : message.encodeMessage(new StringBuilder()).toString());
String tid = message.getTransactionId();
TimeStampHeader tshdr = (TimeStampHeader) message.getHeader(TimeStampHeader.NAME);
long tsval = tshdr == null ? 0 : tshdr.getTime();
logMessage(encoded, from, to, sender, callId, firstLine, status, tid, time, tsval);
}
/**
* Log a message into the log directory. Time stamp associated with the message is the current
* time.
*
* @param message a SIPMessage to log
* @param from from header of the message to log into the log directory
* @param to to header of the message to log into the log directory
* @param status the status to log.
* @param sender is the server the sender or receiver (true if sender).
*/
public void logMessage(SIPMessage message, String from, String to, String status,
boolean sender) {
logMessage(message, from, to, status, sender, System.currentTimeMillis());
}
/**
* Log an exception stack trace.
*
* @param ex Exception to log into the log file
*/
public void logException(Exception ex) {
if (traceLevel >= TRACE_EXCEPTION) {
checkLogFile();
ex.printStackTrace();
if (printWriter != null)
ex.printStackTrace(printWriter);
}
}
/**
* Set the trace level for the stack.
*
* @param level -- the trace level to set. The following trace levels are supported:
* <ul>
* <li> 0 -- no tracing </li>
*
* <li> 16 -- trace messages only </li>
*
* <li> 32 Full tracing including debug messages. </li>
*
* </ul>
*/
public void setTraceLevel(int level) {
traceLevel = level;
}
/**
* Get the trace level for the stack.
*
* @return the trace level
*/
public int getTraceLevel() {
return traceLevel;
}
/**
* Set aux information. Auxiliary information may be associated with the log file. This is
* useful for remote logs.
*
* @param auxInfo -- auxiliary information.
*/
public void setAuxInfo(String auxInfo) {
this.auxInfo = auxInfo;
}
public void setSipStack(SipStack sipStack) {
if(sipStack instanceof SIPTransactionStack) {
this.sipStack = (SIPTransactionStack)sipStack;
this.stackLogger = this.sipStack.getStackLogger();
}
else
throw new IllegalArgumentException("sipStack must be a SIPTransactionStack");
}
public void setStackProperties(Properties stackProperties) {
setProperties(stackProperties);
}
public void setLevel(int jsipLoggingLevel) {
}
}
| |
/******************************************************************************
* Copyright 2015 sakaiproject.org Licensed under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES 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.sakaiproject.mbm.tool;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.mbm.tool.entities.ModulesFilterEntity;
import org.sakaiproject.mbm.tool.entities.MessageEntity;
import org.sakaiproject.mbm.tool.entities.SearchEntity;
import org.sakaiproject.messagebundle.api.MessageBundleProperty;
import org.sakaiproject.messagebundle.api.MessageBundleService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.user.api.PreferencesService;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* MainController
*
* This is the controller used by Spring MVC to handle requests
*
* @author Earle Nietzel
* (earle.nietzel@gmail.com)
*
*/
@Slf4j
@Controller
public class MainController {
@Resource(name="org.sakaiproject.messagebundle.api.MessageBundleService")
private MessageBundleService messageBundleService;
@Inject
private ServerConfigurationService serverConfigurationService;
@Inject
private SecurityService securityService;
@Inject
private MessageSource messageSource;
@Inject
private PreferencesService preferencesService;
@Inject
private SessionManager sessionManager;
@ModelAttribute("listMessageProperties")
public List<MessageBundleProperty> listMessageProperties() {
return messageBundleService.getAllProperties(null, null, null);
}
@ModelAttribute("listModifiedMessageProperties")
public List<MessageBundleProperty> listModifiedMessageProperties() {
return messageBundleService.getModifiedProperties(0, 0, 0, -1);
}
@ModelAttribute("countMessageProperties")
public int countMessageBundleProperties() {
return messageBundleService.getAllPropertiesCount();
}
@ModelAttribute("countModifiedMessageProperties")
public int countModifiedMessageProperties() {
return messageBundleService.getModifiedPropertiesCount();
}
@ModelAttribute("listMessagePropertyModules")
public List<String> listMessagePropertyModules() {
return messageBundleService.getAllModuleNames();
}
@ModelAttribute("listMessagePropertyLocales")
public List<String> listMessagePropertyLocales() {
return messageBundleService.getLocales();
}
@ModelAttribute("isLoadBundlesFromDb")
public boolean isLoadBundlesFromDb() {
return messageBundleService.isEnabled();
}
@ModelAttribute("isAdmin")
public boolean isAdmin() {
return securityService.isSuperUser();
}
@RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
public String showIndex(Model model) {
log.debug("showIndex()");
return "index";
}
@RequestMapping(value = "/modified", method = RequestMethod.GET)
public String showModified(Model model) {
log.debug("showModified()");
return "modified";
}
// @RequestMapping(value = "/modified", params = {"dtf=csv","dti=modified"}, method = RequestMethod.GET, produces = "text/csv")
// public void csv(@DatatablesParams DatatablesCriterias criterias, HttpServletRequest request, HttpServletResponse response)
// throws IOException {
// log.debug("csv() export");
//
// String userId = sessionManager.getCurrentSessionUserId();
// Locale userLocale = preferencesService.getLocale(userId);
// List<MessageBundleProperty> list = listModifiedMessageProperties();
//
// ExportConf csvConf = new ExportConf.Builder(ReservedFormat.CSV)
// .fileName("messages-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern(messageSource.getMessage("modified.csv.date.format", null, userLocale))))
// .header(true)
// .exportClass(new CsvExport())
// .build();
//
// HtmlTable csvTable = new HtmlTableBuilder<MessageBundleProperty>().newBuilder("modified", list, request, csvConf)
// .column().fillWithProperty("id").title(messageSource.getMessage("modified.csv.id", null, userLocale))
// .column().fillWithProperty("moduleName").title(messageSource.getMessage("modified.csv.module", null, userLocale))
// .column().fillWithProperty("propertyName").title(messageSource.getMessage("modified.csv.property", null, userLocale))
// .column().fillWithProperty("value").title(messageSource.getMessage("modified.csv.value", null, userLocale))
// .column().fillWithProperty("defaultValue").title(messageSource.getMessage("modified.csv.default", null, userLocale))
// .column().fillWithProperty("locale").title(messageSource.getMessage("modified.csv.locale", null, userLocale))
// .build();
//
// ExportUtils.renderExport(csvTable, csvConf, response);
// }
@RequestMapping(value = "/modules", method = RequestMethod.GET)
public String showModules(Model model) {
log.debug("showModules()");
List<MessageBundleProperty> properties = Collections.emptyList();
model.addAttribute("properties", properties);
ModulesFilterEntity filter = new ModulesFilterEntity();
model.addAttribute(filter);
return "modules";
}
@RequestMapping(value = "/modules", params={"filter"}, method = RequestMethod.POST)
public String processModules(final ModulesFilterEntity modulesFilterEntity, final BindingResult bindingResult, final ModelMap model) {
if (bindingResult.hasErrors()) {
return "modules";
}
log.debug("processModules(): ModulesFilteredEntity = " + modulesFilterEntity);
model.addAttribute("properties", messageBundleService.getAllProperties(modulesFilterEntity.getLocale(), null, modulesFilterEntity.getModule()));
return "modules";
}
@RequestMapping(value = "/edit", params = { "id" }, method = RequestMethod.GET)
public String showEdit(@RequestParam long id, Model model) {
log.debug("showEdit()");
MessageBundleProperty property = messageBundleService.getMessageBundleProperty(id);
model.addAttribute(property);
MessageEntity message = new MessageEntity(id, property.getValue());
model.addAttribute(message);
return "edit";
}
@RequestMapping(value = "/edit", params={"save"}, method = RequestMethod.POST)
public String processSaveEdit(final MessageEntity messageEntity, final BindingResult bindingResult, final ModelMap model) {
if (bindingResult.hasErrors()) {
return "modified";
}
log.debug("processSaveEdit(): MessageEntity = " + messageEntity);
MessageBundleProperty property = messageBundleService.getMessageBundleProperty(messageEntity.getId());
property.setValue(messageEntity.getValue());
if (securityService.isSuperUser()) {
messageBundleService.updateMessageBundleProperty(property);
} else {
throw new SecurityException("Only an admin type user is allowed to update message bundle properties");
}
model.clear();
return "redirect:/modified";
}
@RequestMapping(value = "/edit", params={"revert"}, method = RequestMethod.POST)
public String processRevertEdit(final MessageEntity messageEntity, final BindingResult bindingResult, final ModelMap model) {
if (bindingResult.hasErrors()) {
return "modified";
}
log.debug("processRevertEdit(): MessageEntity = " + messageEntity);
MessageBundleProperty property = messageBundleService.getMessageBundleProperty(messageEntity.getId());
if (securityService.isSuperUser()) {
messageBundleService.revert(property);
} else {
throw new SecurityException("Only an admin type user is allowed to revert message bundle properties");
}
model.clear();
return "redirect:/modified";
}
@RequestMapping(value = "/search", method = RequestMethod.GET)
public String showSearch(Model model) {
log.debug("showSearch()");
List<MessageBundleProperty> properties = Collections.emptyList();
model.addAttribute("properties", properties);
SearchEntity search = new SearchEntity();
model.addAttribute(search);
return "search";
}
@RequestMapping(value = "/search", params={"search"}, method = RequestMethod.POST)
public String processSearch(final SearchEntity searchEntity, final BindingResult bindingResult, final ModelMap model) {
if (bindingResult.hasErrors()) {
return "search";
}
log.debug("processSearch(): searchEntity = " + searchEntity);
model.addAttribute("properties", messageBundleService.search(searchEntity.getValue(), null, null, searchEntity.getLocale()));
return "search";
}
}
| |
/*
* ja, a Java-bytecode translator toolkit.
* Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later,
* or the Apache License Version 2.0.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/
package ja.bytecode;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import ja.CannotCompileException;
/**
* <code>ClassFile</code> represents a Java <code>.class</code> file, which
* consists of a constant pool, methods, fields, and attributes.
*
* @see ja.CtClass#getClassFile()
*/
public final class ClassFile {
int major, minor; // version number
ConstPool constPool;
int thisClass;
int accessFlags;
int superClass;
int[] interfaces;
ArrayList fields;
ArrayList methods;
ArrayList attributes;
String thisclassname; // not JVM-internal name
String[] cachedInterfaces;
String cachedSuperclass;
/**
* The major version number of class files for JDK 1.1.
*/
public static final int JAVA_1 = 45;
/**
* The major version number of class files for JDK 1.2.
*/
public static final int JAVA_2 = 46;
/**
* The major version number of class files for JDK 1.3.
*/
public static final int JAVA_3 = 47;
/**
* The major version number of class files for JDK 1.4.
*/
public static final int JAVA_4 = 48;
/**
* The major version number of class files for JDK 1.5.
*/
public static final int JAVA_5 = 49;
/**
* The major version number of class files for JDK 1.6.
*/
public static final int JAVA_6 = 50;
/**
* The major version number of class files for JDK 1.7.
*/
public static final int JAVA_7 = 51;
/**
* The major version number of class files for JDK 1.8.
*/
public static final int JAVA_8 = 52;
/**
* The major version number of class files created from scratch. The default
* value is 47 (JDK 1.3). It is 49 (JDK 1.5) if the JVM supports
* <code>java.lang.StringBuilder</code>. It is 50 (JDK 1.6) if the JVM
* supports <code>java.util.zip.DeflaterInputStream</code>. It is 51 (JDK
* 1.7) if the JVM supports <code>java.lang.invoke.CallSite</code>.
*/
public static int MAJOR_VERSION = JAVA_3;
static {
try {
Class.forName("java.lang.StringBuilder");
MAJOR_VERSION = JAVA_5;
Class.forName("java.util.zip.DeflaterInputStream");
MAJOR_VERSION = JAVA_6;
Class.forName("java.lang.invoke.CallSite");
MAJOR_VERSION = JAVA_7;
} catch (Throwable t) {
}
}
/**
* Constructs a class file from a byte stream.
*/
public ClassFile(DataInputStream in) throws IOException {
read(in);
}
/**
* Constructs a class file including no members.
*
* @param isInterface
* true if this is an interface. false if this is a class.
* @param classname
* a fully-qualified class name
* @param superclass
* a fully-qualified super class name
*/
@SuppressWarnings("unchecked")
public ClassFile(boolean isInterface, String classname, String superclass) {
major = MAJOR_VERSION;
minor = 0; // JDK 1.3 or later
constPool = new ConstPool(classname);
thisClass = constPool.getThisClassInfo();
if (isInterface)
accessFlags = AccessFlag.INTERFACE | AccessFlag.ABSTRACT;
else
accessFlags = AccessFlag.SUPER;
initSuperclass(superclass);
interfaces = null;
fields = new ArrayList();
methods = new ArrayList();
thisclassname = classname;
attributes = new ArrayList();
attributes.add(new SourceFileAttribute(constPool,
getSourcefileName(thisclassname)));
}
private void initSuperclass(String superclass) {
if (superclass != null) {
this.superClass = constPool.addClassInfo(superclass);
cachedSuperclass = superclass;
} else {
this.superClass = constPool.addClassInfo("java.lang.Object");
cachedSuperclass = "java.lang.Object";
}
}
private static String getSourcefileName(String qname) {
int index = qname.lastIndexOf('.');
if (index >= 0)
qname = qname.substring(index + 1);
return qname + ".java";
}
/**
* Eliminates dead constant pool items. If a method or a field is removed,
* the constant pool items used by that method/field become dead items. This
* method recreates a constant pool.
*/
public void compact() {
ConstPool cp = compact0();
ArrayList list = methods;
int n = list.size();
for (int i = 0; i < n; ++i) {
MethodInfo minfo = (MethodInfo) list.get(i);
minfo.compact(cp);
}
list = fields;
n = list.size();
for (int i = 0; i < n; ++i) {
FieldInfo finfo = (FieldInfo) list.get(i);
finfo.compact(cp);
}
attributes = AttributeInfo.copyAll(attributes, cp);
constPool = cp;
}
private ConstPool compact0() {
ConstPool cp = new ConstPool(thisclassname);
thisClass = cp.getThisClassInfo();
String sc = getSuperclass();
if (sc != null)
superClass = cp.addClassInfo(getSuperclass());
if (interfaces != null) {
int n = interfaces.length;
for (int i = 0; i < n; ++i)
interfaces[i] = cp.addClassInfo(constPool
.getClassInfo(interfaces[i]));
}
return cp;
}
/**
* Discards all attributes, associated with both the class file and the
* members such as a code attribute and exceptions attribute. The unused
* constant pool entries are also discarded (a new packed constant pool is
* constructed).
*/
public void prune() {
ConstPool cp = compact0();
ArrayList newAttributes = new ArrayList();
AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag);
if (invisibleAnnotations != null) {
invisibleAnnotations = invisibleAnnotations.copy(cp, null);
newAttributes.add(invisibleAnnotations);
}
AttributeInfo visibleAnnotations = getAttribute(AnnotationsAttribute.visibleTag);
if (visibleAnnotations != null) {
visibleAnnotations = visibleAnnotations.copy(cp, null);
newAttributes.add(visibleAnnotations);
}
AttributeInfo signature = getAttribute(SignatureAttribute.tag);
if (signature != null) {
signature = signature.copy(cp, null);
newAttributes.add(signature);
}
ArrayList list = methods;
int n = list.size();
for (int i = 0; i < n; ++i) {
MethodInfo minfo = (MethodInfo) list.get(i);
minfo.prune(cp);
}
list = fields;
n = list.size();
for (int i = 0; i < n; ++i) {
FieldInfo finfo = (FieldInfo) list.get(i);
finfo.prune(cp);
}
attributes = newAttributes;
constPool = cp;
}
/**
* Returns a constant pool table.
*/
public ConstPool getConstPool() {
return constPool;
}
/**
* Returns true if this is an interface.
*/
public boolean isInterface() {
return (accessFlags & AccessFlag.INTERFACE) != 0;
}
/**
* Returns true if this is a final class or interface.
*/
public boolean isFinal() {
return (accessFlags & AccessFlag.FINAL) != 0;
}
/**
* Returns true if this is an abstract class or an interface.
*/
public boolean isAbstract() {
return (accessFlags & AccessFlag.ABSTRACT) != 0;
}
/**
* Returns access flags.
*
* @see ja.bytecode.AccessFlag
*/
public int getAccessFlags() {
return accessFlags;
}
/**
* Changes access flags.
*
* @see ja.bytecode.AccessFlag
*/
public void setAccessFlags(int acc) {
if ((acc & AccessFlag.INTERFACE) == 0)
acc |= AccessFlag.SUPER;
accessFlags = acc;
}
/**
* Returns access and property flags of this nested class. This method
* returns -1 if the class is not a nested class.
*
* <p>
* The returned value is obtained from <code>inner_class_access_flags</code>
* of the entry representing this nested class itself in
* <code>InnerClasses_attribute</code>>.
*/
public int getInnerAccessFlags() {
InnerClassesAttribute ica = (InnerClassesAttribute) getAttribute(InnerClassesAttribute.tag);
if (ica == null)
return -1;
String name = getName();
int n = ica.tableLength();
for (int i = 0; i < n; ++i)
if (name.equals(ica.innerClass(i)))
return ica.accessFlags(i);
return -1;
}
/**
* Returns the class name.
*/
public String getName() {
return thisclassname;
}
/**
* Sets the class name. This method substitutes the new name for all
* occurrences of the old class name in the class file.
*/
public void setName(String name) {
renameClass(thisclassname, name);
}
/**
* Returns the super class name.
*/
public String getSuperclass() {
if (cachedSuperclass == null)
cachedSuperclass = constPool.getClassInfo(superClass);
return cachedSuperclass;
}
/**
* Returns the index of the constant pool entry representing the super
* class.
*/
public int getSuperclassId() {
return superClass;
}
/**
* Sets the super class.
*
* <p>
* The new super class should inherit from the old super class. This method
* modifies constructors so that they call constructors declared in the new
* super class.
*/
public void setSuperclass(String superclass) throws CannotCompileException {
if (superclass == null)
superclass = "java.lang.Object";
try {
this.superClass = constPool.addClassInfo(superclass);
ArrayList list = methods;
int n = list.size();
for (int i = 0; i < n; ++i) {
MethodInfo minfo = (MethodInfo) list.get(i);
minfo.setSuperclass(superclass);
}
} catch (BadBytecode e) {
throw new CannotCompileException(e);
}
cachedSuperclass = superclass;
}
/**
* Replaces all occurrences of a class name in the class file.
*
* <p>
* If class X is substituted for class Y in the class file, X and Y must
* have the same signature. If Y provides a method m(), X must provide it
* even if X inherits m() from the super class. If this fact is not
* guaranteed, the bytecode verifier may cause an error.
*
* @param oldname
* the replaced class name
* @param newname
* the substituted class name
*/
public final void renameClass(String oldname, String newname) {
ArrayList list;
int n;
if (oldname.equals(newname))
return;
if (oldname.equals(thisclassname))
thisclassname = newname;
oldname = Descriptor.toJvmName(oldname);
newname = Descriptor.toJvmName(newname);
constPool.renameClass(oldname, newname);
AttributeInfo.renameClass(attributes, oldname, newname);
list = methods;
n = list.size();
for (int i = 0; i < n; ++i) {
MethodInfo minfo = (MethodInfo) list.get(i);
String desc = minfo.getDescriptor();
minfo.setDescriptor(Descriptor.rename(desc, oldname, newname));
AttributeInfo.renameClass(minfo.getAttributes(), oldname, newname);
}
list = fields;
n = list.size();
for (int i = 0; i < n; ++i) {
FieldInfo finfo = (FieldInfo) list.get(i);
String desc = finfo.getDescriptor();
finfo.setDescriptor(Descriptor.rename(desc, oldname, newname));
AttributeInfo.renameClass(finfo.getAttributes(), oldname, newname);
}
}
/**
* Replaces all occurrences of several class names in the class file.
*
* @param classnames
* specifies which class name is replaced with which new name.
* Class names must be described with the JVM-internal
* representation like <code>java/lang/Object</code>.
* @see #renameClass(String,String)
*/
public final void renameClass(Map classnames) {
String jvmNewThisName = (String) classnames.get(Descriptor
.toJvmName(thisclassname));
if (jvmNewThisName != null)
thisclassname = Descriptor.toJavaName(jvmNewThisName);
constPool.renameClass(classnames);
AttributeInfo.renameClass(attributes, classnames);
ArrayList list = methods;
int n = list.size();
for (int i = 0; i < n; ++i) {
MethodInfo minfo = (MethodInfo) list.get(i);
String desc = minfo.getDescriptor();
minfo.setDescriptor(Descriptor.rename(desc, classnames));
AttributeInfo.renameClass(minfo.getAttributes(), classnames);
}
list = fields;
n = list.size();
for (int i = 0; i < n; ++i) {
FieldInfo finfo = (FieldInfo) list.get(i);
String desc = finfo.getDescriptor();
finfo.setDescriptor(Descriptor.rename(desc, classnames));
AttributeInfo.renameClass(finfo.getAttributes(), classnames);
}
}
/**
* Internal-use only. <code>CtClass.getRefClasses()</code> calls this
* method.
*/
public final void getRefClasses(Map classnames) {
constPool.renameClass(classnames);
AttributeInfo.getRefClasses(attributes, classnames);
ArrayList list = methods;
int n = list.size();
for (int i = 0; i < n; ++i) {
MethodInfo minfo = (MethodInfo) list.get(i);
String desc = minfo.getDescriptor();
Descriptor.rename(desc, classnames);
AttributeInfo.getRefClasses(minfo.getAttributes(), classnames);
}
list = fields;
n = list.size();
for (int i = 0; i < n; ++i) {
FieldInfo finfo = (FieldInfo) list.get(i);
String desc = finfo.getDescriptor();
Descriptor.rename(desc, classnames);
AttributeInfo.getRefClasses(finfo.getAttributes(), classnames);
}
}
/**
* Returns the names of the interfaces implemented by the class. The
* returned array is read only.
*/
public String[] getInterfaces() {
if (cachedInterfaces != null)
return cachedInterfaces;
String[] rtn = null;
if (interfaces == null)
rtn = new String[0];
else {
int n = interfaces.length;
String[] list = new String[n];
for (int i = 0; i < n; ++i)
list[i] = constPool.getClassInfo(interfaces[i]);
rtn = list;
}
cachedInterfaces = rtn;
return rtn;
}
/**
* Sets the interfaces.
*
* @param nameList
* the names of the interfaces.
*/
public void setInterfaces(String[] nameList) {
cachedInterfaces = null;
if (nameList != null) {
int n = nameList.length;
interfaces = new int[n];
for (int i = 0; i < n; ++i)
interfaces[i] = constPool.addClassInfo(nameList[i]);
}
}
/**
* Appends an interface to the interfaces implemented by the class.
*/
public void addInterface(String name) {
cachedInterfaces = null;
int info = constPool.addClassInfo(name);
if (interfaces == null) {
interfaces = new int[1];
interfaces[0] = info;
} else {
int n = interfaces.length;
int[] newarray = new int[n + 1];
System.arraycopy(interfaces, 0, newarray, 0, n);
newarray[n] = info;
interfaces = newarray;
}
}
/**
* Returns all the fields declared in the class.
*
* @return a list of <code>FieldInfo</code>.
* @see FieldInfo
*/
public List getFields() {
return fields;
}
/**
* Appends a field to the class.
*
* @throws DuplicateMemberException
* when the field is already included.
*/
public void addField(FieldInfo finfo) throws DuplicateMemberException {
testExistingField(finfo.getName(), finfo.getDescriptor());
fields.add(finfo);
}
/**
* Just appends a field to the class. It does not check field duplication.
* Use this method only when minimizing performance overheads is seriously
* required.
*
* @since 3.13
*/
public final void addField2(FieldInfo finfo) {
fields.add(finfo);
}
private void testExistingField(String name, String descriptor)
throws DuplicateMemberException {
ListIterator it = fields.listIterator(0);
while (it.hasNext()) {
FieldInfo minfo = (FieldInfo) it.next();
if (minfo.getName().equals(name))
throw new DuplicateMemberException("duplicate field: " + name);
}
}
/**
* Returns all the methods declared in the class.
*
* @return a list of <code>MethodInfo</code>.
* @see MethodInfo
*/
public List getMethods() {
return methods;
}
/**
* Returns the method with the specified name. If there are multiple methods
* with that name, this method returns one of them.
*
* @return null if no such method is found.
*/
public MethodInfo getMethod(String name) {
ArrayList list = methods;
int n = list.size();
for (int i = 0; i < n; ++i) {
MethodInfo minfo = (MethodInfo) list.get(i);
if (minfo.getName().equals(name))
return minfo;
}
return null;
}
/**
* Returns a static initializer (class initializer), or null if it does not
* exist.
*/
public MethodInfo getStaticInitializer() {
return getMethod(MethodInfo.nameClinit);
}
/**
* Appends a method to the class. If there is a bridge method with the same
* name and signature, then the bridge method is removed before a new method
* is added.
*
* @throws DuplicateMemberException
* when the method is already included.
*/
public void addMethod(MethodInfo minfo) throws DuplicateMemberException {
testExistingMethod(minfo);
methods.add(minfo);
}
/**
* Just appends a method to the class. It does not check method duplication
* or remove a bridge method. Use this method only when minimizing
* performance overheads is seriously required.
*
* @since 3.13
*/
public final void addMethod2(MethodInfo minfo) {
methods.add(minfo);
}
private void testExistingMethod(MethodInfo newMinfo)
throws DuplicateMemberException {
String name = newMinfo.getName();
String descriptor = newMinfo.getDescriptor();
ListIterator it = methods.listIterator(0);
while (it.hasNext())
if (isDuplicated(newMinfo, name, descriptor,
(MethodInfo) it.next(), it))
throw new DuplicateMemberException("duplicate method: " + name
+ " in " + this.getName());
}
private static boolean isDuplicated(MethodInfo newMethod, String newName,
String newDesc, MethodInfo minfo, ListIterator it) {
if (!minfo.getName().equals(newName))
return false;
String desc = minfo.getDescriptor();
if (!Descriptor.eqParamTypes(desc, newDesc))
return false;
if (desc.equals(newDesc)) {
if (notBridgeMethod(minfo))
return true;
else {
// if the bridge method with the same signature
// already exists, replace it.
it.remove();
return false;
}
} else
return false;
// return notBridgeMethod(minfo) && notBridgeMethod(newMethod);
}
/*
* For a bridge method, see Sec. 15.12.4.5 of JLS 3rd Ed.
*/
private static boolean notBridgeMethod(MethodInfo minfo) {
return (minfo.getAccessFlags() & AccessFlag.BRIDGE) == 0;
}
/**
* Returns all the attributes. The returned <code>List</code> object is
* shared with this object. If you add a new attribute to the list, the
* attribute is also added to the classs file represented by this object. If
* you remove an attribute from the list, it is also removed from the class
* file.
*
* @return a list of <code>AttributeInfo</code> objects.
* @see AttributeInfo
*/
public List getAttributes() {
return attributes;
}
/**
* Returns the attribute with the specified name. If there are multiple
* attributes with that name, this method returns either of them. It returns
* null if the specified attributed is not found.
*
* @param name
* attribute name
* @see #getAttributes()
*/
public AttributeInfo getAttribute(String name) {
ArrayList list = attributes;
int n = list.size();
for (int i = 0; i < n; ++i) {
AttributeInfo ai = (AttributeInfo) list.get(i);
if (ai.getName().equals(name))
return ai;
}
return null;
}
/**
* Appends an attribute. If there is already an attribute with the same
* name, the new one substitutes for it.
*
* @see #getAttributes()
*/
public void addAttribute(AttributeInfo info) {
AttributeInfo.remove(attributes, info.getName());
attributes.add(info);
}
/**
* Returns the source file containing this class.
*
* @return null if this information is not available.
*/
public String getSourceFile() {
SourceFileAttribute sf = (SourceFileAttribute) getAttribute(SourceFileAttribute.tag);
if (sf == null)
return null;
else
return sf.getFileName();
}
private void read(DataInputStream in) throws IOException {
int i, n;
int magic = in.readInt();
if (magic != 0xCAFEBABE)
throw new IOException("bad magic number: "
+ Integer.toHexString(magic));
minor = in.readUnsignedShort();
major = in.readUnsignedShort();
constPool = new ConstPool(in);
accessFlags = in.readUnsignedShort();
thisClass = in.readUnsignedShort();
constPool.setThisClassInfo(thisClass);
superClass = in.readUnsignedShort();
n = in.readUnsignedShort();
if (n == 0)
interfaces = null;
else {
interfaces = new int[n];
for (i = 0; i < n; ++i)
interfaces[i] = in.readUnsignedShort();
}
ConstPool cp = constPool;
n = in.readUnsignedShort();
fields = new ArrayList();
for (i = 0; i < n; ++i)
addField2(new FieldInfo(cp, in));
n = in.readUnsignedShort();
methods = new ArrayList();
for (i = 0; i < n; ++i)
addMethod2(new MethodInfo(cp, in));
attributes = new ArrayList();
n = in.readUnsignedShort();
for (i = 0; i < n; ++i)
addAttribute(AttributeInfo.read(cp, in));
thisclassname = constPool.getClassInfo(thisClass);
}
/**
* Writes a class file represented by this object into an output stream.
*/
public void write(DataOutputStream out) throws IOException {
int i, n;
out.writeInt(0xCAFEBABE); // magic
out.writeShort(minor); // minor version
out.writeShort(major); // major version
constPool.write(out); // constant pool
out.writeShort(accessFlags);
out.writeShort(thisClass);
out.writeShort(superClass);
if (interfaces == null)
n = 0;
else
n = interfaces.length;
out.writeShort(n);
for (i = 0; i < n; ++i)
out.writeShort(interfaces[i]);
ArrayList list = fields;
n = list.size();
out.writeShort(n);
for (i = 0; i < n; ++i) {
FieldInfo finfo = (FieldInfo) list.get(i);
finfo.write(out);
}
list = methods;
n = list.size();
out.writeShort(n);
for (i = 0; i < n; ++i) {
MethodInfo minfo = (MethodInfo) list.get(i);
minfo.write(out);
}
out.writeShort(attributes.size());
AttributeInfo.writeAll(attributes, out);
}
/**
* Get the Major version.
*
* @return the major version
*/
public int getMajorVersion() {
return major;
}
/**
* Set the major version.
*
* @param major
* the major version
*/
public void setMajorVersion(int major) {
this.major = major;
}
/**
* Get the minor version.
*
* @return the minor version
*/
public int getMinorVersion() {
return minor;
}
/**
* Set the minor version.
*
* @param minor
* the minor version
*/
public void setMinorVersion(int minor) {
this.minor = minor;
}
/**
* Sets the major and minor version to Java 5.
*
* If the major version is older than 49, Java 5 extensions such as
* annotations are ignored by the JVM.
*/
public void setVersionToJava5() {
this.major = 49;
this.minor = 0;
}
}
| |
package org.apache.rya.reasoning;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.HashSet;
import java.util.Set;
import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
/**
* Abstract class for reasoning in the neighborhood of a particular resource.
* Contains general methods for collecting facts and derivations, and
* determining whether those facts are potentially new.
*
* As reasoning rules are applied, facts and inconsistencies are collected and
* stored in this object. (This allows some simple logic to reduce redundant
* fact generation.) The caller can use getFacts and getInconsistencies to
* retrieve them when needed. (This clears the buffered facts in the reasoner
* object.)
*/
public abstract class AbstractReasoner {
/**
* Reasoning is done with respect to this particular node.
*/
protected final Resource node;
/**
* All schema (TBox/RBox) data is accessed through this.
*/
protected final Schema schema;
/**
* The current iteration in the overall reasoning algorithm.
*/
protected final int currentIteration;
/**
* A newly derived fact should have at least one source which is at least
* this recent.
*/
final int minIteration;
/**
* If the global schema has ever been updated during reasoning iteration,
* this will be the iteration number of that update (otherwise 0).
*/
final int lastSchemaChange;
// Newly derived information
Set<Fact> newFacts = new HashSet<>();
Set<Derivation> inconsistencies = new HashSet<>();
/**
* Constructor.
* @param node Conduct reasoning about/around this node
* @param schema Global schema (class/property) information
* @param t Iteration # of new triples
* @param tSchema Iteration # of latest schema update. If the schema has
* not been changed, we can ignore many triples that we
* expect to already have used.
*/
public AbstractReasoner(Resource node, Schema schema, int t, int tSchema) {
this.node = node;
this.schema = schema;
this.currentIteration = t;
this.lastSchemaChange = tSchema;
if (tSchema < (t - 1)) {
this.minIteration = 0;
}
else {
this.minIteration = t - 1;
}
}
/**
* Store inconsistency if it really is new.
* @return Whether it really needed to be stored
*/
protected boolean collectInconsistency(Derivation inconsistency) {
// If at least one of its sources can indeed be used for derivations,
// store this fact
for (Fact source : inconsistency.getSources()) {
if (frontier(source)) {
return inconsistencies.add(inconsistency);
}
}
return false;
}
/**
* Store fact if it really is new.
* @return Whether it really needed to be stored
*/
protected boolean collect(Fact fact) {
// If this fact was just generated, at least one of its sources can
// indeed be used for derivations, and the sources don't include it
// itself, store this fact
if (fact.getIteration() == currentIteration && !fact.isCycle()) {
Derivation d = fact.getDerivation();
for (Fact source : d.getSources()) {
if (frontier(source)) {
return newFacts.add(fact);
}
}
}
return false;
}
/**
* Whether any new facts have been derived and not yet retrieved.
*/
public boolean hasNewFacts() {
return !newFacts.isEmpty();
}
/**
* Whether any inconsistencies have been derived and not retrieved.
*/
public boolean hasInconsistencies() {
return !inconsistencies.isEmpty();
}
/**
* Return the latest facts and set current new results to empty.
*/
public Set<Fact> getFacts() {
Set<Fact> results = newFacts;
newFacts = new HashSet<Fact>();
return results;
}
/**
* Return the latest inconsistencies and set inconsistencies to empty.
*/
public Set<Derivation> getInconsistencies() {
Set<Derivation> results = inconsistencies;
inconsistencies = new HashSet<Derivation>();
return results;
}
/**
* Create a Fact representing a triple inferred by this reasoner.
* @param rule The specific rule rule that yielded the inference
* @param source One (might be the only) fact used in the derivation
*/
protected Fact triple(Resource s, URI p, Value o, OwlRule rule,
Fact source) {
Fact fact = new Fact(s, p, o, this.currentIteration,
rule, this.node);
fact.addSource(source);
return fact;
}
/**
* Create a Derivation representing an inconsistency found by this reasoner.
* @param rule The specific rule rule that yielded the inconsistency
* @param source One (might be the only) fact used in the derivation
*/
protected Derivation inconsistency(OwlRule rule, Fact source) {
Derivation d = new Derivation(this.currentIteration, rule, this.node);
d.addSource(source);
return d;
}
/**
* Determine whether a fact is on the frontier of knowledge so far, meaning
* it is new enough to imply further unknown information. If false, we can
* expect inferences based on this fact to have already been made in the
* step during which it was initially derived. Any interesting fact coming
* from this reasoner should have at least one of its direct sources on
* the frontier. Considers only age, not semantics.
*
* Three cases that indicate this is on the frontier:
* 1) We are looking at all the data (minIteration==0, either because this
* is the first pass through the data or because we reset on updating
* the schema).
* 2) This fact was generated (by this reasoner) during this iteration, so
* it hasn't been seen before.
* 3) It was generated by another node's reasoner since minIteration,
* meaning it hasn't been seen yet by a reasoner for this node.
*
* In any case, inconsistencies are not used to derive anything, so they
* always return false.
*/
protected boolean frontier(Fact fact) {
int t = fact.getIteration();
Resource dNode = null;
if (fact.isInference()) {
dNode = fact.getDerivation().getNode();
}
return (minIteration == 0) || (t == currentIteration)
|| (t >= minIteration && !this.node.equals(dNode));
}
/**
* Get some summary information for logging/debugging.
*/
public String getDiagnostics() {
StringBuilder sb = new StringBuilder();
sb.append(newFacts.size()).append(" new facts buffered");
sb.append(inconsistencies.size()).append(" new inconsistencies buffered");
return sb.toString();
}
/**
* Get the number of inputs cached.
*/
public int getNumStored() { return 0; }
/**
* Get the node this reasoner reasons around.
*/
public Resource getNode() { 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.hadoop.hive.ql.lockmgr;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.LockComponentBuilder;
import org.apache.hadoop.hive.metastore.LockRequestBuilder;
import org.apache.hadoop.hive.metastore.api.*;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.QueryPlan;
import org.apache.hadoop.hive.ql.hooks.Entity;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.thrift.TException;
import java.util.List;
/**
* An implementation of HiveTxnManager that stores the transactions in the
* metastore database.
*/
public class DbTxnManager extends HiveTxnManagerImpl {
static final private String CLASS_NAME = DbTxnManager.class.getName();
static final private Log LOG = LogFactory.getLog(CLASS_NAME);
private DbLockManager lockMgr = null;
private IMetaStoreClient client = null;
private long txnId = 0;
DbTxnManager() {
}
@Override
void setHiveConf(HiveConf conf) {
super.setHiveConf(conf);
if (!conf.getBoolVar(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY)) {
throw new RuntimeException(ErrorMsg.DBTXNMGR_REQUIRES_CONCURRENCY.getMsg());
}
}
@Override
public long openTxn(String user) throws LockException {
init();
try {
txnId = client.openTxn(user);
LOG.debug("Opened txn " + txnId);
return txnId;
} catch (TException e) {
throw new LockException(ErrorMsg.METASTORE_COMMUNICATION_FAILED.getMsg(),
e);
}
}
@Override
public HiveLockManager getLockManager() throws LockException {
init();
if (lockMgr == null) {
lockMgr = new DbLockManager(client);
}
return lockMgr;
}
@Override
public void acquireLocks(QueryPlan plan, Context ctx, String username) throws LockException {
init();
// Make sure we've built the lock manager
getLockManager();
boolean atLeastOneLock = false;
LockRequestBuilder rqstBuilder = new LockRequestBuilder();
LOG.debug("Setting lock request transaction to " + txnId);
rqstBuilder.setTransactionId(txnId)
.setUser(username);
// For each source to read, get a shared lock
for (ReadEntity input : plan.getInputs()) {
if (!input.needsLock() || input.isUpdateOrDelete()) {
// We don't want to acquire readlocks during update or delete as we'll be acquiring write
// locks instead.
continue;
}
LockComponentBuilder compBuilder = new LockComponentBuilder();
compBuilder.setShared();
Table t = null;
switch (input.getType()) {
case DATABASE:
compBuilder.setDbName(input.getDatabase().getName());
break;
case TABLE:
t = input.getTable();
compBuilder.setDbName(t.getDbName());
compBuilder.setTableName(t.getTableName());
break;
case PARTITION:
case DUMMYPARTITION:
compBuilder.setPartitionName(input.getPartition().getName());
t = input.getPartition().getTable();
compBuilder.setDbName(t.getDbName());
compBuilder.setTableName(t.getTableName());
break;
default:
// This is a file or something we don't hold locks for.
continue;
}
LockComponent comp = compBuilder.build();
LOG.debug("Adding lock component to lock request " + comp.toString());
rqstBuilder.addLockComponent(comp);
atLeastOneLock = true;
}
// For each source to write to, get the appropriate lock type. If it's
// an OVERWRITE, we need to get an exclusive lock. If it's an insert (no
// overwrite) than we need a shared. If it's update or delete then we
// need a SEMI-SHARED.
for (WriteEntity output : plan.getOutputs()) {
if (output.getType() == Entity.Type.DFS_DIR || output.getType() ==
Entity.Type.LOCAL_DIR) {
// We don't lock files or directories.
continue;
}
LockComponentBuilder compBuilder = new LockComponentBuilder();
Table t = null;
LOG.debug("output is null " + (output == null));
switch (output.getWriteType()) {
case DDL_EXCLUSIVE:
case INSERT_OVERWRITE:
compBuilder.setExclusive();
break;
case INSERT:
case DDL_SHARED:
compBuilder.setShared();
break;
case UPDATE:
case DELETE:
compBuilder.setSemiShared();
break;
case DDL_NO_LOCK:
continue; // No lock required here
default:
throw new RuntimeException("Unknown write type " +
output.getWriteType().toString());
}
switch (output.getType()) {
case DATABASE:
compBuilder.setDbName(output.getDatabase().getName());
break;
case TABLE:
case DUMMYPARTITION: // in case of dynamic partitioning lock the table
t = output.getTable();
compBuilder.setDbName(t.getDbName());
compBuilder.setTableName(t.getTableName());
break;
case PARTITION:
compBuilder.setPartitionName(output.getPartition().getName());
t = output.getPartition().getTable();
compBuilder.setDbName(t.getDbName());
compBuilder.setTableName(t.getTableName());
break;
default:
// This is a file or something we don't hold locks for.
continue;
}
LockComponent comp = compBuilder.build();
LOG.debug("Adding lock component to lock request " + comp.toString());
rqstBuilder.addLockComponent(comp);
atLeastOneLock = true;
}
// Make sure we need locks. It's possible there's nothing to lock in
// this operation.
if (!atLeastOneLock) return;
List<HiveLock> locks = lockMgr.lock(rqstBuilder.build());
ctx.setHiveLocks(locks);
}
@Override
public void commitTxn() throws LockException {
if (txnId == 0) {
throw new RuntimeException("Attempt to commit before opening a " +
"transaction");
}
try {
lockMgr.clearLocalLockRecords();
LOG.debug("Committing txn " + txnId);
client.commitTxn(txnId);
} catch (NoSuchTxnException e) {
LOG.error("Metastore could not find txn " + txnId);
throw new LockException(ErrorMsg.TXN_NO_SUCH_TRANSACTION.getMsg() , e);
} catch (TxnAbortedException e) {
LOG.error("Transaction " + txnId + " aborted");
throw new LockException(ErrorMsg.TXN_ABORTED.getMsg(), e);
} catch (TException e) {
throw new LockException(ErrorMsg.METASTORE_COMMUNICATION_FAILED.getMsg(),
e);
} finally {
txnId = 0;
}
}
@Override
public void rollbackTxn() throws LockException {
if (txnId == 0) {
throw new RuntimeException("Attempt to rollback before opening a " +
"transaction");
}
try {
lockMgr.clearLocalLockRecords();
LOG.debug("Rolling back txn " + txnId);
client.rollbackTxn(txnId);
} catch (NoSuchTxnException e) {
LOG.error("Metastore could not find txn " + txnId);
throw new LockException(ErrorMsg.TXN_NO_SUCH_TRANSACTION.getMsg() , e);
} catch (TException e) {
throw new LockException(ErrorMsg.METASTORE_COMMUNICATION_FAILED.getMsg(),
e);
} finally {
txnId = 0;
}
}
@Override
public void heartbeat() throws LockException {
LOG.debug("Heartbeating lock and transaction " + txnId);
List<HiveLock> locks = lockMgr.getLocks(false, false);
if (locks.size() == 0) {
if (txnId == 0) {
// No locks, no txn, we outta here.
return;
} else {
// Create one dummy lock so we can go through the loop below
DbLockManager.DbHiveLock dummyLock = new DbLockManager.DbHiveLock(0L);
locks.add(dummyLock);
}
}
for (HiveLock lock : locks) {
long lockId = ((DbLockManager.DbHiveLock)lock).lockId;
try {
client.heartbeat(txnId, lockId);
} catch (NoSuchLockException e) {
LOG.error("Unable to find lock " + lockId);
throw new LockException(ErrorMsg.LOCK_NO_SUCH_LOCK.getMsg(), e);
} catch (NoSuchTxnException e) {
LOG.error("Unable to find transaction " + txnId);
throw new LockException(ErrorMsg.TXN_NO_SUCH_TRANSACTION.getMsg(), e);
} catch (TxnAbortedException e) {
LOG.error("Transaction aborted " + txnId);
throw new LockException(ErrorMsg.TXN_ABORTED.getMsg(), e);
} catch (TException e) {
throw new LockException(
ErrorMsg.METASTORE_COMMUNICATION_FAILED.getMsg(), e);
}
}
}
@Override
public ValidTxnList getValidTxns() throws LockException {
init();
try {
return client.getValidTxns(txnId);
} catch (TException e) {
throw new LockException(ErrorMsg.METASTORE_COMMUNICATION_FAILED.getMsg(),
e);
}
}
@Override
public boolean supportsExplicitLock() {
return false;
}
@Override
public boolean useNewShowLocksFormat() {
return true;
}
@Override
public boolean supportsAcid() {
return true;
}
@Override
protected void destruct() {
try {
if (txnId > 0) rollbackTxn();
if (lockMgr != null) lockMgr.close();
} catch (Exception e) {
LOG.error("Caught exception " + e.getClass().getName() + " with message <" + e.getMessage()
+ ">, swallowing as there is nothing we can do with it.");
// Not much we can do about it here.
}
}
private void init() throws LockException {
if (client == null) {
if (conf == null) {
throw new RuntimeException("Must call setHiveConf before any other " +
"methods.");
}
try {
Hive db = Hive.get(conf);
client = db.getMSC();
} catch (MetaException e) {
throw new LockException(ErrorMsg.METASTORE_COULD_NOT_INITIATE.getMsg(), e);
} catch (HiveException e) {
throw new LockException(ErrorMsg.METASTORE_COULD_NOT_INITIATE.getMsg(), e);
}
}
}
}
| |
/*
* Copyright 2016 Google Inc. 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.physical_web.physicalweb;
import org.physical_web.collection.PhysicalWebCollection;
import org.physical_web.collection.PwPair;
import org.physical_web.collection.PwsClient;
import org.physical_web.collection.PwsResult;
import org.physical_web.collection.UrlDevice;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.view.Menu;
import android.widget.Toast;
import org.uribeacon.scan.util.RangingUtils;
import org.uribeacon.scan.util.RegionResolver;
import org.json.JSONException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* This class is for various static utilities, largely for manipulation of data structures provided
* by the collections library.
*/
class Utils {
public static final String PROD_ENDPOINT = "https://url-caster.appspot.com";
public static final int PROD_ENDPOINT_VERSION = 1;
public static final String DEV_ENDPOINT = "https://url-caster-dev.appspot.com";
public static final int DEV_ENDPOINT_VERSION = 1;
public static final String GOOGLE_ENDPOINT = "https://physicalweb.googleapis.com";
public static final int GOOGLE_ENDPOINT_VERSION = 2;
public static final String FAVORITES_KEY = "favorites";
public static final String BLE_DEVICE_TYPE = "ble";
public static final String FAT_BEACON_DEVICE_TYPE = "fat-beacon";
public static final String MDNS_LOCAL_DEVICE_TYPE = "mdns-local";
public static final String MDNS_PUBLIC_DEVICE_TYPE = "mdns-public";
public static final String WIFI_DIRECT_DEVICE_TYPE = "wifidirect";
public static final String SSDP_DEVICE_TYPE = "ssdp";
private static final String USER_OPTED_IN_KEY = "userOptedIn";
private static final String MAIN_PREFS_KEY = "physical_web_preferences";
private static final String DISCOVERY_SERVICE_PREFS_KEY =
"org.physical_web.physicalweb.DISCOVERY_SERVICE_PREFS";
private static final String SCANTIME_KEY = "scantime";
private static final String TYPE_KEY = "type";
private static final String PUBLIC_KEY = "public";
private static final String TITLE_KEY = "title";
private static final String DESCRIPTION_KEY = "description";
private static final String RSSI_KEY = "rssi";
private static final String TXPOWER_KEY = "tx";
private static final String PWSTRIPTIME_KEY = "pwstriptime";
private static final String WIFIDIRECT_KEY = "wifidirect";
private static final String WIFIDIRECT_PORT_KEY = "wifiport";
private static final RegionResolver REGION_RESOLVER = new RegionResolver();
private static final String SEPARATOR = "\0";
private static Set<String> mFavoriteUrls = new HashSet<>();
private static Set<String> mBlockedUrls = new HashSet<>();
private static final int GZIP_SIGNATURE_LENGTH = 2;
// Compares PwPairs by first considering if it has been favorited
// and then considering distance
public static class PwPairRelevanceComparator implements Comparator<PwPair> {
private Set<String> mFavorites = mFavoriteUrls;
public Map<String, Double> mCachedDistances;
PwPairRelevanceComparator() {
mCachedDistances = new HashMap<>();
}
public double getDistance(UrlDevice urlDevice) {
if (mCachedDistances.containsKey(urlDevice.getId())) {
return mCachedDistances.get(urlDevice.getId());
}
double distance = Utils.getDistance(urlDevice);
mCachedDistances.put(urlDevice.getId(), distance);
return distance;
}
@Override
public int compare(PwPair lhs, PwPair rhs) {
String lSite = lhs.getPwsResult().getSiteUrl();
String rSite = rhs.getPwsResult().getSiteUrl();
if (mFavorites.contains(lSite) == mFavorites.contains(rSite)) {
return Double.compare(getDistance(lhs.getUrlDevice()),
getDistance(rhs.getUrlDevice()));
} else {
if (mFavorites.contains(lSite)) {
return -1;
}
return 1;
}
}
}
/**
* Surface a notification to the user that the Physical Web is broadcasting. The notification
* specifies the transport or URL that is being broadcast and cannot be swiped away.
* @param context
* @param stopServiceReceiver
* @param broadcastNotificationId
* @param title
* @param text
* @param filter
*/
public static void createBroadcastNotification(Context context,
BroadcastReceiver stopServiceReceiver, int broadcastNotificationId, CharSequence title,
CharSequence text, String filter) {
Intent resultIntent = new Intent();
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
context.registerReceiver(stopServiceReceiver, new IntentFilter(filter));
PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, new Intent(filter),
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_leak_add_white_24dp)
.setContentTitle(title)
.setContentText(text)
.setOngoing(true)
.addAction(android.R.drawable.ic_menu_close_clear_cancel,
context.getString(R.string.stop), pIntent);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
notificationManager.notify(broadcastNotificationId, builder.build());
}
/**
* Reads the data from the inputStream.
* @param inputStream The input to read from.
* @return The entire input stream as a byte array
* @throws IOException
*/
public static byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
/**
* Get set of Blocked hosts.
*/
public static Set<String> getBlockedHosts() {
return mBlockedUrls;
}
/**
* Hides all items in the given menu.
* @param menu The menu to hide items for.
*/
public static void hideAllMenuItems(Menu menu) {
menu.findItem(R.id.action_about).setVisible(false);
menu.findItem(R.id.action_settings).setVisible(false);
menu.findItem(R.id.block_settings).setVisible(false);
menu.findItem(R.id.action_demos).setVisible(false);
}
/**
* Check if URL has been favorited.
* @param siteUrl
*/
public static boolean isFavorite(String siteUrl) {
return mFavoriteUrls.contains(siteUrl);
}
/**
* Toggles favorite status.
* @param siteUrl
*/
public static void toggleFavorite(String siteUrl) {
if (isFavorite(siteUrl)) {
mFavoriteUrls.remove(siteUrl);
return;
}
mFavoriteUrls.add(siteUrl);
}
/**
* Save favorites to shared preferences.
* @param context To get shared preferences.
*/
public static void saveFavorites(Context context) {
// Write the PW Collection
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putStringSet(FAVORITES_KEY, mFavoriteUrls)
.apply();
}
/**
* Get favorites from shared preferences.
* @param context To get shared preferences.
*/
public static void restoreFavorites(Context context) {
mFavoriteUrls = new HashSet<>(PreferenceManager.getDefaultSharedPreferences(
context).getStringSet(FAVORITES_KEY, new HashSet<String>()));
}
/**
* Check if any PwPair in the list is favorited.
* @param pairs List of pwPairs
*/
public static boolean containsFavorite(List<PwPair> pairs) {
for (PwPair pair : pairs) {
if (isFavorite(pair.getPwsResult().getSiteUrl())) {
return true;
}
}
return false;
}
/**
* Check if domain of URL has been blocked.
* @param siteUrl
* @return is siteURL blocked
*/
public static boolean isBlocked(PwPair pwPair) {
if (Utils.isWifiDirectDevice(pwPair.getUrlDevice())) {
return mBlockedUrls.contains(Utils.getWifiAddress(pwPair.getUrlDevice()));
}
try {
return mBlockedUrls.contains(new URI(pwPair.getPwsResult().getSiteUrl()).getHost());
} catch (URISyntaxException e) {
return false;
}
}
/**
* Block the host of siteUrl.
* @param siteUrl
*/
public static void addBlocked(PwPair pwPair) {
if (Utils.isWifiDirectDevice(pwPair.getUrlDevice())) {
mBlockedUrls.add(Utils.getWifiAddress(pwPair.getUrlDevice()));
return;
}
try {
mBlockedUrls.add(new URI(pwPair.getPwsResult().getSiteUrl()).getHost());
} catch (URISyntaxException e) {
return;
}
}
/**
* Unblock the host.
* @param host
*/
public static void removeBlocked(String host) {
if (mBlockedUrls.contains(host)) {
mBlockedUrls.remove(host);
}
}
/**
* Save blocked set to shared preferences.
* @param context to access shared preferences
*/
public static void saveBlocked(Context context) {
// Write the PW Collection
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putStringSet("blocked", mBlockedUrls)
.apply();
}
/**
* Restore blocked set from shared preferences.
* @param context to access shared preferences
*/
public static void restoreBlocked(Context context) {
mBlockedUrls = new HashSet<>(PreferenceManager.getDefaultSharedPreferences(
context).getStringSet("blocked", new HashSet<String>()));
}
public static class WifiDirectInfo {
public String title;
public int port;
public WifiDirectInfo(String title, int port) {
this.title = title;
this.port = port;
}
}
/**
* Checks to see if name matches defined wifi direct structure.
* @param name WifiDirect device name
*/
public static WifiDirectInfo parseWifiDirectName(String name) {
String split[] = name.split("-");
if (split.length < 3 || !split[0].equals("PW")
|| !split[split.length - 1].matches("\\d+")) {
return null;
}
return new WifiDirectInfo(name.substring(3, name.lastIndexOf('-')),
Integer.parseInt(split[split.length - 1]));
}
private static class PwsEndpoint {
public String url;
public int apiVersion;
public String apiKey;
public boolean neededApiKey;
public PwsEndpoint(String url, int apiVersion, String apiKey) {
this.url = url;
this.apiVersion = apiVersion;
this.apiKey = apiKey;
this.neededApiKey = needApiKey();
if (this.neededApiKey) {
this.url = PROD_ENDPOINT;
this.apiVersion = PROD_ENDPOINT_VERSION;
}
}
private boolean needApiKey() {
return apiVersion >= 2 && apiKey.isEmpty();
}
}
private static void throwEncodeException(JSONException e) {
throw new RuntimeException("Could not encode JSON", e);
}
private static void deletePreference(Context context, String preferenceName) {
context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE).edit().clear().apply();
}
private static int getGoogleApiKeyResourceId(Context context) {
return context.getResources().getIdentifier("google_api_key", "string",
context.getPackageName());
}
private static PwsEndpoint getCurrentPwsEndpoint(Context context) {
return new PwsEndpoint(getCurrentPwsEndpointUrl(context),
getCurrentPwsEndpointVersion(context),
getCurrentPwsEndpointApiKey(context));
}
private static String getCurrentPwsEndpointString(Context context) {
String defaultEndpoint = getDefaultPwsEndpointPreferenceString(context);
return PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(
R.string.pws_endpoint_setting_key), defaultEndpoint);
}
private static String getCurrentPwsEndpointUrl(Context context) {
String endpoint = getCurrentPwsEndpointString(context);
return endpoint.split(SEPARATOR)[0];
}
private static int getCurrentPwsEndpointVersion(Context context) {
String endpoint = getCurrentPwsEndpointString(context);
return Integer.parseInt(endpoint.split(SEPARATOR)[1]);
}
private static String getCurrentPwsEndpointApiKey(Context context) {
String endpoint = getCurrentPwsEndpointString(context);
if (endpoint.endsWith(SEPARATOR) || endpoint.endsWith("null")) {
return "";
}
return endpoint.split(SEPARATOR)[2];
}
private static String readCustomPwsEndpointUrl(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.custom_pws_url_key), "");
}
private static int readCustomPwsEndpointVersion(Context context) {
return Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.custom_pws_version_key),
context.getString(R.string.custom_pws_version_default)));
}
private static String readCustomPwsEndpointApiKey(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.custom_pws_api_key_key), "");
}
/**
* Gets whether the user has optedIn from SharedPreferences.
* @param context The context for the SharedPreferences.
* @return True if the user has optedIn otherwise false.
*/
public static boolean checkIfUserHasOptedIn(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(USER_OPTED_IN_KEY, false);
}
public abstract static class UrlDeviceDiscoveryServiceConnection implements ServiceConnection {
private Context mContext;
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// Forward the service to the implementing class
serviceHandler((UrlDeviceDiscoveryService.LocalBinder) service);
mContext.unbindService(this);
}
@Override
public void onServiceDisconnected(ComponentName className) {
}
public void connect(Context context) {
mContext = context;
Intent intent = new Intent(mContext, UrlDeviceDiscoveryService.class);
mContext.startService(intent);
mContext.bindService(intent, this, Context.BIND_AUTO_CREATE);
}
public abstract void serviceHandler(UrlDeviceDiscoveryService.LocalBinder localBinder);
}
/**
* Delete the cached results from the UrlDeviceDisoveryService.
* @param context The context for the service.
*/
public static void deleteCache(Context context) {
new UrlDeviceDiscoveryServiceConnection() {
@Override
public void serviceHandler(UrlDeviceDiscoveryService.LocalBinder localBinder) {
localBinder.getServiceInstance().clearCache();
}
}.connect(context);
}
/**
* Starts scanning with UrlDeviceDisoveryService.
* @param context The context for the service.
*/
public static void startScan(Context context) {
new UrlDeviceDiscoveryServiceConnection() {
@Override
public void serviceHandler(UrlDeviceDiscoveryService.LocalBinder localBinder) {
localBinder.getServiceInstance().restartScan();
}
}.connect(context);
}
/**
* Format the endpoint URL, version, and API key.
* @param pwsUrl The URL of the Physical Web Service.
* @param pwsVersion The API version the PWS is running.
* @param apiKey The API key for the PWS.
* @return The PWS endpoint formatted for saving to SharedPreferences.
*/
public static String formatEndpointForSharedPrefernces(String pwsUrl, int pwsVersion,
String apiKey) {
pwsUrl = pwsUrl == null ? "" : pwsUrl;
apiKey = apiKey == null ? "" : apiKey;
return pwsUrl + SEPARATOR + pwsVersion + SEPARATOR + apiKey;
}
/**
* Get the default PWS Endpoint formatted for SharedPreferences.
* @param context The context for the SharedPreferences.
* @return The default PWS endpoint formatted for saving to SharedPreferences.
*/
public static String getDefaultPwsEndpointPreferenceString(Context context) {
if (isGoogleApiKeyAvailable(context)) {
return formatEndpointForSharedPrefernces(GOOGLE_ENDPOINT, GOOGLE_ENDPOINT_VERSION,
getGoogleApiKey(context));
}
return formatEndpointForSharedPrefernces(PROD_ENDPOINT, PROD_ENDPOINT_VERSION, "");
}
/**
* Saves the optIn preference in the default shared preferences file.
* @param context The context for the SharedPreferences.
*/
public static void setOptInPreference(Context context) {
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putBoolean(USER_OPTED_IN_KEY, true).apply();
}
/**
* Saves the endpoint to SharedPreferences.
* @param context The context for the SharedPreferences.
* @param endpoint The endpoint formatted for SharedPreferences.
*/
public static void setPwsEndpointPreference(Context context, String endpoint) {
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putString(context.getString(R.string.pws_endpoint_setting_key), endpoint)
.apply();
}
/**
* Saves the default settings to the SharedPreferences.
* @param context The context for the SharedPreferences.
*/
public static void setSharedPreferencesDefaultValues(Context context) {
PreferenceManager.setDefaultValues(context, R.xml.settings, false);
setPwsEndpointPreference(context, getCurrentPwsEndpointString(context));
if (context.getSharedPreferences(MAIN_PREFS_KEY, Context.MODE_PRIVATE)
.getBoolean(USER_OPTED_IN_KEY, false)) {
setOptInPreference(context);
deletePreference(context, MAIN_PREFS_KEY);
deletePreference(context, DISCOVERY_SERVICE_PREFS_KEY);
}
}
/**
* Sets the client's endpoint to the currently selected endpoint.
* @param context The context for the SharedPreferences.
* @param pwsClient The client used for requests to the Physical Web Service.
* @return If the endpoint was successfully set to current endpoint or if it had to be reverted.
* to the default endpoint.
*/
public static boolean setPwsEndpoint(Context context, PwsClient pwsClient) {
PwsEndpoint endpoint = getCurrentPwsEndpoint(context);
pwsClient.setEndpoint(endpoint.url, endpoint.apiVersion, endpoint.apiKey);
return !endpoint.neededApiKey;
}
/**
* Sets the client's endpoint to the currently selected endpoint.
* @param context The context for the SharedPreferences.
* @param physicalWebCollection The client used for requests to the Physical Web Service.
* @return If the endpoint was successfully set to current endpoint or if it had to be reverted.
* to the default endpoint.
*/
public static boolean setPwsEndpoint(Context context,
PhysicalWebCollection physicalWebCollection) {
PwsEndpoint endpoint = getCurrentPwsEndpoint(context);
physicalWebCollection.setPwsEndpoint(endpoint.url, endpoint.apiVersion, endpoint.apiKey);
return !endpoint.neededApiKey;
}
/**
* Sets the client's endpoint to the Google endpoint.
* @param context The context for the SharedPreferences.
* @param pwsClient The client used for requests to the Physical Web Service.
*/
public static void setPwsEndPointToGoogle(Context context, PwsClient pwsClient) {
pwsClient.setEndpoint(GOOGLE_ENDPOINT, GOOGLE_ENDPOINT_VERSION, getGoogleApiKey(context));
}
/**
* Checks if the currently selected PWS has a valid format, not that it exists.
* @param context The context for the SharedPreferences.
* @return If the current PWS configured properly.
*/
public static boolean isCurrentPwsSelectionValid(Context context) {
String endpoint = getCurrentPwsEndpointUrl(context);
int apiVersion = getCurrentPwsEndpointVersion(context);
String apiKey = getCurrentPwsEndpointApiKey(context);
return !endpoint.isEmpty() && !(apiVersion >= 2 && apiKey.isEmpty());
}
/**
* Checks if the Google API key resource exists.
* @param context The context for the resources.
* @return If the Google API key is available.
*/
public static boolean isGoogleApiKeyAvailable(Context context) {
return getGoogleApiKeyResourceId(context) != 0;
}
/**
* Get the Google API key if available.
* @param context The context for the resources.
* @return The API key for the Google PWS if available or an empty string.
*/
public static String getGoogleApiKey(Context context) {
int resourceId = getGoogleApiKeyResourceId(context);
return resourceId != 0 ? context.getString(resourceId) : "";
}
/**
* Gets the saved settings for the custom PWS.
* @param context The context for the SharedPreferences.
* @return The custom PWS endpoint formatted for SharedPrefences.
*/
public static String getCustomPwsEndpoint(Context context) {
return formatEndpointForSharedPrefernces(readCustomPwsEndpointUrl(context),
readCustomPwsEndpointVersion(context),
readCustomPwsEndpointApiKey(context));
}
/**
* Get the saved setting for enabling Fatbeacon.
* @param context The context for the SharedPreferences.
* @return The enable Fatbeacon setting.
*/
public static boolean isFatBeaconEnabled(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(context.getString(R.string.fatbeacon_key), false);
}
/**
* Get the saved setting for enabling mDNS folder.
* @param context The context for the SharedPreferences.
* @return The enable mDNS folder setting.
*/
public static boolean isMdnsEnabled(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(context.getString(R.string.mDNS_key), false);
}
/**
* Get the saved setting for enabling Wifi direct.
* @param context The context for the SharedPreferences.
* @return The enable wifi direct setting.
*/
public static boolean isWifiDirectEnabled(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(context.getString(R.string.wifi_direct_key), false);
}
/**
* Get the saved setting for debug View.
* @param context The context for the SharedPreferences.
* @return The debug view setting.
*/
public static boolean isDebugViewEnabled(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(context.getString(R.string.debug_key), false);
}
/**
* Get the saved setting for enabling mDNS folder.
* @param context The context for the SharedPreferences.
* @return The enable mDNS folder setting.
*/
public static int getWifiDirectPort(Context context) {
String port = PreferenceManager.getDefaultSharedPreferences(context)
.getString(context.getString(R.string.wifi_port_key), "1234");
if (port.matches("\\d+")) {
return Integer.parseInt(port);
}
return 1234;
}
/**
* Toast the user to indicate the API key is missing.
* @param context The context for the resources.
*/
public static void warnUserOnMissingApiKey(Context context) {
Toast.makeText(context, R.string.error_api_key_no_longer_available, Toast.LENGTH_SHORT).show();
}
/**
* Create an intent for opening a URL.
* @param pwsResult The result that has the URL the user clicked on.
* @return The intent that opens the URL.
*/
public static Intent createNavigateToUrlIntent(PwsResult pwsResult) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(pwsResult.getSiteUrl()));
return intent;
}
/**
* Setup an intent to open the URL.
* @param pwsResult The result that has the URL the user clicked on.
* @param context The context for the activity.
* @return The intent that opens the URL.
*/
public static PendingIntent createNavigateToUrlPendingIntent(
PwsResult pwsResult, Context context) {
Intent intent = createNavigateToUrlIntent(pwsResult);
int requestID = (int) System.currentTimeMillis();
return PendingIntent.getActivity(context, requestID, intent, 0);
}
/**
* Gets the top ranked PwPair with the given groupId.
* @param pwCollection The collection of PwPairs.
* @param groupId The group id of the requested PwPair.
* @return The top ranked PwPair with a given group id if it exist.
*/
public static PwPair getTopRankedPwPairByGroupId(
PhysicalWebCollection pwCollection, String groupId) {
// This does the same thing as the PhysicalWebCollection method, only it uses our custom
// getGroupId method.
for (PwPair pwPair : pwCollection.getGroupedPwPairsSortedByRank(
new PwPairRelevanceComparator())) {
if (getGroupId(pwPair.getPwsResult()).equals(groupId)) {
return pwPair;
}
}
return null;
}
/**
* Decode the downloaded icon to a Bitmap.
* @param pwCollection The collection where the icon is stored.
* @param pwsResult The result the icon is for.
* @return The icon as a Bitmap.
*/
public static Bitmap getBitmapIcon(PhysicalWebCollection pwCollection, PwsResult pwsResult) {
byte[] iconBytes = pwCollection.getIcon(pwsResult.getIconUrl());
if (iconBytes == null) {
return null;
}
return BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
}
/**
* Get the scan time for a device if available.
* @param urlDevice The device to get the scan time for.
* @return The scan time in millisecond for the device.
* @throws RuntimeException If the device doesn't have a scan time.
*/
public static long getScanTimeMillis(UrlDevice urlDevice) {
try {
return urlDevice.getExtraLong(SCANTIME_KEY);
} catch (JSONException e) {
throw new RuntimeException("Scan time not available in device " + urlDevice.getId(), e);
}
}
/**
* Checks if device is public.
* @param urlDevice The device that is getting checked.
* @return If the device is public or not.
*/
public static boolean isPublic(UrlDevice urlDevice) {
return urlDevice.optExtraBoolean(PUBLIC_KEY, true);
}
/**
* Checks if device is PWS resolvable.
* @param urlDevice The device that is getting checked.
* @return If the device is resolvable or not.
*/
public static boolean isResolvableDevice(UrlDevice urlDevice) {
String type = urlDevice.optExtraString(TYPE_KEY, "");
return type.equals(BLE_DEVICE_TYPE)
|| type.equals(SSDP_DEVICE_TYPE)
|| type.equals(MDNS_PUBLIC_DEVICE_TYPE);
}
/**
* Checks if device is Bluetooth Low Energy.
* @param urlDevice The device that is getting checked.
* @return If the device is BLE or not.
*/
public static boolean isBleUrlDevice(UrlDevice urlDevice) {
return urlDevice.optExtraString(TYPE_KEY, "").equals(BLE_DEVICE_TYPE);
}
/**
* Gets if the device is a FatBeacon.
* @param urlDevice The device that is getting checked.
* @return Is a FatBeacon device
*/
public static boolean isFatBeaconDevice(UrlDevice urlDevice) {
return urlDevice.optExtraString(TYPE_KEY, "").equals(FAT_BEACON_DEVICE_TYPE);
}
/**
* Checks if device is mdns device broadcasting public url.
* @param urlDevice The device that is getting checked.
* @return If the device is mdns public or not.
*/
public static boolean isMDNSPublicDevice(UrlDevice urlDevice) {
return urlDevice.optExtraString(TYPE_KEY, "").equals(MDNS_PUBLIC_DEVICE_TYPE);
}
/**
* Checks if device is Local.
* @param urlDevice The device that is getting checked.
* @return If the device is local or not.
*/
public static boolean isMDNSLocalDevice(UrlDevice urlDevice) {
return urlDevice.optExtraString(TYPE_KEY, "").equals(MDNS_LOCAL_DEVICE_TYPE);
}
/**
* Gets if the device is Wifi Direct.
* @param urlDevice The device that is getting checked.
* @return Is a WifiDirect device
*/
public static boolean isWifiDirectDevice(UrlDevice urlDevice) {
return urlDevice.optExtraString(TYPE_KEY, "").equals(WIFI_DIRECT_DEVICE_TYPE);
}
/**
* Gets if the device is SSDP.
* @param urlDevice The device that is getting checked.
* @return Is a SSDP device
*/
public static boolean isSSDPDevice(UrlDevice urlDevice) {
return urlDevice.optExtraString(TYPE_KEY, "").equals(SSDP_DEVICE_TYPE);
}
/**
* Gets the device RSSI if it is Bluetooth Low Energy.
* @param urlDevice The device that is getting checked.
* @return The RSSI for the device.
* @throws RuntimeException If the device is not BLE.
*/
public static int getRssi(UrlDevice urlDevice) {
try {
return urlDevice.getExtraInt(RSSI_KEY);
} catch (JSONException e) {
throw new RuntimeException("Tried to get RSSI from non-ble device " + urlDevice.getId(), e);
}
}
/**
* Gets the device TX power if it is Bluetooth Low Energy.
* @param urlDevice The device that is getting checked.
* @return The TX power for the device.
* @throws RuntimeException If the device is not BLE.
*/
public static int getTxPower(UrlDevice urlDevice) {
try {
return urlDevice.getExtraInt(TXPOWER_KEY);
} catch (JSONException e) {
throw new RuntimeException(
"Tried to get TX power from non-ble device " + urlDevice.getId(), e);
}
}
/**
* Gets the UrlDevice Title.
* @param urlDevice The device that is getting checked.
* @return The Title for the device.
* @throws RuntimeException if no title present.
*/
public static String getTitle(UrlDevice urlDevice) {
try {
return urlDevice.getExtraString(TITLE_KEY);
} catch (JSONException e) {
throw new RuntimeException(
"Tried to get Title when no title set " + urlDevice.getId(), e);
}
}
/**
* Gets the UrlDevice Description.
* @param urlDevice The device that is getting checked.
* @return The Description for the device.
* @throws RuntimeException if no description present.
*/
public static String getDescription(UrlDevice urlDevice) {
try {
return urlDevice.getExtraString(DESCRIPTION_KEY);
} catch (JSONException e) {
throw new RuntimeException(
"Tried to get Description when no description set " + urlDevice.getId(), e);
}
}
/**
* Gets the UrlDevice MAC address.
* @param urlDevice The device that is getting checked.
* @return The MAC address for the device.
* @throws RuntimeException if no address present.
*/
public static String getWifiAddress(UrlDevice urlDevice) {
try {
return urlDevice.getExtraString(WIFIDIRECT_KEY);
} catch (JSONException e) {
throw new RuntimeException(
"Tried to get address when no description set " + urlDevice.getId(), e);
}
}
/**
* Gets the UrlDevice port.
* @param urlDevice The device that is getting checked.
* @return The port for the device.
* @throws RuntimeException if no port present.
*/
public static int getWifiPort(UrlDevice urlDevice) {
try {
return urlDevice.getExtraInt(WIFIDIRECT_PORT_KEY);
} catch (JSONException e) {
throw new RuntimeException(
"Tried to get port when no port set " + urlDevice.getId(), e);
}
}
/**
* Gets the amount of time in milliseconds to get the result from the PWS if available.
* @param pwsResult The result that is being queried.
* @return The trip time for the result.
* @throws RuntimeException If the trip time is not recorded.
*/
public static long getPwsTripTimeMillis(PwsResult pwsResult) {
try {
return pwsResult.getExtraLong(PWSTRIPTIME_KEY);
} catch (JSONException e) {
throw new RuntimeException("PWS trip time not recorded in PwsResult");
}
}
/**
* Gets the groupId for the result.
* @param pwsResult The result that is being queried.
* @return The groupId for the result.
*/
public static String getGroupId(PwsResult pwsResult) {
// The PWS does not always give us a group id yet.
if (pwsResult.getGroupId() == null || pwsResult.getGroupId().equals("")) {
try {
return new URI(pwsResult.getSiteUrl()).getHost() + pwsResult.getTitle();
} catch (URISyntaxException e) {
return pwsResult.getSiteUrl();
}
}
return pwsResult.getGroupId();
}
/**
* Updates the region resolver with the device.
* @param urlDevice The device to update region with.
*/
public static void updateRegion(UrlDevice urlDevice) {
REGION_RESOLVER.onUpdate(urlDevice.getId(), getRssi(urlDevice), getTxPower(urlDevice));
}
/**
* Gets the smoothed RSSI for device from the region resolver.
* @param urlDevice The device being queried.
* @return The smoothed RSSI for the device.
*/
public static double getSmoothedRssi(UrlDevice urlDevice) {
return REGION_RESOLVER.getSmoothedRssi(urlDevice.getId());
}
/**
* Gets the distance for device from the region resolver.
* @param urlDevice The device being queried.
* @return The distance for the device.
*/
public static double getDistance(UrlDevice urlDevice) {
return REGION_RESOLVER.getDistance(urlDevice.getId());
}
/**
* Gets the region string for device from the region resolver.
* @param urlDevice The device being queried.
* @return The region string for the device.
*/
public static String getRegionString(UrlDevice urlDevice) {
return RangingUtils.toString(REGION_RESOLVER.getRegion(urlDevice.getId()));
}
static class UrlDeviceBuilder extends UrlDevice.Builder {
/**
* Constructor for the UrlDeviceBuilder.
* @param id The id of the UrlDevice.
* @param url The url of the UrlDevice.
*/
public UrlDeviceBuilder(String id, String url) {
super(id, url);
}
/**
* Set the device type.
* @return The builder with type set.
*/
public UrlDeviceBuilder setDeviceType(String type) {
addExtra(TYPE_KEY, type);
return this;
}
/**
* Setter for the ScanTimeMillis.
* @param timeMillis The scan time of the UrlDevice.
* @return The builder with ScanTimeMillis set.
*/
public UrlDeviceBuilder setScanTimeMillis(long timeMillis) {
addExtra(SCANTIME_KEY, timeMillis);
return this;
}
/**
* Set the public key to false.
* @return The builder with public set to false.
*/
public UrlDeviceBuilder setPrivate() {
addExtra(PUBLIC_KEY, false);
return this;
}
/**
* Set the public key to true.
* @return The builder with public set to true.
*/
public UrlDeviceBuilder setPublic() {
addExtra(PUBLIC_KEY, true);
return this;
}
/**
* Set the title.
* @param title corresonding to UrlDevice.
* @return The builder with title
*/
public UrlDeviceBuilder setTitle(String title) {
addExtra(TITLE_KEY, title);
return this;
}
/**
* Set the description.
* @param description corresonding to UrlDevice.
* @return The builder with description
*/
public UrlDeviceBuilder setDescription(String description) {
addExtra(DESCRIPTION_KEY, description);
return this;
}
/**
* Set wifi-direct MAC address.
* @param MAC address corresonding to UrlDevice.
* @return The builder with address
*/
public UrlDeviceBuilder setWifiAddress(String address) {
addExtra(WIFIDIRECT_KEY, address);
return this;
}
/**
* Set wifi-direct port.
* @param port corresonding to UrlDevice.
* @return The builder with port
*/
public UrlDeviceBuilder setWifiPort(int port) {
addExtra(WIFIDIRECT_PORT_KEY, port);
return this;
}
/**
* Setter for the RSSI.
* @param rssi The RSSI of the UrlDevice.
* @return The builder with RSSI set.
*/
public UrlDeviceBuilder setRssi(int rssi) {
addExtra(RSSI_KEY, rssi);
return this;
}
/**
* Setter for the TX power.
* @param txPower The TX power of the UrlDevice.
* @return The builder with TX power set.
*/
public UrlDeviceBuilder setTxPower(int txPower) {
addExtra(TXPOWER_KEY, txPower);
return this;
}
}
static class PwsResultBuilder extends PwsResult.Builder {
/**
* Constructor for the PwsResultBuilder.
* @param pwsResult The base result of the PwsResultBuilder.
*/
public PwsResultBuilder(PwsResult pwsResult) {
super(pwsResult);
}
/**
* Setter for the PWS Trip Time.
* @param pwsResult The pwsResult.
* @param timeMillis The PWS Trip Time for the result.
* @return The builder PWS Trip Time set.
*/
public PwsResultBuilder setPwsTripTimeMillis(PwsResult pwsResult, long timeMillis) {
addExtra(PWSTRIPTIME_KEY, timeMillis);
return this;
}
}
/**
* Determines if a file is gzipped by examining the signature of
* the file, which is the first two bytes.
* @param file to be determined if is gzipped.
* @return true If the contents of the file are gzipped otherwise false.
*/
public static boolean isGzippedFile(File file) {
InputStream input;
try {
input = new FileInputStream(file);
} catch(FileNotFoundException e) {
return false;
}
byte[] signature = new byte[GZIP_SIGNATURE_LENGTH];
try {
input.read(signature);
} catch(IOException e) {
return false;
}
return ((signature[0] == (byte) (GZIPInputStream.GZIP_MAGIC))
&& (signature[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8)));
}
/**
* Out-of-place Gunzips from src to dest.
* @param src file containing gzipped information.
* @param dest file to place decompressed information.
* @return File that has decompressed information.
*/
public static File gunzip(File src, File dest) {
byte[] buffer = new byte[1024];
try{
GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(src));
FileOutputStream out = new FileOutputStream(dest);
int len;
while ((len = gzis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
gzis.close();
out.close();
} catch(IOException ex){
ex.printStackTrace();
}
return dest;
}
}
| |
package edu.cmu.lti.oaqa.cse.space.tree;
import java.util.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class Tree<T> {
public enum GenericTreeTraversalOrderEnum {
PRE_ORDER, POST_ORDER
}
private Node<T> root;
private Set<Node<T>> leaves;
public Tree() {
super();
leaves = Sets.newHashSet();
}
public Node<T> getRoot() {
return this.root;
}
public void setRoot(Node<T> root) {
if (root != null)
leaves.add(root);
this.root = root;
}
/*
* public void addToLeaves(Node<T>... nodes) { List<Node<T>> newLeaves =
* Lists.newArrayList(); for (Node<T> newLeaf : nodes) for (Node<T> oldLeaf
* : leaves) addToLeaf(oldLeaf, newLeaf, newLeaves); leaves = newLeaves; }
*/
public Set<Node<T>> getLeaves() {
return leaves;
}
public void addToLeaf(Node<T> oldLeaf, Node<T> newLeaf) {
oldLeaf.addChild(newLeaf);
leaves.add(newLeaf);
leaves.remove(oldLeaf);
}
public int getNumberOfNodes() {
int numberOfNodes = 0;
if (root != null) {
numberOfNodes = auxiliaryGetNumberOfNodes(root) + 1; // 1 for the
// root!
}
return numberOfNodes;
}
private int auxiliaryGetNumberOfNodes(Node<T> node) {
int numberOfNodes = node.getNumberOfChildren();
for (Node<T> child : node.getChildren()) {
numberOfNodes += auxiliaryGetNumberOfNodes(child);
}
return numberOfNodes;
}
public boolean exists(Node<T> nodeToFind) {
return (find(nodeToFind) != null);
}
public Node<T> find(Node<T> nodeToFind) {
Node<T> returnNode = null;
if (root != null) {
returnNode = auxiliaryFind(root, nodeToFind);
}
return returnNode;
}
private Node<T> auxiliaryFind(Node<T> currentNode, Node<T> nodeToFind) {
Node<T> returnNode = null;
int i = 0;
if (currentNode.equals(nodeToFind)) {
returnNode = currentNode;
}
else if (currentNode.hasChildren()) {
i = 0;
while (returnNode == null && i < currentNode.getNumberOfChildren()) {
returnNode = auxiliaryFind(currentNode.getChildAt(i),
nodeToFind);
i++;
}
}
return returnNode;
}
public boolean isEmpty() {
return (root == null);
}
public List<Node<T>> build(GenericTreeTraversalOrderEnum traversalOrder) {
List<Node<T>> returnList = null;
if (root != null) {
returnList = build(root, traversalOrder);
}
return returnList;
}
public List<Node<T>> build(Node<T> node,
GenericTreeTraversalOrderEnum traversalOrder) {
List<Node<T>> traversalResult = new ArrayList<Node<T>>();
if (traversalOrder == GenericTreeTraversalOrderEnum.PRE_ORDER) {
buildPreOrder(node, traversalResult);
}
else if (traversalOrder == GenericTreeTraversalOrderEnum.POST_ORDER) {
buildPostOrder(node, traversalResult);
}
return traversalResult;
}
private void buildPreOrder(Node<T> node, List<Node<T>> traversalResult) {
traversalResult.add(node);
for (Node<T> child : node.getChildren()) {
buildPreOrder(child, traversalResult);
}
}
private void buildPostOrder(Node<T> node, List<Node<T>> traversalResult) {
for (Node<T> child : node.getChildren()) {
buildPostOrder(child, traversalResult);
}
traversalResult.add(node);
}
public Map<Node<T>, Integer> buildWithDepth(
GenericTreeTraversalOrderEnum traversalOrder) {
Map<Node<T>, Integer> returnMap = null;
if (root != null) {
returnMap = buildWithDepth(root, traversalOrder);
}
return returnMap;
}
public Map<Node<T>, Integer> buildWithDepth(Node<T> node,
GenericTreeTraversalOrderEnum traversalOrder) {
Map<Node<T>, Integer> traversalResult = new LinkedHashMap<Node<T>, Integer>();
if (traversalOrder == GenericTreeTraversalOrderEnum.PRE_ORDER) {
buildPreOrderWithDepth(node, traversalResult, 0);
}
else if (traversalOrder == GenericTreeTraversalOrderEnum.POST_ORDER) {
buildPostOrderWithDepth(node, traversalResult, 0);
}
return traversalResult;
}
private void buildPreOrderWithDepth(Node<T> node,
Map<Node<T>, Integer> traversalResult, int depth) {
traversalResult.put(node, depth);
for (Node<T> child : node.getChildren()) {
buildPreOrderWithDepth(child, traversalResult, depth + 1);
}
}
private void buildPostOrderWithDepth(Node<T> node,
Map<Node<T>, Integer> traversalResult, int depth) {
for (Node<T> child : node.getChildren()) {
buildPostOrderWithDepth(child, traversalResult, depth + 1);
}
traversalResult.put(node, depth);
}
public String toString() {
/*
* We're going to assume a pre-order traversal by default
*/
/*
* String stringRepresentation = "";
*
* if (root != null) { stringRepresentation = build(
* GenericTreeTraversalOrderEnum.PRE_ORDER).toString();
*
* }
*
* return stringRepresentation;
*/
return toStringWithDepth();
}
public String toStringWithDepth() {
/*
* We're going to assume a pre-order traversal by default
*/
String stringRepresentation = "";
Map<Node<T>, Integer> depthMap = Collections.EMPTY_MAP;
if (root != null) {
depthMap = buildWithDepth(GenericTreeTraversalOrderEnum.PRE_ORDER);
}
if (!depthMap.isEmpty())
for (Node<T> node : depthMap.keySet())
stringRepresentation += whiteSpace(depthMap.get(node)) + "|---"
+ node + "\n";
return stringRepresentation;
}
private static String whiteSpace(int space) {
String whitespace = "";
for (int i = 0; i < Math.round(space *1.5); i++)
whitespace += " ";
return whitespace;
}
}
| |
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.gettablenames;
import java.util.List;
import java.util.Map;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.shared.SharedObjectInterface;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.w3c.dom.Node;
/*
* Created on 03-Juin-2008
*
*/
public class GetTableNamesMeta extends BaseStepMeta implements StepMetaInterface
{
private static Class<?> PKG = GetTableNamesMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
/** database connection */
private DatabaseMeta database;
private String schemaname;
/** function result: new value name */
private String tablenamefieldname;
private String sqlcreationfieldname;
private String objecttypefieldname;
private String issystemobjectfieldname;
private boolean includeCatalog;
private boolean includeSchema;
private boolean includeTable;
private boolean includeView;
private boolean includeProcedure;
private boolean includeSynonym;
private boolean addSchemaInOutput;
private boolean dynamicSchema;
private String schenameNameField;
public GetTableNamesMeta()
{
super(); // allocate BaseStepMeta
}
/**
* @return Returns the database.
*/
public DatabaseMeta getDatabase()
{
return database;
}
/**
* @param database The database to set.
*/
public void setDatabase(DatabaseMeta database)
{
this.database = database;
}
/**
* @return Returns the resultName.
*/
public String getTablenameFieldName()
{
return tablenamefieldname;
}
/**
* @param tablenamefieldname The tablenamefieldname to set.
*/
public void setTablenameFieldName(String tablenamefieldname)
{
this.tablenamefieldname = tablenamefieldname;
}
/**
* @return Returns the resultName.
*/
public String getSQLCreationFieldName()
{
return sqlcreationfieldname;
}
/**
* @param sqlcreationfieldname The sqlcreationfieldname to set.
*/
public void setSQLCreationFieldName(String sqlcreationfieldname)
{
this.sqlcreationfieldname = sqlcreationfieldname;
}
/**
* @return Returns the resultName.
*/
public String getSchemaName()
{
return schemaname;
}
/**
* @param schemaname The schemaname to set.
*/
public void setSchemaName(String schemaname)
{
this.schemaname = schemaname;
}
/**
* @param objecttypefieldname The objecttypefieldname to set.
*/
public void setObjectTypeFieldName(String objecttypefieldname)
{
this.objecttypefieldname = objecttypefieldname;
}
/**
* @param issystemobjectfieldname The issystemobjectfieldname to set.
*/
public void setIsSystemObjectFieldName(String issystemobjectfieldname)
{
this.issystemobjectfieldname = issystemobjectfieldname;
}
/**
* @return Returns the objecttypefieldname.
*/
public String getObjectTypeFieldName()
{
return objecttypefieldname;
}
/**
* @return Returns the issystemobjectfieldname.
*/
public String isSystemObjectFieldName()
{
return issystemobjectfieldname;
}
/**
* @return Returns the schenameNameField.
*/
public String getSchemaFieldName()
{
return schenameNameField;
}
/**
* @param schenameNameField teh schenameNameField to set.
*/
public void setSchemaFieldName(String schenameNameField)
{
this.schenameNameField= schenameNameField;
}
public void setIncludeTable(boolean includetable)
{
this.includeTable=includetable;
}
public boolean isIncludeTable()
{
return this.includeTable;
}
public void setIncludeSchema(boolean includeSchema)
{
this.includeSchema=includeSchema;
}
public boolean isIncludeSchema()
{
return this.includeSchema;
}
public void setIncludeCatalog(boolean includeCatalog)
{
this.includeCatalog=includeCatalog;
}
public boolean isIncludeCatalog()
{
return this.includeCatalog;
}
public void setIncludeView(boolean includeView)
{
this.includeView=includeView;
}
public boolean isIncludeView()
{
return this.includeView;
}
public void setIncludeProcedure(boolean includeProcedure)
{
this.includeProcedure=includeProcedure;
}
public boolean isIncludeProcedure()
{
return this.includeProcedure;
}
public void setIncludeSynonym(boolean includeSynonym)
{
this.includeSynonym=includeSynonym;
}
public boolean isIncludeSynonym()
{
return this.includeSynonym;
}
public void setDynamicSchema(boolean dynamicSchema)
{
this.dynamicSchema=dynamicSchema;
}
public boolean isDynamicSchema()
{
return this.dynamicSchema;
}
public void setAddSchemaInOut(boolean addSchemaInOutput)
{
this.addSchemaInOutput=addSchemaInOutput;
}
public boolean isAddSchemaInOut()
{
return this.addSchemaInOutput;
}
public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters)
throws KettleXMLException {
readData(stepnode, databases);
}
public Object clone()
{
GetTableNamesMeta retval = (GetTableNamesMeta) super.clone();
return retval;
}
public void setDefault()
{
database = null;
schemaname=null;
includeCatalog=false;
includeSchema=false;
includeTable=true;
includeProcedure=true;
includeView=true;
includeSynonym=true;
addSchemaInOutput=false;
tablenamefieldname = "tablename"; //$NON-NLS-1$
sqlcreationfieldname=null;
objecttypefieldname="type";
issystemobjectfieldname="is system";
dynamicSchema=false;
schenameNameField=null;
}
public void getFields(RowMetaInterface r, String name, RowMetaInterface info[], StepMeta nextStep, VariableSpace space) throws KettleStepException
{
String realtablename=space.environmentSubstitute(tablenamefieldname);
if (!Const.isEmpty(realtablename))
{
ValueMetaInterface v = new ValueMeta(realtablename, ValueMeta.TYPE_STRING);
v.setLength(500);
v.setPrecision(-1);
v.setOrigin(name);
r.addValueMeta(v);
}
String realObjectType=space.environmentSubstitute(objecttypefieldname);
if (!Const.isEmpty(realObjectType))
{
ValueMetaInterface v = new ValueMeta(realObjectType, ValueMeta.TYPE_STRING);
v.setLength(500);
v.setPrecision(-1);
v.setOrigin(name);
r.addValueMeta(v);
}
String sysobject=space.environmentSubstitute(issystemobjectfieldname);
if (!Const.isEmpty(sysobject))
{
ValueMetaInterface v = new ValueMeta(sysobject, ValueMeta.TYPE_BOOLEAN);
v.setOrigin(name);
r.addValueMeta(v);
}
String realSQLCreation=space.environmentSubstitute(sqlcreationfieldname);
if (!Const.isEmpty(realSQLCreation))
{
ValueMetaInterface v = new ValueMeta(realSQLCreation, ValueMeta.TYPE_STRING);
v.setLength(500);
v.setPrecision(-1);
v.setOrigin(name);
r.addValueMeta(v);
}
}
public String getXML()
{
StringBuffer retval = new StringBuffer();
retval.append(" " + XMLHandler.addTagValue("connection", database == null ? "" : database.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
retval.append(" " + XMLHandler.addTagValue("schemaname", schemaname));
retval.append(" " + XMLHandler.addTagValue("tablenamefieldname", tablenamefieldname)); //$NON-NLS-1$ //$NON-NLS-2$
retval.append(" " + XMLHandler.addTagValue("objecttypefieldname", objecttypefieldname));
retval.append(" " + XMLHandler.addTagValue("issystemobjectfieldname", issystemobjectfieldname));
retval.append(" " + XMLHandler.addTagValue("sqlcreationfieldname", sqlcreationfieldname));
retval.append(" " + XMLHandler.addTagValue("includeCatalog", includeCatalog));
retval.append(" " + XMLHandler.addTagValue("includeSchema", includeSchema));
retval.append(" " + XMLHandler.addTagValue("includeTable", includeTable));
retval.append(" " + XMLHandler.addTagValue("includeView", includeView));
retval.append(" " + XMLHandler.addTagValue("includeProcedure", includeProcedure));
retval.append(" " + XMLHandler.addTagValue("includeSynonym", includeSynonym));
retval.append(" " + XMLHandler.addTagValue("addSchemaInOutput", addSchemaInOutput));
retval.append(" " + XMLHandler.addTagValue("dynamicSchema", dynamicSchema));
retval.append(" " + XMLHandler.addTagValue("schenameNameField", schenameNameField));
return retval.toString();
}
private void readData(Node stepnode, List<? extends SharedObjectInterface> databases) throws KettleXMLException
{
try
{
String con = XMLHandler.getTagValue(stepnode, "connection"); //$NON-NLS-1$
database = DatabaseMeta.findDatabase(databases, con);
schemaname = XMLHandler.getTagValue(stepnode, "schemaname");
tablenamefieldname = XMLHandler.getTagValue(stepnode, "tablenamefieldname"); //$NON-NLS-1$
objecttypefieldname = XMLHandler.getTagValue(stepnode, "objecttypefieldname");
sqlcreationfieldname = XMLHandler.getTagValue(stepnode, "sqlcreationfieldname");
issystemobjectfieldname = XMLHandler.getTagValue(stepnode, "issystemobjectfieldname");
includeCatalog = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "includeCatalog"));
includeSchema = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "includeSchema"));
includeTable = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "includeTable"));
includeView = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "includeView"));
includeProcedure = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "includeProcedure"));
includeSynonym = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "includeSynonym"));
addSchemaInOutput = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "addSchemaInOutput"));
dynamicSchema = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "dynamicSchema"));
schenameNameField = XMLHandler.getTagValue(stepnode, "schenameNameField");
}
catch (Exception e)
{
throw new KettleXMLException(BaseMessages.getString(PKG, "GetTableNamesMeta.Exception.UnableToReadStepInfo"), e); //$NON-NLS-1$
}
}
public void readRep(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters)
throws KettleException {
try
{
database = rep.loadDatabaseMetaFromStepAttribute(id_step, "id_connection", databases);
schemaname = rep.getStepAttributeString(id_step, "schemaname");
tablenamefieldname = rep.getStepAttributeString(id_step, "tablenamefieldname"); //$NON-NLS-1$
objecttypefieldname = rep.getStepAttributeString(id_step, "objecttypefieldname");
sqlcreationfieldname = rep.getStepAttributeString(id_step, "sqlcreationfieldname");
issystemobjectfieldname = rep.getStepAttributeString(id_step, "issystemobjectfieldname");
includeCatalog = rep.getStepAttributeBoolean(id_step, "includeCatalog");
includeSchema = rep.getStepAttributeBoolean(id_step, "includeSchema");
includeTable = rep.getStepAttributeBoolean(id_step, "includeTable");
includeView = rep.getStepAttributeBoolean(id_step, "includeView");
includeProcedure = rep.getStepAttributeBoolean(id_step, "includeProcedure");
includeSynonym = rep.getStepAttributeBoolean(id_step, "includeSynonym");
addSchemaInOutput = rep.getStepAttributeBoolean(id_step, "addSchemaInOutput");
dynamicSchema = rep.getStepAttributeBoolean(id_step, "dynamicSchema");
schenameNameField = rep.getStepAttributeString(id_step, "schenameNameField");
}
catch (Exception e)
{
throw new KettleException(BaseMessages.getString(PKG, "GetTableNamesMeta.Exception.UnexpectedErrorReadingStepInfo"), e); //$NON-NLS-1$
}
}
public void saveRep(Repository rep, ObjectId id_transformation, ObjectId id_step)
throws KettleException
{
try
{
rep.saveDatabaseMetaStepAttribute(id_transformation, id_step, "id_connection", database);
rep.saveStepAttribute(id_transformation, id_step, "schemaname", schemaname);
rep.saveStepAttribute(id_transformation, id_step, "tablenamefieldname", tablenamefieldname); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "objecttypefieldname", objecttypefieldname);
rep.saveStepAttribute(id_transformation, id_step, "sqlcreationfieldname", sqlcreationfieldname);
rep.saveStepAttribute(id_transformation, id_step, "issystemobjectfieldname", issystemobjectfieldname);
// Also, save the step-database relationship!
if (database != null) rep.insertStepDatabase(id_transformation, id_step, database.getObjectId());
rep.saveStepAttribute(id_transformation, id_step, "includeCatalog", includeCatalog);
rep.saveStepAttribute(id_transformation, id_step, "includeSchema", includeSchema);
rep.saveStepAttribute(id_transformation, id_step, "includeTable", includeTable);
rep.saveStepAttribute(id_transformation, id_step, "includeView", includeView);
rep.saveStepAttribute(id_transformation, id_step, "includeProcedure", includeProcedure);
rep.saveStepAttribute(id_transformation, id_step, "includeSynonym", includeSynonym);
rep.saveStepAttribute(id_transformation, id_step, "addSchemaInOutput", addSchemaInOutput);
rep.saveStepAttribute(id_transformation, id_step, "dynamicSchema", dynamicSchema);
rep.saveStepAttribute(id_transformation, id_step, "schenameNameField", schenameNameField);
}
catch (Exception e)
{
throw new KettleException(BaseMessages.getString(PKG, "GetTableNamesMeta.Exception.UnableToSaveStepInfo") + id_step, e); //$NON-NLS-1$
}
}
public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta, RowMetaInterface prev, String input[], String output[], RowMetaInterface info)
{
CheckResult cr;
String error_message = ""; //$NON-NLS-1$
if (database == null)
{
error_message = BaseMessages.getString(PKG, "GetTableNamesMeta.CheckResult.InvalidConnection"); //$NON-NLS-1$
cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepMeta);
remarks.add(cr);
}
if (Const.isEmpty(tablenamefieldname))
{
error_message = BaseMessages.getString(PKG, "GetTableNamesMeta.CheckResult.TablenameFieldNameMissing"); //$NON-NLS-1$
cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepMeta);
remarks.add(cr);
}
else
{
error_message = BaseMessages.getString(PKG, "GetTableNamesMeta.CheckResult.TablenameFieldNameOK"); //$NON-NLS-1$
cr = new CheckResult(CheckResult.TYPE_RESULT_OK, error_message, stepMeta);
remarks.add(cr);
}
// See if we have input streams leading to this step!
if (input.length > 0 && !isDynamicSchema())
cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(PKG, "GetTableNamesMeta.CheckResult.NoInpuReceived"), stepMeta); //$NON-NLS-1$
else
cr = new CheckResult(CheckResult.TYPE_RESULT_OK, BaseMessages.getString(PKG, "GetTableNamesMeta.CheckResult.ReceivingInfoFromOtherSteps"), stepMeta); //$NON-NLS-1$
remarks.add(cr);
}
public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans)
{
return new GetTableNames(stepMeta, stepDataInterface, cnr, transMeta, trans);
}
public StepDataInterface getStepData()
{
return new GetTableNamesData();
}
public DatabaseMeta[] getUsedDatabaseConnections()
{
if (database != null)
{
return new DatabaseMeta[] { database };
}
else
{
return super.getUsedDatabaseConnections();
}
}
public boolean supportsErrorHandling()
{
return true;
}
}
| |
package com.sudwood.advancedutilities.entity;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IProjectile;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.server.S2BPacketChangeGameState;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import com.sudwood.advancedutilities.items.AdvancedUtilitiesItems;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class EntityBullet extends Entity implements IProjectile
{
private int field_145791_d = -1;
private int field_145792_e = -1;
private int field_145789_f = -1;
private Block field_145790_g;
private int inData;
private boolean inGround;
/**
* 1 if the player can pick up the arrow
*/
public int canBePickedUp;
/**
* Seems to be some sort of timer for animating an arrow.
*/
public int arrowShake;
/**
* The owner of this arrow.
*/
public Entity shootingEntity;
private int ticksInGround;
private int ticksInAir;
private double damage = 2.0D;
/**
* The amount of knockback an arrow applies when it hits a mob.
*/
private int knockbackStrength;
private static final String __OBFID = "CL_00001715";
public EntityBullet(World par1World)
{
super(par1World);
this.renderDistanceWeight = 10.0D;
this.setSize(0.5F, 0.5F);
}
public EntityBullet(World par1World, double par2, double par4, double par6)
{
super(par1World);
this.renderDistanceWeight = 10.0D;
this.setSize(0.5F, 0.5F);
this.setPosition(par2, par4, par6);
this.yOffset = 0.0F;
}
public EntityBullet(World par1World, EntityLivingBase par2EntityLivingBase, EntityLivingBase par3EntityLivingBase, float par4, float par5)
{
super(par1World);
this.renderDistanceWeight = 10.0D;
this.shootingEntity = par2EntityLivingBase;
if (par2EntityLivingBase instanceof EntityPlayer)
{
this.canBePickedUp = 1;
}
this.posY = par2EntityLivingBase.posY + (double)par2EntityLivingBase.getEyeHeight() - 0.10000000149011612D;
double d0 = par3EntityLivingBase.posX - par2EntityLivingBase.posX;
double d1 = par3EntityLivingBase.boundingBox.minY + (double)(par3EntityLivingBase.height / 3.0F) - this.posY;
double d2 = par3EntityLivingBase.posZ - par2EntityLivingBase.posZ;
double d3 = (double)MathHelper.sqrt_double(d0 * d0 + d2 * d2);
if (d3 >= 1.0E-7D)
{
float f2 = (float)(Math.atan2(d2, d0) * 180.0D / Math.PI) - 90.0F;
float f3 = (float)(-(Math.atan2(d1, d3) * 180.0D / Math.PI));
double d4 = d0 / d3;
double d5 = d2 / d3;
this.setLocationAndAngles(par2EntityLivingBase.posX + d4, this.posY, par2EntityLivingBase.posZ + d5, f2, f3);
this.yOffset = 0.0F;
float f4 = (float)d3 * 0.2F;
this.setThrowableHeading(d0, d1 + (double)f4, d2, par4, par5);
}
}
public EntityBullet(World par1World, EntityLivingBase par2EntityLivingBase, float par3)
{
super(par1World);
this.renderDistanceWeight = 10.0D;
this.shootingEntity = par2EntityLivingBase;
if (par2EntityLivingBase instanceof EntityPlayer)
{
this.canBePickedUp = 1;
}
this.setSize(0.5F, 0.5F);
this.setLocationAndAngles(par2EntityLivingBase.posX, par2EntityLivingBase.posY + (double)par2EntityLivingBase.getEyeHeight(), par2EntityLivingBase.posZ, par2EntityLivingBase.rotationYaw, par2EntityLivingBase.rotationPitch);
this.posX -= (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F);
// this.posY -= 0.10000000149011612D;
this.posZ -= (double)(MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F);
this.setPosition(this.posX, this.posY, this.posZ);
this.yOffset = 0.0F;
this.motionX = (double)(-MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
this.motionZ = (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
this.motionY = (double)(-MathHelper.sin(this.rotationPitch / 180.0F * (float)Math.PI));
this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, par3 * 1.5F, 1.0F);
}
protected void entityInit()
{
this.dataWatcher.addObject(16, Byte.valueOf((byte)0));
}
/**
* Similar to setArrowHeading, it's point the throwable entity to a x, y, z direction.
*/
public void setThrowableHeading(double par1, double par3, double par5, float par7, float par8)
{
float f2 = MathHelper.sqrt_double(par1 * par1 + par3 * par3 + par5 * par5);
par1 /= (double)f2;
par3 /= (double)f2;
par5 /= (double)f2;
par1 += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D * (double)par8;
par3 += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D * (double)par8;
par5 += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D * (double)par8;
par1 *= (double)par7;
par3 *= (double)par7;
par5 *= (double)par7;
this.motionX = par1;
this.motionY = par3;
this.motionZ = par5;
float f3 = MathHelper.sqrt_double(par1 * par1 + par5 * par5);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(par1, par5) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(par3, (double)f3) * 180.0D / Math.PI);
this.ticksInGround = 0;
}
/**
* Sets the position and rotation. Only difference from the other one is no bounding on the rotation. Args: posX,
* posY, posZ, yaw, pitch
*/
@SideOnly(Side.CLIENT)
public void setPositionAndRotation2(double par1, double par3, double par5, float par7, float par8, int par9)
{
this.setPosition(par1, par3, par5);
this.setRotation(par7, par8);
}
/**
* Sets the velocity to the args. Args: x, y, z
*/
@SideOnly(Side.CLIENT)
public void setVelocity(double par1, double par3, double par5)
{
this.motionX = par1;
this.motionY = par3;
this.motionZ = par5;
if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(par1 * par1 + par5 * par5);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(par1, par5) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(par3, (double)f) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch;
this.prevRotationYaw = this.rotationYaw;
this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch);
this.ticksInGround = 0;
}
}
/**
* Called to update the entity's position/logic.
*/
public void onUpdate()
{
super.onUpdate();
if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F)
{
float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(this.motionY, (double)f) * 180.0D / Math.PI);
}
Block block = this.worldObj.getBlock(this.field_145791_d, this.field_145792_e, this.field_145789_f);
if (block.getMaterial() != Material.air)
{
block.setBlockBoundsBasedOnState(this.worldObj, this.field_145791_d, this.field_145792_e, this.field_145789_f);
AxisAlignedBB axisalignedbb = block.getCollisionBoundingBoxFromPool(this.worldObj, this.field_145791_d, this.field_145792_e, this.field_145789_f);
if (axisalignedbb != null && axisalignedbb.isVecInside(Vec3.createVectorHelper(this.posX, this.posY, this.posZ)))
{
this.inGround = true;
}
}
if (this.arrowShake > 0)
{
--this.arrowShake;
}
if (this.inGround)
{
int j = this.worldObj.getBlockMetadata(this.field_145791_d, this.field_145792_e, this.field_145789_f);
if (block == this.field_145790_g && j == this.inData)
{
++this.ticksInGround;
if (this.ticksInGround == 1200)
{
this.setDead();
}
}
else
{
this.inGround = false;
this.motionX *= (double)(this.rand.nextFloat() * 0.2F);
this.motionY *= (double)(this.rand.nextFloat() * 0.2F);
this.motionZ *= (double)(this.rand.nextFloat() * 0.2F);
this.ticksInGround = 0;
this.ticksInAir = 0;
}
}
else
{
++this.ticksInAir;
Vec3 vec31 = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
Vec3 vec3 = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
MovingObjectPosition movingobjectposition = this.worldObj.func_147447_a(vec31, vec3, false, true, false);
vec31 = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
vec3 = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
if (movingobjectposition != null)
{
vec3 = Vec3.createVectorHelper(movingobjectposition.hitVec.xCoord, movingobjectposition.hitVec.yCoord, movingobjectposition.hitVec.zCoord);
}
Entity entity = null;
List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
double d0 = 0.0D;
int i;
float f1;
for (i = 0; i < list.size(); ++i)
{
Entity entity1 = (Entity)list.get(i);
if (entity1.canBeCollidedWith() && (entity1 != this.shootingEntity || this.ticksInAir >= 5))
{
f1 = 0.3F;
AxisAlignedBB axisalignedbb1 = entity1.boundingBox.expand((double)f1, (double)f1, (double)f1);
MovingObjectPosition movingobjectposition1 = axisalignedbb1.calculateIntercept(vec31, vec3);
if (movingobjectposition1 != null)
{
double d1 = vec31.distanceTo(movingobjectposition1.hitVec);
if (d1 < d0 || d0 == 0.0D)
{
entity = entity1;
d0 = d1;
}
}
}
}
if (entity != null)
{
movingobjectposition = new MovingObjectPosition(entity);
}
if (movingobjectposition != null && movingobjectposition.entityHit != null && movingobjectposition.entityHit instanceof EntityPlayer)
{
EntityPlayer entityplayer = (EntityPlayer)movingobjectposition.entityHit;
if (entityplayer.capabilities.disableDamage || this.shootingEntity instanceof EntityPlayer && !((EntityPlayer)this.shootingEntity).canAttackPlayer(entityplayer))
{
movingobjectposition = null;
}
}
float f2;
float f4;
if (movingobjectposition != null)
{
if (movingobjectposition.entityHit != null)
{
f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ);
int k = (int) this.damage;
if (this.getIsCritical())
{
k += this.rand.nextInt(k / 2 + 2);
}
DamageSource damagesource = null;
if (this.shootingEntity == null)
{
damagesource = DamageSource.causeThrownDamage(this, this);
}
else
{
damagesource = DamageSource.causeThrownDamage(this, this.shootingEntity);
}
if (this.isBurning() && !(movingobjectposition.entityHit instanceof EntityEnderman))
{
movingobjectposition.entityHit.setFire(5);
}
if (movingobjectposition.entityHit.attackEntityFrom(damagesource, (float)k))
{
if (movingobjectposition.entityHit instanceof EntityLivingBase)
{
EntityLivingBase entitylivingbase = (EntityLivingBase)movingobjectposition.entityHit;
if (!this.worldObj.isRemote)
{
entitylivingbase.setArrowCountInEntity(entitylivingbase.getArrowCountInEntity() + 1);
}
if (this.knockbackStrength > 0)
{
f4 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
if (f4 > 0.0F)
{
movingobjectposition.entityHit.addVelocity(this.motionX * (double)this.knockbackStrength * 0.6000000238418579D / (double)f4, 0.1D, this.motionZ * (double)this.knockbackStrength * 0.6000000238418579D / (double)f4);
}
}
if (this.shootingEntity != null && this.shootingEntity instanceof EntityLivingBase)
{
EnchantmentHelper.func_151384_a(entitylivingbase, this.shootingEntity);
EnchantmentHelper.func_151385_b((EntityLivingBase)this.shootingEntity, entitylivingbase);
}
if (this.shootingEntity != null && movingobjectposition.entityHit != this.shootingEntity && movingobjectposition.entityHit instanceof EntityPlayer && this.shootingEntity instanceof EntityPlayerMP)
{
((EntityPlayerMP)this.shootingEntity).playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(6, 0.0F));
}
}
// this.playSound("random.bowhit", 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
if (!(movingobjectposition.entityHit instanceof EntityEnderman))
{
// this.setDead();
}
}
else
{
this.motionX *= -0.10000000149011612D;
this.motionY *= -0.10000000149011612D;
this.motionZ *= -0.10000000149011612D;
this.rotationYaw += 180.0F;
this.prevRotationYaw += 180.0F;
this.ticksInAir = 0;
}
}
else
{
this.field_145791_d = movingobjectposition.blockX;
this.field_145792_e = movingobjectposition.blockY;
this.field_145789_f = movingobjectposition.blockZ;
this.field_145790_g = block;
this.inData = this.worldObj.getBlockMetadata(this.field_145791_d, this.field_145792_e, this.field_145789_f);
this.motionX = (double)((float)(movingobjectposition.hitVec.xCoord - this.posX));
this.motionY = (double)((float)(movingobjectposition.hitVec.yCoord - this.posY));
this.motionZ = (double)((float)(movingobjectposition.hitVec.zCoord - this.posZ));
f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ);
this.posX -= this.motionX / (double)f2 * 0.05000000074505806D;
// this.posY -= this.motionY / (double)f2 * 0.05000000074505806D;
this.posZ -= this.motionZ / (double)f2 * 0.05000000074505806D;
// this.playSound("random.bowhit", 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
this.inGround = true;
this.arrowShake = 7;
this.setIsCritical(false);
if (this.field_145790_g.getMaterial() != Material.air)
{
this.field_145790_g.onEntityCollidedWithBlock(this.worldObj, this.field_145791_d, this.field_145792_e, this.field_145789_f, this);
}
}
}
if (this.getIsCritical())
{
for (i = 0; i < 4; ++i)
{
this.worldObj.spawnParticle("crit", this.posX + this.motionX * (double)i / 4.0D, this.posY + this.motionY * (double)i / 4.0D, this.posZ + this.motionZ * (double)i / 4.0D, -this.motionX, -this.motionY + 0.2D, -this.motionZ);
}
}
this.posX += this.motionX;
// this.posY += this.motionY;
this.posZ += this.motionZ;
f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
for (this.rotationPitch = (float)(Math.atan2(this.motionY, (double)f2) * 180.0D / Math.PI); this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
{
}
while (this.rotationPitch - this.prevRotationPitch >= 180.0F)
{
this.prevRotationPitch += 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw < -180.0F)
{
this.prevRotationYaw -= 360.0F;
}
while (this.rotationYaw - this.prevRotationYaw >= 180.0F)
{
this.prevRotationYaw += 360.0F;
}
this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
float f3 = 0.99F;
f1 = 0.05F;
if (this.isInWater())
{
for (int l = 0; l < 4; ++l)
{
f4 = 0.25F;
this.worldObj.spawnParticle("bubble", this.posX - this.motionX * (double)f4, this.posY - this.motionY * (double)f4, this.posZ - this.motionZ * (double)f4, this.motionX, this.motionY, this.motionZ);
}
f3 = 0.8F;
}
if (this.isWet())
{
this.extinguish();
}
this.motionX *= (double)f3;
this.motionY *= (double)f3;
this.motionZ *= (double)f3;
this.motionY -= (double)f1;
this.setPosition(this.posX, this.posY, this.posZ);
this.func_145775_I();
}
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)
{
par1NBTTagCompound.setShort("xTile", (short)this.field_145791_d);
par1NBTTagCompound.setShort("yTile", (short)this.field_145792_e);
par1NBTTagCompound.setShort("zTile", (short)this.field_145789_f);
par1NBTTagCompound.setShort("life", (short)this.ticksInGround);
par1NBTTagCompound.setByte("inTile", (byte)Block.getIdFromBlock(this.field_145790_g));
par1NBTTagCompound.setByte("inData", (byte)this.inData);
par1NBTTagCompound.setByte("shake", (byte)this.arrowShake);
par1NBTTagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0));
par1NBTTagCompound.setByte("pickup", (byte)this.canBePickedUp);
par1NBTTagCompound.setDouble("damage", this.damage);
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)
{
this.field_145791_d = par1NBTTagCompound.getShort("xTile");
this.field_145792_e = par1NBTTagCompound.getShort("yTile");
this.field_145789_f = par1NBTTagCompound.getShort("zTile");
this.ticksInGround = par1NBTTagCompound.getShort("life");
this.field_145790_g = Block.getBlockById(par1NBTTagCompound.getByte("inTile") & 255);
this.inData = par1NBTTagCompound.getByte("inData") & 255;
this.arrowShake = par1NBTTagCompound.getByte("shake") & 255;
this.inGround = par1NBTTagCompound.getByte("inGround") == 1;
if (par1NBTTagCompound.hasKey("damage", 99))
{
this.damage = par1NBTTagCompound.getDouble("damage");
}
if (par1NBTTagCompound.hasKey("pickup", 99))
{
this.canBePickedUp = par1NBTTagCompound.getByte("pickup");
}
else if (par1NBTTagCompound.hasKey("player", 99))
{
this.canBePickedUp = par1NBTTagCompound.getBoolean("player") ? 1 : 0;
}
}
/**
* Called by a player entity when they collide with an entity
*/
public void onCollideWithPlayer(EntityPlayer par1EntityPlayer)
{
if (!this.worldObj.isRemote && this.inGround && this.arrowShake <= 0)
{
boolean flag = this.canBePickedUp == 1 || this.canBePickedUp == 2 && par1EntityPlayer.capabilities.isCreativeMode;
if (this.canBePickedUp == 1 && !par1EntityPlayer.inventory.addItemStackToInventory(new ItemStack(AdvancedUtilitiesItems.bronzeBullet, 1)))
{
flag = false;
}
if (flag)
{
// this.playSound("random.pop", 0.2F, ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F);
par1EntityPlayer.onItemPickup(this, 1);
this.setDead();
}
}
}
/**
* returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to
* prevent them from trampling crops
*/
protected boolean canTriggerWalking()
{
return false;
}
@SideOnly(Side.CLIENT)
public float getShadowSize()
{
return 0.0F;
}
public void setDamage(double par1)
{
this.damage = par1;
}
public double getDamage()
{
return this.damage;
}
/**
* Sets the amount of knockback the arrow applies when it hits a mob.
*/
public void setKnockbackStrength(int par1)
{
this.knockbackStrength = par1;
}
/**
* If returns false, the item will not inflict any damage against entities.
*/
public boolean canAttackWithItem()
{
return false;
}
/**
* Whether the arrow has a stream of critical hit particles flying behind it.
*/
public void setIsCritical(boolean par1)
{
byte b0 = this.dataWatcher.getWatchableObjectByte(16);
if (par1)
{
this.dataWatcher.updateObject(16, Byte.valueOf((byte)(b0 | 1)));
}
else
{
this.dataWatcher.updateObject(16, Byte.valueOf((byte)(b0 & -2)));
}
}
/**
* Whether the arrow has a stream of critical hit particles flying behind it.
*/
public boolean getIsCritical()
{
byte b0 = this.dataWatcher.getWatchableObjectByte(16);
return (b0 & 1) != 0;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.s3native;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystemContractBaseTest;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.s3native.NativeS3FileSystem.NativeS3FsInputStream;
public abstract class NativeS3FileSystemContractBaseTest
extends FileSystemContractBaseTest {
private NativeFileSystemStore store;
abstract NativeFileSystemStore getNativeFileSystemStore() throws IOException;
@Override
protected void setUp() throws Exception {
Configuration conf = new Configuration();
store = getNativeFileSystemStore();
fs = new NativeS3FileSystem(store);
fs.initialize(URI.create(conf.get("test.fs.s3n.name")), conf);
}
@Override
protected void tearDown() throws Exception {
store.purge("test");
super.tearDown();
}
public void testListStatusForRoot() throws Exception {
FileStatus[] paths = fs.listStatus(path("/"));
assertEquals(0, paths.length);
Path testDir = path("/test");
assertTrue(fs.mkdirs(testDir));
paths = fs.listStatus(path("/"));
assertEquals(1, paths.length);
assertEquals(path("/test"), paths[0].getPath());
}
public void testNoTrailingBackslashOnBucket() throws Exception {
assertTrue(fs.getFileStatus(new Path(fs.getUri().toString())).isDirectory());
}
private void createTestFiles(String base) throws IOException {
store.storeEmptyFile(base + "/file1");
store.storeEmptyFile(base + "/dir/file2");
store.storeEmptyFile(base + "/dir/file3");
}
public void testDirWithDifferentMarkersWorks() throws Exception {
for (int i = 0; i < 3; i++) {
String base = "test/hadoop" + i;
Path path = path("/" + base);
createTestFiles(base);
if (i == 0 ) {
//do nothing, we are testing correctness with no markers
}
else if (i == 1) {
// test for _$folder$ marker
store.storeEmptyFile(base + "_$folder$");
store.storeEmptyFile(base + "/dir_$folder$");
}
else if (i == 2) {
// test the end slash file marker
store.storeEmptyFile(base + "/");
store.storeEmptyFile(base + "/dir/");
}
else if (i == 3) {
// test both markers
store.storeEmptyFile(base + "_$folder$");
store.storeEmptyFile(base + "/dir_$folder$");
store.storeEmptyFile(base + "/");
store.storeEmptyFile(base + "/dir/");
}
assertTrue(fs.getFileStatus(path).isDirectory());
assertEquals(2, fs.listStatus(path).length);
}
}
public void testDeleteWithNoMarker() throws Exception {
String base = "test/hadoop";
Path path = path("/" + base);
createTestFiles(base);
fs.delete(path, true);
path = path("/test");
assertTrue(fs.getFileStatus(path).isDirectory());
assertEquals(0, fs.listStatus(path).length);
}
public void testRenameWithNoMarker() throws Exception {
String base = "test/hadoop";
Path dest = path("/test/hadoop2");
createTestFiles(base);
fs.rename(path("/" + base), dest);
Path path = path("/test");
assertTrue(fs.getFileStatus(path).isDirectory());
assertEquals(1, fs.listStatus(path).length);
assertTrue(fs.getFileStatus(dest).isDirectory());
assertEquals(2, fs.listStatus(dest).length);
}
public void testEmptyFile() throws Exception {
store.storeEmptyFile("test/hadoop/file1");
fs.open(path("/test/hadoop/file1")).close();
}
public void testBlockSize() throws Exception {
Path file = path("/test/hadoop/file");
createFile(file);
assertEquals("Default block size", fs.getDefaultBlockSize(file),
fs.getFileStatus(file).getBlockSize());
// Block size is determined at read time
long newBlockSize = fs.getDefaultBlockSize(file) * 2;
fs.getConf().setLong("fs.s3n.block.size", newBlockSize);
assertEquals("Double default block size", newBlockSize,
fs.getFileStatus(file).getBlockSize());
}
public void testRetryOnIoException() throws Exception {
class TestInputStream extends InputStream {
boolean shouldThrow = false;
int throwCount = 0;
int pos = 0;
byte[] bytes;
public TestInputStream() {
bytes = new byte[256];
for (int i = 0; i < 256; i++) {
bytes[i] = (byte)i;
}
}
@Override
public int read() throws IOException {
shouldThrow = !shouldThrow;
if (shouldThrow) {
throwCount++;
throw new IOException();
}
return pos++;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
shouldThrow = !shouldThrow;
if (shouldThrow) {
throwCount++;
throw new IOException();
}
int sizeToRead = Math.min(len, 256 - pos);
for (int i = 0; i < sizeToRead; i++) {
b[i] = bytes[pos + i];
}
pos += sizeToRead;
return sizeToRead;
}
}
final InputStream is = new TestInputStream();
class MockNativeFileSystemStore extends Jets3tNativeFileSystemStore {
@Override
public InputStream retrieve(String key, long byteRangeStart) throws IOException {
return is;
}
}
NativeS3FsInputStream stream = new NativeS3FsInputStream(new MockNativeFileSystemStore(), null, is, "");
// Test reading methods.
byte[] result = new byte[256];
for (int i = 0; i < 128; i++) {
result[i] = (byte)stream.read();
}
for (int i = 128; i < 256; i += 8) {
byte[] temp = new byte[8];
int read = stream.read(temp, 0, 8);
assertEquals(8, read);
System.arraycopy(temp, 0, result, i, 8);
}
// Assert correct
for (int i = 0; i < 256; i++) {
assertEquals((byte)i, result[i]);
}
// Test to make sure the throw path was exercised.
// 144 = 128 + (128 / 8)
assertEquals(144, ((TestInputStream)is).throwCount);
}
}
| |
package barqsoft.footballscores.service;
import android.app.IntentService;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.Vector;
import barqsoft.footballscores.DatabaseContract;
import barqsoft.footballscores.R;
/**
* Created by yehya khaled on 3/2/2015.
*/
public class myFetchService extends IntentService
{
public static final String LOG_TAG = "myFetchService";
public myFetchService()
{
super("myFetchService");
}
@Override
protected void onHandleIntent(Intent intent)
{
getData("n2");
getData("p2");
return;
}
private void getData (String timeFrame)
{
//Creating fetch URL
final String BASE_URL = "http://api.football-data.org/alpha/fixtures"; //Base URL
final String QUERY_TIME_FRAME = "timeFrame"; //Time Frame parameter to determine days
//final String QUERY_MATCH_DAY = "matchday";
Uri fetch_build = Uri.parse(BASE_URL).buildUpon().
appendQueryParameter(QUERY_TIME_FRAME, timeFrame).build();
//Log.v(LOG_TAG, "The url we are looking at is: "+fetch_build.toString()); //log spam
HttpURLConnection m_connection = null;
BufferedReader reader = null;
String JSON_data = null;
//Opening Connection
try {
URL fetch = new URL(fetch_build.toString());
m_connection = (HttpURLConnection) fetch.openConnection();
m_connection.setRequestMethod("GET");
m_connection.addRequestProperty("X-Auth-Token",getString(R.string.api_key));
m_connection.connect();
// Read the input stream into a String
InputStream inputStream = m_connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return;
}
JSON_data = buffer.toString();
}
catch (Exception e)
{
Log.e(LOG_TAG,"Exception here" + e.getMessage());
}
finally {
if(m_connection != null)
{
m_connection.disconnect();
}
if (reader != null)
{
try {
reader.close();
}
catch (IOException e)
{
Log.e(LOG_TAG,"Error Closing Stream");
}
}
}
try {
if (JSON_data != null) {
//This bit is to check if the data contains any matches. If not, we call processJson on the dummy data
JSONArray matches = new JSONObject(JSON_data).getJSONArray("fixtures");
if (matches.length() == 0) {
//if there is no data, call the function on dummy data
//this is expected behavior during the off season.
processJSONdata(getString(R.string.dummy_data), getApplicationContext(), false);
return;
}
processJSONdata(JSON_data, getApplicationContext(), true);
} else {
//Could not Connect
Log.d(LOG_TAG, "Could not connect to server.");
}
}
catch(Exception e)
{
Log.e(LOG_TAG,e.getMessage());
}
}
private void processJSONdata (String JSONdata,Context mContext, boolean isReal)
{
//JSON data
// This set of league codes is for the 2015/2016 season. In fall of 2016, they will need to
// be updated. Feel free to use the codes
final String BUNDESLIGA1 = "394";
final String BUNDESLIGA2 = "395";
final String LIGUE1 = "396";
final String LIGUE2 = "397";
final String PREMIER_LEAGUE = "398";
final String PRIMERA_DIVISION = "399";
final String SEGUNDA_DIVISION = "400";
final String SERIE_A = "401";
final String PRIMERA_LIGA = "402";
final String Bundesliga3 = "403";
final String EREDIVISIE = "404";
final String SEASON_LINK = "http://api.football-data.org/alpha/soccerseasons/";
final String MATCH_LINK = "http://api.football-data.org/alpha/fixtures/";
final String FIXTURES = "fixtures";
final String LINKS = "_links";
final String SOCCER_SEASON = "soccerseason";
final String SELF = "self";
final String MATCH_DATE = "date";
final String HOME_TEAM = "homeTeamName";
final String AWAY_TEAM = "awayTeamName";
final String RESULT = "result";
final String HOME_GOALS = "goalsHomeTeam";
final String AWAY_GOALS = "goalsAwayTeam";
final String MATCH_DAY = "matchday";
//Match data
String League = null;
String mDate = null;
String mTime = null;
String Home = null;
String Away = null;
String Home_goals = null;
String Away_goals = null;
String match_id = null;
String match_day = null;
try {
JSONArray matches = new JSONObject(JSONdata).getJSONArray(FIXTURES);
//ContentValues to be inserted
Vector<ContentValues> values = new Vector <ContentValues> (matches.length());
for(int i = 0;i < matches.length();i++)
{
JSONObject match_data = matches.getJSONObject(i);
League = match_data.getJSONObject(LINKS).getJSONObject(SOCCER_SEASON).
getString("href");
League = League.replace(SEASON_LINK,"");
//This if statement controls which leagues we're interested in the data from.
//add leagues here in order to have them be added to the DB.
// If you are finding no data in the app, check that this contains all the leagues.
// If it doesn't, that can cause an empty DB, bypassing the dummy data routine.
if( League.equals(PREMIER_LEAGUE) ||
League.equals(SERIE_A) ||
League.equals(BUNDESLIGA1) ||
League.equals(BUNDESLIGA2) ||
League.equals(PRIMERA_DIVISION) )
{
match_id = match_data.getJSONObject(LINKS).getJSONObject(SELF).
getString("href");
match_id = match_id.replace(MATCH_LINK, "");
if(!isReal){
//This if statement changes the match ID of the dummy data so that it all goes into the database
match_id=match_id+Integer.toString(i);
}
mDate = match_data.getString(MATCH_DATE);
mTime = mDate.substring(mDate.indexOf("T") + 1, mDate.indexOf("Z"));
mDate = mDate.substring(0,mDate.indexOf("T"));
SimpleDateFormat match_date = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
match_date.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date parseddate = match_date.parse(mDate+mTime);
SimpleDateFormat new_date = new SimpleDateFormat("yyyy-MM-dd:HH:mm");
new_date.setTimeZone(TimeZone.getDefault());
mDate = new_date.format(parseddate);
mTime = mDate.substring(mDate.indexOf(":") + 1);
mDate = mDate.substring(0,mDate.indexOf(":"));
if(!isReal){
//This if statement changes the dummy data's date to match our current date range.
Date fragmentdate = new Date(System.currentTimeMillis()+((i-2)*86400000));
SimpleDateFormat mformat = new SimpleDateFormat("yyyy-MM-dd");
mDate=mformat.format(fragmentdate);
}
}
catch (Exception e)
{
Log.d(LOG_TAG, "error here!");
Log.e(LOG_TAG,e.getMessage());
}
Home = match_data.getString(HOME_TEAM);
Away = match_data.getString(AWAY_TEAM);
Home_goals = match_data.getJSONObject(RESULT).getString(HOME_GOALS);
Away_goals = match_data.getJSONObject(RESULT).getString(AWAY_GOALS);
match_day = match_data.getString(MATCH_DAY);
ContentValues match_values = new ContentValues();
match_values.put(DatabaseContract.scores_table.MATCH_ID,match_id);
match_values.put(DatabaseContract.scores_table.DATE_COL,mDate);
match_values.put(DatabaseContract.scores_table.TIME_COL,mTime);
match_values.put(DatabaseContract.scores_table.HOME_COL,Home);
match_values.put(DatabaseContract.scores_table.AWAY_COL,Away);
match_values.put(DatabaseContract.scores_table.HOME_GOALS_COL,Home_goals);
match_values.put(DatabaseContract.scores_table.AWAY_GOALS_COL,Away_goals);
match_values.put(DatabaseContract.scores_table.LEAGUE_COL,League);
match_values.put(DatabaseContract.scores_table.MATCH_DAY,match_day);
//log spam
//Log.v(LOG_TAG,match_id);
//Log.v(LOG_TAG,mDate);
//Log.v(LOG_TAG,mTime);
//Log.v(LOG_TAG,Home);
//Log.v(LOG_TAG,Away);
//Log.v(LOG_TAG,Home_goals);
//Log.v(LOG_TAG,Away_goals);
values.add(match_values);
}
}
int inserted_data = 0;
ContentValues[] insert_data = new ContentValues[values.size()];
values.toArray(insert_data);
inserted_data = mContext.getContentResolver().bulkInsert(
DatabaseContract.BASE_CONTENT_URI,insert_data);
//Log.v(LOG_TAG,"Succesfully Inserted : " + String.valueOf(inserted_data));
}
catch (JSONException e)
{
Log.e(LOG_TAG,e.getMessage());
}
}
}
| |
/*
* Copyright (C) 2017 Square, 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.squareup.moshi;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.annotation.Nullable;
/**
* This class reads a JSON document by traversing a Java object comprising maps, lists, and JSON
* primitives. It does depth-first traversal keeping a stack starting with the root object. During
* traversal a stack tracks the current position in the document:
*
* <ul>
* <li>The next element to act upon is on the top of the stack.
* <li>When the top of the stack is a {@link List}, calling {@link #beginArray()} replaces the
* list with a {@link ListIterator}. The first element of the iterator is pushed on top of the
* iterator.
* <li>Similarly, when the top of the stack is a {@link Map}, calling {@link #beginObject()}
* replaces the map with an {@link Iterator} of its entries. The first element of the iterator
* is pushed on top of the iterator.
* <li>When the top of the stack is a {@link Map.Entry}, calling {@link #nextName()} returns the
* entry's key and replaces the entry with its value on the stack.
* <li>When an element is consumed it is popped. If the new top of the stack has a non-exhausted
* iterator, the next element of that iterator is pushed.
* <li>If the top of the stack is an exhausted iterator, calling {@link #endArray} or {@link
* #endObject} will pop it.
* </ul>
*/
final class JsonValueReader extends JsonReader {
/** Sentinel object pushed on {@link #stack} when the reader is closed. */
private static final Object JSON_READER_CLOSED = new Object();
private final Object[] stack = new Object[32];
JsonValueReader(Object root) {
scopes[stackSize] = JsonScope.NONEMPTY_DOCUMENT;
stack[stackSize++] = root;
}
@Override public void beginArray() throws IOException {
List<?> peeked = require(List.class, Token.BEGIN_ARRAY);
ListIterator<?> iterator = peeked.listIterator();
stack[stackSize - 1] = iterator;
scopes[stackSize - 1] = JsonScope.EMPTY_ARRAY;
pathIndices[stackSize - 1] = 0;
// If the iterator isn't empty push its first value onto the stack.
if (iterator.hasNext()) {
push(iterator.next());
}
}
@Override public void endArray() throws IOException {
ListIterator<?> peeked = require(ListIterator.class, Token.END_ARRAY);
if (peeked.hasNext()) {
throw typeMismatch(peeked, Token.END_ARRAY);
}
remove();
}
@Override public void beginObject() throws IOException {
Map<?, ?> peeked = require(Map.class, Token.BEGIN_OBJECT);
Iterator<?> iterator = peeked.entrySet().iterator();
stack[stackSize - 1] = iterator;
scopes[stackSize - 1] = JsonScope.EMPTY_OBJECT;
// If the iterator isn't empty push its first value onto the stack.
if (iterator.hasNext()) {
push(iterator.next());
}
}
@Override public void endObject() throws IOException {
Iterator<?> peeked = require(Iterator.class, Token.END_OBJECT);
if (peeked instanceof ListIterator || peeked.hasNext()) {
throw typeMismatch(peeked, Token.END_OBJECT);
}
pathNames[stackSize - 1] = null;
remove();
}
@Override public boolean hasNext() throws IOException {
// TODO(jwilson): this is consistent with BufferedSourceJsonReader but it doesn't make sense.
if (stackSize == 0) return true;
Object peeked = stack[stackSize - 1];
return !(peeked instanceof Iterator) || ((Iterator) peeked).hasNext();
}
@Override public Token peek() throws IOException {
if (stackSize == 0) return Token.END_DOCUMENT;
// If the top of the stack is an iterator, take its first element and push it on the stack.
Object peeked = stack[stackSize - 1];
if (peeked instanceof ListIterator) return Token.END_ARRAY;
if (peeked instanceof Iterator) return Token.END_OBJECT;
if (peeked instanceof List) return Token.BEGIN_ARRAY;
if (peeked instanceof Map) return Token.BEGIN_OBJECT;
if (peeked instanceof Map.Entry) return Token.NAME;
if (peeked instanceof String) return Token.STRING;
if (peeked instanceof Boolean) return Token.BOOLEAN;
if (peeked instanceof Number) return Token.NUMBER;
if (peeked == null) return Token.NULL;
if (peeked == JSON_READER_CLOSED) throw new IllegalStateException("JsonReader is closed");
throw typeMismatch(peeked, "a JSON value");
}
@Override public String nextName() throws IOException {
Map.Entry<?, ?> peeked = require(Map.Entry.class, Token.NAME);
// Swap the Map.Entry for its value on the stack and return its key.
String result = stringKey(peeked);
stack[stackSize - 1] = peeked.getValue();
pathNames[stackSize - 2] = result;
return result;
}
@Override public int selectName(Options options) throws IOException {
Map.Entry<?, ?> peeked = require(Map.Entry.class, Token.NAME);
String name = stringKey(peeked);
for (int i = 0, length = options.strings.length; i < length; i++) {
// Swap the Map.Entry for its value on the stack and return its key.
if (options.strings[i].equals(name)) {
stack[stackSize - 1] = peeked.getValue();
pathNames[stackSize - 2] = name;
return i;
}
}
return -1;
}
@Override public String nextString() throws IOException {
String peeked = require(String.class, Token.STRING);
remove();
return peeked;
}
@Override public int selectString(Options options) throws IOException {
String peeked = require(String.class, Token.STRING);
for (int i = 0, length = options.strings.length; i < length; i++) {
if (options.strings[i].equals(peeked)) {
remove();
return i;
}
}
return -1;
}
@Override public boolean nextBoolean() throws IOException {
Boolean peeked = require(Boolean.class, Token.BOOLEAN);
remove();
return peeked;
}
@Override public @Nullable <T> T nextNull() throws IOException {
require(Void.class, Token.NULL);
remove();
return null;
}
@Override public double nextDouble() throws IOException {
Object peeked = require(Object.class, Token.NUMBER);
double result;
if (peeked instanceof Number) {
result = ((Number) peeked).doubleValue();
} else if (peeked instanceof String) {
try {
result = Double.parseDouble((String) peeked);
} catch (NumberFormatException e) {
throw typeMismatch(peeked, Token.NUMBER);
}
} else {
throw typeMismatch(peeked, Token.NUMBER);
}
if (!lenient && (Double.isNaN(result) || Double.isInfinite(result))) {
throw new JsonEncodingException("JSON forbids NaN and infinities: " + result
+ " at path " + getPath());
}
remove();
return result;
}
@Override public long nextLong() throws IOException {
Object peeked = require(Object.class, Token.NUMBER);
long result;
if (peeked instanceof Number) {
result = ((Number) peeked).longValue();
} else if (peeked instanceof String) {
try {
result = Long.parseLong((String) peeked);
} catch (NumberFormatException e) {
try {
BigDecimal asDecimal = new BigDecimal((String) peeked);
result = asDecimal.longValueExact();
} catch (NumberFormatException e2) {
throw typeMismatch(peeked, Token.NUMBER);
}
}
} else {
throw typeMismatch(peeked, Token.NUMBER);
}
remove();
return result;
}
@Override public int nextInt() throws IOException {
Object peeked = require(Object.class, Token.NUMBER);
int result;
if (peeked instanceof Number) {
result = ((Number) peeked).intValue();
} else if (peeked instanceof String) {
try {
result = Integer.parseInt((String) peeked);
} catch (NumberFormatException e) {
try {
BigDecimal asDecimal = new BigDecimal((String) peeked);
result = asDecimal.intValueExact();
} catch (NumberFormatException e2) {
throw typeMismatch(peeked, Token.NUMBER);
}
}
} else {
throw typeMismatch(peeked, Token.NUMBER);
}
remove();
return result;
}
@Override public void skipValue() throws IOException {
if (failOnUnknown) {
throw new JsonDataException("Cannot skip unexpected " + peek() + " at " + getPath());
}
// If this element is in an object clear out the key.
if (stackSize > 1) {
pathNames[stackSize - 2] = "null";
}
Object skipped = stackSize != 0 ? stack[stackSize - 1] : null;
if (skipped instanceof Map.Entry) {
// We're skipping a name. Promote the map entry's value.
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) stack[stackSize - 1];
stack[stackSize - 1] = entry.getValue();
} else if (stackSize > 0) {
// We're skipping a value.
remove();
}
}
@Override void promoteNameToValue() throws IOException {
if (hasNext()) {
String name = nextName();
push(name);
}
}
@Override public void close() throws IOException {
Arrays.fill(stack, 0, stackSize, null);
stack[0] = JSON_READER_CLOSED;
scopes[0] = JsonScope.CLOSED;
stackSize = 1;
}
private void push(Object newTop) {
if (stackSize == stack.length) {
throw new JsonDataException("Nesting too deep at " + getPath());
}
stack[stackSize++] = newTop;
}
/**
* Returns the top of the stack which is required to be a {@code type}. Throws if this reader is
* closed, or if the type isn't what was expected.
*/
private @Nullable <T> T require(Class<T> type, Token expected) throws IOException {
Object peeked = (stackSize != 0 ? stack[stackSize - 1] : null);
if (type.isInstance(peeked)) {
return type.cast(peeked);
}
if (peeked == null && expected == Token.NULL) {
return null;
}
if (peeked == JSON_READER_CLOSED) {
throw new IllegalStateException("JsonReader is closed");
}
throw typeMismatch(peeked, expected);
}
private String stringKey(Map.Entry<?, ?> entry) {
Object name = entry.getKey();
if (name instanceof String) return (String) name;
throw typeMismatch(name, Token.NAME);
}
/**
* Removes a value and prepares for the next. If we're iterating a map or list this advances the
* iterator.
*/
private void remove() {
stackSize--;
stack[stackSize] = null;
scopes[stackSize] = 0;
// If we're iterating an array or an object push its next element on to the stack.
if (stackSize > 0) {
pathIndices[stackSize - 1]++;
Object parent = stack[stackSize - 1];
if (parent instanceof Iterator && ((Iterator<?>) parent).hasNext()) {
push(((Iterator<?>) parent).next());
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.plugins.memory;
import static org.apache.jackrabbit.oak.api.Type.STRING;
import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Collection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.spi.state.AbstractNodeState;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.jetbrains.annotations.NotNull;
import org.junit.Assume;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class MemoryNodeBuilderTest {
private final NodeState base;
public MemoryNodeBuilderTest(NodeState base) {
this.base = base;
}
@Parameterized.Parameters
public static Collection<Object[]> fixtures() {
NodeBuilder builder = EMPTY_NODE.builder();
builder.setProperty("a", 1L);
builder.setProperty("b", 2L);
builder.setProperty("c", 3L);
builder.child("x").child("q");
builder.child("y");
builder.child("z");
NodeState base = builder.getNodeState();
return ImmutableList.of(
new Object[] { base },
new Object[] { ModifiedNodeState.squeeze(base) }
);
}
@Test
public void testConnectOnAddProperty() {
NodeBuilder root = base.builder();
NodeBuilder childA = root.child("x");
NodeBuilder childB = root.child("x");
assertFalse(childA.hasProperty("test"));
childB.setProperty("test", "foo");
assertTrue(childA.hasProperty("test"));
}
@Test
public void testConnectOnUpdateProperty() {
NodeBuilder root = base.builder();
NodeBuilder childA = root.child("x");
NodeBuilder childB = root.child("x");
childB.setProperty("test", "foo");
childA.setProperty("test", "bar");
assertEquals("bar", childA.getProperty("test").getValue(STRING));
assertEquals("bar", childB.getProperty("test").getValue(STRING));
}
@Test
public void testConnectOnRemoveProperty() {
NodeBuilder root = base.builder();
NodeBuilder childA = root.child("x");
NodeBuilder childB = root.child("x");
childB.setProperty("test", "foo");
childA.removeProperty("test");
assertFalse(childA.hasProperty("test"));
assertFalse(childB.hasProperty("test"));
childA.setProperty("test", "bar");
assertEquals("bar", childA.getProperty("test").getValue(STRING));
assertEquals("bar", childB.getProperty("test").getValue(STRING));
}
@Test
public void testConnectOnAddNode() {
NodeBuilder root = base.builder();
NodeBuilder childA = root.child("x");
NodeBuilder childB = root.child("x");
assertFalse(childA.hasChildNode("test"));
assertFalse(childB.hasChildNode("test"));
childB.child("test");
assertTrue(childA.hasChildNode("test"));
assertTrue(childB.hasChildNode("test"));
}
@Test
public void testWriteOnRemoveNode() {
for (String name : new String[] {"x", "new"}) {
NodeBuilder root = base.builder();
NodeBuilder child = root.child(name);
root.getChildNode(name).remove();
try {
child.setProperty("q", "w");
fail();
} catch (IllegalStateException e) {
// expected
}
root.child(name);
assertEquals(0, child.getChildNodeCount(1)); // reconnect!
}
}
@Test
public void testAddRemovedNodeAgain() {
NodeBuilder root = base.builder();
root.getChildNode("x").remove();
NodeBuilder x = root.child("x");
x.child("q");
assertTrue(x.hasChildNode("q"));
}
@Test
public void testReset() {
NodeBuilder root = base.builder();
NodeBuilder child = root.child("x");
child.child("new");
assertTrue(child.hasChildNode("new"));
assertTrue(root.child("x").hasChildNode("new"));
((MemoryNodeBuilder) root).reset(base);
assertFalse(child.hasChildNode("new"));
assertFalse(root.child("x").hasChildNode("new"));
}
@Test
public void testReset2() {
NodeBuilder root = base.builder();
NodeBuilder x = root.child("x");
x.child("y");
((MemoryNodeBuilder) root).reset(base);
assertTrue(root.hasChildNode("x"));
assertFalse(x.hasChildNode("y"));
}
@Test
public void testUnmodifiedEqualsBase() {
NodeBuilder root = base.builder();
NodeBuilder x = root.child("x");
assertEquals(x.getBaseState(), x.getNodeState());
}
@Test
public void transitiveRemove() {
NodeBuilder root = base.builder();
NodeBuilder x = root.getChildNode("x");
NodeBuilder q = x.getChildNode("q");
assertTrue(x.exists());
assertTrue(q.exists());
root.getChildNode("x").remove();
assertFalse(q.exists());
assertFalse(x.exists());
}
@Test
public void testExistingStatus() {
NodeBuilder root = base.builder();
NodeBuilder x = root.child("x");
assertTrue(x.exists());
assertFalse(x.isNew());
assertFalse(x.isModified());
}
@Test
public void testModifiedStatus() {
NodeBuilder root = base.builder();
NodeBuilder x = root.child("x");
x.setProperty("p", "pValue");
assertTrue(x.exists());
assertFalse(x.isNew());
assertTrue(x.isModified());
}
@Test
public void testReplacedStatus() {
NodeBuilder root = base.builder();
NodeBuilder x = root.getChildNode("x");
x.setChildNode("new");
assertFalse(x.isReplaced());
}
@Test
public void testReplacedStatus2() {
NodeBuilder x = base.builder().getChildNode("x");
NodeBuilder q = x.getChildNode("q");
q.remove();
assertFalse(q.isReplaced());
x.setChildNode("q").setProperty("a", "b");
assertTrue(q.isReplaced());
}
@Test
public void testReplacedStatus3() {
NodeBuilder x = base.builder().getChildNode("x");
NodeBuilder q = x.getChildNode("q");
assertFalse(q.isReplaced());
x.setChildNode("q").setProperty("a", "b");
assertTrue(q.isReplaced());
}
@Test
public void removeParent() {
NodeBuilder x = base.builder().getChildNode("x");
NodeBuilder y = x.setChildNode("y");
x.remove();
assertFalse(x.exists());
}
@Test
public void testRemovedStatus() {
NodeBuilder root = base.builder();
NodeBuilder x = root.child("x");
root.getChildNode("x").remove();
assertFalse(x.exists());
assertFalse(x.isNew());
assertFalse(x.isModified());
}
@Test
public void testNewStatus() {
NodeBuilder root = base.builder();
NodeBuilder n = root.child("n");
assertTrue(n.exists());
assertTrue(n.isNew());
assertFalse(n.isModified());
}
@Test
public void getExistingChildTest() {
NodeBuilder rootBuilder = base.builder();
NodeBuilder x = rootBuilder.getChildNode("x");
assertTrue(x.exists());
assertTrue(x.getNodeState().exists());
}
@Test
public void getNonExistingChildTest() {
NodeBuilder rootBuilder = base.builder();
NodeBuilder any = rootBuilder.getChildNode("any");
assertFalse(any.getChildNode("other").exists());
assertFalse(any.exists());
try {
any.setChildNode("any");
fail();
} catch (IllegalStateException expected) {}
}
@Test
public void addExistingChildTest() {
NodeBuilder rootBuilder = base.builder();
NodeBuilder x = rootBuilder.setChildNode("x");
assertTrue(x.exists());
assertTrue(x.getBaseState().exists());
}
@Test
public void addNewChildTest() {
NodeBuilder rootBuilder = base.builder();
NodeBuilder x = rootBuilder.setChildNode("any");
assertTrue(x.exists());
assertTrue(x.getNodeState().exists());
}
@Test
public void existingChildTest() {
NodeBuilder rootBuilder = base.builder();
NodeBuilder x = rootBuilder.child("x");
assertTrue(x.exists());
assertTrue(x.getBaseState().exists());
}
@Test
public void newChildTest() {
NodeBuilder rootBuilder = base.builder();
NodeBuilder x = rootBuilder.child("any");
assertTrue(x.exists());
assertTrue(x.getNodeState().exists());
}
@Test
public void setNodeTest() {
NodeBuilder rootBuilder = EMPTY_NODE.builder();
// +"/a":{"c":{"c"="cValue"}}
rootBuilder.setChildNode("a", createBC(true));
NodeState c = rootBuilder.getNodeState().getChildNode("a").getChildNode("c");
assertTrue(c.hasProperty("c"));
rootBuilder.child("a").child("c").setProperty("c2", "c2Value");
c = rootBuilder.getNodeState().getChildNode("a").getChildNode("c");
assertTrue(c.hasProperty("c"));
assertTrue(c.hasProperty("c2"));
}
@Test
public void setTest() {
Assume.assumeTrue(EMPTY_NODE.builder() instanceof MemoryNodeBuilder);
MemoryNodeBuilder rootBuilder = (MemoryNodeBuilder) EMPTY_NODE.builder();
assertFalse(base.equals(rootBuilder.getNodeState()));
rootBuilder.set(base);
assertTrue(base.equals(rootBuilder.getNodeState()));
MemoryNodeBuilder xBuilder = (MemoryNodeBuilder) rootBuilder.getChildNode("x");
NodeState yState = base.getChildNode("y");
assertFalse(yState.equals(xBuilder.getNodeState()));
xBuilder.set(yState);
assertTrue(yState.equals(xBuilder.getNodeState()));
}
@Test
public void testMove() {
NodeBuilder rootBuilder = base.builder();
assertTrue(rootBuilder.getChildNode("y").moveTo(rootBuilder.child("x"), "yy"));
NodeState newRoot = rootBuilder.getNodeState();
assertFalse(newRoot.hasChildNode("y"));
assertTrue(newRoot.hasChildNode("x"));
assertTrue(newRoot.getChildNode("x").hasChildNode("q"));
assertTrue(newRoot.getChildNode("x").hasChildNode("yy"));
}
@Test
public void testRename() {
NodeBuilder rootBuilder = base.builder();
assertTrue(rootBuilder.getChildNode("y").moveTo(rootBuilder, "yy"));
NodeState newRoot = rootBuilder.getNodeState();
assertFalse(newRoot.hasChildNode("y"));
assertTrue(newRoot.hasChildNode("yy"));
}
@Test
public void testMoveToSelf() {
NodeBuilder rootBuilder = base.builder();
assertFalse(rootBuilder.getChildNode("y").moveTo(rootBuilder, "y"));
NodeState newRoot = rootBuilder.getNodeState();
assertTrue(newRoot.hasChildNode("y"));
}
@Test
public void testMoveToDescendant() {
NodeBuilder rootBuilder = base.builder();
assertTrue(rootBuilder.getChildNode("x").moveTo(rootBuilder.getChildNode("x"), "xx"));
assertFalse(rootBuilder.hasChildNode("x"));
}
@Test
public void assertion_OAK781() {
NodeBuilder rootBuilder = EMPTY_NODE.builder();
rootBuilder.child("a").setChildNode("b", createBC(false));
NodeState r = rootBuilder.getNodeState();
NodeState a = r.getChildNode("a");
NodeState b = a.getChildNode("b");
NodeState c = b.getChildNode("c");
assertTrue(a.exists());
assertFalse(b.exists());
assertTrue(c.exists());
// No assertion must fail in .child("c")
rootBuilder.child("a").child("b").child("c");
rootBuilder = new MemoryNodeBuilder(r);
// No assertion must fail in .child("c")
rootBuilder.child("a").child("b").child("c");
}
@Test
public void modifyChildNodeOfNonExistingNode() {
NodeBuilder rootBuilder = EMPTY_NODE.builder();
// +"/a":{"b":{"c":{"c"="cValue"}}} where b.exists() == false
rootBuilder.child("a").setChildNode("b", createBC(false));
NodeState r = rootBuilder.getNodeState();
NodeState a = r.getChildNode("a");
NodeState b = a.getChildNode("b");
NodeState c = b.getChildNode("c");
assertTrue(a.exists());
assertFalse(b.exists());
assertTrue(c.exists());
assertTrue(c.hasProperty("c"));
rootBuilder.child("a").getChildNode("b").child("c").setProperty("c2", "c2Value");
r = rootBuilder.getNodeState();
a = r.getChildNode("a");
b = a.getChildNode("b");
c = b.getChildNode("c");
assertTrue(a.exists());
assertFalse(b.exists());
assertTrue(c.exists());
// Node c is modified
assertTrue(c.hasProperty("c"));
assertTrue(c.hasProperty("c2"));
}
@Test
public void shadowNonExistingNode1() {
NodeBuilder rootBuilder = EMPTY_NODE.builder();
// +"/a":{"b":{"c":{"c"="cValue"}}} where b.exists() == false
rootBuilder.child("a").setChildNode("b", createBC(false));
NodeState r = rootBuilder.getNodeState();
NodeState a = r.getChildNode("a");
NodeState b = a.getChildNode("b");
NodeState c = b.getChildNode("c");
assertTrue(a.exists());
assertFalse(b.exists());
assertTrue(c.exists());
assertTrue(c.hasProperty("c"));
rootBuilder.child("a").setChildNode("b").child("c").setProperty("c2", "c2Value");
r = rootBuilder.getNodeState();
a = r.getChildNode("a");
b = a.getChildNode("b");
c = b.getChildNode("c");
assertTrue(a.exists());
assertTrue(b.exists()); // node b is shadowed by above child("b")
assertTrue(c.exists());
// node c is shadowed by subtree b
assertFalse(c.hasProperty("c"));
assertTrue(c.hasProperty("c2"));
}
@Test
public void shadowNonExistingNode2() {
NodeBuilder rootBuilder = EMPTY_NODE.builder();
// +"/a":{"b":{"c":{"c":"cValue"}}} where b.exists() == false
rootBuilder.child("a").setChildNode("b", createBC(false));
NodeState r = rootBuilder.getNodeState();
NodeState a = r.getChildNode("a");
NodeState b = a.getChildNode("b");
NodeState c = b.getChildNode("c");
assertTrue(a.exists());
assertFalse(b.exists());
assertTrue(c.exists());
assertTrue(c.hasProperty("c"));
rootBuilder.child("a").child("b").child("c").setProperty("c2", "c2Value");
r = rootBuilder.getNodeState();
a = r.getChildNode("a");
b = a.getChildNode("b");
c = b.getChildNode("c");
assertTrue(a.exists());
assertTrue(b.exists()); // node b is shadowed by above child("b")
assertTrue(c.exists());
// node c is shadowed by subtree b
assertFalse(c.hasProperty("c"));
assertTrue(c.hasProperty("c2"));
}
@Test
public void navigateNonExistingNode() {
NodeBuilder rootBuilder = EMPTY_NODE.builder();
// +"/a":{"b":{"c":{"c":"cValue"}}} where b.exists() == false
rootBuilder.child("a").setChildNode("b", createBC(false));
NodeState r = rootBuilder.getNodeState();
NodeState a = r.getChildNode("a");
NodeState b = a.getChildNode("b");
NodeState c = b.getChildNode("c");
assertTrue(a.exists());
assertFalse(b.exists());
assertTrue(c.exists());
assertTrue(c.hasProperty("c"));
NodeBuilder aBuilder = rootBuilder.getChildNode("a");
NodeBuilder bBuilder = aBuilder.getChildNode("b");
NodeBuilder cBuilder = bBuilder.getChildNode("c");
assertTrue(aBuilder.exists());
assertTrue(cBuilder.exists());
cBuilder.setProperty("c2", "c2Value");
r = rootBuilder.getNodeState();
a = r.getChildNode("a");
b = a.getChildNode("b");
c = b.getChildNode("c");
assertTrue(a.exists());
assertFalse(b.exists());
assertTrue(c.exists());
assertTrue(c.hasProperty("c"));
assertTrue(c.hasProperty("c2"));
}
@Test
public void removeRoot() {
assertFalse(base.builder().remove());
}
private static NodeState createBC(final boolean exists) {
final NodeState C = new MemoryNodeBuilder(EmptyNodeState.EMPTY_NODE)
.setProperty("c", "cValue")
.getNodeState();
return new AbstractNodeState() {
@Override
public boolean exists() {
return exists;
}
@NotNull
@Override
public Iterable<? extends PropertyState> getProperties() {
return ImmutableSet.of();
}
@Override
public boolean hasChildNode(@NotNull String name) {
return "c".equals(name);
}
@NotNull
@Override
public NodeState getChildNode(@NotNull String name) {
if ("c".equals(name)) {
return C;
} else {
checkValidName(name);
return EmptyNodeState.MISSING_NODE;
}
}
@NotNull
@Override
public Iterable<? extends ChildNodeEntry> getChildNodeEntries() {
if (exists) {
return ImmutableSet.of(new MemoryChildNodeEntry("c", C));
} else {
return ImmutableSet.of();
}
}
@NotNull
@Override
public NodeBuilder builder() {
return new MemoryNodeBuilder(this);
}
};
}
}
| |
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.spongepowered.api.util;
import java.util.Random;
/**
* Represents a value which may vary randomly.
*/
public abstract class VariableAmount {
/**
* Creates a new 'fixed' variable amount, calls to {@link #getAmount} will
* always return the fixed value.
*
* @param value The fixed value
* @return A variable amount representation
*/
public static VariableAmount fixed(double value) {
return new Fixed(value);
}
/**
* Creates a new variable about which has a base and variance. The final
* amount will be the base amount plus or minus a random amount between zero
* (inclusive) and the variance (exclusive).
*
* @param base The base value
* @param variance The variance
* @return A variable amount representation
*/
public static VariableAmount baseWithVariance(double base, double variance) {
return new BaseAndVariance(base, variance);
}
/**
* Creates a new variable amount which has a base and an additional amount.
* The final amount will be the base amount plus a random amount between
* zero (inclusive) and the additional amount (exclusive).
*
* @param base The base value
* @param addition The additional amount
* @return A variable amount representation
*/
public static VariableAmount baseWithRandomAddition(double base, double addition) {
return new BaseAndVariance(base + addition / 2, addition / 2);
}
/**
* Creates a new variable about which has a base and a chance to apply a
* random variance. The chance should be between zero and one with a chance
* of one signifying that the variance will always be applied. If the chance
* succeeds then the final amount will be the base amount plus or minus a
* random amount between zero (inclusive) and the variance (exclusive). If
* the chance fails then the final amount will just be the base value.
*
* @param base The base value
* @param variance The variance
* @param chance The chance to apply the variance
* @return A variable amount representation
*/
public static VariableAmount baseWithOptionalVariance(double base, double variance, double chance) {
return new OptionalAmount(base, chance, baseWithVariance(base, variance));
}
/**
* Creates a new variable about which has a base and a chance to apply a
* random additional amount. The chance should be between zero and one with
* a chance of one signifying that the additional amount will always be
* applied. If the chance succeeds then the final amount will be the base
* amount plus a random amount between zero (inclusive) and the additional
* amount (exclusive). If the chance fails then the final amount will just
* be the base value.
*
* @param base The base value
* @param addition The additional amount
* @param chance The chance to apply the additional amount
* @return A variable amount representation
*/
public static VariableAmount baseWithOptionalAddition(double base, double addition, double chance) {
return new OptionalAmount(base, chance, baseWithRandomAddition(base, addition));
}
/**
* Gets an instance of the variable amount depending on the given random
* object.
*
* @param rand The random object
* @return The amount
*/
public abstract double getAmount(Random rand);
/**
* Gets the amount as if from {@link #getAmount(Random)} but floored to the
* nearest integer equivalent.
*
* @param rand The random object
* @return The floored amount
*/
public int getFlooredAmount(Random rand) {
return (int) Math.floor(getAmount(rand));
}
@Override
public String toString() {
return "a varying amount";
}
/**
* Represents a fixed amount, calls to {@link #getAmount} will always return
* the same fixed value.
*/
public static class Fixed extends VariableAmount {
private double amount;
private Fixed(double amount) {
this.amount = amount;
}
@Override
public double getAmount(Random rand) {
return this.amount;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Fixed amount = (Fixed) obj;
return amount.amount == this.amount;
}
}
/**
* Represents a base amount with a variance, the final amount will be the
* base amount plus or minus a random amount between zero (inclusive) and
* the variance (exclusive).
*/
public static class BaseAndVariance extends VariableAmount {
private double base;
private double variance;
private BaseAndVariance(double base, double variance) {
this.base = base;
this.variance = variance;
}
@Override
public double getAmount(Random rand) {
return this.base + rand.nextDouble() * this.variance * 2 - this.variance;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
BaseAndVariance amount = (BaseAndVariance) obj;
return amount.base == this.base && amount.variance == this.variance;
}
}
/**
* Represents a variable amount which has a base and a chance of varying.
* This wraps another {@link VariableAmount} which it refers to if the
* chance succeeds.
*/
public static class OptionalAmount extends VariableAmount {
private double chance;
private double base;
private VariableAmount inner;
private OptionalAmount(double base, double chance, VariableAmount inner) {
this.inner = inner;
this.chance = chance;
}
@Override
public double getAmount(Random rand) {
if (rand.nextDouble() < this.chance) {
return this.inner.getAmount(rand);
}
return this.base;
}
@Override
public int getFlooredAmount(Random rand) {
if (rand.nextDouble() < this.chance) {
return this.inner.getFlooredAmount(rand);
}
return (int) Math.floor(this.base);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
OptionalAmount amount = (OptionalAmount) obj;
if (!this.inner.equals(amount.inner)) {
return false;
}
return amount.base == this.base && this.chance == amount.chance;
}
}
}
| |
/*
* 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.jdbc.impl;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLXML;
import java.sql.Struct;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Map;
import org.apache.calcite.avatica.util.Cursor.Accessor;
import org.apache.drill.exec.vector.accessor.SqlAccessor;
import org.apache.drill.jdbc.InvalidCursorStateSqlException;
// TODO: Revisit adding null check for non-primitive types to SqlAccessor's
// contract and classes generated by SqlAccessor template (DRILL-xxxx).
public class AvaticaDrillSqlAccessor implements Accessor {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AvaticaDrillSqlAccessor.class);
private final static byte PRIMITIVE_NUM_NULL_VALUE = 0;
private final static boolean BOOLEAN_NULL_VALUE = false;
private SqlAccessor underlyingAccessor;
private DrillCursor cursor;
AvaticaDrillSqlAccessor(SqlAccessor drillSqlAccessor, DrillCursor cursor) {
super();
this.underlyingAccessor = drillSqlAccessor;
this.cursor = cursor;
}
private int getCurrentRecordNumber() throws SQLException {
// WORKAROUND: isBeforeFirst can't be called first here because AvaticaResultSet
// .next() doesn't increment its row field when cursor.next() returns false,
// so in that case row can be left at -1, so isBeforeFirst() returns true
// even though we're not longer before the empty set of rows--and it's all
// private, so we can't get to it to override any of several candidates.
if ( cursor.isAfterLast() ) {
throw new InvalidCursorStateSqlException(
"Result set cursor is already positioned past all rows." );
}
else if ( cursor.isBeforeFirst() ) {
throw new InvalidCursorStateSqlException(
"Result set cursor is positioned before all rows. Call next() first." );
}
else {
return cursor.getCurrentRecordNumber();
}
}
/**
* @see SQLAccessor#getObjectClass()
*/
public Class<?> getObjectClass() {
return underlyingAccessor.getObjectClass();
}
@Override
public boolean wasNull() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber());
}
@Override
public String getString() throws SQLException {
return underlyingAccessor.getString(getCurrentRecordNumber());
}
@Override
public boolean getBoolean() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? BOOLEAN_NULL_VALUE
: underlyingAccessor.getBoolean(getCurrentRecordNumber());
}
@Override
public byte getByte() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getByte(getCurrentRecordNumber());
}
@Override
public short getShort() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getShort(getCurrentRecordNumber());
}
@Override
public int getInt() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getInt(getCurrentRecordNumber());
}
@Override
public long getLong() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getLong(getCurrentRecordNumber());
}
@Override
public float getFloat() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getFloat(getCurrentRecordNumber());
}
@Override
public double getDouble() throws SQLException {
return underlyingAccessor.isNull(getCurrentRecordNumber())
? PRIMITIVE_NUM_NULL_VALUE
: underlyingAccessor.getDouble(getCurrentRecordNumber());
}
@Override
public BigDecimal getBigDecimal() throws SQLException {
return underlyingAccessor.getBigDecimal(getCurrentRecordNumber());
}
@Override
public BigDecimal getBigDecimal(int scale) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public byte[] getBytes() throws SQLException {
return underlyingAccessor.getBytes(getCurrentRecordNumber());
}
@Override
public InputStream getAsciiStream() throws SQLException {
return underlyingAccessor.getStream(getCurrentRecordNumber());
}
@Override
public InputStream getUnicodeStream() throws SQLException {
return underlyingAccessor.getStream(getCurrentRecordNumber());
}
@Override
public InputStream getBinaryStream() throws SQLException {
return underlyingAccessor.getStream(getCurrentRecordNumber());
}
@Override
public Object getObject() throws SQLException {
return underlyingAccessor.getObject(getCurrentRecordNumber());
}
@Override
public Reader getCharacterStream() throws SQLException {
return underlyingAccessor.getReader(getCurrentRecordNumber());
}
@Override
public Object getObject(Map<String, Class<?>> map) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Ref getRef() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Blob getBlob() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Clob getClob() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Array getArray() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Struct getStruct() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public Date getDate(Calendar calendar) throws SQLException {
return underlyingAccessor.getDate(getCurrentRecordNumber());
}
@Override
public Time getTime(Calendar calendar) throws SQLException {
return underlyingAccessor.getTime(getCurrentRecordNumber());
}
@Override
public Timestamp getTimestamp(Calendar calendar) throws SQLException {
return underlyingAccessor.getTimestamp(getCurrentRecordNumber());
}
@Override
public URL getURL() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public NClob getNClob() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public SQLXML getSQLXML() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public String getNString() throws SQLException {
return underlyingAccessor.getString(getCurrentRecordNumber());
}
@Override
public Reader getNCharacterStream() throws SQLException {
return underlyingAccessor.getReader(getCurrentRecordNumber());
}
@Override
public <T> T getObject(Class<T> type) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
}
| |
/*
* Copyright (C) 2016 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 android.content.res;
import android.annotation.ColorInt;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.pm.ActivityInfo.Config;
import android.content.res.Resources.Theme;
import com.android.internal.R;
import com.android.internal.util.GrowingArrayUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.graphics.LinearGradient;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Xml;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Lets you define a gradient color, which is used inside
* {@link android.graphics.drawable.VectorDrawable}.
*
* {@link android.content.res.GradientColor}s are created from XML resource files defined in the
* "color" subdirectory directory of an application's resource directory. The XML file contains
* a single "gradient" element with a number of attributes and elements inside. For example:
* <pre>
* <gradient xmlns:android="http://schemas.android.com/apk/res/android">
* <android:startColor="?android:attr/colorPrimary"/>
* <android:endColor="?android:attr/colorControlActivated"/>
* <.../>
* <android:type="linear"/>
* </gradient>
* </pre>
*
* This can describe either a {@link android.graphics.LinearGradient},
* {@link android.graphics.RadialGradient}, or {@link android.graphics.SweepGradient}.
*
* Note that different attributes are relevant for different types of gradient.
* For example, android:gradientRadius is only applied to RadialGradient.
* android:centerX and android:centerY are only applied to SweepGradient or RadialGradient.
* android:startX, android:startY, android:endX and android:endY are only applied to LinearGradient.
*
* Also note if any color "item" element is defined, then startColor, centerColor and endColor will
* be ignored.
* @hide
*/
public class GradientColor extends ComplexColor {
private static final String TAG = "GradientColor";
private static final boolean DBG_GRADIENT = false;
@IntDef({TILE_MODE_CLAMP, TILE_MODE_REPEAT, TILE_MODE_MIRROR})
@Retention(RetentionPolicy.SOURCE)
private @interface GradientTileMode {}
private static final int TILE_MODE_CLAMP = 0;
private static final int TILE_MODE_REPEAT = 1;
private static final int TILE_MODE_MIRROR = 2;
/** Lazily-created factory for this GradientColor. */
private GradientColorFactory mFactory;
private @Config int mChangingConfigurations;
private int mDefaultColor;
// After parsing all the attributes from XML, this shader is the ultimate result containing
// all the XML information.
private Shader mShader = null;
// Below are the attributes at the root element <gradient>.
// NOTE: they need to be copied in the copy constructor!
private int mGradientType = GradientDrawable.LINEAR_GRADIENT;
private float mCenterX = 0f;
private float mCenterY = 0f;
private float mStartX = 0f;
private float mStartY = 0f;
private float mEndX = 0f;
private float mEndY = 0f;
private int mStartColor = 0;
private int mCenterColor = 0;
private int mEndColor = 0;
private boolean mHasCenterColor = false;
private int mTileMode = 0; // Clamp mode.
private float mGradientRadius = 0f;
// Below are the attributes for the <item> element.
private int[] mItemColors;
private float[] mItemOffsets;
// Theme attributes for the root and item elements.
private int[] mThemeAttrs;
private int[][] mItemsThemeAttrs;
private GradientColor() {
}
private GradientColor(GradientColor copy) {
if (copy != null) {
mChangingConfigurations = copy.mChangingConfigurations;
mDefaultColor = copy.mDefaultColor;
mShader = copy.mShader;
mGradientType = copy.mGradientType;
mCenterX = copy.mCenterX;
mCenterY = copy.mCenterY;
mStartX = copy.mStartX;
mStartY = copy.mStartY;
mEndX = copy.mEndX;
mEndY = copy.mEndY;
mStartColor = copy.mStartColor;
mCenterColor = copy.mCenterColor;
mEndColor = copy.mEndColor;
mHasCenterColor = copy.mHasCenterColor;
mGradientRadius = copy.mGradientRadius;
mTileMode = copy.mTileMode;
if (copy.mItemColors != null) {
mItemColors = copy.mItemColors.clone();
}
if (copy.mItemOffsets != null) {
mItemOffsets = copy.mItemOffsets.clone();
}
if (copy.mThemeAttrs != null) {
mThemeAttrs = copy.mThemeAttrs.clone();
}
if (copy.mItemsThemeAttrs != null) {
mItemsThemeAttrs = copy.mItemsThemeAttrs.clone();
}
}
}
// Set the default to clamp mode.
private static Shader.TileMode parseTileMode(@GradientTileMode int tileMode) {
switch (tileMode) {
case TILE_MODE_CLAMP:
return Shader.TileMode.CLAMP;
case TILE_MODE_REPEAT:
return Shader.TileMode.REPEAT;
case TILE_MODE_MIRROR:
return Shader.TileMode.MIRROR;
default:
return Shader.TileMode.CLAMP;
}
}
/**
* Update the root level's attributes, either for inflate or applyTheme.
*/
private void updateRootElementState(TypedArray a) {
// Extract the theme attributes, if any.
mThemeAttrs = a.extractThemeAttrs();
mStartX = a.getFloat(
R.styleable.GradientColor_startX, mStartX);
mStartY = a.getFloat(
R.styleable.GradientColor_startY, mStartY);
mEndX = a.getFloat(
R.styleable.GradientColor_endX, mEndX);
mEndY = a.getFloat(
R.styleable.GradientColor_endY, mEndY);
mCenterX = a.getFloat(
R.styleable.GradientColor_centerX, mCenterX);
mCenterY = a.getFloat(
R.styleable.GradientColor_centerY, mCenterY);
mGradientType = a.getInt(
R.styleable.GradientColor_type, mGradientType);
mStartColor = a.getColor(
R.styleable.GradientColor_startColor, mStartColor);
mHasCenterColor |= a.hasValue(
R.styleable.GradientColor_centerColor);
mCenterColor = a.getColor(
R.styleable.GradientColor_centerColor, mCenterColor);
mEndColor = a.getColor(
R.styleable.GradientColor_endColor, mEndColor);
mTileMode = a.getInt(
R.styleable.GradientColor_tileMode, mTileMode);
if (DBG_GRADIENT) {
Log.v(TAG, "hasCenterColor is " + mHasCenterColor);
if (mHasCenterColor) {
Log.v(TAG, "centerColor:" + mCenterColor);
}
Log.v(TAG, "startColor: " + mStartColor);
Log.v(TAG, "endColor: " + mEndColor);
Log.v(TAG, "tileMode: " + mTileMode);
}
mGradientRadius = a.getFloat(R.styleable.GradientColor_gradientRadius,
mGradientRadius);
}
/**
* Check if the XML content is valid.
*
* @throws XmlPullParserException if errors were found.
*/
private void validateXmlContent() throws XmlPullParserException {
if (mGradientRadius <= 0
&& mGradientType == GradientDrawable.RADIAL_GRADIENT) {
throw new XmlPullParserException(
"<gradient> tag requires 'gradientRadius' "
+ "attribute with radial type");
}
}
/**
* The shader information will be applied to the native VectorDrawable's path.
* @hide
*/
public Shader getShader() {
return mShader;
}
/**
* A public method to create GradientColor from a XML resource.
*/
public static GradientColor createFromXml(Resources r, XmlResourceParser parser, Theme theme)
throws XmlPullParserException, IOException {
final AttributeSet attrs = Xml.asAttributeSet(parser);
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG
&& type != XmlPullParser.END_DOCUMENT) {
// Seek parser to start tag.
}
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException("No start tag found");
}
return createFromXmlInner(r, parser, attrs, theme);
}
/**
* Create from inside an XML document. Called on a parser positioned at a
* tag in an XML document, tries to create a GradientColor from that tag.
*
* @return A new GradientColor for the current tag.
* @throws XmlPullParserException if the current tag is not <gradient>
*/
@NonNull
static GradientColor createFromXmlInner(@NonNull Resources r,
@NonNull XmlPullParser parser, @NonNull AttributeSet attrs, @Nullable Theme theme)
throws XmlPullParserException, IOException {
final String name = parser.getName();
if (!name.equals("gradient")) {
throw new XmlPullParserException(
parser.getPositionDescription() + ": invalid gradient color tag " + name);
}
final GradientColor gradientColor = new GradientColor();
gradientColor.inflate(r, parser, attrs, theme);
return gradientColor;
}
/**
* Fill in this object based on the contents of an XML "gradient" element.
*/
private void inflate(@NonNull Resources r, @NonNull XmlPullParser parser,
@NonNull AttributeSet attrs, @Nullable Theme theme)
throws XmlPullParserException, IOException {
final TypedArray a = Resources.obtainAttributes(r, theme, attrs, R.styleable.GradientColor);
updateRootElementState(a);
mChangingConfigurations |= a.getChangingConfigurations();
a.recycle();
// Check correctness and throw exception if errors found.
validateXmlContent();
inflateChildElements(r, parser, attrs, theme);
onColorsChange();
}
/**
* Inflates child elements "item"s for each color stop.
*
* Note that at root level, we need to save ThemeAttrs for theme applied later.
* Here similarly, at each child item, we need to save the theme's attributes, and apply theme
* later as applyItemsAttrsTheme().
*/
private void inflateChildElements(@NonNull Resources r, @NonNull XmlPullParser parser,
@NonNull AttributeSet attrs, @NonNull Theme theme)
throws XmlPullParserException, IOException {
final int innerDepth = parser.getDepth() + 1;
int type;
int depth;
// Pre-allocate the array with some size, for better performance.
float[] offsetList = new float[20];
int[] colorList = new int[offsetList.length];
int[][] themeAttrsList = new int[offsetList.length][];
int listSize = 0;
boolean hasUnresolvedAttrs = false;
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& ((depth = parser.getDepth()) >= innerDepth
|| type != XmlPullParser.END_TAG)) {
if (type != XmlPullParser.START_TAG) {
continue;
}
if (depth > innerDepth || !parser.getName().equals("item")) {
continue;
}
final TypedArray a = Resources.obtainAttributes(r, theme, attrs,
R.styleable.GradientColorItem);
boolean hasColor = a.hasValue(R.styleable.GradientColorItem_color);
boolean hasOffset = a.hasValue(R.styleable.GradientColorItem_offset);
if (!hasColor || !hasOffset) {
throw new XmlPullParserException(
parser.getPositionDescription()
+ ": <item> tag requires a 'color' attribute and a 'offset' "
+ "attribute!");
}
final int[] themeAttrs = a.extractThemeAttrs();
int color = a.getColor(R.styleable.GradientColorItem_color, 0);
float offset = a.getFloat(R.styleable.GradientColorItem_offset, 0);
if (DBG_GRADIENT) {
Log.v(TAG, "new item color " + color + " " + Integer.toHexString(color));
Log.v(TAG, "offset" + offset);
}
mChangingConfigurations |= a.getChangingConfigurations();
a.recycle();
if (themeAttrs != null) {
hasUnresolvedAttrs = true;
}
colorList = GrowingArrayUtils.append(colorList, listSize, color);
offsetList = GrowingArrayUtils.append(offsetList, listSize, offset);
themeAttrsList = GrowingArrayUtils.append(themeAttrsList, listSize, themeAttrs);
listSize++;
}
if (listSize > 0) {
if (hasUnresolvedAttrs) {
mItemsThemeAttrs = new int[listSize][];
System.arraycopy(themeAttrsList, 0, mItemsThemeAttrs, 0, listSize);
} else {
mItemsThemeAttrs = null;
}
mItemColors = new int[listSize];
mItemOffsets = new float[listSize];
System.arraycopy(colorList, 0, mItemColors, 0, listSize);
System.arraycopy(offsetList, 0, mItemOffsets, 0, listSize);
}
}
/**
* Apply theme to all the items.
*/
private void applyItemsAttrsTheme(Theme t) {
if (mItemsThemeAttrs == null) {
return;
}
boolean hasUnresolvedAttrs = false;
final int[][] themeAttrsList = mItemsThemeAttrs;
final int N = themeAttrsList.length;
for (int i = 0; i < N; i++) {
if (themeAttrsList[i] != null) {
final TypedArray a = t.resolveAttributes(themeAttrsList[i],
R.styleable.GradientColorItem);
// Extract the theme attributes, if any, before attempting to
// read from the typed array. This prevents a crash if we have
// unresolved attrs.
themeAttrsList[i] = a.extractThemeAttrs(themeAttrsList[i]);
if (themeAttrsList[i] != null) {
hasUnresolvedAttrs = true;
}
mItemColors[i] = a.getColor(R.styleable.GradientColorItem_color, mItemColors[i]);
mItemOffsets[i] = a.getFloat(R.styleable.GradientColorItem_offset, mItemOffsets[i]);
if (DBG_GRADIENT) {
Log.v(TAG, "applyItemsAttrsTheme Colors[i] " + i + " " +
Integer.toHexString(mItemColors[i]));
Log.v(TAG, "Offsets[i] " + i + " " + mItemOffsets[i]);
}
// Account for any configuration changes.
mChangingConfigurations |= a.getChangingConfigurations();
a.recycle();
}
}
if (!hasUnresolvedAttrs) {
mItemsThemeAttrs = null;
}
}
private void onColorsChange() {
int[] tempColors = null;
float[] tempOffsets = null;
if (mItemColors != null) {
int length = mItemColors.length;
tempColors = new int[length];
tempOffsets = new float[length];
for (int i = 0; i < length; i++) {
tempColors[i] = mItemColors[i];
tempOffsets[i] = mItemOffsets[i];
}
} else {
if (mHasCenterColor) {
tempColors = new int[3];
tempColors[0] = mStartColor;
tempColors[1] = mCenterColor;
tempColors[2] = mEndColor;
tempOffsets = new float[3];
tempOffsets[0] = 0.0f;
// Since 0.5f is default value, try to take the one that isn't 0.5f
tempOffsets[1] = 0.5f;
tempOffsets[2] = 1f;
} else {
tempColors = new int[2];
tempColors[0] = mStartColor;
tempColors[1] = mEndColor;
}
}
if (tempColors.length < 2) {
Log.w(TAG, "<gradient> tag requires 2 color values specified!" + tempColors.length
+ " " + tempColors);
}
if (mGradientType == GradientDrawable.LINEAR_GRADIENT) {
mShader = new LinearGradient(mStartX, mStartY, mEndX, mEndY, tempColors, tempOffsets,
parseTileMode(mTileMode));
} else {
if (mGradientType == GradientDrawable.RADIAL_GRADIENT) {
mShader = new RadialGradient(mCenterX, mCenterY, mGradientRadius, tempColors,
tempOffsets, parseTileMode(mTileMode));
} else {
mShader = new SweepGradient(mCenterX, mCenterY, tempColors, tempOffsets);
}
}
mDefaultColor = tempColors[0];
}
/**
* For Gradient color, the default color is not very useful, since the gradient will override
* the color information anyway.
*/
@Override
@ColorInt
public int getDefaultColor() {
return mDefaultColor;
}
/**
* Similar to ColorStateList, setup constant state and its factory.
* @hide only for resource preloading
*/
@Override
public ConstantState<ComplexColor> getConstantState() {
if (mFactory == null) {
mFactory = new GradientColorFactory(this);
}
return mFactory;
}
private static class GradientColorFactory extends ConstantState<ComplexColor> {
private final GradientColor mSrc;
public GradientColorFactory(GradientColor src) {
mSrc = src;
}
@Override
public @Config int getChangingConfigurations() {
return mSrc.mChangingConfigurations;
}
@Override
public GradientColor newInstance() {
return mSrc;
}
@Override
public GradientColor newInstance(Resources res, Theme theme) {
return mSrc.obtainForTheme(theme);
}
}
/**
* Returns an appropriately themed gradient color.
*
* @param t the theme to apply
* @return a copy of the gradient color the theme applied, or the
* gradient itself if there were no unresolved theme
* attributes
* @hide only for resource preloading
*/
@Override
public GradientColor obtainForTheme(Theme t) {
if (t == null || !canApplyTheme()) {
return this;
}
final GradientColor clone = new GradientColor(this);
clone.applyTheme(t);
return clone;
}
/**
* Returns a mask of the configuration parameters for which this gradient
* may change, requiring that it be re-created.
*
* @return a mask of the changing configuration parameters, as defined by
* {@link android.content.pm.ActivityInfo}
*
* @see android.content.pm.ActivityInfo
*/
public int getChangingConfigurations() {
return super.getChangingConfigurations() | mChangingConfigurations;
}
private void applyTheme(Theme t) {
if (mThemeAttrs != null) {
applyRootAttrsTheme(t);
}
if (mItemsThemeAttrs != null) {
applyItemsAttrsTheme(t);
}
onColorsChange();
}
private void applyRootAttrsTheme(Theme t) {
final TypedArray a = t.resolveAttributes(mThemeAttrs, R.styleable.GradientColor);
// mThemeAttrs will be set to null if if there are no theme attributes in the
// typed array.
mThemeAttrs = a.extractThemeAttrs(mThemeAttrs);
// merging the attributes update inside the updateRootElementState().
updateRootElementState(a);
// Account for any configuration changes.
mChangingConfigurations |= a.getChangingConfigurations();
a.recycle();
}
/**
* Returns whether a theme can be applied to this gradient color, which
* usually indicates that the gradient color has unresolved theme
* attributes.
*
* @return whether a theme can be applied to this gradient color.
* @hide only for resource preloading
*/
@Override
public boolean canApplyTheme() {
return mThemeAttrs != null || mItemsThemeAttrs != null;
}
}
| |
/**
* Copyright 2016 Nikita Koksharov
*
* 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.redisson;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentMap;
import org.redisson.api.RCascadeType;
import org.redisson.api.RDeque;
import org.redisson.api.RExpirable;
import org.redisson.api.RExpirableAsync;
import org.redisson.api.RList;
import org.redisson.api.RLiveObject;
import org.redisson.api.RLiveObjectService;
import org.redisson.api.RMap;
import org.redisson.api.RMapAsync;
import org.redisson.api.RObject;
import org.redisson.api.RObjectAsync;
import org.redisson.api.RQueue;
import org.redisson.api.RSet;
import org.redisson.api.RSortedSet;
import org.redisson.api.RedissonClient;
import org.redisson.api.annotation.RCascade;
import org.redisson.api.annotation.REntity;
import org.redisson.api.annotation.RFieldAccessor;
import org.redisson.api.annotation.RId;
import org.redisson.codec.CodecProvider;
import org.redisson.liveobject.LiveObjectTemplate;
import org.redisson.liveobject.core.AccessorInterceptor;
import org.redisson.liveobject.core.FieldAccessorInterceptor;
import org.redisson.liveobject.core.LiveObjectInterceptor;
import org.redisson.liveobject.core.RExpirableInterceptor;
import org.redisson.liveobject.core.RMapInterceptor;
import org.redisson.liveobject.core.RObjectInterceptor;
import org.redisson.liveobject.core.RedissonObjectBuilder;
import org.redisson.liveobject.misc.AdvBeanCopy;
import org.redisson.liveobject.misc.ClassUtils;
import org.redisson.liveobject.misc.Introspectior;
import org.redisson.liveobject.provider.ResolverProvider;
import org.redisson.liveobject.resolver.Resolver;
import jodd.bean.BeanCopy;
import jodd.bean.BeanUtil;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.field.FieldList;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.FieldProxy;
import net.bytebuddy.matcher.ElementMatchers;
public class RedissonLiveObjectService implements RLiveObjectService {
private final ConcurrentMap<Class<?>, Class<?>> classCache;
private final RedissonClient redisson;
private final CodecProvider codecProvider;
private final ResolverProvider resolverProvider;
private final RedissonObjectBuilder objectBuilder;
public RedissonLiveObjectService(RedissonClient redisson, ConcurrentMap<Class<?>, Class<?>> classCache, CodecProvider codecProvider, ResolverProvider resolverProvider) {
this.redisson = redisson;
this.classCache = classCache;
this.codecProvider = codecProvider;
this.resolverProvider = resolverProvider;
this.objectBuilder = new RedissonObjectBuilder(redisson, codecProvider);
}
//TODO: Add ttl renewal functionality
// @Override
// public <T, K> T get(Class<T> entityClass, K id, long timeToLive, TimeUnit timeUnit) {
// T instance = get(entityClass, id);
// RMap map = ((RLiveObject) instance).getLiveObjectLiveMap();
// map.put("RLiveObjectDefaultTimeToLiveValue", timeToLive);
// map.put("RLiveObjectDefaultTimeToLiveUnit", timeUnit.toString());
// map.expire(timeToLive, timeUnit);
// return instance;
// }
public RMap<String, Object> getMap(Object proxied) {
return ClassUtils.getField(proxied, "liveObjectLiveMap");
}
private <T> Object generateId(Class<T> entityClass) throws NoSuchFieldException {
String idFieldName = getRIdFieldName(entityClass);
RId annotation = entityClass
.getDeclaredField(idFieldName)
.getAnnotation(RId.class);
Resolver resolver = resolverProvider.getResolver(entityClass,
annotation.generator(), annotation);
Object id = resolver.resolve(entityClass, annotation, idFieldName, redisson);
return id;
}
@Override
public <T, K> T get(Class<T> entityClass, K id) {
try {
T proxied = instantiateLiveObject(getProxyClass(entityClass), id);
return asLiveObject(proxied).isExists() ? proxied : null;
} catch (Exception ex) {
unregisterClass(entityClass);
throw ex instanceof RuntimeException ? (RuntimeException) ex : new RuntimeException(ex);
}
}
@Override
public <T> T attach(T detachedObject) {
validateDetached(detachedObject);
Class<T> entityClass = (Class<T>) detachedObject.getClass();
try {
String idFieldName = getRIdFieldName(detachedObject.getClass());
Object id = ClassUtils.getField(detachedObject, idFieldName);
Class<? extends T> proxyClass = getProxyClass(entityClass);
return instantiateLiveObject(proxyClass, id);
} catch (Exception ex) {
unregisterClass(entityClass);
throw ex instanceof RuntimeException ? (RuntimeException) ex : new RuntimeException(ex);
}
}
@Override
public <T> T merge(T detachedObject) {
Map<Object, Object> alreadyPersisted = new HashMap<Object, Object>();
return persist(detachedObject, alreadyPersisted, RCascadeType.MERGE);
}
@Override
public <T> T persist(T detachedObject) {
Map<Object, Object> alreadyPersisted = new HashMap<Object, Object>();
return persist(detachedObject, alreadyPersisted, RCascadeType.PERSIST);
}
private <T> T persist(T detachedObject, Map<Object, Object> alreadyPersisted, RCascadeType type) {
String idFieldName = getRIdFieldName(detachedObject.getClass());
Object id = ClassUtils.getField(detachedObject, idFieldName);
if (id == null) {
try {
id = generateId(detachedObject.getClass());
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException(e);
}
ClassUtils.setField(detachedObject, idFieldName, id);
}
T attachedObject = attach(detachedObject);
alreadyPersisted.put(detachedObject, attachedObject);
RMap<String, Object> liveMap = getMap(attachedObject);
List<String> excludedFields = new ArrayList<String>();
excludedFields.add(idFieldName);
boolean fastResult = liveMap.fastPut("redisson_live_object", "1");
if (type == RCascadeType.PERSIST && !fastResult) {
throw new IllegalArgumentException("This REntity already exists.");
}
for (FieldDescription.InDefinedShape field : Introspectior.getFieldsDescription(detachedObject.getClass())) {
Object object = ClassUtils.getField(detachedObject, field.getName());
if (object == null) {
continue;
}
RObject rObject = objectBuilder.createObject(id, detachedObject.getClass(), object.getClass(), field.getName());
if (rObject != null) {
objectBuilder.store(rObject, field.getName(), liveMap);
if (rObject instanceof SortedSet) {
((RSortedSet)rObject).trySetComparator(((SortedSet)object).comparator());
}
if (rObject instanceof Collection) {
for (Object obj : (Collection<Object>)object) {
if (obj != null && obj.getClass().isAnnotationPresent(REntity.class)) {
Object persisted = alreadyPersisted.get(obj);
if (persisted == null) {
if (checkCascade(detachedObject, type, field.getName())) {
persisted = persist(obj, alreadyPersisted, type);
}
}
obj = persisted;
}
((Collection)rObject).add(obj);
}
} else if (rObject instanceof Map) {
Map<Object, Object> rMap = (Map<Object, Object>) rObject;
Map<?, ?> map = (Map<?, ?>)rObject;
for (Entry<?, ?> entry : map.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
if (key != null && key.getClass().isAnnotationPresent(REntity.class)) {
Object persisted = alreadyPersisted.get(key);
if (persisted == null) {
if (checkCascade(detachedObject, type, field.getName())) {
persisted = persist(key, alreadyPersisted, type);
}
}
key = persisted;
}
if (value != null && value.getClass().isAnnotationPresent(REntity.class)) {
Object persisted = alreadyPersisted.get(value);
if (persisted == null) {
if (checkCascade(detachedObject, type, field.getName())) {
persisted = persist(value, alreadyPersisted, type);
}
}
value = persisted;
}
rMap.put(key, value);
}
}
excludedFields.add(field.getName());
} else if (object.getClass().isAnnotationPresent(REntity.class)) {
Object persisted = alreadyPersisted.get(object);
if (persisted == null) {
if (checkCascade(detachedObject, type, field.getName())) {
persisted = persist(object, alreadyPersisted, type);
}
}
excludedFields.add(field.getName());
BeanUtil.pojo.setSimpleProperty(attachedObject, field.getName(), persisted);
} else {
validateAnnotation(detachedObject, field.getName());
}
}
copy(detachedObject, attachedObject, excludedFields);
return attachedObject;
}
private void validateAnnotation(Object instance, String fieldName) {
Class<?> clazz = instance.getClass();
if (isLiveObject(instance)) {
clazz = clazz.getSuperclass();
}
RCascade annotation = ClassUtils.getAnnotation(clazz, fieldName, RCascade.class);
if (annotation != null) {
throw new IllegalArgumentException("RCascade annotation couldn't be defined for non-Redisson object field");
}
}
private <T> boolean checkCascade(Object instance, RCascadeType type, String fieldName) {
Class<?> clazz = instance.getClass();
if (isLiveObject(instance)) {
clazz = clazz.getSuperclass();
}
RCascade annotation = ClassUtils.getAnnotation(clazz, fieldName, RCascade.class);
if (annotation != null && (Arrays.asList(annotation.value()).contains(type)
|| Arrays.asList(annotation.value()).contains(RCascadeType.ALL))) {
return true;
}
return false;
}
@Override
public <T> T detach(T attachedObject) {
Map<String, Object> alreadyDetached = new HashMap<String, Object>();
return detach(attachedObject, alreadyDetached);
}
@SuppressWarnings("unchecked")
private <T> T detach(T attachedObject, Map<String, Object> alreadyDetached) {
validateAttached(attachedObject);
try {
T detached = instantiateDetachedObject((Class<T>) attachedObject.getClass().getSuperclass(), asLiveObject(attachedObject).getLiveObjectId());
BeanCopy.beans(attachedObject, detached).declared(true, true).copy();
alreadyDetached.put(getMap(attachedObject).getName(), detached);
for (Entry<String, Object> obj : getMap(attachedObject).entrySet()) {
if (!checkCascade(attachedObject, RCascadeType.DETACH, obj.getKey())) {
continue;
}
if (obj.getValue() instanceof RSortedSet) {
SortedSet<Object> redissonSet = (SortedSet<Object>) obj.getValue();
Set<Object> set = new TreeSet<Object>(redissonSet.comparator());
for (Object object : redissonSet) {
if (isLiveObject(object)) {
Object detachedObject = alreadyDetached.get(getMap(object).getName());
if (detachedObject == null) {
detachedObject = detach(object, alreadyDetached);
}
object = detachedObject;
}
set.add(object);
}
ClassUtils.setField(detached, obj.getKey(), set);
} else if (obj.getValue() instanceof RDeque) {
Collection<Object> redissonDeque = (Collection<Object>) obj.getValue();
Deque<Object> deque = new LinkedList<Object>();
for (Object object : redissonDeque) {
if (isLiveObject(object)) {
Object detachedObject = alreadyDetached.get(getMap(object).getName());
if (detachedObject == null) {
detachedObject = detach(object, alreadyDetached);
}
object = detachedObject;
}
deque.add(object);
}
ClassUtils.setField(detached, obj.getKey(), deque);
} else if (obj.getValue() instanceof RQueue) {
Collection<Object> redissonQueue = (Collection<Object>) obj.getValue();
Queue<Object> queue = new LinkedList<Object>();
for (Object object : redissonQueue) {
if (isLiveObject(object)) {
Object detachedObject = alreadyDetached.get(getMap(object).getName());
if (detachedObject == null) {
detachedObject = detach(object, alreadyDetached);
}
object = detachedObject;
}
queue.add(object);
}
ClassUtils.setField(detached, obj.getKey(), queue);
} else if (obj.getValue() instanceof RSet) {
Set<Object> set = new HashSet<Object>();
Collection<Object> redissonSet = (Collection<Object>) obj.getValue();
for (Object object : redissonSet) {
if (isLiveObject(object)) {
Object detachedObject = alreadyDetached.get(getMap(object).getName());
if (detachedObject == null) {
detachedObject = detach(object, alreadyDetached);
}
object = detachedObject;
}
set.add(object);
}
ClassUtils.setField(detached, obj.getKey(), set);
} else if (obj.getValue() instanceof RList) {
List<Object> list = new ArrayList<Object>();
Collection<Object> redissonList = (Collection<Object>) obj.getValue();
for (Object object : redissonList) {
if (isLiveObject(object)) {
Object detachedObject = alreadyDetached.get(getMap(object).getName());
if (detachedObject == null) {
detachedObject = detach(object, alreadyDetached);
}
object = detachedObject;
}
list.add(object);
}
ClassUtils.setField(detached, obj.getKey(), list);
} else if (isLiveObject(obj.getValue())) {
Object detachedObject = alreadyDetached.get(getMap(obj.getValue()).getName());
if (detachedObject == null) {
detachedObject = detach(obj.getValue(), alreadyDetached);
}
ClassUtils.setField(detached, obj.getKey(), detachedObject);
} else if (obj.getValue() instanceof RMap) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
Map<Object, Object> redissonMap = (Map<Object, Object>) obj.getValue();
for (Entry<Object, Object> entry : redissonMap.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
if (isLiveObject(key)) {
Object detachedObject = alreadyDetached.get(getMap(key).getName());
if (detachedObject == null) {
detachedObject = detach(key, alreadyDetached);
}
key = detachedObject;
}
if (isLiveObject(value)) {
Object detachedObject = alreadyDetached.get(getMap(value).getName());
if (detachedObject == null) {
detachedObject = detach(value, alreadyDetached);
}
value = detachedObject;
}
map.put(key, value);
}
ClassUtils.setField(detached, obj.getKey(), map);
} else {
validateAnnotation(detached, obj.getKey());
}
}
return detached;
} catch (Exception ex) {
throw ex instanceof RuntimeException ? (RuntimeException) ex : new RuntimeException(ex);
}
}
@Override
public <T> void delete(T attachedObject) {
Set<String> deleted = new HashSet<String>();
delete(attachedObject, deleted);
}
private <T> void delete(T attachedObject, Set<String> deleted) {
validateAttached(attachedObject);
for (Entry<String, Object> obj : getMap(attachedObject).entrySet()) {
if (!checkCascade(attachedObject, RCascadeType.DELETE, obj.getKey())) {
continue;
}
if (obj.getValue() instanceof RSortedSet) {
deleteCollection(deleted, (Iterable<?>)obj.getValue());
((RObject)obj.getValue()).delete();
} else if (obj.getValue() instanceof RDeque) {
deleteCollection(deleted, (Iterable<?>)obj.getValue());
((RObject)obj.getValue()).delete();
} else if (obj.getValue() instanceof RQueue) {
deleteCollection(deleted, (Iterable<?>)obj.getValue());
((RObject)obj.getValue()).delete();
} else if (obj.getValue() instanceof RSet) {
deleteCollection(deleted, (Iterable<?>)obj.getValue());
((RObject)obj.getValue()).delete();
} else if (obj.getValue() instanceof RList) {
deleteCollection(deleted, (Iterable<?>)obj.getValue());
((RObject)obj.getValue()).delete();
} else if (isLiveObject(obj.getValue())) {
if (deleted.add(getMap(obj.getValue()).getName())) {
delete(obj.getValue(), deleted);
}
} else if (obj.getValue() instanceof RMap) {
RMap<Object, Object> map = (RMap<Object, Object>)obj.getValue();
deleteCollection(deleted, map.keySet());
deleteCollection(deleted, map.values());
((RObject)obj.getValue()).delete();
} else {
validateAnnotation(attachedObject, obj.getKey());
}
}
asLiveObject(attachedObject).delete();
}
private void deleteCollection(Set<String> deleted, Iterable<?> objs) {
for (Object object : objs) {
if (isLiveObject(object)) {
if (deleted.add(getMap(object).getName())) {
delete(object, deleted);
}
}
}
}
@Override
public <T, K> void delete(Class<T> entityClass, K id) {
asLiveObject(get(entityClass, id)).delete();
}
@Override
public <T> RLiveObject asLiveObject(T instance) {
return (RLiveObject) instance;
}
@Override
public <T> RExpirable asRExpirable(T instance) {
return (RExpirable) instance;
}
@Override
public <T, K, V> RMap<K, V> asRMap(T instance) {
return (RMap) instance;
}
@Override
public <T> boolean isLiveObject(T instance) {
return instance instanceof RLiveObject;
}
@Override
public <T> boolean isExists(T instance) {
return instance instanceof RLiveObject && asLiveObject(instance).isExists();
}
@Override
public void registerClass(Class cls) {
if (!classCache.containsKey(cls)) {
validateClass(cls);
registerClassInternal(cls);
}
}
@Override
public void unregisterClass(Class cls) {
classCache.remove(cls.isAssignableFrom(RLiveObject.class) ? cls.getSuperclass() : cls);
}
@Override
public boolean isClassRegistered(Class cls) {
return classCache.containsKey(cls) || classCache.containsValue(cls);
}
private <T> void copy(T detachedObject, T attachedObject, List<String> excludedFields) {
new AdvBeanCopy(detachedObject, attachedObject)
.ignoreNulls(true)
.exclude(excludedFields.toArray(new String[excludedFields.size()]))
.copy();
}
private String getRIdFieldName(Class cls) {
return Introspectior.getFieldsWithAnnotation(cls, RId.class)
.getOnly()
.getName();
}
private <T, K> T instantiateLiveObject(Class<T> proxyClass, K id) throws Exception {
if (id == null) {
throw new IllegalStateException("Non-null value is required for the field with RId annotation.");
}
T instance = instantiate(proxyClass, id);
asLiveObject(instance).setLiveObjectId(id);
return instance;
}
private <T, K> T instantiateDetachedObject(Class<T> cls, K id) throws Exception {
T instance = instantiate(cls, id);
String fieldName = getRIdFieldName(cls);
if (ClassUtils.getField(instance, fieldName) == null) {
ClassUtils.setField(instance, fieldName, id);
}
return instance;
}
private <T, K> T instantiate(Class<T> cls, K id) throws Exception {
for (Constructor<?> constructor : cls.getDeclaredConstructors()) {
if (constructor.getParameterTypes().length == 0) {
constructor.setAccessible(true);
return (T) constructor.newInstance();
}
}
throw new IllegalArgumentException("Can't find default constructor for " + cls);
}
private <T> Class<? extends T> getProxyClass(Class<T> entityClass) {
registerClass(entityClass);
return (Class<? extends T>) classCache.get(entityClass);
}
private <T> void validateClass(Class<T> entityClass) {
if (entityClass.isAnonymousClass() || entityClass.isLocalClass()) {
throw new IllegalArgumentException(entityClass.getName() + " is not publically accessable.");
}
if (!entityClass.isAnnotationPresent(REntity.class)) {
throw new IllegalArgumentException("REntity annotation is missing from class type declaration.");
}
FieldList<FieldDescription.InDefinedShape> fieldsWithRIdAnnotation
= Introspectior.getFieldsWithAnnotation(entityClass, RId.class);
if (fieldsWithRIdAnnotation.size() == 0) {
throw new IllegalArgumentException("RId annotation is missing from class field declaration.");
}
if (fieldsWithRIdAnnotation.size() > 1) {
throw new IllegalArgumentException("Only one field with RId annotation is allowed in class field declaration.");
}
FieldDescription.InDefinedShape idFieldDescription = fieldsWithRIdAnnotation.getOnly();
String idFieldName = idFieldDescription.getName();
Field idField = null;
try {
idField = entityClass.getDeclaredField(idFieldName);
} catch (Exception e) {
throw new IllegalStateException(e);
}
if (idField.getType().isAnnotationPresent(REntity.class)) {
throw new IllegalArgumentException("Field with RId annotation cannot be a type of which class is annotated with REntity.");
}
if (idField.getType().isAssignableFrom(RObject.class)) {
throw new IllegalArgumentException("Field with RId annotation cannot be a type of RObject");
}
}
private <T> void validateDetached(T detachedObject) {
if (detachedObject instanceof RLiveObject) {
throw new IllegalArgumentException("The object supplied is already a RLiveObject");
}
}
private <T> void validateAttached(T attachedObject) {
if (!(attachedObject instanceof RLiveObject)) {
throw new IllegalArgumentException("The object supplied is must be a RLiveObject");
}
}
private <T> void registerClassInternal(Class<T> entityClass) {
DynamicType.Builder<T> builder = new ByteBuddy()
.subclass(entityClass);
for (FieldDescription.InDefinedShape field
: Introspectior.getTypeDescription(LiveObjectTemplate.class)
.getDeclaredFields()) {
builder = builder.define(field);
}
Class<? extends T> proxied = builder.method(ElementMatchers.isDeclaredBy(
Introspectior.getTypeDescription(RLiveObject.class))
.and(ElementMatchers.isGetter().or(ElementMatchers.isSetter())
.or(ElementMatchers.named("isPhantom"))
.or(ElementMatchers.named("delete"))))
.intercept(MethodDelegation.withDefaultConfiguration()
.withBinders(FieldProxy.Binder
.install(LiveObjectInterceptor.Getter.class,
LiveObjectInterceptor.Setter.class))
.to(new LiveObjectInterceptor(redisson, codecProvider, entityClass,
getRIdFieldName(entityClass))))
// .intercept(MethodDelegation.to(
// new LiveObjectInterceptor(redisson, codecProvider, entityClass,
// getRIdFieldName(entityClass)))
// .appendParameterBinder(FieldProxy.Binder
// .install(LiveObjectInterceptor.Getter.class,
// LiveObjectInterceptor.Setter.class)))
.implement(RLiveObject.class)
.method(ElementMatchers.isAnnotatedWith(RFieldAccessor.class)
.and(ElementMatchers.named("get")
.or(ElementMatchers.named("set"))))
.intercept(MethodDelegation.to(FieldAccessorInterceptor.class))
.method(ElementMatchers.isDeclaredBy(RObject.class)
.or(ElementMatchers.isDeclaredBy(RObjectAsync.class)))
.intercept(MethodDelegation.to(RObjectInterceptor.class))
.implement(RObject.class)
.method(ElementMatchers.isDeclaredBy(RExpirable.class)
.or(ElementMatchers.isDeclaredBy(RExpirableAsync.class)))
.intercept(MethodDelegation.to(RExpirableInterceptor.class))
.implement(RExpirable.class)
.method(ElementMatchers.isDeclaredBy(Map.class)
.or(ElementMatchers.isDeclaredBy(ConcurrentMap.class))
.or(ElementMatchers.isDeclaredBy(RMapAsync.class))
.or(ElementMatchers.isDeclaredBy(RMap.class)))
.intercept(MethodDelegation.to(RMapInterceptor.class))
.implement(RMap.class)
.method(ElementMatchers.not(ElementMatchers.isDeclaredBy(Object.class))
.and(ElementMatchers.not(ElementMatchers.isDeclaredBy(RLiveObject.class)))
.and(ElementMatchers.not(ElementMatchers.isDeclaredBy(RExpirable.class)))
.and(ElementMatchers.not(ElementMatchers.isDeclaredBy(RExpirableAsync.class)))
.and(ElementMatchers.not(ElementMatchers.isDeclaredBy(RObject.class)))
.and(ElementMatchers.not(ElementMatchers.isDeclaredBy(RObjectAsync.class)))
.and(ElementMatchers.not(ElementMatchers.isDeclaredBy(ConcurrentMap.class)))
.and(ElementMatchers.not(ElementMatchers.isDeclaredBy(Map.class)))
.and(ElementMatchers.isGetter()
.or(ElementMatchers.isSetter()))
.and(ElementMatchers.isPublic()
.or(ElementMatchers.isProtected()))
)
.intercept(MethodDelegation.to(
new AccessorInterceptor(redisson, objectBuilder)))
.make().load(getClass().getClassLoader(),
ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
classCache.putIfAbsent(entityClass, proxied);
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2007-2015 Broad Institute
*
* 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.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.sam;
import org.broad.igv.feature.LocusScore;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.renderer.DataRange;
import org.broad.igv.renderer.SequenceRenderer;
import org.broad.igv.tdf.TDFDataSource;
import org.broad.igv.tdf.TDFReader;
import org.broad.igv.track.*;
import org.broad.igv.ui.panel.IGVPopupMenu;
import org.broad.igv.util.ResourceLocator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Developmental track to explore display of conservation scores.
*
* @author jrobinso
*/
public class EWigTrack extends AbstractTrack {
// double dataMax;
char[] nucleotides = {'A', 'C', 'G', 'T'};
public static Color grey1 = new Color(230, 230, 230);
Map<Character, TDFDataSource> baseSources;
TDFDataSource scoreSource;
public EWigTrack(ResourceLocator locator, Genome genome) {
super(locator);
TDFReader reader = TDFReader.getReader(locator.getPath());
scoreSource = new TDFDataSource(reader, 4, "Pi", genome);
setDataRange(new DataRange(0, 0, 10));
baseSources = new HashMap();
for (int i = 0; i < 4; i++) {
TDFDataSource src = new TDFDataSource(reader, i, Character.toString(nucleotides[i]), genome);
baseSources.put(nucleotides[i], src);
}
}
public void render(RenderContext context, Rectangle rect) {
paint(context, rect);
}
public boolean isLogNormalized() {
return false;
}
public float getRegionScore(String chr, int start, int end, int zoom, RegionScoreType type, String frameName) {
return 0;
}
private void paint(RenderContext context, Rectangle rect) {
// The total score
List<LocusScore> scores = scoreSource.getSummaryScoresForRange(context.getChr(),
(int) context.getOrigin(),
(int) context.getEndLocation(),
context.getZoom());
Map<Character, List<LocusScore>> nScores = new HashMap();
for (Character c : nucleotides) {
nScores.put(c, baseSources.get(c).getSummaryScoresForRange(context.getChr(),
(int) context.getOrigin(),
(int) context.getEndLocation(),
context.getZoom()));
}
Map<Character, Color> nucleotideColors = SequenceRenderer.getNucleotideColors();
for (int idx = 0; idx < scores.size(); idx++) {
LocusScore score = scores.get(idx);
int startPosition = score.getStart();
int endPosition = score.getEnd();
int pX = (int) (rect.getX() + (startPosition - context.getOrigin()) / context.getScale());
int dX = Math.max(1,
(int) (rect.getX() + (endPosition - context.getOrigin()) / context.getScale()) - pX);
if (dX > 4) {
dX -= 2;
pX++;
}
if (pX + dX < 0) {
continue;
} else if (pX > context.getVisibleRect().getMaxX()) {
break;
}
float totalCount = score.getScore();
int pY = (int) rect.getMaxY() - 1;
float dataMax = getDataRange().getMaximum();
double height = (totalCount * rect.getHeight() / dataMax);
height = Math.min(height, rect.height - 1);
for (char c : nucleotides) {
try {
LocusScore ns = nScores.get(c).get(idx);
float count = ns.getScore() * totalCount;
//pY = drawBar(context, idx, rect, dataMax, pY, pX, dX, c, count);
Graphics2D tGraphics = context.getGraphic2DForColor(nucleotideColors.get(c));
int h = (int) Math.round(count * height / totalCount);
h = Math.min(pY - rect.y, h);
int baseY = (int) (pY - h);
if (h > 0) {
tGraphics.fillRect(pX, baseY, dX, h);
}
pY = baseY;
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
// Draw border
context.getGraphic2DForColor(Color.gray).drawLine(
rect.x, rect.y + rect.height,
rect.x + rect.width, rect.y + rect.height);
// Draw scale
/*
DataRange range = getDataRange();
if (range != null) {
Graphics2D g = context.getGraphic2DForColor(Color.black);
Font font = g.getFont();
Font smallFont = FontManager.getScalableFont(8);
try {
g.setFont(smallFont);
String scale = "Scale: " + (int) range.getMinimum() + " - " +
(int) range.getMaximum();
g.drawString(scale, rect.x + 10, rect.y + 10);
} finally {
g.setFont(font);
}
}*/
}
public JPopupMenu getPopupMenu(
final MouseEvent evt) {
JPopupMenu popupMenu = new IGVPopupMenu();
JLabel popupTitle = new JLabel(" " + getName(), JLabel.CENTER);
Font newFont = popupMenu.getFont().deriveFont(Font.BOLD, 12);
popupTitle.setFont(newFont);
if (popupTitle != null) {
popupMenu.add(popupTitle);
}
popupMenu.addSeparator();
// addSortMenuItem(popupMenu);
// addPackMenuItem(popupMenu);
// addShadeBaseMenuItem(popupMenu);
// addCopyToClipboardItem(popupMenu, evt);
// addGoToMate(popupMenu, evt);
// popupMenu.addSeparator();
//JLabel trackSettingsHeading = new JLabel(" Track Settings",
// JLabel.LEFT);
//trackSettingsHeading.setFont(newFont);
//popupMenu.add(trackSettingsHeading);
ArrayList<Track> tmp = new ArrayList();
tmp.add(this);
popupMenu.add(TrackMenuUtils.getTrackRenameItem(tmp));
popupMenu.add(TrackMenuUtils.getChangeTrackHeightItem(tmp));
popupMenu.add(TrackMenuUtils.getDataRangeItem(tmp));
return popupMenu;
}
// public String getValueStringAt(String chr, double position, int y, ReferenceFrame frame) {
// return null;
// }
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.run;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.intellij.execution.DefaultExecutionResult;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.*;
import com.intellij.execution.configurations.GeneralCommandLine.ParentEnvironmentType;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.filters.UrlFilter;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessTerminatedListener;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.facet.Facet;
import com.intellij.facet.FacetManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.SdkAdditionalData;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.libraries.LibraryImpl;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.PersistentLibraryKind;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingProjectManager;
import com.intellij.remote.RemoteProcessHandlerBase;
import com.intellij.util.PlatformUtils;
import com.intellij.util.containers.HashMap;
import com.jetbrains.python.PythonHelpersLocator;
import com.jetbrains.python.console.PyDebugConsoleBuilder;
import com.jetbrains.python.debugger.PyDebugRunner;
import com.jetbrains.python.debugger.PyDebuggerOptionsProvider;
import com.jetbrains.python.facet.LibraryContributingFacet;
import com.jetbrains.python.facet.PythonPathContributingFacet;
import com.jetbrains.python.library.PythonLibraryType;
import com.jetbrains.python.remote.PyRemotePathMapper;
import com.jetbrains.python.sdk.PySdkUtil;
import com.jetbrains.python.sdk.PythonEnvUtil;
import com.jetbrains.python.sdk.PythonSdkAdditionalData;
import com.jetbrains.python.sdk.PythonSdkType;
import com.jetbrains.python.sdk.flavors.JythonSdkFlavor;
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.*;
/**
* @author Leonid Shalupov
*/
public abstract class PythonCommandLineState extends CommandLineState {
// command line has a number of fixed groups of parameters; patchers should only operate on them and not the raw list.
public static final String GROUP_EXE_OPTIONS = "Exe Options";
public static final String GROUP_DEBUGGER = "Debugger";
public static final String GROUP_PROFILER = "Profiler";
public static final String GROUP_SCRIPT = "Script";
private final AbstractPythonRunConfiguration myConfig;
private Boolean myMultiprocessDebug = null;
public boolean isDebug() {
return PyDebugRunner.PY_DEBUG_RUNNER.equals(getEnvironment().getRunner().getRunnerId());
}
public static ServerSocket createServerSocket() throws ExecutionException {
final ServerSocket serverSocket;
try {
//noinspection SocketOpenedButNotSafelyClosed
serverSocket = new ServerSocket(0);
}
catch (IOException e) {
throw new ExecutionException("Failed to find free socket port", e);
}
return serverSocket;
}
public PythonCommandLineState(AbstractPythonRunConfiguration runConfiguration, ExecutionEnvironment env) {
super(env);
myConfig = runConfiguration;
}
@Nullable
public PythonSdkFlavor getSdkFlavor() {
return PythonSdkFlavor.getFlavor(myConfig.getInterpreterPath());
}
public Sdk getSdk() {
return myConfig.getSdk();
}
@NotNull
@Override
public ExecutionResult execute(@NotNull Executor executor, @NotNull ProgramRunner runner) throws ExecutionException {
return execute(executor, (CommandLinePatcher[])null);
}
public ExecutionResult execute(Executor executor, CommandLinePatcher... patchers) throws ExecutionException {
final ProcessHandler processHandler = startProcess(patchers);
final ConsoleView console = createAndAttachConsole(myConfig.getProject(), processHandler, executor);
List<AnAction> actions = Lists.newArrayList(createActions(console, processHandler));
return new DefaultExecutionResult(console, processHandler, actions.toArray(new AnAction[actions.size()]));
}
@NotNull
protected ConsoleView createAndAttachConsole(Project project, ProcessHandler processHandler, Executor executor)
throws ExecutionException {
final ConsoleView consoleView = createConsoleBuilder(project).getConsole();
consoleView.addMessageFilter(new UrlFilter());
addTracebackFilter(project, consoleView, processHandler);
consoleView.attachToProcess(processHandler);
return consoleView;
}
protected void addTracebackFilter(Project project, ConsoleView consoleView, ProcessHandler processHandler) {
if (PySdkUtil.isRemote(myConfig.getSdk())) {
assert processHandler instanceof RemoteProcessHandlerBase;
consoleView
.addMessageFilter(new PyRemoteTracebackFilter(project, myConfig.getWorkingDirectory(), (RemoteProcessHandlerBase)processHandler));
}
else {
consoleView.addMessageFilter(new PythonTracebackFilter(project, myConfig.getWorkingDirectorySafe()));
}
consoleView.addMessageFilter(new UrlFilter()); // Url filter is always nice to have
}
private TextConsoleBuilder createConsoleBuilder(Project project) {
if (isDebug()) {
return new PyDebugConsoleBuilder(project, PythonSdkType.findSdkByPath(myConfig.getInterpreterPath()));
}
else {
return TextConsoleBuilderFactory.getInstance().createBuilder(project);
}
}
@Override
@NotNull
protected ProcessHandler startProcess() throws ExecutionException {
return startProcess(new CommandLinePatcher[]{});
}
/**
* Patches the command line parameters applying patchers from first to last, and then runs it.
*
* @param patchers any number of patchers; any patcher may be null, and the whole argument may be null.
* @return handler of the started process
* @throws ExecutionException
*/
protected ProcessHandler startProcess(CommandLinePatcher... patchers) throws ExecutionException {
GeneralCommandLine commandLine = generateCommandLine(patchers);
// Extend command line
PythonRunConfigurationExtensionsManager.getInstance()
.patchCommandLine(myConfig, getRunnerSettings(), commandLine, getEnvironment().getRunner().getRunnerId());
Sdk sdk = PythonSdkType.findSdkByPath(myConfig.getInterpreterPath());
final ProcessHandler processHandler;
if (PySdkUtil.isRemote(sdk)) {
PyRemotePathMapper pathMapper = createRemotePathMapper();
processHandler = createRemoteProcessStarter().startRemoteProcess(sdk, commandLine, myConfig.getProject(), pathMapper);
}
else {
EncodingEnvironmentUtil.setLocaleEnvironmentIfMac(commandLine);
processHandler = doCreateProcess(commandLine);
ProcessTerminatedListener.attach(processHandler);
}
// attach extensions
PythonRunConfigurationExtensionsManager.getInstance().attachExtensionsToProcess(myConfig, processHandler, getRunnerSettings());
return processHandler;
}
@Nullable
private PyRemotePathMapper createRemotePathMapper() {
if (myConfig.getMappingSettings() == null) {
return null;
} else {
return PyRemotePathMapper.fromSettings(myConfig.getMappingSettings(), PyRemotePathMapper.PyPathMappingType.USER_DEFINED);
}
}
protected PyRemoteProcessStarter createRemoteProcessStarter() {
return new PyRemoteProcessStarter();
}
public GeneralCommandLine generateCommandLine(CommandLinePatcher[] patchers) throws ExecutionException {
GeneralCommandLine commandLine = generateCommandLine();
if (patchers != null) {
for (CommandLinePatcher patcher : patchers) {
if (patcher != null) patcher.patchCommandLine(commandLine);
}
}
return commandLine;
}
protected ProcessHandler doCreateProcess(GeneralCommandLine commandLine) throws ExecutionException {
return PythonProcessRunner.createProcess(commandLine);
}
public GeneralCommandLine generateCommandLine() throws ExecutionException {
GeneralCommandLine commandLine = createCommandLine();
commandLine.withCharset(EncodingProjectManager.getInstance(myConfig.getProject()).getDefaultCharset());
setRunnerPath(commandLine);
// define groups
createStandardGroupsIn(commandLine);
buildCommandLineParameters(commandLine);
initEnvironment(commandLine);
return commandLine;
}
private static GeneralCommandLine createCommandLine() {
return PtyCommandLine.isEnabled() ? new PtyCommandLine() : new GeneralCommandLine();
}
/**
* Creates a number of parameter groups in the command line:
* GROUP_EXE_OPTIONS, GROUP_DEBUGGER, GROUP_SCRIPT.
* These are necessary for command line patchers to work properly.
*
* @param commandLine
*/
public static void createStandardGroupsIn(GeneralCommandLine commandLine) {
ParametersList params = commandLine.getParametersList();
params.addParamsGroup(GROUP_EXE_OPTIONS);
params.addParamsGroup(GROUP_DEBUGGER);
params.addParamsGroup(GROUP_PROFILER);
params.addParamsGroup(GROUP_SCRIPT);
}
protected void initEnvironment(GeneralCommandLine commandLine) {
Map<String, String> env = myConfig.getEnvs();
if (env == null) {
env = new HashMap<String, String>();
}
else {
env = new HashMap<String, String>(env);
}
addPredefinedEnvironmentVariables(env, myConfig.isPassParentEnvs());
addCommonEnvironmentVariables(env);
commandLine.getEnvironment().clear();
commandLine.getEnvironment().putAll(env);
commandLine.withParentEnvironmentType(myConfig.isPassParentEnvs() ? ParentEnvironmentType.SHELL : ParentEnvironmentType.NONE);
buildPythonPath(commandLine, myConfig.isPassParentEnvs());
}
protected static void addCommonEnvironmentVariables(Map<String, String> env) {
PythonEnvUtil.setPythonUnbuffered(env);
env.put("PYCHARM_HOSTED", "1");
}
public void addPredefinedEnvironmentVariables(Map<String, String> envs, boolean passParentEnvs) {
final PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(myConfig.getInterpreterPath());
if (flavor != null) {
flavor.addPredefinedEnvironmentVariables(envs, myConfig.getProject());
}
}
private void buildPythonPath(GeneralCommandLine commandLine, boolean passParentEnvs) {
Sdk pythonSdk = PythonSdkType.findSdkByPath(myConfig.getInterpreterPath());
if (pythonSdk != null) {
List<String> pathList = Lists.newArrayList(getAddedPaths(pythonSdk));
pathList.addAll(collectPythonPath());
initPythonPath(commandLine, passParentEnvs, pathList, myConfig.getInterpreterPath());
}
}
public static void initPythonPath(GeneralCommandLine commandLine,
boolean passParentEnvs,
List<String> pathList,
final String interpreterPath) {
final PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(interpreterPath);
if (flavor != null) {
flavor.initPythonPath(commandLine, pathList);
}
else {
PythonSdkFlavor.initPythonPath(commandLine.getEnvironment(), passParentEnvs, pathList);
}
}
public static List<String> getAddedPaths(Sdk pythonSdk) {
List<String> pathList = new ArrayList<String>();
final SdkAdditionalData sdkAdditionalData = pythonSdk.getSdkAdditionalData();
if (sdkAdditionalData instanceof PythonSdkAdditionalData) {
final Set<VirtualFile> addedPaths = ((PythonSdkAdditionalData)sdkAdditionalData).getAddedPathFiles();
for (VirtualFile file : addedPaths) {
addToPythonPath(file, pathList);
}
}
return pathList;
}
private static void addToPythonPath(VirtualFile file, Collection<String> pathList) {
if (file.getFileSystem() instanceof JarFileSystem) {
final VirtualFile realFile = JarFileSystem.getInstance().getVirtualFileForJar(file);
if (realFile != null) {
addIfNeeded(realFile, pathList);
}
}
else {
addIfNeeded(file, pathList);
}
}
private static void addIfNeeded(@NotNull final VirtualFile file, @NotNull final Collection<String> pathList) {
addIfNeeded(pathList, file.getPath());
}
protected static void addIfNeeded(Collection<String> pathList, String path) {
final Set<String> vals = Sets.newHashSet(pathList);
final String filePath = FileUtil.toSystemDependentName(path);
if (!vals.contains(filePath)) {
pathList.add(filePath);
}
}
protected Collection<String> collectPythonPath() {
final Module module = myConfig.getModule();
Set<String> pythonPath = Sets.newHashSet(collectPythonPath(module, myConfig.shouldAddContentRoots(), myConfig.shouldAddSourceRoots()));
if (isDebug() && getSdkFlavor() instanceof JythonSdkFlavor) { //that fixes Jython problem changing sys.argv on execfile, see PY-8164
pythonPath.add(PythonHelpersLocator.getHelperPath("pycharm"));
pythonPath.add(PythonHelpersLocator.getHelperPath("pydev"));
}
return pythonPath;
}
@NotNull
public static Collection<String> collectPythonPath(@Nullable Module module) {
return collectPythonPath(module, true, true);
}
@NotNull
public static Collection<String> collectPythonPath(@Nullable Module module, boolean addContentRoots,
boolean addSourceRoots) {
Collection<String> pythonPathList = Sets.newLinkedHashSet();
if (module != null) {
Set<Module> dependencies = new HashSet<Module>();
ModuleUtilCore.getDependencies(module, dependencies);
if (addContentRoots) {
addRoots(pythonPathList, ModuleRootManager.getInstance(module).getContentRoots());
for (Module dependency : dependencies) {
addRoots(pythonPathList, ModuleRootManager.getInstance(dependency).getContentRoots());
}
}
if (addSourceRoots) {
addRoots(pythonPathList, ModuleRootManager.getInstance(module).getSourceRoots());
for (Module dependency : dependencies) {
addRoots(pythonPathList, ModuleRootManager.getInstance(dependency).getSourceRoots());
}
}
addLibrariesFromModule(module, pythonPathList);
addRootsFromModule(module, pythonPathList);
for (Module dependency : dependencies) {
addLibrariesFromModule(dependency, pythonPathList);
addRootsFromModule(dependency, pythonPathList);
}
}
return pythonPathList;
}
private static void addLibrariesFromModule(Module module, Collection<String> list) {
final OrderEntry[] entries = ModuleRootManager.getInstance(module).getOrderEntries();
for (OrderEntry entry : entries) {
if (entry instanceof LibraryOrderEntry) {
final String name = ((LibraryOrderEntry)entry).getLibraryName();
if (name != null && name.endsWith(LibraryContributingFacet.PYTHON_FACET_LIBRARY_NAME_SUFFIX)) {
// skip libraries from Python facet
continue;
}
for (VirtualFile root : ((LibraryOrderEntry)entry).getRootFiles(OrderRootType.CLASSES)) {
final Library library = ((LibraryOrderEntry)entry).getLibrary();
if (!PlatformUtils.isPyCharm()) {
addToPythonPath(root, list);
}
else if (library instanceof LibraryImpl) {
final PersistentLibraryKind<?> kind = ((LibraryImpl)library).getKind();
if (kind == PythonLibraryType.getInstance().getKind()) {
addToPythonPath(root, list);
}
}
}
}
}
}
private static void addRootsFromModule(Module module, Collection<String> pythonPathList) {
// for Jython
final CompilerModuleExtension extension = CompilerModuleExtension.getInstance(module);
if (extension != null) {
final VirtualFile path = extension.getCompilerOutputPath();
if (path != null) {
pythonPathList.add(path.getPath());
}
final VirtualFile pathForTests = extension.getCompilerOutputPathForTests();
if (pathForTests != null) {
pythonPathList.add(pathForTests.getPath());
}
}
//additional paths from facets (f.e. buildout)
final Facet[] facets = FacetManager.getInstance(module).getAllFacets();
for (Facet facet : facets) {
if (facet instanceof PythonPathContributingFacet) {
List<String> more_paths = ((PythonPathContributingFacet)facet).getAdditionalPythonPath();
if (more_paths != null) pythonPathList.addAll(more_paths);
}
}
}
private static void addRoots(Collection<String> pythonPathList, VirtualFile[] roots) {
for (VirtualFile root : roots) {
addToPythonPath(root, pythonPathList);
}
}
protected void setRunnerPath(GeneralCommandLine commandLine) throws ExecutionException {
String interpreterPath = getInterpreterPath();
commandLine.setExePath(FileUtil.toSystemDependentName(interpreterPath));
}
protected String getInterpreterPath() throws ExecutionException {
String interpreterPath = myConfig.getInterpreterPath();
if (interpreterPath == null) {
throw new ExecutionException("Cannot find Python interpreter for this run configuration");
}
return interpreterPath;
}
protected void buildCommandLineParameters(GeneralCommandLine commandLine) {
}
public boolean isMultiprocessDebug() {
if (myMultiprocessDebug != null) {
return myMultiprocessDebug;
}
else {
return PyDebuggerOptionsProvider.getInstance(myConfig.getProject()).isAttachToSubprocess();
}
}
public void setMultiprocessDebug(boolean multiprocessDebug) {
myMultiprocessDebug = multiprocessDebug;
}
}
| |
/*
* Copyright 2016-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.lua;
import com.facebook.buck.cxx.AbstractCxxLibrary;
import com.facebook.buck.cxx.CxxBuckConfig;
import com.facebook.buck.cxx.CxxLink;
import com.facebook.buck.cxx.CxxLinkableEnhancer;
import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.CxxPreprocessAndCompile;
import com.facebook.buck.cxx.CxxPreprocessables;
import com.facebook.buck.cxx.CxxPreprocessorDep;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.CxxSource;
import com.facebook.buck.cxx.CxxSourceRuleFactory;
import com.facebook.buck.cxx.HeaderVisibility;
import com.facebook.buck.cxx.Linker;
import com.facebook.buck.cxx.Linkers;
import com.facebook.buck.cxx.NativeLinkTarget;
import com.facebook.buck.cxx.NativeLinkTargetMode;
import com.facebook.buck.cxx.NativeLinkable;
import com.facebook.buck.cxx.NativeLinkableInput;
import com.facebook.buck.file.WriteFile;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.ImmutableFlavor;
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.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.WriteStringTemplateRule;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.util.Escaper;
import com.facebook.buck.util.immutables.BuckStyleTuple;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.base.Suppliers;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.io.Resources;
import org.immutables.value.Value;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
/**
* {@link Starter} implementation which builds a starter as a native executable.
*/
@Value.Immutable
@BuckStyleTuple
abstract class AbstractNativeExecutableStarter implements Starter, NativeLinkTarget {
private static final String NATIVE_STARTER_CXX_SOURCE =
"com/facebook/buck/lua/native-starter.cpp.in";
abstract BuildRuleParams getBaseParams();
abstract BuildRuleResolver getRuleResolver();
abstract SourcePathResolver getPathResolver();
abstract SourcePathRuleFinder getRuleFinder();
abstract LuaConfig getLuaConfig();
abstract CxxBuckConfig getCxxBuckConfig();
abstract CxxPlatform getCxxPlatform();
abstract BuildTarget getTarget();
abstract Path getOutput();
abstract String getMainModule();
abstract Optional<BuildTarget> getNativeStarterLibrary();
abstract Optional<Path> getRelativeModulesDir();
abstract Optional<Path> getRelativePythonModulesDir();
abstract Optional<Path> getRelativeNativeLibsDir();
private String getNativeStarterCxxSourceTemplate() {
try {
return Resources.toString(Resources.getResource(NATIVE_STARTER_CXX_SOURCE), Charsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private CxxSource getNativeStarterCxxSource() {
BuildTarget target =
BuildTarget.builder(getBaseParams().getBuildTarget())
.addFlavors(ImmutableFlavor.of("native-starter-cxx-source"))
.build();
BuildRule rule;
Optional<BuildRule> maybeRule = getRuleResolver().getRuleOptional(target);
if (maybeRule.isPresent()) {
rule = maybeRule.get();
} else {
BuildTarget templateTarget =
BuildTarget.builder(getBaseParams().getBuildTarget())
.addFlavors(ImmutableFlavor.of("native-starter-cxx-source-template"))
.build();
WriteFile templateRule = getRuleResolver().addToIndex(
new WriteFile(
getBaseParams()
.withBuildTarget(templateTarget)
.copyReplacingDeclaredAndExtraDeps(
Suppliers.ofInstance(ImmutableSortedSet.of()),
Suppliers.ofInstance(ImmutableSortedSet.of())),
getNativeStarterCxxSourceTemplate(),
BuildTargets.getGenPath(
getBaseParams().getProjectFilesystem(),
templateTarget,
"%s/native-starter.cpp.in"),
/* executable */ false));
Path output =
BuildTargets.getGenPath(
getBaseParams().getProjectFilesystem(),
target,
"%s/native-starter.cpp");
rule = getRuleResolver().addToIndex(
WriteStringTemplateRule.from(
getBaseParams(),
getRuleFinder(),
target,
output,
templateRule.getSourcePathToOutput(),
ImmutableMap.of(
"MAIN_MODULE",
Escaper.escapeAsPythonString(getMainModule()),
"MODULES_DIR",
getRelativeModulesDir().isPresent() ?
Escaper.escapeAsPythonString(getRelativeModulesDir().get().toString()) :
"NULL",
"PY_MODULES_DIR",
getRelativePythonModulesDir().isPresent() ?
Escaper.escapeAsPythonString(getRelativePythonModulesDir().get().toString()) :
"NULL",
"EXT_SUFFIX",
Escaper.escapeAsPythonString(getCxxPlatform().getSharedLibraryExtension())),
/* executable */ false));
}
return CxxSource.of(
CxxSource.Type.CXX,
Preconditions.checkNotNull(rule.getSourcePathToOutput()),
ImmutableList.of());
}
private ImmutableList<CxxPreprocessorInput> getTransitiveCxxPreprocessorInput(
CxxPlatform cxxPlatform,
Iterable<? extends CxxPreprocessorDep> deps)
throws NoSuchBuildTargetException {
ImmutableList.Builder<CxxPreprocessorInput> inputs = ImmutableList.builder();
inputs.addAll(
CxxPreprocessables.getTransitiveCxxPreprocessorInput(
cxxPlatform,
FluentIterable.from(deps)
.filter(BuildRule.class)));
for (CxxPreprocessorDep dep :
Iterables.filter(deps, Predicates.not(BuildRule.class::isInstance))) {
inputs.add(dep.getCxxPreprocessorInput(cxxPlatform, HeaderVisibility.PUBLIC));
}
return inputs.build();
}
public Iterable<? extends AbstractCxxLibrary> getNativeStarterDeps() {
return ImmutableList.of(
getNativeStarterLibrary().isPresent() ?
getRuleResolver().getRuleWithType(
getNativeStarterLibrary().get(),
AbstractCxxLibrary.class) :
getLuaConfig().getLuaCxxLibrary(getRuleResolver()));
}
private NativeLinkableInput getNativeLinkableInput() throws NoSuchBuildTargetException {
Iterable<? extends AbstractCxxLibrary> nativeStarterDeps = getNativeStarterDeps();
ImmutableMap<CxxPreprocessAndCompile, SourcePath> objects =
CxxSourceRuleFactory.requirePreprocessAndCompileRules(
getBaseParams(),
getRuleResolver(),
getPathResolver(),
getRuleFinder(),
getCxxBuckConfig(),
getCxxPlatform(),
ImmutableList.<CxxPreprocessorInput>builder()
.add(
CxxPreprocessorInput.builder()
.putAllPreprocessorFlags(
CxxSource.Type.CXX,
getNativeStarterLibrary().isPresent() ?
ImmutableList.of() :
ImmutableList.of("-DBUILTIN_NATIVE_STARTER"))
.build())
.addAll(getTransitiveCxxPreprocessorInput(getCxxPlatform(), nativeStarterDeps))
.build(),
ImmutableMultimap.of(),
Optional.empty(),
Optional.empty(),
ImmutableMap.of("native-starter.cpp", getNativeStarterCxxSource()),
CxxSourceRuleFactory.PicType.PDC,
Optional.empty());
return NativeLinkableInput.builder()
.addAllArgs(
getRelativeNativeLibsDir().isPresent() ?
StringArg.from(
Linkers.iXlinker(
"-rpath",
String.format(
"%s/%s",
getCxxPlatform().getLd().resolve(getRuleResolver()).origin(),
getRelativeNativeLibsDir().get().toString()))) :
ImmutableList.of())
.addAllArgs(SourcePathArg.from(objects.values()))
.build();
}
@Override
public SourcePath build() throws NoSuchBuildTargetException {
BuildTarget linkTarget = getTarget();
CxxLink linkRule = getRuleResolver().addToIndex(
CxxLinkableEnhancer.createCxxLinkableBuildRule(
getCxxBuckConfig(),
getCxxPlatform(),
getBaseParams(),
getRuleResolver(),
getPathResolver(),
getRuleFinder(),
linkTarget,
Linker.LinkType.EXECUTABLE,
Optional.empty(),
getOutput(),
Linker.LinkableDepType.SHARED,
getNativeStarterDeps(),
Optional.empty(),
Optional.empty(),
ImmutableSet.of(),
getNativeLinkableInput()));
return linkRule.getSourcePathToOutput();
}
@Override
public BuildTarget getBuildTarget() {
return getBaseParams().getBuildTarget();
}
@Override
public NativeLinkTargetMode getNativeLinkTargetMode(CxxPlatform cxxPlatform) {
return NativeLinkTargetMode.executable();
}
@Override
public Iterable<? extends NativeLinkable> getNativeLinkTargetDeps(CxxPlatform cxxPlatform) {
return getNativeStarterDeps();
}
@Override
public NativeLinkableInput getNativeLinkTargetInput(CxxPlatform cxxPlatform)
throws NoSuchBuildTargetException {
return getNativeLinkableInput();
}
@Override
public Optional<Path> getNativeLinkTargetOutputPath(CxxPlatform cxxPlatform) {
return Optional.of(getOutput());
}
}
| |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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.graphhopper;
import com.graphhopper.routing.util.HintsMap;
import com.graphhopper.util.Helper;
import com.graphhopper.util.shapes.GHPoint;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
* GraphHopper request wrapper to simplify requesting GraphHopper.
*
* @author Peter Karich
* @author ratrun
*/
public class GHRequest {
private final List<GHPoint> points;
private final HintsMap hints = new HintsMap();
// List of favored start (1st element) and arrival heading (all other).
// Headings are north based azimuth (clockwise) in (0, 360) or NaN for equal preference
private final List<Double> favoredHeadings;
private List<String> pointHints = new ArrayList<>();
private List<String> pathDetails = new ArrayList<>();
private String algo = "";
private boolean possibleToAdd = false;
private Locale locale = Locale.US;
public GHRequest() {
this(5);
}
public GHRequest(int size) {
points = new ArrayList<GHPoint>(size);
favoredHeadings = new ArrayList<Double>(size);
possibleToAdd = true;
}
/**
* Set routing request from specified startPlace (fromLat, fromLon) to endPlace (toLat, toLon)
* with a preferred start and end heading. Headings are north based azimuth (clockwise) in (0,
* 360) or NaN for equal preference.
*/
public GHRequest(double fromLat, double fromLon, double toLat, double toLon,
double startHeading, double endHeading) {
this(new GHPoint(fromLat, fromLon), new GHPoint(toLat, toLon), startHeading, endHeading);
}
/**
* Set routing request from specified startPlace (fromLat, fromLon) to endPlace (toLat, toLon)
*/
public GHRequest(double fromLat, double fromLon, double toLat, double toLon) {
this(new GHPoint(fromLat, fromLon), new GHPoint(toLat, toLon));
}
/**
* Set routing request from specified startPlace to endPlace with a preferred start and end
* heading. Headings are north based azimuth (clockwise) in (0, 360) or NaN for equal preference
*/
public GHRequest(GHPoint startPlace, GHPoint endPlace, double startHeading, double endHeading) {
if (startPlace == null)
throw new IllegalStateException("'from' cannot be null");
if (endPlace == null)
throw new IllegalStateException("'to' cannot be null");
points = new ArrayList<GHPoint>(2);
points.add(startPlace);
points.add(endPlace);
favoredHeadings = new ArrayList<Double>(2);
validateAzimuthValue(startHeading);
favoredHeadings.add(startHeading);
validateAzimuthValue(endHeading);
favoredHeadings.add(endHeading);
}
public GHRequest(GHPoint startPlace, GHPoint endPlace) {
this(startPlace, endPlace, Double.NaN, Double.NaN);
}
/**
* Set routing request
* <p>
*
* @param points List of stopover points in order: start, 1st stop, 2nd stop, ..., end
* @param favoredHeadings List of favored headings for starting (start point) and arrival (via
* and end points) Headings are north based azimuth (clockwise) in (0, 360) or NaN for equal
*/
public GHRequest(List<GHPoint> points, List<Double> favoredHeadings) {
if (points.size() != favoredHeadings.size())
throw new IllegalArgumentException("Size of headings (" + favoredHeadings.size()
+ ") must match size of points (" + points.size() + ")");
for (Double heading : favoredHeadings) {
validateAzimuthValue(heading);
}
this.points = points;
this.favoredHeadings = favoredHeadings;
}
/**
* Set routing request
* <p>
*
* @param points List of stopover points in order: start, 1st stop, 2nd stop, ..., end
*/
public GHRequest(List<GHPoint> points) {
this(points, Collections.nCopies(points.size(), Double.NaN));
}
/**
* Add stopover point to routing request.
* <p>
*
* @param point geographical position (see GHPoint)
* @param favoredHeading north based azimuth (clockwise) in (0, 360) or NaN for equal preference
*/
public GHRequest addPoint(GHPoint point, double favoredHeading) {
if (point == null)
throw new IllegalArgumentException("point cannot be null");
if (!possibleToAdd)
throw new IllegalStateException("Please call empty constructor if you intent to use "
+ "more than two places via addPoint method.");
points.add(point);
validateAzimuthValue(favoredHeading);
favoredHeadings.add(favoredHeading);
return this;
}
/**
* Add stopover point to routing request.
* <p>
*
* @param point geographical position (see GHPoint)
*/
public GHRequest addPoint(GHPoint point) {
addPoint(point, Double.NaN);
return this;
}
/**
* @return north based azimuth (clockwise) in (0, 360) or NaN for equal preference
*/
public double getFavoredHeading(int i) {
return favoredHeadings.get(i);
}
/**
* @return if there exist a preferred heading for start/via/end point i
*/
public boolean hasFavoredHeading(int i) {
if (i >= favoredHeadings.size())
return false;
return !Double.isNaN(favoredHeadings.get(i));
}
private void validateAzimuthValue(double heading) {
// heading must be in (0, 360) oder NaN
if (!Double.isNaN(heading) && (Double.compare(heading, 360) > 0 || Double.compare(heading, 0) < 0))
throw new IllegalArgumentException("Heading " + heading + " must be in range (0,360) or NaN");
}
public List<GHPoint> getPoints() {
return points;
}
public String getAlgorithm() {
return algo;
}
/**
* For possible values see AlgorithmOptions.*
*/
public GHRequest setAlgorithm(String algo) {
if (algo != null)
this.algo = Helper.camelCaseToUnderScore(algo);
return this;
}
public Locale getLocale() {
return locale;
}
public GHRequest setLocale(Locale locale) {
if (locale != null)
this.locale = locale;
return this;
}
public GHRequest setLocale(String localeStr) {
return setLocale(Helper.getLocale(localeStr));
}
public String getWeighting() {
return hints.getWeighting();
}
/**
* By default it supports fastest and shortest. Or specify empty to use default.
*/
public GHRequest setWeighting(String w) {
hints.setWeighting(w);
return this;
}
public String getVehicle() {
return hints.getVehicle();
}
/**
* Specify car, bike or foot. Or specify empty to use default.
*/
public GHRequest setVehicle(String vehicle) {
hints.setVehicle(vehicle);
return this;
}
public HintsMap getHints() {
return hints;
}
public GHRequest setPointHints(List<String> pointHints) {
this.pointHints = pointHints;
return this;
}
public List<String> getPointHints() {
return pointHints;
}
public boolean hasPointHints() {
return pointHints.size() == points.size();
}
public GHRequest setPathDetails(List<String> pathDetails) {
this.pathDetails = pathDetails;
return this;
}
public List<String> getPathDetails() {
return this.pathDetails;
}
@Override
public String toString() {
String res = "";
for (GHPoint point : points) {
if (res.isEmpty()) {
res = point.toString();
} else {
res += "; " + point.toString();
}
}
if (!algo.isEmpty())
res += " (" + algo + ")";
if (!pathDetails.isEmpty())
res += " (PathDetails: " + pathDetails + ")";
if (!hints.isEmpty())
res += " (Hints:" + hints + ")";
return res;
}
}
| |
/**
* Copyright (C) 2015 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 io.fabric8.kubernetes.api.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.fabric8.kubernetes.api.Pluralize;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Kind;
import io.fabric8.kubernetes.model.annotation.Plural;
import io.fabric8.kubernetes.model.annotation.Singular;
import io.fabric8.kubernetes.model.annotation.Version;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Represents any {@link KubernetesResource} which possesses a {@link ObjectMeta} and is associated with a kind and API version.
*/
public interface HasMetadata extends KubernetesResource {
String DNS_LABEL_START = "(?!-)[A-Za-z0-9-]{";
String DNS_LABEL_END = ",63}(?<!-)";
String DNS_LABEL_REGEXP = DNS_LABEL_START + 1 + DNS_LABEL_END;
/**
* Pattern that checks the format of finalizer identifiers, which should be in {@code <domain name>/<finalizer name>} format.
*/
Pattern FINALIZER_NAME_MATCHER = Pattern.compile(
"^((" + DNS_LABEL_REGEXP + "\\.)+" + DNS_LABEL_START + 2 + DNS_LABEL_END + ")/"
+ DNS_LABEL_REGEXP);
ObjectMeta getMetadata();
void setMetadata(ObjectMeta metadata);
/**
* Retrieves the kind associated with the specified HasMetadata implementation. If the implementation is annotated with
* {@link Kind}, the annotation value will be used, otherwise the value will be derived from the class name.
*
* @param clazz the HasMetadata implementation whose Kind we want to retrieve
* @return the kind associated with the specified HasMetadata
*/
static String getKind(Class<?> clazz) {
final Kind kind = clazz.getAnnotation(Kind.class);
return kind != null ? kind.value() : clazz.getSimpleName();
}
default String getKind() {
return getKind(getClass());
}
/**
* Computes the {@code apiVersion} associated with this HasMetadata implementation. The value is derived from the
* {@link Group} and {@link Version} annotations.
*
* @param clazz the HasMetadata whose {@code apiVersion} we want to compute
* @return the computed {@code apiVersion} or {@code null} if neither {@link Group} or {@link Version} annotations are present
* @throws IllegalArgumentException if only one of {@link Group} or {@link Version} is provided
*/
static String getApiVersion(Class<?> clazz) {
final String group = getGroup(clazz);
final String version = getVersion(clazz);
if (group != null && version != null) {
return group + "/" + version;
}
if (group != null || version != null) {
throw new IllegalArgumentException(
"You need to specify both @" + Group.class.getSimpleName() + " and @"
+ Version.class.getSimpleName() + " annotations if you specify either");
}
return null;
}
/**
* Retrieves the group associated with the specified HasMetadata as defined by the {@link Group} annotation.
*
* @param clazz the HasMetadata whose group we want to retrieve
* @return the associated group or {@code null} if the HasMetadata is not annotated with {@link Group}
*/
static String getGroup(Class<?> clazz) {
final Group group = clazz.getAnnotation(Group.class);
return group != null ? group.value() : null;
}
/**
* Retrieves the version associated with the specified HasMetadata as defined by the {@link Version} annotation.
*
* @param clazz the HasMetadata whose version we want to retrieve
* @return the associated version or {@code null} if the HasMetadata is not annotated with {@link Version}
*/
static String getVersion(Class<?> clazz) {
final Version version = clazz.getAnnotation(Version.class);
return version != null ? version.value() : null;
}
default String getApiVersion() {
return getApiVersion(getClass());
}
void setApiVersion(String version);
/**
* Retrieves the plural form associated with the specified class if annotated with {@link
* Plural} or computes a default value using the value returned by {@link #getSingular(Class)} as
* input to {@link Pluralize#toPlural(String)}.
*
* @param clazz the CustomResource whose plural form we want to retrieve
* @return the plural form defined by the {@link Plural} annotation or a computed default value
*/
static String getPlural(Class<?> clazz) {
final Plural fromAnnotation = clazz.getAnnotation(Plural.class);
return (fromAnnotation != null ? fromAnnotation.value().toLowerCase(Locale.ROOT)
: Pluralize.toPlural(getSingular(clazz)));
}
@JsonIgnore
default String getPlural() {
return getPlural(getClass());
}
/**
* Retrieves the singular form associated with the specified class as defined by the
* {@link Singular} annotation or computes a default value (lower-cased version of the value
* returned by {@link HasMetadata#getKind(Class)}) if the annotation is not present.
*
* @param clazz the class whose singular form we want to retrieve
* @return the singular form defined by the {@link Singular} annotation or a computed default
* value
*/
static String getSingular(Class<?> clazz) {
final Singular fromAnnotation = clazz.getAnnotation(Singular.class);
return (fromAnnotation != null ? fromAnnotation.value() : HasMetadata.getKind(clazz))
.toLowerCase(Locale.ROOT);
}
@JsonIgnore
default String getSingular() {
return getSingular(getClass());
}
static String getFullResourceName(Class<?> clazz) {
return getFullResourceName(getPlural(clazz), getGroup(clazz));
}
static String getFullResourceName(String plural, String group) {
Objects.requireNonNull(plural);
Objects.requireNonNull(group);
return group.isEmpty() ? plural : plural + "." + group;
}
@JsonIgnore
default String getFullResourceName() {
return getFullResourceName(getClass());
}
/**
* Determines whether this {@code HasMetadata} is marked for deletion or not.
*
* @return {@code true} if the cluster marked this {@code HasMetadata} for deletion, {@code false} otherwise
*/
@JsonIgnore
default boolean isMarkedForDeletion() {
final String deletionTimestamp = optionalMetadata().map(ObjectMeta::getDeletionTimestamp)
.orElse(null);
return deletionTimestamp != null && !deletionTimestamp.isEmpty();
}
/**
* Determines whether this {@code HasMetadata} holds the specified finalizer.
*
* @param finalizer the identifier of the finalizer we want to check
* @return {@code true} if this {@code HasMetadata} holds the specified finalizer, {@code false} otherwise
*/
default boolean hasFinalizer(String finalizer) {
return getFinalizers().contains(finalizer);
}
@JsonIgnore
default List<String> getFinalizers() {
return optionalMetadata().map(ObjectMeta::getFinalizers).orElse(Collections.emptyList());
}
/**
* Adds the specified finalizer to this {@code HasMetadata} if it's valid. See {@link #isFinalizerValid(String)}.
*
* @param finalizer the identifier of the finalizer to add to this {@code HasMetadata} in {@code <domain name>/<finalizer name>} format.
* @return {@code true} if the finalizer was successfully added, {@code false} otherwise (in particular, if the object is marked for deletion)
* @throws IllegalArgumentException if the specified finalizer identifier is null or is invalid
*/
default boolean addFinalizer(String finalizer) {
if (finalizer == null || finalizer.trim().isEmpty()) {
throw new IllegalArgumentException("Must pass a non-null, non-blank finalizer.");
}
if (isMarkedForDeletion() || hasFinalizer(finalizer)) {
return false;
}
if (isFinalizerValid(finalizer)) {
ObjectMeta metadata = getMetadata();
if (metadata == null) {
metadata = new ObjectMeta();
setMetadata(metadata);
}
return metadata.getFinalizers().add(finalizer);
} else {
throw new IllegalArgumentException("Invalid finalizer name: '" + finalizer
+ "'. Must consist of a domain name, a forward slash and the valid kubernetes name.");
}
}
/**
* Determines whether the specified finalizer is valid according to the
* <a href='https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#finalizers'>finalizer
* specification</a>.
*
* @param finalizer the identifier of the finalizer which validity we want to check
* @return {@code true} if the identifier is valid, {@code false} otherwise
*/
static boolean validateFinalizer(String finalizer) {
if (finalizer == null) {
return false;
}
final Matcher matcher = FINALIZER_NAME_MATCHER.matcher(finalizer);
if (matcher.matches()) {
final String group = matcher.group(1);
return group.length() < 256;
} else {
return false;
}
}
/**
* @see HasMetadata#validateFinalizer(String)
*
* @param finalizer the identifier of the finalizer which validity we want to check
* @return {@code true} if the identifier is valid, {@code false} otherwise
*/
default boolean isFinalizerValid(String finalizer) {
return HasMetadata.validateFinalizer(finalizer);
}
/**
* Removes the specified finalizer if it's held by this {@code HasMetadata}.
*
* @param finalizer the identifier of the finalizer we want to remove
* @return {@code true} if the finalizer was successfully removed, {@code false} otherwise
*/
default boolean removeFinalizer(String finalizer) {
final List<String> finalizers = getFinalizers();
return finalizers.contains(finalizer) && finalizers.remove(finalizer);
}
/**
* Checks whether the provided {@code HasMetadata} is defined as an owner for this {@code HasMetadata}.
*
* @param owner the {@code HasMetadata} to check for potential ownership
* @return {@code true} if the provided {@code HasMetadata} is an owner of this instance
*/
default boolean hasOwnerReferenceFor(HasMetadata owner) {
return getOwnerReferenceFor(owner).isPresent();
}
/**
* Checks whether the provided UID identifies an owner for this {@code HasMetadata}.
*
* @param ownerUid the UID of a {@code HasMetadata} to check for potential ownership
* @return {@code true} if the provided {@code HasMetadata} is an owner of this instance
*/
default boolean hasOwnerReferenceFor(String ownerUid) {
return getOwnerReferenceFor(ownerUid).isPresent();
}
/**
* Retrieves the {@link OwnerReference} associated with the specified owner if it's part of this {@code HasMetadata}'s owners.
*
* @param owner the potential owner of which we want to retrieve the associated {@link OwnerReference}
* @return an {@link Optional} containing the {@link OwnerReference} associated with the specified owner if it exists or {@link Optional#empty()} otherwise.
*/
default Optional<OwnerReference> getOwnerReferenceFor(HasMetadata owner) {
if (owner == null) {
return Optional.empty();
}
final String ownerUID = owner.optionalMetadata().map(ObjectMeta::getUid).orElse(null);
return getOwnerReferenceFor(ownerUID);
}
/**
* Retrieves the {@link OwnerReference} associated with the owner identified by the specified UID if it's part of this{@code HasMetadata}'s owners.
*
* @param ownerUid the UID of the potential owner of which we want to retrieve the associated {@link
* OwnerReference}
* @return an {@link Optional} containing the {@link OwnerReference} associated with the
* owner identified by the specified UID if it exists or {@link Optional#empty()} otherwise.
*/
default Optional<OwnerReference> getOwnerReferenceFor(String ownerUid) {
if (ownerUid == null || ownerUid.isEmpty()) {
return Optional.empty();
}
return optionalMetadata()
.map(m -> Optional.ofNullable(m.getOwnerReferences()).orElse(Collections.emptyList()))
.orElse(Collections.emptyList())
.stream()
.filter(o -> ownerUid.equals(o.getUid()))
.findFirst();
}
/**
* Adds an {@link OwnerReference} to the specified owner if possible.
*
* @param owner the owner to add a reference to
* @return the newly added {@link OwnerReference}
*/
default OwnerReference addOwnerReference(HasMetadata owner) {
if (owner == null) {
throw new IllegalArgumentException("Cannot add a reference to a null owner to "
+ optionalMetadata().map(m -> "'" + m.getName() + "' ").orElse("unnamed ")
+ getKind());
}
final ObjectMeta metadata = owner.getMetadata();
if (metadata == null) {
throw new IllegalArgumentException("Cannot add a reference to an owner without metadata to "
+ optionalMetadata().map(m -> "'" + m.getName() + "' ").orElse("unnamed ")
+ getKind());
}
final OwnerReference ownerReference = new OwnerReferenceBuilder()
.withUid(metadata.getUid())
.withApiVersion(owner.getApiVersion())
.withName(metadata.getName())
.withKind(owner.getKind())
.build();
return addOwnerReference(sanitizeAndValidate(ownerReference));
}
/**
* Adds the specified, supposed valid (for example because validated by calling {@link #sanitizeAndValidate(OwnerReference)} beforehand), {@link OwnerReference} to this {@code HasMetadata}
* @param ownerReference the {@link OwnerReference} to add to this {@code HasMetadata}'s owner references
* @return the newly added {@link OwnerReference}
*/
default OwnerReference addOwnerReference(OwnerReference ownerReference) {
if (ownerReference == null) {
throw new IllegalArgumentException("Cannot add a null reference to "
+ optionalMetadata().map(m -> "'" + m.getName() + "' ").orElse("unnamed ")
+ getKind());
}
final Optional<OwnerReference> existing = getOwnerReferenceFor(ownerReference.getUid());
if (existing.isPresent()) {
return existing.get();
}
ObjectMeta metadata = getMetadata();
if (metadata == null) {
metadata = new ObjectMeta();
setMetadata(metadata);
}
List<OwnerReference> ownerReferences = metadata.getOwnerReferences();
if (ownerReferences == null) {
ownerReferences = new ArrayList<>();
metadata.setOwnerReferences(ownerReferences);
}
ownerReferences.add(ownerReference);
return ownerReference;
}
/**
* Sanitizes and validates the specified {@link OwnerReference}, presumably to add it
* @param ownerReference the {@link OwnerReference} to sanitize and validate
* @return the sanitized and validated {@link OwnerReference} which should be used instead of the original one
*/
static OwnerReference sanitizeAndValidate(OwnerReference ownerReference) {
// validate required fields are present
final StringBuilder error = new StringBuilder(100);
error.append("Owner is missing required field(s): ");
final BiFunction<String, String, Optional<String>> trimmedFieldIfValid = (field, value) -> {
boolean isError = false;
if (value == null) {
isError = true;
} else {
value = value.trim();
if (value.isEmpty()) {
isError = true;
}
}
if (isError) {
error.append(field).append(" ");
return Optional.empty();
} else {
return Optional.of(value);
}
};
final Supplier<IllegalArgumentException> exceptionSupplier = () -> new IllegalArgumentException(
error.toString());
final Optional<String> uid = trimmedFieldIfValid.apply("uid", ownerReference.getUid());
final Optional<String> apiVersion = trimmedFieldIfValid.apply("apiVersion",
ownerReference.getApiVersion());
final Optional<String> name = trimmedFieldIfValid.apply("name", ownerReference.getName());
final Optional<String> kind = trimmedFieldIfValid.apply("kind", ownerReference.getKind());
// check that required values are present
ownerReference = new OwnerReferenceBuilder(ownerReference)
.withUid(uid.orElseThrow(exceptionSupplier))
.withApiVersion(apiVersion.orElseThrow(exceptionSupplier))
.withName(name.orElseThrow(exceptionSupplier))
.withKind(kind.orElseThrow(exceptionSupplier))
.build();
return ownerReference;
}
/**
* Removes the {@link OwnerReference} identified by the specified UID if it's part of this {@code HasMetadata}'s owner references
* @param ownerUid the UID of the {@link OwnerReference} to remove
*/
default void removeOwnerReference(String ownerUid) {
if (ownerUid != null && !ownerUid.isEmpty()) {
optionalMetadata()
.map(m -> Optional.ofNullable(m.getOwnerReferences()).orElse(Collections.emptyList()))
.orElse(Collections.emptyList())
.removeIf(o -> ownerUid.equals(o.getUid()));
}
}
/**
* Removes the {@link OwnerReference} associated with the specified owner if it's part of this {@code
* HasMetadata}'s owner references
*
* @param owner the owner whose reference we want to remove
*/
default void removeOwnerReference(HasMetadata owner) {
if (owner != null) {
removeOwnerReference(owner.getMetadata().getUid());
}
}
default Optional<ObjectMeta> optionalMetadata() {
return Optional.ofNullable(getMetadata());
}
}
| |
package com.github.jasonlvhit.sunshine.data;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
/**
* Created by Jason Lyu on 2014/11/19.
*/
public class WeatherProvider extends ContentProvider {
// The URI Matcher used by this content provider.
private static final UriMatcher sUriMatcher = buildUriMatcher();
private WeatherDbHelper mOpenHelper;
private static final int WEATHER = 100;
private static final int WEATHER_WITH_LOCATION = 101;
private static final int WEATHER_WITH_LOCATION_AND_DATE = 102;
private static final int LOCATION = 300;
private static final int LOCATION_ID = 301;
private static final SQLiteQueryBuilder sWeatherByLocationSettingQueryBuilder;
static{
sWeatherByLocationSettingQueryBuilder = new SQLiteQueryBuilder();
sWeatherByLocationSettingQueryBuilder.setTables(
WeatherContract.WeatherEntry.TABLE_NAME + " INNER JOIN " +
WeatherContract.LocationEntry.TABLE_NAME +
" ON " + WeatherContract.WeatherEntry.TABLE_NAME +
"." + WeatherContract.WeatherEntry.COLUMN_LOC_KEY +
" = " + WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry._ID);
}
private static final String sLocationSettingSelection =
WeatherContract.LocationEntry.TABLE_NAME+
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? ";
private static final String sLocationSettingWithStartDateSelection =
WeatherContract.LocationEntry.TABLE_NAME+
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATETEXT + " >= ? ";
private static final String sLocationSettingAndDaySelection =
WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATETEXT + " = ? ";
private Cursor getWeatherByLocationSetting(Uri uri, String[] projection, String sortOrder) {
String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
String startDate = WeatherContract.WeatherEntry.getStartDateFromUri(uri);
String[] selectionArgs;
String selection;
if (startDate == null) {
selection = sLocationSettingSelection;
selectionArgs = new String[]{locationSetting};
} else {
selectionArgs = new String[]{locationSetting, startDate};
selection = sLocationSettingWithStartDateSelection;
}
return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
}
private Cursor getWeatherByLocationSettingAndDate(
Uri uri, String[] projection, String sortOrder) {
String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
String date = WeatherContract.WeatherEntry.getDateFromUri(uri);
return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
sLocationSettingAndDaySelection,
new String[]{locationSetting, date},
null,
null,
sortOrder
);
}
private static UriMatcher buildUriMatcher() {
// I know what you're thinking. Why create a UriMatcher when you can use regular
// expressions instead? Because you're not crazy, that's why.
// All paths added to the UriMatcher have a corresponding code to return when a match is
// found. The code passed into the constructor represents the code to return for the root
// URI. It's common to use NO_MATCH as the code for this case.
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = WeatherContract.CONTENT_AUTHORITY;
// For each type of URI you want to add, create a corresponding code.
matcher.addURI(authority, WeatherContract.PATH_WEATHER, WEATHER);
matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*", WEATHER_WITH_LOCATION);
matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*/*", WEATHER_WITH_LOCATION_AND_DATE);
matcher.addURI(authority, WeatherContract.PATH_LOCATION, LOCATION);
matcher.addURI(authority, WeatherContract.PATH_LOCATION + "/#", LOCATION_ID);
return matcher;
}
@Override
public boolean onCreate() {
mOpenHelper = new WeatherDbHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Here's the switch statement that, given a URI, will determine what kind of request it is,
// and query the database accordingly.
Cursor retCursor;
switch (sUriMatcher.match(uri)) {
// "weather/*/*"
case WEATHER_WITH_LOCATION_AND_DATE:
{
retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder);
break;
}
// "weather/*"
case WEATHER_WITH_LOCATION: {
retCursor = getWeatherByLocationSetting(uri, projection, sortOrder);
break;
}
// "weather"
case WEATHER: {
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.WeatherEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
// "location/*"
case LOCATION_ID: {
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.LocationEntry.TABLE_NAME,
projection,
WeatherContract.LocationEntry._ID + " = '" + ContentUris.parseId(uri) + "'",
null,
null,
null,
sortOrder
);
break;
}
// "location"
case LOCATION: {
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.LocationEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
retCursor.setNotificationUri(getContext().getContentResolver(), uri);
return retCursor;
}
@Override
public String getType(Uri uri) {
// Use the Uri Matcher to determine what kind of URI this is.
final int match = sUriMatcher.match(uri);
switch (match) {
case WEATHER_WITH_LOCATION_AND_DATE:
return WeatherContract.WeatherEntry.CONTENT_ITEM_TYPE;
case WEATHER_WITH_LOCATION:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case WEATHER:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case LOCATION:
return WeatherContract.LocationEntry.CONTENT_TYPE;
case LOCATION_ID:
return WeatherContract.LocationEntry.CONTENT_ITEM_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case WEATHER: {
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, values);
if ( _id > 0 )
returnUri = WeatherContract.WeatherEntry.buildWeatherUri(_id);
else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
case LOCATION: {
long _id = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, values);
if ( _id > 0 )
returnUri = WeatherContract.LocationEntry.buildLocationUri(_id);
else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsDeleted;
switch (match) {
case WEATHER:
rowsDeleted = db.delete(
WeatherContract.WeatherEntry.TABLE_NAME, selection, selectionArgs);
break;
case LOCATION:
rowsDeleted = db.delete(
WeatherContract.LocationEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
// Because a null deletes all rows
if (selection == null || rowsDeleted != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
@Override
public int update(
Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsUpdated;
switch (match) {
case WEATHER:
rowsUpdated = db.update(WeatherContract.WeatherEntry.TABLE_NAME, values, selection,
selectionArgs);
break;
case LOCATION:
rowsUpdated = db.update(WeatherContract.LocationEntry.TABLE_NAME, values, selection,
selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (rowsUpdated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsUpdated;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case WEATHER:
db.beginTransaction();
int returnCount = 0;
try {
for (ContentValues value : values) {
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
if (_id != -1) {
returnCount++;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
getContext().getContentResolver().notifyChange(uri, null);
return returnCount;
default:
return super.bulkInsert(uri, values);
}
}
}
| |
package org.sagebionetworks.repo.model.dbo.verification;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.sagebionetworks.ids.IdGenerator;
import org.sagebionetworks.ids.IdType;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.dbo.dao.TestUtils;
import org.sagebionetworks.repo.model.dbo.file.FileHandleDao;
import org.sagebionetworks.repo.model.file.FileHandle;
import org.sagebionetworks.repo.model.file.S3FileHandle;
import org.sagebionetworks.repo.model.verification.AttachmentMetadata;
import org.sagebionetworks.repo.model.verification.VerificationState;
import org.sagebionetworks.repo.model.verification.VerificationStateEnum;
import org.sagebionetworks.repo.model.verification.VerificationSubmission;
import org.sagebionetworks.repo.web.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = { "classpath:jdomodels-test-context.xml" })
public class VerificationDAOImplTest {
@Autowired
private VerificationDAO verificationDao;
@Autowired
private FileHandleDao fileHandleDao;
@Autowired
private IdGenerator idGenerator;
// take advantage of these user IDs which are always present
private static final String USER_1_ID = "1";
private static final String USER_2_ID = "273950";
private static final String COMPANY = "company";
private static final List<String> EMAILS = Arrays.asList("email1@foo.com", "email2@foo.com");
private static final String FIRST_NAME = "fname";
private static final String LAST_NAME = "lname";
private static final String LOCATION = "location";
private static final String ORCID = "http://orcid.org/0000-1111-2222-3333";
private List<String> vsToDelete;
private List<String> fhsToDelete;
@BeforeEach
public void before() throws Exception {
vsToDelete = new ArrayList<String>();
fhsToDelete = new ArrayList<String>();
}
@AfterEach
public void after() throws Exception {
for (String id : vsToDelete) {
try {
verificationDao.deleteVerificationSubmission(Long.parseLong(id));
} catch (NotFoundException e) {
// continue
}
}
for (String id : fhsToDelete) {
try {
fileHandleDao.delete(id);
} catch (NotFoundException e) {
// continue
}
}
}
private static VerificationSubmission newVerificationSubmission(String createdBy, List<String> fileHandleIds) {
VerificationSubmission dto = new VerificationSubmission();
dto.setCreatedBy(createdBy);
dto.setCreatedOn(new Date());
try {
Thread.sleep(2L); // make sure time stamps are unique
} catch (InterruptedException e) {
// continue;
}
dto.setCompany(COMPANY);
dto.setEmails(EMAILS);
List<AttachmentMetadata> attachments = new ArrayList<AttachmentMetadata>();
if (fileHandleIds!=null) {
for (String fileHandleId : fileHandleIds) {
AttachmentMetadata attachmentMetadata = new AttachmentMetadata();
attachmentMetadata.setId(fileHandleId);
attachments.add(attachmentMetadata);
}
}
dto.setAttachments(attachments);
dto.setFirstName(FIRST_NAME);
dto.setLastName(LAST_NAME);
dto.setLocation(LOCATION);
dto.setOrcid(ORCID);
// note, we don't set stateHistory
return dto;
}
private FileHandle createFileHandle(String createdBy) throws Exception {
S3FileHandle fh = TestUtils.createS3FileHandle(createdBy, idGenerator.generateNewId(IdType.FILE_IDS).toString());
fh = (S3FileHandle) fileHandleDao.createFile(fh);
fhsToDelete.add(fh.getId());
return fh;
}
@Test
public void testCreate() throws Exception {
FileHandle fh1 = createFileHandle(USER_1_ID);
FileHandle fh2 = createFileHandle(USER_1_ID);
List<String> fileHandleIds =Arrays.asList(fh1.getId(), fh2.getId());
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, fileHandleIds);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
assertNotNull(created.getId());
vsToDelete.add(created.getId());
List<VerificationState> states = created.getStateHistory();
assertEquals(1, states.size());
VerificationState state = states.get(0);
assertEquals(USER_1_ID, state.getCreatedBy());
assertNotNull(state.getCreatedOn());
assertEquals(VerificationStateEnum.SUBMITTED, state.getState());
// now 'null out' the history. it should match the submitted object
created.setStateHistory(null);
assertEquals(dto, created);
}
@Test
public void testCreateNoFiles() throws Exception {
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
assertNotNull(created.getId());
vsToDelete.add(created.getId());
created.setStateHistory(null);
// now 'null out' the history. it should match the submitted object
assertEquals(dto, created);
}
@Test
public void testDelete() throws Exception {
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
assertNotNull(created.getId());
vsToDelete.add(created.getId());
assertEquals(1, verificationDao.countVerificationSubmissions(null, null));
verificationDao.deleteVerificationSubmission(Long.parseLong(created.getId()));
assertEquals(0, verificationDao.countVerificationSubmissions(null, null));
}
@Test
public void testAppendVerificationSubmissionState() throws Exception {
// now create a verification submission for User-1 but with another state
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission rejected = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(rejected.getId());
List<VerificationSubmission> list = verificationDao.listVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.REJECTED),
Long.parseLong(USER_1_ID), 1, 0);
// initally there are no rejected submissions for this user
assertEquals(0, list.size());
// now update the state
VerificationState newState = new VerificationState();
newState.setState(VerificationStateEnum.REJECTED);
newState.setCreatedBy(USER_1_ID);
newState.setCreatedOn(new Date());
newState.setReason("your submission is invalid");
verificationDao.appendVerificationSubmissionState(Long.parseLong(rejected.getId()), newState);
list = verificationDao.listVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.REJECTED),
Long.parseLong(USER_1_ID), 1, 0);
assertEquals(1, list.size());
VerificationSubmission retrieved = list.get(0);
assertEquals(rejected.getId(), retrieved.getId());
List<VerificationState> stateHistory = retrieved.getStateHistory();
assertEquals(VerificationStateEnum.SUBMITTED, stateHistory.get(0).getState());
// check that the second (current) state is the one we set
assertEquals(newState, stateHistory.get(1));
}
@Test
public void testListVerificationsIncludeNotes() throws Exception {
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
VerificationState newState = new VerificationState();
newState.setCreatedBy(USER_2_ID);
newState.setCreatedOn(new Date());
newState.setState(VerificationStateEnum.REJECTED);
newState.setNotes("Some note");
newState.setReason("Some reason");
verificationDao.appendVerificationSubmissionState(Long.parseLong(created.getId()), newState);
List<VerificationSubmission> submissions = verificationDao.listVerificationSubmissions(null, Long.valueOf(USER_1_ID), 10, 0);
assertEquals(1, submissions.size());
VerificationSubmission submission = submissions.get(0);
VerificationState currState = submission.getStateHistory().get(submission.getStateHistory().size() - 1);
assertEquals(newState, currState);
}
@Test
public void testListVerifications() throws Exception {
FileHandle fh1 = createFileHandle(USER_1_ID);
FileHandle fh2 = createFileHandle(USER_1_ID);
List<String> fileHandleIds =Arrays.asList(fh1.getId(), fh2.getId());
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, fileHandleIds);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
// get all objects in the system
List<VerificationSubmission> list = verificationDao.listVerificationSubmissions(null, null, 10, 0);
assertEquals(1, list.size());
assertEquals(created, list.get(0));
assertEquals(1, verificationDao.countVerificationSubmissions(null, null));
// get all the objects for this user
list = verificationDao.listVerificationSubmissions(null, Long.parseLong(USER_1_ID), 10, 0);
assertEquals(1, list.size());
assertEquals(created, list.get(0));
assertEquals(1, verificationDao.countVerificationSubmissions(null, Long.parseLong(USER_1_ID)));
// get all the objects for this state
list = verificationDao.listVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.SUBMITTED), null, 10, 0);
assertEquals(1, list.size());
assertEquals(created, list.get(0));
assertEquals(1, verificationDao.countVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.SUBMITTED), null));
// get all the objects for this state and user
list = verificationDao.listVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.SUBMITTED), Long.parseLong(USER_1_ID), 10, 0);
assertEquals(1, list.size());
assertEquals(created, list.get(0));
assertEquals(1, verificationDao.countVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.SUBMITTED), Long.parseLong(USER_1_ID)));
// you can give several states to match
list = verificationDao.listVerificationSubmissions(
Arrays.asList(VerificationStateEnum.SUBMITTED, VerificationStateEnum.REJECTED),
Long.parseLong(USER_1_ID), 10, 0);
assertEquals(1, list.size());
assertEquals(created, list.get(0));
assertEquals(1, verificationDao.countVerificationSubmissions(
Arrays.asList(VerificationStateEnum.SUBMITTED, VerificationStateEnum.REJECTED),
Long.parseLong(USER_1_ID)));
// no objects for another user
assertTrue(verificationDao.listVerificationSubmissions(null, Long.parseLong(USER_2_ID), 10, 0).isEmpty());
assertEquals(0, verificationDao.countVerificationSubmissions(null, Long.parseLong(USER_2_ID)));
// no objects in another state
assertTrue(verificationDao.listVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.APPROVED), null, 10, 0).isEmpty());
assertEquals(0, verificationDao.countVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.APPROVED), null));
// no objects in another state for another user
assertTrue(verificationDao.listVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.APPROVED), Long.parseLong(USER_2_ID), 10, 0).isEmpty());
assertEquals(0, verificationDao.countVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.APPROVED), Long.parseLong(USER_2_ID)));
// make sure limit and offset are wired up right
assertTrue(verificationDao.listVerificationSubmissions(null, null, 10, 1).isEmpty());
assertTrue(verificationDao.listVerificationSubmissions(null, null, 0, 0).isEmpty());
}
@Test
public void testListVerificationsWithFiltering() throws Exception {
FileHandle fh1 = createFileHandle(USER_1_ID);
FileHandle fh2 = createFileHandle(USER_1_ID);
List<String> fileHandleIds =Arrays.asList(fh1.getId(), fh2.getId());
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, fileHandleIds);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
// now create a verification submission for another user
fh1 = createFileHandle(USER_2_ID);
fileHandleIds = Collections.singletonList(fh1.getId());
dto = newVerificationSubmission(USER_2_ID, fileHandleIds);
VerificationSubmission createdForOtherUser = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(createdForOtherUser.getId());
// now create a verification submission for User-1 but with another state
dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission rejected = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(rejected.getId());
VerificationState newState = new VerificationState();
newState.setState(VerificationStateEnum.REJECTED);
newState.setCreatedBy(USER_1_ID);
newState.setCreatedOn(new Date());
newState.setReason("my dog has fleas");
verificationDao.appendVerificationSubmissionState(Long.parseLong(rejected.getId()), newState);
// now update the expected object
List<VerificationState> stateHistory = new ArrayList<VerificationState>(rejected.getStateHistory());
stateHistory.add(newState);
rejected.setStateHistory(stateHistory);
// get all objects in the system
List<VerificationSubmission> list = verificationDao.listVerificationSubmissions(null, null, 10, 0);
assertEquals(3, list.size());
assertTrue(list.contains(created));
assertTrue(list.contains(createdForOtherUser));
assertTrue(list.contains(rejected));
assertEquals(3, verificationDao.countVerificationSubmissions(null, null));
// get all the objects for this user
list = verificationDao.listVerificationSubmissions(null, Long.parseLong(USER_1_ID), 10, 0);
assertEquals(2, list.size());
assertTrue(list.contains(created));
assertTrue(list.contains(rejected));
assertEquals(2, verificationDao.countVerificationSubmissions(null, Long.parseLong(USER_1_ID)));
// get all the objects for this state
list = verificationDao.listVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.SUBMITTED), null, 10, 0);
assertEquals(2, list.size());
assertTrue(list.contains(created));
assertTrue(list.contains(createdForOtherUser));
assertEquals(2, verificationDao.countVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.SUBMITTED), null));
// get all the objects for this state and user
list = verificationDao.listVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.SUBMITTED), Long.parseLong(USER_1_ID), 10, 0);
assertEquals(1, list.size());
assertEquals(created, list.get(0));
assertEquals(1, verificationDao.countVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.SUBMITTED), Long.parseLong(USER_1_ID)));
// the other state
list = verificationDao.listVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.REJECTED), Long.parseLong(USER_1_ID), 10, 0);
assertEquals(1, list.size());
assertEquals(rejected, list.get(0));
assertEquals(1, verificationDao.countVerificationSubmissions(
Collections.singletonList(VerificationStateEnum.REJECTED), Long.parseLong(USER_1_ID)));
// searching for two states gives us both results
list = verificationDao.listVerificationSubmissions(
Arrays.asList(VerificationStateEnum.SUBMITTED, VerificationStateEnum.REJECTED),
Long.parseLong(USER_1_ID), 10, 0);
assertEquals(2, list.size());
assertTrue(list.contains(created));
assertTrue(list.contains(rejected));
assertEquals(2, verificationDao.countVerificationSubmissions(
Arrays.asList(VerificationStateEnum.SUBMITTED, VerificationStateEnum.REJECTED),
Long.parseLong(USER_1_ID)));
}
@Test
public void testListFileHandleIdsInVerificationSubmission() throws Exception {
FileHandle fh1 = createFileHandle(USER_1_ID);
FileHandle fh2 = createFileHandle(USER_1_ID);
List<String> fileHandleIds =Arrays.asList(fh1.getId(), fh2.getId());
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, fileHandleIds);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
assertNotNull(created.getId());
vsToDelete.add(created.getId());
long longId = Long.parseLong(created.getId());
// make sure the file handle IDs appear in the query results
List<Long> retrieved = verificationDao.listFileHandleIds(longId);
assertEquals(2, retrieved.size());
assertTrue(retrieved.contains(Long.parseLong(fh1.getId())));
assertTrue(retrieved.contains(Long.parseLong(fh2.getId())));
// no file handles for this ID
assertTrue(verificationDao.listFileHandleIds(longId*13).isEmpty());
}
@Test
public void testGetCurrentVerificationSubmissionForUser() {
long user1long = Long.parseLong(USER_1_ID);
// when there is no verification submission we should get null
assertNull(verificationDao.getCurrentVerificationSubmissionForUser(user1long));
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
VerificationSubmission current = verificationDao.getCurrentVerificationSubmissionForUser(user1long);
assertEquals(created, current);
dto = newVerificationSubmission(USER_1_ID, null); // this one will have a later time stamp
VerificationSubmission created2 = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created2.getId());
// the new one is different!
assertFalse(created.getId().equals(created2.getId()));
current = verificationDao.getCurrentVerificationSubmissionForUser(user1long);
assertEquals(created2, current);
}
@Test
public void testGetCurrentVerificationSubmissionForUserNoNotes() {
long user1long = Long.parseLong(USER_1_ID);
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
VerificationState newState = new VerificationState();
newState.setCreatedBy(USER_2_ID);
newState.setCreatedOn(new Date());
newState.setState(VerificationStateEnum.REJECTED);
newState.setNotes("Some note");
newState.setReason("Some reason");
verificationDao.appendVerificationSubmissionState(Long.parseLong(created.getId()), newState);
VerificationSubmission current = verificationDao.getCurrentVerificationSubmissionForUser(user1long);
assertFalse(current.getStateHistory().isEmpty());
VerificationState currState = current.getStateHistory().get(current.getStateHistory().size() - 1);
newState.setNotes(null);
assertEquals(newState, currState);
}
@Test
public void testGetVerificationState() {
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
long createdIdLong = Long.parseLong(created.getId());
assertEquals(VerificationStateEnum.SUBMITTED, verificationDao.getVerificationState(createdIdLong));
VerificationState newState = new VerificationState();
newState.setCreatedBy(USER_2_ID);
newState.setCreatedOn(new Date());
newState.setState(VerificationStateEnum.REJECTED);
verificationDao.appendVerificationSubmissionState(createdIdLong, newState);
assertEquals(VerificationStateEnum.REJECTED, verificationDao.getVerificationState(createdIdLong));
// if we make a new one, there's no confusion about which state we're checking...
dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission created2 = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created2.getId());
// ...still get the correct status, that of the first submission
assertEquals(VerificationStateEnum.REJECTED, verificationDao.getVerificationState(createdIdLong));
}
@Test
public void testGetVerificationSubmitter() {
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
long createdIdLong = Long.parseLong(created.getId());
long user1Long = Long.parseLong(USER_1_ID);
assertEquals(user1Long, verificationDao.getVerificationSubmitter(createdIdLong));
// if we make a new one, there's no confusion about which object we're checking...
dto = newVerificationSubmission(USER_2_ID, null);
VerificationSubmission created2 = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created2.getId());
// ...still get the correct submitter, that of the first submission
assertEquals(user1Long, verificationDao.getVerificationSubmitter(createdIdLong));
}
@Test
public void testHaveValidatedProfiles() {
assertFalse(verificationDao.haveValidatedProfiles(null));
HashSet<String> userIds = new HashSet<String>();
assertFalse(verificationDao.haveValidatedProfiles(userIds));
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, null);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
userIds.add(USER_1_ID);
assertFalse(verificationDao.haveValidatedProfiles(userIds));
long createdIdLong = Long.parseLong(created.getId());
VerificationState newState = new VerificationState();
newState.setCreatedBy(USER_2_ID);
newState.setCreatedOn(new Date());
newState.setState(VerificationStateEnum.REJECTED);
verificationDao.appendVerificationSubmissionState(createdIdLong, newState);
assertFalse(verificationDao.haveValidatedProfiles(userIds));
newState = new VerificationState();
newState.setCreatedBy(USER_2_ID);
newState.setCreatedOn(new Date());
newState.setState(VerificationStateEnum.APPROVED);
verificationDao.appendVerificationSubmissionState(createdIdLong, newState);
assertTrue(verificationDao.haveValidatedProfiles(userIds));
userIds.add(USER_2_ID);
assertFalse(verificationDao.haveValidatedProfiles(userIds));
}
@Test
public void testRemoveFileHandleAfterApproval() throws Exception {
testRemoveFileHandlesAfterStateChange(VerificationStateEnum.APPROVED);
}
@Test
public void testRemoveFileHandleAfterRejection() throws Exception {
testRemoveFileHandlesAfterStateChange(VerificationStateEnum.REJECTED);
}
private void testRemoveFileHandlesAfterStateChange(VerificationStateEnum state) throws Exception {
FileHandle fh1 = createFileHandle(USER_1_ID);
FileHandle fh2 = createFileHandle(USER_1_ID);
List<String> fileHandleIds = Arrays.asList(fh1.getId(), fh2.getId());
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, fileHandleIds);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
assertEquals(2, created.getAttachments().size());
VerificationState newState = new VerificationState();
newState.setCreatedBy(USER_2_ID);
newState.setCreatedOn(new Date());
newState.setState(state);
// Call under test
verificationDao.appendVerificationSubmissionState(Long.parseLong(created.getId()), newState);
List<Long> currentFileHandleIds = verificationDao.listFileHandleIds(Long.valueOf(created.getId()));
assertTrue(currentFileHandleIds.isEmpty());
}
@Test
public void testIncludeAttachmentsForSubmittedOnly() throws Exception {
FileHandle fh1 = createFileHandle(USER_1_ID);
FileHandle fh2 = createFileHandle(USER_1_ID);
List<String> fileHandleIds = Arrays.asList(fh1.getId(), fh2.getId());
VerificationSubmission dto = newVerificationSubmission(USER_1_ID, fileHandleIds);
VerificationSubmission created = verificationDao.createVerificationSubmission(dto);
vsToDelete.add(created.getId());
// Call under test
VerificationSubmission submission = verificationDao.getCurrentVerificationSubmissionForUser(Long.valueOf(USER_1_ID));
assertFalse(submission.getAttachments().isEmpty());
for (VerificationStateEnum state : VerificationStateEnum.values()) {
VerificationState newState = new VerificationState();
newState.setCreatedBy(USER_2_ID);
newState.setCreatedOn(new Date());
newState.setState(state);
verificationDao.appendVerificationSubmissionState(Long.parseLong(created.getId()), newState);
// Call under test
submission = verificationDao.getCurrentVerificationSubmissionForUser(Long.valueOf(USER_1_ID));
boolean expected = !VerificationStateEnum.SUBMITTED.equals(state);
assertEquals(expected, submission.getAttachments().isEmpty());
}
}
}
| |
package v1.pyroteck.com.pyroteck.constants;
/**
* Created by Nilesh on 19/05/15.
*/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.provider.Settings.Secure;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class CommonMethods {
private static final String Tag = "CommonMethods";
public static String getUniqueDeviceID(Context ctx){
String android_id = Secure.getString(ctx.getContentResolver(),
Secure.ANDROID_ID);
return android_id;
}
public static Bitmap getFacebookProfilePicture(Context context,String userID){
if(!CommonMethods.isNetworkPresent(context)){
Toast.makeText(context, "No Network Present", Toast.LENGTH_SHORT).show();
return null;
}
URL imageURL;
Bitmap bitmap = null;
try {
imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
public static String callSyncService(Context context,String webservice_url,String TAG) {
if(!CommonMethods.isNetworkPresent(context)){
//Toast.makeText(context, "No Network Present", Toast.LENGTH_SHORT).show();
return "";
}
String resultString = "0";
//Log.d(TAG, " json Value "+jsonString);
try
{
//HttpPost httppost = new HttpPost(webservice_url);
HttpGet httpGet = new HttpGet(webservice_url);
//passing as parameter to webservice as request and then get responsse from there.
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// nameValuePairs.add(new BasicNameValuePair("json",
// jsonString ));
//
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
//int timeoutConnection = 100000;
HttpConnectionParams.setConnectionTimeout(httpParameters, Constants.TIMEOUT_CONNECTION);
//int timeoutSocket = (int) TimeUnit.SECONDS.toMillis(2);
HttpConnectionParams.setSoTimeout(httpParameters, Constants.TIMEOUT_SOCKET);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpGet);
resultString = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Server Response "+resultString);
Log.d(TAG, "This is the Status Line \n "+response.getStatusLine());
Log.d(TAG, "This is the Status code \n "+response.getStatusLine().getStatusCode());
}
catch(ConnectTimeoutException e)
{
Log.d(TAG, "Connection Timeout===>");
e.printStackTrace();
return null;
}
catch (Exception e)
{
Log.d(TAG, "Exception ");
e.printStackTrace();
}
return resultString;
}
public static String callSyncService(Context context,HashMap<String, String> data,String webservice_url,String TAG) {
if(!CommonMethods.isNetworkPresent(context)){
//Toast.makeText(context.getApplicationContext(), "No Network Present", Toast.LENGTH_SHORT).show();
return null;
}
String resultString = "0";
//Log.d(TAG, " json Value "+jsonString);
try{
//HttpPost httppost = new HttpPost(webservice_url);
HttpPost httpPost = new HttpPost(webservice_url);
//passing as parameter to webservice as request and then get responsse from there.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(data != null){
for (Map.Entry<String, String> entry : data.entrySet()){
System.out.println(entry.getKey() + "/" + entry.getValue());
nameValuePairs.add(new BasicNameValuePair(entry.getKey(),
entry.getValue() ));
}
}
// nameValuePairs.add(new BasicNameValuePair("json",
// jsonString ));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
//int timeoutConnection = 100000;
HttpConnectionParams.setConnectionTimeout(httpParameters, Constants.TIMEOUT_CONNECTION);
//int timeoutSocket = (int) TimeUnit.SECONDS.toMillis(2);
HttpConnectionParams.setSoTimeout(httpParameters, Constants.TIMEOUT_SOCKET);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity());
Log.d(TAG, "Server Response "+resultString);
Log.d(TAG, "This is the Status Line \n "+response.getStatusLine());
Log.d(TAG, "This is the Status code \n "+response.getStatusLine().getStatusCode());
}
catch(ConnectTimeoutException e)
{
Log.d(TAG, "Connection Timeout===>");
e.printStackTrace();
}
catch (Exception e)
{
Log.d(TAG, "Exception ");
e.printStackTrace();
}
return resultString;
}
public static boolean isNetworkPresent(Context context) {
boolean isNetworkAvailable = false;
if (context != null) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
if (cm != null) {
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null) {
isNetworkAvailable = netInfo.isConnected();
// Toast.makeText(context, "Connecting...", Toast.LENGTH_SHORT).show();
//Log.d("NETWORK<<","Connecting...."+netInfo.getReason());
}
}
} catch (Exception ex) {
//Log.e("Network Avail Error", ex.getMessage());
}
// check for wifi also
if(!isNetworkAvailable){
WifiManager connec = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
State wifi = cm.getNetworkInfo(1).getState();
if (connec.isWifiEnabled()
&& wifi.toString().equalsIgnoreCase("CONNECTED")) {
isNetworkAvailable = true;
//Log.d("WIFI NETWORK<<","WIFI connected");
} else {
isNetworkAvailable = false;
// Log.d("WIFI Network<<","WIFI not connected");
}
}
}
return isNetworkAvailable;
}
public float convertDIPtoPixel(Context ctx,float value){
Resources r = ctx.getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
return px;
}
public static void writeTextFile(String key,String data){
try {
Log.d(key, data);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date currentDate = new Date();
try {
currentDate=sdf.parse(sdf.format(currentDate));
} catch (ParseException e) {
// TODO Auto-generated catch block
CommonMethods.writeTextFile(Tag," "+getStackTrace(e));
}
String path="/sdcard/gpstrackerlogfile.txt";
File myFile = new File(path);
if(!myFile.exists()){
/**
* android.os.Build.VERSION.SDK // API Level
android.os.Build.DEVICE // Device
android.os.Build.MODEL // Model
android.os.Build.PRODUCT
*/
Log.d("CommonMethods", "Writing the Device info");
myFile.createNewFile();
FileWriter fw = new FileWriter(myFile,true);
fw.write("API Level : "+android.os.Build.VERSION.SDK_INT+"\r\n");
fw.write("Device : "+android.os.Build.DEVICE+"\r\n");//appends the string to the file
fw.write("Model : "+android.os.Build.MODEL+"\r\n");
fw.write("Product : "+android.os.Build.PRODUCT+"\r\n");
fw.write("Manufacturer : "+android.os.Build.MANUFACTURER+"\r\n");
fw.flush();
fw.close();
}
myFile.createNewFile();
FileWriter fw = new FileWriter(myFile,true);
fw.write("Time "+sdf.format(currentDate)+"\r\t "+key+" \r\t "+data +"\r\n");//appends the string to the file
fw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Custom Stack trace ", getStackTrace(e));
} catch (IOException e) {
e.printStackTrace();
Log.d("Custom Stack trace ", getStackTrace(e));
}
}
public static String getStackTrace(Throwable aThrowable) {
aThrowable.printStackTrace();
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.