gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* 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.flink.connectors.hive.read;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.io.CheckpointableInputFormat;
import org.apache.flink.api.common.io.LocatableInputSplitAssigner;
import org.apache.flink.api.common.io.statistics.BaseStatistics;
import org.apache.flink.api.java.hadoop.common.HadoopInputFormatCommonBase;
import org.apache.flink.connectors.hive.FlinkHiveException;
import org.apache.flink.connectors.hive.HiveTablePartition;
import org.apache.flink.connectors.hive.JobConfWrapper;
import org.apache.flink.core.io.InputSplitAssigner;
import org.apache.flink.table.catalog.hive.client.HiveShimLoader;
import org.apache.flink.table.catalog.hive.util.HiveTypeUtil;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.ql.io.IOConstants;
import org.apache.hadoop.hive.serde2.ColumnProjectionUtils;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.util.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.hadoop.mapreduce.lib.input.FileInputFormat.INPUT_DIR;
/**
* The HiveTableInputFormat are inspired by the HCatInputFormat and HadoopInputFormatBase.
* It's used to read from hive partition/non-partition table.
*/
public class HiveTableInputFormat extends HadoopInputFormatCommonBase<RowData, HiveTableInputSplit>
implements CheckpointableInputFormat<HiveTableInputSplit, Long> {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(HiveTableInputFormat.class);
// schema evolution configs are not available in older versions of IOConstants, let's define them ourselves
private static final String SCHEMA_EVOLUTION_COLUMNS = "schema.evolution.columns";
private static final String SCHEMA_EVOLUTION_COLUMNS_TYPES = "schema.evolution.columns.types";
private final JobConfWrapper jobConf;
private final String hiveVersion;
private final List<String> partitionKeys;
private final DataType[] fieldTypes;
private final String[] fieldNames;
//For non-partition hive table, partitions only contains one partition which partitionValues is empty.
private final List<HiveTablePartition> partitions;
// indices of fields to be returned, with projection applied (if any)
private final int[] selectedFields;
//We should limit the input read count of this splits, null represents no limit.
private final Long limit;
private final boolean useMapRedReader;
private transient long currentReadCount = 0L;
@VisibleForTesting
protected transient SplitReader reader;
public HiveTableInputFormat(
JobConf jobConf,
List<String> partitionKeys,
DataType[] fieldTypes,
String[] fieldNames,
int[] projectedFields,
Long limit,
String hiveVersion,
boolean useMapRedReader,
List<HiveTablePartition> partitions) {
super(jobConf.getCredentials());
this.jobConf = new JobConfWrapper(new JobConf(jobConf));
this.partitionKeys = partitionKeys;
this.fieldTypes = fieldTypes;
this.fieldNames = fieldNames;
this.limit = limit;
this.hiveVersion = hiveVersion;
int rowArity = fieldTypes.length;
this.selectedFields = projectedFields != null ? projectedFields : IntStream.range(0, rowArity).toArray();
this.useMapRedReader = useMapRedReader;
this.partitions = checkNotNull(partitions, "partitions can not be null.");
}
public JobConf getJobConf() {
return jobConf.conf();
}
@Override
public void configure(org.apache.flink.configuration.Configuration parameters) {
}
@Override
public void open(HiveTableInputSplit split) throws IOException {
HiveTablePartition partition = split.getHiveTablePartition();
if (!useMapRedReader && useOrcVectorizedRead(partition)) {
this.reader = new HiveVectorizedOrcSplitReader(
hiveVersion, jobConf.conf(), fieldNames, fieldTypes, selectedFields, split);
} else if (!useMapRedReader && useParquetVectorizedRead(partition)) {
this.reader = new HiveVectorizedParquetSplitReader(
hiveVersion, jobConf.conf(), fieldNames, fieldTypes, selectedFields, split);
} else {
JobConf clonedConf = new JobConf(jobConf.conf());
addSchemaToConf(clonedConf);
this.reader = new HiveMapredSplitReader(clonedConf, partitionKeys, fieldTypes, selectedFields, split,
HiveShimLoader.loadHiveShim(hiveVersion));
}
currentReadCount = 0L;
}
// Hive readers may rely on the schema info in configuration
private void addSchemaToConf(JobConf jobConf) {
// set columns/types -- including partition cols
List<String> typeStrs = Arrays.stream(fieldTypes)
.map(t -> HiveTypeUtil.toHiveTypeInfo(t, true).toString())
.collect(Collectors.toList());
jobConf.set(IOConstants.COLUMNS, String.join(",", fieldNames));
jobConf.set(IOConstants.COLUMNS_TYPES, String.join(",", typeStrs));
// set schema evolution -- excluding partition cols
int numNonPartCol = fieldNames.length - partitionKeys.size();
jobConf.set(SCHEMA_EVOLUTION_COLUMNS, String.join(",", Arrays.copyOfRange(fieldNames, 0, numNonPartCol)));
jobConf.set(SCHEMA_EVOLUTION_COLUMNS_TYPES, String.join(",", typeStrs.subList(0, numNonPartCol)));
// in older versions, parquet reader also expects the selected col indices in conf, excluding part cols
String readColIDs = Arrays.stream(selectedFields)
.filter(i -> i < numNonPartCol)
.mapToObj(String::valueOf)
.collect(Collectors.joining(","));
jobConf.set(ColumnProjectionUtils.READ_COLUMN_IDS_CONF_STR, readColIDs);
}
@Override
public void reopen(HiveTableInputSplit split, Long state) throws IOException {
this.open(split);
this.currentReadCount = state;
this.reader.seekToRow(state, new GenericRowData(selectedFields.length));
}
@Override
public Long getCurrentState() {
return currentReadCount;
}
private static boolean isVectorizationUnsupported(LogicalType t) {
switch (t.getTypeRoot()) {
case CHAR:
case VARCHAR:
case BOOLEAN:
case BINARY:
case VARBINARY:
case DECIMAL:
case TINYINT:
case SMALLINT:
case INTEGER:
case BIGINT:
case FLOAT:
case DOUBLE:
case DATE:
case TIME_WITHOUT_TIME_ZONE:
case TIMESTAMP_WITHOUT_TIME_ZONE:
case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
return false;
case TIMESTAMP_WITH_TIME_ZONE:
case INTERVAL_YEAR_MONTH:
case INTERVAL_DAY_TIME:
case ARRAY:
case MULTISET:
case MAP:
case ROW:
case DISTINCT_TYPE:
case STRUCTURED_TYPE:
case NULL:
case RAW:
case SYMBOL:
default:
return true;
}
}
private boolean useParquetVectorizedRead(HiveTablePartition partition) {
boolean isParquet = partition.getStorageDescriptor().getSerdeInfo().getSerializationLib()
.toLowerCase().contains("parquet");
if (!isParquet) {
return false;
}
for (int i : selectedFields) {
if (isVectorizationUnsupported(fieldTypes[i].getLogicalType())) {
LOG.info("Fallback to hadoop mapred reader, unsupported field type: " + fieldTypes[i]);
return false;
}
}
LOG.info("Use flink parquet ColumnarRowData reader.");
return true;
}
private boolean useOrcVectorizedRead(HiveTablePartition partition) {
boolean isOrc = partition.getStorageDescriptor().getSerdeInfo().getSerializationLib()
.toLowerCase().contains("orc");
if (!isOrc) {
return false;
}
for (int i : selectedFields) {
if (isVectorizationUnsupported(fieldTypes[i].getLogicalType())) {
LOG.info("Fallback to hadoop mapred reader, unsupported field type: " + fieldTypes[i]);
return false;
}
}
LOG.info("Use flink orc ColumnarRowData reader.");
return true;
}
@Override
public boolean reachedEnd() throws IOException {
if (limit != null && currentReadCount >= limit) {
return true;
} else {
return reader.reachedEnd();
}
}
@Override
public RowData nextRecord(RowData reuse) throws IOException {
currentReadCount++;
return reader.nextRecord(reuse);
}
@Override
public void close() throws IOException {
if (this.reader != null) {
this.reader.close();
this.reader = null;
}
}
@Override
public HiveTableInputSplit[] createInputSplits(int minNumSplits)
throws IOException {
return createInputSplits(minNumSplits, partitions, jobConf.conf());
}
public static HiveTableInputSplit[] createInputSplits(
int minNumSplits,
List<HiveTablePartition> partitions,
JobConf jobConf) throws IOException {
List<HiveTableInputSplit> hiveSplits = new ArrayList<>();
int splitNum = 0;
FileSystem fs = null;
for (HiveTablePartition partition : partitions) {
StorageDescriptor sd = partition.getStorageDescriptor();
Path inputPath = new Path(sd.getLocation());
if (fs == null) {
fs = inputPath.getFileSystem(jobConf);
}
// it's possible a partition exists in metastore but the data has been removed
if (!fs.exists(inputPath)) {
continue;
}
InputFormat format;
try {
format = (InputFormat)
Class.forName(sd.getInputFormat(), true, Thread.currentThread().getContextClassLoader()).newInstance();
} catch (Exception e) {
throw new FlinkHiveException("Unable to instantiate the hadoop input format", e);
}
ReflectionUtils.setConf(format, jobConf);
jobConf.set(INPUT_DIR, sd.getLocation());
//TODO: we should consider how to calculate the splits according to minNumSplits in the future.
org.apache.hadoop.mapred.InputSplit[] splitArray = format.getSplits(jobConf, minNumSplits);
for (org.apache.hadoop.mapred.InputSplit inputSplit : splitArray) {
hiveSplits.add(new HiveTableInputSplit(splitNum++, inputSplit, jobConf, partition));
}
}
return hiveSplits.toArray(new HiveTableInputSplit[0]);
}
@Override
public BaseStatistics getStatistics(BaseStatistics cachedStats) {
// no statistics available
return null;
}
@Override
public InputSplitAssigner getInputSplitAssigner(HiveTableInputSplit[] inputSplits) {
return new LocatableInputSplitAssigner(inputSplits);
}
public int getNumFiles() throws IOException {
int numFiles = 0;
FileSystem fs = null;
for (HiveTablePartition partition : partitions) {
StorageDescriptor sd = partition.getStorageDescriptor();
Path inputPath = new Path(sd.getLocation());
if (fs == null) {
fs = inputPath.getFileSystem(jobConf.conf());
}
// it's possible a partition exists in metastore but the data has been removed
if (!fs.exists(inputPath)) {
continue;
}
numFiles += fs.listStatus(inputPath).length;
}
return numFiles;
}
}
| |
/*
* Copyright 2015 Fluo authors (see AUTHORS)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.fluo.webindex.ui;
import java.util.Iterator;
import java.util.Map;
import javax.validation.constraints.NotNull;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import com.google.gson.Gson;
import io.fluo.webindex.core.Constants;
import io.fluo.webindex.core.DataConfig;
import io.fluo.webindex.core.models.DomainStats;
import io.fluo.webindex.core.models.Link;
import io.fluo.webindex.core.models.Links;
import io.fluo.webindex.core.models.Page;
import io.fluo.webindex.core.models.Pages;
import io.fluo.webindex.core.models.TopResults;
import io.fluo.webindex.core.models.URL;
import io.fluo.webindex.ui.util.Pager;
import io.fluo.webindex.ui.util.WebUrl;
import io.fluo.webindex.ui.views.HomeView;
import io.fluo.webindex.ui.views.LinksView;
import io.fluo.webindex.ui.views.PageView;
import io.fluo.webindex.ui.views.PagesView;
import io.fluo.webindex.ui.views.TopView;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("/")
public class WebIndexResources {
private static final Logger log = LoggerFactory.getLogger(WebIndexResources.class);
private static final int PAGE_SIZE = 25;
private DataConfig dataConfig;
private Connector conn;
private Gson gson = new Gson();
public WebIndexResources(Connector conn, DataConfig dataConfig) {
this.conn = conn;
this.dataConfig = dataConfig;
}
private static Long getLongValue(Map.Entry<Key, Value> entry) {
return Long.parseLong(entry.getValue().toString());
}
@GET
@Produces(MediaType.TEXT_HTML)
public HomeView getHome() {
return new HomeView();
}
@GET
@Path("pages")
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
public PagesView getPages(@NotNull @QueryParam("domain") String domain,
@DefaultValue("") @QueryParam("next") String next,
@DefaultValue("0") @QueryParam("pageNum") Integer pageNum) {
DomainStats stats = getDomainStats(domain);
Pages pages = new Pages(domain, pageNum);
log.info("Setting total to {}", stats.getTotal());
pages.setTotal(stats.getTotal());
String row = "d:" + URL.reverseHost(domain);
String cf = Constants.RANK;
try {
Scanner scanner = conn.createScanner(dataConfig.accumuloIndexTable, Authorizations.EMPTY);
Pager pager = new Pager(scanner, Range.prefix(row + ":"), PAGE_SIZE) {
@Override
public void foundPageEntry(Map.Entry<Key, Value> entry) {
String url =
URL.fromPageID(entry.getKey().getRowData().toString().split(":", 4)[3]).toString();
Long count = Long.parseLong(entry.getValue().toString());
pages.addPage(url, count);
}
@Override
public void foundNextEntry(Map.Entry<Key, Value> entry) {
pages.setNext(entry.getKey().getRowData().toString().split(":", 3)[2]);
}
};
if (next.isEmpty()) {
pager.getPage(pageNum);
} else {
pager.getPage(new Key(row + ":" + next, cf, ""));
}
} catch (TableNotFoundException e) {
log.error("Table {} not found", dataConfig.accumuloIndexTable);
}
return new PagesView(pages);
}
@GET
@Path("page")
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
public PageView getPageView(@NotNull @QueryParam("url") String url) {
return new PageView(getPage(url));
}
private Page getPage(String rawUrl) {
Page page = null;
Long incount = (long) 0;
URL url;
try {
url = WebUrl.from(rawUrl);
} catch (Exception e) {
log.error("Failed to parse URL {}", rawUrl);
return null;
}
try {
Scanner scanner = conn.createScanner(dataConfig.accumuloIndexTable, Authorizations.EMPTY);
scanner.setRange(Range.exact("p:" + url.toPageID(), Constants.PAGE));
Iterator<Map.Entry<Key, Value>> iterator = scanner.iterator();
while (iterator.hasNext()) {
Map.Entry<Key, Value> entry = iterator.next();
switch (entry.getKey().getColumnQualifier().toString()) {
case Constants.INCOUNT:
incount = getLongValue(entry);
break;
case Constants.CUR:
page = gson.fromJson(entry.getValue().toString(), Page.class);
break;
default:
log.error("Unknown page stat {}", entry.getKey().getColumnQualifier());
}
}
} catch (TableNotFoundException e) {
e.printStackTrace();
}
if (page == null) {
page = new Page(url.toPageID());
}
page.setNumInbound(incount);
return page;
}
private DomainStats getDomainStats(String domain) {
DomainStats stats = new DomainStats(domain);
Scanner scanner;
try {
scanner = conn.createScanner(dataConfig.accumuloIndexTable, Authorizations.EMPTY);
scanner.setRange(Range.exact("d:" + URL.reverseHost(domain), Constants.DOMAIN));
Iterator<Map.Entry<Key, Value>> iterator = scanner.iterator();
while (iterator.hasNext()) {
Map.Entry<Key, Value> entry = iterator.next();
switch (entry.getKey().getColumnQualifier().toString()) {
case Constants.PAGECOUNT:
stats.setTotal(getLongValue(entry));
break;
default:
log.error("Unknown page domain {}", entry.getKey().getColumnQualifier());
}
}
} catch (TableNotFoundException e) {
e.printStackTrace();
}
return stats;
}
@GET
@Path("links")
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
public LinksView getLinks(@NotNull @QueryParam("url") String rawUrl,
@NotNull @QueryParam("linkType") String linkType,
@DefaultValue("") @QueryParam("next") String next,
@DefaultValue("0") @QueryParam("pageNum") Integer pageNum) {
Links links = new Links(rawUrl, linkType, pageNum);
URL url;
try {
url = WebUrl.from(rawUrl);
} catch (Exception e) {
log.error("Failed to parse URL: " + rawUrl);
return new LinksView(links);
}
try {
Scanner scanner = conn.createScanner(dataConfig.accumuloIndexTable, Authorizations.EMPTY);
String row = "p:" + url.toPageID();
if (linkType.equals("in")) {
Page page = getPage(rawUrl);
String cf = Constants.INLINKS;
links.setTotal(page.getNumInbound());
Pager pager = new Pager(scanner, Range.exact(row, cf), PAGE_SIZE) {
@Override
public void foundPageEntry(Map.Entry<Key, Value> entry) {
String pageID = entry.getKey().getColumnQualifier().toString();
String anchorText = entry.getValue().toString();
links.addLink(Link.of(pageID, anchorText));
}
@Override
public void foundNextEntry(Map.Entry<Key, Value> entry) {
links.setNext(entry.getKey().getColumnQualifier().toString());
}
};
if (next.isEmpty()) {
pager.getPage(pageNum);
} else {
pager.getPage(new Key(row, cf, next));
}
} else {
scanner.setRange(Range.exact(row, Constants.PAGE, Constants.CUR));
Iterator<Map.Entry<Key, Value>> iter = scanner.iterator();
if (iter.hasNext()) {
Page curPage = gson.fromJson(iter.next().getValue().toString(), Page.class);
links.setTotal(curPage.getNumOutbound());
int skip = 0;
int add = 0;
for (Link l : curPage.getOutboundLinks()) {
if (skip < (pageNum * PAGE_SIZE)) {
skip++;
} else if (add < PAGE_SIZE) {
links.addLink(l);
add++;
} else {
links.setNext(l.getPageID());
break;
}
}
}
}
} catch (TableNotFoundException e) {
log.error("Table {} not found", dataConfig.accumuloIndexTable);
}
return new LinksView(links);
}
@GET
@Path("top")
@Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
public TopView getTop(@DefaultValue("") @QueryParam("next") String next,
@DefaultValue("0") @QueryParam("pageNum") Integer pageNum) {
TopResults results = new TopResults();
results.setPageNum(pageNum);
try {
Scanner scanner = conn.createScanner(dataConfig.accumuloIndexTable, Authorizations.EMPTY);
Pager pager = new Pager(scanner, Range.prefix("t:"), PAGE_SIZE) {
@Override
public void foundPageEntry(Map.Entry<Key, Value> entry) {
String row = entry.getKey().getRow().toString();
String url = URL.fromPageID(row.split(":", 3)[2]).toString();
Long num = Long.parseLong(entry.getValue().toString());
results.addResult(url, num);
}
@Override
public void foundNextEntry(Map.Entry<Key, Value> entry) {
results.setNext(entry.getKey().getRow().toString());
}
};
if (next.isEmpty()) {
pager.getPage(pageNum);
} else {
pager.getPage(new Key(next));
}
} catch (TableNotFoundException e) {
log.error("Table {} not found", dataConfig.accumuloIndexTable);
}
return new TopView(results);
}
}
| |
/**
* Copyright (c) Microsoft Corporation
* <p/>
* All rights reserved.
* <p/>
* MIT License
* <p/>
* 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:
* <p/>
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
* <p/>
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.microsoft.intellij.util;
import com.intellij.ide.DataManager;
import com.intellij.ide.projectView.impl.ProjectRootsUtil;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.interopbridges.tools.windowsazure.WindowsAzureInvalidProjectOperationException;
import com.interopbridges.tools.windowsazure.WindowsAzureProjectManager;
import com.interopbridges.tools.windowsazure.WindowsAzureRole;
import com.interopbridges.tools.windowsazure.WindowsAzureRoleComponentImportMethod;
import com.microsoft.intellij.AzurePlugin;
import com.microsoft.wacommon.utils.WACommonException;
import java.io.File;
import static com.microsoft.intellij.ui.messages.AzureBundle.message;
public class PluginUtil {
private static final Logger LOG = Logger.getInstance("#com.microsoft.intellij.util.PluginUtil");
public static final String BASE_PATH = "${basedir}" + File.separator + "..";
public static boolean isModuleRoot(VirtualFile moduleFolder, Module module) {
return moduleFolder != null && ProjectRootsUtil.isModuleContentRoot(moduleFolder, module.getProject());
}
public enum ProjExportType {WAR, EAR, JAR}
/**
* This method returns currently selected project in workspace.
*
* @return Project
*/
public static Project getSelectedProject() {
DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResult();
return DataKeys.PROJECT.getData(dataContext);
}
public static String getModulePath(Module module) {
return new File(module.getModuleFilePath()).getParent();
}
/**
* This method will display the error message box when any error occurs.It takes two parameters
*
* @param title the text or title of the window.
* @param message the message which is to be displayed
*/
public static void displayErrorDialog(String title, String message) {
Messages.showErrorDialog(message, title);
}
public static void displayErrorDialogAndLog(String title, String message, Exception e) {
LOG.error(message, e);
displayErrorDialog(title, message);
}
public static void displayErrorDialogInAWTAndLog(final String title, final String message, Exception e) {
LOG.error(message, e);
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
PluginUtil.displayErrorDialog(title, message);
}
});
}
public static void displayInfoDialog(String title, String message) {
Messages.showInfoMessage(message, title);
}
public static void displayWarningDialog(String title, String message) {
Messages.showWarningDialog(message, title);
}
public static void displayWarningDialogInAWT(final String title, final String message) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
displayWarningDialog(title, message);
}
});
}
/**
* Gets location of Azure Libraries
*
* @throws WACommonException
*/
public static String getAzureLibLocation() throws WACommonException {
String libLocation;
try {
String pluginInstLoc = String.format("%s%s%s", PathManager.getPluginsPath(), File.separator, AzurePlugin.COMMON_LIB_PLUGIN_ID);
libLocation = String.format(pluginInstLoc + "%s%s", File.separator, "lib");
File file = new File(String.format(libLocation + "%s%s", File.separator, message("sdkLibBaseJar")));
if (!file.exists()) {
throw new WACommonException(message("SDKLocErrMsg"));
}
} catch (WACommonException e) {
e.printStackTrace();
throw e;
}
return libLocation;
}
/**
* Determines whether a folder is a role folder or not.
*
* @return true if the folder is a role folder else false.
*/
public static boolean isRoleFolder(VirtualFile vFile, Module module) {
boolean retVal = false;
try {
WindowsAzureProjectManager projMngr = WindowsAzureProjectManager.load(new File(getModulePath(module)));
WindowsAzureRole role = projMngr.roleFromPath(new File(vFile.getPath()));
if (role != null) {
retVal = true;
}
} catch (WindowsAzureInvalidProjectOperationException e) {
// not a role folder - silently ignore
}
return retVal;
}
/**
* This method find the absolute path from
* relative path.
*
* @param path : relative path
* @return absolute path
*/
public static String convertPath(Project project, String path) {
String newPath = "";
if (path.startsWith(BASE_PATH)) {
String projectPath = project.getBasePath();
String rplStr = path.substring(path.indexOf('}') + 4, path.length());
newPath = String.format("%s%s", projectPath, rplStr);
} else {
newPath = path;
}
return newPath;
}
/**
* This method returns the deployment name of any component
* it also prepares the name if name is not specified.
*
* @param path
* @param method
* @param asName
* @return
*/
public static String getAsName(Project project, String path,
WindowsAzureRoleComponentImportMethod method,
String asName) {
String name;
if (asName.isEmpty()) {
name = new File(path).getName();
if (method == WindowsAzureRoleComponentImportMethod.auto) {
// ProjExportType type = ProjectNatureHelper.getProjectNature(PluginUtil.findModule(project, convertPath(project, path)));
// todo!!!
ProjExportType type = ProjExportType.WAR;
name = String.format("%s%s%s", name, ".", type.name().toLowerCase());
} else if (method == WindowsAzureRoleComponentImportMethod.zip) {
name = String.format("%s%s", name, ".zip");
}
} else {
name = asName;
}
return name;
}
public static Module findModule(Project project, String path) {
for (Module module : ModuleManager.getInstance(project).getModules()) {
if (PluginUtil.getModulePath(module).equals(path)) {
return module;
}
}
return null;
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kafka.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
*
<p>
* Provisioned cluster.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kafka-2018-11-14/Provisioned" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Provisioned implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* Information about the brokers.
* </p>
*/
private BrokerNodeGroupInfo brokerNodeGroupInfo;
/**
* <p>
* Information about the Apache Kafka version deployed on the brokers.
* </p>
*/
private BrokerSoftwareInfo currentBrokerSoftwareInfo;
/**
* <p>
* Includes all client authentication information.
* </p>
*/
private ClientAuthentication clientAuthentication;
/**
* <p>
* Includes all encryption-related information.
* </p>
*/
private EncryptionInfo encryptionInfo;
/**
* <p>
* Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER,
* PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.
* </p>
*/
private String enhancedMonitoring;
/**
* <p>
* The settings for open monitoring.
* </p>
*/
private OpenMonitoringInfo openMonitoring;
/**
* <p>
* Log delivery information for the cluster.
* </p>
*/
private LoggingInfo loggingInfo;
/**
* <p>
* The number of broker nodes in the cluster.
* </p>
*/
private Integer numberOfBrokerNodes;
/**
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster.
* </p>
*/
private String zookeeperConnectString;
/**
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster on a TLS port.
* </p>
*/
private String zookeeperConnectStringTls;
/**
* <p>
* Information about the brokers.
* </p>
*
* @param brokerNodeGroupInfo
* <p>
* Information about the brokers.
* </p>
*/
public void setBrokerNodeGroupInfo(BrokerNodeGroupInfo brokerNodeGroupInfo) {
this.brokerNodeGroupInfo = brokerNodeGroupInfo;
}
/**
* <p>
* Information about the brokers.
* </p>
*
* @return <p>
* Information about the brokers.
* </p>
*/
public BrokerNodeGroupInfo getBrokerNodeGroupInfo() {
return this.brokerNodeGroupInfo;
}
/**
* <p>
* Information about the brokers.
* </p>
*
* @param brokerNodeGroupInfo
* <p>
* Information about the brokers.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Provisioned withBrokerNodeGroupInfo(BrokerNodeGroupInfo brokerNodeGroupInfo) {
setBrokerNodeGroupInfo(brokerNodeGroupInfo);
return this;
}
/**
* <p>
* Information about the Apache Kafka version deployed on the brokers.
* </p>
*
* @param currentBrokerSoftwareInfo
* <p>
* Information about the Apache Kafka version deployed on the brokers.
* </p>
*/
public void setCurrentBrokerSoftwareInfo(BrokerSoftwareInfo currentBrokerSoftwareInfo) {
this.currentBrokerSoftwareInfo = currentBrokerSoftwareInfo;
}
/**
* <p>
* Information about the Apache Kafka version deployed on the brokers.
* </p>
*
* @return <p>
* Information about the Apache Kafka version deployed on the brokers.
* </p>
*/
public BrokerSoftwareInfo getCurrentBrokerSoftwareInfo() {
return this.currentBrokerSoftwareInfo;
}
/**
* <p>
* Information about the Apache Kafka version deployed on the brokers.
* </p>
*
* @param currentBrokerSoftwareInfo
* <p>
* Information about the Apache Kafka version deployed on the brokers.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Provisioned withCurrentBrokerSoftwareInfo(BrokerSoftwareInfo currentBrokerSoftwareInfo) {
setCurrentBrokerSoftwareInfo(currentBrokerSoftwareInfo);
return this;
}
/**
* <p>
* Includes all client authentication information.
* </p>
*
* @param clientAuthentication
* <p>
* Includes all client authentication information.
* </p>
*/
public void setClientAuthentication(ClientAuthentication clientAuthentication) {
this.clientAuthentication = clientAuthentication;
}
/**
* <p>
* Includes all client authentication information.
* </p>
*
* @return <p>
* Includes all client authentication information.
* </p>
*/
public ClientAuthentication getClientAuthentication() {
return this.clientAuthentication;
}
/**
* <p>
* Includes all client authentication information.
* </p>
*
* @param clientAuthentication
* <p>
* Includes all client authentication information.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Provisioned withClientAuthentication(ClientAuthentication clientAuthentication) {
setClientAuthentication(clientAuthentication);
return this;
}
/**
* <p>
* Includes all encryption-related information.
* </p>
*
* @param encryptionInfo
* <p>
* Includes all encryption-related information.
* </p>
*/
public void setEncryptionInfo(EncryptionInfo encryptionInfo) {
this.encryptionInfo = encryptionInfo;
}
/**
* <p>
* Includes all encryption-related information.
* </p>
*
* @return <p>
* Includes all encryption-related information.
* </p>
*/
public EncryptionInfo getEncryptionInfo() {
return this.encryptionInfo;
}
/**
* <p>
* Includes all encryption-related information.
* </p>
*
* @param encryptionInfo
* <p>
* Includes all encryption-related information.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Provisioned withEncryptionInfo(EncryptionInfo encryptionInfo) {
setEncryptionInfo(encryptionInfo);
return this;
}
/**
* <p>
* Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER,
* PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.
* </p>
*
* @param enhancedMonitoring
* <p>
* Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER,
* PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.
* </p>
* @see EnhancedMonitoring
*/
public void setEnhancedMonitoring(String enhancedMonitoring) {
this.enhancedMonitoring = enhancedMonitoring;
}
/**
* <p>
* Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER,
* PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.
* </p>
*
* @return <p>
* Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER,
* PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.
* </p>
* @see EnhancedMonitoring
*/
public String getEnhancedMonitoring() {
return this.enhancedMonitoring;
}
/**
* <p>
* Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER,
* PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.
* </p>
*
* @param enhancedMonitoring
* <p>
* Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER,
* PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
* @see EnhancedMonitoring
*/
public Provisioned withEnhancedMonitoring(String enhancedMonitoring) {
setEnhancedMonitoring(enhancedMonitoring);
return this;
}
/**
* <p>
* Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER,
* PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.
* </p>
*
* @param enhancedMonitoring
* <p>
* Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER,
* PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
* @see EnhancedMonitoring
*/
public Provisioned withEnhancedMonitoring(EnhancedMonitoring enhancedMonitoring) {
this.enhancedMonitoring = enhancedMonitoring.toString();
return this;
}
/**
* <p>
* The settings for open monitoring.
* </p>
*
* @param openMonitoring
* <p>
* The settings for open monitoring.
* </p>
*/
public void setOpenMonitoring(OpenMonitoringInfo openMonitoring) {
this.openMonitoring = openMonitoring;
}
/**
* <p>
* The settings for open monitoring.
* </p>
*
* @return <p>
* The settings for open monitoring.
* </p>
*/
public OpenMonitoringInfo getOpenMonitoring() {
return this.openMonitoring;
}
/**
* <p>
* The settings for open monitoring.
* </p>
*
* @param openMonitoring
* <p>
* The settings for open monitoring.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Provisioned withOpenMonitoring(OpenMonitoringInfo openMonitoring) {
setOpenMonitoring(openMonitoring);
return this;
}
/**
* <p>
* Log delivery information for the cluster.
* </p>
*
* @param loggingInfo
* <p>
* Log delivery information for the cluster.
* </p>
*/
public void setLoggingInfo(LoggingInfo loggingInfo) {
this.loggingInfo = loggingInfo;
}
/**
* <p>
* Log delivery information for the cluster.
* </p>
*
* @return <p>
* Log delivery information for the cluster.
* </p>
*/
public LoggingInfo getLoggingInfo() {
return this.loggingInfo;
}
/**
* <p>
* Log delivery information for the cluster.
* </p>
*
* @param loggingInfo
* <p>
* Log delivery information for the cluster.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Provisioned withLoggingInfo(LoggingInfo loggingInfo) {
setLoggingInfo(loggingInfo);
return this;
}
/**
* <p>
* The number of broker nodes in the cluster.
* </p>
*
* @param numberOfBrokerNodes
* <p>
* The number of broker nodes in the cluster.
* </p>
*/
public void setNumberOfBrokerNodes(Integer numberOfBrokerNodes) {
this.numberOfBrokerNodes = numberOfBrokerNodes;
}
/**
* <p>
* The number of broker nodes in the cluster.
* </p>
*
* @return <p>
* The number of broker nodes in the cluster.
* </p>
*/
public Integer getNumberOfBrokerNodes() {
return this.numberOfBrokerNodes;
}
/**
* <p>
* The number of broker nodes in the cluster.
* </p>
*
* @param numberOfBrokerNodes
* <p>
* The number of broker nodes in the cluster.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Provisioned withNumberOfBrokerNodes(Integer numberOfBrokerNodes) {
setNumberOfBrokerNodes(numberOfBrokerNodes);
return this;
}
/**
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster.
* </p>
*
* @param zookeeperConnectString
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster.
* </p>
*/
public void setZookeeperConnectString(String zookeeperConnectString) {
this.zookeeperConnectString = zookeeperConnectString;
}
/**
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster.
* </p>
*
* @return <p>
* The connection string to use to connect to the Apache ZooKeeper cluster.
* </p>
*/
public String getZookeeperConnectString() {
return this.zookeeperConnectString;
}
/**
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster.
* </p>
*
* @param zookeeperConnectString
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Provisioned withZookeeperConnectString(String zookeeperConnectString) {
setZookeeperConnectString(zookeeperConnectString);
return this;
}
/**
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster on a TLS port.
* </p>
*
* @param zookeeperConnectStringTls
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster on a TLS port.
* </p>
*/
public void setZookeeperConnectStringTls(String zookeeperConnectStringTls) {
this.zookeeperConnectStringTls = zookeeperConnectStringTls;
}
/**
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster on a TLS port.
* </p>
*
* @return <p>
* The connection string to use to connect to the Apache ZooKeeper cluster on a TLS port.
* </p>
*/
public String getZookeeperConnectStringTls() {
return this.zookeeperConnectStringTls;
}
/**
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster on a TLS port.
* </p>
*
* @param zookeeperConnectStringTls
* <p>
* The connection string to use to connect to the Apache ZooKeeper cluster on a TLS port.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Provisioned withZookeeperConnectStringTls(String zookeeperConnectStringTls) {
setZookeeperConnectStringTls(zookeeperConnectStringTls);
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 (getBrokerNodeGroupInfo() != null)
sb.append("BrokerNodeGroupInfo: ").append(getBrokerNodeGroupInfo()).append(",");
if (getCurrentBrokerSoftwareInfo() != null)
sb.append("CurrentBrokerSoftwareInfo: ").append(getCurrentBrokerSoftwareInfo()).append(",");
if (getClientAuthentication() != null)
sb.append("ClientAuthentication: ").append(getClientAuthentication()).append(",");
if (getEncryptionInfo() != null)
sb.append("EncryptionInfo: ").append(getEncryptionInfo()).append(",");
if (getEnhancedMonitoring() != null)
sb.append("EnhancedMonitoring: ").append(getEnhancedMonitoring()).append(",");
if (getOpenMonitoring() != null)
sb.append("OpenMonitoring: ").append(getOpenMonitoring()).append(",");
if (getLoggingInfo() != null)
sb.append("LoggingInfo: ").append(getLoggingInfo()).append(",");
if (getNumberOfBrokerNodes() != null)
sb.append("NumberOfBrokerNodes: ").append(getNumberOfBrokerNodes()).append(",");
if (getZookeeperConnectString() != null)
sb.append("ZookeeperConnectString: ").append(getZookeeperConnectString()).append(",");
if (getZookeeperConnectStringTls() != null)
sb.append("ZookeeperConnectStringTls: ").append(getZookeeperConnectStringTls());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Provisioned == false)
return false;
Provisioned other = (Provisioned) obj;
if (other.getBrokerNodeGroupInfo() == null ^ this.getBrokerNodeGroupInfo() == null)
return false;
if (other.getBrokerNodeGroupInfo() != null && other.getBrokerNodeGroupInfo().equals(this.getBrokerNodeGroupInfo()) == false)
return false;
if (other.getCurrentBrokerSoftwareInfo() == null ^ this.getCurrentBrokerSoftwareInfo() == null)
return false;
if (other.getCurrentBrokerSoftwareInfo() != null && other.getCurrentBrokerSoftwareInfo().equals(this.getCurrentBrokerSoftwareInfo()) == false)
return false;
if (other.getClientAuthentication() == null ^ this.getClientAuthentication() == null)
return false;
if (other.getClientAuthentication() != null && other.getClientAuthentication().equals(this.getClientAuthentication()) == false)
return false;
if (other.getEncryptionInfo() == null ^ this.getEncryptionInfo() == null)
return false;
if (other.getEncryptionInfo() != null && other.getEncryptionInfo().equals(this.getEncryptionInfo()) == false)
return false;
if (other.getEnhancedMonitoring() == null ^ this.getEnhancedMonitoring() == null)
return false;
if (other.getEnhancedMonitoring() != null && other.getEnhancedMonitoring().equals(this.getEnhancedMonitoring()) == false)
return false;
if (other.getOpenMonitoring() == null ^ this.getOpenMonitoring() == null)
return false;
if (other.getOpenMonitoring() != null && other.getOpenMonitoring().equals(this.getOpenMonitoring()) == false)
return false;
if (other.getLoggingInfo() == null ^ this.getLoggingInfo() == null)
return false;
if (other.getLoggingInfo() != null && other.getLoggingInfo().equals(this.getLoggingInfo()) == false)
return false;
if (other.getNumberOfBrokerNodes() == null ^ this.getNumberOfBrokerNodes() == null)
return false;
if (other.getNumberOfBrokerNodes() != null && other.getNumberOfBrokerNodes().equals(this.getNumberOfBrokerNodes()) == false)
return false;
if (other.getZookeeperConnectString() == null ^ this.getZookeeperConnectString() == null)
return false;
if (other.getZookeeperConnectString() != null && other.getZookeeperConnectString().equals(this.getZookeeperConnectString()) == false)
return false;
if (other.getZookeeperConnectStringTls() == null ^ this.getZookeeperConnectStringTls() == null)
return false;
if (other.getZookeeperConnectStringTls() != null && other.getZookeeperConnectStringTls().equals(this.getZookeeperConnectStringTls()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getBrokerNodeGroupInfo() == null) ? 0 : getBrokerNodeGroupInfo().hashCode());
hashCode = prime * hashCode + ((getCurrentBrokerSoftwareInfo() == null) ? 0 : getCurrentBrokerSoftwareInfo().hashCode());
hashCode = prime * hashCode + ((getClientAuthentication() == null) ? 0 : getClientAuthentication().hashCode());
hashCode = prime * hashCode + ((getEncryptionInfo() == null) ? 0 : getEncryptionInfo().hashCode());
hashCode = prime * hashCode + ((getEnhancedMonitoring() == null) ? 0 : getEnhancedMonitoring().hashCode());
hashCode = prime * hashCode + ((getOpenMonitoring() == null) ? 0 : getOpenMonitoring().hashCode());
hashCode = prime * hashCode + ((getLoggingInfo() == null) ? 0 : getLoggingInfo().hashCode());
hashCode = prime * hashCode + ((getNumberOfBrokerNodes() == null) ? 0 : getNumberOfBrokerNodes().hashCode());
hashCode = prime * hashCode + ((getZookeeperConnectString() == null) ? 0 : getZookeeperConnectString().hashCode());
hashCode = prime * hashCode + ((getZookeeperConnectStringTls() == null) ? 0 : getZookeeperConnectStringTls().hashCode());
return hashCode;
}
@Override
public Provisioned clone() {
try {
return (Provisioned) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.kafka.model.transform.ProvisionedMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
package io.spotnext.infrastructure.type;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Version;
import org.apache.commons.collections4.comparators.NullComparator;
import org.hibernate.Hibernate;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.Index;
import org.hibernate.annotations.UpdateTimestamp;
import org.hibernate.proxy.HibernateProxy;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.spotnext.infrastructure.IdGenerator;
import io.spotnext.infrastructure.IndirectPropertyAccess;
import io.spotnext.infrastructure.annotation.ItemType;
import io.spotnext.infrastructure.annotation.Property;
import io.spotnext.support.util.ClassUtil;
// Hibernate
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "items")
// JPA
@Cacheable
@MappedSuperclass
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@EntityListeners({ AuditingEntityListener.class })
public abstract class Item implements Serializable, Comparable<Item>, IndirectPropertyAccess {
private static final long serialVersionUID = 1L;
public static final String TYPECODE = "item";
public static final String PROPERTY_ID = "id";
public static final String PROPERTY_LAST_MODIFIED_AT = "lastModifiedAt";
public static final String PROPERTY_CREATED_AT = "createdAt";
// @Autowired
// protected AuditingHandler auditingHandler;
// JPA
@Id
@Column(name = "id")
final protected Long id = IdGenerator.createLongId();
// @Index(name = "idx_createdAt")
@CreationTimestamp
@CreatedDate
protected Date createdAt;
@CreatedBy
protected String createdBy;
// @Index(name = "idx_lastModifiedAt")
@UpdateTimestamp
@LastModifiedDate
// the index is needed for ORDER BY in combination with FETCH JOINS and pagination!
// @Property(indexed = true)
@Index(name = "idx_Item_lastModifiedAt")
protected Date lastModifiedAt;
@LastModifiedBy
protected String lastModifiedBy;
@Version
protected int version = -1;
/**
* Indicates that the given item is deleted. This property can be used to implemented "soft-deletion"
*/
@Column
protected boolean deleted = false;
/**
* Returns a hash code calculated of all properties that are defined as unique (with the {@link Property} annotation). This is necessary to implement
* extendible combined unique constraints, regardless of which JPA inheritance strategy is used
*/
@Column(name = "uniquenessHash", unique = true, nullable = false)
private Integer uniquenessHash = null;
/**
* A value of -1 indicates that this is an unpersisted item.
*
* @return the internal version of the Item, used for optimistic locking
*/
public int getVersion() {
return version;
}
public Long getId() {
return id;
}
@PrePersist
public void prePersist() {
this.createdAt = new Date();
updateUniquenessHash();
}
/**
* Update uniqueness hash. This is the only column that has JPA unique-key constraint! This is necessary to make the {@link Column#unique()} annotation work
* with all JPA inheritance strategies.
*/
protected void updateUniquenessHash() {
final Map<String, Object> uniqueProperties = getUniqueHashProperties();
// check
if (uniqueProperties.size() > 0) {
final Collection<Object> uniquePropertyValues = uniqueProperties.values().stream().map(v -> {
final Object prop;
// transform all sub items into uniqueness hashes, use the real value of all
// other properties
if (v instanceof Item) {
prop = ((Item) v).uniquenessHash();
} else {
prop = v;
}
return prop;
}).collect(Collectors.toList());
uniquePropertyValues.add(getTypeCode());
// create a hashcode
this.uniquenessHash = Objects.hash(uniquePropertyValues.toArray());
} else {
// use the ID as fallback, if no unique properties exist or all are null
this.uniquenessHash = Objects.hash(this.id);
}
}
@PreUpdate
protected void preUpdate() {
setLastModifiedAt();
updateUniquenessHash();
}
protected void setLastModifiedAt() {
this.lastModifiedAt = new Date();
}
public int uniquenessHash() {
return getUniqueHashProperties().hashCode();
}
public void setCreatedBy(final String createdBy) {
this.createdBy = createdBy;
}
public String getCreatedBy() {
return createdBy;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(final String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public LocalDateTime getLastModifiedAt() {
return lastModifiedAt != null ? LocalDateTime.ofInstant(lastModifiedAt.toInstant(), ZoneId.systemDefault()) : null;
}
public LocalDateTime getCreatedAt() {
return createdAt != null ? LocalDateTime.ofInstant(createdAt.toInstant(), ZoneId.systemDefault()) : null;
}
/**
* @return true if the item has a ID. It is assumed that it has been saved before. If you set a ID manually and save the item, an existing item with the
* same ID will be overwritten.
*/
public boolean isPersisted() {
return id != null;
}
/**
* Mark the object as dirty, even though it might no be.
*/
public void markAsDirty() {
// auditingHandler.markModified(this);
setLastModifiedAt();
}
/**
* Returns the names and the values of all properties annotated with @Unique.
*
* @return a map containing all the unique properties for this Item (key = property name)
*/
public Map<String, Object> getUniqueHashProperties() {
return getProperties(this::isUniqueField);
}
/**
* Returns all fields annotated with the {@link Property} annotation.
*
* @param filter can be null or a predicate that further filters the returned item properties.
* @return all filtered item properties
*/
@JsonIgnore
public Map<String, Object> getProperties(BiPredicate<Field, Object> filter) {
// TODO is this really necessary?
if (this instanceof HibernateProxy) {
if (!Hibernate.isInitialized(this)) {
Hibernate.initialize(this);
}
}
return IndirectPropertyAccess.super.getProperties(filter);
}
private boolean isUniqueField(Field field, Object fieldValue) {
final Property prop = ClassUtil.getAnnotation(field, Property.class);
return prop != null && prop.unique();
}
/**
* If the type and the id of the given object is the same as the current object, both are equal.
*
* @see Object#equals(Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null || !(obj.getClass().equals(this.getClass()))) {
return false;
}
if (id == null) {
return false;
}
return this.id.equals(((Item) obj).id);
}
@Override
public int hashCode() {
if (id != null) {
return id.hashCode();
} else {
return super.hashCode();
}
}
@Override
public int compareTo(final Item obj) {
if (equals(obj)) {
return 0;
}
if (obj != null) {
return Objects.compare(this.id, obj.id, new NullComparator<Long>());
} else {
return 1;
}
}
public String getTypeCode() {
final ItemType ann = ClassUtil.getAnnotation(this.getClass(), ItemType.class);
return ann.typeCode();
}
}
| |
/*
* 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.lambda.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
* Container for the parameters to the {@link com.amazonaws.services.lambda.AWSLambda#updateAlias(UpdateAliasRequest) UpdateAlias operation}.
* <p>
* Using this API you can update function version to which the alias
* points to and alias description. For more information, see
* <a href="http://docs.aws.amazon.com/lambda/latest/dg/versioning-v2-intro-aliases.html"> Introduction to AWS Lambda Aliases </a>
*
* </p>
* <p>
* This requires permission for the lambda:UpdateAlias action.
* </p>
*
* @see com.amazonaws.services.lambda.AWSLambda#updateAlias(UpdateAliasRequest)
*/
public class UpdateAliasRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* The function name for which the alias is created.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 140<br/>
* <b>Pattern: </b>(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*/
private String functionName;
/**
* The alias name.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
* <b>Pattern: </b>(?!^[0-9]+$)([a-zA-Z0-9-_]+)<br/>
*/
private String name;
/**
* Using this parameter you can optionally change the Lambda function
* version to which the alias to points to.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
* <b>Pattern: </b>(\$LATEST|[0-9]+)<br/>
*/
private String functionVersion;
/**
* You can optionally change the description of the alias using this
* parameter.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 256<br/>
*/
private String description;
/**
* The function name for which the alias is created.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 140<br/>
* <b>Pattern: </b>(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*
* @return The function name for which the alias is created.
*/
public String getFunctionName() {
return functionName;
}
/**
* The function name for which the alias is created.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 140<br/>
* <b>Pattern: </b>(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*
* @param functionName The function name for which the alias is created.
*/
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
/**
* The function name for which the alias is created.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 140<br/>
* <b>Pattern: </b>(arn:aws:lambda:)?([a-z]{2}-[a-z]+-\d{1}:)?(\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?<br/>
*
* @param functionName The function name for which the alias is created.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UpdateAliasRequest withFunctionName(String functionName) {
this.functionName = functionName;
return this;
}
/**
* The alias name.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
* <b>Pattern: </b>(?!^[0-9]+$)([a-zA-Z0-9-_]+)<br/>
*
* @return The alias name.
*/
public String getName() {
return name;
}
/**
* The alias name.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
* <b>Pattern: </b>(?!^[0-9]+$)([a-zA-Z0-9-_]+)<br/>
*
* @param name The alias name.
*/
public void setName(String name) {
this.name = name;
}
/**
* The alias name.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
* <b>Pattern: </b>(?!^[0-9]+$)([a-zA-Z0-9-_]+)<br/>
*
* @param name The alias name.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UpdateAliasRequest withName(String name) {
this.name = name;
return this;
}
/**
* Using this parameter you can optionally change the Lambda function
* version to which the alias to points to.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
* <b>Pattern: </b>(\$LATEST|[0-9]+)<br/>
*
* @return Using this parameter you can optionally change the Lambda function
* version to which the alias to points to.
*/
public String getFunctionVersion() {
return functionVersion;
}
/**
* Using this parameter you can optionally change the Lambda function
* version to which the alias to points to.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
* <b>Pattern: </b>(\$LATEST|[0-9]+)<br/>
*
* @param functionVersion Using this parameter you can optionally change the Lambda function
* version to which the alias to points to.
*/
public void setFunctionVersion(String functionVersion) {
this.functionVersion = functionVersion;
}
/**
* Using this parameter you can optionally change the Lambda function
* version to which the alias to points to.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
* <b>Pattern: </b>(\$LATEST|[0-9]+)<br/>
*
* @param functionVersion Using this parameter you can optionally change the Lambda function
* version to which the alias to points to.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UpdateAliasRequest withFunctionVersion(String functionVersion) {
this.functionVersion = functionVersion;
return this;
}
/**
* You can optionally change the description of the alias using this
* parameter.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 256<br/>
*
* @return You can optionally change the description of the alias using this
* parameter.
*/
public String getDescription() {
return description;
}
/**
* You can optionally change the description of the alias using this
* parameter.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 256<br/>
*
* @param description You can optionally change the description of the alias using this
* parameter.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* You can optionally change the description of the alias using this
* parameter.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 256<br/>
*
* @param description You can optionally change the description of the alias using this
* parameter.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UpdateAliasRequest withDescription(String description) {
this.description = description;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getFunctionName() != null) sb.append("FunctionName: " + getFunctionName() + ",");
if (getName() != null) sb.append("Name: " + getName() + ",");
if (getFunctionVersion() != null) sb.append("FunctionVersion: " + getFunctionVersion() + ",");
if (getDescription() != null) sb.append("Description: " + getDescription() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getFunctionName() == null) ? 0 : getFunctionName().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getFunctionVersion() == null) ? 0 : getFunctionVersion().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof UpdateAliasRequest == false) return false;
UpdateAliasRequest other = (UpdateAliasRequest)obj;
if (other.getFunctionName() == null ^ this.getFunctionName() == null) return false;
if (other.getFunctionName() != null && other.getFunctionName().equals(this.getFunctionName()) == false) return false;
if (other.getName() == null ^ this.getName() == null) return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false) return false;
if (other.getFunctionVersion() == null ^ this.getFunctionVersion() == null) return false;
if (other.getFunctionVersion() != null && other.getFunctionVersion().equals(this.getFunctionVersion()) == false) return false;
if (other.getDescription() == null ^ this.getDescription() == null) return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false;
return true;
}
@Override
public UpdateAliasRequest clone() {
return (UpdateAliasRequest) super.clone();
}
}
| |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver12;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFBsnBwEnableGetRequestVer12 implements OFBsnBwEnableGetRequest {
private static final Logger logger = LoggerFactory.getLogger(OFBsnBwEnableGetRequestVer12.class);
// version: 1.2
final static byte WIRE_VERSION = 3;
final static int LENGTH = 16;
private final static long DEFAULT_XID = 0x0L;
// OF message fields
private final long xid;
//
// Immutable default instance
final static OFBsnBwEnableGetRequestVer12 DEFAULT = new OFBsnBwEnableGetRequestVer12(
DEFAULT_XID
);
// package private constructor - used by readers, builders, and factory
OFBsnBwEnableGetRequestVer12(long xid) {
this.xid = U32.normalize(xid);
}
// Accessors for OF message fields
@Override
public OFVersion getVersion() {
return OFVersion.OF_12;
}
@Override
public OFType getType() {
return OFType.EXPERIMENTER;
}
@Override
public long getXid() {
return xid;
}
@Override
public long getExperimenter() {
return 0x5c16c7L;
}
@Override
public long getSubtype() {
return 0x13L;
}
public OFBsnBwEnableGetRequest.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFBsnBwEnableGetRequest.Builder {
final OFBsnBwEnableGetRequestVer12 parentMessage;
// OF message fields
private boolean xidSet;
private long xid;
BuilderWithParent(OFBsnBwEnableGetRequestVer12 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_12;
}
@Override
public OFType getType() {
return OFType.EXPERIMENTER;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFBsnBwEnableGetRequest.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public long getExperimenter() {
return 0x5c16c7L;
}
@Override
public long getSubtype() {
return 0x13L;
}
@Override
public OFBsnBwEnableGetRequest build() {
long xid = this.xidSet ? this.xid : parentMessage.xid;
//
return new OFBsnBwEnableGetRequestVer12(
xid
);
}
}
static class Builder implements OFBsnBwEnableGetRequest.Builder {
// OF message fields
private boolean xidSet;
private long xid;
@Override
public OFVersion getVersion() {
return OFVersion.OF_12;
}
@Override
public OFType getType() {
return OFType.EXPERIMENTER;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFBsnBwEnableGetRequest.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public long getExperimenter() {
return 0x5c16c7L;
}
@Override
public long getSubtype() {
return 0x13L;
}
//
@Override
public OFBsnBwEnableGetRequest build() {
long xid = this.xidSet ? this.xid : DEFAULT_XID;
return new OFBsnBwEnableGetRequestVer12(
xid
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFBsnBwEnableGetRequest> {
@Override
public OFBsnBwEnableGetRequest readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property version == 3
byte version = bb.readByte();
if(version != (byte) 0x3)
throw new OFParseError("Wrong version: Expected=OFVersion.OF_12(3), got="+version);
// fixed value property type == 4
byte type = bb.readByte();
if(type != (byte) 0x4)
throw new OFParseError("Wrong type: Expected=OFType.EXPERIMENTER(4), got="+type);
int length = U16.f(bb.readShort());
if(length != 16)
throw new OFParseError("Wrong length: Expected=16(16), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long xid = U32.f(bb.readInt());
// fixed value property experimenter == 0x5c16c7L
int experimenter = bb.readInt();
if(experimenter != 0x5c16c7)
throw new OFParseError("Wrong experimenter: Expected=0x5c16c7L(0x5c16c7L), got="+experimenter);
// fixed value property subtype == 0x13L
int subtype = bb.readInt();
if(subtype != 0x13)
throw new OFParseError("Wrong subtype: Expected=0x13L(0x13L), got="+subtype);
OFBsnBwEnableGetRequestVer12 bsnBwEnableGetRequestVer12 = new OFBsnBwEnableGetRequestVer12(
xid
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", bsnBwEnableGetRequestVer12);
return bsnBwEnableGetRequestVer12;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFBsnBwEnableGetRequestVer12Funnel FUNNEL = new OFBsnBwEnableGetRequestVer12Funnel();
static class OFBsnBwEnableGetRequestVer12Funnel implements Funnel<OFBsnBwEnableGetRequestVer12> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFBsnBwEnableGetRequestVer12 message, PrimitiveSink sink) {
// fixed value property version = 3
sink.putByte((byte) 0x3);
// fixed value property type = 4
sink.putByte((byte) 0x4);
// fixed value property length = 16
sink.putShort((short) 0x10);
sink.putLong(message.xid);
// fixed value property experimenter = 0x5c16c7L
sink.putInt(0x5c16c7);
// fixed value property subtype = 0x13L
sink.putInt(0x13);
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFBsnBwEnableGetRequestVer12> {
@Override
public void write(ByteBuf bb, OFBsnBwEnableGetRequestVer12 message) {
// fixed value property version = 3
bb.writeByte((byte) 0x3);
// fixed value property type = 4
bb.writeByte((byte) 0x4);
// fixed value property length = 16
bb.writeShort((short) 0x10);
bb.writeInt(U32.t(message.xid));
// fixed value property experimenter = 0x5c16c7L
bb.writeInt(0x5c16c7);
// fixed value property subtype = 0x13L
bb.writeInt(0x13);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFBsnBwEnableGetRequestVer12(");
b.append("xid=").append(xid);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFBsnBwEnableGetRequestVer12 other = (OFBsnBwEnableGetRequestVer12) obj;
if( xid != other.xid)
return false;
return true;
}
@Override
public boolean equalsIgnoreXid(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFBsnBwEnableGetRequestVer12 other = (OFBsnBwEnableGetRequestVer12) obj;
// ignore XID
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (xid ^ (xid >>> 32));
return result;
}
@Override
public int hashCodeIgnoreXid() {
final int prime = 31;
int result = 1;
// ignore XID
return result;
}
}
| |
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util.internal;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.Closeable;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Locale;
/**
* Helper class to load JNI resources.
*
*/
public final class NativeLibraryLoader {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(NativeLibraryLoader.class);
private static final String NATIVE_RESOURCE_HOME = "META-INF/native/";
private static final String OSNAME;
private static final File WORKDIR;
private static final boolean DELETE_NATIVE_LIB_AFTER_LOADING;
static {
OSNAME = SystemPropertyUtil.get("os.name", "").toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", "");
String workdir = SystemPropertyUtil.get("io.netty.native.workdir");
if (workdir != null) {
File f = new File(workdir);
f.mkdirs();
try {
f = f.getAbsoluteFile();
} catch (Exception ignored) {
// Good to have an absolute path, but it's OK.
}
WORKDIR = f;
logger.debug("-Dio.netty.native.workdir: " + WORKDIR);
} else {
WORKDIR = tmpdir();
logger.debug("-Dio.netty.native.workdir: " + WORKDIR + " (io.netty.tmpdir)");
}
DELETE_NATIVE_LIB_AFTER_LOADING = SystemPropertyUtil.getBoolean(
"io.netty.native.deleteLibAfterLoading", true);
}
private static File tmpdir() {
File f;
try {
f = toDirectory(SystemPropertyUtil.get("io.netty.tmpdir"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: " + f);
return f;
}
f = toDirectory(SystemPropertyUtil.get("java.io.tmpdir"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: " + f + " (java.io.tmpdir)");
return f;
}
// This shouldn't happen, but just in case ..
if (isWindows()) {
f = toDirectory(System.getenv("TEMP"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: " + f + " (%TEMP%)");
return f;
}
String userprofile = System.getenv("USERPROFILE");
if (userprofile != null) {
f = toDirectory(userprofile + "\\AppData\\Local\\Temp");
if (f != null) {
logger.debug("-Dio.netty.tmpdir: " + f + " (%USERPROFILE%\\AppData\\Local\\Temp)");
return f;
}
f = toDirectory(userprofile + "\\Local Settings\\Temp");
if (f != null) {
logger.debug("-Dio.netty.tmpdir: " + f + " (%USERPROFILE%\\Local Settings\\Temp)");
return f;
}
}
} else {
f = toDirectory(System.getenv("TMPDIR"));
if (f != null) {
logger.debug("-Dio.netty.tmpdir: " + f + " ($TMPDIR)");
return f;
}
}
} catch (Exception ignored) {
// Environment variable inaccessible
}
// Last resort.
if (isWindows()) {
f = new File("C:\\Windows\\Temp");
} else {
f = new File("/tmp");
}
logger.warn("Failed to get the temporary directory; falling back to: " + f);
return f;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static File toDirectory(String path) {
if (path == null) {
return null;
}
File f = new File(path);
f.mkdirs();
if (!f.isDirectory()) {
return null;
}
try {
return f.getAbsoluteFile();
} catch (Exception ignored) {
return f;
}
}
private static boolean isWindows() {
return OSNAME.startsWith("windows");
}
private static boolean isOSX() {
return OSNAME.startsWith("macosx") || OSNAME.startsWith("osx");
}
/**
* Loads the first available library in the collection with the specified
* {@link ClassLoader}.
*
* @throws IllegalArgumentException
* if none of the given libraries load successfully.
*/
public static void loadFirstAvailable(ClassLoader loader, String... names) {
for (String name : names) {
try {
load(name, loader);
logger.debug("Successfully loaded the library: {}", name);
return;
} catch (Throwable t) {
logger.debug("Unable to load the library '{}', trying next name...", name, t);
}
}
throw new IllegalArgumentException("Failed to load any of the given libraries: "
+ Arrays.toString(names));
}
/**
* Load the given library with the specified {@link ClassLoader}
*/
public static void load(String originalName, ClassLoader loader) {
// Adjust expected name to support shading of native libraries.
String name = SystemPropertyUtil.get("io.netty.packagePrefix", "").replace('.', '-') + originalName;
String libname = System.mapLibraryName(name);
String path = NATIVE_RESOURCE_HOME + libname;
URL url = loader.getResource(path);
if (url == null && isOSX()) {
if (path.endsWith(".jnilib")) {
url = loader.getResource(NATIVE_RESOURCE_HOME + "lib" + name + ".dynlib");
} else {
url = loader.getResource(NATIVE_RESOURCE_HOME + "lib" + name + ".jnilib");
}
}
if (url == null) {
// Fall back to normal loading of JNI stuff
loadLibrary(loader, name, false);
return;
}
int index = libname.lastIndexOf('.');
String prefix = libname.substring(0, index);
String suffix = libname.substring(index, libname.length());
InputStream in = null;
OutputStream out = null;
File tmpFile = null;
try {
tmpFile = File.createTempFile(prefix, suffix, WORKDIR);
in = url.openStream();
out = new FileOutputStream(tmpFile);
byte[] buffer = new byte[8192];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
// Close the output stream before loading the unpacked library,
// because otherwise Windows will refuse to load it when it's in use by other process.
closeQuietly(out);
out = null;
loadLibrary(loader, tmpFile.getPath(), true);
} catch (Exception e) {
throw (UnsatisfiedLinkError) new UnsatisfiedLinkError(
"could not load a native library: " + name).initCause(e);
} finally {
closeQuietly(in);
closeQuietly(out);
// After we load the library it is safe to delete the file.
// We delete the file immediately to free up resources as soon as possible,
// and if this fails fallback to deleting on JVM exit.
if (tmpFile != null && (!DELETE_NATIVE_LIB_AFTER_LOADING || !tmpFile.delete())) {
tmpFile.deleteOnExit();
}
}
}
/**
* Loading the native library into the specified {@link ClassLoader}.
* @param loader - The {@link ClassLoader} where the native library will be loaded into
* @param name - The native library path or name
* @param absolute - Whether the native library will be loaded by path or by name
*/
private static void loadLibrary(final ClassLoader loader, final String name, final boolean absolute) {
try {
// Make sure the helper is belong to the target ClassLoader.
final Class<?> newHelper = tryToLoadClass(loader, NativeLibraryUtil.class);
loadLibraryByHelper(newHelper, name, absolute);
return;
} catch (UnsatisfiedLinkError e) { // Should by pass the UnsatisfiedLinkError here!
logger.debug("Unable to load the library '{}', trying other loading mechanism.", name, e);
} catch (Exception e) {
logger.debug("Unable to load the library '{}', trying other loading mechanism.", name, e);
}
NativeLibraryUtil.loadLibrary(name, absolute); // Fallback to local helper class.
}
private static void loadLibraryByHelper(final Class<?> helper, final String name, final boolean absolute)
throws UnsatisfiedLinkError {
Object ret = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
// Invoke the helper to load the native library, if succeed, then the native
// library belong to the specified ClassLoader.
Method method = helper.getMethod("loadLibrary", String.class, boolean.class);
method.setAccessible(true);
return method.invoke(null, name, absolute);
} catch (Exception e) {
return e;
}
}
});
if (ret instanceof Throwable) {
Throwable error = (Throwable) ret;
Throwable cause = error.getCause();
if (cause != null) {
if (cause instanceof UnsatisfiedLinkError) {
throw (UnsatisfiedLinkError) cause;
} else {
throw new UnsatisfiedLinkError(cause.getMessage());
}
}
throw new UnsatisfiedLinkError(error.getMessage());
}
}
/**
* Try to load the helper {@link Class} into specified {@link ClassLoader}.
* @param loader - The {@link ClassLoader} where to load the helper {@link Class}
* @param helper - The helper {@link Class}
* @return A new helper Class defined in the specified ClassLoader.
* @throws ClassNotFoundException Helper class not found or loading failed
*/
private static Class<?> tryToLoadClass(final ClassLoader loader, final Class<?> helper)
throws ClassNotFoundException {
try {
return loader.loadClass(helper.getName());
} catch (ClassNotFoundException e) {
// The helper class is NOT found in target ClassLoader, we have to define the helper class.
final byte[] classBinary = classToByteArray(helper);
return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
@Override
public Class<?> run() {
try {
// Define the helper class in the target ClassLoader,
// then we can call the helper to load the native library.
Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class,
byte[].class, int.class, int.class);
defineClass.setAccessible(true);
return (Class<?>) defineClass.invoke(loader, helper.getName(), classBinary, 0,
classBinary.length);
} catch (Exception e) {
throw new IllegalStateException("Define class failed!", e);
}
}
});
}
}
/**
* Load the helper {@link Class} as a byte array, to be redefined in specified {@link ClassLoader}.
* @param clazz - The helper {@link Class} provided by this bundle
* @return The binary content of helper {@link Class}.
* @throws ClassNotFoundException Helper class not found or loading failed
*/
private static byte[] classToByteArray(Class<?> clazz) throws ClassNotFoundException {
String fileName = clazz.getName();
int lastDot = fileName.lastIndexOf('.');
if (lastDot > 0) {
fileName = fileName.substring(lastDot + 1);
}
URL classUrl = clazz.getResource(fileName + ".class");
if (classUrl == null) {
throw new ClassNotFoundException(clazz.getName());
}
byte[] buf = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
InputStream in = null;
try {
in = classUrl.openStream();
for (int r; (r = in.read(buf)) != -1;) {
out.write(buf, 0, r);
}
return out.toByteArray();
} catch (IOException ex) {
throw new ClassNotFoundException(clazz.getName(), ex);
} finally {
closeQuietly(in);
closeQuietly(out);
}
}
private static void closeQuietly(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException ignore) {
// ignore
}
}
}
private NativeLibraryLoader() {
// Utility
}
}
| |
package com.openatk.openatklib.atkmap.views;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.Log;
import android.util.Pair;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.openatk.openatklib.atkmap.listeners.ATKPolygonClickListener;
import com.openatk.openatklib.atkmap.listeners.ATKPolygonDrawListener;
import com.openatk.openatklib.atkmap.models.ATKPolygon;
public class ATKPolygonView {
//Data
private ATKPolygon polygon;
private ATKPolygonViewOptions viewOptions;
//References
private GoogleMap map;
private Polygon mapPolygon;
private Marker mapLabelMarker;
private BitmapDescriptor iconLabel;
private BitmapDescriptor iconLabelSelected;
private PolygonOptions polygonOptions;
private ATKPolygonClickListener clickListener;
private ATKPolygonDrawListener drawListener;
private Object userData;
private String currentLabel;
public ATKPolygonView(GoogleMap map, ATKPolygon polygon){
this.map = map;
this.polygon = polygon;
this.viewOptions = polygon.viewOptions;
this.setLabel(polygon.label);
this.drawPolygon();
}
public void setOnClickListener(ATKPolygonClickListener clickListener){
this.clickListener = clickListener;
}
public void setOnDrawListener(ATKPolygonDrawListener drawListener){ //protected?
this.drawListener = drawListener;
}
public ATKPolygonDrawListener getOnDrawListener(){ //protected?
return this.drawListener;
}
public ATKPolygon getAtkPolygon(){
return polygon;
}
public void setAtkPolygon(ATKPolygon polygon){
this.polygon = polygon; //If the whole model changed
this.drawPolygon();
}
public void update(){
this.drawPolygon();
}
public void remove(){
if(this.mapLabelMarker != null) {
this.mapLabelMarker.remove();
this.mapLabelMarker = null;
}
if(this.mapPolygon != null){
this.mapPolygon.remove();
this.mapPolygon = null;
}
}
public void hide(){
this.viewOptions.setVisible(false);
if(this.mapPolygon != null){
this.mapPolygon.setVisible(false);
}
}
public void show(){
this.viewOptions.setVisible(true);
if(this.mapPolygon != null){
this.mapPolygon.setVisible(true);
}
}
public void setStrokeColor(int color){
this.viewOptions.setStrokeColor(color);
if(this.mapPolygon != null) this.mapPolygon.setStrokeColor(this.viewOptions.getStrokeColor());
}
public void setStrokeColor(float alpha, int red, int green, int blue){
this.viewOptions.setStrokeColor(Color.argb((int)(alpha * 255), red, green, blue));
if(this.mapPolygon != null) this.mapPolygon.setStrokeColor(this.viewOptions.getStrokeColor());
}
public void setFillColor(int color){
this.viewOptions.setFillColor(color);
if(this.mapPolygon != null) this.mapPolygon.setFillColor(this.viewOptions.getFillColor());
}
public void setFillColor(float alpha, int red, int green, int blue){
this.viewOptions.setFillColor(Color.argb((int)(alpha * 255), red, green, blue));
if(this.mapPolygon != null) this.mapPolygon.setFillColor(this.viewOptions.getFillColor());
}
public void setStrokeWidth(float width){
this.viewOptions.setStrokeWidth(width);
if(this.mapPolygon != null) this.mapPolygon.setStrokeWidth(this.viewOptions.getStrokeWidth());
}
public void setOpacity(float opacity){
int fillcolor = this.viewOptions.getFillColor();
this.viewOptions.setFillColor(Color.argb((int)(opacity * 255), Color.red(fillcolor), Color.green(fillcolor), Color.blue(fillcolor)));
if(this.mapPolygon != null) this.mapPolygon.setFillColor(this.viewOptions.getFillColor());
}
public void setZIndex(float zindex){
this.viewOptions.setZindex(zindex);
if(this.mapPolygon != null) this.mapPolygon.setZIndex(this.viewOptions.getZindex());
}
public float getZIndex(){
return this.viewOptions.getZindex();
}
public boolean wasClicked(Point point){ //TODO protected?
//Returns true if clicked, false otherwise
//TODO Speed improvement, store bounding box.
//Convert latlngs to points
List<Point> pointsBoundary = new ArrayList<Point>();
Projection proj = map.getProjection();
for(int i=0; i<this.polygon.boundary.size(); i++){
Point aPoint = proj.toScreenLocation(this.polygon.boundary.get(i));
pointsBoundary.add(aPoint);
}
if(isPointInPolygon(point, pointsBoundary)){
return true;
}
return false;
}
public boolean wasClicked(LatLng point){ //TODO protected?
//Returns null if wasn't clicked, true or false if clicked depending if we consumed it
Point position = this.map.getProjection().toScreenLocation(point);
return this.wasClicked(position);
}
public boolean click(){ //TODO protected?
//Returns true or false depending if listener consumed the click event
if(this.clickListener != null){
return this.clickListener.onPolygonClick(this); //Return if we consumed the click
}
return false;
}
public boolean labelWasClicked(Marker marker){
if(mapLabelMarker != null && this.mapLabelMarker.equals(marker)){
return true;
}
return false;
}
private void drawPolygon(){
if(this.polygon.boundary != null && this.polygon.boundary.size() > 0){
if(this.mapPolygon == null){
//Setup options
this.polygonOptions = new PolygonOptions();
this.polygonOptions.addAll(polygon.boundary);
this.polygonOptions.strokeColor(this.viewOptions.getStrokeColor());
this.polygonOptions.strokeWidth(this.viewOptions.getStrokeWidth());
this.polygonOptions.fillColor(this.viewOptions.getFillColor());
this.polygonOptions.visible(this.viewOptions.isVisible());
this.polygonOptions.zIndex(this.viewOptions.getZindex());
this.mapPolygon = map.addPolygon(this.polygonOptions);
} else {
this.mapPolygon.setPoints(this.polygon.boundary);
}
} else {
//Model doesn't have a boundary remove the polygon from the map
if(this.mapPolygon != null) this.mapPolygon.remove();
this.mapPolygon = null;
}
this.drawLabel();
}
private void drawLabel(){
if(this.polygon.label != null && this.polygon.label.length() > 0 && this.iconLabel != null && this.iconLabelSelected != null && this.polygon.boundary != null && this.polygon.boundary.size() > 2){
if(this.currentLabel.contentEquals(this.polygon.label) == false) setLabel(this.polygon.label);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int i = 0; i < polygon.boundary.size(); i++) {
builder.include(polygon.boundary.get(i));
}
// Have corners
LatLngBounds boundingBox = builder.build();
LatLng where = midPoint(boundingBox.northeast, boundingBox.southwest);
BitmapDescriptor icon;
if(this.viewOptions.isBlnLabelSelected() == true){
icon = this.iconLabelSelected;
} else {
icon = this.iconLabel;
}
if(this.mapLabelMarker == null){
this.mapLabelMarker = map.addMarker(new MarkerOptions().position(where).icon(icon).draggable(false));
} else {
//Move the marker label
this.mapLabelMarker.setPosition(where);
this.mapLabelMarker.setIcon(icon);
}
} else {
if(this.mapLabelMarker != null) this.mapLabelMarker.remove();
this.mapLabelMarker = null;
}
}
public void setLabel(String label){
this.setLabel(label, false);
}
public void setLabel(String label, Boolean selected){
this.currentLabel = label;
this.polygon.label = label;
this.viewOptions.setBlnLabelSelected(selected);
if(label == null || label.trim().length() == 0){
this.drawLabel();
return;
}
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextAlign(Align.LEFT);
paint.setTextSize(20);
paint.setStrokeWidth(12);
Rect bounds = new Rect();
paint.getTextBounds(label, 0, label.length(), bounds);
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bitmapSelected = Bitmap.createBitmap(bounds.width() + 5, bounds.height(), conf);
Bitmap bitmap = Bitmap.createBitmap(bounds.width() + 5, bounds.height(), conf);
float x = 0;
float y = -1.0f * bounds.top + (bitmap.getHeight() * 0.06f);
Canvas canvas = new Canvas(bitmap);
paint.setColor(this.viewOptions.getLabelColor());
canvas.drawText(label, x, y, paint);
canvas = new Canvas(bitmapSelected);
paint.setColor(this.viewOptions.getLabelSelectedColor());
paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);
canvas.drawText(label, x, y, paint);
this.iconLabel = BitmapDescriptorFactory.fromBitmap(bitmap);
this.iconLabelSelected = BitmapDescriptorFactory.fromBitmap(bitmapSelected);
this.drawLabel();
}
public void setLabelSelected(boolean selected){
this.viewOptions.setBlnLabelSelected(selected);
this.drawLabel();
}
public void setLabelColor(int color){
this.viewOptions.setLabelColor(color);
this.drawLabel();
}
public void setLabelColor(float alpha, int red, int green, int blue){
this.viewOptions.setLabelColor(Color.argb((int)(alpha * 255), red, green, blue));
this.drawLabel();
}
public void setLabelSelectedColor(int color){
this.viewOptions.setLabelSelectedColor(color);
this.drawLabel();
}
public void setLabelSelectedColor(float alpha, int red, int green, int blue){
this.viewOptions.setLabelSelectedColor(Color.argb((int)(alpha * 255), red, green, blue));
this.drawLabel();
}
public String getLabel(){
return this.polygon.label;
}
public void setData(Object data){
this.userData = data;
}
public Object getData(){
return this.userData;
}
private boolean isPointInPolygon(Point tap, List<Point> vertices) {
int intersectCount = 0;
if(vertices.size() > 2){
vertices.add(vertices.get(0)); //End with the first point again so we can check all the sides
} else {
return false;
}
for (int j = 0; j < vertices.size() - 1; j++) {
if (rayCastIntersect(tap, vertices.get(j), vertices.get(j + 1))) {
intersectCount++;
}
}
return ((intersectCount % 2) == 1); // odd = inside, even = outside;
}
private boolean rayCastIntersect(Point tap, Point vertA, Point vertB) {
double aY = vertA.y;
double bY = vertB.y;
double aX = vertA.x;
double bX = vertB.x;
double pY = tap.y;
double pX = tap.x;
if ((aY > pY && bY > pY) || (aY < pY && bY < pY)
|| (aX < pX && bX < pX)) {
return false; // a and b can't both be above or below pt.y, and a or
// b must be east of pt.x
}
//If both a and b are east of point tapped at this point then we are good to go
if(aX > pX && bX > pX){
return true;
}
//Otherwise we are forced to do math
double m = (aY - bY) / (aX - bX); // Rise over run
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m; // algebra is neat!
return x > pX;
}
public static LatLng midPoint(LatLng point1, LatLng point2){
//Used by drawLabel
double dLon = Math.toRadians(point2.longitude - point1.longitude);
//convert to radians
double lat1 = Math.toRadians(point1.latitude);
double lat2 = Math.toRadians(point2.latitude);
double lon1 = Math.toRadians(point1.longitude);
double Bx = Math.cos(lat2) * Math.cos(dLon);
double By = Math.cos(lat2) * Math.sin(dLon);
double lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + Bx) * (Math.cos(lat1) + Bx) + By * By));
double lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx);
return(new LatLng(Math.toDegrees(lat3), Math.toDegrees(lon3)));
}
public float getAcres(){
if(this.polygon.boundary.size() < 3) return 0.0f;
double earth_radius = (double) 6371009.0f; // in meters
double lat_dist = (double) ((Math.PI * earth_radius) / (double) 180.0f);
Float newArea = 0.0f;
List<Pair<Double, Double>> xyList = new ArrayList<Pair<Double, Double>>();
for (int i = 0; i < this.polygon.boundary.size(); i++) {
//Reproject
double y = this.polygon.boundary.get(i).latitude * lat_dist;
double x = this.polygon.boundary.get(i).longitude * lat_dist * Math.cos(Math.toRadians(this.polygon.boundary.get(i).latitude));
//Save x, y
xyList.add(new Pair<Double, Double>(x,y));
}
boolean haveRef = false;
double refX = 0.0f;
double refY = 0.0f;
double total1 = 0.0f;
double total2 = 0.0f;
for(int i = 0; i < (xyList.size()-1); i++){
Pair<Double, Double> thisVert = xyList.get(i);
Pair<Double, Double> nextVert = xyList.get(i+1);
if(haveRef == false){
haveRef = true;
refX = thisVert.first;
refY = thisVert.second;
}
total1 += ((thisVert.first - refX) * (nextVert.second - refY)); // x(i) * y(i+1)
total2 += ((thisVert.second - refY) * (nextVert.first - refX)); // y(i) * x(i+1)
}
newArea = (float) (total1 - total2);
newArea = Math.abs(newArea) / (2.0f * 4046.68f);
return newArea;
}
}
| |
/*
* 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.streams.examples.pageview;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.kstream.Serialized;
import org.apache.kafka.streams.kstream.TimeWindows;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Demonstrates how to perform a join between a KStream and a KTable, i.e. an example of a stateful computation,
* using specific data types (here: JSON POJO; but can also be Avro specific bindings, etc.) for serdes
* in Kafka Streams.
*
* In this example, we join a stream of pageviews (aka clickstreams) that reads from a topic named "streams-pageview-input"
* with a user profile table that reads from a topic named "streams-userprofile-input", where the data format
* is JSON string representing a record in the stream or table, to compute the number of pageviews per user region.
*
* Before running this example you must create the input topics and the output topic (e.g. via
* bin/kafka-topics.sh --create ...), and write some data to the input topics (e.g. via
* bin/kafka-console-producer.sh). Otherwise you won't see any data arriving in the output topic.
*/
public class PageViewTypedDemo {
// POJO classes
static public class PageView {
public String user;
public String page;
public Long timestamp;
}
static public class UserProfile {
public String region;
public Long timestamp;
}
static public class PageViewByRegion {
public String user;
public String page;
public String region;
}
static public class WindowedPageViewByRegion {
public long windowStart;
public String region;
}
static public class RegionCount {
public long count;
public String region;
}
public static void main(final String[] args) {
final Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-pageview-typed");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, JsonTimestampExtractor.class);
props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0);
// setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
final StreamsBuilder builder = new StreamsBuilder();
// TODO: the following can be removed with a serialization factory
final Map<String, Object> serdeProps = new HashMap<>();
final Serializer<PageView> pageViewSerializer = new JsonPOJOSerializer<>();
serdeProps.put("JsonPOJOClass", PageView.class);
pageViewSerializer.configure(serdeProps, false);
final Deserializer<PageView> pageViewDeserializer = new JsonPOJODeserializer<>();
serdeProps.put("JsonPOJOClass", PageView.class);
pageViewDeserializer.configure(serdeProps, false);
final Serde<PageView> pageViewSerde = Serdes.serdeFrom(pageViewSerializer, pageViewDeserializer);
final Serializer<UserProfile> userProfileSerializer = new JsonPOJOSerializer<>();
serdeProps.put("JsonPOJOClass", UserProfile.class);
userProfileSerializer.configure(serdeProps, false);
final Deserializer<UserProfile> userProfileDeserializer = new JsonPOJODeserializer<>();
serdeProps.put("JsonPOJOClass", UserProfile.class);
userProfileDeserializer.configure(serdeProps, false);
final Serde<UserProfile> userProfileSerde = Serdes.serdeFrom(userProfileSerializer, userProfileDeserializer);
final Serializer<WindowedPageViewByRegion> wPageViewByRegionSerializer = new JsonPOJOSerializer<>();
serdeProps.put("JsonPOJOClass", WindowedPageViewByRegion.class);
wPageViewByRegionSerializer.configure(serdeProps, false);
final Deserializer<WindowedPageViewByRegion> wPageViewByRegionDeserializer = new JsonPOJODeserializer<>();
serdeProps.put("JsonPOJOClass", WindowedPageViewByRegion.class);
wPageViewByRegionDeserializer.configure(serdeProps, false);
final Serde<WindowedPageViewByRegion> wPageViewByRegionSerde = Serdes.serdeFrom(wPageViewByRegionSerializer, wPageViewByRegionDeserializer);
final Serializer<RegionCount> regionCountSerializer = new JsonPOJOSerializer<>();
serdeProps.put("JsonPOJOClass", RegionCount.class);
regionCountSerializer.configure(serdeProps, false);
final Deserializer<RegionCount> regionCountDeserializer = new JsonPOJODeserializer<>();
serdeProps.put("JsonPOJOClass", RegionCount.class);
regionCountDeserializer.configure(serdeProps, false);
final Serde<RegionCount> regionCountSerde = Serdes.serdeFrom(regionCountSerializer, regionCountDeserializer);
final Serializer<PageViewByRegion> pageViewByRegionSerializer = new JsonPOJOSerializer<>();
serdeProps.put("JsonPOJOClass", PageViewByRegion.class);
pageViewByRegionSerializer.configure(serdeProps, false);
final Deserializer<PageViewByRegion> pageViewByRegionDeserializer = new JsonPOJODeserializer<>();
serdeProps.put("JsonPOJOClass", PageViewByRegion.class);
pageViewByRegionDeserializer.configure(serdeProps, false);
final Serde<PageViewByRegion> pageViewByRegionSerde = Serdes.serdeFrom(pageViewByRegionSerializer, pageViewByRegionDeserializer);
final KStream<String, PageView> views = builder.stream("streams-pageview-input", Consumed.with(Serdes.String(), pageViewSerde));
final KTable<String, UserProfile> users = builder.table("streams-userprofile-input",
Consumed.with(Serdes.String(), userProfileSerde));
final KStream<WindowedPageViewByRegion, RegionCount> regionCount = views
.leftJoin(users, (view, profile) -> {
final PageViewByRegion viewByRegion = new PageViewByRegion();
viewByRegion.user = view.user;
viewByRegion.page = view.page;
if (profile != null) {
viewByRegion.region = profile.region;
} else {
viewByRegion.region = "UNKNOWN";
}
return viewByRegion;
})
.map((user, viewRegion) -> new KeyValue<>(viewRegion.region, viewRegion))
.groupByKey(Serialized.with(Serdes.String(), pageViewByRegionSerde))
.windowedBy(TimeWindows.of(TimeUnit.DAYS.toMillis(7)).advanceBy(TimeUnit.SECONDS.toMillis(1)))
.count()
.toStream()
.map((key, value) -> {
final WindowedPageViewByRegion wViewByRegion = new WindowedPageViewByRegion();
wViewByRegion.windowStart = key.window().start();
wViewByRegion.region = key.key();
final RegionCount rCount = new RegionCount();
rCount.region = key.key();
rCount.count = value;
return new KeyValue<>(wViewByRegion, rCount);
});
// write to the result topic
regionCount.to("streams-pageviewstats-typed-output", Produced.with(wPageViewByRegionSerde, regionCountSerde));
final KafkaStreams streams = new KafkaStreams(builder.build(), props);
final CountDownLatch latch = new CountDownLatch(1);
// attach shutdown handler to catch control-c
Runtime.getRuntime().addShutdownHook(new Thread("streams-pipe-shutdown-hook") {
@Override
public void run() {
streams.close();
latch.countDown();
}
});
try {
streams.start();
latch.await();
} catch (final Throwable e) {
System.exit(1);
}
System.exit(0);
}
}
| |
// Copyright (c) 2013 Aalto University
//
// 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.
// File created: 2013-06-28 13:49:57
package org.seqdoop.hadoop_bam;
import htsjdk.samtools.seekablestream.ByteArraySeekableStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Arrays;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.GenericOptionsParser;
import htsjdk.samtools.FileTruncatedException;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.BlockCompressedInputStream;
import htsjdk.samtools.util.RuntimeEOFException;
import htsjdk.tribble.TribbleException;
import htsjdk.tribble.readers.PositionalBufferedStream;
import htsjdk.variant.bcf2.BCF2Codec;
import htsjdk.variant.vcf.VCFHeader;
import org.seqdoop.hadoop_bam.util.WrapSeekable;
/** A class for heuristically finding BCF record positions inside an area of
* a BCF file. Handles both compressed and uncompressed BCF.
*/
public class BCFSplitGuesser extends BaseSplitGuesser {
// cin is the compressed input: a BlockCompressedInputStream for compressed
// BCF, otherwise equal to in. Unfortunately the closest common type is then
// InputStream, which is why we have the cinSeek() method.
private InputStream cin;
private SeekableStream inFile;
private final boolean bgzf;
private final BCF2Codec bcfCodec = new BCF2Codec();
private final int contigDictionaryLength, genotypeSampleCount;
// The amount of data we verify for uncompressed BCF.
private final static int UNCOMPRESSED_BYTES_NEEDED = 0x80000;
// We want to go through this many BGZF blocks fully, checking that they
// contain valid BCF records, when guessing a BCF record position.
private final static byte BGZF_BLOCKS_NEEDED_FOR_GUESS = 2;
// Since the max size of a BGZF block is 0xffff (64K), and we might be just
// one byte off from the start of the previous one, we need 0xfffe bytes for
// the start, and then 0xffff times the number of blocks we want to go
// through.
private final static int BGZF_MAX_BYTES_READ =
BGZF_BLOCKS_NEEDED_FOR_GUESS * 0xffff + 0xfffe;
// This is probably too conservative.
private final static int SHORTEST_POSSIBLE_BCF_RECORD = 4*8 + 1;
/** The stream must point to a valid BCF file, because the header is read
* from it.
*/
public BCFSplitGuesser(SeekableStream ss) throws IOException {
this(ss, ss);
}
public BCFSplitGuesser(SeekableStream ss, InputStream headerStream)
throws IOException
{
inFile = ss;
InputStream bInFile = new BufferedInputStream(inFile);
bgzf = BlockCompressedInputStream.isValidFile(bInFile);
if (bgzf)
bInFile = new BlockCompressedInputStream(bInFile);
// Excess buffering here but it can't be helped that BCF2Codec only takes
// PositionalBufferedStream.
final VCFHeader header =
(VCFHeader)bcfCodec.readHeader(
new PositionalBufferedStream(bInFile)).getHeaderValue();
contigDictionaryLength = header.getContigLines().size();
genotypeSampleCount = header.getNGenotypeSamples();
}
public boolean isBGZF() { return bgzf; }
private void cinSeek(long virt) throws IOException {
if (bgzf)
((BlockCompressedInputStream)cin).seek(virt);
else
((SeekableStream)cin).seek(virt);
}
/** Finds a (virtual in the case of BGZF) BCF record position in the
* physical position range [beg,end). Returns end if no BCF record was
* found.
*/
public long guessNextBCFRecordStart(long beg, long end)
throws IOException
{
// Buffer what we need to go through.
byte[] arr = new byte[
bgzf ? BGZF_MAX_BYTES_READ : UNCOMPRESSED_BYTES_NEEDED];
this.inFile.seek(beg);
int totalRead = 0;
for (int left = Math.min((int)(end - beg), arr.length); left > 0;) {
final int r = inFile.read(arr, totalRead, left);
if (r < 0)
break;
totalRead += r;
left -= r;
}
arr = Arrays.copyOf(arr, totalRead);
this.in = new ByteArraySeekableStream(arr);
final int firstBGZFEnd;
if (this.bgzf) {
firstBGZFEnd = Math.min((int)(end - beg), 0xffff);
BlockCompressedInputStream bgzfStream =
new BlockCompressedInputStream(this.in);
bgzfStream.setCheckCrcs(true);
this.cin = bgzfStream;
} else {
this.cin = this.in;
firstBGZFEnd = 0; // Actually unused
}
// cp: Compressed Position, indexes the entire BGZF input. If
// we have uncompressed BCF, this loop does nothing.
for (int cp = 0;; ++cp) {
final int cp0;
final long cp0Virt;
final int blockLen;
if (this.bgzf) {
final PosSize psz = guessNextBGZFPos(cp, firstBGZFEnd);
if (psz == null)
break;
cp0 = cp = psz.pos;
cp0Virt = (long)cp0 << 16;
try {
cinSeek(cp0Virt);
// This has to catch Throwable, because it's possible to get an
// OutOfMemoryError due to an overly large size.
} catch (Throwable e) {
// Guessed BGZF position incorrectly: try the next guess.
continue;
}
blockLen = psz.uSize;
} else {
cp0 = 0; // Actually unused
cp0Virt = 0;
blockLen = Math.max(arr.length, UNCOMPRESSED_BYTES_NEEDED);
}
// up: Uncompressed Position, indexes the data inside the BGZF block.
for (int up = 0;; ++up) {
final int up0 = up = guessNextBCFPos(cp0Virt, up, blockLen);
if (up0 < 0) {
// No BCF records found in the BGZF block: try the next BGZF
// block.
break;
}
// Verification time.
cinSeek(cp0Virt | up0);
final PositionalBufferedStream pbIn =
new PositionalBufferedStream(cin);
boolean decodedAny = false;
try {
if (bgzf) {
byte b = 0;
int prevCP = cp0;
while (b < BGZF_BLOCKS_NEEDED_FOR_GUESS && pbIn.peek() != -1)
{
bcfCodec.decode(pbIn);
decodedAny = true;
final int cp2 = (int)
(((BlockCompressedInputStream)cin).getFilePointer()
>>> 16);
if (cp2 != prevCP) {
// The compressed position changed so we must be in a
// new block.
assert cp2 > prevCP;
cp = cp2;
++b;
}
}
// Running out of records to verify is fine as long as we
// verified at least something. It should only happen if we
// couldn't fill the array.
if (b < BGZF_BLOCKS_NEEDED_FOR_GUESS) {
assert arr.length < BGZF_MAX_BYTES_READ;
if (!decodedAny)
continue;
}
} else {
while (pbIn.getPosition() - up0 < UNCOMPRESSED_BYTES_NEEDED
&& pbIn.peek() != -1)
{
bcfCodec.decode(pbIn);
decodedAny = true;
}
// As in the BGZF case.
if (pbIn.getPosition() - up0 < UNCOMPRESSED_BYTES_NEEDED) {
assert arr.length < UNCOMPRESSED_BYTES_NEEDED;
if (!decodedAny)
continue;
}
}
} catch (FileTruncatedException e) { continue; }
catch (OutOfMemoryError e) { continue; }
catch (RuntimeEOFException e) { continue; }
catch (TribbleException e) {
// This is the way in which BCF2Codec reports unexpected EOF.
// Unfortunately, it also reports every other kind of error with
// the same exception. It even wraps IOException in
// TribbleException!
//
// We need to catch EOF in the middle of a record, which can
// happen legitimately if the [beg,end) range is too small and
// cuts off a record. First, require decodedAny, and then, assume
// that this exception means EOF if the stream has hit EOF.
if (!(decodedAny && pbIn.peek() == -1))
continue;
}
return this.bgzf ? beg+cp0 << 16 | up0 : beg + up0;
}
if (!this.bgzf)
break;
}
return end;
}
private int guessNextBCFPos(long cpVirt, int up, int cSize) {
try {
for (; up + SHORTEST_POSSIBLE_BCF_RECORD < cSize; ++up) {
// Note! The BCF2 spec has a table listing the fields and their
// types, but QUAL is misplaced there! It should be before
// n_allele_info, not after n_fmt_sample! The "Putting it all
// together" section shows the correct field order.
// Check that [0] and [4] are big enough to make sense.
cinSeek(cpVirt | up);
IOUtils.readFully(cin, buf.array(), 0, 8);
final long sharedLen = getUInt(0);
final long indivLen = getUInt(4);
if (sharedLen + indivLen < (long)SHORTEST_POSSIBLE_BCF_RECORD)
continue;
// Check that [8] looks like a valid CHROM field and that [12] is a
// 0-based leftmost coordinate.
cinSeek(cpVirt | up+8);
IOUtils.readFully(cin, buf.array(), 0, 8);
final int chrom = buf.getInt(0);
final int pos = buf.getInt(4);
if (chrom < 0 || chrom >= contigDictionaryLength || pos < 0)
continue;
// [24] and [26] are lengths and should thus be nonnegative.
cinSeek(cpVirt | up+24);
IOUtils.readFully(cin, buf.array(), 0, 4);
final int alleleInfo = buf.getInt(0);
final int alleleCount = alleleInfo >> 16;
final int infoCount = alleleInfo & 0xffff;
if (alleleCount < 0) // don't check infoCount since it is always nonnegative
continue;
// Make sure that [28] matches to the same value in the header.
cinSeek(cpVirt | up+28);
IOUtils.readFully(cin, buf.array(), 0, 1);
final short nSamples = getUByte(0);
if ((int)nSamples != genotypeSampleCount)
continue;
// Check that the ID string has a sensible type encoding. That is,
// it should claim to be a character string: [32] & 0x0f == 0x07.
// Further, if it has length 15 or more, i.e. [32] & 0xf0 == 0xf0,
// then it should be followed by an integer, i.e. [33] & 0x0f
// should be in the range [1, 3], and the value of that integer
// should be in the range [15, [0] - x) where x is the guaranteed
// number of bytes in the first part of this record (before the
// genotype block).
cinSeek(cpVirt | up+32);
IOUtils.readFully(cin, buf.array(), 0, 6);
final byte idType = buf.get(0);
if ((idType & 0x0f) != 0x07)
continue;
if ((idType & 0xf0) == 0xf0) {
final byte idLenType = buf.get(1);
final long idLen;
switch (idLenType & 0x0f) {
case 0x01: idLen = getUByte (2); break;
case 0x02: idLen = getUShort(2); break;
case 0x03: idLen = getUInt (2); break;
default: continue;
}
if (idLen < 15
|| idLen > sharedLen - (4*8 + alleleCount + infoCount*2))
continue;
}
// Good enough.
return up;
}
} catch (IOException e) {
// fall through
}
return -1;
}
private long getUInt(final int idx) {
return (long) buf.getInt(idx);
}
private short getUByte(final int idx) {
return (short)((short)buf.get(idx) & 0xff);
}
public static void main(String[] args) throws IOException {
final GenericOptionsParser parser;
try {
parser = new GenericOptionsParser(args);
// This should be IOException but Hadoop 0.20.2 doesn't throw it...
} catch (Exception e) {
System.err.printf("Error in Hadoop arguments: %s\n", e.getMessage());
System.exit(1);
return;
}
args = parser.getRemainingArgs();
final Configuration conf = parser.getConfiguration();
long beg = 0;
if (args.length < 2 || args.length > 3) {
System.err.println(
"Usage: BCFSplitGuesser path-or-uri header-path-or-uri [beg]");
System.exit(2);
}
try {
if (args.length > 2) beg = Long.decode(args[2]);
} catch (NumberFormatException e) {
System.err.println("Invalid beg offset.");
if (e.getMessage() != null)
System.err.println(e.getMessage());
System.exit(2);
}
SeekableStream ss = WrapSeekable.openPath(conf, new Path(args[0]));
SeekableStream hs = WrapSeekable.openPath(conf, new Path(args[1]));
final BCFSplitGuesser guesser = new BCFSplitGuesser(ss, hs);
final long end;
if (guesser.isBGZF()) {
end = beg + BGZF_MAX_BYTES_READ;
System.out.printf(
"This looks like a BGZF-compressed BCF file.\n"+
"Will look for a BGZF block within: [%1$#x,%2$#x) = [%1$d,%2$d)\n"+
"Will then verify BCF data within: [%1$#x,%3$#x) = [%1$d,%3$d)\n",
beg, beg + 0xffff, end);
} else {
end = beg + UNCOMPRESSED_BYTES_NEEDED;
System.out.printf(
"This looks like an uncompressed BCF file.\n"+
"Will look for a BCF record within: [%1$#x,%2$#x) = [%1$d,%2$d)\n"+
"And then will verify all following data in that range.\n",
beg, end);
}
final long g = guesser.guessNextBCFRecordStart(beg, end);
ss.close();
if (g == end) {
System.out.println(
"Didn't find any acceptable BCF record in any BGZF block.");
System.exit(1);
}
if (guesser.isBGZF())
System.out.printf(
"Accepted BGZF block at offset %1$#x (%1$d).\n"+
"Accepted BCF record at offset %2$#x (%2$d) therein.\n",
g >> 16, g & 0xffff);
else
System.out.printf("Accepted BCF record at offset %1$#x (%1$d).\n", g);
}
}
| |
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
package jsr166;
import com.google.j2objc.util.ReflectionUtil;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import junit.framework.Test;
import junit.framework.TestSuite;
public class PriorityQueueTest extends JSR166TestCase {
// android-note: Removed because the CTS runner does a bad job of
// retrying tests that have suite() declarations.
//
// public static void main(String[] args) {
// main(suite(), args);
// }
// public static Test suite() {
// return new TestSuite(PriorityQueueTest.class);
// }
static class MyReverseComparator implements Comparator {
public int compare(Object x, Object y) {
return ((Comparable)y).compareTo(x);
}
}
/**
* Returns a new queue of given size containing consecutive
* Integers 0 ... n.
*/
private PriorityQueue<Integer> populatedQueue(int n) {
PriorityQueue<Integer> q = new PriorityQueue<Integer>(n);
assertTrue(q.isEmpty());
for (int i = n - 1; i >= 0; i -= 2)
assertTrue(q.offer(new Integer(i)));
for (int i = (n & 1); i < n; i += 2)
assertTrue(q.offer(new Integer(i)));
assertFalse(q.isEmpty());
assertEquals(n, q.size());
return q;
}
/**
* A new queue has unbounded capacity
*/
public void testConstructor1() {
assertEquals(0, new PriorityQueue(SIZE).size());
}
/**
* Constructor throws IAE if capacity argument nonpositive
*/
public void testConstructor2() {
try {
new PriorityQueue(0);
shouldThrow();
} catch (IllegalArgumentException success) {}
}
/**
* Initializing from null Collection throws NPE
*/
public void testConstructor3() {
try {
new PriorityQueue((Collection)null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* Initializing from Collection of null elements throws NPE
*/
public void testConstructor4() {
try {
new PriorityQueue(Arrays.asList(new Integer[SIZE]));
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* Initializing from Collection with some null elements throws NPE
*/
public void testConstructor5() {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE - 1; ++i)
ints[i] = new Integer(i);
try {
new PriorityQueue(Arrays.asList(ints));
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* Queue contains all elements of collection used to initialize
*/
public void testConstructor6() {
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
PriorityQueue q = new PriorityQueue(Arrays.asList(ints));
for (int i = 0; i < SIZE; ++i)
assertEquals(ints[i], q.poll());
}
/**
* The comparator used in constructor is used
*/
public void testConstructor7() {
MyReverseComparator cmp = new MyReverseComparator();
PriorityQueue q = new PriorityQueue(SIZE, cmp);
assertEquals(cmp, q.comparator());
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(i);
q.addAll(Arrays.asList(ints));
for (int i = SIZE - 1; i >= 0; --i)
assertEquals(ints[i], q.poll());
}
/**
* isEmpty is true before add, false after
*/
public void testEmpty() {
PriorityQueue q = new PriorityQueue(2);
assertTrue(q.isEmpty());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.add(new Integer(2));
q.remove();
q.remove();
assertTrue(q.isEmpty());
}
/**
* size changes when elements added and removed
*/
public void testSize() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(SIZE - i, q.size());
q.remove();
}
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
q.add(new Integer(i));
}
}
/**
* offer(null) throws NPE
*/
public void testOfferNull() {
PriorityQueue q = new PriorityQueue(1);
try {
q.offer(null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* add(null) throws NPE
*/
public void testAddNull() {
PriorityQueue q = new PriorityQueue(1);
try {
q.add(null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* Offer of comparable element succeeds
*/
public void testOffer() {
PriorityQueue q = new PriorityQueue(1);
assertTrue(q.offer(zero));
assertTrue(q.offer(one));
}
/**
* Offer of non-Comparable throws CCE
*/
public void testOfferNonComparable() {
PriorityQueue q = new PriorityQueue(1);
try {
q.offer(new Object());
q.offer(new Object());
shouldThrow();
} catch (ClassCastException success) {}
}
/**
* add of comparable succeeds
*/
public void testAdd() {
PriorityQueue q = new PriorityQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.size());
assertTrue(q.add(new Integer(i)));
}
}
/**
* addAll(null) throws NPE
*/
public void testAddAll1() {
PriorityQueue q = new PriorityQueue(1);
try {
q.addAll(null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* addAll of a collection with null elements throws NPE
*/
public void testAddAll2() {
PriorityQueue q = new PriorityQueue(SIZE);
try {
q.addAll(Arrays.asList(new Integer[SIZE]));
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* addAll of a collection with any null elements throws NPE after
* possibly adding some elements
*/
public void testAddAll3() {
PriorityQueue q = new PriorityQueue(SIZE);
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE - 1; ++i)
ints[i] = new Integer(i);
try {
q.addAll(Arrays.asList(ints));
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* Queue contains all elements of successful addAll
*/
public void testAddAll5() {
Integer[] empty = new Integer[0];
Integer[] ints = new Integer[SIZE];
for (int i = 0; i < SIZE; ++i)
ints[i] = new Integer(SIZE - 1 - i);
PriorityQueue q = new PriorityQueue(SIZE);
assertFalse(q.addAll(Arrays.asList(empty)));
assertTrue(q.addAll(Arrays.asList(ints)));
for (int i = 0; i < SIZE; ++i)
assertEquals(new Integer(i), q.poll());
}
/**
* poll succeeds unless empty
*/
public void testPoll() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.poll());
}
assertNull(q.poll());
}
/**
* peek returns next element, or null if empty
*/
public void testPeek() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.peek());
assertEquals(i, q.poll());
assertTrue(q.peek() == null ||
!q.peek().equals(i));
}
assertNull(q.peek());
}
/**
* element returns next element, or throws NSEE if empty
*/
public void testElement() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.element());
assertEquals(i, q.poll());
}
try {
q.element();
shouldThrow();
} catch (NoSuchElementException success) {}
}
/**
* remove removes next element, or throws NSEE if empty
*/
public void testRemove() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertEquals(i, q.remove());
}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success) {}
}
/**
* remove(x) removes x and returns true if present
*/
public void testRemoveElement() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 1; i < SIZE; i += 2) {
assertTrue(q.contains(i));
assertTrue(q.remove(i));
assertFalse(q.contains(i));
assertTrue(q.contains(i - 1));
}
for (int i = 0; i < SIZE; i += 2) {
assertTrue(q.contains(i));
assertTrue(q.remove(i));
assertFalse(q.contains(i));
assertFalse(q.remove(i + 1));
assertFalse(q.contains(i + 1));
}
assertTrue(q.isEmpty());
}
/**
* contains(x) reports true when elements added but not yet removed
*/
public void testContains() {
PriorityQueue q = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.contains(new Integer(i)));
q.poll();
assertFalse(q.contains(new Integer(i)));
}
}
/**
* clear removes all elements
*/
public void testClear() {
PriorityQueue q = populatedQueue(SIZE);
q.clear();
assertTrue(q.isEmpty());
assertEquals(0, q.size());
q.add(new Integer(1));
assertFalse(q.isEmpty());
q.clear();
assertTrue(q.isEmpty());
}
/**
* containsAll(c) is true when c contains a subset of elements
*/
public void testContainsAll() {
PriorityQueue q = populatedQueue(SIZE);
PriorityQueue p = new PriorityQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
assertTrue(q.containsAll(p));
assertFalse(p.containsAll(q));
p.add(new Integer(i));
}
assertTrue(p.containsAll(q));
}
/**
* retainAll(c) retains only those elements of c and reports true if changed
*/
public void testRetainAll() {
PriorityQueue q = populatedQueue(SIZE);
PriorityQueue p = populatedQueue(SIZE);
for (int i = 0; i < SIZE; ++i) {
boolean changed = q.retainAll(p);
if (i == 0)
assertFalse(changed);
else
assertTrue(changed);
assertTrue(q.containsAll(p));
assertEquals(SIZE - i, q.size());
p.remove();
}
}
/**
* removeAll(c) removes only those elements of c and reports true if changed
*/
public void testRemoveAll() {
for (int i = 1; i < SIZE; ++i) {
PriorityQueue q = populatedQueue(SIZE);
PriorityQueue p = populatedQueue(i);
assertTrue(q.removeAll(p));
assertEquals(SIZE - i, q.size());
for (int j = 0; j < i; ++j) {
Integer x = (Integer)(p.remove());
assertFalse(q.contains(x));
}
}
}
/**
* toArray contains all elements
*/
public void testToArray() {
PriorityQueue q = populatedQueue(SIZE);
Object[] o = q.toArray();
Arrays.sort(o);
for (int i = 0; i < o.length; i++)
assertSame(o[i], q.poll());
}
/**
* toArray(a) contains all elements
*/
public void testToArray2() {
PriorityQueue<Integer> q = populatedQueue(SIZE);
Integer[] ints = new Integer[SIZE];
Integer[] array = q.toArray(ints);
assertSame(ints, array);
Arrays.sort(ints);
for (int i = 0; i < ints.length; i++)
assertSame(ints[i], q.poll());
}
/**
* iterator iterates through all elements
*/
public void testIterator() {
PriorityQueue q = populatedQueue(SIZE);
Iterator it = q.iterator();
int i;
for (i = 0; it.hasNext(); i++)
assertTrue(q.contains(it.next()));
assertEquals(i, SIZE);
assertIteratorExhausted(it);
}
/**
* iterator of empty collection has no elements
*/
public void testEmptyIterator() {
assertIteratorExhausted(new PriorityQueue().iterator());
}
/**
* iterator.remove removes current element
*/
public void testIteratorRemove() {
final PriorityQueue q = new PriorityQueue(3);
q.add(new Integer(2));
q.add(new Integer(1));
q.add(new Integer(3));
Iterator it = q.iterator();
it.next();
it.remove();
it = q.iterator();
assertEquals(it.next(), new Integer(2));
assertEquals(it.next(), new Integer(3));
assertFalse(it.hasNext());
}
/**
* toString contains toStrings of elements
*/
public void testToString() {
PriorityQueue q = populatedQueue(SIZE);
String s = q.toString();
for (int i = 0; i < SIZE; ++i) {
assertTrue(s.contains(String.valueOf(i)));
}
}
/**
* A deserialized serialized queue has same elements
*/
public void testSerialization() throws Exception {
// J2ObjC reflection-stripping change.
if (ReflectionUtil.isJreReflectionStripped()) {
return;
}
Queue x = populatedQueue(SIZE);
Queue y = serialClone(x);
assertNotSame(x, y);
assertEquals(x.size(), y.size());
while (!x.isEmpty()) {
assertFalse(y.isEmpty());
assertEquals(x.remove(), y.remove());
}
assertTrue(y.isEmpty());
}
}
| |
package com.nixus.raop;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import android.os.Process;
import javax.jmdns.ServiceListener;
import org.apache.http.conn.util.InetAddressUtils;
import android.os.AsyncTask;
import android.util.Log;
import com.nixus.raop.core.PropertyManager;
import com.nixus.raop.core.ServiceContextImpl;
import com.nixus.raop.core.ServicesManager;
import com.nixus.raop.events.SpeakerEvent;
import com.nixus.raop.player.PlayerImpl;
import com.nixus.raop.speaker.airport.Finder;
import com.nixus.raop.speaker.airport.SpeakerImpl;
import com.nixus.raop.zeroconf.ZeroConfFactory;
/**
* RaopHelper, helper for raop
* @author Maxime Flamant
*
*/
public class RaopHelper extends Observable implements ServicesManager{
public static Map<String,ServiceContextImpl> contexts;
public static PropertyManager pm;
protected ServiceListener listener;
private List<NativeRaopTask> raopTasks = new ArrayList<NativeRaopTask>();
private HashMap<String,Boolean> raopSwitches = new HashMap<String,Boolean>();
public final static String HOST_NAME = "android";
private PlayerImpl pl;
private static final String TAG = "RaopHelper";
public RaopHelper(){
super();
}
/* Speaker found
* @see com.nixus.raop.core.ServicesManager#addServiceContext(com.nixus.raop.core.ServiceContextImpl)
*/
public void addServiceContext(final ServiceContextImpl context) {
contexts.put(context.getProperty("host")==null?context.getServiceName():context.getProperty("host"),context);
if (context.getService() instanceof SpeakerImpl){
setChanged();
notifyObservers(new SpeakerEvent(SpeakerEvent.State.ON,context.getProperty("host"),context.getProperty("name").replace("speaker.airport.", ""),context.getProperty("protocol"),context.getProperty("port")));
}
}
/* Speaker removed
* @see com.nixus.raop.core.ServicesManager#removeServiceContext(com.nixus.raop.core.ServiceContextImpl)
*/
public void removeServiceContext(ServiceContextImpl context) {
//contexts.remove(context);
//pm.remove(context.getProperty("name"));
}
/* Return speakers
* @see com.nixus.raop.core.ServicesManager#getServices()
*/
public Iterator<ServiceContextImpl> getServices() {
return contexts.values().iterator();
}
/*
* Start Airplay devices discovery
*/
void startDeviceDiscovery() {
this.setChanged();
notifyObservers("Running");
contexts = new HashMap<String, ServiceContextImpl>();
pm = new PropertyManager();
pm.init();
ServiceContextImpl sczcf = new ServiceContextImpl(new ZeroConfFactory(), "zeroconffactory",pm,this);
sczcf.putProperty("implementation", "jmdns");
sczcf.putProperty("bind", getLocalIpAddress());
sczcf.putProperty("hostname", HOST_NAME);
this.addServiceContext(sczcf);
sczcf.start();
ServiceContextImpl scaf = new ServiceContextImpl(new Finder(), "airportfactory",pm,this);
this.addServiceContext(scaf);
scaf.start();
pl = new PlayerImpl();
ServiceContextImpl scpl = new ServiceContextImpl(pl, "main",pm,this);
this.addServiceContext(scpl);
scpl.start();
}
/**
* Set value of raop switch control file
* @param swtch
*/
static void setRaopSwitch(String swtch) {
FileWriter sfw;
try {
sfw = new FileWriter("/data/raop_switch");
sfw.write(swtch);
sfw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Get local IP address
* @return local IP address
*/
static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
Log.v(TAG,"Found addr = " + inetAddress.getHostAddress().toString());
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("MainPage", ex.toString());
}
return null;
}
/**
* Async task taking care of native raop streaming thread
* @author Maxime Flamant
*
*/
private class NativeRaopTask extends AsyncTask<String,String,String> {
private String address;
private String proto;
private String port;
public NativeRaopTask(String address, String proto, String port) {
this.address =address;
this.proto = proto;
this.port = port;
}
@Override
protected String doInBackground(String... airportAddress) {
Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO);
raopSwitches.put((String) airportAddress[0], true);
String[] args = new String[7];
args[0] = "raop-play";
args[1] = "--port";
args[2] = this.port;
args[3] = "--proto";
args[4] = this.proto;
args[5] = this.address;
args[6] = "socket://";
int pid = raopPlay(args);
Log.v(TAG,"Process exited " + pid);
return null;
}
@Override
protected void onPostExecute(String result) {
RaopHelper.setRaopSwitch("O");
raopSwitches.put(address, false);
Log.v(TAG,"Streaming terminated");
RaopHelper.setRaopSwitch("O");
setChanged();
notifyObservers(new SpeakerEvent(address));
super.onPostExecute(result);
}
}
/**
* Start streaming on given airport address and port using the given protocol
* @param airportAddress airport address
* @param proto protocol (udp/tcp)
* @param port airport port
*/
public void startStreaming(String airportAddress, String proto,String port) {
Log.v(TAG,"Starting streaming on " + airportAddress);
NativeRaopTask raop = new NativeRaopTask(airportAddress,proto,port);
raop.execute(airportAddress);
raopTasks.add(raop);
setChanged();
notifyObservers("Streaming on " + getAirportName(airportAddress));
}
/**
* Stop streaming on given address
* @param airportAddress airport address
*/
public void stopStreaming(String airportAddress) {
setRaopSwitch("0");
raopSwitches.put(airportAddress, false);
setChanged();
notifyObservers("Not streaming");
}
/**
* Get Airport name for a given address
* @param airportAddress
* @return
*/
public String getAirportName(String airportAddress ){
return contexts.get(airportAddress).getProperty("name").replace("speaker.airport.", "");
}
/**
* A native method that is implemented by the
* 'raop_play' native library, which is packaged
* with this application.
* @param args raop_play args
* @return
*/
public native int raopPlay(String[] args);
/*
* Load native libraries
*/
static {
System.loadLibrary("ssl");
System.loadLibrary("crypto");
System.loadLibrary("samplerate");
System.loadLibrary("raop-play");
}
/**
* Notification of readiness for streaming from native library
* @param ready
*/
public boolean notifyReady(boolean ready) {
Log.v(TAG, "JNI process ready for streaming " + ready);
if (ready)
setRaopSwitch("1");
else
setRaopSwitch("0");
return true;
}
/**
* Method to be invoked from native streaming library in order to
* check if streaming is still active on given address
* @param address Airport address
*/
public boolean isActivated(String address) {
return raopSwitches.get(address).booleanValue();
}
}
| |
/*
* Copyright (c) Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.entitlement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.entitlement.cache.DecisionInvalidationCache;
import org.wso2.carbon.identity.entitlement.cache.EntitlementPolicyInvalidationCache;
import org.wso2.carbon.identity.entitlement.dto.PDPDataHolder;
import org.wso2.carbon.identity.entitlement.dto.PIPFinderDataHolder;
import org.wso2.carbon.identity.entitlement.dto.PolicyFinderDataHolder;
import org.wso2.carbon.identity.entitlement.internal.EntitlementServiceComponent;
import org.wso2.carbon.identity.entitlement.pap.EntitlementAdminEngine;
import org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyFinder;
import org.wso2.carbon.identity.entitlement.pdp.EntitlementEngine;
import org.wso2.carbon.identity.entitlement.pip.AbstractPIPAttributeFinder;
import org.wso2.carbon.identity.entitlement.pip.CarbonAttributeFinder;
import org.wso2.carbon.identity.entitlement.pip.CarbonResourceFinder;
import org.wso2.carbon.identity.entitlement.pip.PIPAttributeFinder;
import org.wso2.carbon.identity.entitlement.pip.PIPResourceFinder;
import org.wso2.carbon.identity.entitlement.policy.finder.PolicyFinderModule;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* Entitlement PDP related admin services are exposed
*/
public class EntitlementAdminService {
private static Log log = LogFactory.getLog(EntitlementAdminService.class);
/**
* Clears the decision cache.
*
* @throws EntitlementException throws
*/
public void clearDecisionCache() throws EntitlementException {
DecisionInvalidationCache.getInstance().invalidateCache();
if (log.isDebugEnabled()) {
log.debug("Decision Caching is cleared by using admin service");
}
}
/**
* Clears the policy cache.
*
* @throws EntitlementException throws
*/
public void clearPolicyCache() throws EntitlementException {
EntitlementPolicyInvalidationCache.getInstance().invalidateCache();
if (log.isDebugEnabled()) {
log.debug("Decision Caching is cleared by using admin service");
}
}
/**
* Clears Carbon attribute finder cache and All the attribute cache implementations in each
* PIP attribute finder level
*
* @throws EntitlementException throws
*/
public void clearAllAttributeCaches() throws EntitlementException {
CarbonAttributeFinder finder = EntitlementEngine.getInstance().getCarbonAttributeFinder();
if (finder != null) {
finder.clearAttributeCache();
// we need invalidate decision cache as well.
clearDecisionCache();
} else {
throw new EntitlementException("Can not clear all attribute caches - Carbon Attribute Finder "
+ "is not initialized");
}
Map<PIPAttributeFinder, Properties> designators = EntitlementServiceComponent.getEntitlementConfig()
.getDesignators();
if (designators != null && !designators.isEmpty()) {
Set<PIPAttributeFinder> pipAttributeFinders = designators.keySet();
for (PIPAttributeFinder pipAttributeFinder : pipAttributeFinders) {
pipAttributeFinder.clearCache();
}
}
}
/**
* Clears the carbon attribute cache
*
* @throws EntitlementException throws
*/
public void clearCarbonAttributeCache() throws EntitlementException {
CarbonAttributeFinder finder = EntitlementEngine.getInstance().getCarbonAttributeFinder();
if (finder != null) {
finder.clearAttributeCache();
// we need invalidate decision cache as well.
clearDecisionCache();
} else {
throw new EntitlementException("Can not clear attribute cache - Carbon Attribute Finder "
+ "is not initialized");
}
Map<PIPAttributeFinder, Properties> designators = EntitlementServiceComponent.getEntitlementConfig()
.getDesignators();
if (designators != null && !designators.isEmpty()) {
Set<PIPAttributeFinder> pipAttributeFinders = designators.keySet();
for (PIPAttributeFinder pipAttributeFinder : pipAttributeFinders) {
if (pipAttributeFinder instanceof AbstractPIPAttributeFinder) {
pipAttributeFinder.clearCache();
}
}
}
}
/**
* Clears the cache maintained by the attribute finder.
*
* @param attributeFinder Canonical name of the attribute finder class.
*/
public void clearAttributeFinderCache(String attributeFinder) {
Map<PIPAttributeFinder, Properties> designators = EntitlementServiceComponent.getEntitlementConfig()
.getDesignators();
if (designators != null && !designators.isEmpty()) {
Set<PIPAttributeFinder> pipAttributeFinders = designators.keySet();
for (PIPAttributeFinder pipAttributeFinder : pipAttributeFinders) {
if (pipAttributeFinder instanceof AbstractPIPAttributeFinder) {
if (pipAttributeFinder.getClass().getCanonicalName().equals(attributeFinder)) {
pipAttributeFinder.clearCache();
break;
}
}
}
}
}
/**
* Clears the cache maintained by the attribute finder - by attributes
*
* @param attributeFinder Canonical name of the attribute finder class.
* @param attributeIds An array of attribute id.
*/
public void clearAttributeFinderCacheByAttributes(String attributeFinder, String[] attributeIds) {
Map<PIPAttributeFinder, Properties> designators = EntitlementServiceComponent.getEntitlementConfig()
.getDesignators();
if (designators != null && !designators.isEmpty()) {
Set<PIPAttributeFinder> pipAttributeFinders = designators.keySet();
for (PIPAttributeFinder pipAttributeFinder : pipAttributeFinders) {
if (pipAttributeFinder.getClass().getCanonicalName().equals(attributeFinder)) {
pipAttributeFinder.clearCache(attributeIds);
break;
}
}
}
}
/**
* Clears Carbon resource finder cache and All the resource cache implementations in each
* PIP resource finder level
*
* @throws EntitlementException throws
*/
public void clearAllResourceCaches() throws EntitlementException {
CarbonResourceFinder finder = EntitlementEngine.getInstance().getCarbonResourceFinder();
if (finder != null) {
finder.clearAttributeCache();
// we need invalidate decision cache as well.
clearDecisionCache();
} else {
throw new EntitlementException("Can not clear attribute cache - Carbon Attribute Finder "
+ "is not initialized");
}
}
/**
* Clears the carbon resource cache
*
* @throws EntitlementException throws
*/
public void clearCarbonResourceCache() throws EntitlementException {
CarbonResourceFinder finder = EntitlementEngine.getInstance().getCarbonResourceFinder();
if (finder != null) {
finder.clearAttributeCache();
// we need invalidate decision cache as well.
clearDecisionCache();
} else {
throw new EntitlementException("Can not clear attribute cache - Carbon Attribute Finder "
+ "is not initialized");
}
Map<PIPResourceFinder, Properties> resourceConfigs = EntitlementServiceComponent.getEntitlementConfig()
.getResourceFinders();
if (resourceConfigs != null && !resourceConfigs.isEmpty()) {
Set<PIPResourceFinder> resourceFinders = resourceConfigs.keySet();
for (PIPResourceFinder pipResourceFinder : resourceFinders) {
pipResourceFinder.clearCache();
}
}
}
/**
* Clears the cache maintained by the resource finder.
*
* @param resourceFinder Canonical name of the resource finder class.
*/
public void clearResourceFinderCache(String resourceFinder) {
Map<PIPResourceFinder, Properties> resourceConfigs = EntitlementServiceComponent.getEntitlementConfig()
.getResourceFinders();
if (resourceConfigs != null && !resourceConfigs.isEmpty()) {
Set<PIPResourceFinder> resourceFinders = resourceConfigs.keySet();
for (PIPResourceFinder pipResourceFinder : resourceFinders) {
if (resourceFinder.getClass().getCanonicalName().equals(resourceFinder)) {
pipResourceFinder.clearCache();
break;
}
}
}
}
/**
* Refreshes the supported Attribute ids of a given attribute finder module
*
* @param attributeFinder Canonical name of the attribute finder class.
* @throws EntitlementException throws if fails to refresh
*/
public void refreshAttributeFinder(String attributeFinder) throws EntitlementException {
Map<PIPAttributeFinder, Properties> designators = EntitlementServiceComponent.getEntitlementConfig()
.getDesignators();
if (attributeFinder != null && designators != null && !designators.isEmpty()) {
Set<Map.Entry<PIPAttributeFinder, Properties>> pipAttributeFinders = designators.entrySet();
for (Map.Entry<PIPAttributeFinder, Properties> entry : pipAttributeFinders) {
if (attributeFinder.equals(entry.getKey().getClass().getName()) ||
attributeFinder.equals(entry.getKey().getModuleName())) {
try {
entry.getKey().init(entry.getValue());
entry.getKey().clearCache();
CarbonAttributeFinder carbonAttributeFinder = EntitlementEngine.
getInstance().getCarbonAttributeFinder();
carbonAttributeFinder.init();
} catch (Exception e) {
throw new EntitlementException("Error while refreshing attribute finder - " +
attributeFinder);
}
break;
}
}
}
}
/**
* Refreshes the supported resource id of a given resource finder module
*
* @param resourceFinder Canonical name of the resource finder class.
* @throws EntitlementException throws if fails to refresh
*/
public void refreshResourceFinder(String resourceFinder) throws EntitlementException {
Map<PIPResourceFinder, Properties> resourceFinders = EntitlementServiceComponent.getEntitlementConfig()
.getResourceFinders();
if (resourceFinder != null && resourceFinders != null && !resourceFinders.isEmpty()) {
for (Map.Entry<PIPResourceFinder, Properties> entry : resourceFinders.entrySet()) {
if (resourceFinder.equals(entry.getKey().getClass().getName()) ||
resourceFinder.equals(entry.getKey().getModuleName())) {
try {
entry.getKey().init(entry.getValue());
entry.getKey().clearCache();
CarbonAttributeFinder carbonAttributeFinder = EntitlementEngine.
getInstance().getCarbonAttributeFinder();
carbonAttributeFinder.init();
} catch (Exception e) {
throw new EntitlementException("Error while refreshing attribute finder - " +
resourceFinder);
}
break;
}
}
}
}
/**
* Refreshes the supported resource id of a given resource finder module
*
* @param policyFinder Canonical name of the resource finder class.
* @throws EntitlementException throws if fails to refresh
*/
public void refreshPolicyFinders(String policyFinder) throws EntitlementException {
Map<PolicyFinderModule, Properties> policyFinders = EntitlementServiceComponent.getEntitlementConfig()
.getPolicyFinderModules();
if (policyFinder != null && policyFinders != null && !policyFinders.isEmpty()) {
for (Map.Entry<PolicyFinderModule, Properties> entry : policyFinders.entrySet()) {
if (policyFinder.equals(entry.getKey().getClass().getName()) ||
policyFinder.equals(entry.getKey().getModuleName())) {
try {
entry.getKey().init(entry.getValue());
EntitlementEngine.getInstance().getCarbonPolicyFinder().init();
// need to re init all policy finder modules in the cluster.
// therefore calling invalidation cache
DecisionInvalidationCache.getInstance().invalidateCache();
EntitlementPolicyInvalidationCache.getInstance().invalidateCache();
} catch (Exception e) {
throw new EntitlementException("Error while refreshing attribute finder - " +
policyFinder);
}
break;
}
}
}
}
/**
* Tests engine of PAP policy store
*
* @param xacmlRequest
* @return
* @throws EntitlementException
*/
public String doTestRequest(String xacmlRequest) throws EntitlementException {
return EntitlementEngine.getInstance().test(xacmlRequest);
}
/**
* Tests engine of PAP policy store
*
* @param xacmlRequest
* @param policies policy ids that is evaluated
* @return
* @throws EntitlementException
*/
public String doTestRequestForGivenPolicies(String xacmlRequest, String[] policies)
throws EntitlementException {
EntitlementEngine engine = EntitlementEngine.getInstance();
PAPPolicyFinder papPolicyFinder = (PAPPolicyFinder) engine.getPapPolicyFinder().
getModules().iterator().next();
papPolicyFinder.setPolicyIds(Arrays.asList(policies));
String response = EntitlementEngine.getInstance().test(xacmlRequest);
papPolicyFinder.initPolicyIds();
return response;
}
/**
* @return
*/
public PDPDataHolder getPDPData() {
PDPDataHolder pdpDataHolder = new PDPDataHolder();
Map<PolicyFinderModule, Properties> finderModules = EntitlementServiceComponent.
getEntitlementConfig().getPolicyFinderModules();
Map<PIPAttributeFinder, Properties> attributeModules = EntitlementServiceComponent.
getEntitlementConfig().getDesignators();
Map<PIPResourceFinder, Properties> resourceModules = EntitlementServiceComponent.
getEntitlementConfig().getResourceFinders();
if (finderModules != null) {
List<String> list = new ArrayList<String>();
for (Map.Entry<PolicyFinderModule, Properties> entry : finderModules.entrySet()) {
PolicyFinderModule module = entry.getKey();
if (module != null) {
if (module.getModuleName() != null) {
list.add(module.getModuleName());
} else {
list.add(module.getClass().getName());
}
}
}
pdpDataHolder.setPolicyFinders(list.toArray(new String[list.size()]));
}
if (attributeModules != null) {
List<String> list = new ArrayList<String>();
for (Map.Entry<PIPAttributeFinder, Properties> entry : attributeModules.entrySet()) {
PIPAttributeFinder module = entry.getKey();
if (module != null) {
if (module.getModuleName() != null) {
list.add(module.getModuleName());
} else {
list.add(module.getClass().getName());
}
}
}
pdpDataHolder.setPipAttributeFinders(list.toArray(new String[list.size()]));
}
if (resourceModules != null) {
List<String> list = new ArrayList<String>();
for (Map.Entry<PIPResourceFinder, Properties> entry : resourceModules.entrySet()) {
PIPResourceFinder module = entry.getKey();
if (module != null) {
if (module.getModuleName() != null) {
list.add(module.getModuleName());
} else {
list.add(module.getClass().getName());
}
}
}
pdpDataHolder.setPipResourceFinders(list.toArray(new String[list.size()]));
}
return pdpDataHolder;
}
/**
* @param finder
* @return
*/
public PolicyFinderDataHolder getPolicyFinderData(String finder) {
PolicyFinderDataHolder holder = null;
// get registered finder modules
Map<PolicyFinderModule, Properties> finderModules = EntitlementServiceComponent.
getEntitlementConfig().getPolicyFinderModules();
if (finderModules == null || finder == null) {
return null;
}
for (Map.Entry<PolicyFinderModule, Properties> entry : finderModules.entrySet()) {
PolicyFinderModule module = entry.getKey();
if (module != null && (finder.equals(module.getModuleName()) ||
finder.equals(module.getClass().getName()))) {
holder = new PolicyFinderDataHolder();
if (module.getModuleName() != null) {
holder.setModuleName(module.getModuleName());
} else {
holder.setModuleName(module.getClass().getName());
}
holder.setClassName(module.getClass().getName());
holder.setPolicyIdentifiers(module.getOrderedPolicyIdentifiers());
break;
}
}
return holder;
}
/**
* @param finder
* @return
*/
public PIPFinderDataHolder getPIPAttributeFinderData(String finder) {
PIPFinderDataHolder holder = null;
// get registered finder modules
Map<PIPAttributeFinder, Properties> attributeModules = EntitlementServiceComponent.
getEntitlementConfig().getDesignators();
if (attributeModules == null || finder == null) {
return null;
}
for (Map.Entry<PIPAttributeFinder, Properties> entry : attributeModules.entrySet()) {
PIPAttributeFinder module = entry.getKey();
if (module != null && (finder.equals(module.getModuleName()) ||
finder.equals(module.getClass().getName()))) {
holder = new PIPFinderDataHolder();
if (module.getModuleName() != null) {
holder.setModuleName(module.getModuleName());
} else {
holder.setModuleName(module.getClass().getName());
}
holder.setClassName(module.getClass().getName());
holder.setSupportedAttributeIds(module.getSupportedAttributes().
toArray(new String[module.getSupportedAttributes().size()]));
break;
}
}
return holder;
}
/**
* @param finder
* @return
*/
public PIPFinderDataHolder getPIPResourceFinderData(String finder) {
PIPFinderDataHolder holder = null;
// get registered finder modules
Map<PIPResourceFinder, Properties> resourceModules = EntitlementServiceComponent.
getEntitlementConfig().getResourceFinders();
if (resourceModules == null || finder == null) {
return null;
}
for (Map.Entry<PIPResourceFinder, Properties> entry : resourceModules.entrySet()) {
PIPResourceFinder module = entry.getKey();
if (module != null) {
holder = new PIPFinderDataHolder();
if (module.getModuleName() != null) {
holder.setModuleName(module.getModuleName());
} else {
holder.setModuleName(module.getClass().getName());
}
holder.setClassName(module.getClass().getName());
break;
}
}
return holder;
}
/**
* Gets globally defined policy combining algorithm
*
* @return policy combining algorithm as a String
* @throws EntitlementException throws
*/
public String getGlobalPolicyAlgorithm() throws EntitlementException {
return EntitlementAdminEngine.getInstance().
getPolicyDataStore().getGlobalPolicyAlgorithmName();
}
/**
* Sets policy combining algorithm globally
*
* @param policyCombiningAlgorithm policy combining algorithm as a String
* @throws EntitlementException throws
*/
public void setGlobalPolicyAlgorithm(String policyCombiningAlgorithm) throws EntitlementException {
EntitlementAdminEngine.getInstance().
getPolicyDataStore().setGlobalPolicyAlgorithm(policyCombiningAlgorithm);
}
}
| |
/*************************GO-LICENSE-START*********************************
* Copyright 2015 ThoughtWorks, 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.cruise.page;
import com.thoughtworks.cruise.Regex;
import com.thoughtworks.cruise.SahiBrowserWrapper;
import com.thoughtworks.cruise.client.TalkToCruise;
import com.thoughtworks.cruise.state.CurrentPageState;
import com.thoughtworks.cruise.state.CurrentPageState.Page;
import com.thoughtworks.cruise.state.RepositoryState;
import com.thoughtworks.cruise.state.ScenarioState;
import com.thoughtworks.cruise.util.URL;
import com.thoughtworks.cruise.utils.Assertions;
import com.thoughtworks.cruise.utils.Assertions.Function;
import com.thoughtworks.cruise.utils.Assertions.Predicate;
import com.thoughtworks.cruise.utils.Timeout;
import net.sf.sahi.client.Browser;
import net.sf.sahi.client.ElementStub;
import org.hamcrest.Matchers;
import org.hamcrest.core.Is;
import org.hamcrest.core.IsNot;
import org.hamcrest.text.StringContains;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class AlreadyOnStageDetailPage extends CruisePage {
private CurrentPageState currentPageState;
private boolean autoRefresh;
private StageHeaderPartial stageHeaderPartial;
private final RepositoryState repositoryState;
public AlreadyOnStageDetailPage(CurrentPageState currentPageState, ScenarioState scenarioState, RepositoryState repositoryState, Browser browser, TalkToCruise talkToCruise) {
super(scenarioState, true, browser);
this.currentPageState = currentPageState;
this.repositoryState = repositoryState;
this.autoRefresh = new SahiBrowserWrapper(browser).isAutoRefresh();
currentPageState.assertCurrentPageIs(CurrentPageState.Page.STAGE_DETAILS);
this.stageHeaderPartial = new StageHeaderPartial(scenarioState, this, browser);
}
@Override
protected String url() {
return browserWrapper.getCurrentUrl();
}
@com.thoughtworks.gauge.Step("Verify stage bar is displaying run <runNumber> of <totalRuns>")
public void verifyStageBarIsDisplayingRunOf(Integer runNumber, Integer totalRuns) throws Exception {
Assert.assertThat(currentStageRun(), Matchers.is(formatStageRun(runNumber, totalRuns)));
}
public void waitTillStageBarIsDisplayingRunOf(final int runNumber, final int totalRuns) throws Exception {
Assertions.waitUntil(Timeout.TEN_SECONDS, new Predicate() {
public boolean call() throws Exception {
reloadPage();
return currentStageRun().equals(formatStageRun(runNumber, totalRuns));
}
});
}
private String formatStageRun(Integer runNumber, Integer totalRuns) {
return runNumber + " of " + totalRuns;
}
private String currentStageRun() {
return currentStageRunElement().getText();
}
private ElementStub currentStageRunElement() {
return browser.byId("current_stage_run");
}
@com.thoughtworks.gauge.Step("Click on stage bar run <runNumber> of <totalRuns>")
public void clickOnStageBarRunOf(final Integer runNumber, final Integer totalRuns) throws Exception {
currentStageRunElement().click();
browser.link(String.format("/%s of %s/", runNumber, totalRuns)).in(browser.byId("other_stage_runs")).click();
// driver.findElement(By.id("other_stage_runs")).findElement(By.xpath(String.format("//a[contains(., '%s of %s')]",
// runNumber, totalRuns))).click();
Assertions.waitUntil(Timeout.ONE_MINUTE, new Predicate() {
public boolean call() throws Exception {
return currentStageRun().contains(formatStageRun(runNumber, totalRuns));
}
});
}
@com.thoughtworks.gauge.Step("Verify stage <stage> has action <actionName>")
public void verifyStageHasAction(String stage, String actionName) throws Exception {
stageHeaderPartial.verifyStageHasAction(stage, actionName);
}
@com.thoughtworks.gauge.Step("Verify stage <stage> does not have action <actionName>")
public void verifyStageDoesNotHaveAction(String stage, String actionName) throws Exception {
stageHeaderPartial.verifyStageDoesNotHaveAction(stage, actionName);
}
@com.thoughtworks.gauge.Step("Verify stage <stage> does not have any action")
public void verifyStageDoesNotHaveAnyAction(String stage) throws Exception {
stageHeaderPartial.verifyStageDoesNotHaveAnyAction(stage);
}
@com.thoughtworks.gauge.Step("Reload page - Already On Stage Detail Page")
public void reloadPage() {
if (!autoRefresh) {
reloadPageWithAutoRefreshSetCorrectly();
}
}
private void reloadPageWithAutoRefreshSetCorrectly() {
String currentUrl = browserWrapper.getCurrentUrl();
URL url = new URL(currentUrl);
url.addParameter("autoRefresh", Boolean.toString(autoRefresh));
browser.navigateTo(url.toString(), true);
}
@com.thoughtworks.gauge.Step("Rerun stage <stage>")
public void rerunStage(String stage) throws Exception {
stageHeaderPartial.rerunStage(stage);
}
@com.thoughtworks.gauge.Step("Trigger stage <stage>")
public void triggerStage(String stage) throws Exception {
stageHeaderPartial.triggerStage(stage);
}
@com.thoughtworks.gauge.Step("Cancel <stage> - Already On Stage Detail Page")
public void cancel(String stage) throws Exception {
this.autoRefresh = new SahiBrowserWrapper(browser).isAutoRefresh();
stageHeaderPartial.cancel(stage);
}
@com.thoughtworks.gauge.Step("Verify stage <stage> does not have actions link")
public void verifyStageDoesNotHaveActionsLink(String stage) throws Exception {
stageHeaderPartial.verifyStageDoesNotHaveAnyAction(stage);
}
@com.thoughtworks.gauge.Step("Wait for shine feed to update")
public void waitForShineFeedToUpdate() throws Exception {
Assertions.waitUntil(Timeout.TWO_MINUTES, new Predicate() {
@Override
public boolean call() throws Exception {
return totalCount("failures").contains("Failures") && totalCount("errors").contains("Errors");
}
});
}
@com.thoughtworks.gauge.Step("Verify total runs <integer1> failures <failures> errors <errors>")
public void verifyTotalRunsFailuresErrors(Integer integer1, String failures, String errors) throws Exception {
Assert.assertThat(totalCount("failures"), Matchers.is("Total Failures: " + failures));
Assert.assertThat(totalCount("errors"), Matchers.is("Total Errors: " + errors));
}
@com.thoughtworks.gauge.Step("Verify pipeline <pipelineLabel> has <failures> failures <errors> errors")
public void verifyPipelineHasFailuresErrors(String pipelineLabel, String failures, String errors) throws Exception {
Assert.assertThat(countForPipeline(pipelineLabel, "failures"), Matchers.is("Unique Failures: " + failures));
Assert.assertThat(countForPipeline(pipelineLabel, "errors"), Matchers.is("Unique Errors: " + errors));
}
private String totalCount(String type) {
return browser.span(type).in(browser.div(Regex.wholeWord("counts")).in(browser.div(Regex.wholeWord("non_passing_tests")))).getText();
}
private String countForPipeline(String pipelineLabel, String type) {
return browser.span(type).near(fbhPipelineLabelSpan(pipelineLabel)).in(browser.div("/non_passing_tests/")).getText();
}
@com.thoughtworks.gauge.Step("Verify pipeline <pipelineLabel> has test <testName> with <failureType> type")
public void verifyPipelineHasTestWithType(String pipelineLabel, String testName, String failureType) throws Exception {
String failingTestName = failingTestNameForPipeline(pipelineLabel);
Assert.assertThat(failingTestName, StringContains.containsString(testName));
}
private String failingTestNameForPipeline(String pipelineLabel) {
return browser.span(Regex.wholeWord("name")).near(fbhPipelineLabelSpan(pipelineLabel)).getText();
}
@com.thoughtworks.gauge.Step("Verify jobs shows <title> collapsed")
public void verifyJobsShowsCollapsed(String title) throws Exception {
ElementStub hideRevealDiv = findHideRevealDiv(title);
Assert.assertThat(hideRevealDiv.fetch("className"), Matchers.containsString("hidereveal_collapsed"));
}
@com.thoughtworks.gauge.Step("Verify jobs shows <title> open")
public void verifyJobsShowsOpen(String title) throws Exception {
ElementStub hideRevealDiv = findHideRevealDiv(title);
Assert.assertThat(hideRevealDiv.fetch("className"), IsNot.not(Matchers.containsString("hidereveal_collapsed")));
}
@com.thoughtworks.gauge.Step("Wait for jobs to show <title> with jobs <listOfJobs>")
public void waitForJobsToShowWithJobs(final String title, final String listOfJobs) throws Exception {
Assertions.waitUntil(Timeout.FIVE_MINUTES, new Predicate() {
@Override
public boolean call() throws Exception {
ElementStub hideRevealDiv = findHideRevealDiv(title);
Assert.assertThat(hideRevealDiv.fetch("className"), Matchers.containsString("job_grouping"));
String[] jobs = listOfJobs.split(",");
for (String jobName : jobs) {
ElementStub findElement = browser.link(jobName).in(hideRevealDiv);
Assert.assertNotNull("Should show job " + jobName, findElement);
}
return true;
}
});
}
@com.thoughtworks.gauge.Step("Verify jobs shows <title> open with jobs <listOfJobs>")
public void verifyJobsShowsOpenWithJobs(String title, String listOfJobs) throws Exception {
ElementStub hideRevealDiv = findHideRevealDiv(title);
Assert.assertThat(hideRevealDiv.fetch("className"), IsNot.not(Matchers.containsString("hidereveal_collapsed")));
String[] jobs = listOfJobs.split(",");
for (String jobName : jobs) {
ElementStub findElement = browser.link(jobName).in(hideRevealDiv);
Assert.assertNotNull("Should show job " + jobName, findElement);
}
}
private ElementStub findHideRevealDiv(String title) {
return browser.span(title).parentNode();
}
@com.thoughtworks.gauge.Step("Turn on auto refresh")
public void turnOnAutoRefresh() throws Exception {
autoRefresh = true;
reloadPageWithAutoRefreshSetCorrectly();
}
@com.thoughtworks.gauge.Step("Turn off auto refresh")
public void turnOffAutoRefresh() throws Exception {
autoRefresh = false;
reloadPage();
}
@com.thoughtworks.gauge.Step("Verify message <message> shows up - Already On Stage Detail Page")
public void verifyMessageShowsUp(final String message) throws Exception {
Assertions.waitFor(Timeout.TWENTY_SECONDS, new Function<ElementStub>() {
public ElementStub call() {
return browser.span("message").in(browser.div("/non_passing_tests/"));
}
});
}
@com.thoughtworks.gauge.Step("Verify job <pipelineName> <pipelineCounter> <stageName> <stageCounter> <job> links to the job detail page")
public void verifyJobLinksToTheJobDetailPage(String pipelineName, int pipelineCounter, String stageName, int stageCounter, String job) throws Exception {
navigateToJob(job);
Assert.assertThat(browserWrapper.getCurrentUrl(), StringContains.containsString("tab/build/detail/" + scenarioState.pipelineNamed(pipelineName) + "/" + pipelineCounter + "/" + stageName + "/" + stageCounter + "/" + job));
}
@com.thoughtworks.gauge.Step("Navigate to job <job>")
public void navigateToJob(String job) {
browser.link(job).click();
currentPageState.currentPageIs(Page.JOB_DETAILS);
}
@com.thoughtworks.gauge.Step("Verify stage history has <stageHistories>")
public void verifyStageHistoryHas(final String stageHistories) throws Exception {
final String[] history = stageHistories.split("\\s*,\\s*");
List<ElementStub> historyEntries = Assertions.waitFor(Timeout.THIRTY_SECONDS, new Function<List<ElementStub>>() {
public List<ElementStub> call() {
List<ElementStub> entries = browserWrapper.collectIn("div", "/^stage/", browser.div("stage_history").in(browser.div("/overview_widget/")));
if (entries.size() == history.length) {
return entries;
}
throw new RuntimeException(String.format("Expected the page to have %s entries. Instead found %s entries.", history.length, entries.size()));
}
});
for (int i = 0; i < historyEntries.size(); i++) {
ElementStub stageEntry = historyEntries.get(i);
Assert.assertThat(stageEntry.getText(), Is.is(history[i]));
}
}
@com.thoughtworks.gauge.Step("Verify selected stage history entry is <selected>")
public void verifySelectedStageHistoryEntryIs(String selected) throws Exception {
ElementStub selectedStageEntry = browser.link("/selected/").in(browser.div("/stage_history/").in(browser.div("/overview_widget/")));
Assert.assertThat(selectedStageEntry.getText(), Is.is(selected));
}
@com.thoughtworks.gauge.Step("Verify stage bar does not have other runs")
public void verifyStageBarDoesNotHaveOtherRuns() throws Exception {
ElementStub otherStages = otherStageRunsElement();
Assert.assertThat(browserWrapper.collectIn("list", "", otherStages).size(), Is.is(0));
}
private ElementStub otherStageRunsElement() {
return browser.byId("other_stage_runs");
}
@com.thoughtworks.gauge.Step("Wait for stage bar to show <otherRunLabel> in other runs")
public void waitForStageBarToShowInOtherRuns(final String otherRunLabel) throws Exception {
Assertions.waitUntil(Timeout.TWO_MINUTES, new Predicate() {
public boolean call() throws Exception {
browser.byId("show_other_stage_runs").click();
boolean visible = browser.link("/" + otherRunLabel + "/").in(otherStageRunsElement()).isVisible();
if (!visible) {
throw new Exception("Not visible");
}
return visible;
}
});
}
@com.thoughtworks.gauge.Step("Verify pipeline bar shows <stageName> as <status>")
public void verifyPipelineBarShowsAs(final String stageName, final String status) throws Exception {
final ElementStub element = browser.link("/\\bstage_bar\\b/").near(browser.link(stageName)).in(browser.div("pipeline_status_bar"));
Assertions.waitUntil(Timeout.ONE_MINUTE, new Predicate() {
@Override
public boolean call() throws Exception {
return element.fetch("className").contains(status);
}
public String toString() {
return String.format("Expected stage [%s] status ot be [%s]", stageName, status);
}
});
}
@com.thoughtworks.gauge.Step("Verify stage history shows current stage as <status>")
public void verifyStageHistoryShowsCurrentStageAs(String status) throws Exception {
ElementStub stageBar = browser.div("/color_code_stage/").in(browser.link("/selected/").in(browser.div("stage_history")));
assertThat(stageBar.fetch("className"), Matchers.containsString(status));
}
@com.thoughtworks.gauge.Step("Verify stage result shows <status>")
public void verifyStageResultShows(String status) throws Exception {
ElementStub stageBar = browser.span("/message/").in(browser.div("stage_result"));
assertThat(stageBar.getText(), Matchers.containsString(status));
}
@com.thoughtworks.gauge.Step("Wait for stage result to show <result>")
public void waitForStageResultToShow(final String result) throws Exception {
/* looks like a system latency issue, when cancelled the stage on stage details page and then try to reload the page immediatly
the refresh is not successful, so added this forced wait. Should be removed after analysing the API latency if any */
Assertions.sleepMillis(10000);
Assertions.waitUntil(Timeout.FIVE_MINUTES, new Predicate() {
@Override
public boolean call() throws Exception {
reloadPage();
ElementStub stageBar = browser.span("/message/").in(browser.div("stage_result"));
return stageBar.getText().contains(result);
}
});
}
public void verifyStageBarDurationShows(String duration) throws Exception {
ElementStub stageDuration = browser.span("/message/").in(browser.div("stage_result"));
assertThat(stageDuration.getText(), Matchers.containsString(duration));
}
@com.thoughtworks.gauge.Step("Verify stage bar duration shows a time")
public void verifyStageBarDurationShowsATime() throws Exception {
Assertions.waitUntil(Timeout.TWENTY_SECONDS, new Predicate() {
String duration = "NOT FOUND";
public boolean call() throws Exception {
ElementStub stageDuration = browser.span("time").near(browser.span("Duration:").in(browser.div("stage_run_details")));
duration = stageDuration.getText();
return Pattern.matches("\\d{2}\\:\\d{2}\\:\\d{2}", duration);
}
@Override
public String toString() {
return "Expected duration to be a time but was " + duration;
}
});
}
@com.thoughtworks.gauge.Step("Verify stage bar triggered by shows <user>")
public void verifyStageBarTriggeredByShows(String user) throws Exception {
ElementStub stageTriggeredBy = browser.span(Regex.wholeWord("who")).in(browser.div("schedule_info"));
assertThat(stageTriggeredBy.getText(), Matchers.containsString(user));
}
@com.thoughtworks.gauge.Step("Verify stage bar triggered automatically by changes")
public void verifyStageBarTriggeredAutomaticallyByChanges() throws Exception {
ElementStub stageTriggeredBy = browser.span("label").in(browser.div("schedule_info"));
assertThat(stageTriggeredBy.getText(), Is.is("Automatically triggered"));
}
@com.thoughtworks.gauge.Step("Verify stage bar triggered at shows a date")
public void verifyStageBarTriggeredAtShowsADate() throws Exception {
ElementStub stageTriggeredBy = browser.span(Regex.wholeWord("time")).in(browser.div("schedule_info"));
assertTrue(Pattern.matches("\\d{2} \\w{3}, \\d{4} at \\d{2}:\\d{2}:\\d{2} .*", stageTriggeredBy.getText()));
}
@com.thoughtworks.gauge.Step("Verify the lock status is <lockStatus>")
public void verifyTheLockStatusIs(final String lockStatus) throws Exception {
Assertions.waitUntil(Timeout.TWENTY_SECONDS, new Predicate() {
public boolean call() throws Exception {
reloadPage();
ElementStub element = browser.div(Regex.matches("locked_instance"));
return element.getText().contains(lockStatus);
}
});
}
@com.thoughtworks.gauge.Step("Unlock the pipeline")
public void unlockThePipeline() throws Exception {
Assertions.waitFor(Timeout.FIVE_SECONDS, new Function<ElementStub>() {
public ElementStub call() {
return browser.link("Click to unlock");
}
}).click();
}
@com.thoughtworks.gauge.Step("Verify shows history page <pageNumber>")
public void verifyShowsHistoryPage(Integer pageNumber) throws Exception {
assertThat(pageNumber(pageNumber).getText(), Is.is(String.valueOf(pageNumber)));
}
private ElementStub pageNumber(Integer pageNumber) {
return browser.byId("stage_history_" + pageNumber);
}
@com.thoughtworks.gauge.Step("Click on history page <pageNumber>")
public void clickOnHistoryPage(final Integer pageNumber) throws Exception {
pageNumber(pageNumber).click();
}
@com.thoughtworks.gauge.Step("Verfy pipeline <pipelineLabel> modified by <users>")
public void verfyPipelineModifiedBy(String pipelineLabel, String users) throws Exception {
ElementStub userElement = browser.div("users").near(fbhPipelineLabelSpan(pipelineLabel));
String[] individualUsers = users.split(",");
String actualUsers = userElement.getText();
assertThat(actualUsers.startsWith("By "), Is.is(true));
for (String user : individualUsers) {
assertThat(actualUsers, StringContains.containsString(user));
}
}
@com.thoughtworks.gauge.Step("Verify that <stageLocator> stage is displayed")
public void verifyThatStageIsDisplayed(String stageLocator) throws Exception {
assertThat(browserWrapper.getCurrentUrl(), containsString(scenarioState.expand(stageLocator)));
}
@com.thoughtworks.gauge.Step("Navigate to pipeline dashboard page")
public void navigateToPipelineDashboardPage() throws Exception {
browser.link("PIPELINES").click();
currentPageState.currentPageIs(Page.PIPELINE_DASHBOARD);
}
private String userErrorMessage() {
return browser.div("/message_pane/").getText();
}
public void assertUserErrorMessageContains(final String s) throws Exception {
Assertions.waitUntil(Timeout.TWENTY_SECONDS, new Predicate() {
public boolean call() throws Exception {
return userErrorMessage().contains(s);
}
});
}
public void assertUserErrorMessageIsEmpty() throws Exception {
Assertions.waitUntil(Timeout.TWENTY_SECONDS, new Predicate() {
public boolean call() throws Exception {
return userErrorMessage().trim().length() == 0;
}
});
}
@com.thoughtworks.gauge.Step("Verify cruise footer - Already On Stage Detail Page")
@Override
public void verifyCruiseFooter() throws Exception {
super.verifyCruiseFooter();
}
@com.thoughtworks.gauge.Step("Verify commit <revisionAlias> is shown with user <userName> and comment <comment> for material <materialName> of type <materialType>")
public void verifyCommitIsShownWithUserAndCommentForMaterialOfType(String revisionAlias, String userName, String comment, String materialName, String materialType) throws Exception {
ElementStub materialSection = browser.div(AlreadyOnStageDetailMaterialsTab.materialMessage(materialName, materialType)).parentNode();
assertThat(materialSection.exists(), Is.is(true));
String rev = repositoryState.getRevisionFromAlias(revisionAlias);
String text = materialSection.getText();
assertThat(text, containsString(rev));
assertThat(text, containsString(userName));
assertThat(text, containsString(comment));
}
//Temporary solution until package is being implemented as full fledged material
@com.thoughtworks.gauge.Step("Verify commit <revision> is shown with user <userName> and comment <comment> for package material <materialName>")
public void verifyCommitIsShownWithUserAndCommentForPackageMaterial(String revision, String userName, String comment, String materialName) throws Exception {
ElementStub materialSection = browser.div(AlreadyOnStageDetailMaterialsTab.materialMessage(materialName, "Package")).parentNode();
assertThat(materialSection.exists(), Is.is(true));
String text = materialSection.getText();
assertThat(text, containsString(revision));
assertThat(text, containsString(userName));
assertThat(text, containsString(comment));
}
private void assertSectionIsVisible(ElementStub materialSection, String commentMessage) {
ElementStub commentSection = browser.div(commentMessage).in(materialSection);
assertThat(commentSection.isVisible(), Is.is(true));
}
@com.thoughtworks.gauge.Step("Go to materials tab")
public void goToMaterialsTab() {
goToTab("Materials", CurrentPageState.Page.STAGE_DETAIL_MATERIALS_TAB);
}
public void verifyLabelForMaterial(String label, String pipelineName) throws Exception {
ElementStub materialSection = browser.div(AlreadyOnStageDetailMaterialsTab.materialMessage(scenarioState.expand(pipelineName), "Pipeline")).parentNode();
assertSectionIsVisible(materialSection, AlreadyOnStageDetailMaterialsTab.dependencyRevisionLabelMessage(label));
}
@com.thoughtworks.gauge.Step("Verify revision <revision> having label <label> is shown for material <pipelineName>")
public void verifyRevisionHavingLabelIsShownForMaterial(String revision, String label, String pipelineName) throws Exception {
ElementStub materialSection = browser.div(AlreadyOnStageDetailMaterialsTab.materialMessage(scenarioState.expand(pipelineName), "Pipeline")).parentNode();
assertThat(materialSection.exists(), Is.is(true));
String text = materialSection.getText();
assertThat(text.contains(scenarioState.expand(revision)), Is.is(true));
assertThat(text.contains(label), Is.is(true));
}
@com.thoughtworks.gauge.Step("Go to jobs tab")
public void goToJobsTab() throws Exception {
goToTab("Jobs", CurrentPageState.Page.STAGE_DETAIL_JOBS_TAB);
}
@com.thoughtworks.gauge.Step("Go to overview tab")
public void goToOverviewTab() throws Exception {
goToTab("Overview", CurrentPageState.Page.STAGE_DETAILS);
}
private void goToTab(String tabName, Page expectedPage) {
browser.link(tabName).in(browser.div("sub_tabs_container")).click();
currentPageState.currentPageIs(expectedPage);
}
@com.thoughtworks.gauge.Step("Verify pipeline <pipelineCounter> having label <pipelineLabel> has version <revision>")
public void verifyPipelineHavingLabelHasVersion(String pipelineCounter, String pipelineLabel, String revision) throws Exception {
final ElementStub changesLink = browser.link(String.format("changes_button_for_pipeline_%s", pipelineLabel)).near(fbhPipelineLabelSpan(pipelineLabel));
final String rev = repositoryState.getRevisionFromAlias(revision);
String useNewRails = System.getenv("USE_NEW_RAILS");
final String revisionString = (useNewRails != null && useNewRails.equals("N")) ? rev : rev + " - vsm";
assertThat(browser.isVisible(browser.cell(revisionString)), Is.is(false));
Assertions.waitUntil(Timeout.THIRTY_SECONDS, new Predicate() {
@Override
public boolean call() throws Exception {
ElementStub cell = browser.cell(revisionString);
boolean visible = browser.isVisible(cell);
if (!visible)
changesLink.click();
return visible;
}
});
}
private ElementStub fbhPipelineLabelSpan(String pipelineLabel) {
return browser.span("Pipeline Label: " + pipelineLabel);
}
@com.thoughtworks.gauge.Step("Wait for pipeline with label <label> to appear")
public void waitForPipelineWithLabelToAppear(final String label) throws Exception {
/* looks like a system latency issue, when schedule the pipeline thru API and immediately
start reloading the page on browser, the browser not showing up the latest pipeline results, so added this forced wait. Should be removed after analysing the API latency if any */
Assertions.sleepMillis(10000);
Assertions.waitUntil(Timeout.THREE_MINUTES, new Predicate() {
@Override
public boolean call() throws Exception {
reloadPage();
return fbhPipelineLabelSpan(label).isVisible();
}
});
}
@com.thoughtworks.gauge.Step("Verify failure details for job <jobName> suite <suiteName> test <testName> contains <message> with stacktrace <stacktrace>")
public void verifyFailureDetailsForJobSuiteTestContainsWithStacktrace(String jobName, String suiteName, String testName, String message, String stacktrace) throws Exception {
String detailsLink = String.format("//div[@class='suite' and ./span/.='%s']/..//td[@class='test_name' and ./span[.='%s']]//a[.='[Trace]' and ../a[.='%s']]", suiteName, testName, jobName);
browser.byXPath(detailsLink).click();
assertThat(browser.byXPath("//div[@id='fbh_build_cause_content']//tr[@class='failure_message']").text(), Matchers.containsString(message));
for (String stackTraceLine : stacktrace.split(",")) {
assertThat(browser.byXPath("//div[@id='fbh_build_cause_content']").text(), Matchers.containsString(stackTraceLine));
}
}
public void verifyOnStageDetailsPageFor(String stageLocator) throws Exception {
String url = browser.fetch("window.location.href");
assertThat(url, Matchers.containsString(scenarioState.expand(stageLocator)));
}
@com.thoughtworks.gauge.Step("Click compare link - Already on stage Detail Page")
public void clickCompareLink() throws Exception {
browser.link("Compare").click();
currentPageState.currentPageIs(Page.COMPARE_PAGE);
}
@com.thoughtworks.gauge.Step("Click compare link for pipeline counter <pipelineCounter>")
public void clickCompareLinkForPipelineCounter(String pipelineCounter) throws Exception {
List<ElementStub> entries = browserWrapper.collectIn("div", "/^stage/", browser.div("stage_history").in(browser.div("/overview_widget/")));
for (ElementStub entry : entries) {
if (pipelineCounter.equals(browser.span("pipeline_label").in(entry).text())) {
browser.link(1).in(entry).click();
currentPageState.currentPageIs(Page.COMPARE_PAGE);
return;
}
}
throw new RuntimeException(String.format("Expected the page to have %s pipeline counter under the Stage History widget.", pipelineCounter));
}
@com.thoughtworks.gauge.Step("Goto config tab")
public void gotoConfigTab() throws Exception {
goToTab("Config", CurrentPageState.Page.STAGE_DETAIL_CONFIG_TAB);
}
@com.thoughtworks.gauge.Step("Verify config changed marker after pipeline counter <pipelineCounter> stage counter <stageCounter> is a link")
public void verifyConfigChangedMarkerAfterPipelineCounterStageCounterIsALink(String pipelineCounter, String stageCounter) throws Exception {
verifyConfigChangedMarkerAfterPipelineCounter(pipelineCounter, stageCounter, true);
}
@com.thoughtworks.gauge.Step("Verify config changed marker after pipeline counter <pipelineCounter> stage counter <stageCounter> is not a link")
public void verifyConfigChangedMarkerAfterPipelineCounterStageCounterIsNotALink(String pipelineCounter, String stageCounter) throws Exception {
verifyConfigChangedMarkerAfterPipelineCounter(pipelineCounter, stageCounter, false);
}
@com.thoughtworks.gauge.Step("Click on config changed link after pipeline counter <pipelineCounter> stage counter <stageCounter>")
public void clickOnConfigChangedLinkAfterPipelineCounterStageCounter(String pipelineCounter, String stageCounter) throws Exception {
ElementStub configChangedContainer = browser.div(String.format("config_change counter_%s_%s", pipelineCounter, stageCounter));
browser.link("Config Changed").in(configChangedContainer).click();
currentPageState.currentPageIs(Page.STAGE_CONFIG_CHANGES_POPUP);
}
private void verifyConfigChangedMarkerAfterPipelineCounter(String pipelineCounter, String stageCounter, boolean isLink) {
ElementStub configChangedContainer = browser.div(String.format("config_change counter_%s_%s", pipelineCounter, stageCounter));
Assert.assertThat("Could find config changed marker", configChangedContainer.exists(), Is.is(true));
Assert.assertThat(configChangedContainer.getText(), Is.is("Config Changed"));
Assert.assertThat(browser.link("Config Changed").in(configChangedContainer).exists(), Is.is(isLink));
}
@com.thoughtworks.gauge.Step("Verify no config changed marker is present")
public void verifyNoConfigChangedMarkerIsPresent() throws Exception {
Assert.assertThat("Should not have seen any markers indicating that config changed, but did.", browser.span("Config Changed").exists(), Is.is(false));
}
@com.thoughtworks.gauge.Step("Verify rerun is disabled for stage <stageName>")
public void verifyRerunIsDisabledForStage(String stageName) throws Exception {
ElementStub rerunLink = browser.byId("stage_bar_rerun_" + stageName);
assertThat(rerunLink.exists(), Is.is(false));
}
@com.thoughtworks.gauge.Step("Verify rerun is enabled for stage <stageName>")
public void verifyRerunIsEnabledForStage(String stageName) throws Exception {
ElementStub rerunLink = browser.byId("stage_bar_rerun_" + stageName);
assertThat(rerunLink.exists(), Is.is(true));
}
@com.thoughtworks.gauge.Step("Verify that unauthorized access message is shown - Already On Stage Detail Page")
public void verifyThatUnauthorizedAccessMessageIsShown() throws Exception {
super.verifyThatUnauthorizedAccessMessageIsShown();
}
@com.thoughtworks.gauge.Step("Click on revision <revision>")
public void clickOnRevision(String revision) throws Exception {
browser.link(scenarioState.expand(revision)).click();
}
@com.thoughtworks.gauge.Step("Verify user can view config tab contents")
public void verifyUserCanViewConfigTabContents() throws Exception {
Assertions.waitUntil(Timeout.THIRTY_SECONDS, new Predicate() {
@Override
public boolean call() throws Exception {
browser.link("Config").in(browser.div("sub_tabs_container")).click();
return (notificationElement().getText().trim().contains("This version of config"));
}
});
}
@com.thoughtworks.gauge.Step("Verify user cannot view config tab contents")
public void verifyUserCannotViewConfigTabContents() throws Exception {
Assertions.waitUntil(Timeout.THIRTY_SECONDS, new Predicate() {
@Override
public boolean call() throws Exception {
browser.link("Config").in(browser.div("sub_tabs_container")).click();
return (notificationElement().getText().trim().contains("Historical configuration is available only for Go Administrators"));
}
});
}
private ElementStub notificationElement() {
return browser.byXPath("//div[@id='ran_with_config']//p[@class='information']");
}
@com.thoughtworks.gauge.Step("Go to tests tab")
public void goToTestsTab() {
goToTab("Tests", CurrentPageState.Page.STAGE_DETAIL_TESTS_TAB);
}
@com.thoughtworks.gauge.Step("Verify that there are <numberOfJobsExpected> jobs")
public void verifyThatThereAreJobs(Integer numberOfJobsExpected) throws Exception {
List<ElementStub> jobList = new ArrayList<ElementStub>();
for (int i = 0; i < 100; i++) {
ElementStub row = browser.row(String.format("/job/[%d]", i));
if (!row.exists())
break;
jobList.add(row);
}
assertThat(jobList.size(), is(numberOfJobsExpected));
}
}
| |
package org.oskari.print.request;
import java.util.List;
import org.geotools.referencing.CRS;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import fi.nls.oskari.domain.User;
public class PrintRequest {
private User user;
private double east;
private double north;
private String srsName;
private CoordinateReferenceSystem crs;
private double resolution;
private int width;
private int height;
private int targetWidth;
private int targetHeight;
private PrintFormat format;
private boolean showLogo;
private boolean showScale;
private boolean showDate;
private boolean showTimeSeriesTime;
private String title;
private List<PrintLayer> layers;
private String markers;
private String scaleText;
private String time;
private String formattedTime;
private String timeseriesLabel;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public double getEast() {
return east;
}
public void setEast(double east) {
this.east = east;
}
public double getNorth() {
return north;
}
public void setNorth(double north) {
this.north = north;
}
public String getSrsName() {
return srsName;
}
public void setSrsName(String srsName) throws FactoryException {
this.srsName = srsName;
this.crs = CRS.decode(srsName, true);
}
public CoordinateReferenceSystem getCrs() {
return crs;
}
public double getResolution() {
return resolution;
}
public void setResolution(double resolution) {
this.resolution = resolution;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getTargetWidth() {
return targetWidth;
}
public void setTargetWidth(int targetWidth) {
this.targetWidth = targetWidth;
}
public int getTargetHeight() {
return targetHeight;
}
public void setTargetHeight(int targetHeight) {
this.targetHeight = targetHeight;
}
public PrintFormat getFormat() {
return format;
}
public void setFormat(PrintFormat format) {
this.format = format;
}
public boolean isShowScale() {
return showScale;
}
public void setShowScale(boolean showScale) {
this.showScale = showScale;
}
public boolean isShowDate() {
return showDate;
}
public void setShowDate(boolean showDate) {
this.showDate = showDate;
}
public boolean isShowTimeSeriesTime() {
return showTimeSeriesTime;
}
public void setShowTimeSeriesTime(boolean showTimeSeriesTime) {
this.showTimeSeriesTime = showTimeSeriesTime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<PrintLayer> getLayers() {
return layers;
}
public void setLayers(List<PrintLayer> layers) {
this.layers = layers;
}
public String getMarkers() {
return markers;
}
public void setMarkers(String markers) {
this.markers = markers;
}
public boolean isShowLogo() {
return showLogo;
}
public void setShowLogo(boolean showLogo) {
this.showLogo = showLogo;
}
public String getScaleText() {
return scaleText;
}
public void setScaleText(String scaleText) {
this.scaleText = scaleText;
}
public boolean isScaleText(){
return (this.scaleText != null && !this.scaleText.isEmpty());
}
public double[] getBoundingBox() {
double halfResolution = resolution * 0.5;
double widthHalf = width * halfResolution;
double heightHalf = height * halfResolution;
return new double[] {
east - widthHalf,
north - heightHalf,
east + widthHalf,
north + heightHalf
};
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getFormattedTime() {
return formattedTime;
}
public void setFormattedTime(String formattedTime) {
this.formattedTime = formattedTime;
}
public String getTimeseriesLabel() {
return timeseriesLabel;
}
public void setTimeseriesLabel(String timeseriesLabel) {
this.timeseriesLabel = timeseriesLabel;
}
}
| |
/*
Copyright (c) 2002 JSON.org
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 shall be used for Good, not Evil.
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 sec.web.json.utilities;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* A JSONArray is an ordered sequence of values. Its external text form is a
* string wrapped in square brackets with commas separating the values. The
* internal form is an object having <code>get</code> and <code>opt</code>
* methods for accessing the values by index, and <code>put</code> methods for
* adding or replacing values. The values can be any of these types:
* <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
* <code>Number</code>, <code>String</code>, or the
* <code>JSONObject.NULL object</code>.
* <p>
* The constructor can convert a JSON text into a Java object. The
* <code>toString</code> method converts to JSON text.
* <p>
* A <code>get</code> method returns a value if one can be found, and throws an
* exception if one cannot be found. An <code>opt</code> method returns a
* default value instead of throwing an exception, and so is useful for
* obtaining optional values.
* <p>
* The generic <code>get()</code> and <code>opt()</code> methods return an
* object which you can cast or query for type. There are also typed
* <code>get</code> and <code>opt</code> methods that do type checking and type
* coercion for you.
* <p>
* The texts produced by the <code>toString</code> methods strictly conform to
* JSON syntax rules. The constructors are more forgiving in the texts they will
* accept:
* <ul>
* <li>An extra <code>,</code> <small>(comma)</small> may appear just
* before the closing bracket.</li>
* <li>The <code>null</code> value will be inserted when there
* is <code>,</code> <small>(comma)</small> elision.</li>
* <li>Strings may be quoted with <code>'</code> <small>(single
* quote)</small>.</li>
* <li>Strings do not need to be quoted at all if they do not begin with a quote
* or single quote, and if they do not contain leading or trailing spaces,
* and if they do not contain any of these characters:
* <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
* and if they are not the reserved words <code>true</code>,
* <code>false</code>, or <code>null</code>.</li>
* <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as
* well as by <code>,</code> <small>(comma)</small>.</li>
* <li>Numbers may have the
* <code>0x-</code> <small>(hex)</small> prefix.</li>
* </ul>
* @author JSON.org
* @version 2011-05-04
*/
public class JSONArray {
/**
* The arrayList where the JSONArray's properties are kept.
*/
private ArrayList<Object> myArrayList;
/**
* Construct an empty JSONArray.
*/
public JSONArray() {
this.myArrayList = new ArrayList<Object>();
}
/**
* Construct a JSONArray from a JSONTokener.
* @param x A JSONTokener
* @throws JSONException If there is a syntax error.
*/
public JSONArray(JSONTokener x) throws JSONException {
this();
if (x.nextClean() != '[') {
throw x.syntaxError("A JSONArray text must start with '['");
}
if (x.nextClean() != ']') {
x.back();
for (;;) {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
} else {
x.back();
this.myArrayList.add(x.nextValue());
}
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == ']') {
return;
}
x.back();
break;
case ']':
return;
default:
throw x.syntaxError("Expected a ',' or ']'");
}
}
}
}
/**
* Construct a JSONArray from a source JSON text.
* @param source A string that begins with
* <code>[</code> <small>(left bracket)</small>
* and ends with <code>]</code> <small>(right bracket)</small>.
* @throws JSONException If there is a syntax error.
*/
public JSONArray(String source) throws JSONException {
this(new JSONTokener(source));
}
/**
* Construct a JSONArray from a Collection.
* @param collection A Collection.
*/
public JSONArray(Collection<?> collection) {
this.myArrayList = new ArrayList<Object>();
if (collection != null) {
Iterator<?> iter = collection.iterator();
while (iter.hasNext()) {
this.myArrayList.add(JSONObject.wrap(iter.next()));
}
}
}
/**
* Construct a JSONArray from an array
* @throws JSONException If not an array.
*/
public JSONArray(Object array) throws JSONException {
this();
if (array.getClass().isArray()) {
int length = Array.getLength(array);
for (int i = 0; i < length; i += 1) {
this.put(JSONObject.wrap(Array.get(array, i)));
}
} else {
throw new JSONException(
"JSONArray initial value should be a string or collection or array.");
}
}
/**
* Get the object value associated with an index.
* @param index
* The index must be between 0 and length() - 1.
* @return An object value.
* @throws JSONException If there is no value for the index.
*/
public Object get(int index) throws JSONException {
Object object = opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
}
/**
* Get the boolean value associated with an index.
* The string values "true" and "false" are converted to boolean.
*
* @param index The index must be between 0 and length() - 1.
* @return The truth.
* @throws JSONException If there is no value for the index or if the
* value is not convertible to boolean.
*/
public boolean getBoolean(int index) throws JSONException {
Object object = get(index);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
}
/**
* Get the double value associated with an index.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value cannot
* be converted to a number.
*/
public double getDouble(int index) throws JSONException {
Object object = get(index);
try {
return object instanceof Number ?
((Number)object).doubleValue() :
Double.parseDouble((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
}
/**
* Get the int value associated with an index.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value is not a number.
*/
public int getInt(int index) throws JSONException {
Object object = get(index);
try {
return object instanceof Number ?
((Number)object).intValue() :
Integer.parseInt((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
}
/**
* Get the JSONArray associated with an index.
* @param index The index must be between 0 and length() - 1.
* @return A JSONArray value.
* @throws JSONException If there is no value for the index. or if the
* value is not a JSONArray
*/
public JSONArray getJSONArray(int index) throws JSONException {
Object object = get(index);
if (object instanceof JSONArray) {
return (JSONArray)object;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONArray.");
}
/**
* Get the JSONObject associated with an index.
* @param index subscript
* @return A JSONObject value.
* @throws JSONException If there is no value for the index or if the
* value is not a JSONObject
*/
public JSONObject getJSONObject(int index) throws JSONException {
Object object = get(index);
if (object instanceof JSONObject) {
return (JSONObject)object;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONObject.");
}
/**
* Get the long value associated with an index.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
* @throws JSONException If the key is not found or if the value cannot
* be converted to a number.
*/
public long getLong(int index) throws JSONException {
Object object = get(index);
try {
return object instanceof Number ?
((Number)object).longValue() :
Long.parseLong((String)object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] is not a number.");
}
}
/**
* Get the string associated with an index.
* @param index The index must be between 0 and length() - 1.
* @return A string value.
* @throws JSONException If there is no string value for the index.
*/
public String getString(int index) throws JSONException {
Object object = get(index);
if (object instanceof String) {
return (String)object;
}
throw new JSONException("JSONArray[" + index + "] not a string.");
}
/**
* Determine if the value is null.
* @param index The index must be between 0 and length() - 1.
* @return true if the value at the index is null, or if there is no value.
*/
public boolean isNull(int index) {
return JSONObject.NULL.equals(opt(index));
}
/**
* Make a string from the contents of this JSONArray. The
* <code>separator</code> string is inserted between each element.
* Warning: This method assumes that the data structure is acyclical.
* @param separator A string that will be inserted between the elements.
* @return a string.
* @throws JSONException If the array contains an invalid number.
*/
public String join(String separator) throws JSONException {
int len = length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
}
return sb.toString();
}
/**
* Get the number of elements in the JSONArray, included nulls.
*
* @return The length (or size).
*/
public int length() {
return this.myArrayList.size();
}
/**
* Get the optional object value associated with an index.
* @param index The index must be between 0 and length() - 1.
* @return An object value, or null if there is no
* object at that index.
*/
public Object opt(int index) {
return (index < 0 || index >= length()) ?
null : this.myArrayList.get(index);
}
/**
* Get the optional boolean value associated with an index.
* It returns false if there is no value at that index,
* or if the value is not Boolean.TRUE or the String "true".
*
* @param index The index must be between 0 and length() - 1.
* @return The truth.
*/
public boolean optBoolean(int index) {
return optBoolean(index, false);
}
/**
* Get the optional boolean value associated with an index.
* It returns the defaultValue if there is no value at that index or if
* it is not a Boolean or the String "true" or "false" (case insensitive).
*
* @param index The index must be between 0 and length() - 1.
* @param defaultValue A boolean default.
* @return The truth.
*/
public boolean optBoolean(int index, boolean defaultValue) {
try {
return getBoolean(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional double value associated with an index.
* NaN is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
*/
public double optDouble(int index) {
return optDouble(index, Double.NaN);
}
/**
* Get the optional double value associated with an index.
* The defaultValue is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index subscript
* @param defaultValue The default value.
* @return The value.
*/
public double optDouble(int index, double defaultValue) {
try {
return getDouble(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional int value associated with an index.
* Zero is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
*/
public int optInt(int index) {
return optInt(index, 0);
}
/**
* Get the optional int value associated with an index.
* The defaultValue is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
* @return The value.
*/
public int optInt(int index, int defaultValue) {
try {
return getInt(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional JSONArray associated with an index.
* @param index subscript
* @return A JSONArray value, or null if the index has no value,
* or if the value is not a JSONArray.
*/
public JSONArray optJSONArray(int index) {
Object o = opt(index);
return o instanceof JSONArray ? (JSONArray)o : null;
}
/**
* Get the optional JSONObject associated with an index.
* Null is returned if the key is not found, or null if the index has
* no value, or if the value is not a JSONObject.
*
* @param index The index must be between 0 and length() - 1.
* @return A JSONObject value.
*/
public JSONObject optJSONObject(int index) {
Object o = opt(index);
return o instanceof JSONObject ? (JSONObject)o : null;
}
/**
* Get the optional long value associated with an index.
* Zero is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
*
* @param index The index must be between 0 and length() - 1.
* @return The value.
*/
public long optLong(int index) {
return optLong(index, 0);
}
/**
* Get the optional long value associated with an index.
* The defaultValue is returned if there is no value for the index,
* or if the value is not a number and cannot be converted to a number.
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
* @return The value.
*/
public long optLong(int index, long defaultValue) {
try {
return getLong(index);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Get the optional string value associated with an index. It returns an
* empty string if there is no value at that index. If the value
* is not a string and is not null, then it is coverted to a string.
*
* @param index The index must be between 0 and length() - 1.
* @return A String value.
*/
public String optString(int index) {
return optString(index, "");
}
/**
* Get the optional string associated with an index.
* The defaultValue is returned if the key is not found.
*
* @param index The index must be between 0 and length() - 1.
* @param defaultValue The default value.
* @return A String value.
*/
public String optString(int index, String defaultValue) {
Object object = opt(index);
return object != null ? object.toString() : defaultValue;
}
/**
* Append a boolean value. This increases the array's length by one.
*
* @param value A boolean value.
* @return this.
*/
public JSONArray put(boolean value) {
put(value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection.
* @param value A Collection value.
* @return this.
*/
public JSONArray put(Collection<?> value) {
put(new JSONArray(value));
return this;
}
/**
* Append a double value. This increases the array's length by one.
*
* @param value A double value.
* @throws JSONException if the value is not finite.
* @return this.
*/
public JSONArray put(double value) throws JSONException {
Double d = new Double(value);
JSONObject.testValidity(d);
put(d);
return this;
}
/**
* Append an int value. This increases the array's length by one.
*
* @param value An int value.
* @return this.
*/
public JSONArray put(int value) {
put(new Integer(value));
return this;
}
/**
* Append an long value. This increases the array's length by one.
*
* @param value A long value.
* @return this.
*/
public JSONArray put(long value) {
put(new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONObject which is produced from a Map.
* @param value A Map value.
* @return this.
*/
public JSONArray put(Map<?, ?> value) {
put(new JSONObject(value));
return this;
}
/**
* Append an object value. This increases the array's length by one.
* @param value An object value. The value should be a
* Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
* @return this.
*/
public JSONArray put(Object value) {
this.myArrayList.add(value);
return this;
}
/**
* Put or replace a boolean value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
* @param index The subscript.
* @param value A boolean value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray put(int index, boolean value) throws JSONException {
put(index, value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONArray which is produced from a Collection.
* @param index The subscript.
* @param value A Collection value.
* @return this.
* @throws JSONException If the index is negative or if the value is
* not finite.
*/
public JSONArray put(int index, Collection<?> value) throws JSONException {
put(index, new JSONArray(value));
return this;
}
/**
* Put or replace a double value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
* it out.
* @param index The subscript.
* @param value A double value.
* @return this.
* @throws JSONException If the index is negative or if the value is
* not finite.
*/
public JSONArray put(int index, double value) throws JSONException {
put(index, new Double(value));
return this;
}
/**
* Put or replace an int value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
* it out.
* @param index The subscript.
* @param value An int value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray put(int index, int value) throws JSONException {
put(index, new Integer(value));
return this;
}
/**
* Put or replace a long value. If the index is greater than the length of
* the JSONArray, then null elements will be added as necessary to pad
* it out.
* @param index The subscript.
* @param value A long value.
* @return this.
* @throws JSONException If the index is negative.
*/
public JSONArray put(int index, long value) throws JSONException {
put(index, new Long(value));
return this;
}
/**
* Put a value in the JSONArray, where the value will be a
* JSONObject that is produced from a Map.
* @param index The subscript.
* @param value The Map value.
* @return this.
* @throws JSONException If the index is negative or if the the value is
* an invalid number.
*/
public JSONArray put(int index, Map<?, ?> value) throws JSONException {
put(index, new JSONObject(value));
return this;
}
/**
* Put or replace an object value in the JSONArray. If the index is greater
* than the length of the JSONArray, then null elements will be added as
* necessary to pad it out.
* @param index The subscript.
* @param value The value to put into the array. The value should be a
* Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
* @return this.
* @throws JSONException If the index is negative or if the the value is
* an invalid number.
*/
public JSONArray put(int index, Object value) throws JSONException {
JSONObject.testValidity(value);
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < length()) {
this.myArrayList.set(index, value);
} else {
while (index != length()) {
put(JSONObject.NULL);
}
put(value);
}
return this;
}
/**
* Remove an index and close the hole.
* @param index The index of the element to be removed.
* @return The value that was associated with the index,
* or null if there was no value.
*/
public Object remove(int index) {
Object o = opt(index);
this.myArrayList.remove(index);
return o;
}
/**
* Produce a JSONObject by combining a JSONArray of names with the values
* of this JSONArray.
* @param names A JSONArray containing a list of key strings. These will be
* paired with the values.
* @return A JSONObject, or null if there are no names or if this JSONArray
* has no values.
* @throws JSONException If any of the names are null.
*/
public JSONObject toJSONObject(JSONArray names) throws JSONException {
if (names == null || names.length() == 0 || length() == 0) {
return null;
}
JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i));
}
return jo;
}
/**
* Make a JSON text of this JSONArray. For compactness, no
* unnecessary whitespace is added. If it is not possible to produce a
* syntactically correct JSON text then null will be returned instead. This
* could occur if the array contains an invalid number.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, transmittable
* representation of the array.
*/
public String toString() {
try {
return '[' + join(",") + ']';
} catch (Exception e) {
return null;
}
}
/**
* Make a prettyprinted JSON text of this JSONArray.
* Warning: This method assumes that the data structure is acyclical.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @return a printable, displayable, transmittable
* representation of the object, beginning
* with <code>[</code> <small>(left bracket)</small> and ending
* with <code>]</code> <small>(right bracket)</small>.
* @throws JSONException
*/
public String toString(int indentFactor) throws JSONException {
return toString(indentFactor, 0);
}
/**
* Make a prettyprinted JSON text of this JSONArray.
* Warning: This method assumes that the data structure is acyclical.
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @param indent The indention of the top level.
* @return a printable, displayable, transmittable
* representation of the array.
* @throws JSONException
*/
String toString(int indentFactor, int indent) throws JSONException {
int len = length();
if (len == 0) {
return "[]";
}
int i;
StringBuffer sb = new StringBuffer("[");
if (len == 1) {
sb.append(JSONObject.valueToString(this.myArrayList.get(0),
indentFactor, indent));
} else {
int newindent = indent + indentFactor;
sb.append('\n');
for (i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(",\n");
}
for (int j = 0; j < newindent; j += 1) {
sb.append(' ');
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i),
indentFactor, newindent));
}
sb.append('\n');
for (i = 0; i < indent; i += 1) {
sb.append(' ');
}
}
sb.append(']');
return sb.toString();
}
/**
* Write the contents of the JSONArray as JSON text to a writer.
* For compactness, no whitespace is added.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return The writer.
* @throws JSONException
*/
public Writer write(Writer writer) throws JSONException {
try {
boolean b = false;
int len = length();
writer.write('[');
for (int i = 0; i < len; i += 1) {
if (b) {
writer.write(',');
}
Object v = this.myArrayList.get(i);
if (v instanceof JSONObject) {
((JSONObject)v).write(writer);
} else if (v instanceof JSONArray) {
((JSONArray)v).write(writer);
} else {
writer.write(JSONObject.valueToString(v));
}
b = true;
}
writer.write(']');
return writer;
} catch (IOException e) {
throw new JSONException(e);
}
}
}
| |
package net.mcft.copy.betterstorage.tile.crate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import net.mcft.copy.betterstorage.api.crate.ICrateStorage;
import net.mcft.copy.betterstorage.api.crate.ICrateWatcher;
import net.mcft.copy.betterstorage.config.GlobalConfig;
import net.mcft.copy.betterstorage.container.ContainerBetterStorage;
import net.mcft.copy.betterstorage.container.ContainerCrate;
import net.mcft.copy.betterstorage.content.BetterStorageTiles;
import net.mcft.copy.betterstorage.inventory.InventoryCratePlayerView;
import net.mcft.copy.betterstorage.misc.Constants;
import net.mcft.copy.betterstorage.misc.ItemIdentifier;
import net.mcft.copy.betterstorage.tile.entity.TileEntityContainer;
import net.mcft.copy.betterstorage.utils.PlayerUtils;
import net.mcft.copy.betterstorage.utils.WorldUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraftforge.common.util.ForgeDirection;
public class TileEntityCrate extends TileEntityContainer implements IInventory, ICrateStorage, ICrateWatcher {
private static final ForgeDirection[] sideDirections = {
ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.WEST, ForgeDirection.EAST
};
public static final int slotsPerCrate = 18;
private CratePileData data;
/** Crate pile id of this crate, used only for saving/loading. */
private int id = -1;
public int getID() { return id; }
/** Get the pile data for this tile entity. */
public CratePileData getPileData() {
if (worldObj.isRemote)
throw new IllegalStateException("Can't be called client-side.");
if (data == null) {
CratePileCollection collection = CratePileCollection.getCollection(worldObj);
if (id == -1)
setPileData(collection.createCratePile(), true);
else setPileData(collection.getCratePile(id), false);
}
return data;
}
/** Sets the pile data and adds the crate to it if desired. <br>
* Removes the crate from the old pile data if it had one. */
private void setPileData(CratePileData data, boolean addCrate) {
if (this.data != null)
this.data.removeCrate(this);
this.data = data;
if (data != null) {
id = data.id;
markForUpdate();
if (addCrate) data.addCrate(this);
} else id = -1;
}
/** Destroys all crates above, and makes sure when piles split,
* each pile gets their own CratePileData object. */
private void checkPileConnections(CratePileData data) {
int x = xCoord, y = yCoord, z = zCoord;
// Destroy all crates above.
TileEntityCrate crateAbove = WorldUtils.get(worldObj, x, y + 1, z, TileEntityCrate.class);
if ((crateAbove != null) && (crateAbove.data == data)) {
worldObj.setBlockToAir(x, y + 1, z);
crateAbove.dropItem(new ItemStack(BetterStorageTiles.crate));
}
// If there's still some crates left and this is a
// base crate, see which crates are still connected.
if ((data.getNumCrates() <= 0) || (y != data.getRegion().minY)) return;
// If there's more than one crate set, they need to split.
List<HashSet<TileEntityCrate>> crateSets = getCrateSets(x, y, z, data);
if (crateSets.size() <= 1) return;
// The first crate set will keep the original pile data.
// All other sets will get new pile data objects.
for (int i = 1; i < crateSets.size(); i++) {
HashSet<TileEntityCrate> set = crateSets.get(i);
CratePileData newPileData = data.collection.createCratePile();
int numCrates = set.size();
// Add the base crates from the set.
for (TileEntityCrate newPileCrate : set) {
newPileCrate.setPileData(newPileData, true);
// Add all crates above the base crate.
while (true) {
newPileCrate = WorldUtils.get(worldObj, newPileCrate.xCoord, newPileCrate.yCoord + 1, newPileCrate.zCoord, TileEntityCrate.class);
if (newPileCrate == null) break;
newPileCrate.setPileData(newPileData, true);
numCrates++;
}
}
// Move some of the items over to the new crate pile.
int count = numCrates * data.getOccupiedSlots() / (data.getNumCrates() + numCrates);
for (ItemStack stack : data.getContents().getRandomStacks(count)) {
data.removeItems(stack);
newPileData.addItems(stack);
}
}
// Trim the original map to the size it actually is.
// This is needed because the crates may not be removed in
// order, from outside to inside.
data.trimMap();
}
private List<HashSet<TileEntityCrate>> getCrateSets(int x, int y, int z, CratePileData data) {
List<HashSet<TileEntityCrate>> crateSets = new ArrayList<HashSet<TileEntityCrate>>();
int checkedCrates = 0;
neighborLoop: // Suck it :P
for (ForgeDirection dir : sideDirections) {
int nx = x + dir.offsetX;
int nz = z + dir.offsetZ;
// Continue if this neighbor block is not part of the crate pile.
TileEntityCrate neighborCrate = WorldUtils.get(worldObj, nx, y, nz, TileEntityCrate.class);
if ((neighborCrate == null) || (neighborCrate.data != data)) continue;
// See if the neighbor crate is already in a crate set,
// in that case continue with the next neighbor block.
for (HashSet<TileEntityCrate> set : crateSets)
if (set.contains(neighborCrate)) continue neighborLoop;
// Create a new set of crates and fill it with all connecting crates.
HashSet<TileEntityCrate> set = new HashSet<TileEntityCrate>();
set.add(neighborCrate);
for (ForgeDirection ndir : sideDirections)
checkConnections(nx + ndir.offsetX, y, nz + ndir.offsetZ, data, set);
crateSets.add(set);
// If we checked all crates, stop the loop.
checkedCrates += set.size();
if (checkedCrates >= data.getNumCrates()) break;
}
return crateSets;
}
private void checkConnections(int x, int y, int z, CratePileData data, HashSet<TileEntityCrate> set) {
TileEntityCrate crate = WorldUtils.get(worldObj, x, y, z, TileEntityCrate.class);
if ((crate == null) || (data != crate.data) || set.contains(crate)) return;
set.add(crate);
for (ForgeDirection ndir : sideDirections)
checkConnections(x + ndir.offsetX, y, z + ndir.offsetZ, data, set);
}
@Override
public void updateEntity() {
super.updateEntity();
if (worldObj.isRemote || (data != null)) return;
if (!isInvalid()) getPileData();
}
public void attemptConnect(ForgeDirection side) {
if (worldObj.isRemote || (side == ForgeDirection.UP)) return;
int x = xCoord + side.offsetX;
int y = yCoord + side.offsetY;
int z = zCoord + side.offsetZ;
TileEntityCrate crateClicked = WorldUtils.get(worldObj, x, y, z, TileEntityCrate.class);
if (crateClicked == null) return;
CratePileData pileData = crateClicked.getPileData();
if (pileData.canAdd(this))
setPileData(pileData, true);
}
@Override
public void invalidate() {
super.invalidate();
if (worldObj.isRemote) return;
CratePileData data = getPileData();
if (watcherRegistered)
data.removeWatcher(this);
setPileData(null, false);
dropOverflowContents(data);
checkPileConnections(data);
}
/** Drops a single item from the (destroyed) crate. */
private void dropItem(ItemStack stack) {
WorldUtils.dropStackFromBlock(worldObj, xCoord, yCoord, zCoord, stack);
}
/** Drops multiple item from the (destroyed) crate. */
private void dropItems(List<ItemStack> stacks) {
for (ItemStack stack : stacks)
dropItem(stack);
}
/** Drops contents that don't fit into the
* crate pile after a crate got destroyed. */
private void dropOverflowContents(CratePileData data) {
int amount = -data.getFreeSlots();
if (amount <= 0) return;
List<ItemStack> items = data.getContents().getRandomStacks(amount);
for (ItemStack stack : items) data.removeItems(stack);
dropItems(items);
}
// TileEntityContainer stuff
@Override
protected int getSizeContents() { return 0; }
@Override
public String getName() { return Constants.containerCrate; }
@Override
public void openGui(EntityPlayer player) {
if (!canPlayerUseContainer(player)) return;
PlayerUtils.openGui(player, getName(), getColumns(), 2 * Math.min(data.getNumCrates(), 3),
getContainerTitle(), createContainer(player));
}
@Override
public ContainerBetterStorage createContainer(EntityPlayer player) {
return new ContainerCrate(player, new InventoryCratePlayerView(this));
}
// Comparator related
private boolean watcherRegistered = false;
@Override
protected int getComparatorSignalStengthInternal() {
if (worldObj.isRemote) return 0;
CratePileData data = getPileData();
return ((data.getOccupiedSlots() > 0)
? (1 + data.getOccupiedSlots() * 14 / data.getCapacity()) : 0);
}
@Override
protected void markComparatorAccessed() {
super.markComparatorAccessed();
if (!watcherRegistered && !worldObj.isRemote) {
getPileData().addWatcher(this);
watcherRegistered = true;
}
}
@Override
protected void comparatorUpdateAndReset() {
super.comparatorUpdateAndReset();
if (watcherRegistered && !hasComparatorAccessed()) {
getPileData().removeWatcher(this);
watcherRegistered = false;
}
}
@Override
public void onCrateItemsModified(ItemStack stack) {
markContentsChanged();
}
// IInventory implementation
@Override
public String getInventoryName() { return getName(); }
@Override
public int getInventoryStackLimit() { return 64; }
@Override
public int getSizeInventory() {
if (!GlobalConfig.enableCrateInventoryInterfaceSetting.getValue()) return 0;
if (worldObj.isRemote) return 1;
return getPileData().blockView.getSizeInventory();
}
@Override
public boolean isItemValidForSlot(int slot, ItemStack stack) {
if (!GlobalConfig.enableCrateInventoryInterfaceSetting.getValue()) return false;
return getPileData().blockView.isItemValidForSlot(slot, stack);
}
@Override
public ItemStack getStackInSlot(int slot) {
if (!GlobalConfig.enableCrateInventoryInterfaceSetting.getValue()) return null;
return getPileData().blockView.getStackInSlot(slot);
}
@Override
public void setInventorySlotContents(int slot, ItemStack stack) {
if (GlobalConfig.enableCrateInventoryInterfaceSetting.getValue()) {
getPileData().blockView.setInventorySlotContents(slot, stack);
markDirty();
}
}
@Override
public ItemStack getStackInSlotOnClosing(int slot) {
if (!GlobalConfig.enableCrateInventoryInterfaceSetting.getValue()) return null;
return getPileData().blockView.getStackInSlotOnClosing(slot);
}
@Override
public ItemStack decrStackSize(int slot, int amount) {
if (!GlobalConfig.enableCrateInventoryInterfaceSetting.getValue()) return null;
markDirty();
return getPileData().blockView.decrStackSize(slot, amount);
}
@Override
public void markDirty() {
if (GlobalConfig.enableCrateInventoryInterfaceSetting.getValue())
getPileData().blockView.markDirty();
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) { return false; }
@Override
public boolean hasCustomInventoryName() { return false; }
@Override
public void openInventory() { getPileData().blockView.openInventory(); }
@Override
public void closeInventory() { getPileData().blockView.closeInventory(); }
// ICrateStorage implementation
private static boolean isEnabled() {
return GlobalConfig.enableCrateStorageInterfaceSetting.getValue();
}
@Override
public Object getCrateIdentifier() { return getPileData(); }
@Override
public int getCapacity() { return (isEnabled() ? getPileData().getCapacity() : 0); }
@Override
public int getOccupiedSlots() { return (isEnabled() ? getPileData().getOccupiedSlots() : 0); }
@Override
public int getUniqueItems() { return (isEnabled() ? getPileData().getUniqueItems() : 0); }
@Override
public Iterable<ItemStack> getContents() {
return (isEnabled() ? getPileData().getContents().getItems() : Collections.EMPTY_LIST);
}
@Override
public Iterable<ItemStack> getRandomStacks() {
return (isEnabled() ? getPileData().getContents().getRandomStacks() : Collections.EMPTY_LIST);
}
@Override
public int getItemCount(ItemStack identifier) {
return (isEnabled() ? getPileData().getContents().get(new ItemIdentifier(identifier)) : 0);
}
@Override
public int getSpaceForItem(ItemStack identifier) {
return (isEnabled() ? getPileData().getSpaceForItem(identifier) : 0);
}
@Override
public ItemStack insertItems(ItemStack stack) {
return (isEnabled() ? getPileData().addItems(stack) : stack);
}
@Override
public ItemStack extractItems(ItemStack identifier, int amount) {
return (isEnabled() ? getPileData().removeItems(new ItemIdentifier(identifier), amount) : null);
}
@Override
public void registerCrateWatcher(ICrateWatcher watcher) { if (isEnabled()) getPileData().addWatcher(watcher); }
@Override
public void unregisterCrateWatcher(ICrateWatcher watcher) { if (isEnabled()) getPileData().removeWatcher(watcher); }
// TileEntity synchronization
@Override
public Packet getDescriptionPacket() {
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("crateId", id);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, compound);
}
@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet) {
id = packet.func_148857_g().getInteger("crateId");
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
// Reading from / writing to NBT
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
id = compound.getInteger("crateId");
}
@Override
public void writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
compound.setInteger("crateId", id);
// TODO: This might not be the best place to save the crate data.
getPileData().save();
}
}
| |
package com.example.android.bluetoothlegatt;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
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.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v13.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends BaseActivity {
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private TextView mConnectionState;
private TextView mDataField;
private String mDeviceName;
private String mDeviceAddress;
private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private boolean mConnected = false;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private String deviceAddress = "E9:E6:45:4E:40:78";
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
private TextView txtSpeed;
private TextView txtWeight;
private TextView txtDistance;
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
//updateConnectionState(R.string.connected);
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
//updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
//clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// Show all the supported services and characteristics on the user interface.
//displayGattServices(mBluetoothLeService.getSupportedGattServices());
/*for (ArrayList<BluetoothGattCharacteristic> ch : mGattCharacteristics) {
for (BluetoothGattCharacteristic characteristic : ch) {
mBluetoothLeService.setCharacteristicNotification(characteristic, true);
mBluetoothLeService.setCharacteristicNotification(characteristic, true);
}
}*/
for (BluetoothGattService service : mBluetoothLeService.getSupportedGattServices()) {
for (BluetoothGattCharacteristic ch : service.getCharacteristics()) {
mBluetoothLeService.setCharacteristicNotification(ch, true);
mBluetoothLeService.setCharacteristicNotification(ch, true);
}
}
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)
|| BluetoothLeService.ACTION_DATA_AVAILABLE_DISTANCE.equals(action)
|| BluetoothLeService.ACTION_DATA_AVAILABLE_OBSTACLE.equals(action)
|| BluetoothLeService.ACTION_DATA_AVAILABLE_WEIGHT.equals(action)) {
Log.d("LOG", "Es ist was da... VIELEICHT");
//displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE_BATTERY.equals(action)) {
txtDistance.setText(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE_SPEED.equals(action)) {
txtSpeed.setText(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
Log.d("LOG", "service");
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e("LOG", "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(deviceAddress);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout contentFrameLayout = (FrameLayout) findViewById(R.id.container);
getLayoutInflater().inflate(R.layout.activity_main, contentFrameLayout);
//setContentView(R.layout.activity_main);
//txtSpeed = (TextView) findViewById(R.id.speed);
//txtDistance = (TextView) findViewById(R.id.distance);
//txtWeight = (TextView) findViewById(R.id.weight);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck != PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
Toast.makeText(this, "The permission to get BLE location data is required", Toast.LENGTH_SHORT).show();
}else{
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}else{
Toast.makeText(this, "Location permissions already granted", Toast.LENGTH_SHORT).show();
}
setTitle("Schaeffler 5.0");
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
Log.d("LOG", "Bindservice...");
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
Log.d("LOG", "Ende");
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
Log.d("LOG", "onResume");
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(deviceAddress);
Log.d("LOG", "Connect request result=" + result);
}
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE_WEIGHT);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE_SPEED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE_OBSTACLE);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE_BATTERY);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE_DISTANCE);
return intentFilter;
}
}
| |
/**
* Copyright 2007 - 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* For more information visit
* http://wiki.architecturerules.org/ and
* http://blog.architecturerules.org/
*/
package org.architecturerules.domain;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.architecturerules.exceptions.IllegalArchitectureRuleException;
/**
* <p><code>Rule</code> Tester.</p>
*
* @author mikenereson
*/
public class RuleTest extends TestCase {
/**
* <p>Instance of a <code>Rule</code> to test against.</p>
*
* @parameter rule Rule
*/
private Rule rule;
/**
* <p>Contracts a new test with the given <tt>name</tt></p>
*
* @param name String name of the test
*/
public RuleTest(final String name) {
super(name);
}
/**
* @see TestCase#setUp()
*/
@Override
public void setUp()
throws Exception {
super.setUp();
rule = new Rule();
}
/**
* @see TestCase#tearDown()
*/
@Override
public void tearDown()
throws Exception {
rule = null;
super.tearDown();
}
/**
* <p>Tests for {@link Rule#getViolations()}, {@link Rule#addViolation(String)} and {@link
* Rule#removeViolation(String)}</p>
*
* @throws Exception when <code>Rule</code> throws an unexpected <code>Exception</code>
*/
public void testAddGetViolations()
throws Exception {
final JPackage violation1 = new JPackage("com.seventytwomiles.dao");
final JPackage violation2 = new JPackage("com.seventytwomiles.dao.hibernate");
final JPackage violation3 = new JPackage("com.seventytwomiles.package.does.not.exist");
assertEquals(0, rule.getViolations().size());
assertNotNull(rule.addViolation(violation1));
assertTrue(rule.getViolations().contains(violation1));
assertEquals(1, rule.getViolations().size());
assertNotNull(rule.addViolation(violation2));
assertTrue(rule.getViolations().contains(violation2));
assertEquals(2, rule.getViolations().size());
assertNotNull(rule.addViolation(violation1));
assertTrue(rule.getViolations().contains(violation1));
assertEquals(2, rule.getViolations().size());
assertNotNull(rule.removeViolation(violation1));
assertFalse(rule.getViolations().contains(violation1));
assertEquals(1, rule.getViolations().size());
assertNotNull(rule.removeViolation(violation3));
assertFalse(rule.getViolations().contains(violation3));
assertEquals(1, rule.getViolations().size());
}
/**
* <p>Tests for {@link Rule#getViolations()}, {@link Rule#addViolation(String)} and {@link
* Rule#removeViolation(String)}</p>
*
* @throws Exception when <code>Rule</code> throws an unexpected <code>Exception</code>
*/
public void testAddGetViolations_illegalArguments()
throws Exception {
try {
rule.addViolation("");
fail("expected AssertionFailedError because violation can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("violation") > -1);
}
try {
rule.addViolation(new JPackage(""));
fail("expected AssertionFailedError because violation can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("violation") > -1);
}
try {
rule.addViolation((JPackage) null);
fail("expected AssertionFailedError because violation can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("violation") > -1);
}
try {
rule.addViolation((String) null);
fail("expected AssertionFailedError because violation can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("violation") > -1);
}
try {
rule.getViolations().remove("com.seventytwomiles.dao");
fail("expected UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
// success
}
try {
rule.getViolations().remove(new JPackage("com.seventytwomiles.dao"));
fail("expected UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
// success
}
rule = new Rule("dao");
assertTrue(rule.addPackage("com.seventytwomiles.dao"));
try {
rule.addViolation("com.seventytwomiles.dao");
fail("expected IllegalArchitectureRuleException because packageName can not also be a violation");
} catch (final IllegalArchitectureRuleException e) {
final String message = e.getMessage();
assertTrue(message.indexOf("com.seventytwomiles.dao") > -1);
}
try {
rule.removeViolation("");
fail("expected AssertionFailedError because violation can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("violation") > -1);
}
try {
rule.removeViolation((JPackage) null);
fail("expected AssertionFailedError because violation can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("violation") > -1);
}
try {
rule.removeViolation((String) null);
fail("expected AssertionFailedError because violation can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("violation") > -1);
}
}
public void testAddPackage()
throws Exception {
//TOO: write this method
}
public void testAddPackage_illegalArguments()
throws Exception {
//TOO: write this method
}
public void testDescribe()
throws Exception {
rule = new Rule("web", "com.seventytwomiles.web");
rule.addViolation("com.seventytwomiles.dao");
final String description = rule.describe();
assertTrue(description.indexOf("web") > -1);
assertTrue(description.indexOf("com.seventytwomiles.web") > -1);
}
/**
* <p>Tests for {@link Rule#equals(Object)} </p>
*
* @throws Exception when <code>Rule</code> throws an unexpected <code>Exception</code>
*/
public void testEquals()
throws Exception {
Rule that = new Rule("web");
assertTrue(that.addPackage("com.seventytwomiles.web"));
rule.setId("web");
assertTrue(rule.addPackage("com.seventytwomiles.web"));
assertTrue(rule.equals(that));
assertTrue(rule.hashCode() == that.hashCode());
that = new Rule("controllers");
assertTrue(that.addPackage("com.seventytwomiles.web.controllers"));
assertFalse(rule.equals(that));
assertFalse(rule.hashCode() == that.hashCode());
}
/**
* <p>Tests for {@link Rule#Rule(String)}</p>
*
* @throws Exception when <code>Rule</code> throws an unexpected <code>Exception</code>
*/
public void testInterestingConstructors()
throws Exception {
rule = new Rule("dao");
assertTrue(rule.getId().equals("dao"));
}
public void testInterestingConstructors_illegalArguments()
throws Exception {
try {
rule = new Rule(null);
fail("expected AssertionFailedError because id can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("id") > -1);
}
try {
rule = new Rule("");
fail("expected AssertionFailedError because id can not be empty");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("id") > -1);
}
}
/**
* <p>Tests for {@link Rule#setComment(String)} and {@link Rule#getComment()} </p>
*
* @throws Exception when <code>Rule</code> throws an unexpected <code>Exception</code>
*/
public void testSetGetComment()
throws Exception {
rule.setComment("controllers are cool");
assertTrue(rule.getComment().equals("controllers are cool"));
rule.setComment("");
assertTrue(rule.getComment().equals(""));
}
public void testSetGetComment_illegalArguments()
throws Exception {
try {
rule.setComment(null);
fail("expected AssertionFailedError because comment can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("comment") > -1);
}
}
/**
* <p>Tests for {@link Rule#setId(String)} and {@link Rule#getId()}</p>
*
* @throws Exception when <code>Rule</code> throws an unexpected <code>Exception</code>
*/
public void testSetGetId()
throws Exception {
rule.setId("controllers");
assertTrue(rule.getId().equals("controllers"));
}
public void testSetGetId_illegalArguments()
throws Exception {
try {
rule.setId("");
fail("expected AssertionFailedError because id can not be empty");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("id") > -1);
}
try {
rule.setId(null);
fail("expected AssertionFailedError because id can not be null");
} catch (final AssertionFailedError e) {
final String message = e.getMessage();
assertTrue(message.indexOf("id") > -1);
}
}
}
| |
/*
* 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 es.caib.zkib.jxpath;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import junit.framework.TestCase;
import es.caib.zkib.jxpath.JXPathContext;
import es.caib.zkib.jxpath.Pointer;
import es.caib.zkib.jxpath.ri.model.NodePointer;
/**
* Abstract superclass for various JXPath tests.
*
* @author Dmitri Plotnikov
* @version $Revision: 1.1 $ $Date: 2009-04-03 08:13:14 $
*/
public abstract class JXPathTestCase extends TestCase {
/**
* Construct a new instance of this test case.
*/
public JXPathTestCase() {
Locale.setDefault(Locale.US);
}
protected void assertXPathValue(JXPathContext ctx,
String xpath, Object expected)
{
ctx.setLenient(false);
Object actual = ctx.getValue(xpath);
assertEquals("Evaluating <" + xpath + ">", expected, actual);
}
protected void assertXPathValue(JXPathContext ctx,
String xpath, Object expected, Class resultType)
{
ctx.setLenient(false);
Object actual = ctx.getValue(xpath, resultType);
assertEquals("Evaluating <" + xpath + ">", expected, actual);
}
protected void assertXPathValueLenient(JXPathContext ctx,
String xpath, Object expected)
{
ctx.setLenient(true);
Object actual = ctx.getValue(xpath);
ctx.setLenient(false);
assertEquals("Evaluating lenient <" + xpath + ">", expected, actual);
}
protected void assertXPathSetValue(JXPathContext ctx,
String xpath, Object value)
{
assertXPathSetValue(ctx, xpath, value, value);
}
protected void assertXPathSetValue(JXPathContext ctx,
String xpath, Object value, Object expected)
{
ctx.setValue(xpath, value);
Object actual = ctx.getValue(xpath);
assertEquals("Modifying <" + xpath + ">", expected, actual);
}
protected void assertXPathCreatePath(JXPathContext ctx,
String xpath,
Object expectedValue, String expectedPath)
{
Pointer pointer = ctx.createPath(xpath);
assertEquals("Creating path <" + xpath + ">",
expectedPath, pointer.asPath());
assertEquals("Creating path (pointer value) <" + xpath + ">",
expectedValue, pointer.getValue());
assertEquals("Creating path (context value) <" + xpath + ">",
expectedValue, ctx.getValue(pointer.asPath()));
}
protected void assertXPathCreatePathAndSetValue(JXPathContext ctx,
String xpath, Object value,
String expectedPath)
{
Pointer pointer = ctx.createPathAndSetValue(xpath, value);
assertEquals("Creating path <" + xpath + ">",
expectedPath, pointer.asPath());
assertEquals("Creating path (pointer value) <" + xpath + ">",
value, pointer.getValue());
assertEquals("Creating path (context value) <" + xpath + ">",
value, ctx.getValue(pointer.asPath()));
}
protected void assertXPathPointer(JXPathContext ctx,
String xpath, String expected)
{
ctx.setLenient(false);
Pointer pointer = ctx.getPointer(xpath);
String actual = pointer.toString();
assertEquals("Evaluating pointer <" + xpath + ">", expected, actual);
}
protected void assertXPathPointerLenient(JXPathContext ctx,
String xpath, String expected)
{
ctx.setLenient(true);
Pointer pointer = ctx.getPointer(xpath);
String actual = pointer.toString();
assertEquals("Evaluating pointer <" + xpath + ">", expected, actual);
}
protected void assertXPathValueAndPointer(JXPathContext ctx,
String xpath, Object expectedValue, String expectedPointer)
{
assertXPathValue(ctx, xpath, expectedValue);
assertXPathPointer(ctx, xpath, expectedPointer);
}
protected void assertXPathValueIterator(JXPathContext ctx,
String xpath, Collection expected)
{
Collection actual;
if (expected instanceof List) {
actual = new ArrayList();
}
else {
actual = new HashSet();
}
Iterator it = ctx.iterate(xpath);
while (it.hasNext()) {
actual.add(it.next());
}
assertEquals("Evaluating value iterator <" + xpath + ">",
expected, actual);
}
protected void assertXPathPointerIterator(
JXPathContext ctx,
String xpath,
Collection expected)
{
Collection actual;
if (expected instanceof List) {
actual = new ArrayList();
}
else {
actual = new HashSet();
}
Iterator it = ctx.iteratePointers(xpath);
while (it.hasNext()) {
Pointer pointer = (Pointer) it.next();
actual.add(pointer.toString());
}
assertEquals(
"Evaluating pointer iterator <" + xpath + ">",
expected,
actual);
}
protected void assertDocumentOrder(
JXPathContext context,
String path1,
String path2,
int expected)
{
NodePointer np1 = (NodePointer) context.getPointer(path1);
NodePointer np2 = (NodePointer) context.getPointer(path2);
int res = np1.compareTo(np2);
if (res < 0) {
res = -1;
}
else if (res > 0) {
res = 1;
}
assertEquals(
"Comparing paths '" + path1 + "' and '" + path2 + "'",
expected,
res);
}
protected void assertXPathValueType(
JXPathContext ctx,
String xpath,
Class clazz)
{
ctx.setLenient(false);
Object actual = ctx.getValue(xpath);
assertTrue("Evaluating <" + xpath + "> = " + actual.getClass(),
clazz.isAssignableFrom(actual.getClass()));
}
protected void assertXPathNodeType(
JXPathContext ctx,
String xpath,
Class clazz)
{
ctx.setLenient(false);
Pointer actual = ctx.getPointer(xpath);
assertTrue("Evaluating <" + xpath + "> = " + actual.getNode().getClass(),
clazz.isAssignableFrom(actual.getNode().getClass()));
}
protected static List list() {
return Collections.EMPTY_LIST;
}
protected static List list(Object o1) {
List list = new ArrayList();
list.add(o1);
return list;
}
protected static List list(Object o1, Object o2) {
List list = new ArrayList();
list.add(o1);
list.add(o2);
return list;
}
protected static List list(Object o1, Object o2, Object o3) {
List list = new ArrayList();
list.add(o1);
list.add(o2);
list.add(o3);
return list;
}
protected static Set set(Object o1, Object o2) {
Set list = new HashSet();
list.add(o1);
list.add(o2);
return list;
}
protected static Set set(Object o1, Object o2, Object o3) {
Set list = new HashSet();
list.add(o1);
list.add(o2);
list.add(o3);
return list;
}
protected static List list(Object o1, Object o2, Object o3, Object o4) {
List list = new ArrayList();
list.add(o1);
list.add(o2);
list.add(o3);
list.add(o4);
return list;
}
protected static Set set(Object o1, Object o2, Object o3, Object o4) {
Set list = new HashSet();
list.add(o1);
list.add(o2);
list.add(o3);
list.add(o4);
return list;
}
protected static List list(Object o1, Object o2, Object o3,
Object o4, Object o5)
{
List list = new ArrayList();
list.add(o1);
list.add(o2);
list.add(o3);
list.add(o4);
list.add(o5);
return list;
}
protected static Set set(Object o1, Object o2, Object o3,
Object o4, Object o5)
{
Set list = new HashSet();
list.add(o1);
list.add(o2);
list.add(o3);
list.add(o4);
list.add(o5);
return list;
}
protected static List list(Object o1, Object o2, Object o3,
Object o4, Object o5, Object o6)
{
List list = new ArrayList();
list.add(o1);
list.add(o2);
list.add(o3);
list.add(o4);
list.add(o5);
list.add(o6);
return list;
}
protected static Set set(Object o1, Object o2, Object o3,
Object o4, Object o5, Object o6)
{
Set list = new HashSet();
list.add(o1);
list.add(o2);
list.add(o3);
list.add(o4);
list.add(o5);
list.add(o6);
return list;
}
protected static List list(Object o1, Object o2, Object o3,
Object o4, Object o5, Object o6, Object o7)
{
List list = new ArrayList();
list.add(o1);
list.add(o2);
list.add(o3);
list.add(o4);
list.add(o5);
list.add(o6);
list.add(o7);
return list;
}
protected static Set set(Object o1, Object o2, Object o3,
Object o4, Object o5, Object o6, Object o7)
{
Set list = new HashSet();
list.add(o1);
list.add(o2);
list.add(o3);
list.add(o4);
list.add(o5);
list.add(o6);
list.add(o7);
return list;
}
}
| |
package com.example.dialer;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/*
*
* @author: Vikram Udyawer (04316827)
* @date: 23rd August 2017
* @summary: A Single Activity Dialer Application
*
* */
public class MainActivity extends AppCompatActivity {
// Request Code variable for CALL_PHONE permissions (Choice of a random integer as long as it is >=0)
private static final int CALL_PERMISSION_CODE = 1;
// Declarations for EditText, Buttons and String of edit text to manipulate
EditText numView;
Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, delBtn, starBtn, hashBtn, callBtn;
private String phNum;
// Key to save the String during state changes
private static final String DISPLAYED_PHONE_NUMBER = "displayedPhoneNumber";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Generic private method to request Dangerous Permissions (in this case, "CALL_PHONE")
getUserPermission(Manifest.permission.CALL_PHONE, CALL_PERMISSION_CODE);
// Type casting layout elements to variables in Main Activity
numView = (EditText) findViewById(R.id.num_view);
b0 = (Button) findViewById(R.id.nullBtn);
b1 = (Button) findViewById(R.id.eins);
b2 = (Button) findViewById(R.id.zwei);
b3 = (Button) findViewById(R.id.drei);
b4 = (Button) findViewById(R.id.vier);
b5 = (Button) findViewById(R.id.funf);
b6 = (Button) findViewById(R.id.sechs);
b7 = (Button) findViewById(R.id.sieben);
b8 = (Button) findViewById(R.id.acht);
b9 = (Button) findViewById(R.id.neun);
delBtn = (Button) findViewById(R.id.delBtn);
starBtn = (Button) findViewById(R.id.starBtn);
hashBtn = (Button) findViewById(R.id.hashBtn);
callBtn = (Button)findViewById(R.id.anruf);
// Get text from Edit Text --> Convert to string and place in 'phNum' String variable
phNum = numView.getText().toString();
/*
Below are 14 Click Listeners for all Dial Keys from keys 0 through to 9;
'*'; '#'; backspace & Call buttons
*/
b0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "0";
numView.setText(phNum);
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "1";
numView.setText(phNum);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "2";
numView.setText(phNum);
}
});
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "3";
numView.setText(phNum);
}
});
b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "4";
numView.setText(phNum);
}
});
b5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "5";
numView.setText(phNum);
}
});
b6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "6";
numView.setText(phNum);
}
});
b7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "7";
numView.setText(phNum);
}
});
b8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "8";
numView.setText(phNum);
}
});
b9.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "9";
numView.setText(phNum);
}
});
starBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "*";
numView.setText(phNum);
}
});
hashBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
phNum = phNum + "#";
numView.setText(phNum);
}
});
// Click Listener for the Delete Button
delBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String builtStr;
// Check length of EditText box is greater than zero
if(numView.getText().length()>0){
// If length larger than zero create new String Builder initialised with character sequence
StringBuilder stringBuilder = new StringBuilder(numView.getText());
// Get length odf character sequence and delete the last character in the index
// Remove char at given index position
stringBuilder.deleteCharAt(numView.getText().length() - 1);
// convert the character sequence to a string
builtStr = stringBuilder.toString();
// append string to phNum string
phNum = "" + builtStr;
// set phNum string to EditText variable to display
numView.setText(phNum);
}
}
});
// Click Listener for the Call Button
callBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
placeCall();
}
});
//// Restoring savedInstanceState on any Hardware Configuration Change (such as device rotation)
if (savedInstanceState != null){
phNum = (String)savedInstanceState.get(DISPLAYED_PHONE_NUMBER);
Log.d("TAG", "Restored instance state: phNum => " + phNum);
}
} /// End of onCreate()
// Saving Activity state on any Hardware Configuration Change (such as device rotation)
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(DISPLAYED_PHONE_NUMBER, phNum);
}
/*
Method to call the Intent for ACTION_CALL; setting URI
and starting the activity
*/
public void placeCall(){
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phNum));
startActivity(intent);
}
// Generic private method to request Dangerous Permissions (in this case, "CALL_PHONE")
private void getUserPermission(String requestedPerm, Integer requestedCode){
// Checking if the Build version is API greater than 22
if ((Build.VERSION.SDK_INT > 22)){
// Checking to see with the Permission(s) is Granted or Not
// If Permission(s) is NOT GRANTED
if (ContextCompat.checkSelfPermission(MainActivity.this, requestedPerm) != PackageManager.PERMISSION_GRANTED){
Log.v("TAG","Permission is granted");
// Check to see the user has denied permission(s) previously
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, requestedPerm)){
// Ask permission again in the case the user has denied permissions previously (as it is an important Permission)
ActivityCompat.requestPermissions(MainActivity.this, new String[]{requestedPerm}, requestedCode);
}
// If Permission was Not Denied previously, a request is made
else {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {requestedPerm}, requestedCode);
}
}
// If Permission(s) GRANTED we add a message to say the Permission was granted
else {
Toast.makeText(this, "" + requestedPerm + " is already granted", Toast.LENGTH_SHORT).show();
}
} else {
// If build is lower than 23 then Permission requested and granted during app install
Log.v("TAG","Permission is granted");
}
}
// Method to handle a requested permission
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// Switch case statement is used to handle multiple request permission codes (if needed)
switch (requestCode){
// Permission code for CALL_PHONE
case CALL_PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
finish();
}
}
}
}
}
| |
/**
* Copyright (c) 2008-2010, Gaudenz Alder, David Benson
*/
package com.mxgraph.swing.handler;
import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import com.mxgraph.canvas.mxGraphics2DCanvas;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.model.mxICell;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxEvent;
import com.mxgraph.util.mxEventObject;
import com.mxgraph.util.mxEventSource;
import com.mxgraph.util.mxPoint;
import com.mxgraph.util.mxRectangle;
import com.mxgraph.util.mxUtils;
import com.mxgraph.view.mxCellState;
import com.mxgraph.view.mxGraph;
/**
* Connection handler creates new connections between cells. This control is used to display the connector
* icon, while the preview is used to draw the line.
*/
public class mxConnectPreview extends mxEventSource
{
/**
*
*/
protected mxGraphComponent graphComponent;
/**
*
*/
protected mxCellState previewState;
/**
*
*/
protected mxCellState sourceState;
/**
*
*/
protected mxPoint startPoint;
/**
*
* @param graphComponent
*/
public mxConnectPreview(mxGraphComponent graphComponent)
{
this.graphComponent = graphComponent;
// Installs the paint handler
graphComponent.addListener(mxEvent.AFTER_PAINT, new mxIEventListener()
{
public void invoke(Object sender, mxEventObject evt)
{
Graphics g = (Graphics) evt.getProperty("g");
paint(g);
}
});
}
/**
* Creates a new instance of mxShape for previewing the edge.
*/
protected Object createCell(mxCellState startState, String style)
{
mxGraph graph = graphComponent.getGraph();
mxICell cell = ((mxICell) graph
.createEdge(null, null, "",
(startState != null) ? startState.getCell() : null,
null, style,null));
((mxICell) startState.getCell()).insertEdge(cell, true);
return cell;
}
/**
*
*/
public boolean isActive()
{
return sourceState != null;
}
/**
*
*/
public mxCellState getSourceState()
{
return sourceState;
}
/**
*
*/
public mxCellState getPreviewState()
{
return previewState;
}
/**
*
*/
public mxPoint getStartPoint()
{
return startPoint;
}
/**
* Updates the style of the edge preview from the incoming edge
*/
public void start(MouseEvent e, mxCellState startState, String style)
{
mxGraph graph = graphComponent.getGraph();
sourceState = startState;
startPoint = transformScreenPoint(startState.getCenterX(),
startState.getCenterY());
Object cell = createCell(startState, style);
graph.getView().validateCell(cell);
previewState = graph.getView().getState(cell);
fireEvent(new mxEventObject(mxEvent.START, "event", e, "state",
previewState));
}
/**
*
*/
public void update(MouseEvent e, mxCellState targetState, double x, double y)
{
mxGraph graph = graphComponent.getGraph();
mxICell cell = (mxICell) previewState.getCell();
mxRectangle dirty = graphComponent.getGraph().getPaintBounds(
new Object[] { previewState.getCell() });
if (cell.getTerminal(false) != null)
{
cell.getTerminal(false).removeEdge(cell, false);
}
if (targetState != null)
{
((mxICell) targetState.getCell()).insertEdge(cell, false);
}
mxGeometry geo = graph.getCellGeometry(previewState.getCell());
geo.setTerminalPoint(startPoint, true);
geo.setTerminalPoint(transformScreenPoint(x, y), false);
revalidate(previewState);
fireEvent(new mxEventObject(mxEvent.CONTINUE, "event", e, "x", x, "y",
y));
// Repaints the dirty region
// TODO: Cache the new dirty region for next repaint
Rectangle tmp = getDirtyRect(dirty);
if (tmp != null)
{
graphComponent.getGraphControl().repaint(tmp);
}
else
{
graphComponent.getGraphControl().repaint();
}
}
/**
*
*/
protected Rectangle getDirtyRect()
{
return getDirtyRect(null);
}
/**
*
*/
protected Rectangle getDirtyRect(mxRectangle dirty)
{
if (previewState != null)
{
mxRectangle tmp = graphComponent.getGraph().getPaintBounds(
new Object[] { previewState.getCell() });
if (dirty != null)
{
dirty.add(tmp);
}
else
{
dirty = tmp;
}
if (dirty != null)
{
// TODO: Take arrow size into account
dirty.grow(2);
return dirty.getRectangle();
}
}
return null;
}
/**
*
*/
protected mxPoint transformScreenPoint(double x, double y)
{
mxGraph graph = graphComponent.getGraph();
mxPoint tr = graph.getView().getTranslate();
double scale = graph.getView().getScale();
return new mxPoint(graph.snap(x / scale - tr.getX()), graph.snap(y
/ scale - tr.getY()));
}
/**
*
*/
public void revalidate(mxCellState state)
{
state.getView().invalidate(state.getCell());
state.getView().validateCellState(state.getCell());
}
/**
*
*/
public void paint(Graphics g)
{
if (previewState != null)
{
mxGraphics2DCanvas canvas = graphComponent.getCanvas();
if (graphComponent.isAntiAlias())
{
mxUtils.setAntiAlias((Graphics2D) g, true, false);
}
float alpha = graphComponent.getPreviewAlpha();
if (alpha < 1)
{
((Graphics2D) g).setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, alpha));
}
Graphics2D previousGraphics = canvas.getGraphics();
Point previousTranslate = canvas.getTranslate();
double previousScale = canvas.getScale();
try
{
canvas.setScale(graphComponent.getGraph().getView().getScale());
canvas.setTranslate(0, 0);
canvas.setGraphics((Graphics2D) g);
paintPreview(canvas);
}
finally
{
canvas.setScale(previousScale);
canvas.setTranslate(previousTranslate.x, previousTranslate.y);
canvas.setGraphics(previousGraphics);
}
}
}
/**
* Draws the preview using the graphics canvas.
*/
protected void paintPreview(mxGraphics2DCanvas canvas)
{
graphComponent.getGraphControl().drawCell(graphComponent.getCanvas(),
previewState.getCell());
}
/**
*
*/
public Object stop(boolean commit)
{
return stop(commit, null);
}
/**
*
*/
public Object stop(boolean commit, MouseEvent e)
{
Object result = (sourceState != null) ? sourceState.getCell() : null;
if (previewState != null)
{
mxGraph graph = graphComponent.getGraph();
graph.getModel().beginUpdate();
try
{
mxICell cell = (mxICell) previewState.getCell();
Object src = cell.getTerminal(true);
Object trg = cell.getTerminal(false);
if (src != null)
{
((mxICell) src).removeEdge(cell, true);
}
if (trg != null)
{
((mxICell) trg).removeEdge(cell, false);
}
if (commit)
{
result = graph.addCell(cell, null, null, src, trg);
}
fireEvent(new mxEventObject(mxEvent.STOP, "event", e, "commit",
commit, "cell", (commit) ? result : null));
// Clears the state before the model commits
if (previewState != null)
{
Rectangle dirty = getDirtyRect();
graph.getView().clear(cell, false, true);
previewState = null;
if (!commit && dirty != null)
{
graphComponent.getGraphControl().repaint(dirty);
}
}
}
finally
{
graph.getModel().endUpdate();
}
}
sourceState = null;
startPoint = null;
return result;
}
}
| |
/**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.hystrix;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Test;
import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.hystrix.HystrixCommandProperties.Setter;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
public class HystrixCommandPropertiesTest {
/**
* Utility method for creating baseline properties for unit tests.
*/
/* package */static HystrixCommandProperties.Setter getUnitTestPropertiesSetter() {
return new HystrixCommandProperties.Setter()
.withExecutionTimeoutInMilliseconds(1000)// when an execution will be timed out
.withExecutionTimeoutEnabled(true)
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD) // we want thread execution by default in tests
.withExecutionIsolationThreadInterruptOnTimeout(true)
.withCircuitBreakerForceOpen(false) // we don't want short-circuiting by default
.withCircuitBreakerErrorThresholdPercentage(40) // % of 'marks' that must be failed to trip the circuit
.withMetricsRollingStatisticalWindowInMilliseconds(5000)// milliseconds back that will be tracked
.withMetricsRollingStatisticalWindowBuckets(5) // buckets
.withCircuitBreakerRequestVolumeThreshold(0) // in testing we will not have a threshold unless we're specifically testing that feature
.withCircuitBreakerSleepWindowInMilliseconds(5000000) // milliseconds after tripping circuit before allowing retry (by default set VERY long as we want it to effectively never allow a singleTest for most unit tests)
.withCircuitBreakerEnabled(true)
.withRequestLogEnabled(true)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(20)
.withFallbackIsolationSemaphoreMaxConcurrentRequests(10)
.withFallbackEnabled(true)
.withCircuitBreakerForceClosed(false)
.withMetricsRollingPercentileEnabled(true)
.withRequestCacheEnabled(true)
.withMetricsRollingPercentileWindowInMilliseconds(60000)
.withMetricsRollingPercentileWindowBuckets(12)
.withMetricsRollingPercentileBucketSize(1000)
.withMetricsHealthSnapshotIntervalInMilliseconds(100);
}
/**
* Return a static representation of the properties with values from the Builder so that UnitTests can create properties that are not affected by the actual implementations which pick up their
* values dynamically.
*
* @param builder command properties builder
* @return HystrixCommandProperties
*/
/* package */static HystrixCommandProperties asMock(final Setter builder) {
return new HystrixCommandProperties(TestKey.TEST) {
@Override
public HystrixProperty<Boolean> circuitBreakerEnabled() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerEnabled());
}
@Override
public HystrixProperty<Integer> circuitBreakerErrorThresholdPercentage() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerErrorThresholdPercentage());
}
@Override
public HystrixProperty<Boolean> circuitBreakerForceClosed() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerForceClosed());
}
@Override
public HystrixProperty<Boolean> circuitBreakerForceOpen() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerForceOpen());
}
@Override
public HystrixProperty<Integer> circuitBreakerRequestVolumeThreshold() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerRequestVolumeThreshold());
}
@Override
public HystrixProperty<Integer> circuitBreakerSleepWindowInMilliseconds() {
return HystrixProperty.Factory.asProperty(builder.getCircuitBreakerSleepWindowInMilliseconds());
}
@Override
public HystrixProperty<Integer> executionIsolationSemaphoreMaxConcurrentRequests() {
return HystrixProperty.Factory.asProperty(builder.getExecutionIsolationSemaphoreMaxConcurrentRequests());
}
@Override
public HystrixProperty<ExecutionIsolationStrategy> executionIsolationStrategy() {
return HystrixProperty.Factory.asProperty(builder.getExecutionIsolationStrategy());
}
@Override
public HystrixProperty<Boolean> executionIsolationThreadInterruptOnTimeout() {
return HystrixProperty.Factory.asProperty(builder.getExecutionIsolationThreadInterruptOnTimeout());
}
@Override
public HystrixProperty<String> executionIsolationThreadPoolKeyOverride() {
return HystrixProperty.Factory.nullProperty();
}
@Override
public HystrixProperty<Integer> executionTimeoutInMilliseconds() {
return HystrixProperty.Factory.asProperty(builder.getExecutionTimeoutInMilliseconds());
}
@Override
public HystrixProperty<Boolean> executionTimeoutEnabled() {
return HystrixProperty.Factory.asProperty(builder.getExecutionTimeoutEnabled());
}
@Override
public HystrixProperty<Integer> fallbackIsolationSemaphoreMaxConcurrentRequests() {
return HystrixProperty.Factory.asProperty(builder.getFallbackIsolationSemaphoreMaxConcurrentRequests());
}
@Override
public HystrixProperty<Boolean> fallbackEnabled() {
return HystrixProperty.Factory.asProperty(builder.getFallbackEnabled());
}
@Override
public HystrixProperty<Integer> metricsHealthSnapshotIntervalInMilliseconds() {
return HystrixProperty.Factory.asProperty(builder.getMetricsHealthSnapshotIntervalInMilliseconds());
}
@Override
public HystrixProperty<Integer> metricsRollingPercentileBucketSize() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingPercentileBucketSize());
}
@Override
public HystrixProperty<Boolean> metricsRollingPercentileEnabled() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingPercentileEnabled());
}
@Override
public HystrixProperty<Integer> metricsRollingPercentileWindow() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingPercentileWindowInMilliseconds());
}
@Override
public HystrixProperty<Integer> metricsRollingPercentileWindowBuckets() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingPercentileWindowBuckets());
}
@Override
public HystrixProperty<Integer> metricsRollingStatisticalWindowInMilliseconds() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingStatisticalWindowInMilliseconds());
}
@Override
public HystrixProperty<Integer> metricsRollingStatisticalWindowBuckets() {
return HystrixProperty.Factory.asProperty(builder.getMetricsRollingStatisticalWindowBuckets());
}
@Override
public HystrixProperty<Boolean> requestCacheEnabled() {
return HystrixProperty.Factory.asProperty(builder.getRequestCacheEnabled());
}
@Override
public HystrixProperty<Boolean> requestLogEnabled() {
return HystrixProperty.Factory.asProperty(builder.getRequestLogEnabled());
}
};
}
// NOTE: We use "unitTestPrefix" as a prefix so we can't end up pulling in external properties that change unit test behavior
public enum TestKey implements HystrixCommandKey {
TEST
}
private static class TestPropertiesCommand extends HystrixCommandProperties {
protected TestPropertiesCommand(HystrixCommandKey key, Setter builder, String propertyPrefix) {
super(key, builder, propertyPrefix);
}
}
@After
public void cleanup() {
ConfigurationManager.getConfigInstance().clear();
}
@Test
public void testBooleanBuilderOverride1() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(true), "unitTestPrefix");
// the builder override should take precedence over the default
assertEquals(true, properties.circuitBreakerForceClosed().get());
}
@Test
public void testBooleanBuilderOverride2() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(false), "unitTestPrefix");
// the builder override should take precedence over the default
assertEquals(false, properties.circuitBreakerForceClosed().get());
}
@Test
public void testBooleanCodeDefault() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
assertEquals(HystrixCommandProperties.default_circuitBreakerForceClosed, properties.circuitBreakerForceClosed().get());
}
@Test
public void testBooleanGlobalDynamicOverrideOfCodeDefault() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed", true);
// the global dynamic property should take precedence over the default
assertEquals(true, properties.circuitBreakerForceClosed().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed");
}
@Test
public void testBooleanInstanceBuilderOverrideOfGlobalDynamicOverride1() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(true), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed", false);
// the builder injected should take precedence over the global dynamic property
assertEquals(true, properties.circuitBreakerForceClosed().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed");
}
@Test
public void testBooleanInstanceBuilderOverrideOfGlobalDynamicOverride2() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(false), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed", true);
// the builder injected should take precedence over the global dynamic property
assertEquals(false, properties.circuitBreakerForceClosed().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed");
}
@Test
public void testBooleanInstanceDynamicOverrideOfEverything() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withCircuitBreakerForceClosed(false), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed", false);
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.TEST.circuitBreaker.forceClosed", true);
// the instance specific dynamic property should take precedence over everything
assertEquals(true, properties.circuitBreakerForceClosed().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.circuitBreaker.forceClosed");
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.TEST.circuitBreaker.forceClosed");
}
@Test
public void testIntegerBuilderOverride() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withMetricsRollingStatisticalWindowInMilliseconds(5000), "unitTestPrefix");
// the builder override should take precedence over the default
assertEquals(5000, properties.metricsRollingStatisticalWindowInMilliseconds().get().intValue());
}
@Test
public void testIntegerCodeDefault() {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
assertEquals(HystrixCommandProperties.default_metricsRollingStatisticalWindow, properties.metricsRollingStatisticalWindowInMilliseconds().get());
}
@Test
public void testIntegerGlobalDynamicOverrideOfCodeDefault() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.metrics.rollingStats.timeInMilliseconds", 1234);
// the global dynamic property should take precedence over the default
assertEquals(1234, properties.metricsRollingStatisticalWindowInMilliseconds().get().intValue());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.metrics.rollingStats.timeInMilliseconds");
}
@Test
public void testIntegerInstanceBuilderOverrideOfGlobalDynamicOverride() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withMetricsRollingStatisticalWindowInMilliseconds(5000), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.rollingStats.timeInMilliseconds", 3456);
// the builder injected should take precedence over the global dynamic property
assertEquals(5000, properties.metricsRollingStatisticalWindowInMilliseconds().get().intValue());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.rollingStats.timeInMilliseconds");
}
@Test
public void testIntegerInstanceDynamicOverrideOfEverything() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST,
new HystrixCommandProperties.Setter().withMetricsRollingStatisticalWindowInMilliseconds(5000), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.metrics.rollingStats.timeInMilliseconds", 1234);
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.TEST.metrics.rollingStats.timeInMilliseconds", 3456);
// the instance specific dynamic property should take precedence over everything
assertEquals(3456, properties.metricsRollingStatisticalWindowInMilliseconds().get().intValue());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.metrics.rollingStats.timeInMilliseconds");
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.TEST.metrics.rollingStats.timeInMilliseconds");
}
@Test
public void testThreadPoolOnlyHasInstanceOverride() throws Exception {
HystrixCommandProperties properties = new TestPropertiesCommand(TestKey.TEST, new HystrixCommandProperties.Setter(), "unitTestPrefix");
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.default.threadPoolKeyOverride", 1234);
// it should be null
assertEquals(null, properties.executionIsolationThreadPoolKeyOverride().get());
ConfigurationManager.getConfigInstance().setProperty("unitTestPrefix.command.TEST.threadPoolKeyOverride", "testPool");
// now it should have a value
assertEquals("testPool", properties.executionIsolationThreadPoolKeyOverride().get());
// cleanup
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.default.threadPoolKeyOverride");
ConfigurationManager.getConfigInstance().clearProperty("unitTestPrefix.command.TEST.threadPoolKeyOverride");
}
}
| |
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.launcher.daemon.server;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.internal.concurrent.CompositeStoppable;
import org.gradle.internal.concurrent.ExecutorFactory;
import org.gradle.internal.concurrent.Stoppable;
import org.gradle.internal.event.ListenerManager;
import org.gradle.internal.remote.Address;
import org.gradle.launcher.daemon.context.DaemonContext;
import org.gradle.launcher.daemon.logging.DaemonMessages;
import org.gradle.launcher.daemon.registry.DaemonRegistry;
import org.gradle.launcher.daemon.server.api.DaemonStateControl;
import org.gradle.launcher.daemon.server.exec.DaemonCommandExecuter;
import org.gradle.launcher.daemon.server.expiry.DaemonExpirationListener;
import org.gradle.launcher.daemon.server.expiry.DaemonExpirationResult;
import org.gradle.launcher.daemon.server.expiry.DaemonExpirationStatus;
import org.gradle.launcher.daemon.server.expiry.DaemonExpirationStrategy;
import org.gradle.process.internal.shutdown.ShutdownHooks;
import java.security.SecureRandom;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static org.gradle.launcher.daemon.server.expiry.DaemonExpirationStatus.*;
/**
* A long-lived build server that accepts commands via a communication channel.
* <p>
* Daemon instances are single use and have a start/stop debug. They are also threadsafe.
* <p>
* See {@link org.gradle.launcher.daemon.client.DaemonClient} for a description of the daemon communication protocol.
*/
public class Daemon implements Stoppable {
private static final Logger LOGGER = Logging.getLogger(Daemon.class);
private final DaemonServerConnector connector;
private final DaemonRegistry daemonRegistry;
private final DaemonContext daemonContext;
private final DaemonCommandExecuter commandExecuter;
private final ScheduledExecutorService scheduledExecutorService;
private final ExecutorFactory executorFactory;
private final ListenerManager listenerManager;
private DaemonStateCoordinator stateCoordinator;
private final Lock lifecycleLock = new ReentrantLock();
private Address connectorAddress;
private DaemonRegistryUpdater registryUpdater;
private DefaultIncomingConnectionHandler connectionHandler;
/**
* Creates a new daemon instance.
*
* @param connector The provider of server connections for this daemon
* @param daemonRegistry The registry that this daemon should advertise itself in
*/
public Daemon(DaemonServerConnector connector, DaemonRegistry daemonRegistry, DaemonContext daemonContext, DaemonCommandExecuter commandExecuter, ExecutorFactory executorFactory, ListenerManager listenerManager) {
this.connector = connector;
this.daemonRegistry = daemonRegistry;
this.daemonContext = daemonContext;
this.commandExecuter = commandExecuter;
this.executorFactory = executorFactory;
this.scheduledExecutorService = executorFactory.createScheduled("Daemon periodic checks", 1);
this.listenerManager = listenerManager;
}
public String getUid() {
return daemonContext.getUid();
}
public Address getAddress() {
return connectorAddress;
}
public DaemonContext getDaemonContext() {
return daemonContext;
}
public DaemonRegistry getDaemonRegistry() {
return this.daemonRegistry;
}
/**
* Starts the daemon, receiving connections asynchronously (i.e. returns immediately).
*
* @throws IllegalStateException if this daemon is already running, or has already been stopped.
*/
public void start() {
LOGGER.info("start() called on daemon - {}", daemonContext);
lifecycleLock.lock();
try {
if (stateCoordinator != null) {
throw new IllegalStateException("cannot start daemon as it is already running");
}
// Generate an authentication token, which must be provided by the client in any requests it makes
SecureRandom secureRandom = new SecureRandom();
byte[] token = new byte[16];
secureRandom.nextBytes(token);
registryUpdater = new DaemonRegistryUpdater(daemonRegistry, daemonContext, token);
ShutdownHooks.addShutdownHook(new Runnable() {
@Override
public void run() {
try {
daemonRegistry.remove(connectorAddress);
} catch (Exception e) {
LOGGER.debug("VM shutdown hook was unable to remove the daemon address from the registry. It will be cleaned up later.", e);
}
}
});
Runnable onStartCommand = new Runnable() {
@Override
public void run() {
registryUpdater.onStartActivity();
}
};
Runnable onFinishCommand = new Runnable() {
@Override
public void run() {
registryUpdater.onCompleteActivity();
}
};
Runnable onCancelCommand = new Runnable() {
@Override
public void run() {
registryUpdater.onCancel();
}
};
// Start the pipeline in reverse order:
// 1. mark daemon as running
// 2. start handling incoming commands
// 3. start accepting incoming connections
// 4. advertise presence in registry
stateCoordinator = new DaemonStateCoordinator(executorFactory, onStartCommand, onFinishCommand, onCancelCommand);
connectionHandler = new DefaultIncomingConnectionHandler(commandExecuter, daemonContext, stateCoordinator, executorFactory, token);
Runnable connectionErrorHandler = new Runnable() {
@Override
public void run() {
stateCoordinator.stop();
}
};
connectorAddress = connector.start(connectionHandler, connectionErrorHandler);
LOGGER.debug("Daemon starting at: {}, with address: {}", new Date(), connectorAddress);
registryUpdater.onStart(connectorAddress);
} finally {
lifecycleLock.unlock();
}
LOGGER.lifecycle(DaemonMessages.PROCESS_STARTED);
}
/**
* Stops the daemon, blocking until any current requests/connections have been satisfied.
* <p>
* This is the semantically the same as sending the daemon the Stop command.
* <p>
* This method does not quite conform to the semantics of the Stoppable contract in that it will NOT
* wait for any executing builds to stop before returning. This is by design as we currently have no way of
* gracefully stopping a build process and blocking until it's done would not allow us to tear down the jvm
* like we need to. This may change in the future if we create a way to interrupt a build.
* <p>
* What will happen though is that the daemon will immediately disconnect from any clients and remove itself
* from the registry.
*/
@Override
public void stop() {
LOGGER.debug("stop() called on daemon");
lifecycleLock.lock();
try {
if (stateCoordinator == null) {
throw new IllegalStateException("cannot stop daemon as it has not been started.");
}
LOGGER.info(DaemonMessages.REMOVING_PRESENCE_DUE_TO_STOP);
// Stop periodic checks
scheduledExecutorService.shutdown();
// Stop the pipeline:
// 1. mark daemon as stopped, so that any incoming requests will be rejected with 'daemon unavailable'
// 2. remove presence from registry
// 3. stop accepting new connections
// 4. wait for commands in progress to finish (except for abandoned long running commands, like running a build)
CompositeStoppable.stoppable(stateCoordinator, registryUpdater, connector, connectionHandler).stop();
} finally {
lifecycleLock.unlock();
}
}
public void stopOnExpiration(DaemonExpirationStrategy expirationStrategy, int checkIntervalMills) {
LOGGER.debug("stopOnExpiration() called on daemon");
scheduleExpirationChecks(expirationStrategy, checkIntervalMills);
awaitExpiration();
}
private void scheduleExpirationChecks(DaemonExpirationStrategy expirationStrategy, int checkIntervalMills) {
DaemonExpirationPeriodicCheck periodicCheck = new DaemonExpirationPeriodicCheck(expirationStrategy, listenerManager);
listenerManager.addListener(new DefaultDaemonExpirationListener(stateCoordinator, registryUpdater));
scheduledExecutorService.scheduleAtFixedRate(periodicCheck, checkIntervalMills, checkIntervalMills, TimeUnit.MILLISECONDS);
}
/**
* Tell DaemonStateCoordinator to block until it's state is Stopped.
*/
private void awaitExpiration() {
LOGGER.debug("awaitExpiration() called on daemon");
DaemonStateCoordinator stateCoordinator;
lifecycleLock.lock();
try {
if (this.stateCoordinator == null) {
throw new IllegalStateException("cannot await stop on daemon as it has not been started.");
}
stateCoordinator = this.stateCoordinator;
} finally {
lifecycleLock.unlock();
}
stateCoordinator.awaitStop();
}
public DaemonStateCoordinator getStateCoordinator() {
return stateCoordinator;
}
private static class DaemonExpirationPeriodicCheck implements Runnable {
private final DaemonExpirationStrategy expirationStrategy;
private final DaemonExpirationListener listenerBroadcast;
private final Lock lock = new ReentrantLock();
DaemonExpirationPeriodicCheck(DaemonExpirationStrategy expirationStrategy, ListenerManager listenerManager) {
this.expirationStrategy = expirationStrategy;
this.listenerBroadcast = listenerManager.getBroadcaster(DaemonExpirationListener.class);
}
@Override
public void run() {
if (lock.tryLock()) {
try {
final DaemonExpirationResult result = expirationStrategy.checkExpiration();
if (result.getStatus() != DO_NOT_EXPIRE) {
listenerBroadcast.onExpirationEvent(result);
}
} catch (Throwable t) {
LOGGER.error("Problem in daemon expiration check", t);
if (t instanceof Error) {
// never swallow java.lang.Error
throw (Error) t;
}
} finally {
lock.unlock();
}
} else {
LOGGER.warn("Previous DaemonExpirationPeriodicCheck was still running when the next run was scheduled.");
}
}
}
private static class DefaultDaemonExpirationListener implements DaemonExpirationListener {
private final DaemonStateControl stateControl;
private final DaemonRegistryUpdater registryUpdater;
public DefaultDaemonExpirationListener(DaemonStateControl stateControl, DaemonRegistryUpdater registryUpdater) {
this.stateControl = stateControl;
this.registryUpdater = registryUpdater;
}
@Override
public void onExpirationEvent(DaemonExpirationResult result) {
final DaemonExpirationStatus expirationCheck = result.getStatus();
if (expirationCheck != DO_NOT_EXPIRE) {
if (expirationCheck != QUIET_EXPIRE) {
registryUpdater.onExpire(result.getReason(), expirationCheck);
}
if (expirationCheck == IMMEDIATE_EXPIRE) {
stateControl.requestForcefulStop(result.getReason());
} else {
stateControl.requestStop(result.getReason());
}
}
}
}
}
| |
/*
* 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.felix.ipojo.manipulator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.jar.JarFile;
import org.apache.felix.ipojo.manipulator.manifest.FileManifestProvider;
import org.apache.felix.ipojo.manipulator.metadata.AnnotationMetadataProvider;
import org.apache.felix.ipojo.manipulator.metadata.CompositeMetadataProvider;
import org.apache.felix.ipojo.manipulator.metadata.EmptyMetadataProvider;
import org.apache.felix.ipojo.manipulator.metadata.FileMetadataProvider;
import org.apache.felix.ipojo.manipulator.metadata.StreamMetadataProvider;
import org.apache.felix.ipojo.manipulator.render.MetadataRenderer;
import org.apache.felix.ipojo.manipulator.reporter.SystemReporter;
import org.apache.felix.ipojo.manipulator.store.DirectoryResourceStore;
import org.apache.felix.ipojo.manipulator.store.JarFileResourceStore;
import org.apache.felix.ipojo.manipulator.store.builder.DefaultManifestBuilder;
import org.apache.felix.ipojo.manipulator.store.mapper.WABResourceMapper;
import org.apache.felix.ipojo.manipulator.util.Metadatas;
import org.apache.felix.ipojo.manipulator.util.Strings;
import org.apache.felix.ipojo.manipulator.visitor.check.CheckFieldConsistencyVisitor;
import org.apache.felix.ipojo.manipulator.visitor.writer.ManipulatedResourcesWriter;
import org.apache.felix.ipojo.metadata.Element;
import org.apache.felix.ipojo.xml.parser.SchemaResolver;
/**
* Pojoization allows creating an iPOJO bundle from a "normal" bundle.
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class Pojoization {
/**
* iPOJO Imported Package Version.
*/
public static final String IPOJO_PACKAGE_VERSION = " 1.8.0";
/**
* Flag describing if we need or not compute annotations.
* By default, compute the annotations.
*/
private boolean m_ignoreAnnotations;
/**
* Flag describing if we need or not use local XSD files
* (i.e. use the {@link SchemaResolver} or not).
* If <code>true</code> the local XSD are used (default to {@literal false}).
*/
private boolean m_useLocalXSD = false;
/**
* Reporter for error reporting.
*/
private Reporter m_reporter;
public Pojoization() {
this(new SystemReporter());
}
public Pojoization(Reporter reporter) {
m_reporter = reporter;
}
/**
* Activates annotation processing.
*/
public void disableAnnotationProcessing() {
m_ignoreAnnotations = true;
}
/**
* Activates the entity resolver loading
* XSD files from the classloader.
*/
public void setUseLocalXSD() {
m_useLocalXSD = true;
}
/**
* @return all the errors (fatal) reported by the manipulation process.
*/
public List<String> getErrors() {
// Simple delegation for backward compatibility
return m_reporter.getErrors();
}
/**
* @return all the warnings (non fatal) reported by the manipulation process.
*/
public List<String> getWarnings() {
// Simple delegation for backward compatibility
return m_reporter.getWarnings();
}
/**
* Manipulates an input bundle.
* This method creates an iPOJO bundle based on the given metadata file.
* The original and final bundles must be different.
* @param in the original bundle.
* @param out the final bundle.
* @param metadata the iPOJO metadata input stream.
*/
public void pojoization(File in, File out, InputStream metadata) {
StreamMetadataProvider provider = new StreamMetadataProvider(metadata, m_reporter);
provider.setValidateUsingLocalSchemas(m_useLocalXSD);
ResourceStore store;
try {
JarFile origin = new JarFile(in);
JarFileResourceStore jfrs = new JarFileResourceStore(origin, out);
if (in.getName().endsWith(".war")) {
// this is a war file, use the right mapper
jfrs.setResourceMapper(new WABResourceMapper());
}
jfrs.setManifest(origin.getManifest());
DefaultManifestBuilder dmb = new DefaultManifestBuilder();
dmb.setMetadataRenderer(new MetadataRenderer());
jfrs.setManifestBuilder(dmb);
store = jfrs;
} catch (IOException e) {
m_reporter.error("The input file " + in.getAbsolutePath() + " is not a Jar file");
return;
}
ManipulationVisitor visitor = createDefaultVisitorChain(store);
pojoization(store, provider, visitor);
}
private ManipulationVisitor createDefaultVisitorChain(ResourceStore store) {
ManipulatedResourcesWriter writer = new ManipulatedResourcesWriter();
writer.setReporter(m_reporter);
writer.setResourceStore(store);
CheckFieldConsistencyVisitor checkFieldConsistencyVisitor = new CheckFieldConsistencyVisitor(writer);
checkFieldConsistencyVisitor.setReporter(m_reporter);
return checkFieldConsistencyVisitor;
}
/**
* Manipulates an input bundle.
* This method creates an iPOJO bundle based on the given metadata file.
* The original and final bundles must be different.
* @param in the original bundle.
* @param out the final bundle.
* @param metadataFile the iPOJO metadata file (XML).
*/
public void pojoization(File in, File out, File metadataFile) {
MetadataProvider provider = new EmptyMetadataProvider();
if (metadataFile != null) {
FileMetadataProvider fileMetadataProvider = new FileMetadataProvider(metadataFile, m_reporter);
fileMetadataProvider.setValidateUsingLocalSchemas(m_useLocalXSD);
provider = fileMetadataProvider;
}
ResourceStore store;
try {
JarFile origin = new JarFile(in);
JarFileResourceStore jfrs = new JarFileResourceStore(origin, out);
if (in.getName().endsWith(".war")) {
// this is a war file, use the right mapper
jfrs.setResourceMapper(new WABResourceMapper());
}
jfrs.setManifest(origin.getManifest());
DefaultManifestBuilder dmb = new DefaultManifestBuilder();
dmb.setMetadataRenderer(new MetadataRenderer());
jfrs.setManifestBuilder(dmb);
store = jfrs;
} catch (IOException e) {
m_reporter.error("The input file " + in.getAbsolutePath() + " is not a Jar file");
return;
}
ManipulationVisitor visitor = createDefaultVisitorChain(store);
pojoization(store, provider, visitor);
}
/**
* Manipulates an expanded bundles.
* Classes are in the specified directory.
* this method allows to update a customized manifest.
* @param directory the directory containing classes
* @param metadataFile the metadata file
* @param manifestFile the manifest file. <code>null</code> to use directory/META-INF/MANIFEST.mf
*/
public void directoryPojoization(File directory, File metadataFile, File manifestFile) {
// Get the metadata.xml location if not null
MetadataProvider provider = new EmptyMetadataProvider();
if (metadataFile != null) {
FileMetadataProvider fileMetadataProvider = new FileMetadataProvider(metadataFile, m_reporter);
fileMetadataProvider.setValidateUsingLocalSchemas(m_useLocalXSD);
provider = fileMetadataProvider;
}
ManifestProvider manifestProvider;
if (manifestFile != null) {
if (manifestFile.isFile()) {
try {
manifestProvider = new FileManifestProvider(manifestFile);
} catch (IOException e) {
m_reporter.error("Cannot read Manifest from '" + manifestFile.getAbsolutePath() + "'");
return;
}
} else {
m_reporter.error("The manifest file " + manifestFile.getAbsolutePath() + " does not exist");
return;
}
} else {
// If the manifest is not specified, the m_dir/META-INF/MANIFEST.MF is used.
File metaInf = new File(directory, "META-INF");
File original = new File(metaInf, "MANIFEST.MF");
if (original.isFile()) {
try {
manifestProvider = new FileManifestProvider(original);
} catch (IOException e) {
m_reporter.error("Cannot read Manifest from '" + original.getAbsolutePath() + "'");
return;
}
} else {
m_reporter.error("The manifest file " + original.getAbsolutePath() + " does not exist");
return;
}
}
DirectoryResourceStore store;
if (directory.exists() && directory.isDirectory()) {
store = new DirectoryResourceStore(directory);
File webinf = new File(directory, "WEB-INF");
if (directory.getName().endsWith(".war") || webinf.isDirectory()) {
// this is a war file, use the right mapper
store.setResourceMapper(new WABResourceMapper());
}
store.setManifest(manifestProvider.getManifest());
DefaultManifestBuilder dmb = new DefaultManifestBuilder();
dmb.setMetadataRenderer(new MetadataRenderer());
store.setManifestBuilder(dmb);
} else {
m_reporter.error("The directory " + directory.getAbsolutePath() + " does not exist or is not a directory.");
return;
}
ManipulationVisitor visitor = createDefaultVisitorChain(store);
pojoization(store, provider, visitor);
}
public void pojoization(final ResourceStore store,
final MetadataProvider metadata,
final ManipulationVisitor visitor) {
ManipulationEngine engine = new ManipulationEngine();
engine.setResourceStore(store);
engine.setReporter(m_reporter);
engine.setManipulationVisitor(visitor);
try {
// Creates a composite to store multiple metadata providers
CompositeMetadataProvider composite = new CompositeMetadataProvider(m_reporter);
composite.addMetadataProvider(metadata);
if (!m_ignoreAnnotations) {
composite.addMetadataProvider(new AnnotationMetadataProvider(store, m_reporter));
}
// Get metadata
List<Element> metadatas = composite.getMetadatas();
// Construct ManipulationUnits
// And collect non-component metadata
for (Element meta : metadatas) {
String name = Metadatas.getComponentType(meta);
if (name != null) {
// Only handler and component have a classname attribute
String path = Strings.asResourcePath(name);
engine.addManipulationUnit(new ManipulationUnit(path, meta));
} else {
visitor.visitMetadata(meta);
}
}
} catch (IOException e) {
m_reporter.error("Cannot load metadata " + e.getMessage());
return;
}
// Start the manipulation
engine.generate();
// Tell the visitor that we have finished
visitor.visitEnd();
}
}
| |
/* __ __ __ __ __ ___
* \ \ / / \ \ / / __/
* \ \/ / /\ \ \/ / /
* \____/__/ \__\____/__/
*
* Copyright 2014-2017 Vavr, http://vavr.io
*
* 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.vavr.collection;
import io.vavr.Function2;
import io.vavr.Tuple2;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.List;
import java.util.Random;
import java.util.function.Function;
import java.util.function.Predicate;
import static io.vavr.API.Tuple;
import static org.assertj.core.api.Assertions.assertThat;
public class VectorPropertyTest {
@Test
public void shouldCreateAndGet() {
for (int i = 0; i < 500; i++) {
final Seq<Integer> expected = Array.range(0, i);
final Vector<Integer> actual = Vector.ofAll(expected);
for (int j = 0; j < actual.size(); j++) {
assertThat(expected.get(j)).isEqualTo(actual.get(j));
}
assert (i == 0) || !actual.trie.type.type().isPrimitive();
/* boolean */
final Seq<Boolean> expectedBoolean = expected.map(v -> v > 0);
final Vector<Boolean> actualBoolean = Vector.ofAll(ArrayType.<boolean[]> asPrimitives(boolean.class, expectedBoolean));
assert (i == 0) || (actualBoolean.trie.type.type() == boolean.class);
assertAreEqual(expectedBoolean, actualBoolean);
assertAreEqual(expectedBoolean.append(null), actualBoolean.append(null));
/* byte */
final Seq<Byte> expectedByte = expected.map(Integer::byteValue);
final Vector<Byte> actualByte = Vector.ofAll(ArrayType.<byte[]> asPrimitives(byte.class, expectedByte));
assert (i == 0) || (actualByte.trie.type.type() == byte.class);
assertAreEqual(expectedByte, actualByte);
assertAreEqual(expectedByte.append(null), actualByte.append(null));
/* char */
final Seq<Character> expectedChar = expected.map(v -> (char) v.intValue());
final Vector<Character> actualChar = Vector.ofAll(ArrayType.<char[]> asPrimitives(char.class, expectedChar));
assert (i == 0) || (actualChar.trie.type.type() == char.class);
assertAreEqual(expectedChar, actualChar);
assertAreEqual(expectedChar.append(null), actualChar.append(null));
/* double */
final Seq<Double> expectedDouble = expected.map(Integer::doubleValue);
final Vector<Double> actualDouble = Vector.ofAll(ArrayType.<double[]> asPrimitives(double.class, expectedDouble));
assert (i == 0) || (actualDouble.trie.type.type() == double.class);
assertAreEqual(expectedDouble, actualDouble);
assertAreEqual(expectedDouble.append(null), actualDouble.append(null));
/* float */
final Seq<Float> expectedFloat = expected.map(Integer::floatValue);
final Vector<Float> actualFloat = Vector.ofAll(ArrayType.<float[]> asPrimitives(float.class, expectedFloat));
assert (i == 0) || (actualFloat.trie.type.type() == float.class);
assertAreEqual(expectedFloat, actualFloat);
assertAreEqual(expectedFloat.append(null), actualFloat.append(null));
/* int */
final Vector<Integer> actualInt = Vector.ofAll(ArrayType.<int[]> asPrimitives(int.class, expected));
assert (i == 0) || (actualInt.trie.type.type() == int.class);
assertAreEqual(expected, actualInt);
assertAreEqual(expected.append(null), actual.append(null));
/* long */
final Seq<Long> expectedLong = expected.map(Integer::longValue);
final Vector<Long> actualLong = Vector.ofAll(ArrayType.<long[]> asPrimitives(long.class, expectedLong));
assert (i == 0) || (actualLong.trie.type.type() == long.class);
assertAreEqual(expectedLong, actualLong);
assertAreEqual(expectedLong.append(null), actualLong.append(null));
/* short */
final Seq<Short> expectedShort = expected.map(Integer::shortValue);
final Vector<Short> actualShort = Vector.ofAll(ArrayType.<short[]> asPrimitives(short.class, expectedShort));
assert (i == 0) || (actualShort.trie.type.type() == short.class);
assertAreEqual(expectedShort, actualShort);
assertAreEqual(expectedShort.append(null), actualShort.append(null));
}
}
@Test
public void shouldIterate() {
for (byte depth = 0; depth <= 2; depth++) {
for (int i = 0; i < 5000; i++) {
final Seq<Integer> expected = Array.range(0, i);
final Vector<Integer> actual = Vector.ofAll(expected);
assertAreEqual(actual, expected);
}
}
Seq<Integer> expected = Array.range(0, 1000);
Vector<Integer> actual = Vector.ofAll(ArrayType.<int[]> asPrimitives(int.class, expected));
for (int drop = 0; drop <= (BitMappedTrie.BRANCHING_FACTOR + 1); drop++) {
final Iterator<Integer> expectedIterator = expected.iterator();
actual.trie.<int[]> visit((index, leaf, start, end) -> {
for (int i = start; i < end; i++) {
assertThat(leaf[i]).isEqualTo(expectedIterator.next());
}
return -1;
});
expected = expected.tail().init();
actual = actual.tail().init();
}
}
@Test
public void shouldPrepend() {
Seq<Integer> expected = Array.empty();
Vector<Integer> actual = Vector.empty();
for (int drop = 0; drop <= (BitMappedTrie.BRANCHING_FACTOR + 1); drop++) {
for (Integer value : Iterator.range(0, 1000)) {
expected = expected.drop(drop);
actual = assertAreEqual(actual, drop, Vector::drop, expected);
expected = expected.prepend(value);
actual = assertAreEqual(actual, value, Vector::prepend, expected);
}
}
}
@Test
public void shouldAppend() {
Seq<Integer> expected = Array.empty();
Vector<Integer> actual = Vector.empty();
for (int drop = 0; drop <= (BitMappedTrie.BRANCHING_FACTOR + 1); drop++) {
for (Integer value : Iterator.range(0, 500)) {
expected = expected.drop(drop);
actual = assertAreEqual(actual, drop, Vector::drop, expected);
expected = expected.append(value);
actual = assertAreEqual(actual, value, Vector::append, expected);
}
}
}
@Test
public void shouldUpdate() {
final Function<Integer, Integer> mapper = i -> i + 1;
for (byte depth = 0; depth <= 2; depth++) {
final int length = 10_000;
for (int drop = 0; drop <= (BitMappedTrie.BRANCHING_FACTOR + 1); drop++) {
Seq<Integer> expected = Array.range(0, length);
Vector<Integer> actual = Vector.ofAll(expected);
expected = expected.drop(drop); // test the `trailing` drops and the internal tree offset
actual = assertAreEqual(actual, drop, Vector::drop, expected);
for (int i = 0; i < actual.length(); i++) {
final Integer newValue = mapper.apply(actual.get(i));
actual = actual.update(i, newValue);
}
assertAreEqual(actual, 0, (a, p) -> a, expected.map(mapper));
}
}
}
@Test
public void shouldDrop() {
final Seq<Integer> expected = Array.range(0, 2_000);
final Vector<Integer> actual = Vector.ofAll(expected);
Vector<Integer> actualSingleDrop = actual;
for (int i = 0; i <= expected.length(); i++) {
final Seq<Integer> expectedDrop = expected.drop(i);
assertAreEqual(actual, i, Vector::drop, expectedDrop);
assertAreEqual(actualSingleDrop, null, (a, p) -> a, expectedDrop);
actualSingleDrop = actualSingleDrop.drop(1);
}
}
@Test
public void shouldDropRight() {
final Seq<Integer> expected = Array.range(0, 2_000);
final Vector<Integer> actual = Vector.ofAll(expected);
Vector<Integer> actualSingleDrop = actual;
for (int i = 0; i <= expected.length(); i++) {
final Seq<Integer> expectedDrop = expected.dropRight(i);
assertAreEqual(actual, i, Vector::dropRight, expectedDrop);
assertAreEqual(actualSingleDrop, null, (a, p) -> a, expectedDrop);
actualSingleDrop = actualSingleDrop.dropRight(1);
}
}
@Test
public void shouldSlice() {
for (int length = 1, end = 500; length <= end; length++) {
Seq<Integer> expected = Array.range(0, length);
Vector<Integer> actual = Vector.ofAll(expected);
for (int i = 0; i <= expected.length(); i++) {
expected = expected.slice(1, expected.size() - 1);
actual = assertAreEqual(actual, i, (a, p) -> a.slice(1, a.size() - 1), expected);
}
}
}
@Test
public void shouldBehaveLikeArray() {
final Random random = new Random(13579);
for (int i = 1; i < 10; i++) {
Seq<Object> expected = Array.empty();
Vector<Object> actual = Vector.empty();
for (int j = 0; j < 20_000; j++) {
Seq<Tuple2<Seq<Object>, Vector<Object>>> history = Array.empty();
if (percent(random) < 20) {
expected = Array.ofAll(Vector.ofAll(randomValues(random, 100)).filter(v -> v instanceof Integer));
actual = (percent(random) < 30) ? Vector.narrow(Vector.ofAll(ArrayType.<int[]> asPrimitives(int.class, expected))) : Vector.ofAll(expected);
assertAreEqual(expected, actual);
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 50) {
final Object value = randomValue(random);
expected = expected.append(value);
actual = assertAreEqual(actual, value, Vector::append, expected);
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 10) {
Iterable<Object> values = randomValues(random, random.nextInt(2 * BitMappedTrie.BRANCHING_FACTOR));
expected = expected.appendAll(values);
values = (percent(random) < 50) ? Iterator.ofAll(values.iterator()) : values; /* not traversable again */
actual = assertAreEqual(actual, values, Vector::appendAll, expected);
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 50) {
final Object value = randomValue(random);
expected = expected.prepend(value);
actual = assertAreEqual(actual, value, Vector::prepend, expected);
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 10) {
Iterable<Object> values = randomValues(random, random.nextInt(2 * BitMappedTrie.BRANCHING_FACTOR));
expected = expected.prependAll(values);
values = (percent(random) < 50) ? Iterator.ofAll(values) : values; /* not traversable again */
actual = assertAreEqual(actual, values, Vector::prependAll, expected);
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 30) {
final int n = random.nextInt(expected.size() + 1);
expected = expected.drop(n);
actual = assertAreEqual(actual, n, Vector::drop, expected);
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 10) {
final int index = random.nextInt(expected.size() + 1);
Iterable<Object> values = randomValues(random, random.nextInt(2 * BitMappedTrie.BRANCHING_FACTOR));
expected = expected.insertAll(index, values);
values = (percent(random) < 50) ? Iterator.ofAll(values) : values; /* not traversable again */
actual = assertAreEqual(actual, values, (a, p) -> a.insertAll(index, p), expected);
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 30) {
final int n = random.nextInt(expected.size() + 1);
expected = expected.take(n);
actual = assertAreEqual(actual, n, Vector::take, expected);
history = history.append(Tuple(expected, actual));
}
if (!expected.isEmpty()) {
assertThat(actual.head()).isEqualTo(expected.head());
Assertions.assertThat(actual.tail().toJavaList()).isEqualTo(expected.tail().toJavaList());
history = history.append(Tuple(expected, actual));
}
if (!expected.isEmpty()) {
final int index = random.nextInt(expected.size());
assertThat(actual.get(index)).isEqualTo(expected.get(index));
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 50) {
if (!expected.isEmpty()) {
final int index = random.nextInt(expected.size());
final Object value = randomValue(random);
expected = expected.update(index, value);
actual = assertAreEqual(actual, null, (a, p) -> a.update(index, value), expected);
history = history.append(Tuple(expected, actual));
}
}
if (percent(random) < 20) {
final Function<Object, Object> mapper = val -> (val instanceof Integer) ? ((Integer) val + 1) : val;
expected = expected.map(mapper);
actual = assertAreEqual(actual, null, (a, p) -> a.map(mapper), expected);
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 30) {
final Predicate<Object> filter = val -> (String.valueOf(val).length() % 10) == 0;
expected = expected.filter(filter);
actual = assertAreEqual(actual, null, (a, p) -> a.filter(filter), expected);
history = history.append(Tuple(expected, actual));
}
if (percent(random) < 30) {
for (int k = 0; k < 2; k++) {
if (!expected.isEmpty()) {
final int to = random.nextInt(expected.size());
final int from = random.nextInt(to + 1);
expected = expected.slice(from, to);
actual = assertAreEqual(actual, null, (a, p) -> a.slice(from, to), expected);
history = history.append(Tuple(expected, actual));
}
}
}
history.forEach(t -> assertAreEqual(t._1, t._2)); // test that the modifications are persistent
}
}
}
private int percent(Random random) { return random.nextInt(101); }
private Iterable<Object> randomValues(Random random, int count) {
final Vector<Object> values = Vector.range(0, count).map(v -> randomValue(random));
final int percent = percent(random);
if (percent < 30) {
return values.toJavaList(); /* not Traversable */
} else {
return values;
}
}
private Object randomValue(Random random) {
final int percent = percent(random);
if (percent < 5) {
return null;
} else if (percent < 10) {
return "String";
} else {
return random.nextInt();
}
}
private static <T extends Seq<?>, P> T assertAreEqual(T previousActual, P param, Function2<T, P, T> actualProvider, Seq<?> expected) {
final T actual = actualProvider.apply(previousActual, param);
assertAreEqual(expected, actual);
return actual; // makes debugging a lot easier, as the frame can be dropped and rerun on AssertError
}
private static void assertAreEqual(Seq<?> expected, Seq<?> actual) {
final List<?> actualList = actual.toJavaList();
final List<?> expectedList = expected.toJavaList();
assertThat(actualList).isEqualTo(expectedList); // a lot faster than `hasSameElementsAs`
}
}
| |
/*
* 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.websockets.core;
import io.undertow.util.ImmediatePooledByteBuffer;
import org.xnio.Buffers;
import org.xnio.ChannelExceptionHandler;
import org.xnio.ChannelListener;
import org.xnio.IoUtils;
import org.xnio.XnioExecutor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import static org.xnio.ChannelListeners.flushingChannelListener;
/**
* @author Stuart Douglas
*/
public class WebSockets {
/**
* Sends a complete text message, invoking the callback when complete
*
* @param message
* @param wsChannel
* @param callback
*/
public static void sendText(final String message, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
final ByteBuffer data = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8));
sendInternal(data, WebSocketFrameType.TEXT, wsChannel, callback, -1);
}
/**
* Sends a complete text message, invoking the callback when complete
*
* @param message
* @param wsChannel
* @param callback
* @param timeoutmillis the timeout in milliseconds
*/
public static void sendText(final String message, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
final ByteBuffer data = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8));
sendInternal(data, WebSocketFrameType.TEXT, wsChannel, callback, timeoutmillis);
}
/**
* Sends a complete text message, invoking the callback when complete
*
* @param message
* @param wsChannel
* @param callback
*/
public static void sendText(final ByteBuffer message, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendInternal(message, WebSocketFrameType.TEXT, wsChannel, callback, -1);
}
/**
* Sends a complete text message, invoking the callback when complete
*
* @param message
* @param wsChannel
* @param callback
*/
public static void sendText(final ByteBuffer message, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
sendInternal(message, WebSocketFrameType.TEXT, wsChannel, callback, timeoutmillis);
}
/**
* Sends a complete text message, invoking the callback when complete
*
* @param message
* @param wsChannel
*/
public static void sendTextBlocking(final String message, final WebSocketChannel wsChannel) throws IOException {
final ByteBuffer data = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8));
sendBlockingInternal(data, WebSocketFrameType.TEXT, wsChannel);
}
/**
* Sends a complete text message, invoking the callback when complete
*
* @param message
* @param wsChannel
*/
public static void sendTextBlocking(final ByteBuffer message, final WebSocketChannel wsChannel) throws IOException {
sendBlockingInternal(message, WebSocketFrameType.TEXT, wsChannel);
}
/**
* Sends a complete ping message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendPing(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendInternal(data, WebSocketFrameType.PING, wsChannel, callback, -1);
}
/**
* Sends a complete ping message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendPing(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
sendInternal(data, WebSocketFrameType.PING, wsChannel, callback, timeoutmillis);
}
/**
* Sends a complete ping message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendPing(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendInternal(mergeBuffers(data), WebSocketFrameType.PING, wsChannel, callback, -1);
}
/**
* Sends a complete ping message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendPing(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
sendInternal(mergeBuffers(data), WebSocketFrameType.PING, wsChannel, callback, timeoutmillis);
}
/**
* Sends a complete ping message using blocking IO
*
* @param data
* @param wsChannel
*/
public static void sendPingBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException {
sendBlockingInternal(data, WebSocketFrameType.PING, wsChannel);
}
/**
* Sends a complete ping message using blocking IO
*
* @param data
* @param wsChannel
*/
public static void sendPingBlocking(final ByteBuffer[] data, final WebSocketChannel wsChannel) throws IOException {
sendBlockingInternal(mergeBuffers(data), WebSocketFrameType.PING, wsChannel);
}
/**
* Sends a complete pong message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendPong(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendInternal(data, WebSocketFrameType.PONG, wsChannel, callback, -1);
}
/**
* Sends a complete pong message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendPong(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
sendInternal(data, WebSocketFrameType.PONG, wsChannel, callback, timeoutmillis);
}
/**
* Sends a complete pong message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendPong(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendInternal(mergeBuffers(data), WebSocketFrameType.PONG, wsChannel, callback, -1);
}
/**
* Sends a complete pong message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendPong(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
sendInternal(mergeBuffers(data), WebSocketFrameType.PONG, wsChannel, callback, timeoutmillis);
}
/**
* Sends a complete pong message using blocking IO
*
* @param data
* @param wsChannel
*/
public static void sendPongBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException {
sendBlockingInternal(data, WebSocketFrameType.PONG, wsChannel);
}
/**
* Sends a complete pong message using blocking IO
*
* @param data
* @param wsChannel
*/
public static void sendPongBlocking(final ByteBuffer[] data, final WebSocketChannel wsChannel) throws IOException {
sendBlockingInternal(mergeBuffers(data), WebSocketFrameType.PONG, wsChannel);
}
/**
* Sends a complete text message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendBinary(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendInternal(data, WebSocketFrameType.BINARY, wsChannel, callback, -1);
}
/**
* Sends a complete text message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendBinary(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
sendInternal(data, WebSocketFrameType.BINARY, wsChannel, callback, timeoutmillis);
}
/**
* Sends a complete text message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendBinary(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendInternal(mergeBuffers(data), WebSocketFrameType.BINARY, wsChannel, callback, -1);
}
/**
* Sends a complete text message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendBinary(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
sendInternal(mergeBuffers(data), WebSocketFrameType.BINARY, wsChannel, callback, timeoutmillis);
}
/**
* Sends a complete binary message using blocking IO
*
* @param data
* @param wsChannel
*/
public static void sendBinaryBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException {
sendBlockingInternal(data, WebSocketFrameType.BINARY, wsChannel);
}
/**
* Sends a complete binary message using blocking IO
*
* @param data
* @param wsChannel
*/
public static void sendBinaryBlocking(final ByteBuffer[] data, final WebSocketChannel wsChannel) throws IOException {
sendBlockingInternal(mergeBuffers(data), WebSocketFrameType.BINARY, wsChannel);
}
/**
* Sends a complete close message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendClose(final ByteBuffer data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
CloseMessage sm = new CloseMessage(data);
sendClose(sm, wsChannel, callback);
}
/**
* Sends a complete close message, invoking the callback when complete
*
* @param data
* @param wsChannel
* @param callback
*/
public static void sendClose(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
CloseMessage sm = new CloseMessage(data);
sendClose(sm, wsChannel, callback);
}
/**
* Sends a complete close message, invoking the callback when complete
*
* @param code The close code
* @param wsChannel
* @param callback
*/
public static void sendClose(final int code, String reason, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
sendClose(new CloseMessage(code, reason), wsChannel, callback);
}
/**
* Sends a complete close message, invoking the callback when complete
*
* @param closeMessage The close message
* @param wsChannel
* @param callback
*/
public static void sendClose(final CloseMessage closeMessage, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback) {
wsChannel.setCloseCode(closeMessage.getCode());
wsChannel.setCloseReason(closeMessage.getReason());
sendInternal(closeMessage.toByteBuffer(), WebSocketFrameType.CLOSE, wsChannel, callback, -1);
}
/**
* Sends a complete close message, invoking the callback when complete
*
* @param closeMessage the close message
* @param wsChannel
*/
public static void sendCloseBlocking(final CloseMessage closeMessage, final WebSocketChannel wsChannel) throws IOException {
wsChannel.setCloseReason(closeMessage.getReason());
wsChannel.setCloseCode(closeMessage.getCode());
sendBlockingInternal(closeMessage.toByteBuffer(), WebSocketFrameType.CLOSE, wsChannel);
}
/**
* Sends a complete close message, invoking the callback when complete
*
* @param code
* @param wsChannel
*/
public static void sendCloseBlocking(final int code, String reason, final WebSocketChannel wsChannel) throws IOException {
sendCloseBlocking(new CloseMessage(code, reason), wsChannel);
}
/**
* Sends a complete close message, invoking the callback when complete
*
* @param data
* @param wsChannel
*/
public static void sendCloseBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException {
sendCloseBlocking(new CloseMessage(data), wsChannel);
}
/**
* Sends a complete close message, invoking the callback when complete
*
* @param data
* @param wsChannel
*/
public static void sendCloseBlocking(final ByteBuffer[] data, final WebSocketChannel wsChannel) throws IOException {
sendCloseBlocking(new CloseMessage(data), wsChannel);
}
private static void sendInternal(final ByteBuffer data, WebSocketFrameType type, final WebSocketChannel wsChannel, final WebSocketCallback<Void> callback, long timeoutmillis) {
try {
StreamSinkFrameChannel channel = wsChannel.send(type);
// TODO chunk data into some MTU-like thing to control packet size
if(!channel.send(new ImmediatePooledByteBuffer(data))) {
throw WebSocketMessages.MESSAGES.unableToSendOnNewChannel();
}
flushChannelAsync(wsChannel, callback, channel, null, timeoutmillis);
} catch (IOException e) {
if (callback != null) {
callback.onError(wsChannel, null, e);
} else {
IoUtils.safeClose(wsChannel);
}
}
}
private static <T> void flushChannelAsync(final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, StreamSinkFrameChannel channel, final T context, long timeoutmillis) throws IOException {
final WebSocketFrameType type = channel.getType();
channel.shutdownWrites();
if (!channel.flush()) {
channel.getWriteSetter().set(flushingChannelListener(
new ChannelListener<StreamSinkFrameChannel>() {
@Override
public void handleEvent(StreamSinkFrameChannel channel) {
if (callback != null) {
callback.complete(wsChannel, context);
}
if (type == WebSocketFrameType.CLOSE && wsChannel.isCloseFrameReceived()) {
IoUtils.safeClose(wsChannel);
}
}
}, new ChannelExceptionHandler<StreamSinkFrameChannel>() {
@Override
public void handleException(StreamSinkFrameChannel channel, IOException exception) {
if (callback != null) {
callback.onError(wsChannel, context, exception);
}
IoUtils.safeClose(channel, wsChannel);
}
}
));
if(timeoutmillis > 0) {
setupTimeout(channel, timeoutmillis);
}
channel.resumeWrites();
return;
}
if (callback != null) {
callback.complete(wsChannel, context);
}
}
private static void setupTimeout(final StreamSinkFrameChannel channel, long timeoutmillis) {
final XnioExecutor.Key key = channel.getIoThread().executeAfter(new Runnable() {
@Override
public void run() {
if (channel.isOpen()) {
IoUtils.safeClose(channel);
}
}
}, timeoutmillis, TimeUnit.MILLISECONDS);
channel.getCloseSetter().set(new ChannelListener<StreamSinkFrameChannel>() {
@Override
public void handleEvent(StreamSinkFrameChannel channel) {
key.remove();
}
});
}
private static void sendBlockingInternal(final ByteBuffer data, WebSocketFrameType type, final WebSocketChannel wsChannel) throws IOException {
StreamSinkFrameChannel channel = wsChannel.send(type);
// TODO chunk data into some MTU-like thing to control packet size
if(!channel.send(new ImmediatePooledByteBuffer(data))) {
throw WebSocketMessages.MESSAGES.unableToSendOnNewChannel();
}
channel.shutdownWrites();
while (!channel.flush()) {
channel.awaitWritable();
}
if (type == WebSocketFrameType.CLOSE && wsChannel.isCloseFrameReceived()) {
IoUtils.safeClose(wsChannel);
}
}
private WebSockets() {
}
public static ByteBuffer mergeBuffers(ByteBuffer... payload) {
int size = (int) Buffers.remaining(payload);
if (size == 0) {
return Buffers.EMPTY_BYTE_BUFFER;
}
ByteBuffer buffer = ByteBuffer.allocate(size);
for (ByteBuffer buf : payload) {
buffer.put(buf);
}
buffer.flip();
return buffer;
}
}
| |
package com.stabilise.entity.component.core;
import com.stabilise.entity.Entities;
import com.stabilise.entity.Entity;
import com.stabilise.entity.damage.GeneralSource;
import com.stabilise.entity.damage.IDamageSource;
import com.stabilise.entity.event.EDamaged;
import com.stabilise.entity.event.ETileCollision;
import com.stabilise.entity.event.EntityEvent;
import com.stabilise.entity.event.EntityEvent.Type;
import com.stabilise.entity.particle.ParticleIndicator;
import com.stabilise.entity.particle.ParticleSmoke;
import com.stabilise.entity.particle.manager.ParticleEmitter;
import com.stabilise.item.Item;
import com.stabilise.util.Direction;
import com.stabilise.util.io.data.DataCompound;
import com.stabilise.world.World;
/**
* Basic mob implementation.
*
* <p>This class will need a pretty heavy rewrite sometime in the future.
*/
public abstract class CBaseMob extends CCore {
/** The default number of ticks a mob becomes invulnerable for after being
* hit. */
protected static final int INVULNERABILITY_TICKS = 20;
/** The default number of ticks a mob remains in the world after being
* killed, before vanishing. */
protected static final int DEATH_TICKS = 40;
/** Possible state priorities. */
public static enum StatePriority {
/** An ordinary state, in which a mob can do other stuff. */
ORDINARY(0),
/** A mob is considered 'occupied' if in a state with this priority
* (e.g. an attack animation) and must wait for it to finish before
* being able to do other stuff. */
OCCUPIED(1),
/** A state with this priority cannot be overridden by the mob (e.g.
* hitstun, or being dead). */
UNOVERRIDEABLE(2);
/** The StatePriority's underlying integer value, for comparison
* purposes. */
private final int value;
private StatePriority(int value) {
this.value = value;
}
/**
* @return {@code true} if something with this priority is capable of
* overriding something with the given priority.
*/
public boolean canOverride(StatePriority priority) {
return value >= priority.value;
}
}
/** States mobs may be in. */
public static enum State {
// ground,canMove,canAct, priority
IDLE,
RUN,
SLIDE_FORWARD,
SLIDE_BACK,
CROUCH (true, false, true ),
JUMP_CROUCH (true, false, false, StatePriority.OCCUPIED ),
JUMP (false, true, true ),
FALL (false, true, true ),
LAND_CROUCH (true, false, false, StatePriority.OCCUPIED ),
BLOCK (true, true, false ),
DODGE_AIR (false, true, false, StatePriority.OCCUPIED ),
HITSTUN_GROUND (true, false, false, StatePriority.UNOVERRIDEABLE),
HITSTUN_AIR (false, false, false, StatePriority.UNOVERRIDEABLE),
SIDESTEP_BACK (true, false, false, StatePriority.OCCUPIED ),
SIDESTEP_FORWARD (true, false, false, StatePriority.OCCUPIED ),
DEAD (true, false, false, StatePriority.UNOVERRIDEABLE),
ATTACK_UP_GROUND (true, false, false, StatePriority.OCCUPIED ),
ATTACK_DOWN_GROUND (true, false, false, StatePriority.OCCUPIED ),
ATTACK_SIDE_GROUND (true, false, false, StatePriority.OCCUPIED ),
SPECIAL_UP_GROUND (true, false, false, StatePriority.OCCUPIED ),
SPECIAL_DOWN_GROUND(true, false, false, StatePriority.OCCUPIED ),
SPECIAL_SIDE_GROUND(true, false, false, StatePriority.OCCUPIED ),
ATTACK_UP_AIR (false, true, false, StatePriority.OCCUPIED ),
ATTACK_DOWN_AIR (false, true, false, StatePriority.OCCUPIED ),
ATTACK_SIDE_AIR (false, true, false, StatePriority.OCCUPIED ),
SPECIAL_UP_AIR (false, true, false, StatePriority.OCCUPIED ),
SPECIAL_DOWN_AIR (false, true, false, StatePriority.OCCUPIED ),
SPECIAL_SIDE_AIR (false, true, false, StatePriority.OCCUPIED );
/** Whether or not the state is a ground state. */
public final boolean ground;
/** Whether or not a mob can move while in the state. */
public final boolean canMove;
/** Whether or not a mob can perform an action while in the state. */
public final boolean canAct;
/** The priority required to change out of the state. */
public final StatePriority priority;
private State() {
this(true);
}
private State(boolean ground) {
this(ground, true, true);
}
private State(boolean ground, boolean canMove, boolean canAct) {
this(ground, canMove, canAct, StatePriority.ORDINARY);
}
private State(boolean ground, boolean canMove, boolean canAct, StatePriority priority) {
this.ground = ground;
this.canMove = canMove;
this.canAct = canAct;
this.priority = priority;
}
};
//--------------------==========--------------------
//-------------=====Member Variables=====-----------
//--------------------==========--------------------
/** Convenience reference to the entity */
public Entity e;
public boolean facingRight;
/** The mob's state. */
public State state = State.IDLE;
/** The number of ticks the mob has remained in its current state. */
public int stateTicks = 0;
/** The number of ticks the mob is locked in the state, unless overridden
* by a state of greater priority. */
public int stateLockDuration = 0;
/** The Mob's max health. */
public int maxHealth;
/** The Mob's health. */
public int health;
/** Whether or not the Mob is dead. */
public boolean dead = false;
public boolean invulnerable = false;
/** The number of ticks until the Mob loses its invulnerability. */
public int invulnerabilityTicks = 0;
/** Whether or not the Mob is currently attempting to move. */
public boolean moving = false;
/** Whether or not the Mob was on the ground at the end of the last tick. */
protected boolean wasOnGround = false;
// The mob's physical properties
/** Initial jump velocity. */
public float jumpVelocity;
/** Acceleration along the x-axis. */
public float acceleration;
/** How much of its horizontal acceleration an entity maintains while
* airborne. */
public float airAcceleration;
/** The entity's max speed. */
public float maxDx;
/** The pre-jump crouch duration, in ticks. */
public int jumpCrouchDuration;
/** Max number of jumps we can do. Set to 2 for double-jump, etc. */
public int maxJumpCount = 1;
/** Our jump count. */
public int jumpCount = 0;
// Visual things
protected ParticleEmitter<ParticleIndicator> srcDmgIndicator;
protected ParticleEmitter<ParticleSmoke> srcSmoke;
/** Whether or not the mob has a tint. */
public boolean hasTint = false;
/** The strength of the mob's 'effect tint'. */
public float tintStrength = 0.0f;
@Override
public void init(Entity e) {
this.e = e;
}
@Override
public void update(World w, Entity e, float dt) {
stateTicks++;
if(state == State.DEAD && stateTicks == DEATH_TICKS) {
srcSmoke.createCentredOutwardsBurst(w, 30, 1f, 7f, e);
e.destroy();
return;
}
if(state == State.JUMP_CROUCH && stateTicks == stateLockDuration)
doJump();
if(invulnerable && --invulnerabilityTicks == 0)
invulnerable = false;
if(hasTint) {
if(dead)
tintStrength *= 0.99f;
else
tintStrength -= 0.05f;
if(tintStrength <= 0)
hasTint = false;
}
wasOnGround = e.physics.onGround();
if(Math.abs(e.dx) < 0.001)
e.dx = 0f;
if(wasOnGround) {
if(moving) {
if((facingRight && e.dx > 0) || (!facingRight && e.dx < 0))
setState(State.RUN, true);
else
setState(State.SLIDE_BACK, true);
} else {
if(e.dx == 0f)
setState(State.IDLE, true);
else
if((facingRight && e.dx > 0) || (!facingRight && e.dx < 0))
setState(State.SLIDE_FORWARD, true);
else
setState(State.SLIDE_BACK, true);
}
} else {
if(e.dy > 0)
setState(State.JUMP, true);
else
setState(State.FALL, true);
}
moving = false;
}
protected void onVerticalCollision(World w, Entity e, ETileCollision ev) {
if(ev.dv < 0 && !wasOnGround) {
jumpCount = 0;
if(state.priority != StatePriority.UNOVERRIDEABLE) {
if(e.dy < -2*jumpVelocity) {
if(e.dy < -2.1*jumpVelocity)
damage(w, e, GeneralSource.fallDamage((int)((-e.dy-2*jumpVelocity) * 2)));
setState(State.LAND_CROUCH, true, 12);
} else
onLand();
}
}
}
protected void onLand() {
stateLockDuration = 0;
}
/**
* Restores the Mob to full health.
*/
public void restore() {
health = maxHealth;
}
// ----------Begin things to be called by the Mob's controller----------
/**
* Makes the Mob attempt to move in a direction. Its manner of movement is
* determined by its current state.
*
* @param direction The direction in which to move the Mob.
*/
public void move(Direction direction) {
if(!state.canMove)
return;
if(direction.hasHorizontalComponent()) {
float ddx = e.physics.onGround() ? acceleration : airAcceleration;
if(direction.hasRight())
e.dx += ddx;
else
e.dx -= ddx;
// in the future: modulate better than just setting a hard cap
if(e.dx > maxDx)
e.dx = maxDx;
else if(e.dx < -maxDx)
e.dx = -maxDx;
facingRight = direction.hasRight();
}
moving = true;
}
/**
* Commences a jump.
*
* <p>
* The Mob will not necessarily jump immediately; rather, it will enter
* the {@link State#JUMP_CROUCH JUMP_CROUCH} state, after which it will
* actually jump.
* </p>
*/
public void jump() {
if(e.physics.onGround() && state.ground && state.canAct)
setState(State.JUMP_CROUCH, true, jumpCrouchDuration);
else if(state.canAct)
doJump(); // straight to double-jump
}
protected void doJump() {
if(jumpCount >= maxJumpCount)
return;
setState(State.JUMP, false); // no need to validate -- checked elsewhere
jumpCount++;
doNthJump(jumpCount);
}
protected void doNthJump(int n) {
e.dy = jumpVelocity;
}
/**
* Attacks, if able, in a given direction.
*/
public abstract void attack(World w, Direction direction);
/**
* Performs a special attack, if able, in a given direction.
*/
public abstract void specialAttack(World w, Direction direction);
// ----------End things to be called by the mob's controller----------
@Override
public boolean damage(World w, Entity e, IDamageSource src) {
if((invulnerable && !src.type().bypassesInvulFrames) || dead)
return false;
src.applyEffects(e);
applyDamageReduction(src);
health -= src.damage();
e.dx = (e.dx + src.impulseX());
e.dy = (e.dy + src.impulseY());
ParticleIndicator p = srcDmgIndicator.createAlwaysAt(w,
srcDmgIndicator.dummyPos.set(e.pos, 0f, e.aabb.maxY()));
p.text = String.valueOf(src.damage());
p.orange = src.damage() == 0;
hasTint = true;
if(health <= 0) {
health = 0;
tintStrength = 0.6f;
kill(w, e, src);
} else {
tintStrength = 0.75f;
if(src.invincibilityFrames()) {
invulnerable = true;
invulnerabilityTicks = INVULNERABILITY_TICKS;
}
}
return true;
}
/**
* Applies damage reduction (e.g. due to armour) to the given incoming
* damage source. The default implementation does nothing and is intended
* to be overridden.
*/
protected void applyDamageReduction(IDamageSource src) {
}
/**
* Kills the mob by setting its state to {@link State#DEAD DEAD}.
*/
@Override
public void kill(World w, Entity e, IDamageSource src) {
if(e.post(w, EDamaged.killed(src))) {
dead = true;
setState(State.DEAD, false, DEATH_TICKS);
} else
health = 1; // some component doesn't want us dead!
}
protected void dropItem(World w, Entity e, Item item, int quantity, float chance) {
if(w.chance(chance)) {
Entity ei = Entities.item(w, item.stackOf(quantity));
ei.pos.set(e.pos);
w.addEntity(ei);
}
}
/**
* Gets the Mob's current state.
*
* @return The Mob's state.
*/
public State getState() {
return state;
}
/**
* Sets the Mob's state, which doesn't have a lock.
*
* @param state The new state.
* @param validatePriority Whether or not the priority of the new state
* should be checked before being set.
*/
public void setState(State state, boolean validatePriority) {
setState(state, validatePriority, 0);
}
/**
* Sets the Mob's state.
*
* @param state The new state.
* @param validatePriority Whether or not the priority of the new state
* should be checked before being set.
* @param stateLockDuration The number of ticks for which the mob is
* considered locked in the state.
*/
public void setState(State state, boolean validatePriority, int stateLockDuration) {
if(this.state == state || (validatePriority && stateTicks < this.stateLockDuration
&& !state.priority.canOverride(this.state.priority)))
return;
this.state = state;
this.stateLockDuration = stateLockDuration;
stateTicks = 0;
}
@Override
public boolean handle(World w, Entity e, EntityEvent ev) {
if(ev.type() == EntityEvent.Type.TILE_COLLISION_V)
onVerticalCollision(w, e, (ETileCollision)ev);
else if(ev.type() == EntityEvent.Type.ADDED_TO_WORLD) {
srcDmgIndicator = w.particleEmitter(ParticleIndicator.class);
srcSmoke = w.particleEmitter(ParticleSmoke.class);
} else if(ev.type() == EntityEvent.Type.DAMAGED)
damage(w, e, ((EDamaged)ev).src);
else if(ev.type() == Type.THROUGH_PORTAL_INTER)
this.e = e; // update our ref to e
return false;
}
@Override
public void importFromCompound(DataCompound c) {
facingRight = c.getBool("facingRight");
state = State.values()[c.getI32("state")];
stateTicks = c.getI32("stateTicks");
stateLockDuration = c.getI32("stateLockDuration");
maxHealth = c.getI32("maxHealth");
health = c.getI32("health");
dead = c.getBool("dead");
invulnerable = c.getBool("invul");
invulnerabilityTicks = c.getI32("invulTicks");
moving = c.getBool("moving");
jumpVelocity = c.getF32("jumpVelocity");
acceleration = c.getF32("acceleration");
airAcceleration = c.getF32("airAcceleration");
maxDx = c.getF32("maxDx");
jumpCrouchDuration = c.getI32("jumpCrouchDuration");
maxJumpCount = c.getI32("maxJumpCount");
jumpCount = c.getI32("jumpCount");
}
@Override
public void exportToCompound(DataCompound c) {
c.put("facingRight", facingRight);
c.put("state", state.ordinal());
c.put("stateTicks", stateTicks);
c.put("stateLockDuration", stateLockDuration);
c.put("maxHealth", maxHealth);
c.put("health", health);
c.put("dead", dead);
c.put("invul", invulnerable);
c.put("invulTicks", invulnerabilityTicks);
c.put("moving", moving);
c.put("jumpVelocity", jumpVelocity);
c.put("acceleration", acceleration);
c.put("airAcceleration", airAcceleration);
c.put("maxDx", maxDx);
c.put("jumpCrouchDuration", jumpCrouchDuration);
c.put("maxJumpCount", maxJumpCount);
c.put("jumpCount", jumpCount);
}
}
| |
package com.bernard.beaconportal.activities;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.widget.TextView;
public class EllipsizingTextView extends TextView {
private static final String ELLIPSIS = "\u2026";
private static final Pattern DEFAULT_END_PUNCTUATION = Pattern.compile(
"[\\.,\u2026;\\:\\s]*$", Pattern.DOTALL);
public interface EllipsizeListener {
void ellipsizeStateChanged(boolean ellipsized);
}
private final List<EllipsizeListener> ellipsizeListeners = new ArrayList<EllipsizeListener>();
private boolean isEllipsized;
private boolean isStale;
private boolean programmaticChange;
private String fullText;
private int maxLines;
private float lineSpacingMultiplier = 1.0f;
private float lineAdditionalVerticalPadding = 0.0f;
/**
* The end punctuation which will be removed when appending #ELLIPSIS.
*/
private Pattern endPunctuationPattern;
public EllipsizingTextView(Context context) {
this(context, null);
}
public EllipsizingTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EllipsizingTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
super.setEllipsize(null);
TypedArray a = context.obtainStyledAttributes(attrs,
new int[] { android.R.attr.maxLines });
setMaxLines(a.getInt(0, Integer.MAX_VALUE));
a.recycle();
setEndPunctuationPattern(DEFAULT_END_PUNCTUATION);
}
public void setEndPunctuationPattern(Pattern pattern) {
this.endPunctuationPattern = pattern;
}
public void addEllipsizeListener(EllipsizeListener listener) {
if (listener == null) {
throw new NullPointerException();
}
ellipsizeListeners.add(listener);
}
public void removeEllipsizeListener(EllipsizeListener listener) {
ellipsizeListeners.remove(listener);
}
public boolean isEllipsized() {
return isEllipsized;
}
@Override
public void setMaxLines(int maxLines) {
super.setMaxLines(maxLines);
this.maxLines = maxLines;
isStale = true;
}
@Override
@SuppressLint("Override")
public int getMaxLines() {
return maxLines;
}
public boolean ellipsizingLastFullyVisibleLine() {
return maxLines == Integer.MAX_VALUE;
}
@Override
public void setLineSpacing(float add, float mult) {
this.lineAdditionalVerticalPadding = add;
this.lineSpacingMultiplier = mult;
super.setLineSpacing(add, mult);
}
@Override
protected void onTextChanged(CharSequence text, int start, int before,
int after) {
super.onTextChanged(text, start, before, after);
if (!programmaticChange) {
fullText = text.toString();
isStale = true;
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (ellipsizingLastFullyVisibleLine()) {
isStale = true;
}
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
super.setPadding(left, top, right, bottom);
if (ellipsizingLastFullyVisibleLine()) {
isStale = true;
}
}
@Override
protected void onDraw(Canvas canvas) {
if (isStale) {
resetText();
}
super.onDraw(canvas);
}
private void resetText() {
String workingText = fullText;
boolean ellipsized = false;
Layout layout = createWorkingLayout(workingText);
int linesCount = getLinesCount();
if (layout.getLineCount() > linesCount) {
// We have more lines of text than we are allowed to display.
workingText = fullText.substring(0,
layout.getLineEnd(linesCount - 1)).trim();
while (createWorkingLayout(workingText + ELLIPSIS).getLineCount() > linesCount) {
int lastSpace = workingText.lastIndexOf(' ');
if (lastSpace == -1) {
break;
}
workingText = workingText.substring(0, lastSpace);
}
// We should do this in the loop above, but it's cheaper this way.
workingText = endPunctuationPattern.matcher(workingText)
.replaceFirst("");
workingText = workingText + ELLIPSIS;
ellipsized = true;
}
if (!workingText.equals(getText())) {
programmaticChange = true;
try {
setText(workingText);
} finally {
programmaticChange = false;
}
}
isStale = false;
if (ellipsized != isEllipsized) {
isEllipsized = ellipsized;
for (EllipsizeListener listener : ellipsizeListeners) {
listener.ellipsizeStateChanged(ellipsized);
}
}
}
/**
* Get how many lines of text we are allowed to display.
*/
private int getLinesCount() {
if (ellipsizingLastFullyVisibleLine()) {
int fullyVisibleLinesCount = getFullyVisibleLinesCount();
if (fullyVisibleLinesCount == -1) {
return 1;
} else {
return fullyVisibleLinesCount;
}
} else {
return maxLines;
}
}
/**
* Get how many lines of text we can display so their full height is
* visible.
*/
private int getFullyVisibleLinesCount() {
Layout layout = createWorkingLayout("");
int height = getHeight() - getPaddingTop() - getPaddingBottom();
int lineHeight = layout.getLineBottom(0);
return height / lineHeight;
}
private Layout createWorkingLayout(String workingText) {
return new StaticLayout(workingText, getPaint(), getWidth()
- getPaddingLeft() - getPaddingRight(), Alignment.ALIGN_NORMAL,
lineSpacingMultiplier, lineAdditionalVerticalPadding, false /* includepad */);
}
@Override
public void setEllipsize(TruncateAt where) {
// Ellipsize settings are not respected
}
}
| |
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.schedassist.portlet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.property.Location;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.schedassist.ConflictExistsException;
import org.jasig.schedassist.NoAppointmentExistsException;
import org.jasig.schedassist.RelationshipDao;
import org.jasig.schedassist.SchedulingAssistantService;
import org.jasig.schedassist.SchedulingException;
import org.jasig.schedassist.messaging.AvailableBlockElement;
import org.jasig.schedassist.messaging.AvailableStatusType;
import org.jasig.schedassist.messaging.CancelAppointmentRequest;
import org.jasig.schedassist.messaging.CancelAppointmentResponse;
import org.jasig.schedassist.messaging.CreateAppointmentRequest;
import org.jasig.schedassist.messaging.CreateAppointmentResponse;
import org.jasig.schedassist.messaging.GetRelationshipsRequest;
import org.jasig.schedassist.messaging.GetRelationshipsResponse;
import org.jasig.schedassist.messaging.GetTargetAvailableBlockRequest;
import org.jasig.schedassist.messaging.GetTargetAvailableBlockResponse;
import org.jasig.schedassist.messaging.IsEligibleRequest;
import org.jasig.schedassist.messaging.IsEligibleResponse;
import org.jasig.schedassist.messaging.RelationshipElement;
import org.jasig.schedassist.messaging.ScheduleOwnerElement;
import org.jasig.schedassist.messaging.VisibleScheduleRequest;
import org.jasig.schedassist.messaging.VisibleScheduleResponse;
import org.jasig.schedassist.messaging.VisitorConflictsRequest;
import org.jasig.schedassist.messaging.VisitorConflictsResponse;
import org.jasig.schedassist.messaging.XMLDataUtils;
import org.jasig.schedassist.model.AvailableBlock;
import org.jasig.schedassist.model.AvailableBlockBuilder;
import org.jasig.schedassist.model.IScheduleOwner;
import org.jasig.schedassist.model.IScheduleVisitor;
import org.jasig.schedassist.model.MeetingDurations;
import org.jasig.schedassist.model.Relationship;
import org.jasig.schedassist.model.VisibleSchedule;
import org.springframework.ws.soap.client.SoapFaultClientException;
/**
* Mimics {@link SchedulingAssistantService} and {@link RelationshipDao}, however {@link IScheduleOwner}
* and {@link IScheduleVisitor} arguments are replaced with {@link String}s containing solely the username.
*
* @author Nicholas Blair, nblair@doit.wisc.edu
* @version $Id: PortletAvailableServiceImpl.java 3024 2011-02-01 19:25:08Z npblair $
*/
public final class PortletSchedulingAssistantServiceImpl extends WebServicesDaoSupport implements PortletSchedulingAssistantService {
private Log LOG = LogFactory.getLog(this.getClass());
public static final String CONFLICT_MESSAGE = "conflict exists";
public static final String TIME_NOT_AVAILABLE_MESSAGE = "time not available";
public static final String CANCEL_FAILED_MESSAGE = "Appointment no longer exists";
/*
* (non-Javadoc)
* @see org.jasig.schedassist.portlet.PortletSchedulingAssistantService#isEligible(java.lang.String)
*/
@Override
public boolean isEligible(String visitorUsername) {
IsEligibleRequest request = new IsEligibleRequest();
request.setVisitorNetid(visitorUsername);
if(LOG.isDebugEnabled()) {
LOG.debug("sending isEligible request for " + visitorUsername);
}
IsEligibleResponse response = (IsEligibleResponse) this.doSendAndReceive(request);
if(LOG.isDebugEnabled()) {
LOG.debug("isEligible for " + visitorUsername + " returns " + response.isEligible());
}
return response.isEligible();
}
/*
* (non-Javadoc)
* @see org.jasig.schedassist.portlet.PortletSchedulingAssistantService#cancelAppointment(java.lang.String, long, org.jasig.schedassist.model.AvailableBlock, java.lang.String)
*/
public EventCancellation cancelAppointment(final String visitorUsername, final long ownerId,
final AvailableBlock block, final String cancelReason) throws SchedulingException {
if(LOG.isDebugEnabled()) {
LOG.debug("sending cancelAppointment request, visitor: " + visitorUsername + ", owner: " + ownerId + ", block: " + block);
}
CancelAppointmentRequest request = new CancelAppointmentRequest();
request.setEndTime(XMLDataUtils.convertDateToXMLGregorianCalendar(block.getEndTime()));
request.setOwnerId(ownerId);
request.setStartTime(XMLDataUtils.convertDateToXMLGregorianCalendar(block.getStartTime()));
request.setVisitorNetid(visitorUsername);
request.setReason(cancelReason);
try {
CancelAppointmentResponse response = (CancelAppointmentResponse) this.doSendAndReceive(request);
LOG.debug("cancelAppointment success");
EventCancellation result = new EventCancellation(
XMLDataUtils.convertXMLGregorianCalendarToDate(response.getStartTime()),
XMLDataUtils.convertXMLGregorianCalendarToDate(response.getEndTime()));
return result;
} catch (SoapFaultClientException e) {
if(CANCEL_FAILED_MESSAGE.equals(e.getFaultStringOrReason())) {
LOG.info("cancelAppointment request for visitor " + visitorUsername + " and owner " + ownerId + " failed since appointment no longer exists");
throw new NoAppointmentExistsException(CANCEL_FAILED_MESSAGE, e);
} else {
LOG.error("cancelAppointment request for visitor " + visitorUsername + " and owner " + ownerId + " failed with SoapFaultClientException", e);
throw new SchedulingException(e);
}
}
}
/*
* (non-Javadoc)
* @see org.jasig.schedassist.portlet.PortletSchedulingAssistantService#getVisibleSchedule(java.lang.String, long)
*/
@Override
public VisibleSchedule getVisibleSchedule(final String visitorUsername,
final long ownerId) {
return getVisibleSchedule(visitorUsername, ownerId, 1);
}
/*
* (non-Javadoc)
* @see org.jasig.schedassist.portlet.PortletSchedulingAssistantService#getVisibleSchedule(java.lang.String, long, int)
*/
@Override
public VisibleSchedule getVisibleSchedule(String visitorUsername,
long ownerId, int weekStart) {
if(LOG.isDebugEnabled()) {
LOG.debug("sending getVisibleSchedule request, visitor: " + visitorUsername + ", owner: " + ownerId);
}
VisibleScheduleRequest request = new VisibleScheduleRequest();
request.setOwnerId(ownerId);
request.setVisitorNetid(visitorUsername);
request.setWeekStart(weekStart);
if(LOG.isDebugEnabled()) {
LOG.debug(request);
}
VisibleScheduleResponse response = (VisibleScheduleResponse) this.doSendAndReceive(request);
MeetingDurations durations = MeetingDurations.fromKey(response.getOwnerMeetingDurationsPreference().getValue());
VisibleSchedule result = new VisibleSchedule(durations);
List<AvailableBlockElement> blockElements = response.getAvailableBlockList().getAvailableBlockElement();
for(AvailableBlockElement blockElement : blockElements) {
AvailableStatusType status = blockElement.getStatus();
AvailableBlock block = AvailableBlockBuilder.createBlock(
blockElement.getStartTime().toGregorianCalendar().getTime(),
blockElement.getEndTime().toGregorianCalendar().getTime(),
blockElement.getVisitorLimit());
block.setVisitorsAttending(blockElement.getVisitorsAttending());
// first add the block as a freeblock
result.addFreeBlock(block);
// then add with it's true status
switch (status) {
case ATTENDING:
result.setAttendingBlock(block);
break;
case BUSY:
result.setBusyBlock(block);
break;
}
}
return result;
}
/*
* (non-Javadoc)
* @see org.jasig.schedassist.portlet.PortletSchedulingAssistantService#calculateVisitorConflicts(java.lang.String, long, int)
*/
@Override
public List<AvailableBlock> calculateVisitorConflicts(
String visitorUsername, long ownerId, int weekStart) {
if(LOG.isDebugEnabled()) {
LOG.debug("calculateVisitorConflicts, visitor: " + visitorUsername + ", owner: " + ownerId);
}
VisitorConflictsRequest request = new VisitorConflictsRequest();
request.setOwnerId(ownerId);
request.setVisitorNetid(visitorUsername);
request.setWeekStart(weekStart);
if(LOG.isDebugEnabled()) {
LOG.debug(request);
}
VisitorConflictsResponse response = (VisitorConflictsResponse) this.doSendAndReceive(request);
List<AvailableBlockElement> blockElements = response.getAvailableBlockList().getAvailableBlockElement();
List<AvailableBlock> results = new ArrayList<AvailableBlock>();
for(AvailableBlockElement blockElement : blockElements) {
AvailableBlock block = AvailableBlockBuilder.createBlock(
blockElement.getStartTime().toGregorianCalendar().getTime(),
blockElement.getEndTime().toGregorianCalendar().getTime());
results.add(block);
}
if(LOG.isDebugEnabled()) {
LOG.debug("calculateVisitorConflicts result has " + results.size() + " elements");
}
return results;
}
/*
* (non-Javadoc)
* @see org.jasig.schedassist.portlet.PortletSchedulingAssistantService#getTargetBlock(org.jasig.schedassist.model.IScheduleOwner, java.util.Date)
*/
@Override
public AvailableBlock getTargetBlock(IScheduleOwner owner, Date startTime) {
return getTargetBlockInternal(owner, startTime, false);
}
/*
* (non-Javadoc)
* @see org.jasig.schedassist.portlet.PortletSchedulingAssistantService#getTargetDoubleLengthBlock(org.jasig.schedassist.model.IScheduleOwner, java.util.Date)
*/
@Override
public AvailableBlock getTargetDoubleLengthBlock(IScheduleOwner owner,
Date startTime) {
return getTargetBlockInternal(owner, startTime, true);
}
/**
*
* @param owner
* @param startTime
* @param doubleLength
* @return
*/
protected AvailableBlock getTargetBlockInternal(IScheduleOwner owner,
Date startTime, boolean doubleLength) {
GetTargetAvailableBlockRequest request = new GetTargetAvailableBlockRequest();
request.setOwnerId(owner.getId());
request.setDoubleLength(doubleLength);
request.setStartTime(XMLDataUtils.convertDateToXMLGregorianCalendar(startTime));
//GetTargetAvailableBlockResponse response = (GetTargetAvailableBlockResponse) this.webServiceTemplate.marshalSendAndReceive(request);
GetTargetAvailableBlockResponse response = (GetTargetAvailableBlockResponse) this.doSendAndReceive(request);
if(null == response.getAvailableBlockElement()) {
return null;
} else {
AvailableBlock result = convertAvailableBlockElement(response.getAvailableBlockElement());
return result;
}
}
/*
* (non-Javadoc)
* @see org.jasig.schedassist.portlet.PortletSchedulingAssistantService#scheduleAppointment(java.lang.String, long, org.jasig.schedassist.model.AvailableBlock, java.lang.String)
*/
@Override
public VEvent scheduleAppointment(final String visitorUsername,
final long ownerId, final AvailableBlock block, final String eventDescription)
throws SchedulingException {
LOG.debug("scheduleAppointment called; visitor: " + visitorUsername + ", owner: " + ownerId + ", block: " + block);
CreateAppointmentRequest request = new CreateAppointmentRequest();
request.setSelectedDuration(block.getDurationInMinutes());
request.setEventDescription(eventDescription);
request.setOwnerId(ownerId);
request.setStartTime(XMLDataUtils.convertDateToXMLGregorianCalendar(block.getStartTime()));
request.setVisitorNetid(visitorUsername);
try {
//CreateAppointmentResponse response = (CreateAppointmentResponse) webServiceTemplate.marshalSendAndReceive(request);
CreateAppointmentResponse response = (CreateAppointmentResponse) this.doSendAndReceive(request);
if(null == response) {
LOG.error("response was null!");
}
LOG.debug("received response; start: " + response.getStartTime() + ", end: " + response.getEndTime() + ", location: " + response.getEventLocation() + ", title: " + response.getEventTitle());
VEvent vevent = new VEvent(
new DateTime(response.getStartTime().toGregorianCalendar().getTime()),
new DateTime(response.getEndTime().toGregorianCalendar().getTime()),
response.getEventTitle());
Location location = new Location(response.getEventLocation());
vevent.getProperties().add(location);
LOG.debug("scheduleAppointment success");
return vevent;
} catch (SoapFaultClientException e) {
LOG.error("caught SOAP Fault in scheduleAppointment: ", e);
if(e.getFaultStringOrReason().contains(CONFLICT_MESSAGE) || e.getFaultStringOrReason().contains(TIME_NOT_AVAILABLE_MESSAGE)) {
throw new ConflictExistsException("a conflict exists for " + block, e);
} else {
throw e;
}
}
}
/*
* (non-Javadoc)
* @see org.jasig.schedassist.portlet.PortletSchedulingAssistantService#relationshipsForVisitor(java.lang.String)
*/
@Override
public List<Relationship> relationshipsForVisitor(final String visitorUsername) {
LOG.debug("relationshipsForVisitor, visitor: " + visitorUsername);
List<Relationship> result = new ArrayList<Relationship>();
GetRelationshipsRequest request = new GetRelationshipsRequest();
request.setVisitorNetid(visitorUsername);
GetRelationshipsResponse response = (GetRelationshipsResponse) this.doSendAndReceive(request);
LOG.debug("getRelationships response received");
List<RelationshipElement> relationshipElements = response.getRelationshipList().getRelationshipElement();
LOG.debug("getRelationships response received with size " + relationshipElements.size());
for(RelationshipElement relationshipElement : relationshipElements) {
IScheduleOwner owner = convertOwnerElement(relationshipElement.getScheduleOwnerElement());
LOG.debug("-> " + visitorUsername + ", " + owner.getCalendarAccount().getUsername());
Relationship relationship = new Relationship();
relationship.setDescription(relationshipElement.getDescription());
relationship.setOwner(owner);
result.add(relationship);
}
return result;
}
/**
* Convert a {@link ScheduleOwnerElement} into an {@link IScheduleOwner}.
*
* @param element
* @return
*/
protected static IScheduleOwner convertOwnerElement(ScheduleOwnerElement element) {
PortletScheduleOwnerImpl owner = new PortletScheduleOwnerImpl(element);
return owner;
}
/**
* Convert a {@link AvailableBlockElement} into a {@link AvailableBlock}.
*
* @param element
* @return
*/
protected static AvailableBlock convertAvailableBlockElement(AvailableBlockElement element) {
Date startTime = XMLDataUtils.convertXMLGregorianCalendarToDate(element.getStartTime());
Date endTime = XMLDataUtils.convertXMLGregorianCalendarToDate(element.getEndTime());
AvailableBlock result = AvailableBlockBuilder.createBlock(startTime, endTime, element.getVisitorLimit());
result.setVisitorsAttending(element.getVisitorsAttending());
return result;
}
}
| |
/*
* Copyright (C) 2012 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*/
package gov.nasa.worldwindx.examples;
import gov.nasa.worldwind.*;
import gov.nasa.worldwind.avlist.*;
import gov.nasa.worldwind.event.*;
import gov.nasa.worldwindx.examples.util.*;
import gov.nasa.worldwind.formats.gcps.GCPSReader;
import gov.nasa.worldwind.formats.tab.TABRasterReader;
import gov.nasa.worldwind.formats.worldfile.WorldFile;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.layers.RenderableLayer;
import gov.nasa.worldwind.pick.PickedObject;
import gov.nasa.worldwind.render.SurfaceImage;
import gov.nasa.worldwind.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.Box;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.File;
import java.util.ArrayList;
/**
* Demonstrates the use of the {@link gov.nasa.worldwind.render.SurfaceImage} class to create a "rubber sheet" image
* that can be arbitrarily positioned, scaled and warped on the globe's surface using control points at the image's four
* corners.
*
* @author tag
* @version $Id: RubberSheetImage.java 1171 2013-02-11 21:45:02Z dcollins $
*/
public class RubberSheetImage extends ApplicationTemplate
{
public static final String OPEN_IMAGE_FILE = "OpenImageFile";
public static final String SET_IMAGE_OPACITY = "SetImageOpacity";
public static final String TOGGLE_EDITING = "ToggleEditing";
public static class AppFrame extends ApplicationTemplate.AppFrame implements ActionListener
{
private Controller controller;
public AppFrame()
{
this.controller = new Controller(this);
this.getWwd().addSelectListener(this.controller);
this.initComponents();
}
private void initComponents()
{
Box controlBox = Box.createVerticalBox();
controlBox.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // top, left, bottom, right
{
JButton openFileButton = new JButton("Open Image File...");
openFileButton.setActionCommand(OPEN_IMAGE_FILE);
openFileButton.setAlignmentX(JComponent.LEFT_ALIGNMENT);
openFileButton.addActionListener(this);
controlBox.add(openFileButton);
controlBox.add(Box.createVerticalStrut(10));
JCheckBox toggleEditBox = new JCheckBox("Enable Editing", true);
toggleEditBox.setActionCommand(TOGGLE_EDITING);
toggleEditBox.setAlignmentX(JComponent.LEFT_ALIGNMENT);
toggleEditBox.addActionListener(this);
controlBox.add(toggleEditBox);
controlBox.add(Box.createVerticalStrut(10));
JLabel label = new JLabel("Opacity");
JSlider slider = new JSlider(0, 100, 100);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent event)
{
ActionEvent actionEvent = new ActionEvent(event.getSource(), 0, SET_IMAGE_OPACITY);
AppFrame.this.actionPerformed(actionEvent);
}
});
Box box = Box.createHorizontalBox();
box.setAlignmentX(JComponent.LEFT_ALIGNMENT);
box.add(label);
box.add(slider);
controlBox.add(box);
controlBox.add(Box.createVerticalGlue());
}
this.getLayerPanel().add(controlBox, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
if (e == null)
return;
if (this.controller == null)
return;
this.controller.actionPerformed(e);
}
}
public static class SurfaceImageEntry
{
private SurfaceImage surfaceImage;
private SurfaceImageEditor editor;
private RenderableLayer layer;
public SurfaceImageEntry(WorldWindow wwd, SurfaceImage surfaceImage, String name)
{
this.surfaceImage = surfaceImage;
this.editor = new SurfaceImageEditor(wwd, surfaceImage);
this.layer = new RenderableLayer();
this.layer.setName(name);
this.layer.setPickEnabled(true);
this.layer.addRenderable(surfaceImage);
insertBeforePlacenames(wwd, this.layer);
}
public SurfaceImage getSurfaceImage()
{
return this.surfaceImage;
}
public SurfaceImageEditor getEditor()
{
return this.editor;
}
public RenderableLayer getLayer()
{
return this.layer;
}
}
public static class Controller implements ActionListener, SelectListener
{
private AppFrame appFrame;
private JFileChooser openFileChooser;
private boolean isEditingEnabled = true;
private ArrayList<SurfaceImageEntry> entryList = new ArrayList<SurfaceImageEntry>();
public Controller(AppFrame appFrame)
{
this.appFrame = appFrame;
}
@SuppressWarnings( {"StringEquality"})
public void actionPerformed(ActionEvent event)
{
String actionCommand = event.getActionCommand();
if (WWUtil.isEmpty(actionCommand))
return;
if (actionCommand == OPEN_IMAGE_FILE)
{
this.doOpenImageFile();
}
else if (actionCommand == SET_IMAGE_OPACITY)
{
JSlider slider = (JSlider) event.getSource();
this.doSetImageOpacity(slider.getValue() / 100.0);
}
else if (actionCommand == TOGGLE_EDITING)
{
AbstractButton button = (AbstractButton) event.getSource();
this.enableEditing(button.isSelected());
}
}
public void selected(SelectEvent e)
{
PickedObject topObject = e.getTopPickedObject();
if (e.getEventAction().equals(SelectEvent.LEFT_PRESS))
{
if (topObject != null && !topObject.isTerrain() && topObject.getObject() instanceof SurfaceImage)
{
SurfaceImageEntry entry = this.getEntryFor((SurfaceImage) topObject.getObject());
if (entry != null)
{
this.setSelectedEntry(entry);
}
}
}
}
protected void enableEditing(boolean enable)
{
this.isEditingEnabled = enable;
for (SurfaceImageEntry entry : this.entryList)
{
entry.getLayer().setPickEnabled(enable);
if (!enable)
{
entry.getEditor().setArmed(false);
}
}
}
protected void addSurfaceImage(SurfaceImage surfaceImage, String name)
{
SurfaceImageEntry entry = new SurfaceImageEntry(this.appFrame.getWwd(), surfaceImage, name);
this.entryList.add(entry);
this.setSelectedEntry(entry);
entry.getLayer().setPickEnabled(this.isEditingEnabled);
if (!this.isEditingEnabled)
{
entry.getEditor().setArmed(false);
}
this.appFrame.getLayerPanel().update(this.appFrame.getWwd());
}
protected SurfaceImageEntry getEntryFor(SurfaceImage surfaceImage)
{
for (SurfaceImageEntry entry : this.entryList)
{
if (entry.getSurfaceImage() == surfaceImage)
{
return entry;
}
}
return null;
}
protected void setSelectedEntry(SurfaceImageEntry selected)
{
for (SurfaceImageEntry entry : this.entryList)
{
if (entry != selected)
{
if (entry.getEditor().isArmed())
{
entry.getEditor().setArmed(false);
}
}
}
if (!selected.getEditor().isArmed())
{
selected.getEditor().setArmed(true);
}
}
protected void doOpenImageFile()
{
if (this.openFileChooser == null)
{
this.openFileChooser = new JFileChooser(Configuration.getUserHomeDirectory());
this.openFileChooser.setAcceptAllFileFilterUsed(false);
this.openFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
this.openFileChooser.setMultiSelectionEnabled(true);
this.openFileChooser.addChoosableFileFilter(
new FileNameExtensionFilter("Images", ImageIO.getReaderFormatNames()));
}
int retVal = this.openFileChooser.showOpenDialog(this.appFrame);
if (retVal != JFileChooser.APPROVE_OPTION)
return;
File[] files = this.openFileChooser.getSelectedFiles();
this.loadFiles(files);
}
protected void doSetImageOpacity(double opacity)
{
for (SurfaceImageEntry entry : this.entryList)
{
entry.getSurfaceImage().setOpacity(opacity);
}
this.appFrame.getWwd().redraw();
}
protected void loadFiles(final File[] files)
{
this.appFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Thread thread = new Thread(new Runnable()
{
public void run()
{
for (File f : files)
{
loadFile(f);
}
appFrame.setCursor(null);
}
});
thread.start();
}
protected void loadFile(final File file)
{
final BufferedImage image = this.readImage(file);
if (image == null)
return;
final SurfaceImage si = this.createGeoreferencedSurfaceImage(file, image);
if (si == null)
{
this.addNonGeoreferencedSurfaceImage(file, image, this.appFrame.getWwd());
return;
}
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
addSurfaceImage(si, file.getName());
}
});
}
protected BufferedImage readImage(File file)
{
try
{
return ImageIO.read(file);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
protected SurfaceImage createGeoreferencedSurfaceImage(File file, BufferedImage image)
{
try
{
SurfaceImage si = null;
File tabFile = this.getAssociatedTABFile(file);
if (tabFile != null)
si = this.createSurfaceImageFromTABFile(image, tabFile);
if (si == null)
{
File gcpsFile = this.getAssociatedGCPSFile(file);
if (gcpsFile != null)
si = this.createSurfaceImageFromGCPSFile(image, gcpsFile);
}
if (si == null)
{
File[] worldFiles = this.getAssociatedWorldFiles(file);
if (worldFiles != null)
si = this.createSurfaceImageFromWorldFiles(image, worldFiles);
}
return si;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public File getAssociatedTABFile(File file)
{
File tabFile = TABRasterReader.getTABFileFor(file);
if (tabFile != null && tabFile.exists())
{
TABRasterReader reader = new TABRasterReader();
if (reader.canRead(tabFile))
return tabFile;
}
return null;
}
public File getAssociatedGCPSFile(File file)
{
File gcpsFile = GCPSReader.getGCPSFileFor(file);
if (gcpsFile != null && gcpsFile.exists())
{
GCPSReader reader = new GCPSReader();
if (reader.canRead(gcpsFile))
return gcpsFile;
}
return null;
}
public File[] getAssociatedWorldFiles(File file)
{
try
{
File[] worldFiles = WorldFile.getWorldFiles(file);
if (worldFiles != null && worldFiles.length > 0)
return worldFiles;
}
catch (Exception ignored)
{
}
return null;
}
protected SurfaceImage createSurfaceImageFromWorldFiles(BufferedImage image, File[] worldFiles)
throws java.io.IOException
{
AVList worldFileParams = new AVListImpl();
WorldFile.decodeWorldFiles(worldFiles, worldFileParams);
BufferedImage alignedImage = createPowerOfTwoImage(image.getWidth(), image.getHeight());
Sector sector = ImageUtil.warpImageWithWorldFile(image, worldFileParams, alignedImage);
return new SurfaceImage(alignedImage, sector);
}
protected SurfaceImage createSurfaceImageFromTABFile(BufferedImage image, File tabFile)
throws java.io.IOException
{
TABRasterReader reader = new TABRasterReader();
RasterControlPointList controlPoints = reader.read(tabFile);
return this.createSurfaceImageFromControlPoints(image, controlPoints);
}
protected SurfaceImage createSurfaceImageFromGCPSFile(BufferedImage image, File gcpsFile)
throws java.io.IOException
{
GCPSReader reader = new GCPSReader();
RasterControlPointList controlPoints = reader.read(gcpsFile);
return this.createSurfaceImageFromControlPoints(image, controlPoints);
}
protected SurfaceImage createSurfaceImageFromControlPoints(BufferedImage image,
RasterControlPointList controlPoints) throws java.io.IOException
{
int numControlPoints = controlPoints.size();
Point2D[] imagePoints = new Point2D[numControlPoints];
LatLon[] geoPoints = new LatLon[numControlPoints];
for (int i = 0; i < numControlPoints; i++)
{
RasterControlPointList.ControlPoint p = controlPoints.get(i);
imagePoints[i] = p.getRasterPoint();
geoPoints[i] = p.getWorldPointAsLatLon();
}
BufferedImage destImage = createPowerOfTwoImage(image.getWidth(), image.getHeight());
Sector sector = ImageUtil.warpImageWithControlPoints(image, imagePoints, geoPoints, destImage);
return new SurfaceImage(destImage, sector);
}
protected void addNonGeoreferencedSurfaceImage(final File file, final BufferedImage image,
final WorldWindow wwd)
{
if (!SwingUtilities.isEventDispatchThread())
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
addNonGeoreferencedSurfaceImage(file, image, wwd);
}
});
}
else
{
StringBuilder message = new StringBuilder();
message.append("Unable to find geographic coordinates for: ");
message.append("\"").append(file.getPath()).append("\"");
message.append("\n");
message.append("Open image anyway?");
int retVal = JOptionPane.showConfirmDialog(this.appFrame, message, null, JOptionPane.YES_NO_OPTION);
if (retVal != JOptionPane.YES_OPTION)
return;
Position position = ShapeUtils.getNewShapePosition(wwd);
double lat = position.getLatitude().radians;
double lon = position.getLongitude().radians;
double sizeInMeters = ShapeUtils.getViewportScaleFactor(wwd);
double arcLength = sizeInMeters / wwd.getModel().getGlobe().getRadiusAt(position);
Sector sector = Sector.fromRadians(lat - arcLength, lat + arcLength, lon - arcLength, lon + arcLength);
BufferedImage powerOfTwoImage = createPowerOfTwoScaledCopy(image);
this.addSurfaceImage(new SurfaceImage(powerOfTwoImage, sector), file.getName());
}
}
}
protected static BufferedImage createPowerOfTwoImage(int minWidth, int minHeight)
{
return new BufferedImage(WWMath.powerOfTwoCeiling(minWidth), WWMath.powerOfTwoCeiling(minHeight),
BufferedImage.TYPE_INT_ARGB);
}
protected static BufferedImage createPowerOfTwoScaledCopy(BufferedImage image)
{
if (WWMath.isPowerOfTwo(image.getWidth()) && WWMath.isPowerOfTwo(image.getHeight()))
return image;
BufferedImage powerOfTwoImage = createPowerOfTwoImage(image.getWidth(), image.getHeight());
ImageUtil.getScaledCopy(image, powerOfTwoImage);
return powerOfTwoImage;
}
public static void main(String[] args)
{
ApplicationTemplate.start("World Wind Rubber Sheet Image", RubberSheetImage.AppFrame.class);
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2001-2015 Aspose Pty Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.aspose.examples;
import com.aspose.utils.AsposeConstants;
import com.aspose.utils.AsposeJavaAPI;
import com.aspose.utils.AsposeMavenProjectManager;
import com.aspose.utils.FormatExamples;
import com.aspose.utils.execution.ModalTaskImpl;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.treeStructure.Tree;
import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.io.File;
import java.util.*;
/**
* Created by Adeel Ilyas on 9/9/2015.
*/
public final class AsposeExamplePanel extends JPanel {
AsposeExampleDialog dialog;
/**
* Creates new form AsposeExamplePanel
*/
public AsposeExamplePanel(AsposeExampleDialog dialog) {
initComponents();
initComponentsUser();
this.dialog = dialog;
}
private void initComponentsUser() {
CustomMutableTreeNode top = new CustomMutableTreeNode("");
read();
validateDialog();
}
@Override
public String getName() {
return AsposeConstants.API_NAME + " for Java API and Examples";
}
private void initComponents() {
ResourceBundle bundle = ResourceBundle.getBundle("Bundle");
jPanel1 = new JPanel();
jLabel2 = new JLabel();
componentSelection = new ComboBox();
jLabel1 = new JLabel();
jLabelMessage = new JLabel();
jLabelMessage.setOpaque(true);
jScrollPane1 = new JBScrollPane();
examplesTree = new Tree();
jPanel1.setBackground(new Color(255, 255, 255));
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setForeground(new Color(255, 255, 255));
jLabel2.setIcon(icon); // NOI18N
jLabel2.setText("");
jLabel2.setHorizontalAlignment(SwingConstants.CENTER);
jLabel2.setDoubleBuffered(true);
jLabel2.setOpaque(true);
jLabel2.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
jLabel2ComponentResized(evt);
}
});
GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup()
.addComponent(jLabel2, GroupLayout.PREFERRED_SIZE, 390, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(0, 0, Short.MAX_VALUE))
);
componentSelection.setModel(new DefaultComboBoxModel());
componentSelection.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
componentSelection_Propertychanged(evt);
}
});
jLabel1.setText(bundle.getString("AsposeExample.jLabel1_text"));
jLabelMessage.setText("");
examplesTree.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
examplesTree_clicked(evt);
}
});
jScrollPane1.setViewportView(examplesTree);
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(componentSelection, GroupLayout.PREFERRED_SIZE, 198, GroupLayout.PREFERRED_SIZE))
.addComponent(jLabelMessage, GroupLayout.PREFERRED_SIZE, 361, GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(componentSelection, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 229, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelMessage, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE))
);
}
//=========================================================================
private void jLabel2ComponentResized(java.awt.event.ComponentEvent evt) {
int labelwidth = jLabel2.getWidth();
int labelheight = jLabel2.getHeight();
Image img = icon.getImage();
jLabel2.setIcon(new ImageIcon(img.getScaledInstance(labelwidth, labelheight, Image.SCALE_FAST)));
}
public String getSelectedProjectRootPath() {
return AsposeMavenProjectManager.getInstance().getProjectHandle().getBasePath();
}
//=========================================================================
void read() {
AsposeConstants.println(" === New File Visual Panel.read() === " + AsposeMavenProjectManager.getInstance().getProjectHandle().getBaseDir().getName());
retrieveAPIDependency();
retrieveAPIExamples();
}
//=========================================================================
private boolean retrieveAPIDependency() {
getComponentSelection().removeAllItems();
String versionNo = AsposeMavenProjectManager.getInstance().getDependencyVersionFromPOM(AsposeConstants.API_MAVEN_DEPENDENCY);
if (versionNo == null) {
getComponentSelection().addItem(AsposeConstants.API_DEPENDENCY_NOT_FOUND);
} else {
getComponentSelection().addItem(versionNo);
}
return true;
}
//=========================================================================
private void retrieveAPIExamples() {
final String item = (String) getComponentSelection().getSelectedItem();
CustomMutableTreeNode top = new CustomMutableTreeNode("");
DefaultTreeModel model = (DefaultTreeModel) getExamplesTree().getModel();
model.setRoot(top);
model.reload(top);
if (item != null && !item.equals(AsposeConstants.API_DEPENDENCY_NOT_FOUND)) {
AsposeExampleCallback callback = new AsposeExampleCallback(this, top);
final ModalTaskImpl modalTask = new ModalTaskImpl(AsposeMavenProjectManager.getInstance().getProjectHandle(), callback, "Please wait...");
ProgressManager.getInstance().run(modalTask);
top.setTopTreeNodeText(AsposeConstants.API_NAME);
model.setRoot(top);
model.reload(top);
getExamplesTree().expandPath(new TreePath(top.getPath()));
}
}
//=========================================================================
@Override
public void validate() {
AsposeConstants.println("AsposeExamplePanel validate called..");
}
//=========================================================================
public boolean validateDialog() {
if (isExampleSelected()) {
if (dialog != null)
dialog.updateControls(true);
clearMessage();
return true;
}
final String item = (String) getComponentSelection().getSelectedItem();
if (item == null || item.equals(AsposeConstants.API_DEPENDENCY_NOT_FOUND)) {
if (dialog != null)
dialog.updateControls(false);
diplayMessage("Please first add maven dependency of " + AsposeConstants.API_NAME + " for java API", true);
return false;
} else if (!isExampleSelected()) {
if (dialog != null)
dialog.updateControls(false);
diplayMessage(AsposeConstants.ASPOSE_SELECT_EXAMPLE, true);
return false;
}
if (dialog != null)
dialog.updateControls(true);
clearMessage();
return true;
}
//=========================================================================
private boolean isExampleSelected() {
CustomMutableTreeNode comp = (CustomMutableTreeNode) getExamplesTree().getLastSelectedPathComponent();
if (comp == null) {
return false;
}
try {
if (!comp.isFolder()) {
return false;
}
} catch (Exception ex) {
return false;
}
return true;
}
//=========================================================================
public void diplayMessage(String message, boolean error) {
if (error) {
jLabelMessage.setForeground(Color.RED);
} else {
jLabelMessage.setForeground(Color.GREEN);
}
jLabelMessage.setText(message);
}
//=========================================================================
private void clearMessage() {
jLabelMessage.setText("");
}
//=========================================================================
public int showMessage(String title, String message, int buttons, int icon) {
int result = JOptionPane.showConfirmDialog(null, message, title, buttons, icon);
return result;
}
//====================================================================
public void populateExamplesTree(AsposeJavaAPI asposeComponent, CustomMutableTreeNode top, ProgressIndicator p)
{
String examplesFullPath = asposeComponent.getLocalRepositoryPath() + File.separator + AsposeConstants.SOURCE_API_EXAMPLES_LOCATION;
File directory = new File(examplesFullPath);
AsposeConstants.println(examplesFullPath+ "exists?"+directory.exists());
getExamplesTree().removeAll();
top.setExPath(examplesFullPath);
Queue<Object[]> queue = new LinkedList<>();
queue.add(new Object[]{null, directory});
while (!queue.isEmpty()) {
Object[] _entry = queue.remove();
File childFile = ((File) _entry[1]);
CustomMutableTreeNode parentItem = ((CustomMutableTreeNode) _entry[0]);
if (childFile.isDirectory()) {
if (parentItem != null) {
CustomMutableTreeNode child = new CustomMutableTreeNode(FormatExamples.formatTitle(childFile.getName()));
child.setExPath(childFile.getAbsolutePath());
child.setFolder(true);
parentItem.add(child);
parentItem = child;
} else {
parentItem = top;
}
for (File f : childFile.listFiles()) {
String fileName=f.getName().toLowerCase();
queue.add(new Object[]{parentItem, f});
}
} else if (childFile.isFile()) {
String title = FormatExamples.formatTitle(childFile.getName());
CustomMutableTreeNode child = new CustomMutableTreeNode(title);
child.setFolder(false);
parentItem.add(child);
}
}
}
private void componentSelection_Propertychanged(java.beans.PropertyChangeEvent evt) {
}
//=========================================================================
private void examplesTree_clicked(java.awt.event.MouseEvent evt)
{
// TODO add your handling code here:
TreePath path = getExamplesTree().getSelectionPath();
validateDialog();
}
// Variables declaration
private JComboBox componentSelection;
private JTree examplesTree;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabelMessage;
private JPanel jPanel1;
private JScrollPane jScrollPane1;
private ImageIcon icon = new ImageIcon(getClass().getResource("/resources/long_bannerIntelliJ.png"));
// End of variables declaration
/**
* @return the examplesTree
*/
public JTree getExamplesTree() {
return examplesTree;
}
/**
* @return the componentSelection
*/
public JComboBox getComponentSelection() {
return componentSelection;
}
}
| |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kew.api.rule;
import java.io.Serializable;
import java.util.Collection;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.w3c.dom.Element;
@XmlRootElement(name = RuleExpression.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = RuleExpression.Constants.TYPE_NAME, propOrder = {
RuleExpression.Elements.TYPE,
RuleExpression.Elements.EXPRESSION,
RuleExpression.Elements.ID,
CoreConstants.CommonElements.VERSION_NUMBER,
CoreConstants.CommonElements.OBJECT_ID,
CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class RuleExpression
extends AbstractDataTransferObject
implements RuleExpressionContract
{
@XmlElement(name = Elements.TYPE, required = false)
private final String type;
@XmlElement(name = Elements.EXPRESSION, required = false)
private final String expression;
@XmlElement(name = Elements.ID, required = false)
private final String id;
@XmlElement(name = CoreConstants.CommonElements.VERSION_NUMBER, required = false)
private final Long versionNumber;
@XmlElement(name = CoreConstants.CommonElements.OBJECT_ID, required = false)
private final String objectId;
@SuppressWarnings("unused")
@XmlAnyElement
private final Collection<Element> _futureElements = null;
/**
* Private constructor used only by JAXB.
*
*/
private RuleExpression() {
this.type = null;
this.expression = null;
this.id = null;
this.versionNumber = null;
this.objectId = null;
}
private RuleExpression(Builder builder) {
this.type = builder.getType();
this.expression = builder.getExpression();
this.id = builder.getId();
this.versionNumber = builder.getVersionNumber();
this.objectId = builder.getObjectId();
}
@Override
public String getType() {
return this.type;
}
@Override
public String getExpression() {
return this.expression;
}
@Override
public String getId() {
return this.id;
}
@Override
public Long getVersionNumber() {
return this.versionNumber;
}
@Override
public String getObjectId() {
return this.objectId;
}
/**
* A builder which can be used to construct {@link RuleExpression} instances. Enforces the constraints of the {@link RuleExpressionContract}.
*
*/
public final static class Builder
implements Serializable, ModelBuilder, RuleExpressionContract
{
private String type;
private String expression;
private String id;
private Long versionNumber;
private String objectId;
private Builder() {
// TODO modify this constructor as needed to pass any required values and invoke the appropriate 'setter' methods
}
public static Builder create() {
// TODO modify as needed to pass any required values and add them to the signature of the 'create' method
return new Builder();
}
public static Builder create(RuleExpressionContract contract) {
if (contract == null) {
throw new IllegalArgumentException("contract was null");
}
// TODO if create() is modified to accept required parameters, this will need to be modified
Builder builder = create();
builder.setType(contract.getType());
builder.setExpression(contract.getExpression());
builder.setId(contract.getId());
builder.setVersionNumber(contract.getVersionNumber());
builder.setObjectId(contract.getObjectId());
return builder;
}
public RuleExpression build() {
return new RuleExpression(this);
}
@Override
public String getType() {
return this.type;
}
@Override
public String getExpression() {
return this.expression;
}
@Override
public String getId() {
return this.id;
}
@Override
public Long getVersionNumber() {
return this.versionNumber;
}
@Override
public String getObjectId() {
return this.objectId;
}
public void setType(String type) {
// TODO add validation of input value if required and throw IllegalArgumentException if needed
this.type = type;
}
public void setExpression(String expression) {
// TODO add validation of input value if required and throw IllegalArgumentException if needed
this.expression = expression;
}
public void setId(String id) {
// TODO add validation of input value if required and throw IllegalArgumentException if needed
this.id = id;
}
public void setVersionNumber(Long versionNumber) {
// TODO add validation of input value if required and throw IllegalArgumentException if needed
this.versionNumber = versionNumber;
}
public void setObjectId(String objectId) {
// TODO add validation of input value if required and throw IllegalArgumentException if needed
this.objectId = objectId;
}
}
/**
* Defines some internal constants used on this class.
*
*/
static class Constants {
final static String ROOT_ELEMENT_NAME = "ruleExpression";
final static String TYPE_NAME = "RuleExpressionType";
}
/**
* A private class which exposes constants which define the XML element names to use when this object is marshalled to XML.
*
*/
static class Elements {
final static String TYPE = "type";
final static String EXPRESSION = "expression";
final static String ID = "id";
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jeremy Othieno.
*
* 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 clockwork.scene;
import java.util.Observable;
import java.util.Observer;
import clockwork.graphics.camera.Frustum;
import clockwork.graphics.camera.Viewport;
import clockwork.graphics.camera.projection.Projection;
import clockwork.graphics.camera.projection.ProjectionFactory;
import clockwork.graphics.renderer.RenderContext;
import clockwork.graphics.renderer.Renderer;
import clockwork.graphics.renderer.RendererFactory;
import clockwork.system.Debug;
import clockwork.system.RuntimeOptions;
import clockwork.types.math.Matrix4;
import clockwork.types.math.Orientation;
import clockwork.types.math.Point3f;
import clockwork.types.math.Vector3f;
/**
* A SceneViewer allows us to view the scene, obviously. A viewer can be anything from
* a camera to a telescope, but this class handles the important manipulations all
* viewer's share which are, essentially, accessing matrix transformations.
* @see http://www.opengl.org/archives/resources/faq/technical/transformations.htm
*/
public abstract class SceneViewer extends SceneObject implements Observer
{
/**
* The Viewer's render context.
*/
private final RenderContext renderContext = new RenderContext(this);
/**
* The camera's projection.
*/
private Projection projection = ProjectionFactory.getDefaultProjection();
/**
* There can only be a single viewer active at a time. Is this it?
*/
private boolean isActive = false;
/**
* The viewer's up vector.
*/
protected final Vector3f up = new Vector3f(0, 1, 0);
/**
* The viewer's viewport.
*/
private final Viewport viewport = new Viewport();
/**
* Has the VIEW matrix been updated?
*/
private boolean isUpdatedVIEW = true;
/**
* Has the PROJECTION matrix been updated?
*/
private boolean isUpdatedPROJECTION = true;
/**
* Calculate the VIEW matrix.
*/
protected abstract Matrix4 calculateVIEW();
/**
* Return the viewing frustum.
*/
public abstract Frustum getFrustum();
/**
* Instantiate a viewer with a given name, position, orientation, and up vector.
* @param name the viewer's name.
* @param position the viewer's position in the world.
* @param orientation the viewer's orientation in the world.
* @param up the viewer's up direction.
*/
protected SceneViewer
(
final String name,
final Point3f position,
final Orientation orientation,
final Vector3f up
)
{
super(name, position, orientation);
setUp(up);
// Make this viewer a scene observer.
Scene.getUniqueInstance().addObserver(this);
}
/**
* Instantiate a viewer with a given name, position, and orientation.
* @param name the viewer's name.
* @param position the viewer's position in the world.
* @param orientation the viewer's orientation in the world.
*/
protected SceneViewer
(
final String name,
final Point3f position,
final Orientation orientation
)
{
super(name, position, orientation);
Scene.getUniqueInstance().addObserver(this);
}
/**
* Activate or deactivate the viewer.
* @param activate true to activate the viewer, false otherwise.
*/
public final void setActive(final boolean isActive)
{
this.isActive = isActive;
SceneGraph.GUITreeModel.nodeChanged(GUITreeNode);
// Change the scene's current viewer.
if (isActive)
{
Scene.getUniqueInstance().setViewer(this);
Debug.ViewerName = this.getName();
}
else
{
Scene.getUniqueInstance().removeViewer();
Debug.ViewerName = "NONE";
}
}
/**
* Return true if the viewer is active, false otherwise.
*/
public final boolean isActive()
{
return isActive;
}
/**
* Activate the viewer if it's deactivated or vice-versa.
*/
public void toggleActive()
{
setActive(!isActive);
}
/**
* Set the viewing frustum.
* @param frustum the viewing frustum to set.
*/
public abstract void setFrustum(final Frustum frustum);
/**
* Get the camera's projection.
*/
public final Projection.Type getProjectionType()
{
return projection.getType();
}
/**
* Set the camera's projection.
* @param type the type of projection to set.
*/
public final void setProjection(final Projection.Type type)
{
if (type != null)
setProjection(ProjectionFactory.get(type));
}
/**
* Set the camera's projection.
* @param projection the projection to set.
*/
public final void setProjection(final Projection projection)
{
if (projection != null && this.projection != projection)
{
this.projection = projection;
setUpdatedPROJECTION(true);
}
}
/**
* Return the type of renderer used by this viewer.
*/
public Renderer.Type getRendererType()
{
return renderContext.getRendererType();
}
/**
* Set the renderer used by this viewer.
* @param type the type of renderer to set.
*/
public final void setRenderer(final Renderer.Type type)
{
if (type != null)
setRenderer(RendererFactory.get(type));
}
/**
* Set the renderer used by this viewer.
* @param renderer the renderer to set.
*/
public final void setRenderer(final Renderer renderer)
{
renderContext.setRenderer(renderer);
}
/**
* Set the viewer's position and update it's VIEW matrix.
*/
@Override
public final void setPosition(final Point3f position)
{
if (position != null && !this.position.equals(position))
{
super.setPosition(position);
setUpdatedVIEW(true);
}
}
/**
* Set the viewer's orientation and update it's VIEW matrix.
*/
@Override
public final void setOrientation(final Orientation orientation)
{
if (orientation != null && !this.orientation.equals(orientation))
{
super.setOrientation(orientation);
setUpdatedVIEW(true);
}
}
/**
* The Observer's update method, a method triggered by this object's registered
* observables. Since all viewer's observe the scene, this method will be called
* when the scene has been modified (changed). This, will in turn convert the
* scene into a set of renderable objects.
*
* @param observable the Observable object that triggered the update. This should be
* a scene object.
* @param unused an unused parameter.
*/
@Override
public void update(final Observable observable, final Object unused)
{
if (isActive && observable != null && observable instanceof Scene)
{
final Scene scene = (Scene)observable;
// Update the current VIEW and PROJECTION transformation matrices, if need be.
if (isUpdatedVIEW)
{
renderContext.setVIEW(RuntimeOptions.EnableVIEW ? calculateVIEW() : new Matrix4());
isUpdatedVIEW = false;
}
if (isUpdatedPROJECTION)
{
renderContext.setPROJECTION(calculatePROJECTION());
isUpdatedPROJECTION = false;
}
// Convert the scene to a set of renderables, then render it.
scene.render(renderContext);
}
}
/**
* Get the VIEW transformation matrix.
*/
public Matrix4 getVIEW()
{
return renderContext.getVIEW();
}
/**
* Get the PROJECTION transformation matrix.
*/
public Matrix4 getPROJECTON()
{
return renderContext.getPROJECTION();
}
/**
* Calculate the PROJECTION transform.
*/
public Matrix4 calculatePROJECTION()
{
return RuntimeOptions.EnablePROJECTION ? projection.toMatrix(getFrustum()) : new Matrix4();
}
/**
* Does the VIEW matrix need to be updated?
*/
public final void setUpdatedVIEW(final boolean updated)
{
isUpdatedVIEW = updated;
}
/**
* Does the PROJECTION matrix need to be updated?
*/
public final void setUpdatedPROJECTION(final boolean updated)
{
isUpdatedPROJECTION = updated;
}
/**
* Get the viewer's up direction.
*/
public Vector3f getUp()
{
return up;
}
/**
* Set the viewer's up direction.
* @param up the direction to set.
*/
public void setUp(final Vector3f up)
{
this.up.setIJK(up);
}
/**
* Get the viewer's viewport.
*/
public Viewport getViewport()
{
return viewport;
}
/**
* Set the viewer's viewport.
* @param viewport the viewport to set.
*/
public void setViewport(final Viewport viewport)
{
this.viewport.copy(viewport);
this.viewport.validate();
}
/**
* Return the viewer's render context.
*/
public RenderContext getRenderContext()
{
return renderContext;
}
/**
* Dispose of the viewer.
*/
@Override
public void dispose()
{
if (Scene.getUniqueInstance().getViewer() == this)
Scene.getUniqueInstance().removeViewer();
super.dispose();
}
/**
* Convert the viewer data to string format.
*/
@Override
public String getState()
{
if (isActive)
return "active";
else
return null;
}
}
| |
package com.google.ratel.deps.jackson.core.base;
import java.io.IOException;
import com.google.ratel.deps.jackson.core.*;
import com.google.ratel.deps.jackson.core.JsonParser.Feature;
import com.google.ratel.deps.jackson.core.io.NumberInput;
import com.google.ratel.deps.jackson.core.util.ByteArrayBuilder;
import com.google.ratel.deps.jackson.core.util.VersionUtil;
/**
* Intermediate base class used by all Jackson {@link JsonParser}
* implementations, but does not add any additional fields that depend
* on particular method of obtaining input.
*<p>
* Note that 'minimal' here mostly refers to minimal number of fields
* (size) and functionality that is specific to certain types
* of parser implementations; but not necessarily to number of methods.
*
* @author Tatu Saloranta
*/
public abstract class ParserMinimalBase
extends JsonParser
{
// Control chars:
protected final static int INT_TAB = '\t';
protected final static int INT_LF = '\n';
protected final static int INT_CR = '\r';
protected final static int INT_SPACE = 0x0020;
// Markup
protected final static int INT_LBRACKET = '[';
protected final static int INT_RBRACKET = ']';
protected final static int INT_LCURLY = '{';
protected final static int INT_RCURLY = '}';
protected final static int INT_QUOTE = '"';
protected final static int INT_BACKSLASH = '\\';
protected final static int INT_SLASH = '/';
protected final static int INT_COLON = ':';
protected final static int INT_COMMA = ',';
protected final static int INT_ASTERISK = '*';
protected final static int INT_APOSTROPHE = '\'';
// Letters we need
protected final static int INT_b = 'b';
protected final static int INT_f = 'f';
protected final static int INT_n = 'n';
protected final static int INT_r = 'r';
protected final static int INT_t = 't';
protected final static int INT_u = 'u';
/*
/**********************************************************
/* Minimal generally useful state
/**********************************************************
*/
/**
* Last token retrieved via {@link #nextToken}, if any.
* Null before the first call to <code>nextToken()</code>,
* as well as if token has been explicitly cleared
* (by call to {@link #clearCurrentToken})
*/
protected JsonToken _currToken;
/**
* Last cleared token, if any: that is, value that was in
* effect when {@link #clearCurrentToken} was called.
*/
protected JsonToken _lastClearedToken;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
protected ParserMinimalBase() { }
protected ParserMinimalBase(int features) {
super(features);
}
@Override
public Version version() {
return VersionUtil.versionFor(getClass());
}
/*
/**********************************************************
/* Configuration overrides if any
/**********************************************************
*/
// from base class:
//public void enableFeature(Feature f)
//public void disableFeature(Feature f)
//public void setFeature(Feature f, boolean state)
//public boolean isFeatureEnabled(Feature f)
/*
/**********************************************************
/* JsonParser impl
/**********************************************************
*/
@Override
public abstract JsonToken nextToken() throws IOException, JsonParseException;
@Override
public JsonToken getCurrentToken() {
return _currToken;
}
@Override
public boolean hasCurrentToken() {
return _currToken != null;
}
@Override
public JsonToken nextValue()
throws IOException, JsonParseException
{
/* Implementation should be as trivial as follows; only
* needs to change if we are to skip other tokens (for
* example, if comments were exposed as tokens)
*/
JsonToken t = nextToken();
if (t == JsonToken.FIELD_NAME) {
t = nextToken();
}
return t;
}
@Override
public JsonParser skipChildren() throws IOException, JsonParseException
{
if (_currToken != JsonToken.START_OBJECT
&& _currToken != JsonToken.START_ARRAY) {
return this;
}
int open = 1;
/* Since proper matching of start/end markers is handled
* by nextToken(), we'll just count nesting levels here
*/
while (true) {
JsonToken t = nextToken();
if (t == null) {
_handleEOF();
/* given constraints, above should never return;
* however, FindBugs doesn't know about it and
* complains... so let's add dummy break here
*/
return this;
}
switch (t) {
case START_OBJECT:
case START_ARRAY:
++open;
break;
case END_OBJECT:
case END_ARRAY:
if (--open == 0) {
return this;
}
break;
}
}
}
/**
* Method sub-classes need to implement
*/
protected abstract void _handleEOF() throws JsonParseException;
//public JsonToken getCurrentToken()
//public boolean hasCurrentToken()
@Override
public abstract String getCurrentName() throws IOException, JsonParseException;
@Override
public abstract void close() throws IOException;
@Override
public abstract boolean isClosed();
@Override
public abstract JsonStreamContext getParsingContext();
// public abstract JsonLocation getTokenLocation();
// public abstract JsonLocation getCurrentLocation();
/*
/**********************************************************
/* Public API, token state overrides
/**********************************************************
*/
@Override
public void clearCurrentToken() {
if (_currToken != null) {
_lastClearedToken = _currToken;
_currToken = null;
}
}
@Override
public JsonToken getLastClearedToken() {
return _lastClearedToken;
}
@Override
public abstract void overrideCurrentName(String name);
/*
/**********************************************************
/* Public API, access to token information, text
/**********************************************************
*/
@Override
public abstract String getText() throws IOException, JsonParseException;
@Override
public abstract char[] getTextCharacters() throws IOException, JsonParseException;
@Override
public abstract boolean hasTextCharacters();
@Override
public abstract int getTextLength() throws IOException, JsonParseException;
@Override
public abstract int getTextOffset() throws IOException, JsonParseException;
/*
/**********************************************************
/* Public API, access to token information, binary
/**********************************************************
*/
@Override
public abstract byte[] getBinaryValue(Base64Variant b64variant)
throws IOException, JsonParseException;
/*
/**********************************************************
/* Public API, access with conversion/coercion
/**********************************************************
*/
@Override
public boolean getValueAsBoolean(boolean defaultValue) throws IOException, JsonParseException
{
if (_currToken != null) {
switch (_currToken) {
case VALUE_NUMBER_INT:
return getIntValue() != 0;
case VALUE_TRUE:
return true;
case VALUE_FALSE:
case VALUE_NULL:
return false;
case VALUE_EMBEDDED_OBJECT:
{
Object value = this.getEmbeddedObject();
if (value instanceof Boolean) {
return (Boolean) value;
}
}
case VALUE_STRING:
String str = getText().trim();
if ("true".equals(str)) {
return true;
}
break;
}
}
return defaultValue;
}
@Override
public int getValueAsInt(int defaultValue) throws IOException, JsonParseException
{
if (_currToken != null) {
switch (_currToken) {
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
return getIntValue();
case VALUE_TRUE:
return 1;
case VALUE_FALSE:
case VALUE_NULL:
return 0;
case VALUE_STRING:
return NumberInput.parseAsInt(getText(), defaultValue);
case VALUE_EMBEDDED_OBJECT:
{
Object value = this.getEmbeddedObject();
if (value instanceof Number) {
return ((Number) value).intValue();
}
}
}
}
return defaultValue;
}
@Override
public long getValueAsLong(long defaultValue) throws IOException, JsonParseException
{
if (_currToken != null) {
switch (_currToken) {
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
return getLongValue();
case VALUE_TRUE:
return 1;
case VALUE_FALSE:
case VALUE_NULL:
return 0;
case VALUE_STRING:
return NumberInput.parseAsLong(getText(), defaultValue);
case VALUE_EMBEDDED_OBJECT:
{
Object value = this.getEmbeddedObject();
if (value instanceof Number) {
return ((Number) value).longValue();
}
}
}
}
return defaultValue;
}
@Override
public double getValueAsDouble(double defaultValue) throws IOException, JsonParseException
{
if (_currToken != null) {
switch (_currToken) {
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
return getDoubleValue();
case VALUE_TRUE:
return 1;
case VALUE_FALSE:
case VALUE_NULL:
return 0;
case VALUE_STRING:
return NumberInput.parseAsDouble(getText(), defaultValue);
case VALUE_EMBEDDED_OBJECT:
{
Object value = this.getEmbeddedObject();
if (value instanceof Number) {
return ((Number) value).doubleValue();
}
}
}
}
return defaultValue;
}
@Override
public String getValueAsString(String defaultValue) throws IOException, JsonParseException
{
if (_currToken != JsonToken.VALUE_STRING) {
if (_currToken == null || _currToken == JsonToken.VALUE_NULL || !_currToken.isScalarValue()) {
return defaultValue;
}
}
return getText();
}
/*
/**********************************************************
/* Base64 decoding
/**********************************************************
*/
/**
* Helper method that can be used for base64 decoding in cases where
* encoded content has already been read as a String.
*/
protected void _decodeBase64(String str, ByteArrayBuilder builder, Base64Variant b64variant)
throws IOException, JsonParseException
{
int ptr = 0;
int len = str.length();
main_loop:
while (ptr < len) {
// first, we'll skip preceding white space, if any
char ch;
do {
ch = str.charAt(ptr++);
if (ptr >= len) {
break main_loop;
}
} while (ch <= INT_SPACE);
int bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
_reportInvalidBase64(b64variant, ch, 0, null);
}
int decodedData = bits;
// then second base64 char; can't get padding yet, nor ws
if (ptr >= len) {
_reportBase64EOF();
}
ch = str.charAt(ptr++);
bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
_reportInvalidBase64(b64variant, ch, 1, null);
}
decodedData = (decodedData << 6) | bits;
// third base64 char; can be padding, but not ws
if (ptr >= len) {
// but as per [JACKSON-631] can be end-of-input, iff not using padding
if (!b64variant.usesPadding()) {
decodedData >>= 4;
builder.append(decodedData);
break;
}
_reportBase64EOF();
}
ch = str.charAt(ptr++);
bits = b64variant.decodeBase64Char(ch);
// First branch: can get padding (-> 1 byte)
if (bits < 0) {
if (bits != Base64Variant.BASE64_VALUE_PADDING) {
_reportInvalidBase64(b64variant, ch, 2, null);
}
// Ok, must get padding
if (ptr >= len) {
_reportBase64EOF();
}
ch = str.charAt(ptr++);
if (!b64variant.usesPaddingChar(ch)) {
_reportInvalidBase64(b64variant, ch, 3, "expected padding character '"+b64variant.getPaddingChar()+"'");
}
// Got 12 bits, only need 8, need to shift
decodedData >>= 4;
builder.append(decodedData);
continue;
}
// Nope, 2 or 3 bytes
decodedData = (decodedData << 6) | bits;
// fourth and last base64 char; can be padding, but not ws
if (ptr >= len) {
// but as per [JACKSON-631] can be end-of-input, iff not using padding
if (!b64variant.usesPadding()) {
decodedData >>= 2;
builder.appendTwoBytes(decodedData);
break;
}
_reportBase64EOF();
}
ch = str.charAt(ptr++);
bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
if (bits != Base64Variant.BASE64_VALUE_PADDING) {
_reportInvalidBase64(b64variant, ch, 3, null);
}
decodedData >>= 2;
builder.appendTwoBytes(decodedData);
} else {
// otherwise, our triple is now complete
decodedData = (decodedData << 6) | bits;
builder.appendThreeBytes(decodedData);
}
}
}
/**
* @param bindex Relative index within base64 character unit; between 0
* and 3 (as unit has exactly 4 characters)
*/
protected void _reportInvalidBase64(Base64Variant b64variant, char ch, int bindex, String msg)
throws JsonParseException
{
String base;
if (ch <= INT_SPACE) {
base = "Illegal white space character (code 0x"+Integer.toHexString(ch)+") as character #"+(bindex+1)+" of 4-char base64 unit: can only used between units";
} else if (b64variant.usesPaddingChar(ch)) {
base = "Unexpected padding character ('"+b64variant.getPaddingChar()+"') as character #"+(bindex+1)+" of 4-char base64 unit: padding only legal as 3rd or 4th character";
} else if (!Character.isDefined(ch) || Character.isISOControl(ch)) {
// Not sure if we can really get here... ? (most illegal xml chars are caught at lower level)
base = "Illegal character (code 0x"+Integer.toHexString(ch)+") in base64 content";
} else {
base = "Illegal character '"+ch+"' (code 0x"+Integer.toHexString(ch)+") in base64 content";
}
if (msg != null) {
base = base + ": " + msg;
}
throw _constructError(base);
}
protected void _reportBase64EOF() throws JsonParseException {
throw _constructError("Unexpected end-of-String in base64 content");
}
/*
/**********************************************************
/* Error reporting
/**********************************************************
*/
protected void _reportUnexpectedChar(int ch, String comment)
throws JsonParseException
{
String msg = "Unexpected character ("+_getCharDesc(ch)+")";
if (comment != null) {
msg += ": "+comment;
}
_reportError(msg);
}
protected void _reportInvalidEOF()
throws JsonParseException
{
_reportInvalidEOF(" in "+_currToken);
}
protected void _reportInvalidEOF(String msg)
throws JsonParseException
{
_reportError("Unexpected end-of-input"+msg);
}
protected void _reportInvalidEOFInValue() throws JsonParseException
{
_reportInvalidEOF(" in a value");
}
protected void _throwInvalidSpace(int i)
throws JsonParseException
{
char c = (char) i;
String msg = "Illegal character ("+_getCharDesc(c)+"): only regular white space (\\r, \\n, \\t) is allowed between tokens";
_reportError(msg);
}
/**
* Method called to report a problem with unquoted control character.
* Note: starting with version 1.4, it is possible to suppress
* exception by enabling {@link Feature#ALLOW_UNQUOTED_CONTROL_CHARS}.
*/
protected void _throwUnquotedSpace(int i, String ctxtDesc)
throws JsonParseException
{
// JACKSON-208; possible to allow unquoted control chars:
if (!isEnabled(Feature.ALLOW_UNQUOTED_CONTROL_CHARS) || i >= INT_SPACE) {
char c = (char) i;
String msg = "Illegal unquoted character ("+_getCharDesc(c)+"): has to be escaped using backslash to be included in "+ctxtDesc;
_reportError(msg);
}
}
protected char _handleUnrecognizedCharacterEscape(char ch) throws JsonProcessingException
{
// as per [JACKSON-300]
if (isEnabled(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)) {
return ch;
}
// and [JACKSON-548]
if (ch == '\'' && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) {
return ch;
}
_reportError("Unrecognized character escape "+_getCharDesc(ch));
return ch;
}
/*
/**********************************************************
/* Error reporting, generic
/**********************************************************
*/
protected final static String _getCharDesc(int ch)
{
char c = (char) ch;
if (Character.isISOControl(c)) {
return "(CTRL-CHAR, code "+ch+")";
}
if (ch > 255) {
return "'"+c+"' (code "+ch+" / 0x"+Integer.toHexString(ch)+")";
}
return "'"+c+"' (code "+ch+")";
}
protected final void _reportError(String msg)
throws JsonParseException
{
throw _constructError(msg);
}
protected final void _wrapError(String msg, Throwable t)
throws JsonParseException
{
throw _constructError(msg, t);
}
protected final void _throwInternal() {
VersionUtil.throwInternal();
}
protected final JsonParseException _constructError(String msg, Throwable t)
{
return new JsonParseException(msg, getCurrentLocation(), t);
}
}
| |
/*
* Copyright 2015 APPNEXUS 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.appnexus.opensdk;
import com.appnexus.opensdk.shadows.ShadowAsyncTaskNoExecutor;
import com.appnexus.opensdk.shadows.ShadowSettings;
import com.appnexus.opensdk.shadows.ShadowWebSettings;
import com.appnexus.opensdk.ut.UTRequestParameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLog;
import org.robolectric.shadows.ShadowWebView;
import java.lang.reflect.Method;
import java.util.ArrayList;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
/**
* This tests if the options set on a BannerAdView are represented in the UT Post data in the right format.
*/
@Config(sdk = 21,
shadows = {ShadowAsyncTaskNoExecutor.class,
ShadowWebView.class, ShadowWebSettings.class, ShadowSettings.class, ShadowLog.class})
@RunWith(RobolectricTestRunner.class)
public class BannerAdToRequestParametersTest extends BaseRoboTest {
BannerAdView bannerAdView;
UTRequestParameters requestParameters;
@Override
public void setup() {
super.setup();
bannerAdView = new BannerAdView(activity);
requestParameters = bannerAdView.requestParameters;
// This would later be over-ridden by test specific values
bannerAdView.setAdSize(320,50);
}
// Setting setAdSize should do
// Set primary_size = size
// Add size to sizes array
// Set allow_smaller_sizes to false
@Test
public void testSetAdSize(){
setAdSize();
assertSetAdSize();
}
// Setting sizes using setAdSizesArray should set the first size as primary_size.
// All sizes set should be there in sizes array
// Set allow_smaller_sizes to false
@Test
public void testSetAdSizesArray(){
setAdSizesArray();
assertSetAdSizesArray();
}
//Setting MAX size should
//Set primary_size = max_size
//Add max_size to sizes array
//Set allow_smaller_sizes to true
@Test
public void testSetMaxSize(){
setMaxSize();
assertSetMaxSize();
}
// Setting setAdSize should reset all the other size params set earlier
@Test
public void testSetAdSizeOverRidesEverythingElse(){
setAdSizesArray();
setMaxSize();
setAdSize();
assertSetAdSize();
}
// Setting setAdSize should reset all the other size params set earlier
@Test
public void testSetAdSizeArrayOverRidesEverythingElse(){
setAdSize();
setMaxSize();
setAdSizesArray();
assertSetAdSizesArray();
}
// Test setAllowVideo
@Test
public void testSetAllowVideo(){
assertEquals(false,bannerAdView.getAllowVideoDemand());
String bannerPostData = getRequestParametersPostData();
assertTrue(bannerPostData.contains("\"allowed_media_types\":[1]"));
bannerAdView.setAllowVideoDemand(true);
assertEquals(true,bannerAdView.getAllowVideoDemand());
String bannerVideoPostData = getRequestParametersPostData();
assertTrue(bannerVideoPostData.contains("\"allowed_media_types\":[1,4]"));
}
// Test setAllowBanner
@Test
public void testSetAllowBanner(){
assertEquals(false,bannerAdView.getAllowVideoDemand());
String bannerPostData = getRequestParametersPostData();
assertTrue(bannerPostData.contains("\"allowed_media_types\":[1]"));
bannerAdView.setAllowBannerDemand(false);
bannerPostData = getRequestParametersPostData();
assertTrue(bannerPostData.contains("\"allowed_media_types\":[]"));
bannerAdView.setAllowVideoDemand(true);
assertEquals(true,bannerAdView.getAllowVideoDemand());
bannerPostData = getRequestParametersPostData();
assertTrue(bannerPostData.contains("\"allowed_media_types\":[4]"));
bannerAdView.setAllowVideoDemand(false);
bannerAdView.setAllowNativeDemand(true);
assertEquals(true,bannerAdView.getAllowNativeDemand());
bannerPostData = getRequestParametersPostData();
assertTrue(bannerPostData.contains("\"allowed_media_types\":[12]"));
bannerAdView.setAllowBannerDemand(true);
assertEquals(false,bannerAdView.getAllowVideoDemand());
bannerPostData = getRequestParametersPostData();
assertTrue(bannerPostData.contains("\"allowed_media_types\":[1,12]"));
}
// Test setAllowNative
@Test
public void testSetAllowNative(){
assertEquals(false,bannerAdView.getAllowNativeDemand());
String bannerPostData = getRequestParametersPostData();
assertTrue(bannerPostData.contains("\"allowed_media_types\":[1]"));
bannerAdView.setAllowNativeDemand(true, 127);
assertEquals(true,bannerAdView.getAllowNativeDemand());
String bannerNativePostData = getRequestParametersPostData();
assertTrue(bannerNativePostData.contains("\"allowed_media_types\":[1,12]"));
assertTrue(bannerNativePostData.contains("\"native\":{\"renderer_id\":127}}]"));
}
// Test setAllowNative and setAllowVideo
@Test
public void testSetAllowVideoAndNative(){
assertEquals(false,bannerAdView.getAllowNativeDemand());
assertEquals(false,bannerAdView.getAllowVideoDemand());
String bannerPostData = getRequestParametersPostData();
assertTrue(bannerPostData.contains("\"allowed_media_types\":[1]"));
bannerAdView.setAllowNativeDemand(true, 127);
bannerAdView.setAllowVideoDemand(true);
assertEquals(true,bannerAdView.getAllowNativeDemand());
assertEquals(true,bannerAdView.getAllowVideoDemand());
String bannerNativePostData = getRequestParametersPostData();
assertTrue(bannerNativePostData.contains("\"allowed_media_types\":[1,4,12]"));
assertTrue(bannerNativePostData.contains("\"native\":{\"renderer_id\":127}}]"));
}
// Setting MAX size should reset all the other size params set earlier
@Test
public void testSetMAXSizeOverRidesEverythingElse(){
setAdSize();
setAdSizesArray();
setMaxSize();
assertSetMaxSize();
}
// Testing the content_url in the post data.
@Test
public void testContentUrl(){
bannerAdView.addCustomKeywords("content_url", "www.appnexus.com");
String postData = getRequestParametersPostData();
assertTrue(postData.contains("\"key\":\"content_url\",\"value\":[\"www.appnexus.com\"]"));
bannerAdView.getRequestParameters().getCustomKeywords().contains("content_url");
}
// Testing the force creative Id in the post data.
@Test
public void testForceCreativeId(){
bannerAdView.setForceCreativeId(135482485);
String postData = getRequestParametersPostData();
assertTrue(postData.contains("\"force_creative_id\":135482485"));
}
@Test
public void testIsNativeAssemblyRendererEnabled(){
useNativeRenderer(true);
assertIsNativeAssemblyRendererEnabled(true);
useNativeRenderer(false);
assertIsNativeAssemblyRendererEnabled(false);
}
/**
* Validates the Traffic Source in the request
*
* @throws Exception
*/
@Test
public void testTrafficSourceCode() {
assertNull(bannerAdView.getTrafficSourceCode());
bannerAdView.setTrafficSourceCode("Xandr");
assertEquals("Xandr", bannerAdView.getTrafficSourceCode());
String postData = getRequestParametersPostData();
assertTrue(postData.contains("\"traffic_source_code\":\"Xandr\""));
}
/**
* Validates the Ext Inv Code in the request
*
* @throws Exception
*/
@Test
public void testExtInvCode() {
assertNull(bannerAdView.getExtInvCode());
bannerAdView.setExtInvCode("Xandr");
assertEquals("Xandr", bannerAdView.getExtInvCode());
String postData = getRequestParametersPostData();
assertTrue(postData.contains("\"ext_inv_code\":\"Xandr\""));
}
private void useNativeRenderer(boolean isNativeAssemblyRendererEnabled) {
bannerAdView.enableNativeRendering(isNativeAssemblyRendererEnabled);
}
private void assertIsNativeAssemblyRendererEnabled(boolean isNativeAssemblyRendererEnabled){
assertEquals(isNativeAssemblyRendererEnabled, bannerAdView.isNativeRenderingEnabled());
}
private void setAdSize(){
bannerAdView.setAdSize(720,90);
}
private void setAdSizesArray(){
ArrayList<AdSize> adSizeArrayList = new ArrayList<AdSize>();
adSizeArrayList.add(new AdSize(10,10));
adSizeArrayList.add(new AdSize(320,50));
adSizeArrayList.add(new AdSize(300,250));
bannerAdView.setAdSizes(adSizeArrayList);
}
private void setMaxSize(){
bannerAdView.setMaxSize(1080,720);
}
private void assertSetAdSize(){
String postData = getRequestParametersPostData();
assertTrue(postData.contains("\"primary_size\":{\"width\":720,\"height\":90},"));
assertTrue(postData.contains("\"sizes\":[{\"width\":720,\"height\":90}],"));
assertTrue(postData.contains("\"allow_smaller_sizes\":false,"));
}
private void assertSetAdSizesArray(){
String postData = getRequestParametersPostData();
assertTrue(postData.contains("\"primary_size\":{\"width\":10,\"height\":10},"));
assertTrue(postData.contains("\"sizes\":[{\"width\":10,\"height\":10},{\"width\":320,\"height\":50},{\"width\":300,\"height\":250}],"));
assertTrue(postData.contains("\"allow_smaller_sizes\":false,"));
}
private void assertSetMaxSize(){
String postData = getRequestParametersPostData();
assertTrue(postData.contains("\"primary_size\":{\"width\":1080,\"height\":720},"));
assertTrue(postData.contains("\"sizes\":[{\"width\":1080,\"height\":720}],"));
assertTrue(postData.contains("\"allow_smaller_sizes\":true,"));
}
public UTRequestParameters getRequestParameters() {
return requestParameters;
}
/**
* getPostData method is private in UTRequestParameters using reflection to access it.
* There might be better way of doing this but this works.!!
* @return
*/
private String getRequestParametersPostData() {
String postData = "";
try {
Method getPostData = UTRequestParameters.class.getDeclaredMethod("getPostData", null);
getPostData.setAccessible(true);
postData = (String) getPostData.invoke(requestParameters, null);
System.out.println("postData = " + postData);
}catch (Exception e){
e.printStackTrace();
}
return postData;
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner;
import com.facebook.presto.metadata.FunctionHandle;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.MetadataUtil;
import com.facebook.presto.metadata.QualifiedTableName;
import com.facebook.presto.metadata.TableMetadata;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.TableHandle;
import com.facebook.presto.sql.analyzer.Analysis;
import com.facebook.presto.sql.analyzer.Field;
import com.facebook.presto.sql.analyzer.FieldOrExpression;
import com.facebook.presto.sql.analyzer.Session;
import com.facebook.presto.sql.analyzer.TupleDescriptor;
import com.facebook.presto.sql.analyzer.Type;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.FilterNode;
import com.facebook.presto.sql.planner.plan.LimitNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.SortNode;
import com.facebook.presto.sql.planner.plan.TableScanNode;
import com.facebook.presto.sql.planner.plan.TopNNode;
import com.facebook.presto.sql.planner.plan.WindowNode;
import com.facebook.presto.sql.tree.DefaultTraversalVisitor;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.InPredicate;
import com.facebook.presto.sql.tree.QualifiedName;
import com.facebook.presto.sql.tree.QualifiedNameReference;
import com.facebook.presto.sql.tree.Query;
import com.facebook.presto.sql.tree.QuerySpecification;
import com.facebook.presto.sql.tree.SortItem;
import com.facebook.presto.sql.tree.SubqueryExpression;
import com.facebook.presto.util.IterableTransformer;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.facebook.presto.sql.planner.plan.TableScanNode.GeneratedPartitions;
import static com.facebook.presto.sql.tree.FunctionCall.argumentsGetter;
import static com.facebook.presto.sql.tree.FunctionCall.distinctPredicate;
import static com.facebook.presto.sql.tree.SortItem.sortKeyGetter;
import static com.google.common.base.Preconditions.checkState;
class QueryPlanner
extends DefaultTraversalVisitor<PlanBuilder, Void>
{
private final Analysis analysis;
private final SymbolAllocator symbolAllocator;
private final PlanNodeIdAllocator idAllocator;
private final Metadata metadata;
private final Session session;
QueryPlanner(Analysis analysis, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator, Metadata metadata, Session session)
{
Preconditions.checkNotNull(analysis, "analysis is null");
Preconditions.checkNotNull(symbolAllocator, "symbolAllocator is null");
Preconditions.checkNotNull(idAllocator, "idAllocator is null");
Preconditions.checkNotNull(metadata, "metadata is null");
Preconditions.checkNotNull(session, "session is null");
this.analysis = analysis;
this.symbolAllocator = symbolAllocator;
this.idAllocator = idAllocator;
this.metadata = metadata;
this.session = session;
}
@Override
protected PlanBuilder visitQuery(Query query, Void context)
{
PlanBuilder builder = planQueryBody(query);
Set<InPredicate> inPredicates = analysis.getInPredicates(query);
builder = appendSemiJoins(builder, inPredicates);
List<FieldOrExpression> orderBy = analysis.getOrderByExpressions(query);
List<FieldOrExpression> outputs = analysis.getOutputExpressions(query);
builder = project(builder, Iterables.concat(orderBy, outputs));
builder = sort(builder, query);
builder = project(builder, analysis.getOutputExpressions(query));
builder = limit(builder, query);
return builder;
}
@Override
protected PlanBuilder visitQuerySpecification(QuerySpecification node, Void context)
{
PlanBuilder builder = planFrom(node);
Set<InPredicate> inPredicates = analysis.getInPredicates(node);
builder = appendSemiJoins(builder, inPredicates);
builder = filter(builder, analysis.getWhere(node));
builder = aggregate(builder, node);
builder = filter(builder, analysis.getHaving(node));
builder = window(builder, node);
List<FieldOrExpression> orderBy = analysis.getOrderByExpressions(node);
List<FieldOrExpression> outputs = analysis.getOutputExpressions(node);
builder = project(builder, Iterables.concat(orderBy, outputs));
builder = distinct(builder, node, outputs, orderBy);
builder = sort(builder, node);
builder = project(builder, analysis.getOutputExpressions(node));
builder = limit(builder, node);
return builder;
}
private PlanBuilder planQueryBody(Query query)
{
RelationPlan relationPlan = new RelationPlanner(analysis, symbolAllocator, idAllocator, metadata, session)
.process(query.getQueryBody(), null);
TranslationMap translations = new TranslationMap(relationPlan, analysis);
// Make field->symbol mapping from underlying relation plan available for translations
// This makes it possible to rewrite FieldOrExpressions that reference fields from the QuerySpecification directly
translations.setFieldMappings(relationPlan.getOutputSymbols());
return new PlanBuilder(translations, relationPlan.getRoot());
}
private PlanBuilder planFrom(QuerySpecification node)
{
RelationPlan relationPlan;
if (node.getFrom() == null || node.getFrom().isEmpty()) {
relationPlan = planImplicitTable();
}
else {
relationPlan = new RelationPlanner(analysis, symbolAllocator, idAllocator, metadata, session)
.process(Iterables.getOnlyElement(node.getFrom()), null);
}
TranslationMap translations = new TranslationMap(relationPlan, analysis);
// Make field->symbol mapping from underlying relation plan available for translations
// This makes it possible to rewrite FieldOrExpressions that reference fields from the FROM clause directly
translations.setFieldMappings(relationPlan.getOutputSymbols());
return new PlanBuilder(translations, relationPlan.getRoot());
}
private RelationPlan planImplicitTable()
{
// TODO: replace this with a table-generating operator that produces 1 row with no columns
QualifiedTableName name = MetadataUtil.createQualifiedTableName(session, QualifiedName.of("dual"));
Optional<TableHandle> optionalHandle = metadata.getTableHandle(name);
checkState(optionalHandle.isPresent(), "Dual table provider not installed");
TableHandle table = optionalHandle.get();
TableMetadata tableMetadata = metadata.getTableMetadata(table);
Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(table);
ImmutableMap.Builder<Symbol, ColumnHandle> columns = ImmutableMap.builder();
for (ColumnMetadata column : tableMetadata.getColumns()) {
Symbol symbol = symbolAllocator.newSymbol(column.getName(), Type.fromRaw(column.getType()));
columns.put(symbol, columnHandles.get(column.getName()));
}
ImmutableMap<Symbol, ColumnHandle> assignments = columns.build();
TableScanNode tableScan = new TableScanNode(idAllocator.getNextId(), table, ImmutableList.copyOf(assignments.keySet()), assignments, null, Optional.<GeneratedPartitions>absent());
return new RelationPlan(tableScan, new TupleDescriptor(), ImmutableList.<Symbol>of());
}
private PlanBuilder filter(PlanBuilder subPlan, Expression predicate)
{
if (predicate == null) {
return subPlan;
}
Expression rewritten = subPlan.rewrite(predicate);
return new PlanBuilder(subPlan.getTranslations(), new FilterNode(idAllocator.getNextId(), subPlan.getRoot(), rewritten));
}
private PlanBuilder project(PlanBuilder subPlan, Iterable<FieldOrExpression> expressions)
{
TranslationMap outputTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis);
ImmutableMap.Builder<Symbol, Expression> projections = ImmutableMap.builder();
for (FieldOrExpression fieldOrExpression : ImmutableSet.copyOf(expressions)) {
Symbol symbol;
if (fieldOrExpression.isFieldReference()) {
Field field = subPlan.getRelationPlan().getDescriptor().getFields().get(fieldOrExpression.getFieldIndex());
symbol = symbolAllocator.newSymbol(field);
}
else {
Expression expression = fieldOrExpression.getExpression();
symbol = symbolAllocator.newSymbol(expression, analysis.getType(expression));
}
projections.put(symbol, subPlan.rewrite(fieldOrExpression));
outputTranslations.put(fieldOrExpression, symbol);
}
return new PlanBuilder(outputTranslations, new ProjectNode(idAllocator.getNextId(), subPlan.getRoot(), projections.build()));
}
private PlanBuilder aggregate(PlanBuilder subPlan, QuerySpecification node)
{
if (analysis.getAggregates(node).isEmpty() && analysis.getGroupByExpressions(node).isEmpty()) {
return subPlan;
}
Set<FieldOrExpression> arguments = IterableTransformer.on(analysis.getAggregates(node))
.transformAndFlatten(argumentsGetter())
.transform(toFieldOrExpression())
.set();
// 1. Pre-project all scalar inputs (arguments and non-trivial group by expressions)
Iterable<FieldOrExpression> inputs = Iterables.concat(analysis.getGroupByExpressions(node), arguments);
if (!Iterables.isEmpty(inputs)) { // avoid an empty projection if the only aggregation is COUNT (which has no arguments)
subPlan = project(subPlan, inputs);
}
// 1.a Rewrite DISTINCT aggregates as a group by
// All DISTINCT argument lists must match see TupleAnalyzer::analyzeAggregations
if (Iterables.any(analysis.getAggregates(node), distinctPredicate())) {
AggregationNode aggregation = new AggregationNode(idAllocator.getNextId(),
subPlan.getRoot(),
subPlan.getRoot().getOutputSymbols(),
ImmutableMap.<Symbol, FunctionCall>of(),
ImmutableMap.<Symbol, FunctionHandle>of());
subPlan = new PlanBuilder(subPlan.getTranslations(), aggregation);
}
// 2. Aggregate
ImmutableMap.Builder<Symbol, FunctionCall> aggregationAssignments = ImmutableMap.builder();
ImmutableMap.Builder<Symbol, FunctionHandle> functions = ImmutableMap.builder();
// 2.a. Rewrite aggregates in terms of pre-projected inputs
TranslationMap translations = new TranslationMap(subPlan.getRelationPlan(), analysis);
for (FunctionCall aggregate : analysis.getAggregates(node)) {
FunctionCall rewritten = (FunctionCall) subPlan.rewrite(aggregate);
Symbol newSymbol = symbolAllocator.newSymbol(rewritten, analysis.getType(aggregate));
aggregationAssignments.put(newSymbol, rewritten);
translations.put(aggregate, newSymbol);
functions.put(newSymbol, analysis.getFunctionInfo(aggregate).getHandle());
}
// 2.b. Rewrite group by expressions in terms of pre-projected inputs
Set<Symbol> groupBySymbols = new LinkedHashSet<>();
for (FieldOrExpression fieldOrExpression : analysis.getGroupByExpressions(node)) {
Symbol symbol = subPlan.translate(fieldOrExpression);
groupBySymbols.add(symbol);
translations.put(fieldOrExpression, symbol);
}
return new PlanBuilder(translations, new AggregationNode(idAllocator.getNextId(), subPlan.getRoot(), ImmutableList.copyOf(groupBySymbols), aggregationAssignments.build(), functions.build()));
}
private PlanBuilder window(PlanBuilder subPlan, QuerySpecification node)
{
Set<FunctionCall> windowFunctions = ImmutableSet.copyOf(analysis.getWindowFunctions(node));
if (windowFunctions.isEmpty()) {
return subPlan;
}
for (FunctionCall windowFunction : windowFunctions) {
// Pre-project inputs
ImmutableList<Expression> inputs = ImmutableList.<Expression>builder()
.addAll(windowFunction.getArguments())
.addAll(windowFunction.getWindow().get().getPartitionBy())
.addAll(Iterables.transform(windowFunction.getWindow().get().getOrderBy(), sortKeyGetter()))
.build();
subPlan = appendProjections(subPlan, inputs);
// Rewrite PARTITION BY in terms of pre-projected inputs
ImmutableList.Builder<Symbol> partitionBySymbols = ImmutableList.builder();
for (Expression expression : windowFunction.getWindow().get().getPartitionBy()) {
partitionBySymbols.add(subPlan.translate(expression));
}
// Rewrite ORDER BY in terms of pre-projected inputs
ImmutableList.Builder<Symbol> orderBySymbols = ImmutableList.builder();
Map<Symbol, SortItem.Ordering> orderings = new HashMap<>();
for (SortItem item : windowFunction.getWindow().get().getOrderBy()) {
Symbol symbol = subPlan.translate(item.getSortKey());
orderBySymbols.add(symbol);
orderings.put(symbol, item.getOrdering());
}
TranslationMap outputTranslations = new TranslationMap(subPlan.getRelationPlan(), analysis);
outputTranslations.copyMappingsFrom(subPlan.getTranslations());
ImmutableMap.Builder<Symbol, FunctionCall> assignments = ImmutableMap.builder();
Map<Symbol, FunctionHandle> functionHandles = new HashMap<>();
// Rewrite function call in terms of pre-projected inputs
FunctionCall rewritten = (FunctionCall) subPlan.rewrite(windowFunction);
Symbol newSymbol = symbolAllocator.newSymbol(rewritten, analysis.getType(windowFunction));
assignments.put(newSymbol, rewritten);
outputTranslations.put(windowFunction, newSymbol);
functionHandles.put(newSymbol, analysis.getFunctionInfo(windowFunction).getHandle());
// create window node
subPlan = new PlanBuilder(outputTranslations,
new WindowNode(idAllocator.getNextId(), subPlan.getRoot(), partitionBySymbols.build(), orderBySymbols.build(), orderings, assignments.build(), functionHandles));
}
return subPlan;
}
private PlanBuilder appendProjections(PlanBuilder subPlan, Iterable<Expression> expressions)
{
TranslationMap translations = new TranslationMap(subPlan.getRelationPlan(), analysis);
// Carry over the translations from the source because we are appending projections
translations.copyMappingsFrom(subPlan.getTranslations());
ImmutableMap.Builder<Symbol, Expression> projections = ImmutableMap.builder();
// add an identity projection for underlying plan
for (Symbol symbol : subPlan.getRoot().getOutputSymbols()) {
Expression expression = new QualifiedNameReference(symbol.toQualifiedName());
projections.put(symbol, expression);
}
ImmutableMap.Builder<Symbol, Expression> newTranslations = ImmutableMap.builder();
for (Expression expression : expressions) {
Symbol symbol = symbolAllocator.newSymbol(expression, analysis.getType(expression));
projections.put(symbol, translations.rewrite(expression));
newTranslations.put(symbol, expression);
}
// Now append the new translations into the TranslationMap
for (Map.Entry<Symbol, Expression> entry : newTranslations.build().entrySet()) {
translations.put(entry.getValue(), entry.getKey());
}
return new PlanBuilder(translations, new ProjectNode(idAllocator.getNextId(), subPlan.getRoot(), projections.build()));
}
private PlanBuilder appendSemiJoins(PlanBuilder subPlan, Set<InPredicate> inPredicates)
{
for (InPredicate inPredicate : inPredicates) {
subPlan = appendSemiJoin(subPlan, inPredicate);
}
return subPlan;
}
/**
* Semijoins are planned as follows:
* 1) SQL constructs that need to be semijoined are extracted during Analysis phase (currently only InPredicates so far)
* 2) Create a new SemiJoinNode that connects the semijoin lookup field with the planned subquery and have it output a new boolean
* symbol for the result of the semijoin.
* 3) Add an entry to the TranslationMap that notes to map the InPredicate into semijoin output symbol
* <p/>
* Currently, we only support semijoins deriving from InPredicates, but we will probably need
* to add support for more SQL constructs in the future.
*/
private PlanBuilder appendSemiJoin(PlanBuilder subPlan, InPredicate inPredicate)
{
TranslationMap translations = new TranslationMap(subPlan.getRelationPlan(), analysis);
translations.copyMappingsFrom(subPlan.getTranslations());
subPlan = appendProjections(subPlan, ImmutableList.of(inPredicate.getValue()));
Symbol sourceJoinSymbol = subPlan.translate(inPredicate.getValue());
Preconditions.checkState(inPredicate.getValueList() instanceof SubqueryExpression);
SubqueryExpression subqueryExpression = (SubqueryExpression) inPredicate.getValueList();
RelationPlanner relationPlanner = new RelationPlanner(analysis, symbolAllocator, idAllocator, metadata, session);
RelationPlan valueListRelation = relationPlanner.process(subqueryExpression.getQuery(), null);
Symbol filteringSourceJoinSymbol = Iterables.getOnlyElement(valueListRelation.getRoot().getOutputSymbols());
Symbol semiJoinOutputSymbol = symbolAllocator.newSymbol("semijoinresult", Type.BOOLEAN);
translations.put(inPredicate, semiJoinOutputSymbol);
return new PlanBuilder(translations,
new SemiJoinNode(idAllocator.getNextId(),
subPlan.getRoot(),
valueListRelation.getRoot(),
sourceJoinSymbol,
filteringSourceJoinSymbol,
semiJoinOutputSymbol));
}
private PlanBuilder distinct(PlanBuilder subPlan, QuerySpecification node, List<FieldOrExpression> outputs, List<FieldOrExpression> orderBy)
{
if (node.getSelect().isDistinct()) {
checkState(outputs.containsAll(orderBy), "Expected ORDER BY terms to be in SELECT. Broken analysis");
AggregationNode aggregation = new AggregationNode(idAllocator.getNextId(),
subPlan.getRoot(),
subPlan.getRoot().getOutputSymbols(),
ImmutableMap.<Symbol, FunctionCall>of(),
ImmutableMap.<Symbol, FunctionHandle>of());
return new PlanBuilder(subPlan.getTranslations(), aggregation);
}
return subPlan;
}
private PlanBuilder sort(PlanBuilder subPlan, Query node)
{
return sort(subPlan, node.getOrderBy(), node.getLimit(), analysis.getOrderByExpressions(node));
}
private PlanBuilder sort(PlanBuilder subPlan, QuerySpecification node)
{
return sort(subPlan, node.getOrderBy(), node.getLimit(), analysis.getOrderByExpressions(node));
}
private PlanBuilder sort(PlanBuilder subPlan, List<SortItem> orderBy, Optional<String> limit, List<FieldOrExpression> orderByExpressions)
{
if (orderBy.isEmpty()) {
return subPlan;
}
Iterator<SortItem> sortItems = orderBy.iterator();
ImmutableList.Builder<Symbol> orderBySymbols = ImmutableList.builder();
ImmutableMap.Builder<Symbol, SortItem.Ordering> orderings = ImmutableMap.builder();
for (FieldOrExpression fieldOrExpression : orderByExpressions) {
Symbol symbol = subPlan.translate(fieldOrExpression);
orderBySymbols.add(symbol);
orderings.put(symbol, sortItems.next().getOrdering());
}
PlanNode planNode;
if (limit.isPresent()) {
planNode = new TopNNode(idAllocator.getNextId(), subPlan.getRoot(), Long.valueOf(limit.get()), orderBySymbols.build(), orderings.build(), false);
}
else {
planNode = new SortNode(idAllocator.getNextId(), subPlan.getRoot(), orderBySymbols.build(), orderings.build());
}
return new PlanBuilder(subPlan.getTranslations(), planNode);
}
private PlanBuilder limit(PlanBuilder subPlan, Query node)
{
return limit(subPlan, node.getOrderBy(), node.getLimit());
}
private PlanBuilder limit(PlanBuilder subPlan, QuerySpecification node)
{
return limit(subPlan, node.getOrderBy(), node.getLimit());
}
private PlanBuilder limit(PlanBuilder subPlan, List<SortItem> orderBy, Optional<String> limit)
{
if (orderBy.isEmpty() && limit.isPresent()) {
long limitValue = Long.valueOf(limit.get());
return new PlanBuilder(subPlan.getTranslations(), new LimitNode(idAllocator.getNextId(), subPlan.getRoot(), limitValue));
}
return subPlan;
}
public static Function<Expression, FieldOrExpression> toFieldOrExpression()
{
return new Function<Expression, FieldOrExpression>()
{
@Nullable
@Override
public FieldOrExpression apply(Expression input)
{
return new FieldOrExpression(input);
}
};
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.percolator;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.PrefixCodedTerms;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.queries.BlendedTermQuery;
import org.apache.lucene.queries.CommonTermsQuery;
import org.apache.lucene.queries.TermsQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.spans.FieldMaskingSpanQuery;
import org.apache.lucene.search.spans.SpanContainingQuery;
import org.apache.lucene.search.spans.SpanFirstQuery;
import org.apache.lucene.search.spans.SpanMultiTermQueryWrapper;
import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.search.spans.SpanNotQuery;
import org.apache.lucene.search.spans.SpanOrQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.search.spans.SpanWithinQuery;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.elasticsearch.common.logging.LoggerMessageFormat;
import org.elasticsearch.index.mapper.ParseContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Utility to extract query terms from queries and create queries from documents.
*/
public final class ExtractQueryTermsService {
private static final byte FIELD_VALUE_SEPARATOR = 0; // nul code point
private ExtractQueryTermsService() {
}
/**
* Extracts all terms from the specified query and adds it to the specified document.
* @param query The query to extract terms from
* @param document The document to add the extracted terms to
* @param queryTermsFieldField The field in the document holding the extracted terms
* @param unknownQueryField The field used to mark a document that not all query terms could be extracted. For example
* the query contained an unsupported query (e.g. WildcardQuery).
* @param fieldType The field type for the query metadata field
*/
public static void extractQueryTerms(Query query, ParseContext.Document document, String queryTermsFieldField, String unknownQueryField, FieldType fieldType) {
Set<Term> queryTerms;
try {
queryTerms = extractQueryTerms(query);
} catch (UnsupportedQueryException e) {
document.add(new Field(unknownQueryField, new BytesRef(), fieldType));
return;
}
for (Term term : queryTerms) {
BytesRefBuilder builder = new BytesRefBuilder();
builder.append(new BytesRef(term.field()));
builder.append(FIELD_VALUE_SEPARATOR);
builder.append(term.bytes());
document.add(new Field(queryTermsFieldField, builder.toBytesRef(), fieldType));
}
}
/**
* Extracts all query terms from the provided query and adds it to specified list.
*
* From boolean query with no should clauses or phrase queries only the longest term are selected,
* since that those terms are likely to be the rarest. Boolean query's must_not clauses are always ignored.
*
* If from part of the query, no query terms can be extracted then term extraction is stopped and
* an UnsupportedQueryException is thrown.
*/
static Set<Term> extractQueryTerms(Query query) {
if (query instanceof TermQuery) {
return Collections.singleton(((TermQuery) query).getTerm());
} else if (query instanceof TermsQuery) {
Set<Term> terms = new HashSet<>();
TermsQuery termsQuery = (TermsQuery) query;
PrefixCodedTerms.TermIterator iterator = termsQuery.getTermData().iterator();
for (BytesRef term = iterator.next(); term != null; term = iterator.next()) {
terms.add(new Term(iterator.field(), term));
}
return terms;
} else if (query instanceof PhraseQuery) {
Term[] terms = ((PhraseQuery) query).getTerms();
if (terms.length == 0) {
return Collections.emptySet();
}
// the longest term is likely to be the rarest,
// so from a performance perspective it makes sense to extract that
Term longestTerm = terms[0];
for (Term term : terms) {
if (longestTerm.bytes().length < term.bytes().length) {
longestTerm = term;
}
}
return Collections.singleton(longestTerm);
} else if (query instanceof BooleanQuery) {
List<BooleanClause> clauses = ((BooleanQuery) query).clauses();
boolean hasRequiredClauses = false;
for (BooleanClause clause : clauses) {
if (clause.isRequired()) {
hasRequiredClauses = true;
break;
}
}
if (hasRequiredClauses) {
Set<Term> bestClause = null;
for (BooleanClause clause : clauses) {
if (clause.isRequired() == false) {
// skip must_not clauses, we don't need to remember the things that do *not* match...
// skip should clauses, this bq has must clauses, so we don't need to remember should clauses, since they are completely optional.
continue;
}
Set<Term> temp = extractQueryTerms(clause.getQuery());
bestClause = selectTermListWithTheLongestShortestTerm(temp, bestClause);
}
if (bestClause != null) {
return bestClause;
} else {
return Collections.emptySet();
}
} else {
Set<Term> terms = new HashSet<>();
for (BooleanClause clause : clauses) {
if (clause.isProhibited()) {
// we don't need to remember the things that do *not* match...
continue;
}
terms.addAll(extractQueryTerms(clause.getQuery()));
}
return terms;
}
} else if (query instanceof ConstantScoreQuery) {
Query wrappedQuery = ((ConstantScoreQuery) query).getQuery();
return extractQueryTerms(wrappedQuery);
} else if (query instanceof BoostQuery) {
Query wrappedQuery = ((BoostQuery) query).getQuery();
return extractQueryTerms(wrappedQuery);
} else if (query instanceof CommonTermsQuery) {
List<Term> terms = ((CommonTermsQuery) query).getTerms();
return new HashSet<>(terms);
} else if (query instanceof BlendedTermQuery) {
List<Term> terms = ((BlendedTermQuery) query).getTerms();
return new HashSet<>(terms);
} else if (query instanceof SpanTermQuery) {
return Collections.singleton(((SpanTermQuery) query).getTerm());
} else if (query instanceof SpanNearQuery) {
Set<Term> bestClause = null;
SpanNearQuery spanNearQuery = (SpanNearQuery) query;
for (SpanQuery clause : spanNearQuery.getClauses()) {
Set<Term> temp = extractQueryTerms(clause);
bestClause = selectTermListWithTheLongestShortestTerm(temp, bestClause);
}
return bestClause;
} else if (query instanceof SpanOrQuery) {
Set<Term> terms = new HashSet<>();
SpanOrQuery spanOrQuery = (SpanOrQuery) query;
for (SpanQuery clause : spanOrQuery.getClauses()) {
terms.addAll(extractQueryTerms(clause));
}
return terms;
} else if (query instanceof SpanFirstQuery) {
return extractQueryTerms(((SpanFirstQuery)query).getMatch());
} else if (query instanceof SpanNotQuery) {
return extractQueryTerms(((SpanNotQuery) query).getInclude());
} else {
throw new UnsupportedQueryException(query);
}
}
static Set<Term> selectTermListWithTheLongestShortestTerm(Set<Term> terms1, Set<Term> terms2) {
if (terms1 == null) {
return terms2;
} else if (terms2 == null) {
return terms1;
} else {
int terms1ShortestTerm = minTermLength(terms1);
int terms2ShortestTerm = minTermLength(terms2);
// keep the clause with longest terms, this likely to be rarest.
if (terms1ShortestTerm >= terms2ShortestTerm) {
return terms1;
} else {
return terms2;
}
}
}
private static int minTermLength(Set<Term> terms) {
int min = Integer.MAX_VALUE;
for (Term term : terms) {
min = Math.min(min, term.bytes().length);
}
return min;
}
/**
* Creates a boolean query with a should clause for each term on all fields of the specified index reader.
*/
public static Query createQueryTermsQuery(IndexReader indexReader, String queryMetadataField, String unknownQueryField) throws IOException {
List<Term> extractedTerms = new ArrayList<>();
extractedTerms.add(new Term(unknownQueryField));
Fields fields = MultiFields.getFields(indexReader);
for (String field : fields) {
Terms terms = fields.terms(field);
if (terms == null) {
continue;
}
BytesRef fieldBr = new BytesRef(field);
TermsEnum tenum = terms.iterator();
for (BytesRef term = tenum.next(); term != null ; term = tenum.next()) {
BytesRefBuilder builder = new BytesRefBuilder();
builder.append(fieldBr);
builder.append(FIELD_VALUE_SEPARATOR);
builder.append(term);
extractedTerms.add(new Term(queryMetadataField, builder.toBytesRef()));
}
}
return new TermsQuery(extractedTerms);
}
/**
* Exception indicating that none or some query terms couldn't extracted from a percolator query.
*/
public static class UnsupportedQueryException extends RuntimeException {
private final Query unsupportedQuery;
public UnsupportedQueryException(Query unsupportedQuery) {
super(LoggerMessageFormat.format("no query terms can be extracted from query [{}]", unsupportedQuery));
this.unsupportedQuery = unsupportedQuery;
}
/**
* The actual Lucene query that was unsupported and caused this exception to be thrown.
*/
public Query getUnsupportedQuery() {
return unsupportedQuery;
}
}
}
| |
/*
* 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.segment.column;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Strings;
import io.druid.java.util.common.guava.CloseQuietly;
import io.druid.query.extraction.ExtractionFn;
import io.druid.query.filter.ValueMatcher;
import io.druid.query.monomorphicprocessing.RuntimeShapeInspector;
import io.druid.segment.DimensionSelectorUtils;
import io.druid.segment.IdLookup;
import io.druid.segment.data.CachingIndexed;
import io.druid.segment.data.IndexedInts;
import io.druid.segment.data.IndexedMultivalue;
import io.druid.segment.data.ReadableOffset;
import io.druid.segment.data.SingleIndexedInt;
import io.druid.segment.filter.BooleanValueMatcher;
import io.druid.segment.historical.HistoricalDimensionSelector;
import io.druid.segment.historical.SingleValueHistoricalDimensionSelector;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.BitSet;
/**
*/
public class SimpleDictionaryEncodedColumn
implements DictionaryEncodedColumn<String>
{
private final IndexedInts column;
private final IndexedMultivalue<IndexedInts> multiValueColumn;
private final CachingIndexed<String> cachedLookups;
public SimpleDictionaryEncodedColumn(
IndexedInts singleValueColumn,
IndexedMultivalue<IndexedInts> multiValueColumn,
CachingIndexed<String> cachedLookups
)
{
this.column = singleValueColumn;
this.multiValueColumn = multiValueColumn;
this.cachedLookups = cachedLookups;
}
@Override
public int length()
{
return hasMultipleValues() ? multiValueColumn.size() : column.size();
}
@Override
public boolean hasMultipleValues()
{
return column == null;
}
@Override
public int getSingleValueRow(int rowNum)
{
return column.get(rowNum);
}
@Override
public IndexedInts getMultiValueRow(int rowNum)
{
return multiValueColumn.get(rowNum);
}
@Override
public String lookupName(int id)
{
//Empty to Null will ensure that null and empty are equivalent for extraction function
return Strings.emptyToNull(cachedLookups.get(id));
}
@Override
public int lookupId(String name)
{
return cachedLookups.indexOf(name);
}
@Override
public int getCardinality()
{
return cachedLookups.size();
}
@Override
public HistoricalDimensionSelector makeDimensionSelector(final ReadableOffset offset, final ExtractionFn extractionFn)
{
abstract class QueryableDimensionSelector implements HistoricalDimensionSelector, IdLookup
{
@Override
public int getValueCardinality()
{
return getCardinality();
}
@Override
public String lookupName(int id)
{
final String value = SimpleDictionaryEncodedColumn.this.lookupName(id);
return extractionFn == null ?
value :
extractionFn.apply(value);
}
@Override
public boolean nameLookupPossibleInAdvance()
{
return true;
}
@Nullable
@Override
public IdLookup idLookup()
{
return extractionFn == null ? this : null;
}
@Override
public int lookupId(String name)
{
if (extractionFn != null) {
throw new UnsupportedOperationException(
"cannot perform lookup when applying an extraction function"
);
}
return SimpleDictionaryEncodedColumn.this.lookupId(name);
}
}
if (hasMultipleValues()) {
class MultiValueDimensionSelector extends QueryableDimensionSelector
{
@Override
public IndexedInts getRow()
{
return multiValueColumn.get(offset.getOffset());
}
@Override
public IndexedInts getRow(int offset)
{
return multiValueColumn.get(offset);
}
@Override
public ValueMatcher makeValueMatcher(String value)
{
return DimensionSelectorUtils.makeValueMatcherGeneric(this, value);
}
@Override
public ValueMatcher makeValueMatcher(Predicate<String> predicate)
{
return DimensionSelectorUtils.makeValueMatcherGeneric(this, predicate);
}
@Override
public void inspectRuntimeShape(RuntimeShapeInspector inspector)
{
inspector.visit("multiValueColumn", multiValueColumn);
inspector.visit("offset", offset);
inspector.visit("extractionFn", extractionFn);
}
}
return new MultiValueDimensionSelector();
} else {
class SingleValueQueryableDimensionSelector extends QueryableDimensionSelector
implements SingleValueHistoricalDimensionSelector
{
@Override
public IndexedInts getRow()
{
return new SingleIndexedInt(getRowValue());
}
@Override
public int getRowValue()
{
return column.get(offset.getOffset());
}
@Override
public IndexedInts getRow(int offset)
{
return new SingleIndexedInt(getRowValue(offset));
}
@Override
public int getRowValue(int offset)
{
return column.get(offset);
}
@Override
public ValueMatcher makeValueMatcher(final String value)
{
if (extractionFn == null) {
final int valueId = lookupId(value);
if (valueId >= 0) {
return new ValueMatcher()
{
@Override
public boolean matches()
{
return getRowValue() == valueId;
}
@Override
public void inspectRuntimeShape(RuntimeShapeInspector inspector)
{
inspector.visit("column", SimpleDictionaryEncodedColumn.this);
}
};
} else {
return BooleanValueMatcher.of(false);
}
} else {
// Employ precomputed BitSet optimization
return makeValueMatcher(Predicates.equalTo(value));
}
}
@Override
public ValueMatcher makeValueMatcher(final Predicate<String> predicate)
{
final BitSet predicateMatchingValueIds = DimensionSelectorUtils.makePredicateMatchingSet(
this,
predicate
);
return new ValueMatcher()
{
@Override
public boolean matches()
{
return predicateMatchingValueIds.get(getRowValue());
}
@Override
public void inspectRuntimeShape(RuntimeShapeInspector inspector)
{
inspector.visit("column", SimpleDictionaryEncodedColumn.this);
}
};
}
@Override
public void inspectRuntimeShape(RuntimeShapeInspector inspector)
{
inspector.visit("column", column);
inspector.visit("offset", offset);
inspector.visit("extractionFn", extractionFn);
}
}
return new SingleValueQueryableDimensionSelector();
}
}
@Override
public void close() throws IOException
{
CloseQuietly.close(cachedLookups);
if (column != null) {
column.close();
}
if (multiValueColumn != null) {
multiValueColumn.close();
}
}
}
| |
/*
* 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.blockray;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.flowpowered.math.GenericMath;
import com.flowpowered.math.imaginary.Quaterniond;
import com.flowpowered.math.vector.Vector3d;
import com.flowpowered.math.vector.Vector3i;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.data.property.block.FullBlockSelectionBoxProperty;
import org.spongepowered.api.data.property.entity.EyeLocationProperty;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.util.Functional;
import org.spongepowered.api.util.Tuple;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.extent.Extent;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.function.Predicate;
/**
* A block ray which traces a line and returns all block boundaries intersected
* in order, starting from the start location. If the ray starts in a block,
* that block is never returned because it is never entered (the ray is already
* inside).
*
* <p>This class implements the
* {@link Iterator} interface with the exception of {@link Iterator#remove()}.
* </p>
*
* <p>Filters determine what blocks the {@link BlockRay} should accept. First
* the stop filter is called. If it returns false then the iterator ends there.
* Otherwise the skip filter is called. If it returns false then the iterator
* proceeds to the next block and it is never returned. Otherwise the block is
* returned. If the distance limit is enabled then it is applied before both
* filters and acts like the stop filter.</p>
*
* <p>Any one instance of a {@link Predicate} should only be run on one path.
* It is not specified that {@link Predicate}s have to be stateless, pure
* functions. They are allowed to keep state along an individual path, based on
* the assertion that a single instance is only called on one path.</p>
*
* <p>Filters are most useful for limiting the target block a player is looking
* at based on some metric, like transparency, block model, or even distance.
* The standard Bukkit-like behavior for finding the target block can be
* achieved with using {@link BlockRay#ONLY_AIR_FILTER} as the
* {@code stopFilter}, combined with
* {@link #continueAfterFilter(Predicate, int)} with a second argument of 1, to
* obtain the block just after the last air.</p>
*
* <p>To get a block ray for an entities' line of sight, use
* <pre>{@code BlockRay.from(entity);}</pre></p>
*
* @param <E> The extent in which this ray is being cast
* @see BlockRayHit
*/
public class BlockRay<E extends Extent> implements Iterator<BlockRayHit<E>> {
@SuppressWarnings("rawtypes")
private static final Predicate ONLY_AIR_FILTER = blockTypeFilter(BlockTypes.AIR);
@SuppressWarnings("rawtypes")
static final Predicate ALL_FILTER = input -> true;
private static final Vector3d X_POSITIVE = Vector3d.UNIT_X;
private static final Vector3d X_NEGATIVE = X_POSITIVE.negate();
private static final Vector3d Y_POSITIVE = Vector3d.UNIT_Y;
private static final Vector3d Y_NEGATIVE = Y_POSITIVE.negate();
private static final Vector3d Z_POSITIVE = Vector3d.UNIT_Z;
private static final Vector3d Z_NEGATIVE = Z_POSITIVE.negate();
// Skipping and ending test predicates
private final Predicate<BlockRayHit<E>> skipFilter;
private final Predicate<BlockRayHit<E>> stopFilter;
// Extent to iterate in
private final E extent;
// Starting position
private final Vector3d position;
// Direction of the ray
private final Vector3d direction;
// Perform narrow phase intersections for blocks with smaller selection boxes
private final boolean narrowPhase;
// The directions the faces are passed through
private final Vector3d xNormal;
private final Vector3d yNormal;
private final Vector3d zNormal;
// The directions the edges and corners are passed through, lazily computed
private Vector3d xyzNormal;
private Vector3d xyNormal;
private Vector3d xzNormal;
private Vector3d yzNormal;
// The plane increments for the direction
private final int xPlaneIncrement;
private final int yPlaneIncrement;
private final int zPlaneIncrement;
// The current coordinates
private double xCurrent;
private double yCurrent;
private double zCurrent;
// The current passed face
private Vector3d normalCurrent;
// The next plane values
private int xPlaneNext;
private int yPlaneNext;
private int zPlaneNext;
// The solutions for the nearest plane intersections
private double xPlaneT;
private double yPlaneT;
private double zPlaneT;
// Limits to help prevent infinite iteration
private final double distanceLimit;
// Last block hit
private BlockRayHit<E> hit;
// If hasNext() is called, we need to move ahead to check the next hit
private boolean ahead;
private BlockRay(Predicate<BlockRayHit<E>> skipFilter, Predicate<BlockRayHit<E>> stopFilter, E extent, Vector3d position, Vector3d direction,
boolean narrowPhase, double distanceLimit) {
checkArgument(direction.lengthSquared() != 0, "Direction cannot be the zero vector");
this.skipFilter = skipFilter;
this.stopFilter = stopFilter;
this.extent = extent;
this.position = position;
this.direction = direction;
this.narrowPhase = narrowPhase;
this.distanceLimit = distanceLimit;
// Figure out the direction of the ray for each axis
if (this.direction.getX() >= 0) {
this.xPlaneIncrement = 1;
this.xNormal = X_NEGATIVE;
} else {
this.xPlaneIncrement = -1;
this.xNormal = X_POSITIVE;
}
if (this.direction.getY() >= 0) {
this.yPlaneIncrement = 1;
this.yNormal = Y_NEGATIVE;
} else {
this.yPlaneIncrement = -1;
this.yNormal = Y_POSITIVE;
}
if (this.direction.getZ() >= 0) {
this.zPlaneIncrement = 1;
this.zNormal = Z_NEGATIVE;
} else {
this.zPlaneIncrement = -1;
this.zNormal = Z_POSITIVE;
}
reset();
}
/**
* Resets the iterator; it will iterate from the starting location again.
*/
public final void reset() {
// Start at the position
this.xCurrent = this.position.getX();
this.yCurrent = this.position.getY();
this.zCurrent = this.position.getZ();
// First planes are for the block that contains the coordinates
this.xPlaneNext = GenericMath.floor(this.xCurrent);
// noinspection SuspiciousNameCombination
this.yPlaneNext = GenericMath.floor(this.yCurrent);
this.zPlaneNext = GenericMath.floor(this.zCurrent);
// Correct the next planes for the direction when inside the block
if (this.xCurrent - this.xPlaneNext != 0 && this.direction.getX() >= 0) {
this.xPlaneNext++;
}
if (this.yCurrent - this.yPlaneNext != 0 && this.direction.getY() >= 0) {
this.yPlaneNext++;
}
if (this.zCurrent - this.zPlaneNext != 0 && this.direction.getZ() >= 0) {
this.zPlaneNext++;
}
// Compute the first intersection solutions for each plane
this.xPlaneT = (this.xPlaneNext - this.position.getX()) / this.direction.getX();
this.yPlaneT = (this.yPlaneNext - this.position.getY()) / this.direction.getY();
this.zPlaneT = (this.zPlaneNext - this.position.getZ()) / this.direction.getZ();
// We start in the block, no plane has been entered yet
this.normalCurrent = Vector3d.ZERO;
// Reset the block
this.ahead = false;
this.hit = null;
}
@Override
public boolean hasNext() {
if (this.ahead) {
// We already checked
return true;
}
try {
advance();
this.ahead = true;
return true;
} catch (NoSuchElementException exception) {
return false;
}
}
@Override
public BlockRayHit<E> next() {
if (this.ahead) {
// We already advanced in hasNext()
this.ahead = false;
} else {
advance();
}
return this.hit;
}
/**
* Traces the block ray to the end and returns the last block
* accepted by the filter, or none if the extent or block limit was reached.
* This advances the iterator.
*
* @return The last block of the ray, if any
*/
public Optional<BlockRayHit<E>> end() {
BlockRayHit<E> last = null;
while (hasNext()) {
last = next();
}
return Optional.ofNullable(last);
}
@SuppressWarnings("StatementWithEmptyBody")
private void advance() {
while (!advanceOneBlock()) {
}
}
private boolean advanceOneBlock() {
/*
The ray can be modeled using the following parametric equations:
x = d_x * t + p_x
y = d_y * t + p_y
z = d_z * t + p_z
Where d is the direction vector, p the starting point and t is in |R.
The block boundary grid can be modeled as an infinity of perpendicular planes
on the x, y and z axes, on integer coordinates, spaced 1 unit away.
Such a plane has an equation:
A = n
Where A is the axis label and n is in |Z
The solution of the intersection between the above ray and such a plane is:
n = d_A * t_s + p_A
t_s = (n - p_A) / d_A
x_s = d_x * t_s + p_x
y_s = d_y * t_s + p_y
z_s = d_z * t_s + p_z
Where t_s is the solution parameter and x_s, y_s, z_s are the intersection coordinates.
A small optimization is that A_s = n, which also helps with rounding errors.
The iterator solves these equations and provides the solutions in increasing order with respect to t_s.
*/
if (this.direction.getX() == 0) {
if (this.direction.getY() == 0) {
// Only zPlaneT exists
zIntersect();
} else if (this.direction.getZ() == 0) {
// Only yPlaneT exists
yIntersect();
} else {
// yPlaneT and zPlaneT exist
solveIntersections();
}
} else if (this.direction.getY() == 0) {
if (this.direction.getZ() == 0) {
// Only xPlaneT exists
xIntersect();
} else {
// xPlaneT and zPlaneT exist
solveIntersections();
}
} else {
// xPlaneT and yPlaneT exist
solveIntersections();
}
BlockRayHit<E> hit = new BlockRayHit<>(this.extent, this.xCurrent, this.yCurrent, this.zCurrent, this.direction, this.normalCurrent);
// Make sure we actually have a block
if (!hit.mapBlock(Extent::containsBlock)) {
throw new NoSuchElementException("Extent limit reached");
}
// Now if using the narrow phase, test on small selection boxes, if needed
if (this.narrowPhase && !hit.getExtent().getProperty(hit.getBlockPosition(), FullBlockSelectionBoxProperty.class)
.map(FullBlockSelectionBoxProperty::getValue).orElse(true)) {
// Get the selection box and perform the narrow phase intersection test
final Optional<Tuple<Vector3d, Vector3d>> intersection = hit.mapBlock(Extent::getBlockSelectionBox)
.flatMap(aabb -> aabb.intersects(this.position, this.direction));
// Create the new narrow hit if there was an intersection
if (intersection.isPresent()) {
final Tuple<Vector3d, Vector3d> pair = intersection.get();
final Vector3d narrowHit = pair.getFirst();
hit = new BlockRayHit<>(this.extent, narrowHit.getX(), narrowHit.getY(), narrowHit.getZ(), this.direction, pair.getSecond());
} else {
// Otherwise return false to attempt the next block
return false;
}
}
// Check the distance limit if in use
if (this.distanceLimit >= 0 && this.position.distanceSquared(hit.getPosition()) > this.distanceLimit * this.distanceLimit) {
throw new NoSuchElementException("Distance limit reached");
}
// Check the block end filter
if (!this.stopFilter.test(hit)) {
throw new NoSuchElementException("Filter limit reached");
}
// Check the block skip filter
if (!this.skipFilter.test(hit)) {
return false;
}
this.hit = hit;
return true;
}
private void solveIntersections() {
if (this.xPlaneT == this.yPlaneT) {
if (this.xPlaneT == this.zPlaneT) {
// xPlaneT, yPlaneT and zPlaneT are equal
xyzIntersect();
} else {
// xPlaneT and yPlaneT are equal
xyIntersect();
}
} else if (this.xPlaneT == this.zPlaneT) {
// xPlaneT and zPlaneT are equal
xzIntersect();
} else if (this.yPlaneT == this.zPlaneT) {
// yPlaneT and zPlaneT are equal
yzIntersect();
} else if (this.xPlaneT < this.yPlaneT) {
if (this.xPlaneT < this.zPlaneT) {
// xPlaneT is smallest
xIntersect();
} else {
// zPlaneT is smallest
zIntersect();
}
} else if (this.yPlaneT < this.zPlaneT) {
// yPlaneT is smallest
yIntersect();
} else {
// zPlaneT is smallest
zIntersect();
}
}
private void xyzIntersect() {
this.xCurrent = this.xPlaneNext;
this.yCurrent = this.yPlaneNext;
this.zCurrent = this.zPlaneNext;
this.normalCurrent = getXyzNormal();
// Prepare next intersection
this.xPlaneNext += this.xPlaneIncrement;
this.yPlaneNext += this.yPlaneIncrement;
this.zPlaneNext += this.zPlaneIncrement;
this.xPlaneT = (this.xPlaneNext - this.position.getX()) / this.direction.getX();
this.yPlaneT = (this.yPlaneNext - this.position.getY()) / this.direction.getY();
this.zPlaneT = (this.zPlaneNext - this.position.getZ()) / this.direction.getZ();
}
private void xyIntersect() {
this.xCurrent = this.xPlaneNext;
this.yCurrent = this.yPlaneNext;
this.zCurrent = this.direction.getZ() * this.xPlaneT + this.position.getZ();
this.normalCurrent = getXyNormal();
// Prepare next intersection
this.xPlaneNext += this.xPlaneIncrement;
this.yPlaneNext += this.yPlaneIncrement;
this.xPlaneT = (this.xPlaneNext - this.position.getX()) / this.direction.getX();
this.yPlaneT = (this.yPlaneNext - this.position.getY()) / this.direction.getY();
}
private void xzIntersect() {
this.xCurrent = this.xPlaneNext;
this.yCurrent = this.direction.getY() * this.xPlaneT + this.position.getY();
this.zCurrent = this.zPlaneNext;
this.normalCurrent = getXzNormal();
// Prepare next intersection
this.xPlaneNext += this.xPlaneIncrement;
this.zPlaneNext += this.zPlaneIncrement;
this.xPlaneT = (this.xPlaneNext - this.position.getX()) / this.direction.getX();
this.zPlaneT = (this.zPlaneNext - this.position.getZ()) / this.direction.getZ();
}
private void yzIntersect() {
this.xCurrent = this.direction.getX() * this.yPlaneT + this.position.getX();
this.yCurrent = this.yPlaneNext;
this.zCurrent = this.zPlaneNext;
this.normalCurrent = getYzNormal();
// Prepare next intersection
this.yPlaneNext += this.yPlaneIncrement;
this.zPlaneNext += this.zPlaneIncrement;
this.yPlaneT = (this.yPlaneNext - this.position.getY()) / this.direction.getY();
this.zPlaneT = (this.zPlaneNext - this.position.getZ()) / this.direction.getZ();
}
private void xIntersect() {
this.xCurrent = this.xPlaneNext;
this.yCurrent = this.direction.getY() * this.xPlaneT + this.position.getY();
this.zCurrent = this.direction.getZ() * this.xPlaneT + this.position.getZ();
this.normalCurrent = this.xNormal;
// Prepare next intersection
this.xPlaneNext += this.xPlaneIncrement;
this.xPlaneT = (this.xPlaneNext - this.position.getX()) / this.direction.getX();
}
private void yIntersect() {
this.xCurrent = this.direction.getX() * this.yPlaneT + this.position.getX();
this.yCurrent = this.yPlaneNext;
this.zCurrent = this.direction.getZ() * this.yPlaneT + this.position.getZ();
this.normalCurrent = this.yNormal;
// Prepare next intersection
this.yPlaneNext += this.yPlaneIncrement;
this.yPlaneT = (this.yPlaneNext - this.position.getY()) / this.direction.getY();
}
private void zIntersect() {
this.xCurrent = this.direction.getX() * this.zPlaneT + this.position.getX();
this.yCurrent = this.direction.getY() * this.zPlaneT + this.position.getY();
this.zCurrent = this.zPlaneNext;
this.normalCurrent = this.zNormal;
// Prepare next intersection
this.zPlaneNext += this.zPlaneIncrement;
this.zPlaneT = (this.zPlaneNext - this.position.getZ()) / this.direction.getZ();
}
private Vector3d getXyzNormal() {
if (this.xyzNormal == null) {
this.xyzNormal = this.xNormal.add(this.yNormal).add(this.zNormal).normalize();
}
return this.xyzNormal;
}
private Vector3d getXyNormal() {
if (this.xyNormal == null) {
this.xyNormal = this.xNormal.add(this.yNormal).normalize();
}
return this.xyNormal;
}
private Vector3d getXzNormal() {
if (this.xzNormal == null) {
this.xzNormal = this.xNormal.add(this.zNormal).normalize();
}
return this.xzNormal;
}
private Vector3d getYzNormal() {
if (this.yzNormal == null) {
this.yzNormal = this.yNormal.add(this.zNormal).normalize();
}
return this.yzNormal;
}
/**
* Initializes a block ray builder with the given starting location.
*
* @param start The starting location
* @param <E> The extent to be applied in
* @return A new block ray builder
*/
public static <E extends Extent> BlockRayBuilder<E> from(Location<E> start) {
checkNotNull(start, "start");
return from(start.getExtent(), start.getPosition());
}
/**
* Initializes a block ray builder with the given starting location.
*
* @param extent The extent in which to trace the ray
* @param start The starting position
* @param <E> The extent to be applied in
* @return A new block ray builder
*/
public static <E extends Extent> BlockRayBuilder<E> from(E extent, Vector3d start) {
checkNotNull(extent, "extent");
checkNotNull(start, "start");
return new BlockRayBuilder<>(extent, start);
}
/**
* Initializes a block ray builder for the entity's eye.
* If the eye location isn't defined for the entity, the
* regular location is used. This sets both the starting
* point and direction.
*
* @param entity The entity
* @return A new block ray builder
*/
public static BlockRayBuilder<World> from(Entity entity) {
checkNotNull(entity, "entity");
final Vector3d rotation = entity.getRotation();
final Vector3d direction = Quaterniond.fromAxesAnglesDeg(rotation.getX(), -rotation.getY(), rotation.getZ()).getDirection();
final Location<World> location = entity.getLocation();
final Optional<EyeLocationProperty> data = entity.getProperty(EyeLocationProperty.class);
final Vector3d position = data.map(EyeLocationProperty::getValue).orElse(location.getPosition());
return from(location.getExtent(), position).direction(direction);
}
/**
* A builder for block ray, which also implements {@link Iterable}, making it
* useful for 'advanced for loops'. Use {@link #from(Location)} to get an instance.
*
* @param <E> The type of the extent for the block ray
*/
public static class BlockRayBuilder<E extends Extent> implements Iterable<BlockRayHit<E>> {
private static final double DEFAULT_DISTANCE_LIMIT = 1000;
private final E extent;
private final Vector3d position;
private Predicate<BlockRayHit<E>> skipFilter = allFilter();
private Predicate<BlockRayHit<E>> stopFilter = allFilter();
private Vector3d direction = null;
private double distanceLimit = DEFAULT_DISTANCE_LIMIT;
private boolean narrowPhase = true;
private BlockRayBuilder(E extent, Vector3d position) {
this.extent = extent;
this.position = position;
}
/**
* Adds the filter to the block ray.
* The block ray will skip over blocks that do not pass this predicate.
* This is optional.
* Multiple filters will be ANDed together.
*
* @param skipFilter The filter to add
* @return This for chained calls
*/
public BlockRayBuilder<E> skipFilter(final Predicate<BlockRayHit<E>> skipFilter) {
checkNotNull(skipFilter, "skipFilter");
if (this.skipFilter == ALL_FILTER) {
this.skipFilter = skipFilter;
} else {
this.skipFilter = this.skipFilter.and(skipFilter);
}
return this;
}
/**
* Adds filters to the block ray.
* The block ray will skip over blocks that do not pass this predicate.
* This is optional.
* Multiple filters will be ANDed together.
*
* @param skipFilters The filters to add
* @return This for chained calls
*/
@SafeVarargs
@SuppressWarnings("varargs")
public final BlockRayBuilder<E> skipFilter(final Predicate<BlockRayHit<E>>... skipFilters) {
checkNotNull(skipFilters, "filters");
final Predicate<BlockRayHit<E>> skipFilter = skipFilters.length == 1 ? skipFilters[0] : Functional.predicateAnd(skipFilters);
if (this.skipFilter == ALL_FILTER) {
this.skipFilter = skipFilter;
} else {
this.skipFilter = this.skipFilter.and(skipFilter);
}
return this;
}
/**
* Adds the filter to the block ray.
* The block ray will end if a block does not pass this predicate.
* This is optional.
* Multiple filters will be ANDed together.
*
* @param stopFilter The filter to add
* @return This for chained calls
*/
public BlockRayBuilder<E> stopFilter(final Predicate<BlockRayHit<E>> stopFilter) {
checkNotNull(stopFilter, "stopFilter");
if (this.stopFilter == ALL_FILTER) {
this.stopFilter = stopFilter;
} else {
this.stopFilter = this.stopFilter.and(stopFilter);
}
return this;
}
/**
* Adds filters to the block ray.
* The block ray will end if a block does not pass this predicate.
* This is optional.
* Multiple filters will be ANDed together.
*
* @param stopFilters The filters to add
* @return This for chained calls
*/
@SafeVarargs
@SuppressWarnings("varargs")
public final BlockRayBuilder<E> stopFilter(final Predicate<BlockRayHit<E>>... stopFilters) {
checkNotNull(stopFilters, "stopFilters");
final Predicate<BlockRayHit<E>> endFilter = stopFilters.length == 1 ? stopFilters[0] : Functional.predicateAnd(stopFilters);
if (this.stopFilter == ALL_FILTER) {
this.stopFilter = endFilter;
} else {
this.stopFilter = this.stopFilter.and(endFilter);
}
return this;
}
/**
* Sets the direction and ending location. This or setting the direction
* is required and can only be done once.
*
* @param end The ending location
* @return This for chained calls
*/
public BlockRayBuilder<E> to(Vector3d end) {
checkState(this.direction == null, "Direction has already been set");
checkNotNull(end, "end");
checkArgument(!this.position.equals(end), "Start and end cannot be equal");
this.direction = end.sub(this.position).normalize();
return stopFilter(new TargetBlockFilter<>(end));
}
/**
* Sets the direction. This or setting the ending location is required
* and can only be done once.
*
* @param direction The direction
* @return This for chained calls
*/
public BlockRayBuilder<E> direction(Vector3d direction) {
checkState(this.direction == null, "Direction has already been set");
checkNotNull(direction, "direction");
checkArgument(direction.lengthSquared() != 0, "Direction must be a non-zero vector");
this.direction = direction.normalize();
return this;
}
/**
* Sets the maximum distance before stopping.
* This is a safeguard to prevent infinite iteration.
* Default value is 1000. Use a negative value to disable this.
*
* @param distanceLimit The distance limit
* @return This for chained calls
*/
public BlockRayBuilder<E> distanceLimit(double distanceLimit) {
this.distanceLimit = distanceLimit;
return this;
}
/**
* Sets whether or not to perform narrow phase intersections. The
* narrow phase performs intersections with the block selection boxes
* if they are smaller than a voxel. This is necessary to obtain
* correct intersections with small blocks like: signs, buttons,
* fences, etc. This is enabled by default.
*
* @param enable Whether or not to enable the narrow phase
* @return This for chained calls
*/
public BlockRayBuilder<E> narrowPhase(boolean enable) {
this.narrowPhase = enable;
return this;
}
/**
* Gets the starting position of the block ray. Given here since some
* filters might require it.
*
* @return The position of the block ray
*/
public Vector3d position() {
return this.position;
}
/**
* Returns a block ray build from the settings. An ending location or
* direction needs to have been set.
*
* @return A block ray
*/
public BlockRay<E> build() {
checkState(this.direction != null, "Either end point or direction needs to be set");
return new BlockRay<>(this.skipFilter, this.stopFilter, this.extent, this.position, this.direction, this.narrowPhase, this.distanceLimit);
}
@Override
public Iterator<BlockRayHit<E>> iterator() {
return build();
}
/**
* Iterates the built block ray until the end
* and returns the last hit, if any.
*
* @return The last block hit, if any
* @see #build()
* @see BlockRay#end()
*/
public Optional<BlockRayHit<E>> end() {
return build().end();
}
}
/**
* A filter that accepts all blocks. A {@link BlockRay} combined with no
* other filter than this one could run endlessly.
*
* @param <E> The extent to be applied in
* @return A filter that accepts all blocks
*/
@SuppressWarnings("unchecked")
public static <E extends Extent> Predicate<BlockRayHit<E>> allFilter() {
return ALL_FILTER;
}
/**
* A block type filter that only permits air as a transparent block.
*
* <p>This is provided for convenience, as the default behavior in previous
* systems was to pass through air blocks only until a non-air block was
* hit.</p>
*
* @param <E> The extent to be applied in
* @return A filter that only accepts air blocks
*/
@SuppressWarnings("unchecked")
public static <E extends Extent> Predicate<BlockRayHit<E>> onlyAirFilter() {
return ONLY_AIR_FILTER;
}
/**
* A filter that only allows blocks of a certain type.
*
* @param type The type of blocks to allow
* @param <E> The extent to be applied in
* @return The filter instance
*/
public static <E extends Extent> Predicate<BlockRayHit<E>> blockTypeFilter(final BlockType type) {
return lastHit -> lastHit.getExtent().getBlockType(lastHit.getBlockX(), lastHit.getBlockY(), lastHit.getBlockZ()).equals(type);
}
/**
* Extends a filter by a number of blocks, regardless of what the extended
* filter does.
*
* @param filter The filter to extend
* @param numberOfBlocks The number of blocks to extend it by
* @param <E> The extent to be applied in
* @return The extended block filter
*/
public static <E extends Extent> Predicate<BlockRayHit<E>> continueAfterFilter(Predicate<BlockRayHit<E>> filter, int numberOfBlocks) {
return new ContinueAfterFilter<>(filter, numberOfBlocks);
}
private static class ContinueAfterFilter<E extends Extent> implements Predicate<BlockRayHit<E>> {
private final Predicate<BlockRayHit<E>> filter;
final int numberOfBlocks;
int extraBlockCount = 0;
ContinueAfterFilter(Predicate<BlockRayHit<E>> filter, int numberOfBlocks) {
this.filter = filter;
this.numberOfBlocks = numberOfBlocks;
}
@Override
public boolean test(BlockRayHit<E> lastHit) {
if (this.extraBlockCount <= 0) {
if (!this.filter.test(lastHit)) {
this.extraBlockCount = 1;
}
return true;
}
return this.extraBlockCount++ < this.numberOfBlocks;
}
}
private static class TargetBlockFilter<E extends Extent> implements Predicate<BlockRayHit<E>> {
private final Vector3i target;
TargetBlockFilter(Vector3d target) {
this.target = target.toInt();
}
@Override
public boolean test(BlockRayHit<E> lastHit) {
return lastHit.getBlockX() != this.target.getX() || lastHit.getBlockY() != this.target.getY()
|| lastHit.getBlockZ() != this.target.getZ();
}
}
}
| |
/*
* Copyright 2004-2005 Alexey Efimov
*
* 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.intellij.images.editor.impl;
import com.intellij.ide.CopyPasteDelegator;
import com.intellij.ide.CopyPasteSupport;
import com.intellij.ide.CopyProvider;
import com.intellij.ide.DeleteProvider;
import com.intellij.ide.util.DeleteHandler;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.ui.components.Magnificator;
import com.intellij.ui.scale.ScaleContext;
import com.intellij.util.LazyInitializer;
import com.intellij.util.SVGLoader;
import com.intellij.util.ui.JBUI;
import org.intellij.images.ImagesBundle;
import org.intellij.images.editor.ImageDocument;
import org.intellij.images.editor.ImageDocument.ScaledImageProvider;
import org.intellij.images.editor.ImageEditor;
import org.intellij.images.editor.ImageZoomModel;
import org.intellij.images.editor.actionSystem.ImageEditorActions;
import org.intellij.images.options.*;
import org.intellij.images.thumbnail.actionSystem.ThumbnailViewActions;
import org.intellij.images.thumbnail.actions.ShowBorderAction;
import org.intellij.images.ui.ImageComponent;
import org.intellij.images.ui.ImageComponentDecorator;
import org.intellij.images.vfs.IfsUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.ByteArrayInputStream;
/**
* Image editor UI
*
* @author <a href="mailto:aefimov.box@gmail.com">Alexey Efimov</a>
*/
final class ImageEditorUI extends JPanel implements DataProvider, CopyProvider, ImageComponentDecorator, Disposable {
@NonNls
private static final String IMAGE_PANEL = "image";
@NonNls
private static final String ERROR_PANEL = "error";
@NonNls
private static final String ZOOM_FACTOR_PROP = "ImageEditor.zoomFactor";
@Nullable
private final ImageEditor editor;
private final DeleteProvider deleteProvider;
private final CopyPasteSupport copyPasteSupport;
private final ImageZoomModel zoomModel = new ImageZoomModelImpl();
private final ImageWheelAdapter wheelAdapter = new ImageWheelAdapter();
private final ChangeListener changeListener = new DocumentChangeListener();
private final ImageComponent imageComponent = new ImageComponent();
private final JPanel contentPanel;
private JLabel infoLabel = null;
private final JScrollPane myScrollPane;
private final boolean isEmbedded;
ImageEditorUI(@Nullable ImageEditor editor) {
this(editor, false, true);
}
ImageEditorUI(@Nullable ImageEditor editor, boolean isEmbedded, boolean isOpaque) {
this.editor = editor;
this.isEmbedded = isEmbedded;
imageComponent.addPropertyChangeListener(ZOOM_FACTOR_PROP, e -> imageComponent.setZoomFactor(getZoomModel().getZoomFactor()));
Options options = OptionsManager.getInstance().getOptions();
EditorOptions editorOptions = options.getEditorOptions();
options.addPropertyChangeListener(new OptionsChangeListener(), this);
copyPasteSupport = editor != null ? new CopyPasteDelegator(editor.getProject(), this) : null;
deleteProvider = new DeleteHandler.DefaultDeleteProvider();
ImageDocument document = imageComponent.getDocument();
document.addChangeListener(changeListener);
// Set options
TransparencyChessboardOptions chessboardOptions = editorOptions.getTransparencyChessboardOptions();
GridOptions gridOptions = editorOptions.getGridOptions();
imageComponent.setTransparencyChessboardCellSize(chessboardOptions.getCellSize());
imageComponent.setTransparencyChessboardWhiteColor(chessboardOptions.getWhiteColor());
imageComponent.setTransparencyChessboardBlankColor(chessboardOptions.getBlackColor());
imageComponent.setGridLineZoomFactor(gridOptions.getLineZoomFactor());
imageComponent.setGridLineSpan(gridOptions.getLineSpan());
imageComponent.setGridLineColor(gridOptions.getLineColor());
imageComponent.setBorderVisible(ShowBorderAction.isBorderVisible());
// Create layout
ImageContainerPane view = new ImageContainerPane(imageComponent);
view.addMouseListener(new EditorMouseAdapter());
view.addMouseListener(new FocusRequester());
myScrollPane = ScrollPaneFactory.createScrollPane(view, true);
myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
// Zoom by wheel listener
myScrollPane.addMouseWheelListener(wheelAdapter);
// Construct UI
setLayout(new BorderLayout());
// toolbar is disabled in embedded mode
JComponent toolbarPanel = null;
if (!isEmbedded) {
ActionManager actionManager = ActionManager.getInstance();
ActionGroup actionGroup = (ActionGroup)actionManager.getAction(ImageEditorActions.GROUP_TOOLBAR);
ActionToolbar actionToolbar = actionManager.createActionToolbar(
ImageEditorActions.ACTION_PLACE, actionGroup, true
);
// Make sure toolbar is 'ready' before it's added to component hierarchy
// to prevent ActionToolbarImpl.updateActionsImpl(boolean, boolean) from increasing popup size unnecessarily
actionToolbar.updateActionsImmediately();
actionToolbar.setTargetComponent(this);
toolbarPanel = actionToolbar.getComponent();
toolbarPanel.addMouseListener(new FocusRequester());
}
JLabel errorLabel = new JLabel(
ImagesBundle.message("error.broken.image.file.format"),
Messages.getErrorIcon(), SwingConstants.CENTER
);
JPanel errorPanel = new JPanel(new BorderLayout());
errorPanel.add(errorLabel, BorderLayout.CENTER);
contentPanel = new JPanel(new CardLayout());
contentPanel.add(myScrollPane, IMAGE_PANEL);
contentPanel.add(errorPanel, ERROR_PANEL);
JPanel topPanel = new JPanel(new BorderLayout());
if (!isEmbedded) {
topPanel.add(toolbarPanel, BorderLayout.WEST);
infoLabel = new JLabel((String)null, SwingConstants.RIGHT);
infoLabel.setBorder(JBUI.Borders.emptyRight(2));
topPanel.add(infoLabel, BorderLayout.EAST);
}
add(topPanel, BorderLayout.NORTH);
add(contentPanel, BorderLayout.CENTER);
myScrollPane.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
updateZoomFactor();
}
});
if (!isOpaque) {
setOpaque(false);
contentPanel.setOpaque(false);
myScrollPane.setOpaque(false);
myScrollPane.getViewport().setOpaque(false);
}
updateInfo();
}
private void updateInfo() {
if (isEmbedded) return;
ImageDocument document = imageComponent.getDocument();
BufferedImage image = document.getValue();
if (image != null) {
ColorModel colorModel = image.getColorModel();
String format = document.getFormat();
if (format == null) {
format = editor != null ? ImagesBundle.message("unknown.format") : "";
} else {
format = StringUtil.toUpperCase(format);
}
VirtualFile file = editor != null ? editor.getFile() : null;
infoLabel.setText(
ImagesBundle.message("image.info",
image.getWidth(), image.getHeight(), format,
colorModel.getPixelSize(), file != null ? StringUtil.formatFileSize(file.getLength()) : ""));
} else {
infoLabel.setText(null);
}
}
@SuppressWarnings("UnusedDeclaration")
JComponent getContentComponent() {
return contentPanel;
}
ImageComponent getImageComponent() {
return imageComponent;
}
@Override
public void dispose() {
imageComponent.removeMouseWheelListener(wheelAdapter);
imageComponent.getDocument().removeChangeListener(changeListener);
removeAll();
}
@Override
public void setTransparencyChessboardVisible(boolean visible) {
imageComponent.setTransparencyChessboardVisible(visible);
repaint();
}
@Override
public boolean isTransparencyChessboardVisible() {
return imageComponent.isTransparencyChessboardVisible();
}
@Override
public boolean isEnabledForActionPlace(String place) {
// Disable for thumbnails action
return !ThumbnailViewActions.ACTION_PLACE.equals(place);
}
@Override
public void setGridVisible(boolean visible) {
imageComponent.setGridVisible(visible);
repaint();
}
@Override
public boolean isGridVisible() {
return imageComponent.isGridVisible();
}
@Override
public ImageZoomModel getZoomModel() {
return zoomModel;
}
public void setImageProvider(ScaledImageProvider imageProvider, String format) {
ImageDocument document = imageComponent.getDocument();
BufferedImage previousImage = document.getValue();
document.setValue(imageProvider);
if (imageProvider == null) return;
document.setFormat(format);
if (previousImage == null || !zoomModel.isZoomLevelChanged()) {
Options options = OptionsManager.getInstance().getOptions();
ZoomOptions zoomOptions = options.getEditorOptions().getZoomOptions();
if (!(zoomOptions.isSmartZooming() && updateZoomFactor())) {
zoomModel.setZoomFactor(1.0);
}
}
}
private boolean updateZoomFactor() {
Options options = OptionsManager.getInstance().getOptions();
ZoomOptions zoomOptions = options.getEditorOptions().getZoomOptions();
if (zoomOptions.isSmartZooming() && !zoomModel.isZoomLevelChanged()) {
Double smartZoomFactor = getSmartZoomFactor(zoomOptions);
if (smartZoomFactor != null) {
zoomModel.setZoomFactor(smartZoomFactor);
return true;
}
}
return false;
}
private final class ImageContainerPane extends JBLayeredPane {
private final ImageComponent imageComponent;
ImageContainerPane(final ImageComponent imageComponent) {
this.imageComponent = imageComponent;
add(imageComponent);
putClientProperty(Magnificator.CLIENT_PROPERTY_KEY, new Magnificator() {
@Override
public Point magnify(double scale, Point at) {
Point locationBefore = imageComponent.getLocation();
ImageZoomModel model = editor != null ? editor.getZoomModel() : getZoomModel();
double factor = model.getZoomFactor();
model.setZoomFactor(scale * factor);
return new Point(((int)((at.x - Math.max(scale > 1.0 ? locationBefore.x : 0, 0)) * scale)),
((int)((at.y - Math.max(scale > 1.0 ? locationBefore.y : 0, 0)) * scale)));
}
});
}
private void centerComponents() {
Rectangle bounds = getBounds();
Point point = imageComponent.getLocation();
// in embedded mode images should be left-side aligned
point.x = isEmbedded ? 0 : (bounds.width - imageComponent.getWidth()) / 2;
point.y = (bounds.height - imageComponent.getHeight()) / 2;
imageComponent.setLocation(point);
}
@Override
public void invalidate() {
centerComponents();
super.invalidate();
}
@Override
public Dimension getPreferredSize() {
return imageComponent.getSize();
}
}
private final class ImageWheelAdapter implements MouseWheelListener {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
Options options = OptionsManager.getInstance().getOptions();
EditorOptions editorOptions = options.getEditorOptions();
ZoomOptions zoomOptions = editorOptions.getZoomOptions();
if (zoomOptions.isWheelZooming() && e.isControlDown()) {
int rotation = e.getWheelRotation();
double oldZoomFactor = zoomModel.getZoomFactor();
Point oldPosition = myScrollPane.getViewport().getViewPosition();
if (rotation > 0) {
zoomModel.zoomOut();
}
else if (rotation < 0) {
zoomModel.zoomIn();
}
// reset view, otherwise view size is not obtained correctly sometimes
Component view = myScrollPane.getViewport().getView();
myScrollPane.setViewport(null);
myScrollPane.setViewportView(view);
if (oldZoomFactor > 0 && rotation != 0) {
Point mousePoint = e.getPoint();
double zoomChange = zoomModel.getZoomFactor() / oldZoomFactor;
Point newPosition = new Point((int)Math.max(0, (oldPosition.getX() + mousePoint.getX()) * zoomChange - mousePoint.getX()),
(int)Math.max(0, (oldPosition.getY() + mousePoint.getY()) * zoomChange - mousePoint.getY()));
myScrollPane.getViewport().setViewPosition(newPosition);
}
e.consume();
}
}
}
private final class ImageZoomModelImpl implements ImageZoomModel {
private boolean myZoomLevelChanged;
private final LazyInitializer.LazyValue<@NotNull Double> IMAGE_MAX_ZOOM_FACTOR = LazyInitializer.create(() -> {
if (editor == null) return Double.MAX_VALUE;
VirtualFile file = editor.getFile();
if (IfsUtil.isSVG(file)) {
try {
return Math.max(1, SVGLoader.getMaxZoomFactor(file.getPath(), new ByteArrayInputStream(file.contentsToByteArray()),
ScaleContext.create(editor.getComponent())));
}
catch (Throwable t) {
Logger.getInstance(ImageEditorUI.class).warn(t);
}
}
return Double.MAX_VALUE;
});
private double zoomFactor = 0.0d;
@Override
public double getZoomFactor() {
return zoomFactor;
}
@Override
public void setZoomFactor(double zoomFactor) {
double oldZoomFactor = getZoomFactor();
if (Double.compare(oldZoomFactor, zoomFactor) == 0) return;
this.zoomFactor = zoomFactor;
// Change current size
updateImageComponentSize();
revalidate();
repaint();
myZoomLevelChanged = false;
imageComponent.firePropertyChange(ZOOM_FACTOR_PROP, oldZoomFactor, zoomFactor);
}
private double getMaximumZoomFactor() {
double factor = IMAGE_MAX_ZOOM_FACTOR.get();
return Math.min(factor, MACRO_ZOOM_LIMIT);
}
private double getMinimumZoomFactor() {
Rectangle bounds = imageComponent.getDocument().getBounds();
double factor = bounds != null ? 1.0d / bounds.getWidth() : 0.0d;
return Math.max(factor, MICRO_ZOOM_LIMIT);
}
@Override
public void fitZoomToWindow() {
Options options = OptionsManager.getInstance().getOptions();
ZoomOptions zoomOptions = options.getEditorOptions().getZoomOptions();
Double smartZoomFactor = getSmartZoomFactor(zoomOptions);
if (smartZoomFactor != null) {
zoomModel.setZoomFactor(smartZoomFactor);
}
else {
zoomModel.setZoomFactor(1.0d);
}
myZoomLevelChanged = false;
}
@Override
public void zoomOut() {
setZoomFactor(getNextZoomOut());
myZoomLevelChanged = true;
}
@Override
public void zoomIn() {
setZoomFactor(getNextZoomIn());
myZoomLevelChanged = true;
}
private double getNextZoomOut() {
double factor = getZoomFactor();
if (factor > 1.0d) {
// Macro
factor /= MACRO_ZOOM_RATIO;
factor = Math.max(factor, 1.0d);
}
else {
// Micro
factor /= MICRO_ZOOM_RATIO;
}
return Math.max(factor, getMinimumZoomFactor());
}
private double getNextZoomIn() {
double factor = getZoomFactor();
if (factor >= 1.0d) {
// Macro
factor *= MACRO_ZOOM_RATIO;
}
else {
// Micro
factor *= MICRO_ZOOM_RATIO;
factor = Math.min(factor, 1.0d);
}
return Math.min(factor, getMaximumZoomFactor());
}
@Override
public boolean canZoomOut() {
// Ignore small differences caused by floating-point arithmetic.
return getZoomFactor() - 1.0e-14 > getMinimumZoomFactor();
}
@Override
public boolean canZoomIn() {
return getZoomFactor() < getMaximumZoomFactor();
}
@Override
public void setZoomLevelChanged(boolean value) {
myZoomLevelChanged = value;
}
@Override
public boolean isZoomLevelChanged() {
return myZoomLevelChanged;
}
}
@Nullable
private Double getSmartZoomFactor(@NotNull ZoomOptions zoomOptions) {
Rectangle bounds = imageComponent.getDocument().getBounds();
if (bounds == null) return null;
if (bounds.getWidth() == 0 || bounds.getHeight() == 0) return null;
int width = bounds.width;
int height = bounds.height;
Dimension preferredMinimumSize = zoomOptions.getPrefferedSize();
if (width < preferredMinimumSize.width &&
height < preferredMinimumSize.height) {
double factor = (preferredMinimumSize.getWidth() / (double)width +
preferredMinimumSize.getHeight() / (double)height) / 2.0d;
return Math.ceil(factor);
}
Dimension canvasSize = myScrollPane.getViewport().getExtentSize();
canvasSize.height -= ImageComponent.IMAGE_INSETS * 2;
canvasSize.width -= ImageComponent.IMAGE_INSETS * 2;
if (canvasSize.width <= 0 || canvasSize.height <= 0) return null;
if (canvasSize.width < width ||
canvasSize.height < height) {
return Math.min((double)canvasSize.height / height,
(double)canvasSize.width / width);
}
return 1.0d;
}
private void updateImageComponentSize() {
Rectangle bounds = imageComponent.getDocument().getBounds();
if (bounds != null) {
final double zoom = getZoomModel().getZoomFactor();
imageComponent.setCanvasSize((int)Math.ceil(bounds.width * zoom), (int)Math.ceil(bounds.height * zoom));
}
}
private class DocumentChangeListener implements ChangeListener {
@Override
public void stateChanged(@NotNull ChangeEvent e) {
updateImageComponentSize();
ImageDocument document = imageComponent.getDocument();
BufferedImage value = document.getValue();
CardLayout layout = (CardLayout)contentPanel.getLayout();
layout.show(contentPanel, value != null ? IMAGE_PANEL : ERROR_PANEL);
updateInfo();
revalidate();
repaint();
}
}
private class FocusRequester extends MouseAdapter {
@Override
public void mousePressed(@NotNull MouseEvent e) {
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(ImageEditorUI.this, true));
}
}
private static final class EditorMouseAdapter extends PopupHandler {
@Override
public void invokePopup(Component comp, int x, int y) {
// Single right click
ActionManager actionManager = ActionManager.getInstance();
ActionGroup actionGroup = (ActionGroup)actionManager.getAction(ImageEditorActions.GROUP_POPUP);
ActionPopupMenu menu = actionManager.createActionPopupMenu(ImageEditorActions.ACTION_PLACE, actionGroup);
JPopupMenu popupMenu = menu.getComponent();
popupMenu.pack();
popupMenu.show(comp, x, y);
}
}
@Override
@Nullable
public Object getData(@NotNull String dataId) {
if (CommonDataKeys.PROJECT.is(dataId)) {
return editor != null ? editor.getProject() : null;
}
else if (CommonDataKeys.VIRTUAL_FILE.is(dataId)) {
return editor != null ? editor.getFile() : null;
}
else if (CommonDataKeys.VIRTUAL_FILE_ARRAY.is(dataId)) {
return editor != null ? new VirtualFile[]{editor.getFile()} : VirtualFile.EMPTY_ARRAY;
}
else if (CommonDataKeys.PSI_FILE.is(dataId)) {
return findPsiFile();
}
else if (CommonDataKeys.PSI_ELEMENT.is(dataId)) {
return findPsiFile();
}
else if (LangDataKeys.PSI_ELEMENT_ARRAY.is(dataId)) {
PsiElement psi = findPsiFile();
return psi != null ? new PsiElement[]{psi} : PsiElement.EMPTY_ARRAY;
}
else if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
return this;
}
else if (PlatformDataKeys.CUT_PROVIDER.is(dataId) && copyPasteSupport != null) {
return copyPasteSupport.getCutProvider();
}
else if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) {
return deleteProvider;
}
else if (ImageComponentDecorator.DATA_KEY.is(dataId)) {
return editor != null ? editor : this;
}
return null;
}
@Nullable
private PsiFile findPsiFile() {
VirtualFile file = editor != null ? editor.getFile() : null;
return file != null && file.isValid() ? PsiManager.getInstance(editor.getProject()).findFile(file) : null;
}
@Override
public void performCopy(@NotNull DataContext dataContext) {
ImageDocument document = imageComponent.getDocument();
BufferedImage image = document.getValue();
CopyPasteManager.getInstance().setContents(new ImageTransferable(image));
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
return true;
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
private static class ImageTransferable implements Transferable {
private final BufferedImage myImage;
ImageTransferable(@NotNull BufferedImage image) {
myImage = image;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
@Override
public boolean isDataFlavorSupported(DataFlavor dataFlavor) {
return DataFlavor.imageFlavor.equals(dataFlavor);
}
@Override
public Object getTransferData(DataFlavor dataFlavor) throws UnsupportedFlavorException {
if (!DataFlavor.imageFlavor.equals(dataFlavor)) {
throw new UnsupportedFlavorException(dataFlavor);
}
return myImage;
}
}
private class OptionsChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
Options options = (Options) evt.getSource();
EditorOptions editorOptions = options.getEditorOptions();
TransparencyChessboardOptions chessboardOptions = editorOptions.getTransparencyChessboardOptions();
GridOptions gridOptions = editorOptions.getGridOptions();
imageComponent.setTransparencyChessboardCellSize(chessboardOptions.getCellSize());
imageComponent.setTransparencyChessboardWhiteColor(chessboardOptions.getWhiteColor());
imageComponent.setTransparencyChessboardBlankColor(chessboardOptions.getBlackColor());
imageComponent.setGridLineZoomFactor(gridOptions.getLineZoomFactor());
imageComponent.setGridLineSpan(gridOptions.getLineSpan());
imageComponent.setGridLineColor(gridOptions.getLineColor());
}
}
}
| |
package socialite.codegen;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import socialite.engine.Config;
import socialite.engine.LocalEngine;
import socialite.eval.Eval;
import socialite.functions.FunctionLoader;
import socialite.parser.Parser;
import socialite.parser.Rule;
import socialite.parser.Table;
import socialite.resource.SRuntime;
import socialite.resource.TableInstRegistry;
import socialite.tables.QueryVisitor;
import socialite.tables.TableInst;
import socialite.tables.TableUtil;
import socialite.tables.Tuple;
import socialite.util.AnalysisException;
import socialite.util.Assert;
import socialite.util.SociaLiteException;
import socialite.visitors.IVisitor;
public class VisitorCodeGenTest {
static Epoch findEpoch(Analysis an, Rule r) {
for (Epoch e:an.getEpochs()) {
if (e.getRules().contains(r))
return e;
}
assert false:"unexpected!";
return null;
}
static void simpleIterate() {
String query = "Foo(int a, int b).\n" +
"Bar(int a, int b).\n" +
"Bar(a,b) :- a=10, b=11. \n" +
"Foo(n1, n3) :- Bar(n3, n1).";
Config conf=Config.par();
//conf.setDebugOpt("GenerateTable", false);
//conf.setDebugOpt("GenerateVisitor", false);
LocalEngine e=new LocalEngine(conf);
e.run(query);
e.shutdown();
}
static void simpleJoin() {
String query = "Foo(int a, int b).\n" +
"Bar(int a, int b).\n" +
"Baz(String a, int b).\n" +
"Qux(int a, String b) indexby a, indexby b.\n" +
"Foo(n1, n2) :- Bar(n3, n1), Bar(n1,n2).\n" +
"Foo(a, b) :- Bar(a, c), Baz(s, c), Qux(b, s).";
Analysis an = parseAndAnalysis(query);
TableCodeGen.ensureExistOrDie(an.getNewTables());
for (Rule r:an.getRules()) {
Epoch s=findEpoch(an, r);
compileRule(s, r, an.getTableMap());
}
}
static void funcExpr() {
String query = "Edge(int s:0..10, (int t)).\n" +
"Edge(s, t) :- s=1, t1=\"2\", t=$toInt(t1).\n";
Analysis an = parseAndAnalysis(query);
TableCodeGen.ensureExistOrDie(an.getNewTables());
for (Rule r:an.getRules()) {
Epoch s=findEpoch(an, r);
compileRule(s, r, an.getTableMap());
}
}
static void exprAndJoin() {
String query = "Edge(int s:0..10, (int t)).\n" +
"Triangle(int x, int y, int z) sortby x.\n" +
"Triangle(x, y, z):-Edge(x, y),y>x,Edge(y, z),z>y,Edge(z, x).";
Analysis an = parseAndAnalysis(query);
TableCodeGen.ensureExistOrDie(an.getNewTables());
for (Rule r:an.getRules()) {
Epoch s=findEpoch(an, r);
compileRule(s, r, an.getTableMap());
}
}
static void funcAndJoin() {
String simpleQuery = "Edge(int s:0..10, (int t)).\n" +
"Foo(int x, int y) sortby x.\n" +
"Foo(x, z):-Edge(x, a), b=a+3*2, y=$toInt(\"1\"), Edge(b, z) .";
Analysis an = parseAndAnalysis(simpleQuery);
TableCodeGen.ensureExistOrDie(an.getNewTables());
for (Rule r:an.getRules()) {
Epoch s=findEpoch(an, r);
compileRule(s, r, an.getTableMap());
}
}
static void createInst() {
String query = "Edge1(int s:0..10, (int t)).\n"
+ "Triangle1(int x, int y, int z) sortby x.\n"
+ "Triangle1(x, y, z):-Edge1(x, y),y>x,Edge1(y, z),z>y,Edge1(z, x).";
LocalEngine en=new LocalEngine(Config.seq());
CodeGenMain c=en.compile(query);
Analysis an=c.an;
List<Eval> evals=c.getEvalInsts();
//for (Eval e:evals) e.run();
Rule r = an.getRules().get(0);
IVisitor[] visitors =
c.getRuntime().getVisitorBuilder(r.id()).getNewVisitorInst(r.id());
Assert.not_null(visitors);
Assert.equals(visitors.length, 1);
IVisitor v=visitors[0];
en.shutdown();
}
static void iterateRange() {
String query="Edge(int s:1..1000, (int t)) sortby t.\n" +
"Clique(int x, int y, int z) sortby x.\n" +
"Clique(x, y, z) :- Edge(x, y), x<y, Edge(y, z), y<z, Edge(x, z).";
Analysis an=parseAndAnalysis(query);
Config conf=Config.seq();
CodeGenMain c=new CodeGenMain(conf, an, SRuntime.create(conf));
c.generate();
}
static void iterateRange2() {
String query="Edge(int s:1..1000, int a, (int s2:1..100, int t)).\n" +
"Clique2(int x, int y, int z) sortby x.\n" +
"Clique2(x, y, z) :- Edge(1, u, 9, y), Edge(y, 2, z, _), y<z, Edge(x, z, _, _).";
Analysis an=parseAndAnalysis(query);
Config conf=Config.seq();
CodeGenMain c=new CodeGenMain(conf, an, SRuntime.create(conf));
c.generate();
}
static void iterateWithIndex() {
String query="RDF(Utf8 s, Utf8 p, Utf8 o) indexby s, indexby p.\n"+
"RDF(s,p,o) :- s=u\"s1\", p=u\"p1\", o=u\"o1\". \n"+
"RDF(s,p,o) :- s=u\"s1\", p=u\"p2\", o=u\"o2\". \n"+
"RDF(s,p,o) :- s=u\"s2\", p=u\"p3\", o=u\"o3\". \n"+
"RDF(s,p,o) :- s=u\"s2\", p=u\"p4\", o=u\"s1\". \n";
LocalEngine en = new LocalEngine(Config.par(4));
en.run(query);
query = "Tmp(int a:0..10, Utf8 x1, Utf8 x2).\n" +
"Tmp(0, x1, x2) :- RDF(x1, u\"p1\", x2). "+
"?-Tmp(0, x1, x2).";
final String[] x = new String[]{""};
en.run(query, new QueryVisitor() {
public boolean visit(Tuple t) {
//System.out.println(t);
x[0] += t.get(1);
x[0] += t.get(2);
return true;
}
});
assert x[0].equals("s1o1"): "x[0]:"+x[0];
en.shutdown();
}
static void iterateWithIndex2() {
String query="Foo(int a:0..100, (int b:0..10, double c)).\n"+
"Foo(a,b,c) :- a=1, b=2, c=3.3. \n"+
"Bar(int a, int b, double c). \n"+
"Bar(a,b,c) :- a=10, b=20, Foo(1,2,c).";
LocalEngine en = new LocalEngine(Config.par(4));
en.compile(query);
en.shutdown();
}
static void testAggrFunction() {
String query="Edge(int s:1..1000, (int t)) sortby t.\n" +
"Foo(int a, int b).\n" +
"Bar(int a, String b).\n" +
"Edge(s, t) :- s=1, t=1.\n" +
"Edge(s, t) :- s=1, t=2.\n" +
"Edge(s, t) :- s=1, t=3.\n" +
"Foo(a, $sum(b)) :- Edge(a, b).\n"+
"Bar(a, $sum(c)) :- Edge(a, b), c=$toStr(b).";
LocalEngine en = new LocalEngine(Config.par(4));
en.run(query);
final String s[]=new String[]{""};
en.run("?-Bar(a,b).", new QueryVisitor() {
public boolean visit(Tuple t) {
s[0] += t.get(0)+","+t.get(1)+";";
return true;
}
});
assert s[0].equals("1,123;"):s[0];
en.shutdown();
}
static void testScc() {
String query = "Foo(int s, int t).\n" +
"Bar(int a, int b).\n" +
"Baz(int a, int b).\n" +
"Foo(a,b) :- a=10, b=11.\n" +
"Foo(a,b) :- Bar(a,b).\n" +
"Baz(a,b) :- Foo(a,b).\n" +
"Bar(a,b) :- Baz(a,b).\n";
Config conf = Config.par(4);
//conf.setDebugOpt("GenerateTable", false);
//conf.setDebugOpt("GenerateVisitor", false);
LocalEngine en = new LocalEngine(conf);
en.run(query);
final String[] x = new String[]{""};
en.run("?-Bar(a,b).", new QueryVisitor() {
public boolean visit(Tuple t) {
x[0] += t.getInt(0)+","+t.getInt(1)+";";
return true;
}
});
assert x[0].equals("10,11;"):"x[0]:"+x[0];
en.shutdown();
}
static void testIterCol() {
String query ="InEdge(int t:0..100, (int src)) sortby src. \n" +
"EdgeCnt(int s:0..100, int cnt).\n" +
"Rank(int i:iterator, int s:0..100, double rank) groupby(2).\n" +
"InEdge(t, s) :- t=$range(0, 99), s=t+1. \n"+
"EdgeCnt(s, $inc(1)) :- InEdge(t, s).\n";
Config conf = Config.par(4);
LocalEngine en = new LocalEngine(conf);
en.run(query);
query = "Rank(0,_,r) :- r=100.0/100.0 . \n"+
"Rank(1,_,r) :- r=100.0/100.0 . \n"+
"Rank(1,p,$sum(r)) :- InEdge(p,n), Rank(0,n,r1), EdgeCnt(n,cnt), r=0.85*r1/cnt.\n";
en.run(query);
query = "Rank(2,_,r) :- r=100.0/100.0 . \n"+
"Rank(2,p,$sum(r)) :- InEdge(p,n), Rank(1,n,r1), EdgeCnt(n,cnt), r=0.85*r1/cnt.\n";
en.run(query);
en.shutdown();
}
static void testContains() {
String query ="Base(int a, int b). \n" +
"Arr1(int a:0..10, int b) indexby a. \n" +
"Test(int a, int b). \n" +
"Base(0, b) :- b=1 . \n" +
"Arr1(1, b) :- b=1 . \n"+
"Test(a,b) :- Base(a,b), !Arr1(b, _). \n"+
"?-Test(a,b).";
LocalEngine en = new LocalEngine(Config.par(4));
final String[] s=new String[]{""};
en.run(query, new QueryVisitor() {
public boolean visit(Tuple t) {
s[0] += t.get(0)+","+t.get(1)+";";
return true;
}
});
assert s[0].equals("");
en.run("clear Test.");
s[0]="";
query = "Arr2(int a:0..10, (int b:0..10, int c)) indexby a. \n" +
"Arr2(1, b, b) :- b=1 . \n" +
"Test(a,b) :- Base(a,b), !Arr2(b, _, _). \n"+
"?-Test(a,b).";
en.run("?-Test(a,b).", new QueryVisitor() {
public boolean visit(Tuple t) {
s[0] += t.get(0)+","+t.get(1)+";";
return true;
}
});
assert s[0].equals("");
en.run("clear Test."); s[0]="";
query = "Dyn1(int a, int b) indexby a. \n" +
"Dyn1(1, b) :- b=1 . \n"+
"Test(a,b) :- Base(a,b), !Dyn1(b, _). \n"+
"?-Test(a,b).";
en.run(query, new QueryVisitor() {
public boolean visit(Tuple t) {
s[0] += t.get(0)+","+t.get(1)+";";
return true;
}
});
assert s[0].equals("");
en.run("clear Test."); s[0]="";
query = "Dyn2(int a, (int b)) indexby a. \n" +
"Dyn2(1, b) :- b=1 . \n"+
"Test(a,b) :- Base(a,b), !Dyn2(b, _). \n"+
"?-Test(a,b).";
en.run(query, new QueryVisitor() {
public boolean visit(Tuple t) {
s[0] += t.get(0)+","+t.get(1)+";";
return true;
}
});
assert s[0].equals("");
en.shutdown();
}
static void testChoice() {
String query ="Diff(int n:0..0, int t) groupby(1).\n"+
"Gradient(int x, int y , int z).\n"+
"Gradient(a,b,c) :- a=1,b=1,c=1.\n"+
"Gradient(a,b,c) :- a=1,b=1,c=2.\n"+
"Diff(0, $choice(d)) :- Gradient(x,y,z), tmp=x+y+z, tmp>1, d=z.\n";
Config c=Config.par(4);
LocalEngine en = new LocalEngine(c);
en.run(query);
final int[] count=new int[]{0};
en.run("?-Diff(a,b).", new QueryVisitor() {
public boolean visit(Tuple t) {
count[0]++;
return true;
}
});
assert count[0]==1;
en.shutdown();
}
static void testChoice2() {
String query ="Path(int i:0..100, (int depth, int to)). \n"+
"Edge(int s:0..100, (int t)).\n"+
"EdgeCnt(int s:0..100, int cnt).\n"+
"PathCnt(int s:0..100, int cnt).\n"+
"Source(int n:0..0, int s).\n"+
"Depth(int n:0..0, int s). \n"+
"Edge(int s:0..100, (int t)).\n"+
"Edge(s, t) :- s=0, t=1. \n"+
"Edge(s, t) :- s=1, t=2. \n"+
"Edge(s, t) :- s=2, t=3. \n"+
"Edge(s, t) :- s=3, t=4. \n"+
"Edge(s, t) :- s=4, t=5. \n"+
"Edge(s, t) :- s=5, t=6. \n"+
"Edge(s, t) :- s=6, t=0. \n"+
"Edge(s, t) :- s=2, t=7. \n"+
"Edge(s, t) :- s=7, t=8. \n"+
"Edge(s, t) :- s=8, t=2. \n"+
"Edge(s, t) :- s=5, t=10. \n"+
"Edge(s, t) :- s=10, t=11. \n"+
"Edge(s, t) :- s=11, t=12. \n"+
"Edge(s, t) :- s=12, t=15. \n";
Config c=Config.par(4);
LocalEngine en = new LocalEngine(c);
en.run(query);
System.err.println("Starting eulerian path..");
query = "Path(s, depth, $choice(to)) :- s=0, depth=1, Edge(s, to), !Path(s, _, to); \n"+
" :- Path(_, prevDepth, s), depth=prevDepth+1, Edge(s, to), !Path(s, _, to).\n" +
"PathCnt(s, $inc(1)) :- Path(s, depth, to).\n"+
"Depth(0, $max(depth)) :- Path(s, depth, to). \n";
en.run(query);
en.run("Source(0, $choice(s)) :- PathCnt(s, cnt1), EdgeCnt(s, cnt2), cnt1 < cnt2.");
en.run("clear PathCnt. clear Source.");
query = "Path(s, depth, $choice(to)) :- s=2, depth=8, Edge(s, to), !Path(s, _, to); \n"+
" :- Path(_, prevDepth, s), depth=prevDepth+1, Edge(s, to), !Path(s, _, to).\n"+
"PathCnt(s, $inc(1)) :- Path(s, depth, to).\n"+
"Depth(0, $max(depth)) :- Path(s, depth, to). \n";
en.run(query);
en.run("clear PathCnt. clear Source.");
en.run("Source(0, $choice(s)) :- PathCnt(s, cnt1), EdgeCnt(s, cnt2), cnt1 < cnt2.");
System.err.println("Querying ?-Path");
en.run("?-Path(a,d, c).", new QueryVisitor() {
public boolean visit(Tuple t) {
System.out.println(t.get(0)+"-->"+t.get(2)+":"+t.get(1));
return true;
}
});
en.shutdown();
}
static void testit2() {
int N=1000;
String q = "InEdge(int t:0.." + N + ", (int s)) sortby s.\n" +
"EdgeCnt(int s:0.." + N+ ", int cnt).\n" +
"EdgeCntInv(int s:0.." + N + ", float i).\n" +
"Rank(int n:0.." + N + ", int i:iter, float val) groupby(2).\n" +
"Term(int i:0..1, float d).\n" +
"InEdge(t, s) :- t=1, s=23 .\n" +
"EdgeCnt(s, $inc(1)) :- InEdge(t, s).\n" +
"EdgeCntInv(s, i) :- EdgeCnt(s, c), i=0.7f/c.\n" +
"Rank(_, 0, v) :- v=1.0f .";
Config c=Config.par(2);
LocalEngine en = new LocalEngine(c);
en.run(q);
en.shutdown();
}
static void testNegated() {
String query = "Foo(int a, int b).\n"+
"Bar(int a, int b).\n"+
"Bar(a,b) :- a=10, b=20. \n"+
"Bar(a,b) :- a=20, b=10. \n"+
"Foo(a,b) :- Bar(a, b), ! Bar(b, a).\n";
Config c=Config.seq();
LocalEngine en = new LocalEngine(c);
en.run(query);
en.shutdown();
}
static void testCastCodeGen() {
String query = "Foo(int a, double b).\n"+
"Foo(a,b) :- a=100, c=20, d=3.3, b= -(double)d, b=(double)d+d.\n"+
"Foo(a,b) :- a=100, c=20, b=(double)c.\n";
Config c=Config.seq();
LocalEngine en = new LocalEngine(c);
en.run(query);
en.shutdown();
}
static void testDottedVar() {
String query = "Foo(int a, String s).\n"+
"Foo(a,b) :- b=\"100\", a=$toInt(b).\n";
Config c=Config.par(4);
LocalEngine en = new LocalEngine(c);
en.run(query);
en.shutdown();
}
static void testAggr() {
String query = "Foo(int a, Avg x).\n"+
"Foo(0, $avg(x)) :- x=42.42. ";
Config c=Config.par(4);
LocalEngine en = new LocalEngine(c);
en.run(query);
query="Bar(String a, Count b).\n"+
" Bar(a, $count(b)) :- a=\"abc\", b=3.3.";
en.run(query);
en.shutdown();
}
static void testArgmin() {
String query ="Data(int n:0..40000, double x, double y).\n"+
"Data(id, lat, lng) :- id=$range(0, 40000), lat=1.2, lng=5.2.\n"+
"Center(int k:0..100, Avg[] avg) groupby(1).\n";
Config c=Config.par(2);
LocalEngine en = new LocalEngine(c);
en.run(query);
double x=-10.5, y=-10.5;
for (int i=0; i<100; i++) {
query="Center("+i+", $avg(a)) :- a=$darray("+x+","+y+").";
en.run(query);
x+=0.2; y+=0.2;
}
en.run("Cluster(int did:0..40000, int i:iter,ArgMin min) groupby(2).");
for (int i=0; i<10; i++) {
query="Cluster(did, "+i+", $argmin(idx, diff)) :- Data(did, x, y), Center(idx, a), (cx,cy)=$unpack(a),"+
"diff= (x-cx.value)*(x-cx.value)+(y-cy.value)*(y-cy.value).";
en.run(query);
}
en.shutdown();
}
public static void main(String args[]) {
//System.out.println("Some tests are disabled");
simpleIterate(); dot();
simpleJoin(); dot();
funcExpr(); dot();
exprAndJoin(); dot();
funcAndJoin(); dot();
createInst(); dot();
iterateRange(); dot();
iterateRange2(); dot();
iterateWithIndex(); dot();
iterateWithIndex2(); dot();
testScc(); dot();
testIterCol(); dot();
testAggrFunction(); dot();
testContains(); dot();
testChoice(); dot();
testCastCodeGen(); dot();
testNegated(); dot();
testDottedVar(); dot();
testAggr(); dot();
testArgmin(); dot();
System.out.println("Visitor Code Generation Test done");
}
static void dot() { System.out.print("."); }
static Analysis parseAndAnalysis(String query) {
Parser p = new Parser(query);
p.parse();
Analysis an = new Analysis(p);
an.run();
return an;
}
static void compileRule(Epoch e, Rule r, Map<String, Table> tableMap) {
VisitorCodeGen gen = new VisitorCodeGen(e, r, tableMap, Config.par(2));
String src = gen.generate();
Compiler c= new Compiler();
boolean success=c.compile(gen.visitorName(), src);
if (!success) {
System.out.println(c.getErrorMsg());
throw new SociaLiteException();
}
}
}
| |
/*
* Copyright 2000-2012 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 git4idea.branch;
import com.intellij.dvcs.DvcsUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import git4idea.GitLocalBranch;
import git4idea.GitUtil;
import git4idea.commands.Git;
import git4idea.commands.GitMessageWithFilesDetector;
import git4idea.config.GitVcsSettings;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.openapi.application.ModalityState.defaultModalityState;
import static com.intellij.openapi.util.text.StringUtil.pluralize;
/**
* Common class for Git operations with branches aware of multi-root configuration,
* which means showing combined error information, proposing to rollback, etc.
*/
abstract class GitBranchOperation {
protected static final Logger LOG = Logger.getInstance(GitBranchOperation.class);
@NotNull protected final Project myProject;
@NotNull protected final Git myGit;
@NotNull protected final GitBranchUiHandler myUiHandler;
@NotNull private final Collection<GitRepository> myRepositories;
@NotNull protected final Map<GitRepository, String> myCurrentHeads;
@NotNull private final GitVcsSettings mySettings;
@NotNull private final Collection<GitRepository> mySuccessfulRepositories;
@NotNull private final Collection<GitRepository> mySkippedRepositories;
@NotNull private final Collection<GitRepository> myRemainingRepositories;
protected GitBranchOperation(@NotNull Project project, @NotNull Git git,
@NotNull GitBranchUiHandler uiHandler, @NotNull Collection<GitRepository> repositories) {
myProject = project;
myGit = git;
myUiHandler = uiHandler;
myRepositories = repositories;
myCurrentHeads = ContainerUtil.map2Map(repositories, new Function<GitRepository, Pair<GitRepository, String>>() {
@Override
public Pair<GitRepository, String> fun(GitRepository repository) {
GitLocalBranch currentBranch = repository.getCurrentBranch();
return Pair.create(repository, currentBranch == null ? repository.getCurrentRevision() : currentBranch.getName());
}
});
mySuccessfulRepositories = new ArrayList<GitRepository>();
mySkippedRepositories = new ArrayList<GitRepository>();
myRemainingRepositories = new ArrayList<GitRepository>(myRepositories);
mySettings = GitVcsSettings.getInstance(myProject);
}
protected abstract void execute();
protected abstract void rollback();
@NotNull
public abstract String getSuccessMessage();
@NotNull
protected abstract String getRollbackProposal();
/**
* Returns a short downcased name of the operation.
* It is used by some dialogs or notifications which are common to several operations.
* Some operations (like checkout new branch) can be not mentioned in these dialogs, so their operation names would be not used.
*/
@NotNull
protected abstract String getOperationName();
/**
* @return next repository that wasn't handled (e.g. checked out) yet.
*/
@NotNull
protected GitRepository next() {
return myRemainingRepositories.iterator().next();
}
/**
* @return true if there are more repositories on which the operation wasn't executed yet.
*/
protected boolean hasMoreRepositories() {
return !myRemainingRepositories.isEmpty();
}
/**
* Marks repositories as successful, i.e. they won't be handled again.
*/
protected void markSuccessful(GitRepository... repositories) {
for (GitRepository repository : repositories) {
mySuccessfulRepositories.add(repository);
myRemainingRepositories.remove(repository);
}
}
/**
* Marks repositories as successful, i.e. they won't be handled again.
*/
protected void markSkip(GitRepository... repositories) {
for (GitRepository repository : repositories) {
mySkippedRepositories.add(repository);
myRemainingRepositories.remove(repository);
}
}
/**
* @return true if the operation has already succeeded in at least one of repositories.
*/
protected boolean wereSuccessful() {
return !mySuccessfulRepositories.isEmpty();
}
protected boolean wereSkipped() {
return !mySkippedRepositories.isEmpty();
}
@NotNull
protected Collection<GitRepository> getSuccessfulRepositories() {
return mySuccessfulRepositories;
}
@NotNull
protected Collection<GitRepository> getSkippedRepositories() {
return mySkippedRepositories;
}
@NotNull
protected String successfulRepositoriesJoined() {
return GitUtil.joinToHtml(mySuccessfulRepositories);
}
@NotNull
protected Collection<GitRepository> getRepositories() {
return myRepositories;
}
@NotNull
protected Collection<GitRepository> getRemainingRepositories() {
return myRemainingRepositories;
}
@NotNull
protected List<GitRepository> getRemainingRepositoriesExceptGiven(@NotNull final GitRepository currentRepository) {
List<GitRepository> repositories = new ArrayList<GitRepository>(myRemainingRepositories);
repositories.remove(currentRepository);
return repositories;
}
protected void notifySuccess(@NotNull String message) {
VcsNotifier.getInstance(myProject).notifySuccess(message);
}
protected final void notifySuccess() {
notifySuccess(getSuccessMessage());
}
protected final void saveAllDocuments() {
ApplicationManager.getApplication().invokeAndWait(() -> FileDocumentManager.getInstance().saveAllDocuments(), defaultModalityState());
}
/**
* Show fatal error as a notification or as a dialog with rollback proposal.
*/
protected void fatalError(@NotNull String title, @NotNull String message) {
if (wereSuccessful()) {
showFatalErrorDialogWithRollback(title, message);
}
else {
showFatalNotification(title, message);
}
}
protected void showFatalErrorDialogWithRollback(@NotNull final String title, @NotNull final String message) {
boolean rollback = myUiHandler.notifyErrorWithRollbackProposal(title, message, getRollbackProposal());
if (rollback) {
rollback();
}
}
protected void showFatalNotification(@NotNull String title, @NotNull String message) {
notifyError(title, message);
}
protected void notifyError(@NotNull String title, @NotNull String message) {
VcsNotifier.getInstance(myProject).notifyError(title, message);
}
@NotNull
protected ProgressIndicator getIndicator() {
return myUiHandler.getProgressIndicator();
}
/**
* Display the error saying that the operation can't be performed because there are unmerged files in a repository.
* Such error prevents checking out and creating new branch.
*/
protected void fatalUnmergedFilesError() {
if (wereSuccessful()) {
showUnmergedFilesDialogWithRollback();
}
else {
showUnmergedFilesNotification();
}
}
@NotNull
protected String repositories() {
return pluralize("repository", getSuccessfulRepositories().size());
}
/**
* Updates the recently visited branch in the settings.
* This is to be performed after successful checkout operation.
*/
protected void updateRecentBranch() {
if (getRepositories().size() == 1) {
GitRepository repository = myRepositories.iterator().next();
String currentHead = myCurrentHeads.get(repository);
if (currentHead != null) {
mySettings.setRecentBranchOfRepository(repository.getRoot().getPath(), currentHead);
}
else {
LOG.error("Current head is not known for " + repository.getRoot().getPath());
}
}
else {
String recentCommonBranch = getRecentCommonBranch();
if (recentCommonBranch != null) {
mySettings.setRecentCommonBranch(recentCommonBranch);
}
}
}
@Nullable
private String getRecentCommonBranch() {
String recentCommonBranch = null;
for (String branch : myCurrentHeads.values()) {
if (recentCommonBranch == null) {
recentCommonBranch = branch;
}
else if (!recentCommonBranch.equals(branch)) {
return null;
}
}
return recentCommonBranch;
}
private void showUnmergedFilesDialogWithRollback() {
boolean ok = myUiHandler.showUnmergedFilesMessageWithRollback(getOperationName(), getRollbackProposal());
if (ok) {
rollback();
}
}
private void showUnmergedFilesNotification() {
myUiHandler.showUnmergedFilesNotification(getOperationName(), getRepositories());
}
/**
* Asynchronously refreshes the VFS root directory of the given repository.
*/
protected void refreshRoot(@NotNull GitRepository repository) {
// marking all files dirty, because sometimes FileWatcher is unable to process such a large set of changes that can happen during
// checkout on a large repository: IDEA-89944
VfsUtil.markDirtyAndRefresh(false, true, false, repository.getRoot());
}
protected void fatalLocalChangesError(@NotNull String reference) {
String title = String.format("Couldn't %s %s", getOperationName(), reference);
if (wereSuccessful()) {
showFatalErrorDialogWithRollback(title, "");
}
}
/**
* Shows the error "The following untracked working tree files would be overwritten by checkout/merge".
* If there were no repositories that succeeded the operation, shows a notification with a link to the list of these untracked files.
* If some repositories succeeded, shows a dialog with the list of these files and a proposal to rollback the operation of those
* repositories.
*/
protected void fatalUntrackedFilesError(@NotNull VirtualFile root, @NotNull Collection<String> relativePaths) {
if (wereSuccessful()) {
showUntrackedFilesDialogWithRollback(root, relativePaths);
}
else {
showUntrackedFilesNotification(root, relativePaths);
}
}
private void showUntrackedFilesNotification(@NotNull VirtualFile root, @NotNull Collection<String> relativePaths) {
myUiHandler.showUntrackedFilesNotification(getOperationName(), root, relativePaths);
}
private void showUntrackedFilesDialogWithRollback(@NotNull VirtualFile root, @NotNull Collection<String> relativePaths) {
boolean ok = myUiHandler.showUntrackedFilesDialogWithRollback(getOperationName(), getRollbackProposal(), root, relativePaths);
if (ok) {
rollback();
}
}
/**
* TODO this is non-optimal and even incorrect, since such diff shows the difference between committed changes
* For each of the given repositories looks to the diff between current branch and the given branch and converts it to the list of
* local changes.
*/
@NotNull
Map<GitRepository, List<Change>> collectLocalChangesConflictingWithBranch(@NotNull Collection<GitRepository> repositories,
@NotNull String currentBranch, @NotNull String otherBranch) {
Map<GitRepository, List<Change>> changes = new HashMap<GitRepository, List<Change>>();
for (GitRepository repository : repositories) {
try {
Collection<String> diff = GitUtil.getPathsDiffBetweenRefs(myGit, repository, currentBranch, otherBranch);
List<Change> changesInRepo = GitUtil.findLocalChangesForPaths(myProject, repository.getRoot(), diff, false);
if (!changesInRepo.isEmpty()) {
changes.put(repository, changesInRepo);
}
}
catch (VcsException e) {
// ignoring the exception: this is not fatal if we won't collect such a diff from other repositories.
// At worst, use will get double dialog proposing the smart checkout.
LOG.warn(String.format("Couldn't collect diff between %s and %s in %s", currentBranch, otherBranch, repository.getRoot()), e);
}
}
return changes;
}
/**
* When checkout or merge operation on a repository fails with the error "local changes would be overwritten by...",
* affected local files are captured by the {@link git4idea.commands.GitMessageWithFilesDetector detector}.
* Then all remaining (non successful repositories) are searched if they are about to fail with the same problem.
* All collected local changes which prevent the operation, together with these repositories, are returned.
* @param currentRepository The first repository which failed the operation.
* @param localChangesOverwrittenBy The detector of local changes would be overwritten by merge/checkout.
* @param currentBranch Current branch.
* @param nextBranch Branch to compare with (the branch to be checked out, or the branch to be merged).
* @return Repositories that have failed or would fail with the "local changes" error, together with these local changes.
*/
@NotNull
protected Pair<List<GitRepository>, List<Change>> getConflictingRepositoriesAndAffectedChanges(
@NotNull GitRepository currentRepository, @NotNull GitMessageWithFilesDetector localChangesOverwrittenBy,
String currentBranch, String nextBranch) {
// get changes overwritten by checkout from the error message captured from Git
List<Change> affectedChanges = GitUtil.findLocalChangesForPaths(myProject, currentRepository.getRoot(),
localChangesOverwrittenBy.getRelativeFilePaths(), true
);
// get all other conflicting changes
// get changes in all other repositories (except those which already have succeeded) to avoid multiple dialogs proposing smart checkout
Map<GitRepository, List<Change>> conflictingChangesInRepositories =
collectLocalChangesConflictingWithBranch(getRemainingRepositoriesExceptGiven(currentRepository), currentBranch, nextBranch);
Set<GitRepository> otherProblematicRepositories = conflictingChangesInRepositories.keySet();
List<GitRepository> allConflictingRepositories = new ArrayList<GitRepository>(otherProblematicRepositories);
allConflictingRepositories.add(currentRepository);
for (List<Change> changes : conflictingChangesInRepositories.values()) {
affectedChanges.addAll(changes);
}
return Pair.create(allConflictingRepositories, affectedChanges);
}
@NotNull
protected static String stringifyBranchesByRepos(@NotNull Map<GitRepository, String> heads) {
MultiMap<String, VirtualFile> grouped = groupByBranches(heads);
if (grouped.size() == 1) {
return grouped.keySet().iterator().next();
}
return StringUtil.join(grouped.entrySet(), new Function<Map.Entry<String, Collection<VirtualFile>>, String>() {
@Override
public String fun(Map.Entry<String, Collection<VirtualFile>> entry) {
String roots = StringUtil.join(entry.getValue(), new Function<VirtualFile, String>() {
@Override
public String fun(VirtualFile file) {
return file.getName();
}
}, ", ");
return entry.getKey() + " (in " + roots + ")";
}
}, "<br/>");
}
@NotNull
private static MultiMap<String, VirtualFile> groupByBranches(@NotNull Map<GitRepository, String> heads) {
MultiMap<String, VirtualFile> result = MultiMap.createLinked();
List<GitRepository> sortedRepos = DvcsUtil.sortRepositories(heads.keySet());
for (GitRepository repo : sortedRepos) {
result.putValue(heads.get(repo), repo.getRoot());
}
return result;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.markup.html;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.markup.MarkupType;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.parser.filter.HtmlHeaderSectionHandler;
import org.apache.wicket.markup.renderStrategy.AbstractHeaderRenderStrategy;
import org.apache.wicket.model.IModel;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.handler.IPageRequestHandler;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.response.StringResponse;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for HTML pages. This subclass of Page simply returns HTML when asked for its markup
* type. It also has a method which subclasses can use to retrieve a bookmarkable link to the
* application's home page.
* <p>
* WebPages can be constructed with any constructor when they are being used in a Wicket session,
* but if you wish to link to a Page using a URL that is "bookmarkable" (which implies that the URL
* will not have any session information encoded in it, and that you can call this page directly
* without having a session first directly from your browser), you need to implement your Page with
* a no-arg constructor or with a constructor that accepts a PageParameters argument (which wraps
* any query string parameters for a request). In case the page has both constructors, the
* constructor with PageParameters will be used.
*
* @author Jonathan Locke
* @author Eelco Hillenius
* @author Juergen Donnerstag
* @author Gwyn Evans
*/
public class WebPage extends Page
{
/** log. */
private static final Logger log = LoggerFactory.getLogger(WebPage.class);
private static final long serialVersionUID = 1L;
/**
* Constructor. Having this constructor public means that your page is 'bookmarkable' and hence
* can be called/ created from anywhere.
*/
protected WebPage()
{
commonInit();
}
/**
* @see Page#Page(IModel)
*/
protected WebPage(final IModel<?> model)
{
super(model);
commonInit();
}
/**
* Constructor which receives wrapped query string parameters for a request. Having this
* constructor public means that your page is 'bookmarkable' and hence can be called/ created
* from anywhere. For bookmarkable pages (as opposed to when you construct page instances
* yourself, this constructor will be used in preference to a no-arg constructor, if both exist.
* Note that nothing is done with the page parameters argument. This constructor is provided so
* that tools such as IDEs will include it their list of suggested constructors for derived
* classes.
*
* Please call this constructor if you want to remember the pageparameters
* {@link #getPageParameters()}. So that they are reused for stateless links.
*
* @param parameters
* Wrapped query string parameters.
*/
protected WebPage(final PageParameters parameters)
{
super(parameters);
commonInit();
}
/**
* Gets the markup type for a WebPage, which is "html" by default. Support for pages in another
* markup language, such as VXML, would require the creation of a different Page subclass in an
* appropriate package under org.apache.wicket.markup. To support VXML (voice markup), one might
* create the package org.apache.wicket.markup.vxml and a subclass of Page called VoicePage.
*
* @return Markup type for HTML
*/
@Override
public MarkupType getMarkupType()
{
return MarkupType.HTML_MARKUP_TYPE;
}
/**
* Common code executed by constructors.
*/
private void commonInit()
{
// so far a noop
}
@Override
protected void onRender()
{
// Configure the response such as headers etc.
configureResponse((WebResponse)RequestCycle.get().getResponse());
// The rules if and when to insert an xml decl in the response are a it tricky. Allow the
// user to replace the default per page and per application.
renderXmlDecl();
super.onRender();
}
/**
* The rules if and when to insert an xml decl in the response are a it tricky. Allow the user
* to replace the default per page and per application.
*/
protected void renderXmlDecl()
{
WebApplication.get().renderXmlDecl(this, false);
}
/**
* Set-up response with appropriate content type, locale and encoding. The locale is set equal
* to the session's locale. The content type header contains information about the markup type
* (@see #getMarkupType()) and the encoding. The response (and request) encoding is determined
* by an application setting (@see ApplicationSettings#getResponseRequestEncoding()). If null,
* no xml decl will be written.
*
* @param response
* The WebResponse object
*/
protected void configureResponse(final WebResponse response)
{
// Users may subclass setHeader() to set there own headers
setHeaders(response);
// The response encoding is an application setting
final String encoding = getApplication().getRequestCycleSettings()
.getResponseRequestEncoding();
final boolean validEncoding = (Strings.isEmpty(encoding) == false);
final String contentType;
if (validEncoding)
{
contentType = getMarkupType().getMimeType() + "; charset=" + encoding;
}
else
{
contentType = getMarkupType().getMimeType();
}
response.setContentType(contentType);
}
/**
* Subclasses can override this to set there headers when the Page is being served. By default
* these headers are set:
*
* <pre>
* response.setHeader("Date", "[now]");
* response.setHeader("Expires", "[0]");
* response.setHeader("Pragma", "no-cache");
* response.setHeader("Cache-Control", "no-cache");
* </pre>
*
* So if a Page wants to control this or doesn't want to set this info it should override this
* method and don't call super.
*
* @param response
* The WebResponse where set(Date)Header can be called on.
*/
protected void setHeaders(WebResponse response)
{
response.disableCaching();
}
/**
*
* @see org.apache.wicket.Component#onAfterRender()
*/
@Override
protected void onAfterRender()
{
super.onAfterRender();
// only in development mode validate the headers
if (getApplication().usesDevelopmentConfig())
{
// Ignore if an exception and a redirect happened in between (e.g.
// RestartResponseAtInterceptPageException)
IRequestHandler activeHandler = getRequestCycle().getActiveRequestHandler();
if (activeHandler instanceof IPageRequestHandler)
{
IPageRequestHandler h = (IPageRequestHandler)activeHandler;
if (h.getPage() == this)
{
validateHeaders();
}
}
}
}
/**
* Validate that each component which wanted to contribute to the header section actually was
* able to do so.
*/
private void validateHeaders()
{
// search for HtmlHeaderContainer in the first level of children or deeper
// if there are transparent resolvers used
HtmlHeaderContainer header = visitChildren(new IVisitor<Component, HtmlHeaderContainer>()
{
public void component(final Component component, final IVisit<HtmlHeaderContainer> visit)
{
if (component instanceof HtmlHeaderContainer)
{
visit.stop((HtmlHeaderContainer)component);
}
else if (component instanceof TransparentWebMarkupContainer == false)
{
visit.dontGoDeeper();
}
}
});
if (header == null)
{
// the markup must at least contain a <body> tag for wicket to automatically
// create a HtmlHeaderContainer. Log an error if no header container
// was created but any of the components or behaviors want to contribute
// something to the header.
header = new HtmlHeaderContainer(HtmlHeaderSectionHandler.HEADER_ID);
add(header);
Response orgResponse = getRequestCycle().getResponse();
try
{
final StringResponse response = new StringResponse();
getRequestCycle().setResponse(response);
// Render all header sections of all components on the page
AbstractHeaderRenderStrategy.get().renderHeader(header, getPage());
response.close();
if (response.getBuffer().length() > 0)
{
// @TODO it is not yet working properly. JDo to fix it
log.error("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
log.error("You probably forgot to add a <body> or <head> tag to your markup since no Header Container was \n" +
"found but components were found which want to write to the <head> section.\n" +
response.getBuffer());
log.error("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
}
}
catch (Exception e)
{
// just swallow this exception, there isn't much we can do about.
log.error("header/body check throws exception", e);
}
finally
{
this.remove(header);
getRequestCycle().setResponse(orgResponse);
}
}
}
/**
* Creates and returns a bookmarkable link to this application's home page.
*
* @param id
* Name of link
* @return Link to home page for this application
*/
protected final BookmarkablePageLink<Void> homePageLink(final String id)
{
return new BookmarkablePageLink<Void>(id, getApplication().getHomePage());
}
/**
* Prevents page from get dirt inside an AJAX request.
*/
@Override
public final void dirty(boolean isInitialization)
{
Request request = getRequest();
if (isInitialization == false && request instanceof WebRequest &&
((WebRequest)request).isAjax())
{
return;
}
super.dirty(isInitialization);
}
}
| |
/*
* 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.
*/
/* $Id$ */
package org.apache.fop.layoutmgr;
import java.util.List;
import java.util.ListIterator;
import org.apache.fop.traits.MinOptMax;
import org.apache.fop.util.ListUtil;
/**
* Utilities for Knuth element lists.
*/
public final class ElementListUtils {
private ElementListUtils() {
// Utility class.
}
/**
* Removes legal breaks in an element list. A constraint can be specified to limit the
* range in which the breaks are removed. Legal breaks occuring before at least
* constraint.opt space is filled will be removed.
* @param elements the element list
* @param constraint min/opt/max value to restrict the range in which the breaks are removed.
* @return true if the opt constraint is bigger than the list contents
*/
public static boolean removeLegalBreaks(List elements, MinOptMax constraint) {
return removeLegalBreaks(elements, constraint.getOpt());
}
/**
* Removes legal breaks in an element list. A constraint can be specified to limit the
* range in which the breaks are removed. Legal breaks occuring before at least
* constraint space is filled will be removed.
* @param elements the element list
* @param constraint value to restrict the range in which the breaks are removed.
* @return true if the constraint is bigger than the list contents
*/
public static boolean removeLegalBreaks(List elements, int constraint) {
return removeLegalBreaks(elements, constraint, false);
}
/**
* Removes legal breaks in an element list. A constraint can be specified to limit the
* range in which the breaks are removed. Legal breaks within the space specified through the
* constraint (starting from the end of the element list) will be removed.
* @param elements the element list
* @param constraint value to restrict the range in which the breaks are removed.
* @return true if the constraint is bigger than the list contents
*/
public static boolean removeLegalBreaksFromEnd(List elements, int constraint) {
return removeLegalBreaks(elements, constraint, true);
}
private static boolean removeLegalBreaks(List elements, int constraint, boolean fromEnd) {
int len = 0;
ListElement el;
for (ListIterator iter = elements.listIterator(fromEnd ? elements.size() : 0);
(fromEnd ? iter.hasPrevious() : iter.hasNext());) {
if (fromEnd) {
el = (ListElement) iter.previous();
} else {
el = (ListElement) iter.next();
}
if (el.isPenalty()) {
KnuthPenalty penalty = (KnuthPenalty)el;
//Convert penalty to break inhibitor
if (penalty.getPenalty() < KnuthPenalty.INFINITE) {
iter.set(new KnuthPenalty(penalty.getWidth(), KnuthPenalty.INFINITE,
penalty.isPenaltyFlagged(), penalty.getPosition(),
penalty.isAuxiliary()));
}
} else if (el.isGlue()) {
KnuthGlue glue = (KnuthGlue)el;
len += glue.getWidth();
//check if previous is a box
if (!fromEnd) {
iter.previous();
}
el = (ListElement)iter.previous();
iter.next();
if (el.isBox()) {
//add break inhibitor
iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false,
null, false));
}
if (!fromEnd) {
iter.next();
}
} else if (el.isUnresolvedElement()) {
if (el instanceof BreakElement) {
BreakElement breakEl = (BreakElement)el;
if (breakEl.getPenaltyValue() < KnuthPenalty.INFINITE) {
breakEl.setPenaltyValue(KnuthPenalty.INFINITE);
}
} else if (el instanceof UnresolvedListElementWithLength) {
UnresolvedListElementWithLength uel = (UnresolvedListElementWithLength)el;
len += uel.getLength().getOpt();
}
} else {
KnuthElement kel = (KnuthElement)el;
len += kel.getWidth();
}
if (len >= constraint) {
return false;
}
}
return true;
}
/**
* Calculates the content length of the given element list. Warning: It doesn't take any
* stretch and shrink possibilities into account.
* @param elems the element list
* @param start element at which to start
* @param end element at which to stop
* @return the content length
*/
public static int calcContentLength(List elems, int start, int end) {
ListIterator iter = elems.listIterator(start);
int count = end - start + 1;
int len = 0;
while (iter.hasNext()) {
ListElement el = (ListElement)iter.next();
if (el.isBox()) {
len += ((KnuthElement)el).getWidth();
} else if (el.isGlue()) {
len += ((KnuthElement)el).getWidth();
} else {
//log.debug("Ignoring penalty: " + el);
//ignore penalties
}
count--;
if (count == 0) {
break;
}
}
return len;
}
/**
* Calculates the content length of the given element list. Warning: It doesn't take any
* stretch and shrink possibilities into account.
* @param elems the element list
* @return the content length
*/
public static int calcContentLength(List elems) {
return calcContentLength(elems, 0, elems.size() - 1);
}
/**
* Indicates whether the given element list ends with a forced break.
* @param elems the element list
* @return true if the list ends with a forced break
*/
public static boolean endsWithForcedBreak(List elems) {
return ((ListElement) ListUtil.getLast(elems)).isForcedBreak();
}
/**
* Indicates whether the given element list starts with a forced break.
* @param elems the element list
* @return true if the list starts with a forced break
*/
public static boolean startsWithForcedBreak(List elems) {
return !elems.isEmpty() && ((ListElement) elems.get(0)).isForcedBreak();
}
/**
* Indicates whether the given element list ends with a penalty with a non-infinite penalty
* value.
* @param elems the element list
* @return true if the list ends with a non-infinite penalty
*/
public static boolean endsWithNonInfinitePenalty(List elems) {
ListElement last = (ListElement) ListUtil.getLast(elems);
if (last.isPenalty() && ((KnuthPenalty)last).getPenalty() < KnuthElement.INFINITE) {
return true;
} else if (last instanceof BreakElement
&& ((BreakElement)last).getPenaltyValue() < KnuthElement.INFINITE) {
return true;
}
return false;
}
/**
* Determines the position of the previous break before the start index on an
* element list.
* @param elems the element list
* @param startIndex the start index
* @return the position of the previous break, or -1 if there was no previous break
*/
public static int determinePreviousBreak(List elems, int startIndex) {
int prevBreak = startIndex - 1;
while (prevBreak >= 0) {
KnuthElement el = (KnuthElement)elems.get(prevBreak);
if (el.isPenalty() && el.getPenalty() < KnuthElement.INFINITE) {
break;
}
prevBreak--;
}
return prevBreak;
}
public static boolean isEmptyBox(List elements) {
if (elements.size() == 1 && elements.get(0) instanceof KnuthBox) {
KnuthBox kb = (KnuthBox) elements.get(0);
if (kb.getWidth() == 0) {
return true;
}
}
return false;
}
}
| |
package org.yesod.ktisis.java;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.yesod.ktisis.TemplateProcessor;
import org.yesod.ktisis.VariableResolver;
import org.yesod.ktisis.base.ExtensionMethod.ExtensionPoint;
import org.yesod.ktisis.base.FeatureTags;
import org.yesod.ktisis.base.FeatureTags.Feature;
import org.yesod.ktisis.base.FunctionsPlugin.FunctionRegistration;
import org.yesod.ktisis.base.WhitespaceHelper;
import org.yesod.ktisis.base.WhitespaceHelperConfig;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.ImmutableMap;
public class ClassBase
{
public static List<Map<?, ?>> getSuperFields(VariableResolver ctx)
{
Builder<Map<?, ?>> builder = ImmutableList.builder();
Map<?, ?> superdef = ctx.getAs("supertype", Map.class).orElse(null);
if (superdef != null)
{
List<?> fields = (List<?>) superdef.get("fields");
fields.stream().map(Map.class::cast).forEach(builder::add);
}
return builder.build();
}
public static List<Map<?, ?>> getFields(VariableResolver ctx)
{
Builder<Map<?, ?>> builder = ImmutableList.builder();
List<?> fields = ctx.getAs("fields", List.class).orElseThrow(RuntimeException::new);
fields.stream().map(Map.class::cast).forEach(builder::add);
return builder.build();
}
public static List<Map<?, ?>> getFieldsAndSuperFields(VariableResolver ctx)
{
Builder<Map<?, ?>> builder = ImmutableList.builder();
return builder.addAll(getSuperFields(ctx)).addAll(getFields(ctx)).build();
}
public static boolean isOptional(Map<?, ?> field)
{
return isOptional(field::get);
}
public static boolean isOptional(VariableResolver fieldCtx)
{
return fieldCtx.getAs("optional", Boolean.class).orElse(null) == Boolean.TRUE;
}
@ExtensionPoint("class")
public String writeClass(VariableResolver variableResolver) throws IOException
{
try (InputStream template = TemplateProcessor.getResource("templates/ktisis/java/ClassBase.template", ClassBase.class))
{
ImmutableMap<?, ?> subParts = ImmutableMap.builder()
.put("ctor_args", ctorArgs(variableResolver))
.put("super_type_opt", superTypeOpt(variableResolver))
.put("class_modifiers",
variableResolver.getAs("class_modifiers", Collection.class)
.map(s -> " " + Joiner.on(" ").join(s))
.orElse(""))
.build();
VariableResolver subResolver = VariableResolver.merge(subParts::get, variableResolver);
return TemplateProcessor.processTemplate(template, subResolver);
}
}
private String ctorArgs(VariableResolver ctx)
{
List<String> builder = new ArrayList<>();
for (Object field : getFieldsAndSuperFields(ctx))
{
Map<?, ?> fieldAttrs = (Map<?, ?>) field;
builder.add(TemplateProcessor.processTemplate("@{ctor_arg}${type} ${name}", VariableResolver.merge(fieldAttrs::get, ctx)));
}
int column = WhitespaceHelper.length(ctx.apply("name"), ctx.apply("scope")) + 4;
return WhitespaceHelper.joinWithWrapIfNecessary(builder, ", ", column, 120);
}
private String superTypeOpt(VariableResolver variableResolver)
{
Map<?, ?> superdef = variableResolver.getAs("supertype", Map.class).orElse(null);
String impls = variableResolver.getAs("implements", String.class).map(impl -> " implements " + impl).orElse("");
if (superdef == null)
{
return impls;
}
return String.format(" extends %s%s", superdef.get("name"), impls);
}
@ExtensionPoint("super_ctor_opt")
public String superCtorOpt(VariableResolver ctx)
{
List<Map<?, ?>> superFields = getSuperFields(ctx);
if (superFields.isEmpty())
{
return null;
}
String args = superFields.stream().map((f) -> (String) f.get("name")).collect(Collectors.joining(", "));
return String.format(" super(%s);", args);
}
@ExtensionPoint("class_ctor_body")
public String ctorBody(VariableResolver variableResolver)
{
List<?> fields = variableResolver.getAs("fields", List.class).orElse(null);
Preconditions.checkState(fields != null, "Trying to build a class without fields?");
List<String> lines = new ArrayList<>();
for (Object field : fields)
{
Map<?, ?> fieldAttrs = Map.class.cast(field);
VariableResolver merge = VariableResolver.merge(fieldAttrs::get, variableResolver);
if (!isOptional(fieldAttrs))
{
Imports.addImport(Preconditions.class);
lines.add(TemplateProcessor.processTemplate("Preconditions.checkNotNull(${name}, \"${name} (${type}) is a required field\");", merge));
}
lines.add(TemplateProcessor.processTemplate("this.${name} = ${name};", merge));
}
WhitespaceHelperConfig config = WhitespaceHelperConfig.lineJoiner(4);
return WhitespaceHelper.spaces(4) + WhitespaceHelper.join(config, lines);
}
@ExtensionPoint("class_fields")
public String writeClassFields(VariableResolver variableResolver)
{
Collection<String> lines = new ArrayList<>();
List<?> fields = variableResolver.getAs("fields", List.class).orElse(null);
Preconditions.checkState(fields != null, "Trying to build a class without fields?");
for (Object field : fields)
{
Map<?, ?> fieldAttrs = Map.class.cast(field);
VariableResolver vr = VariableResolver.merge(fieldAttrs::get, variableResolver);
if (!FeatureTags.hasTag(Setters.TAG, vr, false) && vr.apply("final") != Boolean.FALSE)
{
lines.add(TemplateProcessor.processTemplate(" @{field}private final ${type} ${name};", vr));
}
else
{
lines.add(TemplateProcessor.processTemplate(" @{field}private ${type} ${name};", vr));
}
}
return Joiner.on(WhitespaceHelper.lf()).join(lines);
}
public static String upcase(String name)
{
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
public static String getterName(String name, String type)
{
return String.format("%s%s", type.equals("Boolean") ? "is" : "get", upcase(name));
}
@Feature(value = "getters", includeByDefault = true)
@ExtensionPoint("getters")
public String writeClassGetters(VariableResolver variableResolver) throws IOException
{
Collection<String> lines = new ArrayList<>();
List<?> fields = variableResolver.getAs("fields", List.class).orElse(null);
Preconditions.checkState(fields != null, "Trying to build a class without fields?");
for (Object field : fields)
{
Map<?, ?> fieldAttrs = Map.class.cast(field);
String name = fieldAttrs.get("name").toString();
String type = fieldAttrs.get("type").toString();
boolean isOptional = isOptional(fieldAttrs);
if (isOptional)
{
Imports.addImport(Optional.class);
}
String getterName = getterName(name, type);
String returnType = isOptional ? String.format("Optional<%s>", type) : type;
String returnStr = isOptional ? String.format("Optional.ofNullable(%s)", name) : name;
if (BasicBuilder.isCollector(fieldAttrs) && !type.contains("Immutable"))
{
Imports.addImport(Collections.class);
returnStr = String.format("Collections.unmodifiable%s(%s)", BasicBuilder.baseCollectionType(type), name);
returnType = type;
}
Map<?, ?> overrides = ImmutableMap.builder()
.put("getter_name", getterName)
.put("type", returnType)
.put("return", returnStr)
.build();
try (InputStream template = TemplateProcessor.getResource("templates/ktisis/java/Getter.template", ClassBase.class))
{
lines.add(TemplateProcessor.processTemplate(template, VariableResolver.merge(overrides::get, fieldAttrs::get, variableResolver)));
}
}
return Joiner.on(WhitespaceHelper.lf()).join(lines);
}
@FunctionRegistration("formatComment")
public String formatComment(String[] args, VariableResolver ctx)
{
Preconditions.checkArgument(args.length >= 2);
// The args list has been split on ", "; if the comment contained that string then we need to restore it
String comment = args[0];
for (int i = 1; i < args.length - 1; i++)
{
comment += ", " + args[i];
}
comment = TemplateProcessor.processTemplate(comment, ctx);
int indent = Integer.parseInt(args[args.length - 1]);
String[] words = comment.split(" ");
String line = words[0];
Collection<String> lines = new ArrayList<>();
for (int i = 1; i < words.length; i++)
{
String word = words[i];
if (line.length() + word.length() < 80)
{
line += " " + word;
}
else
{
lines.add(line);
line = word;
}
}
lines.add(line);
WhitespaceHelperConfig config = new WhitespaceHelperConfig.Builder().postJoin(" * ")
.wrappedIndent(indent)
.lineLength(0)
.build();
return WhitespaceHelper.join(config, lines);
}
@Feature(value = "hashEquals", includeByDefault = true)
@ExtensionPoint("end_class")
public String writeHashCode(VariableResolver variableResolver) throws IOException
{
Collection<String> lines = new ArrayList<>();
List<?> fields = variableResolver.getAs("fields", List.class).orElse(null);
Preconditions.checkState(fields != null, "Trying to build a class without fields?");
List<Map<?, ?>> superFields = getSuperFields(variableResolver);
if (!superFields.isEmpty())
{
lines.add("super.hashCode()");
}
for (Object field : fields)
{
Map<?, ?> fieldAttrs = (Map<?, ?>) field;
if (fieldAttrs.get("hashcode") != Boolean.FALSE)
{
lines.add(fieldAttrs.get("name").toString());
}
}
String hashCodeBody = WhitespaceHelper.joinWithWrapIfNecessary(lines, ", ", 13, 120);
VariableResolver inner = (s) -> hashCodeBody;
try (InputStream is = TemplateProcessor.getResource("templates/ktisis/java/HashCode.template", getClass()))
{
return TemplateProcessor.processTemplate(is, inner);
}
}
@Feature(value = "hashEquals", includeByDefault = true)
@ExtensionPoint("end_class")
public String writeEquals(VariableResolver variableResolver) throws IOException
{
Collection<String> lines = new ArrayList<>();
List<?> fields = variableResolver.getAs("fields", List.class).orElse(null);
Preconditions.checkState(fields != null, "Trying to build a class without fields?");
List<Map<?, ?>> superFields = getSuperFields(variableResolver);
if (!superFields.isEmpty())
{
lines.add("super.equals(that)");
}
Imports.addImport(Objects.class);
for (Object field : fields)
{
Map<?, ?> fieldAttrs = (Map<?, ?>) field;
if (fieldAttrs.get("equals") != Boolean.FALSE)
{
String name = fieldAttrs.get("name").toString();
lines.add(String.format("Objects.equal(this.%s, that.%s)", name, name));
}
}
String equalsBody = WhitespaceHelper.joinWithWrapIfNecessary(lines, "", " && ", 10, 120);
VariableResolver inner = (s) -> equalsBody;
try (InputStream is = TemplateProcessor.getResource("templates/ktisis/java/Equals.template", getClass()))
{
return TemplateProcessor.processTemplate(is, VariableResolver.merge(variableResolver, inner));
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.execution;
import com.facebook.presto.OutputBuffers;
import com.facebook.presto.OutputBuffers.OutputBufferId;
import com.facebook.presto.TaskSource;
import com.facebook.presto.client.NodeVersion;
import com.facebook.presto.event.query.QueryMonitor;
import com.facebook.presto.event.query.QueryMonitorConfig;
import com.facebook.presto.eventlistener.EventListenerManager;
import com.facebook.presto.execution.buffer.BufferResult;
import com.facebook.presto.execution.buffer.BufferState;
import com.facebook.presto.execution.executor.TaskExecutor;
import com.facebook.presto.memory.MemoryPool;
import com.facebook.presto.memory.QueryContext;
import com.facebook.presto.spi.QueryId;
import com.facebook.presto.spi.memory.MemoryPoolId;
import com.facebook.presto.spiller.SpillSpaceTracker;
import com.facebook.presto.sql.planner.LocalExecutionPlanner;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ListenableFuture;
import io.airlift.json.ObjectMapperProvider;
import io.airlift.node.NodeInfo;
import io.airlift.units.DataSize;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import java.net.URI;
import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import static com.facebook.presto.OutputBuffers.BufferType.PARTITIONED;
import static com.facebook.presto.OutputBuffers.createInitialEmptyOutputBuffers;
import static com.facebook.presto.SessionTestUtils.TEST_SESSION;
import static com.facebook.presto.execution.TaskTestUtils.EMPTY_SOURCES;
import static com.facebook.presto.execution.TaskTestUtils.PLAN_FRAGMENT;
import static com.facebook.presto.execution.TaskTestUtils.SPLIT;
import static com.facebook.presto.execution.TaskTestUtils.TABLE_SCAN_NODE_ID;
import static com.facebook.presto.execution.TaskTestUtils.createTestingPlanner;
import static com.facebook.presto.execution.TaskTestUtils.updateTask;
import static io.airlift.concurrent.Threads.threadsNamed;
import static io.airlift.json.JsonCodec.jsonCodec;
import static io.airlift.units.DataSize.Unit.GIGABYTE;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static java.util.concurrent.Executors.newScheduledThreadPool;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
@Test(singleThreaded = true)
public class TestSqlTask
{
public static final OutputBufferId OUT = new OutputBufferId(0);
private final TaskExecutor taskExecutor;
private final ScheduledExecutorService taskNotificationExecutor;
private final SqlTaskExecutionFactory sqlTaskExecutionFactory;
private final AtomicInteger nextTaskId = new AtomicInteger();
public TestSqlTask()
{
taskExecutor = new TaskExecutor(8, 16);
taskExecutor.start();
taskNotificationExecutor = newScheduledThreadPool(10, threadsNamed("task-notification-%s"));
LocalExecutionPlanner planner = createTestingPlanner();
sqlTaskExecutionFactory = new SqlTaskExecutionFactory(
taskNotificationExecutor,
taskExecutor,
planner,
new QueryMonitor(new ObjectMapperProvider().get(), jsonCodec(StageInfo.class), new EventListenerManager(), new NodeInfo("test"), new NodeVersion("testVersion"), new QueryMonitorConfig()),
new TaskManagerConfig());
}
@AfterClass
public void destroy()
throws Exception
{
taskExecutor.stop();
taskNotificationExecutor.shutdownNow();
}
@Test
public void testEmptyQuery()
throws Exception
{
SqlTask sqlTask = createInitialTask();
TaskInfo taskInfo = sqlTask.updateTask(TEST_SESSION,
Optional.of(PLAN_FRAGMENT),
ImmutableList.of(),
createInitialEmptyOutputBuffers(PARTITIONED)
.withNoMoreBufferIds());
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);
taskInfo = sqlTask.getTaskInfo();
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);
taskInfo = sqlTask.updateTask(TEST_SESSION,
Optional.of(PLAN_FRAGMENT),
ImmutableList.of(new TaskSource(TABLE_SCAN_NODE_ID, ImmutableSet.of(), true)),
createInitialEmptyOutputBuffers(PARTITIONED)
.withNoMoreBufferIds());
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.FINISHED);
taskInfo = sqlTask.getTaskInfo();
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.FINISHED);
}
@Test
public void testSimpleQuery()
throws Exception
{
SqlTask sqlTask = createInitialTask();
TaskInfo taskInfo = sqlTask.updateTask(TEST_SESSION,
Optional.of(PLAN_FRAGMENT),
ImmutableList.of(new TaskSource(TABLE_SCAN_NODE_ID, ImmutableSet.of(SPLIT), true)),
createInitialEmptyOutputBuffers(PARTITIONED).withBuffer(OUT, 0).withNoMoreBufferIds());
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);
taskInfo = sqlTask.getTaskInfo();
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);
BufferResult results = sqlTask.getTaskResults(OUT, 0, new DataSize(1, MEGABYTE)).get();
assertEquals(results.isBufferComplete(), false);
assertEquals(results.getSerializedPages().size(), 1);
assertEquals(results.getSerializedPages().get(0).getPositionCount(), 1);
for (boolean moreResults = true; moreResults; moreResults = !results.isBufferComplete()) {
results = sqlTask.getTaskResults(OUT, results.getToken() + results.getSerializedPages().size(), new DataSize(1, MEGABYTE)).get();
}
assertEquals(results.getSerializedPages().size(), 0);
// complete the task by calling abort on it
TaskInfo info = sqlTask.abortTaskResults(OUT);
assertEquals(info.getOutputBuffers().getState(), BufferState.FINISHED);
taskInfo = sqlTask.getTaskInfo(taskInfo.getTaskStatus().getState()).get(1, SECONDS);
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.FINISHED);
taskInfo = sqlTask.getTaskInfo();
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.FINISHED);
}
@Test
public void testCancel()
throws Exception
{
SqlTask sqlTask = createInitialTask();
TaskInfo taskInfo = sqlTask.updateTask(TEST_SESSION,
Optional.of(PLAN_FRAGMENT),
ImmutableList.of(),
createInitialEmptyOutputBuffers(PARTITIONED)
.withBuffer(OUT, 0)
.withNoMoreBufferIds());
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);
assertNull(taskInfo.getStats().getEndTime());
taskInfo = sqlTask.getTaskInfo();
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);
assertNull(taskInfo.getStats().getEndTime());
taskInfo = sqlTask.cancel();
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.CANCELED);
assertNotNull(taskInfo.getStats().getEndTime());
taskInfo = sqlTask.getTaskInfo();
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.CANCELED);
assertNotNull(taskInfo.getStats().getEndTime());
}
@Test
public void testAbort()
throws Exception
{
SqlTask sqlTask = createInitialTask();
TaskInfo taskInfo = sqlTask.updateTask(TEST_SESSION,
Optional.of(PLAN_FRAGMENT),
ImmutableList.of(new TaskSource(TABLE_SCAN_NODE_ID, ImmutableSet.of(SPLIT), true)),
createInitialEmptyOutputBuffers(PARTITIONED).withBuffer(OUT, 0).withNoMoreBufferIds());
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);
taskInfo = sqlTask.getTaskInfo();
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);
sqlTask.abortTaskResults(OUT);
taskInfo = sqlTask.getTaskInfo(taskInfo.getTaskStatus().getState()).get(1, SECONDS);
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.FINISHED);
taskInfo = sqlTask.getTaskInfo();
assertEquals(taskInfo.getTaskStatus().getState(), TaskState.FINISHED);
}
@Test
public void testBufferCloseOnFinish()
throws Exception
{
SqlTask sqlTask = createInitialTask();
OutputBuffers outputBuffers = createInitialEmptyOutputBuffers(PARTITIONED).withBuffer(OUT, 0).withNoMoreBufferIds();
updateTask(sqlTask, EMPTY_SOURCES, outputBuffers);
ListenableFuture<BufferResult> bufferResult = sqlTask.getTaskResults(OUT, 0, new DataSize(1, MEGABYTE));
assertFalse(bufferResult.isDone());
// close the sources (no splits will ever be added)
updateTask(sqlTask, ImmutableList.of(new TaskSource(TABLE_SCAN_NODE_ID, ImmutableSet.of(), true)), outputBuffers);
// finish the task by calling abort on it
sqlTask.abortTaskResults(OUT);
// buffer will be closed by cancel event (wait for event to fire)
bufferResult.get(1, SECONDS);
// verify the buffer is closed
bufferResult = sqlTask.getTaskResults(OUT, 0, new DataSize(1, MEGABYTE));
assertTrue(bufferResult.isDone());
assertTrue(bufferResult.get().isBufferComplete());
}
@Test
public void testBufferCloseOnCancel()
throws Exception
{
SqlTask sqlTask = createInitialTask();
updateTask(sqlTask, EMPTY_SOURCES, createInitialEmptyOutputBuffers(PARTITIONED).withBuffer(OUT, 0).withNoMoreBufferIds());
ListenableFuture<BufferResult> bufferResult = sqlTask.getTaskResults(OUT, 0, new DataSize(1, MEGABYTE));
assertFalse(bufferResult.isDone());
sqlTask.cancel();
assertEquals(sqlTask.getTaskInfo().getTaskStatus().getState(), TaskState.CANCELED);
// buffer future will complete.. the event is async so wait a bit for event to propagate
bufferResult.get(1, SECONDS);
bufferResult = sqlTask.getTaskResults(OUT, 0, new DataSize(1, MEGABYTE));
assertTrue(bufferResult.isDone());
assertTrue(bufferResult.get().isBufferComplete());
}
@Test
public void testBufferNotCloseOnFail()
throws Exception
{
SqlTask sqlTask = createInitialTask();
updateTask(sqlTask, EMPTY_SOURCES, createInitialEmptyOutputBuffers(PARTITIONED).withBuffer(OUT, 0).withNoMoreBufferIds());
ListenableFuture<BufferResult> bufferResult = sqlTask.getTaskResults(OUT, 0, new DataSize(1, MEGABYTE));
assertFalse(bufferResult.isDone());
TaskState taskState = sqlTask.getTaskInfo().getTaskStatus().getState();
sqlTask.failed(new Exception("test"));
assertEquals(sqlTask.getTaskInfo(taskState).get(1, SECONDS).getTaskStatus().getState(), TaskState.FAILED);
// buffer will not be closed by fail event. event is async so wait a bit for event to fire
try {
assertTrue(bufferResult.get(1, SECONDS).isBufferComplete());
fail("expected TimeoutException");
}
catch (TimeoutException expected) {
// expected
}
assertFalse(sqlTask.getTaskResults(OUT, 0, new DataSize(1, MEGABYTE)).isDone());
}
public SqlTask createInitialTask()
{
TaskId taskId = new TaskId("query", 0, nextTaskId.incrementAndGet());
URI location = URI.create("fake://task/" + taskId);
return new SqlTask(
taskId,
location,
new QueryContext(new QueryId("query"), new DataSize(1, MEGABYTE), new MemoryPool(new MemoryPoolId("test"), new DataSize(1, GIGABYTE)), new MemoryPool(new MemoryPoolId("testSystem"), new DataSize(1, GIGABYTE)), taskNotificationExecutor, new DataSize(1, MEGABYTE), new SpillSpaceTracker(new DataSize(1, GIGABYTE))),
sqlTaskExecutionFactory,
taskNotificationExecutor,
Functions.identity(),
new DataSize(32, MEGABYTE));
}
}
| |
/*
* 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.
*/
/**
* @author Igor V. Stolyarov
* @version $Revision$
*/
package awt.java.awt.image;
/**
* The Class DataBufferFloat is the subclass of DataBuffer for the case where
* the underlying data is float.
*
* @since Android 1.0
*/
public final class DataBufferFloat extends DataBuffer {
/**
* The data.
*/
float data[][];
/**
* Instantiates a new data buffer of type float.
*
* @param dataArrays
* the data arrays to copy the data from.
* @param size
* the length (number of elements) to use from the data arrays.
* @param offsets
* the starting indices for reading the data from the internal
* data arrays.
*/
public DataBufferFloat(float dataArrays[][], int size, int offsets[]) {
super(TYPE_FLOAT, size, dataArrays.length, offsets);
data = dataArrays.clone();
}
/**
* Instantiates a new data buffer of type float.
*
* @param dataArrays
* the data arrays to copy the data from.
* @param size
* the length (number of elements) to use from the data arrays.
*/
public DataBufferFloat(float dataArrays[][], int size) {
super(TYPE_FLOAT, size, dataArrays.length);
data = dataArrays.clone();
}
/**
* Instantiates a new data buffer of type float with a single underlying
* array of data.
*
* @param dataArray
* the data array to copy the data from.
* @param size
* the length (number of elements) to use.
* @param offset
* the starting index to use when reading the data.
*/
public DataBufferFloat(float dataArray[], int size, int offset) {
super(TYPE_FLOAT, size, 1, offset);
data = new float[1][];
data[0] = dataArray;
}
/**
* Instantiates a new data buffer of type float with a single underlying
* array of data starting at index 0.
*
* @param dataArray
* the data array to copy the data from.
* @param size
* the length (number of elements) to use.
*/
public DataBufferFloat(float dataArray[], int size) {
super(TYPE_FLOAT, size);
data = new float[1][];
data[0] = dataArray;
}
/**
* Instantiates a new empty data buffer of type float with offsets equal to
* zero.
*
* @param size
* the length (number of elements) to use from the data arrays.
* @param numBanks
* the number of data arrays to create.
*/
public DataBufferFloat(int size, int numBanks) {
super(TYPE_FLOAT, size, numBanks);
data = new float[numBanks][];
int i = 0;
while (i < numBanks) {
data[i++] = new float[size];
}
}
/**
* Instantiates a new empty data buffer of type float with a single
* underlying array of data starting at index 0.
*
* @param size
* the length (number of elements) to use.
*/
public DataBufferFloat(int size) {
super(TYPE_FLOAT, size);
data = new float[1][];
data[0] = new float[size];
}
@Override
public void setElem(int bank, int i, int val) {
data[bank][offsets[bank] + i] = val;
notifyChanged();
}
@Override
public void setElemFloat(int bank, int i, float val) {
data[bank][offsets[bank] + i] = val;
notifyChanged();
}
@Override
public void setElemDouble(int bank, int i, double val) {
data[bank][offsets[bank] + i] = (float)val;
notifyChanged();
}
@Override
public void setElem(int i, int val) {
data[0][offset + i] = val;
notifyChanged();
}
@Override
public int getElem(int bank, int i) {
return (int)(data[bank][offsets[bank] + i]);
}
@Override
public float getElemFloat(int bank, int i) {
return data[bank][offsets[bank] + i];
}
@Override
public double getElemDouble(int bank, int i) {
return data[bank][offsets[bank] + i];
}
@Override
public void setElemFloat(int i, float val) {
data[0][offset + i] = val;
notifyChanged();
}
@Override
public void setElemDouble(int i, double val) {
data[0][offset + i] = (float)val;
notifyChanged();
}
/**
* Gets the data of the specified internal data array.
*
* @param bank
* the index of the desired array.
* @return the data.
*/
public float[] getData(int bank) {
notifyTaken();
return data[bank];
}
@Override
public int getElem(int i) {
return (int)(data[0][offset + i]);
}
@Override
public float getElemFloat(int i) {
return data[0][offset + i];
}
@Override
public double getElemDouble(int i) {
return data[0][offset + i];
}
/**
* Gets the bank data.
*
* @return the bank data.
*/
public float[][] getBankData() {
notifyTaken();
return data.clone();
}
/**
* Gets the data of the first data array.
*
* @return the data.
*/
public float[] getData() {
notifyTaken();
return data[0];
}
}
| |
// Copyright 2015 The Project Buendia 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 distrib-
// uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied. See the License for
// specific language governing permissions and limitations under the License.
package org.projectbuendia.client.data.app;
import android.database.ContentObserver;
import android.support.annotation.Nullable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.projectbuendia.client.utils.Logger;
/**
* A tree containing a hierarchy of {@link AppLocation} objects, where the root is assumed to be a
* single medical center.
*/
public class AppLocationTree implements AppModelObservable {
private static final Logger LOG = Logger.create();
public static final int ABSOLUTE_DEPTH_ROOT = 0;
public static final int ABSOLUTE_DEPTH_ZONE = 1;
public static final int ABSOLUTE_DEPTH_TENT = 2;
public static final int ABSOLUTE_DEPTH_BED = 3;
/**
* Creates a {@link AppLocationTree} from a {@link TypedCursor} of {@link AppLocation}s.
* If there are no locations in the local database, the location tree will have a null
* root node (i.e. getRoot() == null).
*
* <p>Callers must call {@link #close} when done with an instance of this class.
*
* @throws IllegalArgumentException if the location tree contains multiple root nodes or if the
* the location tree has no root node or if the location tree
* contains any nodes whose parents are missing
*/
public static AppLocationTree forTypedCursor(TypedCursor<AppLocation> cursor) {
AppLocation root = null;
Map<String, AppLocation> uuidsToLocations = new HashMap<>();
Map<String, AppLocation> uuidsToParents = new HashMap<>();
ImmutableSetMultimap.Builder<String, AppLocation> uuidsToChildrenBuilder =
ImmutableSetMultimap.builder();
// First, create mappings from location UUIDs to the locations themselves and to their
// children.
for (AppLocation location : cursor) {
if (location.parentUuid == null) {
if (root != null) {
LOG.w(
"Creating location tree with multiple root nodes. Both location '"
+ root.name + "' (UUID '" + root.uuid + "') and location '"
+ location.name + "' (UUID '" + location.uuid + "') have "
+ "no parent nodes. The first location will be considered "
+ "the root node.");
}
root = location;
} else {
uuidsToChildrenBuilder.put(location.parentUuid, location);
}
uuidsToLocations.put(location.uuid, location);
}
if (root == null) {
LOG.w("Creating a location tree with no root node. This tree has no data.");
return new AppLocationTree(
cursor, null, uuidsToLocations, uuidsToParents, uuidsToChildrenBuilder.build());
}
// Then, create a mapping from location UUIDs to their parents.
for (AppLocation location : uuidsToLocations.values()) {
if (location.parentUuid == null) {
continue;
}
AppLocation parent = uuidsToLocations.get(location.parentUuid);
if (parent == null) {
// TODO: Consider making this a warning rather than an exception.
throw new IllegalArgumentException(
"Unable to create tree because a location's parent does not exist. "
+ "Location '" + location.name + "' (UUID '" + location.uuid
+ "' points to parent location with UUID '"
+ location.parentUuid + "', which does not exist.");
}
uuidsToParents.put(location.uuid, parent);
}
return new AppLocationTree(
cursor, root, uuidsToLocations, uuidsToParents, uuidsToChildrenBuilder.build());
}
private final TypedCursor<AppLocation> mCursor;
private final AppLocation mRoot;
private final Map<String, AppLocation> mUuidsToLocations;
private final Map<String, AppLocation> mUuidsToParents;
private final ImmutableSetMultimap<String, AppLocation> mUuidsToChildren;
private AppLocationTree(
TypedCursor<AppLocation> cursor,
AppLocation root,
Map<String, AppLocation> uuidsToLocations,
Map<String, AppLocation> uuidsToParents,
ImmutableSetMultimap<String, AppLocation> uuidsToChildren) {
mCursor = cursor;
mRoot = root;
mUuidsToLocations = uuidsToLocations;
mUuidsToParents = uuidsToParents;
mUuidsToChildren = uuidsToChildren;
}
@Nullable
public AppLocation getRoot() {
return mRoot;
}
/** Returns the parent of a given {@link AppLocation}. */
@Nullable
public AppLocation getParent(@Nullable AppLocation location) {
if (location == null) {
return null;
}
return mUuidsToParents.get(location.uuid);
}
/**
* Returns all immediate children of a given {@link AppLocation}, or an empty set if the
* {@link AppLocation} is null or has no children.
*/
public ImmutableSet<AppLocation> getChildren(@Nullable AppLocation location) {
if (location == null) {
return ImmutableSet.of();
}
ImmutableSet<AppLocation> children = mUuidsToChildren.get(location.uuid);
return children == null ? ImmutableSet.<AppLocation>of() : children;
}
/**
* Returns the sorted descendants of the root location at the specified absolute depth.
*
* <p>The named values {@link #ABSOLUTE_DEPTH_ROOT}, {@link #ABSOLUTE_DEPTH_ZONE},
* {@link #ABSOLUTE_DEPTH_TENT}, and {@link #ABSOLUTE_DEPTH_BED} can be used for the
* {@code level} parameter.
*/
public ImmutableSortedSet<AppLocation> getDescendantsAtDepth(int absoluteDepth) {
return getDescendantsAtDepth(mRoot, absoluteDepth);
}
/**
* Returns the sorted descendants of the specified location at the specified depth relative to
* that location.
*/
public ImmutableSortedSet<AppLocation> getDescendantsAtDepth(
AppLocation location, int relativeDepth) {
if (location == null) {
return ImmutableSortedSet.of();
}
if (relativeDepth == 0) {
ImmutableSortedSet.Builder<AppLocation> thisLocationSet =
ImmutableSortedSet.orderedBy(new AppLocationComparator(this));
thisLocationSet.add(location);
return thisLocationSet.build();
}
ImmutableSortedSet.Builder<AppLocation> descendants =
ImmutableSortedSet.orderedBy(new AppLocationComparator(this));
for (AppLocation child : getChildren(location)) {
descendants.addAll(getDescendantsAtDepth(child, relativeDepth - 1));
}
return descendants.build();
}
/**
* Returns a {@link List} representing a branch of {@link AppLocation}s starting at the root
* of the location tree and terminating at the given {@link AppLocation}.
*/
public List<AppLocation> getAncestorsStartingFromRoot(AppLocation node) {
List<AppLocation> result = new ArrayList<>();
AppLocation current = node;
while (current != null) {
result.add(current);
current = getParent(current);
}
Collections.reverse(result);
return result;
}
@Nullable
public AppLocation findByUuid(String uuid) {
return mUuidsToLocations.get(uuid);
}
/**
* Returns a list of all AppLocations within a subtree rooted at the given {@link AppLocation}.
*
* @param subroot the AppLocation that will form the root of the subtree
* @return a List of AppLocations in a subtree with the given root
*/
public List<AppLocation> locationsInSubtree(AppLocation subroot) {
List<AppLocation> result = new ArrayList<>();
result.add(subroot);
addChildrenToCollection(result, subroot);
return result;
}
private void addChildrenToCollection(Collection<AppLocation> collection, AppLocation root) {
for (AppLocation child : getChildren(root)) {
collection.add(child);
addChildrenToCollection(collection, child);
}
}
/** Returns the total number of patients in this location and its descendant locations. */
public int getTotalPatientCount(AppLocation location) {
if (location == null) {
return 0;
}
int count = location.patientCount;
for (AppLocation child : getChildren(location)) {
count += getTotalPatientCount(child);
}
return count;
}
@Override
public void registerContentObserver(ContentObserver observer) {
mCursor.registerContentObserver(observer);
}
@Override
public void unregisterContentObserver(ContentObserver observer) {
mCursor.unregisterContentObserver(observer);
}
@Override
public void close() {
mCursor.close();
}
}
| |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright The ZAP development team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.zaproxy.zap.extension.ascan;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.core.scanner.HostProcess;
import org.parosproxy.paros.core.scanner.Scanner;
import org.parosproxy.paros.core.scanner.ScannerListener;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.model.SiteMapEventPublisher;
import org.parosproxy.paros.model.SiteNode;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.ZAP;
import org.zaproxy.zap.eventBus.Event;
import org.zaproxy.zap.eventBus.EventConsumer;
import org.zaproxy.zap.extension.alert.ExtensionAlert;
import org.zaproxy.zap.extension.log4j.ExtensionLog4j;
import org.zaproxy.zap.extension.ruleconfig.ExtensionRuleConfig;
import org.zaproxy.zap.extension.ruleconfig.RuleConfigParam;
import org.zaproxy.zap.view.ScanStatus;
public class AttackModeScanner implements EventConsumer {
private static final String ATTACK_ICON_RESOURCE = "/resource/icon/16/093.png";
private ExtensionActiveScan extension;
private long lastUpdated;
private ScanStatus scanStatus;
private ExtensionAlert extAlert = null;
private AttackModeThread attackModeThread = null;
private boolean rescanOnChange = false;
private Logger log = Logger.getLogger(AttackModeScanner.class);
private List<SiteNode> nodeStack = new ArrayList<SiteNode>();
public AttackModeScanner(ExtensionActiveScan extension) {
this.extension = extension;
ZAP.getEventBus().registerConsumer(this, SiteMapEventPublisher.class.getCanonicalName());
if (extension.getView() != null) {
lastUpdated = System.currentTimeMillis();
scanStatus = new ScanStatus(
new ImageIcon(
ExtensionLog4j.class.getResource("/resource/icon/fugue/target.png")),
Constant.messages.getString("ascan.attack.icon.title"));
}
}
public void start() {
log.debug("Starting");
nodeStack.clear();
this.addAllInScope();
if (attackModeThread != null) {
attackModeThread.shutdown();
}
attackModeThread = new AttackModeThread();
Thread t = new Thread(attackModeThread, "ZAP-AttackMode");
t.setDaemon(true);
t.start();
}
private void addAllInScope() {
if (this.rescanOnChange) {
this.nodeStack.addAll(Model.getSingleton().getSession().getNodesInScopeFromSiteTree());
log.debug("Added existing in scope nodes to attack mode stack " + this.nodeStack.size());
updateCount();
}
}
public void stop() {
log.debug("Stopping");
if (this.attackModeThread != null) {
this.attackModeThread.shutdown();
}
nodeStack.clear();
updateCount();
}
@Override
public void eventReceived(Event event) {
if (this.attackModeThread != null && this.attackModeThread.isRunning()) {
if (event.getEventType().equals(SiteMapEventPublisher.SITE_NODE_ADDED_EVENT) &&
event.getTarget().getStartNode().isIncludedInScope()) {
if (event.getTarget().getStartNode().getHistoryReference().getHistoryType()
!= HistoryReference.TYPE_TEMPORARY) {
// Add to the stack awaiting attack
log.debug("Adding node to attack mode stack " + event.getTarget().getStartNode());
nodeStack.add(event.getTarget().getStartNode());
updateCount();
}
} else if (event.getEventType().equals(SiteMapEventPublisher.SITE_NODE_REMOVED_EVENT)) {
if (nodeStack.contains(event.getTarget().getStartNode())) {
nodeStack.remove(event.getTarget().getStartNode());
}
}
}
}
/**
* Gets the {@link ScanStatus}.
*
* @return the {@code ScanStatus}, or {@code null} if there's no view/UI.
*/
public ScanStatus getScanStatus() {
return scanStatus;
}
public void sessionScopeChanged(Session session) {
this.addAllInScope();
}
public void sessionModeChanged(Mode mode) {
if (mode.equals(Mode.attack)) {
if (View.isInitialised() && extension.getScannerParam().isPromptInAttackMode()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
int res = View.getSingleton().showYesNoRememberDialog(
View.getSingleton().getMainFrame(),
Constant.messages.getString("ascan.attack.prompt"));
if (View.getSingleton().isRememberLastDialogChosen()) {
extension.getScannerParam().setPromptInAttackMode(false);
extension.getScannerParam().setRescanInAttackMode(res == JOptionPane.YES_OPTION);
}
rescanOnChange = (res == JOptionPane.YES_OPTION);
start();
}});
} else {
this.rescanOnChange = extension.getScannerParam().isRescanInAttackMode();
this.start();
}
} else {
this.stop();
}
}
/**
* Updates the count of the {@link #scanStatus scan status}' label.
* <p>
* The call to this method has no effect if the view was not initialised.
*/
private void updateCount() {
if (scanStatus == null) {
return;
}
long now = System.currentTimeMillis();
if (now - this.lastUpdated > 200) {
// Dont update too frequently, eg using the spider could hammer the UI unnecessarily
this.lastUpdated = now;
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
scanStatus.setScanCount(nodeStack.size());
}});
}
}
public int getStackSize() {
int count = nodeStack.size();
if (count > 0) {
// There are nodes to scan
return count;
}
// Work out if any scanning is in progress
if (this.attackModeThread != null && this.attackModeThread.isActive()) {
return 0;
}
return -1;
}
public boolean isRescanOnChange() {
return rescanOnChange;
}
public void setRescanOnChange(boolean rescanOnChange) {
this.rescanOnChange = rescanOnChange;
}
private ExtensionAlert getExtensionAlert() {
if (extAlert == null) {
extAlert = (ExtensionAlert) Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.NAME);
}
return extAlert;
}
private class AttackModeThread implements Runnable, ScannerListener, AttackModeScannerThread {
private int scannerCount = 4;
private List<Scanner> scanners = new ArrayList<Scanner>();
private AttackScan ascanWrapper;
private boolean running = false;
@Override
public void run() {
log.debug("Starting attack thread");
this.running = true;
RuleConfigParam ruleConfigParam = null;
ExtensionRuleConfig extRC =
Control.getSingleton().getExtensionLoader().getExtension(ExtensionRuleConfig.class);
if (extRC != null) {
ruleConfigParam = extRC.getRuleConfigParam();
}
ascanWrapper = new AttackScan(Constant.messages.getString("ascan.attack.scan"), extension.getScannerParam(),
extension.getModel().getOptionsParam().getConnectionParam(),
extension.getPolicyManager().getAttackScanPolicy(), ruleConfigParam, this);
extension.registerScan(ascanWrapper);
while (running) {
if (scanStatus != null && scanStatus.getScanCount() != nodeStack.size()) {
updateCount();
}
if (nodeStack.size() == 0 || scanners.size() == scannerCount) {
if (scanners.size() > 0) {
// Check to see if any have finished
scannerComplete(-1);
}
// Still scanning a node or nothing to scan now
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// Ignore
}
continue;
}
while (nodeStack.size() > 0 && scanners.size() < scannerCount) {
SiteNode node = nodeStack.remove(0);
log.debug("Attacking node " + node.getNodeName());
Scanner scanner = new Scanner(extension.getScannerParam(),
extension.getModel().getOptionsParam().getConnectionParam(),
extension.getPolicyManager().getAttackScanPolicy(),
ruleConfigParam);
scanner.setStartNode(node);
scanner.setScanChildren(false);
scanner.addScannerListener(this);
synchronized (this.scanners) {
this.scanners.add(scanner);
}
if (View.isInitialised()) {
// set icon to show its being scanned
node.addCustomIcon(ATTACK_ICON_RESOURCE, false);
}
scanner.start(node);
}
}
synchronized (this.scanners) {
for (Scanner scanner : this.scanners) {
scanner.stop();
}
}
log.debug("Attack thread finished");
}
@Override
public void scannerComplete(int id) {
// Clear so we can attack the next node
List<Scanner> stoppedScanners = new ArrayList<Scanner>();
synchronized (this.scanners) {
for (Scanner scanner : this.scanners) {
if (scanner.isStop()) {
SiteNode node = scanner.getStartNode();
if (node != null) {
log.debug("Finished attacking node " + node.getNodeName());
if (View.isInitialised()) {
// Remove the icon
node.removeCustomIcon(ATTACK_ICON_RESOURCE);
}
}
stoppedScanners.add(scanner);
}
}
for (Scanner scanner : stoppedScanners) {
// Cant remove them in the above loop
scanners.remove(scanner);
}
}
updateCount();
}
@Override
public void hostNewScan(int id, String hostAndPort, HostProcess hostThread) {
// Ignore
}
@Override
public void hostProgress(int id, String hostAndPort, String msg, int percentage) {
// Ignore
}
@Override
public void hostComplete(int id, String hostAndPort) {
// Ignore
}
@Override
public void alertFound(Alert alert) {
alert.setSource(Alert.Source.ACTIVE);
getExtensionAlert().alertFound(alert, alert.getHistoryRef());
}
@Override
public void notifyNewMessage(HttpMessage msg) {
ascanWrapper.notifyNewMessage(msg);
}
public void shutdown() {
this.running = false;
}
@Override
public boolean isRunning() {
return this.running;
}
/**
* Tells whether or not any of the scan threads are currently active.
* @return {@code true} if there's at least one scan active, {@code false} otherwise
*/
@Override
public boolean isActive() {
synchronized (this.scanners) {
for (Scanner scanner : this.scanners) {
if (! scanner.isStop()) {
return true;
}
}
}
return false;
}
}
interface AttackModeScannerThread {
boolean isRunning();
boolean isActive();
}
}
| |
/*
* Copyright (C) 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.genomics.dataflow.functions;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import Jama.EigenvalueDecomposition;
import Jama.Matrix;
import com.google.api.client.util.Lists;
import com.google.api.client.util.Preconditions;
import com.google.cloud.dataflow.sdk.transforms.DoFn;
import com.google.cloud.dataflow.sdk.values.KV;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableList;
/**
* This function runs a Principal Coordinate Analysis inside of a SeqDo.
* It can not be parallelized.
*
* See http://en.wikipedia.org/wiki/PCoA for more information.
*
* Note that this is not the same as
* Principal Component Analysis (http://en.wikipedia.org/wiki/Principal_component_analysis)
*
* The input data to this algorithm must be for a similarity matrix - and the
* resulting matrix must be symmetric.
*
* Input: KV(KV(dataName, dataName), count of how similar the data pair is)
* Output: GraphResults - an x/y pair and a label
*
* Example input for a tiny dataset of size 2:
*
* KV(KV(data1, data1), 5)
* KV(KV(data1, data2), 2)
* KV(KV(data2, data2), 5)
* KV(KV(data2, data1), 2)
*/
public class PCoAnalysis extends DoFn<Iterable<KV<KV<String, String>, Long>>,
Iterable<PCoAnalysis.GraphResult>> {
public static class GraphResult implements Serializable {
public double graphX;
public double graphY;
public String name;
public GraphResult(String name, double x, double y) {
this.name = name;
this.graphX = Math.floor(x * 100) / 100;
this.graphY = Math.floor(y * 100) / 100;
}
@Override public String toString() {
return String.format("%s\t\t%s\t%s", name, graphX, graphY);
}
public static GraphResult fromString(String tsv) {
Preconditions.checkNotNull(tsv);
String[] tokens = tsv.split("[\\s\t]+");
Preconditions.checkState(3 == tokens.length,
"Expected three values in serialized GraphResult but found %d", tokens.length);
return new GraphResult(tokens[0],
Double.parseDouble(tokens[1]),
Double.parseDouble(tokens[2]));
}
@Override // auto-generated via eclipse
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(graphX);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(graphY);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override // auto-generated via eclipse
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GraphResult other = (GraphResult) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(graphX) != Double.doubleToLongBits(other.graphX))
return false;
if (Double.doubleToLongBits(graphY) != Double.doubleToLongBits(other.graphY))
return false;
return true;
}
}
private BiMap<String, Integer> dataIndices;
public PCoAnalysis(BiMap<String, Integer> dataIndices) {
this.dataIndices = dataIndices;
}
// Convert the similarity matrix to an Eigen matrix.
private List<GraphResult> getPcaData(double[][] data, BiMap<Integer, String> dataNames) {
int rows = data.length;
int cols = data.length;
// Center the similarity matrix.
double matrixSum = 0;
double[] rowSums = new double[rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrixSum += data[i][j];
rowSums[i] += data[i][j];
}
}
double matrixMean = matrixSum / rows / cols;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
double rowMean = rowSums[i] / rows;
double colMean = rowSums[j] / rows;
data[i][j] = data[i][j] - rowMean - colMean + matrixMean;
}
}
// Determine the eigenvectors, and scale them so that their
// sum of squares equals their associated eigenvalue.
Matrix matrix = new Matrix(data);
EigenvalueDecomposition eig = matrix.eig();
Matrix eigenvectors = eig.getV();
double[] realEigenvalues = eig.getRealEigenvalues();
for (int j = 0; j < eigenvectors.getColumnDimension(); j++) {
double sumSquares = 0;
for (int i = 0; i < eigenvectors.getRowDimension(); i++) {
sumSquares += eigenvectors.get(i, j) * eigenvectors.get(i, j);
}
for (int i = 0; i < eigenvectors.getRowDimension(); i++) {
eigenvectors.set(i, j, eigenvectors.get(i,j) * Math.sqrt(realEigenvalues[j] / sumSquares));
}
}
// Find the indices of the top two eigenvalues.
int maxIndex = -1;
int secondIndex = -1;
double maxEigenvalue = 0;
double secondEigenvalue = 0;
for (int i = 0; i < realEigenvalues.length; i++) {
double eigenvector = realEigenvalues[i];
if (eigenvector > maxEigenvalue) {
secondEigenvalue = maxEigenvalue;
secondIndex = maxIndex;
maxEigenvalue = eigenvector;
maxIndex = i;
} else if (eigenvector > secondEigenvalue) {
secondEigenvalue = eigenvector;
secondIndex = i;
}
}
// Return projected data
List<GraphResult> results = Lists.newArrayList();
for (int i = 0; i < rows; i++) {
results.add(new GraphResult(dataNames.get(i),
eigenvectors.get(i, maxIndex), eigenvectors.get(i, secondIndex)));
}
return results;
}
@Override public void processElement(ProcessContext context) {
Collection<KV<KV<String, String>, Long>> element = ImmutableList.copyOf(context.element());
int dataSize = dataIndices.size();
double[][] matrixData = new double[dataSize][dataSize];
for (KV<KV<String, String>, Long> entry : element) {
int d1 = dataIndices.get(entry.getKey().getKey());
int d2 = dataIndices.get(entry.getKey().getValue());
double value = entry.getValue();
matrixData[d1][d2] = value;
if (d1 != d2) {
matrixData[d2][d1] = value;
}
}
context.output(getPcaData(matrixData, dataIndices.inverse()));
}
}
| |
package com.squareup.timessquare.sample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.squareup.timessquare.CalendarCellDecorator;
import com.squareup.timessquare.CalendarPickerView;
import com.squareup.timessquare.CalendarPickerView.SelectionMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Set;
import static android.widget.Toast.LENGTH_SHORT;
public class SampleTimesSquareActivity extends Activity {
private static final String TAG = "SampleTimesSquareActivi";
private CalendarPickerView calendar;
private AlertDialog theDialog;
private CalendarPickerView dialogView;
private final Set<Button> modeButtons = new LinkedHashSet<Button>();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_calendar_picker);
final Calendar nextYear = Calendar.getInstance();
nextYear.add(Calendar.YEAR, 1);
final Calendar lastYear = Calendar.getInstance();
lastYear.add(Calendar.YEAR, -1);
calendar = (CalendarPickerView) findViewById(R.id.calendar_view);
calendar.init(lastYear.getTime(), nextYear.getTime()) //
.inMode(SelectionMode.SINGLE) //
.withSelectedDate(new Date());
initButtonListeners(nextYear, lastYear);
}
private void initButtonListeners(final Calendar nextYear, final Calendar lastYear) {
final Button single = (Button) findViewById(R.id.button_single);
final Button multi = (Button) findViewById(R.id.button_multi);
final Button range = (Button) findViewById(R.id.button_range);
final Button displayOnly = (Button) findViewById(R.id.button_display_only);
final Button dialog = (Button) findViewById(R.id.button_dialog);
final Button customized = (Button) findViewById(R.id.button_customized);
final Button decorator = (Button) findViewById(R.id.button_decorator);
final Button rtl = (Button) findViewById(R.id.button_rtl);
modeButtons.addAll(Arrays.asList(single, multi, range, displayOnly, decorator));
single.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
setButtonsEnabled(single);
calendar.setDecorators(Collections.<CalendarCellDecorator>emptyList());
calendar.init(lastYear.getTime(), nextYear.getTime()) //
.inMode(SelectionMode.SINGLE) //
.withSelectedDate(new Date());
}
});
multi.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
setButtonsEnabled(multi);
Calendar today = Calendar.getInstance();
ArrayList<Date> dates = new ArrayList<Date>();
for (int i = 0; i < 5; i++) {
today.add(Calendar.DAY_OF_MONTH, 3);
dates.add(today.getTime());
}
calendar.setDecorators(Collections.<CalendarCellDecorator>emptyList());
calendar.init(new Date(), nextYear.getTime()) //
.inMode(SelectionMode.MULTIPLE) //
.withSelectedDates(dates);
}
});
range.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
setButtonsEnabled(range);
Calendar today = Calendar.getInstance();
ArrayList<Date> dates = new ArrayList<Date>();
today.add(Calendar.DATE, 3);
dates.add(today.getTime());
today.add(Calendar.DATE, 5);
dates.add(today.getTime());
calendar.setDecorators(Collections.<CalendarCellDecorator>emptyList());
calendar.init(new Date(), nextYear.getTime()) //
.inMode(SelectionMode.RANGE) //
.withSelectedDates(dates);
}
});
displayOnly.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
setButtonsEnabled(displayOnly);
calendar.setDecorators(Collections.<CalendarCellDecorator>emptyList());
calendar.init(new Date(), nextYear.getTime()) //
.inMode(SelectionMode.SINGLE) //
.withSelectedDate(new Date()) //
.displayOnly();
}
});
dialog.setOnClickListener(new OnClickListener() {
@Override public void onClick(View view) {
String title = "I'm a dialog!";
showCalendarInDialog(title, R.layout.dialog);
dialogView.init(lastYear.getTime(), nextYear.getTime()) //
.withSelectedDate(new Date());
}
});
customized.setOnClickListener(new OnClickListener() {
@Override public void onClick(View view) {
showCalendarInDialog("Pimp my calendar!", R.layout.dialog_customized);
dialogView.init(lastYear.getTime(), nextYear.getTime())
.withSelectedDate(new Date());
}
});
decorator.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
setButtonsEnabled(decorator);
calendar.setDecorators(Arrays.<CalendarCellDecorator>asList(new SampleDecorator()));
calendar.init(lastYear.getTime(), nextYear.getTime()) //
.inMode(SelectionMode.SINGLE) //
.withSelectedDate(new Date());
}
});
rtl.setOnClickListener(new OnClickListener() {
@Override public void onClick(View view) {
showCalendarInDialog("I'm right-to-left!", R.layout.dialog);
dialogView.init(lastYear.getTime(), nextYear.getTime(), new Locale("iw", "IL")) //
.withSelectedDate(new Date());
}
});
findViewById(R.id.done_button).setOnClickListener(new OnClickListener() {
@Override public void onClick(View view) {
Log.d(TAG, "Selected time in millis: " + calendar.getSelectedDate().getTime());
String toast = "Selected: " + calendar.getSelectedDate().getTime();
Toast.makeText(SampleTimesSquareActivity.this, toast, LENGTH_SHORT).show();
}
});
}
private void showCalendarInDialog(String title, int layoutResId) {
dialogView = (CalendarPickerView) getLayoutInflater().inflate(layoutResId, null, false);
theDialog = new AlertDialog.Builder(this) //
.setTitle(title)
.setView(dialogView)
.setNeutralButton("Dismiss", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.create();
theDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override public void onShow(DialogInterface dialogInterface) {
Log.d(TAG, "onShow: fix the dimens!");
dialogView.fixDialogDimens();
}
});
theDialog.show();
}
private void setButtonsEnabled(Button currentButton) {
for (Button modeButton : modeButtons) {
modeButton.setEnabled(modeButton != currentButton);
}
}
@Override public void onConfigurationChanged(Configuration newConfig) {
boolean applyFixes = theDialog != null && theDialog.isShowing();
if (applyFixes) {
Log.d(TAG, "Config change: unfix the dimens so I'll get remeasured!");
dialogView.unfixDialogDimens();
}
super.onConfigurationChanged(newConfig);
if (applyFixes) {
dialogView.post(new Runnable() {
@Override public void run() {
Log.d(TAG, "Config change done: re-fix the dimens!");
dialogView.fixDialogDimens();
}
});
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.maven.packaging;
import java.io.File;
import java.nio.file.Path;
import java.util.Collections;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.sonatype.plexus.build.incremental.BuildContext;
import static org.apache.camel.maven.packaging.StringHelper.camelDashToTitle;
/**
* Analyses the Camel plugins in a project and generates extra descriptor information for easier auto-discovery in Camel.
*/
@Mojo(name = "generate-others-list", threadSafe = true)
public class PackageOtherMojo extends AbstractGeneratorMojo {
/**
* The output directory for generated components file
*/
@Parameter(defaultValue = "${project.build.directory}/generated/camel/others")
protected File otherOutDir;
/**
* The output directory for generated languages file
*/
@Parameter(defaultValue = "${project.build.directory}/classes")
protected File schemaOutDir;
/**
* Execute goal.
*
* @throws MojoExecutionException execution of the main class or one of the
* threads it generated failed.
* @throws MojoFailureException something bad happened...
*/
public void execute() throws MojoExecutionException, MojoFailureException {
File f = new File(project.getBasedir(), "target/classes");
File comp = new File(f, "META-INF/services/org/apache/camel/component");
if (comp.exists() && comp.isDirectory()) {
return;
}
File df = new File(f, "META-INF/services/org/apache/camel/dataformat");
if (df.exists() && df.isDirectory()) {
return;
}
File lan = new File(f, "META-INF/services/org/apache/camel/language");
if (lan.exists() && lan.isDirectory()) {
return;
}
prepareOthers(getLog(), project, projectHelper, otherOutDir, schemaOutDir, buildContext);
}
public static void prepareOthers(Log log, MavenProject project, MavenProjectHelper projectHelper, File otherOutDir,
File schemaOutDir, BuildContext buildContext) throws MojoExecutionException {
// first we need to setup the output directory because the next check
// can stop the build before the end and eclipse always needs to know about that directory
if (projectHelper != null) {
projectHelper.addResource(project, otherOutDir.getPath(), Collections.singletonList("**/other.properties"), Collections.emptyList());
}
String name = project.getArtifactId();
// strip leading camel-
if (name.startsWith("camel-")) {
name = name.substring(6);
}
try {
// create json model
OtherModel otherModel = new OtherModel();
otherModel.setName(name);
otherModel.setGroupId(project.getGroupId());
otherModel.setArtifactId(project.getArtifactId());
otherModel.setVersion(project.getVersion());
otherModel.setDescription(project.getDescription());
if (project.getName() != null && project.getName().contains("(deprecated)")) {
otherModel.setDeprecated("true");
} else {
otherModel.setDeprecated("false");
}
otherModel.setFirstVersion(project.getProperties().getProperty("firstVersion"));
otherModel.setLabel(project.getProperties().getProperty("label"));
String title = project.getProperties().getProperty("title");
if (title == null) {
title = camelDashToTitle(name);
}
otherModel.setTitle(title);
if (log.isDebugEnabled()) {
log.debug("Model: " + otherModel);
}
String schema = createJsonSchema(otherModel);
// write this to the directory
Path out = schemaOutDir.toPath()
.resolve(name + ".json");
updateResource(buildContext, out, schema);
if (log.isDebugEnabled()) {
log.debug("Generated " + out + " containing JSon schema for " + name + " other");
}
} catch (Exception e) {
throw new MojoExecutionException("Error loading other model. Reason: " + e, e);
}
// now create properties file
File camelMetaDir = new File(otherOutDir, "META-INF/services/org/apache/camel/");
Path outFile = camelMetaDir.toPath().resolve("other.properties");
String properties = createProperties(project, "name", name);
updateResource(buildContext, outFile, properties);
log.info("Generated " + outFile + " containing 1 Camel other: " + name);
}
private static String createJsonSchema(OtherModel otherModel) {
StringBuilder buffer = new StringBuilder("{");
// language model
buffer.append("\n \"other\": {");
buffer.append("\n \"name\": \"").append(otherModel.getName()).append("\",");
buffer.append("\n \"kind\": \"").append("other").append("\",");
if (otherModel.getTitle() != null) {
buffer.append("\n \"title\": \"").append(otherModel.getTitle()).append("\",");
}
if (otherModel.getDescription() != null) {
buffer.append("\n \"description\": \"").append(otherModel.getDescription()).append("\",");
}
buffer.append("\n \"deprecated\": \"").append(otherModel.getDeprecated()).append("\",");
if (otherModel.getFirstVersion() != null) {
buffer.append("\n \"firstVersion\": \"").append(otherModel.getFirstVersion()).append("\",");
}
if (otherModel.getLabel() != null) {
buffer.append("\n \"label\": \"").append(otherModel.getLabel()).append("\",");
}
buffer.append("\n \"groupId\": \"").append(otherModel.getGroupId()).append("\",");
buffer.append("\n \"artifactId\": \"").append(otherModel.getArtifactId()).append("\",");
buffer.append("\n \"version\": \"").append(otherModel.getVersion()).append("\"");
buffer.append("\n }");
buffer.append("\n}");
return buffer.toString();
}
private static class OtherModel {
private String name;
private String title;
private String description;
private String deprecated;
private String deprecationNote;
private String firstVersion;
private String label;
private String groupId;
private String artifactId;
private String version;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDeprecated() {
return deprecated;
}
public void setDeprecated(String deprecated) {
this.deprecated = deprecated;
}
public String getDeprecationNote() {
return deprecationNote;
}
public void setDeprecationNote(String deprecationNote) {
this.deprecationNote = deprecationNote;
}
public String getFirstVersion() {
return firstVersion;
}
public void setFirstVersion(String firstVersion) {
this.firstVersion = firstVersion;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getArtifactId() {
return artifactId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
@Override
public String toString() {
return "OtherModel["
+ "name='" + name + '\''
+ ", title='" + title + '\''
+ ", description='" + description + '\''
+ ", label='" + label + '\''
+ ", groupId='" + groupId + '\''
+ ", artifactId='" + artifactId + '\''
+ ", version='" + version + '\''
+ ']';
}
}
}
| |
/**
* Copyright (C) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject;
import com.google.inject.internal.ErrorsException;
import com.google.inject.internal.Lists;
import static com.google.inject.matcher.Matchers.annotatedWith;
import static com.google.inject.matcher.Matchers.any;
import static com.google.inject.matcher.Matchers.not;
import static com.google.inject.matcher.Matchers.only;
import com.google.inject.spi.InjectionPoint;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* @author crazybob@google.com (Bob Lee)
*/
public class ProxyFactoryTest extends TestCase {
List<MethodAspect> aspects = Lists.newArrayList();
public void testSimpleCase()
throws NoSuchMethodException, InvocationTargetException, ErrorsException {
SimpleInterceptor interceptor = new SimpleInterceptor();
InjectionPoint injectionPoint = InjectionPoint.forConstructorOf(Simple.class);
aspects.add(new MethodAspect(any(), any(), interceptor));
ProxyFactory<Simple> factory = new ProxyFactory<Simple>(injectionPoint, aspects);
ConstructionProxy<Simple> constructionProxy = factory.create();
Simple simple = constructionProxy.newInstance();
simple.invoke();
assertTrue(simple.invoked);
assertTrue(interceptor.invoked);
}
static class Simple {
boolean invoked = false;
public void invoke() {
invoked = true;
}
}
static class SimpleInterceptor implements MethodInterceptor {
boolean invoked = false;
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
invoked = true;
return methodInvocation.proceed();
}
}
public void testInterceptOneMethod()
throws NoSuchMethodException, InvocationTargetException, ErrorsException {
SimpleInterceptor interceptor = new SimpleInterceptor();
aspects.add(new MethodAspect(only(Bar.class), annotatedWith(Intercept.class), interceptor));
ConstructionProxy<Foo> fooFactory
= new ProxyFactory<Foo>(InjectionPoint.forConstructorOf(Foo.class), aspects).create();
ConstructionProxy<Bar> barFactory
= new ProxyFactory<Bar>(InjectionPoint.forConstructorOf(Bar.class), aspects).create();
Foo foo = fooFactory.newInstance();
Bar bar = barFactory.newInstance();
foo.foo();
assertTrue(foo.fooCalled);
assertFalse(interceptor.invoked);
bar.bar();
assertTrue(bar.barCalled);
assertFalse(interceptor.invoked);
bar.intercepted();
assertTrue(bar.interceptedCalled);
assertTrue(interceptor.invoked);
}
static class Foo {
boolean fooCalled;
@Intercept
void foo() {
fooCalled = true;
}
}
static class Bar {
boolean barCalled;
void bar() {
barCalled = true;
}
boolean interceptedCalled;
@Intercept
void intercepted() {
interceptedCalled = true;
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface Intercept {}
public void testWithConstructorArguments()
throws InvocationTargetException, NoSuchMethodException, ErrorsException {
SimpleInterceptor interceptor = new SimpleInterceptor();
aspects.add(new MethodAspect(any(), any(), interceptor));
ProxyFactory<A> factory
= new ProxyFactory<A>(InjectionPoint.forConstructorOf(A.class), aspects);
ConstructionProxy<A> constructor = factory.create();
A a = constructor.newInstance(5);
a.a();
assertEquals(5, a.i);
}
public void testNotProxied()
throws NoSuchMethodException, InvocationTargetException, ErrorsException {
SimpleInterceptor interceptor = new SimpleInterceptor();
aspects.add(new MethodAspect(not(any()), not(any()), interceptor));
ProxyFactory<A> factory
= new ProxyFactory<A>(InjectionPoint.forConstructorOf(A.class), aspects);
ConstructionProxy<A> constructor = factory.create();
A a = constructor.newInstance(5);
assertEquals(A.class, a.getClass());
}
static class A {
final int i;
@Inject public A(int i) {
this.i = i;
}
public void a() {}
}
public void testMultipleInterceptors()
throws NoSuchMethodException, InvocationTargetException, ErrorsException {
DoubleInterceptor doubleInterceptor = new DoubleInterceptor();
CountingInterceptor countingInterceptor = new CountingInterceptor();
aspects.add(new MethodAspect(any(), any(), doubleInterceptor, countingInterceptor));
ProxyFactory<Counter> factory
= new ProxyFactory<Counter>(InjectionPoint.forConstructorOf(Counter.class), aspects);
ConstructionProxy<Counter> constructor = factory.create();
Counter counter = constructor.newInstance();
counter.inc();
assertEquals(2, counter.count);
assertEquals(2, countingInterceptor.count);
}
static class CountingInterceptor implements MethodInterceptor {
int count;
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
count++;
return methodInvocation.proceed();
}
}
static class DoubleInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
methodInvocation.proceed();
return methodInvocation.proceed();
}
}
static class Counter {
int count;
void inc() {
count++;
}
}
}
| |
/**
* Copyright (C) 2009-2013 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.aws;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.aws.compute.EC2Exception;
import org.dasein.cloud.aws.compute.EC2Method;
import org.dasein.cloud.dc.*;
import org.dasein.cloud.util.APITrace;
import org.dasein.cloud.util.Cache;
import org.dasein.cloud.util.CacheLevel;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
public class RegionsAndZones extends AbstractDataCenterServices<AWSCloud> {
static private final Logger logger = Logger.getLogger(RegionsAndZones.class);
static public final String DESCRIBE_AVAILABILITY_ZONES = "DescribeAvailabilityZones";
static public final String DESCRIBE_REGIONS = "DescribeRegions";
private String oneRegionId;
private String oneZoneId;
RegionsAndZones(AWSCloud provider) {
super(provider);
if( (getProvider().getEC2Provider().isStorage() && "google".equalsIgnoreCase(getProvider().getProviderName())) ) {
oneRegionId = "us";
oneZoneId = "us1";
}
else {
oneRegionId = "region-1";
oneZoneId = "zone-1";
}
}
private transient volatile RegionsAndZonesCapabilities capabilities;
@Nonnull
@Override
public DataCenterCapabilities getCapabilities() throws InternalException, CloudException {
if( capabilities == null ) {
capabilities = new RegionsAndZonesCapabilities(getProvider());
}
return capabilities;
}
private @Nonnull DataCenter getZone() {
DataCenter dc = new DataCenter() ;
dc.setActive(true);
dc.setAvailable(true);
dc.setName(oneZoneId);
dc.setProviderDataCenterId(oneZoneId);
dc.setRegionId(oneRegionId);
return dc;
}
@Override
public @Nullable DataCenter getDataCenter(@Nonnull String zoneId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "DC.getDataCenter");
try {
if( getProvider().getEC2Provider().isStorage() ) {
return (zoneId.equals(oneZoneId) ? getZone() : null);
}
Map<String,String> parameters = getProvider().getStandardParameters(getProvider().getContext(), DESCRIBE_AVAILABILITY_ZONES);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("ZoneName", zoneId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidZone") ) {
return null;
}
if( code != null && code.equals("InvalidParameterValue") ) {
String message = e.getMessage();
if( message != null && message.startsWith("Invalid availability") ) {
return null;
}
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("availabilityZoneInfo");
for( int i=0; i<blocks.getLength(); i++ ) {
NodeList zones = blocks.item(i).getChildNodes();
for( int j=0; j<zones.getLength(); j++ ) {
Node region = zones.item(j);
if( region.getNodeName().equals("item") ) {
DataCenter dc = toDataCenter(null, zones.item(j));
if( dc != null && dc.getProviderDataCenterId().equals(zoneId) ) {
if( dc.getRegionId() == null ) {
for( Region r : listRegions() ) {
for( DataCenter d : listDataCenters(r.getProviderRegionId()) ) {
if( d.getProviderDataCenterId().equals(dc.getProviderDataCenterId()) ) {
dc.setRegionId(r.getProviderRegionId());
break;
}
}
if( dc.getRegionId() != null ) {
break;
}
}
}
return dc;
}
}
}
}
return null;
}
finally {
APITrace.end();
}
}
private @Nonnull Region getRegion() {
Region region = new Region();
region.setActive(true);
region.setAvailable(true);
region.setJurisdiction("US");
region.setName(oneRegionId);
region.setProviderRegionId(oneRegionId);
return region;
}
@Override
public Region getRegion(String regionId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "DC.getRegion");
try {
if( getProvider().getEC2Provider().isStorage() ) {
return (regionId.equals(oneRegionId) ? getRegion() : null);
}
Map<String,String> parameters = getProvider().getStandardParameters(getProvider().getContext(), DESCRIBE_REGIONS);
NodeList blocks, regions;
EC2Method method;
Document doc;
parameters.put("RegionName.1", regionId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidRegion") ) {
return null;
}
if( code != null && code.equals("InvalidParameterValue") ) {
String message = e.getMessage();
if( message != null && message.startsWith("Invalid region") ) {
return null;
}
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("regionInfo");
for( int i=0; i<blocks.getLength(); i++ ) {
regions = blocks.item(i).getChildNodes();
for( int j=0; j<regions.getLength(); j++ ) {
Node region = regions.item(j);
if( region.getNodeName().equals("item") ) {
Region r = toRegion(region);
if( r != null ) {
return r;
}
}
}
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public Collection<DataCenter> listDataCenters(String regionId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "DC.listDataCenters");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was set for this request");
}
Cache<DataCenter> cache = null;
Collection<DataCenter> dataCenters;
String originalRegionId = ctx.getRegionId();
if( regionId.equals(originalRegionId) ) {
cache = Cache.getInstance(getProvider(), "dataCenters", DataCenter.class, CacheLevel.REGION_ACCOUNT);
dataCenters = (Collection<DataCenter>)cache.get(ctx);
if( dataCenters != null ) {
return dataCenters;
}
}
if( getProvider().getEC2Provider().isStorage() ) {
if( regionId.equals(oneRegionId) ) {
return Collections.singletonList(getZone());
}
throw new CloudException("No such region: " + regionId);
}
Map<String,String> parameters = getProvider().getStandardParameters(getProvider().getContext(), DESCRIBE_AVAILABILITY_ZONES);
EC2Method method = new EC2Method(getProvider(), getProvider().getEc2Url(regionId), parameters);
NodeList blocks;
Document doc;
dataCenters = new ArrayList<DataCenter>();
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("availabilityZoneInfo");
for( int i=0; i<blocks.getLength(); i++ ) {
NodeList zones = blocks.item(i).getChildNodes();
for( int j=0; j<zones.getLength(); j++ ) {
Node region = zones.item(j);
if( region.getNodeName().equals("item") ) {
dataCenters.add(toDataCenter(regionId, zones.item(j)));
}
}
}
if( cache != null ) {
cache.put(ctx, dataCenters);
}
return dataCenters;
}
finally {
APITrace.end();
}
}
@Override
public Collection<Region> listRegions() throws InternalException, CloudException {
APITrace.begin(getProvider(), "DC.listRegions");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was set for this request");
}
Cache<Region> cache = Cache.getInstance(getProvider(), "regions", Region.class, CacheLevel.CLOUD_ACCOUNT);
Collection<Region> regions = (Collection<Region>)cache.get(ctx);
if( regions != null ) {
return regions;
}
if( getProvider().getEC2Provider().isStorage() ) {
return Collections.singletonList(getRegion());
}
regions = new ArrayList<Region>();
Map<String,String> parameters = getProvider().getStandardParameters(getProvider().getContext(), DESCRIBE_REGIONS);
EC2Method method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
NodeList blocks, nodes;
Document doc;
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
e.printStackTrace();
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("regionInfo");
for( int i=0; i<blocks.getLength(); i++ ) {
nodes = blocks.item(i).getChildNodes();
for( int j=0; j<nodes.getLength(); j++ ) {
Node region = nodes.item(j);
if( region.getNodeName().equals("item") ) {
Region r = toRegion(nodes.item(j));
if( r.getName().startsWith("eu-central") ) {
// FIXME(stas): ignore new central european regions until we transitioned to v4 signatures
continue;
}
if( getProvider().getEC2Provider().isEucalyptus() ) {
if( r.getProviderRegionId().equalsIgnoreCase("eucalyptus") ) {
regions.add(r);
}
}
else {
regions.add(r);
}
}
}
}
cache.put(ctx, regions);
return regions;
}
finally {
APITrace.end();
}
}
Map<String,String> mapRegions(String url) throws InternalException, CloudException {
APITrace.begin(getProvider(), "DC.mapRegions");
try {
Map<String,String> parameters = getProvider().getStandardParameters(getProvider().getContext(), DESCRIBE_REGIONS);
HashMap<String,String> results = new HashMap<String,String>();
EC2Method method = new EC2Method(getProvider(), url, parameters);
NodeList blocks, regions;
Document doc;
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("regionInfo");
for( int i=0; i<blocks.getLength(); i++ ) {
regions = blocks.item(i).getChildNodes();
for( int j=0; j<regions.getLength(); j++ ) {
Node region = regions.item(j);
if( region.getNodeName().equals("item") ) {
NodeList data = region.getChildNodes();
String name = null, endpoint = null;
for( int k=0; k<data.getLength(); k++ ) {
Node item = data.item(k);
if( item.getNodeName().equals("regionName") ) {
name = item.getFirstChild().getNodeValue();
}
else if( item.getNodeName().equals("regionEndpoint") ) {
endpoint = item.getFirstChild().getNodeValue();
}
}
if( name != null && endpoint != null ) {
logger.debug(name + "=" + endpoint);
results.put(name, endpoint);
}
}
}
}
return results;
}
finally {
APITrace.end();
}
}
public String isRegionEC2VPC(String regionId) throws CloudException, InternalException{
ProviderContext ctx = getProvider().getContext();
Cache<HashMap> cache = Cache.getInstance(getProvider(), "ec2-types", HashMap.class, CacheLevel.CLOUD_ACCOUNT);
Collection<HashMap> region2Ec2Types = (Collection<HashMap>)cache.get(ctx);
HashMap<String, String> platformMap = null;
if(region2Ec2Types == null){
region2Ec2Types = new ArrayList<HashMap>();
Collection<Region> regions = listRegions();
platformMap = new HashMap<String, String>();
for(Region r : regions){
Map<String,String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_ACCOUNT_ATTRIBUTES);
parameters.put("AttributeName.1", "supported-platforms");
EC2Method method = new EC2Method(getProvider(), getProvider().getEc2Url(r.getProviderRegionId()), parameters);
try{
Document doc = method.invoke();
String supportedPlatform = null;
NodeList attributes = doc.getElementsByTagName("attributeValueSet").item(0).getChildNodes();
for(int i=0;i<attributes.getLength();i++){
Node attribute = attributes.item(i);
if(attribute.getNodeType() == Node.TEXT_NODE)continue;
if(attribute.getNodeName().equals("item")){
NodeList data = attribute.getChildNodes();
for(int j=0;j<data.getLength();j++){
Node value = data.item(j);
if(value.getNodeType() == Node.TEXT_NODE)continue;
if(supportedPlatform != null){
supportedPlatform = AWSCloud.PLATFORM_EC2;//For now if it can be either we'll use EC2-Classic
}
else{
supportedPlatform = value.getFirstChild().getNodeValue().trim();
}
platformMap.put(r.getProviderRegionId(), supportedPlatform);
}
}
}
}
catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
}
region2Ec2Types.add(platformMap);
cache.put(ctx, region2Ec2Types);
}
else{
platformMap = region2Ec2Types.iterator().next();
}
return platformMap.get(regionId);
}
private DataCenter toDataCenter(String regionId, Node zone) throws CloudException {
NodeList data = zone.getChildNodes();
DataCenter dc = new DataCenter();
dc.setActive(true);
dc.setAvailable(false);
dc.setRegionId(regionId);
for( int i=0; i<data.getLength(); i++ ) {
Node item = data.item(i);
String name = item.getNodeName();
if( name.equals("zoneName") ) {
String value = item.getFirstChild().getNodeValue().trim();
dc.setName(value);
dc.setProviderDataCenterId(value);
}
else if( name.equals("zoneState") ) {
String value = item.getFirstChild().getNodeValue();
if( !getProvider().getEC2Provider().isAWS() ) {
dc.setAvailable(true);
}
else {
dc.setAvailable(value != null && value.trim().equalsIgnoreCase("available"));
}
}
else if( name.equals("regionName") ) {
if( item.hasChildNodes() ) {
String value = item.getFirstChild().getNodeValue();
if( value != null ) {
dc.setRegionId(value.trim());
}
}
}
}
if( dc.getName() == null ) {
throw new CloudException("Availability zone info is incomplete for " + dc.getProviderDataCenterId() + ".");
}
return dc;
}
private Region toRegion(Node region) throws CloudException {
String name = null, endpoint = null;
NodeList data;
data = region.getChildNodes();
for( int i=0; i<data.getLength(); i++ ) {
Node item = data.item(i);
if( item.getNodeName().equals("regionName") ) {
name = item.getFirstChild().getNodeValue();
}
else if( item.getNodeName().equals("regionEndpoint") ) {
endpoint = item.getFirstChild().getNodeValue();
}
}
if( name == null || endpoint == null ) {
throw new CloudException("Invalid region data.");
}
Region r = new Region();
r.setActive(true);
r.setAvailable(true);
r.setName(name);
r.setProviderRegionId(name);
if( name.startsWith("eu") ) {
r.setJurisdiction("EU");
}
else if( name.startsWith("ap-northeast") ) {
r.setJurisdiction("JP");
}
else if( name.startsWith("ap-southeast") ) {
if( name.equals("ap-southeast-1") ) {
r.setJurisdiction("SG");
}
else {
r.setJurisdiction("AU");
}
}
else if( name.startsWith("sa-east") ) {
r.setJurisdiction("BR");
}
else {
r.setJurisdiction("US");
}
return r;
}
}
| |
/**
* Copyright (C) 2009 GIP RECIA http://www.recia.fr
* @Author (C) 2009 GIP RECIA <contact@recia.fr>
* @Contributor (C) 2009 SOPRA http://www.sopragroup.com/
* @Contributor (C) 2011 Pierre Legay <pierre.legay@recia.fr>
*
* 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.
*/
/*
* 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.myfaces.el;
import org.apache.myfaces.el.ValueBindingImpl.NotVariableReferenceException;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.faces.application.Application;
import javax.faces.component.StateHolder;
import javax.faces.context.FacesContext;
import javax.faces.el.*;
import javax.faces.event.AbortProcessingException;
import javax.faces.validator.ValidatorException;
import javax.servlet.jsp.el.ELException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author Anton Koinov (latest modification by $Author: grantsmith $)
* @version $Revision: 472618 $ $Date: 2006-11-08 21:06:54 +0100 (Mi, 08 Nov 2006) $
*/
public class MethodBindingImpl extends MethodBinding
implements StateHolder
{
static final Log log = LogFactory.getLog(MethodBindingImpl.class);
//~ Instance fields -------------------------------------------------------
ValueBindingImpl _valueBinding;
Class[] _argClasses;
//~ Constructors ----------------------------------------------------------
public MethodBindingImpl(Application application, String reference,
Class[] argClasses)
{
// Note: using ValueBindingImpl, istead of creating a common subclass,
// to share single Expression cache
// Note: we can trim() reference, since string-binding mixed
// expressions are not allowed for MethodBindings
_valueBinding = new ValueBindingImpl(application, reference.trim());
_argClasses = argClasses;
}
//~ Methods ---------------------------------------------------------------
public String getExpressionString()
{
return _valueBinding._expressionString;
}
public Class getType(FacesContext facesContext)
{
if (facesContext == null) {
throw new NullPointerException("facesContext");
}
try
{
Object[] baseAndProperty = resolveToBaseAndProperty(facesContext);
Object base = baseAndProperty[0];
Object property = baseAndProperty[1];
Class returnType = base.getClass().getMethod(property.toString(), _argClasses).getReturnType();
if (returnType.getName().equals("void")) {
// the spec document says: "if type is void return null"
// but the RI returns Void.class, so let's follow the RI
return Void.class;
}
return returnType;
}
catch (ReferenceSyntaxException e)
{
throw e;
}
catch (IndexOutOfBoundsException e)
{
// ArrayIndexOutOfBoundsException also here
throw new PropertyNotFoundException("Expression: "
+ getExpressionString(), e);
}
catch (Exception e)
{
throw new EvaluationException("Cannot get type for expression "
+ getExpressionString(), e);
}
}
public Object invoke(FacesContext facesContext, Object[] args)
throws EvaluationException, MethodNotFoundException
{
if (facesContext == null) {
throw new NullPointerException("facesContext");
}
try
{
Object[] baseAndProperty = resolveToBaseAndProperty(facesContext);
Object base = baseAndProperty[0];
Object property = baseAndProperty[1];
Method m = base.getClass().getMethod(property.toString(), _argClasses);
// Check if the concrete class of this method is accessible and if not
// search for a public interface that declares this method
m = MethodUtils.getAccessibleMethod(m);
if (m == null)
{
throw new MethodNotFoundException(
getExpressionString() + " (not accessible!)");
}
return m.invoke(base, args);
}
catch (ReferenceSyntaxException e)
{
throw e;
}
catch (IndexOutOfBoundsException e)
{
// ArrayIndexOutOfBoundsException also here
throw new PropertyNotFoundException("Expression: "
+ getExpressionString(), e);
}
catch (InvocationTargetException e)
{
Throwable cause = e.getCause();
if (cause != null)
{
if (cause instanceof ValidatorException ||
cause instanceof AbortProcessingException)
{
throw new EvaluationException(cause);
}
else
{
throw new EvaluationException("Exception while invoking expression "
+ getExpressionString(), cause);
}
}
else
{
throw new EvaluationException("Exception while invoking expression "
+ getExpressionString(), e);
}
}
catch (Exception e)
{
throw new EvaluationException("Exception while invoking expression "
+ getExpressionString(), e);
}
}
protected Object[] resolveToBaseAndProperty(FacesContext facesContext)
throws ELException
{
if (facesContext == null)
{
throw new NullPointerException("facesContext");
}
try
{
Object base = _valueBinding.resolveToBaseAndProperty(facesContext);
if (!(base instanceof Object[]))
{
String errorMessage = "Expression not a valid method binding: "
+ getExpressionString();
throw new ReferenceSyntaxException(errorMessage);
}
return (Object[]) base;
}
catch (NotVariableReferenceException e)
{
throw new ReferenceSyntaxException("Expression: "
+ getExpressionString(), e);
}
}
public String toString()
{
return _valueBinding.toString();
}
//~ StateHolder implementation --------------------------------------------
private boolean _transient = false;
/**
* Empty constructor, so that new instances can be created when restoring
* state.
*/
public MethodBindingImpl()
{
_valueBinding = null;
_argClasses = null;
}
public Object saveState(FacesContext facescontext)
{
return new Object[] { _valueBinding.saveState(facescontext),
_argClasses};
}
public void restoreState(FacesContext facescontext, Object obj)
{
Object[] ar = (Object[]) obj;
_valueBinding = new ValueBindingImpl();
_valueBinding.restoreState(facescontext, ar[0]);
_argClasses = (Class[]) ar[1];
}
public boolean isTransient()
{
return _transient;
}
public void setTransient(boolean flag)
{
_transient = flag;
}
}
| |
package ie.ucd.clops.dsl;
import ie.ucd.clops.dsl.errors.DSLParseResult;
import ie.ucd.clops.dsl.errors.DuplicateOptionIdentifier;
import ie.ucd.clops.dsl.errors.MissingPropertyError;
import ie.ucd.clops.dsl.errors.PropertyValueError;
import ie.ucd.clops.dsl.errors.UnknownIdentifierError;
import ie.ucd.clops.dsl.errors.UnusedIdentifierWarning;
import ie.ucd.clops.dsl.structs.DSLInformation;
import ie.ucd.clops.dsl.structs.OptionDescription;
import ie.ucd.clops.dsl.structs.OptionGroupDescription;
import ie.ucd.clops.runtime.automaton.Token;
import ie.ucd.clops.runtime.automaton.Tokenizer;
import ie.ucd.clops.runtime.options.IEnumOption;
import ie.ucd.clops.runtime.options.IMatchString;
import ie.ucd.clops.runtime.options.IMatchable;
import ie.ucd.clops.runtime.options.Option;
import ie.ucd.clops.runtime.options.exception.InvalidOptionPropertyValueException;
import ie.ucd.clops.util.Pair;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class StaticChecker {
private DSLInformation dslInfo;
public StaticChecker(DSLInformation dslInfo) {
this.dslInfo = dslInfo;
}
public DSLParseResult runAllChecks() {
DSLParseResult errors = new DSLParseResult();
errors.addAll(checkForDuplicateIdentifierUse());
errors.addAll(checkForUnusedOptionsOrGroups());
errors.addAll(checkProperties());
return errors;
}
public DSLParseResult checkForDuplicateIdentifierUse() {
DSLParseResult result = new DSLParseResult();
//Duplicates within option identifiers or option group identifiers
//are already checked as we parse
//So just check if we have overlaps between options and groups
for (OptionDescription option : dslInfo.getOptionDescriptions()) {
OptionGroupDescription other = dslInfo.getOptionGroupNameMap().get(option.getIdentifier());
if (other != null) {
result.addError(new DuplicateOptionIdentifier(other.getSourceLocation(), option.getIdentifier(), option.getSourceLocation()));
}
}
return result;
}
public DSLParseResult checkForUnusedOptionsOrGroups() {
DSLParseResult result = new DSLParseResult();
String formatString = dslInfo.getFormatString();
Set<String> identifiersUsedInFormatString = getUsedIdentifiers(formatString);
Set<String> allUsedIdentifiers = expandUsedIdentifiers(identifiersUsedInFormatString);
Set<String> allIdentifiers = dslInfo.getOptionAndGroupNameMap().keySet();
Set<String> missingIdentifiers = new HashSet<String>(allUsedIdentifiers);
missingIdentifiers.removeAll(allIdentifiers);
for (String missing : missingIdentifiers) {
//TODO more specific source locations for format string!
if (!missing.equals("AllOptions")) {
result.addError(new UnknownIdentifierError(dslInfo.getFormatSourceLocation(), missing));
}
}
Set<String> unusedIdentifiers = new HashSet<String>(allIdentifiers);
unusedIdentifiers.removeAll(allUsedIdentifiers);
for (String unused : unusedIdentifiers) {
OptionDescription unusedOption = dslInfo.getOptionNameMap().get(unused);
if (unusedOption != null && !virtualOption(unusedOption)) {
result.addWarning(new UnusedIdentifierWarning(dslInfo.getFormatSourceLocation(), dslInfo.getOptionNameMap().containsKey(unused), unused));
}
}
return result;
}
private static boolean virtualOption(OptionDescription option) {
for (Pair<String,String> property : option.getProperties()) {
if (property.getFirst().equalsIgnoreCase("virtual") && property.getSecond().equalsIgnoreCase("true")) {
return true;
}
}
return false;
}
private Set<String> expandUsedIdentifiers(Set<String> usedInFormat) {
Set<String> toVisit = new HashSet<String>(usedInFormat);
Set<String> visited = new HashSet<String>();
while (!toVisit.isEmpty()) {
toVisit.removeAll(visited);
for (String newId : new HashSet<String>(toVisit)) {
visited.add(newId);
toVisit.remove(newId);
if (newId.equals("AllOptions")) {
toVisit.addAll(dslInfo.getOptionNameMap().keySet());
} else {
OptionGroupDescription group = dslInfo.getOptionGroupNameMap().get(newId);
if (group != null) {
Set<String> children = new HashSet<String>(group.getChildren());
children.removeAll(visited);
toVisit.addAll(children);
}
}
}
}
return visited;
}
private static Set<String> getUsedIdentifiers(String formatString) {
Tokenizer tokenizer = new Tokenizer();
List<Token<IMatchable>> tokens = tokenizer.tokenize(formatString, new IMatchString() {
public IMatchable getMatchable(String param) {
return new FakeIMatchable(param);
}
});
Set<String> usedIdentifiers = new HashSet<String>();
for (Token<IMatchable> token : tokens) {
if (token.match != null) {
usedIdentifiers.add(token.match.getIdentifier());
}
}
return usedIdentifiers;
}
private static class FakeIMatchable implements IMatchable {
private final String id;
public FakeIMatchable(String id) {
this.id = id;
}
@Override
public String getIdentifier() {
return id;
}
@Override
public Set<Option<?>> getAllOptions() {
return null;
}
@Override
public Option<?> getMatchingOption(String argumentString, int index) {
return null;
}
@Override
public boolean hasAtLeastOneOptionWithValue() {
return false;
}
}
public DSLParseResult checkProperties() {
DSLParseResult result = new DSLParseResult();
for (OptionDescription option : dslInfo.getOptionDescriptions()) {
try {
String typeClass = option.getType().getOptionTypeClass();
Class<?> opClass = Class.forName(typeClass);
Constructor<?>[] constructors = opClass.getConstructors();
if (constructors.length > 0) {
Constructor<?> constructor = constructors[0];
Class<?>[] params = constructor.getParameterTypes();
if (params.length == 2 && params[0] == String.class && params[1] == String.class) {
Object[] args = { option.getIdentifier(), OptionType.unifyRegexps(option.getPrefixRegexps()) };
Object instance = constructor.newInstance(args);
if (instance instanceof Option<?>) {
Option<?> optionInstance = (Option<?>)instance;
boolean hasChoices = false;
for (Pair<String,String> property : option.getProperties()) {
try {
optionInstance.setProperty(property.getFirst(), property.getSecond());
} catch (InvalidOptionPropertyValueException e) {
result.addError(new PropertyValueError(dslInfo.getPropertyValueLocation(property), property.getFirst(), option.getIdentifier(), e.getMessage()));
}
hasChoices |= "choices".equals(property.getFirst());
}
if (optionInstance instanceof IEnumOption && !hasChoices) {
result.addError(new MissingPropertyError(option.getSourceLocation(), option.getIdentifier(), "choices"));
}
}
}
}
} catch (ClassNotFoundException cnfe) {
//TODO not on classpath error
} catch (IllegalArgumentException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return result;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.connectors.kinesis.table;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.data.TimestampData;
import org.apache.flink.table.factories.TableOptionsBuilder;
import org.apache.flink.table.factories.TestFormatFactory;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.util.TestLogger;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import static org.apache.flink.core.testutils.FlinkMatchers.containsCause;
import static org.apache.flink.streaming.connectors.kinesis.table.RowDataFieldsKinesisPartitioner.MAX_PARTITION_KEY_LENGTH;
import static org.apache.flink.table.utils.EncodingUtils.repeat;
import static org.junit.Assert.assertEquals;
/** Test for {@link RowDataFieldsKinesisPartitioner}. */
public class RowDataFieldsKinesisPartitionerTest extends TestLogger {
/** Table name to use for the tests. */
private static final String TABLE_NAME = "click_stream";
/** Row type to use for the tests. */
private static final RowType ROW_TYPE =
(RowType)
DataTypes.ROW(
DataTypes.FIELD("time", DataTypes.TIMESTAMP(3)),
DataTypes.FIELD("ip", DataTypes.VARCHAR(16)),
DataTypes.FIELD("route", DataTypes.STRING()),
DataTypes.FIELD("date", DataTypes.STRING()),
DataTypes.FIELD("year", DataTypes.STRING()),
DataTypes.FIELD("month", DataTypes.STRING()),
DataTypes.FIELD("day", DataTypes.STRING()))
.getLogicalType();
/** A list of field delimiters to use in the tests. */
private static final List<String> FIELD_DELIMITERS = Arrays.asList("", "|", ",", "--");
/** A {@code PARTITION BY(date, ip)} clause to use for the positive tests. */
private static final List<String> PARTITION_BY_DATE_AND_IP = Arrays.asList("date", "ip");
/** A {@code PARTITION BY(year, month, day)} clause to use for the positive tests. */
private static final List<String> PARTITION_BY_DATE = Arrays.asList("year", "month", "day");
/** A {@code PARTITION BY(route)} clause to use for the positive tests. */
private static final List<String> PARTITION_BY_ROUTE = Collections.singletonList("route");
/**
* Some not-so-random {@link LocalDateTime} instances to use for sample {@link RowData} elements
* in the tests.
*/
private static final List<LocalDateTime> DATE_TIMES =
Arrays.asList(
LocalDateTime.of(2014, 10, 22, 12, 0),
LocalDateTime.of(2015, 11, 13, 10, 0),
LocalDateTime.of(2015, 12, 14, 14, 0),
LocalDateTime.of(2018, 10, 31, 15, 0));
/** A default IP to use for sample {@link RowData} elements in the tests. */
private static final String IP = "255.255.255.255";
@Rule public ExpectedException thrown = ExpectedException.none();
// --------------------------------------------------------------------------------------------
// Positive tests
// --------------------------------------------------------------------------------------------
@Test
public void testGoodPartitioner() {
for (String delimiter : FIELD_DELIMITERS) {
RowDataFieldsKinesisPartitioner partitioner =
new RowDataFieldsKinesisPartitioner(
ROW_TYPE, PARTITION_BY_DATE_AND_IP, delimiter);
for (LocalDateTime time : DATE_TIMES) {
String expectedKey = String.join(delimiter, String.valueOf(days(time)), IP);
String actualKey = partitioner.getPartitionId(createElement(time, IP));
assertEquals(expectedKey, actualKey);
}
}
}
@Test
public void testGoodPartitionerExceedingMaxLength() {
RowDataFieldsKinesisPartitioner partitioner =
new RowDataFieldsKinesisPartitioner(ROW_TYPE, PARTITION_BY_ROUTE);
String ip = "255.255.255.255";
String route = "http://www.very-" + repeat("long-", 50) + "address.com/home";
String expectedKey = route.substring(0, MAX_PARTITION_KEY_LENGTH);
for (LocalDateTime time : DATE_TIMES) {
String actualKey = partitioner.getPartitionId(createElement(time, ip, route));
assertEquals(expectedKey, actualKey);
}
}
@Test
public void testGoodPartitionerWithStaticPrefix() {
// fixed prefix
String year = String.valueOf(year(DATE_TIMES.get(0)));
String month = String.valueOf(monthOfYear(DATE_TIMES.get(0)));
for (String delimiter : FIELD_DELIMITERS) {
RowDataFieldsKinesisPartitioner partitioner =
new RowDataFieldsKinesisPartitioner(ROW_TYPE, PARTITION_BY_DATE, delimiter);
partitioner.setStaticFields(
new HashMap<String, String>() {
{
put("year", year);
put("month", month);
}
});
for (LocalDateTime time : DATE_TIMES) {
String day = String.valueOf(dayOfMonth(time));
String expectedKey = String.join(delimiter, year, month, day);
String actualKey = partitioner.getPartitionId(createElement(time, IP));
assertEquals(expectedKey, actualKey);
}
}
}
@Test
public void testGoodPartitionerWithStaticSuffix() {
// fixed suffix
String month = String.valueOf(monthOfYear(DATE_TIMES.get(0)));
String day = String.valueOf(dayOfMonth(DATE_TIMES.get(0)));
for (String delimiter : FIELD_DELIMITERS) {
RowDataFieldsKinesisPartitioner partitioner =
new RowDataFieldsKinesisPartitioner(ROW_TYPE, PARTITION_BY_DATE, delimiter);
partitioner.setStaticFields(
new HashMap<String, String>() {
{
put("month", month);
put("day", day);
}
});
for (LocalDateTime time : DATE_TIMES) {
String year = String.valueOf(year(time));
String expectedKey = String.join(delimiter, year, month, day);
String actualKey = partitioner.getPartitionId(createElement(time, IP));
assertEquals(expectedKey, actualKey);
}
}
}
@Test
public void testGoodPartitionerWithStaticInfix() {
// fixed infix
String month = String.valueOf(monthOfYear(DATE_TIMES.get(0)));
for (String delimiter : FIELD_DELIMITERS) {
RowDataFieldsKinesisPartitioner partitioner =
new RowDataFieldsKinesisPartitioner(ROW_TYPE, PARTITION_BY_DATE, delimiter);
partitioner.setStaticFields(
new HashMap<String, String>() {
{
put("month", month);
}
});
for (LocalDateTime time : DATE_TIMES) {
String year = String.valueOf(year(time));
String day = String.valueOf(dayOfMonth(time));
String expectedKey = String.join(delimiter, year, month, day);
String actualKey = partitioner.getPartitionId(createElement(time, IP));
assertEquals(expectedKey, actualKey);
}
}
}
// --------------------------------------------------------------------------------------------
// Negative tests
// --------------------------------------------------------------------------------------------
@Test
public void testBadPartitionerWithEmptyPrefix() {
thrown.expect(IllegalArgumentException.class);
thrown.expect(
containsCause(
new IllegalArgumentException(
"Cannot create a RowDataFieldsKinesisPartitioner for a non-partitioned table")));
new RowDataFieldsKinesisPartitioner(ROW_TYPE, Collections.emptyList());
}
@Test
public void testBadPartitionerWithDuplicatePartitionKeys() {
thrown.expect(IllegalArgumentException.class);
thrown.expect(
containsCause(
new IllegalArgumentException(
"The sequence of partition keys cannot contain duplicates")));
new RowDataFieldsKinesisPartitioner(ROW_TYPE, Arrays.asList("ip", "ip"));
}
@Test
public void testBadPartitionerWithBadFieldFieldNames() {
thrown.expect(IllegalArgumentException.class);
thrown.expect(
containsCause(
new IllegalArgumentException(
"The following partition keys are not present in the table: abc")));
new RowDataFieldsKinesisPartitioner(ROW_TYPE, Arrays.asList("ip", "abc"));
}
@Test
public void testBadPartitionerWithBadFieldFieldTypes() {
thrown.expect(IllegalArgumentException.class);
thrown.expect(
containsCause(
new IllegalArgumentException(
"The following partition keys have types that are not supported by Kinesis: time")));
new RowDataFieldsKinesisPartitioner(ROW_TYPE, Arrays.asList("time", "ip"));
}
// --------------------------------------------------------------------------------------------
// Utilities
// --------------------------------------------------------------------------------------------
private RowData createElement(LocalDateTime time, String ip) {
return createElement(time, ip, "https://flink.apache.org/home");
}
private RowData createElement(LocalDateTime time, String ip, String route) {
GenericRowData element = new GenericRowData(ROW_TYPE.getFieldCount());
element.setField(0, TimestampData.fromLocalDateTime(time));
element.setField(1, StringData.fromString(ip));
element.setField(2, StringData.fromString(route));
element.setField(3, StringData.fromString(String.valueOf(days(time))));
element.setField(4, StringData.fromString(String.valueOf(year(time))));
element.setField(5, StringData.fromString(String.valueOf(monthOfYear(time))));
element.setField(6, StringData.fromString(String.valueOf(dayOfMonth(time))));
return element;
}
private int days(LocalDateTime time) {
return (int) ChronoUnit.DAYS.between(LocalDate.ofEpochDay(0), time);
}
private int year(LocalDateTime time) {
return time.get(ChronoField.YEAR);
}
private int monthOfYear(LocalDateTime time) {
return time.get(ChronoField.MONTH_OF_YEAR);
}
private int dayOfMonth(LocalDateTime time) {
return time.get(ChronoField.DAY_OF_MONTH);
}
private TableOptionsBuilder defaultTableOptions() {
String connector = KinesisDynamicTableFactory.IDENTIFIER;
String format = TestFormatFactory.IDENTIFIER;
return new TableOptionsBuilder(connector, format)
// default table options
.withTableOption(KinesisConnectorOptions.STREAM, TABLE_NAME)
.withTableOption("properties.aws.region", "us-west-2")
// default format options
.withFormatOption(TestFormatFactory.DELIMITER, ",");
}
}
| |
/*
* Copyright (C) 2014 Mukesh Y 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.examples.android.calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* @author Mukesh Y
*/
public class CalendarAdapter extends BaseAdapter {
private Context mContext;
private java.util.Calendar month;
public GregorianCalendar pmonth; // calendar instance for previous month
/**
* calendar instance for previous month for getting complete view
*/
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int lastWeekDay;
int leftDays;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;
private ArrayList<String> items;
public static List<String> dayString;
private View previousView;
public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {
CalendarAdapter.dayString = new ArrayList<String>();
Locale.setDefault(Locale.US);
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
mContext = c;
month.set(GregorianCalendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public void setItems(ArrayList<String> items) {
for (int i = 0; i != items.size(); i++) {
if (items.get(i).length() == 1) {
items.set(i, "0" + items.get(i));
}
}
this.items = items;
}
public int getCount() {
return dayString.size();
}
public Object getItem(int position) {
return dayString.get(position);
}
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);
}
dayView = (TextView) v.findViewById(R.id.date);
// separates daystring into parts.
String[] separatedTime = dayString.get(position).split("-");
// taking last part of date. ie; 2 from 2012-12-02
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
// checking whether the day is in current month or not.
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
// setting offdays to white color.
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.BLUE);
}
if (dayString.get(position).equals(curentDateString)) {
setSelected(v);
previousView = v;
} else {
v.setBackgroundResource(R.drawable.list_item_background);
}
dayView.setText(gridvalue);
// create date string for comparison
String date = dayString.get(position);
if (date.length() == 1) {
date = "0" + date;
}
String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
if (monthStr.length() == 1) {
monthStr = "0" + monthStr;
}
// show icon if date is not empty and it exists in the items array
ImageView iw = (ImageView) v.findViewById(R.id.date_icon);
if (date.length() > 0 && items != null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
} else {
iw.setVisibility(View.INVISIBLE);
}
return v;
}
public View setSelected(View view) {
if (previousView != null) {
previousView.setBackgroundResource(R.drawable.list_item_background);
}
previousView = view;
view.setBackgroundResource(R.drawable.calendar_cel_selectl);
return view;
}
public void refreshDays() {
// clear items
items.clear();
dayString.clear();
Locale.setDefault(Locale.US);
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
/**
* Calendar instance for getting a complete gridview including the three
* month's (previous,current,next) dates.
*/
pmonthmaxset = (GregorianCalendar) pmonth.clone();
/**
* setting the start date as previous month's required date.
*/
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
/**
* filling calendar gridview.
*/
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(GregorianCalendar.DATE, 1);
dayString.add(itemvalue);
}
}
private int getMaxP() {
int maxP;
if (month.get(GregorianCalendar.MONTH) == month
.getActualMinimum(GregorianCalendar.MONTH)) {
pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
pmonth.set(GregorianCalendar.MONTH,
month.get(GregorianCalendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
return maxP;
}
}
| |
/**
* 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.openejb.jee.jpa;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
*
*
* The entity-mappings element is the root element of an mapping
* file. It contains the following four types of elements:
*
* 1. The persistence-unit-metadata element contains metadata
* for the entire persistence unit. It is undefined if this element
* occurs in multiple mapping files within the same persistence unit.
*
* 2. The package, schema, catalog and access elements apply to all of
* the entity, mapped-superclass and embeddable elements defined in
* the same file in which they occur.
*
* 3. The sequence-generator, table-generator, named-query,
* named-native-query and sql-result-set-mapping elements are global
* to the persistence unit. It is undefined to have more than one
* sequence-generator or table-generator of the same name in the same
* or different mapping files in a persistence unit. It is also
* undefined to have more than one named-query or named-native-query
* of the same name in the same or different mapping files in a
* persistence unit.
*
* 4. The entity, mapped-superclass and embeddable elements each define
* the mapping information for a managed persistent class. The mapping
* information contained in these elements may be complete or it may
* be partial.
*
*
*
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="persistence-unit-metadata" type="{http://java.sun.com/xml/ns/persistence/orm}persistence-unit-metadata" minOccurs="0"/>
* <element name="package" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="schema" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="catalog" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="access" type="{http://java.sun.com/xml/ns/persistence/orm}access-type" minOccurs="0"/>
* <element name="sequence-generator" type="{http://java.sun.com/xml/ns/persistence/orm}sequence-generator" maxOccurs="unbounded" minOccurs="0"/>
* <element name="table-generator" type="{http://java.sun.com/xml/ns/persistence/orm}table-generator" maxOccurs="unbounded" minOccurs="0"/>
* <element name="named-query" type="{http://java.sun.com/xml/ns/persistence/orm}named-query" maxOccurs="unbounded" minOccurs="0"/>
* <element name="named-native-query" type="{http://java.sun.com/xml/ns/persistence/orm}named-native-query" maxOccurs="unbounded" minOccurs="0"/>
* <element name="sql-result-set-mapping" type="{http://java.sun.com/xml/ns/persistence/orm}sql-result-set-mapping" maxOccurs="unbounded" minOccurs="0"/>
* <element name="mapped-superclass" type="{http://java.sun.com/xml/ns/persistence/orm}mapped-superclass" maxOccurs="unbounded" minOccurs="0"/>
* <element name="entity" type="{http://java.sun.com/xml/ns/persistence/orm}entity" maxOccurs="unbounded" minOccurs="0"/>
* <element name="embeddable" type="{http://java.sun.com/xml/ns/persistence/orm}embeddable" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="version" use="required" type="{http://java.sun.com/xml/ns/persistence/orm}versionType" fixed="1.0" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"description",
"persistenceUnitMetadata",
"_package",
"schema",
"catalog",
"access",
"sequenceGenerator",
"tableGenerator",
"namedQuery",
"namedNativeQuery",
"sqlResultSetMapping",
"mappedSuperclass",
"entity",
"embeddable"
})
@XmlRootElement(name = "entity-mappings")
public class EntityMappings {
protected String description;
@XmlElement(name = "persistence-unit-metadata")
protected PersistenceUnitMetadata persistenceUnitMetadata;
@XmlElement(name = "package")
protected String _package;
protected String schema;
protected String catalog;
protected AccessType access;
@XmlElement(name = "sequence-generator")
protected List<SequenceGenerator> sequenceGenerator;
@XmlElement(name = "table-generator")
protected List<TableGenerator> tableGenerator;
@XmlElement(name = "named-query")
protected List<NamedQuery> namedQuery;
@XmlElement(name = "named-native-query")
protected List<NamedNativeQuery> namedNativeQuery;
@XmlElement(name = "sql-result-set-mapping")
protected List<SqlResultSetMapping> sqlResultSetMapping;
@XmlElement(name = "mapped-superclass")
protected List<MappedSuperclass> mappedSuperclass;
protected List<Entity> entity;
protected List<Embeddable> embeddable;
@XmlAttribute(required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String version = "1.0";
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the persistenceUnitMetadata property.
*
* @return
* possible object is
* {@link PersistenceUnitMetadata }
*
*/
public PersistenceUnitMetadata getPersistenceUnitMetadata() {
return persistenceUnitMetadata;
}
/**
* Sets the value of the persistenceUnitMetadata property.
*
* @param value
* allowed object is
* {@link PersistenceUnitMetadata }
*
*/
public void setPersistenceUnitMetadata(PersistenceUnitMetadata value) {
this.persistenceUnitMetadata = value;
}
/**
* Gets the value of the package property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPackage() {
return _package;
}
/**
* Sets the value of the package property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPackage(String value) {
this._package = value;
}
/**
* Gets the value of the schema property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSchema() {
return schema;
}
/**
* Sets the value of the schema property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSchema(String value) {
this.schema = value;
}
/**
* Gets the value of the catalog property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCatalog() {
return catalog;
}
/**
* Sets the value of the catalog property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCatalog(String value) {
this.catalog = value;
}
/**
* Gets the value of the access property.
*
* @return
* possible object is
* {@link AccessType }
*
*/
public AccessType getAccess() {
return access;
}
/**
* Sets the value of the access property.
*
* @param value
* allowed object is
* {@link AccessType }
*
*/
public void setAccess(AccessType value) {
this.access = value;
}
/**
* Gets the value of the sequenceGenerator 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 sequenceGenerator property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSequenceGenerator().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SequenceGenerator }
*
*
*/
public List<SequenceGenerator> getSequenceGenerator() {
if (sequenceGenerator == null) {
sequenceGenerator = new ArrayList<SequenceGenerator>();
}
return this.sequenceGenerator;
}
/**
* Gets the value of the tableGenerator 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 tableGenerator property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTableGenerator().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TableGenerator }
*
*
*/
public List<TableGenerator> getTableGenerator() {
if (tableGenerator == null) {
tableGenerator = new ArrayList<TableGenerator>();
}
return this.tableGenerator;
}
/**
* Gets the value of the namedQuery 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 namedQuery property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNamedQuery().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link NamedQuery }
*
*
*/
public List<NamedQuery> getNamedQuery() {
if (namedQuery == null) {
namedQuery = new ArrayList<NamedQuery>();
}
return this.namedQuery;
}
/**
* Gets the value of the namedNativeQuery 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 namedNativeQuery property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNamedNativeQuery().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link NamedNativeQuery }
*
*
*/
public List<NamedNativeQuery> getNamedNativeQuery() {
if (namedNativeQuery == null) {
namedNativeQuery = new ArrayList<NamedNativeQuery>();
}
return this.namedNativeQuery;
}
/**
* Gets the value of the sqlResultSetMapping 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 sqlResultSetMapping property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSqlResultSetMapping().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SqlResultSetMapping }
*
*
*/
public List<SqlResultSetMapping> getSqlResultSetMapping() {
if (sqlResultSetMapping == null) {
sqlResultSetMapping = new ArrayList<SqlResultSetMapping>();
}
return this.sqlResultSetMapping;
}
/**
* Gets the value of the mappedSuperclass 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 mappedSuperclass property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getMappedSuperclass().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link MappedSuperclass }
*
*
*/
public List<MappedSuperclass> getMappedSuperclass() {
if (mappedSuperclass == null) {
mappedSuperclass = new ArrayList<MappedSuperclass>();
}
return this.mappedSuperclass;
}
/**
* Gets the value of the entity 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 entity property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEntity().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Entity }
*
*
*/
public List<Entity> getEntity() {
if (entity == null) {
entity = new ArrayList<Entity>();
}
return this.entity;
}
/**
* Gets the value of the embeddable 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 embeddable property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEmbeddable().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Embeddable }
*
*
*/
public List<Embeddable> getEmbeddable() {
if (embeddable == null) {
embeddable = new ArrayList<Embeddable>();
}
return this.embeddable;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
if (version == null) {
return "1.0";
} else {
return version;
}
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
| |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cognitoidentity.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* The result of a successful ListIdentityPools action.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-identity-2014-06-30/ListIdentityPools" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListIdentityPoolsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The identity pools returned by the ListIdentityPools action.
* </p>
*/
private java.util.List<IdentityPoolShortDescription> identityPools;
/**
* <p>
* A pagination token.
* </p>
*/
private String nextToken;
/**
* <p>
* The identity pools returned by the ListIdentityPools action.
* </p>
*
* @return The identity pools returned by the ListIdentityPools action.
*/
public java.util.List<IdentityPoolShortDescription> getIdentityPools() {
return identityPools;
}
/**
* <p>
* The identity pools returned by the ListIdentityPools action.
* </p>
*
* @param identityPools
* The identity pools returned by the ListIdentityPools action.
*/
public void setIdentityPools(java.util.Collection<IdentityPoolShortDescription> identityPools) {
if (identityPools == null) {
this.identityPools = null;
return;
}
this.identityPools = new java.util.ArrayList<IdentityPoolShortDescription>(identityPools);
}
/**
* <p>
* The identity pools returned by the ListIdentityPools action.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setIdentityPools(java.util.Collection)} or {@link #withIdentityPools(java.util.Collection)} if you want
* to override the existing values.
* </p>
*
* @param identityPools
* The identity pools returned by the ListIdentityPools action.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListIdentityPoolsResult withIdentityPools(IdentityPoolShortDescription... identityPools) {
if (this.identityPools == null) {
setIdentityPools(new java.util.ArrayList<IdentityPoolShortDescription>(identityPools.length));
}
for (IdentityPoolShortDescription ele : identityPools) {
this.identityPools.add(ele);
}
return this;
}
/**
* <p>
* The identity pools returned by the ListIdentityPools action.
* </p>
*
* @param identityPools
* The identity pools returned by the ListIdentityPools action.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListIdentityPoolsResult withIdentityPools(java.util.Collection<IdentityPoolShortDescription> identityPools) {
setIdentityPools(identityPools);
return this;
}
/**
* <p>
* A pagination token.
* </p>
*
* @param nextToken
* A pagination token.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* A pagination token.
* </p>
*
* @return A pagination token.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* A pagination token.
* </p>
*
* @param nextToken
* A pagination token.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListIdentityPoolsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getIdentityPools() != null)
sb.append("IdentityPools: ").append(getIdentityPools()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListIdentityPoolsResult == false)
return false;
ListIdentityPoolsResult other = (ListIdentityPoolsResult) obj;
if (other.getIdentityPools() == null ^ this.getIdentityPools() == null)
return false;
if (other.getIdentityPools() != null && other.getIdentityPools().equals(this.getIdentityPools()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getIdentityPools() == null) ? 0 : getIdentityPools().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ListIdentityPoolsResult clone() {
try {
return (ListIdentityPoolsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/*
* 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.raptor.storage;
import com.facebook.presto.orc.OrcAggregatedMemoryContext;
import com.facebook.presto.orc.OrcBatchRecordReader;
import com.facebook.presto.orc.OrcDataSource;
import com.facebook.presto.raptor.storage.DeltaShardLoader.RowsToKeepResult;
import com.facebook.presto.spi.ConnectorPageSource;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.LazyBlock;
import com.facebook.presto.spi.block.LazyBlockLoader;
import com.facebook.presto.spi.block.RunLengthEncodedBlock;
import com.facebook.presto.spi.type.Type;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.util.List;
import java.util.OptionalInt;
import java.util.UUID;
import static com.facebook.presto.orc.OrcReader.MAX_BATCH_SIZE;
import static com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_ERROR;
import static com.facebook.presto.spi.predicate.Utils.nativeValueToBlock;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.slice.Slices.utf8Slice;
import static java.util.Objects.requireNonNull;
public class OrcPageSource
implements ConnectorPageSource
{
public static final int NULL_COLUMN = -1;
public static final int ROWID_COLUMN = -2;
public static final int SHARD_UUID_COLUMN = -3;
public static final int BUCKET_NUMBER_COLUMN = -4;
private final OrcBatchRecordReader recordReader;
private final OrcDataSource orcDataSource;
// for shard with existing delta
private final DeltaShardLoader deltaShardLoader;
private final List<Long> columnIds;
private final List<Type> types;
private final Block[] constantBlocks;
private final int[] columnIndexes;
private final OrcAggregatedMemoryContext systemMemoryContext;
private int batchId;
private long completedPositions;
private boolean closed;
public OrcPageSource(
OrcBatchRecordReader recordReader,
OrcDataSource orcDataSource,
List<Long> columnIds,
List<Type> columnTypes,
List<Integer> columnIndexes,
UUID shardUuid,
OptionalInt bucketNumber,
OrcAggregatedMemoryContext systemMemoryContext,
DeltaShardLoader deltaShardLoader)
{
this.recordReader = requireNonNull(recordReader, "recordReader is null");
this.orcDataSource = requireNonNull(orcDataSource, "orcDataSource is null");
this.deltaShardLoader = requireNonNull(deltaShardLoader, "Optional<deltaShardUuid> is null");
checkArgument(columnIds.size() == columnTypes.size(), "ids and types mismatch");
checkArgument(columnIds.size() == columnIndexes.size(), "ids and indexes mismatch");
int size = columnIds.size();
this.columnIds = ImmutableList.copyOf(columnIds);
this.types = ImmutableList.copyOf(columnTypes);
this.constantBlocks = new Block[size];
this.columnIndexes = new int[size];
requireNonNull(shardUuid, "shardUuid is null");
for (int i = 0; i < size; i++) {
this.columnIndexes[i] = columnIndexes.get(i);
if (this.columnIndexes[i] == NULL_COLUMN) {
constantBlocks[i] = buildSingleValueBlock(columnTypes.get(i), null);
}
else if (this.columnIndexes[i] == SHARD_UUID_COLUMN) {
constantBlocks[i] = buildSingleValueBlock(columnTypes.get(i), utf8Slice(shardUuid.toString()));
}
else if (this.columnIndexes[i] == BUCKET_NUMBER_COLUMN) {
if (bucketNumber.isPresent()) {
constantBlocks[i] = buildSingleValueBlock(columnTypes.get(i), (long) bucketNumber.getAsInt());
}
else {
constantBlocks[i] = buildSingleValueBlock(columnTypes.get(i), null);
}
}
}
this.systemMemoryContext = requireNonNull(systemMemoryContext, "systemMemoryContext is null");
}
@Override
public long getCompletedBytes()
{
return orcDataSource.getReadBytes();
}
@Override
public long getCompletedPositions()
{
return completedPositions;
}
@Override
public long getReadTimeNanos()
{
return orcDataSource.getReadTimeNanos();
}
@Override
public boolean isFinished()
{
return closed;
}
@Override
public Page getNextPage()
{
try {
batchId++;
int batchSize = recordReader.nextBatch();
if (batchSize <= 0) {
close();
return null;
}
completedPositions += batchSize;
long filePosition = recordReader.getFilePosition();
// for every page, will generate its rowsToKeep
RowsToKeepResult rowsToKeep = deltaShardLoader.getRowsToKeep(batchSize, filePosition);
Block[] blocks = new Block[columnIndexes.length];
for (int fieldId = 0; fieldId < blocks.length; fieldId++) {
if (constantBlocks[fieldId] != null) {
blocks[fieldId] = constantBlocks[fieldId].getRegion(0, rowsToKeep.keepAll() ? batchSize : rowsToKeep.size());
}
else if (columnIndexes[fieldId] == ROWID_COLUMN) {
blocks[fieldId] = buildSequenceBlock(filePosition, batchSize, rowsToKeep);
}
else {
blocks[fieldId] = new LazyBlock(batchSize, new OrcBlockLoader(columnIndexes[fieldId], rowsToKeep));
}
}
return new Page(rowsToKeep.keepAll() ? batchSize : rowsToKeep.size(), blocks);
}
catch (IOException | RuntimeException e) {
closeWithSuppression(e);
throw new PrestoException(RAPTOR_ERROR, e);
}
}
@Override
public void close()
{
closed = true;
try {
recordReader.close();
}
catch (IOException e) {
throw new PrestoException(RAPTOR_ERROR, e);
}
}
@Override
public String toString()
{
return toStringHelper(this)
.add("columnNames", columnIds)
.add("types", types)
.toString();
}
@Override
public long getSystemMemoryUsage()
{
return systemMemoryContext.getBytes();
}
private void closeWithSuppression(Throwable throwable)
{
requireNonNull(throwable, "throwable is null");
try {
close();
}
catch (RuntimeException e) {
// Self-suppression not permitted
if (throwable != e) {
throwable.addSuppressed(e);
}
}
}
private static Block buildSequenceBlock(long start, int count, RowsToKeepResult rowsToKeep)
{
BlockBuilder builder = BIGINT.createFixedSizeBlockBuilder(count);
for (int i = 0; i < count; i++) {
if (rowsToKeep.keepAll() || rowsToKeep.getRowsToKeep().contains(i)) {
BIGINT.writeLong(builder, start + i);
}
}
return builder.build();
}
private static Block buildSingleValueBlock(Type type, Object value)
{
Block block = nativeValueToBlock(type, value);
return new RunLengthEncodedBlock(block, MAX_BATCH_SIZE);
}
private final class OrcBlockLoader
implements LazyBlockLoader<LazyBlock>
{
private final int expectedBatchId = batchId;
private final int columnIndex;
private final RowsToKeepResult rowsToKeep;
private boolean loaded;
public OrcBlockLoader(int columnIndex, RowsToKeepResult rowsToKeep)
{
this.columnIndex = columnIndex;
this.rowsToKeep = rowsToKeep;
}
@Override
public final void load(LazyBlock lazyBlock)
{
if (loaded) {
return;
}
checkState(batchId == expectedBatchId);
try {
Block block = recordReader.readBlock(columnIndex);
if (rowsToKeep.keepAll()) {
lazyBlock.setBlock(block);
}
else {
lazyBlock.setBlock(block.getPositions(rowsToKeep.elements(), 0, rowsToKeep.size()));
}
}
catch (IOException e) {
throw new PrestoException(RAPTOR_ERROR, e);
}
loaded = true;
}
}
}
| |
/*
* 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.haskell;
import com.facebook.buck.cxx.CxxDeps;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.CxxPreprocessorDep;
import com.facebook.buck.cxx.Linker;
import com.facebook.buck.cxx.Linkers;
import com.facebook.buck.cxx.NativeLinkable;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorConvertible;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.model.InternalFlavor;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.CellPathResolver;
import com.facebook.buck.rules.CommandTool;
import com.facebook.buck.rules.CommonDescriptionArg;
import com.facebook.buck.rules.DefaultBuildTargetSourcePath;
import com.facebook.buck.rules.DefaultSourcePathResolver;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.HasDeclaredDeps;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.SymlinkTree;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.rules.coercer.PatternMatchedCollection;
import com.facebook.buck.rules.coercer.SourceList;
import com.facebook.buck.rules.macros.StringWithMacros;
import com.facebook.buck.rules.query.Query;
import com.facebook.buck.rules.query.QueryUtils;
import com.facebook.buck.util.MoreIterables;
import com.facebook.buck.util.RichStream;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.facebook.buck.versions.VersionRoot;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import java.nio.file.Path;
import java.util.Optional;
import org.immutables.value.Value;
public class HaskellBinaryDescription
implements Description<HaskellBinaryDescriptionArg>,
ImplicitDepsInferringDescription<
HaskellBinaryDescription.AbstractHaskellBinaryDescriptionArg>,
Flavored,
VersionRoot<HaskellBinaryDescriptionArg> {
private static final FlavorDomain<Type> BINARY_TYPE =
FlavorDomain.from("Haskell Binary Type", Type.class);
private final HaskellConfig haskellConfig;
private final FlavorDomain<CxxPlatform> cxxPlatforms;
private final CxxPlatform defaultCxxPlatform;
public HaskellBinaryDescription(
HaskellConfig haskellConfig,
FlavorDomain<CxxPlatform> cxxPlatforms,
CxxPlatform defaultCxxPlatform) {
this.haskellConfig = haskellConfig;
this.cxxPlatforms = cxxPlatforms;
this.defaultCxxPlatform = defaultCxxPlatform;
}
@Override
public Class<HaskellBinaryDescriptionArg> getConstructorArgType() {
return HaskellBinaryDescriptionArg.class;
}
private Linker.LinkableDepType getLinkStyle(BuildTarget target, HaskellBinaryDescriptionArg arg) {
Optional<Type> type = BINARY_TYPE.getValue(target);
if (type.isPresent()) {
return type.get().getLinkStyle();
}
if (arg.getLinkStyle().isPresent()) {
return arg.getLinkStyle().get();
}
return Linker.LinkableDepType.STATIC;
}
// Return the C/C++ platform to build against.
private CxxPlatform getCxxPlatform(BuildTarget target, HaskellBinaryDescriptionArg arg) {
Optional<CxxPlatform> flavorPlatform = cxxPlatforms.getValue(target);
if (flavorPlatform.isPresent()) {
return flavorPlatform.get();
}
if (arg.getCxxPlatform().isPresent()) {
return cxxPlatforms.getValue(arg.getCxxPlatform().get());
}
return defaultCxxPlatform;
}
@Override
public BuildRule createBuildRule(
TargetGraph targetGraph,
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
BuildRuleResolver resolver,
CellPathResolver cellRoots,
HaskellBinaryDescriptionArg args)
throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);
CxxPlatform cxxPlatform = getCxxPlatform(buildTarget, args);
Linker.LinkableDepType depType = getLinkStyle(buildTarget, args);
// The target to use for the link rule.
BuildTarget binaryTarget = buildTarget.withFlavors(InternalFlavor.of("binary"));
// Maintain backwards compatibility to ease upgrade flows.
if (haskellConfig.shouldUsedOldBinaryOutputLocation().orElse(true)) {
binaryTarget = binaryTarget.withAppendedFlavors(cxxPlatform.getFlavor());
}
ImmutableSet.Builder<BuildRule> depsBuilder = ImmutableSet.builder();
depsBuilder.addAll(
CxxDeps.builder()
.addDeps(args.getDeps())
.addPlatformDeps(args.getPlatformDeps())
.build()
.get(resolver, cxxPlatform));
args.getDepsQuery()
.ifPresent(
query ->
QueryUtils.resolveDepQuery(
buildTarget, query, resolver, cellRoots, targetGraph, args.getDeps())
.filter(NativeLinkable.class::isInstance)
.forEach(depsBuilder::add));
ImmutableSet<BuildRule> deps = depsBuilder.build();
// Inputs we'll be linking (archives, objects, etc.)
ImmutableList.Builder<Arg> linkInputsBuilder = ImmutableList.builder();
// Additional linker flags passed to the Haskell linker
ImmutableList.Builder<Arg> linkFlagsBuilder = ImmutableList.builder();
CommandTool.Builder executableBuilder = new CommandTool.Builder();
// Add the binary as the first argument.
executableBuilder.addArg(SourcePathArg.of(new DefaultBuildTargetSourcePath(binaryTarget)));
Path outputDir = BuildTargets.getGenPath(projectFilesystem, binaryTarget, "%s").getParent();
Path outputPath = outputDir.resolve(binaryTarget.getShortName());
Path absBinaryDir = buildTarget.getCellPath().resolve(outputDir);
// Special handling for dynamically linked binaries.
if (depType == Linker.LinkableDepType.SHARED) {
// Create a symlink tree with for all shared libraries needed by this binary.
SymlinkTree sharedLibraries =
resolver.addToIndex(
CxxDescriptionEnhancer.createSharedLibrarySymlinkTree(
buildTarget,
projectFilesystem,
cxxPlatform,
deps,
NativeLinkable.class::isInstance));
// Embed a origin-relative library path into the binary so it can find the shared libraries.
// The shared libraries root is absolute. Also need an absolute path to the linkOutput
linkFlagsBuilder.addAll(
StringArg.from(
MoreIterables.zipAndConcat(
Iterables.cycle("-optl"),
Linkers.iXlinker(
"-rpath",
String.format(
"%s/%s",
cxxPlatform.getLd().resolve(resolver).origin(),
absBinaryDir.relativize(sharedLibraries.getRoot()).toString())))));
// Add all the shared libraries and the symlink tree as inputs to the tool that represents
// this binary, so that users can attach the proper deps.
executableBuilder.addDep(sharedLibraries);
executableBuilder.addInputs(sharedLibraries.getLinks().values());
}
// Add in linker flags.
linkFlagsBuilder.addAll(
ImmutableList.copyOf(
Iterables.transform(
args.getLinkerFlags(),
f ->
CxxDescriptionEnhancer.toStringWithMacrosArgs(
buildTarget, cellRoots, resolver, cxxPlatform, f))));
// Generate the compile rule and add its objects to the link.
HaskellCompileRule compileRule =
resolver.addToIndex(
HaskellDescriptionUtils.requireCompileRule(
buildTarget,
projectFilesystem,
params,
resolver,
ruleFinder,
RichStream.from(deps)
.filter(
dep ->
dep instanceof HaskellCompileDep || dep instanceof CxxPreprocessorDep)
.toImmutableSet(),
cxxPlatform,
haskellConfig,
depType,
false,
args.getMain(),
Optional.empty(),
args.getCompilerFlags(),
HaskellSources.from(
buildTarget,
resolver,
pathResolver,
ruleFinder,
cxxPlatform,
"srcs",
args.getSrcs())));
linkInputsBuilder.addAll(SourcePathArg.from(compileRule.getObjects()));
ImmutableList<Arg> linkInputs = linkInputsBuilder.build();
ImmutableList<Arg> linkFlags = linkFlagsBuilder.build();
final CommandTool executable = executableBuilder.build();
final HaskellLinkRule linkRule =
HaskellDescriptionUtils.createLinkRule(
binaryTarget,
projectFilesystem,
params,
resolver,
ruleFinder,
cxxPlatform,
haskellConfig,
Linker.LinkType.EXECUTABLE,
linkFlags,
linkInputs,
RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(),
depType,
outputPath,
Optional.empty(),
false);
return new HaskellBinary(
buildTarget,
projectFilesystem,
params.copyAppendingExtraDeps(linkRule),
deps,
executable,
linkRule.getSourcePathToOutput());
}
@Override
public void findDepsForTargetFromConstructorArgs(
BuildTarget buildTarget,
CellPathResolver cellRoots,
AbstractHaskellBinaryDescriptionArg constructorArg,
ImmutableCollection.Builder<BuildTarget> extraDepsBuilder,
ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) {
HaskellDescriptionUtils.getParseTimeDeps(
haskellConfig,
ImmutableList.of(
cxxPlatforms.getValue(buildTarget.getFlavors()).orElse(defaultCxxPlatform)),
extraDepsBuilder);
constructorArg
.getDepsQuery()
.ifPresent(
depsQuery ->
QueryUtils.extractParseTimeTargets(buildTarget, cellRoots, depsQuery)
.forEach(extraDepsBuilder::add));
}
@Override
public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
if (cxxPlatforms.containsAnyOf(flavors)) {
return true;
}
for (Type type : Type.values()) {
if (flavors.contains(type.getFlavor())) {
return true;
}
}
return false;
}
@Override
public boolean isVersionRoot(ImmutableSet<Flavor> flavors) {
return true;
}
protected enum Type implements FlavorConvertible {
SHARED(CxxDescriptionEnhancer.SHARED_FLAVOR, Linker.LinkableDepType.SHARED),
STATIC_PIC(CxxDescriptionEnhancer.STATIC_PIC_FLAVOR, Linker.LinkableDepType.STATIC_PIC),
STATIC(CxxDescriptionEnhancer.STATIC_FLAVOR, Linker.LinkableDepType.STATIC),
;
private final Flavor flavor;
private final Linker.LinkableDepType linkStyle;
Type(Flavor flavor, Linker.LinkableDepType linkStyle) {
this.flavor = flavor;
this.linkStyle = linkStyle;
}
@Override
public Flavor getFlavor() {
return flavor;
}
public Linker.LinkableDepType getLinkStyle() {
return linkStyle;
}
}
@BuckStyleImmutable
@Value.Immutable
interface AbstractHaskellBinaryDescriptionArg extends CommonDescriptionArg, HasDeclaredDeps {
@Value.Default
default SourceList getSrcs() {
return SourceList.EMPTY;
}
ImmutableList<String> getCompilerFlags();
ImmutableList<StringWithMacros> getLinkerFlags();
@Value.Default
default PatternMatchedCollection<ImmutableSortedSet<BuildTarget>> getPlatformDeps() {
return PatternMatchedCollection.of();
}
Optional<Query> getDepsQuery();
Optional<String> getMain();
Optional<Linker.LinkableDepType> getLinkStyle();
Optional<Flavor> getCxxPlatform();
}
}
| |
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.powermock.core.transformers.impl;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.CtPrimitiveType;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import org.powermock.core.IndicateReloadClass;
import org.powermock.core.testlisteners.GlobalNotificationBuildSupport;
import org.powermock.core.transformers.MockTransformer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
/**
* MockTransformer implementation that will make PowerMock test-class
* enhancements for four purposes...
* 1) Make test-class static initializer and constructor send crucial details
* (for PowerMockTestListener events) to GlobalNotificationBuildSupport so that
* this information can be forwarded to whichever
* facility is used for composing the PowerMockTestListener events.
* 2) Removal of test-method annotations as a mean to achieve test-suite
* chunking!
* 3) Restore original test-class constructors` accesses
* (in case they have all been made public by {@link
* ClassMockTransformer#setAllConstructorsToPublic(javassist.CtClass)})
* - to avoid that multiple <i>public</i> test-class constructors cause
* a delegate runner from JUnit (or 3rd party) to bail out with an
* error message such as "Test class can only have one constructor".
* 4) Set test-class defer constructor (if exist) as protected instead of public.
* Otherwise a delegate runner from JUnit (or 3rd party) might get confused by
* the presence of more than one test-class constructor and bail out with an
* error message such as "Test class can only have one constructor".
*
* The #3 and #4 enhancements will also be enforced on the constructors
* of classes that are nested within the test-class.
*/
public abstract class TestClassTransformer implements MockTransformer {
private final Class<?> testClass;
private final Class<? extends Annotation> testMethodAnnotationType;
public interface ForTestClass {
RemovesTestMethodAnnotation removesTestMethodAnnotation(Class<? extends Annotation> testMethodAnnotation);
interface RemovesTestMethodAnnotation {
TestClassTransformer fromMethods(Collection<Method> testMethodsThatRunOnOtherClassLoaders);
TestClassTransformer fromAllMethodsExcept(Method singleMethodToRunOnThisClassLoader);
}
}
public static ForTestClass forTestClass(final Class<?> testClass) {
return new ForTestClass() {
@Override
public RemovesTestMethodAnnotation removesTestMethodAnnotation(
final Class<? extends Annotation> testMethodAnnotation) {
return new RemovesTestMethodAnnotation() {
@Override
public TestClassTransformer fromMethods(
final Collection<Method> testMethodsThatRunOnOtherClassLoaders) {
return new TestClassTransformer(testClass, testMethodAnnotation) {
/**
* Is lazily initilized because of
* AbstractTestSuiteChunkerImpl#chunkClass(Class)
*/
Collection<String> methodsThatRunOnOtherClassLoaders;
@Override
boolean mustHaveTestAnnotationRemoved(CtMethod method)
throws NotFoundException {
if (null == methodsThatRunOnOtherClassLoaders) {
/* This lazy initialization is necessary - see above */
methodsThatRunOnOtherClassLoaders = new HashSet<String>();
for (Method m : testMethodsThatRunOnOtherClassLoaders) {
methodsThatRunOnOtherClassLoaders.add(
signatureOf(m));
}
testMethodsThatRunOnOtherClassLoaders.clear();
}
return methodsThatRunOnOtherClassLoaders
.contains(signatureOf(method));
}
};
}
@Override
public TestClassTransformer fromAllMethodsExcept(
Method singleMethodToRunOnTargetClassLoader) {
final String targetMethodSignature =
signatureOf(singleMethodToRunOnTargetClassLoader);
return new TestClassTransformer(testClass, testMethodAnnotation) {
@Override
boolean mustHaveTestAnnotationRemoved(CtMethod method)
throws Exception {
return !signatureOf(method).equals(targetMethodSignature);
}
};
}
};
}
};
}
private TestClassTransformer(
Class<?> testClass, Class<? extends Annotation> testMethodAnnotationType) {
this.testClass = testClass;
this.testMethodAnnotationType = testMethodAnnotationType;
}
private boolean isTestClass(CtClass clazz) {
try {
return Class.forName(clazz.getName(), false, testClass.getClassLoader())
.isAssignableFrom(testClass);
} catch (ClassNotFoundException ex) {
return false;
}
}
private boolean isNestedWithinTestClass(CtClass clazz) {
String clazzName = clazz.getName();
return clazzName.startsWith(testClass.getName())
&& '$' == clazzName.charAt(testClass.getName().length());
}
private Class<?> asOriginalClass(CtClass type) throws Exception {
try {
return type.isArray()
? Array.newInstance(asOriginalClass(type.getComponentType()), 0).getClass()
: type.isPrimitive()
? Primitives.getClassFor((CtPrimitiveType) type)
: Class.forName(type.getName(), true, testClass.getClassLoader());
} catch (Exception ex) {
throw new RuntimeException("Cannot resolve type: " + type, ex);
}
}
private Class<?>[] asOriginalClassParams(CtClass[] parameterTypes)
throws Exception {
final Class<?>[] classParams = new Class[parameterTypes.length];
for (int i = 0; i < classParams.length; ++i) {
classParams[i] = asOriginalClass(parameterTypes[i]);
}
return classParams;
}
abstract boolean mustHaveTestAnnotationRemoved(CtMethod method) throws Exception;
private void removeTestMethodAnnotationFrom(CtMethod m)
throws ClassNotFoundException {
final AnnotationsAttribute attr = (AnnotationsAttribute)
m.getMethodInfo().getAttribute(AnnotationsAttribute.visibleTag);
javassist.bytecode.annotation.Annotation[] newAnnotations =
new javassist.bytecode.annotation.Annotation[attr.numAnnotations() - 1];
int i = -1;
for (javassist.bytecode.annotation.Annotation a : attr.getAnnotations()) {
if (a.getTypeName().equals(testMethodAnnotationType.getName())) {
continue;
}
newAnnotations[++i] = a;
}
attr.setAnnotations(newAnnotations);
}
private void removeTestAnnotationsForTestMethodsThatRunOnOtherClassLoader(CtClass clazz)
throws Exception {
for (CtMethod m : clazz.getDeclaredMethods()) {
if (m.hasAnnotation(testMethodAnnotationType)
&& mustHaveTestAnnotationRemoved(m)) {
removeTestMethodAnnotationFrom(m);
}
}
}
@Override
public CtClass transform(final CtClass clazz) throws Exception {
if (clazz.isFrozen()) {
clazz.defrost();
}
if (isTestClass(clazz)) {
removeTestAnnotationsForTestMethodsThatRunOnOtherClassLoader(clazz);
addLifeCycleNotifications(clazz);
makeDeferConstructorNonPublic(clazz);
restoreOriginalConstructorsAccesses(clazz);
} else if (isNestedWithinTestClass(clazz)) {
makeDeferConstructorNonPublic(clazz);
restoreOriginalConstructorsAccesses(clazz);
}
return clazz;
}
private void addLifeCycleNotifications(CtClass clazz) {
try {
addClassInitializerNotification(clazz);
addConstructorNotification(clazz);
} catch (CannotCompileException ex) {
throw new Error("Powermock error: " + ex.getMessage(), ex);
}
}
private void addClassInitializerNotification(CtClass clazz)
throws CannotCompileException {
if (null == clazz.getClassInitializer()) {
clazz.makeClassInitializer();
}
clazz.getClassInitializer().insertBefore(
GlobalNotificationBuildSupport.class.getName()
+ ".testClassInitiated(" + clazz.getName() + ".class);");
}
private static boolean hasSuperClass(CtClass clazz) {
try {
CtClass superClazz = clazz.getSuperclass();
/*
* Being extra careful here - and backup in case the
* work-in-progress clazz doesn't cause NotFoundException ...
*/
return null != superClazz
&& !"java.lang.Object".equals(superClazz.getName());
} catch (NotFoundException noWasSuperClassFound) {
return false;
}
}
private void addConstructorNotification(final CtClass clazz)
throws CannotCompileException {
final String notificationCode =
GlobalNotificationBuildSupport.class.getName()
+ ".testInstanceCreated(this);";
final boolean asFinally = !hasSuperClass(clazz);
for (final CtConstructor constr : clazz.getDeclaredConstructors()) {
constr.insertAfter(
notificationCode,
asFinally/* unless there is a super-class, because of this
* problem: https://community.jboss.org/thread/94194*/);
}
}
private void restoreOriginalConstructorsAccesses(CtClass clazz) throws Exception {
Class<?> originalClass = testClass.getName().equals(clazz.getName())
? testClass
: Class.forName(clazz.getName(), true, testClass.getClassLoader());
for (final CtConstructor ctConstr : clazz.getConstructors()) {
int ctModifiers = ctConstr.getModifiers();
if (!Modifier.isPublic(ctModifiers)) {
/* Probably a defer-constructor */
continue;
}
int desiredAccessModifiers = originalClass.getDeclaredConstructor(
asOriginalClassParams(ctConstr.getParameterTypes())).getModifiers();
if (Modifier.isPrivate(desiredAccessModifiers)) {
ctConstr.setModifiers(Modifier.setPrivate(ctModifiers));
} else if (Modifier.isProtected(desiredAccessModifiers)) {
ctConstr.setModifiers(Modifier.setProtected(ctModifiers));
} else if (!Modifier.isPublic(desiredAccessModifiers)) {
ctConstr.setModifiers(Modifier.setPackage(ctModifiers));
} else {
/* ctConstr remains public */
}
}
}
private void makeDeferConstructorNonPublic(final CtClass clazz) {
for (final CtConstructor constr : clazz.getConstructors()) {
try {
for (CtClass paramType : constr.getParameterTypes()) {
if (IndicateReloadClass.class.getName()
.equals(paramType.getName())) {
/* Found defer constructor ... */
final int modifiers = constr.getModifiers();
if (Modifier.isPublic(modifiers)) {
constr.setModifiers(Modifier.setProtected(modifiers));
}
break;
}
}
} catch (NotFoundException thereAreNoParameters) {
/* ... but to get an exception here seems odd. */
}
}
}
private static String signatureOf(Method m) {
Class<?>[] paramTypes = m.getParameterTypes();
String[] paramTypeNames = new String[paramTypes.length];
for (int i = 0; i < paramTypeNames.length; ++i) {
paramTypeNames[i] = paramTypes[i].getSimpleName();
}
return createSignature(
m.getDeclaringClass().getSimpleName(),
m.getReturnType().getSimpleName(),
m.getName(), paramTypeNames);
}
private static String signatureOf(CtMethod m) throws NotFoundException {
CtClass[] paramTypes = m.getParameterTypes();
String[] paramTypeNames = new String[paramTypes.length];
for (int i = 0; i < paramTypeNames.length; ++i) {
paramTypeNames[i] = paramTypes[i].getSimpleName();
}
return createSignature(
m.getDeclaringClass().getSimpleName(),
m.getReturnType().getSimpleName(),
m.getName(), paramTypeNames);
}
private static String createSignature(
String testClass, String returnType, String methodName, String[] paramTypes) {
StringBuilder builder = new StringBuilder(testClass)
.append('\n').append(returnType)
.append('\n').append(methodName);
for (String param : paramTypes) {
builder.append('\n').append(param);
}
return builder.toString();
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.formatting.engine;
import com.intellij.formatting.*;
import com.intellij.openapi.editor.Document;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class ExpandChildrenIndentState extends State {
private final Document myDocument;
private final WrapBlocksState myWrapState;
private IndentAdjuster myIndentAdjuster;
private MultiMap<ExpandableIndent, AbstractBlockWrapper> myExpandableIndents;
private LeafBlockWrapper myCurrentBlock;
private Iterator<ExpandableIndent> myIterator;
private final MultiMap<Alignment, LeafBlockWrapper> myBlocksToRealign = new MultiMap<>();
public ExpandChildrenIndentState(Document document, WrapBlocksState state) {
myDocument = document;
myWrapState = state;
}
@Override
public void prepare() {
myExpandableIndents = myWrapState.getExpandableIndent();
myIndentAdjuster = myWrapState.getIndentAdjuster();
myIterator = myExpandableIndents.keySet().iterator();
}
@Override
protected void doIteration() {
if (!myIterator.hasNext()) {
setDone(true);
return;
}
final ExpandableIndent indent = myIterator.next();
Collection<AbstractBlockWrapper> blocksToExpandIndent = myExpandableIndents.get(indent);
if (shouldExpand(blocksToExpandIndent)) {
for (AbstractBlockWrapper block : blocksToExpandIndent) {
indent.setEnforceIndent(true);
reindentNewLineChildren(block);
indent.setEnforceIndent(false);
}
}
restoreAlignments(myBlocksToRealign);
myBlocksToRealign.clear();
}
private void restoreAlignments(MultiMap<Alignment, LeafBlockWrapper> blocks) {
for (Alignment alignment : blocks.keySet()) {
AlignmentImpl alignmentImpl = (AlignmentImpl)alignment;
if (!alignmentImpl.isAllowBackwardShift()) continue;
Set<LeafBlockWrapper> toRealign = alignmentImpl.getOffsetResponsibleBlocks();
arrangeSpaces(toRealign);
LeafBlockWrapper rightMostBlock = getRightMostBlock(toRealign);
int maxSpacesBeforeBlock = rightMostBlock.getNumberOfSymbolsBeforeBlock().getTotalSpaces();
int rightMostBlockLine = myDocument.getLineNumber(rightMostBlock.getStartOffset());
for (LeafBlockWrapper block : toRealign) {
int currentBlockLine = myDocument.getLineNumber(block.getStartOffset());
if (currentBlockLine == rightMostBlockLine) continue;
int blockIndent = block.getNumberOfSymbolsBeforeBlock().getTotalSpaces();
int delta = maxSpacesBeforeBlock - blockIndent;
if (delta > 0) {
int newSpaces = block.getWhiteSpace().getTotalSpaces() + delta;
adjustSpacingToKeepAligned(block, newSpaces);
}
}
}
}
private static void adjustSpacingToKeepAligned(LeafBlockWrapper block, int newSpaces) {
WhiteSpace space = block.getWhiteSpace();
SpacingImpl property = block.getSpaceProperty();
if (property == null) return;
space.arrangeSpaces(new SpacingImpl(newSpaces, newSpaces,
property.getMinLineFeeds(),
property.isReadOnly(),
property.isSafe(),
property.shouldKeepLineFeeds(),
property.getKeepBlankLines(),
property.shouldKeepFirstColumn(),
property.getPrefLineFeeds()));
}
private static LeafBlockWrapper getRightMostBlock(Collection<LeafBlockWrapper> toRealign) {
int maxSpacesBeforeBlock = -1;
LeafBlockWrapper rightMostBlock = null;
for (LeafBlockWrapper block : toRealign) {
int spaces = block.getNumberOfSymbolsBeforeBlock().getTotalSpaces();
if (spaces > maxSpacesBeforeBlock) {
maxSpacesBeforeBlock = spaces;
rightMostBlock = block;
}
}
return rightMostBlock;
}
private static void arrangeSpaces(Collection<LeafBlockWrapper> toRealign) {
for (LeafBlockWrapper block : toRealign) {
WhiteSpace whiteSpace = block.getWhiteSpace();
SpacingImpl spacing = block.getSpaceProperty();
whiteSpace.arrangeSpaces(spacing);
}
}
private static boolean shouldExpand(Collection<AbstractBlockWrapper> blocksToExpandIndent) {
AbstractBlockWrapper last = null;
for (AbstractBlockWrapper block : blocksToExpandIndent) {
if (block.getWhiteSpace().containsLineFeeds()) {
return true;
}
last = block;
}
if (last != null) {
AbstractBlockWrapper next = getNextBlock(last);
if (next != null && next.getWhiteSpace().containsLineFeeds()) {
int nextNewLineBlockIndent = next.getNumberOfSymbolsBeforeBlock().getTotalSpaces();
if (nextNewLineBlockIndent >= finMinNewLineIndent(blocksToExpandIndent)) {
return true;
}
}
}
return false;
}
private static int finMinNewLineIndent(@NotNull Collection<AbstractBlockWrapper> wrappers) {
int totalMinimum = Integer.MAX_VALUE;
for (AbstractBlockWrapper wrapper : wrappers) {
int minNewLineIndent = findMinNewLineIndent(wrapper);
if (minNewLineIndent < totalMinimum) {
totalMinimum = minNewLineIndent;
}
}
return totalMinimum;
}
private static int findMinNewLineIndent(@NotNull AbstractBlockWrapper block) {
if (block instanceof LeafBlockWrapper && block.getWhiteSpace().containsLineFeeds()) {
return block.getNumberOfSymbolsBeforeBlock().getTotalSpaces();
}
else if (block instanceof CompositeBlockWrapper) {
List<AbstractBlockWrapper> children = ((CompositeBlockWrapper)block).getChildren();
int currentMin = Integer.MAX_VALUE;
for (AbstractBlockWrapper child : children) {
int childIndent = findMinNewLineIndent(child);
if (childIndent < currentMin) {
currentMin = childIndent;
}
}
return currentMin;
}
return Integer.MAX_VALUE;
}
private static AbstractBlockWrapper getNextBlock(AbstractBlockWrapper block) {
List<AbstractBlockWrapper> children = block.getParent().getChildren();
int nextBlockIndex = children.indexOf(block) + 1;
if (nextBlockIndex < children.size()) {
return children.get(nextBlockIndex);
}
return null;
}
private void reindentNewLineChildren(final @NotNull AbstractBlockWrapper block) {
if (block instanceof LeafBlockWrapper) {
WhiteSpace space = block.getWhiteSpace();
if (space.containsLineFeeds()) {
myCurrentBlock = (LeafBlockWrapper)block;
myIndentAdjuster.adjustIndent(myCurrentBlock); //since aligned block starts new line, it should not touch any other block
storeAlignmentsAfterCurrentBlock();
}
}
else if (block instanceof CompositeBlockWrapper) {
List<AbstractBlockWrapper> children = ((CompositeBlockWrapper)block).getChildren();
for (AbstractBlockWrapper childBlock : children) {
reindentNewLineChildren(childBlock);
}
}
}
private void storeAlignmentsAfterCurrentBlock() {
LeafBlockWrapper current = myCurrentBlock.getNextBlock();
while (current != null && !current.getWhiteSpace().containsLineFeeds()) {
if (current.getAlignment() != null) {
myBlocksToRealign.putValue(current.getAlignment(), current);
}
current = current.getNextBlock();
}
}
}
| |
/**
* Copyright (c) 2008-2012 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.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.profile2.dao;
import java.util.Date;
import java.util.List;
import org.sakaiproject.profile2.hbm.model.ProfileFriend;
import org.sakaiproject.profile2.hbm.model.ProfileImageExternal;
import org.sakaiproject.profile2.hbm.model.ProfileImageOfficial;
import org.sakaiproject.profile2.hbm.model.ProfileImageUploaded;
import org.sakaiproject.profile2.hbm.model.ProfileKudos;
import org.sakaiproject.profile2.model.CompanyProfile;
import org.sakaiproject.profile2.model.ExternalIntegrationInfo;
import org.sakaiproject.profile2.model.GalleryImage;
import org.sakaiproject.profile2.model.Message;
import org.sakaiproject.profile2.model.MessageParticipant;
import org.sakaiproject.profile2.model.MessageThread;
import org.sakaiproject.profile2.model.ProfilePreferences;
import org.sakaiproject.profile2.model.ProfilePrivacy;
import org.sakaiproject.profile2.model.ProfileStatus;
import org.sakaiproject.profile2.model.SocialNetworkingInfo;
import org.sakaiproject.profile2.model.UserProfile;
import org.sakaiproject.profile2.model.WallItem;
import org.sakaiproject.profile2.model.WallItemComment;
/**
* Internal DAO Interface for Profile2.
*
* @author Steve Swinsburg (steve.swinsburg@gmail.com)
*
*/
public interface ProfileDao {
/**
* Get a list of unconfirmed Friend requests for a given user. Uses a native SQL query
* Returns: (all those where userId is the friend_uuid and confirmed=false)
*
* @param userId uuid of the user to retrieve the list of friends for
*/
public List<String> getRequestedConnectionUserIdsForUser(final String userId);
/**
* Get a list of confirmed connections for a given user. Uses a native SQL query so we can use unions
* Returns: (all those where userId is the user_uuid and confirmed=true) & (all those where user is friend_uuid and confirmed=true)
*
* This only returns userIds. If you want a list of Person objects, see getConnectionsForUser()
*
* @param userId uuid of the user to retrieve the list of friends for
*/
public List<String> getConfirmedConnectionUserIdsForUser(final String userId);
/**
* Get a list of all userIds that match the search criteria in name or email
*
* @param search string to search on
* @return
*/
public List<String> findSakaiPersonsByNameOrEmail(final String search);
/**
* Get a list of all userIds that match the search criteria in the interest fields.
*
* @param search string to search on
* @param includeBusinessBio <code>true</code> if the business biography should also be searched.
* @return
*/
public List<String> findSakaiPersonsByInterest(final String search, boolean includeBusinessBio);
/**
* Get the current ProfileImage records from the database.
* There should only ever be one, but in case things get out of sync this returns all.
* This method is only used when we are adding a new image as we need to invalidate all of the others
* If you are just wanting to retrieve the latest image, see getCurrentProfileImageRecord()
*
* @param userId userId of the user
*/
public List<ProfileImageUploaded> getCurrentProfileImageRecords(final String userId);
/**
* Get the current ProfileImage record from the database.
* There should only ever be one, but if there are more this will return the latest.
* This is called when retrieving a profile image for a user. When adding a new image, there is a call
* to a private method called getCurrentProfileImageRecords() which should invalidate any multiple current images
*
* @param userId userId of the user
*/
public ProfileImageUploaded getCurrentProfileImageRecord(final String userId);
/**
* Get old ProfileImage records from the database.
* TODO: Used for displaying old the profile pictures album
*
* @param userId userId of the user
*/
public List<ProfileImageUploaded> getOtherProfileImageRecords(final String userId);
/**
* Get the ProfileImageOfficial record from the database for the given user
* @param userUuid uuid of the user
* @return
*/
public ProfileImageOfficial getOfficialImageRecordForUser(final String userUuid);
/**
* Save the ProfileImageOfficial record the database
* @param officialImage ProfileImageOfficial object
* @return
*/
public boolean saveOfficialImageUrl(ProfileImageOfficial officialImage);
/**
* Get a connection record for a user/friend pair
* <p>This tries both column arrangements, ie user/friend and friend/user</p>
* @param userId uuid of the user
* @param friendId uuid of the other user
* @return
*/
public ProfileFriend getConnectionRecord(final String userId, final String friendId);
/**
* Save a new connection record
* @param profileFriend ProfileFriend record
* @return
*/
public boolean addNewConnection(ProfileFriend profileFriend);
/**
* Update a connection record
* @param profileFriend ProfileFriend record
* @return
*/
public boolean updateConnection(ProfileFriend profileFriend);
/**
* Remove a connection record
* @param profileFriend ProfileFriend record
* @return
*/
public boolean removeConnection(ProfileFriend profileFriend);
/**
* Get a connection record that is pending
* @param userId uuid of the user
* @param friendId uuid of the friend
* @return
*/
public ProfileFriend getPendingConnection(final String userId, final String friendId);
/**
* Get a ProfileStatus record for a user, but only if the date of the record is within the given time
* @param userId uuid of the user
* @param oldestStatusDate oldest date to search until
* @return
*/
public ProfileStatus getUserStatus(final String userId, final Date oldestStatusDate);
/**
* Set the status for a user
* @param profileStatus ProfileStatus object
* @return
*/
public boolean setUserStatus(ProfileStatus profileStatus);
/**
* Remove the ProfileStatus record for a user
* @param profileStatus ProfileStatus object
* @return
*/
public boolean clearUserStatus(ProfileStatus profileStatus);
/**
* Get a count of all status updates for a user
* @param userUuid uuid of the user
* @return
*/
public int getStatusUpdatesCount(final String userUuid);
/**
* Add a new ProfilePrivacy record
* @param privacy ProfilePrivacy object
* @return
*/
public ProfilePrivacy addNewPrivacyRecord(ProfilePrivacy privacy);
/**
* Get the ProfilePrivacy record for the user
* @param userId uuid of the user
* @return
*/
public ProfilePrivacy getPrivacyRecord(final String userId);
/**
* Update the ProfilePrivacy record
* @param privacy ProfilePrivacy object
* @return
*/
public boolean updatePrivacyRecord(final ProfilePrivacy privacy);
/**
* Save a new CompanyProfile record
* @param companyProfile CompanyProfile record
* @return
*/
public boolean addNewCompanyProfile(final CompanyProfile companyProfile);
/**
* Update a CompanyProfile record
* @param companyProfile CompanyProfile record
* @return
*/
public boolean updateCompanyProfile(final CompanyProfile companyProfile);
/**
* Get the CompanyProfile record for a user and company ID
* @param userId uuid of the user
* @param companyProfileId id of the company
* @return
*/
public CompanyProfile getCompanyProfile(final String userId, final long companyProfileId);
/**
* Get all CompanyProfile records for a user
* @param userId uuid of the user
* @return
*/
public List<CompanyProfile> getCompanyProfiles(final String userId);
/**
* Remove a CompanyProfile record
* @param companyProfile CompanyProfile record
* @return
*/
public boolean removeCompanyProfile(final CompanyProfile companyProfile);
/**
* Add a new GalleryImage record
*
* @param galleryImage GalleryImage record
* @return
*/
public boolean addNewGalleryImage(final GalleryImage galleryImage);
/**
* Get the GalleryImage record for a user and image ID
* @param userId uuid of the user
* @param imageId id of the image
* @return
*/
public GalleryImage getGalleryImageRecord(final String userId, final long imageId);
/**
* Get all GalleryImage records for a user
* @param userId uuid of the user
* @return
*/
public List<GalleryImage> getGalleryImages(final String userId);
/**
* Remove a GalleryImage record
*
* @param galleryImage GalleryImage record
* @return
*/
public boolean removeGalleryImage(final GalleryImage galleryImage);
/**
* Get a count of all gallery images that a user has
* @param userUuid uuid of the user
* @return
*/
public int getGalleryImagesCount(final String userUuid);
/**
* Get a SocialNetworkingInfo record for a user
* @param userId uuid of the user
* @return
*/
public SocialNetworkingInfo getSocialNetworkingInfo(final String userId);
/**
* Save a SocialNetworkingInfo record
* @param socialNetworkingInfo SocialNetworkingInfo object
* @return
*/
public boolean saveSocialNetworkingInfo(final SocialNetworkingInfo socialNetworkingInfo);
/**
* Add a new profile image record to the database. Invalidates others before it adds itself.
*
* @param profileImage ProfileImageUploaded obj
*/
public boolean addNewProfileImage(final ProfileImageUploaded profileImage);
/**
* Get a list of uuids for all users that have a SakaiPerson record
* @return list of uuids
*/
public List<String> getAllSakaiPersonIds();
/**
* Get a total count of all users with SakaiPerson records
* @return count
*/
public int getAllSakaiPersonIdsCount();
/**
* Get a ProfileImageExternal record for a user
* @param userId uuid of the user
* @return
*/
public ProfileImageExternal getExternalImageRecordForUser(final String userId);
/**
* Save a ProfileImageExternal record
* @param externalImage ProfileImageExternal record
* @return
*/
public boolean saveExternalImage(final ProfileImageExternal externalImage);
/**
* Persist a new ProfilePreferences record and return it.
*
* @param prefs complete ProfilePreferences record
*/
public ProfilePreferences addNewPreferencesRecord(ProfilePreferences prefs);
/**
* Get a ProfilePreferences record for the user
* @param userId uuid for the user
* @return
*/
public ProfilePreferences getPreferencesRecordForUser(final String userId);
/**
* Save a ProfilePreferences record
* @param prefs ProfilePreferences record
* @return
*/
public boolean savePreferencesRecord(ProfilePreferences prefs);
/**
* Get a count of all unread messages for a user
* @param userId uuid of the user
* @return
*/
public int getAllUnreadMessagesCount(final String userId);
/**
* Get a count of all threads with unread messages for a user
* @param userId uuid of the user
* @return
*/
public int getThreadsWithUnreadMessagesCount(final String userId);
/**
* Get a count of all sent messages for a user
* @param userId uuid of the user
* @return
*/
public int getSentMessagesCount(final String userId);
/**
* Get a list of MessageThreads for a user
* @param userId uuid of the user
* @return
*/
public List<MessageThread> getMessageThreads(final String userId);
/**
* Get a count of all message threads for a user
* @param userId uuid of the user
* @return
*/
public int getMessageThreadsCount(final String userId);
/**
* Get a list of all Messages in a given thread
* @param threadId id of the thread
* @return
*/
public List<Message> getMessagesInThread(final String threadId);
/**
* Get a count of all Messages in a given thread
* @param threadId id of the thread
* @return
*/
public int getMessagesInThreadCount(final String threadId);
/**
* Get a Message record
* @param id uuid of the Message
* @return
*/
public Message getMessage(final String id);
/**
* Get a MessageThread record
* @param threadId id of the thread
* @return
*/
public MessageThread getMessageThread(final String threadId);
/**
* Get the latest Message in a MessageThread
* @param threadId id of the thread
* @return
*/
public Message getLatestMessageInThread(final String threadId);
/**
* Toggle a Message as being read by the given participant
* @param participant MessageParticipant
* @param status true/false for read/unread
* @return
*/
public boolean toggleMessageRead(MessageParticipant participant, final boolean status);
/**
* Get a MessageParticipant record for the given message and user id
* @param messageId uuid of the message
* @param userUuid uuid of the user
* @return
*/
public MessageParticipant getMessageParticipant(final String messageId, final String userUuid);
/**
* Get a list of uuids of all perticipants in a thread
* @param threadId id of the thread
* @return
*/
public List<String> getThreadParticipants(final String threadId);
/**
* Save a MessageThread record
* @param thread MessageThread object
*/
public void saveNewThread(MessageThread thread);
/**
* Save a Message record
* @param thread Message object
*/
public void saveNewMessage(Message message);
/**
* Save a MessageParticipant record
* @param thread MessageParticipant object
*/
public void saveNewMessageParticipant(MessageParticipant participant);
/**
* Save a list of MessageParticipants
* @param participants List of MessageParticipant objects
*/
public void saveNewMessageParticipants(List<MessageParticipant> participants);
/**
* Get a list of UserProfiles withing the given pageing parameters
* @param start first record
* @param count total number of records
* @return
*/
public List<UserProfile> getUserProfiles(final int start, final int count);
/**
* Get the kudos record for a user
* @param userUuid
* @return ProfileKudos record, or null
*/
public ProfileKudos getKudos(String userUuid);
/**
* Update a user's kudos record
* @param kudos ProfileKudos for the user
* @return
*/
public boolean updateKudos(ProfileKudos kudos);
/**
* Get the ExternalIntegrationInfo record for a user
* @param userUuid
* @return
*/
public ExternalIntegrationInfo getExternalIntegrationInfo(final String userUuid);
/**
* Update a user's ExternalIntegrationInfo record
* @param info ExternalIntegrationInfo for the user
* @return
*/
public boolean updateExternalIntegrationInfo(ExternalIntegrationInfo info);
/**
* Adds a wall item for the specified user.
*
* @param userUuid the user ID.
* @param item the wall item to add.
* @return <code>true</code> on success, <code>false</code> on failure.
*/
public boolean addNewWallItemForUser(final String userUuid, final WallItem item);
/**
* Removes a wall item.
*
* @param item the wall item to remove.
* @return <code>true</code> on success, <code>false</code> on failure.
*/
public boolean removeWallItemFromWall(final WallItem item);
/**
* Retrieves all wall items for the specified user.
*
* @param userUuid the user ID.
* @return the wall items for the specified user.
*/
public List<WallItem> getWallItemsForUser(final String userUuid);
/**
* Adds a new wall item comment.
*
* @param wallItemComment the wall item comment to add.
* @return <code>true</code> if the add is successful and
* <code>false</code> if the add fails.
*/
public boolean addNewCommentToWallItem(WallItemComment wallItemComment);
/**
* Invalidate the current profile image for a user.
*
* @param userUuid the uuid for the user
*/
public boolean invalidateCurrentProfileImage(final String userUuid);
// Hibernate query constants
final String QUERY_GET_COMPANY_PROFILE = "getCompanyProfile";
final String QUERY_GET_COMPANY_PROFILES = "getCompanyProfiles";
final String QUERY_GET_FRIEND_REQUESTS_FOR_USER = "getFriendRequestsForUser";
final String QUERY_GET_CONFIRMED_FRIEND_USERIDS_FOR_USER = "getConfirmedFriendUserIdsForUser";
final String QUERY_GET_FRIEND_REQUEST = "getFriendRequest";
final String QUERY_GET_FRIEND_RECORD = "getFriendRecord";
final String QUERY_GET_USER_STATUS = "getUserStatus";
final String QUERY_GET_PRIVACY_RECORD = "getPrivacyRecord";
final String QUERY_GET_CURRENT_PROFILE_IMAGE_RECORD = "getCurrentProfileImageRecord";
final String QUERY_OTHER_PROFILE_IMAGE_RECORDS = "getOtherProfileImageRecords";
final String QUERY_GET_STATUS_UPDATES_COUNT = "getStatusUpdatesCount";
//GalleryImage
final String QUERY_GET_GALLERY_IMAGE_RECORDS = "getGalleryImageRecords";
final String QUERY_GET_GALLERY_RECORD = "getGalleryRecord";
final String QUERY_GET_GALLERY_IMAGE_RECORDS_COUNT = "getGalleryImageRecordsCount";
final String QUERY_GET_PREFERENCES_RECORD = "getPreferencesRecord";
final String QUERY_GET_SOCIAL_NETWORKING_INFO = "getSocialNetworkingInfo";
final String QUERY_GET_EXTERNAL_IMAGE_RECORD = "getProfileImageExternalRecord";
//SakaiPersonMeta
final String QUERY_FIND_SAKAI_PERSONS_BY_NAME_OR_EMAIL = "findSakaiPersonsByNameOrEmail";
final String QUERY_FIND_SAKAI_PERSONS_BY_INTEREST = "findSakaiPersonsByInterest";
final String QUERY_FIND_SAKAI_PERSONS_BY_INTEREST_AND_BUSINESS_BIO = "findSakaiPersonsByInterestAndBusinessBio";
final String QUERY_GET_SAKAI_PERSON = "getSakaiPerson";
final String QUERY_GET_ALL_SAKAI_PERSON_IDS = "getAllSakaiPersonIds";
final String QUERY_GET_ALL_SAKAI_PERSON_IDS_COUNT = "getAllSakaiPersonIdsCount";
//ProfileImageOfficial
final String QUERY_GET_OFFICIAL_IMAGE_RECORD = "getProfileImageOfficialRecord";
// from Message.hbm.xml
final String QUERY_GET_ALL_UNREAD_MESSAGES_COUNT = "getAllUnreadMessagesCount";
final String QUERY_GET_THREADS_WITH_UNREAD_MESSAGES_COUNT = "getThreadsWithUnreadMessagesCount";
final String QUERY_GET_MESSAGES_IN_THREAD="getMessagesInThread";
final String QUERY_GET_MESSAGES_IN_THREAD_COUNT="getMessagesInThreadCount";
final String QUERY_GET_MESSAGE="getMessage";
final String QUERY_GET_LATEST_MESSAGE_IN_THREAD = "getLatestMessageInThread";
final String QUERY_GET_MESSAGE_THREADS="getMessageThreads";
final String QUERY_GET_MESSAGE_THREADS_COUNT="getMessageThreadsCount";
final String QUERY_GET_SENT_MESSAGES_COUNT="getSentMessagesCount";
//from MessageThread.hbm.xml
final String QUERY_GET_MESSAGE_THREAD="getMessageThread";
//from MessageRecipient.hbm.xml
final String QUERY_GET_MESSAGE_PARTICIPANT_FOR_MESSAGE_AND_UUID="getMessageParticipantForMessageAndUuid";
final String QUERY_GET_THREAD_PARTICIPANTS="getThreadParticipants";
//from ProfileKudos.hbm.xml
final String QUERY_GET_KUDOS_RECORD="getKudosRecord";
//from ExternalIntegrationInfo.hbm.xml
final String QUERY_GET_EXTERNAL_INTEGRATION_INFO="getExternalIntegrationInfo";
//from WallItem.hbm.xml
final String QUERY_GET_WALL_ITEMS = "getWallItemRecords";
// TODO remove these unused strings
//from WallItemComment.hbm.xml
//final String QUERY_GET_WALL_ITEM_COMMENTS = "getWallItemComments";
//final String QUERY_GET_WALL_ITEMS_COUNT = "getWallItemsCount";
// Hibernate object fields
final String USER_UUID = "userUuid";
final String FRIEND_UUID = "friendUuid";
final String CONFIRMED = "confirmed";
final String OLDEST_STATUS_DATE = "oldestStatusDate";
final String SEARCH = "search";
final String UUID = "uuid";
final String ID = "id";
final String THREAD = "thread";
final String MESSAGE_ID = "messageId";
}
| |
/* JAT: Java Astrodynamics Toolkit
*
* Copyright (c) 2003 National Aeronautics and Space Administration. All rights reserved.
*
* This file is part of JAT. JAT is free software; you can
* redistribute it and/or modify it under the terms of the
* NASA Open Source Agreement
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* NASA Open Source Agreement for more details.
*
* You should have received a copy of the NASA Open Source Agreement
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*
* File Created on May 19, 2003
*/
package jat.coreNOSA.gps_ins.relative;
import jat.coreNOSA.algorithm.estimators.EstSTM;
import jat.coreNOSA.algorithm.estimators.ProcessModel;
import jat.coreNOSA.algorithm.integrators.LinePrinter;
import jat.coreNOSA.cm.Constants;
import jat.coreNOSA.cm.TwoBody;
import jat.coreNOSA.forces.CIRA_ExponentialDrag;
import jat.coreNOSA.forces.J2Gravity;
import jat.coreNOSA.gps.GPS_Constellation;
import jat.coreNOSA.gps.IonoModel;
import jat.coreNOSA.gps.ReceiverFilterModel;
import jat.coreNOSA.gps.URE_Model;
import jat.coreNOSA.gps.filters.DragProcessModel;
import jat.coreNOSA.gps_ins.Derivs;
import jat.coreNOSA.ins.INS_Measurement;
import jat.coreNOSA.ins.INS_MeasurementList;
import jat.coreNOSA.ins.RK4_INS;
import jat.coreNOSA.ins.SIGIAccelFilterModel;
import jat.coreNOSA.ins.SIGIGyroFilterModel;
import jat.coreNOSA.ins.SIMUAccelFilterModel;
import jat.coreNOSA.ins.SIMUGyroFilterModel;
import jat.coreNOSA.math.MathUtils;
import jat.coreNOSA.math.MatrixVector.data.GaussianVector;
import jat.coreNOSA.math.MatrixVector.data.Matrix;
import jat.coreNOSA.math.MatrixVector.data.Quaternion;
import jat.coreNOSA.math.MatrixVector.data.VectorN;
import jat.coreNOSA.timeRef.EarthRef;
import jat.coreNOSA.timeRef.RSW_Frame;
/**
* The RGPS_SIMU_ProcessModel.java Class provides the process model for RGPS/SIMU,
* an RGPS/INS with an improved IMU.
*
* @author
* @version 1.0
*/
public class RGPS_SIMU_ProcessModel implements Derivs, ProcessModel {
private INS_MeasurementList insData;
private SIMUGyroFilterModel gyro = new SIMUGyroFilterModel();
private SIMUAccelFilterModel accel = new SIMUAccelFilterModel();
// private SIGIAccelFilterModel accel = new SIGIAccelFilterModel();
private IonoModel iono = new IonoModel();
private DragProcessModel dragModel = new DragProcessModel();
private ReceiverFilterModel rcvr = new ReceiverFilterModel();
// private JGM3 jgm3 = new JGM3(12,12);
private RK4_INS rk4;
private double dt = 1.0;
// private INS_Measurement insMeas;
private GPS_Constellation gpscon;
private URE_Model ure;
private double t_mjd0 = 51969.0;
private double issMass = 128990.0;
private double issArea = 640.7;
private double issCd = 2.35;
private CIRA_ExponentialDrag ced = new CIRA_ExponentialDrag(this.issCd, this.issArea, this.issMass);
private int issIndex;
private int iaIndex;
private int nsv;
private LinePrinter lp1;
private LinePrinter lp2;
private LinePrinter lp3;
private long seed;
/**
* Constructor
* @param ins INS_MeasurementList
* @param gps GPS_Constellation
* @param l1 LinePrinter for absolute state, covariance output
* @param l2 LinePrinter for relative state, covariance output
* @param l3 LinePrinter for residual output
* @param seed long containing random number seed to be used
*/
public RGPS_SIMU_ProcessModel(INS_MeasurementList ins, GPS_Constellation gps, LinePrinter l1, LinePrinter l2, LinePrinter l3, long sd) {
this.insData = ins;
this.gpscon = gps;
this.nsv = gps.size();
this.issIndex = 19 + this.nsv;
this.iaIndex = 28 + this.nsv;
this.ure = new URE_Model(this.nsv);
this.lp1 = l1;
this.lp2 = l2;
this.lp3 = l3;
this.rk4 = new RK4_INS(this.insData);
}
/**
* return the initial state vector
*/
public VectorN xref0() {
int n = this.numberOfStates();
double d = 15.0/6765.5000;
double theta = 360.0 - d * Constants.rad2deg;
// set initial position, velocity, attitude
TwoBody orbit1 = new TwoBody(Constants.GM_Earth, 6765500.0, 0.0, 51.8, 0.0, 0.0, theta);
TwoBody orbit2 = new TwoBody(Constants.GM_Earth, 6765500.0, 0.0, 51.8, 0.0, 0.0, 0.0);
VectorN r = orbit1.getR();
VectorN v = orbit1.getV();
//perturb ICs
VectorN mean = new VectorN(3);
VectorN sigp = new VectorN(3);
VectorN sigv = new VectorN(3);
sigp.set(10.0);
sigv.set(0.1);
GaussianVector ppert = new GaussianVector(mean, sigp, this.seed);
r = r.plus(ppert);
GaussianVector vpert = new GaussianVector(mean, sigv, (this.seed - 1));
v = v.plus(vpert);
RSW_Frame rsw = new RSW_Frame(r, v);
Matrix Cb2i = rsw.ECI2RSW().transpose();
VectorN out = new VectorN(n);
out.set(0, r);
out.set(3, v);
Quaternion q0 = new Quaternion(Cb2i);
out.set(6, q0);
// set initial gyro bias, assume perfect
out.set(10, 0.0);
out.set(11, 0.0);
out.set(12, 0.0);
// set initial accel bias, assume perfect
out.set(13, 0.0);
out.set(14, 0.0);
out.set(15, 0.0);
// set initial clock bias, assume perfect
out.set(16, 0.0);
out.set(17, 0.0);
// out.set(16, 1.0E-02*con.c);
// out.set(17, 6.7E-07*con.c);
// set initial iono state
out.set(18, 0.0);
// set initial ure states to zero
// set ISS initial states
VectorN rv = orbit2.rv;
// perturb ICs
// rv = rv.plus(pt);
out.set(this.issIndex, rv);
// set initial ISS clock states, integer amb states to zero
return out;
}
/**
* @see jat.coreNOSA.algorithm.estimators.ProcessModel#P0()
*/
public Matrix P0() {
Matrix out = new Matrix(this.numberOfStates());
double sigma_r = 10.0;
double sigma_v = 0.1;
double sigma_q = 0.001;
double sigma_bg = 0.0003 * MathUtils.DEG2RAD / 3600.0;
double sigma_ba = 1.0E-03;
// double sigma_ba = 5.0E-05 * 9.81;
double sigma_bc = 1.0E-06;
double sigma_dc = 1.0E-06;
double sigma2_r = sigma_r * sigma_r;
double sigma2_v = sigma_v * sigma_v;
double sigma2_q = sigma_q * sigma_q;
double sigma2_bg = sigma_bg * sigma_bg;
double sigma2_ba = sigma_ba * sigma_ba;
double sigma2_bc = sigma_bc * sigma_bc;
double sigma2_dc = sigma_dc * sigma_dc;
double sigma2_ure = ure.sigma()*ure.sigma();
double sigma2_iono = iono.sigma * iono.sigma;
// double sigma2_ia = 1.0E+12*GPS_Utils.lambda*GPS_Utils.lambda;
double sigma2_drag = 0.8 * 0.8;
out.set(0, 0, sigma2_r);
out.set(1, 1, sigma2_r);
out.set(2, 2, sigma2_r);
out.set(3, 3, sigma2_v);
out.set(4, 4, sigma2_v);
out.set(5, 5, sigma2_v);
out.set(6, 6, sigma2_q);
out.set(7, 7, sigma2_q);
out.set(8, 8, sigma2_q);
out.set(9, 9, sigma2_q);
out.set(10, 10, sigma2_bg);
out.set(11, 11, sigma2_bg);
out.set(12, 12, sigma2_bg);
out.set(13, 13, sigma2_ba);
out.set(14, 14, sigma2_ba);
out.set(15, 15, sigma2_ba);
out.set(16, 16, sigma2_bc);
out.set(17, 17, sigma2_dc);
out.set(18, 18, sigma2_iono);
for (int i = 0; i < this.nsv; i++){
out.set((i+19),(i+19), sigma2_ure);
out.set((this.iaIndex+i),(this.iaIndex+i), 8.0);
}
int k = this.issIndex;
out.set(k, k, sigma2_r);
out.set(k+1, k+1, sigma2_r);
out.set(k+2, k+2, sigma2_r);
out.set(k+3, k+3, sigma2_v);
out.set(k+4, k+4, sigma2_v);
out.set(k+5, k+5, sigma2_v);
out.set(k+6, k+6, sigma2_bc);
out.set(k+7, k+7, sigma2_dc);
out.set(k+8, k+8, sigma2_drag);
return out;
}
/**
* @see jat.coreNOSA.algorithm.estimators.ProcessModel#numberOfStates()
*/
public int numberOfStates() {
int n = 28 + 2*this.nsv;
return n;
}
/**
* @see jat.coreNOSA.algorithm.integrators.Derivatives#derivs(double, double[])
*/
public double[] derivs(double t, double[] x, INS_Measurement measl_1, INS_Measurement measl, int sw) {
int n = this.numberOfStates();
VectorN out = new VectorN(x.length);
// get the gyro measurements
VectorN dthetal_1 = measl_1.omega;
VectorN dthetal = measl.omega;
// get accelerometer measurements
VectorN dvl_1 = measl_1.f;
VectorN dvl = measl.f;
// strip out the incoming data
VectorN r = new VectorN(x[0], x[1], x[2]);
VectorN v = new VectorN(x[3], x[4], x[5]);
Quaternion q = new Quaternion(x[6], x[7], x[8], x[9]);
q.unitize();
EstSTM stm = new EstSTM(x, n);
Matrix phi = stm.phi();
VectorN bg = new VectorN(x[10], x[11], x[12]);
VectorN ba = new VectorN(x[13], x[14], x[15]);
// strip off clock states
VectorN clock1 = new VectorN(2);
clock1.set(0, x[16]);
clock1.set(1, x[17]);
double del_iono = x[18]; // iono state
// strip off incoming ure states
VectorN urevec = new VectorN(this.nsv);
for (int i = 0; i < this.nsv; i++) {
urevec.set(i, x[i+19]);
}
// strip off ISS states
int kk = this.issIndex;
VectorN rISS = new VectorN(x[kk], x[kk+1], x[kk+2]);
VectorN vISS = new VectorN(x[kk+3], x[kk+4], x[kk+5]);
VectorN clock2 = new VectorN(2);
clock2.set(0, x[kk+6]);
clock2.set(1, x[kk+7]);
double ddrag = x[kk+8];
// Body to inertial DCM
Matrix cib = q.quat2DCM();
// get the IMU measurements
// double t_ins = this.insMeas.t;
// form the appropriate specific force and omega vectors
VectorN f;
VectorN rate;
switch(sw) {
case 0:
f = this.dvl_2(dvl_1, dvl);
rate = this.wl_2(dthetal_1, dthetal);
break;
case 1:
f = this.dvl_1(dvl_1, dvl);
rate = this.wl_1(dthetal_1, dthetal);
break;
case 2:
f = this.dvl_0(dvl_1, dvl);
rate = this.wl_0(dthetal_1, dthetal);
break;
default:
f = new VectorN(3);
rate = new VectorN(3);
break;
}
// compensate for IMU errors
f = f.plus(ba);
rate = rate.plus(bg);
// position derivatives
out.set(0, v);
// velocity derivatives
// TwoBody orbit = new TwoBody(Constants.GM_Earth, r, v);
// VectorN g = orbit.local_grav();
J2Gravity j2chaser = new J2Gravity(r);
VectorN g = j2chaser.local_gravity();
double Mjd = this.t_mjd0 + t/86400.0;
EarthRef ref = new EarthRef(Mjd);
// ref.setIERS(3.3E-07, 1.17E-06, 0.649232);
// Matrix E = ref.eci2ecef();
//
// // Acceleration due to harmonic gravity field
// VectorN g = jgm3.gravity(r, E);
VectorN sf = cib.times(f);
VectorN vdot = sf.plus(g);
out.set(3, vdot);
// quaternion derivatives
Matrix omega = Quaternion.omega(rate);
VectorN qdot = omega.times(q);
out.set(6, qdot);
// gyro bias derivatives
VectorN bgdot = this.gyro.biasProcess(bg);
out.set(10, bgdot);
// accelerometer bias derivatives
VectorN badot = this.accel.biasProcess(ba);
out.set(13, badot);
// GPS clock model derivatives
VectorN bcdot = rcvr.biasProcess(clock1);
out.set(16, bcdot);
// iono derivs
double ionodot = iono.ionoProcess(del_iono);
out.set(18, ionodot);
//ure derivs
VectorN uredot = ure.ureProcess(urevec);
out.set(19, uredot);
// position derivatives
out.set(kk, vISS);
// velocity derivatives
// TwoBody orbit2 = new TwoBody(Constants.GM_Earth, rISS, vISS);
// g = orbit2.local_grav();
J2Gravity j2iss = new J2Gravity(rISS);
g = j2iss.local_gravity();
// g = jgm3.gravity(rISS, E);
// double Mjd = this.t_mjd0 + t/86400.0;
// EarthRef ref = new EarthRef(Mjd);
ced.compute(ref, rISS, vISS);
VectorN drag0 = ced.dragAccel();
double dragfactor = 1.0 + ddrag;
VectorN drag = drag0.times(dragfactor);
vdot = g.plus(drag);
out.set((kk+3), vdot);
// GPS clock model derivatives
VectorN bcdot2 = rcvr.biasProcess(clock2);
out.set((kk+6), bcdot2);
double dragdot = DragProcessModel.dragProcess(ddrag);
out.set((kk+8), dragdot);
// integer ambiguity derivs = 0
// A matrix
Matrix A = new Matrix(n, n);
// position rows
Matrix eye = new Matrix(3);
A.setMatrix(0, 3, eye);
// velocity rows
Matrix G = j2chaser.gravityGradient();
A.setMatrix(3, 0, G);
Matrix abar = this.abar(f);
Matrix atrans = abar.transpose();
Matrix rhat = q.rMatrix();
Matrix rtrans = rhat.transpose();
Matrix d = cib.times(atrans.times(rtrans));
d = d.times(2.0);
A.setMatrix(3, 6, d);
A.setMatrix(3, 13, cib);
// quaternion rows
A.setMatrix(6, 6, omega);
Matrix qmat = q.qMatrix();
A.setMatrix(6, 10, qmat);
// gyro bias rows
Matrix taug = eye.times(-1.0/SIGIGyroFilterModel.correlationTime);
A.setMatrix(10, 10, taug);
// accel bias rows
Matrix taua = eye.times(-1.0/SIGIAccelFilterModel.correlationTime);
A.setMatrix(13, 13, taua);
//clock drift row
A.set(16, 17, 1.0);
// iono row
double tau_iono = -1.0/iono.correlationTime;
A.set(18, 18, tau_iono);
// ure part
Matrix bigeye = new Matrix(this.nsv);
Matrix tau_ure = eye.times(-1.0/URE_Model.correlationTime);
A.setMatrix(19, 19, tau_ure);
// position rows
A.setMatrix(kk, (kk+3), eye);
// velocity rows
G = j2iss.gravityGradient();
Matrix D = ced.partialR().times(dragfactor);
Matrix GD = G.plus(D);
A.setMatrix((kk+3), kk, GD);
D = ced.partialV().times(dragfactor);
A.setMatrix((kk+3),(kk+3), D);
// partials of drag accel wrt drag state
A.set((kk+3),(kk+8), drag0.x[0]);
A.set((kk+4),(kk+8), drag0.x[1]);
A.set((kk+5),(kk+8), drag0.x[2]);
//clock drift row
A.set((kk+6),(kk+7), 1.0);
// drag rows
double tau_drag = -1.0/DragProcessModel.correlationTime;
A.set((kk+8), (kk+8), tau_drag);
// phi derivatives
Matrix phidot = A.times(phi);
// put phi derivatives into output array
int k = n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
out.x[k] = phidot.A[i][j];
k = k + 1;
}
}
return out.x;
}
private Matrix abar(VectorN f) {
f.checkVectorDimensions(3);
double [] x = f.getArray();
Matrix out = new Matrix(4, 3);
out.set(0, 1, -x[2]);
out.set(0, 2, x[1]);
out.set(1, 0, x[2]);
out.set(1, 2, -x[0]);
out.set(2, 0, -x[1]);
out.set(2, 1, x[0]);
out.set(3, 0, -x[0]);
out.set(3, 1, -x[1]);
out.set(3, 2, -x[2]);
return out;
}
/**
* @see jat.coreNOSA.algorithm.estimators.ProcessModel#Q(double, double)
*/
// public Matrix Q(double t, double dt, VectorN x) {
// int n = this.numberOfStates();
// Matrix q = new Matrix(n, n);
//// double sp = 1.0E-03;
//
//// double sp = 1.0E-06;
//
// // blockage tuning
//// double sp = 1.0E-11;
//
// // nominal tuning
//// double sp = 1.0E-06;
//
// // adaptive
// double sp = 0.0;
// if (t < 7200.0) {
// sp = 1.0E-06;
// } else {
// sp = 1.0E-11;
// }
//
//
//
// double sp3 = sp/3.0;
// double sp2 = sp/2.0;
// q.set(0, 0, sp3);
// q.set(1, 1, sp3);
// q.set(2, 2, sp3);
// q.set(3, 3, sp);
// q.set(4, 4, sp);
// q.set(5, 5, sp);
// q.set(0, 3, sp2);
// q.set(1, 4, sp2);
// q.set(2, 5, sp2);
// q.set(3, 0, sp2);
// q.set(4, 1, sp2);
// q.set(5, 2, sp2);
// q.set(6, 6, 1.0E-25);
// q.set(7, 7, 1.0E-25);
// q.set(8, 8, 1.0E-25);
// q.set(9, 9, 1.0E-25);
//
// q.set(10, 10, gyro.biasQ());
// q.set(11, 11, gyro.biasQ());
// q.set(12, 12, gyro.biasQ());
// q.set(13, 13, accel.biasQ());
// q.set(14, 14, accel.biasQ());
// q.set(15, 15, accel.biasQ());
//
// // adaptive
// if (t < 7200.0) {
// q.setMatrix(16, 16, rcvr.biasQ(dt));
// q.set(18, 18, iono.ionoQ(dt));
//
// } else {
// q.setMatrix(16, 16, rcvr.biasQ(dt).times(10.0));
// q.set(18, 18, 10.0*iono.ionoQ(dt));
// }
//
//
// for (int i = 0; i < this.nsv; i++) {
//
// // adaptive
// if (t < 7200.0) {
// q.set((i+19),(i+19), ure.biasQ());
// } else {
// q.set((i+19),(i+19), 10.0*ure.biasQ());
// }
//
// q.set((i+this.iaIndex),(i+this.iaIndex), 1.0E-6*dt);
// }
//
// int kk = this.issIndex;
//
// // nominal tuning
//// sp = 1.0E-05;
//// sp3 = sp/3.0;
//// sp2 = sp/2.0;
//
// q.set(kk, kk, sp3);
// q.set(kk+1, kk+1, sp3);
// q.set(kk+2, kk+2, sp3);
// q.set(kk+3, kk+3, sp);
// q.set(kk+4, kk+4, sp);
// q.set(kk+5, kk+5, sp);
// q.set(kk, kk+3, sp2);
// q.set(kk+1, kk+4, sp2);
// q.set(kk+2, kk+5, sp2);
// q.set(kk+3, kk, sp2);
// q.set(kk+4, kk+1, sp2);
// q.set(kk+5, kk+2, sp2);
//
//
// q.setMatrix(kk+6, kk+6, rcvr.biasQ(dt));
//
// q.set(kk+8, kk+8, dragModel.dragQ(dt));
//
// VectorN r = new VectorN(x.x[0], x.x[1], x.x[2]);
// VectorN v = new VectorN(x.x[3], x.x[4], x.x[5]);
// Quaternion w = new Quaternion(x.x[6], x.x[7], x.x[8], x.x[9]);
//
// RSW_Frame rsw = new RSW_Frame(r, v);
// Matrix Cb2i = rsw.ECI2RSW().transpose();
// Matrix W = w.qMatrix();
//
// Matrix g = new Matrix(n);
// g.setMatrix(3, 13, Cb2i);
// g.setMatrix(6, 10, W);
//// g.print("gmatrix");
//
// Matrix gT = g.transpose();
//
// Matrix out = g.times(q.times(gT));
// return out;
// }
public Matrix Q(double t, double dt, EstSTM stm) {
int n = this.numberOfStates();
VectorN x = stm.state();
Matrix phi = stm.phi();
Matrix phiT = phi.transpose();
VectorN r = new VectorN(x.x[0], x.x[1], x.x[2]);
VectorN v = new VectorN(x.x[3], x.x[4], x.x[5]);
Quaternion w = new Quaternion(x.x[6], x.x[7], x.x[8], x.x[9]);
RSW_Frame rsw = new RSW_Frame(r, v);
Matrix Cb2i = rsw.ECI2RSW().transpose();
Matrix W = w.qMatrix();
Matrix q = new Matrix(n, n);
double accel_sigma = 1.0E-10;
double accel_q = accel_sigma * accel_sigma;
VectorN acc = new VectorN(3);
// double tsw = 7200.0;
// double sp = 0.0;
// if (t < tsw) {
// sp = 1.0E-06;
// }
// else {
double sp = 1.0E-09;
// }
acc.set(accel_q);
VectorN accelx = Cb2i.times(acc);
q.set(3, 3, sp);
q.set(4, 4, sp);
q.set(5, 5, sp);
double gyro_sigma = 7.9E-05 * MathUtils.DEG2RAD; // in rad/rt-hr
double gyro_q = gyro_sigma * gyro_sigma / 3600.0; // in (rad/s)^2/Hz
VectorN gyro_sig = new VectorN(3);
gyro_sig.set(gyro_q);
VectorN gyros = W.times(gyro_sig);
q.set(6, 6, gyros.x[0]);
q.set(7, 7, gyros.x[1]);
q.set(8, 8, gyros.x[2]);
q.set(9, 9, gyros.x[3]);
q.set(10, 10, gyro.Q());
q.set(11, 11, gyro.Q());
q.set(12, 12, gyro.Q());
q.set(13, 13, accel.Q());
q.set(14, 14, accel.Q());
q.set(15, 15, accel.Q());
// adaptive
// if (t < tsw) {
// q.setMatrix(16, 16, rcvr.Q());
// q.set(18, 18, iono.Q());
//
// } else {
q.setMatrix(16, 16, rcvr.biasQ(dt).times(10.0));
q.set(18, 18, 10.0*iono.ionoQ(dt));
// }
for (int i = 0; i < this.nsv; i++) {
// adaptive
// if (t < tsw) {
// q.set((i+19),(i+19), ure.Q());
// } else {
q.set((i+19),(i+19), 10.0*ure.Q());
// }
q.set((i+this.iaIndex),(i+this.iaIndex), 1.0E-6);
}
int kk = this.issIndex;
q.set(kk+3, kk+3, sp);
q.set(kk+4, kk+4, sp);
q.set(kk+5, kk+5, sp);
q.setMatrix(kk+6, kk+6, rcvr.Q());
q.set(kk+8, kk+8, DragProcessModel.Q());
// Relative Nav correlation
double rho = 0.99;
Matrix qab = new Matrix(6, 6);
for (int i = 0; i < 6; i++) {
double qa = q.get(i, i);
double qb = q.get(kk+i, kk+i);
double val = rho * Math.sqrt(qa * qb);
q.set(i, (kk+i), val);
q.set((kk+i), i, val);
}
Matrix g = new Matrix(n);
g.setMatrix(3, 13, Cb2i);
g.setMatrix(6, 10, W);
// g.print("gmatrix");
Matrix gT = g.transpose();
Matrix temp = g.times(q.times(gT));
Matrix out = stm.phi().times(temp.times(phiT));
out = out.times(dt);
return out;
}
/**
* @see jat.coreNOSA.algorithm.estimators.ProcessModel#propagate(double, double[], double)
*/
public double[] propagate(double t0, double[] xin, double tf) {
if ((tf - t0) != dt) {
System.out.println("propagate step size messed up");
}
// fix the attitude quaternion
EstSTM x = new EstSTM(xin, this.numberOfStates());
VectorN q = this.getQuat(x);
q.unitize();
x.setState(6, q);
double [] xold = x.longarray();
double [] xnew = x.longarray();
// propagate
xnew = rk4.step(t0, xold, this);
// fix the attitude quaternion again
EstSTM y = new EstSTM(xnew, this.numberOfStates());
q = this.getQuat(y);
q.unitize();
y.setState(6, q);
double [] out = y.longarray();
return out;
}
public VectorN getQuat(EstSTM x){
VectorN q = x.get(6, 4);
return q;
}
/**
* Print output
* @param t sim time in seconds
* @param state VectorN containing the state vector
* @param cov Matrix containing the covariance matrix
*/
public void print(double t, VectorN state, Matrix cov) {
// absolute state processing
VectorN sigmas = cov.diagonal();
sigmas = sigmas.ebeSqrt();
VectorN printvector = new VectorN(state, sigmas);
lp1.print(t, printvector.x);
// relative state processing
VectorN r_chaser = state.get(0,3);
VectorN v_chaser = state.get(3,3);
VectorN r_iss = state.get(this.issIndex,3);
VectorN v_iss = state.get(this.issIndex+3,3);
RSW_Frame rsw = new RSW_Frame(r_iss, v_iss);
VectorN r_rel = r_chaser.minus(r_iss);
VectorN v_rel = v_chaser.minus(v_iss);
VectorN rv_rel = rsw.transform(r_rel, v_rel);
Matrix p_chaser = cov.getMatrix(0, 5, 0, 5);
Matrix p_iss = cov.getMatrix(this.issIndex, this.issIndex+5,this.issIndex, this.issIndex+5);
Matrix p_a = cov.getMatrix(0, 5, this.issIndex, this.issIndex+5);
Matrix p_b = cov.getMatrix(this.issIndex, this.issIndex+5, 0, 5);
Matrix temp1 = p_chaser.plus(p_iss);
Matrix temp2 = p_a.plus(p_b);
Matrix p_rel = temp1.minus(temp2);
Matrix eci2rsw = rsw.ECI2RSW();
Matrix T = new Matrix(6,6);
T.setMatrix(0, 0, eci2rsw);
T.setMatrix(3, 3, eci2rsw);
Matrix Ttrans = T.transpose();
Matrix temp3 = p_rel.times(Ttrans);
Matrix p_rsw = T.times(temp3);
sigmas = p_rsw.diagonal();
sigmas = sigmas.ebeSqrt();
printvector = new VectorN(rv_rel, sigmas);
lp2.print(t, printvector.x);
}
/**
* Print residuals
* @param t sim time in seconds
* @param r1 residual before measurement update
* @param r2 residual after measurement update
*/
public void printResiduals(double t, double r1, double r2) {
double[] y = new double[3];
y[0] = t;
y[1] = r1;
y[2] = r2;
lp3.print(y);
}
/**
* close the LinePrinters
*/
public void closeLinePrinter(){
lp1.close();
lp2.close();
lp3.close();
}
private VectorN wl_0 (VectorN dthetal_1, VectorN dthetal_0){
VectorN part1 = dthetal_0.times(3.0);
VectorN w = part1.minus(dthetal_1);
return w;
}
private VectorN wl_1 (VectorN dthetal_1, VectorN dthetal_0){
VectorN w = dthetal_0.plus(dthetal_1);
return w;
}
private VectorN wl_2 (VectorN dthetal_1, VectorN dthetal_0){
VectorN part1 = dthetal_1.times(3.0);
VectorN w = part1.minus(dthetal_0);
return w;
}
private VectorN dvl_0 (VectorN dvl_1, VectorN dvl_0){
VectorN part1 = dvl_0.times(3.0);
VectorN out = part1.minus(dvl_1);
return out;
}
private VectorN dvl_1 (VectorN dvl_1, VectorN dvl_0){
VectorN out = dvl_0.plus(dvl_1);
return out;
}
private VectorN dvl_2 (VectorN dvl_1, VectorN dvl_0){
VectorN part1 = dvl_1.times(3.0);
VectorN out = part1.minus(dvl_0);
return out;
}
}
| |
/* 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.flowable.bpmn.converter.util;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.constants.BpmnXMLConstants;
import org.flowable.bpmn.converter.child.BaseChildElementParser;
import org.flowable.bpmn.converter.child.CancelEventDefinitionParser;
import org.flowable.bpmn.converter.child.CompensateEventDefinitionParser;
import org.flowable.bpmn.converter.child.ConditionExpressionParser;
import org.flowable.bpmn.converter.child.ConditionParser;
import org.flowable.bpmn.converter.child.ConditionalEventDefinitionParser;
import org.flowable.bpmn.converter.child.DataInputAssociationParser;
import org.flowable.bpmn.converter.child.DataOutputAssociationParser;
import org.flowable.bpmn.converter.child.DataStateParser;
import org.flowable.bpmn.converter.child.DocumentationParser;
import org.flowable.bpmn.converter.child.ErrorEventDefinitionParser;
import org.flowable.bpmn.converter.child.EscalationEventDefinitionParser;
import org.flowable.bpmn.converter.child.ExecutionListenerParser;
import org.flowable.bpmn.converter.child.FieldExtensionParser;
import org.flowable.bpmn.converter.child.FlowNodeRefParser;
import org.flowable.bpmn.converter.child.FlowableEventListenerParser;
import org.flowable.bpmn.converter.child.FlowableFailedjobRetryParser;
import org.flowable.bpmn.converter.child.FlowableHttpRequestHandlerParser;
import org.flowable.bpmn.converter.child.FlowableHttpResponseHandlerParser;
import org.flowable.bpmn.converter.child.FlowableMapExceptionParser;
import org.flowable.bpmn.converter.child.FormPropertyParser;
import org.flowable.bpmn.converter.child.IOSpecificationParser;
import org.flowable.bpmn.converter.child.MessageEventDefinitionParser;
import org.flowable.bpmn.converter.child.MultiInstanceParser;
import org.flowable.bpmn.converter.child.SignalEventDefinitionParser;
import org.flowable.bpmn.converter.child.TaskListenerParser;
import org.flowable.bpmn.converter.child.TerminateEventDefinitionParser;
import org.flowable.bpmn.converter.child.TimeCycleParser;
import org.flowable.bpmn.converter.child.TimeDateParser;
import org.flowable.bpmn.converter.child.TimeDurationParser;
import org.flowable.bpmn.converter.child.TimerEventDefinitionParser;
import org.flowable.bpmn.model.BaseElement;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.ExtensionAttribute;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.GraphicInfo;
import org.flowable.bpmn.model.IOParameter;
public class BpmnXMLUtil implements BpmnXMLConstants {
private static Map<String, BaseChildElementParser> genericChildParserMap = new HashMap<>();
static {
addGenericParser(new CancelEventDefinitionParser());
addGenericParser(new CompensateEventDefinitionParser());
addGenericParser(new ConditionalEventDefinitionParser());
addGenericParser(new ConditionParser());
addGenericParser(new ConditionExpressionParser());
addGenericParser(new DataInputAssociationParser());
addGenericParser(new DataOutputAssociationParser());
addGenericParser(new DataStateParser());
addGenericParser(new DocumentationParser());
addGenericParser(new ErrorEventDefinitionParser());
addGenericParser(new EscalationEventDefinitionParser());
addGenericParser(new ExecutionListenerParser());
addGenericParser(new FieldExtensionParser());
addGenericParser(new FlowableEventListenerParser());
addGenericParser(new FlowableHttpRequestHandlerParser());
addGenericParser(new FlowableHttpResponseHandlerParser());
addGenericParser(new FormPropertyParser());
addGenericParser(new IOSpecificationParser());
addGenericParser(new MessageEventDefinitionParser());
addGenericParser(new MultiInstanceParser());
addGenericParser(new SignalEventDefinitionParser());
addGenericParser(new TaskListenerParser());
addGenericParser(new TerminateEventDefinitionParser());
addGenericParser(new TimerEventDefinitionParser());
addGenericParser(new TimeDateParser());
addGenericParser(new TimeCycleParser());
addGenericParser(new TimeDurationParser());
addGenericParser(new FlowNodeRefParser());
addGenericParser(new FlowableFailedjobRetryParser());
addGenericParser(new FlowableMapExceptionParser());
}
private static void addGenericParser(BaseChildElementParser parser) {
genericChildParserMap.put(parser.getElementName(), parser);
}
public static void addXMLLocation(BaseElement element, XMLStreamReader xtr) {
Location location = xtr.getLocation();
element.setXmlRowNumber(location.getLineNumber());
element.setXmlColumnNumber(location.getColumnNumber());
}
public static void addXMLLocation(GraphicInfo graphicInfo, XMLStreamReader xtr) {
Location location = xtr.getLocation();
graphicInfo.setXmlRowNumber(location.getLineNumber());
graphicInfo.setXmlColumnNumber(location.getColumnNumber());
}
public static void parseChildElements(String elementName, BaseElement parentElement, XMLStreamReader xtr, BpmnModel model) throws Exception {
parseChildElements(elementName, parentElement, xtr, null, model);
}
public static void parseChildElements(String elementName, BaseElement parentElement, XMLStreamReader xtr,
Map<String, BaseChildElementParser> childParsers, BpmnModel model) throws Exception {
Map<String, BaseChildElementParser> localParserMap = new HashMap<>(genericChildParserMap);
if (childParsers != null) {
localParserMap.putAll(childParsers);
}
boolean inExtensionElements = false;
boolean readyWithChildElements = false;
while (!readyWithChildElements && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement()) {
if (ELEMENT_EXTENSIONS.equals(xtr.getLocalName())) {
inExtensionElements = true;
} else if (localParserMap.containsKey(xtr.getLocalName())) {
BaseChildElementParser childParser = localParserMap.get(xtr.getLocalName());
// if we're into an extension element but the current element is not accepted by this parentElement then is read as a custom extension element
if (inExtensionElements && !childParser.accepts(parentElement)) {
ExtensionElement extensionElement = BpmnXMLUtil.parseExtensionElement(xtr);
parentElement.addExtensionElement(extensionElement);
continue;
}
localParserMap.get(xtr.getLocalName()).parseChildElement(xtr, parentElement, model);
} else if (inExtensionElements) {
ExtensionElement extensionElement = BpmnXMLUtil.parseExtensionElement(xtr);
parentElement.addExtensionElement(extensionElement);
}
} else if (xtr.isEndElement()) {
if (ELEMENT_EXTENSIONS.equals(xtr.getLocalName())) {
inExtensionElements = false;
}
if (elementName.equalsIgnoreCase(xtr.getLocalName())) {
readyWithChildElements = true;
}
}
}
}
public static ExtensionElement parseExtensionElement(XMLStreamReader xtr) throws Exception {
ExtensionElement extensionElement = new ExtensionElement();
extensionElement.setName(xtr.getLocalName());
if (StringUtils.isNotEmpty(xtr.getNamespaceURI())) {
extensionElement.setNamespace(xtr.getNamespaceURI());
}
if (StringUtils.isNotEmpty(xtr.getPrefix())) {
extensionElement.setNamespacePrefix(xtr.getPrefix());
}
for (int i = 0; i < xtr.getAttributeCount(); i++) {
ExtensionAttribute extensionAttribute = new ExtensionAttribute();
extensionAttribute.setName(xtr.getAttributeLocalName(i));
extensionAttribute.setValue(xtr.getAttributeValue(i));
if (StringUtils.isNotEmpty(xtr.getAttributeNamespace(i))) {
extensionAttribute.setNamespace(xtr.getAttributeNamespace(i));
}
if (StringUtils.isNotEmpty(xtr.getAttributePrefix(i))) {
extensionAttribute.setNamespacePrefix(xtr.getAttributePrefix(i));
}
extensionElement.addAttribute(extensionAttribute);
}
boolean readyWithExtensionElement = false;
while (!readyWithExtensionElement && xtr.hasNext()) {
xtr.next();
if (xtr.isCharacters() || XMLStreamReader.CDATA == xtr.getEventType()) {
if (StringUtils.isNotEmpty(xtr.getText().trim())) {
extensionElement.setElementText(xtr.getText().trim());
}
} else if (xtr.isStartElement()) {
ExtensionElement childExtensionElement = parseExtensionElement(xtr);
extensionElement.addChildElement(childExtensionElement);
} else if (xtr.isEndElement() && extensionElement.getName().equalsIgnoreCase(xtr.getLocalName())) {
readyWithExtensionElement = true;
}
}
return extensionElement;
}
public static String getAttributeValue(String attributeName, XMLStreamReader xtr) {
String attributeValue = xtr.getAttributeValue(FLOWABLE_EXTENSIONS_NAMESPACE, attributeName);
if (attributeValue == null) {
attributeValue = xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, attributeName);
}
return attributeValue;
}
public static void writeDefaultAttribute(String attributeName, String value, XMLStreamWriter xtw) throws Exception {
if (StringUtils.isNotEmpty(value) && !"null".equalsIgnoreCase(value)) {
xtw.writeAttribute(attributeName, value);
}
}
public static void writeQualifiedAttribute(String attributeName, String value, XMLStreamWriter xtw) throws Exception {
if (StringUtils.isNotEmpty(value)) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, attributeName, value);
}
}
public static boolean writeExtensionElements(BaseElement baseElement, boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception {
return writeExtensionElements(baseElement, didWriteExtensionStartElement, null, xtw);
}
public static boolean writeExtensionElements(BaseElement baseElement, boolean didWriteExtensionStartElement, Map<String, String> namespaceMap, XMLStreamWriter xtw) throws Exception {
if (!baseElement.getExtensionElements().isEmpty()) {
if (!didWriteExtensionStartElement) {
xtw.writeStartElement(ELEMENT_EXTENSIONS);
didWriteExtensionStartElement = true;
}
if (namespaceMap == null) {
namespaceMap = new HashMap<>();
}
for (List<ExtensionElement> extensionElements : baseElement.getExtensionElements().values()) {
for (ExtensionElement extensionElement : extensionElements) {
writeExtensionElement(extensionElement, namespaceMap, xtw);
}
}
}
return didWriteExtensionStartElement;
}
protected static void writeExtensionElement(ExtensionElement extensionElement, Map<String, String> namespaceMap, XMLStreamWriter xtw) throws Exception {
if (StringUtils.isNotEmpty(extensionElement.getName())) {
Map<String, String> localNamespaceMap = new HashMap<>();
if (StringUtils.isNotEmpty(extensionElement.getNamespace())) {
if (StringUtils.isNotEmpty(extensionElement.getNamespacePrefix())) {
xtw.writeStartElement(extensionElement.getNamespacePrefix(), extensionElement.getName(), extensionElement.getNamespace());
if (!namespaceMap.containsKey(extensionElement.getNamespacePrefix()) || !namespaceMap.get(extensionElement.getNamespacePrefix()).equals(extensionElement.getNamespace())) {
xtw.writeNamespace(extensionElement.getNamespacePrefix(), extensionElement.getNamespace());
namespaceMap.put(extensionElement.getNamespacePrefix(), extensionElement.getNamespace());
localNamespaceMap.put(extensionElement.getNamespacePrefix(), extensionElement.getNamespace());
}
} else {
xtw.writeStartElement(extensionElement.getNamespace(), extensionElement.getName());
}
} else {
xtw.writeStartElement(extensionElement.getName());
}
for (List<ExtensionAttribute> attributes : extensionElement.getAttributes().values()) {
for (ExtensionAttribute attribute : attributes) {
if (StringUtils.isNotEmpty(attribute.getName()) && attribute.getValue() != null) {
if (StringUtils.isNotEmpty(attribute.getNamespace())) {
if (StringUtils.isNotEmpty(attribute.getNamespacePrefix())) {
if (!namespaceMap.containsKey(attribute.getNamespacePrefix()) || !namespaceMap.get(attribute.getNamespacePrefix()).equals(attribute.getNamespace())) {
xtw.writeNamespace(attribute.getNamespacePrefix(), attribute.getNamespace());
namespaceMap.put(attribute.getNamespacePrefix(), attribute.getNamespace());
localNamespaceMap.put(attribute.getNamespacePrefix(), attribute.getNamespace());
}
xtw.writeAttribute(attribute.getNamespacePrefix(), attribute.getNamespace(), attribute.getName(), attribute.getValue());
} else {
xtw.writeAttribute(attribute.getNamespace(), attribute.getName(), attribute.getValue());
}
} else {
xtw.writeAttribute(attribute.getName(), attribute.getValue());
}
}
}
}
if (extensionElement.getElementText() != null) {
xtw.writeCData(extensionElement.getElementText());
} else {
for (List<ExtensionElement> childElements : extensionElement.getChildElements().values()) {
for (ExtensionElement childElement : childElements) {
writeExtensionElement(childElement, namespaceMap, xtw);
}
}
}
for (String prefix : localNamespaceMap.keySet()) {
namespaceMap.remove(prefix);
}
xtw.writeEndElement();
}
}
public static boolean writeIOParameters(String elementName, List<IOParameter> parameterList, boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception {
if (parameterList.isEmpty()) {
return didWriteExtensionStartElement;
}
for (IOParameter ioParameter : parameterList) {
if (!didWriteExtensionStartElement) {
xtw.writeStartElement(ELEMENT_EXTENSIONS);
didWriteExtensionStartElement = true;
}
xtw.writeStartElement(FLOWABLE_EXTENSIONS_PREFIX, elementName, FLOWABLE_EXTENSIONS_NAMESPACE);
if (StringUtils.isNotEmpty(ioParameter.getSourceExpression())) {
writeDefaultAttribute(ATTRIBUTE_IOPARAMETER_SOURCE_EXPRESSION, ioParameter.getSourceExpression(), xtw);
} else if (StringUtils.isNotEmpty(ioParameter.getSource())) {
writeDefaultAttribute(ATTRIBUTE_IOPARAMETER_SOURCE, ioParameter.getSource(), xtw);
}
if (StringUtils.isNotEmpty(ioParameter.getAttributeValue(null, "sourceType"))) {
writeDefaultAttribute("sourceType", ioParameter.getAttributeValue(null, "sourceType"), xtw);
}
if (StringUtils.isNotEmpty(ioParameter.getTargetExpression())) {
writeDefaultAttribute(ATTRIBUTE_IOPARAMETER_TARGET_EXPRESSION, ioParameter.getTargetExpression(), xtw);
} else if (StringUtils.isNotEmpty(ioParameter.getTarget())) {
writeDefaultAttribute(ATTRIBUTE_IOPARAMETER_TARGET, ioParameter.getTarget(), xtw);
}
if (StringUtils.isNotEmpty(ioParameter.getAttributeValue(null, "targetType"))) {
writeDefaultAttribute("targetType", ioParameter.getAttributeValue(null, "targetType"), xtw);
}
if (ioParameter.isTransient()) {
writeDefaultAttribute(ATTRIBUTE_IOPARAMETER_TRANSIENT, "true", xtw);
}
xtw.writeEndElement();
}
return didWriteExtensionStartElement;
}
public static List<String> parseDelimitedList(String s) {
List<String> result = new ArrayList<>();
if (StringUtils.isNotEmpty(s)) {
StringCharacterIterator iterator = new StringCharacterIterator(s);
char c = iterator.first();
StringBuilder strb = new StringBuilder();
boolean insideExpression = false;
while (c != StringCharacterIterator.DONE) {
if (c == '{' || c == '$') {
insideExpression = true;
} else if (c == '}') {
insideExpression = false;
} else if (c == ',' && !insideExpression) {
result.add(strb.toString().trim());
strb.delete(0, strb.length());
}
if (c != ',' || insideExpression) {
strb.append(c);
}
c = iterator.next();
}
if (strb.length() > 0) {
result.add(strb.toString().trim());
}
}
return result;
}
public static String convertToDelimitedString(List<String> stringList) {
StringBuilder resultString = new StringBuilder();
if (stringList != null) {
for (String result : stringList) {
if (resultString.length() > 0) {
resultString.append(",");
}
resultString.append(result);
}
}
return resultString.toString();
}
/**
* add all attributes from XML to element extensionAttributes (except blackListed).
*
* @param xtr
* @param element
* @param blackLists
*/
public static void addCustomAttributes(XMLStreamReader xtr, BaseElement element, List<ExtensionAttribute>... blackLists) {
for (int i = 0; i < xtr.getAttributeCount(); i++) {
ExtensionAttribute extensionAttribute = new ExtensionAttribute();
extensionAttribute.setName(xtr.getAttributeLocalName(i));
extensionAttribute.setValue(xtr.getAttributeValue(i));
if (StringUtils.isNotEmpty(xtr.getAttributeNamespace(i))) {
extensionAttribute.setNamespace(xtr.getAttributeNamespace(i));
}
if (StringUtils.isNotEmpty(xtr.getAttributePrefix(i))) {
extensionAttribute.setNamespacePrefix(xtr.getAttributePrefix(i));
}
if (!isBlacklisted(extensionAttribute, blackLists)) {
element.addAttribute(extensionAttribute);
}
}
}
public static void writeCustomAttributes(Collection<List<ExtensionAttribute>> attributes, XMLStreamWriter xtw, List<ExtensionAttribute>... blackLists) throws XMLStreamException {
writeCustomAttributes(attributes, xtw, new LinkedHashMap<>(), blackLists);
}
/**
* write attributes to xtw (except blacklisted)
*
* @param attributes
* @param xtw
* @param namespaceMap
* @param blackLists
*/
public static void writeCustomAttributes(Collection<List<ExtensionAttribute>> attributes, XMLStreamWriter xtw, Map<String, String> namespaceMap, List<ExtensionAttribute>... blackLists)
throws XMLStreamException {
for (List<ExtensionAttribute> attributeList : attributes) {
if (attributeList != null && !attributeList.isEmpty()) {
for (ExtensionAttribute attribute : attributeList) {
if (!isBlacklisted(attribute, blackLists)) {
if (attribute.getNamespacePrefix() == null) {
if (attribute.getNamespace() == null)
xtw.writeAttribute(attribute.getName(), attribute.getValue());
else {
xtw.writeAttribute(attribute.getNamespace(), attribute.getName(), attribute.getValue());
}
} else {
if (!namespaceMap.containsKey(attribute.getNamespacePrefix())) {
namespaceMap.put(attribute.getNamespacePrefix(), attribute.getNamespace());
xtw.writeNamespace(attribute.getNamespacePrefix(), attribute.getNamespace());
}
xtw.writeAttribute(attribute.getNamespacePrefix(), attribute.getNamespace(), attribute.getName(), attribute.getValue());
}
}
}
}
}
}
public static boolean isBlacklisted(ExtensionAttribute attribute, List<ExtensionAttribute>... blackLists) {
if (blackLists != null) {
for (List<ExtensionAttribute> blackList : blackLists) {
for (ExtensionAttribute blackAttribute : blackList) {
if (blackAttribute.getName().equals(attribute.getName())) {
if (attribute.getNamespace() != null && (FLOWABLE_EXTENSIONS_NAMESPACE.equals(attribute.getNamespace()) ||
ACTIVITI_EXTENSIONS_NAMESPACE.equals(attribute.getNamespace()))) {
return true;
}
if (blackAttribute.getNamespace() == null && attribute.getNamespace() == null) {
return true;
}
}
}
}
}
return false;
}
}
| |
/*
* The MIT License
*
* Copyright 2021 Y.K. Chan
*
* 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 jacobi.core.sym.parser;
import java.text.ParseException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import jacobi.core.lexer.ItemLexer;
import jacobi.core.sym.Add;
import jacobi.core.sym.Const;
import jacobi.core.sym.Expr;
import jacobi.core.sym.Inv;
import jacobi.core.sym.Mul;
import jacobi.core.sym.Neg;
import jacobi.core.sym.Pow;
import jacobi.core.sym.Var;
/**
*
* Implementation of parser of mathematical Expr.
*
* <p>
* This class accept the most basic and common form of syntax for mathematical expression.<br>
* The syntax can be defined in ENBF:<br>
* <br>
* <element> := number|idfr|(<expr>)|idfr(<expr>{,<expr>})<br>
* <exp> := <element>{^<element>}<br>
* <product> := <exp>{*<exp> | /<exp>}<br>
* <expr> := <exp>{+<exp> | -<exp>}<br>
* </p>
*
* @author Y.K. Chan
*
*/
public class Parser implements ItemLexer<Expr> {
/**
* Parsing a string of symbolic expression
* @param expr String of symbolic expression
* @return Symbolic expression
* @throws ParseException when syntax error is found
*/
public static Expr parse(String expr) throws ParseException {
Parser parser = new Parser(Tokenizer::new);
for(int i = 0; i < expr.length(); i++){
char ch = expr.charAt(i);
Action action = parser.push(ch);
switch(action){
case ACCEPT:
throw new ParseException("Expr has ended", i);
case MOVE:
break;
default:
throw new ParseException("Error found at " + i + " in " + expr, i);
}
}
if(parser.push('\0') != Action.ACCEPT){
throw new ParseException("Un-expected end of Expr", expr.length());
}
return parser.get()
.orElseThrow(() -> new IllegalStateException("Invalid parser state " + parser.state));
}
/**
* Constructor.
* @param factory Tokenizer factory
*/
public Parser(Supplier<ItemLexer<Token>> factory) {
this.factory = factory;
this.state = State.INIT;
}
@Override
public Optional<Expr> get() {
if(this.state != State.END){
return Optional.empty();
}
if(this.stack.isEmpty()){
throw new IllegalStateException("No Expr parsed.");
}
if(this.stack.size() > 1){
throw new IllegalStateException("Un-expected end of Expr.");
}
Expr expr = this.stack.peek().expr;
return Optional.of(expr);
}
@Override
public Action push(char ch) {
if(this.lexer == null){
this.lexer = this.factory.get();
}
Action action = this.lexer.push(ch);
if(action != Action.ACCEPT){
return action;
}
Token token = this.lexer.get()
.orElseThrow(() -> new IllegalStateException("Tokenizer " + this.lexer + " accepted with no token"));
Action next = this.push(token);
switch(next){
case MOVE:
break;
case FAIL:
return next;
default:
throw new IllegalStateException();
}
if(ch == '\0'){
return this.push(Token.END);
}
this.lexer = this.factory.get();
this.lexer.push(ch);
return next;
}
/**
* Push down a token
* @param token Input token
* @return Action to take
*/
protected Action push(Token token) {
State next = this.state.jump(this, token);
this.state = next;
return next == State.END ? Action.ACCEPT : Action.MOVE;
}
/**
* Convert a token to a constant
* @param token Input token
* @return Constant value
*/
protected Const<?> toConst(Token token) {
if(token.type != Token.Type.CONST){
throw new IllegalArgumentException("Token " + token + " is not a constant.");
}
String val = token.value;
if(val.indexOf('.') >= 0){
double v = Double.parseDouble(val);
return v == 0.0 ? Const.ZERO : v == 1.0 ? Const.ONE : Const.of(v);
}
if(val.length() < 10){
int v = Integer.parseInt(val);
return v == 0 ? Const.ZERO : v == 1 ? Const.ONE : Const.of(v);
}
long v = Long.parseLong(val);
return v == 0L ? Const.ZERO : v == 1L ? Const.ONE : Const.of(v);
}
/**
* Get the top element of the current stack
* @return Top element
*/
protected Element peek() {
return this.stack.peek();
}
/**
* Get the current state of the parser
* @return Current state
*/
protected State getState() {
return this.state;
}
private Supplier<ItemLexer<Token>> factory;
private ItemLexer<Token> lexer;
private Deque<Element> stack;
private State state;
/**
* Parser state
*
* @author Y.K. Chan
*
*/
protected enum State {
/**
* Initializing
*/
INIT {
@Override
public State jump(Parser parser, Token token) {
parser.stack = new ArrayDeque<>();
return BEGIN_ELEMENT.jump(parser, token);
}
},
/**
* Before a new element
*/
BEGIN_ELEMENT {
@Override
public State jump(Parser parser, Token token) {
Deque<Element> stack = parser.stack;
switch(token.type){
case CONST: {
Const<?> item = parser.toConst(token);
stack.push(new Element('\0', item));
}
return END_ELEMENT;
case IDFR: {
Var var = Var.of(token.value);
stack.push(new Element('\0', var));
}
return INVOKE_FUNC;
case DLMR:
if("(".equals(token.value)){
stack.push(new Element('(', null));
return BEGIN_SUM;
}
break;
case OPRT:
if("+".equals(token.value)){
// ignore positive sign
return this;
}
if("-".equals(token.value)){
// negation operator
stack.push(new Element('!', null));
return this;
}
break;
default:
break;
}
return FAIL;
}
},
/**
* After an identifier, determine if element is a variable or function call
*/
INVOKE_FUNC {
@Override
public State jump(Parser parser, Token token) {
if(!"(".equals(token.value)){
return END_ELEMENT.jump(parser, token);
}
Deque<Element> stack = parser.stack;
Element elem = stack.pop();
stack.push(new Element('(', elem.expr));
return BEGIN_SUM;
}
},
/**
* After the end of an element
*/
END_ELEMENT {
@Override
public State jump(Parser parser, Token token) {
Deque<Element> stack = parser.stack;
Expr expr = stack.pop().expr;
if("^".equals(token.value)){
stack.push(new Element('^', expr));
return BEGIN_ELEMENT;
}
stack.push(new Element('\0', expr));
return END_EXPONENTIALS.jump(parser, token);
}
},
/**
* Before a composite exponential expression
*/
BEGIN_EXPONENTIALS {
@Override
public State jump(Parser parser, Token token) {
return BEGIN_ELEMENT.jump(parser, token);
}
},
/**
* After a composite exponential expression
*/
END_EXPONENTIALS {
@Override
public State jump(Parser parser, Token token) {
Deque<Element> stack = parser.stack;
Expr expr = stack.pop().expr;
while(!stack.isEmpty()){
char suffix = stack.peek().suffix;
if(suffix != '^' && suffix != '!'){
break;
}
Element elem = stack.pop();
if(suffix == '^'){
expr = Pow.of(elem.expr, expr);
}
if(suffix == '!'){
expr = new Neg(expr);
}
}
expr = this.pop(stack, expr);
if("*".equals(token.value) || "/".equals(token.value)){
char suffix = token.value.charAt(0);
stack.push(new Element(suffix, expr));
return BEGIN_EXPONENTIALS;
}
stack.push(new Element('\0', expr));
return END_PRODUCT.jump(parser, token);
}
protected Expr pop(Deque<Element> stack, Expr right) {
if(stack.isEmpty()){
return right;
}
if(stack.peek().suffix == '*'){
Expr left = stack.pop().expr;
return Mul.of(left, right);
}
if(stack.peek().suffix == '/'){
Expr left = stack.pop().expr;
return Mul.of(left, new Inv(right));
}
return right;
}
},
/**
* Before a composite product
*/
BEGIN_PRODUCT {
@Override
public State jump(Parser parser, Token token) {
return BEGIN_EXPONENTIALS.jump(parser, token);
}
},
/**
* After a composite product
*/
END_PRODUCT {
@Override
public State jump(Parser parser, Token token) {
Deque<Element> stack = parser.stack;
Expr expr = stack.pop().expr;
expr = this.pop(stack, expr);
if("+".equals(token.value) || "-".equals(token.value)){
char op = token.value.charAt(0);
stack.push(new Element(op, expr));
return BEGIN_PRODUCT;
}
stack.push(new Element('\0', expr));
return END_SUM.jump(parser, token);
}
protected Expr pop(Deque<Element> stack, Expr right) {
if(stack.isEmpty()){
return right;
}
if(stack.peek().suffix == '+'){
Expr left = stack.pop().expr;
return Add.of(left, right);
}
if(stack.peek().suffix == '-'){
Expr left = stack.pop().expr;
return Add.of(left, new Neg(right));
}
return right;
}
},
/**
* Before a composite sum
*/
BEGIN_SUM {
@Override
public State jump(Parser parser, Token token) {
return BEGIN_PRODUCT.jump(parser, token);
}
},
/**
* After a composite product
*/
END_SUM {
@Override
public State jump(Parser parser, Token token) {
Deque<Element> stack = parser.stack;
Expr expr = stack.pop().expr;
if(",".equals(token.value)){
stack.push(new Element(',', expr));
return BEGIN_SUM;
}
if(")".equals(token.value)){
expr = this.popAll(stack, expr);
stack.push(new Element('\0', expr));
return expr == null ? FAIL : END_ELEMENT;
}
stack.push(new Element('\0', expr));
return END;
}
protected Expr popAll(Deque<Element> stack, Expr right) {
List<Expr> args = new ArrayList<>();
args.add(right);
Element bracket = null;
while(!stack.isEmpty()){
Element elem = stack.pop();
if(elem.suffix == '('){
bracket = elem;
break;
}
args.add(elem.expr);
}
if(bracket == null){
return null;
}
if(bracket.expr instanceof Var){
// function call
Collections.reverse(args);
// ...
}
if(args.size() > 1){
return null;
}
return right;
}
},
/**
* Parser has failed
*/
FAIL {
@Override
public State jump(Parser parser, Token token) {
throw new UnsupportedOperationException("Parser has failed.");
}
},
/**
* Parser is ended
*/
END {
@Override
public State jump(Parser parser, Token token) {
throw new UnsupportedOperationException("Parser is ended.");
}
};
public abstract State jump(Parser parser, Token token);
}
/**
* Data class for an element in the parsing stack
*
* @author Y.K. Chan
*
*/
protected static class Element {
/**
* Operator following the expression
*/
public final char suffix;
/**
* Symbolic expression
*/
public final Expr expr;
/**
* Constructor.
* @param suffix Operator following the expression
* @param expr Symbolic expression
*/
public Element(char suffix, Expr expr) {
this.suffix = suffix;
this.expr = expr;
}
}
}
| |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.uif.view;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.krad.uif.container.CollectionGroup;
import org.kuali.rice.krad.uif.component.Component;
import org.kuali.rice.krad.uif.field.DataField;
import org.kuali.rice.krad.uif.field.InputField;
import org.kuali.rice.krad.uif.util.ComponentUtils;
import org.kuali.rice.krad.uif.util.ViewCleaner;
import java.beans.PropertyEditor;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Holds field indexes of a <code>View</code> instance for retrieval
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class ViewIndex implements Serializable {
private static final long serialVersionUID = 4700818801272201371L;
private Map<String, Component> index;
private Map<String, DataField> dataFieldIndex;
private Map<String, CollectionGroup> collectionsIndex;
private Map<String, Component> initialComponentStates;
private Map<String, PropertyEditor> fieldPropertyEditors;
private Map<String, PropertyEditor> secureFieldPropertyEditors;
private Map<String, Integer> idSequenceSnapshot;
/**
* Constructs new instance
*/
public ViewIndex() {
index = new HashMap<String, Component>();
dataFieldIndex = new HashMap<String, DataField>();
collectionsIndex = new HashMap<String, CollectionGroup>();
initialComponentStates = new HashMap<String, Component>();
fieldPropertyEditors = new HashMap<String, PropertyEditor>();
secureFieldPropertyEditors = new HashMap<String, PropertyEditor>();
idSequenceSnapshot = new HashMap<String, Integer>();
}
/**
* Walks through the View tree and indexes all components found. All components
* are indexed by their IDs with the special indexing done for certain components
*
* <p>
* <code>DataField</code> instances are indexed by the attribute path.
* This is useful for retrieving the InputField based on the incoming
* request parameter
* </p>
*
* <p>
* <code>CollectionGroup</code> instances are indexed by the collection
* path. This is useful for retrieving the CollectionGroup based on the
* incoming request parameter
* </p>
*/
protected void index(View view) {
index = new HashMap<String, Component>();
dataFieldIndex = new HashMap<String, DataField>();
collectionsIndex = new HashMap<String, CollectionGroup>();
fieldPropertyEditors = new HashMap<String, PropertyEditor>();
secureFieldPropertyEditors = new HashMap<String, PropertyEditor>();
indexComponent(view);
}
/**
* Adds an entry to the main index for the given component. If the component
* is of type <code>DataField</code> or <code>CollectionGroup</code> an
* entry is created in the corresponding indexes for those types as well. Then
* the #indexComponent method is called for each of the component's children
*
* <p>
* If the component is already contained in the indexes, it will be replaced
* </p>
*
* <p>
* Special processing is done for DataField instances to register their property editor which will
* be used for form binding
* </p>
*
* @param component - component instance to index
*/
public void indexComponent(Component component) {
if (component == null) {
return;
}
index.put(component.getId(), component);
if (component instanceof DataField) {
DataField field = (DataField) component;
dataFieldIndex.put(field.getBindingInfo().getBindingPath(), field);
// pull out information we will need to support the form post
if (component.isRender()) {
if (field.hasSecureValue()) {
secureFieldPropertyEditors.put(field.getBindingInfo().getBindingPath(), field.getPropertyEditor());
} else {
fieldPropertyEditors.put(field.getBindingInfo().getBindingPath(), field.getPropertyEditor());
}
}
} else if (component instanceof CollectionGroup) {
CollectionGroup collectionGroup = (CollectionGroup) component;
collectionsIndex.put(collectionGroup.getBindingInfo().getBindingPath(), collectionGroup);
}
for (Component nestedComponent : component.getComponentsForLifecycle()) {
indexComponent(nestedComponent);
}
}
/**
* Invoked after the view lifecycle or component refresh has run to clear indexes that are not
* needed for the post
*/
public void clearIndexesAfterRender() {
// build list of factory ids for components whose initial state needs to be keep
Set<String> holdIds = new HashSet<String>();
Set<String> holdFactoryIds = new HashSet<String>();
for (Component component : index.values()) {
if (component != null) {
// if component has a refresh condition we need to keep it
if (StringUtils.isNotBlank(component.getProgressiveRender()) || StringUtils.isNotBlank(
component.getConditionalRefresh()) || StringUtils.isNotBlank(
component.getRefreshWhenChanged()) || component.isRefreshedByAction()) {
holdFactoryIds.add(component.getFactoryId());
holdIds.add(component.getId());
}
// if component is marked as persist in session we need to keep it
else if (component.isPersistInSession()) {
holdFactoryIds.add(component.getFactoryId());
holdIds.add(component.getId());
}
// if component is a collection we need to keep it
else if (component instanceof CollectionGroup) {
ViewCleaner.cleanCollectionGroup((CollectionGroup) component);
holdFactoryIds.add(component.getFactoryId());
holdIds.add(component.getId());
}
// if component is input field and has a query we need to keep the final state
else if ((component instanceof InputField)) {
InputField inputField = (InputField) component;
if ((inputField.getFieldAttributeQuery() != null) || inputField.getFieldSuggest().isRender()) {
holdIds.add(component.getId());
}
}
}
}
// remove initial states for components we don't need for post
Map<String, Component> holdInitialComponentStates = new HashMap<String, Component>();
for (String factoryId : initialComponentStates.keySet()) {
if (holdFactoryIds.contains(factoryId)) {
holdInitialComponentStates.put(factoryId, initialComponentStates.get(factoryId));
}
}
initialComponentStates = holdInitialComponentStates;
// remove final states for components we don't need for post
Map<String, Component> holdComponentStates = new HashMap<String, Component>();
for (String id : index.keySet()) {
if (holdIds.contains(id)) {
holdComponentStates.put(id, index.get(id));
}
}
index = holdComponentStates;
dataFieldIndex = new HashMap<String, DataField>();
}
/**
* Retrieves a <code>Component</code> from the view index by Id
*
* @param id - id for the component to retrieve
* @return Component instance found in index, or null if no such component exists
*/
public Component getComponentById(String id) {
return index.get(id);
}
/**
* Retrieves a <code>DataField</code> instance from the index
*
* @param propertyPath - full path of the data field (from the form)
* @return DataField instance for the path or Null if not found
*/
public DataField getDataFieldByPath(String propertyPath) {
return dataFieldIndex.get(propertyPath);
}
/**
* Retrieves a <code>DataField</code> instance that has the given property name
* specified (note this is not the full binding path and first match is returned)
*
* @param propertyName - property name for field to retrieve
* @return DataField instance found or null if not found
*/
public DataField getDataFieldByPropertyName(String propertyName) {
DataField dataField = null;
for (DataField field : dataFieldIndex.values()) {
if (StringUtils.equals(propertyName, field.getPropertyName())) {
dataField = field;
break;
}
}
return dataField;
}
/**
* Gets the Map that contains attribute field indexing information. The Map
* key points to an attribute binding path, and the Map value is the
* <code>DataField</code> instance
*
* @return Map<String, DataField> data fields index map
*/
public Map<String, DataField> getDataFieldIndex() {
return this.dataFieldIndex;
}
/**
* Gets the Map that contains collection indexing information. The Map key
* gives the binding path to the collection, and the Map value givens the
* <code>CollectionGroup</code> instance
*
* @return Map<String, CollectionGroup> collection index map
*/
public Map<String, CollectionGroup> getCollectionsIndex() {
return this.collectionsIndex;
}
/**
* Retrieves a <code>CollectionGroup</code> instance from the index
*
* @param collectionPath - full path of the collection (from the form)
* @return CollectionGroup instance for the collection path or Null if not
* found
*/
public CollectionGroup getCollectionGroupByPath(String collectionPath) {
return collectionsIndex.get(collectionPath);
}
/**
* Preserves initial state of components needed for doing component refreshes
*
* <p>
* Some components, such as those that are nested or created in code cannot be requested from the
* spring factory to get new instances. For these a copy of the component in its initial state is
* set in this map which will be used when doing component refreshes (which requires running just that
* component's lifecycle)
* </p>
*
* <p>
* Map entries are added during the perform initialize phase from {@link org.kuali.rice.krad.uif.service.ViewHelperService}
* </p>
*
* @return Map<String, Component> - map with key giving the factory id for the component and the value the
* component
* instance
*/
public Map<String, Component> getInitialComponentStates() {
return initialComponentStates;
}
/**
* Adds a copy of the given component instance to the map of initial component states keyed
*
* <p>
* Component is only added if its factory id is not set yet (which would happen if it had a spring bean id
* and we can get the state from Spring). Once added the factory id will be set to the component id
* </p>
*
* @param component - component instance to add
*/
public void addInitialComponentStateIfNeeded(Component component) {
if (StringUtils.isBlank(component.getFactoryId())) {
component.setFactoryId(component.getId());
initialComponentStates.put(component.getFactoryId(), ComponentUtils.copy(component));
}
}
/**
* Setter for the map holding initial component states
*
* @param initialComponentStates
*/
public void setInitialComponentStates(Map<String, Component> initialComponentStates) {
this.initialComponentStates = initialComponentStates;
}
/**
* Maintains configuration of properties that have been configured for the view (if render was set to
* true) and there corresponding PropertyEdtior (if configured)
*
* <p>
* Information is pulled out of the View during the lifecycle so it can be used when a form post is done
* from the View. Note if a field is secure, it will be placed in the {@link #getSecureFieldPropertyEditors()} map
* instead
* </p>
*
* @return Map<String, PropertyEditor> map of property path (full) to PropertyEditor
*/
public Map<String, PropertyEditor> getFieldPropertyEditors() {
return fieldPropertyEditors;
}
/**
* Setter for the Map that holds view property paths to configured Property Editors (non secure fields only)
*
* @param fieldPropertyEditors
*/
public void setFieldPropertyEditors(Map<String, PropertyEditor> fieldPropertyEditors) {
this.fieldPropertyEditors = fieldPropertyEditors;
}
/**
* Maintains configuration of secure properties that have been configured for the view (if render was set to
* true) and there corresponding PropertyEdtior (if configured)
*
* <p>
* Information is pulled out of the View during the lifecycle so it can be used when a form post is done
* from the View. Note if a field is non-secure, it will be placed in the {@link #getFieldPropertyEditors()} map
* instead
* </p>
*
* @return Map<String, PropertyEditor> map of property path (full) to PropertyEditor
*/
public Map<String, PropertyEditor> getSecureFieldPropertyEditors() {
return secureFieldPropertyEditors;
}
/**
* Setter for the Map that holds view property paths to configured Property Editors (secure fields only)
*
* @param secureFieldPropertyEditors
*/
public void setSecureFieldPropertyEditors(Map<String, PropertyEditor> secureFieldPropertyEditors) {
this.secureFieldPropertyEditors = secureFieldPropertyEditors;
}
public Map<String, Integer> getIdSequenceSnapshot() {
return idSequenceSnapshot;
}
public void setIdSequenceSnapshot(Map<String, Integer> idSequenceSnapshot) {
this.idSequenceSnapshot = idSequenceSnapshot;
}
public void addSequenceValueToSnapshot(String componentId, int sequenceVal) {
idSequenceSnapshot.put(componentId, sequenceVal);
}
}
| |
package org.joml.geom;
import org.joml.FrustumCuller;
import org.joml.Vector3f;
/**
* This class contains utility methods for intersections between various geometric shapes.
* Note: The ray intersection methods always return the distance to the 'hit point', or positive infinity if there is no hit.
* Note: No validations what-so-ever are done on the input by this class. NONE!
**/
public class Intersections {
// The vectors defined here are private for the
// simple reason that they should NOT BE CHANGED.
private static final Vector3f ORIGIN = new Vector3f();
private static final Vector3f RIGHT = new Vector3f(1,0,0);
private static final Vector3f UP = new Vector3f(0,1,0);
private static final Vector3f FRONT = new Vector3f(0,0,1);
private static final Vector3f LEFT = new Vector3f(-1,0,0);
private static final Vector3f DOWN = new Vector3f(0,-1,0);
private static final Vector3f BACK = new Vector3f(0,0,-1);
/**
* @return True, if the given {@link Aabbf} intersects the given frustum.
**/
public static final boolean intersectAabbWithFrustum(Aabbf aabb, FrustumCuller culler) {
return culler.isAabInsideFrustum(
aabb.originX - aabb.extentX,
aabb.originY - aabb.extentY,
aabb.originZ - aabb.extentZ,
aabb.originX + aabb.extentX,
aabb.originY + aabb.extentY,
aabb.originZ + aabb.extentZ
) == -1;
}
/**
* @param aabb The AABB.
* @param position The center of the sphere.
* @param radius The radius of the sphere.
* @return True, if the given {@link Aabbf} overlaps with the sphere defined by the given position and radius. False if not.
**/
public static final boolean intersectAabbWithSphere(Aabbf aabb, Vector3f position, float radius) {
return aabb.minDistanceSquared(position) <= (radius*radius);
}
/**
* @param aabb The AABB.
* @param sphere The sphere
* @return True, if the given {@link Aabbf} overlaps with the given sphere. False if not.
**/
public static final boolean intersectAabbWithSphere(Aabbf aabb, Spheref sphere) {
return aabb.minDistanceSquared(sphere.centerX,sphere.centerY,sphere.centerZ) <= sphere.getRadiusSquared();
}
public static final boolean intersectAabbWithAabb(Aabbf aabbA, Aabbf aabbB) {
return aabbA.intersect(aabbB);
}
public static final boolean intersectAabbWithAabb(Aabbf aabb,
float extentX, float extentY, float extentZ, float originX, float originY, float originZ) {
// XXX: The 'abs'-method could be inlined manually here.
if (abs(originX - aabb.originX) >= (extentX + aabb.extentX) ) return false;
if (abs(originY - aabb.originY) >= (extentY + aabb.extentY) ) return false;
if (abs(originZ - aabb.originZ) >= (extentZ + aabb.extentZ) ) return false;
// We have an overlap
return true;
}
public static final boolean intersectAabbWithAabb(
float extentX, float extentY, float extentZ, float originX, float originY, float originZ,
float extentXb, float extentYb, float extentZb, float originXb, float originYb, float originZb) {
// XXX: The 'abs'-method could be inlined manually here.
if (abs(originX - originXb) >= (extentX + extentXb) ) return false;
if (abs(originY - originYb) >= (extentY + extentYb) ) return false;
if (abs(originZ - originZb) >= (extentZ + extentZb) ) return false;
// We have an overlap
return true;
}
public static final boolean intersectSphereWithSphere(Spheref sphereA, Spheref sphereB) {
return sphereA.intersect(sphereB);
}
public static final boolean intersectSphereWithFrustum(Spheref sphere, FrustumCuller culler) {
return culler.isSphereInsideFrustum(sphere.centerX, sphere.centerY, sphere.centerZ, sphere.radius);
}
/** Warning: Not yet tested. **/
public static final float intersectRayWithPlane(Rayf ray, Vector3f normal, Vector3f point) {
// unwrap ray onto stack
float rayDirX = ray.directionX;
float rayDirY = ray.directionY;
float rayDirZ = ray.directionZ;
float rayOrgX = ray.originX;
float rayOrgY = ray.originY;
float rayOrgZ = ray.originZ;
// -((normal.dot(ray.origin) + (-normal.dot(Point))) / normal.dot(ray.direction));
// float : NDR = NORMAL dot RAYDIR
float NDR = normal.x*rayDirX + normal.y*rayDirY + normal.z*rayDirZ;
// float : NNDP = negate (NORMAL dot POINT)
float NNDP = -(normal.x*point.x + normal.y*point.y + normal.z*point.z);
// float : NDO = NORMAL dot RAYPOS
float NDO = normal.x*rayOrgX + normal.y*rayOrgY + normal.z*rayOrgZ;
// float : RET = -((NDO + NNDP) / NDR)
float T = -((NDO + NNDP) / NDR);
return T > 0 ? T : Float.POSITIVE_INFINITY;
}
/** Warning: Not yet tested. **/
public static final float intersectRayWithPlane(Rayf ray, Vector3f normal, float pointX, float pointY, float pointZ) {
// unwrap ray onto stack
float rayDirX = ray.directionX;
float rayDirY = ray.directionY;
float rayDirZ = ray.directionZ;
float rayOrgX = ray.originX;
float rayOrgY = ray.originY;
float rayOrgZ = ray.originZ;
// -((normal.dot(ray.origin) + (-normal.dot(Point))) / normal.dot(ray.direction));
// float : NDR = NORMAL dot RAYDIR
float NDR = normal.x*rayDirX + normal.y*rayDirY + normal.z*rayDirZ;
// float : NNDP = negate (NORMAL dot POINT)
float NNDP = -(normal.x*pointX + normal.y*pointY + normal.z*pointZ);
// float : NDO = NORMAL dot RAYPOS
float NDO = normal.x*rayOrgX + normal.y*rayOrgY + normal.z*rayOrgZ;
// float : RET = -((NDO + NNDP) / NDR)
float T = -((NDO + NNDP) / NDR);
return T > 0 ? T : Float.POSITIVE_INFINITY;
}
public static final float intersectRayWithPositiveXAxisPlane(Rayf ray) {
return intersectRayWithPlane(ray, RIGHT, ORIGIN);
}
public static final float intersectRayWithPositiveYAxisPlane(Rayf ray) {
return intersectRayWithPlane(ray, UP, ORIGIN);
}
public static final float intersectRayWithPositiveZAxisPlane(Rayf ray) {
return intersectRayWithPlane(ray, FRONT, ORIGIN);
}
public static final float intersectRayWithNegativeXAxisPlane(Rayf ray) {
return intersectRayWithPlane(ray, LEFT, ORIGIN);
}
public static final float intersectRayWithNegativeYAxisPlane(Rayf ray) {
return intersectRayWithPlane(ray, DOWN, ORIGIN);
}
public static final float intersectRayWithNegativeZAxisPlane(Rayf ray) {
return intersectRayWithPlane(ray, BACK, ORIGIN);
}
public static final float intersectRayWithPlaneInBox(Rayf ray, Vector3f normal, Vector3f point, Aabbf aabb) {
float t = intersectRayWithPlane(ray, normal, point);
float px = ray.originX + ray.directionX * t;
float py = ray.originY + ray.directionY * t;
float pz = ray.originZ + ray.directionZ * t;
return aabb.inside(px, py, pz) ? t : Float.POSITIVE_INFINITY;
}
public static final float intersectRayWithPlaneInBox(Rayf ray, Vector3f normal, float pointX, float pointY, float pointZ, Aabbf aabb) {
float t = intersectRayWithPlane(ray, normal, pointX, pointY, pointZ);
float px = ray.originX + ray.directionX * t;
float py = ray.originY + ray.directionY * t;
float pz = ray.originZ + ray.directionZ * t;
return aabb.inside(px, py, pz) ? t : Float.POSITIVE_INFINITY;
}
/** Warning: Not yet tested. **/
public static final float intersectRayWithDisk(Rayf ray, Vector3f n, Vector3f p0, float radius) {
float planeIntersect = intersectRayWithPlane(ray, n, p0);
if (planeIntersect < Float.POSITIVE_INFINITY) {
float pX = ray.originX + ray.directionX*planeIntersect;
float pY = ray.originY + ray.directionY*planeIntersect;
float pZ = ray.originZ + ray.directionZ*planeIntersect;
float vX = pX - p0.x;
float vY = pY - p0.y;
float vZ = pZ - p0.z;
float d2 = vX*vX+vY*vY+vZ*vZ;
return (d2 <= radius*radius) ? planeIntersect : Float.POSITIVE_INFINITY;
}
return Float.POSITIVE_INFINITY;
}
public static final float intersectRayWithSphere(Rayf ray, Spheref sphere) {
return intersectRayWithSphere(ray, sphere.centerX, sphere.centerY, sphere.centerZ, sphere.radius);
}
/** Warning: Not yet tested. **/
public static final float intersectRayWithSphere(Rayf ray, float centerX, float centerY, float centerZ, float radius) {
// unwrap ray onto stack
float rayOrgX = ray.originX;
float rayOrgY = ray.originY;
float rayOrgZ = ray.originZ;
float rayDirX = ray.directionX;
float rayDirY = ray.directionY;
float rayDirZ = ray.directionZ;
float vX = centerX - rayOrgX;
float vY = centerY - rayOrgY;
float vZ = centerZ - rayOrgZ;
float b = vX * rayDirX + vY * rayDirY + vZ * rayDirZ;
float vDot = vX*vX+vY*vY+vZ*vZ;
float disc = b*b - vDot + radius*radius;
if (disc < 0)
return Float.POSITIVE_INFINITY;
float d = (float) Math.sqrt(disc);
float t2 = b+d;
if (t2 < 0)
return Float.POSITIVE_INFINITY;
float t1 = b-d;
return (t1 > 0 ? t1 : t2);
}
public static final float intersectRayWithAabb(Rayf ray, Aabbf aabb) {
float tTop = intersectRayWithPlaneInBox(ray, Intersections.UP , 0,aabb.getMaxY(),0, aabb);
float tBottom= intersectRayWithPlaneInBox(ray, Intersections.DOWN , 0,aabb.getMinY(),0, aabb);
float tLeft = intersectRayWithPlaneInBox(ray, Intersections.LEFT , aabb.getMinX(),0,0, aabb);
float tRight = intersectRayWithPlaneInBox(ray, Intersections.RIGHT, aabb.getMaxX(),0,0, aabb);
float tFront = intersectRayWithPlaneInBox(ray, Intersections.FRONT, 0,0,aabb.getMaxZ(), aabb);
float tBack = intersectRayWithPlaneInBox(ray, Intersections.BACK , 0,0,aabb.getMinZ(), aabb);
return Math.min(tTop, Math.min(tBottom, Math.min(tLeft, Math.min(tRight, Math.min(tFront, tBack)))));
}
public static final float intersectRayWithAabb_doesNotWork_doNotUse(Rayf ray, Aabbf aabb) {
float lbX = aabb.originX - aabb.extentX;
float lbY = aabb.originY - aabb.extentY;
float lbZ = aabb.originZ - aabb.extentZ;
float rtX = aabb.originX + aabb.extentX;
float rtY = aabb.originY + aabb.extentY;
float rtZ = aabb.originZ + aabb.extentZ;
// ray.directionXYZ is unit direction vector of ray
// take inverse of ray direction
float dirfracX = 1.0f / ray.directionX;
float dirfracY = 1.0f / ray.directionY;
float dirfracZ = 1.0f / ray.directionZ;
// LB.XYZ is the corner of AABB with minimal coordinates, RT.XYZ is maximal corner
// ray.originXYZ is origin of ray
float t1 = (lbX - ray.originX)*dirfracX;
float t2 = (rtX - ray.originX)*dirfracX;
float t3 = (lbY - ray.originY)*dirfracY;
float t4 = (rtY - ray.originY)*dirfracY;
float t5 = (lbZ - ray.originZ)*dirfracZ;
float t6 = (rtZ - ray.originZ)*dirfracZ;
// This is some insane min/max-ing.
float tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
float tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));
float t = Float.POSITIVE_INFINITY;
// if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behind us
if (tmax < 0)
{
t = tmax;
return Float.POSITIVE_INFINITY;
}
// if tmin > tmax, ray doesn't intersect AABB
if (tmin > tmax)
{
t = tmax;
return Float.POSITIVE_INFINITY;
}
t = tmin;
return t;
}
public static float intersectRayWithLine(Rayf ray, Vector3f lineStart,Vector3f lineEnd){
float uX = ray.directionX;
float uY = ray.directionY;
float uZ = ray.directionZ;
float vX = lineEnd.x - lineStart.x;
float vY = lineEnd.y - lineStart.y;
float vZ = lineEnd.z - lineStart.z;
float wX = ray.originX - lineStart.x;
float wY = ray.originY - lineStart.y;
float wZ = ray.originZ - lineStart.z;
float a = uX * uX + uY * uY + uZ * uZ; // always >= 0
float b = uX * vX + uY * vY + uZ * vZ;
float c = vX * vX + vY * vY + vZ * vZ; // always >= 0
float d = uX * wX + uY * wY + uZ * wZ;
float e = vX * wX + vY * wY + vZ * wZ;
float D = (a*c) - (b*b); // always >= 0
float sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
float tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
final float epsilon = (float) Math.E;
// compute the line parameters of the two closest points
if (D < epsilon) { // the lines are almost parallel
sN = 0F; // force using point P0 on segment S1
sD = 1F; // to prevent possible division by 0.0 later
tN = e;
tD = c;
}
else { // get the closest points on the infinite lines
sN = ((b*e) - (c*d));
tN = ((a*e) - (b*d));
if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
sN = 0.0f;
tN = e;
tD = c;
}
}
if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
tN = 0.0f;
// recompute sc for this edge
if (-d < 0.0) {
sN = 0.0f;
} else {
sN = -d;
sD = a;
}
}
else if (tN > tD) { // tc > 1 => the t=1 edge is visible
tN = tD;
// recompute sc for this edge
if ((-d + b) < 0.0) {
sN = 0;
} else {
sN = (-d + b);
sD = a;
}
}
// finally do the division to get sc and tc
sc = (Math.abs(sN) < epsilon ? 0.0f : sN / sD);
tc = (Math.abs(tN) < epsilon ? 0.0f : tN / tD);
float uscX = uX * sc;
float uscY = uY * sc;
float uscZ = uZ * sc;
float vtcX = vX * tc;
float vtcY = vY * tc;
float vtcZ = vZ * tc;
// get the difference of the two closest points
// = S1(sc) - S2(tc)
float dpX = wX + (uscX - vtcX);
float dpY = wY + (uscY - vtcY);
float dpZ = wZ + (uscZ - vtcZ);
float distToRay = (float) Math.sqrt(dpX*dpX+dpY*dpY+dpZ*dpZ);
float uscLEN = (float) Math.sqrt(uscX*uscX+uscY*uscY+uscZ*uscZ);
float vtcLEN = (float) Math.sqrt(vtcX*vtcX+vtcY*vtcY+vtcZ*vtcZ);
float distToRayOrigin = (float) Math.min(uscLEN, vtcLEN);
// return the distance to the point that is the nearest.
return distToRay < 0.1 ? distToRayOrigin : Float.POSITIVE_INFINITY;
}
public static final float intersectRayWithTriangle(Rayf ray, Vector3f point1, Vector3f point2, Vector3f point3){
// unwrap ray onto stack
float rayOrgX = ray.originX;
float rayOrgY = ray.originY;
float rayOrgZ = ray.originZ;
float rayDirX = ray.directionX;
float rayDirY = ray.directionY;
float rayDirZ = ray.directionZ;
float edge1X = point2.x - point1.x;
float edge1Y = point2.y - point1.y;
float edge1Z = point2.z - point1.z;
float edge2X = point3.x - point1.x;
float edge2Y = point3.y - point1.y;
float edge2Z = point3.z - point1.z;
// Find the cross product of edge2 and the ray direction
float s1X = rayDirY * edge2Z - rayDirZ * edge2Y;
float s1Y = rayDirZ * edge2X - rayDirX * edge2Z;
float s1Z = rayDirX * edge2Y - rayDirY * edge2X;
// Find the divisor, if its zero, return false as the triangle is
// degenerated
final float divisor = s1X*edge1X + s1Y*edge1Y + s1Z*edge1Z;
if (divisor == 0.0) {
return Float.POSITIVE_INFINITY;
}
// A inverted divisor, as multiplying is faster then division
final float invDivisor = 1 / divisor;
// Calculate the first barycentic coordinate. Barycentic coordinates
// are between 0.0 and 1.0
final float distanceX = rayOrgX - point1.x;
final float distanceY = rayOrgY - point1.y;
final float distanceZ = rayOrgZ - point1.z;
final float barycCoord_1 = (distanceX*s1X+distanceY*s1Y+distanceZ*s1Z) * invDivisor;
if ((barycCoord_1 < 0.0) || (barycCoord_1 > 1.0)) {
return Float.POSITIVE_INFINITY;
}
final float s2X = distanceY * edge1Z - distanceZ * edge1Y;
final float s2Y = distanceZ * edge1X - distanceX * edge1Z;
final float s2Z = distanceX * edge1Y - distanceY * edge1X;
final float barycCoord_2 = (rayDirX*s2X+rayDirY*s2Y+rayDirZ*s2Z) * invDivisor;
if ((barycCoord_2 < 0.0) || ((barycCoord_1 + barycCoord_2) > 1.0)) {
return Float.POSITIVE_INFINITY;
}
// After doing the barycentic coordinate test we know if the ray hits or
// not. If we got this far the ray hits.
// Calculate the distance to the intersection point
final float intersectionDistance = (edge2X*s2X+edge2Y*s2Y+edge2Z*s2Z) * invDivisor;
return intersectionDistance >= 0 ? intersectionDistance : Float.POSITIVE_INFINITY;
}
/**
* @return <ul>
* <li> 0: No Intersection
* <li> 1: Point Intersection
* <li> 2: Line Intersection
* </ul>
**/
public static final int intersectLineWithPlane(Vector3f Sp0, Vector3f Sp1, Vector3f pNormal, Vector3f pPoint, Vector3f store) {
// Vector3f u = Sp1 - Sp0;
float uX = Sp1.x - Sp0.x;
float uY = Sp1.y - Sp0.y;
float uZ = Sp1.z - Sp0.z;
// Vector3f w = Sp0 - Pn.V0;
float wX = Sp0.x - pPoint.x;
float wY = Sp0.y - pPoint.y;
float wZ = Sp0.z - pPoint.z;
float D = pNormal.x*uX+pNormal.y*uY+pNormal.z*uZ; // normal DOT u
float N = -(pNormal.x*wX+pNormal.y*wY+pNormal.z*wZ); // normal DOT w
if (abs(D) < Float.MIN_VALUE) {
// segment is parallel to plane
if (N == 0)
// segment lies in plane
return 2;
else
// no intersection
return 0;
}
// they are not parallel
// compute intersect parameter
float sI = N / D;
if (sI < 0 || sI > 1)
// no intersection
return 0;
// compute segment intersect point
// store = S.P0 + sI * u;
store.set(
Sp0.x + sI * uX,
Sp0.y + sI * uY,
Sp0.z + sI * uZ
);
return 1;
}
/**
* @return <ul>
* <li> 0: No Intersection
* <li> 1: Point Intersection
* <li> 2: Line Intersection
* </ul>
**/
public static final int intersectLineWithPlane(
float Sp0X, float Sp0Y, float Sp0Z,
float Sp1X, float Sp1Y, float Sp1Z,
Vector3f pNormal, Vector3f pPoint, Vector3f store) {
// Vector3f u = Sp1 - Sp0;
float uX = Sp1X - Sp0X;
float uY = Sp1Y - Sp0Y;
float uZ = Sp1Z - Sp0Z;
// Vector3f w = Sp0 - Pn.V0;
float wX = Sp0X - pPoint.x;
float wY = Sp0Y - pPoint.y;
float wZ = Sp0Z - pPoint.z;
float D = pNormal.x*uX+pNormal.y*uY+pNormal.z*uZ; // normal DOT u
float N = -(pNormal.x*wX+pNormal.y*wY+pNormal.z*wZ); // normal DOT w
if (abs(D) < Float.MIN_VALUE) {
// segment is parallel to plane
if (N == 0)
// segment lies in plane
return 2;
else
// no intersection
return 0;
}
// they are not parallel
// compute intersect parameter
float sI = N / D;
if (sI < 0 || sI > 1)
// no intersection
return 0;
// compute segment intersect point
// store = S.P0 + sI * u;
store.set(
Sp0X + sI * uX,
Sp0Y + sI * uY,
Sp0Z + sI * uZ
);
return 1;
}
/**
* This method uses a given plane to cut trough a given AABB, producing 0..6 points.
*
* @param pNormal The normal vector of the cutting plane.
* @param pPoint A point that is located on the cutting plane.
* @param aabb The AABB to cut trough.
* @param store A array of 6 {@link Vector3f} in which the cutting points will be stored in.
**/
public static final int intersectAabbWithPlane(Vector3f pNormal, Vector3f pPoint, Aabbf aabb, Vector3f[] store) {
float minX = aabb.originX - aabb.extentX;
float minY = aabb.originY - aabb.extentY;
float minZ = aabb.originZ - aabb.extentZ;
float maxX = aabb.originX + aabb.extentX;
float maxY = aabb.originY + aabb.extentY;
float maxZ = aabb.originZ + aabb.extentZ;
int pointPtr = 0;
int maximum = 6;
// TOP TO BOTTOM
if(intersectLineWithPlane(minX, minY, minZ, minX, maxY, minZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
if(intersectLineWithPlane(maxX, minY, minZ, maxX, maxY, minZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
if(intersectLineWithPlane(maxX, minY, maxZ, maxX, maxY, maxZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
if(intersectLineWithPlane(minX, minY, maxZ, minX, maxY, maxZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
// BOTTOM
if(intersectLineWithPlane(minX, minY, minZ, maxX, minY, minZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
if(intersectLineWithPlane(minX, minY, maxZ, maxX, minY, maxZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
if(intersectLineWithPlane(minX, minY, minZ, minX, minY, maxZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
if(intersectLineWithPlane(maxX, minY, minZ, maxX, minY, maxZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
// TOP
if(intersectLineWithPlane(minX, maxY, minZ, maxX, maxY, minZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
if(intersectLineWithPlane(minX, maxY, maxZ, maxX, maxY, maxZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
if(intersectLineWithPlane(minX, maxY, minZ, minX, maxY, maxZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
if(intersectLineWithPlane(maxX, maxY, minZ, maxX, maxY, maxZ, pNormal, pPoint, store[pointPtr]) == 1) {
if(++pointPtr >= maximum)return pointPtr;
}
return pointPtr;
}
private static float abs(final float x) {
return Float.intBitsToFloat(0x7fffffff & Float.floatToRawIntBits(x));
}
}
| |
package com.cogitareforma.hexrepublics.client.views;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.tuple.Pair;
import trendli.me.makhana.client.util.NiftyFactory;
import trendli.me.makhana.common.data.ServerStatus;
import trendli.me.makhana.common.net.msg.ServerListRequest;
import trendli.me.makhana.common.net.msg.UserListRequest;
import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.controls.Chat;
import de.lessvoid.nifty.controls.ChatTextSendEvent;
import de.lessvoid.nifty.controls.CheckBox;
import de.lessvoid.nifty.controls.ListBox;
import de.lessvoid.nifty.controls.ListBoxSelectionChangedEvent;
import de.lessvoid.nifty.controls.RadioButton;
import de.lessvoid.nifty.controls.RadioButtonGroupStateChangedEvent;
import de.lessvoid.nifty.controls.TextFieldChangedEvent;
import de.lessvoid.nifty.input.NiftyInputEvent;
import de.lessvoid.nifty.screen.KeyInputHandler;
/**
*
* @author Ryan Grier
*/
public class NetworkViewController extends GeneralController implements KeyInputHandler
{
/**
* The logger for this class.
*/
private final static Logger logger = Logger.getLogger( NetworkViewController.class.getName( ) );
private final static int chatInterval = 1000;
private Chat chat;
private Pair< Date, Boolean > lastMessage;
private boolean search;
private String searchText;
private String serverSelected = "";
private int port = 0;
public void applyFilters( )
{
@SuppressWarnings( "unchecked" )
ListBox< ServerStatus > networks = getApp( ).getNifty( ).getScreen( "network" ).findNiftyControl( "networkScroll", ListBox.class );
networks.clear( );
RadioButton full = getApp( ).getNifty( ).getScreen( "network" ).findNiftyControl( "option-2", RadioButton.class );
RadioButton empty = getApp( ).getNifty( ).getScreen( "network" ).findNiftyControl( "option-3", RadioButton.class );
CheckBox hasPlayers = getApp( ).getNifty( ).getScreen( "network" ).findNiftyControl( "hasPlayer", CheckBox.class );
for ( ServerStatus stat : getApp( ).getMasterConnectionManager( ).getServers( ) )
{
if ( search == true )
{
String serverName = stat.getServerName( ).toLowerCase( );
String search = this.searchText.toLowerCase( );
if ( serverName.contains( search ) || search.contains( serverName ) )
{
networks.addItem( stat );
}
}
else
{
if ( full.isActivated( ) )
{
if ( stat.getCurrentPlayers( ) == stat.getMaxPlayers( ) )
{
networks.addItem( stat );
}
}
else if ( empty.isActivated( ) )
{
if ( stat.getCurrentPlayers( ) == 0 )
{
networks.addItem( stat );
}
}
else
{
if ( hasPlayers.isChecked( ) )
{
if ( stat.getCurrentPlayers( ) > 0 && stat.getCurrentPlayers( ) < stat.getMaxPlayers( ) )
{
networks.addItem( stat );
}
}
else
{
networks.addItem( stat );
}
}
}
}
}
public void getUsers( )
{
}
/**
* Starts chat and lists all legal game lobbies that can be joined.
*/
public void initialize( AppStateManager stateManager, Application app )
{
setScreenId( "network" );
super.initialize( stateManager, app );
getApp( ).getMasterConnectionManager( ).send( new UserListRequest( ) );
getApp( ).getMasterConnectionManager( ).send( new ServerListRequest( ) );
logger.log( Level.INFO, "Initialised " + this.getClass( ) );
getApp( ).getNifty( ).getCurrentScreen( ).findElementByName( "chat" );
chat = getApp( ).getNifty( ).getCurrentScreen( ).findNiftyControl( "networkChat", Chat.class );
getApp( ).currentScreen = "network";
}
public void joinServer( )
{
if ( this.serverSelected.length( ) > 0 || this.port != 0 )
{
System.out.println( this.serverSelected + " , " + this.port );
getApp( ).connectToGameSever( serverSelected, port );
}
}
public boolean keyEvent( NiftyInputEvent inputEvent )
{
return false;
}
public void logout( )
{
NiftyFactory.createStartView( getApp( ).getNifty( ) );
gotoScreen( "start", true, true, true, ( ) ->
{
getApp( ).sendLogout( );
return null;
}, null );
}
/**
* Sends the text the user inputs into the chat to the server.
*
* @param id
* @param event
*/
@NiftyEventSubscriber( id = "networkChat" )
public void onChatTextSendEvent( final String id, final ChatTextSendEvent event )
{
Date timeNow = new Date( );
if ( lastMessage == null || lastMessage.getLeft( ).getTime( ) <= timeNow.getTime( ) - chatInterval )
{
logger.log( Level.INFO, "Chat -> " + event.getText( ) );
getApp( ).sendNetworkChat( event.getText( ) );
lastMessage = Pair.of( timeNow, false );
}
else
{
if ( lastMessage.getRight( ) == false )
{
logger.log( Level.INFO, "Chat -> You are spamming the chat." );
chat.receivedChatLine( "Client Warning: You are spamming the chat", null );
lastMessage = Pair.of( lastMessage.getLeft( ), true );
}
}
}
/**
* Gives which game lobby the user has selected. Currently just logs
* selected.
*
* @param id
* @param event
*/
@NiftyEventSubscriber( id = "networkScroll" )
public void onListBoxSelectionChanged( final String id, final ListBoxSelectionChangedEvent< ServerStatus > event )
{
if ( event != null )
{
if ( event.getSelection( ).size( ) > 0 )
{
List< ServerStatus > stat = event.getSelection( );
serverSelected = stat.get( 0 ).getAddress( );
port = stat.get( 0 ).getPort( );
logger.log( Level.INFO, stat.toString( ) );
}
}
// TODO: do something with the selection
}
@NiftyEventSubscriber( id = "RadioGroup-1" )
public void onRadioGroup1Changed( final String id, final RadioButtonGroupStateChangedEvent event )
{
/*
* System.out.println( "RadioButton [" + event.getSelectedId( ) +
* "] is now selected. The old selection was [" +
* event.getPreviousSelectedId( ) + "]" );
*/
}
@NiftyEventSubscriber( id = "search" )
public void onTextFieldChanged( final String id, final TextFieldChangedEvent event )
{
if ( event.getText( ).equals( "" ) )
{
search = false;
searchText = "";
}
else
{
search = true;
searchText = event.getText( );
}
}
public void refreshServerList( )
{
getApp( ).getMasterConnectionManager( ).send( new ServerListRequest( ) );
}
}
| |
/*
* 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.arrow.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.ipc.ArrowFileReader;
import org.apache.arrow.vector.ipc.ArrowFileWriter;
import org.apache.arrow.vector.ipc.JsonFileReader;
import org.apache.arrow.vector.ipc.JsonFileWriter;
import org.apache.arrow.vector.ipc.message.ArrowBlock;
import org.apache.arrow.vector.types.pojo.DictionaryEncoding;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.Schema;
import org.apache.arrow.vector.util.Validator;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Integration {
private static final Logger LOGGER = LoggerFactory.getLogger(Integration.class);
private final Options options;
Integration() {
this.options = new Options();
this.options.addOption("a", "arrow", true, "arrow file");
this.options.addOption("j", "json", true, "json file");
this.options.addOption("c", "command", true, "command to execute: " + Arrays.toString(Command
.values()));
}
public static void main(String[] args) {
try {
new Integration().run(args);
} catch (ParseException e) {
fatalError("Invalid parameters", e);
} catch (IOException e) {
fatalError("Error accessing files", e);
} catch (RuntimeException e) {
fatalError("Incompatible files", e);
}
}
private static void fatalError(String message, Throwable e) {
System.err.println(message);
System.err.println(e.getMessage());
LOGGER.error(message, e);
System.exit(1);
}
private File validateFile(String type, String fileName, boolean shouldExist) {
if (fileName == null) {
throw new IllegalArgumentException("missing " + type + " file parameter");
}
File f = new File(fileName);
if (shouldExist && (!f.exists() || f.isDirectory())) {
throw new IllegalArgumentException(type + " file not found: " + f.getAbsolutePath());
}
if (!shouldExist && f.exists()) {
throw new IllegalArgumentException(type + " file already exists: " + f.getAbsolutePath());
}
return f;
}
static void extractDictionaryEncodings(List<Field> fields, List<DictionaryEncoding> encodings) {
for (Field field : fields) {
DictionaryEncoding encoding = field.getDictionary();
if (encoding != null) {
encodings.add(encoding);
}
extractDictionaryEncodings(field.getChildren(), encodings);
}
}
void run(String[] args) throws ParseException, IOException {
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args, false);
Command command = toCommand(cmd.getOptionValue("command"));
File arrowFile = validateFile("arrow", cmd.getOptionValue("arrow"), command.arrowExists);
File jsonFile = validateFile("json", cmd.getOptionValue("json"), command.jsonExists);
command.execute(arrowFile, jsonFile);
}
private Command toCommand(String commandName) {
try {
return Command.valueOf(commandName);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Unknown command: " + commandName + " expected one of " +
Arrays.toString(Command.values()));
}
}
enum Command {
ARROW_TO_JSON(true, false) {
@Override
public void execute(File arrowFile, File jsonFile) throws IOException {
try (BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE);
FileInputStream fileInputStream = new FileInputStream(arrowFile);
ArrowFileReader arrowReader = new ArrowFileReader(fileInputStream.getChannel(),
allocator)) {
VectorSchemaRoot root = arrowReader.getVectorSchemaRoot();
Schema schema = root.getSchema();
LOGGER.debug("Input file size: " + arrowFile.length());
LOGGER.debug("Found schema: " + schema);
try (JsonFileWriter writer = new JsonFileWriter(jsonFile, JsonFileWriter.config()
.pretty(true))) {
writer.start(schema, arrowReader);
for (ArrowBlock rbBlock : arrowReader.getRecordBlocks()) {
if (!arrowReader.loadRecordBatch(rbBlock)) {
throw new IOException("Expected to load record batch");
}
writer.write(root);
}
}
LOGGER.debug("Output file size: " + jsonFile.length());
}
}
},
JSON_TO_ARROW(false, true) {
@Override
public void execute(File arrowFile, File jsonFile) throws IOException {
try (BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE);
JsonFileReader reader = new JsonFileReader(jsonFile, allocator)) {
Schema schema = reader.start();
LOGGER.debug("Input file size: " + jsonFile.length());
LOGGER.debug("Found schema: " + schema);
try (FileOutputStream fileOutputStream = new FileOutputStream(arrowFile);
VectorSchemaRoot root = VectorSchemaRoot.create(schema, allocator);
// TODO json dictionaries
ArrowFileWriter arrowWriter = new ArrowFileWriter(root, reader, fileOutputStream
.getChannel())) {
arrowWriter.start();
while (reader.read(root)) {
arrowWriter.writeBatch();
}
arrowWriter.end();
}
LOGGER.debug("Output file size: " + arrowFile.length());
}
}
},
VALIDATE(true, true) {
@Override
public void execute(File arrowFile, File jsonFile) throws IOException {
try (BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE);
JsonFileReader jsonReader = new JsonFileReader(jsonFile, allocator);
FileInputStream fileInputStream = new FileInputStream(arrowFile);
ArrowFileReader arrowReader = new ArrowFileReader(fileInputStream.getChannel(),
allocator)) {
Schema jsonSchema = jsonReader.start();
VectorSchemaRoot arrowRoot = arrowReader.getVectorSchemaRoot();
Schema arrowSchema = arrowRoot.getSchema();
LOGGER.debug("Arrow Input file size: " + arrowFile.length());
LOGGER.debug("ARROW schema: " + arrowSchema);
LOGGER.debug("JSON Input file size: " + jsonFile.length());
LOGGER.debug("JSON schema: " + jsonSchema);
Validator.compareSchemas(jsonSchema, arrowSchema);
List<ArrowBlock> recordBatches = arrowReader.getRecordBlocks();
Iterator<ArrowBlock> iterator = recordBatches.iterator();
VectorSchemaRoot jsonRoot;
int totalBatches = 0;
while ((jsonRoot = jsonReader.read()) != null && iterator.hasNext()) {
ArrowBlock rbBlock = iterator.next();
if (!arrowReader.loadRecordBatch(rbBlock)) {
throw new IOException("Expected to load record batch");
}
Validator.compareVectorSchemaRoot(arrowRoot, jsonRoot);
jsonRoot.close();
totalBatches++;
}
// Validate Dictionaries after ArrowFileReader has read batches
List<DictionaryEncoding> encodingsJson = new ArrayList<>();
extractDictionaryEncodings(jsonSchema.getFields(), encodingsJson);
List<DictionaryEncoding> encodingsArrow = new ArrayList<>();
extractDictionaryEncodings(arrowSchema.getFields(), encodingsArrow);
Validator.compareDictionaries(encodingsJson, encodingsArrow, jsonReader, arrowReader);
boolean hasMoreJSON = jsonRoot != null;
boolean hasMoreArrow = iterator.hasNext();
if (hasMoreJSON || hasMoreArrow) {
throw new IllegalArgumentException("Unexpected RecordBatches. Total: " + totalBatches +
" J:" + hasMoreJSON + " " +
"A:" + hasMoreArrow);
}
}
}
};
public final boolean arrowExists;
public final boolean jsonExists;
Command(boolean arrowExists, boolean jsonExists) {
this.arrowExists = arrowExists;
this.jsonExists = jsonExists;
}
public abstract void execute(File arrowFile, File jsonFile) throws IOException;
}
}
| |
package com.cerner.beadledom.avro;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.google.common.collect.Lists;
import com.wordnik.swagger.converter.SwaggerSchemaConverter;
import com.wordnik.swagger.core.SwaggerSpec;
import com.wordnik.swagger.core.SwaggerTypes;
import com.wordnik.swagger.model.AllowableListValues;
import com.wordnik.swagger.model.AnyAllowableValues$;
import com.wordnik.swagger.model.Model;
import com.wordnik.swagger.model.ModelProperty;
import com.wordnik.swagger.model.ModelRef;
import java.lang.reflect.Field;
import java.util.Collections;
import javax.annotation.Nullable;
import org.apache.avro.Schema;
import org.apache.avro.specific.SpecificRecordBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Option;
import scala.collection.JavaConversions;
import scala.collection.immutable.Map;
import scala.collection.mutable.LinkedHashMap;
/**
* This produces Swagger model schemas for Avro generated classes, by looking at the Avro schema
* (rather than by inspecting the Java class for members and annotations).
*
* <p>This will only attempt to process classes which derive from
* {@link SpecificRecordBase} and contain a static field named SCHEMA$
* which is an instance of {@link Schema}. The default Avro code generator for Java
* produces such classes. If you need to handle other classes, override {@link #getSchema(Class)}.
*
* <p>All of the following are currently unsupported and will result in omitted fields:
* <ul>
* <li>schema type 'fixed'</li>
* <li>maps</li>
* <li>unions, except unions of 'null' with one other type</li>
* <li>nested collections such as {@code array<array<string>>} are unsupported, you can of
* course have a collection inside a record inside a collection</li>
* </ul>
*
* <p>Unions of 'null' and one other type will be treated as optional fields; all other fields will
* be assumed required.
*
* <p>Avro fields of type 'bytes' are represented as Swagger properties of type 'string', format
* 'byte'.
*
* <p>By default, field names are converted to snake case. You can override the
* {@link #getFieldName(Schema.Field)} method to change this.
*
* <p>To accommodate javadoc-style comments in avdl files, by default, if a line of a model/field
* description begins with whitespace followed by an asterisk, those characters (along with one
* subsequent whitespace character) will be removed. You can override the
* {@link #adjustDescription(String)} method to change this.
*/
public class SwaggerAvroModelConverter extends SwaggerSchemaConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerAvroModelConverter.class);
@Override
public Option<Model> read(Class<?> cls, Map<String, String> typeMap) {
Schema schema = getSchema(cls);
if (schema == null) {
return Option.empty();
}
LinkedHashMap<String, ModelProperty> properties = new LinkedHashMap<>();
for (Schema.Field field : schema.getFields()) {
ModelProperty property = parseField(field);
if (property == null) {
LOGGER.debug(
"Omitted field {} of schema {} from swagger docs", field.name(), schema.getName());
} else {
properties.update(getFieldName(field), property);
}
}
return Option.apply(
new Model(
toName(cls),
toName(cls),
cls.getName(),
properties,
toDescriptionOpt(cls),
Option.<String>empty(),
Option.<String>empty(),
JavaConversions.asScalaBuffer(Collections.<String>emptyList()).toList()));
}
@Override
public String toName(Class<?> cls) {
Schema schema = getSchema(cls);
if (schema == null) {
return super.toName(cls);
}
return getName(schema);
}
@Override
public Option<String> toDescriptionOpt(Class<?> cls) {
Schema schema = getSchema(cls);
if (schema == null) {
return Option.empty();
}
return Option.apply(adjustDescription(schema.getDoc()));
}
protected String getName(Schema schema) {
return schema.getName();
}
/**
* Generate a ModelProperty for the given schema.
*
* <p>This is used by {@link #parseField(Schema.Field)}, which is responsible for
* overriding the parts of the ModelProperty (such as position and description) that cannot be
* determined merely by looking at the schema. It may also be used recursively to build collection
* and union types.
*
* @return the parsed property, or null if it cannot/should not be represented in the Swagger
* model
*/
@Nullable
protected ModelProperty parseSchema(Schema schema) {
switch (schema.getType()) {
case RECORD:
return simpleProperty(getName(schema), schema.getFullName());
case ENUM:
// TODO may wish to include the enum's documentation in the field documentation, since it
// won't appear anywhere else
return new ModelProperty(
"string",
"string",
0,
true,
Option.<String>empty(),
new AllowableListValues(
JavaConversions.asScalaBuffer(schema.getEnumSymbols()).toList(),
"LIST"),
Option.<ModelRef>empty()
);
case ARRAY:
ModelProperty elementsProperty = parseSchema(schema.getElementType());
if (elementsProperty == null) {
return null;
}
if (SwaggerSpec.containerTypes().contains(elementsProperty.type())) {
LOGGER.debug("Cannot include nested collection schema in swagger docs: {}", schema);
return null;
}
return new ModelProperty(
"List",
"List",
elementsProperty.position(),
true,
elementsProperty.description(),
elementsProperty.allowableValues(),
Option.apply(modelRef(elementsProperty))
);
case BOOLEAN:
return simpleProperty("boolean", "boolean");
case UNION:
// We can't represent unions, except for the special case of a union with null, which can
// can be treated as a non-required field.
// In json-schema, 'required' is really about whether a field is guaranteed to have some
// value rather than whether that value is permitted to be null. It is unclear whether this
// is the intended meaning in swagger or not. But the behavior of this code should be
// acceptable on either interpretation.
java.util.List<Schema> memberSchemas = Lists.newArrayList();
for (Schema memberSchema : schema.getTypes()) {
if (memberSchema.getType() != Schema.Type.NULL) {
memberSchemas.add(memberSchema);
}
}
if (memberSchemas.size() > 1) {
LOGGER.debug(
"Cannot include schema with union (containing multiple non-null types) in swagger "
+ "docs: {}", schema);
return null;
} else if (memberSchemas.size() < 1) {
LOGGER.warn("Union has no non-null types, this should be impossible: {}", schema);
return null;
}
ModelProperty memberProperty = parseSchema(memberSchemas.get(0));
if (memberProperty == null) {
return null;
}
return new ModelProperty(
memberProperty.type(),
memberProperty.qualifiedType(),
memberProperty.position(),
false,
memberProperty.description(),
memberProperty.allowableValues(),
memberProperty.items()
);
case STRING:
return simpleProperty("string", "string");
case BYTES:
return simpleProperty("byte", "byte");
case INT:
return simpleProperty("int", "int");
case LONG:
return simpleProperty("long", "long");
case FLOAT:
return simpleProperty("float", "float");
case DOUBLE:
return simpleProperty("double", "double");
default:
// TODO support Schema.Type.FIXED
// Schema.Type.MAP is ignored because Swagger does not support maps
return null;
}
}
private ModelProperty simpleProperty(String type, String qualifiedType) {
return new ModelProperty(
type,
qualifiedType,
0,
true,
Option.<String>empty(),
AnyAllowableValues$.MODULE$,
Option.<ModelRef>empty()
);
}
private ModelRef modelRef(ModelProperty target) {
if (SwaggerTypes.primitives().contains(target.type())) {
return new ModelRef(
target.type(),
Option.<String>empty(),
Option.apply(target.qualifiedType())
);
}
return new ModelRef(
null,
Option.apply(target.type()),
Option.apply(target.qualifiedType())
);
}
/**
* Generate a ModelProperty for the given field.
*
* @return the parsed property, or null if the property should be excluded from the Swagger model
*/
@Nullable
protected ModelProperty parseField(Schema.Field field) {
ModelProperty property = parseSchema(field.schema());
if (property == null) {
return null;
}
return new ModelProperty(
property.type(),
property.qualifiedType(),
field.pos(),
property.required(),
Option.apply(adjustDescription(field.doc())),
property.allowableValues(),
property.items()
);
}
/**
* Return the Avro schema for the given class, or null if this converter should not handle this
* class.
*/
@Nullable
protected Schema getSchema(Class<?> cls) {
if (!SpecificRecordBase.class.isAssignableFrom(cls)) {
return null;
}
Field field;
try {
field = cls.getDeclaredField("SCHEMA$");
} catch (NoSuchFieldException e) {
return null;
}
Object schema;
try {
schema = field.get(null);
} catch (IllegalAccessException e) {
return null;
}
if (schema instanceof Schema) {
return (Schema) schema;
}
return null;
}
/**
* Given an Avro field, return the name that should be used for the Swagger property.
*/
protected String getFieldName(Schema.Field field) {
return ((PropertyNamingStrategy.SnakeCaseStrategy)
PropertyNamingStrategy.SNAKE_CASE)
.translate(field.name());
}
/**
* Given the doc string for an Avro entity, return the Swagger description to use.
*
* @param doc the avro doc string to adjust (may be null)
* @return the adjusted documentation, or null
*/
@Nullable
protected String adjustDescription(@Nullable String doc) {
if (doc == null) {
return null;
}
return doc.replaceAll("(?m)^\\s*\\*\\s?", "");
}
}
| |
package LeetCode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class SubstringwithConcatenationofAllWords {
// You are given a string, S, and a list of words, L, that are all of the
// same length.
// Find all starting indices of substring(s) in S that is a concatenation of
// each word
// in L exactly once and without any intervening characters.
public static ArrayList<Integer> findSubstring2(String S, String[] L) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> ans = new ArrayList<Integer>();
HashMap<String, Integer> ids = new HashMap<String, Integer>();
int m = S.length();
int n = L.length;
int len = L[0].length();
int[] need = new int[n];
for (int i = 0; i < n; i++) {
if (!ids.containsKey(L[i]))
ids.put(L[i], i);
need[ids.get(L[i])]++;
}
int[] s = new int[m];
for (int i = 0; i < m; i++) {
s[i] = -1;// there is a word in L that can be found start from s[i]
}
for (int i = 0; i < m - len + 1; ++i) {
String sub = S.substring(i, i + len);
if (ids.containsKey(sub)) {
s[i] = ids.get(sub);
}
}
for (int offset = 0; offset < len; offset++) {
int[] found = new int[n];
int count = 0, begin = offset;
for (int i = offset; i < m - len + 1; i += len) {
if (s[i] < 0) {
begin = i + len;
count = 0;
found = new int[n];
} else {
int id = s[i];
found[id]++;
if (need[id] > 0 && found[id] <= need[id]) {
count++;
}
if (count == n) {
ans.add(begin);
}
if ((i - begin) / len + 1 == n) {
id = s[begin];
if (need[id] > 0 && need[id] == found[id]) {
count--;
}
found[id]--;
begin += len;
}
}
}
}
return ans;
}
// pass both O(NL)
public static ArrayList<Integer> findSubstring1(String S, String[] L) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> ans = new ArrayList<Integer>();
HashMap<String, Integer> need = new HashMap<String, Integer>();
HashMap<String, Integer> found = new HashMap<String, Integer>();
for (String l : L) {
if (need.get(l) == null)
need.put(l, 1);
else
need.put(l, need.get(l) + 1);
}
int l = L[0].length();
int n = L.length;
loop:
for (int i = 0; i < S.length() - l * n + 1; i++) {
String sub = S.substring(i, i + l);
// if L has this sub
if (need.get(sub) != null) {
found.clear();
found.put(sub, 1);
// if i is the answer
// then i + n * L should contain all L
for (int j = 1; j < n; j++) {
int s = i + j * l;
sub = S.substring(s, s + l);
if (found.get(sub) == null)
found.put(sub, 1);
else
found.put(sub, found.get(sub) + 1);
Integer toFind = need.get(sub);
if (toFind == null)
continue loop;
Integer foundVal = found.get(sub);
if (foundVal > toFind)
continue loop;
found.put(sub, foundVal);
}
ans.add(i);
}
}
return ans;
}
// there exist linear algorithm
// pass both take longer time?
public static ArrayList<Integer> findSubstring(String S, String[] L) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> ret = new ArrayList<Integer>();
if (L.length == 0) {
return ret;
}
// I will create another string array without the duplcates
ArrayList<String> l = new ArrayList<String>();
ArrayList<Integer> c = new ArrayList<Integer>();
Arrays.sort(L);
for (int i = 0; i < L.length; i++) {
l.add(L[i]);
int count = 1;
while (i + 1 < L.length && L[i].equals(L[i + 1])) {
i++;
count++;
}
c.add(count);
}
int[] starts = new int[S.length()];
for (int i = 0; i < S.length(); i++) {
starts[i] = -1;
for (int j = 0; j < l.size(); j++) {
if (S.substring(i).startsWith(l.get(j))) {
starts[i] = j;
}
}
}
int step = L[0].length();
for (int i = 0; i <= S.length() - step * L.length; i++) {
int[] perm = new int[L.length];
boolean needTest = true;
for (int j = 0; j < L.length; j++) {
perm[j] = starts[i + j * step];
if (perm[j] == -1) {
needTest = false;
}
}
if (needTest && testPerm(perm, c)) {
ret.add(i);
}
}
return ret;
}
private static boolean testPerm(int[] perm, ArrayList<Integer> c) {
int[] count = new int[c.size()];
for (int i = 0; i < count.length; i++) {
count[i] = 0;
}
for (int i = 0; i < perm.length; i++) {
count[perm[i]]++;
}
for (int i = 0; i < count.length; i++) {
if (count[i] != c.get(i)) {
return false;
}
}
return true;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "lingmindraboofooowingdingbarrwingmonkeypoundcake";
String[] L = {"fooo", "barr", "wing", "ding", "wing"};
System.out.println(findSubstring2(s, L));
}
}
| |
/******************************************************************************
* Copyright (c) 2006, 2010 VMware Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
* is available at http://www.opensource.org/licenses/apache2.0.php.
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
* VMware Inc.
*****************************************************************************/
package org.eclipse.gemini.blueprint.context.support;
import org.eclipse.gemini.blueprint.context.DelegatedExecutionOsgiBundleApplicationContext;
import org.eclipse.gemini.blueprint.context.DependencyAwareBeanFactoryPostProcessor;
import org.eclipse.gemini.blueprint.context.DependencyInitializationAwareBeanPostProcessor;
import org.eclipse.gemini.blueprint.context.OsgiBundleApplicationContextExecutor;
import org.eclipse.gemini.blueprint.context.event.*;
import org.eclipse.gemini.blueprint.util.OsgiBundleUtils;
import org.eclipse.gemini.blueprint.util.OsgiStringUtils;
import org.eclipse.gemini.blueprint.util.internal.PrivilegedUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import java.io.IOException;
import java.util.*;
/**
* OSGi-specific application context that delegates the execution of its life cycle methods to a different class. The
* main reason behind this is to <em>break</em> the startup of the application context in steps that can be executed
* asynchronously. <p/> <p/> <p/> The {@link #refresh()} and {@link #close()} methods delegate their execution to an
* {@link OsgiBundleApplicationContextExecutor} class that chooses how to call the lifecycle methods. <p/> <p/> <p/> One
* can still call the 'traditional' lifecycle methods through {@link #normalRefresh()} and {@link #normalClose()}.
*
* @author Costin Leau
* @author Olaf Otto
*
* @see DelegatedExecutionOsgiBundleApplicationContext
*/
public abstract class AbstractDelegatedExecutionApplicationContext extends AbstractOsgiBundleApplicationContext
implements DelegatedExecutionOsgiBundleApplicationContext {
/**
* Executor that offers the traditional way of <code>refreshing</code>/ <code>closing</code> of an
* ApplicationContext (no conditions have to be met and the refresh happens in only one step).
*
* @author Costin Leau
*/
private static class NoDependenciesWaitRefreshExecutor implements OsgiBundleApplicationContextExecutor {
private final DelegatedExecutionOsgiBundleApplicationContext context;
private NoDependenciesWaitRefreshExecutor(DelegatedExecutionOsgiBundleApplicationContext ctx) {
context = ctx;
}
public void refresh() throws BeansException, IllegalStateException {
context.normalRefresh();
}
public void close() {
context.normalClose();
}
}
/**
* BeanPostProcessor that logs an info message when a bean is created during BeanPostProcessor instantiation, i.e.
* when a bean is not eligible for getting processed by all BeanPostProcessors.
*/
private class BeanPostProcessorChecker implements BeanPostProcessor {
private final ConfigurableListableBeanFactory beanFactory;
private final int beanPostProcessorTargetCount;
public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
this.beanFactory = beanFactory;
this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (!(bean instanceof BeanPostProcessor)
&& this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
if (logger.isInfoEnabled()) {
logger.info("Bean '" + beanName + "' is not eligible for getting processed by all "
+ "BeanPostProcessors (for example: not eligible for auto-proxying)");
}
}
return bean;
}
}
/**
* Default executor
*/
private OsgiBundleApplicationContextExecutor executor = new NoDependenciesWaitRefreshExecutor(this);
/**
* monitor used during refresh/close
*/
private final Object startupShutdownMonitor = new Object();
/**
* Delegated multicaster
*/
private OsgiBundleApplicationContextEventMulticaster delegatedMulticaster;
private ContextClassLoaderProvider cclProvider;
/**
* Constructs a new <code>AbstractDelegatedExecutionApplicationContext</code> instance.
*/
public AbstractDelegatedExecutionApplicationContext() {
super();
}
/**
* Constructs a new <code>AbstractDelegatedExecutionApplicationContext</code> instance.
*
* @param parent parent application context
*/
public AbstractDelegatedExecutionApplicationContext(ApplicationContext parent) {
super(parent);
}
/**
* Delegate execution of refresh method to a third party. This allows breaking the refresh process into several
* small pieces providing continuation-like behaviour or completion of the refresh method on several threads, in a
* asynch manner. <p/> By default, the refresh method in executed in <em>one go</em> (normal behaviour). <p/>
* {@inheritDoc}
*/
public void refresh() throws BeansException, IllegalStateException {
executor.refresh();
}
public void normalRefresh() {
Assert.notNull(getBundleContext(), "bundle context should be set before refreshing the application context");
try {
PrivilegedUtils.executeWithCustomTCCL(contextClassLoaderProvider().getContextClassLoader(),
new PrivilegedUtils.UnprivilegedExecution() {
public Object run() {
AbstractDelegatedExecutionApplicationContext.super.refresh();
sendRefreshedEvent();
return null;
}
});
} catch (Throwable th) {
if (logger.isDebugEnabled()) {
logger.debug("Refresh error", th);
}
sendFailedEvent(th);
// propagate exception to the caller
// rethrow the problem w/o rewrapping
if (th instanceof RuntimeException) {
throw (RuntimeException) th;
} else {
throw (Error) th;
}
}
}
public void normalClose() {
try {
PrivilegedUtils.executeWithCustomTCCL(contextClassLoaderProvider().getContextClassLoader(),
new PrivilegedUtils.UnprivilegedExecution() {
public Object run() {
AbstractDelegatedExecutionApplicationContext.super.doClose();
sendClosedEvent();
return null;
}
});
} catch (Throwable th) {
// send failure event
sendClosedEvent(th);
// rethrow the problem w/o rewrapping
if (th instanceof RuntimeException) {
throw (RuntimeException) th;
} else {
throw (Error) th;
}
}
}
// Adds behaviour for isAvailable flag.
protected void doClose() {
executor.close();
}
public void startRefresh() {
try {
PrivilegedUtils.executeWithCustomTCCL(contextClassLoaderProvider().getContextClassLoader(),
new PrivilegedUtils.UnprivilegedExecution<Object>() {
public Object run() {
synchronized (startupShutdownMonitor) {
if (ObjectUtils.isEmpty(getConfigLocations())) {
setConfigLocations(getDefaultConfigLocations());
}
if (!OsgiBundleUtils.isBundleActive(getBundle())
&& !OsgiBundleUtils.isBundleLazyActivated(getBundle())) {
throw new ApplicationContextException(
"Unable to refresh application context: bundle is neither active nor lazy-activated but "
+ OsgiStringUtils.bundleStateAsString(getBundle()));
}
ConfigurableListableBeanFactory beanFactory = null;
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean
// factory.
beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in
// context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans
// in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean
// creation.
registerBeanPostProcessors(beanFactory,
DependencyInitializationAwareBeanPostProcessor.class, null, false);
return null;
} catch (BeansException ex) {
// Destroy already created singletons to avoid
// dangling resources.
beanFactory.destroySingletons();
cancelRefresh(ex);
// propagate exception to the caller
throw ex;
}
}
}
});
} catch (Throwable th) {
if (logger.isDebugEnabled()) {
logger.debug("Pre refresh error", th);
}
// send failure event
sendFailedEvent(th);
// rethrow the problem w/o rewrapping
if (th instanceof RuntimeException) {
throw (RuntimeException) th;
} else {
throw (Error) th;
}
}
}
public void completeRefresh() {
try {
PrivilegedUtils.executeWithCustomTCCL(contextClassLoaderProvider().getContextClassLoader(),
new PrivilegedUtils.UnprivilegedExecution<Object>() {
public Object run() {
synchronized (startupShutdownMonitor) {
try {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// Invoke factory processors registered as beans
// in the context.
invokeBeanFactoryPostProcessors(beanFactory,
DependencyAwareBeanFactoryPostProcessor.class, null);
// Register bean processors that intercept bean
// creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this
// context.
initApplicationEventMulticaster();
// Initialize other special beans in specific
// context
// subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init)
// singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
// everything went okay, post notification
sendRefreshedEvent();
return null;
} catch (BeansException ex) {
// Destroy already created singletons to avoid
// dangling
// resources.
getBeanFactory().destroySingletons();
cancelRefresh(ex);
// propagate exception to the caller
throw ex;
}
}
}
});
} catch (Throwable th) {
if (logger.isDebugEnabled()) {
logger.debug("Post refresh error", th);
}
// post notification
sendFailedEvent(th);
// rethrow the problem w/o rewrapping
if (th instanceof RuntimeException) {
throw (RuntimeException) th;
} else {
throw (Error) th;
}
}
}
// customized to handle DependencyAwareBeanFactoryPostProcessor classes
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
invokeBeanFactoryPostProcessors(beanFactory, BeanFactoryPostProcessor.class,
DependencyAwareBeanFactoryPostProcessor.class);
}
/**
* This version of the original
* {@link org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory, List) post processor invocation}
* implementation adds including and excluding processor types to allow for a multi-staged
* context initialization, see for instance {{@link #completeRefresh()}}.
*
* @param beanFactory must not be <code>null</code>
* @param include only invoke post processors that are assignment-compatible with this type. Must not be <code>null</code>
* @param exclude exclude all post processors that are assignment-compatible with this type. Can be <code>null</code>
*/
private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory,
Class<? extends BeanFactoryPostProcessor> include,
Class<? extends BeanFactoryPostProcessor> exclude) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<String>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
new LinkedList<BeanDefinitionRegistryPostProcessor>();
for (BeanFactoryPostProcessor postProcessor : getBeanFactoryPostProcessors()) {
if (isExcluded(include, exclude, postProcessor)) {
continue;
}
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryPostProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
registryPostProcessors.add(registryPostProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
if (include.isAssignableFrom(BeanDefinitionRegistryPostProcessor.class)) {
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
registryPostProcessors.addAll(priorityOrderedPostProcessors);
invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(beanFactory, orderedPostProcessors);
registryPostProcessors.addAll(orderedPostProcessors);
invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
registryPostProcessors.add(pp);
processedBeans.add(ppName);
pp.postProcessBeanDefinitionRegistry(registry);
reiterate = true;
}
}
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
}
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(getBeanFactoryPostProcessors(), beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(include, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName) || exclude != null && isTypeMatch(ppName, exclude)) {
continue;
}
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, include));
} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
} else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, include));
}
sortPostProcessors(beanFactory, orderedPostProcessors);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, include));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
private boolean isExcluded(Class<? extends BeanFactoryPostProcessor> include, Class<? extends BeanFactoryPostProcessor> exclude, BeanFactoryPostProcessor postProcessor) {
return !include.isInstance(postProcessor) || exclude != null && exclude.isInstance(postProcessor);
}
/**
* Invoke the given BeanDefinitionRegistryPostProcessor beans.
*/
private static void invokeBeanDefinitionRegistryPostProcessors(
Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {
for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanDefinitionRegistry(registry);
}
}
/**
* Invoke the given BeanFactoryPostProcessor beans.
*/
private static void invokeBeanFactoryPostProcessors(
Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanFactory(beanFactory);
}
}
private static void sortPostProcessors(ConfigurableListableBeanFactory beanFactory, List<?> postProcessors) {
Comparator<Object> comparatorToUse = null;
if (beanFactory instanceof DefaultListableBeanFactory) {
comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
}
if (comparatorToUse == null) {
comparatorToUse = OrderComparator.INSTANCE;
}
Collections.sort(postProcessors, comparatorToUse);
}
// customized to handle DependencyInitializationAwareBeanPostProcessor
// classes
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
registerBeanPostProcessors(beanFactory, BeanPostProcessor.class,
DependencyInitializationAwareBeanPostProcessor.class, true);
}
/**
* Instantiate and invoke all registered BeanPostProcessor beans, respecting explicit order if given. <p/> Must be
* called before any instantiation of application beans. Very similar to
* {@link AbstractApplicationContext#invokeBeanFactoryPostProcessors} but allowing exclusion of a certain type.
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, Class<?> type,
Class<?> exclude, boolean check) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(type, true, false);
if (check) {
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e.
// when
// a bean is not eligible for getting processed by all
// BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
}
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (int i = 0; i < postProcessorNames.length; i++) {
// check exclude type first
if (exclude == null || !isTypeMatch(postProcessorNames[i], exclude)) {
if (isTypeMatch(postProcessorNames[i], PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(postProcessorNames[i],
BeanPostProcessor.class));
} else if (isTypeMatch(postProcessorNames[i], Ordered.class)) {
orderedPostProcessorNames.add(postProcessorNames[i]);
} else {
nonOrderedPostProcessorNames.add(postProcessorNames[i]);
}
}
}
// First, register the BeanPostProcessors that implement
// PriorityOrdered.
Collections.sort(priorityOrderedPostProcessors, new OrderComparator());
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(getBean(postProcessorName, BeanPostProcessor.class));
}
Collections.sort(orderedPostProcessors, new OrderComparator());
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Finally, register all other BeanPostProcessors.
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(getBean(postProcessorName, BeanPostProcessor.class));
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
}
/**
* Register the given BeanPostProcessor beans.
*/
private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory,
List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
public void setExecutor(OsgiBundleApplicationContextExecutor executor) {
this.executor = executor;
}
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException, BeansException {
}
public void setDelegatedEventMulticaster(OsgiBundleApplicationContextEventMulticaster multicaster) {
this.delegatedMulticaster = multicaster;
}
/**
* Sets the OSGi multicaster by using a Spring {@link ApplicationEventMulticaster}. This method is added as a
* covenience.
*
* @param multicaster Spring multi-caster used for propagating OSGi specific events
* @see OsgiBundleApplicationContextEventMulticasterAdapter
*/
public void setDelegatedEventMulticaster(ApplicationEventMulticaster multicaster) {
this.delegatedMulticaster = new OsgiBundleApplicationContextEventMulticasterAdapter(multicaster);
}
public OsgiBundleApplicationContextEventMulticaster getDelegatedEventMulticaster() {
return this.delegatedMulticaster;
}
private void sendFailedEvent(Throwable cause) {
if (delegatedMulticaster != null)
delegatedMulticaster.multicastEvent(new OsgiBundleContextFailedEvent(this, this.getBundle(), cause));
}
private void sendRefreshedEvent() {
if (delegatedMulticaster != null)
delegatedMulticaster.multicastEvent(new OsgiBundleContextRefreshedEvent(this, this.getBundle()));
}
private void sendClosedEvent() {
if (delegatedMulticaster != null)
delegatedMulticaster.multicastEvent(new OsgiBundleContextClosedEvent(this, this.getBundle()));
}
private void sendClosedEvent(Throwable cause) {
if (delegatedMulticaster != null)
delegatedMulticaster.multicastEvent(new OsgiBundleContextClosedEvent(this, this.getBundle(), cause));
}
/**
* private method used for doing lazy-init-if-not-set for cclProvider
*/
private ContextClassLoaderProvider contextClassLoaderProvider() {
if (cclProvider == null) {
DefaultContextClassLoaderProvider defaultProvider = new DefaultContextClassLoaderProvider();
defaultProvider.setBeanClassLoader(getClassLoader());
cclProvider = defaultProvider;
}
return cclProvider;
}
/**
* Sets the {@link ContextClassLoaderProvider} used by this OSGi application context instance. By default,
* {@link DefaultContextClassLoaderProvider} is used.
*
* @param contextClassLoaderProvider context class loader provider to use
* @see ContextClassLoaderProvider
* @see DefaultContextClassLoaderProvider
*/
public void setContextClassLoaderProvider(ContextClassLoaderProvider contextClassLoaderProvider) {
this.cclProvider = contextClassLoaderProvider;
}
}
| |
// 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.externalSystem.service.project.manage;
import com.intellij.concurrency.ConcurrentCollectionFactory;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.externalSystem.ExternalSystemManager;
import com.intellij.openapi.externalSystem.model.*;
import com.intellij.openapi.externalSystem.model.internal.InternalExternalProjectInfo;
import com.intellij.openapi.externalSystem.model.project.ExternalConfigPathAware;
import com.intellij.openapi.externalSystem.model.project.ExternalProjectPojo;
import com.intellij.openapi.externalSystem.model.project.ModuleData;
import com.intellij.openapi.externalSystem.model.project.ProjectData;
import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemLocalSettings;
import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
import com.intellij.openapi.module.ModuleTypeId;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.Alarm;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.xmlb.annotations.MapAnnotation;
import com.intellij.util.xmlb.annotations.Property;
import com.intellij.util.xmlb.annotations.XCollection;
import com.intellij.util.xmlb.annotations.XMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.intellij.openapi.externalSystem.model.ProjectKeys.MODULE;
import static com.intellij.openapi.externalSystem.model.ProjectKeys.PROJECT;
/**
* @author Vladislav.Soroka
*/
@State(name = "ExternalProjectsData", storages = {@Storage(StoragePathMacros.WORKSPACE_FILE)})
public class ExternalProjectsDataStorage implements SettingsSavingComponent, PersistentStateComponent<ExternalProjectsDataStorage.State> {
private static final Logger LOG = Logger.getInstance(ExternalProjectsDataStorage.class);
private static final String STORAGE_VERSION = ExternalProjectsDataStorage.class.getSimpleName() + ".2";
@NotNull
private final Project myProject;
private final Alarm myAlarm;
@NotNull
private final Map<Pair<ProjectSystemId, File>, InternalExternalProjectInfo> myExternalRootProjects =
ConcurrentCollectionFactory.createMap(ExternalSystemUtil.HASHING_STRATEGY);
private final AtomicBoolean changed = new AtomicBoolean();
private State myState = new State();
public static ExternalProjectsDataStorage getInstance(@NotNull Project project) {
return ServiceManager.getService(project, ExternalProjectsDataStorage.class);
}
public ExternalProjectsDataStorage(@NotNull Project project) {
myProject = project;
myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myProject);
}
@TestOnly
public ExternalProjectsDataStorage(@NotNull Project project, @NotNull Alarm alarm) {
myProject = project;
myAlarm = alarm;
}
public synchronized void load() {
myExternalRootProjects.clear();
long startTs = System.currentTimeMillis();
try {
final Collection<InternalExternalProjectInfo> projectInfos = load(myProject);
if (projectInfos.isEmpty() &&
myProject.getUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT) != Boolean.TRUE &&
hasLinkedExternalProjects()) {
markDirtyAllExternalProjects();
}
for (InternalExternalProjectInfo projectInfo : projectInfos) {
if (validate(projectInfo)) {
myExternalRootProjects.put(
Pair.create(projectInfo.getProjectSystemId(), new File(projectInfo.getExternalProjectPath())), projectInfo);
if (projectInfo.getLastImportTimestamp() != projectInfo.getLastSuccessfulImportTimestamp()) {
markDirty(projectInfo.getExternalProjectPath());
}
}
else {
String projectPath = projectInfo.getNullSafeExternalProjectPath();
if (projectPath != null) {
markDirty(projectPath);
}
}
}
}
catch (IOException e) {
LOG.debug(e);
markDirtyAllExternalProjects();
}
mergeLocalSettings();
long finishTs = System.currentTimeMillis();
LOG.info("Loaded external projects data in " + (finishTs - startTs) + " millis");
}
private boolean hasLinkedExternalProjects() {
return ExternalSystemApiUtil.getAllManagers().stream()
.anyMatch(manager -> !manager.getSettingsProvider().fun(myProject).getLinkedProjectsSettings().isEmpty());
}
private void markDirtyAllExternalProjects() {
ExternalProjectsManager.getInstance(myProject).getExternalProjectsWatcher().markDirtyAllExternalProjects();
}
private void markDirty(String projectPath) {
ExternalProjectsManager.getInstance(myProject).getExternalProjectsWatcher().markDirty(projectPath);
}
private static boolean validate(InternalExternalProjectInfo externalProjectInfo) {
try {
final DataNode<ProjectData> projectStructure = externalProjectInfo.getExternalProjectStructure();
if (projectStructure == null) return false;
ProjectDataManagerImpl.getInstance().ensureTheDataIsReadyToUse(projectStructure);
return externalProjectInfo.getExternalProjectPath().equals(projectStructure.getData().getLinkedExternalProjectPath());
}
catch (Exception e) {
LOG.warn(e);
}
return false;
}
@Override
public synchronized void save() {
if (!changed.compareAndSet(true, false)) return;
myAlarm.cancelAllRequests();
myAlarm.addRequest(new MySaveTask(myProject, myExternalRootProjects.values()), 0);
}
@TestOnly
public synchronized void saveAndWait() throws Exception {
LOG.assertTrue(ApplicationManager.getApplication().isUnitTestMode(), "This method is available for tests only");
save();
myAlarm.waitForAllExecuted(10, TimeUnit.SECONDS);
}
synchronized void update(@NotNull ExternalProjectInfo externalProjectInfo) {
restoreInclusionSettings(externalProjectInfo.getExternalProjectStructure());
final ProjectSystemId projectSystemId = externalProjectInfo.getProjectSystemId();
final String projectPath = externalProjectInfo.getExternalProjectPath();
DataNode<ProjectData> externalProjectStructure = externalProjectInfo.getExternalProjectStructure();
long lastSuccessfulImportTimestamp = externalProjectInfo.getLastSuccessfulImportTimestamp();
long lastImportTimestamp = externalProjectInfo.getLastImportTimestamp();
final Pair<ProjectSystemId, File> key = Pair.create(projectSystemId, new File(projectPath));
final InternalExternalProjectInfo old = myExternalRootProjects.get(key);
if (old != null) {
lastImportTimestamp = externalProjectInfo.getLastImportTimestamp();
if (lastSuccessfulImportTimestamp == -1) {
lastSuccessfulImportTimestamp = old.getLastSuccessfulImportTimestamp();
}
if (externalProjectInfo.getExternalProjectStructure() == null) {
externalProjectStructure = old.getExternalProjectStructure();
}
else {
externalProjectStructure = externalProjectInfo.getExternalProjectStructure().graphCopy();
}
}
else {
externalProjectStructure = externalProjectStructure != null ? externalProjectStructure.graphCopy() : null;
}
InternalExternalProjectInfo merged = new InternalExternalProjectInfo(
projectSystemId,
projectPath,
externalProjectStructure
);
merged.setLastImportTimestamp(lastImportTimestamp);
merged.setLastSuccessfulImportTimestamp(lastSuccessfulImportTimestamp);
myExternalRootProjects.put(key, merged);
changed.set(true);
}
synchronized void restoreInclusionSettings(@Nullable DataNode<ProjectData> projectDataNode) {
if (projectDataNode == null) return;
final String rootProjectPath = projectDataNode.getData().getLinkedExternalProjectPath();
final ProjectState projectState = myState.map.get(rootProjectPath);
if (projectState == null) return;
ExternalSystemApiUtil.visit(projectDataNode, node -> {
final DataNode<ExternalConfigPathAware> projectOrModuleNode = resolveProjectNode(node);
assert projectOrModuleNode != null;
final ModuleState moduleState = projectState.map.get(projectOrModuleNode.getData().getLinkedExternalProjectPath());
node.setIgnored(isIgnored(projectState, moduleState, node.getKey()));
});
}
synchronized void saveInclusionSettings(@Nullable DataNode<ProjectData> projectDataNode) {
if (projectDataNode == null) return;
final MultiMap<String, String> inclusionMap = MultiMap.create();
final MultiMap<String, String> exclusionMap = MultiMap.create();
ExternalSystemApiUtil.visit(projectDataNode, dataNode -> {
DataNode<ExternalConfigPathAware> projectNode = resolveProjectNode(dataNode);
if (projectNode != null) {
final String projectPath = projectNode.getData().getLinkedExternalProjectPath();
if (projectNode.isIgnored() || dataNode.isIgnored()) {
exclusionMap.putValue(projectPath, dataNode.getKey().getDataType());
}
else {
inclusionMap.putValue(projectPath, dataNode.getKey().getDataType());
}
}
});
final MultiMap<String, String> map;
ProjectState projectState = new ProjectState();
if (inclusionMap.size() < exclusionMap.size()) {
projectState.isInclusion = true;
map = inclusionMap;
}
else {
projectState.isInclusion = false;
map = exclusionMap;
}
for (String path : map.keySet()) {
projectState.map.put(path, new ModuleState(map.get(path)));
}
myState.map.put(projectDataNode.getData().getLinkedExternalProjectPath(), projectState);
changed.set(true);
}
@Nullable
synchronized ExternalProjectInfo get(@NotNull ProjectSystemId projectSystemId, @NotNull String externalProjectPath) {
return myExternalRootProjects.get(Pair.create(projectSystemId, new File(externalProjectPath)));
}
synchronized void remove(@NotNull ProjectSystemId projectSystemId, @NotNull String externalProjectPath) {
final InternalExternalProjectInfo removed = myExternalRootProjects.remove(Pair.create(projectSystemId, new File(externalProjectPath)));
if (removed != null) {
changed.set(true);
}
}
@NotNull
synchronized Collection<ExternalProjectInfo> list(@NotNull final ProjectSystemId projectSystemId) {
return ContainerUtil.mapNotNull(myExternalRootProjects.values(),
info -> projectSystemId.equals(info.getProjectSystemId()) ? info : null);
}
private void mergeLocalSettings() {
for (ExternalSystemManager<?, ?, ?, ?, ?> manager : ExternalSystemApiUtil.getAllManagers()) {
final ProjectSystemId systemId = manager.getSystemId();
AbstractExternalSystemLocalSettings settings = manager.getLocalSettingsProvider().fun(myProject);
final Map<ExternalProjectPojo, Collection<ExternalProjectPojo>> availableProjects = settings.getAvailableProjects();
for (Map.Entry<ExternalProjectPojo, Collection<ExternalProjectPojo>> entry : availableProjects.entrySet()) {
final ExternalProjectPojo projectPojo = entry.getKey();
final String externalProjectPath = projectPojo.getPath();
final Pair<ProjectSystemId, File> key = Pair.create(systemId, new File(externalProjectPath));
InternalExternalProjectInfo externalProjectInfo = myExternalRootProjects.get(key);
if (externalProjectInfo == null) {
final DataNode<ProjectData> dataNode = convert(systemId, projectPojo, entry.getValue());
externalProjectInfo = new InternalExternalProjectInfo(systemId, externalProjectPath, dataNode);
myExternalRootProjects.put(key, externalProjectInfo);
ExternalProjectsManager.getInstance(myProject).getExternalProjectsWatcher().markDirty(externalProjectPath);
changed.set(true);
}
// restore linked project sub-modules
ExternalProjectSettings linkedProjectSettings =
manager.getSettingsProvider().fun(myProject).getLinkedProjectSettings(externalProjectPath);
if (linkedProjectSettings != null && ContainerUtil.isEmpty(linkedProjectSettings.getModules())) {
final Set<String> modulePaths = ContainerUtil.map2Set(
ExternalSystemApiUtil.findAllRecursively(externalProjectInfo.getExternalProjectStructure(), MODULE),
node -> node.getData().getLinkedExternalProjectPath());
linkedProjectSettings.setModules(modulePaths);
}
}
}
}
private static DataNode<ProjectData> convert(@NotNull ProjectSystemId systemId,
@NotNull ExternalProjectPojo rootProject,
@NotNull Collection<? extends ExternalProjectPojo> childProjects) {
ProjectData projectData = new ProjectData(systemId, rootProject.getName(), rootProject.getPath(), rootProject.getPath());
DataNode<ProjectData> projectDataNode = new DataNode<>(PROJECT, projectData, null);
for (ExternalProjectPojo childProject : childProjects) {
String moduleConfigPath = childProject.getPath();
ModuleData moduleData = new ModuleData(childProject.getName(), systemId,
ModuleTypeId.JAVA_MODULE, childProject.getName(),
moduleConfigPath, moduleConfigPath);
projectDataNode.createChild(MODULE, moduleData);
}
return projectDataNode;
}
private static void doSave(@NotNull final Project project, @NotNull Collection<InternalExternalProjectInfo> externalProjects)
throws IOException {
final Path projectConfigurationFile = getProjectConfigurationFile(project);
if (!FileUtil.createParentDirs(projectConfigurationFile.toFile())) {
throw new IOException("Unable to save " + projectConfigurationFile);
}
for (Iterator<InternalExternalProjectInfo> iterator = externalProjects.iterator(); iterator.hasNext(); ) {
InternalExternalProjectInfo externalProject = iterator.next();
if (!validate(externalProject)) {
iterator.remove();
continue;
}
ExternalSystemApiUtil.visit(externalProject.getExternalProjectStructure(), dataNode -> {
try {
dataNode.checkIsSerializable();
}
catch (IOException e) {
dataNode.clear(true);
}
});
}
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(projectConfigurationFile)));
try {
out.writeUTF(STORAGE_VERSION);
out.writeInt(externalProjects.size());
ObjectOutputStream os = new ObjectOutputStream(out);
try {
for (InternalExternalProjectInfo externalProject : externalProjects) {
os.writeObject(externalProject);
}
}
finally {
os.close();
}
}
finally {
out.close();
}
}
@SuppressWarnings("unchecked")
@Nullable
private static DataNode<ExternalConfigPathAware> resolveProjectNode(@NotNull DataNode node) {
if ((MODULE.equals(node.getKey()) || PROJECT.equals(node.getKey())) && node.getData() instanceof ExternalConfigPathAware) {
return (DataNode<ExternalConfigPathAware>)node;
}
DataNode parent = ExternalSystemApiUtil.findParent(node, MODULE);
if (parent == null) {
parent = ExternalSystemApiUtil.findParent(node, PROJECT);
}
return parent;
}
@NotNull
private static Collection<InternalExternalProjectInfo> load(@NotNull Project project) throws IOException {
SmartList<InternalExternalProjectInfo> projects = new SmartList<>();
final Path configurationFile = getProjectConfigurationFile(project);
if (!configurationFile.toFile().isFile()) return projects;
DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(configurationFile)));
try {
final String storage_version = in.readUTF();
if (!STORAGE_VERSION.equals(storage_version)) return projects;
final int size = in.readInt();
ObjectInputStream os = new ObjectInputStream(in);
try {
for (int i = 0; i < size; i++) {
InternalExternalProjectInfo projectDataDataNode = (InternalExternalProjectInfo)os.readObject();
projects.add(projectDataDataNode);
}
}
catch (Exception e) {
throw new IOException(e);
}
finally {
os.close();
}
}
finally {
in.close();
}
return projects;
}
@NotNull
private static Path getProjectConfigurationFile(@NotNull Project project) {
return getProjectConfigurationDir(project).resolve("project.dat");
}
@NotNull
public static Path getProjectConfigurationDir(@NotNull Project project) {
return ProjectUtil.getExternalConfigurationDir(project);
}
@Nullable
@Override
public synchronized State getState() {
return myState;
}
@Override
public synchronized void loadState(@NotNull State state) {
myState = state == null ? new State() : state;
}
synchronized void setIgnored(@NotNull final DataNode<?> dataNode, final boolean isIgnored) {
//noinspection unchecked
final DataNode<ProjectData> projectDataNode =
PROJECT.equals(dataNode.getKey()) ? (DataNode<ProjectData>)dataNode : ExternalSystemApiUtil.findParent(dataNode, PROJECT);
if (projectDataNode == null) {
return;
}
ExternalSystemApiUtil.visit(dataNode, node -> node.setIgnored(isIgnored));
saveInclusionSettings(projectDataNode);
}
synchronized boolean isIgnored(@NotNull String rootProjectPath, @NotNull String modulePath, @NotNull Key key) {
final ProjectState projectState = myState.map.get(rootProjectPath);
if (projectState == null) return false;
final ModuleState moduleState = projectState.map.get(modulePath);
return isIgnored(projectState, moduleState, key);
}
private static boolean isIgnored(@NotNull ProjectState projectState, @Nullable ModuleState moduleState, @NotNull Key<?> key) {
return projectState.isInclusion ^ (moduleState != null && moduleState.set.contains(key.getDataType()));
}
static class State {
@Property(surroundWithTag = false)
@MapAnnotation(surroundWithTag = false, surroundValueWithTag = false, surroundKeyWithTag = false,
keyAttributeName = "path", entryTagName = "projectState")
public final Map<String, ProjectState> map = ContainerUtil.newConcurrentMap();
}
static class ProjectState {
@Property(surroundWithTag = false)
@XMap(keyAttributeName = "path", entryTagName = "dataType")
public final Map<String, ModuleState> map = ContainerUtil.newConcurrentMap();
public boolean isInclusion;
}
static class ModuleState {
@Property(surroundWithTag = false)
@XCollection(elementName = "id")
public final Set<String> set = ContainerUtil.newConcurrentSet();
ModuleState() {
}
ModuleState(Collection<String> values) {
set.addAll(values);
}
}
private static class MySaveTask implements Runnable {
private final Project myProject;
private final Collection<InternalExternalProjectInfo> myExternalProjects;
MySaveTask(Project project, Collection<InternalExternalProjectInfo> externalProjects) {
myProject = project;
myExternalProjects = ContainerUtil.map(externalProjects, info -> (InternalExternalProjectInfo)info.copy());
}
@Override
public void run() {
try {
doSave(myProject, myExternalProjects);
}
catch (IOException e) {
LOG.debug(e);
}
}
}
}
| |
/*
* Copyright 2014 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.samples.apps.iosched.util;
import android.app.*;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.samples.apps.iosched.BuildConfig;
import com.google.samples.apps.iosched.Config;
import com.google.samples.apps.iosched.R;
import java.util.List;
import static com.google.samples.apps.iosched.util.LogUtils.makeLogTag;
public class WiFiUtils {
// Preference key and values associated with WiFi AP configuration.
public static final String PREF_WIFI_AP_CONFIG = "pref_wifi_ap_config";
public static final String WIFI_CONFIG_DONE = "done";
public static final String WIFI_CONFIG_REQUESTED = "requested";
private static final String TAG = makeLogTag(WiFiUtils.class);
public static void installConferenceWiFi(final Context context) {
// Create config
WifiConfiguration config = new WifiConfiguration();
// Must be in double quotes to tell system this is an ASCII SSID and passphrase.
config.SSID = String.format("\"%s\"", Config.WIFI_SSID);
config.preSharedKey = String.format("\"%s\"", Config.WIFI_PASSPHRASE);
// Store config
final WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int netId = wifiManager.addNetwork(config);
if (netId != -1) {
wifiManager.enableNetwork(netId, false);
boolean result = wifiManager.saveConfiguration();
if (!result) {
Log.e(TAG, "Unknown error while calling WiFiManager.saveConfiguration()");
Toast.makeText(context,
context.getResources().getString(R.string.wifi_install_error_message),
Toast.LENGTH_SHORT).show();
}
} else {
Log.e(TAG, "Unknown error while calling WiFiManager.addNetwork()");
Toast.makeText(context,
context.getResources().getString(R.string.wifi_install_error_message),
Toast.LENGTH_SHORT).show();
}
}
/**
* Helper method to decide whether to bypass conference WiFi setup. Return true if
* WiFi AP is already configured (WiFi adapter enabled) or WiFi configuration is complete
* as per shared preference.
*/
public static boolean shouldBypassWiFiSetup(final Context context) {
final WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// Is WiFi on?
if (wifiManager.isWifiEnabled()) {
// Check for existing APs.
final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
final String conferenceSSID = String.format("\"%s\"", Config.WIFI_SSID);
for(WifiConfiguration config : configs) {
if (conferenceSSID.equalsIgnoreCase(config.SSID)) return true;
}
}
return WIFI_CONFIG_DONE.equals(getWiFiConfigStatus(context));
}
public static boolean isWiFiEnabled(final Context context) {
final WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
return wifiManager.isWifiEnabled();
}
public static boolean isWiFiApConfigured(final Context context) {
final WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
if (configs == null) return false;
// Check for existing APs.
final String conferenceSSID = String.format("\"%s\"", Config.WIFI_SSID);
for(WifiConfiguration config : configs) {
if (conferenceSSID.equalsIgnoreCase(config.SSID)) return true;
}
return false;
}
// Stored preferences associated with WiFi AP configuration.
public static String getWiFiConfigStatus(final Context context) {
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(PREF_WIFI_AP_CONFIG, null);
}
public static void setWiFiConfigStatus(final Context context, final String status) {
if (!WIFI_CONFIG_DONE.equals(status) && !WIFI_CONFIG_REQUESTED.equals(status))
throw new IllegalArgumentException("Invalid WiFi Config status: " + status);
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PREF_WIFI_AP_CONFIG, status).commit();
}
public static boolean installWiFiIfRequested(final Context context) {
if (WIFI_CONFIG_REQUESTED.equals(getWiFiConfigStatus(context)) && isWiFiEnabled(context)) {
installConferenceWiFi(context);
if (isWiFiApConfigured(context)) {
setWiFiConfigStatus(context, WiFiUtils.WIFI_CONFIG_DONE);
return true;
}
}
return false;
}
public static void showWiFiDialog(Activity activity) {
FragmentManager fm = activity.getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_wifi");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new WiFiDialog(isWiFiEnabled(activity)).show(ft, "dialog_wifi");
}
public static class WiFiDialog extends DialogFragment {
private boolean mWiFiEnabled;
public WiFiDialog() {}
public WiFiDialog(boolean wifiEnabled) {
super();
mWiFiEnabled = wifiEnabled;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final int padding =
getResources().getDimensionPixelSize(R.dimen.content_padding_normal);
final TextView wifiTextView = new TextView(getActivity());
int dialogCallToActionText;
int dialogPositiveButtonText;
if (mWiFiEnabled) {
dialogCallToActionText = R.string.calltoaction_wifi_configure;
dialogPositiveButtonText = R.string.wifi_dialog_button_configure;
} else {
dialogCallToActionText = R.string.calltoaction_wifi_settings;
dialogPositiveButtonText = R.string.wifi_dialog_button_settings;
}
wifiTextView.setText(Html.fromHtml(getString(R.string.description_setup_wifi_body) +
getString(dialogCallToActionText)));
wifiTextView.setMovementMethod(LinkMovementMethod.getInstance());
wifiTextView.setPadding(padding, padding, padding, padding);
final Context context = getActivity();
return new AlertDialog.Builder(context)
.setTitle(R.string.description_configure_wifi)
.setView(wifiTextView)
.setPositiveButton(dialogPositiveButtonText,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Attempt to configure the Wi-Fi access point.
if (mWiFiEnabled) {
installConferenceWiFi(context);
if (WiFiUtils.isWiFiApConfigured(context)) {
WiFiUtils.setWiFiConfigStatus(
context,
WiFiUtils.WIFI_CONFIG_DONE);
}
// Launch Wi-Fi settings screen for user to enable Wi-Fi.
} else {
WiFiUtils.setWiFiConfigStatus(context,
WiFiUtils.WIFI_CONFIG_REQUESTED);
final Intent wifiIntent =
new Intent(Settings.ACTION_WIFI_SETTINGS);
wifiIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(wifiIntent);
}
dialog.dismiss();
}
}
)
.create();
}
}
/**
* Returns whether we should or should not offer to set up wifi. If asCard == true
* this will decide whether or not to offer wifi setup actively (as a card, for instance).
* If asCard == false, this will return whether or not to offer wifi setup passively
* (in the overflow menu, for instance).
*/
public static boolean shouldOfferToSetupWifi(final Context context, boolean actively) {
long now = UIUtils.getCurrentTime(context);
if (now < Config.WIFI_SETUP_OFFER_START) {
// too early to offer
return false;
}
if (now > Config.CONFERENCE_END_MILLIS) {
// too late
return false;
}
if (!WiFiUtils.isWiFiEnabled(context)) {
// no wifi, no offer
return false;
}
if (!PrefUtils.isAttendeeAtVenue(context)) {
// wifi setup not relevant
return false;
}
if (WiFiUtils.isWiFiApConfigured(context)) {
// already set up
return false;
}
if (actively && PrefUtils.hasDeclinedWifiSetup(context)) {
// user said no
return false;
}
return true;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.undertow;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.camel.CamelContext;
import org.apache.camel.ComponentVerifier;
import org.apache.camel.Consumer;
import org.apache.camel.Endpoint;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.SSLContextParametersAware;
import org.apache.camel.VerifiableComponent;
import org.apache.camel.impl.DefaultComponent;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.RestApiConsumerFactory;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestConsumerFactory;
import org.apache.camel.spi.RestProducerFactory;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.HostUtils;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ServiceHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.UnsafeUriCharactersEncoder;
import org.apache.camel.util.jsse.SSLContextParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents the component that manages {@link UndertowEndpoint}.
*/
@Metadata(label = "verifiers", enums = "parameters,connectivity")
public class UndertowComponent extends DefaultComponent implements RestConsumerFactory, RestApiConsumerFactory, RestProducerFactory, VerifiableComponent, SSLContextParametersAware {
private static final Logger LOG = LoggerFactory.getLogger(UndertowEndpoint.class);
private Map<UndertowHostKey, UndertowHost> undertowRegistry = new ConcurrentHashMap<UndertowHostKey, UndertowHost>();
@Metadata(label = "advanced")
private UndertowHttpBinding undertowHttpBinding;
@Metadata(label = "security")
private SSLContextParameters sslContextParameters;
@Metadata(label = "security", defaultValue = "false")
private boolean useGlobalSslContextParameters;
@Metadata(label = "advanced")
private UndertowHostOptions hostOptions;
public UndertowComponent() {
}
public UndertowComponent(CamelContext context) {
super(context);
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
URI uriHttpUriAddress = new URI(UnsafeUriCharactersEncoder.encodeHttpURI(remaining));
URI endpointUri = URISupport.createRemainingURI(uriHttpUriAddress, parameters);
// any additional channel options
Map<String, Object> options = IntrospectionSupport.extractProperties(parameters, "option.");
// determine sslContextParameters
SSLContextParameters sslParams = this.sslContextParameters;
if (sslParams == null) {
sslParams = retrieveGlobalSslContextParameters();
}
// create the endpoint first
UndertowEndpoint endpoint = createEndpointInstance(endpointUri, this);
// set options from component
endpoint.setSslContextParameters(sslParams);
// Prefer endpoint configured over component configured
if (undertowHttpBinding == null) {
// fallback to component configured
undertowHttpBinding = getUndertowHttpBinding();
}
if (undertowHttpBinding != null) {
endpoint.setUndertowHttpBinding(undertowHttpBinding);
}
// set options from parameters
setProperties(endpoint, parameters);
if (options != null) {
endpoint.setOptions(options);
}
// then re-create the http uri with the remaining parameters which the endpoint did not use
URI httpUri = URISupport.createRemainingURI(
new URI(uriHttpUriAddress.getScheme(),
uriHttpUriAddress.getUserInfo(),
uriHttpUriAddress.getHost(),
uriHttpUriAddress.getPort(),
uriHttpUriAddress.getPath(),
uriHttpUriAddress.getQuery(),
uriHttpUriAddress.getFragment()),
parameters);
endpoint.setHttpURI(httpUri);
return endpoint;
}
protected UndertowEndpoint createEndpointInstance(URI endpointUri, UndertowComponent component) throws URISyntaxException {
return new UndertowEndpoint(endpointUri.toString(), component);
}
@Override
public Consumer createConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
return doCreateConsumer(camelContext, processor, verb, basePath, uriTemplate, consumes, produces, configuration, parameters, false);
}
@Override
public Consumer createApiConsumer(CamelContext camelContext, Processor processor, String contextPath,
RestConfiguration configuration, Map<String, Object> parameters) throws Exception {
// reuse the createConsumer method we already have. The api need to use GET and match on uri prefix
return doCreateConsumer(camelContext, processor, "GET", contextPath, null, null, null, configuration, parameters, true);
}
Consumer doCreateConsumer(CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters, boolean api) throws Exception {
String path = basePath;
if (uriTemplate != null) {
// make sure to avoid double slashes
if (uriTemplate.startsWith("/")) {
path = path + uriTemplate;
} else {
path = path + "/" + uriTemplate;
}
}
path = FileUtil.stripLeadingSeparator(path);
String scheme = "http";
String host = "";
int port = 0;
RestConfiguration config = configuration;
if (config == null) {
config = camelContext.getRestConfiguration("undertow", true);
}
if (config.getScheme() != null) {
scheme = config.getScheme();
}
if (config.getHost() != null) {
host = config.getHost();
}
int num = config.getPort();
if (num > 0) {
port = num;
}
// prefix path with context-path if configured in rest-dsl configuration
String contextPath = config.getContextPath();
if (ObjectHelper.isNotEmpty(contextPath)) {
contextPath = FileUtil.stripTrailingSeparator(contextPath);
contextPath = FileUtil.stripLeadingSeparator(contextPath);
if (ObjectHelper.isNotEmpty(contextPath)) {
path = contextPath + "/" + path;
}
}
// if no explicit hostname set then resolve the hostname
if (ObjectHelper.isEmpty(host)) {
if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
host = "0.0.0.0";
} else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
host = HostUtils.getLocalHostName();
} else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
host = HostUtils.getLocalIp();
}
}
Map<String, Object> map = new HashMap<String, Object>();
// build query string, and append any endpoint configuration properties
if (config.getComponent() == null || config.getComponent().equals("undertow")) {
// setup endpoint options
if (config.getEndpointProperties() != null && !config.getEndpointProperties().isEmpty()) {
map.putAll(config.getEndpointProperties());
}
}
boolean cors = config.isEnableCORS();
if (cors) {
// allow HTTP Options as we want to handle CORS in rest-dsl
map.put("optionsEnabled", "true");
}
String query = URISupport.createQueryString(map);
String url;
if (api) {
url = "undertow:%s://%s:%s/%s?matchOnUriPrefix=true&httpMethodRestrict=%s";
} else {
url = "undertow:%s://%s:%s/%s?httpMethodRestrict=%s";
}
// must use upper case for restrict
String restrict = verb.toUpperCase(Locale.US);
if (cors) {
restrict += ",OPTIONS";
}
// get the endpoint
url = String.format(url, scheme, host, port, path, restrict);
if (!query.isEmpty()) {
url = url + "&" + query;
}
UndertowEndpoint endpoint = camelContext.getEndpoint(url, UndertowEndpoint.class);
setProperties(camelContext, endpoint, parameters);
if (!map.containsKey("undertowHttpBinding")) {
// use the rest binding, if not using a custom http binding
endpoint.setUndertowHttpBinding(new RestUndertowHttpBinding());
}
// configure consumer properties
Consumer consumer = endpoint.createConsumer(processor);
if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {
setProperties(camelContext, consumer, config.getConsumerProperties());
}
return consumer;
}
@Override
public Producer createProducer(CamelContext camelContext, String host,
String verb, String basePath, String uriTemplate, String queryParameters,
String consumes, String produces, Map<String, Object> parameters) throws Exception {
// avoid leading slash
basePath = FileUtil.stripLeadingSeparator(basePath);
uriTemplate = FileUtil.stripLeadingSeparator(uriTemplate);
// get the endpoint
String url = "undertow:" + host;
if (!ObjectHelper.isEmpty(basePath)) {
url += "/" + basePath;
}
if (!ObjectHelper.isEmpty(uriTemplate)) {
url += "/" + uriTemplate;
}
UndertowEndpoint endpoint = camelContext.getEndpoint(url, UndertowEndpoint.class);
if (parameters != null && !parameters.isEmpty()) {
setProperties(camelContext, endpoint, parameters);
}
String path = uriTemplate != null ? uriTemplate : basePath;
endpoint.setHeaderFilterStrategy(new UndertowRestHeaderFilterStrategy(path, queryParameters));
// the endpoint must be started before creating the producer
ServiceHelper.startService(endpoint);
return endpoint.createProducer();
}
@Override
protected void doStart() throws Exception {
super.doStart();
RestConfiguration config = getCamelContext().getRestConfiguration("undertow", true);
// configure additional options on undertow configuration
if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) {
setProperties(this, config.getComponentProperties());
}
}
public void registerConsumer(UndertowConsumer consumer) {
URI uri = consumer.getEndpoint().getHttpURI();
UndertowHostKey key = new UndertowHostKey(uri.getHost(), uri.getPort(), consumer.getEndpoint().getSslContext());
UndertowHost host = undertowRegistry.get(key);
if (host == null) {
host = createUndertowHost(key);
undertowRegistry.put(key, host);
}
host.validateEndpointURI(uri);
host.registerHandler(consumer.getHttpHandlerRegistrationInfo(), consumer.getHttpHandler());
}
public void unregisterConsumer(UndertowConsumer consumer) {
URI uri = consumer.getEndpoint().getHttpURI();
UndertowHostKey key = new UndertowHostKey(uri.getHost(), uri.getPort(), consumer.getEndpoint().getSslContext());
UndertowHost host = undertowRegistry.get(key);
host.unregisterHandler(consumer.getHttpHandlerRegistrationInfo());
}
protected UndertowHost createUndertowHost(UndertowHostKey key) {
return new DefaultUndertowHost(key, hostOptions);
}
public UndertowHttpBinding getUndertowHttpBinding() {
return undertowHttpBinding;
}
/**
* To use a custom HttpBinding to control the mapping between Camel message and HttpClient.
*/
public void setUndertowHttpBinding(UndertowHttpBinding undertowHttpBinding) {
this.undertowHttpBinding = undertowHttpBinding;
}
public SSLContextParameters getSslContextParameters() {
return sslContextParameters;
}
/**
* To configure security using SSLContextParameters
*/
public void setSslContextParameters(SSLContextParameters sslContextParameters) {
this.sslContextParameters = sslContextParameters;
}
@Override
public boolean isUseGlobalSslContextParameters() {
return this.useGlobalSslContextParameters;
}
/**
* Enable usage of global SSL context parameters.
*/
@Override
public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) {
this.useGlobalSslContextParameters = useGlobalSslContextParameters;
}
public UndertowHostOptions getHostOptions() {
return hostOptions;
}
/**
* To configure common options, such as thread pools
*/
public void setHostOptions(UndertowHostOptions hostOptions) {
this.hostOptions = hostOptions;
}
/**
*
*/
public ComponentVerifier getVerifier() {
return new UndertowComponentVerifier(this);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.support;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.camel.AfterPropertiesConfigured;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Component;
import org.apache.camel.Endpoint;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.ResolveEndpointFailedException;
import org.apache.camel.component.extension.ComponentExtension;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.PropertyConfigurer;
import org.apache.camel.spi.PropertyConfigurerAware;
import org.apache.camel.support.service.ServiceSupport;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.PropertiesHelper;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.UnsafeUriCharactersEncoder;
import org.apache.camel.util.function.Suppliers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default component to use for base for components implementations.
*/
public abstract class DefaultComponent extends ServiceSupport implements Component {
private static final Logger LOG = LoggerFactory.getLogger(DefaultComponent.class);
/**
* Simple RAW() pattern used only for validating URI in this class
*/
private static final Pattern RAW_PATTERN = Pattern.compile("RAW[({].*&&.*[)}]");
private static final String RESOURCE_PATH = "META-INF/services/org/apache/camel/configurer/";
private volatile PropertyConfigurer componentPropertyConfigurer;
private volatile PropertyConfigurer endpointPropertyConfigurer;
private final List<Supplier<ComponentExtension>> extensions = new ArrayList<>();
private CamelContext camelContext;
@Metadata(label = "advanced",
description = "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities")
private boolean basicPropertyBinding;
@Metadata(label = "consumer", description = "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.")
private boolean bridgeErrorHandler;
@Metadata(label = "producer",
description = "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.")
private boolean lazyStartProducer;
public DefaultComponent() {
}
public DefaultComponent(CamelContext context) {
this.camelContext = context;
}
@Override
public Endpoint createEndpoint(String uri, Map<String, Object> properties) throws Exception {
// need to encode before its safe to parse with java.net.Uri
String encodedUri = UnsafeUriCharactersEncoder.encode(uri);
URI u = new URI(encodedUri);
String path;
if (u.getScheme() != null) {
// if there is a scheme then there is also a path
path = URISupport.extractRemainderPath(u, useRawUri());
} else {
// this uri has no context-path as the leading text is the component name (scheme)
path = null;
}
// use encoded or raw uri?
Map<String, Object> parameters;
if (useRawUri()) {
// when using raw uri then the query is taking from the uri as is
String query;
int idx = uri.indexOf('?');
if (idx > -1) {
query = uri.substring(idx + 1);
} else {
query = u.getRawQuery();
}
// and use method parseQuery
parameters = URISupport.parseQuery(query, true);
} else {
// however when using the encoded (default mode) uri then the query,
// is taken from the URI (ensures values is URI encoded)
// and use method parseParameters
parameters = URISupport.parseParameters(u);
}
if (properties != null) {
parameters.putAll(properties);
}
// This special property is only to identify endpoints in a unique manner
parameters.remove("hash");
validateURI(uri, path, parameters);
if (LOG.isTraceEnabled()) {
// at trace level its okay to have parameters logged, that may contain passwords
LOG.trace("Creating endpoint uri=[{}], path=[{}], parameters=[{}]", URISupport.sanitizeUri(uri), URISupport.sanitizePath(path), parameters);
} else if (LOG.isDebugEnabled()) {
// but at debug level only output sanitized uris
LOG.debug("Creating endpoint uri=[{}], path=[{}]", URISupport.sanitizeUri(uri), URISupport.sanitizePath(path));
}
// extract these global options and infer their value based on global/component level configuration
boolean basic = getAndRemoveParameter(parameters, "basicPropertyBinding", boolean.class, basicPropertyBinding
? basicPropertyBinding : getCamelContext().getGlobalEndpointConfiguration().isBasicPropertyBinding());
boolean bridge = getAndRemoveParameter(parameters, "bridgeErrorHandler", boolean.class, bridgeErrorHandler
? bridgeErrorHandler : getCamelContext().getGlobalEndpointConfiguration().isBridgeErrorHandler());
boolean lazy = getAndRemoveParameter(parameters, "lazyStartProducer", boolean.class, lazyStartProducer
? lazyStartProducer : getCamelContext().getGlobalEndpointConfiguration().isLazyStartProducer());
// create endpoint
Endpoint endpoint = createEndpoint(uri, path, parameters);
if (endpoint == null) {
return null;
}
// inject camel context
endpoint.setCamelContext(getCamelContext());
// and setup those global options afterwards
if (endpoint instanceof DefaultEndpoint) {
DefaultEndpoint de = (DefaultEndpoint) endpoint;
de.setBasicPropertyBinding(basic);
de.setBridgeErrorHandler(bridge);
de.setLazyStartProducer(lazy);
}
// configure remainder of the parameters
setProperties(endpoint, parameters);
// if endpoint is strict (not lenient) and we have unknown parameters configured then
// fail if there are parameters that could not be set, then they are probably misspell or not supported at all
if (!endpoint.isLenientProperties()) {
validateParameters(uri, parameters, null);
}
afterConfiguration(uri, path, endpoint, parameters);
return endpoint;
}
@Override
public Endpoint createEndpoint(String uri) throws Exception {
// need to encode before its safe to parse with java.net.Uri
String encodedUri = UnsafeUriCharactersEncoder.encode(uri);
URI u = new URI(encodedUri);
String path;
if (u.getScheme() != null) {
// if there is a scheme then there is also a path
path = URISupport.extractRemainderPath(u, useRawUri());
} else {
// this uri has no context-path as the leading text is the component name (scheme)
path = null;
}
Map<String, Object> parameters;
if (useRawUri()) {
// when using raw uri then the query is taking from the uri as is
String query;
int idx = uri.indexOf('?');
if (idx > -1) {
query = uri.substring(idx + 1);
} else {
query = u.getRawQuery();
}
// and use method parseQuery
parameters = URISupport.parseQuery(query, true);
} else {
// however when using the encoded (default mode) uri then the query,
// is taken from the URI (ensures values is URI encoded)
// and use method parseParameters
parameters = URISupport.parseParameters(u);
}
// parameters using raw syntax: RAW(value)
// should have the token removed, so its only the value we have in parameters, as we are about to create
// an endpoint and want to have the parameter values without the RAW tokens
URISupport.resolveRawParameterValues(parameters);
// use encoded or raw uri?
uri = useRawUri() ? uri : encodedUri;
validateURI(uri, path, parameters);
if (LOG.isTraceEnabled()) {
// at trace level its okay to have parameters logged, that may contain passwords
LOG.trace("Creating endpoint uri=[{}], path=[{}], parameters=[{}]", URISupport.sanitizeUri(uri), URISupport.sanitizePath(path), parameters);
} else if (LOG.isDebugEnabled()) {
// but at debug level only output sanitized uris
LOG.debug("Creating endpoint uri=[{}], path=[{}]", URISupport.sanitizeUri(uri), URISupport.sanitizePath(path));
}
// extract these global options and infer their value based on global/component level configuration
boolean basic = getAndRemoveParameter(parameters, "basicPropertyBinding", boolean.class, basicPropertyBinding
? basicPropertyBinding : getCamelContext().getGlobalEndpointConfiguration().isBasicPropertyBinding());
boolean bridge = getAndRemoveParameter(parameters, "bridgeErrorHandler", boolean.class, bridgeErrorHandler
? bridgeErrorHandler : getCamelContext().getGlobalEndpointConfiguration().isBridgeErrorHandler());
boolean lazy = getAndRemoveParameter(parameters, "lazyStartProducer", boolean.class, lazyStartProducer
? lazyStartProducer : getCamelContext().getGlobalEndpointConfiguration().isLazyStartProducer());
Endpoint endpoint = createEndpoint(uri, path, parameters);
if (endpoint == null) {
return null;
}
// inject camel context
endpoint.setCamelContext(getCamelContext());
// and setup those global options afterwards
if (endpoint instanceof DefaultEndpoint) {
DefaultEndpoint de = (DefaultEndpoint) endpoint;
de.setBasicPropertyBinding(basic);
de.setBridgeErrorHandler(bridge);
de.setLazyStartProducer(lazy);
}
// configure remainder of the parameters
setProperties(endpoint, parameters);
// if endpoint is strict (not lenient) and we have unknown parameters configured then
// fail if there are parameters that could not be set, then they are probably misspell or not supported at all
if (!endpoint.isLenientProperties()) {
validateParameters(uri, parameters, null);
}
// allow custom configuration after properties has been configured
if (endpoint instanceof AfterPropertiesConfigured) {
((AfterPropertiesConfigured) endpoint).afterPropertiesConfigured(getCamelContext());
}
afterConfiguration(uri, path, endpoint, parameters);
return endpoint;
}
@Override
public boolean useRawUri() {
// should use encoded uri by default
return false;
}
/**
* Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities.
*/
public boolean isBasicPropertyBinding() {
return basicPropertyBinding;
}
/**
* Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities.
*/
public void setBasicPropertyBinding(boolean basicPropertyBinding) {
this.basicPropertyBinding = basicPropertyBinding;
}
public boolean isLazyStartProducer() {
return lazyStartProducer;
}
/**
* 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.
*/
public void setLazyStartProducer(boolean lazyStartProducer) {
this.lazyStartProducer = lazyStartProducer;
}
public boolean isBridgeErrorHandler() {
return bridgeErrorHandler;
}
/**
* 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.
* <p/>
* By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions,
* that will be logged at WARN/ERROR level and ignored.
*/
public void setBridgeErrorHandler(boolean bridgeErrorHandler) {
this.bridgeErrorHandler = bridgeErrorHandler;
}
/**
* Strategy to do post configuration logic.
* <p/>
* Can be used to construct an URI based on the remaining parameters. For example the parameters that configures
* the endpoint have been removed from the parameters which leaves only the additional parameters left.
*
* @param uri the uri
* @param remaining the remaining part of the URI without the query parameters or component prefix
* @param endpoint the created endpoint
* @param parameters the remaining parameters after the endpoint has been created and parsed the parameters
* @throws Exception can be thrown to indicate error creating the endpoint
*/
protected void afterConfiguration(String uri, String remaining, Endpoint endpoint, Map<String, Object> parameters) throws Exception {
// noop
}
/**
* Strategy for validation of parameters, that was not able to be resolved to any endpoint options.
*
* @param uri the uri
* @param parameters the parameters, an empty map if no parameters given
* @param optionPrefix optional prefix to filter the parameters for validation. Use <tt>null</tt> for validate all.
* @throws ResolveEndpointFailedException should be thrown if the URI validation failed
*/
protected void validateParameters(String uri, Map<String, Object> parameters, String optionPrefix) {
if (parameters == null || parameters.isEmpty()) {
return;
}
Map<String, Object> param = parameters;
if (optionPrefix != null) {
param = PropertiesHelper.extractProperties(parameters, optionPrefix);
}
if (param.size() > 0) {
throw new ResolveEndpointFailedException(uri, "There are " + param.size()
+ " parameters that couldn't be set on the endpoint."
+ " Check the uri if the parameters are spelt correctly and that they are properties of the endpoint."
+ " Unknown parameters=[" + param + "]");
}
}
/**
* Strategy for validation of the uri when creating the endpoint.
*
* @param uri the uri
* @param path the path - part after the scheme
* @param parameters the parameters, an empty map if no parameters given
* @throws ResolveEndpointFailedException should be thrown if the URI validation failed
*/
protected void validateURI(String uri, String path, Map<String, Object> parameters) {
// check for uri containing double && markers without include by RAW
if (uri.contains("&&")) {
Matcher m = RAW_PATTERN.matcher(uri);
// we should skip the RAW part
if (!m.find()) {
throw new ResolveEndpointFailedException(uri, "Invalid uri syntax: Double && marker found. "
+ "Check the uri and remove the duplicate & marker.");
}
}
// if we have a trailing & then that is invalid as well
if (uri.endsWith("&")) {
throw new ResolveEndpointFailedException(uri, "Invalid uri syntax: Trailing & marker found. "
+ "Check the uri and remove the trailing & marker.");
}
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void setCamelContext(CamelContext context) {
this.camelContext = context;
}
@Override
protected void doInit() throws Exception {
org.apache.camel.spi.annotations.Component ann = ObjectHelper.getAnnotation(this, org.apache.camel.spi.annotations.Component.class);
if (ann != null) {
String name = ann.value();
// just grab first scheme name if the component has scheme alias (eg http,https)
if (name.contains(",")) {
name = StringHelper.before(name, ",");
}
final String componentConfigurerName = name + "-component-configurer";
componentPropertyConfigurer = getCamelContext().adapt(ExtendedCamelContext.class).getConfigurerResolver().resolvePropertyConfigurer(componentConfigurerName, getCamelContext());
final String endpointConfigurerName = name + "-endpoint-configurer";
endpointPropertyConfigurer = getCamelContext().adapt(ExtendedCamelContext.class).getConfigurerResolver().resolvePropertyConfigurer(endpointConfigurerName, getCamelContext());
}
}
@Override
protected void doStart() throws Exception {
ObjectHelper.notNull(getCamelContext(), "camelContext");
}
@Override
protected void doStop() throws Exception {
// noop
}
/**
* A factory method allowing derived components to create a new endpoint
* from the given URI, remaining path and optional parameters
*
* @param uri the full URI of the endpoint
* @param remaining the remaining part of the URI without the query
* parameters or component prefix
* @param parameters the optional parameters passed in
* @return a newly created endpoint or null if the endpoint cannot be
* created based on the inputs
* @throws Exception is thrown if error creating the endpoint
*/
protected abstract Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
throws Exception;
/**
* Configure an endpoint using the given parameters.
* In the usual cases, this is the only call needed after having created the endpoint
* in the {@link #createEndpoint(String, String, Map)} method's implementation.
*
* This method will call the {@link Endpoint#configureProperties(Map)} method which
* should delegate the the endpoint's {@link PropertyConfigurer} instance.
* In some rare cases, you need to override this method to explicitely set parameters
* in case a simple generated configurer can not be used.
*
* @param endpoint the endpoint
* @param parameters properties to set
*/
protected void setProperties(Endpoint endpoint, Map<String, Object> parameters) throws Exception {
endpoint.configureProperties(parameters);
}
/**
* Sets the bean properties on the given bean
*
* @param bean the bean
* @param parameters properties to set
*/
protected void setProperties(Object bean, Map<String, Object> parameters) throws Exception {
setProperties(getCamelContext(), bean, parameters);
}
/**
* Sets the bean properties on the given bean using the given {@link CamelContext}.
*
* @param camelContext the {@link CamelContext} to use
* @param bean the bean
* @param parameters properties to set
*/
protected void setProperties(CamelContext camelContext, Object bean, Map<String, Object> parameters) throws Exception {
if (parameters == null || parameters.isEmpty()) {
return;
}
boolean basic = basicPropertyBinding || "true".equals(parameters.getOrDefault("basicPropertyBinding", "false"));
if (basic) {
// use basic binding
PropertyBindingSupport.build()
.withPlaceholder(false).withNesting(false).withDeepNesting(false).withReference(false)
.bind(camelContext, bean, parameters);
} else {
PropertyConfigurer configurer;
if (bean instanceof Component) {
configurer = getComponentPropertyConfigurer();
} else if (bean instanceof Endpoint) {
configurer = getEndpointPropertyConfigurer();
} else if (bean instanceof PropertyConfigurerAware) {
configurer = ((PropertyConfigurerAware) bean).getPropertyConfigurer(bean);
} else {
configurer = null;
}
// use advanced binding
PropertyBindingSupport.build().withConfigurer(configurer).bind(camelContext, bean, parameters);
}
}
@Override
public PropertyConfigurer getComponentPropertyConfigurer() {
return componentPropertyConfigurer;
}
@Override
public PropertyConfigurer getEndpointPropertyConfigurer() {
return endpointPropertyConfigurer;
}
/**
* Derived classes may wish to overload this to prevent the default introspection of URI parameters
* on the created {@link Endpoint} instance.
*/
protected boolean useIntrospectionOnEndpoint() {
return true;
}
/**
* Gets the parameter and remove it from the parameter map. This method doesn't resolve
* reference parameters in the registry.
*
* @param parameters the parameters
* @param key the key
* @param type the requested type to convert the value from the parameter
* @return the converted value parameter, <tt>null</tt> if parameter does not exists.
* @see #resolveAndRemoveReferenceParameter(Map, String, Class)
*/
public <T> T getAndRemoveParameter(Map<String, Object> parameters, String key, Class<T> type) {
return getAndRemoveParameter(parameters, key, type, null);
}
/**
* Gets the parameter and remove it from the parameter map. This method doesn't resolve
* reference parameters in the registry.
*
* @param parameters the parameters
* @param key the key
* @param type the requested type to convert the value from the parameter
* @param defaultValue use this default value if the parameter does not contain the key
* @return the converted value parameter
* @see #resolveAndRemoveReferenceParameter(Map, String, Class, Object)
*/
public <T> T getAndRemoveParameter(Map<String, Object> parameters, String key, Class<T> type, T defaultValue) {
Object value = parameters.remove(key);
if (value != null) {
// if we have a value then convert it
return CamelContextHelper.mandatoryConvertTo(getCamelContext(), type, value);
} else {
value = defaultValue;
}
if (value == null) {
return null;
}
return CamelContextHelper.mandatoryConvertTo(getCamelContext(), type, value);
}
/**
* Gets the parameter and remove it from the parameter map. This method resolves
* reference parameters in the registry as well.
*
* @param parameters the parameters
* @param key the key
* @param type the requested type to convert the value from the parameter
* @return the converted value parameter
*/
public <T> T getAndRemoveOrResolveReferenceParameter(Map<String, Object> parameters, String key, Class<T> type) {
return getAndRemoveOrResolveReferenceParameter(parameters, key, type, null);
}
/**
* Gets the parameter and remove it from the parameter map. This method resolves
* reference parameters in the registry as well.
*
* @param parameters the parameters
* @param key the key
* @param type the requested type to convert the value from the parameter
* @param defaultValue use this default value if the parameter does not contain the key
* @return the converted value parameter
*/
public <T> T getAndRemoveOrResolveReferenceParameter(Map<String, Object> parameters, String key, Class<T> type, T defaultValue) {
String value = getAndRemoveParameter(parameters, key, String.class);
if (value == null) {
return defaultValue;
} else if (EndpointHelper.isReferenceParameter(value)) {
return EndpointHelper.resolveReferenceParameter(getCamelContext(), value, type);
} else {
return getCamelContext().getTypeConverter().convertTo(type, value);
}
}
/**
* Resolves a reference parameter in the registry and removes it from the map.
*
* @param <T> type of object to lookup in the registry.
* @param parameters parameter map.
* @param key parameter map key.
* @param type type of object to lookup in the registry.
* @return the referenced object or <code>null</code> if the parameter map
* doesn't contain the key.
* @throws IllegalArgumentException if a non-null reference was not found in
* registry.
*/
public <T> T resolveAndRemoveReferenceParameter(Map<String, Object> parameters, String key, Class<T> type) {
return resolveAndRemoveReferenceParameter(parameters, key, type, null);
}
/**
* Resolves a reference parameter in the registry and removes it from the map.
*
* @param <T> type of object to lookup in the registry.
* @param parameters parameter map.
* @param key parameter map key.
* @param type type of object to lookup in the registry.
* @param defaultValue default value to use if the parameter map doesn't
* contain the key.
* @return the referenced object or the default value.
* @throws IllegalArgumentException if referenced object was not found in
* registry.
*/
public <T> T resolveAndRemoveReferenceParameter(Map<String, Object> parameters, String key, Class<T> type, T defaultValue) {
String value = getAndRemoveParameter(parameters, key, String.class);
if (value == null) {
return defaultValue;
} else {
return EndpointHelper.resolveReferenceParameter(getCamelContext(), value, type);
}
}
/**
* Resolves a reference list parameter in the registry and removes it from
* the map.
*
* @param parameters parameter map.
* @param key parameter map key.
* @param elementType result list element type.
* @return the list of referenced objects or an empty list if the parameter
* map doesn't contain the key.
* @throws IllegalArgumentException if any of the referenced objects was
* not found in registry.
* @see EndpointHelper#resolveReferenceListParameter(CamelContext, String, Class)
*/
public <T> List<T> resolveAndRemoveReferenceListParameter(Map<String, Object> parameters, String key, Class<T> elementType) {
return resolveAndRemoveReferenceListParameter(parameters, key, elementType, new ArrayList<>(0));
}
/**
* Resolves a reference list parameter in the registry and removes it from
* the map.
*
* @param parameters parameter map.
* @param key parameter map key.
* @param elementType result list element type.
* @param defaultValue default value to use if the parameter map doesn't
* contain the key.
* @return the list of referenced objects or the default value.
* @throws IllegalArgumentException if any of the referenced objects was
* not found in registry.
* @see EndpointHelper#resolveReferenceListParameter(CamelContext, String, Class)
*/
public <T> List<T> resolveAndRemoveReferenceListParameter(Map<String, Object> parameters, String key, Class<T> elementType, List<T> defaultValue) {
String value = getAndRemoveParameter(parameters, key, String.class);
if (value == null) {
return defaultValue;
} else {
return EndpointHelper.resolveReferenceListParameter(getCamelContext(), value, elementType);
}
}
/**
* Returns the reminder of the text if it starts with the prefix.
* <p/>
* Is useable for string parameters that contains commands.
*
* @param prefix the prefix
* @param text the text
* @return the reminder, or null if no reminder
*/
protected String ifStartsWithReturnRemainder(String prefix, String text) {
if (text.startsWith(prefix)) {
String remainder = text.substring(prefix.length());
if (remainder.length() > 0) {
return remainder;
}
}
return null;
}
protected void registerExtension(ComponentExtension extension) {
extensions.add(() -> extension);
}
protected void registerExtension(Supplier<ComponentExtension> supplier) {
extensions.add(Suppliers.memorize(supplier));
}
@Override
public Collection<Class<? extends ComponentExtension>> getSupportedExtensions() {
return extensions.stream()
.map(Supplier::get)
.map(ComponentExtension::getClass)
.collect(Collectors.toList());
}
@Override
public <T extends ComponentExtension> Optional<T> getExtension(Class<T> extensionType) {
return extensions.stream()
.map(Supplier::get)
.filter(extensionType::isInstance)
.findFirst()
.map(extensionType::cast)
.map(e -> Component.trySetComponent(e, this))
.map(e -> CamelContextAware.trySetCamelContext(e, getCamelContext()));
}
}
| |
package org.openapitools.model;
import java.util.ArrayList;
import java.util.List;
import org.openapitools.model.AllView;
import org.openapitools.model.FreeStyleProject;
import org.openapitools.model.HudsonassignedLabels;
import org.openapitools.model.UnlabeledLoadStatistics;
import javax.validation.constraints.*;
import javax.validation.Valid;
import io.swagger.annotations.ApiModelProperty;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Hudson {
@ApiModelProperty(value = "")
private String propertyClass;
@ApiModelProperty(value = "")
@Valid
private List<HudsonassignedLabels> assignedLabels = null;
@ApiModelProperty(value = "")
private String mode;
@ApiModelProperty(value = "")
private String nodeDescription;
@ApiModelProperty(value = "")
private String nodeName;
@ApiModelProperty(value = "")
private Integer numExecutors;
@ApiModelProperty(value = "")
private String description;
@ApiModelProperty(value = "")
@Valid
private List<FreeStyleProject> jobs = null;
@ApiModelProperty(value = "")
@Valid
private AllView primaryView;
@ApiModelProperty(value = "")
private Boolean quietingDown;
@ApiModelProperty(value = "")
private Integer slaveAgentPort;
@ApiModelProperty(value = "")
@Valid
private UnlabeledLoadStatistics unlabeledLoad;
@ApiModelProperty(value = "")
private Boolean useCrumbs;
@ApiModelProperty(value = "")
private Boolean useSecurity;
@ApiModelProperty(value = "")
@Valid
private List<AllView> views = null;
/**
* Get propertyClass
* @return propertyClass
**/
@JsonProperty("_class")
public String getPropertyClass() {
return propertyClass;
}
public void setPropertyClass(String propertyClass) {
this.propertyClass = propertyClass;
}
public Hudson propertyClass(String propertyClass) {
this.propertyClass = propertyClass;
return this;
}
/**
* Get assignedLabels
* @return assignedLabels
**/
@JsonProperty("assignedLabels")
public List<HudsonassignedLabels> getAssignedLabels() {
return assignedLabels;
}
public void setAssignedLabels(List<HudsonassignedLabels> assignedLabels) {
this.assignedLabels = assignedLabels;
}
public Hudson assignedLabels(List<HudsonassignedLabels> assignedLabels) {
this.assignedLabels = assignedLabels;
return this;
}
public Hudson addAssignedLabelsItem(HudsonassignedLabels assignedLabelsItem) {
this.assignedLabels.add(assignedLabelsItem);
return this;
}
/**
* Get mode
* @return mode
**/
@JsonProperty("mode")
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
public Hudson mode(String mode) {
this.mode = mode;
return this;
}
/**
* Get nodeDescription
* @return nodeDescription
**/
@JsonProperty("nodeDescription")
public String getNodeDescription() {
return nodeDescription;
}
public void setNodeDescription(String nodeDescription) {
this.nodeDescription = nodeDescription;
}
public Hudson nodeDescription(String nodeDescription) {
this.nodeDescription = nodeDescription;
return this;
}
/**
* Get nodeName
* @return nodeName
**/
@JsonProperty("nodeName")
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public Hudson nodeName(String nodeName) {
this.nodeName = nodeName;
return this;
}
/**
* Get numExecutors
* @return numExecutors
**/
@JsonProperty("numExecutors")
public Integer getNumExecutors() {
return numExecutors;
}
public void setNumExecutors(Integer numExecutors) {
this.numExecutors = numExecutors;
}
public Hudson numExecutors(Integer numExecutors) {
this.numExecutors = numExecutors;
return this;
}
/**
* Get description
* @return description
**/
@JsonProperty("description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Hudson description(String description) {
this.description = description;
return this;
}
/**
* Get jobs
* @return jobs
**/
@JsonProperty("jobs")
public List<FreeStyleProject> getJobs() {
return jobs;
}
public void setJobs(List<FreeStyleProject> jobs) {
this.jobs = jobs;
}
public Hudson jobs(List<FreeStyleProject> jobs) {
this.jobs = jobs;
return this;
}
public Hudson addJobsItem(FreeStyleProject jobsItem) {
this.jobs.add(jobsItem);
return this;
}
/**
* Get primaryView
* @return primaryView
**/
@JsonProperty("primaryView")
public AllView getPrimaryView() {
return primaryView;
}
public void setPrimaryView(AllView primaryView) {
this.primaryView = primaryView;
}
public Hudson primaryView(AllView primaryView) {
this.primaryView = primaryView;
return this;
}
/**
* Get quietingDown
* @return quietingDown
**/
@JsonProperty("quietingDown")
public Boolean getQuietingDown() {
return quietingDown;
}
public void setQuietingDown(Boolean quietingDown) {
this.quietingDown = quietingDown;
}
public Hudson quietingDown(Boolean quietingDown) {
this.quietingDown = quietingDown;
return this;
}
/**
* Get slaveAgentPort
* @return slaveAgentPort
**/
@JsonProperty("slaveAgentPort")
public Integer getSlaveAgentPort() {
return slaveAgentPort;
}
public void setSlaveAgentPort(Integer slaveAgentPort) {
this.slaveAgentPort = slaveAgentPort;
}
public Hudson slaveAgentPort(Integer slaveAgentPort) {
this.slaveAgentPort = slaveAgentPort;
return this;
}
/**
* Get unlabeledLoad
* @return unlabeledLoad
**/
@JsonProperty("unlabeledLoad")
public UnlabeledLoadStatistics getUnlabeledLoad() {
return unlabeledLoad;
}
public void setUnlabeledLoad(UnlabeledLoadStatistics unlabeledLoad) {
this.unlabeledLoad = unlabeledLoad;
}
public Hudson unlabeledLoad(UnlabeledLoadStatistics unlabeledLoad) {
this.unlabeledLoad = unlabeledLoad;
return this;
}
/**
* Get useCrumbs
* @return useCrumbs
**/
@JsonProperty("useCrumbs")
public Boolean getUseCrumbs() {
return useCrumbs;
}
public void setUseCrumbs(Boolean useCrumbs) {
this.useCrumbs = useCrumbs;
}
public Hudson useCrumbs(Boolean useCrumbs) {
this.useCrumbs = useCrumbs;
return this;
}
/**
* Get useSecurity
* @return useSecurity
**/
@JsonProperty("useSecurity")
public Boolean getUseSecurity() {
return useSecurity;
}
public void setUseSecurity(Boolean useSecurity) {
this.useSecurity = useSecurity;
}
public Hudson useSecurity(Boolean useSecurity) {
this.useSecurity = useSecurity;
return this;
}
/**
* Get views
* @return views
**/
@JsonProperty("views")
public List<AllView> getViews() {
return views;
}
public void setViews(List<AllView> views) {
this.views = views;
}
public Hudson views(List<AllView> views) {
this.views = views;
return this;
}
public Hudson addViewsItem(AllView viewsItem) {
this.views.add(viewsItem);
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Hudson {\n");
sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n");
sb.append(" assignedLabels: ").append(toIndentedString(assignedLabels)).append("\n");
sb.append(" mode: ").append(toIndentedString(mode)).append("\n");
sb.append(" nodeDescription: ").append(toIndentedString(nodeDescription)).append("\n");
sb.append(" nodeName: ").append(toIndentedString(nodeName)).append("\n");
sb.append(" numExecutors: ").append(toIndentedString(numExecutors)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" jobs: ").append(toIndentedString(jobs)).append("\n");
sb.append(" primaryView: ").append(toIndentedString(primaryView)).append("\n");
sb.append(" quietingDown: ").append(toIndentedString(quietingDown)).append("\n");
sb.append(" slaveAgentPort: ").append(toIndentedString(slaveAgentPort)).append("\n");
sb.append(" unlabeledLoad: ").append(toIndentedString(unlabeledLoad)).append("\n");
sb.append(" useCrumbs: ").append(toIndentedString(useCrumbs)).append("\n");
sb.append(" useSecurity: ").append(toIndentedString(useSecurity)).append("\n");
sb.append(" views: ").append(toIndentedString(views)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private static String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| |
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.core.linker;
import com.google.gwt.core.ext.LinkerContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.linker.Artifact;
import com.google.gwt.core.ext.linker.ArtifactSet;
import com.google.gwt.core.ext.linker.CompilationResult;
import com.google.gwt.core.ext.linker.EmittedArtifact;
import com.google.gwt.core.ext.linker.LinkerOrder;
import com.google.gwt.core.ext.linker.LinkerOrder.Order;
import com.google.gwt.core.ext.linker.Shardable;
import com.google.gwt.core.ext.linker.Transferable;
import com.google.gwt.core.ext.linker.impl.SelectionScriptLinker;
import com.google.gwt.dev.About;
import com.google.gwt.dev.util.DefaultTextOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
/**
* A Linker for producing a single JavaScript file from a GWT module. The use of
* this Linker requires that the module has exactly one distinct compilation
* result.
*/
@LinkerOrder(Order.PRIMARY)
@Shardable
public class SingleScriptLinker extends SelectionScriptLinker {
@Override
public String getDescription() {
return "Single Script";
}
@Transferable
private static class Script extends Artifact<Script> {
private final String javaScript;
private final String strongName;
public Script(String strongName, String javaScript) {
super(SingleScriptLinker.class);
this.strongName = strongName;
this.javaScript = javaScript;
}
@Override
public int compareToComparableArtifact(Script that) {
int res = strongName.compareTo(that.strongName);
if (res == 0) {
res = javaScript.compareTo(that.javaScript);
}
return res;
}
@Override
public Class<Script> getComparableArtifactType() {
return Script.class;
}
public String getJavaScript() {
return javaScript;
}
public String getStrongName() {
return strongName;
}
@Override
public int hashCode() {
return strongName.hashCode() ^ javaScript.hashCode();
}
@Override
public String toString() {
return "Script " + strongName;
}
}
@Override
protected Collection<Artifact<?>> doEmitCompilation(TreeLogger logger,
LinkerContext context, CompilationResult result, ArtifactSet artifacts)
throws UnableToCompleteException {
String[] js = result.getJavaScript();
if (js.length != 1) {
logger.branch(TreeLogger.ERROR,
"The module must not have multiple fragments when using the "
+ getDescription() + " Linker.", null);
throw new UnableToCompleteException();
}
Collection<Artifact<?>> toReturn = new ArrayList<Artifact<?>>();
toReturn.add(new Script(result.getStrongName(), js[0]));
toReturn.addAll(emitSelectionInformation(result.getStrongName(), result));
return toReturn;
}
@Override
protected EmittedArtifact emitSelectionScript(TreeLogger logger,
LinkerContext context, ArtifactSet artifacts)
throws UnableToCompleteException {
// Find the single Script result
Set<Script> results = artifacts.find(Script.class);
if (results.size() != 1) {
logger.log(TreeLogger.ERROR, "The module must have exactly one distinct"
+ " permutation when using the " + getDescription() + " Linker; found " + results.size(),
null);
throw new UnableToCompleteException();
}
Script result = results.iterator().next();
DefaultTextOutput out = new DefaultTextOutput(true);
// Emit the selection script.
String bootstrap = generateSelectionScript(logger, context, artifacts);
bootstrap = context.optimizeJavaScript(logger, bootstrap);
out.print(bootstrap);
out.newlineOpt();
// Emit the module's JS a closure.
out.print("(function () {");
out.newlineOpt();
out.print("var $gwt_version = \"" + About.getGwtVersionNum() + "\";");
out.newlineOpt();
out.print("var $wnd = window;");
out.newlineOpt();
out.print("var $doc = $wnd.document;");
out.newlineOpt();
out.print("var $moduleName, $moduleBase;");
out.newlineOpt();
out.print("var $stats = $wnd.__gwtStatsEvent ? function(a) {$wnd.__gwtStatsEvent(a)} : null;");
out.newlineOpt();
out.print("var $strongName = '" + result.getStrongName() + "';");
out.newlineOpt();
out.print(result.getJavaScript());
// Generate the call to tell the bootstrap code that we're ready to go.
out.newlineOpt();
out.print("if (" + context.getModuleFunctionName() + ") "
+ context.getModuleFunctionName() + ".onScriptLoad(gwtOnLoad);");
out.newlineOpt();
out.print("})();");
out.newlineOpt();
return emitString(logger, out.toString(), context.getModuleName()
+ ".nocache.js");
}
/**
* Unimplemented. Normally required by
* {@link #doEmitCompilation(TreeLogger, LinkerContext, CompilationResult, ArtifactSet)}.
*/
@Override
protected String getCompilationExtension(TreeLogger logger,
LinkerContext context) throws UnableToCompleteException {
throw new UnableToCompleteException();
}
/**
* Unimplemented. Normally required by
* {@link #doEmitCompilation(TreeLogger, LinkerContext, CompilationResult, ArtifactSet)}.
*/
@Override
protected String getModulePrefix(TreeLogger logger, LinkerContext context,
String strongName) throws UnableToCompleteException {
throw new UnableToCompleteException();
}
/**
* Unimplemented. Normally required by
* {@link #doEmitCompilation(TreeLogger, LinkerContext, CompilationResult, ArtifactSet)}.
*/
@Override
protected String getModuleSuffix(TreeLogger logger, LinkerContext context)
throws UnableToCompleteException {
throw new UnableToCompleteException();
}
@Override
protected String getSelectionScriptTemplate(TreeLogger logger, LinkerContext context)
throws UnableToCompleteException {
return "com/google/gwt/core/linker/SingleScriptTemplate.js";
}
}
| |
package alien4cloud.tosca.parser;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.ProviderNotFoundException;
import java.util.EnumSet;
import java.util.List;
import javax.annotation.Resource;
import org.alien4cloud.tosca.model.CSARDependency;
import org.alien4cloud.tosca.model.CsarDependenciesBean;
import org.springframework.stereotype.Component;
import alien4cloud.tosca.context.ToscaContextual;
import alien4cloud.tosca.model.ArchiveRoot;
import alien4cloud.tosca.model.ToscaMeta;
import alien4cloud.tosca.parser.impl.ErrorCode;
import alien4cloud.tosca.parser.mapping.ToscaMetaMapping;
import alien4cloud.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
/**
* Parse a TOSCA archive.
*/
@Slf4j
@Component
public class ToscaArchiveParser {
public static final String TOSCA_META_FOLDER_NAME = "TOSCA-Metadata";
public static final String TOSCA_META_FILE_LOCATION = FileSystems.getDefault().getSeparator() + TOSCA_META_FOLDER_NAME
+ FileSystems.getDefault().getSeparator() + "TOSCA.meta";
@Resource
private ToscaMetaMapping toscaMetaMapping;
@Resource
private ToscaParser toscaParser;
@Resource
private ToscaImportParser toscaImportParser;
/**
* Parse a TOSCA archive and reuse an existing TOSCA Context. Other methods will create an independent context for the parsing.
* Note that a TOSCA Context MUST have been initialized in order to use this method.
*
* @param archiveFile The archive file to parse.
* @return A parsing result that contains the Archive Root and eventual errors and/or warnings.
* @throws ParsingException In case of a severe issue while parsing (incorrect yaml, no tosca file etc.)
*/
public ParsingResult<ArchiveRoot> parseWithExistingContext(Path archiveFile) throws ParsingException {
return parse(archiveFile, false);
}
/**
* Parse a TOSCA archive with a fresh new TOSCA Context.
*
* @param archiveFile The archive file to parse.
* @return A parsing result that contains the Archive Root and eventual errors and/or warnings.
* @throws ParsingException In case of a severe issue while parsing (incorrect yaml, no tosca file etc.)
*/
@ToscaContextual(requiresNew = true)
public ParsingResult<ArchiveRoot> parse(Path archiveFile) throws ParsingException {
return parse(archiveFile, false);
}
/**
* Parse an archive file from a zip.
*
* @param archiveFile The archive file currently zipped.
* @return A parsing result that contains the Archive Root and eventual errors and/or warnings.
* @throws ParsingException In case of a severe issue while parsing (incorrect yaml, no tosca file etc.)
*/
@ToscaContextual(requiresNew = true)
public ParsingResult<ArchiveRoot> parse(Path archiveFile, boolean allowYamlFile) throws ParsingException {
try (FileSystem csarFS = FileSystems.newFileSystem(archiveFile, null)) {
if (Files.exists(csarFS.getPath(TOSCA_META_FILE_LOCATION))) {
return parseFromToscaMeta(csarFS);
}
return parseFromRootDefinitions(csarFS, toscaParser);
} catch (IOException e) {
log.error("Unable to read uploaded archive [" + archiveFile + "]", e);
throw new ParsingException("Archive",
new ParsingError(ErrorCode.FAILED_TO_READ_FILE, "Problem happened while accessing file", null, null, null, archiveFile.toString()));
} catch (ProviderNotFoundException e) {
if (allowYamlFile) {
// the file may be a yaml so let's parse
log.debug("File is not a tosca archive, try to parse it as tosca template. ", e);
return toscaParser.parseFile(archiveFile);
} else {
log.warn("Failed to import archive", e);
throw new ParsingException("Archive", new ParsingError(ErrorCode.ERRONEOUS_ARCHIVE_FILE,
"File is not in good format, only zip file is supported ", null, e.getMessage(), null, null));
}
}
}
// TODO Find a proper way to refactor avoid code duplication with parsing methods from file system
/**
* Parse an archive from a directory, it's very convenient for internal use and test
*
* @param archiveDir the directory which contains the archive
* @return A parsing result that contains the Archive Root and eventual errors and/or warnings.
* @throws ParsingException In case of a severe issue while parsing (incorrect yaml, no tosca file etc.)
*/
@ToscaContextual(requiresNew = true)
public ParsingResult<ArchiveRoot> parseDir(Path archiveDir) throws ParsingException {
Path toscaMetaFile = archiveDir.resolve(TOSCA_META_FILE_LOCATION);
if (Files.exists(toscaMetaFile)) {
return parseFromToscaMeta(archiveDir);
}
return parseFromRootDefinitions(archiveDir);
}
@ToscaContextual(requiresNew = true)
public ParsingResult<CsarDependenciesBean> parseImports(Path archiveFile) throws ParsingException {
try (FileSystem csarFS = FileSystems.newFileSystem(archiveFile, null)) {
if (Files.exists(csarFS.getPath(TOSCA_META_FILE_LOCATION))) {
YamlSimpleParser<ToscaMeta> parser = new YamlSimpleParser<ToscaMeta>(toscaMetaMapping.getParser());
ParsingResult<ToscaMeta> parsingResult = parser.parseFile(csarFS.getPath(TOSCA_META_FILE_LOCATION));
CsarDependenciesBean csarDependenciesBean = initDependencyBeanFromToscaMeta(parsingResult.getResult());
return parseFromToscaMeta(csarFS, parsingResult.getResult(), TOSCA_META_FILE_LOCATION, csarDependenciesBean, toscaImportParser);
}
return parseFromRootDefinitions(csarFS, toscaImportParser);
} catch (IOException e) {
log.error("Unable to read uploaded archive [" + archiveFile + "]", e);
throw new ParsingException("Archive",
new ParsingError(ErrorCode.FAILED_TO_READ_FILE, "Problem happened while accessing file", null, null, null, archiveFile.toString()));
} catch (ProviderNotFoundException e) {
log.warn("Failed to import archive", e);
throw new ParsingException("Archive", new ParsingError(ErrorCode.ERRONEOUS_ARCHIVE_FILE, "File is not in good format, only zip file is supported ",
null, e.getMessage(), null, null));
}
}
private CsarDependenciesBean initDependencyBeanFromToscaMeta(ToscaMeta toscaMeta) {
CsarDependenciesBean csarDependenciesBean = new CsarDependenciesBean();
csarDependenciesBean.setSelf(new CSARDependency(toscaMeta.getName(), toscaMeta.getVersion()));
return csarDependenciesBean;
}
private ParsingResult<ArchiveRoot> parseFromToscaMeta(Path csarPath) throws ParsingException {
YamlSimpleParser<ToscaMeta> parser = new YamlSimpleParser<ToscaMeta>(toscaMetaMapping.getParser());
ParsingResult<ToscaMeta> parsingResult = parser.parseFile(csarPath.resolve(TOSCA_META_FILE_LOCATION));
ArchiveRoot archiveRoot = initFromToscaMeta(parsingResult);
return parseFromToscaMeta(csarPath, parsingResult.getResult(), TOSCA_META_FILE_LOCATION, archiveRoot);
}
private ParsingResult<ArchiveRoot> parseFromToscaMeta(FileSystem csarFS) throws ParsingException {
YamlSimpleParser<ToscaMeta> parser = new YamlSimpleParser<ToscaMeta>(toscaMetaMapping.getParser());
ParsingResult<ToscaMeta> parsingResult = parser.parseFile(csarFS.getPath(TOSCA_META_FILE_LOCATION));
// FIXME shouldn't we check here if the meta parsing went well?
ArchiveRoot archiveRoot = initFromToscaMeta(parsingResult);
return parseFromToscaMeta(csarFS, parsingResult.getResult(), TOSCA_META_FILE_LOCATION, archiveRoot, toscaParser);
}
private ArchiveRoot initFromToscaMeta(ParsingResult<ToscaMeta> toscaMeta) {
ArchiveRoot archiveRoot = new ArchiveRoot();
archiveRoot.getArchive().setName(toscaMeta.getResult().getName());
if (toscaMeta.getResult().getVersion() != null) {
archiveRoot.getArchive().setVersion(toscaMeta.getResult().getVersion());
}
if (toscaMeta.getResult().getCreatedBy() != null) {
archiveRoot.getArchive().setTemplateAuthor(toscaMeta.getResult().getCreatedBy());
}
return archiveRoot;
}
private ParsingResult<ArchiveRoot> parseFromToscaMeta(Path csarPath, ToscaMeta toscaMeta, String metaFileName, ArchiveRoot instance)
throws ParsingException {
if (toscaMeta.getEntryDefinitions() != null) {
return toscaParser.parseFile(csarPath.resolve(toscaMeta.getEntryDefinitions()), instance);
}
throw new ParsingException(metaFileName,
new ParsingError(ErrorCode.ENTRY_DEFINITION_NOT_FOUND, "No entry definitions found in the meta file.", null, null, null, null));
}
private <T> ParsingResult<T> parseFromToscaMeta(FileSystem csarFS, ToscaMeta toscaMeta, String metaFileName, T instance, YamlParser<T> parser)
throws ParsingException {
if (toscaMeta.getEntryDefinitions() != null) {
return parser.parseFile(csarFS.getPath(toscaMeta.getEntryDefinitions()), instance);
}
throw new ParsingException(metaFileName,
new ParsingError(ErrorCode.ENTRY_DEFINITION_NOT_FOUND, "No entry definitions found in the meta file.", null, null, null, null));
}
private ParsingResult<ArchiveRoot> parseFromRootDefinitions(Path csarPath) throws ParsingException {
// load definitions from the archive root
try {
List<Path> yamls = FileUtil.listFiles(csarPath, ".+\\.ya?ml");
if (yamls.size() == 1) {
return toscaParser.parseFile(yamls.get(0));
}
throw new ParsingException("Archive", new ParsingError(ErrorCode.SINGLE_DEFINITION_SUPPORTED,
"Alien only supports archives with a single root definition.", null, null, null, String.valueOf(yamls.size())));
} catch (IOException e) {
throw new ParsingException("Archive", new ParsingError(ErrorCode.FAILED_TO_READ_FILE, "Failed to list root definitions", null, null, null, null));
}
}
private <T> ParsingResult<T> parseFromRootDefinitions(FileSystem csarFS, YamlParser<T> parser) throws ParsingException {
// load definitions from the archive root
try {
DefinitionVisitor visitor = new DefinitionVisitor(csarFS);
Files.walkFileTree(csarFS.getPath(csarFS.getSeparator()), EnumSet.noneOf(FileVisitOption.class), 1, visitor);
if (visitor.getDefinitionFiles().size() == 1) {
return parser.parseFile(visitor.getDefinitionFiles().get(0));
}
throw new ParsingException("Archive",
new ParsingError(ErrorCode.SINGLE_DEFINITION_SUPPORTED, "Alien only supports archives with a single root definition.", null, null, null,
"Matching file count in root of " + csarFS + ": " + visitor.getDefinitionFiles().size()));
} catch (IOException e) {
throw new ParsingException("Archive",
new ParsingError(ErrorCode.FAILED_TO_READ_FILE, "Failed to list root definitions", null, null, null, "Error reading " + csarFS + ": " + e));
}
}
}
| |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/dashboard/v1/dashboards_service.proto
package com.google.monitoring.dashboard.v1;
public final class DashboardsServiceProto {
private DashboardsServiceProto() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_monitoring_dashboard_v1_CreateDashboardRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_monitoring_dashboard_v1_CreateDashboardRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_monitoring_dashboard_v1_ListDashboardsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_monitoring_dashboard_v1_ListDashboardsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_monitoring_dashboard_v1_GetDashboardRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_monitoring_dashboard_v1_GetDashboardRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_monitoring_dashboard_v1_DeleteDashboardRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_monitoring_dashboard_v1_DeleteDashboardRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_monitoring_dashboard_v1_UpdateDashboardRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_monitoring_dashboard_v1_UpdateDashboardRequest_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n7google/monitoring/dashboard/v1/dashboa"
+ "rds_service.proto\022\036google.monitoring.das"
+ "hboard.v1\032\034google/api/annotations.proto\032"
+ "\037google/api/field_behavior.proto\032\031google"
+ "/api/resource.proto\032.google/monitoring/d"
+ "ashboard/v1/dashboard.proto\032\033google/prot"
+ "obuf/empty.proto\032 google/protobuf/field_"
+ "mask.proto\032\027google/api/client.proto\"\207\001\n\026"
+ "CreateDashboardRequest\022\023\n\006parent\030\001 \001(\tB\003"
+ "\340A\002\022A\n\tdashboard\030\002 \001(\0132).google.monitori"
+ "ng.dashboard.v1.DashboardB\003\340A\002\022\025\n\rvalida"
+ "te_only\030\003 \001(\010\"\203\001\n\025ListDashboardsRequest\022"
+ "C\n\006parent\030\001 \001(\tB3\340A\002\372A-\n+cloudresourcema"
+ "nager.googleapis.com/Project\022\021\n\tpage_siz"
+ "e\030\002 \001(\005\022\022\n\npage_token\030\003 \001(\t\"p\n\026ListDashb"
+ "oardsResponse\022=\n\ndashboards\030\001 \003(\0132).goog"
+ "le.monitoring.dashboard.v1.Dashboard\022\027\n\017"
+ "next_page_token\030\002 \001(\t\"P\n\023GetDashboardReq"
+ "uest\0229\n\004name\030\001 \001(\tB+\340A\002\372A%\n#monitoring.g"
+ "oogleapis.com/Dashboard\"S\n\026DeleteDashboa"
+ "rdRequest\0229\n\004name\030\001 \001(\tB+\340A\002\372A%\n#monitor"
+ "ing.googleapis.com/Dashboard\"r\n\026UpdateDa"
+ "shboardRequest\022A\n\tdashboard\030\001 \001(\0132).goog"
+ "le.monitoring.dashboard.v1.DashboardB\003\340A"
+ "\002\022\025\n\rvalidate_only\030\003 \001(\0102\261\010\n\021DashboardsS"
+ "ervice\022\253\001\n\017CreateDashboard\0226.google.moni"
+ "toring.dashboard.v1.CreateDashboardReque"
+ "st\032).google.monitoring.dashboard.v1.Dash"
+ "board\"5\202\323\344\223\002/\"\"/v1/{parent=projects/*}/d"
+ "ashboards:\tdashboard\022\253\001\n\016ListDashboards\022"
+ "5.google.monitoring.dashboard.v1.ListDas"
+ "hboardsRequest\0326.google.monitoring.dashb"
+ "oard.v1.ListDashboardsResponse\"*\202\323\344\223\002$\022\""
+ "/v1/{parent=projects/*}/dashboards\022\232\001\n\014G"
+ "etDashboard\0223.google.monitoring.dashboar"
+ "d.v1.GetDashboardRequest\032).google.monito"
+ "ring.dashboard.v1.Dashboard\"*\202\323\344\223\002$\022\"/v1"
+ "/{name=projects/*/dashboards/*}\022\215\001\n\017Dele"
+ "teDashboard\0226.google.monitoring.dashboar"
+ "d.v1.DeleteDashboardRequest\032\026.google.pro"
+ "tobuf.Empty\"*\202\323\344\223\002$*\"/v1/{name=projects/"
+ "*/dashboards/*}\022\265\001\n\017UpdateDashboard\0226.go"
+ "ogle.monitoring.dashboard.v1.UpdateDashb"
+ "oardRequest\032).google.monitoring.dashboar"
+ "d.v1.Dashboard\"?\202\323\344\223\00292,/v1/{dashboard.n"
+ "ame=projects/*/dashboards/*}:\tdashboard\032"
+ "\332\001\312A\031monitoring.googleapis.com\322A\272\001https:"
+ "//www.googleapis.com/auth/cloud-platform"
+ ",https://www.googleapis.com/auth/monitor"
+ "ing,https://www.googleapis.com/auth/moni"
+ "toring.read,https://www.googleapis.com/a"
+ "uth/monitoring.writeB\200\002\n\"com.google.moni"
+ "toring.dashboard.v1B\026DashboardsServicePr"
+ "otoP\001ZGgoogle.golang.org/genproto/google"
+ "apis/monitoring/dashboard/v1;dashboard\252\002"
+ "$Google.Cloud.Monitoring.Dashboard.V1\312\002$"
+ "Google\\Cloud\\Monitoring\\Dashboard\\V1\352\002(G"
+ "oogle::Cloud::Monitoring::Dashboard::V1b"
+ "\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.monitoring.dashboard.v1.DashboardsProto.getDescriptor(),
com.google.protobuf.EmptyProto.getDescriptor(),
com.google.protobuf.FieldMaskProto.getDescriptor(),
com.google.api.ClientProto.getDescriptor(),
});
internal_static_google_monitoring_dashboard_v1_CreateDashboardRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_monitoring_dashboard_v1_CreateDashboardRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_monitoring_dashboard_v1_CreateDashboardRequest_descriptor,
new java.lang.String[] {
"Parent", "Dashboard", "ValidateOnly",
});
internal_static_google_monitoring_dashboard_v1_ListDashboardsRequest_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_monitoring_dashboard_v1_ListDashboardsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_monitoring_dashboard_v1_ListDashboardsRequest_descriptor,
new java.lang.String[] {
"Parent", "PageSize", "PageToken",
});
internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_monitoring_dashboard_v1_ListDashboardsResponse_descriptor,
new java.lang.String[] {
"Dashboards", "NextPageToken",
});
internal_static_google_monitoring_dashboard_v1_GetDashboardRequest_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_monitoring_dashboard_v1_GetDashboardRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_monitoring_dashboard_v1_GetDashboardRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_monitoring_dashboard_v1_DeleteDashboardRequest_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_monitoring_dashboard_v1_DeleteDashboardRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_monitoring_dashboard_v1_DeleteDashboardRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_monitoring_dashboard_v1_UpdateDashboardRequest_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_google_monitoring_dashboard_v1_UpdateDashboardRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_monitoring_dashboard_v1_UpdateDashboardRequest_descriptor,
new java.lang.String[] {
"Dashboard", "ValidateOnly",
});
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.ClientProto.defaultHost);
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
registry.add(com.google.api.AnnotationsProto.http);
registry.add(com.google.api.ClientProto.oauthScopes);
registry.add(com.google.api.ResourceProto.resourceReference);
com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
descriptor, registry);
com.google.api.AnnotationsProto.getDescriptor();
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.monitoring.dashboard.v1.DashboardsProto.getDescriptor();
com.google.protobuf.EmptyProto.getDescriptor();
com.google.protobuf.FieldMaskProto.getDescriptor();
com.google.api.ClientProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.nn.transferlearning;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.BaseDL4JTest;
import org.deeplearning4j.TestUtils;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.BackpropType;
import org.deeplearning4j.nn.conf.GradientNormalization;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.constraint.UnitNormConstraint;
import org.deeplearning4j.nn.conf.distribution.ConstantDistribution;
import org.deeplearning4j.nn.conf.distribution.NormalDistribution;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.deeplearning4j.nn.conf.layers.*;
import org.deeplearning4j.nn.conf.preprocessor.CnnToFeedForwardPreProcessor;
import org.deeplearning4j.nn.conf.preprocessor.FeedForwardToRnnPreProcessor;
import org.deeplearning4j.nn.conf.preprocessor.RnnToCnnPreProcessor;
import org.deeplearning4j.nn.conf.serde.JsonMappers;
import org.deeplearning4j.nn.conf.weightnoise.DropConnect;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.nn.weights.WeightInitDistribution;
import org.deeplearning4j.nn.weights.WeightInitRelu;
import org.deeplearning4j.nn.weights.WeightInitXavier;
import org.junit.Test;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.learning.config.*;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import org.nd4j.shade.jackson.core.JsonProcessingException;
import static org.junit.Assert.*;
/**
* Created by susaneraly on 2/15/17.
*/
@Slf4j
public class TransferLearningMLNTest extends BaseDL4JTest {
@Test
public void simpleFineTune() {
long rng = 12345L;
DataSet randomData = new DataSet(Nd4j.rand(10, 4), Nd4j.rand(10, 3));
//original conf
NeuralNetConfiguration.Builder confToChange =
new NeuralNetConfiguration.Builder().seed(rng).optimizationAlgo(OptimizationAlgorithm.LBFGS)
.updater(new Nesterovs(0.01, 0.99));
MultiLayerNetwork modelToFineTune = new MultiLayerNetwork(confToChange.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(3).build())
.layer(1, new org.deeplearning4j.nn.conf.layers.OutputLayer.Builder(
LossFunctions.LossFunction.MCXENT).activation(Activation.SOFTMAX).nIn(3).nOut(3)
.build())
.build());
modelToFineTune.init();
//model after applying changes with transfer learning
MultiLayerNetwork modelNow =
new TransferLearning.Builder(modelToFineTune)
.fineTuneConfiguration(new FineTuneConfiguration.Builder().seed(rng)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.updater(new RmsProp(0.5)) //Intent: override both weight and bias LR, unless bias LR is manually set also
.l2(0.4).build())
.build();
for (org.deeplearning4j.nn.api.Layer l : modelNow.getLayers()) {
BaseLayer bl = ((BaseLayer) l.conf().getLayer());
assertEquals(new RmsProp(0.5), bl.getIUpdater());
}
NeuralNetConfiguration.Builder confSet = new NeuralNetConfiguration.Builder().seed(rng)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.updater(new RmsProp(0.5)).l2(0.4);
MultiLayerNetwork expectedModel = new MultiLayerNetwork(confSet.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(3).build())
.layer(1, new org.deeplearning4j.nn.conf.layers.OutputLayer.Builder(
LossFunctions.LossFunction.MCXENT).activation(Activation.SOFTMAX).nIn(3).nOut(3)
.build())
.build());
expectedModel.init();
expectedModel.setParams(modelToFineTune.params().dup());
assertEquals(expectedModel.params(), modelNow.params());
//Check json
MultiLayerConfiguration expectedConf = expectedModel.getLayerWiseConfigurations();
assertEquals(expectedConf.toJson(), modelNow.getLayerWiseConfigurations().toJson());
//Check params after fit
modelNow.fit(randomData);
expectedModel.fit(randomData);
assertEquals(modelNow.score(), expectedModel.score(), 1e-6);
INDArray pExp = expectedModel.params();
INDArray pNow = modelNow.params();
assertEquals(pExp, pNow);
}
@Test
public void testNoutChanges() {
DataSet randomData = new DataSet(Nd4j.rand(10, 4), Nd4j.rand(10, 2));
NeuralNetConfiguration.Builder equivalentConf = new NeuralNetConfiguration.Builder().updater(new Sgd(0.1));
FineTuneConfiguration overallConf = new FineTuneConfiguration.Builder().updater(new Sgd(0.1))
.build();
MultiLayerNetwork modelToFineTune = new MultiLayerNetwork(equivalentConf.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(5).build())
.layer(1, new DenseLayer.Builder().nIn(3).nOut(2).build())
.layer(2, new DenseLayer.Builder().nIn(2).nOut(3).build())
.layer(3, new org.deeplearning4j.nn.conf.layers.OutputLayer.Builder(
LossFunctions.LossFunction.MCXENT).activation(Activation.SOFTMAX).nIn(3).nOut(3)
.build())
.build());
modelToFineTune.init();
MultiLayerNetwork modelNow = new TransferLearning.Builder(modelToFineTune).fineTuneConfiguration(overallConf)
.nOutReplace(3, 2, WeightInit.XAVIER, WeightInit.XAVIER)
.nOutReplace(0, 3, WeightInit.XAVIER, new NormalDistribution(1, 1e-1)).build();
MultiLayerNetwork modelExpectedArch = new MultiLayerNetwork(equivalentConf.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(3).build())
.layer(1, new DenseLayer.Builder().nIn(3).nOut(2).build())
.layer(2, new DenseLayer.Builder().nIn(2).nOut(3).build())
.layer(3, new org.deeplearning4j.nn.conf.layers.OutputLayer.Builder(
LossFunctions.LossFunction.MCXENT).activation(Activation.SOFTMAX).nIn(3).nOut(2)
.build())
.build());
modelExpectedArch.init();
//Will fail - expected because of dist and weight init changes
//assertEquals(modelExpectedArch.getLayerWiseConfigurations().toJson(), modelNow.getLayerWiseConfigurations().toJson());
BaseLayer bl0 = ((BaseLayer) modelNow.getLayerWiseConfigurations().getConf(0).getLayer());
BaseLayer bl1 = ((BaseLayer) modelNow.getLayerWiseConfigurations().getConf(1).getLayer());
BaseLayer bl3 = ((BaseLayer) modelNow.getLayerWiseConfigurations().getConf(3).getLayer());
assertEquals(bl0.getWeightInitFn().getClass(), WeightInitXavier.class);
try {
assertEquals(JsonMappers.getMapper().writeValueAsString(bl1.getWeightInitFn()),
JsonMappers.getMapper().writeValueAsString(new WeightInitDistribution(new NormalDistribution(1, 1e-1))));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
assertEquals(bl3.getWeightInitFn(), new WeightInitXavier());
//modelNow should have the same architecture as modelExpectedArch
assertArrayEquals(modelExpectedArch.params().shape(), modelNow.params().shape());
assertArrayEquals(modelExpectedArch.getLayer(0).params().shape(), modelNow.getLayer(0).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(1).params().shape(), modelNow.getLayer(1).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(2).params().shape(), modelNow.getLayer(2).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(3).params().shape(), modelNow.getLayer(3).params().shape());
modelNow.setParams(modelExpectedArch.params());
//fit should give the same results
modelExpectedArch.fit(randomData);
modelNow.fit(randomData);
assertEquals(modelExpectedArch.score(), modelNow.score(), 0.000001);
assertEquals(modelExpectedArch.params(), modelNow.params());
}
@Test
public void testRemoveAndAdd() {
DataSet randomData = new DataSet(Nd4j.rand(10, 4), Nd4j.rand(10, 3));
NeuralNetConfiguration.Builder equivalentConf = new NeuralNetConfiguration.Builder().updater(new Sgd(0.1));
FineTuneConfiguration overallConf = new FineTuneConfiguration.Builder().updater(new Sgd(0.1)).build();
MultiLayerNetwork modelToFineTune = new MultiLayerNetwork(//overallConf.list()
equivalentConf.list().layer(0, new DenseLayer.Builder().nIn(4).nOut(5).build())
.layer(1, new DenseLayer.Builder().nIn(5).nOut(2).build())
.layer(2, new DenseLayer.Builder().nIn(2).nOut(3).build())
.layer(3, new org.deeplearning4j.nn.conf.layers.OutputLayer.Builder(
LossFunctions.LossFunction.MCXENT)
.activation(Activation.SOFTMAX).nIn(3).nOut(3)
.build())
.build());
modelToFineTune.init();
MultiLayerNetwork modelNow =
new TransferLearning.Builder(modelToFineTune).fineTuneConfiguration(overallConf)
.nOutReplace(0, 7, WeightInit.XAVIER, WeightInit.XAVIER)
.nOutReplace(2, 5, WeightInit.XAVIER).removeOutputLayer()
.addLayer(new OutputLayer.Builder(LossFunctions.LossFunction.MCXENT).nIn(5)
.nOut(3).updater(new Sgd(0.5)).activation(Activation.SOFTMAX)
.build())
.build();
MultiLayerNetwork modelExpectedArch = new MultiLayerNetwork(equivalentConf.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(7).build())
.layer(1, new DenseLayer.Builder().nIn(7).nOut(2).build())
.layer(2, new DenseLayer.Builder().nIn(2).nOut(5).build())
.layer(3, new org.deeplearning4j.nn.conf.layers.OutputLayer.Builder(
LossFunctions.LossFunction.MCXENT).activation(Activation.SOFTMAX)
.updater(new Sgd(0.5)).nIn(5).nOut(3).build())
.build());
modelExpectedArch.init();
//modelNow should have the same architecture as modelExpectedArch
assertArrayEquals(modelExpectedArch.params().shape(), modelNow.params().shape());
assertArrayEquals(modelExpectedArch.getLayer(0).params().shape(), modelNow.getLayer(0).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(1).params().shape(), modelNow.getLayer(1).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(2).params().shape(), modelNow.getLayer(2).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(3).params().shape(), modelNow.getLayer(3).params().shape());
modelNow.setParams(modelExpectedArch.params());
//fit should give the same results
modelExpectedArch.fit(randomData);
modelNow.fit(randomData);
double scoreExpected = modelExpectedArch.score();
double scoreActual = modelNow.score();
assertEquals(scoreExpected, scoreActual, 1e-4);
assertEquals(modelExpectedArch.params(), modelNow.params());
}
@Test
public void testRemoveAndProcessing() {
int V_WIDTH = 130;
int V_HEIGHT = 130;
int V_NFRAMES = 150;
MultiLayerConfiguration confForArchitecture =
new NeuralNetConfiguration.Builder().seed(12345).l2(0.001) //l2 regularization on all layers
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.updater(new AdaGrad(0.4)).list()
.layer(0, new ConvolutionLayer.Builder(10, 10).nIn(3) //3 channels: RGB
.nOut(30).stride(4, 4).activation(Activation.RELU).weightInit(
WeightInit.RELU).build()) //Output: (130-10+0)/4+1 = 31 -> 31*31*30
.layer(1, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
.kernelSize(3, 3).stride(2, 2).build()) //(31-3+0)/2+1 = 15
.layer(2, new ConvolutionLayer.Builder(3, 3).nIn(30).nOut(10).stride(2, 2)
.activation(Activation.RELU).weightInit(WeightInit.RELU)
.build()) //Output: (15-3+0)/2+1 = 7 -> 7*7*10 = 490
.layer(3, new DenseLayer.Builder().activation(Activation.RELU).nIn(490).nOut(50)
.weightInit(WeightInit.RELU).updater(new AdaGrad(0.5))
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue)
.gradientNormalizationThreshold(10).build())
.layer(4, new GravesLSTM.Builder().activation(Activation.SOFTSIGN).nIn(50)
.nOut(50).weightInit(WeightInit.XAVIER).updater(new AdaGrad(0.6))
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue)
.gradientNormalizationThreshold(10).build())
.layer(5, new RnnOutputLayer.Builder(LossFunctions.LossFunction.MCXENT)
.activation(Activation.SOFTMAX).nIn(50).nOut(4) //4 possible shapes: circle, square, arc, line
.weightInit(WeightInit.XAVIER)
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue)
.gradientNormalizationThreshold(10).build())
.inputPreProcessor(0, new RnnToCnnPreProcessor(V_HEIGHT, V_WIDTH, 3))
.inputPreProcessor(3, new CnnToFeedForwardPreProcessor(7, 7, 10))
.inputPreProcessor(4, new FeedForwardToRnnPreProcessor())
.backpropType(BackpropType.TruncatedBPTT)
.tBPTTForwardLength(V_NFRAMES / 5).tBPTTBackwardLength(V_NFRAMES / 5).build();
MultiLayerNetwork modelExpectedArch = new MultiLayerNetwork(confForArchitecture);
modelExpectedArch.init();
MultiLayerNetwork modelToTweak =
new MultiLayerNetwork(
new NeuralNetConfiguration.Builder().seed(12345)
.updater(new RmsProp(0.1))
.list()
.layer(0, new ConvolutionLayer.Builder(10, 10) //Only keep the first layer the same
.nIn(3) //3 channels: RGB
.nOut(30).stride(4, 4)
.activation(Activation.RELU)
.weightInit(WeightInit.RELU)
.updater(new AdaGrad(0.1)).build()) //Output: (130-10+0)/4+1 = 31 -> 31*31*30
.layer(1, new SubsamplingLayer.Builder(
SubsamplingLayer.PoolingType.MAX) //change kernel size
.kernelSize(5, 5).stride(2, 2)
.build()) //(31-5+0)/2+1 = 14
.layer(2, new ConvolutionLayer.Builder(6, 6) //change here
.nIn(30).nOut(10).stride(2, 2)
.activation(Activation.RELU)
.weightInit(WeightInit.RELU).build()) //Output: (14-6+0)/2+1 = 5 -> 5*5*10 = 250
.layer(3, new DenseLayer.Builder() //change here
.activation(Activation.RELU).nIn(250).nOut(50)
.weightInit(WeightInit.RELU)
.gradientNormalization(
GradientNormalization.ClipElementWiseAbsoluteValue)
.gradientNormalizationThreshold(10)
.updater(new RmsProp(0.01)).build())
.layer(4, new GravesLSTM.Builder() //change here
.activation(Activation.SOFTSIGN).nIn(50)
.nOut(25).weightInit(WeightInit.XAVIER)
.build())
.layer(5, new RnnOutputLayer.Builder(
LossFunctions.LossFunction.MCXENT)
.activation(Activation.SOFTMAX)
.nIn(25).nOut(4)
.weightInit(WeightInit.XAVIER)
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue)
.gradientNormalizationThreshold(10)
.build())
.inputPreProcessor(0,new RnnToCnnPreProcessor(V_HEIGHT, V_WIDTH, 3))
.inputPreProcessor(3,new CnnToFeedForwardPreProcessor(5, 5, 10))
.inputPreProcessor(4, new FeedForwardToRnnPreProcessor())
.backpropType(BackpropType.TruncatedBPTT)
.tBPTTForwardLength(V_NFRAMES / 5)
.tBPTTBackwardLength(V_NFRAMES / 5).build());
modelToTweak.init();
MultiLayerNetwork modelNow = new TransferLearning.Builder(modelToTweak)
.fineTuneConfiguration(
new FineTuneConfiguration.Builder().seed(12345).l2(0.001) //l2 regularization on all layers
.updater(new AdaGrad(0.4))
.weightInit(WeightInit.RELU).build())
.removeLayersFromOutput(5)
.addLayer(new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX).kernelSize(3, 3)
.stride(2, 2).build())
.addLayer(new ConvolutionLayer.Builder(3, 3).nIn(30).nOut(10).stride(2, 2)
.activation(Activation.RELU).weightInit(WeightInit.RELU).build())
.addLayer(new DenseLayer.Builder().activation(Activation.RELU).nIn(490).nOut(50)
.weightInit(WeightInit.RELU).updater(new AdaGrad(0.5))
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue)
.gradientNormalizationThreshold(10).build())
.addLayer(new GravesLSTM.Builder().activation(Activation.SOFTSIGN).nIn(50).nOut(50)
.weightInit(WeightInit.XAVIER).updater(new AdaGrad(0.6))
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue)
.gradientNormalizationThreshold(10).build())
.addLayer(new RnnOutputLayer.Builder(LossFunctions.LossFunction.MCXENT)
.activation(Activation.SOFTMAX).nIn(50).nOut(4) //4 possible shapes: circle, square, arc, line
.weightInit(WeightInit.XAVIER)
.gradientNormalization(GradientNormalization.ClipElementWiseAbsoluteValue)
.gradientNormalizationThreshold(10).build())
.setInputPreProcessor(3, new CnnToFeedForwardPreProcessor(7, 7, 10))
.setInputPreProcessor(4, new FeedForwardToRnnPreProcessor()).build();
//modelNow should have the same architecture as modelExpectedArch
assertEquals(modelExpectedArch.getLayerWiseConfigurations().getConf(0).toJson(),
modelNow.getLayerWiseConfigurations().getConf(0).toJson());
//some learning related info the subsampling layer will not be overwritten
//assertTrue(modelExpectedArch.getLayerWiseConfigurations().getConf(1).toJson().equals(modelNow.getLayerWiseConfigurations().getConf(1).toJson()));
assertEquals(modelExpectedArch.getLayerWiseConfigurations().getConf(2).toJson(),
modelNow.getLayerWiseConfigurations().getConf(2).toJson());
assertEquals(modelExpectedArch.getLayerWiseConfigurations().getConf(3).toJson(),
modelNow.getLayerWiseConfigurations().getConf(3).toJson());
assertEquals(modelExpectedArch.getLayerWiseConfigurations().getConf(4).toJson(),
modelNow.getLayerWiseConfigurations().getConf(4).toJson());
assertEquals(modelExpectedArch.getLayerWiseConfigurations().getConf(5).toJson(),
modelNow.getLayerWiseConfigurations().getConf(5).toJson());
assertArrayEquals(modelExpectedArch.params().shape(), modelNow.params().shape());
assertArrayEquals(modelExpectedArch.getLayer(0).params().shape(), modelNow.getLayer(0).params().shape());
//subsampling has no params
//assertArrayEquals(modelExpectedArch.getLayer(1).params().shape(), modelNow.getLayer(1).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(2).params().shape(), modelNow.getLayer(2).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(3).params().shape(), modelNow.getLayer(3).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(4).params().shape(), modelNow.getLayer(4).params().shape());
assertArrayEquals(modelExpectedArch.getLayer(5).params().shape(), modelNow.getLayer(5).params().shape());
}
@Test
public void testAllWithCNN() {
DataSet randomData = new DataSet(Nd4j.rand(10, 28 * 28 * 3).reshape(10, 3, 28, 28), Nd4j.rand(10, 10));
MultiLayerNetwork modelToFineTune =
new MultiLayerNetwork(
new NeuralNetConfiguration.Builder().seed(123)
.weightInit(WeightInit.XAVIER)
.updater(new Nesterovs(0.01, 0.9))
.list()
.layer(0, new ConvolutionLayer.Builder(5, 5).nIn(3).stride(1, 1)
.nOut(20).activation(Activation.IDENTITY)
.build())
.layer(1, new SubsamplingLayer.Builder(
SubsamplingLayer.PoolingType.MAX)
.kernelSize(2, 2).stride(2, 2)
.build())
.layer(2, new ConvolutionLayer.Builder(5, 5).stride(1, 1)
.nOut(50).activation(Activation.IDENTITY)
.build())
.layer(3, new SubsamplingLayer.Builder(
SubsamplingLayer.PoolingType.MAX)
.kernelSize(2, 2).stride(2, 2)
.build())
.layer(4, new DenseLayer.Builder().activation(Activation.RELU)
.nOut(500).build())
.layer(5, new DenseLayer.Builder().activation(Activation.RELU)
.nOut(250).build())
.layer(6, new OutputLayer.Builder(
LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nOut(100)
.activation(Activation.SOFTMAX)
.build())
.setInputType(InputType.convolutionalFlat(28, 28, 3))
.build());
modelToFineTune.init();
INDArray asFrozenFeatures = modelToFineTune.feedForwardToLayer(2, randomData.getFeatures(), false).get(2); //10x20x12x12
NeuralNetConfiguration.Builder equivalentConf = new NeuralNetConfiguration.Builder().updater(new Sgd(0.2))
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT);
FineTuneConfiguration overallConf = new FineTuneConfiguration.Builder().updater(new Sgd(0.2))
.build();
MultiLayerNetwork modelNow = new TransferLearning.Builder(modelToFineTune).fineTuneConfiguration(overallConf)
.setFeatureExtractor(1).nOutReplace(4, 600, WeightInit.XAVIER).removeLayersFromOutput(2)
.addLayer(new DenseLayer.Builder().activation(Activation.RELU).nIn(600).nOut(300).build())
.addLayer(new DenseLayer.Builder().activation(Activation.RELU).nIn(300).nOut(150).build())
.addLayer(new DenseLayer.Builder().activation(Activation.RELU).nIn(150).nOut(50).build())
.addLayer(new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.activation(Activation.SOFTMAX).nIn(50).nOut(10).build())
.build();
MultiLayerNetwork notFrozen = new MultiLayerNetwork(equivalentConf.list()
.layer(0, new ConvolutionLayer.Builder(5, 5).stride(1, 1).nOut(50)
.activation(Activation.IDENTITY).build())
.layer(1, new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX).kernelSize(2, 2)
.stride(2, 2).build())
.layer(2, new DenseLayer.Builder().activation(Activation.RELU).nOut(600).build())
.layer(3, new DenseLayer.Builder().activation(Activation.RELU).nOut(300).build())
.layer(4, new DenseLayer.Builder().activation(Activation.RELU).nOut(150).build())
.layer(5, new DenseLayer.Builder().activation(Activation.RELU).nOut(50).build())
.layer(6, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD).nOut(10)
.activation(Activation.SOFTMAX).build())
.setInputType(InputType.convolutionalFlat(12, 12, 20)).build());
notFrozen.init();
assertArrayEquals(modelToFineTune.getLayer(0).params().shape(), modelNow.getLayer(0).params().shape());
//subsampling has no params
//assertArrayEquals(modelExpectedArch.getLayer(1).params().shape(), modelNow.getLayer(1).params().shape());
assertArrayEquals(notFrozen.getLayer(0).params().shape(), modelNow.getLayer(2).params().shape());
modelNow.getLayer(2).setParams(notFrozen.getLayer(0).params());
//subsampling has no params
//assertArrayEquals(notFrozen.getLayer(1).params().shape(), modelNow.getLayer(3).params().shape());
assertArrayEquals(notFrozen.getLayer(2).params().shape(), modelNow.getLayer(4).params().shape());
modelNow.getLayer(4).setParams(notFrozen.getLayer(2).params());
assertArrayEquals(notFrozen.getLayer(3).params().shape(), modelNow.getLayer(5).params().shape());
modelNow.getLayer(5).setParams(notFrozen.getLayer(3).params());
assertArrayEquals(notFrozen.getLayer(4).params().shape(), modelNow.getLayer(6).params().shape());
modelNow.getLayer(6).setParams(notFrozen.getLayer(4).params());
assertArrayEquals(notFrozen.getLayer(5).params().shape(), modelNow.getLayer(7).params().shape());
modelNow.getLayer(7).setParams(notFrozen.getLayer(5).params());
assertArrayEquals(notFrozen.getLayer(6).params().shape(), modelNow.getLayer(8).params().shape());
modelNow.getLayer(8).setParams(notFrozen.getLayer(6).params());
int i = 0;
while (i < 3) {
notFrozen.fit(new DataSet(asFrozenFeatures, randomData.getLabels()));
modelNow.fit(randomData);
i++;
}
INDArray expectedParams = Nd4j.hstack(modelToFineTune.getLayer(0).params(), notFrozen.params());
assertEquals(expectedParams, modelNow.params());
}
@Test
public void testFineTuneOverride() {
//Check that fine-tune overrides are selective - i.e., if I only specify a new LR, only the LR should be modified
MultiLayerConfiguration conf =
new NeuralNetConfiguration.Builder().updater(new Adam(1e-4))
.activation(Activation.TANH).weightInit(WeightInit.RELU)
.l1(0.1).l2(0.2).list()
.layer(0, new DenseLayer.Builder().nIn(10).nOut(5).build()).layer(1,
new OutputLayer.Builder().nIn(5).nOut(4)
.activation(Activation.HARDSIGMOID).build())
.build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
MultiLayerNetwork net2 = new TransferLearning.Builder(net)
.fineTuneConfiguration(new FineTuneConfiguration.Builder().updater(new Adam(2e-2))
.backpropType(BackpropType.TruncatedBPTT) //Should be set on MLC
.build())
.build();
//Check original net isn't modified:
BaseLayer l0 = (BaseLayer) net.getLayer(0).conf().getLayer();
assertEquals(new Adam(1e-4), l0.getIUpdater());
assertEquals(Activation.TANH.getActivationFunction(), l0.getActivationFn());
assertEquals(new WeightInitRelu(), l0.getWeightInitFn());
assertEquals(0.1, TestUtils.getL1(l0), 1e-6);
BaseLayer l1 = (BaseLayer) net.getLayer(1).conf().getLayer();
assertEquals(new Adam(1e-4), l1.getIUpdater());
assertEquals(Activation.HARDSIGMOID.getActivationFunction(), l1.getActivationFn());
assertEquals(new WeightInitRelu(), l1.getWeightInitFn());
assertEquals(0.2, TestUtils.getL2(l1), 1e-6);
assertEquals(BackpropType.Standard, conf.getBackpropType());
//Check new net has only the appropriate things modified (i.e., LR)
l0 = (BaseLayer) net2.getLayer(0).conf().getLayer();
assertEquals(new Adam(2e-2), l0.getIUpdater());
assertEquals(Activation.TANH.getActivationFunction(), l0.getActivationFn());
assertEquals(new WeightInitRelu(), l0.getWeightInitFn());
assertEquals(0.1, TestUtils.getL1(l0), 1e-6);
l1 = (BaseLayer) net2.getLayer(1).conf().getLayer();
assertEquals(new Adam(2e-2), l1.getIUpdater());
assertEquals(Activation.HARDSIGMOID.getActivationFunction(), l1.getActivationFn());
assertEquals(new WeightInitRelu(), l1.getWeightInitFn());
assertEquals(0.2, TestUtils.getL2(l1), 1e-6);
assertEquals(BackpropType.TruncatedBPTT, net2.getLayerWiseConfigurations().getBackpropType());
}
@Test
public void testAllWithCNNNew() {
DataSet randomData = new DataSet(Nd4j.rand(10, 28 * 28 * 3).reshape(10, 3, 28, 28), Nd4j.rand(10, 10));
MultiLayerNetwork modelToFineTune =
new MultiLayerNetwork(
new NeuralNetConfiguration.Builder().seed(123)
.weightInit(WeightInit.XAVIER)
.updater(new Nesterovs(0.01, 0.9))
.list()
.layer(0, new ConvolutionLayer.Builder(5, 5).nIn(3).stride(1, 1)
.nOut(20).activation(Activation.IDENTITY).build())
.layer(1, new SubsamplingLayer.Builder(PoolingType.MAX)
.kernelSize(2, 2).stride(2, 2).build())
.layer(2, new ConvolutionLayer.Builder(5, 5).stride(1, 1)
.nOut(50).activation(Activation.IDENTITY).build())
.layer(3, new SubsamplingLayer.Builder(PoolingType.MAX)
.kernelSize(2, 2).stride(2, 2).build())
.layer(4, new DenseLayer.Builder().activation(Activation.RELU).nOut(500).build())
.layer(5, new DenseLayer.Builder().activation(Activation.RELU).nOut(250).build())
.layer(6, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nOut(100).activation(Activation.SOFTMAX).build())
.setInputType(InputType.convolutionalFlat(28, 28, 3)) //See note below
.build());
modelToFineTune.init();
INDArray asFrozenFeatures = modelToFineTune.feedForwardToLayer(2, randomData.getFeatures(), false).get(2); //10x20x12x12
NeuralNetConfiguration.Builder equivalentConf = new NeuralNetConfiguration.Builder().updater(new Sgd(0.2));
FineTuneConfiguration overallConf = new FineTuneConfiguration.Builder().updater(new Sgd(0.2)).build();
MultiLayerNetwork modelNow = new TransferLearning.Builder(modelToFineTune).fineTuneConfiguration(overallConf)
.setFeatureExtractor(1).removeLayersFromOutput(5)
.addLayer(new DenseLayer.Builder().activation(Activation.RELU).nIn(12 * 12 * 20).nOut(300)
.build())
.addLayer(new DenseLayer.Builder().activation(Activation.RELU).nIn(300).nOut(150).build())
.addLayer(new DenseLayer.Builder().activation(Activation.RELU).nIn(150).nOut(50).build())
.addLayer(new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.activation(Activation.SOFTMAX).nIn(50).nOut(10).build())
.setInputPreProcessor(2, new CnnToFeedForwardPreProcessor(12, 12, 20)).build();
MultiLayerNetwork notFrozen = new MultiLayerNetwork(equivalentConf.list()
.layer(0, new DenseLayer.Builder().activation(Activation.RELU).nIn(12 * 12 * 20).nOut(300)
.build())
.layer(1, new DenseLayer.Builder().activation(Activation.RELU).nIn(300).nOut(150).build())
.layer(2, new DenseLayer.Builder().activation(Activation.RELU).nIn(150).nOut(50).build())
.layer(3, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD).nIn(50)
.nOut(10).activation(Activation.SOFTMAX).build())
.inputPreProcessor(0, new CnnToFeedForwardPreProcessor(12, 12, 20))
.build());
notFrozen.init();
assertArrayEquals(modelToFineTune.getLayer(0).params().shape(), modelNow.getLayer(0).params().shape());
//subsampling has no params
//assertArrayEquals(modelExpectedArch.getLayer(1).params().shape(), modelNow.getLayer(1).params().shape());
assertArrayEquals(notFrozen.getLayer(0).params().shape(), modelNow.getLayer(2).params().shape());
modelNow.getLayer(2).setParams(notFrozen.getLayer(0).params());
assertArrayEquals(notFrozen.getLayer(1).params().shape(), modelNow.getLayer(3).params().shape());
modelNow.getLayer(3).setParams(notFrozen.getLayer(1).params());
assertArrayEquals(notFrozen.getLayer(2).params().shape(), modelNow.getLayer(4).params().shape());
modelNow.getLayer(4).setParams(notFrozen.getLayer(2).params());
assertArrayEquals(notFrozen.getLayer(3).params().shape(), modelNow.getLayer(5).params().shape());
modelNow.getLayer(5).setParams(notFrozen.getLayer(3).params());
int i = 0;
while (i < 3) {
notFrozen.fit(new DataSet(asFrozenFeatures, randomData.getLabels()));
modelNow.fit(randomData);
i++;
}
INDArray expectedParams = Nd4j.hstack(modelToFineTune.getLayer(0).params(), notFrozen.params());
assertEquals(expectedParams, modelNow.params());
}
@Test
public void testObjectOverrides(){
//https://github.com/deeplearning4j/deeplearning4j/issues/4368
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.dropOut(0.5)
.weightNoise(new DropConnect(0.5))
.l2(0.5)
.constrainWeights(new UnitNormConstraint())
.list()
.layer(new DenseLayer.Builder().nIn(10).nOut(10).build())
.build();
MultiLayerNetwork orig = new MultiLayerNetwork(conf);
orig.init();
FineTuneConfiguration ftc = new FineTuneConfiguration.Builder()
.dropOut(0)
.weightNoise(null)
.constraints(null)
.l2(0.0)
.build();
MultiLayerNetwork transfer = new TransferLearning.Builder(orig)
.fineTuneConfiguration(ftc)
.build();
DenseLayer l = (DenseLayer) transfer.getLayer(0).conf().getLayer();
assertNull(l.getIDropout());
assertNull(l.getWeightNoise());
assertNull(l.getConstraints());
assertNull(TestUtils.getL2Reg(l));
}
@Test
public void testTransferLearningSubsequent() {
final INDArray input = Nd4j.create(6,6,6,6);
final MultiLayerNetwork net = new MultiLayerNetwork(new NeuralNetConfiguration.Builder()
.weightInit(new ConstantDistribution(666))
.list()
.setInputType(InputType.inferInputTypes(input)[0])
.layer(new Convolution2D.Builder(3, 3).nOut(10).build())
.layer(new Convolution2D.Builder(1, 1).nOut(3).build())
.layer(new OutputLayer.Builder().nOut(2).lossFunction(LossFunctions.LossFunction.MSE)
.build()).build());
net.init();
MultiLayerNetwork newGraph = new TransferLearning
.Builder(net)
.fineTuneConfiguration(new FineTuneConfiguration.Builder().build())
.nOutReplace(0, 7, new ConstantDistribution(333))
.nOutReplace(1, 3, new ConstantDistribution(111))
.removeLayersFromOutput(1)
.addLayer(new OutputLayer.Builder()
.nIn(48).nOut(2)
.lossFunction(LossFunctions.LossFunction.MSE)
.build())
.setInputPreProcessor(2, new CnnToFeedForwardPreProcessor(4,4,3))
.build();
newGraph.init();
assertEquals("Incorrect # inputs", 7, newGraph.layerInputSize(1));
newGraph.output(input);
}
@Test
public void testChangeNOutNIn() {
INDArray input = Nd4j.create(new long[] {1, 2, 4, 4});
MultiLayerNetwork net = new MultiLayerNetwork(new NeuralNetConfiguration.Builder()
.list()
.setInputType(InputType.inferInputTypes(input)[0])
.layer(new Convolution2D.Builder(1, 1).nOut(10).build())
.layer(new SubsamplingLayer.Builder(1,1).build())
.layer(new Convolution2D.Builder(1, 1).nOut(7).build())
.layer(new OutputLayer.Builder().activation(Activation.SOFTMAX).nOut(2).build())
.build());
net.init();
final MultiLayerNetwork newNet = new TransferLearning.Builder(net)
.nOutReplace(0, 5, WeightInit.XAVIER)
.nInReplace(2, 5, WeightInit.XAVIER)
.build();
newNet.init();
assertEquals("Incorrect number of outputs!", 5 , newNet.layerSize(0));
assertEquals("Incorrect number of inputs!", 5, newNet.layerInputSize(2));
newNet.output(input);
}
}
| |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
import java.io.Serializable;
/**
* <p>
* Describes the volume status.
* </p>
*/
public class VolumeStatusItem implements Serializable, Cloneable {
/**
* The volume ID.
*/
private String volumeId;
/**
* The Availability Zone of the volume.
*/
private String availabilityZone;
/**
* The volume status.
*/
private VolumeStatusInfo volumeStatus;
/**
* A list of events associated with the volume.
*/
private com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusEvent> events;
/**
* The details of the operation.
*/
private com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusAction> actions;
/**
* The volume ID.
*
* @return The volume ID.
*/
public String getVolumeId() {
return volumeId;
}
/**
* The volume ID.
*
* @param volumeId The volume ID.
*/
public void setVolumeId(String volumeId) {
this.volumeId = volumeId;
}
/**
* The volume ID.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param volumeId The volume ID.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public VolumeStatusItem withVolumeId(String volumeId) {
this.volumeId = volumeId;
return this;
}
/**
* The Availability Zone of the volume.
*
* @return The Availability Zone of the volume.
*/
public String getAvailabilityZone() {
return availabilityZone;
}
/**
* The Availability Zone of the volume.
*
* @param availabilityZone The Availability Zone of the volume.
*/
public void setAvailabilityZone(String availabilityZone) {
this.availabilityZone = availabilityZone;
}
/**
* The Availability Zone of the volume.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param availabilityZone The Availability Zone of the volume.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public VolumeStatusItem withAvailabilityZone(String availabilityZone) {
this.availabilityZone = availabilityZone;
return this;
}
/**
* The volume status.
*
* @return The volume status.
*/
public VolumeStatusInfo getVolumeStatus() {
return volumeStatus;
}
/**
* The volume status.
*
* @param volumeStatus The volume status.
*/
public void setVolumeStatus(VolumeStatusInfo volumeStatus) {
this.volumeStatus = volumeStatus;
}
/**
* The volume status.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param volumeStatus The volume status.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public VolumeStatusItem withVolumeStatus(VolumeStatusInfo volumeStatus) {
this.volumeStatus = volumeStatus;
return this;
}
/**
* A list of events associated with the volume.
*
* @return A list of events associated with the volume.
*/
public java.util.List<VolumeStatusEvent> getEvents() {
if (events == null) {
events = new com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusEvent>();
events.setAutoConstruct(true);
}
return events;
}
/**
* A list of events associated with the volume.
*
* @param events A list of events associated with the volume.
*/
public void setEvents(java.util.Collection<VolumeStatusEvent> events) {
if (events == null) {
this.events = null;
return;
}
com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusEvent> eventsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusEvent>(events.size());
eventsCopy.addAll(events);
this.events = eventsCopy;
}
/**
* A list of events associated with the volume.
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setEvents(java.util.Collection)} or {@link
* #withEvents(java.util.Collection)} if you want to override the
* existing values.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param events A list of events associated with the volume.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public VolumeStatusItem withEvents(VolumeStatusEvent... events) {
if (getEvents() == null) setEvents(new java.util.ArrayList<VolumeStatusEvent>(events.length));
for (VolumeStatusEvent value : events) {
getEvents().add(value);
}
return this;
}
/**
* A list of events associated with the volume.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param events A list of events associated with the volume.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public VolumeStatusItem withEvents(java.util.Collection<VolumeStatusEvent> events) {
if (events == null) {
this.events = null;
} else {
com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusEvent> eventsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusEvent>(events.size());
eventsCopy.addAll(events);
this.events = eventsCopy;
}
return this;
}
/**
* The details of the operation.
*
* @return The details of the operation.
*/
public java.util.List<VolumeStatusAction> getActions() {
if (actions == null) {
actions = new com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusAction>();
actions.setAutoConstruct(true);
}
return actions;
}
/**
* The details of the operation.
*
* @param actions The details of the operation.
*/
public void setActions(java.util.Collection<VolumeStatusAction> actions) {
if (actions == null) {
this.actions = null;
return;
}
com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusAction> actionsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusAction>(actions.size());
actionsCopy.addAll(actions);
this.actions = actionsCopy;
}
/**
* The details of the operation.
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setActions(java.util.Collection)} or {@link
* #withActions(java.util.Collection)} if you want to override the
* existing values.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param actions The details of the operation.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public VolumeStatusItem withActions(VolumeStatusAction... actions) {
if (getActions() == null) setActions(new java.util.ArrayList<VolumeStatusAction>(actions.length));
for (VolumeStatusAction value : actions) {
getActions().add(value);
}
return this;
}
/**
* The details of the operation.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param actions The details of the operation.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public VolumeStatusItem withActions(java.util.Collection<VolumeStatusAction> actions) {
if (actions == null) {
this.actions = null;
} else {
com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusAction> actionsCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<VolumeStatusAction>(actions.size());
actionsCopy.addAll(actions);
this.actions = actionsCopy;
}
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getVolumeId() != null) sb.append("VolumeId: " + getVolumeId() + ",");
if (getAvailabilityZone() != null) sb.append("AvailabilityZone: " + getAvailabilityZone() + ",");
if (getVolumeStatus() != null) sb.append("VolumeStatus: " + getVolumeStatus() + ",");
if (getEvents() != null) sb.append("Events: " + getEvents() + ",");
if (getActions() != null) sb.append("Actions: " + getActions() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getVolumeId() == null) ? 0 : getVolumeId().hashCode());
hashCode = prime * hashCode + ((getAvailabilityZone() == null) ? 0 : getAvailabilityZone().hashCode());
hashCode = prime * hashCode + ((getVolumeStatus() == null) ? 0 : getVolumeStatus().hashCode());
hashCode = prime * hashCode + ((getEvents() == null) ? 0 : getEvents().hashCode());
hashCode = prime * hashCode + ((getActions() == null) ? 0 : getActions().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof VolumeStatusItem == false) return false;
VolumeStatusItem other = (VolumeStatusItem)obj;
if (other.getVolumeId() == null ^ this.getVolumeId() == null) return false;
if (other.getVolumeId() != null && other.getVolumeId().equals(this.getVolumeId()) == false) return false;
if (other.getAvailabilityZone() == null ^ this.getAvailabilityZone() == null) return false;
if (other.getAvailabilityZone() != null && other.getAvailabilityZone().equals(this.getAvailabilityZone()) == false) return false;
if (other.getVolumeStatus() == null ^ this.getVolumeStatus() == null) return false;
if (other.getVolumeStatus() != null && other.getVolumeStatus().equals(this.getVolumeStatus()) == false) return false;
if (other.getEvents() == null ^ this.getEvents() == null) return false;
if (other.getEvents() != null && other.getEvents().equals(this.getEvents()) == false) return false;
if (other.getActions() == null ^ this.getActions() == null) return false;
if (other.getActions() != null && other.getActions().equals(this.getActions()) == false) return false;
return true;
}
@Override
public VolumeStatusItem clone() {
try {
return (VolumeStatusItem) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!",
e);
}
}
}
| |
package com.planet_ink.coffee_mud.Common.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.Vector;
/*
Copyright 2000-2010 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* A quest object manages the details and text for a single
* descriptive script that is scheduled and, when directed,
* spawns, creates, watches, shuts down, and cleans up the various
* objects, subsidiary quests, and existing objects modifications
* related to this Quest.
*
* To the user, a quest is a task the user must complete for
* reward. To the Archon, a quest is something that adds
* content to an area at particular times, or under particular
* circumstances.
* @see com.planet_ink.coffee_mud.Libraries.interfaces.QuestManager
*/
@SuppressWarnings("unchecked")
public interface Quest extends Tickable, CMCommon, CMModifiable
{
/**
* Returns the unique name of the quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setName(String)
* @return the unique name of the quest
*/
public String name();
/**
* Sets the unique name of the quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#name()
* @param newName the unique name of the quest
*/
public void setName(String newName);
/**
* Returns the author of the quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setAuthor(String)
* @return the author of the quest
*/
public String author();
/**
* Sets the author of the quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#author()
* @param newName the author of the quest
*/
public void setAuthor(String newName);
/**
* Returns the friendly display name of the quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setDisplayName(String)
* @return the friendly display name of the quest
*/
public String displayName();
/**
* Sets the friendly display name of the quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#displayName()
* @param newName the friendly display name of the quest
*/
public void setDisplayName(String newName);
/**
* Returns the unique start date of the quest. The format
* is either MONTH-DAY for real life dates, or
* MUDDAY MONTH-DAY for mudday based dates.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setStartDate(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setStartMudDate(String)
* @return the unique formatted start date of the quest
*/
public String startDate();
/**
* Sets the real-life start date of this quest. The format
* is MONTH-DAY.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startDate()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setStartMudDate(String)
* @param newName the real-life start date of this quest
*/
public void setStartDate(String newName);
/**
* Sets the in-game mud start date of this quest. The format
* is MONTH-DAY.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startDate()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setStartDate(String)
* @param newName the in-game mud start date of this quest
*/
public void setStartMudDate(String newName);
/**
* Returns the duration, in ticks of this quest. A value of
* 0 means the quest runs indefinitely.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setDuration(int)
* @return the duration, in ticks, of this quest
*/
public int duration();
/**
* Sets the duration, in ticks of this quest. A value of
* 0 means the quest runs indefinitely.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#duration()
* @param newTicks the duration, in ticks, of this quest
*/
public void setDuration(int newTicks);
/**
* Returns whether this quest object is suspended. A
* suspended quest is always in a stopped state.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setSuspended(boolean)
* @return true if this quest object is suspended
*/
public boolean suspended();
/**
* Sets whether this quest object is suspended. A
* suspended quest should always in a stopped state.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#suspended()
* @param truefalse true if this quest object is suspended
*/
public void setSuspended(boolean truefalse);
/**
* Sets the quest script. This may be semicolon-separated
* instructions, or a LOAD command followed by the quest
* script path.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#script()
* @param parm the actual quest script
*/
public void setScript(String parm);
/**
* Accepts a pre-parsed quest script and extracts certain
* non-iterative variables, such as the quest name and
* similar variables.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest
* @param script the parsed quest script
* @param startAtLine which line of the script to start at
*/
public void setVars(Vector script, int startAtLine);
/**
* Returns the unparsed quest script as a single happy string.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setScript(String)
* @return the unparsed quest script as a single happy string.
*/
public String script();
/**
* This will execute the quest script. If the quest is running, it
* will call stopQuest first to shut it down. It will spawn its
* subquests and subsections if necessary.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuestOnTime()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#resetQuest(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#stepQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#stopQuest()
* @return whether the quest was successfully started
*/
public boolean startQuest();
/**
* this will stop executing of the quest script. It will clean up
* any objects or mobs which may have been loaded, restoring map
* mobs to their previous state. If the quest is autorandom, it
* will restart the waiting process
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#stepQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#resetQuest(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuestOnTime()
*/
public void stopQuest();
/**
* this will stop executing of the quest script. It will clean up
* any objects or mobs which may have been loaded, restoring map
* mobs to their previous state. It will then enter a stopped-paused
* state for the given ticks. Any start failures after that
* will cause the pause time to be doubled before the next try.
* @param firstPauseTicks ticks to remain in stopped state before restarting
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#stepQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#stopQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuestOnTime()
*/
public void resetQuest(int firstPauseTicks);
/**
* If any files are embedded and cached inside this quest
* script, this method will clear them from resources and
* memory.
*/
public void internalQuestDelete();
/**
* This method is called when a quest is done with a
* particular step in a multi-step quest. This method
* will clean up any objects from the current step or
* previous steps and attempt to start up the next
* step in the quest. If there are no more steps, or
* the quest is only 1 step, stopQuest() will be called.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#stopQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuestOnTime()
* @return true if another step was started, false otherwise
*/
public boolean stepQuest();
/**
* A dormant state is the state where a quest is no longer running, but
* is not, or has not yet, been scheduled to wait for another run time.
* This may result in a quest being deleted if it was a spawned temporary
* quest.
* @return true if it is in a dormant state, or false if quest was deleted
*/
public boolean enterDormantState();
/**
* Sets whether this quest object is a spawned copy
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#isCopy()
* @param truefalse true if this quest object is a spawned copy
*/
public void setCopy(boolean truefalse);
/**
* Returns whether this quest object is a spawned copy
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setCopy(boolean)
* @return whether this quest object is a spawned copy
*/
public boolean isCopy();
/**
* Sets the flag denoting whether this quest spawns new ones
* from its several steps and if so, by what method.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#SPAWN_ANY
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#SPAWN_FIRST
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#SPAWN_NO
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#SPAWN_DESCS
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getSpawn()
* @param spawnFlag the quest spawn flag info
*/
public void setSpawn(int spawnFlag);
/**
* Returns the flag denoting whether this quest spawns new ones
* from its several steps and if so, by what method.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#SPAWN_ANY
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#SPAWN_FIRST
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#SPAWN_NO
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#SPAWN_DESCS
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setSpawn(int)
* @return the quest spawn flag info
*/
public int getSpawn();
/**
* Quest scripts can have files of various sorts embedded
* in them. This method will return the text of any such
* files of the given name, if they were embedded, or if
* not, it will attempt to open the file in the filesystem
* and return that one instead.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest
* @param named the name of the resource path file to return
* @return the text of the file, if found.
*/
public StringBuffer getResourceFileData(String named);
/**
* Returns the index of a room, mob, or item of the given name
* in use by this quest.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#isObjectInUse(Environmental)
* @param name the given name
* @return the index of a room, mob, or item of the given name
*/
public int getObjectInUseIndex(String name);
/**
* Returns whether the exact given object is in use by this quest.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getObjectInUseIndex(String)
* @param E the object to check
* @return true if its in use, false otherwise
*/
public boolean isObjectInUse(Environmental E);
/**
* From the given official quest variable name, it derives
* either an object or a vector of objects that reflect it.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#QOBJS
* @param named the code to return a string, object, or vector for
* @return a string, mob, item, room, vector, etc..
*/
public Object getDesignatedObject(String named);
/**
* Returns the index of a mob of the given name in use by this quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestMobName(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestMob(int)
* @param name the given name
* @return the index of a mob of the given name in use by this quest
*/
public int getQuestMobIndex(String name);
/**
* Returns the mob in use by this quest at the given index
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestMobName(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestMobIndex(String)
* @param i the index
* @return the mob in use by this quest at the given index
*/
public MOB getQuestMob(int i);
/**
* Returns the name of the mob in use by this quest at the given index
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestMob(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestMobIndex(String)
* @param i the index
* @return the name of the mob in use by this quest at the given index
*/
public String getQuestMobName(int i);
/**
* Returns the index of a item of the given name in use by this quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestItem(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestItemName(int)
* @param name the given name
* @return the index of a item of the given name in use by this quest
*/
public int getQuestItemIndex(String name);
/**
* Returns the item in use by this quest at the given index
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestItemIndex(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestItemName(int)
* @param i the index
* @return the item in use by this quest at the given index
*/
public Item getQuestItem(int i);
/**
* Returns the name of the item in use by this quest at the given index
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestItem(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestItemIndex(String)
* @param i the index
* @return the name of the item in use by this quest at the given index
*/
public String getQuestItemName(int i);
/**
* Returns the index of a room of the given id in use by this quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestRoom(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestRoomID(int)
* @param roomID the given room id
* @return the index of a room of the given id in use by this quest
*/
public int getQuestRoomIndex(String roomID);
/**
* Returns the room in use by this quest at the given index
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestRoomIndex(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestRoomID(int)
* @param i the index
* @return the room in use by this quest at the given index
*/
public Room getQuestRoom(int i);
/**
* Returns the id of the room in use by this quest at the given index
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestRoom(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getQuestRoomIndex(String)
* @param i the index
* @return the id of the room in use by this quest at the given index
*/
public String getQuestRoomID(int i);
/**
* they are called when you want the quest engine to be aware of a
* a quest-specific object thats being added to the map, so that it
* can be cleaned up later. Ditto for abilities, affects, and behaviors.
* this method should only be used WHILE a quest script is being interpreted
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterBehavior(Environmental, String, String, boolean)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterEffect(Environmental, String, String, boolean)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterObject(Environmental)
* @param mob the mob receiving the ability
* @param abilityID the id of the ability
* @param parms any ability parameters
* @param give false to remove this ability, true to replace an existing one
*/
public void runtimeRegisterAbility(MOB mob, String abilityID, String parms, boolean give);
/**
* Called when you want the quest engine to be aware of a quest specific object
* that is being added to the map, so that it can be cleaned up later.
* this method should only be used WHILE a quest script is being interpreted
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterAbility(MOB, String, String, boolean)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterBehavior(Environmental, String, String, boolean)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterEffect(Environmental, String, String, boolean)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest
* @param object the object added to the map
*/
public void runtimeRegisterObject(Environmental object);
/**
* Called when you want the quest engine to be aware of a quest specific object
* that is being added to the map, so that it can be cleaned up later. This is
* called to add an effect to the given object.
* this method should only be used WHILE a quest script is being interpreted
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterAbility(MOB, String, String, boolean)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterBehavior(Environmental, String, String, boolean)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterObject(Environmental)
* @param affected the object receiving the effect
* @param abilityID the id of the effect
* @param parms any effect parameters
* @param give false to remove this effect, true to replace an existing one
*/
public void runtimeRegisterEffect(Environmental affected, String abilityID, String parms, boolean give);
/**
* Called when you want the quest engine to be aware of a quest specific object
* that is being added to the map, so that it can be cleaned up later. This is
* called to add a behavior to the given object.
* this method should only be used WHILE a quest script is being interpreted
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterAbility(MOB, String, String, boolean)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterEffect(Environmental, String, String, boolean)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runtimeRegisterObject(Environmental)
* @param behaving the object receiving the behavior
* @param behaviorID the id of the behavior
* @param parms any behavior parameters
* @param give false to remove this behavior, true to replace an existing one
*/
public void runtimeRegisterBehavior(Environmental behaving, String behaviorID, String parms, boolean give);
/**
* Registers the given player name as having won this quest.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getWinners()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getWinnerStr()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#wasWinner(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setWinners(String)
* @param mobName the player name
*/
public void declareWinner(String mobName);
/**
* Returns the names of all the winners of this quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#declareWinner(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getWinnerStr()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#wasWinner(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setWinners(String)
* @return the names of all the winners of this quest
*/
public Vector getWinners();
/**
* Returns a semicolon delimited string of all the winners of this quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#declareWinner(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getWinners()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#wasWinner(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setWinners(String)
* @return a semicolon delimited string of all the winners of this quest
*/
public String getWinnerStr();
/**
* Returns whether a player of the given name has won this quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#declareWinner(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getWinners()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getWinnerStr()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setWinners(String)
* @param name the player name
* @return true if a player of the given name has won this quest
*/
public boolean wasWinner(String name);
/**
* Sets the list of player names that have won this quest
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#declareWinner(String)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getWinners()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#getWinnerStr()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#wasWinner(String)
* @param list a semicolon delimtied list of player names
*/
public void setWinners(String list);
/**
* The minimum number of players matching player criteria required before
* this quest will start
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setMinPlayers(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#playerMask()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setPlayerMask(String)
* @return minimum number of players matching player criteria required
*/
public int minPlayers();
/**
* Sets minimum number of players matching player criteria required before
* this quest will start
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#minPlayers()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#playerMask()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setPlayerMask(String)
* @param players minimum number of players matching player criteria required
*/
public void setMinPlayers(int players);
/**
* Returns the run level. -1 means runs always, otherwise,
* this quest will always defer to running quests of equal
* or lower run level. Higher, therefore, is weaker.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setRunLevel(int)
* @return the run level. -1 means runs always
*/
public int runLevel();
/**
* Sets the run level. -1 means runs always, otherwise,
* this quest will always defer to running quests of equal
* or lower run level. Higher, therefore, is weaker.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#runLevel()
* @param level the run level. -1 means runs always
*/
public void setRunLevel(int level);
/**
* Returns the zappermask that determines who counts as an
* elligible player for the purposes of the minPlayer setting.
* @see com.planet_ink.coffee_mud.Libraries.interfaces.MaskingLibrary
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setMinPlayers(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#minPlayers()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setPlayerMask(String)
* @return the zappermask that determines who counts as a player
*/
public String playerMask();
/**
* Sets the zappermask that determines who counts as an
* elligible player for the purposes of the minPlayer setting.
* @see com.planet_ink.coffee_mud.Libraries.interfaces.MaskingLibrary
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setMinPlayers(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#minPlayers()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#playerMask()
* @param mask the zappermask that determines who counts as a player
*/
public void setPlayerMask(String mask);
/**
* Returns the minimum number of ticks between attempts to run this quest.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setMinWait(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#waitInterval()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setWaitInterval(int)
* @return the minimum number of ticks between attempts to run this quest.
*/
public int minWait();
/**
* Sets the minimum number of ticks between attempts to run this quest.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#minWait()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#waitInterval()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setWaitInterval(int)
* @param wait the minimum number of ticks between attempts to run this quest.
*/
public void setMinWait(int wait);
/**
* Returns the maximum ticks, above the minimum wait, that must go by
* before an attempt to run a quest. This is therefore, the random part.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setMinWait(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#minWait()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setWaitInterval(int)
* @return the maximum ticks, above the minimum wait, that must go by
*/
public int waitInterval();
/**
* Sets the maximum ticks, above the minimum wait, that must go by
* before an attempt to run a quest. This is therefore, the random part.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#setMinWait(int)
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#minWait()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#waitInterval()
* @param wait the maximum ticks, above the minimum wait, that must go by
*/
public void setWaitInterval(int wait);
/**
* After a quest is added to the list of quests, this method is
* called to put the quest into its initial wait state, and get
* it thread time.
*/
public void autostartup();
/**
* Returns whether this quest is in a running state
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#suspended()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#waiting()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuestOnTime()
* @return true if the quest is running, false if stopped
*/
public boolean running();
/**
* Returns whether this quest is in a midway stopping state
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#suspended()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#waiting()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#running()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#stopQuest()
* @return true if the quest is in the processess of stopping
*/
public boolean stopping();
/**
* Returns whether this quest is in a wait state between runs
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#suspended()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#waiting()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#running()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#stopQuest()
* @return true if this quest is in a wait state between runs
*/
public boolean waiting();
/**
* Returns the number of ticks before this quest will go from
* a running state to a stopped state.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#minsRemaining()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuestOnTime()
* @return the numer of ticks the quest will keep running
*/
public int ticksRemaining();
/**
* Returns the number of minutes before this quest will go from
* a running state to a stopped state.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#ticksRemaining()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuest()
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#startQuestOnTime()
* @return the numer of minutes the quest will keep running
*/
public int minsRemaining();
/**
* Returns the number of ticks before this quest will attempt to start.
* A number >=0 means the quest is currently in a stopped state.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#resetWaitRemaining(long)
* @return the number of ticks before this quest will attempt to start.
*/
public int waitRemaining();
/**
* Sets the number of ticks before this quest will attempt to start.
* A number >=0 means the quest is currently in a stopped state.
* @see com.planet_ink.coffee_mud.Common.interfaces.Quest#waitRemaining()
* @param minusEllapsed the number of miliseconds already ellapsed before wait began
* @return true if the quest is successfully put into a non-running wait state
*/
public boolean resetWaitRemaining(long minusEllapsed);
/** A quest spawn flag denoting that this quest does not spawn its steps */
public final static int SPAWN_NO=0;
/** A quest spawn flag denoting that this quest spawns only its first step */
public final static int SPAWN_FIRST=1;
/** A quest spawn flag denoting that this quest attempts to spawn every step at once */
public final static int SPAWN_ANY=2;
/** Descriptions of the several quest step spawn flags */
public final static String[] SPAWN_DESCS={"FALSE","TRUE","ALL"};
/** The list of BASIC non-iterative variable codes that pertain to a quest object */
public final static String[] QCODES={"CLASS", "NAME", "DURATION", "WAIT", "MINPLAYERS", "PLAYERMASK",
"RUNLEVEL", "DATE", "MUDDAY", "INTERVAL","SPAWNABLE", "DISPLAY",
"INSTRUCTIONS", "PERSISTANCE", "AUTHOR"};
/** The list of basic quest objects defined in an iterative fashion during quest script execution */
public final static String[] QOBJS={"LOADEDMOBS", "LOADEDITEMS", "AREA", "ROOM", "MOBGROUP", "ITEMGROUP", "ROOMGROUP",
"ITEM", "ENVOBJ", "STUFF", "MOB"};
/** The list of basic mystery quest objects defined in an iterative fashion during quest script execution */
public static final String[] MYSTERY_QCODES={"FACTION","FACTIONGROUP",
"AGENT","AGENTGROUP",
"ACTION","ACTIONGROUP",
"TARGET","TARGETGROUP",
"MOTIVE","MOTIVEGROUP",
"WHEREHAPPENED","WHEREHAPPENEDGROUP",
"WHEREAT","WHEREATGROUP",
"WHENHAPPENED","WHENHAPPENEDGROUP",
"WHENAT","WHENATGROUP",
"TOOL","TOOLGROUP"};
/** the list of room-related mystery quest objects defined in an iterative fashion during quest script execution */
public static final String[] ROOM_REFERENCE_QCODES={"WHEREHAPPENED","WHEREHAPPENEDGROUP",
"WHEREAT","WHEREATGROUP",
"ROOM","ROOMGROUP"
};
}
| |
/*
* #%L
* BroadleafCommerce Framework
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.core.offer.service.processor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadleafcommerce.common.money.Money;
import org.broadleafcommerce.core.offer.dao.OfferDao;
import org.broadleafcommerce.core.offer.domain.FulfillmentGroupAdjustment;
import org.broadleafcommerce.core.offer.domain.Offer;
import org.broadleafcommerce.core.offer.domain.OfferRule;
import org.broadleafcommerce.core.offer.domain.OrderAdjustment;
import org.broadleafcommerce.core.offer.domain.OrderItemPriceDetailAdjustment;
import org.broadleafcommerce.core.offer.service.OfferServiceUtilities;
import org.broadleafcommerce.core.offer.service.discount.CandidatePromotionItems;
import org.broadleafcommerce.core.offer.service.discount.PromotionQualifier;
import org.broadleafcommerce.core.offer.service.discount.domain.PromotableCandidateOrderOffer;
import org.broadleafcommerce.core.offer.service.discount.domain.PromotableFulfillmentGroup;
import org.broadleafcommerce.core.offer.service.discount.domain.PromotableFulfillmentGroupAdjustment;
import org.broadleafcommerce.core.offer.service.discount.domain.PromotableItemFactory;
import org.broadleafcommerce.core.offer.service.discount.domain.PromotableOrder;
import org.broadleafcommerce.core.offer.service.discount.domain.PromotableOrderAdjustment;
import org.broadleafcommerce.core.offer.service.discount.domain.PromotableOrderItem;
import org.broadleafcommerce.core.offer.service.discount.domain.PromotableOrderItemPriceDetail;
import org.broadleafcommerce.core.offer.service.discount.domain.PromotableOrderItemPriceDetailAdjustment;
import org.broadleafcommerce.core.offer.service.type.OfferDiscountType;
import org.broadleafcommerce.core.offer.service.type.OfferRuleType;
import org.broadleafcommerce.core.order.dao.OrderItemDao;
import org.broadleafcommerce.core.order.domain.FulfillmentGroup;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.order.domain.OrderItem;
import org.broadleafcommerce.core.order.domain.OrderItemPriceDetail;
import org.broadleafcommerce.core.order.domain.OrderItemQualifier;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
/**
* @author jfischer, bpolster
*/
@Service("blOrderOfferProcessor")
public class OrderOfferProcessorImpl extends AbstractBaseProcessor implements OrderOfferProcessor {
private static final Log LOG = LogFactory.getLog(OrderOfferProcessorImpl.class);
@Resource(name = "blPromotableItemFactory")
protected PromotableItemFactory promotableItemFactory;
@Resource(name = "blOrderItemDao")
protected OrderItemDao orderItemDao;
@Resource(name = "blOfferDao")
protected OfferDao offerDao;
@Resource(name = "blOfferServiceUtilities")
protected OfferServiceUtilities offerServiceUtilities;
@Override
public void filterOrderLevelOffer(PromotableOrder promotableOrder, List<PromotableCandidateOrderOffer> qualifiedOrderOffers, Offer offer) {
if (offer.getDiscountType().getType().equals(OfferDiscountType.FIX_PRICE.getType())) {
LOG.warn("Offers of type ORDER may not have a discount type of FIX_PRICE. Ignoring order offer (name=" + offer.getName() + ")");
return;
}
boolean orderLevelQualification = false;
//Order Qualification
orderQualification:
{
if (couldOfferApplyToOrder(offer, promotableOrder)) {
orderLevelQualification = true;
break orderQualification;
}
for (PromotableOrderItem orderItem : promotableOrder.getDiscountableOrderItems(offer.getApplyDiscountToSalePrice())) {
if (couldOfferApplyToOrder(offer, promotableOrder, orderItem)) {
orderLevelQualification = true;
break orderQualification;
}
}
for (PromotableFulfillmentGroup fulfillmentGroup : promotableOrder.getFulfillmentGroups()) {
if (couldOfferApplyToOrder(offer, promotableOrder, fulfillmentGroup)) {
orderLevelQualification = true;
break orderQualification;
}
}
}
//Item Qualification - new for 1.5!
if (orderLevelQualification) {
CandidatePromotionItems candidates = couldOfferApplyToOrderItems(offer, promotableOrder.getDiscountableOrderItems(offer.getApplyDiscountToSalePrice()));
if (candidates.isMatchedQualifier()) {
PromotableCandidateOrderOffer candidateOffer = createCandidateOrderOffer(promotableOrder, qualifiedOrderOffers, offer);
candidateOffer.getCandidateQualifiersMap().putAll(candidates.getCandidateQualifiersMap());
}
}
}
@Override
public boolean couldOfferApplyToOrder(Offer offer, PromotableOrder promotableOrder) {
return couldOfferApplyToOrder(offer, promotableOrder, null, null);
}
/**
* Private method which executes the appliesToOrderRules in the Offer to determine if this offer
* can be applied to the Order, OrderItem, or FulfillmentGroup.
*
* @param offer
* @param order
* @param orderItem
* @return true if offer can be applied, otherwise false
*/
protected boolean couldOfferApplyToOrder(Offer offer, PromotableOrder promotableOrder, PromotableOrderItem orderItem) {
return couldOfferApplyToOrder(offer, promotableOrder, orderItem, null);
}
/**
* Private method which executes the appliesToOrderRules in the Offer to determine if this offer
* can be applied to the Order, OrderItem, or FulfillmentGroup.
*
* @param offer
* @param order
* @param fulfillmentGroup
* @return true if offer can be applied, otherwise false
*/
protected boolean couldOfferApplyToOrder(Offer offer, PromotableOrder promotableOrder, PromotableFulfillmentGroup fulfillmentGroup) {
return couldOfferApplyToOrder(offer, promotableOrder, null, fulfillmentGroup);
}
/**
* Private method which executes the appliesToOrderRules in the Offer to determine if this offer
* can be applied to the Order, OrderItem, or FulfillmentGroup.
*
* @param offer
* @param order
* @param promotableOrderItem
* @param promotableFulfillmentGroup
* @return true if offer can be applied, otherwise false
*/
protected boolean couldOfferApplyToOrder(Offer offer, PromotableOrder promotableOrder, PromotableOrderItem promotableOrderItem, PromotableFulfillmentGroup promotableFulfillmentGroup) {
boolean appliesToItem = false;
String rule = null;
if (offer.getAppliesToOrderRules() != null && offer.getAppliesToOrderRules().trim().length() != 0) {
rule = offer.getAppliesToOrderRules();
} else {
OfferRule orderRule = offer.getOfferMatchRules().get(OfferRuleType.ORDER.getType());
if (orderRule != null) {
rule = orderRule.getMatchRule();
}
}
if (rule != null) {
HashMap<String, Object> vars = new HashMap<String, Object>();
promotableOrder.updateRuleVariables(vars);
vars.put("offer", offer);
if (promotableFulfillmentGroup != null) {
promotableFulfillmentGroup.updateRuleVariables(vars);
}
if (promotableOrderItem != null) {
promotableOrderItem.updateRuleVariables(vars);
}
Boolean expressionOutcome = executeExpression(rule, vars);
if (expressionOutcome != null && expressionOutcome) {
appliesToItem = true;
}
} else {
appliesToItem = true;
}
return appliesToItem;
}
protected PromotableCandidateOrderOffer createCandidateOrderOffer(PromotableOrder promotableOrder, List<PromotableCandidateOrderOffer> qualifiedOrderOffers, Offer offer) {
PromotableCandidateOrderOffer promotableCandidateOrderOffer = promotableItemFactory.createPromotableCandidateOrderOffer(promotableOrder, offer);
qualifiedOrderOffers.add(promotableCandidateOrderOffer);
return promotableCandidateOrderOffer;
}
@Override
public List<PromotableCandidateOrderOffer> removeTrailingNotCombinableOrderOffers(List<PromotableCandidateOrderOffer> candidateOffers) {
List<PromotableCandidateOrderOffer> remainingCandidateOffers = new ArrayList<PromotableCandidateOrderOffer>();
int offerCount = 0;
for (PromotableCandidateOrderOffer candidateOffer : candidateOffers) {
if (offerCount == 0) {
remainingCandidateOffers.add(candidateOffer);
} else {
boolean treatAsNewFormat = false;
if (candidateOffer.getOffer().getTreatAsNewFormat() != null && candidateOffer.getOffer().getTreatAsNewFormat()) {
treatAsNewFormat = true;
}
if ((!treatAsNewFormat && candidateOffer.getOffer().isCombinableWithOtherOffers()) || (treatAsNewFormat && (candidateOffer.getOffer().isTotalitarianOffer() == null || !candidateOffer.getOffer().isTotalitarianOffer()))) {
remainingCandidateOffers.add(candidateOffer);
}
}
offerCount++;
}
return remainingCandidateOffers;
}
@Override
public void applyAllOrderOffers(List<PromotableCandidateOrderOffer> orderOffers, PromotableOrder promotableOrder) {
// If order offer is not combinable, first verify order adjustment is zero, if zero, compare item discount total vs this offer's total
Iterator<PromotableCandidateOrderOffer> orderOfferIterator = orderOffers.iterator();
while (orderOfferIterator.hasNext()) {
PromotableCandidateOrderOffer orderOffer = orderOfferIterator.next();
if (promotableOrder.canApplyOrderOffer(orderOffer)) {
applyOrderOffer(promotableOrder, orderOffer);
if (orderOffer.isTotalitarian() || promotableOrder.isTotalitarianItemOfferApplied()) {
if (LOG.isTraceEnabled()) {
LOG.trace("Totalitarian Order Offer Applied. Comparing order and item offers for best outcome.");
}
compareAndAdjustOrderAndItemOffers(promotableOrder);
// We continue because this could be the first offer and marked as totalitarian, but not as good as an
// item offer. There could be other order offers that are not totalitarian that also qualify.
continue;
}
if (!orderOffer.isCombinable()) {
if (LOG.isTraceEnabled()) {
LOG.trace("Non-Combinable Order Offer Applied with id=[" + orderOffer.getOffer().getId() +"]. No other order offers can be applied");
}
break;
}
}
}
promotableOrder.getOrder().setSubTotal(promotableOrder.calculateSubtotalWithAdjustments());
}
/**
* Called when the system must determine whether to apply order or item adjustments.
* @param promotableOrder
* @param orderOffersApplied
*/
protected void compareAndAdjustOrderAndItemOffers(PromotableOrder promotableOrder) {
Money orderAdjustmentTotal = promotableOrder.calculateOrderAdjustmentTotal();
Money itemAdjustmentTotal = promotableOrder.calculateItemAdjustmentTotal();
if (orderAdjustmentTotal.greaterThanOrEqual(itemAdjustmentTotal)) {
promotableOrder.removeAllCandidateItemOfferAdjustments();
} else {
promotableOrder.removeAllCandidateOrderOfferAdjustments();
}
}
/**
* Private method used by applyAllOrderOffers to create an OrderAdjustment from a CandidateOrderOffer
* and associates the OrderAdjustment to the Order.
*
* @param orderOffer a CandidateOrderOffer to apply to an Order
*/
protected void applyOrderOffer(PromotableOrder promotableOrder, PromotableCandidateOrderOffer orderOffer) {
PromotableOrderAdjustment promotableOrderAdjustment = promotableItemFactory.createPromotableOrderAdjustment(orderOffer, promotableOrder);
promotableOrder.addCandidateOrderAdjustment(promotableOrderAdjustment);
}
@Override
public PromotableItemFactory getPromotableItemFactory() {
return promotableItemFactory;
}
@Override
public void setPromotableItemFactory(PromotableItemFactory promotableItemFactory) {
this.promotableItemFactory = promotableItemFactory;
}
protected Map<Long, PromotableOrderAdjustment> buildPromotableOrderAdjustmentsMap(PromotableOrder promotableOrder) {
Map<Long, PromotableOrderAdjustment> adjustmentsMap = new HashMap<Long, PromotableOrderAdjustment>();
for (PromotableOrderAdjustment adjustment : promotableOrder.getCandidateOrderAdjustments()) {
adjustmentsMap.put(adjustment.getOffer().getId(), adjustment);
}
return adjustmentsMap;
}
protected void synchronizeOrderAdjustments(PromotableOrder promotableOrder) {
Order order = promotableOrder.getOrder();
if (order.getOrderAdjustments().isEmpty() && promotableOrder.getCandidateOrderAdjustments().isEmpty()) {
return;
}
Map<Long, PromotableOrderAdjustment> newAdjustmentsMap = buildPromotableOrderAdjustmentsMap(promotableOrder);
Iterator<OrderAdjustment> orderAdjIterator = order.getOrderAdjustments().iterator();
while (orderAdjIterator.hasNext()) {
OrderAdjustment adjustment = orderAdjIterator.next();
if (adjustment.getOffer() != null) {
Long offerId = adjustment.getOffer().getId();
PromotableOrderAdjustment promotableAdjustment = newAdjustmentsMap.remove(offerId);
if (promotableAdjustment != null) {
if (!adjustment.getValue().equals(promotableAdjustment.getAdjustmentValue())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Updating value for order adjustment with offer Id " + offerId + " to " +
promotableAdjustment.getAdjustmentValue());
}
adjustment.setValue(promotableAdjustment.getAdjustmentValue());
}
} else {
// No longer using this order adjustment, remove it.
orderAdjIterator.remove();
}
}
}
for (PromotableOrderAdjustment promotableOrderAdjustment : newAdjustmentsMap.values()) {
// Add the newly introduced adjustments.
Offer offer = promotableOrderAdjustment.getOffer();
OrderAdjustment orderAdjustment = offerDao.createOrderAdjustment();
orderAdjustment.init(order, offer, offer.getName());
orderAdjustment.setValue(promotableOrderAdjustment.getAdjustmentValue());
order.getOrderAdjustments().add(orderAdjustment);
}
}
protected void synchronizeOrderItems(PromotableOrder promotableOrder) {
Order order = promotableOrder.getOrder();
Map<OrderItem, PromotableOrderItem> promotableItemMap = offerServiceUtilities.buildPromotableItemMap(promotableOrder);
List<OrderItem> orderItemList = offerServiceUtilities.buildOrderItemList(order);
for (OrderItem orderItem : orderItemList) {
PromotableOrderItem promotableItem = promotableItemMap.get(orderItem);
if (promotableItem == null) {
continue;
}
synchronizeItemPriceDetails(orderItem, promotableItem);
synchronizeItemQualifiers(orderItem, promotableItem);
}
}
protected void synchronizeItemPriceDetails(OrderItem orderItem, PromotableOrderItem promotableOrderItem) {
Map<String, PromotableOrderItemPriceDetail> promotableDetailsMap = buildPromotableDetailsMap(promotableOrderItem);
Map<Long, OrderItemPriceDetail> unmatchedDetailsMap = new HashMap<Long, OrderItemPriceDetail>();
for (OrderItemPriceDetail orderItemPriceDetail : orderItem.getOrderItemPriceDetails()) {
String detailKey = buildItemPriceDetailKey(orderItemPriceDetail);
PromotableOrderItemPriceDetail promotableDetail = promotableDetailsMap.remove(detailKey);
if (promotableDetail != null) {
processMatchingDetails(orderItemPriceDetail, promotableDetail);
} else {
unmatchedDetailsMap.put(orderItemPriceDetail.getId(), orderItemPriceDetail);
}
}
Iterator<OrderItemPriceDetail> unmatchedDetailsIterator = unmatchedDetailsMap.values().iterator();
for (PromotableOrderItemPriceDetail priceDetail : promotableDetailsMap.values()) {
if (unmatchedDetailsIterator.hasNext()) {
// Reuse an existing priceDetail
OrderItemPriceDetail existingDetail = unmatchedDetailsIterator.next();
// Reset use Sale flag to true
existingDetail.setUseSalePrice(true);
offerServiceUtilities.updatePriceDetail(existingDetail, priceDetail);
unmatchedDetailsIterator.remove();
} else {
// Create a new priceDetail
OrderItemPriceDetail newPriceDetail = orderItemDao.createOrderItemPriceDetail();
newPriceDetail.setOrderItem(orderItem);
offerServiceUtilities.updatePriceDetail(newPriceDetail, priceDetail);
orderItem.getOrderItemPriceDetails().add(newPriceDetail);
}
}
// Remove any unmatched details
Iterator<OrderItemPriceDetail> pdIterator = orderItem.getOrderItemPriceDetails().iterator();
offerServiceUtilities.removeUnmatchedPriceDetails(unmatchedDetailsMap, pdIterator);
}
protected void synchronizeItemQualifiers(OrderItem orderItem, PromotableOrderItem promotableOrderItem) {
Map<Long, PromotionQualifier> qualifiersMap = buildPromotableQualifiersMap(promotableOrderItem);
Map<Long, OrderItemQualifier> unmatchedQualifiersMap = new HashMap<Long, OrderItemQualifier>();
for (OrderItemQualifier orderItemQualifier : orderItem.getOrderItemQualifiers()) {
PromotionQualifier promotableQualifier = qualifiersMap.remove(orderItemQualifier.getOffer().getId());
if (promotableQualifier != null) {
// Offer was used as a qualifier on previous run. Update quantity if needed.
if (orderItemQualifier.getQuantity() != promotableQualifier.getQuantity()) {
orderItemQualifier.setQuantity(new Long(promotableQualifier.getQuantity()));
}
} else {
unmatchedQualifiersMap.put(orderItemQualifier.getId(), orderItemQualifier);
}
}
Iterator<OrderItemQualifier> unmatchedQualifiersIterator = unmatchedQualifiersMap.values().iterator();
for (PromotionQualifier qualifier : qualifiersMap.values()) {
if (unmatchedQualifiersIterator.hasNext()) {
// Reuse an existing qualifier
OrderItemQualifier existingQualifier = unmatchedQualifiersIterator.next();
existingQualifier.setOffer(qualifier.getPromotion());
existingQualifier.setQuantity(Long.valueOf(qualifier.getQuantity()));
unmatchedQualifiersIterator.remove();
} else {
// Create a new qualifier
OrderItemQualifier newQualifier = orderItemDao.createOrderItemQualifier();
newQualifier.setOrderItem(orderItem);
newQualifier.setOffer(qualifier.getPromotion());
newQualifier.setQuantity(Long.valueOf(qualifier.getQuantity()));
orderItem.getOrderItemQualifiers().add(newQualifier);
}
}
// Remove any unmatched qualifiers
Iterator<OrderItemQualifier> qIterator = orderItem.getOrderItemQualifiers().iterator();
offerServiceUtilities.removeUnmatchedQualifiers(unmatchedQualifiersMap, qIterator);
}
protected void processMatchingDetails(OrderItemPriceDetail itemDetail,
PromotableOrderItemPriceDetail promotableItemDetail) {
Map<Long, OrderItemPriceDetailAdjustment> itemAdjustmentMap =
offerServiceUtilities.buildItemDetailAdjustmentMap(itemDetail);
if (itemDetail.getQuantity() != promotableItemDetail.getQuantity()) {
itemDetail.setQuantity(promotableItemDetail.getQuantity());
}
for (PromotableOrderItemPriceDetailAdjustment adjustment : promotableItemDetail.getCandidateItemAdjustments()) {
OrderItemPriceDetailAdjustment itemAdjustment = itemAdjustmentMap.get(adjustment.getOfferId());
if (!itemAdjustment.getValue().equals(adjustment.getAdjustmentValue())) {
itemAdjustment.setValue(adjustment.getAdjustmentValue());
itemAdjustment.setAppliedToSalePrice(adjustment.isAppliedToSalePrice());
}
}
}
protected String buildItemPriceDetailKey(OrderItemPriceDetail itemDetail) {
List<Long> offerIds = new ArrayList<Long>();
for (OrderItemPriceDetailAdjustment adjustment : itemDetail.getOrderItemPriceDetailAdjustments()) {
Long offerId = adjustment.getOffer().getId();
offerIds.add(offerId);
}
Collections.sort(offerIds);
return itemDetail.getOrderItem().toString() + offerIds.toString() + itemDetail.getUseSalePrice();
}
protected Map<String, PromotableOrderItemPriceDetail> buildPromotableDetailsMap(PromotableOrderItem item) {
Map<String, PromotableOrderItemPriceDetail> detailsMap = new HashMap<String, PromotableOrderItemPriceDetail>();
for (PromotableOrderItemPriceDetail detail : item.getPromotableOrderItemPriceDetails()) {
detailsMap.put(detail.buildDetailKey(), detail);
}
return detailsMap;
}
protected Map<Long, PromotionQualifier> buildPromotableQualifiersMap(PromotableOrderItem item) {
Map<Long, PromotionQualifier> qualifiersMap = new HashMap<Long, PromotionQualifier>();
for (PromotableOrderItemPriceDetail detail : item.getPromotableOrderItemPriceDetails()) {
for (PromotionQualifier qualifier : detail.getPromotionQualifiers()) {
PromotionQualifier existingQualifier = qualifiersMap.get(qualifier.getPromotion().getId());
if (existingQualifier != null) {
existingQualifier.setQuantity(existingQualifier.getQuantity() + qualifier.getQuantity());
} else {
qualifiersMap.put(qualifier.getPromotion().getId(), qualifier);
}
}
}
return qualifiersMap;
}
protected void synchronizeFulfillmentGroups(PromotableOrder promotableOrder) {
Order order = promotableOrder.getOrder();
Map<Long, PromotableFulfillmentGroup> fgMap = buildPromotableFulfillmentGroupMap(promotableOrder);
for (FulfillmentGroup fg : order.getFulfillmentGroups()) {
synchronizeFulfillmentGroupAdjustments(fg, fgMap.get(fg.getId()));
}
}
protected Map<Long, PromotableFulfillmentGroup> buildPromotableFulfillmentGroupMap(PromotableOrder order) {
Map<Long, PromotableFulfillmentGroup> fgMap = new HashMap<Long, PromotableFulfillmentGroup>();
for (PromotableFulfillmentGroup fg : order.getFulfillmentGroups()) {
fgMap.put(fg.getFulfillmentGroup().getId(), fg);
}
return fgMap;
}
protected Map<Long, PromotableFulfillmentGroupAdjustment> buildPromFulfillmentAdjMap(PromotableFulfillmentGroup fg) {
Map<Long, PromotableFulfillmentGroupAdjustment> fgMap = new HashMap<Long, PromotableFulfillmentGroupAdjustment>();
for (PromotableFulfillmentGroupAdjustment adjustment : fg.getCandidateFulfillmentGroupAdjustments()) {
fgMap.put(adjustment.getPromotableCandidateFulfillmentGroupOffer().getOffer().getId(), adjustment);
}
return fgMap;
}
protected void synchronizeFulfillmentGroupAdjustments(FulfillmentGroup fg, PromotableFulfillmentGroup promotableFG) {
Iterator<FulfillmentGroupAdjustment> adjustmentIterator = fg.getFulfillmentGroupAdjustments().iterator();
Map<Long, PromotableFulfillmentGroupAdjustment> promotableAdjMap = buildPromFulfillmentAdjMap(promotableFG);
// First try and update existing adjustment records
while (adjustmentIterator.hasNext()) {
FulfillmentGroupAdjustment currentAdj = adjustmentIterator.next();
PromotableFulfillmentGroupAdjustment newAdj = promotableAdjMap.remove(currentAdj.getOffer().getId());
if (newAdj != null) {
if (!currentAdj.getValue().equals(newAdj.getAdjustmentValue())) {
// Update the currentAdj.
currentAdj.setValue(newAdj.getAdjustmentValue());
}
} else {
// Removing no longer valid adjustment
adjustmentIterator.remove();
}
}
// Now add missing adjustments
for (PromotableFulfillmentGroupAdjustment newAdj : promotableAdjMap.values()) {
FulfillmentGroupAdjustment fa = offerDao.createFulfillmentGroupAdjustment();
fa.setFulfillmentGroup(fg);
fa.init(fg, newAdj.getPromotableCandidateFulfillmentGroupOffer().getOffer(), null);
fa.setValue(newAdj.getAdjustmentValue());
fg.getFulfillmentGroupAdjustments().add(fa);
}
}
@Override
public void synchronizeAdjustmentsAndPrices(PromotableOrder promotableOrder) {
synchronizeOrderAdjustments(promotableOrder);
synchronizeOrderItems(promotableOrder);
if (extensionManager != null) {
extensionManager.getProxy().synchronizeAdjustmentsAndPrices(promotableOrder);
}
synchronizeFulfillmentGroups(promotableOrder);
}
@Override
public void setOfferDao(OfferDao offerDao) {
this.offerDao = offerDao;
}
@Override
public void setOrderItemDao(OrderItemDao orderItemDao) {
this.orderItemDao = orderItemDao;
}
public OfferServiceUtilities getOfferServiceUtilities() {
return offerServiceUtilities;
}
public void setOfferServiceUtilities(OfferServiceUtilities offerServiceUtilities) {
this.offerServiceUtilities = offerServiceUtilities;
}
}
| |
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.maps.tiled;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.assets.loaders.TextureLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.ImageResolver;
import com.badlogic.gdx.maps.ImageResolver.AssetManagerImageResolver;
import com.badlogic.gdx.maps.ImageResolver.DirectImageResolver;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.XmlReader.Element;
/** @brief synchronous loader for TMX maps created with the Tiled tool */
public class TmxMapLoader extends BaseTmxMapLoader<TmxMapLoader.Parameters> {
public static class Parameters extends BaseTmxMapLoader.Parameters {
}
public TmxMapLoader () {
super(new InternalFileHandleResolver());
}
/** Creates loader
*
* @param resolver */
public TmxMapLoader (FileHandleResolver resolver) {
super(resolver);
}
/** Loads the {@link TiledMap} from the given file. The file is resolved via the {@link FileHandleResolver} set in the
* constructor of this class. By default it will resolve to an internal file. The map will be loaded for a y-up coordinate
* system.
* @param fileName the filename
* @return the TiledMap */
public TiledMap load (String fileName) {
return load(fileName, new TmxMapLoader.Parameters());
}
/** Loads the {@link TiledMap} from the given file. The file is resolved via the {@link FileHandleResolver} set in the
* constructor of this class. By default it will resolve to an internal file.
* @param fileName the filename
* @param parameter specifies whether to use y-up, generate mip maps etc.
* @return the TiledMap */
public TiledMap load (String fileName, TmxMapLoader.Parameters parameter) {
FileHandle tmxFile = resolve(fileName);
this.root = xml.parse(tmxFile);
ObjectMap<String, Texture> textures = new ObjectMap<String, Texture>();
final Array<FileHandle> textureFiles = getDependencyFileHandles(tmxFile);
for (FileHandle textureFile : textureFiles) {
Texture texture = new Texture(textureFile, parameter.generateMipMaps);
texture.setFilter(parameter.textureMinFilter, parameter.textureMagFilter);
textures.put(textureFile.path(), texture);
}
TiledMap map = loadTiledMap(tmxFile, parameter, new DirectImageResolver(textures));
map.setOwnedResources(textures.values().toArray());
return map;
}
@Override
public void loadAsync (AssetManager manager, String fileName, FileHandle tmxFile, Parameters parameter) {
this.map = loadTiledMap(tmxFile, parameter, new AssetManagerImageResolver(manager));
}
@Override
public TiledMap loadSync (AssetManager manager, String fileName, FileHandle file, Parameters parameter) {
return map;
}
@Override
protected Array<AssetDescriptor> getDependencyAssetDescriptors (FileHandle tmxFile, TextureLoader.TextureParameter textureParameter) {
Array<AssetDescriptor> descriptors = new Array<AssetDescriptor>();
final Array<FileHandle> fileHandles = getDependencyFileHandles(tmxFile);
for (FileHandle handle : fileHandles) {
descriptors.add(new AssetDescriptor(handle, Texture.class, textureParameter));
}
return descriptors;
}
private Array<FileHandle> getDependencyFileHandles (FileHandle tmxFile) {
Array<FileHandle> fileHandles = new Array<FileHandle>();
// TileSet descriptors
for (Element tileset : root.getChildrenByName("tileset")) {
String source = tileset.getAttribute("source", null);
if (source != null) {
FileHandle tsxFile = getRelativeFileHandle(tmxFile, source);
tileset = xml.parse(tsxFile);
Element imageElement = tileset.getChildByName("image");
if (imageElement != null) {
String imageSource = tileset.getChildByName("image").getAttribute("source");
FileHandle image = getRelativeFileHandle(tsxFile, imageSource);
fileHandles.add(image);
} else {
for (Element tile : tileset.getChildrenByName("tile")) {
String imageSource = tile.getChildByName("image").getAttribute("source");
FileHandle image = getRelativeFileHandle(tsxFile, imageSource);
fileHandles.add(image);
}
}
} else {
Element imageElement = tileset.getChildByName("image");
if (imageElement != null) {
String imageSource = tileset.getChildByName("image").getAttribute("source");
FileHandle image = getRelativeFileHandle(tmxFile, imageSource);
fileHandles.add(image);
} else {
for (Element tile : tileset.getChildrenByName("tile")) {
String imageSource = tile.getChildByName("image").getAttribute("source");
FileHandle image = getRelativeFileHandle(tmxFile, imageSource);
fileHandles.add(image);
}
}
}
}
// ImageLayer descriptors
for (Element imageLayer : root.getChildrenByName("imagelayer")) {
Element image = imageLayer.getChildByName("image");
String source = image.getAttribute("source", null);
if (source != null) {
FileHandle handle = getRelativeFileHandle(tmxFile, source);
fileHandles.add(handle);
}
}
return fileHandles;
}
@Override
protected void addStaticTiles (FileHandle tmxFile, ImageResolver imageResolver, TiledMapTileSet tileSet, Element element,
Array<Element> tileElements, String name, int firstgid, int tilewidth, int tileheight, int spacing, int margin,
String source, int offsetX, int offsetY, String imageSource, int imageWidth, int imageHeight, FileHandle image) {
MapProperties props = tileSet.getProperties();
if (image != null) {
// One image for the whole tileSet
TextureRegion texture = imageResolver.getImage(image.path());
props.put("imagesource", imageSource);
props.put("imagewidth", imageWidth);
props.put("imageheight", imageHeight);
props.put("tilewidth", tilewidth);
props.put("tileheight", tileheight);
props.put("margin", margin);
props.put("spacing", spacing);
int stopWidth = texture.getRegionWidth() - tilewidth;
int stopHeight = texture.getRegionHeight() - tileheight;
int id = firstgid;
for (int y = margin; y <= stopHeight; y += tileheight + spacing) {
for (int x = margin; x <= stopWidth; x += tilewidth + spacing) {
TextureRegion tileRegion = new TextureRegion(texture, x, y, tilewidth, tileheight);
int tileId = id++;
addStaticTiledMapTile(tileSet, tileRegion, tileId, offsetX, offsetY);
}
}
} else {
// Every tile has its own image source
for (Element tileElement : tileElements) {
Element imageElement = tileElement.getChildByName("image");
if (imageElement != null) {
imageSource = imageElement.getAttribute("source");
if (source != null) {
image = getRelativeFileHandle(getRelativeFileHandle(tmxFile, source), imageSource);
} else {
image = getRelativeFileHandle(tmxFile, imageSource);
}
}
TextureRegion texture = imageResolver.getImage(image.path());
int tileId = firstgid + tileElement.getIntAttribute("id");
addStaticTiledMapTile(tileSet, texture, tileId, offsetX, offsetY);
}
}
}
}
| |
/*
* Copyright (C) 2011 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.net.wifi.p2p;
import android.os.Parcelable;
import android.os.Parcel;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* A class representing a Wi-Fi P2p group
*
* {@see WifiP2pManager}
*/
public class WifiP2pGroup implements Parcelable {
/** The temporary network id.
* {@hide} */
public static final int TEMPORARY_NET_ID = -1;
/** The persistent network id.
* If a matching persistent profile is found, use it.
* Otherwise, create a new persistent profile.
* {@hide} */
public static final int PERSISTENT_NET_ID = -2;
/** The network name */
private String mNetworkName;
/** Group owner */
private WifiP2pDevice mOwner;
/** Device is group owner */
private boolean mIsGroupOwner;
/** Group clients */
private List<WifiP2pDevice> mClients = new ArrayList<WifiP2pDevice>();
/** The passphrase used for WPA2-PSK */
private String mPassphrase;
private String mInterface;
/** The network id in the wpa_supplicant */
private int mNetId;
/** P2P group started string pattern */
private static final Pattern groupStartedPattern = Pattern.compile(
"ssid=\"(.+)\" " +
"freq=(\\d+) " +
"(?:psk=)?([0-9a-fA-F]{64})?" +
"(?:passphrase=)?(?:\"(.{0,63})\")? " +
"go_dev_addr=((?:[0-9a-f]{2}:){5}[0-9a-f]{2})" +
" ?(\\[PERSISTENT\\])?"
);
public WifiP2pGroup() {
}
/**
* @param supplicantEvent formats supported include
*
* P2P-GROUP-STARTED p2p-wlan0-0 [client|GO] ssid="DIRECT-W8" freq=2437
* [psk=2182b2e50e53f260d04f3c7b25ef33c965a3291b9b36b455a82d77fd82ca15bc|
* passphrase="fKG4jMe3"] go_dev_addr=fa:7b:7a:42:02:13 [PERSISTENT]
*
* P2P-GROUP-REMOVED p2p-wlan0-0 [client|GO] reason=REQUESTED
*
* P2P-INVITATION-RECEIVED sa=fa:7b:7a:42:02:13 go_dev_addr=f8:7b:7a:42:02:13
* bssid=fa:7b:7a:42:82:13 unknown-network
*
* P2P-INVITATION-RECEIVED sa=b8:f9:34:2a:c7:9d persistent=0
*
* Note: The events formats can be looked up in the wpa_supplicant code
* @hide
*/
public WifiP2pGroup(String supplicantEvent) throws IllegalArgumentException {
String[] tokens = supplicantEvent.split(" ");
if (tokens.length < 3) {
throw new IllegalArgumentException("Malformed supplicant event");
}
if (tokens[0].startsWith("P2P-GROUP")) {
mInterface = tokens[1];
mIsGroupOwner = tokens[2].equals("GO");
Matcher match = groupStartedPattern.matcher(supplicantEvent);
if (!match.find()) {
return;
}
mNetworkName = match.group(1);
//freq and psk are unused right now
//int freq = Integer.parseInt(match.group(2));
//String psk = match.group(3);
mPassphrase = match.group(4);
mOwner = new WifiP2pDevice(match.group(5));
if (match.group(6) != null) {
mNetId = PERSISTENT_NET_ID;
} else {
mNetId = TEMPORARY_NET_ID;
}
} else if (tokens[0].equals("P2P-INVITATION-RECEIVED")) {
String sa = null;
mNetId = PERSISTENT_NET_ID;
for (String token : tokens) {
String[] nameValue = token.split("=");
if (nameValue.length != 2) continue;
if (nameValue[0].equals("sa")) {
sa = nameValue[1];
// set source address into the client list.
WifiP2pDevice dev = new WifiP2pDevice();
dev.deviceAddress = nameValue[1];
mClients.add(dev);
continue;
}
if (nameValue[0].equals("go_dev_addr")) {
mOwner = new WifiP2pDevice(nameValue[1]);
continue;
}
if (nameValue[0].equals("persistent")) {
mOwner = new WifiP2pDevice(sa);
mNetId = Integer.parseInt(nameValue[1]);
continue;
}
}
} else {
throw new IllegalArgumentException("Malformed supplicant event");
}
}
/** @hide */
public void setNetworkName(String networkName) {
mNetworkName = networkName;
}
/**
* Get the network name (SSID) of the group. Legacy Wi-Fi clients will discover
* the p2p group using the network name.
*/
public String getNetworkName() {
return mNetworkName;
}
/** @hide */
public void setIsGroupOwner(boolean isGo) {
mIsGroupOwner = isGo;
}
/** Check whether this device is the group owner of the created p2p group */
public boolean isGroupOwner() {
return mIsGroupOwner;
}
/** @hide */
public void setOwner(WifiP2pDevice device) {
mOwner = device;
}
/** Get the details of the group owner as a {@link WifiP2pDevice} object */
public WifiP2pDevice getOwner() {
return mOwner;
}
/** @hide */
public void addClient(String address) {
addClient(new WifiP2pDevice(address));
}
/** @hide */
public void addClient(WifiP2pDevice device) {
for (WifiP2pDevice client : mClients) {
if (client.equals(device)) return;
}
mClients.add(device);
}
/** @hide */
public boolean removeClient(String address) {
return mClients.remove(new WifiP2pDevice(address));
}
/** @hide */
public boolean removeClient(WifiP2pDevice device) {
return mClients.remove(device);
}
/** @hide */
public boolean isClientListEmpty() {
return mClients.size() == 0;
}
/** @hide Returns {@code true} if the device is part of the group */
public boolean contains(WifiP2pDevice device) {
if (mOwner.equals(device) || mClients.contains(device)) return true;
return false;
}
/** Get the list of clients currently part of the p2p group */
public Collection<WifiP2pDevice> getClientList() {
return Collections.unmodifiableCollection(mClients);
}
/** @hide */
public void setPassphrase(String passphrase) {
mPassphrase = passphrase;
}
/**
* Get the passphrase of the group. This function will return a valid passphrase only
* at the group owner. Legacy Wi-Fi clients will need this passphrase alongside
* network name obtained from {@link #getNetworkName()} to join the group
*/
public String getPassphrase() {
return mPassphrase;
}
/** @hide */
public void setInterface(String intf) {
mInterface = intf;
}
/** Get the interface name on which the group is created */
public String getInterface() {
return mInterface;
}
/** @hide */
public int getNetworkId() {
return mNetId;
}
/** @hide */
public void setNetworkId(int netId) {
this.mNetId = netId;
}
public String toString() {
StringBuffer sbuf = new StringBuffer();
sbuf.append("network: ").append(mNetworkName);
sbuf.append("\n isGO: ").append(mIsGroupOwner);
sbuf.append("\n GO: ").append(mOwner);
for (WifiP2pDevice client : mClients) {
sbuf.append("\n Client: ").append(client);
}
sbuf.append("\n interface: ").append(mInterface);
sbuf.append("\n networkId: ").append(mNetId);
return sbuf.toString();
}
/** Implement the Parcelable interface */
public int describeContents() {
return 0;
}
/** copy constructor */
public WifiP2pGroup(WifiP2pGroup source) {
if (source != null) {
mNetworkName = source.getNetworkName();
mOwner = new WifiP2pDevice(source.getOwner());
mIsGroupOwner = source.mIsGroupOwner;
for (WifiP2pDevice d : source.getClientList()) mClients.add(d);
mPassphrase = source.getPassphrase();
mInterface = source.getInterface();
mNetId = source.getNetworkId();
}
}
/** Implement the Parcelable interface */
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mNetworkName);
dest.writeParcelable(mOwner, flags);
dest.writeByte(mIsGroupOwner ? (byte) 1: (byte) 0);
dest.writeInt(mClients.size());
for (WifiP2pDevice client : mClients) {
dest.writeParcelable(client, flags);
}
dest.writeString(mPassphrase);
dest.writeString(mInterface);
dest.writeInt(mNetId);
}
/** Implement the Parcelable interface */
public static final Creator<WifiP2pGroup> CREATOR =
new Creator<WifiP2pGroup>() {
public WifiP2pGroup createFromParcel(Parcel in) {
WifiP2pGroup group = new WifiP2pGroup();
group.setNetworkName(in.readString());
group.setOwner((WifiP2pDevice)in.readParcelable(null));
group.setIsGroupOwner(in.readByte() == (byte)1);
int clientCount = in.readInt();
for (int i=0; i<clientCount; i++) {
group.addClient((WifiP2pDevice) in.readParcelable(null));
}
group.setPassphrase(in.readString());
group.setInterface(in.readString());
group.setNetworkId(in.readInt());
return group;
}
public WifiP2pGroup[] newArray(int size) {
return new WifiP2pGroup[size];
}
};
}
| |
/*###
#
# Copyright Alan Kennedy.
#
# You may contact the copyright holder at this uri:
#
# http://www.xhaus.com/contact/modjy
#
# The licence under which this code is released is the Apache License v2.0.
#
# The terms and conditions of this license are listed in a file contained
# in the distribution that also contained this file, under the name
# LICENSE.txt.
#
# You may also read a copy of the license at the following web address.
#
# http://modjy.xhaus.com/LICENSE.txt
#
###*/
package com.xhaus.modjy;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Enumeration;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.python.core.Options;
import org.python.core.Py;
import org.python.core.PyException;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.core.PyType;
import org.python.util.PythonInterpreter;
public class ModjyJServlet extends HttpServlet {
protected final static String MODJY_PYTHON_CLASSNAME = "modjy_servlet";
protected final static String LIB_PYTHON = "/WEB-INF/lib-python";
protected final static String PTH_FILE_EXTENSION = ".pth";
protected final static String LOAD_SITE_PACKAGES_PARAM = "load_site_packages";
protected final static String PYTHON_HOME_PARAM = "python.home";
protected PythonInterpreter interp;
protected HttpServlet modjyServlet;
/**
* Read configuration
* 1. Both context and servlet parameters are included in the set, so that
* the definition of some parameters (e.g python.*) can be shared between multiple WSGI
* servlets.
* 2. servlet params take precedence over context parameters
*/
protected Properties readConfiguration() {
Properties props = new Properties();
// Context parameters
ServletContext context = getServletContext();
Enumeration<?> e = context.getInitParameterNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
props.put(name, context.getInitParameter(name));
}
// Servlet parameters override context parameters
e = getInitParameterNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
props.put(name, getInitParameter(name));
}
// Check if python home is relative, in which case find it in the servlet context
String pythonHomeString = props.getProperty(PYTHON_HOME_PARAM);
if (pythonHomeString != null) {
File pythonHome = new File(pythonHomeString);
if (!pythonHome.isAbsolute())
pythonHomeString = context.getRealPath(pythonHomeString);
props.setProperty(PYTHON_HOME_PARAM, pythonHomeString);
}
return props;
}
/**
* Initialise the modjy servlet.
* 1. Read the configuration
* 2. Initialise the jython runtime
* 3. Setup, in relation to the J2EE servlet environment
* 4. Create the jython-implemented servlet
* 5. Initialise the jython-implemented servlet
*/
@Override
public void init() throws ServletException {
try {
Properties props = readConfiguration();
// We check for site packages settings before initialising the runtime
// https://hg.python.org/jython/rev/51b28cc2c43d
checkSitePackages(props);
PythonInterpreter.initialize(System.getProperties(), props, new String[0]);
PySystemState systemState = new PySystemState();
interp = new PythonInterpreter(null, systemState);
setupEnvironment(interp, props, systemState);
try {
interp.exec("from modjy.modjy import " + MODJY_PYTHON_CLASSNAME);
} catch (PyException ix) {
throw new ServletException("Unable to import '" + MODJY_PYTHON_CLASSNAME
+ "': maybe you need to set the '" + PYTHON_HOME_PARAM + "' parameter?", ix);
}
PyObject pyServlet = ((PyType)interp.get(MODJY_PYTHON_CLASSNAME)).__call__();
Object temp = pyServlet.__tojava__(HttpServlet.class);
if (temp == Py.NoConversion)
throw new ServletException("Corrupted modjy file: cannot find definition of '"
+ MODJY_PYTHON_CLASSNAME + "' class");
modjyServlet = (HttpServlet)temp;
modjyServlet.init(this);
} catch (PyException pyx) {
throw new ServletException("Exception creating modjy servlet: " + pyx.toString(), pyx);
}
}
/**
* Actually service the incoming request. Simply delegate to the jython servlet.
*
* @param req
* - The incoming HttpServletRequest
* @param resp
* - The outgoing HttpServletResponse
*/
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
modjyServlet.service(req, resp);
}
/**
* Close down the modjy servlet.
*
*/
@Override
public void destroy( ) {
interp.cleanup();
}
/**
* Setup the modjy environment, i.e.
* 1. Find the location of the modjy.jar file and add it to sys.path
* 2. Process the WEB-INF/lib-python directory, if it exists
*
* @param interp
* - The PythonInterpreter used to service requests
* @param props
* - The properties from which config options are found
* @param systemState
* - The PySystemState corresponding to the interpreter servicing requests
*/
protected void setupEnvironment(PythonInterpreter interp,
Properties props,
PySystemState systemState) throws PyException {
processPythonLib(interp, systemState);
}
/**
* Check if the user has requested to initialise the jython installation "site-packages".
* The value defaults to true, i.e. load site packages
*
* @param props
* - The properties from which config options are found
*/
protected void checkSitePackages(Properties props) throws PyException {
boolean loadSitePackages = true;
String loadSitePackagesParam = props.getProperty(LOAD_SITE_PACKAGES_PARAM);
if (loadSitePackagesParam != null && loadSitePackagesParam.trim().compareTo("0") == 0) {
loadSitePackages = false;
}
Options.importSite = loadSitePackages;
}
/**
* Do all processing in relation to the lib-python subdirectory of WEB-INF
*
* @param interp
* - The PythonInterpreter used to service requests
* @param systemState
* - The PySystemState whose path should be updated
*/
protected void processPythonLib(PythonInterpreter interp, PySystemState systemState) {
// Add the lib-python directory to sys.path
String pythonLibPath = getServletContext().getRealPath(LIB_PYTHON);
if (pythonLibPath == null) {
return;
}
File pythonLib = new File(pythonLibPath);
if (!pythonLib.exists()) {
return;
}
systemState.path.append(new PyString(pythonLibPath));
// Now check for .pth files in lib-python and process each one
String[] libPythonContents = pythonLib.list();
for (String libPythonContent : libPythonContents) {
if (libPythonContent.endsWith(PTH_FILE_EXTENSION)) {
processPthFile(interp, systemState, pythonLibPath, libPythonContent);
}
}
}
/**
* Process an individual file .pth file in the lib-python directory
*
* @param interp
* - The PythonInterpreter which will execute imports
* @param systemState
* - The PySystemState whose path should be updated
* @param pythonLibPath
* - The actual path to the lib-python directory
* @param pthFilename
* - The PySystemState whose path should be updated
*/
protected void processPthFile(PythonInterpreter interp,
PySystemState systemState,
String pythonLibPath,
String pthFilename) {
try {
LineNumberReader lineReader = new LineNumberReader(new FileReader(new File(pythonLibPath,
pthFilename)));
String line;
while ((line = lineReader.readLine()) != null) {
line = line.trim();
if (line.length() == 0) {
continue;
}
if (line.startsWith("#")) {
continue;
}
if (line.startsWith("import")) {
interp.exec(line);
continue;
}
File archiveFile = new File(pythonLibPath, line);
String archiveRealpath = archiveFile.getAbsolutePath();
systemState.path.append(new PyString(archiveRealpath));
}
} catch (IOException iox) {
System.err.println("IOException: " + iox.toString());
}
}
}
| |
package org.apache.hadoop.mapred;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.Collection;
import java.util.EnumMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.corona.ClusterManagerAvailabilityChecker;
import org.apache.hadoop.corona.ClusterManagerService;
import org.apache.hadoop.corona.ClusterNode;
import org.apache.hadoop.corona.ClusterNodeInfo;
import org.apache.hadoop.corona.ComputeSpecs;
import org.apache.hadoop.corona.CoronaConf;
import org.apache.hadoop.corona.CoronaTaskTrackerService;
import org.apache.hadoop.corona.DisallowedNode;
import org.apache.hadoop.corona.InetAddress;
import org.apache.hadoop.corona.InvalidSessionHandle;
import org.apache.hadoop.corona.ResourceType;
import org.apache.hadoop.corona.SafeModeException;
import org.apache.hadoop.corona.NodeHeartbeatResponse;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.ipc.ProtocolSignature;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RPC.Server;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.util.CoronaFailureEventInjector;
import org.apache.hadoop.util.DiskChecker.DiskErrorException;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.ResourceCalculatorPlugin;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.VersionInfo;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class CoronaTaskTracker extends TaskTracker
implements CoronaTaskTrackerProtocol, CoronaTaskTrackerService.Iface {
public static final Log LOG = LogFactory.getLog(CoronaTaskTracker.class);
public static final String CORONA_TASK_TRACKER_SERVER_CLIENTTIMEOUT_KEY = "corona.task.tracker.server.clienttimeout";
public static final String CORONA_TASK_TRACKER_HANDLER_COUNT_KEY = "corona.task.tracker.handler.count";
public static final String HEART_BEAT_INTERVAL_KEY = "corona.clustermanager.heartbeat.interval";
public static final String JT_CONNECT_TIMEOUT_MSEC_KEY = "corona.jobtracker.connect.timeout.msec";
/**
* Multiplier for the number of slots to simulate on Corona to allow task
* overlapping (1 means no task overlapping) key
*/
public static final String SLOT_MULTIPLIER_KEY = "corona.slot.multiplier";
/**
* Default multiplier for the number of slots to simulate on Corona to allow
* task overlapping, 10 seems to be enough.
*/
public static final int SLOT_MULTIPLIER_DEFAULT = 10;
private static final int MAX_CM_CONNECT_RETRIES = 10;
private ClusterManagerService.Client client = null;
private TTransport transport = null;
// Thrift server to serve ClusterManager
private TServer clusterManagerCallbackServer = null;
private TServerThread clusterManagerCallbackServerThread = null;
InetAddress clusterManagerCallbackServerAddr = null;
InetSocketAddress actionServerAddr = null;
ConcurrentHashMap<String, String> blacklistedSessions =
new ConcurrentHashMap<String, String>();
private final long heartbeatCMInterval;
private volatile long lastCMHeartbeat = 0;
Server actionServer;
ConcurrentHashMap<JobID, JobTrackerReporter> jobTrackerReporters;
long jtConnectTimeoutMsec = 0;
private int clusterManagerConnectRetries;
private CoronaReleaseManager crReleaseManager;
/**
* Multiplier for the number of slots to simulate on Corona to allow
* task overlapping (1 means no task overlapping)
*/
private final int slotMultiplier;
/**
* Purge old Corona Job Tracker logs.
*/
private final Thread cjtLogCleanupThread =
new Thread(
new LogCleanupThread(
TaskLog.getLogDir(CoronaTaskTracker.jobTrackerLogDir())),
"CJTLogCleanup");
// for failure emulation
CoronaFailureEventInjector jtFailureEventInjector = null;
public void setJTFailureEventInjector(CoronaFailureEventInjector jtFailureEventInjector) {
this.jtFailureEventInjector = jtFailureEventInjector;
}
public CoronaTaskTracker(JobConf conf) throws IOException {
slotMultiplier = conf.getInt(SLOT_MULTIPLIER_KEY, SLOT_MULTIPLIER_DEFAULT);
// Default is to use netty over jetty
boolean useNetty = conf.getBoolean(NETTY_MAPOUTPUT_USE, true);
this.shuffleServerMetrics = new ShuffleServerMetrics(conf);
if (useNetty) {
initNettyMapOutputHttpServer(conf);
}
initHttpServer(conf, useNetty);
LOG.info("Http port " + httpPort +
", netty map output http port " + nettyMapOutputHttpPort +
", use netty = " + useNetty);
super.initialize(conf);
initializeTaskActionServer();
initializeClusterManagerCallbackServer();
initializeCleanupThreads();
heartbeatCMInterval = conf.getLong(HEART_BEAT_INTERVAL_KEY, 3000L);
jtConnectTimeoutMsec = conf.getLong(JT_CONNECT_TIMEOUT_MSEC_KEY, 60000L);
crReleaseManager = new CoronaReleaseManager(conf);
crReleaseManager.start();
}
private synchronized void initializeTaskActionServer() throws IOException {
// Create Hadoop RPC to serve JobTrackers
actionServerAddr = NetUtils.createSocketAddr(getLocalHostname(), 0);
int handlerCount = fConf.getInt(CORONA_TASK_TRACKER_HANDLER_COUNT_KEY, 10);
this.actionServer = RPC.getServer
(this, actionServerAddr.getHostName(), 0, handlerCount, false, fConf);
this.actionServer.start();
actionServerAddr = actionServer.getListenerAddress();
LOG.info("TaskActionServer up at " +
actionServerAddr.getHostName() + ":" + actionServerAddr.getPort());
jobTrackerReporters = new ConcurrentHashMap<JobID, JobTrackerReporter>();
String dir = fConf.get(JobTracker.MAPRED_SYSTEM_DIR_KEY,
JobTracker.DEFAULT_MAPRED_SYSTEM_DIR);
if (dir == null) {
throw new IOException("Failed to get system directory");
}
systemDirectory = new Path(dir);
systemFS = systemDirectory.getFileSystem(fConf);
}
private synchronized void initializeClusterManagerCallbackServer()
throws IOException {
// Create thrift RPC to serve ClusterManager
int soTimeout = fConf.getInt(
CORONA_TASK_TRACKER_SERVER_CLIENTTIMEOUT_KEY, 30 * 1000);
ServerSocket serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(0));
TServerSocket tSocket = new TServerSocket(serverSocket, soTimeout);
CoronaTaskTrackerService.Processor proc =
new CoronaTaskTrackerService.Processor(this);
TBinaryProtocol.Factory protocolFactory =
new TBinaryProtocol.Factory(true, true);
TThreadPoolServer.Args args = new TThreadPoolServer.Args(tSocket);
args.processor(proc);
args.protocolFactory(protocolFactory);
clusterManagerCallbackServer = new TThreadPoolServer(args);
clusterManagerCallbackServerThread =
new TServerThread(clusterManagerCallbackServer);
clusterManagerCallbackServerThread.start();
clusterManagerCallbackServerAddr = new InetAddress(
getLocalHostname(), serverSocket.getLocalPort());
LOG.info("SessionServer up at " + serverSocket.getLocalSocketAddress());
}
private synchronized void initializeClusterManagerClient()
throws IOException {
// Connect to cluster manager thrift service
String target = CoronaConf.getClusterManagerAddress(fConf);
LOG.info("Connecting to Cluster Manager at " + target);
InetSocketAddress address = NetUtils.createSocketAddr(target);
transport = new TFramedTransport(
new TSocket(address.getHostName(), address.getPort()));
TProtocol protocol = new TBinaryProtocol(transport);
client = new ClusterManagerService.Client(protocol);
try {
transport.open();
} catch (TTransportException e) {
throw new IOException(e);
}
}
private synchronized void closeClusterManagerClient() {
client = null;
if (transport != null) {
transport.close();
transport = null;
}
}
private synchronized void initializeCleanupThreads() {
cjtLogCleanupThread.setDaemon(true);
cjtLogCleanupThread.start();
}
class TServerThread extends Thread {
TServer server;
TServerThread(TServer server) {
this.server = server;
}
@Override
public void run() {
server.serve();
}
}
/**
* The server retry loop.
* This while-loop attempts to connect to the JobTracker.
*/
@Override
public void run() {
try {
startCleanupThreads();
try {
while (running && !shuttingDown) {
try {
heartbeatToClusterManager();
} catch (IOException e) {
LOG.error("Error initializing heartbeat to Cluster Manager", e);
try {
Thread.sleep(5000L);
} catch (InterruptedException ie) {
}
}
if (shuttingDown) {
return;
}
}
} finally {
shutdown();
}
} catch (IOException iex) {
LOG.error("Got fatal exception while initializing TaskTracker", iex);
return;
}
}
/**
* Main service loop. Will stay in this loop forever.
*/
private void heartbeatToClusterManager() throws IOException {
CoronaConf coronaConf = new CoronaConf(fConf);
int numCpu = coronaConf.getInt("mapred.coronatasktracker.num.cpus",
resourceCalculatorPlugin.getNumProcessors());
if (numCpu == ResourceCalculatorPlugin.UNAVAILABLE) {
numCpu = 1;
}
LOG.info("Will report " + numCpu + " CPUs");
int totalMemoryMB = (int) (resourceCalculatorPlugin.getPhysicalMemorySize() / 1024D / 1024);
ComputeSpecs total = new ComputeSpecs((short)numCpu);
total.setNetworkMBps((short)100);
total.setMemoryMB(totalMemoryMB);
total.setDiskGB(
(int)(getDiskSpace(false) / 1024D / 1024 / 1024));
String appInfo = null;
if (getLocalHostAddress() != null) {
appInfo = getLocalHostAddress() + ":" + actionServerAddr.getPort();
}
else {
appInfo = getLocalHostname() + ":" + actionServerAddr.getPort();
}
Map<ResourceType, String> resourceInfos =
new EnumMap<ResourceType, String>(ResourceType.class);
resourceInfos.put(ResourceType.MAP, appInfo);
resourceInfos.put(ResourceType.REDUCE, appInfo);
resourceInfos.put(ResourceType.JOBTRACKER, appInfo);
while (running && !shuttingDown) {
try {
long now = System.currentTimeMillis();
Thread.sleep(heartbeatCMInterval);
float cpuUsage = resourceCalculatorPlugin.getCpuUsage();
if (cpuUsage == ResourceCalculatorPlugin.UNAVAILABLE) {
cpuUsage = 0;
}
ComputeSpecs free = new ComputeSpecs((short)(numCpu * cpuUsage / 100D));
// TODO find free network.
free.setNetworkMBps((short)100);
int availableMemoryMB =
(int)(resourceCalculatorPlugin.
getAvailablePhysicalMemorySize() / 1024D / 1024);
free.setMemoryMB(availableMemoryMB);
long freeDiskSpace = getDiskSpace(true);
long freeLogDiskSpace = getLogDiskFreeSpace();
free.setDiskGB((int)(
Math.min(freeDiskSpace, freeLogDiskSpace) / 1024D / 1024 / 1024));
// TT puts it's MR specific host:port tuple here
ClusterNodeInfo node = new ClusterNodeInfo
(this.getName(), clusterManagerCallbackServerAddr, total);
node.setFree(free);
node.setResourceInfos(resourceInfos);
LOG.debug("ClusterManager heartbeat: " + node.toString());
if (client == null) {
initializeClusterManagerClient();
}
NodeHeartbeatResponse nodeHeartbeatResponse =
client.nodeHeartbeat(node);
if (nodeHeartbeatResponse.restartFlag) {
LOG.fatal("Get CM notice to exit");
System.exit(0);
}
clusterManagerConnectRetries = 0;
lastCMHeartbeat = System.currentTimeMillis();
markUnresponsiveTasks();
killOverflowingTasks();
//we've cleaned up, resume normal operation
if (!acceptNewTasks && isIdle()) {
acceptNewTasks=true;
}
//The check below may not be required every iteration but we are
//erring on the side of caution here. We have seen many cases where
//the call to jetty's getLocalPort() returns different values at
//different times. Being a real paranoid here.
checkJettyPort();
} catch (InterruptedException ie) {
LOG.info("Interrupted. Closing down.");
return;
} catch (DisallowedNode ex) {
LOG.error("CM has excluded node, shutting down TT");
shutdown();
} catch (SafeModeException e) {
LOG.info("Cluster Manager is in Safe Mode");
try {
ClusterManagerAvailabilityChecker.
waitWhileClusterManagerInSafeMode(coronaConf);
} catch (IOException ie) {
LOG.error("Could not wait while Cluster Manager is in Safe Mode ",
ie);
}
} catch (TException ex) {
if (!shuttingDown) {
LOG.error("Error connecting to CM. " + clusterManagerConnectRetries
+ "th retry. Retry in 10 seconds.", ex);
closeClusterManagerClient();
if (++clusterManagerConnectRetries >= MAX_CM_CONNECT_RETRIES) {
LOG.error("Cannot connect to CM " + clusterManagerConnectRetries +
" times. Shutting down TT");
shutdown();
}
try {
Thread.sleep(10000L);
} catch (InterruptedException ie) {
}
ClusterManagerAvailabilityChecker.
waitWhileClusterManagerInSafeMode(coronaConf);
}
}
}
}
/**
* Send heartbeats to a JobTracker to report task status
*/
class JobTrackerReporter extends Thread {
private static final long SLOW_HEARTBEAT_INTERVAL = 3 * 60 * 1000;
private InetSocketAddress jobTrackerAddr;
final InetSocketAddress secondaryTrackerAddr;
final String sessionHandle;
final RunningJob rJob;
InterTrackerProtocol jobClient = null;
boolean justInited = true;
long lastJTHeartbeat = -1;
long previousCounterUpdate = -1;
long heartbeatJTInterval = 3000L;
short heartbeatResponseId = -1;
TaskTrackerStatus status = null;
final String name;
int errorCount = 0;
// Can make configurable later, 10 is the count used for connection errors.
final int maxErrorCount = 10;
JobTrackerReporter(RunningJob rJob, InetSocketAddress jobTrackerAddr,
InetSocketAddress secondaryTrackerAddr, String sessionHandle) {
this.rJob = rJob;
this.jobTrackerAddr = jobTrackerAddr;
this.secondaryTrackerAddr = secondaryTrackerAddr;
this.sessionHandle = sessionHandle;
this.name = "JobTrackerReporter(" + rJob.getJobID() + ")";
}
volatile boolean shuttingDown = false;
@Override
public void run() {
try {
if (CoronaTaskTracker.this.running &&
!CoronaTaskTracker.this.shuttingDown) {
connect();
}
while (CoronaTaskTracker.this.running &&
!CoronaTaskTracker.this.shuttingDown &&
!this.shuttingDown) {
long now = System.currentTimeMillis();
synchronized (finishedCount) {
if (finishedCount.get() == 0) {
finishedCount.wait(heartbeatJTInterval);
}
finishedCount.set(0);
}
// If the reporter is just starting up, verify the buildVersion
if(justInited) {
String jobTrackerBV = jobClient.getBuildVersion();
if(doCheckBuildVersion() &&
!VersionInfo.getBuildVersion().equals(jobTrackerBV)) {
String msg = name + " shutting down. Incompatible buildVersion." +
"\nJobTracker's: " + jobTrackerBV +
"\nTaskTracker's: "+ VersionInfo.getBuildVersion();
LOG.error(msg);
try {
jobClient.reportTaskTrackerError(taskTrackerName, null, msg);
} catch(Exception e ) {
LOG.warn(name + " problem reporting to jobtracker: " + e);
}
shuttingDown = true;
return;
}
justInited = false;
}
Collection<TaskInProgress> tipsInSession = new LinkedList<TaskInProgress>();
boolean doHeartbeat = false;
synchronized (CoronaTaskTracker.this) {
for (TaskTracker.TaskInProgress tip : runningTasks.values()) {
if (rJob.getJobID().equals(tip.getTask().getJobID())) {
tipsInSession.add(tip);
}
}
if (!tipsInSession.isEmpty() ||
now - lastJTHeartbeat > SLOW_HEARTBEAT_INTERVAL) {
doHeartbeat = true;
// We need slow heartbeat to check if the JT is still alive
boolean sendCounters = false;
if (now > (previousCounterUpdate + COUNTER_UPDATE_INTERVAL)) {
sendCounters = true;
previousCounterUpdate = now;
}
status = updateTaskTrackerStatus(
sendCounters, null, tipsInSession, jobTrackerAddr);
}
}
if (doHeartbeat) {
// Send heartbeat only when there is at least one running tip in
// this session, or we have reached the slow heartbeat interval.
LOG.info(name + " heartbeat:" + jobTrackerAddr.toString() +
" hearbeatId:" + heartbeatResponseId + " " + status.toString());
try {
HeartbeatResponse heartbeatResponse =
(new Caller<HeartbeatResponse>() {
@Override
protected HeartbeatResponse call() throws IOException {
return transmitHeartBeat(jobClient, heartbeatResponseId,
status);
}
}).makeCall();
// The heartbeat got through successfully!
// Reset error count after a successful heartbeat.
errorCount = 0;
heartbeatResponseId = heartbeatResponse.getResponseId();
heartbeatJTInterval = heartbeatResponse.getHeartbeatInterval();
// Note the time when the heartbeat returned, use this to decide when to send the
// next heartbeat
lastJTHeartbeat = System.currentTimeMillis();
// resetting heartbeat interval from the response.
justStarted = false;
} catch (ConnectException e) {
// JobTracker is dead. Purge the job.
// Or it will timeout this task.
// Treat the task as killed
LOG.error(name + " connect error in reporting to " + jobTrackerAddr, e);
throw e;
} catch (IOException e) {
handleIOException(e);
}
}
}
} catch (DiskErrorException de) {
String msg = name + " exiting for disk error:\n" +
StringUtils.stringifyException(de);
LOG.error(msg);
try {
jobClient.reportTaskTrackerError(taskTrackerName,
"DiskErrorException", msg);
} catch (IOException exp) {
LOG.error(name + " cannot report TaskTracker failure");
}
} catch (IOException e) {
purgeSession(this.sessionHandle);
} catch (InterruptedException e) {
LOG.info(name + " interrupted");
}
}
private void connect() throws IOException {
try {
LOG.info(name + " connecting to " + this.jobTrackerAddr);
jobClient = RPC.waitForProtocolProxy(
InterTrackerProtocol.class,
InterTrackerProtocol.versionID,
this.jobTrackerAddr,
CoronaTaskTracker.this.fConf,
jtConnectTimeoutMsec).getProxy();
rJob.setJobClient(jobClient);
} catch (IOException e) {
LOG.error(name + " failed to connect to " + jobTrackerAddr, e);
throw e;
}
}
public void shutdown() {
LOG.info(name + " shutting down");
// shutdown RPC connections
RPC.stopProxy(jobClient);
shuttingDown = true;
}
private void handleIOException(IOException e) throws IOException {
errorCount++;
if (errorCount >= maxErrorCount) {
LOG.error(name + " too many errors " + maxErrorCount +
" in reporting to " + jobTrackerAddr, e);
throw e;
} else {
long backoff = errorCount * heartbeatJTInterval;
LOG.warn(
name + " error " + errorCount + " in reporting to " + jobTrackerAddr +
" will wait " + backoff + " msec", e);
try {
Thread.sleep(backoff);
} catch (InterruptedException ie) {
}
}
}
/**
* Handles fallback process and connecting to new job tracker
* @param <T> return type of called function
*/
private abstract class Caller<T> extends CoronaJTFallbackCaller<T> {
@Override
protected void handleIOException(IOException e) throws IOException {
JobTrackerReporter.this.handleIOException(e);
}
@Override
protected void connect(InetSocketAddress address) throws IOException {
JobTrackerReporter.this.jobTrackerAddr = address;
JobTrackerReporter.this.connect();
}
@Override
protected void shutdown() {
RPC.stopProxy(JobTrackerReporter.this.jobClient);
}
@Override
protected InetSocketAddress getCurrentClientAddress() {
return JobTrackerReporter.this.jobTrackerAddr;
}
@Override
protected JobConf getConf() {
return CoronaTaskTracker.this.fConf;
}
@Override
protected boolean predRetry(int retryNum) {
return super.predRetry(retryNum)
&& (CoronaTaskTracker.this.running
&& !CoronaTaskTracker.this.shuttingDown
&& !JobTrackerReporter.this.shuttingDown);
}
@Override
protected void waitRetry() throws InterruptedException {
synchronized (finishedCount) {
finishedCount.wait(heartbeatJTInterval);
}
}
@Override
protected InetSocketAddress getSecondaryTracker() {
return JobTrackerReporter.this.secondaryTrackerAddr;
}
}
}
@Override
public Boolean isAlive() {
long timeSinceHeartbeat = System.currentTimeMillis() - lastCMHeartbeat;
CoronaConf cConf = new CoronaConf(fConf);
long expire = cConf.getNodeExpiryInterval();
if (timeSinceHeartbeat > expire) {
return false;
}
return true;
}
@Override
public void submitActions(TaskTrackerAction[] actions) throws IOException,
InterruptedException {
if (actions != null){
for(TaskTrackerAction action: actions) {
CoronaSessionInfo info = (CoronaSessionInfo)(action.getExtensible());
if (info == null ||
info.getSessionHandle() == null ||
info.getJobTrackerAddr() == null) {
LOG.warn("Received a " + action + " from unkown JobTracker. Ignored.");
continue;
}
if (blacklistedSessions.contains(info.getSessionHandle())) {
LOG.warn("Received a " + action + " from blacklisted session " +
info.getSessionHandle() + ". Ignored.");
continue;
}
switch (action.getActionId()) {
case LAUNCH_TASK:
LaunchTaskAction launchAction = (LaunchTaskAction)action;
LOG.info("Received launch task action for " +
launchAction.getTask().getTaskID());
addToTaskQueue(launchAction);
break;
case COMMIT_TASK:
CommitTaskAction commitAction = (CommitTaskAction)action;
if (!commitResponses.contains(commitAction.getTaskID())) {
LOG.info("Received commit task action for " +
commitAction.getTaskID());
commitResponses.add(commitAction.getTaskID());
}
break;
case KILL_JOB:
JobID jobId = ((KillJobAction)action).getJobID();
LOG.info("Received kill job action for " + jobId);
List<TaskAttemptID> running = getRunningTasksForJob(jobId);
for (TaskAttemptID attemptID : running) {
removeRunningTask(attemptID);
}
tasksToCleanup.put(action);
break;
case KILL_TASK:
LOG.info("Received kill task action for " +
((KillTaskAction)action).getTaskID());
tasksToCleanup.put(action);
break;
case REINIT_TRACKER:
LOG.error("Recieved unsupport RenitTrackerAction from " +
info.getJobTrackerAddr() + " Ignored.");
}
}
}
}
@SuppressWarnings("deprecation")
@Override
public void startCoronaJobTracker(Task jobTask, CoronaSessionInfo info)
throws IOException {
// The "client" should already have submitted the
// job.xml file and the split file to the system directory.
LOG.info("Processing startCoronaJobTracker request for "
+ jobTask.getJobID() + " from " + info.getJobTrackerAddr());
TaskTracker.TaskInProgress tip = new TaskInProgress(jobTask, fConf, null,
null);
String releasePath = crReleaseManager.getRelease(jobTask.getJobID());
String originalPath = crReleaseManager.getOriginal();
CoronaJobTrackerRunner runner =
new CoronaJobTrackerRunner(tip, jobTask, this, new JobConf(this.getJobConf()), info,
originalPath, releasePath);
runner.start();
}
void stopActionServer() {
if (actionServer != null) {
actionServer.stop();
actionServer = null;
}
}
@Override
public synchronized void close() throws IOException {
super.close();
LOG.info(CoronaTaskTracker.class + " closed.");
closeClusterManagerClient();
stopActionServer();
if (transport != null) {
transport.close();
}
if (clusterManagerCallbackServerThread != null) {
clusterManagerCallbackServerThread.interrupt();
}
if (clusterManagerCallbackServer != null) {
clusterManagerCallbackServer.stop();
}
for (JobTrackerReporter reporter : jobTrackerReporters.values()) {
reporter.shutdown();
}
if (crReleaseManager != null){
crReleaseManager.shutdown();
}
}
@Override
protected int getMaxSlots(JobConf conf, int numCpuOnTT, TaskType type) {
int ret = getMaxActualSlots(conf, numCpuOnTT, type);
// Use a large value of slots if desired. This effectively removes slots as
// a concept and lets the Cluster Manager manage the resources.
return ret * slotMultiplier;
}
@Override
int getMaxActualSlots(JobConf conf, int numCpuOnTT, TaskType type) {
Map<Integer, Map<ResourceType, Integer>> cpuToResourcePartitioning =
CoronaConf.getUncachedCpuToResourcePartitioning(conf);
if (numCpuOnTT == ResourceCalculatorPlugin.UNAVAILABLE) {
numCpuOnTT = 1;
}
Map<ResourceType, Integer> resourceTypeToCountMap =
ClusterNode.getResourceTypeToCountMap(numCpuOnTT,
cpuToResourcePartitioning);
switch (type) {
case MAP:
return resourceTypeToCountMap.get(ResourceType.MAP);
case REDUCE:
return resourceTypeToCountMap.get(ResourceType.REDUCE);
default:
throw new RuntimeException("getMaxActualSlots: Illegal type " + type);
}
}
/**
* Override this method to create the proper jobClient and the thread that
* sends jobTracker heartbeat.
*/
@Override
protected RunningJob createRunningJob(JobID jobId, TaskInProgress tip)
throws IOException {
CoronaSessionInfo info = (CoronaSessionInfo)(tip.getExtensible());
// JobClient will be set by JobTrackerReporter thread later
RunningJob rJob = new RunningJob(jobId, null, info);
JobTrackerReporter reporter = new JobTrackerReporter(rJob,
info.getJobTrackerAddr(), info.getSecondaryTracker(),
info.getSessionHandle());
reporter.setName("JobTrackerReporter for " + jobId);
// Start the heartbeat to the jobtracker
reporter.start();
jobTrackerReporters.put(jobId, reporter);
return rJob;
}
/**
* Override this to shutdown the heartbeat the the corresponding jobtracker
*/
@Override
protected synchronized void purgeJob(KillJobAction action) throws IOException {
JobID jobId = action.getJobID();
JobTrackerReporter reporter = jobTrackerReporters.remove(jobId);
if (reporter != null) {
reporter.shutdown();
}
super.purgeJob(action);
crReleaseManager.returnRelease(jobId);
}
@Override
public long getProtocolVersion(String protocol,
long clientVersion) throws IOException {
if (protocol.equals(CoronaTaskTrackerProtocol.class.getName())) {
return CoronaTaskTrackerProtocol.versionID;
}
return super.getProtocolVersion(protocol, clientVersion);
}
@Override
public ProtocolSignature getProtocolSignature(String protocol,
long clientVersion, int clientMethodsHash) throws IOException {
return ProtocolSignature.getProtocolSignature(this, protocol,
clientVersion, clientMethodsHash);
}
/**
* Start the TaskTracker, point toward the indicated JobTracker
*/
public static void main(String argv[]) throws Exception {
StringUtils.startupShutdownMessage(CoronaTaskTracker.class, argv, LOG);
if (argv.length != 0) {
System.out.println("usage: CoronaTaskTracker");
System.exit(-1);
}
JobConf conf=new JobConf();
// enable the server to track time spent waiting on locks
ReflectionUtils.setContentionTracing
(conf.getBoolean("tasktracker.contention.tracking", false));
try {
new CoronaTaskTracker(conf).run();
} catch (Throwable t) {
LOG.fatal("Error running CoronaTaskTracker", t);
System.exit(-2);
}
}
@Override
public void purgeSession(String handle) {
synchronized (runningJobs) {
for (TaskTracker.RunningJob job : this.runningJobs.values()) {
CoronaSessionInfo info = (CoronaSessionInfo)(job.getExtensible());
if (info.getSessionHandle().equals(handle)) {
tasksToCleanup.add(new KillJobAction(job.getJobID()));
}
}
}
}
@Override
public void blacklistSession(String handle) throws InvalidSessionHandle,
TException {
blacklistedSessions.put(handle, handle);
}
@Override
protected void reconfigureLocalJobConf(JobConf localJobConf,
Path localJobFile, TaskInProgress tip, boolean changed)
throws IOException {
localJobConf.set(JobConf.TASK_RUNNER_CHILD_CLASS_CONF,
CoronaChild.class.getName());
CoronaSessionInfo info = (CoronaSessionInfo) (tip.getExtensible());
InetSocketAddress directAddress = CoronaDirectTaskUmbilical.getAddress(
localJobConf, CoronaDirectTaskUmbilical.DIRECT_UMBILICAL_JT_ADDRESS);
if (directAddress == null
|| !directAddress.equals(info.getJobTrackerAddr())) {
CoronaDirectTaskUmbilical.setAddress(localJobConf,
CoronaDirectTaskUmbilical.DIRECT_UMBILICAL_JT_ADDRESS,
info.getJobTrackerAddr());
CoronaDirectTaskUmbilical.setAddress(localJobConf,
CoronaDirectTaskUmbilical.DIRECT_UMBILICAL_FALLBACK_ADDRESS,
info.getSecondaryTracker());
changed = true;
}
super.reconfigureLocalJobConf(localJobConf, localJobFile, tip, changed);
}
@Override
protected TaskUmbilicalProtocol getUmbilical(TaskInProgress tip)
throws IOException {
CoronaSessionInfo info = (CoronaSessionInfo)(tip.getExtensible());
if (info != null) {
return CoronaDirectTaskUmbilical.createDirectUmbilical(
this, info.getJobTrackerAddr(), info.getSecondaryTracker(), fConf);
}
return this;
}
@Override
protected void cleanupUmbilical(TaskUmbilicalProtocol t) {
if (t instanceof CoronaDirectTaskUmbilical) {
((CoronaDirectTaskUmbilical) t).close();
}
}
public static String jobTrackerLogDir() {
return new File(
System.getProperty("hadoop.log.dir"), "jtlogs").getAbsolutePath();
}
}
| |
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.stream.binder;
import java.io.IOException;
import java.util.Collections;
import java.util.Properties;
import org.junit.Before;
import org.junit.Test;
import org.springframework.cloud.stream.binder.MessageChannelBinderSupport.JavaClassMimeTypeConversion;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.ContentTypeResolver;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.xd.dirt.integration.bus.serializer.kryo.PojoCodec;
import org.springframework.xd.tuple.DefaultTuple;
import org.springframework.xd.tuple.Tuple;
import org.springframework.xd.tuple.TupleBuilder;
import org.springframework.xd.tuple.serializer.kryo.TupleKryoRegistrar;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/**
* @author Gary Russell
* @author David Turanski
*/
public class MessageChannelBinderSupportTests {
private ContentTypeResolver contentTypeResolver = new StringConvertingContentTypeResolver();
private final TestMessageChannelBinder binder = new TestMessageChannelBinder();
@SuppressWarnings({"unchecked", "rawtypes"})
@Before
public void setUp() {
binder.setCodec(new PojoCodec(new TupleKryoRegistrar()));
}
@Test
public void testBytesPassThru() {
byte[] payload = "foo".getBytes();
Message<byte[]> message = MessageBuilder.withPayload(payload).build();
MessageValues converted = binder.serializePayloadIfNecessary(message);
assertSame(payload, converted.getPayload());
Message<?> convertedMessage = converted.toMessage();
assertSame(payload, convertedMessage.getPayload());
assertEquals(MimeTypeUtils.APPLICATION_OCTET_STREAM,
contentTypeResolver.resolve(convertedMessage.getHeaders()));
MessageValues reconstructed = binder.deserializePayloadIfNecessary(convertedMessage);
payload = (byte[]) reconstructed.getPayload();
assertSame(converted.getPayload(), payload);
assertNull(reconstructed.get(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE));
}
@Test
public void testBytesPassThruContentType() {
byte[] payload = "foo".getBytes();
Message<byte[]> message = MessageBuilder.withPayload(payload)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE)
.build();
MessageValues messageValues = binder.serializePayloadIfNecessary(message);
Message<?> converted = messageValues.toMessage();
assertSame(payload, converted.getPayload());
assertEquals(MimeTypeUtils.APPLICATION_OCTET_STREAM,
contentTypeResolver.resolve(converted.getHeaders()));
MessageValues reconstructed = binder.deserializePayloadIfNecessary(converted);
payload = (byte[]) reconstructed.getPayload();
assertSame(converted.getPayload(), payload);
assertEquals(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE,
reconstructed.get(MessageHeaders.CONTENT_TYPE));
assertNull(reconstructed.get(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE));
}
@Test
public void testString() throws IOException {
MessageValues convertedValues = binder.serializePayloadIfNecessary(
new GenericMessage<String>("foo"));
Message<?> converted = convertedValues.toMessage();
assertEquals(MimeTypeUtils.TEXT_PLAIN,
contentTypeResolver.resolve(converted.getHeaders()));
MessageValues reconstructed = binder.deserializePayloadIfNecessary(converted);
assertEquals("foo", reconstructed.getPayload());
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testContentTypePreserved() throws IOException {
Message<String> inbound = MessageBuilder.withPayload("{\"foo\":\"foo\"}")
.copyHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON))
.build();
MessageValues convertedValues = binder.serializePayloadIfNecessary(
inbound);
Message<?> converted = convertedValues.toMessage();
assertEquals(MimeTypeUtils.TEXT_PLAIN,
contentTypeResolver.resolve(converted.getHeaders()));
assertEquals(MimeTypeUtils.APPLICATION_JSON,
converted.getHeaders().get(BinderHeaders.BINDER_ORIGINAL_CONTENT_TYPE));
MessageValues reconstructed = binder.deserializePayloadIfNecessary(converted);
assertEquals("{\"foo\":\"foo\"}", reconstructed.getPayload());
assertEquals(MimeTypeUtils.APPLICATION_JSON, reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testPojoSerialization() {
MessageValues convertedValues = binder.serializePayloadIfNecessary(
new GenericMessage<Foo>(new Foo("bar")));
Message<?> converted = convertedValues.toMessage();
MimeType mimeType = contentTypeResolver.resolve(converted.getHeaders());
assertEquals("application", mimeType.getType());
assertEquals("x-java-object", mimeType.getSubtype());
assertEquals(Foo.class.getName(), mimeType.getParameter("type"));
MessageValues reconstructed = binder.deserializePayloadIfNecessary(converted);
assertEquals("bar", ((Foo) reconstructed.getPayload()).getBar());
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testPojoWithXJavaObjectMimeTypeNoType() {
MessageValues convertedValues = binder.serializePayloadIfNecessary(
new GenericMessage<Foo>(new Foo("bar")));
Message<?> converted = convertedValues.toMessage();
MimeType mimeType = contentTypeResolver.resolve(converted.getHeaders());
assertEquals("application", mimeType.getType());
assertEquals("x-java-object", mimeType.getSubtype());
assertEquals(Foo.class.getName(), mimeType.getParameter("type"));
MessageValues reconstructed = binder.deserializePayloadIfNecessary(converted);
assertEquals("bar", ((Foo) reconstructed.getPayload()).getBar());
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testPojoWithXJavaObjectMimeTypeExplicitType() {
MessageValues convertedValues = binder.serializePayloadIfNecessary(
new GenericMessage<Foo>(new Foo("bar")));
Message<?> converted = convertedValues.toMessage();
MimeType mimeType = contentTypeResolver.resolve(converted.getHeaders());
assertEquals("application", mimeType.getType());
assertEquals("x-java-object", mimeType.getSubtype());
assertEquals(Foo.class.getName(), mimeType.getParameter("type"));
MessageValues reconstructed = binder.deserializePayloadIfNecessary(converted);
assertEquals("bar", ((Foo) reconstructed.getPayload()).getBar());
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testTupleSerialization() {
Tuple payload = TupleBuilder.tuple().of("foo", "bar");
MessageValues convertedValues = binder.serializePayloadIfNecessary(new GenericMessage<Tuple>(payload));
Message<?> converted = convertedValues.toMessage();
MimeType mimeType = contentTypeResolver.resolve(converted.getHeaders());
assertEquals("application", mimeType.getType());
assertEquals("x-java-object", mimeType.getSubtype());
assertEquals(DefaultTuple.class.getName(), mimeType.getParameter("type"));
MessageValues reconstructed = binder.deserializePayloadIfNecessary(converted);
assertEquals("bar", ((Tuple) reconstructed.getPayload()).getString("foo"));
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void mimeTypeIsSimpleObject() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new Object());
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(Object.class, Class.forName(className));
}
@Test
public void mimeTypeIsObjectArray() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new String[0]);
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(String[].class, Class.forName(className));
}
@Test
public void mimeTypeIsMultiDimensionalObjectArray() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new String[0][0][0]);
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(String[][][].class, Class.forName(className));
}
@Test
public void mimeTypeIsPrimitiveArray() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new int[0]);
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(int[].class, Class.forName(className));
}
@Test
public void mimeTypeIsMultiDimensionalPrimitiveArray() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new int[0][0][0]);
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(int[][][].class, Class.forName(className));
}
public static class Foo {
private String bar;
public Foo() {
}
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
public static class Bar {
private String foo;
public Bar() {
}
public Bar(String foo) {
this.foo = foo;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
public class TestMessageChannelBinder extends MessageChannelBinderSupport {
@Override
public void bindConsumer(String name, MessageChannel channel, Properties properties) {
}
@Override
public void bindPubSubConsumer(String name, MessageChannel moduleInputChannel,
Properties properties) {
}
@Override
public void bindPubSubProducer(String name, MessageChannel moduleOutputChannel,
Properties properties) {
}
@Override
public void bindProducer(String name, MessageChannel channel, Properties properties) {
}
@Override
public void bindRequestor(String name, MessageChannel requests, MessageChannel replies,
Properties properties) {
}
@Override
public void bindReplier(String name, MessageChannel requests, MessageChannel replies,
Properties properties) {
}
}
}
| |
/**
* 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.openejb.test.entity.cmp;
import java.util.StringTokenizer;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.EJBHome;
import javax.ejb.EJBMetaData;
import javax.ejb.EJBObject;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.Handle;
import javax.naming.InitialContext;
import org.apache.openejb.test.object.ObjectGraph;
public abstract class RmiIiopCmp2Bean implements EntityBean {
private static int nextId;
public EntityContext ejbContext;
public abstract Integer getId();
public abstract void setId(Integer primaryKey);
public abstract String getFirstName();
public abstract void setFirstName(String firstName);
public abstract String getLastName();
public abstract void setLastName(String lastName);
//=============================
// Home interface methods
//
/**
* Maps to RmiIiopCmpHome.create
*/
public Integer ejbCreate(String name) throws CreateException {
setId(nextId++);
StringTokenizer st = new StringTokenizer(name, " ");
setFirstName(st.nextToken());
setLastName(st.nextToken());
return null;
}
public void ejbPostCreate(String name) {
}
//
// Home interface methods
//=============================
//=============================
// Remote interface methods
//
/*-------------------------------------------------*/
/* String */
/*-------------------------------------------------*/
public String returnStringObject(String data) {
return data;
}
public String[] returnStringObjectArray(String[] data) {
return data;
}
/*-------------------------------------------------*/
/* Character */
/*-------------------------------------------------*/
public Character returnCharacterObject(Character data) {
return data;
}
public char returnCharacterPrimitive(char data) {
return data;
}
public Character[] returnCharacterObjectArray(Character[] data) {
return data;
}
public char[] returnCharacterPrimitiveArray(char[] data) {
return data;
}
/*-------------------------------------------------*/
/* Boolean */
/*-------------------------------------------------*/
public Boolean returnBooleanObject(Boolean data) {
return data;
}
public boolean returnBooleanPrimitive(boolean data) {
return data;
}
public Boolean[] returnBooleanObjectArray(Boolean[] data) {
return data;
}
public boolean[] returnBooleanPrimitiveArray(boolean[] data) {
return data;
}
/*-------------------------------------------------*/
/* Byte */
/*-------------------------------------------------*/
public Byte returnByteObject(Byte data) {
return data;
}
public byte returnBytePrimitive(byte data) {
return data;
}
public Byte[] returnByteObjectArray(Byte[] data) {
return data;
}
public byte[] returnBytePrimitiveArray(byte[] data) {
return data;
}
/*-------------------------------------------------*/
/* Short */
/*-------------------------------------------------*/
public Short returnShortObject(Short data) {
return data;
}
public short returnShortPrimitive(short data) {
return data;
}
public Short[] returnShortObjectArray(Short[] data) {
return data;
}
public short[] returnShortPrimitiveArray(short[] data) {
return data;
}
/*-------------------------------------------------*/
/* Integer */
/*-------------------------------------------------*/
public Integer returnIntegerObject(Integer data) {
return data;
}
public int returnIntegerPrimitive(int data) {
return data;
}
public Integer[] returnIntegerObjectArray(Integer[] data) {
return data;
}
public int[] returnIntegerPrimitiveArray(int[] data) {
return data;
}
/*-------------------------------------------------*/
/* Long */
/*-------------------------------------------------*/
public Long returnLongObject(Long data) {
return data;
}
public long returnLongPrimitive(long data) {
return data;
}
public Long[] returnLongObjectArray(Long[] data) {
return data;
}
public long[] returnLongPrimitiveArray(long[] data) {
return data;
}
/*-------------------------------------------------*/
/* Float */
/*-------------------------------------------------*/
public Float returnFloatObject(Float data) {
return data;
}
public float returnFloatPrimitive(float data) {
return data;
}
public Float[] returnFloatObjectArray(Float[] data) {
return data;
}
public float[] returnFloatPrimitiveArray(float[] data) {
return data;
}
/*-------------------------------------------------*/
/* Double */
/*-------------------------------------------------*/
public Double returnDoubleObject(Double data) {
return data;
}
public double returnDoublePrimitive(double data) {
return data;
}
public Double[] returnDoubleObjectArray(Double[] data) {
return data;
}
public double[] returnDoublePrimitiveArray(double[] data) {
return data;
}
/*-------------------------------------------------*/
/* EJBHome */
/*-------------------------------------------------*/
public EJBHome returnEJBHome(EJBHome data) {
return data;
}
public EJBHome returnEJBHome() {
EJBHome data = null;
try {
InitialContext ctx = new InitialContext();
data = (EJBHome) ctx.lookup("java:comp/env/cmp/rmi-iiop/home");
} catch (Exception e) {
e.printStackTrace();
throw new EJBException(e);
}
return data;
}
public ObjectGraph returnNestedEJBHome() {
ObjectGraph data = null;
try {
InitialContext ctx = new InitialContext();
Object object = ctx.lookup("java:comp/env/cmp/rmi-iiop/home");
data = new ObjectGraph(object);
} catch (Exception e) {
throw new EJBException(e);
}
return data;
}
public EJBHome[] returnEJBHomeArray(EJBHome[] data) {
return data;
}
/*-------------------------------------------------*/
/* EJBObject */
/*-------------------------------------------------*/
public EJBObject returnEJBObject(EJBObject data) {
return data;
}
public EJBObject returnEJBObject() {
EncCmpObject data = null;
try {
InitialContext ctx = new InitialContext();
EncCmpHome home = (EncCmpHome) ctx.lookup("java:comp/env/cmp/rmi-iiop/home");
data = home.create("Test01 CmpBean");
} catch (Exception e) {
throw new EJBException(e);
}
return data;
}
public ObjectGraph returnNestedEJBObject() {
ObjectGraph data = null;
try {
InitialContext ctx = new InitialContext();
EncCmpHome home = (EncCmpHome) ctx.lookup("java:comp/env/cmp/rmi-iiop/home");
EncCmpObject object = home.create("Test02 CmpBean");
data = new ObjectGraph(object);
} catch (Exception e) {
throw new EJBException(e);
}
return data;
}
public EJBObject[] returnEJBObjectArray(EJBObject[] data) {
return data;
}
/*-------------------------------------------------*/
/* EJBMetaData */
/*-------------------------------------------------*/
public EJBMetaData returnEJBMetaData(EJBMetaData data) {
return data;
}
public EJBMetaData returnEJBMetaData() {
EJBMetaData data = null;
try {
InitialContext ctx = new InitialContext();
EncCmpHome home = (EncCmpHome) ctx.lookup("java:comp/env/cmp/rmi-iiop/home");
data = home.getEJBMetaData();
} catch (Exception e) {
throw new EJBException(e);
}
return data;
}
public ObjectGraph returnNestedEJBMetaData() {
ObjectGraph data = null;
try {
InitialContext ctx = new InitialContext();
EncCmpHome home = (EncCmpHome) ctx.lookup("java:comp/env/cmp/rmi-iiop/home");
EJBMetaData object = home.getEJBMetaData();
data = new ObjectGraph(object);
} catch (Exception e) {
throw new EJBException(e);
}
return data;
}
public EJBMetaData[] returnEJBMetaDataArray(EJBMetaData[] data) {
return data;
}
/*-------------------------------------------------*/
/* Handle */
/*-------------------------------------------------*/
public Handle returnHandle(Handle data) {
return data;
}
public Handle returnHandle() {
Handle data = null;
try {
InitialContext ctx = new InitialContext();
EncCmpHome home = (EncCmpHome) ctx.lookup("java:comp/env/cmp/rmi-iiop/home");
EncCmpObject object = home.create("Test03 CmpBean");
data = object.getHandle();
} catch (Exception e) {
throw new EJBException(e);
}
return data;
}
public ObjectGraph returnNestedHandle() {
ObjectGraph data = null;
try {
InitialContext ctx = new InitialContext();
EncCmpHome home = (EncCmpHome) ctx.lookup("java:comp/env/cmp/rmi-iiop/home");
EncCmpObject object = home.create("Test04 CmpBean");
data = new ObjectGraph(object.getHandle());
} catch (Exception e) {
throw new EJBException(e);
}
return data;
}
public Handle[] returnHandleArray(Handle[] data) {
return data;
}
/*-------------------------------------------------*/
/* ObjectGraph */
/*-------------------------------------------------*/
public ObjectGraph returnObjectGraph(ObjectGraph data) {
return data;
}
public ObjectGraph[] returnObjectGraphArray(ObjectGraph[] data) {
return data;
}
//
// Remote interface methods
//=============================
//================================
// EntityBean interface methods
//
/**
* A container invokes this method to instruct the
* instance to synchronize its state by loading it state from the
* underlying database.
*/
public void ejbLoad() {
}
/**
* Set the associated entity context. The container invokes this method
* on an instance after the instance has been created.
*/
public void setEntityContext(EntityContext ctx) {
ejbContext = ctx;
}
/**
* Unset the associated entity context. The container calls this method
* before removing the instance.
*/
public void unsetEntityContext() {
}
/**
* A container invokes this method to instruct the
* instance to synchronize its state by storing it to the underlying
* database.
*/
public void ejbStore() {
}
/**
* A container invokes this method before it removes the EJB object
* that is currently associated with the instance. This method
* is invoked when a client invokes a remove operation on the
* enterprise Bean's home interface or the EJB object's remote interface.
* This method transitions the instance from the ready state to the pool
* of available instances.
*/
public void ejbRemove() {
}
/**
* A container invokes this method when the instance
* is taken out of the pool of available instances to become associated
* with a specific EJB object. This method transitions the instance to
* the ready state.
*/
public void ejbActivate() {
}
/**
* A container invokes this method on an instance before the instance
* becomes disassociated with a specific EJB object. After this method
* completes, the container will place the instance into the pool of
* available instances.
*/
public void ejbPassivate() {
}
//
// EntityBean interface methods
//================================
}
| |
/**
*
*/
package controller;
import static common.TEST.random;
import static common.TEST.DEFAULT_TIMEOUT;
import static org.junit.Assert.*;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import model.CelestialObject;
import model.CelestialObjectTest;
import model.MaserComponent;
import model.MaserComponentTest;
import model.DBTable;
import model.DBTableTest;
import model.DataBase;
import model.Observation;
import view.ColorCodeImage;
import view.GridImage;
import view.MaserComponentsImage;
import view.MaserComponentsImageTest;
import view.ObservationImage;
import view.TextDataImage;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.SystemUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import tools.MyImage;
import tools.ToolBox;
public class ObservationImageBuilderTest {
static DataBase dataBase;
static ObservationImageBuilder obsImgBuilder;
static File tmpDir = SystemUtils.getJavaIoTmpDir();
Observation observation;
HashMap<String, Object> obsData;
MaserComponent[] maserComponents;
CelestialObject celObj;
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
dataBase = new DataBase(true, common.TEST.dbURL, common.TEST.dbFile);
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
dataBase=null;
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
// create CelestialObject
celObj = new CelestialObject(CelestialObjectTest.randomCelObjRow());
DBTable celObjTable=new DBTable("CELESTIALOBJECTS");
celObj.insertMap2DBTable(celObj.getDataMap());
int celObjTableID=(Integer)celObjTable.getRowsOrderByID()[0].get("id");
celObj.setID(celObjTableID);
// create Observation
obsData =DBTableTest.randomRowData("OBSERVATIONS");
obsData.put("object_id", celObjTableID);
observation = new Observation(obsData);
// create components
int numberOfComponents = random.nextInt(100) + 1;
maserComponents=new MaserComponent[numberOfComponents];
for (int i = 0; i < numberOfComponents; i++) {
HashMap<String, Object> row = MaserComponentTest.randomComponentRow(MaserComponentsImageTest.xRange,
MaserComponentsImageTest.yRange, MaserComponentsImageTest.vRange,
MaserComponentsImageTest.iRange, MaserComponentsImageTest.bRange);
row.put("id", 0);
row.put("object_id", 666);
maserComponents[i]=new MaserComponent(row, false);
}
observation.setComponents(maserComponents);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
dataBase.clearTables();
obsImgBuilder=null;
observation=null;
obsData=null;
maserComponents=null;
celObj=null;
}
/**
* Test method for
* {@link controller.ObservationImageBuilder#ObservationImageBuilder()}.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public final void testObservationImageBuilder() {
//MUT
obsImgBuilder = new ObservationImageBuilder();
//the tests
assertTrue("obsImgBuilder exists: ", obsImgBuilder!=null);
}
/**
* Test method for
* {@link controller.ObservationImageBuilder#ObservationImageBuilder(model.Observation)}.
*
* @throws Exception
*/
@Test(timeout = DEFAULT_TIMEOUT)
public final void testObservationImageBuilderObservation() throws Exception {
// MUT
//observation = new Observation(obsData);
obsImgBuilder = new ObservationImageBuilder(observation);
String imagePath = FilenameUtils.separatorsToSystem(tmpDir
.getCanonicalPath()
+ "/"+ToolBox.getCurrentMethodName()+".png");
obsImgBuilder.save(obsImgBuilder.obsImg, imagePath);
//the test
assertEquals("observation: ", obsData, obsImgBuilder.getObservation()
.getDataMap());
// cleanup
// File imageFile = new File(imagePath);
// FileUtils.forceDeleteOnExit(imageFile);
}
/**
* Test method for {@link controller.ObservationImageBuilder#build()}.
*
* @throws IOException
*/
@Test
// (timeout = DEFAULT_TIMEOUT)
public final void testBuild() throws Exception {
// obsImgBuilder = new ObservationImageBuilder();
// TODO grid,colorCode,ComponentImg,TextImg
String placeHolderImgPath=FilenameUtils.separatorsToSystem("lib/image/nopicture.png");
BufferedImage placeHolderImg=MyImage.readImage(placeHolderImgPath);
String imagePath = FilenameUtils.separatorsToSystem(tmpDir
.getCanonicalPath()
+ "/"+ToolBox.getCurrentMethodName()+".png");
placeHolderImg =new BufferedImage(10,10,2);
Color color=Color.WHITE;
placeHolderImg=MyImage.setBackgroundColor(placeHolderImg, color);
// MUT
obsImgBuilder = new ObservationImageBuilder();
obsImgBuilder.setObservation(observation);
obsImgBuilder.gridImg=new GridImage(600,600);
obsImgBuilder.celestialObjectTextImg=new TextDataImage(celObj.getDataMap(),"CELESTIALOBJECT", celObj.getKeyOrder());
obsImgBuilder.observationTextImg=new TextDataImage(observation.getDataMap(),"OBSERVATION", observation.getKeyOrder());
obsImgBuilder.colorCodeImg=new ColorCodeImage(50,500);
//create components
int numberOfComponents = random.nextInt(100) + 1;
MaserComponent[] components=new MaserComponent[numberOfComponents];
for (int i = 0; i < numberOfComponents; i++) {
HashMap<String, Object> row = MaserComponentTest.randomComponentRow(MaserComponentsImageTest.xRange,
MaserComponentsImageTest.yRange, MaserComponentsImageTest.vRange,
MaserComponentsImageTest.iRange, MaserComponentsImageTest.bRange);
row.put("observation_id".toUpperCase(), 0);
components[i]=new MaserComponent(row, false);
}
obsImgBuilder.maserCompsImg=new MaserComponentsImage(500, 500,components,
observation.isInterpolated());
obsImgBuilder.save(obsImgBuilder.maserCompsImg, imagePath.replace(".png", "_maserCompsImg.png"));
obsImgBuilder.setObsImg(obsImgBuilder.build());
ObservationImage obsImg = obsImgBuilder.getObsImg();//build();
obsImgBuilder.save(obsImgBuilder.obsImg, imagePath.replace(".png", "_with_maserCompsImg.png"));
// MyImage.png2jpg(imagePath.replace(".png", "_with_maserCompsImg.png"));
// the tests
assertEquals("width: ", obsImgBuilder.width, obsImgBuilder.obsImg.getWidth());
assertEquals("height: ", obsImgBuilder.height, obsImgBuilder.obsImg.getHeight());
assertEquals("bgColor GridImg: ", color.getRGB(),
obsImg.getRGB(obsImg.getGridImgX(), obsImg.getGridImgY()));
assertEquals("bgColor CelestialObjectTextImg: ", obsImgBuilder.celestialObjectTextImg.getRGB(0, 0),
obsImg.getRGB(obsImg.getCelestialObjectTextImgX(), obsImg.getCelestialObjectTextImgY()));
assertEquals("bgColor observationTextImg: ", obsImgBuilder.observationTextImg.getRGB(0,0),
obsImg.getRGB(obsImg.getObservationTextImgX(), obsImg.getObservationTextImgY()));
assertEquals("bgColor colorCodeImg: ", obsImgBuilder.colorCodeImg.getRGB(0,0),
obsImg.getRGB(obsImg.getColorCodeImgX(), obsImg.getColorCodeImgY()));
assertEquals("bgColor maserImg: ", obsImgBuilder.maserCompsImg.getRGB(0,0),
obsImg.getRGB(obsImg.getMaserImgX(), obsImg.getMaserImgY()));
assertEquals("Interpolated: ", obsImgBuilder.maserCompsImg.getRGB(0,0),
obsImg.getRGB(obsImg.getMaserImgX(), obsImg.getMaserImgY()));
//
//set every part-Image alone and test content
// obsImgBuilder = new ObservationImageBuilder(observation);
// BufferedImage returnImg = obsImgBuilder.getSubimage(
// obsImgBuilder.backgroundImgX, obsImgBuilder.backgroundImgY,
// obsImgBuilder.backgroundImg.getWidth(),
// obsImgBuilder.backgroundImg.getHeight());
//
// BufferedImage expectedImg = MyImage.translateBi2Type(
// obsImgBuilder.backgroundImg, returnImg.getType());
// obsImgBuilder.save(returnImg, imagePath + "1");
//
// assertTrue("backgroundImg: ", MyImage.compareImagesRawData(returnImg,
// expectedImg));
// cleanup
// File imageFile = new File(imagePath);
// FileUtils.forceDeleteOnExit(imageFile);
}
/**
* Test method for
* {@link controller.ObservationImageBuilder#save(java.io.File)}.
*
* @throws Exception
*/
@Test
// (timeout = DEFAULT_TIMEOUT, expected = IOException.class)
public final void testSave() throws Exception {
obsImgBuilder = new ObservationImageBuilder();
String imagePath = FilenameUtils.separatorsToSystem(tmpDir
.getCanonicalPath()
+ "/"+ToolBox.getCurrentMethodName()+".png");
File imageFile = new File(imagePath);
BufferedImage testImg=new BufferedImage(50,40,2);
testImg=MyImage.setBackgroundColor(testImg, Color.BLACK);
// MUT
obsImgBuilder.save(testImg, imagePath);
// the test
BufferedImage savedImg = MyImage.readImage(imagePath);
savedImg = MyImage.translateBi2Type(savedImg, 2);
assertTrue("Image-compare", MyImage.compareImagesRawData(testImg, savedImg));
// cleanup
FileUtils.forceDeleteOnExit(imageFile);
}
}
| |
/*
*
* 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.wso2.andes.transport.codec;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.UUID;
/**
* Byte Buffer Encoder.
* Encoder concrete implementor using a backing byte buffer for encoding data.
*
* @author Rafael H. Schloming
*/
public final class BBEncoder extends AbstractEncoder
{
private ByteBuffer out;
private int segment;
public BBEncoder(int capacity) {
out = ByteBuffer.allocate(capacity);
out.order(ByteOrder.BIG_ENDIAN);
segment = 0;
}
public void init()
{
out.clear();
segment = 0;
}
public ByteBuffer segment()
{
int pos = out.position();
out.position(segment);
ByteBuffer slice = out.slice();
slice.limit(pos - segment);
out.position(pos);
segment = pos;
return slice;
}
public ByteBuffer buffer()
{
int pos = out.position();
out.position(segment);
ByteBuffer slice = out.slice();
slice.limit(pos - segment);
out.position(pos);
return slice;
}
private void grow(int size)
{
ByteBuffer old = out;
int capacity = old.capacity();
out = ByteBuffer.allocate(Math.max(capacity + size, 2*capacity));
out.order(ByteOrder.BIG_ENDIAN);
old.flip();
out.put(old);
}
protected void doPut(byte b)
{
try
{
out.put(b);
}
catch (BufferOverflowException e)
{
grow(1);
out.put(b);
}
}
protected void doPut(ByteBuffer src)
{
try
{
out.put(src);
}
catch (BufferOverflowException e)
{
grow(src.remaining());
out.put(src);
}
}
protected void put(byte[] bytes)
{
try
{
out.put(bytes);
}
catch (BufferOverflowException e)
{
grow(bytes.length);
out.put(bytes);
}
}
public void writeUint8(short b)
{
assert b < 0x100;
try
{
out.put((byte) b);
}
catch (BufferOverflowException e)
{
grow(1);
out.put((byte) b);
}
}
public void writeUint16(int s)
{
assert s < 0x10000;
try
{
out.putShort((short) s);
}
catch (BufferOverflowException e)
{
grow(2);
out.putShort((short) s);
}
}
public void writeUint32(long i)
{
assert i < 0x100000000L;
try
{
out.putInt((int) i);
}
catch (BufferOverflowException e)
{
grow(4);
out.putInt((int) i);
}
}
public void writeUint64(long l)
{
try
{
out.putLong(l);
}
catch (BufferOverflowException e)
{
grow(8);
out.putLong(l);
}
}
public int beginSize8()
{
int pos = out.position();
try
{
out.put((byte) 0);
}
catch (BufferOverflowException e)
{
grow(1);
out.put((byte) 0);
}
return pos;
}
public void endSize8(int pos)
{
int cur = out.position();
out.put(pos, (byte) (cur - pos - 1));
}
public int beginSize16()
{
int pos = out.position();
try
{
out.putShort((short) 0);
}
catch (BufferOverflowException e)
{
grow(2);
out.putShort((short) 0);
}
return pos;
}
public void endSize16(int pos)
{
int cur = out.position();
out.putShort(pos, (short) (cur - pos - 2));
}
public int beginSize32()
{
int pos = out.position();
try
{
out.putInt(0);
}
catch (BufferOverflowException e)
{
grow(4);
out.putInt(0);
}
return pos;
}
public void endSize32(int pos)
{
int cur = out.position();
out.putInt(pos, (cur - pos - 4));
}
public void writeDouble(double aDouble)
{
try
{
out.putDouble(aDouble);
} catch(BufferOverflowException exception)
{
grow(8);
out.putDouble(aDouble);
}
}
public void writeInt16(short aShort)
{
try
{
out.putShort(aShort);
} catch(BufferOverflowException exception)
{
grow(2);
out.putShort(aShort);
}
}
public void writeInt32(int anInt)
{
try
{
out.putInt(anInt);
} catch(BufferOverflowException exception)
{
grow(4);
out.putInt(anInt);
}
}
public void writeInt64(long aLong)
{
try
{
out.putLong(aLong);
} catch(BufferOverflowException exception)
{
grow(8);
out.putLong(aLong);
}
}
public void writeInt8(byte aByte)
{
try
{
out.put(aByte);
} catch(BufferOverflowException exception)
{
grow(1);
out.put(aByte);
}
}
public void writeBin128(byte[] byteArray)
{
byteArray = (byteArray != null) ? byteArray : new byte [16];
assert byteArray.length == 16;
try
{
out.put(byteArray);
} catch(BufferOverflowException exception)
{
grow(16);
out.put(byteArray);
}
}
public void writeBin128(UUID id)
{
byte[] data = new byte[16];
long msb = id.getMostSignificantBits();
long lsb = id.getLeastSignificantBits();
assert data.length == 16;
for (int i=7; i>=0; i--)
{
data[i] = (byte)(msb & 0xff);
msb = msb >> 8;
}
for (int i=15; i>=8; i--)
{
data[i] = (byte)(lsb & 0xff);
lsb = (lsb >> 8);
}
writeBin128(data);
}
public void writeFloat(float aFloat)
{
try
{
out.putFloat(aFloat);
} catch(BufferOverflowException exception)
{
grow(4);
out.putFloat(aFloat);
}
}
public void writeMagicNumber()
{
out.put("AM2".getBytes());
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/longrunning/operations.proto
package com.google.longrunning;
/**
* <pre>
* The request message for [Operations.DeleteOperation][google.longrunning.Operations.DeleteOperation].
* </pre>
*
* Protobuf type {@code google.longrunning.DeleteOperationRequest}
*/
public final class DeleteOperationRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.longrunning.DeleteOperationRequest)
DeleteOperationRequestOrBuilder {
// Use DeleteOperationRequest.newBuilder() to construct.
private DeleteOperationRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteOperationRequest() {
name_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private DeleteOperationRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.longrunning.OperationsProto.internal_static_google_longrunning_DeleteOperationRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.longrunning.OperationsProto.internal_static_google_longrunning_DeleteOperationRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.longrunning.DeleteOperationRequest.class, com.google.longrunning.DeleteOperationRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
* <pre>
* The name of the operation resource to be deleted.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <pre>
* The name of the operation resource to be deleted.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.longrunning.DeleteOperationRequest)) {
return super.equals(obj);
}
com.google.longrunning.DeleteOperationRequest other = (com.google.longrunning.DeleteOperationRequest) obj;
boolean result = true;
result = result && getName()
.equals(other.getName());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.longrunning.DeleteOperationRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.longrunning.DeleteOperationRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.longrunning.DeleteOperationRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.longrunning.DeleteOperationRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.longrunning.DeleteOperationRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.longrunning.DeleteOperationRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.longrunning.DeleteOperationRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.longrunning.DeleteOperationRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.longrunning.DeleteOperationRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.longrunning.DeleteOperationRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.longrunning.DeleteOperationRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* The request message for [Operations.DeleteOperation][google.longrunning.Operations.DeleteOperation].
* </pre>
*
* Protobuf type {@code google.longrunning.DeleteOperationRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.longrunning.DeleteOperationRequest)
com.google.longrunning.DeleteOperationRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.longrunning.OperationsProto.internal_static_google_longrunning_DeleteOperationRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.longrunning.OperationsProto.internal_static_google_longrunning_DeleteOperationRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.longrunning.DeleteOperationRequest.class, com.google.longrunning.DeleteOperationRequest.Builder.class);
}
// Construct using com.google.longrunning.DeleteOperationRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
name_ = "";
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.longrunning.OperationsProto.internal_static_google_longrunning_DeleteOperationRequest_descriptor;
}
public com.google.longrunning.DeleteOperationRequest getDefaultInstanceForType() {
return com.google.longrunning.DeleteOperationRequest.getDefaultInstance();
}
public com.google.longrunning.DeleteOperationRequest build() {
com.google.longrunning.DeleteOperationRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.longrunning.DeleteOperationRequest buildPartial() {
com.google.longrunning.DeleteOperationRequest result = new com.google.longrunning.DeleteOperationRequest(this);
result.name_ = name_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.longrunning.DeleteOperationRequest) {
return mergeFrom((com.google.longrunning.DeleteOperationRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.longrunning.DeleteOperationRequest other) {
if (other == com.google.longrunning.DeleteOperationRequest.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.longrunning.DeleteOperationRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.longrunning.DeleteOperationRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
* <pre>
* The name of the operation resource to be deleted.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* The name of the operation resource to be deleted.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The name of the operation resource to be deleted.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
* <pre>
* The name of the operation resource to be deleted.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <pre>
* The name of the operation resource to be deleted.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:google.longrunning.DeleteOperationRequest)
}
// @@protoc_insertion_point(class_scope:google.longrunning.DeleteOperationRequest)
private static final com.google.longrunning.DeleteOperationRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.longrunning.DeleteOperationRequest();
}
public static com.google.longrunning.DeleteOperationRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteOperationRequest>
PARSER = new com.google.protobuf.AbstractParser<DeleteOperationRequest>() {
public DeleteOperationRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new DeleteOperationRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<DeleteOperationRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteOperationRequest> getParserForType() {
return PARSER;
}
public com.google.longrunning.DeleteOperationRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
package edu.memphis.books.web;
import java.io.*;
import java.util.concurrent.locks.ReentrantLock;
import java.lang.Integer;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**Servlet implementation class AddBooksServlet*/
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final ReentrantLock loctite=new ReentrantLock();
/*** @see HttpServlet#HttpServlet()*/
/**@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
loctite.lock();
try{
RequestDispatcher view;
PrintWriter out = response.getWriter();
ServletContext context = getServletContext();
String dBaseAddr = context.getInitParameter("dbUrl");
String dBName = context.getInitParameter("dbName");
String dBUname = context.getInitParameter("dbUser");
String dBPwd = context.getInitParameter("dbPasswd");
out.println("<!DOCTYPE html>\n<html>\n<body>");
int taskChoice=Integer.parseInt(request.getParameter("actionType"));
try //====================begin try==========================================
{
//======================database connection code==========================//
Connection con = DriverManager.getConnection(dBaseAddr+dBName,dBUname,dBPwd);//connection from the DriverManager
Statement s = con.createStatement();
//=====================end database connection code=======================//
if(taskChoice==1)//add a new book
{
addBook(request,response,s,con);//add a new book
}
else if(taskChoice==2)//add a new author
{
addAuthor(request,response,s,con);//add a new author
}
else if(taskChoice==3)//add a publisher
{
addPublisher(request,response,s,con);//add a new publisher
}
s.close();//close the statement
con.close();//close the connection
}catch(Exception ex)//end try/catch=======================================//
{
ex.printStackTrace();
}
view = request.getRequestDispatcher("add_success.jsp");
view.forward(request, response);
}finally{
loctite.unlock();
}
}//=========================================end of doGet()===========================//
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request,response);
}
protected void addBook(HttpServletRequest request, HttpServletResponse response, Statement s, Connection c)
{
String book = "", bookAuthor="";
String newBook = "INSERT INTO Titles (ISBN,Title,EditionNumber,YearPublished,"//update Titles
+ "Description,PublisherID)VALUES(";
String newAuthor = "INSERT INTO AuthorISBN (ISBN,AuthorID)VALUES(";//update AuthorISBN
try{//begin try/catch statement=============================================//
book += "'" + request.getParameter("ISBN") + "',";
book += "'" + request.getParameter("Title") + "',";
book += "'" + request.getParameter("EditionNumber") + "',";
int year=Integer.parseInt(request.getParameter("YearPublished"));
book += "" + year + ",";
book += "'" + request.getParameter("Description") + "',";
book += "" + request.getParameter("PublisherID") + "";
newBook += book + ")";//concatenate for insertion into Titles
s.executeUpdate(newBook); //insert book record
bookAuthor+="'"+ request.getParameter("ISBN") + "',";
int author=Integer.parseInt(request.getParameter("AuthorID"));
book += "" + author + "";
newAuthor += bookAuthor + ")";//concatenate for insertion into AuthorISBN
s.executeUpdate(newAuthor); //insert book record
s.close();//close the statement
c.close();//close the connection
}catch(SQLException sx)//end try/catch======================================//
{
sx.printStackTrace();
}
}//=================================end addBook()=========================//
protected void addAuthor(HttpServletRequest request, HttpServletResponse response, Statement s, Connection c)
{
try{ //begin try/catch statement=========================================//
String author="";
String newAuthor = "INSERT INTO Authors (AuthorID,FirstName,LastName,"
+ "YearBorn)VALUES(";//query
author += "'" + request.getParameter("AuthorID") + "',";
author += "'" + request.getParameter("FirstName") + "',";
author += "'" + request.getParameter("LastName") + "',";
int birthYear=Integer.parseInt(request.getParameter("yearBorn"));
author += "" + birthYear + "";
newAuthor += author + ")";//concatenate for insertion into d-base
s.executeUpdate(newAuthor); //insert author record
s.close();//close the statement
c.close();//close the connection
}catch(SQLException sx)//end try/catch===================================//
{
sx.printStackTrace();
}
}//=================================end addAuthor()=========================//
protected void addPublisher(HttpServletRequest request, HttpServletResponse response, Statement s, Connection c)
{
String publisher = "";
String newPub = "INSERT INTO Publishers (PublisherID,PublisherName)VALUES(";
try{//begin try/catch statement=============================================//
publisher += "'" + request.getParameter("PublisherID") + "',";
publisher += "'" + request.getParameter("PublisherName") + "'";
newPub += publisher + ")";//concatenate for insertion into d-base
s.executeUpdate(newPub); //insert publisher record
s.close();//close the statement
c.close();//close the connection
}catch(SQLException sx)//end try/catch======================================//
{
sx.printStackTrace();
}
}//=================================end addPublisher()============================//
}//=============================================end of class==============================================
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.core.summary;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.accumulo.core.metadata.schema.TabletMetadata.ColumnType.FILES;
import static org.apache.accumulo.core.metadata.schema.TabletMetadata.ColumnType.LAST;
import static org.apache.accumulo.core.metadata.schema.TabletMetadata.ColumnType.LOCATION;
import static org.apache.accumulo.core.metadata.schema.TabletMetadata.ColumnType.PREV_ROW;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.summary.SummarizerConfiguration;
import org.apache.accumulo.core.clientImpl.ClientContext;
import org.apache.accumulo.core.clientImpl.ServerClient;
import org.apache.accumulo.core.clientImpl.Translator;
import org.apache.accumulo.core.clientImpl.Translators;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.dataImpl.KeyExtent;
import org.apache.accumulo.core.dataImpl.thrift.TRowRange;
import org.apache.accumulo.core.dataImpl.thrift.TSummaries;
import org.apache.accumulo.core.dataImpl.thrift.TSummaryRequest;
import org.apache.accumulo.core.metadata.TabletFile;
import org.apache.accumulo.core.metadata.schema.TabletMetadata;
import org.apache.accumulo.core.metadata.schema.TabletsMetadata;
import org.apache.accumulo.core.rpc.ThriftUtil;
import org.apache.accumulo.core.spi.cache.BlockCache;
import org.apache.accumulo.core.spi.crypto.CryptoService;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService;
import org.apache.accumulo.core.tabletserver.thrift.TabletClientService.Client;
import org.apache.accumulo.core.trace.TraceUtil;
import org.apache.accumulo.core.trace.thrift.TInfo;
import org.apache.accumulo.core.util.ByteBufferUtil;
import org.apache.accumulo.core.util.CancelFlagFuture;
import org.apache.accumulo.core.util.CompletableFutureUtil;
import org.apache.accumulo.core.util.HostAndPort;
import org.apache.accumulo.core.util.TextUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.thrift.TApplicationException;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.cache.Cache;
import com.google.common.collect.Lists;
import com.google.common.hash.Hashing;
/**
* This class implements using multiple tservers to gather summaries.
*
* Below is a rough outline of the RPC process.
*
* <ol>
* <li>Clients pick a random tserver and make an RPC to remotely execute
* {@link #gather(ExecutorService)}.
* <li>{@link #gather(ExecutorService)} will call make RPC calls to multiple tservers to remotely
* execute {@link #processPartition(ExecutorService, int, int)}
* <li>{@link #processPartition(ExecutorService, int, int)} will make RPC calls to multiple tserver
* to remotely execute
* <li>{@link #processFiles(FileSystemResolver, Map, BlockCache, BlockCache, Cache, ExecutorService)}
* </ol>
*/
public class Gatherer {
private static final Logger log = LoggerFactory.getLogger(Gatherer.class);
private ClientContext ctx;
private TableId tableId;
private SummarizerFactory factory;
private Text startRow = null;
private Text endRow = null;
private Range clipRange;
private Predicate<SummarizerConfiguration> summarySelector;
private CryptoService cryptoService;
private TSummaryRequest request;
private String summarizerPattern;
private Set<SummarizerConfiguration> summaries;
public Gatherer(ClientContext context, TSummaryRequest request, AccumuloConfiguration tableConfig,
CryptoService cryptoService) {
this.ctx = context;
this.tableId = TableId.of(request.tableId);
this.startRow = ByteBufferUtil.toText(request.bounds.startRow);
this.endRow = ByteBufferUtil.toText(request.bounds.endRow);
this.clipRange = new Range(startRow, false, endRow, true);
this.summaries = request.getSummarizers().stream().map(SummarizerConfigurationUtil::fromThrift)
.collect(Collectors.toSet());
this.request = request;
this.cryptoService = cryptoService;
this.summarizerPattern = request.getSummarizerPattern();
if (summarizerPattern != null) {
Pattern pattern = Pattern.compile(summarizerPattern);
// The way conf is converted to string below is documented in the API, so consider this when
// making changes!
summarySelector = conf -> pattern
.matcher(conf.getClassName() + " " + new TreeMap<>(conf.getOptions())).matches();
if (!summaries.isEmpty()) {
summarySelector = summarySelector.or(conf -> summaries.contains(conf));
}
} else if (!summaries.isEmpty()) {
summarySelector = conf -> summaries.contains(conf);
} else {
summarySelector = conf -> true;
}
this.factory = new SummarizerFactory(tableConfig);
}
private TSummaryRequest getRequest() {
return request;
}
/**
* @param fileSelector
* only returns files that match this predicate
* @return A map of the form : {@code map<tserver location, map<path, list<range>>} . The ranges
* associated with a file represent the tablets that use the file.
*/
private Map<String,Map<TabletFile,List<TRowRange>>>
getFilesGroupedByLocation(Predicate<TabletFile> fileSelector) {
Iterable<TabletMetadata> tmi = TabletsMetadata.builder().forTable(tableId)
.overlapping(startRow, endRow).fetch(FILES, LOCATION, LAST, PREV_ROW).build(ctx);
// get a subset of files
Map<TabletFile,List<TabletMetadata>> files = new HashMap<>();
for (TabletMetadata tm : tmi) {
for (TabletFile file : tm.getFiles()) {
if (fileSelector.test(file)) {
// TODO push this filtering to server side and possibly use batch scanner
files.computeIfAbsent(file, s -> new ArrayList<>()).add(tm);
}
}
}
// group by location, then file
Map<String,Map<TabletFile,List<TRowRange>>> locations = new HashMap<>();
List<String> tservers = null;
for (Entry<TabletFile,List<TabletMetadata>> entry : files.entrySet()) {
String location = entry.getValue().stream().filter(tm -> tm.getLocation() != null) // filter
// tablets
// w/o a
// location
.map(tm -> tm.getLocation().getHostAndPort().toString()) // convert to host:port strings
.min(String::compareTo) // find minimum host:port
.orElse(entry.getValue().stream().filter(tm -> tm.getLast() != null) // if no locations,
// then look at last
// locations
.map(tm -> tm.getLast().getHostAndPort().toString()) // convert to host:port strings
.min(String::compareTo).orElse(null)); // find minimum last location or return null
if (location == null) {
if (tservers == null) {
tservers = ctx.instanceOperations().getTabletServers();
Collections.sort(tservers);
}
// When no location, the approach below will consistently choose the same tserver for the
// same file (as long as the set of tservers is stable).
int idx =
Math.abs(Hashing.murmur3_32().hashString(entry.getKey().getPathStr(), UTF_8).asInt())
% tservers.size();
location = tservers.get(idx);
}
// merge contiguous ranges
List<Range> merged = Range
.mergeOverlapping(Lists.transform(entry.getValue(), tm -> tm.getExtent().toDataRange()));
List<TRowRange> ranges =
merged.stream().map(r -> toClippedExtent(r).toThrift()).collect(Collectors.toList()); // clip
// ranges
// to
// queried
// range
locations.computeIfAbsent(location, s -> new HashMap<>()).put(entry.getKey(), ranges);
}
return locations;
}
private <K,V> Iterable<Map<K,V>> partition(Map<K,V> map, int max) {
if (map.size() < max) {
return Collections.singletonList(map);
}
return () -> {
Iterator<Entry<K,V>> esi = map.entrySet().iterator();
return new Iterator<>() {
@Override
public boolean hasNext() {
return esi.hasNext();
}
@Override
public Map<K,V> next() {
Map<K,V> workingMap = new HashMap<>(max);
while (esi.hasNext() && workingMap.size() < max) {
Entry<K,V> entry = esi.next();
workingMap.put(entry.getKey(), entry.getValue());
}
return workingMap;
}
};
};
}
private static class ProcessedFiles {
final SummaryCollection summaries;
final Set<TabletFile> failedFiles;
public ProcessedFiles() {
this.summaries = new SummaryCollection();
this.failedFiles = new HashSet<>();
}
public ProcessedFiles(SummaryCollection summaries, SummarizerFactory factory) {
this();
this.summaries.merge(summaries, factory);
}
static ProcessedFiles merge(ProcessedFiles pf1, ProcessedFiles pf2, SummarizerFactory factory) {
ProcessedFiles ret = new ProcessedFiles();
ret.failedFiles.addAll(pf1.failedFiles);
ret.failedFiles.addAll(pf2.failedFiles);
ret.summaries.merge(pf1.summaries, factory);
ret.summaries.merge(pf2.summaries, factory);
return ret;
}
}
private class FilesProcessor implements Supplier<ProcessedFiles> {
HostAndPort location;
Map<TabletFile,List<TRowRange>> allFiles;
private TInfo tinfo;
private AtomicBoolean cancelFlag;
public FilesProcessor(TInfo tinfo, HostAndPort location,
Map<TabletFile,List<TRowRange>> allFiles, AtomicBoolean cancelFlag) {
this.location = location;
this.allFiles = allFiles;
this.tinfo = tinfo;
this.cancelFlag = cancelFlag;
}
@Override
public ProcessedFiles get() {
ProcessedFiles pfiles = new ProcessedFiles();
Client client = null;
try {
client = ThriftUtil.getTServerClient(location, ctx);
// partition files into smaller chunks so that not too many are sent to a tserver at once
for (Map<TabletFile,List<TRowRange>> files : partition(allFiles, 500)) {
if (!pfiles.failedFiles.isEmpty()) {
// there was a previous failure on this tserver, so just fail the rest of the files
pfiles.failedFiles.addAll(files.keySet());
continue;
}
try {
TSummaries tSums = client.startGetSummariesFromFiles(tinfo, ctx.rpcCreds(),
getRequest(), Translator.translate(files, Translators.TFT));
while (!tSums.finished && !cancelFlag.get()) {
tSums = client.contiuneGetSummaries(tinfo, tSums.sessionId);
}
pfiles.summaries.merge(new SummaryCollection(tSums), factory);
} catch (TApplicationException tae) {
throw new RuntimeException(tae);
} catch (TTransportException e) {
pfiles.failedFiles.addAll(files.keySet());
continue;
} catch (TException e) {
throw new RuntimeException(e);
}
}
} catch (TTransportException e1) {
pfiles.failedFiles.addAll(allFiles.keySet());
} finally {
ThriftUtil.returnClient(client);
}
if (cancelFlag.get()) {
throw new RuntimeException("Operation canceled");
}
return pfiles;
}
}
private class PartitionFuture implements Future<SummaryCollection> {
private CompletableFuture<ProcessedFiles> future;
private int modulus;
private int remainder;
private ExecutorService execSrv;
private TInfo tinfo;
private AtomicBoolean cancelFlag = new AtomicBoolean(false);
PartitionFuture(TInfo tinfo, ExecutorService execSrv, int modulus, int remainder) {
this.tinfo = tinfo;
this.execSrv = execSrv;
this.modulus = modulus;
this.remainder = remainder;
}
private synchronized void initiateProcessing(ProcessedFiles previousWork) {
try {
Predicate<TabletFile> fileSelector =
file -> Math.abs(Hashing.murmur3_32().hashString(file.getPathStr(), UTF_8).asInt())
% modulus == remainder;
if (previousWork != null) {
fileSelector = fileSelector.and(previousWork.failedFiles::contains);
}
Map<String,Map<TabletFile,List<TRowRange>>> filesGBL;
filesGBL = getFilesGroupedByLocation(fileSelector);
List<CompletableFuture<ProcessedFiles>> futures = new ArrayList<>();
if (previousWork != null) {
futures.add(CompletableFuture
.completedFuture(new ProcessedFiles(previousWork.summaries, factory)));
}
for (Entry<String,Map<TabletFile,List<TRowRange>>> entry : filesGBL.entrySet()) {
HostAndPort location = HostAndPort.fromString(entry.getKey());
Map<TabletFile,List<TRowRange>> allFiles = entry.getValue();
futures.add(CompletableFuture
.supplyAsync(new FilesProcessor(tinfo, location, allFiles, cancelFlag), execSrv));
}
future = CompletableFutureUtil.merge(futures,
(pf1, pf2) -> ProcessedFiles.merge(pf1, pf2, factory), ProcessedFiles::new);
// when all processing is done, check for failed files... and if found starting processing
// again
future.thenRun(this::updateFuture);
} catch (Exception e) {
future = CompletableFuture.completedFuture(new ProcessedFiles());
// force future to have this exception
future.obtrudeException(e);
}
}
private ProcessedFiles _get() {
try {
return future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
private synchronized CompletableFuture<ProcessedFiles> updateFuture() {
if (future.isDone()) {
if (!future.isCancelled() && !future.isCompletedExceptionally()) {
ProcessedFiles pf = _get();
if (!pf.failedFiles.isEmpty()) {
initiateProcessing(pf);
}
}
}
return future;
}
synchronized void initiateProcessing() {
Preconditions.checkState(future == null);
initiateProcessing(null);
}
@Override
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
boolean canceled = future.cancel(mayInterruptIfRunning);
if (canceled) {
cancelFlag.set(true);
}
return canceled;
}
@Override
public synchronized boolean isCancelled() {
return future.isCancelled();
}
@Override
public synchronized boolean isDone() {
updateFuture();
if (future.isDone()) {
if (future.isCancelled() || future.isCompletedExceptionally()) {
return true;
}
ProcessedFiles pf = _get();
if (pf.failedFiles.isEmpty()) {
return true;
} else {
updateFuture();
}
}
return false;
}
@Override
public SummaryCollection get() throws InterruptedException, ExecutionException {
CompletableFuture<ProcessedFiles> futureRef = updateFuture();
ProcessedFiles processedFiles = futureRef.get();
while (!processedFiles.failedFiles.isEmpty()) {
futureRef = updateFuture();
processedFiles = futureRef.get();
}
return processedFiles.summaries;
}
@Override
public SummaryCollection get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
long nanosLeft = unit.toNanos(timeout);
long t1, t2;
CompletableFuture<ProcessedFiles> futureRef = updateFuture();
t1 = System.nanoTime();
ProcessedFiles processedFiles = futureRef.get(Long.max(1, nanosLeft), TimeUnit.NANOSECONDS);
t2 = System.nanoTime();
nanosLeft -= (t2 - t1);
while (!processedFiles.failedFiles.isEmpty()) {
futureRef = updateFuture();
t1 = System.nanoTime();
processedFiles = futureRef.get(Long.max(1, nanosLeft), TimeUnit.NANOSECONDS);
t2 = System.nanoTime();
nanosLeft -= (t2 - t1);
}
return processedFiles.summaries;
}
}
/**
* This methods reads a subset of file paths into memory and groups them by location. Then it
* request summaries for files from each location/tablet server.
*/
public Future<SummaryCollection> processPartition(ExecutorService execSrv, int modulus,
int remainder) {
PartitionFuture future =
new PartitionFuture(TraceUtil.traceInfo(), execSrv, modulus, remainder);
future.initiateProcessing();
return future;
}
public interface FileSystemResolver {
FileSystem get(Path file);
}
/**
* This method will read summaries from a set of files.
*/
public Future<SummaryCollection> processFiles(FileSystemResolver volMgr,
Map<String,List<TRowRange>> files, BlockCache summaryCache, BlockCache indexCache,
Cache<String,Long> fileLenCache, ExecutorService srp) {
List<CompletableFuture<SummaryCollection>> futures = new ArrayList<>();
for (Entry<String,List<TRowRange>> entry : files.entrySet()) {
futures.add(CompletableFuture.supplyAsync(() -> {
List<RowRange> rrl = Lists.transform(entry.getValue(), RowRange::new);
return getSummaries(volMgr, entry.getKey(), rrl, summaryCache, indexCache, fileLenCache);
}, srp));
}
return CompletableFutureUtil.merge(futures,
(sc1, sc2) -> SummaryCollection.merge(sc1, sc2, factory), SummaryCollection::new);
}
private int countFiles() {
// TODO use a batch scanner + iterator to parallelize counting files
return TabletsMetadata.builder().forTable(tableId).overlapping(startRow, endRow)
.fetch(FILES, PREV_ROW).build(ctx).stream().mapToInt(tm -> tm.getFiles().size()).sum();
}
private class GatherRequest implements Supplier<SummaryCollection> {
private int remainder;
private int modulus;
private TInfo tinfo;
private AtomicBoolean cancelFlag;
GatherRequest(TInfo tinfo, int remainder, int modulus, AtomicBoolean cancelFlag) {
this.remainder = remainder;
this.modulus = modulus;
this.tinfo = tinfo;
this.cancelFlag = cancelFlag;
}
@Override
public SummaryCollection get() {
TSummaryRequest req = getRequest();
TSummaries tSums;
try {
tSums = ServerClient.execute(ctx, new TabletClientService.Client.Factory(), client -> {
TSummaries tsr =
client.startGetSummariesForPartition(tinfo, ctx.rpcCreds(), req, modulus, remainder);
while (!tsr.finished && !cancelFlag.get()) {
tsr = client.contiuneGetSummaries(tinfo, tsr.sessionId);
}
return tsr;
});
} catch (AccumuloException | AccumuloSecurityException e) {
throw new RuntimeException(e);
}
if (cancelFlag.get()) {
throw new RuntimeException("Operation canceled");
}
return new SummaryCollection(tSums);
}
}
public Future<SummaryCollection> gather(ExecutorService es) {
int numFiles = countFiles();
log.debug("Gathering summaries from {} files", numFiles);
if (numFiles == 0) {
return CompletableFuture.completedFuture(new SummaryCollection());
}
// have each tablet server process ~100K files
int numRequest = Math.max(numFiles / 100_000, 1);
List<CompletableFuture<SummaryCollection>> futures = new ArrayList<>();
AtomicBoolean cancelFlag = new AtomicBoolean(false);
TInfo tinfo = TraceUtil.traceInfo();
for (int i = 0; i < numRequest; i++) {
futures.add(
CompletableFuture.supplyAsync(new GatherRequest(tinfo, i, numRequest, cancelFlag), es));
}
Future<SummaryCollection> future = CompletableFutureUtil.merge(futures,
(sc1, sc2) -> SummaryCollection.merge(sc1, sc2, factory), SummaryCollection::new);
return new CancelFlagFuture<>(future, cancelFlag);
}
private static Text removeTrailingZeroFromRow(Key k) {
if (k != null) {
Text t = new Text();
ByteSequence row = k.getRowData();
Preconditions.checkArgument(row.length() >= 1 && row.byteAt(row.length() - 1) == 0);
t.set(row.getBackingArray(), row.offset(), row.length() - 1);
return t;
} else {
return null;
}
}
private RowRange toClippedExtent(Range r) {
r = clipRange.clip(r);
Text startRow = removeTrailingZeroFromRow(r.getStartKey());
Text endRow = removeTrailingZeroFromRow(r.getEndKey());
return new RowRange(startRow, endRow);
}
public static class RowRange {
private Text startRow;
private Text endRow;
public RowRange(KeyExtent ke) {
this.startRow = ke.getPrevEndRow();
this.endRow = ke.getEndRow();
}
public RowRange(TRowRange trr) {
this.startRow = ByteBufferUtil.toText(trr.startRow);
this.endRow = ByteBufferUtil.toText(trr.endRow);
}
public RowRange(Text startRow, Text endRow) {
this.startRow = startRow;
this.endRow = endRow;
}
public Range toRange() {
return new Range(startRow, false, endRow, true);
}
public TRowRange toThrift() {
return new TRowRange(TextUtil.getByteBuffer(startRow), TextUtil.getByteBuffer(endRow));
}
public Text getStartRow() {
return startRow;
}
public Text getEndRow() {
return endRow;
}
@Override
public String toString() {
return startRow + " " + endRow;
}
}
private SummaryCollection getSummaries(FileSystemResolver volMgr, String file,
List<RowRange> ranges, BlockCache summaryCache, BlockCache indexCache,
Cache<String,Long> fileLenCache) {
Path path = new Path(file);
Configuration conf = ctx.getHadoopConf();
return SummaryReader.load(volMgr.get(path), conf, factory, path, summarySelector, summaryCache,
indexCache, fileLenCache, cryptoService).getSummaries(ranges);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.