code
stringlengths 10
749k
| repo_name
stringlengths 5
108
| path
stringlengths 7
333
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 10
749k
|
---|---|---|---|---|---|
package com.github.hadoop.maven.plugin;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
/**
* Writes jars.
*
*
*/
public class JarWriter {
/**
* Given a root directory, this writes the contents of the same as a jar file.
* The path to files inside the jar are relative paths, relative to the root
* directory specified.
*
* @param jarRootDir
* Root Directory that serves as an input to writing the jars.
* @param os
* OutputStream to which the jar is to be packed
* @throws FileNotFoundException
* @throws IOException
*/
public void packToJar(File jarRootDir, OutputStream os)
throws FileNotFoundException, IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
JarOutputStream target = new JarOutputStream(os, manifest);
for (File nestedFile : jarRootDir.listFiles())
add(jarRootDir.getPath().replace("\\", "/"), nestedFile, target);
target.close();
}
private void add(String prefix, File source, JarOutputStream target)
throws IOException {
BufferedInputStream in = null;
try {
if (source.isDirectory()) {
String name = source.getPath().replace("\\", "/");
if (!name.isEmpty()) {
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name.substring(prefix.length() + 1));
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile : source.listFiles())
add(prefix, nestedFile, target);
return;
}
String jarentryName = source.getPath().replace("\\", "/").substring(
prefix.length() + 1);
JarEntry entry = new JarEntry(jarentryName);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true) {
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
} finally {
if (in != null)
in.close();
}
}
}
| akkumar/maven-hadoop | src/main/java/com/github/hadoop/maven/plugin/JarWriter.java | Java | apache-2.0 | 2,529 |
/*
* 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.transfer.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum HomeDirectoryType {
PATH("PATH"),
LOGICAL("LOGICAL");
private String value;
private HomeDirectoryType(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return HomeDirectoryType corresponding to the value
*
* @throws IllegalArgumentException
* If the specified value does not map to one of the known values in this enum.
*/
public static HomeDirectoryType fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (HomeDirectoryType enumEntry : HomeDirectoryType.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| aws/aws-sdk-java | aws-java-sdk-transfer/src/main/java/com/amazonaws/services/transfer/model/HomeDirectoryType.java | Java | apache-2.0 | 1,790 |
package com.ilad.teamwork;
import org.openqa.selenium.WebElement;
import io.appium.java_client.android.AndroidDriver;
public class TabsMenu extends AbstractTeamWork {
public TabsMenu(AndroidDriver<WebElement> driver) {
super(driver);
}
public AllProjectsPage goToProjects() {
driver.findElementByXPath("//android.widget.TextView[@text='Projects']").click();
return new AllProjectsPage(driver);
}
}
| Solomon1732/infinity-labs-repository | TeamWorkAndroid/src/main/java/com/ilad/teamwork/TabsMenu.java | Java | apache-2.0 | 414 |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES 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.api.ads.admanager.jaxws.v202111;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Gets an {@link ActivityGroupPage} of {@link ActivityGroup} objects that satisfy the given
* {@link Statement#query}. The following fields are supported for filtering:
*
* <table>
* <tr>
* <th scope="col">PQL Property</th> <th scope="col">Object Property</th>
* </tr>
* <tr>
* <td>{@code id}</td>
* <td>{@link ActivityGroup#id}</td>
* </tr>
* <tr>
* <td>{@code name}</td>
* <td>{@link ActivityGroup#name}</td>
* </tr>
* <tr>
* <td>{@code impressionsLookback}</td>
* <td>{@link ActivityGroup#impressionsLookback}</td>
* </tr>
* <tr>
* <td>{@code clicksLookback}</td>
* <td>{@link ActivityGroup#clicksLookback}</td>
* </tr>
* <tr>
* <td>{@code status}</td>
* <td>{@link ActivityGroup#status}</td>
* </tr>
* </table>
*
* @param filterStatement a statement used to filter a set of activity groups
* @return the activity groups that match the given filter
*
*
* <p>Java class for getActivityGroupsByStatement element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getActivityGroupsByStatement">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="filterStatement" type="{https://www.google.com/apis/ads/publisher/v202111}Statement" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"filterStatement"
})
@XmlRootElement(name = "getActivityGroupsByStatement")
public class ActivityGroupServiceInterfacegetActivityGroupsByStatement {
protected Statement filterStatement;
/**
* Gets the value of the filterStatement property.
*
* @return
* possible object is
* {@link Statement }
*
*/
public Statement getFilterStatement() {
return filterStatement;
}
/**
* Sets the value of the filterStatement property.
*
* @param value
* allowed object is
* {@link Statement }
*
*/
public void setFilterStatement(Statement value) {
this.filterStatement = value;
}
}
| googleads/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202111/ActivityGroupServiceInterfacegetActivityGroupsByStatement.java | Java | apache-2.0 | 3,560 |
package org.ovirt.engine.ui.uicommonweb.models.vms;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskImageBase;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_pool;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.IEventListener;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.compat.ObservableCollection;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.core.compat.StringFormat;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation;
@SuppressWarnings("unused")
public class ImportVmModel extends ListWithDetailsModel {
boolean sameSelectedDestinationStorage = false;
ArrayList<storage_domains> uniqueDestStorages;
ArrayList<storage_domains> allDestStorages;
storage_domains selectedDestinationStorage;
HashMap<Guid, ArrayList<Guid>> templateGuidUniqueStorageDomainDic;
HashMap<Guid, ArrayList<Guid>> templateGuidAllStorageDomainDic;
HashMap<Guid, ArrayList<DiskImage>> templateGuidDiskImagesDic;
VmImportDiskListModel importDiskListModel;
ArrayList<storage_domains> allStorageDomains;
int uniqueDomains;
Guid templateGuid;
private storage_domain_static privateSourceStorage;
public storage_domain_static getSourceStorage() {
return privateSourceStorage;
}
public void setSourceStorage(storage_domain_static value) {
privateSourceStorage = value;
}
private storage_pool privateStoragePool;
public storage_pool getStoragePool() {
return privateStoragePool;
}
public void setStoragePool(storage_pool value) {
privateStoragePool = value;
}
private ListModel privateDestinationStorage;
public ListModel getDestinationStorage() {
return privateDestinationStorage;
}
private void setDestinationStorage(ListModel value) {
privateDestinationStorage = value;
}
private ListModel privateAllDestinationStorage;
public ListModel getAllDestinationStorage() {
return privateAllDestinationStorage;
}
private void setAllDestinationStorage(ListModel value) {
privateAllDestinationStorage = value;
}
private ListModel privateCluster;
public ListModel getCluster() {
return privateCluster;
}
private void setCluster(ListModel value) {
privateCluster = value;
}
private ListModel privateSystemDiskFormat;
public ListModel getSystemDiskFormat() {
return privateSystemDiskFormat;
}
private void setSystemDiskFormat(ListModel value) {
privateSystemDiskFormat = value;
}
private ListModel privateDataDiskFormat;
public ListModel getDataDiskFormat() {
return privateDataDiskFormat;
}
private void setDataDiskFormat(ListModel value) {
privateDataDiskFormat = value;
}
private EntityModel collapseSnapshots;
public EntityModel getCollapseSnapshots() {
return collapseSnapshots;
}
public void setCollapseSnapshots(EntityModel value) {
this.collapseSnapshots = value;
}
private boolean isMissingStorages;
public boolean getIsMissingStorages() {
return isMissingStorages;
}
public void setIsMissingStorages(boolean value) {
if (isMissingStorages != value) {
isMissingStorages = value;
OnPropertyChanged(new PropertyChangedEventArgs("IsMissingStorages"));
}
}
private String nameAndDescription;
private AsyncQuery onCollapseSnapshotsChangedFinish;
public String getNameAndDescription() {
return nameAndDescription;
}
public void setNameAndDescription(String value) {
if (!StringHelper.stringsEqual(nameAndDescription, value)) {
nameAndDescription = value;
OnPropertyChanged(new PropertyChangedEventArgs("NameAndDescription"));
}
}
private java.util.List<VM> problematicItems;
public java.util.List<VM> getProblematicItems() {
return problematicItems;
}
public void setProblematicItems(java.util.List<VM> value) {
if (problematicItems != value) {
problematicItems = value;
OnPropertyChanged(new PropertyChangedEventArgs("ProblematicItems"));
}
}
private EntityModel privateIsSingleDestStorage;
public EntityModel getIsSingleDestStorage() {
return privateIsSingleDestStorage;
}
public void setIsSingleDestStorage(EntityModel value) {
privateIsSingleDestStorage = value;
}
private ListModel privateStorageDoamins;
public ListModel getStorageDoamins() {
return privateStorageDoamins;
}
private void setStorageDoamins(ListModel value) {
privateStorageDoamins = value;
}
private HashMap<Guid, HashMap<Guid, Guid>> privateDiskStorageMap;
public HashMap<Guid, HashMap<Guid, Guid>> getDiskStorageMap()
{
return privateDiskStorageMap;
}
public void setDiskStorageMap(HashMap<Guid, HashMap<Guid, Guid>> value)
{
privateDiskStorageMap = value;
}
@Override
public void setSelectedItem(Object value) {
super.setSelectedItem(value);
OnEntityChanged();
}
public ImportVmModel() {
setProblematicItems(new ArrayList<VM>());
setCollapseSnapshots(new EntityModel());
getCollapseSnapshots().setEntity(false);
getCollapseSnapshots().getPropertyChangedEvent().addListener(
new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender,
EventArgs args) {
OnCollapseSnapshotsChanged();
}
});
setDestinationStorage(new ListModel());
getDestinationStorage().getSelectedItemChangedEvent().addListener(
new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender,
EventArgs args) {
DestinationStorage_SelectedItemChanged();
}
});
setCluster(new ListModel());
setSystemDiskFormat(new ListModel());
setDataDiskFormat(new ListModel());
setDiskStorageMap(new HashMap<Guid, HashMap<Guid, Guid>>());
setIsSingleDestStorage(new EntityModel());
getIsSingleDestStorage().setEntity(true);
setAllDestinationStorage(new ListModel());
}
public void OnCollapseSnapshotsChanged(AsyncQuery _asyncQuery) {
this.onCollapseSnapshotsChangedFinish = _asyncQuery;
OnCollapseSnapshotsChanged();
}
public void initStorageDomains() {
templateGuidUniqueStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>();
templateGuidAllStorageDomainDic = new java.util.HashMap<Guid, ArrayList<Guid>>();
templateGuidDiskImagesDic = new java.util.HashMap<Guid, ArrayList<DiskImage>>();
uniqueDomains = 0;
for (Object item : getItems()) {
VM vm = (VM) item;
templateGuid = vm.getvmt_guid();
if (templateGuid.equals(NGuid.Empty)) {
uniqueDomains++;
templateGuidUniqueStorageDomainDic.put(templateGuid, null);
templateGuidAllStorageDomainDic.put(templateGuid, null);
} else {
AsyncDataProvider.GetTemplateDiskList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
ImportVmModel importVmModel = (ImportVmModel) target;
ArrayList<DiskImage> disks = (ArrayList<DiskImage>) returnValue;
ArrayList<ArrayList<Guid>> allSourceStorages = new ArrayList<ArrayList<Guid>>();
for (DiskImage disk : disks) {
allSourceStorages.add(disk.getstorage_ids());
}
ArrayList<Guid> intersectStorageDomains = Linq.Intersection(allSourceStorages);
ArrayList<Guid> unionStorageDomains = Linq.Union(allSourceStorages);
uniqueDomains++;
templateGuidUniqueStorageDomainDic.put(importVmModel.templateGuid,
intersectStorageDomains);
templateGuidAllStorageDomainDic.put(importVmModel.templateGuid,
unionStorageDomains);
templateGuidDiskImagesDic.put(importVmModel.templateGuid, disks);
importVmModel.postInitStorageDomains();
}
}),
templateGuid);
}
}
postInitStorageDomains();
}
protected void postInitStorageDomains() {
if (templateGuidUniqueStorageDomainDic.size() != uniqueDomains) {
return;
}
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.Model = this;
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void OnSuccess(Object model, Object returnValue) {
allStorageDomains = (ArrayList<storage_domains>) returnValue;
OnCollapseSnapshotsChanged();
initDiskStorageMap();
}
};
AsyncDataProvider.GetDataDomainsListByDomain(_asyncQuery, this.getSourceStorage().getId());
}
private void initDiskStorageMap() {
for (Object item : getItems()) {
VM vm = (VM) item;
for (DiskImage disk : vm.getDiskMap().values()) {
if (NGuid.Empty.equals(vm.getvmt_guid())) {
Guid storageId = !allDestStorages.isEmpty() ?
allDestStorages.get(0).getId() : new Guid();
addToDiskStorageMap(vm.getId(), disk, storageId);
}
else {
ArrayList<Guid> storageIds =
templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid());
Guid storageId = storageIds != null ?
templateGuidUniqueStorageDomainDic.get(vm.getvmt_guid()).get(0) : new Guid();
addToDiskStorageMap(vm.getId(), disk, storageId);
}
}
}
}
public void OnCollapseSnapshotsChanged() {
if (this.getItems() == null || allStorageDomains == null) {
return;
}
selectedDestinationStorage = null;
sameSelectedDestinationStorage = false;
uniqueDestStorages = new ArrayList<storage_domains>();
allDestStorages = new ArrayList<storage_domains>();
setIsMissingStorages(false);
if (getDestinationStorage().getSelectedItem() != null) {
selectedDestinationStorage = (storage_domains) getDestinationStorage().getSelectedItem();
}
for (storage_domains domain : allStorageDomains) {
boolean addStorage = false;
if (Linq.IsDataActiveStorageDomain(domain)) {
allDestStorages.add(domain);
if (((Boolean) getCollapseSnapshots().getEntity()).equals(true)) {
addStorage = true;
}
else {
for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidUniqueStorageDomainDic.entrySet())
{
if (NGuid.Empty.equals(keyValuePair.getKey())) {
addStorage = true;
} else {
addStorage = false;
for (Guid storageDomainId : keyValuePair.getValue()) {
if (storageDomainId.equals(domain.getId()))
{
addStorage = true;
break;
}
}
}
if (addStorage == false) {
break;
}
}
}
}
else {
for (Map.Entry<Guid, ArrayList<Guid>> keyValuePair : templateGuidAllStorageDomainDic.entrySet())
{
if (!NGuid.Empty.equals(keyValuePair.getKey())) {
for (Guid storageDomainId : keyValuePair.getValue()) {
if (storageDomainId.equals(domain.getId()))
{
setIsMissingStorages(true);
break;
}
}
}
}
}
if (addStorage) {
uniqueDestStorages.add(domain);
if (sameSelectedDestinationStorage == false && domain.equals(selectedDestinationStorage)) {
sameSelectedDestinationStorage = true;
selectedDestinationStorage = domain;
}
}
}
getAllDestinationStorage().setItems(allDestStorages);
getDestinationStorage().setItems(uniqueDestStorages);
if (sameSelectedDestinationStorage) {
getDestinationStorage().setSelectedItem(selectedDestinationStorage);
} else {
getDestinationStorage().setSelectedItem(Linq.FirstOrDefault(uniqueDestStorages));
}
if (getDetailModels() != null
&& getActiveDetailModel() instanceof VmImportDiskListModel) {
VmImportDiskListModel detailModel = (VmImportDiskListModel) getActiveDetailModel();
detailModel
.setCollapseSnapshots((Boolean) getCollapseSnapshots()
.getEntity());
}
if (onCollapseSnapshotsChangedFinish != null) {
onCollapseSnapshotsChangedFinish.asyncCallback.OnSuccess(
onCollapseSnapshotsChangedFinish.getModel(), null);
onCollapseSnapshotsChangedFinish = null;
}
}
@Override
protected void ActiveDetailModelChanged() {
super.ActiveDetailModelChanged();
OnCollapseSnapshotsChanged();
}
@Override
protected void InitDetailModels() {
super.InitDetailModels();
importDiskListModel = new VmImportDiskListModel();
ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>();
list.add(new VmGeneralModel());
list.add(new VmImportInterfaceListModel());
list.add(importDiskListModel);
list.add(new VmAppListModel());
setDetailModels(list);
}
public boolean Validate() {
getDestinationStorage().ValidateSelectedItem(
new IValidation[] { new NotEmptyValidation() });
getCluster().ValidateSelectedItem(
new IValidation[] { new NotEmptyValidation() });
return getDestinationStorage().getIsValid()
&& getCluster().getIsValid();
}
@Override
protected void OnSelectedItemChanged() {
super.OnSelectedItemChanged();
if (getSelectedItem() != null) {
VM vm = (VM) getSelectedItem();
setNameAndDescription(StringFormat.format("%1$s%2$s",
vm.getvm_name(),
!StringHelper.isNullOrEmpty(vm.getvm_description()) ? " ["
+ vm.getvm_description() + "]" : ""));
} else {
setNameAndDescription("");
}
}
public void setItems(Iterable value)
{
super.setItems(value);
for (Object vm : getItems()) {
getDiskStorageMap().put(((VM) vm).getId(), new HashMap<Guid, Guid>());
}
initStorageDomains();
}
@Override
protected String getListName() {
return "ImportVmModel";
}
public void setSelectedVMsCount(int size) {
importDiskListModel.setSelectedVMsCount(((List) getItems()).size());
}
storage_domains currStorageDomain = null;
private void DestinationStorage_SelectedItemChanged() {
storage_domains selectedStorageDomain = (storage_domains) getDestinationStorage().getSelectedItem();
List destinationStorageDomains = ((List) getDestinationStorage().getItems());
if (selectedStorageDomain == null && !destinationStorageDomains.isEmpty()) {
selectedStorageDomain = (storage_domains) destinationStorageDomains.get(0);
}
if (currStorageDomain == null || selectedStorageDomain == null
|| !currStorageDomain.getQueryableId().equals(selectedStorageDomain.getQueryableId())) {
currStorageDomain = selectedStorageDomain;
UpdateImportWarnings();
}
}
public void DestinationStorage_SelectedItemChanged(DiskImage disk, String storageDomainName) {
VM item = (VM) getSelectedItem();
addToDiskStorageMap(item.getId(), disk, getStorageDomainByName(storageDomainName).getId());
}
public void addToDiskStorageMap(Guid vmId, DiskImage disk, Guid storageId) {
HashMap<Guid, Guid> vmDiskStorageMap = getDiskStorageMap().get(vmId);
vmDiskStorageMap.put(disk.getId(), storageId);
}
private storage_domains getStorageDomainByName(String storageDomainName) {
storage_domains storage = null;
for (Object storageDomain : getDestinationStorage().getItems()) {
storage = (storage_domains) storageDomain;
if (storageDomainName.equals(storage.getstorage_name())) {
break;
}
}
return storage;
}
@Override
protected void ItemsChanged() {
super.ItemsChanged();
UpdateImportWarnings();
}
public VmImportDiskListModel getImportDiskListModel() {
return importDiskListModel;
}
private void UpdateImportWarnings() {
// Clear problematic state.
getProblematicItems().clear();
if (getItems() == null) {
return;
}
storage_domains destinationStorage = (storage_domains) getDestinationStorage()
.getSelectedItem();
for (Object item : getItems()) {
VM vm = (VM) item;
if (vm.getDiskMap() != null) {
for (java.util.Map.Entry<String, DiskImage> pair : vm
.getDiskMap().entrySet()) {
DiskImage disk = pair.getValue();
if (disk.getvolume_type() == VolumeType.Sparse
&& disk.getvolume_format() == VolumeFormat.RAW
&& destinationStorage != null
&& (destinationStorage.getstorage_type() == StorageType.ISCSI || destinationStorage
.getstorage_type() == StorageType.FCP)) {
getProblematicItems().add(vm);
}
}
}
}
// Decide what to do with the CollapseSnapshots option.
if (problematicItems.size() > 0) {
if (problematicItems.size() == Linq.Count(getItems())) {
// All items are problematic.
getCollapseSnapshots().setIsChangable(false);
getCollapseSnapshots().setEntity(true);
getCollapseSnapshots()
.setMessage(
"Note that all snapshots will be collapsed due to different storage types");
} else {
// Some items are problematic.
getCollapseSnapshots()
.setMessage(
"Use a separate import operation for the marked VMs or\nApply \"Collapse Snapshots\" for all VMs");
}
} else {
// No problematic items.
getCollapseSnapshots().setIsChangable(true);
getCollapseSnapshots().setMessage(null);
}
}
public void VolumeType_SelectedItemChanged(DiskImage disk,
VolumeType tempVolumeType) {
for (Object item : getItems()) {
VM vm = (VM) item;
java.util.HashMap<String, DiskImageBase> diskDictionary = new java.util.HashMap<String, DiskImageBase>();
for (java.util.Map.Entry<String, DiskImage> a : vm.getDiskMap()
.entrySet()) {
if (a.getValue().getQueryableId().equals(disk.getQueryableId())) {
a.getValue().setvolume_type(tempVolumeType);
break;
}
}
}
}
public ArrayList<String> getAvailableStorageDomainsByDiskId(Guid diskId) {
ArrayList<String> storageDomains = null;
ArrayList<Guid> storageDomainsIds = getImportDiskListModel().getAvailableStorageDomainsByDiskId(diskId);
if (storageDomainsIds != null) {
storageDomains = new ArrayList<String>();
for (Guid storageId : storageDomainsIds) {
if (Linq.IsActiveStorageDomain(getStorageById(storageId))) {
storageDomains.add(getStorageNameById(storageId));
}
}
}
if (storageDomains != null) {
Collections.sort(storageDomains);
}
return storageDomains;
}
public String getStorageNameById(NGuid storageId) {
String storageName = "";
for (Object storageDomain : getAllDestinationStorage().getItems()) {
storage_domains storage = (storage_domains) storageDomain;
if (storage.getId().equals(storageId)) {
storageName = storage.getstorage_name();
}
}
return storageName;
}
public storage_domains getStorageById(Guid storageId) {
for (storage_domains storage : allDestStorages) {
if (storage.getId().equals(storageId)) {
return storage;
}
}
return null;
}
}
| Dhandapani/gluster-ovirt | frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/vms/ImportVmModel.java | Java | apache-2.0 | 23,592 |
package com.pengrad.telegrambot.request;
import com.pengrad.telegrambot.response.BaseResponse;
/**
* Mirco Ianese
* 07 December 2021
*/
public class UnbanChatSenderChat extends BaseRequest<UnbanChatSenderChat, BaseResponse> {
public UnbanChatSenderChat(Object chatId, long sender_chat_id) {
super(BaseResponse.class);
add("chat_id", chatId).add("sender_chat_id", sender_chat_id);
}
}
| pengrad/java-telegram-bot-api | library/src/main/java/com/pengrad/telegrambot/request/UnbanChatSenderChat.java | Java | apache-2.0 | 415 |
/*
* Copyright (c) 2017-2018. 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 li.allan.easycache.config;
import li.allan.easycache.CacheKeyGenerator;
import li.allan.easycache.LocalCacheConfig;
/**
* @author lialun
*/
public class ConfigProperties {
private LocalCacheConfig localCacheConfig;
private CacheKeyGenerator cacheKeyGenerator;
public LocalCacheConfig getLocalCacheConfig() {
return localCacheConfig;
}
public void setLocalCacheConfig(LocalCacheConfig localCacheConfig) {
this.localCacheConfig = localCacheConfig;
}
public CacheKeyGenerator getCacheKeyGenerator() {
return cacheKeyGenerator;
}
public void setCacheKeyGenerator(CacheKeyGenerator cacheKeyGenerator) {
this.cacheKeyGenerator = cacheKeyGenerator;
}
}
| lialun/EasyCache | easycache/src/main/java/li/allan/easycache/config/ConfigProperties.java | Java | apache-2.0 | 1,360 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.appsync.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appsync-2017-07-25/GetFunction" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetFunctionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The <code>Function</code> object.
* </p>
*/
private FunctionConfiguration functionConfiguration;
/**
* <p>
* The <code>Function</code> object.
* </p>
*
* @param functionConfiguration
* The <code>Function</code> object.
*/
public void setFunctionConfiguration(FunctionConfiguration functionConfiguration) {
this.functionConfiguration = functionConfiguration;
}
/**
* <p>
* The <code>Function</code> object.
* </p>
*
* @return The <code>Function</code> object.
*/
public FunctionConfiguration getFunctionConfiguration() {
return this.functionConfiguration;
}
/**
* <p>
* The <code>Function</code> object.
* </p>
*
* @param functionConfiguration
* The <code>Function</code> object.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetFunctionResult withFunctionConfiguration(FunctionConfiguration functionConfiguration) {
setFunctionConfiguration(functionConfiguration);
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 (getFunctionConfiguration() != null)
sb.append("FunctionConfiguration: ").append(getFunctionConfiguration());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetFunctionResult == false)
return false;
GetFunctionResult other = (GetFunctionResult) obj;
if (other.getFunctionConfiguration() == null ^ this.getFunctionConfiguration() == null)
return false;
if (other.getFunctionConfiguration() != null && other.getFunctionConfiguration().equals(this.getFunctionConfiguration()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getFunctionConfiguration() == null) ? 0 : getFunctionConfiguration().hashCode());
return hashCode;
}
@Override
public GetFunctionResult clone() {
try {
return (GetFunctionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| jentfoo/aws-sdk-java | aws-java-sdk-appsync/src/main/java/com/amazonaws/services/appsync/model/GetFunctionResult.java | Java | apache-2.0 | 4,022 |
/*
* Copyright 2008-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 groovy.lang;
import org.codehaus.groovy.transform.GroovyASTTransformationClass;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Field annotation to simplify lazy initialization.
* <p>
* Example usage without any special modifiers just defers initialization until the first call but is not thread-safe:
* <pre>
* {@code @Lazy} T x
* </pre>
* becomes
* <pre>
* private T $x
*
* T getX() {
* if ($x != null)
* return $x
* else {
* $x = new T()
* return $x
* }
* }
* </pre>
*
* If the field is declared volatile then initialization will be synchronized using
* the <a href="http://en.wikipedia.org/wiki/Double-checked_locking">double-checked locking</a> pattern as shown here:
*
* <pre>
* {@code @Lazy} volatile T x
* </pre>
* becomes
* <pre>
* private volatile T $x
*
* T getX() {
* T $x_local = $x
* if ($x_local != null)
* return $x_local
* else {
* synchronized(this) {
* if ($x == null) {
* $x = new T()
* }
* return $x
* }
* }
* }
* </pre>
*
* By default a field will be initialized by calling its default constructor.
*
* If the field has an initial value expression then this expression will be used instead of calling the default constructor.
* In particular, it is possible to use closure <code>{ ... } ()</code> syntax as follows:
*
* <pre>
* {@code @Lazy} T x = { [1, 2, 3] } ()
* </pre>
* becomes
* <pre>
* private T $x
*
* T getX() {
* T $x_local = $x
* if ($x_local != null)
* return $x_local
* else {
* synchronized(this) {
* if ($x == null) {
* $x = { [1, 2, 3] } ()
* }
* return $x
* }
* }
* }
* </pre>
* <p>
* <code>@Lazy(soft=true)</code> will use a soft reference instead of the field and use the above rules each time re-initialization is required.
* <p>
* If the <code>soft</code> flag for the annotation is not set but the field is static, then
* the <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom">initialization on demand holder idiom</a> is
* used as follows:
* <pre>
* {@code @Lazy} static FieldType field
* {@code @Lazy} static Date date1
* {@code @Lazy} static Date date2 = { new Date().updated(year: 2000) }()
* {@code @Lazy} static Date date3 = new GregorianCalendar(2009, Calendar.JANUARY, 1).time
* </pre>
* becomes these methods and inners classes within the class containing the above definitions:
* <pre>
* private static class FieldTypeHolder_field {
* private static final FieldType INSTANCE = new FieldType()
* }
*
* private static class DateHolder_date1 {
* private static final Date INSTANCE = new Date()
* }
*
* private static class DateHolder_date2 {
* private static final Date INSTANCE = { new Date().updated(year: 2000) }()
* }
*
* private static class DateHolder_date3 {
* private static final Date INSTANCE = new GregorianCalendar(2009, Calendar.JANUARY, 1).time
* }
*
* static FieldType getField() {
* return FieldTypeHolder_field.INSTANCE
* }
*
* static Date getDate1() {
* return DateHolder_date1.INSTANCE
* }
*
* static Date getDate2() {
* return DateHolder_date2.INSTANCE
* }
*
* static Date getDate3() {
* return DateHolder_date3.INSTANCE
* }
* </pre>
*
* @author Alex Tkachman
* @author Paul King
*/
@java.lang.annotation.Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.FIELD})
@GroovyASTTransformationClass("org.codehaus.groovy.transform.LazyASTTransformation")
public @interface Lazy {
/**
* @return if field should be soft referenced instead of hard referenced
*/
boolean soft () default false;
}
| Selventa/model-builder | tools/groovy/src/src/main/groovy/lang/Lazy.java | Java | apache-2.0 | 4,644 |
/*
* Copyright 2013-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.event.listener;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import com.facebook.buck.artifact_cache.ArtifactCacheConnectEvent;
import com.facebook.buck.artifact_cache.CacheResult;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent;
import com.facebook.buck.event.CommandEvent;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEventFetchData;
import com.facebook.buck.event.ArtifactCompressionEvent;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusFactory;
import com.facebook.buck.event.ChromeTraceEvent;
import com.facebook.buck.event.CompilerPluginDurationEvent;
import com.facebook.buck.event.PerfEventId;
import com.facebook.buck.event.SimplePerfEvent;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.jvm.java.AnnotationProcessingEvent;
import com.facebook.buck.jvm.java.tracing.JavacPhaseEvent;
import com.facebook.buck.log.InvocationInfo;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildEvent;
import com.facebook.buck.rules.BuildRuleEvent;
import com.facebook.buck.rules.BuildRuleKeys;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleStatus;
import com.facebook.buck.rules.BuildRuleSuccessType;
import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.rules.FakeBuildRule;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.step.StepEvent;
import com.facebook.buck.timing.Clock;
import com.facebook.buck.timing.FakeClock;
import com.facebook.buck.timing.IncrementingFakeClock;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.ObjectMappers;
import com.facebook.buck.util.perf.PerfStatsTracking;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
public class ChromeTraceBuildListenerTest {
private static final long TIMESTAMP_NANOS = 1409702151000000000L;
private static final String EXPECTED_DIR =
"buck-out/log/2014-09-02_23h55m51s_no_sub_command_BUILD_ID/";
@Rule
public TemporaryFolder tmpDir = new TemporaryFolder();
private InvocationInfo invocationInfo;
@Before
public void setUp() throws IOException {
invocationInfo = InvocationInfo.builder()
.setTimestampMillis(TimeUnit.NANOSECONDS.toMillis(TIMESTAMP_NANOS))
.setBuckLogDir(tmpDir.getRoot().toPath().resolve("buck-out/log"))
.setBuildId(new BuildId("BUILD_ID"))
.setSubCommand("no_sub_command")
.setIsDaemon(false)
.setSuperConsoleEnabled(false)
.build();
}
@Test
public void testDeleteFiles() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
String tracePath = invocationInfo.getLogDirectoryPath().resolve("build.trace").toString();
File traceFile = new File(tracePath);
projectFilesystem.createParentDirs(tracePath);
traceFile.createNewFile();
traceFile.setLastModified(0);
for (int i = 0; i < 10; ++i) {
File oldResult = new File(
String.format("%s/build.100%d.trace", invocationInfo.getLogDirectoryPath(), i));
oldResult.createNewFile();
oldResult.setLastModified(TimeUnit.SECONDS.toMillis(i));
}
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 3,
false);
listener.outputTrace(invocationInfo.getBuildId());
ImmutableList<String> files = FluentIterable.
from(Arrays.asList(projectFilesystem.listFiles(invocationInfo.getLogDirectoryPath()))).
filter(input -> input.toString().endsWith(".trace")).
transform(File::getName).
toList();
assertEquals(4, files.size());
assertEquals(
ImmutableSortedSet.of(
"build.trace",
"build.1009.trace",
"build.1008.trace",
"build.2014-09-02.16-55-51.BUILD_ID.trace"),
ImmutableSortedSet.copyOf(files));
}
@Test
public void testBuildJson() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
ObjectMapper mapper = ObjectMappers.newDefaultInstance();
BuildId buildId = new BuildId("ChromeTraceBuildListenerTestBuildId");
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
mapper,
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 42,
false);
BuildTarget target = BuildTargetFactory.newInstance("//fake:rule");
FakeBuildRule rule = new FakeBuildRule(
target,
new SourcePathResolver(
new BuildRuleResolver(
TargetGraph.EMPTY,
new DefaultTargetNodeToBuildRuleTransformer())
),
ImmutableSortedSet.of());
RuleKey ruleKey = new RuleKey("abc123");
String stepShortName = "fakeStep";
String stepDescription = "I'm a Fake Step!";
UUID stepUuid = UUID.randomUUID();
ImmutableSet<BuildTarget> buildTargets = ImmutableSet.of(target);
Iterable<String> buildArgs = Iterables.transform(buildTargets, Object::toString);
Clock fakeClock = new IncrementingFakeClock(TimeUnit.MILLISECONDS.toNanos(1));
BuckEventBus eventBus = BuckEventBusFactory.newInstance(fakeClock, buildId);
eventBus.register(listener);
CommandEvent.Started commandEventStarted = CommandEvent.started(
"party",
ImmutableList.of("arg1", "arg2"),
/* isDaemon */ true);
eventBus.post(commandEventStarted);
eventBus.post(new PerfStatsTracking.MemoryPerfStatsEvent(
/* freeMemoryBytes */ 1024 * 1024L,
/* totalMemoryBytes */ 3 * 1024 * 1024L,
/* timeSpentInGcMs */ -1,
/* currentMemoryBytesUsageByPool */ ImmutableMap.of("flower", 42L * 1024 * 1024)));
ArtifactCacheConnectEvent.Started artifactCacheConnectEventStarted =
ArtifactCacheConnectEvent.started();
eventBus.post(artifactCacheConnectEventStarted);
eventBus.post(ArtifactCacheConnectEvent.finished(artifactCacheConnectEventStarted));
BuildEvent.Started buildEventStarted = BuildEvent.started(buildArgs);
eventBus.post(buildEventStarted);
HttpArtifactCacheEvent.Started artifactCacheEventStarted =
HttpArtifactCacheEvent.newFetchStartedEvent(ruleKey);
eventBus.post(artifactCacheEventStarted);
eventBus.post(
HttpArtifactCacheEvent.newFinishedEventBuilder(artifactCacheEventStarted)
.setFetchDataBuilder(
HttpArtifactCacheEventFetchData.builder()
.setFetchResult(CacheResult.hit("http")))
.build());
ArtifactCompressionEvent.Started artifactCompressionStartedEvent =
ArtifactCompressionEvent.started(
ArtifactCompressionEvent.Operation.COMPRESS, ImmutableSet.of(ruleKey));
eventBus.post(artifactCompressionStartedEvent);
eventBus.post(ArtifactCompressionEvent.finished(artifactCompressionStartedEvent));
eventBus.post(BuildRuleEvent.started(rule));
eventBus.post(StepEvent.started(stepShortName, stepDescription, stepUuid));
JavacPhaseEvent.Started runProcessorsStartedEvent = JavacPhaseEvent.started(
target,
JavacPhaseEvent.Phase.RUN_ANNOTATION_PROCESSORS,
ImmutableMap.of());
eventBus.post(runProcessorsStartedEvent);
String annotationProcessorName = "com.facebook.FakeProcessor";
AnnotationProcessingEvent.Operation operation = AnnotationProcessingEvent.Operation.PROCESS;
int annotationRound = 1;
boolean isLastRound = false;
AnnotationProcessingEvent.Started annotationProcessingEventStarted =
AnnotationProcessingEvent.started(
target,
annotationProcessorName,
operation,
annotationRound,
isLastRound);
eventBus.post(annotationProcessingEventStarted);
HttpArtifactCacheEvent.Scheduled httpScheduled = HttpArtifactCacheEvent.newStoreScheduledEvent(
Optional.of("TARGET_ONE"), ImmutableSet.of(ruleKey));
HttpArtifactCacheEvent.Started httpStarted =
HttpArtifactCacheEvent.newStoreStartedEvent(httpScheduled);
eventBus.post(httpStarted);
HttpArtifactCacheEvent.Finished httpFinished =
HttpArtifactCacheEvent.newFinishedEventBuilder(httpStarted).build();
eventBus.post(httpFinished);
final CompilerPluginDurationEvent.Started processingPartOneStarted =
CompilerPluginDurationEvent.started(
target,
annotationProcessorName,
"processingPartOne",
ImmutableMap.of());
eventBus.post(processingPartOneStarted);
eventBus.post(
CompilerPluginDurationEvent.finished(
processingPartOneStarted,
ImmutableMap.of()));
eventBus.post(AnnotationProcessingEvent.finished(annotationProcessingEventStarted));
eventBus.post(
JavacPhaseEvent.finished(runProcessorsStartedEvent, ImmutableMap.of()));
eventBus.post(StepEvent.finished(
StepEvent.started(stepShortName, stepDescription, stepUuid),
0));
eventBus.post(
BuildRuleEvent.finished(
rule,
BuildRuleKeys.of(ruleKey),
BuildRuleStatus.SUCCESS,
CacheResult.miss(),
Optional.of(BuildRuleSuccessType.BUILT_LOCALLY),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty()));
try (final SimplePerfEvent.Scope scope1 = SimplePerfEvent.scope(
eventBus,
PerfEventId.of("planning"),
ImmutableMap.<String, Object>of("nefarious", "true"))) {
try (final SimplePerfEvent.Scope scope2 = SimplePerfEvent.scope(
eventBus,
PerfEventId.of("scheming"))) {
scope2.appendFinishedInfo("success", "false");
}
}
eventBus.post(BuildEvent.finished(buildEventStarted, 0));
eventBus.post(CommandEvent.finished(commandEventStarted, /* exitCode */ 0));
listener.outputTrace(new BuildId("BUILD_ID"));
File resultFile = new File(tmpDir.getRoot(), "buck-out/log/build.trace");
List<ChromeTraceEvent> originalResultList = mapper.readValue(
resultFile,
new TypeReference<List<ChromeTraceEvent>>() {});
List<ChromeTraceEvent> resultListCopy = new ArrayList<>();
resultListCopy.addAll(originalResultList);
ImmutableMap<String, String> emptyArgs = ImmutableMap.of();
assertNextResult(
resultListCopy,
"process_name",
ChromeTraceEvent.Phase.METADATA,
ImmutableMap.of("name", "buck"));
assertNextResult(
resultListCopy,
"party",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("command_args", "arg1 arg2"));
assertNextResult(
resultListCopy,
"memory",
ChromeTraceEvent.Phase.COUNTER,
ImmutableMap.of(
"used_memory_mb", "2",
"free_memory_mb", "1",
"total_memory_mb", "3",
"time_spent_in_gc_sec", "0",
"pool_flower_mb", "42"));
assertNextResult(
resultListCopy,
"artifact_connect",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"artifact_connect",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"build",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"http_artifact_fetch",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("rule_key", "abc123"));
assertNextResult(
resultListCopy,
"http_artifact_fetch",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"rule_key", "abc123",
"success", "true",
"cache_result", "HTTP_HIT"));
assertNextResult(
resultListCopy,
"artifact_compress",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("rule_key", "abc123"));
assertNextResult(
resultListCopy,
"artifact_compress",
ChromeTraceEvent.Phase.END,
ImmutableMap.of("rule_key", "abc123"));
// BuildRuleEvent.Started
assertNextResult(
resultListCopy,
"//fake:rule",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of());
assertNextResult(
resultListCopy,
"fakeStep",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"run annotation processors",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"com.facebook.FakeProcessor.process",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"http_artifact_store",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of(
"rule_key", "abc123"));
assertNextResult(
resultListCopy,
"http_artifact_store",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"success", "true",
"rule_key", "abc123"));
assertNextResult(
resultListCopy,
"processingPartOne",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"processingPartOne",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"com.facebook.FakeProcessor.process",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"run annotation processors",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"fakeStep",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"description", "I'm a Fake Step!",
"exit_code", "0"));
assertNextResult(
resultListCopy,
"//fake:rule",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"cache_result", "miss",
"success_type", "BUILT_LOCALLY"));
assertNextResult(
resultListCopy,
"planning",
ChromeTraceEvent.Phase.BEGIN,
ImmutableMap.of("nefarious", "true"));
assertNextResult(
resultListCopy,
"scheming",
ChromeTraceEvent.Phase.BEGIN,
emptyArgs);
assertNextResult(
resultListCopy,
"scheming",
ChromeTraceEvent.Phase.END,
ImmutableMap.of("success", "false"));
assertNextResult(
resultListCopy,
"planning",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"build",
ChromeTraceEvent.Phase.END,
emptyArgs);
assertNextResult(
resultListCopy,
"party",
ChromeTraceEvent.Phase.END,
ImmutableMap.of(
"command_args", "arg1 arg2",
"daemon", "true"));
assertEquals(0, resultListCopy.size());
}
private static void assertNextResult(
List<ChromeTraceEvent> resultList,
String expectedName,
ChromeTraceEvent.Phase expectedPhase,
ImmutableMap<String, String> expectedArgs) {
assertTrue(resultList.size() > 0);
assertEquals(expectedName, resultList.get(0).getName());
assertEquals(expectedPhase, resultList.get(0).getPhase());
assertEquals(expectedArgs, resultList.get(0).getArgs());
resultList.remove(0);
}
@Test
public void testOutputFailed() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
assumeTrue("Can make the root directory read-only", tmpDir.getRoot().setReadOnly());
try {
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 3,
false);
listener.outputTrace(invocationInfo.getBuildId());
fail("Expected an exception.");
} catch (HumanReadableException e) {
assertEquals(
"Unable to write trace file: java.nio.file.AccessDeniedException: " +
projectFilesystem.resolve(projectFilesystem.getBuckPaths().getBuckOut()),
e.getMessage());
} finally {
tmpDir.getRoot().setWritable(true);
}
}
@Test
public void outputFileUsesCurrentTime() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 1,
false);
listener.outputTrace(invocationInfo.getBuildId());
assertTrue(
projectFilesystem.exists(
Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace")));
}
@Test
public void canCompressTraces() throws IOException {
ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmpDir.getRoot().toPath());
ChromeTraceBuildListener listener = new ChromeTraceBuildListener(
projectFilesystem,
invocationInfo,
new FakeClock(TIMESTAMP_NANOS),
ObjectMappers.newDefaultInstance(),
Locale.US,
TimeZone.getTimeZone("America/Los_Angeles"),
/* tracesToKeep */ 1,
true);
listener.outputTrace(invocationInfo.getBuildId());
Path tracePath = Paths.get(EXPECTED_DIR + "build.2014-09-02.16-55-51.BUILD_ID.trace.gz");
assertTrue(projectFilesystem.exists(tracePath));
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(projectFilesystem.newFileInputStream(tracePath))));
List<?> elements = new Gson().fromJson(reader, List.class);
assertThat(elements, notNullValue());
}
}
| justinmuller/buck | test/com/facebook/buck/event/listener/ChromeTraceBuildListenerTest.java | Java | apache-2.0 | 20,351 |
/*
* Copyright (C) 2016 CaMnter [email protected]
*
* 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.camnter.savevolley.network.adapter.core;
import com.camnter.savevolley.network.core.http.SaveHttpEntity;
/**
* Description:SaveHttpEntityAdapter
* Created by:CaMnter
* Time:2016-05-27 14:10
*/
public interface SaveHttpEntityAdapter<T> {
SaveHttpEntity adaptiveEntity(T t);
}
| CaMnter/SaveVolley | savevolley-network-adapter/src/main/java/com/camnter/savevolley/network/adapter/core/SaveHttpEntityAdapter.java | Java | apache-2.0 | 925 |
/*******************************************************************************
* Copyright 2007-2013 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 xworker.dataObject.http;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.dataObject.DataObject;
public class DataObjectHttpUtils {
/**
* 通过给定的DataObject从httpRequest中分析参数。
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object parseHttpRequestData(ActionContext actionContext){
DataObject theData = (DataObject) actionContext.get("theData");
Thing self = (Thing) actionContext.get("self");
if(theData == null){
theData = new DataObject(self);
}
HttpServletRequest request = (HttpServletRequest) actionContext.get("request");
Map paramMap = request.getParameterMap();
for(Thing attribute : self.getChilds("attribute")){
String name = attribute.getString("name");
if(paramMap.containsKey(name)){
theData.put(name, request.getParameter(name));
}else if("truefalse".equals(attribute.getString("inputtype"))){
//checkbox特殊处理
theData.put(name, "false");
}
}
return theData;
}
} | x-meta/xworker | xworker_dataobject/src/main/java/xworker/dataObject/http/DataObjectHttpUtils.java | Java | apache-2.0 | 2,037 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 17.11.2006
* Time: 17:36:42
*/
package com.intellij.openapi.vcs.changes.patch;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class PatchFileType implements FileType {
public static final PatchFileType INSTANCE = new PatchFileType();
public static final String NAME = "PATCH";
@NotNull
@NonNls
public String getName() {
return NAME;
}
@NotNull
public String getDescription() {
return VcsBundle.message("patch.file.type.description");
}
@NotNull
@NonNls
public String getDefaultExtension() {
return "patch";
}
@Nullable
public Icon getIcon() {
return AllIcons.Nodes.Pointcut;
}
public boolean isBinary() {
return false;
}
public boolean isReadOnly() {
return false;
}
@Nullable
@NonNls
public String getCharset(@NotNull VirtualFile file, final byte[] content) {
return null;
}
}
| ernestp/consulo | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/PatchFileType.java | Java | apache-2.0 | 1,803 |
package io.ray.streaming.runtime.core.processor;
import io.ray.streaming.message.Record;
import io.ray.streaming.operator.SourceOperator;
/**
* The processor for the stream sources, containing a SourceOperator.
*
* @param <T> The type of source data.
*/
public class SourceProcessor<T> extends StreamProcessor<Record, SourceOperator<T>> {
public SourceProcessor(SourceOperator<T> operator) {
super(operator);
}
@Override
public void process(Record record) {
throw new UnsupportedOperationException("SourceProcessor should not process record");
}
public void fetch() {
operator.fetch();
}
@Override
public void close() {}
}
| pcmoritz/ray-1 | streaming/java/streaming-runtime/src/main/java/io/ray/streaming/runtime/core/processor/SourceProcessor.java | Java | apache-2.0 | 663 |
/**
* Copyright 2012-2015 Niall Gallagher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.googlecode.cqengine.index.support;
import com.googlecode.cqengine.query.QueryFactory;
import com.googlecode.cqengine.testutil.Car;
import org.junit.Test;
import static com.googlecode.cqengine.query.QueryFactory.noQueryOptions;
import static org.mockito.Mockito.*;
/**
* Tests for {@link PartialSortedKeyStatisticsAttributeIndex}.
*
* @author niall.gallagher
*/
public class PartialSortedKeyStatisticsAttributeIndexTest {
@Test
public void testGetDistinctKeys1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeys(noQueryOptions());
}
@Test
public void testGetDistinctKeys2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeys(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeys(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetDistinctKeysDescending1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeysDescending(noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeysDescending(noQueryOptions());
}
@Test
public void testGetDistinctKeysDescending2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getDistinctKeysDescending(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getDistinctKeysDescending(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetStatisticsForDistinctKeysDescending() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getStatisticsForDistinctKeysDescending(noQueryOptions());
verify(backingIndex, times(1)).getStatisticsForDistinctKeysDescending(noQueryOptions());
}
@Test
public void testGetKeysAndValues1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValues(noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValues(noQueryOptions());
}
@Test
public void testGetKeysAndValues2() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValues(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValues(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetKeysAndValuesDescending() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValuesDescending(noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValuesDescending(noQueryOptions());
}
@Test
public void testGetKeysAndValuesDescending1() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getKeysAndValuesDescending(1, true, 2, true, noQueryOptions());
verify(backingIndex, times(1)).getKeysAndValuesDescending(1, true, 2, true, noQueryOptions());
}
@Test
public void testGetCountForKey() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getCountForKey(1, noQueryOptions());
verify(backingIndex, times(1)).getCountForKey(1, noQueryOptions());
}
@Test
public void testGetCountOfDistinctKeys() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getCountOfDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getCountOfDistinctKeys(noQueryOptions());
}
@Test
public void testGetStatisticsForDistinctKeys() {
SortedKeyStatisticsAttributeIndex<Integer, Car> backingIndex = mockBackingIndex();
PartialSortedKeyStatisticsAttributeIndex<Integer, Car> index = wrapWithPartialIndex(backingIndex);
index.getStatisticsForDistinctKeys(noQueryOptions());
verify(backingIndex, times(1)).getStatisticsForDistinctKeys(noQueryOptions());
}
static PartialSortedKeyStatisticsAttributeIndex<Integer, Car> wrapWithPartialIndex(final SortedKeyStatisticsAttributeIndex<Integer, Car> mockedBackingIndex) {
return new PartialSortedKeyStatisticsAttributeIndex<Integer, Car>(Car.CAR_ID, QueryFactory.between(Car.CAR_ID, 2, 5)) {
@Override
protected SortedKeyStatisticsAttributeIndex<Integer, Car> createBackingIndex() {
return mockedBackingIndex;
}
};
}
@SuppressWarnings("unchecked")
static SortedKeyStatisticsAttributeIndex<Integer, Car> mockBackingIndex() {
return mock(SortedKeyStatisticsAttributeIndex.class);
}
} | npgall/cqengine | code/src/test/java/com/googlecode/cqengine/index/support/PartialSortedKeyStatisticsAttributeIndexTest.java | Java | apache-2.0 | 6,673 |
/*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.common.policy;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.lang.Validate;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.LimitationsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordLifeTimeType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
/**
*
* @author mamut
*
*/
public class PasswordPolicyUtils {
private static final transient Trace LOGGER = TraceManager.getTrace(PasswordPolicyUtils.class);
private static final String DOT_CLASS = PasswordPolicyUtils.class.getName() + ".";
private static final String OPERATION_PASSWORD_VALIDATION = DOT_CLASS + "passwordValidation";
/**
* add defined default values
*
* @param pp
* @return
*/
public static void normalize(ValuePolicyType pp) {
if (null == pp) {
throw new IllegalArgumentException("Password policy cannot be null");
}
if (null == pp.getStringPolicy()) {
StringPolicyType sp = new StringPolicyType();
pp.setStringPolicy(StringPolicyUtils.normalize(sp));
} else {
pp.setStringPolicy(StringPolicyUtils.normalize(pp.getStringPolicy()));
}
if (null == pp.getLifetime()) {
PasswordLifeTimeType lt = new PasswordLifeTimeType();
lt.setExpiration(-1);
lt.setWarnBeforeExpiration(0);
lt.setLockAfterExpiration(0);
lt.setMinPasswordAge(0);
lt.setPasswordHistoryLength(0);
}
return;
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param policies
* - Password List of policies used to check
* @param result
* - Operation result of password validator.
* @return true if password meet all criteria , false if any criteria is not
* met
*/
public static boolean validatePassword(String password, List <ValuePolicyType> policies, OperationResult result) {
boolean ret=true;
//iterate through policies
for (ValuePolicyType pp: policies) {
OperationResult op = validatePassword(password, pp);
result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
public static boolean validatePassword(String password, List<PrismObject<ValuePolicyType>> policies) {
boolean ret=true;
//iterate through policies
for (PrismObject<ValuePolicyType> pp: policies) {
OperationResult op = validatePassword(password, pp.asObjectable());
// result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
public static boolean validatePassword(ProtectedStringType password, List<PrismObject<ValuePolicyType>> policies) {
boolean ret=true;
//iterate through policies
for (PrismObject<ValuePolicyType> pp: policies) {
OperationResult op = validatePassword(password.getClearValue(), pp.asObjectable());
// result.addSubresult(op);
//if one fail then result is failure
if (ret == true && ! op.isSuccess()) {
ret = false;
}
}
return ret;
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param pp
* - Password policy used to check
* @param result
* - Operation result of password validator.
* @return true if password meet all criteria , false if any criteria is not
* met
*/
public static boolean validatePassword(String password, ValuePolicyType pp, OperationResult result) {
OperationResult op = validatePassword(password, pp);
result.addSubresult(op);
return op.isSuccess();
}
/**
* Check provided password against provided policy
*
* @param password
* - password to check
* @param pp
* - Password policy used
* @return - Operation result of this validation
*/
public static OperationResult validatePassword(String password, ValuePolicyType pp) {
// check input params
// if (null == pp) {
// throw new IllegalArgumentException("No policy provided: NULL");
// }
//
// if (null == password) {
// throw new IllegalArgumentException("Password for validaiton is null.");
// }
Validate.notNull(pp, "Password policy must not be null.");
Validate.notNull(password, "Password to validate must not be null.");
OperationResult ret = new OperationResult(OPERATION_PASSWORD_VALIDATION);
ret.addParam("policyName", pp.getName());
normalize(pp);
LimitationsType lims = pp.getStringPolicy().getLimitations();
StringBuilder message = new StringBuilder();
// Test minimal length
if (lims.getMinLength() == null){
lims.setMinLength(0);
}
if (lims.getMinLength() > password.length()) {
String msg = "Required minimal size (" + lims.getMinLength() + ") of password is not met (password length: "
+ password.length() + ")";
ret.addSubresult(new OperationResult("Check global minimal length", OperationResultStatus.FATAL_ERROR,
msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check global minimal length. Minimal length of password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
// Test maximal length
if (lims.getMaxLength() != null) {
if (lims.getMaxLength() < password.length()) {
String msg = "Required maximal size (" + lims.getMaxLength()
+ ") of password was exceeded (password length: " + password.length() + ").";
ret.addSubresult(new OperationResult("Check global maximal length", OperationResultStatus.FATAL_ERROR,
msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check global maximal length. Maximal length of password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
}
// Test uniqueness criteria
HashSet<String> tmp = new HashSet<String>(StringPolicyUtils.stringTokenizer(password));
if (lims.getMinUniqueChars() != null) {
if (lims.getMinUniqueChars() > tmp.size()) {
String msg = "Required minimal count of unique characters ("
+ lims.getMinUniqueChars()
+ ") in password are not met (unique characters in password " + tmp.size() + ")";
ret.addSubresult(new OperationResult("Check minimal count of unique chars",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult(
// "Check minimal count of unique chars. Password satisfies minimal required unique characters.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
}
// check limitation
HashSet<String> allValidChars = new HashSet<String>(128);
ArrayList<String> validChars = null;
ArrayList<String> passwd = StringPolicyUtils.stringTokenizer(password);
if (lims.getLimit() == null || lims.getLimit().isEmpty()){
if (message.toString() == null || message.toString().isEmpty()){
ret.computeStatus();
} else {
ret.computeStatus(message.toString());
}
return ret;
}
for (StringLimitType l : lims.getLimit()) {
OperationResult limitResult = new OperationResult("Tested limitation: " + l.getDescription());
if (null != l.getCharacterClass().getValue()) {
validChars = StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue());
} else {
validChars = StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(pp
.getStringPolicy().getCharacterClass(), l.getCharacterClass().getRef()));
}
// memorize validChars
allValidChars.addAll(validChars);
// Count how many character for this limitation are there
int count = 0;
for (String s : passwd) {
if (validChars.contains(s)) {
count++;
}
}
// Test minimal occurrence
if (l.getMinOccurs() == null){
l.setMinOccurs(0);
}
if (l.getMinOccurs() > count) {
String msg = "Required minimal occurrence (" + l.getMinOccurs()
+ ") of characters ("+l.getDescription()+") in password is not met (occurrence of characters in password "
+ count + ").";
limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters in password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
// Test maximal occurrence
if (l.getMaxOccurs() != null) {
if (l.getMaxOccurs() < count) {
String msg = "Required maximal occurrence (" + l.getMaxOccurs()
+ ") of characters ("+l.getDescription()+") in password was exceeded (occurrence of characters in password "
+ count + ").";
limitResult.addSubresult(new OperationResult("Check maximal occurrence of characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult(
// "Check maximal occurrence of characters in password OK.", OperationResultStatus.SUCCESS,
// "PASSED"));
// }
}
// test if first character is valid
if (l.isMustBeFirst() == null){
l.setMustBeFirst(false);
}
if (l.isMustBeFirst() && !validChars.contains(password.substring(0, 1))) {
String msg = "First character is not from allowed set. Allowed set: "
+ validChars.toString();
limitResult.addSubresult(new OperationResult("Check valid first char",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// limitResult.addSubresult(new OperationResult("Check valid first char in password OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
limitResult.computeStatus();
ret.addSubresult(limitResult);
}
// Check if there is no invalid character
StringBuilder sb = new StringBuilder();
for (String s : passwd) {
if (!allValidChars.contains(s)) {
// memorize all invalid characters
sb.append(s);
}
}
if (sb.length() > 0) {
String msg = "Characters [ " + sb
+ " ] are not allowed to be use in password";
ret.addSubresult(new OperationResult("Check if password does not contain invalid characters",
OperationResultStatus.FATAL_ERROR, msg));
message.append(msg);
message.append("\n");
}
// else {
// ret.addSubresult(new OperationResult("Check if password does not contain invalid characters OK.",
// OperationResultStatus.SUCCESS, "PASSED"));
// }
if (message.toString() == null || message.toString().isEmpty()){
ret.computeStatus();
} else {
ret.computeStatus(message.toString());
}
return ret;
}
}
| sabriarabacioglu/engerek | infra/common/src/main/java/com/evolveum/midpoint/common/policy/PasswordPolicyUtils.java | Java | apache-2.0 | 12,321 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=======================================================================*/
// This class has been generated, DO NOT EDIT!
package org.tensorflow.op.linalg;
import java.util.Arrays;
import org.tensorflow.GraphOperation;
import org.tensorflow.Operand;
import org.tensorflow.Operation;
import org.tensorflow.OperationBuilder;
import org.tensorflow.Output;
import org.tensorflow.op.RawOp;
import org.tensorflow.op.RawOpInputs;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Endpoint;
import org.tensorflow.op.annotation.OpInputsMetadata;
import org.tensorflow.op.annotation.OpMetadata;
import org.tensorflow.op.annotation.Operator;
import org.tensorflow.proto.framework.DataType;
import org.tensorflow.types.TInt32;
import org.tensorflow.types.family.TType;
/**
* Returns the batched diagonal part of a batched tensor.
* Returns a tensor with the {@code k[0]}-th to {@code k[1]}-th diagonals of the batched
* {@code input}.
* <p>Assume {@code input} has {@code r} dimensions {@code [I, J, ..., L, M, N]}.
* Let {@code max_diag_len} be the maximum length among all diagonals to be extracted,
* {@code max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))}
* Let {@code num_diags} be the number of diagonals to extract,
* {@code num_diags = k[1] - k[0] + 1}.
* <p>If {@code num_diags == 1}, the output tensor is of rank {@code r - 1} with shape
* {@code [I, J, ..., L, max_diag_len]} and values:
* <pre>
* diagonal[i, j, ..., l, n]
* = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
* padding_value ; otherwise.
* </pre>
* <p>where {@code y = max(-k[1], 0)}, {@code x = max(k[1], 0)}.
* <p>Otherwise, the output tensor has rank {@code r} with dimensions
* {@code [I, J, ..., L, num_diags, max_diag_len]} with values:
* <pre>
* diagonal[i, j, ..., l, m, n]
* = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,
* padding_value ; otherwise.
* </pre>
* <p>where {@code d = k[1] - m}, {@code y = max(-d, 0)}, and {@code x = max(d, 0)}.
* <p>The input must be at least a matrix.
* <p>For example:
* <pre>
* input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)
* [5, 6, 7, 8],
* [9, 8, 7, 6]],
* [[5, 4, 3, 2],
* [1, 2, 3, 4],
* [5, 6, 7, 8]]])
*
* # A main diagonal from each batch.
* tf.matrix_diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)
* [5, 2, 7]]
*
* # A superdiagonal from each batch.
* tf.matrix_diag_part(input, k = 1)
* ==> [[2, 7, 6], # Output shape: (2, 3)
* [4, 3, 8]]
*
* # A tridiagonal band from each batch.
* tf.matrix_diag_part(input, k = (-1, 1))
* ==> [[[2, 7, 6], # Output shape: (2, 3, 3)
* [1, 6, 7],
* [5, 8, 0]],
* [[4, 3, 8],
* [5, 2, 7],
* [1, 6, 0]]]
*
* # Padding value = 9
* tf.matrix_diag_part(input, k = (1, 3), padding_value = 9)
* ==> [[[4, 9, 9], # Output shape: (2, 3, 3)
* [3, 8, 9],
* [2, 7, 6]],
* [[2, 9, 9],
* [3, 4, 9],
* [4, 3, 8]]]
* </pre>
*
* @param <T> data type for {@code diagonal} output
*/
@OpMetadata(
opType = MatrixDiagPart.OP_NAME,
inputsClass = MatrixDiagPart.Inputs.class
)
@Operator(
group = "linalg"
)
public final class MatrixDiagPart<T extends TType> extends RawOp implements Operand<T> {
/**
* The name of this op, as known by TensorFlow core engine
*/
public static final String OP_NAME = "MatrixDiagPartV2";
private Output<T> diagonal;
public MatrixDiagPart(Operation operation) {
super(operation, OP_NAME);
int outputIdx = 0;
diagonal = operation.output(outputIdx++);
}
/**
* Factory method to create a class wrapping a new MatrixDiagPartV2 operation.
*
* @param scope current scope
* @param input Rank {@code r} tensor where {@code r >= 2}.
* @param k Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main
* diagonal, and negative value means subdiagonals. {@code k} can be a single integer
* (for a single diagonal) or a pair of integers specifying the low and high ends
* of a matrix band. {@code k[0]} must not be larger than {@code k[1]}.
* @param paddingValue The value to fill the area outside the specified diagonal band with.
* Default is 0.
* @param <T> data type for {@code MatrixDiagPartV2} output and operands
* @return a new instance of MatrixDiagPart
*/
@Endpoint(
describeByClass = true
)
public static <T extends TType> MatrixDiagPart<T> create(Scope scope, Operand<T> input,
Operand<TInt32> k, Operand<T> paddingValue) {
OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "MatrixDiagPart");
opBuilder.addInput(input.asOutput());
opBuilder.addInput(k.asOutput());
opBuilder.addInput(paddingValue.asOutput());
return new MatrixDiagPart<>(opBuilder.build());
}
/**
* Gets diagonal.
* The extracted diagonal(s).
* @return diagonal.
*/
public Output<T> diagonal() {
return diagonal;
}
@Override
public Output<T> asOutput() {
return diagonal;
}
@OpInputsMetadata(
outputsClass = MatrixDiagPart.class
)
public static class Inputs<T extends TType> extends RawOpInputs<MatrixDiagPart<T>> {
/**
* Rank {@code r} tensor where {@code r >= 2}.
*/
public final Operand<T> input;
/**
* Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main
* diagonal, and negative value means subdiagonals. {@code k} can be a single integer
* (for a single diagonal) or a pair of integers specifying the low and high ends
* of a matrix band. {@code k[0]} must not be larger than {@code k[1]}.
*/
public final Operand<TInt32> k;
/**
* The value to fill the area outside the specified diagonal band with.
* Default is 0.
*/
public final Operand<T> paddingValue;
/**
* The T attribute
*/
public final DataType T;
public Inputs(GraphOperation op) {
super(new MatrixDiagPart<>(op), op, Arrays.asList("T"));
int inputIndex = 0;
input = (Operand<T>) op.input(inputIndex++);
k = (Operand<TInt32>) op.input(inputIndex++);
paddingValue = (Operand<T>) op.input(inputIndex++);
T = op.attributes().getAttrType("T");
}
}
}
| tensorflow/java | tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/op/linalg/MatrixDiagPart.java | Java | apache-2.0 | 7,043 |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2012 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.control;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
import org.junit.jupiter.api.Test;
import org.zaproxy.zap.control.AddOn.BundleData;
import org.zaproxy.zap.control.AddOn.HelpSetData;
import org.zaproxy.zap.control.AddOn.ValidationResult;
import org.zaproxy.zap.utils.ZapXmlConfiguration;
/** Unit test for {@link AddOn}. */
class AddOnUnitTest extends AddOnTestUtils {
private static final File ZAP_VERSIONS_XML =
getResourcePath("ZapVersions-deps.xml", AddOnUnitTest.class).toFile();
@Test
void testAlpha2UpdatesAlpha1() throws Exception {
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "2"));
assertTrue(addOnA2.isUpdateTo(addOnA1));
}
@Test
void testAlpha1DoesNotUpdateAlpha2() throws Exception {
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "1"));
assertFalse(addOnA1.isUpdateTo(addOnA2));
}
@Test
void testAlpha2UpdatesBeta1() throws Exception {
AddOn addOnB1 = new AddOn(createAddOnFile("test-beta-1.zap", "beta", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("test-alpha-2.zap", "alpha", "2"));
assertTrue(addOnA2.isUpdateTo(addOnB1));
}
@Test
void testAlpha2DoesNotUpdateTestyAlpha1() throws Exception {
// Given
AddOn addOnA1 = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
AddOn addOnA2 = new AddOn(createAddOnFile("testy-alpha-2.zap", "alpha", "1"));
// When
IllegalArgumentException e =
assertThrows(IllegalArgumentException.class, () -> addOnA2.isUpdateTo(addOnA1));
// Then
assertThat(e.getMessage(), containsString("Different addons"));
}
@Test
void shouldBeUpdateIfSameVersionWithHigherStatus() throws Exception {
// Given
String name = "addon.zap";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, "beta", version));
AddOn addOnHigherStatus = new AddOn(createAddOnFile(name, "release", version));
// When
boolean update = addOnHigherStatus.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfSameVersionWithLowerStatus() throws Exception {
// Given
String name = "addon.zap";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, "beta", version));
AddOn addOnHigherStatus = new AddOn(createAddOnFile(name, "release", version));
// When
boolean update = addOn.isUpdateTo(addOnHigherStatus);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeUpdateIfFileIsNewerWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn newestAddOn = new AddOn(createAddOnFile(name, status, version));
newestAddOn.getFile().setLastModified(System.currentTimeMillis() + 1000);
// When
boolean update = newestAddOn.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfFileIsOlderWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn newestAddOn = new AddOn(createAddOnFile(name, status, version));
newestAddOn.getFile().setLastModified(System.currentTimeMillis() + 1000);
// When
boolean update = addOn.isUpdateTo(newestAddOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeUpdateIfOtherAddOnDoesNotHaveFileWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn addOnWithoutFile = new AddOn(createAddOnFile(name, status, version));
addOnWithoutFile.setFile(null);
// When
boolean update = addOn.isUpdateTo(addOnWithoutFile);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateIfCurrentAddOnDoesNotHaveFileWithSameStatusAndVersion() throws Exception {
// Given
String name = "addon.zap";
String status = "release";
String version = "1.0.0";
AddOn addOn = new AddOn(createAddOnFile(name, status, version));
AddOn addOnWithoutFile = new AddOn(createAddOnFile(name, status, version));
addOnWithoutFile.setFile(null);
// When
boolean update = addOnWithoutFile.isUpdateTo(addOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void testCanLoadAddOnNotBefore() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertFalse(ao.canLoadInVersion("1.4.0"));
assertFalse(ao.canLoadInVersion("2.0.alpha"));
}
@Test
void testCanLoadAddOnNotFrom() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
ao.setNotFromVersion("2.8.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertTrue(ao.canLoadInVersion("2.7.0"));
assertFalse(ao.canLoadInVersion("2.8.0"));
assertFalse(ao.canLoadInVersion("2.8.0.1"));
assertFalse(ao.canLoadInVersion("2.9.0"));
}
@Test
void testCanLoadAddOnNotBeforeNotFrom() throws Exception {
AddOn ao = new AddOn(createAddOnFile("test-alpha-1.zap", "alpha", "1"));
ao.setNotBeforeVersion("2.4.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
ao.setNotFromVersion("2.7.0");
assertTrue(ao.canLoadInVersion("2.4.0"));
assertTrue(ao.canLoadInVersion("2.5.0"));
assertTrue(ao.canLoadInVersion("2.6.0"));
assertFalse(ao.canLoadInVersion("2.7.0"));
assertFalse(ao.canLoadInVersion("2.7.0.1"));
assertFalse(ao.canLoadInVersion("2.8.0"));
}
@Test
void shouldNotBeAddOnFileNameIfNull() throws Exception {
// Given
String fileName = null;
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnFileNameIfNotEndsWithZapExtension() throws Exception {
// Given
String fileName = "addon.txt";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(false)));
}
@Test
void shouldBeAddOnFileNameIfEndsWithZapExtension() throws Exception {
// Given
String fileName = "addon.zap";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(true)));
}
@Test
void shouldBeAddOnFileNameEvenIfZapExtensionIsUpperCase() throws Exception {
// Given
String fileName = "addon.ZAP";
// When
boolean addOnFileName = AddOn.isAddOnFileName(fileName);
// Then
assertThat(addOnFileName, is(equalTo(true)));
}
@Test
void shouldNotBeAddOnIfPathIsNull() throws Exception {
// Given
Path file = null;
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfPathIsDirectory() throws Exception {
// Given
Path file = Files.createDirectory(newTempDir().resolve("addon.zap"));
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfFileNameNotEndsWithZapExtension() throws Exception {
// Given
Path file = createAddOnFile("addon.txt", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldNotBeAddOnIfAddOnDoesNotHaveManifestFile() throws Exception {
// Given
Path file = createEmptyAddOnFile("addon.zap");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(false)));
}
@Test
void shouldBeAddOnIfPathEndsWithZapExtension() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(true)));
}
@Test
void shouldBeAddOnEvenIfZapExtensionIsUpperCase() throws Exception {
// Given
Path file = createAddOnFile("addon.ZAP", "alpha", "1");
// When
boolean addOnFile = AddOn.isAddOn(file);
// Then
assertThat(addOnFile, is(equalTo(true)));
}
@Test
void shouldNotBeValidAddOnIfPathIsNull() throws Exception {
// Given
Path file = null;
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_PATH)));
}
@Test
void shouldNotBeValidAddOnIfPathHasNoFileName() throws Exception {
// Given
Path file = Paths.get("/");
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_PATH)));
}
@Test
void shouldNotBeValidAddOnIfFileDoesNotHaveZapExtension() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zip"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_FILE_NAME)));
}
@Test
void shouldNotBeValidAddOnIfPathIsDirectory() throws Exception {
// Given
Path file = Files.createDirectory(newTempDir().resolve("addon.zap"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.FILE_NOT_READABLE)));
}
@Test
void shouldNotBeValidAddOnIfPathIsNotReadable() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "1");
assumeTrue(
Files.getFileStore(file).supportsFileAttributeView(PosixFileAttributeView.class),
"Test requires support for POSIX file attributes.");
Set<PosixFilePermission> perms =
Files.readAttributes(file, PosixFileAttributes.class).permissions();
perms.remove(PosixFilePermission.OWNER_READ);
Files.setPosixFilePermissions(file, perms);
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.FILE_NOT_READABLE)));
}
@Test
void shouldNotBeValidAddOnIfNotZipFile() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(
result.getValidity(), is(equalTo(ValidationResult.Validity.UNREADABLE_ZIP_FILE)));
assertThat(result.getException(), is(notNullValue()));
}
@Test
void shouldNotBeValidAddOnIfItHasNoManifest() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.toFile()))) {
zos.putNextEntry(new ZipEntry("Not a manifest"));
zos.closeEntry();
}
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.MISSING_MANIFEST)));
}
@Test
void shouldNotBeValidAddOnIfManifestIsMalformed() throws Exception {
// Given
Path file = Files.createFile(newTempDir().resolve("addon.zap"));
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.toFile()))) {
zos.putNextEntry(new ZipEntry(AddOn.MANIFEST_FILE_NAME));
zos.closeEntry();
}
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_MANIFEST)));
assertThat(result.getException(), is(notNullValue()));
}
@Test
void shouldNotBeValidAddOnIfHasMissingLib() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest ->
manifest.append("<libs>")
.append("<lib>missing.jar</lib>")
.append("</libs>"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_LIB)));
}
@Test
void shouldNotBeValidAddOnIfHasLibWithMissingName() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest ->
manifest.append("<libs>")
.append("<lib>dir/</lib>")
.append("</libs>"));
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.INVALID_LIB)));
}
@Test
void shouldBeValidAddOnIfValid() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
// When
ValidationResult result = AddOn.isValidAddOn(file);
// Then
assertThat(result.getValidity(), is(equalTo(ValidationResult.Validity.VALID)));
assertThat(result.getManifest(), is(notNullValue()));
}
@Test
void shouldFailToCreateAddOnFromNullFile() {
// Given
Path file = null;
// When
IOException e = assertThrows(IOException.class, () -> new AddOn(file));
// Then
assertThat(e.getMessage(), is(AddOn.ValidationResult.Validity.INVALID_PATH.name()));
}
@Test
void shouldFailToCreateAddOnFromFileWithInvalidFileName() throws Exception {
// Given
String invalidFileName = "addon.txt";
Path file = createAddOnFile(invalidFileName, "alpha", "1");
// When
IOException e = assertThrows(IOException.class, () -> new AddOn(file));
// Then
assertThat(e.getMessage(), is(AddOn.ValidationResult.Validity.INVALID_FILE_NAME.name()));
}
@Test
@SuppressWarnings("deprecation")
void shouldCreateAddOnFromFileAndUseManifestData() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "beta", "1.6.7");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getId(), is(equalTo("addon")));
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.beta)));
assertThat(addOn.getVersion().toString(), is(equalTo("1.6.7")));
assertThat(addOn.getFileVersion(), is(equalTo(1)));
}
@Test
void shouldCreateAddOnWithDotsInId() throws Exception {
// Given
Path file = createAddOnFile("addon.x.zap", "release", "1.0.0");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getId(), is(equalTo("addon.x")));
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.release)));
assertThat(addOn.getVersion().toString(), is(equalTo("1.0.0")));
}
@Test
void shouldIgnoreStatusInFileNameWhenCreatingAddOnFromFile() throws Exception {
// Given
Path file = createAddOnFile("addon-alpha.zap", "release", "1");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getStatus(), is(equalTo(AddOn.Status.release)));
}
@Test
@SuppressWarnings("deprecation")
void shouldIgnoreVersionInFileNameWhenCreatingAddOnFromFile() throws Exception {
// Given
Path file = createAddOnFile("addon-alpha-2.zap", "alpha", "3.2.10");
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getVersion().toString(), is(equalTo("3.2.10")));
assertThat(addOn.getFileVersion(), is(equalTo(3)));
}
@Test
void shouldReturnNormalisedFileName() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "alpha", "2.8.1");
AddOn addOn = new AddOn(file);
// When
String normalisedFileName = addOn.getNormalisedFileName();
// Then
assertThat(normalisedFileName, is(equalTo("addon-2.8.1.zap")));
}
@Test
void shouldHaveNoReleaseDate() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("addon.zap"));
// When
String releaseDate = addOn.getReleaseDate();
// Then
assertThat(releaseDate, is(nullValue()));
}
@Test
void shouldHaveCorrectSize() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("addon.zap"));
// When
long size = addOn.getSize();
// Then
assertThat(size, is(equalTo(189L)));
}
@Test
void shouldHaveEmptyBundleByDefault() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(true)));
assertThat(bundleData.getBaseName(), is(equalTo("")));
assertThat(bundleData.getPrefix(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredBundle() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<bundle>")
.append("org.zaproxy.Messages")
.append("</bundle>");
});
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(false)));
assertThat(bundleData.getBaseName(), is(equalTo("org.zaproxy.Messages")));
assertThat(bundleData.getPrefix(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredBundleWithPrefix() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<bundle prefix=\"msgs\">")
.append("org.zaproxy.Messages")
.append("</bundle>");
});
AddOn addOn = new AddOn(file);
// When
BundleData bundleData = addOn.getBundleData();
// Then
assertThat(bundleData, is(notNullValue()));
assertThat(bundleData.isEmpty(), is(equalTo(false)));
assertThat(bundleData.getBaseName(), is(equalTo("org.zaproxy.Messages")));
assertThat(bundleData.getPrefix(), is(equalTo("msgs")));
}
@Test
void shouldHaveEmptyHelpSetByDefault() throws Exception {
// Given
Path file = createAddOnFile("addon.zap", "release", "1.0.0");
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(true)));
assertThat(helpSetData.getBaseName(), is(equalTo("")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredHelpSet() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<helpset>")
.append("org.zaproxy.help.helpset")
.append("</helpset>");
});
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(false)));
assertThat(helpSetData.getBaseName(), is(equalTo("org.zaproxy.help.helpset")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("")));
}
@Test
void shouldHaveDeclaredHelpSetWithLocaleToken() throws Exception {
// Given
Path file =
createAddOnFile(
"addon.zap",
"release",
"1.0.0",
manifest -> {
manifest.append("<helpset localetoken=\"%LC%\">")
.append("org.zaproxy.help%LC%.helpset")
.append("</helpset>");
});
AddOn addOn = new AddOn(file);
// When
HelpSetData helpSetData = addOn.getHelpSetData();
// Then
assertThat(helpSetData, is(notNullValue()));
assertThat(helpSetData.isEmpty(), is(equalTo(false)));
assertThat(helpSetData.getBaseName(), is(equalTo("org.zaproxy.help%LC%.helpset")));
assertThat(helpSetData.getLocaleToken(), is(equalTo("%LC%")));
}
@Test
void shouldDependOnDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn dependency = createAddOn("AddOn3", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(dependency);
// Then
assertThat(depends, is(equalTo(true)));
}
@Test
void shouldNotDependIfNoDependencies() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnFile("AddOn-release-1.zap", "release", "1"));
AddOn nonDependency = createAddOn("AddOn3", createZapVersionsXml());
// When
boolean depends = addOn.dependsOn(nonDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnNonDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn9", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn3", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(nonDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDirectlyDependOnNonDirectDependency() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDirectDependency = createAddOn("AddOn8", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(nonDirectDependency);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnItSelf() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn sameAddOn = createAddOn("AddOn1", zapVersionsXml);
// When
boolean depends = addOn.dependsOn(sameAddOn);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldDependOnDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn9", zapVersionsXml);
AddOn dependency = createAddOn("AddOn3", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency, dependency});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(true)));
}
@Test
void shouldNotDirectlyDependOnNonDirectDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency = createAddOn("AddOn9", zapVersionsXml);
AddOn nonDirectDependency = createAddOn("AddOn8", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency, nonDirectDependency});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldNotDependOnNonDependencies() throws Exception {
// Given
ZapXmlConfiguration zapVersionsXml = createZapVersionsXml();
AddOn addOn = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency1 = createAddOn("AddOn1", zapVersionsXml);
AddOn nonDependency2 = createAddOn("AddOn9", zapVersionsXml);
Collection<AddOn> addOns = Arrays.asList(new AddOn[] {nonDependency1, nonDependency2});
// When
boolean depends = addOn.dependsOn(addOns);
// Then
assertThat(depends, is(equalTo(false)));
}
@Test
void shouldBeUpdateToOlderVersionIfNewer() throws Exception {
// Given
AddOn olderAddOn = new AddOn(createAddOnFile("addon-2.4.8.zap", "release", "2.4.8"));
AddOn newerAddOn = new AddOn(createAddOnFile("addon-3.5.9.zap", "release", "3.5.9"));
// When
boolean update = newerAddOn.isUpdateTo(olderAddOn);
// Then
assertThat(update, is(equalTo(true)));
}
@Test
void shouldNotBeUpdateToNewerVersionIfOlder() throws Exception {
// Given
AddOn olderAddOn = new AddOn(createAddOnFile("addon-2.4.8.zap", "release", "2.4.8"));
AddOn newerAddOn = new AddOn(createAddOnFile("addon-3.5.9.zap", "release", "3.5.9"));
// When
boolean update = olderAddOn.isUpdateTo(newerAddOn);
// Then
assertThat(update, is(equalTo(false)));
}
@Test
void shouldBeAbleToRunIfItHasNoMinimumJavaVersion() throws Exception {
// Given
String minimumJavaVersion = null;
String runningJavaVersion = "1.8";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldBeAbleToRunInJava9MajorIfMinimumJavaVersionIsMet() throws Exception {
// Given
String minimumJavaVersion = "1.8";
String runningJavaVersion = "9";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldBeAbleToRunInJava9MinorIfMinimumJavaVersionIsMet() throws Exception {
// Given
String minimumJavaVersion = "1.8";
String runningJavaVersion = "9.1.2";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(true)));
}
@Test
void shouldNotBeAbleToRunInJava9MajorIfMinimumJavaVersionIsNotMet() throws Exception {
// Given
String minimumJavaVersion = "10";
String runningJavaVersion = "9";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(false)));
}
@Test
void shouldNotBeAbleToRunInJava9MinorIfMinimumJavaVersionIsNotMet() throws Exception {
// Given
String minimumJavaVersion = "10";
String runningJavaVersion = "9.1.2";
AddOn addOn =
new AddOn(
createAddOnFile("addon-2.4.8.zap", "release", "2.4.8", minimumJavaVersion));
// When
boolean canRun = addOn.canRunInJavaVersion(runningJavaVersion);
// Then
assertThat(canRun, is(equalTo(false)));
}
@Test
void shouldReturnLibsInManifest() throws Exception {
// Given
String lib1 = "lib1.jar";
String lib2 = "dir/lib2.jar";
Path file = createAddOnWithLibs(lib1, lib2);
// When
AddOn addOn = new AddOn(file);
// Then
assertThat(addOn.getLibs(), contains(new AddOn.Lib(lib1), new AddOn.Lib(lib2)));
}
@Test
void shouldNotBeRunnableIfLibsAreNotInFileSystem() throws Exception {
// Given
AddOn addOn = new AddOn(createAddOnWithLibs("lib1.jar", "lib2.jar"));
// When
AddOn.AddOnRunRequirements reqs = addOn.calculateRunRequirements(Collections.emptyList());
// Then
assertThat(reqs.isRunnable(), is(equalTo(false)));
assertThat(reqs.hasMissingLibs(), is(equalTo(true)));
assertThat(reqs.getAddOnMissingLibs(), is(equalTo(addOn)));
}
@Test
void shouldBeRunnableIfLibsAreInFileSystem() throws Exception {
// Given
String lib1 = "lib1.jar";
String lib2 = "lib2.jar";
AddOn addOn = new AddOn(createAddOnWithLibs(lib1, lib2));
Path libsDir = newTempDir("libsDir");
addOn.getLibs().get(0).setFileSystemUrl(libsDir.resolve(lib1).toUri().toURL());
addOn.getLibs().get(1).setFileSystemUrl(libsDir.resolve(lib2).toUri().toURL());
// When
AddOn.AddOnRunRequirements reqs = addOn.calculateRunRequirements(Collections.emptyList());
// Then
assertThat(reqs.isRunnable(), is(equalTo(true)));
assertThat(reqs.hasMissingLibs(), is(equalTo(false)));
assertThat(reqs.getAddOnMissingLibs(), is(nullValue()));
}
@Test
void shouldCreateAddOnLibFromRootJarPath() throws Exception {
// Given
String jarPath = "lib.jar";
// When
AddOn.Lib lib = new AddOn.Lib(jarPath);
// Then
assertThat(lib.getJarPath(), is(equalTo(jarPath)));
assertThat(lib.getName(), is(equalTo(jarPath)));
}
@Test
void shouldCreateAddOnLibFromNonRootJarPath() throws Exception {
// Given
String name = "lib.jar";
String jarPath = "dir/" + name;
// When
AddOn.Lib lib = new AddOn.Lib(jarPath);
// Then
assertThat(lib.getJarPath(), is(equalTo(jarPath)));
assertThat(lib.getName(), is(equalTo(name)));
}
@Test
void shouldNotHaveFileSystemUrlInAddOnLibByDefault() throws Exception {
// Given / When
AddOn.Lib lib = new AddOn.Lib("lib.jar");
// Then
assertThat(lib.getFileSystemUrl(), is(nullValue()));
}
@Test
void shouldSetFileSystemUrlToAddOnLib() throws Exception {
// Given
AddOn.Lib lib = new AddOn.Lib("lib.jar");
URL fsUrl = new URL("file:///some/path");
// When
lib.setFileSystemUrl(fsUrl);
// Then
assertThat(lib.getFileSystemUrl(), is(equalTo(fsUrl)));
}
@Test
void shouldSetNullFileSystemUrlToAddOnLib() throws Exception {
// Given
AddOn.Lib lib = new AddOn.Lib("lib.jar");
lib.setFileSystemUrl(new URL("file:///some/path"));
// When
lib.setFileSystemUrl(null);
// Then
assertThat(lib.getFileSystemUrl(), is(nullValue()));
}
private static ZapXmlConfiguration createZapVersionsXml() throws Exception {
ZapXmlConfiguration zapVersionsXml = new ZapXmlConfiguration(ZAP_VERSIONS_XML);
zapVersionsXml.setExpressionEngine(new XPathExpressionEngine());
return zapVersionsXml;
}
}
| zaproxy/zaproxy | zap/src/test/java/org/zaproxy/zap/control/AddOnUnitTest.java | Java | apache-2.0 | 36,238 |
package com.qinyadan.monitor.network.util;
import java.util.Map;
import com.qinyadan.monitor.network.control.ControlMessageDecoder;
import com.qinyadan.monitor.network.control.ControlMessageEncoder;
import com.qinyadan.monitor.network.control.ProtocolException;
public final class ControlMessageEncodingUtils {
private static final ControlMessageEncoder encoder = new ControlMessageEncoder();
private static final ControlMessageDecoder decoder = new ControlMessageDecoder();
private ControlMessageEncodingUtils() {
}
public static byte[] encode(Map<String, Object> value) throws ProtocolException {
return encoder.encode(value);
}
public static Object decode(byte[] in) throws ProtocolException {
return decoder.decode(in);
}
}
| O2O-Market/Market-monitor | market-network/src/main/java/com/qinyadan/monitor/network/util/ControlMessageEncodingUtils.java | Java | apache-2.0 | 809 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package de.hub.specificmodels.tests.testsourcemodel.impl;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.impl.EPackageImpl;
import de.hub.specificmodels.tests.testsourcemodel.ClassWithListFeatures;
import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass1;
import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass2;
import de.hub.specificmodels.tests.testsourcemodel.ListFeatureElementClass3;
import de.hub.specificmodels.tests.testsourcemodel.RootClass;
import de.hub.specificmodels.tests.testsourcemodel.TestSourceModelFactory;
import de.hub.specificmodels.tests.testsourcemodel.TestSourceModelPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class TestSourceModelPackageImpl extends EPackageImpl implements TestSourceModelPackage {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass rootClassEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass classWithListFeaturesEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass listFeatureElementClass1EClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass listFeatureElementClass2EClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass listFeatureElementClass3EClass = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see de.hub.specificmodels.tests.testsourcemodel.TestSourceModelPackage#eNS_URI
* @see #init()
* @generated
*/
private TestSourceModelPackageImpl() {
super(eNS_URI, TestSourceModelFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends.
*
* <p>This method is used to initialize {@link TestSourceModelPackage#eINSTANCE} when that field is accessed.
* Clients should not invoke it directly. Instead, they should simply access that field to obtain the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static TestSourceModelPackage init() {
if (isInited) return (TestSourceModelPackage)EPackage.Registry.INSTANCE.getEPackage(TestSourceModelPackage.eNS_URI);
// Obtain or create and register package
TestSourceModelPackageImpl theTestSourceModelPackage = (TestSourceModelPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof TestSourceModelPackageImpl ? EPackage.Registry.INSTANCE.get(eNS_URI) : new TestSourceModelPackageImpl());
isInited = true;
// Create package meta-data objects
theTestSourceModelPackage.createPackageContents();
// Initialize created meta-data
theTestSourceModelPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theTestSourceModelPackage.freeze();
// Update the registry and return the package
EPackage.Registry.INSTANCE.put(TestSourceModelPackage.eNS_URI, theTestSourceModelPackage);
return theTestSourceModelPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getRootClass() {
return rootClassEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRootClass_AnAttribute1() {
return (EAttribute)rootClassEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRootClass_NormalReference() {
return (EReference)rootClassEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getRootClass_Any() {
return (EAttribute)rootClassEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getRootClass_NonManyReference() {
return (EReference)rootClassEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getClassWithListFeatures() {
return classWithListFeaturesEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getClassWithListFeatures_ListFeature1() {
return (EReference)classWithListFeaturesEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getClassWithListFeatures_ListFeature2() {
return (EReference)classWithListFeaturesEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getClassWithListFeatures_AnAttribute1() {
return (EAttribute)classWithListFeaturesEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getListFeatureElementClass1() {
return listFeatureElementClass1EClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass1_Name() {
return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getListFeatureElementClass1_ListFeature3() {
return (EReference)listFeatureElementClass1EClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass1_AnAttributeOfFeatureClass1() {
return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass1_Any() {
return (EAttribute)listFeatureElementClass1EClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getListFeatureElementClass2() {
return listFeatureElementClass2EClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass2_Name() {
return (EAttribute)listFeatureElementClass2EClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass2_AnAttributeOfFeatureClass2() {
return (EAttribute)listFeatureElementClass2EClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getListFeatureElementClass3() {
return listFeatureElementClass3EClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass3_Name() {
return (EAttribute)listFeatureElementClass3EClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getListFeatureElementClass3_AnAttributeOfFeatureClass3() {
return (EAttribute)listFeatureElementClass3EClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TestSourceModelFactory getTestSourceModelFactory() {
return (TestSourceModelFactory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
// Create classes and their features
rootClassEClass = createEClass(ROOT_CLASS);
createEAttribute(rootClassEClass, ROOT_CLASS__AN_ATTRIBUTE1);
createEReference(rootClassEClass, ROOT_CLASS__NORMAL_REFERENCE);
createEAttribute(rootClassEClass, ROOT_CLASS__ANY);
createEReference(rootClassEClass, ROOT_CLASS__NON_MANY_REFERENCE);
classWithListFeaturesEClass = createEClass(CLASS_WITH_LIST_FEATURES);
createEReference(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__LIST_FEATURE1);
createEReference(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__LIST_FEATURE2);
createEAttribute(classWithListFeaturesEClass, CLASS_WITH_LIST_FEATURES__AN_ATTRIBUTE1);
listFeatureElementClass1EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS1);
createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__NAME);
createEReference(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__LIST_FEATURE3);
createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__AN_ATTRIBUTE_OF_FEATURE_CLASS1);
createEAttribute(listFeatureElementClass1EClass, LIST_FEATURE_ELEMENT_CLASS1__ANY);
listFeatureElementClass2EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS2);
createEAttribute(listFeatureElementClass2EClass, LIST_FEATURE_ELEMENT_CLASS2__NAME);
createEAttribute(listFeatureElementClass2EClass, LIST_FEATURE_ELEMENT_CLASS2__AN_ATTRIBUTE_OF_FEATURE_CLASS2);
listFeatureElementClass3EClass = createEClass(LIST_FEATURE_ELEMENT_CLASS3);
createEAttribute(listFeatureElementClass3EClass, LIST_FEATURE_ELEMENT_CLASS3__NAME);
createEAttribute(listFeatureElementClass3EClass, LIST_FEATURE_ELEMENT_CLASS3__AN_ATTRIBUTE_OF_FEATURE_CLASS3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents() {
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
// Initialize classes and features; add operations and parameters
initEClass(rootClassEClass, RootClass.class, "RootClass", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getRootClass_AnAttribute1(), ecorePackage.getEString(), "anAttribute1", null, 0, 1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getRootClass_NormalReference(), this.getClassWithListFeatures(), null, "normalReference", null, 0, -1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getRootClass_Any(), ecorePackage.getEFeatureMapEntry(), "any", null, 0, -1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getRootClass_NonManyReference(), this.getClassWithListFeatures(), null, "nonManyReference", null, 0, 1, RootClass.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(classWithListFeaturesEClass, ClassWithListFeatures.class, "ClassWithListFeatures", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getClassWithListFeatures_ListFeature1(), this.getListFeatureElementClass1(), null, "listFeature1", null, 0, -1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getClassWithListFeatures_ListFeature2(), this.getListFeatureElementClass2(), null, "listFeature2", null, 0, -1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getClassWithListFeatures_AnAttribute1(), ecorePackage.getEInt(), "anAttribute1", null, 0, 1, ClassWithListFeatures.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(listFeatureElementClass1EClass, ListFeatureElementClass1.class, "ListFeatureElementClass1", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getListFeatureElementClass1_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getListFeatureElementClass1_ListFeature3(), this.getListFeatureElementClass3(), null, "listFeature3", null, 0, -1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass1_AnAttributeOfFeatureClass1(), ecorePackage.getEString(), "anAttributeOfFeatureClass1", null, 0, 1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass1_Any(), ecorePackage.getEFeatureMapEntry(), "any", null, 0, -1, ListFeatureElementClass1.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(listFeatureElementClass2EClass, ListFeatureElementClass2.class, "ListFeatureElementClass2", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getListFeatureElementClass2_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass2.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass2_AnAttributeOfFeatureClass2(), ecorePackage.getEString(), "anAttributeOfFeatureClass2", null, 0, 1, ListFeatureElementClass2.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(listFeatureElementClass3EClass, ListFeatureElementClass3.class, "ListFeatureElementClass3", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getListFeatureElementClass3_Name(), ecorePackage.getEString(), "name", null, 0, 1, ListFeatureElementClass3.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getListFeatureElementClass3_AnAttributeOfFeatureClass3(), ecorePackage.getEString(), "anAttributeOfFeatureClass3", null, 0, 1, ListFeatureElementClass3.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
// Create resource
createResource(eNS_URI);
// Create annotations
// http:///org/eclipse/emf/ecore/util/ExtendedMetaData
createExtendedMetaDataAnnotations();
}
/**
* Initializes the annotations for <b>http:///org/eclipse/emf/ecore/util/ExtendedMetaData</b>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void createExtendedMetaDataAnnotations() {
String source = "http:///org/eclipse/emf/ecore/util/ExtendedMetaData";
addAnnotation
(getRootClass_Any(),
source,
new String[] {
"kind", "elementWildcard",
"name", ":1",
"processing", "lax",
"wildcards", "##any"
});
addAnnotation
(getListFeatureElementClass1_Any(),
source,
new String[] {
"kind", "elementWildcard",
"name", ":1",
"processing", "lax",
"wildcards", "##any"
});
}
} //TestSourceModelPackageImpl
| markus1978/clickwatch | util/de.hub.specificmodels.test/src-gen/de/hub/specificmodels/tests/testsourcemodel/impl/TestSourceModelPackageImpl.java | Java | apache-2.0 | 16,757 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.typeCook.deductive.util;
import com.intellij.psi.*;
import com.intellij.refactoring.typeCook.Settings;
import com.intellij.refactoring.typeCook.Util;
import java.util.HashSet;
/**
* @author db
*/
public class VictimCollector extends Visitor {
final HashSet<PsiElement> myVictims = new HashSet<PsiElement>();
final PsiElement[] myElements;
final Settings mySettings;
public VictimCollector(final PsiElement[] elements, final Settings settings) {
myElements = elements;
mySettings = settings;
}
private void testNAdd(final PsiElement element, final PsiType t) {
if (Util.isRaw(t, mySettings)) {
if (element instanceof PsiNewExpression && t.getCanonicalText().equals("java.lang.Object")){
return;
}
myVictims.add(element);
}
}
@Override public void visitLocalVariable(final PsiLocalVariable variable) {
testNAdd(variable, variable.getType());
super.visitLocalVariable(variable);
}
@Override public void visitForeachStatement(final PsiForeachStatement statement) {
super.visitForeachStatement(statement);
final PsiParameter parameter = statement.getIterationParameter();
testNAdd(parameter, parameter.getType());
}
@Override public void visitField(final PsiField field) {
testNAdd(field, field.getType());
super.visitField(field);
}
@Override public void visitMethod(final PsiMethod method) {
final PsiParameter[] parms = method.getParameterList().getParameters();
for (PsiParameter parm : parms) {
testNAdd(parm, parm.getType());
}
if (Util.isRaw(method.getReturnType(), mySettings)) {
myVictims.add(method);
}
final PsiCodeBlock body = method.getBody();
if (body != null) {
body.accept(this);
}
}
@Override public void visitNewExpression(final PsiNewExpression expression) {
if (expression.getClassReference() != null) {
testNAdd(expression, expression.getType());
}
super.visitNewExpression(expression);
}
@Override public void visitTypeCastExpression (final PsiTypeCastExpression cast){
final PsiTypeElement typeElement = cast.getCastType();
if (typeElement != null) {
testNAdd(cast, typeElement.getType());
}
super.visitTypeCastExpression(cast);
}
@Override public void visitReferenceExpression(final PsiReferenceExpression expression) {
}
@Override public void visitFile(PsiFile file) {
if (file instanceof PsiJavaFile) {
super.visitFile(file);
}
}
public HashSet<PsiElement> getVictims() {
for (PsiElement element : myElements) {
element.accept(this);
}
return myVictims;
}
}
| joewalnes/idea-community | java/java-impl/src/com/intellij/refactoring/typeCook/deductive/util/VictimCollector.java | Java | apache-2.0 | 3,283 |
/**
* Copyright 2002-2016 xiaoyuepeng
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* @author xiaoyuepeng <[email protected]>
*/
package com.xyp260466.dubbo.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Created by xyp on 16-5-9.
*/
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Documented
public @interface Consumer {
String value() default "";
}
| xyp260466/dubbo-lite | dubbo-spring/src/main/java/com/xyp260466/dubbo/annotation/Consumer.java | Java | apache-2.0 | 1,109 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import org.apache.commons.logging.*;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.hdfs.server.common.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.ipc.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.http.HttpServer;
import org.apache.hadoop.net.NetUtils;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.hadoop.metrics.jvm.JvmMetrics;
/**********************************************************
* The Secondary NameNode is a helper to the primary NameNode. The Secondary is
* responsible for supporting periodic checkpoints of the HDFS metadata. The
* current design allows only one Secondary NameNode per HDFs cluster.
*
* The Secondary NameNode is a daemon that periodically wakes up (determined by
* the schedule specified in the configuration), triggers a periodic checkpoint
* and then goes back to sleep. The Secondary NameNode uses the ClientProtocol
* to talk to the primary NameNode.
*
**********************************************************/
public class SecondaryNameNode implements Runnable {
public static final Log LOG = LogFactory.getLog(SecondaryNameNode.class
.getName());
private String fsName;
private CheckpointStorage checkpointImage;
private NamenodeProtocol namenode;
private Configuration conf;
private InetSocketAddress nameNodeAddr;
private volatile boolean shouldRun;
private HttpServer infoServer;
private int infoPort;
private String infoBindAddress;
private Collection<File> checkpointDirs;
private Collection<File> checkpointEditsDirs;
private long checkpointPeriod; // in seconds
private long checkpointSize; // size (in MB) of current Edit Log
/**
* Utility class to facilitate junit test error simulation.
*/
static class ErrorSimulator {
private static boolean[] simulation = null; // error simulation events
static void initializeErrorSimulationEvent(int numberOfEvents) {
simulation = new boolean[numberOfEvents];
for (int i = 0; i < numberOfEvents; i++) {
simulation[i] = false;
}
}
static boolean getErrorSimulation(int index) {
if (simulation == null)
return false;
assert (index < simulation.length);
return simulation[index];
}
static void setErrorSimulation(int index) {
assert (index < simulation.length);
simulation[index] = true;
}
static void clearErrorSimulation(int index) {
assert (index < simulation.length);
simulation[index] = false;
}
}
FSImage getFSImage() {
return checkpointImage;
}
/**
* Create a connection to the primary namenode.
*/
public SecondaryNameNode(Configuration conf) throws IOException {
try {
initialize(conf);
} catch (IOException e) {
shutdown();
throw e;
}
}
/**
* Initialize SecondaryNameNode.
*/
private void initialize(Configuration conf) throws IOException {
// initiate Java VM metrics
JvmMetrics.init("SecondaryNameNode", conf.get("session.id"));
// Create connection to the namenode.
shouldRun = true;
nameNodeAddr = NameNode.getAddress(conf);
this.conf = conf;
this.namenode = (NamenodeProtocol) RPC.waitForProxy(
NamenodeProtocol.class, NamenodeProtocol.versionID,
nameNodeAddr, conf);
// initialize checkpoint directories
fsName = getInfoServer();
checkpointDirs = FSImage.getCheckpointDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf,
"/tmp/hadoop/dfs/namesecondary");
checkpointImage = new CheckpointStorage();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
// Initialize other scheduling parameters from the configuration
checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
checkpointSize = conf.getLong("fs.checkpoint.size", 4194304);
// initialize the webserver for uploading files.
String infoAddr = NetUtils.getServerAddress(conf,
"dfs.secondary.info.bindAddress", "dfs.secondary.info.port",
"dfs.secondary.http.address");
InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
infoBindAddress = infoSocAddr.getHostName();
int tmpInfoPort = infoSocAddr.getPort();
infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort,
tmpInfoPort == 0, conf);
infoServer.setAttribute("name.system.image", checkpointImage);
this.infoServer.setAttribute("name.conf", conf);
infoServer.addInternalServlet("getimage", "/getimage",
GetImageServlet.class);
infoServer.start();
// The web-server port can be ephemeral... ensure we have the correct
// info
infoPort = infoServer.getPort();
conf
.set("dfs.secondary.http.address", infoBindAddress + ":"
+ infoPort);
LOG.info("Secondary Web-server up at: " + infoBindAddress + ":"
+ infoPort);
LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " + "("
+ checkpointPeriod / 60 + " min)");
LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " + "("
+ checkpointSize / 1024 + " KB)");
}
/**
* Shut down this instance of the datanode. Returns only after shutdown is
* complete.
*/
public void shutdown() {
shouldRun = false;
try {
if (infoServer != null)
infoServer.stop();
} catch (Exception e) {
LOG.warn("Exception shutting down SecondaryNameNode", e);
}
try {
if (checkpointImage != null)
checkpointImage.close();
} catch (IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
}
//
// The main work loop
//
public void run() {
//
// Poll the Namenode (once every 5 minutes) to find the size of the
// pending edit log.
//
long period = 5 * 60; // 5 minutes
long lastCheckpointTime = 0;
if (checkpointPeriod < period) {
period = checkpointPeriod;
}
while (shouldRun) {
try {
Thread.sleep(1000 * period);
} catch (InterruptedException ie) {
// do nothing
}
if (!shouldRun) {
break;
}
try {
long now = System.currentTimeMillis();
long size = namenode.getEditLogSize();
if (size >= checkpointSize
|| now >= lastCheckpointTime + 1000 * checkpointPeriod) {
doCheckpoint();
lastCheckpointTime = now;
}
} catch (IOException e) {
LOG.error("Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
} catch (Throwable e) {
LOG.error("Throwable Exception in doCheckpoint: ");
LOG.error(StringUtils.stringifyException(e));
e.printStackTrace();
Runtime.getRuntime().exit(-1);
}
}
}
/**
* Download <code>fsimage</code> and <code>edits</code> files from the
* name-node.
*
* @throws IOException
*/
private void downloadCheckpointFiles(CheckpointSignature sig)
throws IOException {
checkpointImage.cTime = sig.cTime;
checkpointImage.checkpointTime = sig.checkpointTime;
// get fsimage
String fileid = "getimage=1";
File[] srcNames = checkpointImage.getImageFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size "
+ srcNames[0].length() + " bytes.");
// get edits file
fileid = "getedit=1";
srcNames = checkpointImage.getEditsFiles();
assert srcNames.length > 0 : "No checkpoint targets.";
TransferFsImage.getFileClient(fsName, fileid, srcNames);
LOG.info("Downloaded file " + srcNames[0].getName() + " size "
+ srcNames[0].length() + " bytes.");
checkpointImage.checkpointUploadDone();
}
/**
* Copy the new fsimage into the NameNode
*/
private void putFSImage(CheckpointSignature sig) throws IOException {
String fileid = "putimage=1&port=" + infoPort + "&machine="
+ InetAddress.getLocalHost().getHostAddress() + "&token="
+ sig.toString();
LOG.info("Posted URL " + fsName + fileid);
TransferFsImage.getFileClient(fsName, fileid, (File[]) null);
}
/**
* Returns the Jetty server that the Namenode is listening on.
*/
private String getInfoServer() throws IOException {
URI fsName = FileSystem.getDefaultUri(conf);
if (!"hdfs".equals(fsName.getScheme())) {
throw new IOException("This is not a DFS");
}
return NetUtils.getServerAddress(conf, "dfs.info.bindAddress",
"dfs.info.port", "dfs.http.address");
}
/**
* Create a new checkpoint
*/
void doCheckpoint() throws IOException {
// Do the required initialization of the merge work area.
startCheckpoint();
// Tell the namenode to start logging transactions in a new edit file
// Retuns a token that would be used to upload the merged image.
CheckpointSignature sig = (CheckpointSignature) namenode.rollEditLog();
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(0)) {
throw new IOException("Simulating error0 "
+ "after creating edits.new");
}
downloadCheckpointFiles(sig); // Fetch fsimage and edits
doMerge(sig); // Do the merge
//
// Upload the new image into the NameNode. Then tell the Namenode
// to make this new uploaded image as the most current image.
//
putFSImage(sig);
// error simulation code for junit test
if (ErrorSimulator.getErrorSimulation(1)) {
throw new IOException("Simulating error1 "
+ "after uploading new image to NameNode");
}
namenode.rollFsImage();
checkpointImage.endCheckpoint();
LOG.warn("Checkpoint done. New Image Size: "
+ checkpointImage.getFsImageName().length());
}
private void startCheckpoint() throws IOException {
checkpointImage.unlockAll();
checkpointImage.getEditLog().close();
checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs);
checkpointImage.startCheckpoint();
}
/**
* Merge downloaded image and edits and write the new image into current
* storage directory.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
FSNamesystem namesystem = new FSNamesystem(checkpointImage, conf);
assert namesystem.dir.fsImage == checkpointImage;
checkpointImage.doMerge(sig);
}
/**
* @param argv
* The parameters passed to this program.
* @exception Exception
* if the filesystem does not exist.
* @return 0 on success, non zero on error.
*/
private int processArgs(String[] argv) throws Exception {
if (argv.length < 1) {
printUsage("");
return -1;
}
int exitCode = -1;
int i = 0;
String cmd = argv[i++];
//
// verify that we have enough command line parameters
//
if ("-geteditsize".equals(cmd)) {
if (argv.length != 1) {
printUsage(cmd);
return exitCode;
}
} else if ("-checkpoint".equals(cmd)) {
if (argv.length != 1 && argv.length != 2) {
printUsage(cmd);
return exitCode;
}
if (argv.length == 2 && !"force".equals(argv[i])) {
printUsage(cmd);
return exitCode;
}
}
exitCode = 0;
try {
if ("-checkpoint".equals(cmd)) {
long size = namenode.getEditLogSize();
if (size >= checkpointSize || argv.length == 2
&& "force".equals(argv[i])) {
doCheckpoint();
} else {
System.err.println("EditLog size " + size + " bytes is "
+ "smaller than configured checkpoint " + "size "
+ checkpointSize + " bytes.");
System.err.println("Skipping checkpoint.");
}
} else if ("-geteditsize".equals(cmd)) {
long size = namenode.getEditLogSize();
System.out.println("EditLog size is " + size + " bytes");
} else {
exitCode = -1;
LOG.error(cmd.substring(1) + ": Unknown command");
printUsage("");
}
} catch (RemoteException e) {
//
// This is a error returned by hadoop server. Print
// out the first line of the error mesage, ignore the stack trace.
exitCode = -1;
try {
String[] content;
content = e.getLocalizedMessage().split("\n");
LOG.error(cmd.substring(1) + ": " + content[0]);
} catch (Exception ex) {
LOG.error(cmd.substring(1) + ": " + ex.getLocalizedMessage());
}
} catch (IOException e) {
//
// IO exception encountered locally.
//
exitCode = -1;
LOG.error(cmd.substring(1) + ": " + e.getLocalizedMessage());
} finally {
// Does the RPC connection need to be closed?
}
return exitCode;
}
/**
* Displays format of commands.
*
* @param cmd
* The command that is being executed.
*/
private void printUsage(String cmd) {
if ("-geteditsize".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-geteditsize]");
} else if ("-checkpoint".equals(cmd)) {
System.err.println("Usage: java SecondaryNameNode"
+ " [-checkpoint [force]]");
} else {
System.err.println("Usage: java SecondaryNameNode "
+ "[-checkpoint [force]] " + "[-geteditsize] ");
}
}
/**
* main() has some simple utility methods.
*
* @param argv
* Command line parameters.
* @exception Exception
* if the filesystem does not exist.
*/
public static void main(String[] argv) throws Exception {
StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);
Configuration tconf = new Configuration();
if (argv.length >= 1) {
SecondaryNameNode secondary = new SecondaryNameNode(tconf);
int ret = secondary.processArgs(argv);
System.exit(ret);
}
// Create a never ending deamon
Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));
checkpointThread.start();
}
static class CheckpointStorage extends FSImage {
/**
*/
CheckpointStorage() throws IOException {
super();
}
@Override
public boolean isConversionNeeded(StorageDirectory sd) {
return false;
}
/**
* Analyze checkpoint directories. Create directories if they do not
* exist. Recover from an unsuccessful checkpoint is necessary.
*
* @param dataDirs
* @param editsDirs
* @throws IOException
*/
void recoverCreate(Collection<File> dataDirs, Collection<File> editsDirs)
throws IOException {
Collection<File> tempDataDirs = new ArrayList<File>(dataDirs);
Collection<File> tempEditsDirs = new ArrayList<File>(editsDirs);
this.storageDirs = new ArrayList<StorageDirectory>();
setStorageDirectories(tempDataDirs, tempEditsDirs);
for (Iterator<StorageDirectory> it = dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
boolean isAccessible = true;
try { // create directories if don't exist yet
if (!sd.getRoot().mkdirs()) {
// do nothing, directory is already created
}
} catch (SecurityException se) {
isAccessible = false;
}
if (!isAccessible)
throw new InconsistentFSStateException(sd.getRoot(),
"cannot access checkpoint directory.");
StorageState curState;
try {
curState = sd
.analyzeStorage(HdfsConstants.StartupOption.REGULAR);
// sd is locked but not opened
switch (curState) {
case NON_EXISTENT:
// fail if any of the configured checkpoint dirs are
// inaccessible
throw new InconsistentFSStateException(sd.getRoot(),
"checkpoint directory does not exist or is not accessible.");
case NOT_FORMATTED:
break; // it's ok since initially there is no current
// and VERSION
case NORMAL:
break;
default: // recovery is possible
sd.doRecover(curState);
}
} catch (IOException ioe) {
sd.unlock();
throw ioe;
}
}
}
/**
* Prepare directories for a new checkpoint.
* <p>
* Rename <code>current</code> to <code>lastcheckpoint.tmp</code> and
* recreate <code>current</code>.
*
* @throws IOException
*/
void startCheckpoint() throws IOException {
for (StorageDirectory sd : storageDirs) {
File curDir = sd.getCurrentDir();
File tmpCkptDir = sd.getLastCheckpointTmp();
assert !tmpCkptDir.exists() : tmpCkptDir.getName()
+ " directory must not exist.";
if (curDir.exists()) {
// rename current to tmp
rename(curDir, tmpCkptDir);
}
if (!curDir.mkdir())
throw new IOException("Cannot create directory " + curDir);
}
}
void endCheckpoint() throws IOException {
for (StorageDirectory sd : storageDirs) {
File tmpCkptDir = sd.getLastCheckpointTmp();
File prevCkptDir = sd.getPreviousCheckpoint();
// delete previous dir
if (prevCkptDir.exists())
deleteDir(prevCkptDir);
// rename tmp to previous
if (tmpCkptDir.exists())
rename(tmpCkptDir, prevCkptDir);
}
}
/**
* Merge image and edits, and verify consistency with the signature.
*/
private void doMerge(CheckpointSignature sig) throws IOException {
getEditLog().open();
StorageDirectory sdName = null;
StorageDirectory sdEdits = null;
Iterator<StorageDirectory> it = null;
it = dirIterator(NameNodeDirType.IMAGE);
if (it.hasNext())
sdName = it.next();
it = dirIterator(NameNodeDirType.EDITS);
if (it.hasNext())
sdEdits = it.next();
if ((sdName == null) || (sdEdits == null))
throw new IOException("Could not locate checkpoint directories");
loadFSImage(FSImage.getImageFile(sdName, NameNodeFile.IMAGE));
loadFSEdits(sdEdits);
sig.validateStorageInfo(this);
saveFSImage();
}
}
}
| shot/hadoop-source-reading | src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java | Java | apache-2.0 | 18,270 |
package me.soulmachine;
import org.jruby.embed.ScriptingContainer;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
* A simple JRuby example to execute Python scripts from Java.
*/
final class JRubyExample {
private JRubyExample() {}
/**
* Main entrypoint.
*
* @param args arguments
* @throws ScriptException ScriptException
*/
public static void main(final String[] args) throws ScriptException {
listEngines();
final String rubyHelloWord = "puts 'Hello World from JRuby!'";
// First way: Use built-in ScriptEngine from JDK
{
final ScriptEngineManager mgr = new ScriptEngineManager();
final ScriptEngine pyEngine = mgr.getEngineByName("ruby");
try {
pyEngine.eval(rubyHelloWord);
} catch (ScriptException ex) {
ex.printStackTrace();
}
}
// Second way: Use ScriptingContainer() from JRuby
{
final ScriptingContainer scriptingContainer = new ScriptingContainer();
scriptingContainer.runScriptlet(rubyHelloWord);
}
// Call Ruby Methods from Java
{
final ScriptingContainer scriptingContainer = new ScriptingContainer();
final String rubyMethod = "def myAdd(a,b)\n\treturn a+b\nend";
final Object receiver = scriptingContainer.runScriptlet(rubyMethod);
final Object[] arguments = new Object[2];
arguments[0] = Integer.valueOf(6);
arguments[1] = Integer.valueOf(4);
final Integer result = scriptingContainer.callMethod(receiver, "myAdd",
arguments, Integer.class);
System.out.println("Result: " + result);
}
}
/**
* Display all script engines.
*/
public static void listEngines() {
final ScriptEngineManager mgr = new ScriptEngineManager();
final List<ScriptEngineFactory> factories =
mgr.getEngineFactories();
for (final ScriptEngineFactory factory: factories) {
System.out.println("ScriptEngineFactory Info");
final String engName = factory.getEngineName();
final String engVersion = factory.getEngineVersion();
final String langName = factory.getLanguageName();
final String langVersion = factory.getLanguageVersion();
System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion);
final List<String> engNames = factory.getNames();
for (final String name: engNames) {
System.out.printf("\tEngine Alias: %s\n", name);
}
System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion);
}
}
}
| soulmachine/JRubyExample | JRubyExample/src/main/java/me/soulmachine/JRubyExample.java | Java | apache-2.0 | 2,633 |
package com.arthurb.iterator.dinermergergery;
import java.util.Iterator;
/**
* Created by Blackwood on 07.03.2016 18:16.
*/
public class DinerMenu implements Menu {
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems;
public DinerMenu() {
menuItems = new MenuItem[MAX_ITEMS];
addItem("Vegetarian BLT", "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99);
addItem("BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99);
addItem("Soup of the day", "Soup of the day, with a side of potato salad", false, 2.99);
addItem("Hotdog", "A got dog, with saurkraut, relish, onions, topped with cheese", false, 3.05);
addItem("Steamed Veggies and Brown Rice", "Steamed vegetables over brown rice", true, 3.99);
addItem("Pasta", "Spaghetti with Marinara Sauce, and a slice of sourdough bread", true, 3.89);
}
private void addItem(String name, String description, boolean vegetarian, double price) {
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
if (numberOfItems >= MAX_ITEMS) { // Ограничиваем размер меню, чтобы не запоминать слишком много рецептов
System.err.println("Sorry, menu is full! Can't add item to menu");
} else {
menuItems[numberOfItems] = menuItem;
numberOfItems = numberOfItems + 1;
}
}
public Iterator createIterator() {
return new DinerMenuIterator(menuItems);
}
}
| NeverNight/SimplesPatterns.Java | src/com/arthurb/iterator/dinermergergery/DinerMenu.java | Java | apache-2.0 | 1,583 |
package org.apache.helix.controller.rebalancer.waged.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.helix.HelixException;
import org.apache.helix.controller.rebalancer.util.WagedValidationUtil;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.InstanceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class represents a possible allocation of the replication.
* Note that any usage updates to the AssignableNode are not thread safe.
*/
public class AssignableNode implements Comparable<AssignableNode> {
private static final Logger LOG = LoggerFactory.getLogger(AssignableNode.class.getName());
// Immutable Instance Properties
private final String _instanceName;
private final String _faultZone;
// maximum number of the partitions that can be assigned to the instance.
private final int _maxPartition;
private final ImmutableSet<String> _instanceTags;
private final ImmutableMap<String, List<String>> _disabledPartitionsMap;
private final ImmutableMap<String, Integer> _maxAllowedCapacity;
// Mutable (Dynamic) Instance Properties
// A map of <resource name, <partition name, replica>> that tracks the replicas assigned to the
// node.
private Map<String, Map<String, AssignableReplica>> _currentAssignedReplicaMap;
// A map of <capacity key, capacity value> that tracks the current available node capacity
private Map<String, Integer> _remainingCapacity;
/**
* Update the node with a ClusterDataCache. This resets the current assignment and recalculates
* currentCapacity.
* NOTE: While this is required to be used in the constructor, this can also be used when the
* clusterCache needs to be
* refreshed. This is under the assumption that the capacity mappings of InstanceConfig and
* ResourceConfig could
* subject to change. If the assumption is no longer true, this function should become private.
*/
AssignableNode(ClusterConfig clusterConfig, InstanceConfig instanceConfig, String instanceName) {
_instanceName = instanceName;
Map<String, Integer> instanceCapacity = fetchInstanceCapacity(clusterConfig, instanceConfig);
_faultZone = computeFaultZone(clusterConfig, instanceConfig);
_instanceTags = ImmutableSet.copyOf(instanceConfig.getTags());
_disabledPartitionsMap = ImmutableMap.copyOf(instanceConfig.getDisabledPartitionsMap());
// make a copy of max capacity
_maxAllowedCapacity = ImmutableMap.copyOf(instanceCapacity);
_remainingCapacity = new HashMap<>(instanceCapacity);
_maxPartition = clusterConfig.getMaxPartitionsPerInstance();
_currentAssignedReplicaMap = new HashMap<>();
}
/**
* This function should only be used to assign a set of new partitions that are not allocated on
* this node. It's because the any exception could occur at the middle of batch assignment and the
* previous finished assignment cannot be reverted
* Using this function avoids the overhead of updating capacity repeatedly.
*/
void assignInitBatch(Collection<AssignableReplica> replicas) {
Map<String, Integer> totalPartitionCapacity = new HashMap<>();
for (AssignableReplica replica : replicas) {
// TODO: the exception could occur in the middle of for loop and the previous added records cannot be reverted
addToAssignmentRecord(replica);
// increment the capacity requirement according to partition's capacity configuration.
for (Map.Entry<String, Integer> capacity : replica.getCapacity().entrySet()) {
totalPartitionCapacity.compute(capacity.getKey(),
(key, totalValue) -> (totalValue == null) ? capacity.getValue()
: totalValue + capacity.getValue());
}
}
// Update the global state after all single replications' calculation is done.
for (String capacityKey : totalPartitionCapacity.keySet()) {
updateRemainingCapacity(capacityKey, totalPartitionCapacity.get(capacityKey));
}
}
/**
* Assign a replica to the node.
* @param assignableReplica - the replica to be assigned
*/
void assign(AssignableReplica assignableReplica) {
addToAssignmentRecord(assignableReplica);
assignableReplica.getCapacity().entrySet().stream()
.forEach(capacity -> updateRemainingCapacity(capacity.getKey(), capacity.getValue()));
}
/**
* Release a replica from the node.
* If the replication is not on this node, the assignable node is not updated.
* @param replica - the replica to be released
*/
void release(AssignableReplica replica)
throws IllegalArgumentException {
String resourceName = replica.getResourceName();
String partitionName = replica.getPartitionName();
// Check if the release is necessary
if (!_currentAssignedReplicaMap.containsKey(resourceName)) {
LOG.warn("Resource {} is not on node {}. Ignore the release call.", resourceName,
getInstanceName());
return;
}
Map<String, AssignableReplica> partitionMap = _currentAssignedReplicaMap.get(resourceName);
if (!partitionMap.containsKey(partitionName) || !partitionMap.get(partitionName)
.equals(replica)) {
LOG.warn("Replica {} is not assigned to node {}. Ignore the release call.",
replica.toString(), getInstanceName());
return;
}
AssignableReplica removedReplica = partitionMap.remove(partitionName);
removedReplica.getCapacity().entrySet().stream()
.forEach(entry -> updateRemainingCapacity(entry.getKey(), -1 * entry.getValue()));
}
/**
* @return A set of all assigned replicas on the node.
*/
Set<AssignableReplica> getAssignedReplicas() {
return _currentAssignedReplicaMap.values().stream()
.flatMap(replicaMap -> replicaMap.values().stream()).collect(Collectors.toSet());
}
/**
* @return The current assignment in a map of <resource name, set of partition names>
*/
Map<String, Set<String>> getAssignedPartitionsMap() {
Map<String, Set<String>> assignmentMap = new HashMap<>();
for (String resourceName : _currentAssignedReplicaMap.keySet()) {
assignmentMap.put(resourceName, _currentAssignedReplicaMap.get(resourceName).keySet());
}
return assignmentMap;
}
/**
* @param resource Resource name
* @return A set of the current assigned replicas' partition names in the specified resource.
*/
public Set<String> getAssignedPartitionsByResource(String resource) {
return _currentAssignedReplicaMap.getOrDefault(resource, Collections.emptyMap()).keySet();
}
/**
* @param resource Resource name
* @return A set of the current assigned replicas' partition names with the top state in the
* specified resource.
*/
Set<String> getAssignedTopStatePartitionsByResource(String resource) {
return _currentAssignedReplicaMap.getOrDefault(resource, Collections.emptyMap()).entrySet()
.stream().filter(partitionEntry -> partitionEntry.getValue().isReplicaTopState())
.map(partitionEntry -> partitionEntry.getKey()).collect(Collectors.toSet());
}
/**
* @return The total count of assigned top state partitions.
*/
public int getAssignedTopStatePartitionsCount() {
return (int) _currentAssignedReplicaMap.values().stream()
.flatMap(replicaMap -> replicaMap.values().stream())
.filter(AssignableReplica::isReplicaTopState).count();
}
/**
* @return The total count of assigned replicas.
*/
public int getAssignedReplicaCount() {
return _currentAssignedReplicaMap.values().stream().mapToInt(Map::size).sum();
}
/**
* @return The current available capacity.
*/
public Map<String, Integer> getRemainingCapacity() {
return _remainingCapacity;
}
/**
* @return A map of <capacity category, capacity number> that describes the max capacity of the
* node.
*/
public Map<String, Integer> getMaxCapacity() {
return _maxAllowedCapacity;
}
/**
* Return the most concerning capacity utilization number for evenly partition assignment.
* The method dynamically calculates the projected highest utilization number among all the
* capacity categories assuming the new capacity usage is added to the node.
* For example, if the current node usage is {CPU: 0.9, MEM: 0.4, DISK: 0.6}. Then this call shall
* return 0.9.
* @param newUsage the proposed new additional capacity usage.
* @return The highest utilization number of the node among all the capacity category.
*/
public float getProjectedHighestUtilization(Map<String, Integer> newUsage) {
float highestCapacityUtilization = 0;
for (String capacityKey : _maxAllowedCapacity.keySet()) {
float capacityValue = _maxAllowedCapacity.get(capacityKey);
float utilization = (capacityValue - _remainingCapacity.get(capacityKey) + newUsage
.getOrDefault(capacityKey, 0)) / capacityValue;
highestCapacityUtilization = Math.max(highestCapacityUtilization, utilization);
}
return highestCapacityUtilization;
}
public String getInstanceName() {
return _instanceName;
}
public Set<String> getInstanceTags() {
return _instanceTags;
}
public String getFaultZone() {
return _faultZone;
}
public boolean hasFaultZone() {
return _faultZone != null;
}
/**
* @return A map of <resource name, set of partition names> contains all the partitions that are
* disabled on the node.
*/
public Map<String, List<String>> getDisabledPartitionsMap() {
return _disabledPartitionsMap;
}
/**
* @return The max partition count that are allowed to be allocated on the node.
*/
public int getMaxPartition() {
return _maxPartition;
}
/**
* Computes the fault zone id based on the domain and fault zone type when topology is enabled.
* For example, when
* the domain is "zone=2, instance=testInstance" and the fault zone type is "zone", this function
* returns "2".
* If cannot find the fault zone type, this function leaves the fault zone id as the instance name.
* Note the WAGED rebalancer does not require full topology tree to be created. So this logic is
* simpler than the CRUSH based rebalancer.
*/
private String computeFaultZone(ClusterConfig clusterConfig, InstanceConfig instanceConfig) {
if (!clusterConfig.isTopologyAwareEnabled()) {
// Instance name is the default fault zone if topology awareness is false.
return instanceConfig.getInstanceName();
}
String topologyStr = clusterConfig.getTopology();
String faultZoneType = clusterConfig.getFaultZoneType();
if (topologyStr == null || faultZoneType == null) {
LOG.debug("Topology configuration is not complete. Topology define: {}, Fault Zone Type: {}",
topologyStr, faultZoneType);
// Use the instance name, or the deprecated ZoneId field (if exists) as the default fault
// zone.
String zoneId = instanceConfig.getZoneId();
return zoneId == null ? instanceConfig.getInstanceName() : zoneId;
} else {
// Get the fault zone information from the complete topology definition.
String[] topologyKeys = topologyStr.trim().split("/");
if (topologyKeys.length == 0 || Arrays.stream(topologyKeys)
.noneMatch(type -> type.equals(faultZoneType))) {
throw new HelixException(
"The configured topology definition is empty or does not contain the fault zone type.");
}
Map<String, String> domainAsMap = instanceConfig.getDomainAsMap();
StringBuilder faultZoneStringBuilder = new StringBuilder();
for (String key : topologyKeys) {
if (!key.isEmpty()) {
// if a key does not exist in the instance domain config, apply the default domain value.
faultZoneStringBuilder.append(domainAsMap.getOrDefault(key, "Default_" + key));
if (key.equals(faultZoneType)) {
break;
} else {
faultZoneStringBuilder.append('/');
}
}
}
return faultZoneStringBuilder.toString();
}
}
/**
* @throws HelixException if the replica has already been assigned to the node.
*/
private void addToAssignmentRecord(AssignableReplica replica) {
String resourceName = replica.getResourceName();
String partitionName = replica.getPartitionName();
if (_currentAssignedReplicaMap.containsKey(resourceName) && _currentAssignedReplicaMap
.get(resourceName).containsKey(partitionName)) {
throw new HelixException(String
.format("Resource %s already has a replica with state %s from partition %s on node %s",
replica.getResourceName(), replica.getReplicaState(), replica.getPartitionName(),
getInstanceName()));
} else {
_currentAssignedReplicaMap.computeIfAbsent(resourceName, key -> new HashMap<>())
.put(partitionName, replica);
}
}
private void updateRemainingCapacity(String capacityKey, int usage) {
if (!_remainingCapacity.containsKey(capacityKey)) {
//if the capacityKey belongs to replicas does not exist in the instance's capacity,
// it will be treated as if it has unlimited capacity of that capacityKey
return;
}
_remainingCapacity.put(capacityKey, _remainingCapacity.get(capacityKey) - usage);
}
/**
* Get and validate the instance capacity from instance config.
* @throws HelixException if any required capacity key is not configured in the instance config.
*/
private Map<String, Integer> fetchInstanceCapacity(ClusterConfig clusterConfig,
InstanceConfig instanceConfig) {
Map<String, Integer> instanceCapacity =
WagedValidationUtil.validateAndGetInstanceCapacity(clusterConfig, instanceConfig);
// Remove all the non-required capacity items from the map.
instanceCapacity.keySet().retainAll(clusterConfig.getInstanceCapacityKeys());
return instanceCapacity;
}
@Override
public int hashCode() {
return _instanceName.hashCode();
}
@Override
public int compareTo(AssignableNode o) {
return _instanceName.compareTo(o.getInstanceName());
}
@Override
public String toString() {
return _instanceName;
}
}
| lei-xia/helix | helix-core/src/main/java/org/apache/helix/controller/rebalancer/waged/model/AssignableNode.java | Java | apache-2.0 | 15,277 |
/*
* 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.taverna.workbench.views.graph.config;
import javax.swing.JPanel;
import org.apache.taverna.configuration.Configurable;
import org.apache.taverna.configuration.ConfigurationUIFactory;
/**
* ConfigurationFactory for the GraphViewConfiguration.
*
* @author David Withers
*/
public class GraphViewConfigurationUIFactory implements ConfigurationUIFactory {
private GraphViewConfiguration graphViewConfiguration;
@Override
public boolean canHandle(String uuid) {
return uuid.equals(getConfigurable().getUUID());
}
@Override
public JPanel getConfigurationPanel() {
return new GraphViewConfigurationPanel(graphViewConfiguration);
}
@Override
public Configurable getConfigurable() {
return graphViewConfiguration;
}
public void setGraphViewConfiguration(
GraphViewConfiguration graphViewConfiguration) {
this.graphViewConfiguration = graphViewConfiguration;
}
}
| ThilinaManamgoda/incubator-taverna-workbench | taverna-graph-view/src/main/java/org/apache/taverna/workbench/views/graph/config/GraphViewConfigurationUIFactory.java | Java | apache-2.0 | 1,714 |
/*
* 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.cloudsearchv2.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.cloudsearchv2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* UpdateDomainEndpointOptionsResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateDomainEndpointOptionsResultStaxUnmarshaller implements Unmarshaller<UpdateDomainEndpointOptionsResult, StaxUnmarshallerContext> {
public UpdateDomainEndpointOptionsResult unmarshall(StaxUnmarshallerContext context) throws Exception {
UpdateDomainEndpointOptionsResult updateDomainEndpointOptionsResult = new UpdateDomainEndpointOptionsResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 2;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return updateDomainEndpointOptionsResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("DomainEndpointOptions", targetDepth)) {
updateDomainEndpointOptionsResult.setDomainEndpointOptions(DomainEndpointOptionsStatusStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return updateDomainEndpointOptionsResult;
}
}
}
}
private static UpdateDomainEndpointOptionsResultStaxUnmarshaller instance;
public static UpdateDomainEndpointOptionsResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new UpdateDomainEndpointOptionsResultStaxUnmarshaller();
return instance;
}
}
| aws/aws-sdk-java | aws-java-sdk-cloudsearch/src/main/java/com/amazonaws/services/cloudsearchv2/model/transform/UpdateDomainEndpointOptionsResultStaxUnmarshaller.java | Java | apache-2.0 | 2,682 |
/*
* Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved.
*
* The Sun Project JXTA(TM) Software License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: "This product includes software
* developed by Sun Microsystems, Inc. for JXTA(TM) technology."
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
* not be used to endorse or promote products derived from this software
* without prior written permission. For written permission, please contact
* Project JXTA at http://www.jxta.org.
*
* 5. Products derived from this software may not be called "JXTA", nor may
* "JXTA" appear in their name, without prior written permission of Sun.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN
* MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* JXTA is a registered trademark of Sun Microsystems, Inc. in the United
* States and other countries.
*
* Please see the license information page at :
* <http://www.jxta.org/project/www/license.html> for instructions on use of
* the license in source files.
*
* ====================================================================
*
* This software consists of voluntary contributions made by many individuals
* on behalf of Project JXTA. For more information on Project JXTA, please see
* http://www.jxta.org.
*
* This license is based on the BSD license adopted by the Apache Foundation.
*/
package net.jxta.platform;
import net.jxta.document.Advertisement;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.MimeMediaType;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.StructuredDocumentUtils;
import net.jxta.document.XMLDocument;
import net.jxta.document.XMLElement;
import net.jxta.endpoint.EndpointAddress;
import net.jxta.id.ID;
import net.jxta.id.IDFactory;
import net.jxta.impl.membership.pse.PSEUtils;
import net.jxta.impl.membership.pse.PSEUtils.IssuerInfo;
import net.jxta.impl.peergroup.StdPeerGroup;
import net.jxta.impl.protocol.HTTPAdv;
import net.jxta.impl.protocol.PSEConfigAdv;
import net.jxta.impl.protocol.PeerGroupConfigAdv;
import net.jxta.impl.protocol.PlatformConfig;
import net.jxta.impl.protocol.RdvConfigAdv;
import net.jxta.impl.protocol.RdvConfigAdv.RendezVousConfiguration;
import net.jxta.impl.protocol.RelayConfigAdv;
import net.jxta.impl.protocol.TCPAdv;
import net.jxta.logging.Logging;
import net.jxta.peer.PeerID;
import net.jxta.peergroup.PeerGroup;
import net.jxta.peergroup.PeerGroupID;
import net.jxta.protocol.ConfigParams;
import net.jxta.protocol.TransportAdvertisement;
import javax.security.cert.CertificateException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.List;
import java.util.MissingResourceException;
import java.util.NoSuchElementException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Logger;
import net.jxta.impl.protocol.MulticastAdv;
/**
* NetworkConfigurator provides a simple programmatic interface for JXTA configuration.
* <p/>
* By default, it defines an edge configuration with TCP in auto mode w/port
* range 9701-9799, multicast enabled on group "224.0.1.85", and port 1234,
* HTTP transport with only outgoing enabled.
* <p/>
* By default a new PeerID is always generated. This can be overridden via
* {@link NetworkConfigurator#setPeerID} method or loading a PlatformConfig via
* {@link NetworkConfigurator#load}.
* <p/>
* A facility is provided to initialize a configuration by loading from an
* existing configuration. This provides limited platform configuration lifecycle
* management as well as configuration change management.
* <p/>
* Also by default, this class sets the default platform configurator to
* {@link net.jxta.impl.peergroup.NullConfigurator}. <code>NullConfigurator<code>
* is a no operation configurator intended to prevent any other configurators from
* being invoked.
* <p/>
* NetworkConfigurator makes use of classes from the {@code net.jxta.impl.*}
* packages. Applications are very strongly encouraged to avoid importing these
* classes as their interfaces may change without notice in future JXTA releases.
* The NetworkConfigurator API abstracts the configuration implementation details
* and will provide continuity and stability i.e. the NetworkConfigurator API
* won't change and it will automatically accommodate changes to service
* configuration.
* <p/>
* <em> Configuration example :</em>
* <pre>
* NetworkConfigurator config = new NetworkConfigurator();
* if (!config.exists()) {
* // Create a new configuration with a new name, principal, and pass
* config.setName("New Name");
* config.setPrincipal("username");
* config.setPassword("password");
* try {
* //persist it
* config.save();
* } catch (IOException io) {
* // deal with the io error
* }
* } else {
* // Load the pre-existing configuration
* File pc = new File(config.getHome(), "PlatformConfig");
* try {
* config.load(pc.toURI());
* // make changes if so desired
* ..
* ..
* // store the PlatformConfig under the default home
* config.save();
* } catch (CertificateException ce) {
* // In case the root cert is invalid, this creates a new one
* try {
* //principal
* config.setPrincipal("principal");
* //password to encrypt private key with
* config.setPassword("password");
* config.save();
* } catch (Exception e) {
* e.printStackTrace();
* }
* }
* <p/>
* </pre>
*
* @since JXTA JSE 2.4
*/
public class NetworkConfigurator {
/**
* Logger
*/
private final static transient Logger LOG = Logger.getLogger(NetworkConfigurator.class.getName());
// begin configuration modes
/**
* Relay off Mode
*/
public final static int RELAY_OFF = 1 << 2;
/**
* Relay client Mode
*/
public final static int RELAY_CLIENT = 1 << 3;
/**
* Relay Server Mode
*/
public final static int RELAY_SERVER = 1 << 4;
/**
* Proxy Server Mode
*/
public final static int PROXY_SERVER = 1 << 5;
/**
* TCP transport client Mode
*/
public final static int TCP_CLIENT = 1 << 6;
/**
* TCP transport Server Mode
*/
public final static int TCP_SERVER = 1 << 7;
/**
* HTTP transport client Mode
*/
public final static int HTTP_CLIENT = 1 << 8;
/**
* HTTP transport server Mode
*/
public final static int HTTP_SERVER = 1 << 9;
/**
* IP multicast transport Mode
*/
public final static int IP_MULTICAST = 1 << 10;
/**
* RendezVousService Mode
*/
public final static int RDV_SERVER = 1 << 11;
/**
* RendezVousService Client
*/
public final static int RDV_CLIENT = 1 << 12;
/**
* RendezVousService Ad-Hoc mode
*/
public final static int RDV_AD_HOC = 1 << 13;
/**
* HTTP2 (netty http tunnel) client
*/
public final static int HTTP2_CLIENT = 1 << 14;
/**
* HTTP2 (netty http tunnel) server
*/
public final static int HTTP2_SERVER = 1 << 15;
/**
* Default AD-HOC configuration
*/
public final static int ADHOC_NODE = TCP_CLIENT | TCP_SERVER | IP_MULTICAST | RDV_AD_HOC | RELAY_OFF;
/**
* Default Edge configuration
*/
public final static int EDGE_NODE = TCP_CLIENT | TCP_SERVER | HTTP_CLIENT | HTTP2_CLIENT | IP_MULTICAST | RDV_CLIENT | RELAY_CLIENT;
/**
* Default Rendezvous configuration
*/
public final static int RDV_NODE = RDV_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER | HTTP2_SERVER;
/**
* Default Relay configuration
*/
public final static int RELAY_NODE = RELAY_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER | HTTP2_SERVER;
// /**
// * Default Proxy configuration
// *
// * @since 2.6 Will be removed in a future release
// */
// @Deprecated
// public final static int PROXY_NODE = PROXY_SERVER | RELAY_NODE;
// /**
// * Default Rendezvous/Relay/Proxy configuration
// *
// * @since 2.6 Will be removed in a future release
// */
// @Deprecated
// public final static int RDV_RELAY_PROXY_NODE = RDV_NODE | PROXY_NODE;
// end configuration modes
/**
* Default mode
*/
protected transient int mode = EDGE_NODE;
/**
* Default PlatformConfig Peer Description
*/
protected transient String description = "Platform Config Advertisement created by : " + NetworkConfigurator.class.getName();
/**
* The location which will serve as the parent for all stored items used
* by JXTA.
*/
private transient URI storeHome = null;
/**
* Default peer name
*/
protected transient String name = "unknown";
/**
* AuthenticationType used by PSEMembership to specify the type of authentication.
*/
protected transient String authenticationType = null;
/**
* Password value used to generate root Certificate and to protect the
* Certificate's PrivateKey.
*/
protected transient String password = null;
/**
* Default PeerID
*/
protected transient PeerID peerid = null;
/**
* Principal value used to generate root certificate
*/
protected transient String principal = null;
/**
* Public Certificate chain
*/
protected transient X509Certificate[] cert = null;
/**
* Subject private key
*/
protected transient PrivateKey subjectPkey = null;
/**
* Freestanding keystore location
*/
protected transient URI keyStoreLocation = null;
/**
* Proxy Service Document
*/
@Deprecated
protected transient XMLElement proxyConfig;
/**
* Personal Security Environment Config Advertisement
*
* @see net.jxta.impl.membership.pse.PSEConfig
*/
protected transient PSEConfigAdv pseConf;
/**
* Rendezvous Config Advertisement
*/
protected transient RdvConfigAdv rdvConfig;
/**
* Default Rendezvous Seeding URI
*/
protected URI rdvSeedingURI = null;
/**
* Relay Config Advertisement
*/
protected transient RelayConfigAdv relayConfig;
/**
* Default Relay Seeding URI
*/
protected transient URI relaySeedingURI = null;
/**
* TCP Config Advertisement
*/
protected transient TCPAdv tcpConfig;
/**
* Multicating Config Advertisement
*/
protected transient MulticastAdv multicastConfig;
/**
* Default TCP transport state
*/
protected transient boolean tcpEnabled = true;
/**
* Default Multicast transport state
*/
protected transient boolean multicastEnabled = true;
/**
* HTTP Config Advertisement
*/
protected transient HTTPAdv httpConfig;
/**
* Default HTTP transport state
*/
protected transient boolean httpEnabled = true;
/**
* HTTP2 Config Advertisement
*/
protected transient TCPAdv http2Config;
/**
* Default HTTP2 transport state
*/
protected transient boolean http2Enabled = true;
/**
* Infrastructure Peer Group Configuration
*/
protected transient PeerGroupConfigAdv infraPeerGroupConfig;
/**
* Creates NetworkConfigurator instance with default AD-HOC configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default AD-HOC configuration
*/
public static NetworkConfigurator newAdHocConfiguration(URI storeHome) {
return new NetworkConfigurator(ADHOC_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Edge configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default AD-HOC configuration
*/
public static NetworkConfigurator newEdgeConfiguration(URI storeHome) {
return new NetworkConfigurator(EDGE_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Rendezvous configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default Rendezvous configuration
*/
public static NetworkConfigurator newRdvConfiguration(URI storeHome) {
return new NetworkConfigurator(RDV_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Relay configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default Relay configuration
*/
public static NetworkConfigurator newRelayConfiguration(URI storeHome) {
return new NetworkConfigurator(RELAY_NODE, storeHome);
}
/**
* Creates NetworkConfigurator instance with default Rendezvous configuration
*
* @param storeHome the URI to persistent store
* @return NetworkConfigurator instance with default Rendezvous configuration
*/
public static NetworkConfigurator newRdvRelayConfiguration(URI storeHome) {
return new NetworkConfigurator(RDV_NODE | RELAY_SERVER, storeHome);
}
// /**
// * Creates NetworkConfigurator instance with default Proxy configuration
// *
// * @param storeHome the URI to persistent store
// * @return NetworkConfigurator instance with defaultProxy configuration
// *
// * @since 2.6 Will be removed in a future release
// */
// @Deprecated
// public static NetworkConfigurator newProxyConfiguration(URI storeHome) {
// return new NetworkConfigurator(PROXY_NODE, storeHome);
// }
// /**
// * Creates NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration
// *
// * @param storeHome the URI to persistent store
// * @return NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration
// *
// * @since 2.6 It will be removed in a future release
// */
// @Deprecated
// public static NetworkConfigurator newRdvRelayProxyConfiguration(URI storeHome) {
// return new NetworkConfigurator(RDV_RELAY_PROXY_NODE, storeHome);
// }
/**
* Creates the default NetworkConfigurator. The configuration is stored with a default configuration mode of EDGE_NODE
*/
public NetworkConfigurator() {
this(EDGE_NODE, new File(".jxta").toURI());
}
/**
* Creates a NetworkConfigurator with the default configuration of the
* specified mode. <p/>Valid modes include ADHOC_NODE, EDGE_NODE, RDV_NODE
* PROXY_NODE, RELAY_NODE, RDV_RELAY_PROXY_NODE, or any combination of
* specific configuration.<p/> e.g. RDV_NODE | HTTP_CLIENT
*
* @param mode the new configuration mode
* @param storeHome the URI to persistent store
* @see #setMode
*/
public NetworkConfigurator(int mode, URI storeHome) {
Logging.logCheckedFine(LOG, "Creating a default configuration");
setStoreHome(storeHome);
httpConfig = createHttpAdv();
rdvConfig = createRdvConfigAdv();
relayConfig = createRelayConfigAdv();
// proxyConfig = createProxyAdv();
tcpConfig = createTcpAdv();
multicastConfig = createMulticastAdv();
http2Config = createHttp2Adv();
infraPeerGroupConfig = createInfraConfigAdv();
setMode(mode);
}
/**
* Sets PlaformConfig Peer Description element
*
* @param description the peer description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Set the current directory for configuration and cache persistent store
* <p/>(default is $CWD/.jxta)
* <p/>
* <dt>Simple example :</dt>
* <pre>
* <code>
* //Create an application home
* File appHome = new File(System.getProperty("JXTA_HOME", ".cache"));
* //Create an instance home under the application home
* File instanceHome = new File(appHome, instanceName);
* jxtaConfig.setHome(instanceHome);
* </code>
* </pre>
*
* @param home the new home value
* @see #getHome
*/
public void setHome(File home) {
this.storeHome = home.toURI();
}
/**
* Returns the current directory for configuration and cache persistent
* store. This is the same location as returned by {@link #getStoreHome()}
* which is more general than this method.
*
* @return Returns the current home directory
* @see #setHome
*/
public File getHome() {
if ("file".equalsIgnoreCase(storeHome.getScheme())) {
return new File(storeHome);
} else {
throw new UnsupportedOperationException("Home location is not a file:// URI : " + storeHome);
}
}
/**
* Returns the location which will serve as the parent for all stored items
* used by JXTA.
*
* @return The location which will serve as the parent for all stored
* items used by JXTA.
* @see net.jxta.peergroup.PeerGroup#getStoreHome()
*/
public URI getStoreHome() {
return storeHome;
}
/**
* Sets the location which will serve as the parent for all stored items
* used by JXTA.
*
* @param newHome new home directory URI
* @see net.jxta.peergroup.PeerGroup#getStoreHome()
*/
public void setStoreHome(URI newHome) {
// Fail if the URI is not absolute.
if (!newHome.isAbsolute()) {
throw new IllegalArgumentException("Only absolute URIs accepted for store home location.");
}
// Fail if the URI is Opaque.
if (newHome.isOpaque()) {
throw new IllegalArgumentException("Only hierarchical URIs accepted for store home location.");
}
// FIXME this should be removed when 1488 is committed
if (!"file".equalsIgnoreCase(newHome.getScheme())) {
throw new IllegalArgumentException("Only file based URI currently supported");
}
// Adds a terminating /
if (!newHome.toString().endsWith("/")) {
newHome = URI.create(newHome.toString() + "/");
}
storeHome = newHome;
}
/**
* Toggles HTTP transport state
*
* @param enabled if true, enables HTTP transport
*/
public void setHttpEnabled(boolean enabled) {
this.httpEnabled = enabled;
if (!httpEnabled) {
httpConfig.setClientEnabled(false);
httpConfig.setServerEnabled(false);
}
}
/**
* Toggles the HTTP transport server (incoming) mode
*
* @param incoming toggles HTTP transport server mode
*/
public void setHttpIncoming(boolean incoming) {
httpConfig.setServerEnabled(incoming);
}
/**
* Toggles the HTTP transport client (outgoing) mode
*
* @param outgoing toggles HTTP transport client mode
*/
public void setHttpOutgoing(boolean outgoing) {
httpConfig.setClientEnabled(outgoing);
}
/**
* Sets the HTTP listening port (default 9901)
*
* @param port the new HTTP port value
*/
public void setHttpPort(int port) {
httpConfig.setPort(port);
}
/**
* Sets the HTTP interface Address to bind the HTTP transport to
* <p/>e.g. "192.168.1.1"
*
* @param address the new address value
*/
public void setHttpInterfaceAddress(String address) {
httpConfig.setInterfaceAddress(address);
}
/**
* Returns the HTTP interface Address
*
* @param address the HTTP interface address
*/
public String getHttpInterfaceAddress() {
return httpConfig.getInterfaceAddress();
}
/**
* Sets the HTTP JXTA Public Address
* e.g. "192.168.1.1:9700"
*
* @param address the HTTP transport public address
* @param exclusive determines whether an address is advertised exclusively
*/
public void setHttpPublicAddress(String address, boolean exclusive) {
httpConfig.setServer(address);
httpConfig.setPublicAddressOnly(exclusive);
}
public boolean isHttp2Enabled() {
return http2Enabled;
}
public void setHttp2Enabled(boolean enabled) {
http2Enabled = enabled;
if(http2Enabled) {
http2Config.setClientEnabled(false);
http2Config.setServerEnabled(false);
}
}
public boolean getHttp2IncomingStatus() {
return http2Config.getServerEnabled();
}
public void setHttp2Incoming(boolean enabled) {
http2Config.setServerEnabled(enabled);
}
public boolean getHttp2OutgoingStatus() {
return http2Config.getClientEnabled();
}
public void setHttp2Outgoing(boolean enabled) {
http2Config.setClientEnabled(enabled);
}
public int getHttp2Port() {
return http2Config.getPort();
}
public void setHttp2Port(int port) {
http2Config.setPort(port);
}
public int getHttp2StartPort() {
return http2Config.getStartPort();
}
public void setHttp2StartPort(int startPort) {
http2Config.setStartPort(startPort);
}
public int getHttp2EndPort() {
return http2Config.getEndPort();
}
public void setHttp2EndPort(int endPort) {
http2Config.setEndPort(endPort);
}
public String getHttp2InterfaceAddress() {
return http2Config.getInterfaceAddress();
}
public void setHttp2InterfaceAddress(String address) {
http2Config.setInterfaceAddress(address);
}
public String getHttp2PublicAddress() {
return http2Config.getServer();
}
public boolean isHttp2PublicAddressExclusive() {
return http2Config.getPublicAddressOnly();
}
public void setHttp2PublicAddress(String address, boolean exclusive) {
http2Config.setServer(address);
http2Config.setPublicAddressOnly(exclusive);
}
/**
* Returns the HTTP JXTA Public Address
*
* @return exclusive determines whether an address is advertised exclusively
*/
public String getHttpPublicAddress() {
return httpConfig.getServer();
}
/**
* Returns the HTTP JXTA Public Address exclusivity
*
* @return exclusive determines whether an address is advertised exclusively
*/
public boolean isHttpPublicAddressExclusive() {
return httpConfig.getPublicAddressOnly();
}
/**
* Sets the ID which will be used for new net peer group instances.
* <p/>
* <p/>By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup),
* it prevents heterogeneous infrastructure PeerGroups from intersecting.
* <p/>This is highly recommended practice for application deployment
*
* @param id the new infrastructure PeerGroupID as a string
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGID
*/
public void setInfrastructureID(ID id) {
if (id == null || id.equals(ID.nullID)) {
throw new IllegalArgumentException("PeerGroupID can not be null");
}
infraPeerGroupConfig.setPeerGroupID(id);
}
/**
* Sets the ID which will be used for new net peer group instances.
* <p/>
* <p/>By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup),
* it prevents heterogeneous infrastructure PeerGroups from intersecting.
* <p/>This is highly recommended practice for application deployment
*
* @param idStr the new infrastructure PeerGroupID as a string
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGID
*/
public void setInfrastructureID(String idStr) {
if (idStr == null || idStr.length() == 0) {
throw new IllegalArgumentException("PeerGroupID string can not be empty or null");
}
PeerGroupID pgid = (PeerGroupID) ID.create(URI.create(idStr));
setInfrastructureID(pgid);
}
/**
* Gets the ID which will be used for new net peer group instances.
* <p/>
*
* @return the infrastructure PeerGroupID as a string
*/
public String getInfrastructureIDStr() {
return infraPeerGroupConfig.getPeerGroupID().toString();
}
/**
* Sets the infrastructure PeerGroup name meta-data
*
* @param name the Infrastructure PeerGroup name
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGName
*/
public void setInfrastructureName(String name) {
infraPeerGroupConfig.setName(name);
}
/**
* Gets the infrastructure PeerGroup name meta-data
*
* @return the Infrastructure PeerGroup name
*/
public String getInfrastructureName() {
return infraPeerGroupConfig.getName();
}
/**
* Sets the infrastructure PeerGroup description meta-data
*
* @param description the infrastructure PeerGroup description
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc
*/
public void setInfrastructureDescriptionStr(String description) {
infraPeerGroupConfig.setDescription(description);
}
/**
* Returns the infrastructure PeerGroup description meta-data
*
* @return the infrastructure PeerGroup description meta-data
*/
public String getInfrastructureDescriptionStr() {
return infraPeerGroupConfig.getDescription();
}
/**
* Sets the infrastructure PeerGroup description meta-data
*
* @param description the infrastructure PeerGroup description
* @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc
*/
public void setInfrastructureDesc(XMLElement description) {
infraPeerGroupConfig.setDesc(description);
}
/**
* Sets the current node configuration mode.
* <p/>The default mode is EDGE, unless modified at construction time.
* A node configuration mode defined a preset configuration
* parameters based on a operating mode. i.e. an EDGE mode, enable
* client/server side tcp, multicast, client side http, RelayService
* client mode.
* <p/> Valid modes include EDGE, RDV_SERVER,
* RELAY_OFF, RELAY_CLIENT, RELAY_SERVER, PROXY_SERVER, or any combination
* of which.<p/> e.g. RDV_SERVER + RELAY_SERVER
*
* @param mode the new configuration mode
* @see #getMode
*/
public void setMode(int mode) {
this.mode = mode;
if ((mode & PROXY_SERVER) == PROXY_SERVER && ((mode & RELAY_SERVER) != RELAY_SERVER)) {
mode = mode | RELAY_SERVER;
}
// RELAY config
relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT);
relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER);
// RDV_SERVER
if ((mode & RDV_SERVER) == RDV_SERVER) {
rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS);
} else if ((mode & RDV_CLIENT) == RDV_CLIENT) {
rdvConfig.setConfiguration(RendezVousConfiguration.EDGE);
} else if ((mode & RDV_AD_HOC) == RDV_AD_HOC) {
rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC);
}
// TCP
tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT);
tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER);
// HTTP
httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT);
httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER);
// HTTP2
http2Config.setClientEnabled((mode & HTTP2_CLIENT) == HTTP2_CLIENT);
http2Config.setServerEnabled((mode & HTTP2_SERVER) == HTTP2_SERVER);
// Multicast
multicastConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST);
// EDGE
if (mode == EDGE_NODE) {
rdvConfig.setConfiguration(RendezVousConfiguration.EDGE);
}
}
/**
* Returns the current configuration mode
* <p/>The default mode is EDGE, unless modified at construction time or through
* Method {@link NetworkConfigurator#setMode}. A node configuration mode defined a preset configuration
* parameters based on a operating mode. i.e. an EDGE mode, enable
* client/server side tcp, multicast, client side http, RelayService
* client mode.
*
* @return mode the current mode value
* @see #setMode
*/
public int getMode() {
return mode;
}
/**
* Sets the IP group multicast packet size
*
* @param size the new multicast packet
*/
public void setMulticastSize(int size) {
multicastConfig.setMulticastSize(size);
}
/**
* Gets the IP group multicast packet size
*
* @return the multicast packet
*/
public int getMulticastSize() {
return multicastConfig.getMulticastSize();
}
/**
* Sets the IP group multicast address (default 224.0.1.85)
*
* @param mcastAddress the new multicast group address
* @see #setMulticastPort
*/
public void setMulticastAddress(String mcastAddress) {
multicastConfig.setMulticastAddr(mcastAddress);
}
/**
* Gets the multicast network interface
*
* @return the multicast network interface, null if none specified
*/
public String getMulticastInterface() {
return multicastConfig.getMulticastInterface();
}
/**
* Sets the multicast network interface
*
* @param interfaceAddress multicast network interface
*/
public void setMulticastInterface(String interfaceAddress) {
multicastConfig.setMulticastInterface(interfaceAddress);
}
/**
* Sets the IP group multicast port (default 1234)
*
* @param port the new IP group multicast port
* @see #setMulticastAddress
*/
public void setMulticastPort(int port) {
multicastConfig.setMulticastPort(port);
}
/**
* Sets the group multicast thread pool size (default 10)
*
* @param size the new multicast thread pool size
*/
public void setMulticastPoolSize(int size) {
multicastConfig.setMulticastPoolSize(size);
}
/**
* Sets the node name
*
* @param name node name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the node name
*
* @return node name
*/
public String getName() {
return this.name;
}
/**
* Sets the Principal for the peer root certificate
*
* @param principal the new principal value
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public void setPrincipal(String principal) {
this.principal = principal;
}
/**
* Gets the Principal for the peer root certificate
*
* @return principal if a principal is set, null otherwise
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public String getPrincipal() {
return principal;
}
/**
* Sets the public Certificate for this configuration.
*
* @param cert the new cert value
*/
public void setCertificate(X509Certificate cert) {
this.cert = new X509Certificate[]{cert};
}
/**
* Returns the public Certificate for this configuration.
*
* @return X509Certificate
*/
public X509Certificate getCertificate() {
return (cert == null || cert.length == 0 ? null : cert[0]);
}
/**
* Sets the public Certificate chain for this configuration.
*
* @param certificateChain the new Certificate chain value
*/
public void setCertificateChain(X509Certificate[] certificateChain) {
this.cert = certificateChain;
}
/**
* Gets the public Certificate chain for this configuration.
*
* @return X509Certificate chain
*/
public X509Certificate[] getCertificateChain() {
return cert;
}
/**
* Sets the Subject private key
*
* @param subjectPkey the subject private key
*/
public void setPrivateKey(PrivateKey subjectPkey) {
this.subjectPkey = subjectPkey;
}
/**
* Gets the Subject private key
*
* @return the subject private key
*/
public PrivateKey getPrivateKey() {
return this.subjectPkey;
}
/**
* Sets freestanding keystore location
*
* @param keyStoreLocation the absolute location of the freestanding keystore
*/
public void setKeyStoreLocation(URI keyStoreLocation) {
this.keyStoreLocation = keyStoreLocation;
}
/**
* Gets the freestanding keystore location
*
* @return the location of the freestanding keystore
*/
public URI getKeyStoreLocation() {
return keyStoreLocation;
}
/**
* Gets the authenticationType
*
* @return authenticationType the authenticationType value
*/
public String getAuthenticationType() {
return this.authenticationType;
}
/**
* Sets the authenticationType
*
* @param authenticationType the new authenticationType value
*/
public void setAuthenticationType(String authenticationType) {
this.authenticationType = authenticationType;
}
/**
* Sets the password used to sign the private key of the root certificate
*
* @param password the new password value
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Gets the password used to sign the private key of the root certificate
*
* @return password if a password is set, null otherwise
* @see #setPassword
* @see #getPrincipal
* @see #setPrincipal
*/
public String getPassword() {
return password;
}
/**
* Sets the PeerID (by default, a new PeerID is generated).
* <p/>Note: Persist the PeerID generated, or use load()
* to avoid overridding a node's PeerID between restarts.
*
* @param peerid the new <code>net.jxta.peer.PeerID</code>
*/
public void setPeerID(PeerID peerid) {
this.peerid = peerid;
}
/**
* Gets the PeerID
*
* @return peerid the <code>net.jxta.peer.PeerID</code> value
*/
public PeerID getPeerID() {
return this.peerid;
}
/**
* Sets Rendezvous Seeding URI
*
* @param seedURI Rendezvous service seeding URI
*/
public void addRdvSeedingURI(URI seedURI) {
rdvConfig.addSeedingURI(seedURI);
}
// /**
// * Sets Rendezvous Access Control URI
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3
// *
// * @param aclURI Rendezvous Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRendezvousSeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public void setRdvACLURI(URI aclURI) {
// rdvConfig.setAclUri(aclURI);
// }
// /**
// * Gets Rendezvous Access Control URI if set
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3
// *
// * @return aclURI Rendezvous Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRendezvousSeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public URI getRdvACLURI() {
// return rdvConfig.getAclUri();
// }
// /**
// * Sets Relay Access Control URI
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3
// *
// * @param aclURI Relay Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRelaySeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public void setRelayACLURI(URI aclURI) {
// relayConfig.setAclUri(aclURI);
// }
// /**
// * Gets Relay Access Control URI if set
// * <p/>e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3
// *
// * @return aclURI Relay Access Control URI
// *
// * @deprecated ACL seed lists are in functional conflict with 'UseOnlyRelaySeedsStatus'.
// * They will be deprecated and removed in a future release.
// */
// @Deprecated
// public URI getRelayACLURI() {
// return relayConfig.getAclUri();
// }
/**
* Sets the RelayService maximum number of simultaneous relay clients
*
* @param relayMaxClients the new relayMaxClients value
*/
public void setRelayMaxClients(int relayMaxClients) {
if ((relayMaxClients != -1) && (relayMaxClients <= 0)) {
throw new IllegalArgumentException("Relay Max Clients : " + relayMaxClients + " must be > 0");
}
relayConfig.setMaxClients(relayMaxClients);
}
/**
* Sets the RelayService Seeding URI
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint addresse(s) to relay peers
*
* @param seedURI RelayService seeding URI
*/
public void addRelaySeedingURI(URI seedURI) {
relayConfig.addSeedingURI(seedURI);
}
/**
* Sets the RendezVousService maximum number of simultaneous rendezvous clients
*
* @param rdvMaxClients the new rendezvousMaxClients value
*/
public void setRendezvousMaxClients(int rdvMaxClients) {
if ((rdvMaxClients != -1) && (rdvMaxClients <= 0)) {
throw new IllegalArgumentException("Rendezvous Max Clients : " + rdvMaxClients + " must be > 0");
}
rdvConfig.setMaxClients(rdvMaxClients);
}
/**
* Toggles TCP transport state
*
* @param enabled if true, enables TCP transport
*/
public void setTcpEnabled(boolean enabled) {
this.tcpEnabled = enabled;
if (!tcpEnabled) {
tcpConfig.setClientEnabled(false);
tcpConfig.setServerEnabled(false);
}
}
/**
* Sets the TCP transport listening port (default 9701)
*
* @param port the new tcpPort value
*/
public void setTcpPort(int port) {
tcpConfig.setPort(port);
}
/**
* Sets the lowest port on which the TCP Transport will listen if configured
* to do so. Valid values are <code>-1</code>, <code>0</code> and
* <code>1-65535</code>. The <code>-1</code> value is used to signify that
* the port range feature should be disabled. The <code>0</code> specifies
* that the Socket API dynamic port allocation should be used. For values
* <code>1-65535</code> the value must be equal to or less than the value
* used for end port.
*
* @param start the lowest port on which to listen.
*/
public void setTcpStartPort(int start) {
tcpConfig.setStartPort(start);
}
/**
* Returns the highest port on which the TCP Transport will listen if
* configured to do so. Valid values are <code>-1</code>, <code>0</code> and
* <code>1-65535</code>. The <code>-1</code> value is used to signify that
* the port range feature should be disabled. The <code>0</code> specifies
* that the Socket API dynamic port allocation should be used. For values
* <code>1-65535</code> the value must be equal to or greater than the value
* used for start port.
*
* @param end the new TCP end port
*/
public void setTcpEndPort(int end) {
tcpConfig.setEndPort(end);
}
/**
* Toggles TCP transport server (incoming) mode (default is on)
*
* @param incoming the new TCP server mode
*/
public void setTcpIncoming(boolean incoming) {
tcpConfig.setServerEnabled(incoming);
}
/**
* Toggles TCP transport client (outgoing) mode (default is true)
*
* @param outgoing the new tcpOutgoing value
*/
public void setTcpOutgoing(boolean outgoing) {
tcpConfig.setClientEnabled(outgoing);
}
/**
* Sets the TCP transport interface address
* <p/>e.g. "192.168.1.1"
*
* @param address the TCP transport interface address
*/
public void setTcpInterfaceAddress(String address) {
tcpConfig.setInterfaceAddress(address);
}
/**
* Sets the node public address
* <p/>e.g. "192.168.1.1:9701"
* <p/>This address is the physical address defined in a node's
* AccessPointAdvertisement. This often required for NAT'd/FW nodes
*
* @param address the TCP transport public address
* @param exclusive public address advertised exclusively
*/
public void setTcpPublicAddress(String address, boolean exclusive) {
tcpConfig.setServer(address);
tcpConfig.setPublicAddressOnly(exclusive);
}
/**
* Toggles whether to use IP group multicast (default is true)
*
* @param multicastOn the new useMulticast value
*/
public void setUseMulticast(boolean multicastOn) {
multicastConfig.setMulticastState(multicastOn);
}
/**
* Determines whether to restrict RelayService leases to those defined in
* the seed list. In other words, only registered endpoint address seeds
* and seeds fetched from seeding URIs will be used.
* </p>WARNING: Disabling 'use only relay seed' will cause this peer to
* search and fetch RdvAdvertisements for use as relay candidates. Rdvs
* are not necessarily relays.
*
* @param useOnlyRelaySeeds restrict RelayService lease to seed list
*/
public void setUseOnlyRelaySeeds(boolean useOnlyRelaySeeds) {
relayConfig.setUseOnlySeeds(useOnlyRelaySeeds);
}
/**
* Determines whether to restrict RendezvousService leases to those defined in
* the seed list. In other words, only registered endpoint address seeds
* and seeds fetched from seeding URIs will be used.
*
* @param useOnlyRendezvouSeeds restrict RendezvousService lease to seed list
*/
public void setUseOnlyRendezvousSeeds(boolean useOnlyRendezvouSeeds) {
rdvConfig.setUseOnlySeeds(useOnlyRendezvouSeeds);
}
/**
* Adds RelayService peer seed address
* <p/>A RelayService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seedURI the relay seed URI
*/
public void addSeedRelay(URI seedURI) {
relayConfig.addSeedRelay(seedURI.toString());
}
/**
* Adds Rendezvous peer seed, physical endpoint address
* <p/>A RendezVousService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seedURI the rendezvous seed URI
*/
public void addSeedRendezvous(URI seedURI) {
rdvConfig.addSeedRendezvous(seedURI);
}
/**
* Returns true if a PlatformConfig file exist under store home
*
* @return true if a PlatformConfig file exist under store home
*/
public boolean exists() {
URI platformConfig = storeHome.resolve("PlatformConfig");
try {
return null != read(platformConfig);
} catch (IOException failed) {
return false;
}
}
/**
* Sets the PeerID for this Configuration
*
* @param peerIdStr the new PeerID as a string
*/
public void setPeerId(String peerIdStr) {
this.peerid = (PeerID) ID.create(URI.create(peerIdStr));
}
/**
* Sets the new RendezvousService seeding URI as a string.
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint address to rendezvous peers
*
* @param seedURIStr the new rendezvous seed URI as a string
*/
public void addRdvSeedingURI(String seedURIStr) {
rdvConfig.addSeedingURI(URI.create(seedURIStr));
}
/**
* Sets the new RelayService seeding URI as a string.
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint address to relay peers
*
* @param seedURIStr the new RelayService seed URI as a string
*/
public void addRelaySeedingURI(String seedURIStr) {
relayConfig.addSeedingURI(URI.create(seedURIStr));
}
/**
* Sets the List relaySeeds represented as Strings
* <p/>A RelayService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seeds the Set RelayService seed URIs as a string
*/
public void setRelaySeedURIs(List<String> seeds) {
relayConfig.clearSeedRelays();
for (String seedStr : seeds) {
relayConfig.addSeedRelay(new EndpointAddress(seedStr));
}
}
/**
* Sets the relaySeeds represented as Strings
* <p/>A seeding URI (when read) is expected to provide a list of
* physical endpoint address to relay peers
*
* @param seedURIs the List relaySeeds represented as Strings
*/
public void setRelaySeedingURIs(Set<String> seedURIs) {
relayConfig.clearSeedingURIs();
for (String seedStr : seedURIs) {
relayConfig.addSeedingURI(URI.create(seedStr));
}
}
/**
* Clears the List of RelayService seeds
*/
public void clearRelaySeeds() {
relayConfig.clearSeedRelays();
}
/**
* Clears the List of RelayService seeding URIs
*/
public void clearRelaySeedingURIs() {
relayConfig.clearSeedingURIs();
}
/**
* Sets the List of RendezVousService seeds represented as Strings
* <p/>A RendezvousService seed is defined as a physical endpoint address
* <p/>e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701
*
* @param seeds the Set of rendezvousSeeds represented as Strings
*/
public void setRendezvousSeeds(Set<String> seeds) {
rdvConfig.clearSeedRendezvous();
for (String seedStr : seeds) {
rdvConfig.addSeedRendezvous(URI.create(seedStr));
}
}
/**
* Sets the List of RendezVousService seeding URIs represented as Strings.
* A seeding URI (when read) is expected to provide a list of
* physical endpoint address to rendezvous peers.
*
* @param seedingURIs the List rendezvousSeeds represented as Strings.
*/
public void setRendezvousSeedingURIs(List<String> seedingURIs) {
rdvConfig.clearSeedingURIs();
for (String seedStr : seedingURIs) {
rdvConfig.addSeedingURI(URI.create(seedStr));
}
}
/**
* Clears the list of RendezVousService seeds
*/
public void clearRendezvousSeeds() {
rdvConfig.clearSeedRendezvous();
}
/**
* Clears the list of RendezVousService seeding URIs
*/
public void clearRendezvousSeedingURIs() {
rdvConfig.clearSeedingURIs();
}
/**
* Load a configuration from the specified store home uri
* <p/>
* e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge
*
* @return The loaded configuration.
* @throws IOException if an i/o error occurs
* @throws CertificateException if the MembershipService is invalid
*/
public ConfigParams load() throws IOException, CertificateException {
return load(storeHome.resolve("PlatformConfig"));
}
/**
* Loads a configuration from a specified uri
* <p/>
* e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge
*
* @param uri the URI to PlatformConfig
* @return The loaded configuration.
* @throws IOException if an i/o error occurs
* @throws CertificateException if the MemebershipService is invalid
*/
public ConfigParams load(URI uri) throws IOException, CertificateException {
if (uri == null) throw new IllegalArgumentException("URI can not be null");
Logging.logCheckedFine(LOG, "Loading configuration : ", uri);
PlatformConfig platformConfig = read(uri);
name = platformConfig.getName();
peerid = platformConfig.getPeerID();
description = platformConfig.getDescription();
XMLElement<?> param;
// TCP
tcpEnabled = platformConfig.isSvcEnabled(PeerGroup.tcpProtoClassID);
tcpConfig = loadTcpAdv(platformConfig, PeerGroup.tcpProtoClassID);
multicastEnabled = platformConfig.isSvcEnabled(PeerGroup.multicastProtoClassID);
multicastConfig = loadMulticastAdv(platformConfig, PeerGroup.multicastProtoClassID);
// HTTP
try {
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.httpProtoClassID);
httpEnabled = platformConfig.isSvcEnabled(PeerGroup.httpProtoClassID);
Enumeration httpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType());
// get the TransportAdv from either TransportAdv
if (httpChilds.hasMoreElements()) {
param = (XMLElement) httpChilds.nextElement();
} else {
throw new IllegalStateException("Missing HTTP Advertisment");
}
// Read-in the adv as it is now.
httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(param);
} catch (Exception failure) {
IOException ioe = new IOException("error processing the HTTP config advertisement");
ioe.initCause(failure);
throw ioe;
}
// HTTP2
http2Enabled = platformConfig.isSvcEnabled(PeerGroup.http2ProtoClassID);
http2Config = loadTcpAdv(platformConfig, PeerGroup.http2ProtoClassID);
// // ProxyService
// try {
// param = (XMLElement) platformConfig.getServiceParam(PeerGroup.proxyClassID);
// if (param != null && !platformConfig.isSvcEnabled(PeerGroup.proxyClassID)) {
// mode = mode | PROXY_SERVER;
// }
// } catch (Exception failure) {
// IOException ioe = new IOException("error processing the pse config advertisement");
// ioe.initCause(failure);
// throw ioe;
// }
// Rendezvous
try {
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.rendezvousClassID);
// backwards compatibility
param.addAttribute("type", RdvConfigAdv.getAdvertisementType());
rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(param);
if (rdvConfig.getConfiguration() == RendezVousConfiguration.AD_HOC) {
mode = mode | RDV_AD_HOC;
} else if (rdvConfig.getConfiguration() == RendezVousConfiguration.EDGE) {
mode = mode | RDV_CLIENT;
} else if (rdvConfig.getConfiguration() == RendezVousConfiguration.RENDEZVOUS) {
mode = mode | RDV_SERVER;
}
} catch (Exception failure) {
IOException ioe = new IOException("error processing the rendezvous config advertisement");
ioe.initCause(failure);
throw ioe;
}
// Relay
try {
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.relayProtoClassID);
if (param != null && !platformConfig.isSvcEnabled(PeerGroup.relayProtoClassID)) {
mode = mode | RELAY_OFF;
}
// backwards compatibility
param.addAttribute("type", RelayConfigAdv.getAdvertisementType());
relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(param);
} catch (Exception failure) {
IOException ioe = new IOException("error processing the relay config advertisement");
ioe.initCause(failure);
throw ioe;
}
// PSE
param = (XMLElement) platformConfig.getServiceParam(PeerGroup.membershipClassID);
if (param != null) {
Advertisement adv = null;
try {
adv = AdvertisementFactory.newAdvertisement(param);
} catch (NoSuchElementException notAnAdv) {
CertificateException cnfe = new CertificateException("No membership advertisement found");
cnfe.initCause(notAnAdv);
} catch (IllegalArgumentException invalidAdv) {
CertificateException cnfe = new CertificateException("Invalid membership advertisement");
cnfe.initCause(invalidAdv);
}
if (adv instanceof PSEConfigAdv) {
pseConf = (PSEConfigAdv) adv;
cert = pseConf.getCertificateChain();
} else {
throw new CertificateException("Error processing the Membership config advertisement. Unexpected membership advertisement "
+ adv.getAdvertisementType());
}
}
// Infra Group
infraPeerGroupConfig = (PeerGroupConfigAdv) platformConfig.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID);
if (null == infraPeerGroupConfig) {
infraPeerGroupConfig = createInfraConfigAdv();
try {
URI configPropsURI = storeHome.resolve("config.properties");
InputStream configPropsIS = configPropsURI.toURL().openStream();
ResourceBundle rsrcs = new PropertyResourceBundle(configPropsIS);
configPropsIS.close();
NetGroupTunables tunables = new NetGroupTunables(rsrcs, new NetGroupTunables());
infraPeerGroupConfig.setPeerGroupID(tunables.id);
infraPeerGroupConfig.setName(tunables.name);
infraPeerGroupConfig.setDesc(tunables.desc);
} catch (IOException ignored) {
//ignored
} catch (MissingResourceException ignored) {
//ignored
}
}
return platformConfig;
}
private TCPAdv loadTcpAdv(PlatformConfig platformConfig, ModuleClassID moduleClassID) {
XMLElement<?> param = (XMLElement<?>) platformConfig.getServiceParam(moduleClassID);
Enumeration<?> tcpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType());
// get the TransportAdv from either TransportAdv or tcpConfig
if (tcpChilds.hasMoreElements()) {
param = (XMLElement<?>) tcpChilds.nextElement();
} else {
throw new IllegalStateException("Missing TCP Advertisement");
}
return (TCPAdv) AdvertisementFactory.newAdvertisement(param);
}
private MulticastAdv loadMulticastAdv(PlatformConfig platformConfig, ModuleClassID moduleClassID) {
XMLElement<?> param2 = (XMLElement<?>) platformConfig.getServiceParam(moduleClassID);
Enumeration<?> tcpChilds2 = param2.getChildren(TransportAdvertisement.getAdvertisementType());
// get the TransportAdv from either TransportAdv or multicastConfig
if (tcpChilds2.hasMoreElements()) {
param2 = (XMLElement<?>) tcpChilds2.nextElement();
} else {
throw new IllegalStateException("Missing Multicast Advertisment");
}
return (MulticastAdv) AdvertisementFactory.newAdvertisement(param2);
}
/**
* Persists a PlatformConfig advertisement under getStoreHome()+"/PlaformConfig"
* <p/>
* Home may be overridden by a call to setHome()
*
* @throws IOException If there is a failure saving the PlatformConfig.
* @see #load
*/
public void save() throws IOException {
httpEnabled = (httpConfig.isClientEnabled() || httpConfig.isServerEnabled());
tcpEnabled = (tcpConfig.isClientEnabled() || tcpConfig.isServerEnabled());
http2Enabled = (http2Config.isClientEnabled() || http2Config.isServerEnabled());
ConfigParams advertisement = getPlatformConfig();
OutputStream out = null;
try {
if ("file".equalsIgnoreCase(storeHome.getScheme())) {
File saveDir = new File(storeHome);
saveDir.mkdirs();
// Sadly we can't use URL.openConnection() to create the
// OutputStream for file:// URLs. bogus.
out = new FileOutputStream(new File(saveDir, "PlatformConfig"));
} else {
out = storeHome.resolve("PlatformConfig").toURL().openConnection().getOutputStream();
}
XMLDocument aDoc = (XMLDocument) advertisement.getDocument(MimeMediaType.XMLUTF8);
OutputStreamWriter os = new OutputStreamWriter(out, "UTF-8");
aDoc.sendToWriter(os);
os.flush();
} finally {
if (null != out) {
out.close();
}
}
}
/**
* Returns a XMLDocument representation of an Advertisement
*
* @param enabled whether the param doc is enabled, adds a "isOff"
* element if disabled
* @param adv the Advertisement to retrieve the param doc from
* @return the parmDoc value
*/
protected XMLDocument getParmDoc(boolean enabled, Advertisement adv) {
XMLDocument parmDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm");
XMLDocument doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8);
StructuredDocumentUtils.copyElements(parmDoc, parmDoc, doc);
if (!enabled) {
parmDoc.appendChild(parmDoc.createElement("isOff"));
}
return parmDoc;
}
/**
* Creates an HTTP transport advertisement
*
* @return an HTTP transport advertisement
*/
protected HTTPAdv createHttpAdv() {
httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(HTTPAdv.getAdvertisementType());
httpConfig.setProtocol("http");
httpConfig.setPort(9700);
httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT);
httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER);
return httpConfig;
}
/**
* Creates Personal Security Environment Config Advertisement
* <p/>The configuration advertisement can include an optional seed certificate
* chain and encrypted private key. If this seed information is present the PSE
* Membership Service will require an initial authentication to unlock the
* encrypted private key before creating the PSE keystore. The newly created
* PSE keystore will be "seeded" with the certificate chain and the private key.
*
* @param principal principal
* @param password the password used to sign the private key of the root certificate
* @return PSEConfigAdv an PSE config advertisement
* @see net.jxta.impl.protocol.PSEConfigAdv
*/
protected PSEConfigAdv createPSEAdv(String principal, String password) {
pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType());
if (principal != null && password != null) {
IssuerInfo info = PSEUtils.genCert(principal, null);
pseConf.setCertificate(info.cert);
pseConf.setPrivateKey(info.subjectPkey, password.toCharArray());
}
return pseConf;
}
/**
* Creates Personal Security Environment Config Advertisement
* <p/>The configuration advertisement can include an optional seed certificate
* chain and encrypted private key. If this seed information is present the PSE
* Membership Service will require an initial authentication to unlock the
* encrypted private key before creating the PSE keystore. The newly created
* PSE keystore will be "seeded" with the certificate chain and the private key.
*
* @param cert X509Certificate
* @return PSEConfigAdv an PSE config advertisement
* @see net.jxta.impl.protocol.PSEConfigAdv
*/
protected PSEConfigAdv createPSEAdv(X509Certificate cert) {
pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType());
if (subjectPkey != null && password != null) {
pseConf.setCertificate(cert);
pseConf.setPrivateKey(subjectPkey, password.toCharArray());
}
return pseConf;
}
/**
* Creates Personal Security Environment Config Advertisement
* <p/>The configuration advertisement can include an optional seed certificate
* chain and encrypted private key. If this seed information is present the PSE
* Membership Service will require an initial authentication to unlock the
* encrypted private key before creating the PSE keystore. The newly created
* PSE keystore will be "seeded" with the certificate chain and the private key.
*
* @param certificateChain X509Certificate[]
* @return PSEConfigAdv an PSE config advertisement
* @see net.jxta.impl.protocol.PSEConfigAdv
*/
protected PSEConfigAdv createPSEAdv(X509Certificate[] certificateChain) {
pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType());
if (subjectPkey != null && password != null) {
pseConf.setCertificateChain(certificateChain);
pseConf.setPrivateKey(subjectPkey, password.toCharArray());
}
return pseConf;
}
/**
* Creates a ProxyService configuration advertisement
*
* @return ProxyService configuration advertisement
*/
@Deprecated
protected XMLDocument createProxyAdv() {
return (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm");
}
/**
* Creates a RendezVousService configuration advertisement with default values (EDGE)
*
* @return a RdvConfigAdv
*/
protected RdvConfigAdv createRdvConfigAdv() {
rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType());
if (mode == RDV_AD_HOC) {
rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC);
} else if ((mode & RDV_CLIENT) == RDV_CLIENT) {
rdvConfig.setConfiguration(RendezVousConfiguration.EDGE);
} else if ((mode & RDV_SERVER) == RDV_SERVER) {
rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS);
}
// A better alternative is to reference rdv service defaults (currently private)
// rdvConfig.setMaxClients(200);
return rdvConfig;
}
/**
* Creates a RelayService configuration advertisement with default values (EDGE)
*
* @return a RelayConfigAdv
*/
protected RelayConfigAdv createRelayConfigAdv() {
relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(RelayConfigAdv.getAdvertisementType());
// Since 2.6 - We should only use seeds when it comes to relay (see Javadoc)
// relayConfig.setUseOnlySeeds(false);
relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT || mode == EDGE_NODE);
relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER);
return relayConfig;
}
/**
* Creates an TCP transport advertisement with the platform default values.
* multicast on, 224.0.1.85:1234, with a max packet size of 16K
*
* @return a TCP transport advertisement
*/
protected TCPAdv createTcpAdv() {
tcpConfig = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType());
tcpConfig.setProtocol("tcp");
tcpConfig.setInterfaceAddress(null);
tcpConfig.setPort(9701);
//tcpConfig.setStartPort(9701);
//tcpConfig.setEndPort(9799);
tcpConfig.setServer(null);
tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT);
tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER);
return tcpConfig;
}
/**
* Creates an multicast transport advertisement with the platform default values.
* Multicast on, 224.0.1.85:1234, with a max packet size of 16K.
*
* @return a TCP transport advertisement
*/
protected MulticastAdv createMulticastAdv() {
multicastConfig = (MulticastAdv) AdvertisementFactory.newAdvertisement(MulticastAdv.getAdvertisementType());
multicastConfig.setProtocol("tcp");
multicastConfig.setMulticastAddr("224.0.1.85");
multicastConfig.setMulticastPort(1234);
multicastConfig.setMulticastSize(16384);
multicastConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST);
return multicastConfig;
}
protected TCPAdv createHttp2Adv() {
http2Config = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType());
http2Config.setProtocol("http2");
http2Config.setInterfaceAddress(null);
http2Config.setPort(8080);
http2Config.setStartPort(8080);
http2Config.setEndPort(8089);
http2Config.setServer(null);
http2Config.setClientEnabled((mode & HTTP2_CLIENT) == TCP_CLIENT);
http2Config.setServerEnabled((mode & HTTP2_SERVER) == TCP_SERVER);
return http2Config;
}
protected PeerGroupConfigAdv createInfraConfigAdv() {
infraPeerGroupConfig = (PeerGroupConfigAdv) AdvertisementFactory.newAdvertisement(
PeerGroupConfigAdv.getAdvertisementType());
NetGroupTunables tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables());
infraPeerGroupConfig.setPeerGroupID(tunables.id);
infraPeerGroupConfig.setName(tunables.name);
infraPeerGroupConfig.setDesc(tunables.desc);
return infraPeerGroupConfig;
}
/**
* Returns a PlatformConfig which represents a platform configuration.
* <p/>Fine tuning is achieved through accessing each configured advertisement
* and achieved through accessing each configured advertisement and modifying
* each object directly.
*
* @return the PeerPlatformConfig Advertisement
*/
public ConfigParams getPlatformConfig() {
PlatformConfig advertisement = (PlatformConfig) AdvertisementFactory.newAdvertisement(
PlatformConfig.getAdvertisementType());
advertisement.setName(name);
advertisement.setDescription(description);
if (tcpConfig != null) {
boolean enabled = tcpEnabled && (tcpConfig.isServerEnabled() || tcpConfig.isClientEnabled());
advertisement.putServiceParam(PeerGroup.tcpProtoClassID, getParmDoc(enabled, tcpConfig));
}
if (multicastConfig != null) {
boolean enabled = multicastConfig.getMulticastState();
advertisement.putServiceParam(PeerGroup.multicastProtoClassID, getParmDoc(enabled, multicastConfig));
}
if (httpConfig != null) {
boolean enabled = httpEnabled && (httpConfig.isServerEnabled() || httpConfig.isClientEnabled());
advertisement.putServiceParam(PeerGroup.httpProtoClassID, getParmDoc(enabled, httpConfig));
}
if (http2Config != null) {
boolean enabled = http2Enabled && (http2Config.isServerEnabled() || http2Config.isClientEnabled());
advertisement.putServiceParam(PeerGroup.http2ProtoClassID, getParmDoc(enabled, http2Config));
}
if (relayConfig != null) {
boolean isOff = ((mode & RELAY_OFF) == RELAY_OFF) || (relayConfig.isServerEnabled() && relayConfig.isClientEnabled());
XMLDocument relayDoc = (XMLDocument) relayConfig.getDocument(MimeMediaType.XMLUTF8);
if (isOff) {
relayDoc.appendChild(relayDoc.createElement("isOff"));
}
advertisement.putServiceParam(PeerGroup.relayProtoClassID, relayDoc);
}
if (rdvConfig != null) {
XMLDocument rdvDoc = (XMLDocument) rdvConfig.getDocument(MimeMediaType.XMLUTF8);
advertisement.putServiceParam(PeerGroup.rendezvousClassID, rdvDoc);
}
if (principal == null) {
principal = System.getProperty("impl.membership.pse.authentication.principal", "JxtaCN");
}
if (password == null) {
password = System.getProperty("impl.membership.pse.authentication.password", "the!one!password");
}
if (cert != null) {
pseConf = createPSEAdv(cert);
} else {
pseConf = createPSEAdv(principal, password);
cert = pseConf.getCertificateChain();
}
if (pseConf != null) {
if (keyStoreLocation != null) {
if (keyStoreLocation.isAbsolute()) {
pseConf.setKeyStoreLocation(keyStoreLocation);
} else {
Logging.logCheckedWarning(LOG, "Keystore location set, but is not absolute: ", keyStoreLocation);
}
}
XMLDocument pseDoc = (XMLDocument) pseConf.getDocument(MimeMediaType.XMLUTF8);
advertisement.putServiceParam(PeerGroup.membershipClassID, pseDoc);
}
if (authenticationType == null) {
authenticationType = System.getProperty("impl.membership.pse.authentication.type", "StringAuthentication");
}
StdPeerGroup.setPSEMembershipServiceKeystoreInfoFactory(new StdPeerGroup.DefaultPSEMembershipServiceKeystoreInfoFactory(authenticationType, password));
if (peerid == null) {
peerid = IDFactory.newPeerID(PeerGroupID.worldPeerGroupID, cert[0].getPublicKey().getEncoded());
}
advertisement.setPeerID(peerid);
// if (proxyConfig != null && ((mode & PROXY_SERVER) == PROXY_SERVER)) {
// advertisement.putServiceParam(PeerGroup.proxyClassID, proxyConfig);
// }
if ((null != infraPeerGroupConfig) && (null != infraPeerGroupConfig.getPeerGroupID())
&& (ID.nullID != infraPeerGroupConfig.getPeerGroupID())
&& (PeerGroupID.defaultNetPeerGroupID != infraPeerGroupConfig.getPeerGroupID())) {
advertisement.setSvcConfigAdvertisement(PeerGroup.peerGroupClassID, infraPeerGroupConfig);
}
return advertisement;
}
/**
* @param location The location of the platform config.
* @return The platformConfig
* @throws IOException Thrown for failures reading the PlatformConfig.
*/
private PlatformConfig read(URI location) throws IOException {
URL url;
try {
url = location.toURL();
} catch (MalformedURLException mue) {
IllegalArgumentException failure = new IllegalArgumentException("Failed to convert URI to URL");
failure.initCause(mue);
throw failure;
}
InputStream input = url.openStream();
try {
XMLDocument document = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, input);
PlatformConfig platformConfig = (PlatformConfig) AdvertisementFactory.newAdvertisement(document);
return platformConfig;
} finally {
input.close();
}
}
/**
* Indicates whether Http is enabled
*
* @return true if Http is enabled, else returns false
* @see #setHttpEnabled
*/
public boolean isHttpEnabled() {
return this.httpEnabled;
}
/**
* Retrieves the Http incoming status
*
* @return true if Http incomming status is enabled, else returns false
* @see #setHttpIncoming
*/
public boolean getHttpIncomingStatus() {
return httpConfig.getServerEnabled();
}
/**
* Retrieves the Http outgoing status
*
* @return true if Http outgoing status is enabled, else returns false
* @see #setHttpOutgoing
*/
public boolean getHttpOutgoingStatus() {
return httpConfig.getClientEnabled();
}
/**
* Retrieves the Http port
*
* @return the current Http port
* @see #setHttpPort
*/
public int getHttpPort() {
return httpConfig.getPort();
}
/**
* Retrieves the current infrastructure ID
*
* @return the current infrastructure ID
* @see #setInfrastructureID
*/
public ID getInfrastructureID() {
return infraPeerGroupConfig.getPeerGroupID();
}
/**
* Retrieves the current multicast address
*
* @return the current multicast address
* @see #setMulticastAddress
*/
public String getMulticastAddress() {
return multicastConfig.getMulticastAddr();
}
/**
* Retrieves the current multicast port
*
* @return the current mutlicast port
* @see #setMulticastPort
*/
public int getMulticastPort() {
return multicastConfig.getMulticastPort();
}
/**
* Gets the group multicast thread pool size
*
* @return multicast thread pool size
*/
public int getMulticastPoolSize() {
return multicastConfig.getMulticastPoolSize();
}
/**
* Indicates whether tcp is enabled
*
* @return true if tcp is enabled, else returns false
* @see #setTcpEnabled
*/
public boolean isTcpEnabled() {
return this.tcpEnabled;
}
/**
* Retrieves the current tcp end port
*
* @return the current tcp port
* @see #setTcpEndPort
*/
public int getTcpEndport() {
return tcpConfig.getEndPort();
}
/**
* Retrieves the Tcp incoming status
*
* @return true if tcp incoming is enabled, else returns false
* @see #setTcpIncoming
*/
public boolean getTcpIncomingStatus() {
return tcpConfig.getServerEnabled();
}
/**
* Retrieves the Tcp outgoing status
*
* @return true if tcp outcoming is enabled, else returns false
* @see #setTcpOutgoing
*/
public boolean getTcpOutgoingStatus() {
return tcpConfig.getClientEnabled();
}
/**
* Retrieves the Tcp interface address
*
* @return the current tcp interface address
* @see #setTcpInterfaceAddress
*/
public String getTcpInterfaceAddress() {
return tcpConfig.getInterfaceAddress();
}
/**
* Retrieves the current Tcp port
*
* @return the current tcp port
* @see #setTcpPort
*/
public int getTcpPort() {
return tcpConfig.getPort();
}
/**
* Retrieves the current Tcp public address
*
* @return the current tcp public address
* @see #setTcpPublicAddress
*/
public String getTcpPublicAddress() {
return tcpConfig.getServer();
}
/**
* Indicates whether the current Tcp public address is exclusive
*
* @return true if the current tcp public address is exclusive, else returns false
* @see #setTcpPublicAddress
*/
public boolean isTcpPublicAddressExclusive() {
return tcpConfig.getPublicAddressOnly();
}
/**
* Retrieves the current Tcp start port
*
* @return the current tcp start port
* @see #setTcpStartPort
*/
public int getTcpStartPort() {
return tcpConfig.getStartPort();
}
/**
* Retrieves the multicast use status
*
* @return true if multicast is enabled, else returns false
* @see #setUseMulticast
*/
public boolean getMulticastStatus() {
return multicastConfig.getMulticastState();
}
/**
* Retrieves the use relay seeds only status
*
* @return true if only relay seeds are used, else returns false
* @see #setUseOnlyRelaySeeds
*/
public boolean getUseOnlyRelaySeedsStatus() {
return relayConfig.getUseOnlySeeds();
}
/**
* Retrieves the use rendezvous seeds only status
*
* @return true if only rendezvous seeds are used, else returns false
* @see #setUseOnlyRendezvousSeeds
*/
public boolean getUseOnlyRendezvousSeedsStatus() {
return rdvConfig.getUseOnlySeeds();
}
/**
* Retrieves the RendezVousService maximum number of simultaneous rendezvous clients
*
* @return the RendezVousService maximum number of simultaneous rendezvous clients
* @see #setRendezvousMaxClients
*/
public int getRendezvousMaxClients() {
return rdvConfig.getMaxClients();
}
/**
* Retrieves the RelayVousService maximum number of simultaneous relay clients
*
* @return the RelayService maximum number of simultaneous relay clients
* @see #setRelayMaxClients
*/
public int getRelayMaxClients() {
return relayConfig.getMaxClients();
}
/**
* Retrieves the rendezvous seedings
*
* @return the array of rendezvous seeding URL
* @see #addRdvSeedingURI
*/
public URI[] getRdvSeedingURIs() {
return rdvConfig.getSeedingURIs();
}
/**
* Retrieves the rendezvous seeds
*
* @return the array of rendezvous seeds URL
* @see #addRdvSeedURI
*/
public URI[] getRdvSeedURIs() {
return rdvConfig.getSeedRendezvous();
}
/**
* Retrieves the relay seeds
*
* @return the array of relay seeds URL
* @see #addRelaySeedURI
*/
public URI[] getRelaySeedURIs() {
return relayConfig.getSeedRelayURIs();
}
/**
* Retrieves the relay seeds
*
* @return the array of rendezvous seed URL
* @see #addRelaySeedingURI
*/
public URI[] getRelaySeedingURIs() {
return relayConfig.getSeedingURIs();
}
/**
* Holds the construction tunables for the Net Peer Group. This consists of
* the peer group id, the peer group name and the peer group description.
*/
static class NetGroupTunables {
final ID id;
final String name;
final XMLElement desc;
/**
* Constructor for loading the default Net Peer Group construction
* tunables.
*/
NetGroupTunables() {
id = PeerGroupID.defaultNetPeerGroupID;
name = "NetPeerGroup";
desc = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", "default Net Peer Group");
}
/**
* Constructor for loading the default Net Peer Group construction
* tunables.
*
* @param pgid the PeerGroupID
* @param pgname the group name
* @param pgdesc the group description
*/
NetGroupTunables(ID pgid, String pgname, XMLElement pgdesc) {
id = pgid;
name = pgname;
desc = pgdesc;
}
/**
* Constructor for loading the Net Peer Group construction
* tunables from the provided resource bundle.
*
* @param rsrcs The resource bundle from which resources will be loaded.
* @param defaults default values
*/
NetGroupTunables(ResourceBundle rsrcs, NetGroupTunables defaults) {
ID idTmp;
String nameTmp;
XMLElement descTmp;
try {
String idTmpStr = rsrcs.getString("NetPeerGroupID").trim();
if (idTmpStr.startsWith(ID.URNNamespace + ":")) {
idTmpStr = idTmpStr.substring(5);
}
idTmp = IDFactory.fromURI(new URI(ID.URIEncodingName + ":" + ID.URNNamespace + ":" + idTmpStr));
nameTmp = rsrcs.getString("NetPeerGroupName").trim();
descTmp = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", rsrcs.getString("NetPeerGroupDesc").trim());
} catch (Exception failed) {
if (null != defaults) {
Logging.logCheckedFine(LOG, "NetPeerGroup tunables not defined or could not be loaded. Using defaults.\n\n", failed);
idTmp = defaults.id;
nameTmp = defaults.name;
descTmp = defaults.desc;
} else {
Logging.logCheckedSevere(LOG, "NetPeerGroup tunables not defined or could not be loaded.\n", failed);
throw new IllegalStateException("NetPeerGroup tunables not defined or could not be loaded.");
}
}
id = idTmp;
name = nameTmp;
desc = descTmp;
}
}
}
| johnjianfang/jxse | src/main/java/net/jxta/platform/NetworkConfigurator.java | Java | apache-2.0 | 82,829 |
package com.sissi.protocol.message;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import com.sissi.io.read.Metadata;
/**
* @author kim 2014年1月28日
*/
@Metadata(uri = Message.XMLNS, localName = Thread.NAME)
@XmlRootElement
public class Thread {
public final static String NAME = "thread";
private String text;
private String parent;
public Thread() {
super();
}
public Thread(String text) {
super();
this.text = text;
}
public Thread(String text, String parent) {
super();
this.text = text;
this.parent = parent;
}
@XmlValue
public String getText() {
return this.text;
}
public Thread setText(String text) {
this.text = text;
return this;
}
@XmlAttribute
public String getParent() {
return this.parent;
}
public Thread setParent(String parent) {
this.parent = parent;
return this;
}
public boolean content() {
return this.text != null && this.text.length() > 0;
}
}
| KimShen/sissi | src/main/java/com/sissi/protocol/message/Thread.java | Java | apache-2.0 | 1,026 |
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* 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.yx.asm;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.yx.bean.Loader;
import org.yx.conf.AppInfo;
import org.yx.exception.SumkException;
import org.yx.log.Log;
import org.yx.log.Logs;
import org.yx.main.StartContext;
public final class AsmUtils {
private static Method defineClass;
static {
try {
defineClass = getMethod(ClassLoader.class, "defineClass",
new Class<?>[] { String.class, byte[].class, int.class, int.class });
defineClass.setAccessible(true);
} catch (Exception e) {
Log.printStack("sumk.error", e);
StartContext.startFailed();
}
}
public static String proxyCalssName(Class<?> clz) {
String name = clz.getName();
int index = name.lastIndexOf('.');
return name.substring(0, index) + ".sumkbox" + name.substring(index);
}
public static int asmVersion() {
return AppInfo.getInt("sumk.asm.version", Opcodes.ASM7);
}
public static int jvmVersion() {
return AppInfo.getInt("sumk.asm.jvm.version", Opcodes.V1_8);
}
public static InputStream openStreamForClass(String name) {
String internalName = name.replace('.', '/') + ".class";
return Loader.getResourceAsStream(internalName);
}
public static boolean sameType(Type[] types, Class<?>[] clazzes) {
if (types.length != clazzes.length) {
return false;
}
for (int i = 0; i < types.length; i++) {
if (!Type.getType(clazzes[i]).equals(types[i])) {
return false;
}
}
return true;
}
public static List<MethodParamInfo> buildMethodInfos(List<Method> methods) throws IOException {
Map<Class<?>, List<Method>> map = new HashMap<>();
for (Method m : methods) {
List<Method> list = map.get(m.getDeclaringClass());
if (list == null) {
list = new ArrayList<>();
map.put(m.getDeclaringClass(), list);
}
list.add(m);
}
List<MethodParamInfo> ret = new ArrayList<>();
for (List<Method> ms : map.values()) {
ret.addAll(buildMethodInfos(ms.get(0).getDeclaringClass(), ms));
}
return ret;
}
private static List<MethodParamInfo> buildMethodInfos(Class<?> declaringClass, List<Method> methods)
throws IOException {
String classFullName = declaringClass.getName();
ClassReader cr = new ClassReader(openStreamForClass(classFullName));
MethodInfoClassVisitor cv = new MethodInfoClassVisitor(methods);
cr.accept(cv, 0);
return cv.getMethodInfos();
}
public static Method getMethod(Class<?> clz, String methodName, Class<?>[] paramTypes) {
while (clz != Object.class) {
Method[] ms = clz.getDeclaredMethods();
for (Method m : ms) {
if (!m.getName().equals(methodName)) {
continue;
}
Class<?>[] paramTypes2 = m.getParameterTypes();
if (!Arrays.equals(paramTypes2, paramTypes)) {
continue;
}
return m;
}
clz = clz.getSuperclass();
}
return null;
}
public static Class<?> loadClass(String fullName, byte[] b) throws Exception {
String clzOutPath = AppInfo.get("sumk.asm.debug.output");
if (clzOutPath != null && clzOutPath.length() > 0) {
try {
File f = new File(clzOutPath, fullName + ".class");
try (FileOutputStream fos = new FileOutputStream(f)) {
fos.write(b);
fos.flush();
}
} catch (Exception e) {
if (Logs.asm().isTraceEnabled()) {
Logs.asm().error(e.getLocalizedMessage(), e);
}
}
}
synchronized (AsmUtils.class) {
try {
return Loader.loadClass(fullName);
} catch (Throwable e) {
if (!(e instanceof ClassNotFoundException)) {
Logs.asm().warn(fullName + " 加载失败", e);
}
}
Class<?> clz = (Class<?>) defineClass.invoke(Loader.loader(), fullName, b, 0, b.length);
if (clz == null) {
throw new SumkException(-235345436, "cannot load class " + fullName);
}
return clz;
}
}
public static final int BADMODIFIERS = Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.PRIVATE;
public static boolean notPublicOnly(int modifiers) {
return (modifiers & (Modifier.PUBLIC | BADMODIFIERS)) != Modifier.PUBLIC;
}
public static boolean canProxy(int modifiers) {
return (modifiers & BADMODIFIERS) == 0;
}
public static List<Object> getImplicitFrame(String desc) {
List<Object> locals = new ArrayList<>(5);
if (desc.isEmpty()) {
return locals;
}
int i = 0;
while (desc.length() > i) {
int j = i;
switch (desc.charAt(i++)) {
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
locals.add(Opcodes.INTEGER);
break;
case 'F':
locals.add(Opcodes.FLOAT);
break;
case 'J':
locals.add(Opcodes.LONG);
break;
case 'D':
locals.add(Opcodes.DOUBLE);
break;
case '[':
while (desc.charAt(i) == '[') {
++i;
}
if (desc.charAt(i) == 'L') {
++i;
while (desc.charAt(i) != ';') {
++i;
}
}
locals.add(desc.substring(j, ++i));
break;
case 'L':
while (desc.charAt(i) != ';') {
++i;
}
locals.add(desc.substring(j + 1, i++));
break;
default:
break;
}
}
return locals;
}
public static Method getSameMethod(Method method, Class<?> otherClass) {
Class<?> clz = method.getDeclaringClass();
if (clz == otherClass) {
return method;
}
String methodName = method.getName();
Class<?>[] argTypes = method.getParameterTypes();
Method[] proxyedMethods = otherClass.getMethods();
for (Method proxyedMethod : proxyedMethods) {
if (proxyedMethod.getName().equals(methodName) && Arrays.equals(argTypes, proxyedMethod.getParameterTypes())
&& !proxyedMethod.getDeclaringClass().isInterface()) {
return proxyedMethod;
}
}
return method;
}
}
| youtongluan/sumk | src/main/java/org/yx/asm/AsmUtils.java | Java | apache-2.0 | 6,539 |
/**********************************************************************
Copyright (c) 2009 Stefan Seelmann. 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.example.dao;
import java.util.Collection;
import com.example.Team;
public class TeamDao extends AbstractDao<Team>
{
public Collection<Team> findByName( String name )
{
return super.findByQuery( "name.startsWith(s1)", "java.lang.String s1", name );
}
public Team loadWithUsers( Object id )
{
return super.load( id, "users" );
}
public Team load( Object id )
{
return super.load( id );
}
public Collection<Team> loadAll()
{
return super.loadAll();
}
}
| seelmann/ldapcon2009-datanucleus | DataNucleus-Advanced/src/main/java/com/example/dao/TeamDao.java | Java | apache-2.0 | 1,280 |
package com.metrink.action;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Provider;
import com.metrink.alert.ActionBean;
import com.metrink.alert.AlertBean;
import com.metrink.metric.Metric;
/**
* The base action for all SMS actions.
*
* A list of gateways can be found here: http://www.emailtextmessages.com/
*
*/
public abstract class SmsAction implements Action {
private static final Logger LOG = LoggerFactory.getLogger(SmsAction.class);
private final Provider<SimpleEmail> emailProvider;
public SmsAction(final Provider<SimpleEmail> emailProvider) {
this.emailProvider = emailProvider;
}
@Override
public void triggerAction(Metric metric, AlertBean alertBean, ActionBean actionBean) {
final String toAddr = constructAddress(actionBean.getValue());
final String alertQuery = alertBean.getAlertQuery().substring(0, alertBean.getAlertQuery().lastIndexOf(" do "));
final StringBuilder sb = new StringBuilder();
sb.append(metric.getId());
sb.append(" ");
sb.append(metric.getValue());
sb.append(" triggered ");
sb.append(alertQuery);
try {
final SimpleEmail email = emailProvider.get();
email.addTo(toAddr);
email.setSubject("METRINK Alert");
email.setMsg(sb.toString());
final String messageId = email.send();
LOG.info("Sent message {} to {}", messageId, toAddr);
} catch (final EmailException e) {
LOG.error("Error sending email: {}", e.getMessage());
}
}
/**
* Given a phone number, create the address for the gateway.
* @param phoneNumber the phone number.
* @return the email address to use.
*/
protected abstract String constructAddress(String phoneNumber);
}
| Metrink/metrink | src/main/java/com/metrink/action/SmsAction.java | Java | apache-2.0 | 1,947 |
/**
* Copyright 2017-2019 The GreyCat Authors. All rights reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package greycat.internal.task;
import greycat.*;
import greycat.base.BaseNode;
import greycat.plugin.Job;
import greycat.struct.Buffer;
class ActionDelete implements Action {
@Override
public void eval(final TaskContext ctx) {
TaskResult previous = ctx.result();
DeferCounter counter = ctx.graph().newCounter(previous.size());
for (int i = 0; i < previous.size(); i++) {
if (previous.get(i) instanceof BaseNode) {
((Node) previous.get(i)).drop(new Callback() {
@Override
public void on(Object result) {
counter.count();
}
});
}
}
counter.then(new Job() {
@Override
public void run() {
previous.clear();
ctx.continueTask();
}
});
}
@Override
public void serialize(final Buffer builder) {
builder.writeString(CoreActionNames.DELETE);
builder.writeChar(Constants.TASK_PARAM_OPEN);
builder.writeChar(Constants.TASK_PARAM_CLOSE);
}
@Override
public final String name() {
return CoreActionNames.DELETE;
}
}
| datathings/greycat | greycat/src/main/java/greycat/internal/task/ActionDelete.java | Java | apache-2.0 | 1,871 |
package com.at.springboot.mybatis.po;
public class JsonUser {
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.JSON_USER_ID
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private byte[] jsonUserId;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.USER_NAME
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private String userName;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_RESULT
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private String lastLoginResult;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_INFO
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
private String lastLoginInfo;
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.JSON_USER_ID
* @return the value of JSON_USER.JSON_USER_ID
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public byte[] getJsonUserId() {
return jsonUserId;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.JSON_USER_ID
* @param jsonUserId the value for JSON_USER.JSON_USER_ID
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setJsonUserId(byte[] jsonUserId) {
this.jsonUserId = jsonUserId;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.USER_NAME
* @return the value of JSON_USER.USER_NAME
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public String getUserName() {
return userName;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.USER_NAME
* @param userName the value for JSON_USER.USER_NAME
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_RESULT
* @return the value of JSON_USER.LAST_LOGIN_RESULT
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public String getLastLoginResult() {
return lastLoginResult;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_RESULT
* @param lastLoginResult the value for JSON_USER.LAST_LOGIN_RESULT
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setLastLoginResult(String lastLoginResult) {
this.lastLoginResult = lastLoginResult == null ? null : lastLoginResult.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_INFO
* @return the value of JSON_USER.LAST_LOGIN_INFO
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public String getLastLoginInfo() {
return lastLoginInfo;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_INFO
* @param lastLoginInfo the value for JSON_USER.LAST_LOGIN_INFO
* @mbg.generated Thu Aug 29 17:59:18 CST 2019
*/
public void setLastLoginInfo(String lastLoginInfo) {
this.lastLoginInfo = lastLoginInfo == null ? null : lastLoginInfo.trim();
}
} | alphatan/workspace_java | spring-boot-web-fps-demo/src/main/java/com/at/springboot/mybatis/po/JsonUser.java | Java | apache-2.0 | 3,937 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.stylehair.servicos;
import br.com.stylehair.dao.AgendamentoDAO;
import br.com.stylehair.entity.Agendamento;
import com.google.gson.Gson;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
/**
*
* @author vinicius
*/
@Stateless
@Path("agendamento")
public class AgendamentoResource {
@PersistenceContext(unitName = "StyleHairPU")
private EntityManager em;
private Gson gson = new Gson();
@Context
private UriInfo context;
@GET
@Produces("application/json")
public String getJson() {
AgendamentoDAO dao = new AgendamentoDAO(em);
List<Agendamento> agendamentos;
agendamentos = dao.buscarTodosAgendamentos();
return gson.toJson(agendamentos);
}
@GET
@Path("{agendamentoId}")
@Produces("application/json")
public String getAgendamento(@PathParam("agendamentoId") String id){
System.out.println("pegando o cliente");
Long n = Long.parseLong(id);
System.out.println(n);
AgendamentoDAO dao = new AgendamentoDAO(em);
Agendamento agend = dao.consultarPorId(Agendamento.class, Long.parseLong(id));
return gson.toJson(agend);
}
@GET
@Path("{buscardata}/{dia}/{mes}/{ano}")
@Produces("application/json")
public String getAgendamentoPorData(@PathParam("dia") String dia,@PathParam("mes") String mes,@PathParam("ano") String ano ) {
AgendamentoDAO dao = new AgendamentoDAO(em);
List<Agendamento> agendamentos;
SimpleDateFormat dateFormat_hora = new SimpleDateFormat("HH:mm");
Date data = new Date();
String horaAtual = dateFormat_hora.format(data);
System.out.println("hora Atual" + horaAtual);
Date d1 = new Date();
SimpleDateFormat dateFormataData = new SimpleDateFormat("dd/MM/yyyy");
String dataHoje = dateFormataData.format(d1);
System.out.println("dataHoje ----" + dataHoje + "-------- " + dia+"/"+mes+"/"+ano );
if(dataHoje.equalsIgnoreCase(dia+"/"+mes+"/"+ano)){
agendamentos = dao.buscarAgendamentoPorData(dia+"/"+mes+"/"+ano + " ",horaAtual);
return gson.toJson(agendamentos);
}
agendamentos = dao.buscarAgendamentoPorData(dia+"/"+mes+"/"+ano + " ","08:00");
return gson.toJson(agendamentos);
}
@POST
@Consumes("application/json")
@Produces("application/json")
public String salvarAgendamento(String agendamento) throws Exception{
Agendamento ag1 = gson.fromJson(agendamento, Agendamento.class);
AgendamentoDAO dao = new AgendamentoDAO(em);
return gson.toJson(dao.salvar(ag1));
}
@PUT
@Consumes("application/json")
public void atualizarAgendamento(String agendamento) throws Exception {
salvarAgendamento(agendamento);
}
}
| ViniciusBezerra94/WsStyleHair | src/main/java/br/com/stylehair/servicos/AgendamentoResource.java | Java | apache-2.0 | 3,529 |
package com.sampleapp.base;
import android.app.Application;
import com.crashlytics.android.Crashlytics;
import com.sampleapp.BuildConfig;
import com.sampleapp.utils.UtilsModule;
import io.fabric.sdk.android.Fabric;
import timber.log.Timber;
/**
* Created by saveen_dhiman on 05-November-16.
* Initialization of required libraries
*/
public class SampleApplication extends Application {
private AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
//create component
mAppComponent = DaggerAppComponent.builder()
.utilsModule(new UtilsModule(this)).build();
//configure timber for logging
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
}
}
public AppComponent getAppComponent() {
return mAppComponent;
}
}
| saveendhiman/SampleApp | app/src/main/java/com/sampleapp/base/SampleApplication.java | Java | apache-2.0 | 915 |
/*
* Copyright 2017 Axway Software
*
* 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.axway.ats.core.filesystem.exceptions;
import java.io.File;
import com.axway.ats.common.filesystem.FileSystemOperationException;
/**
* Exception thrown when a file does not exist
*/
@SuppressWarnings( "serial")
public class FileDoesNotExistException extends FileSystemOperationException {
/**
* Constructor
*
* @param fileName name of the file which does not exist
*/
public FileDoesNotExistException( String fileName ) {
super("File '" + fileName + "' does not exist");
}
/**
* Constructor
*
* @param file the file which does not exist
*/
public FileDoesNotExistException( File file ) {
super("File '" + file.getPath() + "' does not exist");
}
}
| Axway/ats-framework | corelibrary/src/main/java/com/axway/ats/core/filesystem/exceptions/FileDoesNotExistException.java | Java | apache-2.0 | 1,344 |
package com.fasterxml.jackson.databind.node;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.io.NumberOutput;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* Numeric node that contains simple 32-bit integer values.
*/
@SuppressWarnings("serial")
public class IntNode
extends NumericNode
{
// // // Let's cache small set of common value
final static int MIN_CANONICAL = -1;
final static int MAX_CANONICAL = 10;
private final static IntNode[] CANONICALS;
static {
int count = MAX_CANONICAL - MIN_CANONICAL + 1;
CANONICALS = new IntNode[count];
for (int i = 0; i < count; ++i) {
CANONICALS[i] = new IntNode(MIN_CANONICAL + i);
}
}
/**
* Integer value this node contains
*/
protected final int _value;
/*
************************************************
* Construction
************************************************
*/
public IntNode(int v) { _value = v; }
public static IntNode valueOf(int i) {
if (i > MAX_CANONICAL || i < MIN_CANONICAL) return new IntNode(i);
return CANONICALS[i - MIN_CANONICAL];
}
/*
/**********************************************************
/* BaseJsonNode extended API
/**********************************************************
*/
@Override public JsonToken asToken() { return JsonToken.VALUE_NUMBER_INT; }
@Override
public JsonParser.NumberType numberType() { return JsonParser.NumberType.INT; }
/*
/**********************************************************
/* Overrridden JsonNode methods
/**********************************************************
*/
@Override
public boolean isIntegralNumber() { return true; }
@Override
public boolean isInt() { return true; }
@Override public boolean canConvertToInt() { return true; }
@Override public boolean canConvertToLong() { return true; }
@Override
public Number numberValue() {
return Integer.valueOf(_value);
}
@Override
public short shortValue() { return (short) _value; }
@Override
public int intValue() { return _value; }
@Override
public long longValue() { return (long) _value; }
@Override
public float floatValue() { return (float) _value; }
@Override
public double doubleValue() { return (double) _value; }
@Override
public BigDecimal decimalValue() { return BigDecimal.valueOf(_value); }
@Override
public BigInteger bigIntegerValue() { return BigInteger.valueOf(_value); }
@Override
public String asText() {
return NumberOutput.toString(_value);
}
@Override
public boolean asBoolean(boolean defaultValue) {
return _value != 0;
}
@Override
public final void serialize(JsonGenerator g, SerializerProvider provider)
throws IOException
{
g.writeNumber(_value);
}
@Override
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o instanceof IntNode) {
return ((IntNode) o)._value == _value;
}
return false;
}
@Override
public int hashCode() { return _value; }
}
| FasterXML/jackson-databind | src/main/java/com/fasterxml/jackson/databind/node/IntNode.java | Java | apache-2.0 | 3,398 |
package lena.lerning.selenium;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleContains;
/**
* Created by Lena on 01/05/2017.
*/
public class EdgeTest {
private WebDriver driver;
private WebDriverWait wait;
@Before
public void edgeStart(){
driver = new EdgeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void firstTest(){
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("webdriver");
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
wait.until(titleContains("webdriver"));
}
@After
public void stop(){
driver.quit();
driver=null;
}
}
| etarnovskaya/sel_6_Lena | sel-test/src/test/java/lena/lerning/selenium/EdgeTest.java | Java | apache-2.0 | 1,062 |
/*
* 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/ecl1.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.kra.common.notification.exception;
/**
* This exception is thrown if the given role id is not known to the given context.
*/
public class UnknownRoleException extends Exception {
private static final long serialVersionUID = -1925770520412550327L;
private final String roleId;
private final String context;
/**
* Constructs an Unknown Role exception.
*
* @param roleId
* @param context
*/
public UnknownRoleException(final String roleId, final String context) {
super("Role " + roleId + " not recognized for context " + context);
this.roleId = roleId;
this.context = context;
}
public String getRoleId() {
return roleId;
}
public String getContext() {
return context;
}
} | vivantech/kc_fixes | src/main/java/org/kuali/kra/common/notification/exception/UnknownRoleException.java | Java | apache-2.0 | 1,435 |
package org.develnext.jphp.android.ext.classes.app;
import android.os.Bundle;
import org.develnext.jphp.android.AndroidStandaloneLoader;
import org.develnext.jphp.android.ext.AndroidExtension;
import php.runtime.annotation.Reflection;
@Reflection.Name(AndroidExtension.NAMESPACE + "app\\BootstrapActivity")
public class WrapBootstrapActivity extends WrapActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreateClearly(savedInstanceState);
AndroidStandaloneLoader.INSTANCE.run(this);
getEnvironment().invokeMethodNoThrow(this, "onCreate");
}
}
| livingvirus/jphp | jphp-android/src/main/java/org/develnext/jphp/android/ext/classes/app/WrapBootstrapActivity.java | Java | apache-2.0 | 616 |
package com.truward.brikar.maintenance.log.processor;
import com.truward.brikar.common.log.LogUtil;
import com.truward.brikar.maintenance.log.CommaSeparatedValueParser;
import com.truward.brikar.maintenance.log.Severity;
import com.truward.brikar.maintenance.log.message.LogMessage;
import com.truward.brikar.maintenance.log.message.MaterializedLogMessage;
import com.truward.brikar.maintenance.log.message.MultiLinePartLogMessage;
import com.truward.brikar.maintenance.log.message.NullLogMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Message processor that converts a line into a message.
*
* @author Alexander Shabanov
*/
@ParametersAreNonnullByDefault
public final class LogMessageProcessor {
public static final Pattern RECORD_PATTERN = Pattern.compile(
"^(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}) " + // date+time
"(\\p{Upper}+) " + // severity
"([\\w\\p{Punct}]+) " + // class name
"((?:[\\w]+=[\\w\\+/.\\$]+)(?:, (?:[\\w]+=[\\w\\+/\\.\\$]+))*)? " + // variables
"\\[[\\w\\p{Punct}&&[^\\]]]+\\] " + // thread ID
"(.+)" + // message
"$"
);
private static final String METRIC_MARKER = LogUtil.METRIC_ENTRY + ' ';
private final Logger log = LoggerFactory.getLogger(getClass());
private final DateFormat dateFormat;
public LogMessageProcessor() {
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public LogMessage parse(String line, LogMessage previousMessage) {
if (previousMessage.hasMetrics() && line.startsWith("\t")) {
// special case: this line is a continuation of metrics entry started on the previous line
final MaterializedLogMessage logMessage = new MaterializedLogMessage(previousMessage.getUnixTime(),
previousMessage.getSeverity(), line);
addAttributesFromMetrics(logMessage, line.substring(1));
return logMessage;
}
final Matcher matcher = RECORD_PATTERN.matcher(line);
if (!matcher.matches()) {
return new MultiLinePartLogMessage(line);
}
if (matcher.groupCount() < 5) {
log.error("Count of groups is not six: actual={} for line={}", matcher.groupCount(), line);
return NullLogMessage.INSTANCE; // should not happen
}
final Date date;
try {
date = dateFormat.parse(matcher.group(1));
} catch (ParseException e) {
log.error("Malformed date in line={}", line, e);
return NullLogMessage.INSTANCE; // should not happen
}
final Severity severity = Severity.fromString(matcher.group(2), Severity.WARN);
final MaterializedLogMessage logMessage = new MaterializedLogMessage(date.getTime(), severity, line);
addAttributesFromVariables(logMessage, matcher.group(4));
final String message = matcher.group(5);
if (message != null) {
final int metricIndex = message.indexOf(METRIC_MARKER);
if (metricIndex >= 0) {
addAttributesFromMetrics(logMessage, message.substring(metricIndex + METRIC_MARKER.length()));
}
}
return logMessage;
}
//
// Private
//
private void addAttributesFromMetrics(MaterializedLogMessage logMessage, String metricBody) {
putAllAttributes(logMessage, new CommaSeparatedValueParser(metricBody).readAsMap());
}
private void addAttributesFromVariables(MaterializedLogMessage logMessage, @Nullable String variables) {
if (variables != null) {
putAllAttributes(logMessage, new CommaSeparatedValueParser(variables).readAsMap());
}
}
private void putAllAttributes(MaterializedLogMessage logMessage, Map<String, String> vars) {
for (final Map.Entry<String, String> entry : vars.entrySet()) {
final String key = entry.getKey();
final Object value;
if (LogUtil.TIME_DELTA.equals(key)) {
value = Long.parseLong(entry.getValue());
} else if (LogUtil.START_TIME.equals(key)) {
value = Long.parseLong(entry.getValue());
} else if (LogUtil.COUNT.equals(key)) {
value = Long.parseLong(entry.getValue());
} else if (LogUtil.FAILED.equals(key)) {
value = Boolean.valueOf(entry.getValue());
} else {
value = entry.getValue();
}
logMessage.putAttribute(key, value);
}
}
}
| truward/brikar | brikar-maintenance/src/main/java/com/truward/brikar/maintenance/log/processor/LogMessageProcessor.java | Java | apache-2.0 | 4,636 |
package ru.job4j.servlet.services;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.job4j.servlet.model.User;
import ru.job4j.servlet.repository.RepositoryException;
import ru.job4j.servlet.repository.UserStore;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* UpdateUserController.
*
* @author Stanislav ([email protected])
* @since 11.01.2018
*/
public class UpdateUserController extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(UpdateUserController.class);
private static final long serialVersionUID = 6328444530140780881L;
private UserStore userStore = UserStore.getInstance();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
User user = userStore.findByID(Integer.valueOf(req.getParameter("id")));
if (user != null) {
String name = req.getParameter("name");
String login = req.getParameter("login");
String email = req.getParameter("email");
if (name != null && !name.trim().isEmpty()) {
user.setName(name);
}
if (login != null && !login.trim().isEmpty()) {
user.setLogin(login);
}
if (email != null && !email.trim().isEmpty()) {
user.setEmail(email);
}
userStore.update(user);
}
} catch (NumberFormatException e) {
LOG.error("Not the correct format id. ", e);
} catch (RepositoryException e) {
LOG.error("Error adding user. ", e);
}
resp.sendRedirect(req.getContextPath().length() == 0 ? "/" : req.getContextPath());
}
} | StanislavEsin/estanislav | chapter_007/src/main/java/ru/job4j/servlet/services/UpdateUserController.java | Java | apache-2.0 | 1,967 |
package com.kenshin.windystreet.db;
import org.litepal.crud.DataSupport;
/**
* Created by Kenshin on 2017/4/3.
*/
public class County extends DataSupport {
private int id; //编号
private String countyName; //县名
private String weatherId; //对应的天气id
private int cityId; //所属市的id
public void setId(int id) {
this.id = id;
}
public void setCountyName(String countyName) {
this.countyName = countyName;
}
public void setWeatherId(String weatherId) {
this.weatherId = weatherId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public int getId() {
return id;
}
public String getCountyName() {
return countyName;
}
public String getWeatherId() {
return weatherId;
}
public int getCityId() {
return cityId;
}
}
| Asucanc/Windy-Street-Weather | app/src/main/java/com/kenshin/windystreet/db/County.java | Java | apache-2.0 | 901 |
/*
* 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.core.model.actiongraph;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.util.immutables.BuckStyleImmutable;
import org.immutables.value.Value;
/** Holds an ActionGraph with the BuildRuleResolver that created it. */
@Value.Immutable
@BuckStyleImmutable
interface AbstractActionGraphAndResolver {
@Value.Parameter
ActionGraph getActionGraph();
@Value.Parameter
BuildRuleResolver getResolver();
}
| LegNeato/buck | src/com/facebook/buck/core/model/actiongraph/AbstractActionGraphAndResolver.java | Java | apache-2.0 | 1,075 |
package water.api;
import org.reflections.Reflections;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hex.schemas.ModelBuilderSchema;
import water.DKV;
import water.H2O;
import water.Iced;
import water.Job;
import water.Key;
import water.Value;
import water.exceptions.H2OIllegalArgumentException;
import water.exceptions.H2OKeyNotFoundArgumentException;
import water.exceptions.H2ONotFoundArgumentException;
import water.fvec.Frame;
import water.util.IcedHashMap;
import water.util.Log;
import water.util.MarkdownBuilder;
import water.util.Pair;
import water.util.PojoUtils;
import water.util.ReflectionUtils;
/**
* Base Schema class; all REST API Schemas inherit from here.
* <p>
* The purpose of Schemas is to provide a stable, versioned interface to
* the functionality in H2O, which allows the back end implementation to
* change rapidly without breaking REST API clients such as the Web UI
* and R and Python bindings. Schemas also allow for functionality which exposes the
* schema metadata to clients, allowing them to do service discovery and
* to adapt dynamically to new H2O functionality, e.g. to be able to call
* any ModelBuilder, even new ones written since the client was built,
* without knowing any details about the specific algo.
* <p>
* In most cases, Java developers who wish to expose new functionality through the
* REST API will need only to define their schemas with the fields that they
* wish to expose, adding @API annotations to denote the field metadata.
* Their fields will be copied back and forth through the reflection magic in this
* class. If there are fields they have to adapt between the REST API representation
* and the back end this can be done piecemeal by overriding the fill* methods, calling
* the versions in super, and making only those changes that are absolutely necessary.
* A lot of work has gone into avoiding boilerplate code.
* <p>
* Schemas are versioned for stability. When you look up the schema for a given impl
* object or class you supply a version number. If a schema for that version doesn't
* exist then the versions are searched in reverse order. For example, if you ask for
* version 5 and the highest schema version for that impl class is 3 then V3 will be returned.
* This allows us to move to higher versions without having to write gratuitous new schema
* classes for the things that haven't changed in the new version.
* <p>
* The current version can be found by calling
* Schema.getHighestSupportedVersion(). For schemas that are still in flux
* because development is ongoing we also support an EXPERIMENTAL_VERSION, which
* indicates that there are no interface stability guarantees between H2O versions.
* Eventually these schemas will move to a normal, stable version number. Call
* Schema.getExperimentalVersion() to find the experimental version number (99 as
* of this writing).
* <p>
* Schema names must be unique within an application in a single namespace. The
* class getSimpleName() is used as the schema name. During Schema discovery and
* registration there are checks to ensure that the names are unique.
* <p>
* Most schemas have a 1-to-1 mapping to an Iced implementation object, aka the "impl"
* or implementation class. This class is specified as a type parameter to the Schema class.
* This type parameter is used by reflection magic to avoid a large amount of boilerplate
* code.
* <p>
* Both the Schema and the Iced object may have children, or (more often) not.
* Occasionally, e.g. in the case of schemas used only to handle HTTP request
* parameters, there will not be a backing impl object and the Schema will be
* parameterized by Iced.
* <p>
* Other than Schemas backed by Iced this 1-1 mapping is enforced: a check at Schema
* registration time ensures that at most one Schema is registered for each Iced class.
* This 1-1 mapping allows us to have generic code here in the Schema class which does
* all the work for common cases. For example, one can write code which accepts any
* Schema instance and creates and fills an instance of its associated impl class:
* {@code
* I impl = schema.createAndFillImpl();
* }
* <p>
* Schemas have a State section (broken into Input, Output and InOut fields)
* and an Adapter section. The adapter methods fill the State to and from the
* Iced impl objects and from HTTP request parameters. In the simple case, where
* the backing object corresponds 1:1 with the Schema and no adapting need be
* done, the methods here in the Schema class will do all the work based on
* reflection. In that case your Schema need only contain the fields you wish
* to expose, and no adapter code.
* <p>
* Methods here allow us to convert from Schema to Iced (impl) and back in a
* flexible way. The default behaviour is to map like-named fields back and
* forth, often with some default type conversions (e.g., a Keyed object like a
* Model will be automagically converted back and forth to a Key).
* Subclasses can override methods such as fillImpl or fillFromImpl to
* provide special handling when adapting from schema to impl object and back.
* Usually they will want to call super to get the default behavior, and then
* modify the results a bit (e.g., to map differently-named fields, or to
* compute field values).
* <p>
* Schema Fields must have a single @API annotation describing their direction
* of operation and any other properties such as "required". Fields are
* API.Direction.INPUT by default. Transient and static fields are ignored.
* <p>
* Most Java developers need not be concerned with the details that follow, because the
* framework will make these calls as necessary.
* <p>
* Some use cases:
* <p>
* To find and create an instance of the appropriate schema for an Iced object, with the
* given version or the highest previous version:<pre>
* Schema s = Schema.schema(6, impl);
* </pre>
* <p>
* To create a schema object and fill it from an existing impl object (the common case):<pre>
* S schema = MySchemaClass(version).fillFromImpl(impl);</pre>
* or more generally:
* <pre>
* S schema = Schema(version, impl).fillFromImpl(impl);</pre>
* To create an impl object and fill it from an existing schema object (the common case):
* <pre>
* I impl = schema.createImpl(); // create an empty impl object and any empty children
* schema.fillImpl(impl); // fill the empty impl object and any children from the Schema and its children</pre>
* or
* <pre>
* I impl = schema.createAndFillImpl(); // helper which does schema.fillImpl(schema.createImpl())</pre>
* <p>
* Schemas that are used for HTTP requests are filled with the default values of their impl
* class, and then any present HTTP parameters override those default values.
* <p>
* To create a schema object filled from the default values of its impl class and then
* overridden by HTTP request params:
* <pre>
* S schema = MySchemaClass(version);
* I defaults = schema.createImpl();
* schema.fillFromImpl(defaults);
* schema.fillFromParms(parms);
* </pre>
* or more tersely:
* <pre>
* S schema = MySchemaClass(version).fillFromImpl(schema.createImpl()).fillFromParms(parms);
* </pre>
* @see Meta#getSchema_version()
* @see Meta#getSchema_name()
* @see Meta#getSchema_type()
* @see water.api.API
*/
public class Schema<I extends Iced, S extends Schema<I,S>> extends Iced {
private transient Class<I> _impl_class = getImplClass(); // see getImplClass()
private static final int HIGHEST_SUPPORTED_VERSION = 3;
private static final int EXPERIMENTAL_VERSION = 99;
/**
* Metadata for a Schema, including the version, name and type. This information is included in all REST API
* responses as a field in the Schema so that the payloads are self-describing, and it is also available through
* the /Metadata/schemas REST API endpoint for the purposes of REST service discovery.
*/
public static final class Meta extends Iced {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CAREFUL: This class has its own JSON serializer. If you add a field here you probably also want to add it to the serializer!
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, meaning that
* there are no stability guarantees between H2O versions.
*/
@API(help="Version number of this Schema. Must not be changed after creation (treat as final).", direction=API.Direction.OUTPUT)
private int schema_version;
/** Get the simple schema (class) name, for example DeepLearningParametersV3. Must not be changed after creation (treat as final). */
@API(help="Simple name of this Schema. NOTE: the schema_names form a single namespace.", direction=API.Direction.OUTPUT)
private String schema_name;
/** Get the simple name of H2O type that this Schema represents, for example DeepLearningParameters. */
@API(help="Simple name of H2O type that this Schema represents. Must not be changed after creation (treat as final).", direction=API.Direction.OUTPUT)
private String schema_type; // subclasses can redefine this
/** Default constructor used only for newInstance() in generic reflection-based code. */
public Meta() {}
/** Standard constructor which supplies all the fields. The fields should be treated as immutable once set. */
public Meta(int version, String name, String type) {
this.schema_version = version;
this.schema_name = name;
this.schema_type = type;
}
/**
* Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version,
* meaning that there are no stability guarantees between H2O versions.
*/
public int getSchema_version() {
return schema_version;
}
/** Get the simple schema (class) name, for example DeepLearningParametersV3. */
public String getSchema_name() {
return schema_name;
}
/** Get the simple name of the H2O type that this Schema represents, for example DeepLearningParameters. */
public String getSchema_type() {
return schema_type;
}
/** Set the simple name of the H2O type that this Schema represents, for example Key<Frame>. NOTE: using this is a hack and should be avoided. */
protected void setSchema_type(String schema_type) {
this.schema_type = schema_type;
}
// TODO: make private in Iced:
/** Override the JSON serializer to prevent a recursive loop in AutoBuffer. User code should not call this, and soon it should be made protected. */
@Override
public final water.AutoBuffer writeJSON_impl(water.AutoBuffer ab) {
// Overridden because otherwise we get in a recursive loop trying to serialize this$0.
ab.putJSON4("schema_version", schema_version)
.put1(',').putJSONStr("schema_name", schema_name)
.put1(',').putJSONStr("schema_type", schema_type);
return ab;
}
}
@API(help="Metadata on this schema instance, to make it self-describing.", direction=API.Direction.OUTPUT)
private Meta __meta = null;
/** Get the metadata for this schema instance which makes it self-describing when serialized to JSON. */
protected Meta get__meta() {
return __meta;
}
// Registry which maps a simple schema name to its class. NOTE: the simple names form a single namespace.
// E.g., "DeepLearningParametersV2" -> hex.schemas.DeepLearningV2.DeepLearningParametersV2
private static Map<String, Class<? extends Schema>> schemas = new HashMap<>();
// Registry which maps a Schema simpleName to its Iced Class.
// E.g., "DeepLearningParametersV2" -> hex.deeplearning.DeepLearning.DeepLearningParameters
private static Map<String, Class<? extends Iced>> schema_to_iced = new HashMap<>();
// Registry which maps an Iced simpleName (type) and schema_version to its Schema Class.
// E.g., (DeepLearningParameters, 2) -> "DeepLearningParametersV2"
//
// Note that iced_to_schema gets lazily filled if a higher version is asked for than is
// available (e.g., if the highest version of Frame is FrameV2 and the client asks for
// the schema for (Frame, 17) then FrameV2 will be returned, and all the mappings between
// 17 and 3 will get added to the Map.
private static Map<Pair<String, Integer>, Class<? extends Schema>> iced_to_schema = new HashMap<>();
/**
* Default constructor; triggers lazy schema registration.
* @throws water.exceptions.H2OFailException if there is a name collision or there is more than one schema which maps to the same Iced class
*/
public Schema() {
String name = this.getClass().getSimpleName();
int version = extractVersion(name);
String type = _impl_class.getSimpleName();
__meta = new Meta(version, name, type);
if (null == schema_to_iced.get(name)) {
Log.debug("Registering schema: " + name + " schema_version: " + version + " with Iced class: " + _impl_class.toString());
if (null != schemas.get(name))
throw H2O.fail("Found a duplicate schema name in two different packages: " + schemas.get(name) + " and: " + this.getClass().toString());
schemas.put(name, this.getClass());
schema_to_iced.put(name, _impl_class);
if (_impl_class != Iced.class) {
Pair versioned = new Pair(type, version);
// Check for conflicts
if (null != iced_to_schema.get(versioned)) {
throw H2O.fail("Found two schemas mapping to the same Iced class with the same version: " + iced_to_schema.get(versioned) + " and: " + this.getClass().toString() + " both map to version: " + version + " of Iced class: " + _impl_class);
}
iced_to_schema.put(versioned, this.getClass());
}
}
}
private static Pattern _version_pattern = null;
/** Extract the version number from the schema class name. Returns -1 if there's no version number at the end of the classname. */
private static int extractVersion(String clz_name) {
if (null == _version_pattern) // can't just use a static initializer
_version_pattern = Pattern.compile(".*V(\\d+)");
Matcher m = _version_pattern.matcher(clz_name);
if (! m.matches()) return -1;
return Integer.valueOf(m.group(1));
}
/**
* Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, meaning that
* there are no stability guarantees between H2O versions.
*/
public int getSchemaVersion() {
return __meta.schema_version;
}
private static int latest_version = -1;
/**
* Get the highest schema version number that we've encountered during schema registration.
*/
public final static int getLatestVersion() {
return latest_version;
}
/**
* Get the highest schema version that we support. This bounds the search for a schema if we haven't yet
* registered all schemas and don't yet know the latest_version.
*/
public final static int getHighestSupportedVersion() {
return HIGHEST_SUPPORTED_VERSION;
}
/**
* Get the experimental schema version, which indicates that a schema is not guaranteed stable between H2O releases.
*/
public final static int getExperimentalVersion() {
return EXPERIMENTAL_VERSION;
}
/**
* Register the given schema class.
* @throws water.exceptions.H2OFailException if there is a name collision, if the type parameters are bad, or if the version is bad
*/
private static void register(Class<? extends Schema> clz) {
synchronized(clz) {
// Was there a race to get here? If so, return.
Class<? extends Schema> existing = schemas.get(clz.getSimpleName());
if (null != existing) {
if (clz != existing)
throw H2O.fail("Two schema classes have the same simpleName; this is not supported: " + clz + " and " + existing + ".");
return;
}
// Check that the Schema has the correct type parameters:
if (clz.getGenericSuperclass() instanceof ParameterizedType) {
Type[] schema_type_parms = ((ParameterizedType) (clz.getGenericSuperclass())).getActualTypeArguments();
if (schema_type_parms.length < 2)
throw H2O.fail("Found a Schema that does not pass at least two type parameters. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz);
Class parm0 = ReflectionUtils.findActualClassParameter(clz, 0);
if (!Iced.class.isAssignableFrom(parm0))
throw H2O.fail("Found a Schema with bad type parameters. First parameter is a subclass of Iced. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm0);
if (Schema.class.isAssignableFrom(parm0))
throw H2O.fail("Found a Schema with bad type parameters. First parameter is a subclass of Schema. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm0);
Class parm1 = ReflectionUtils.findActualClassParameter(clz, 1);
if (!Schema.class.isAssignableFrom(parm1))
throw H2O.fail("Found a Schema with bad type parameters. Second parameter is not a subclass of Schema. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm1);
} else {
throw H2O.fail("Found a Schema that does not have a parameterized superclass. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz);
}
int version = extractVersion(clz.getSimpleName());
if (version > getHighestSupportedVersion() && version != EXPERIMENTAL_VERSION)
throw H2O.fail("Found a schema with a version higher than the highest supported version; you probably want to bump the highest supported version: " + clz);
// NOTE: we now allow non-versioned schemas, for example base classes like ModelMetricsBase, so that we can fetch the metadata for them.
if (version > -1 && version != EXPERIMENTAL_VERSION) {
// Track highest version of all schemas; only valid after all are registered at startup time.
if (version > HIGHEST_SUPPORTED_VERSION)
throw H2O.fail("Found a schema with a version greater than the highest supported version of: " + getHighestSupportedVersion() + ": " + clz);
if (version > latest_version) {
synchronized (Schema.class) {
if (version > latest_version) latest_version = version;
}
}
}
Schema s = null;
try {
s = clz.newInstance();
} catch (Exception e) {
Log.err("Failed to instantiate schema class: " + clz + " because: " + e);
}
if (null != s) {
Log.debug("Registered Schema: " + clz.getSimpleName());
// Validate the fields:
SchemaMetadata meta = new SchemaMetadata(s);
for (SchemaMetadata.FieldMetadata field_meta : meta.fields) {
String name = field_meta.name;
if ("__meta".equals(name) || "__http_status".equals(name) || "_exclude_fields".equals(name) || "_include_fields".equals(name))
continue;
if ("Gini".equals(name)) // proper name
continue;
if (name.endsWith("AUC")) // trainAUC, validAUC
continue;
// TODO: remove after we move these into a TwoDimTable:
if ("F0point5".equals(name) || "F0point5_for_criteria".equals(name) || "F1_for_criteria".equals(name) || "F2_for_criteria".equals(name))
continue;
if (name.startsWith("_"))
Log.warn("Found schema field which violates the naming convention; name starts with underscore: " + meta.name + "." + name);
if (!name.equals(name.toLowerCase()) && !name.equals(name.toUpperCase())) // allow AUC but not residualDeviance
Log.warn("Found schema field which violates the naming convention; name has mixed lowercase and uppercase characters: " + meta.name + "." + name);
}
}
}
}
/**
* Create an appropriate implementation object and any child objects but does not fill them.
* The standard purpose of a createImpl without a fillImpl is to be able to get the default
* values for all the impl's fields.
* <p>
* For objects without children this method does all the required work. For objects
* with children the subclass will need to override, e.g. by calling super.createImpl()
* and then calling createImpl() on its children.
* <p>
* Note that impl objects for schemas which override this method don't need to have
* a default constructor (e.g., a Keyed object constructor can still create and set
* the Key), but they must not fill any fields which can be filled later from the schema.
* <p>
* TODO: We could handle the common case of children with the same field names here
* by finding all of our fields that are themselves Schemas.
* @throws H2OIllegalArgumentException if Class.newInstance fails
*/
public I createImpl() {
try {
return this.getImplClass().newInstance();
}
catch (Exception e) {
String msg = "Exception instantiating implementation object of class: " + this.getImplClass().toString() + " for schema class: " + this.getClass();
Log.err(msg + ": " + e);
H2OIllegalArgumentException heae = new H2OIllegalArgumentException(msg);
heae.initCause(e);
throw heae;
}
}
/** Fill an impl object and any children from this schema and its children. If a schema doesn't need to adapt any fields if does not need to override this method. */
public I fillImpl(I impl) {
PojoUtils.copyProperties(impl, this, PojoUtils.FieldNaming.CONSISTENT); // TODO: make field names in the impl classes consistent and remove
PojoUtils.copyProperties(impl, this, PojoUtils.FieldNaming.DEST_HAS_UNDERSCORES);
return impl;
}
/** Convenience helper which creates and fills an impl object from this schema. */
final public I createAndFillImpl() {
return this.fillImpl(this.createImpl());
}
/** Fill this Schema from the given implementation object. If a schema doesn't need to adapt any fields if does not need to override this method. */
public S fillFromImpl(I impl) {
PojoUtils.copyProperties(this, impl, PojoUtils.FieldNaming.ORIGIN_HAS_UNDERSCORES);
PojoUtils.copyProperties(this, impl, PojoUtils.FieldNaming.CONSISTENT); // TODO: make field names in the impl classes consistent and remove
return (S)this;
}
/** Return the class of the implementation type parameter I for the given Schema class. Used by the metadata facilities and the reflection-base field-copying magic in PojoUtils. */
public static Class<? extends Iced> getImplClass(Class<? extends Schema> clz) {
Class<? extends Iced> impl_class = (Class<? extends Iced>)ReflectionUtils.findActualClassParameter(clz, 0);
if (null == impl_class)
Log.warn("Failed to find an impl class for Schema: " + clz);
return impl_class;
}
/** Return the class of the implementation type parameter I for this Schema. Used by generic code which deals with arbitrary schemas and their backing impl classes. */
public Class<I> getImplClass() {
if (null == _impl_class)
_impl_class = (Class<I>) ReflectionUtils.findActualClassParameter(this.getClass(), 0);
if (null == _impl_class)
Log.warn("Failed to find an impl class for Schema: " + this.getClass());
return _impl_class;
}
/**
* Fill this Schema object from a set of parameters.
*
* @param parms parameters - set of tuples (parameter name, parameter value)
* @return this schema
*
* @see #fillFromParms(Properties, boolean)
*/
public S fillFromParms(Properties parms) {
return fillFromParms(parms, true);
}
/**
* Fill this Schema from a set of (generally HTTP) parameters.
* <p>
* Using reflection this process determines the type of the target field and
* conforms the types if possible. For example, if the field is a Keyed type
* the name (ID) will be looked up in the DKV and mapped appropriately.
* <p>
* The process ignores parameters which are not fields in the schema, and it
* verifies that all fields marked as required are present in the parameters
* list.
* <p>
* It also does various sanity checks for broken Schemas, for example fields must
* not be private, and since input fields get filled here they must not be final.
* @param parms Properties map of parameter values
* @param checkRequiredFields perform check for missing required fields
* @return this schema
* @throws H2OIllegalArgumentException for bad/missing parameters
*/
public S fillFromParms(Properties parms, boolean checkRequiredFields) {
// Get passed-in fields, assign into Schema
Class thisSchemaClass = this.getClass();
Map<String, Field> fields = new HashMap<>();
Field current = null; // declare here so we can print in catch{}
try {
Class clz = thisSchemaClass;
do {
Field[] some_fields = clz.getDeclaredFields();
for (Field f : some_fields) {
current = f;
if (null == fields.get(f.getName()))
fields.put(f.getName(), f);
}
clz = clz.getSuperclass();
} while (Iced.class.isAssignableFrom(clz.getSuperclass()));
}
catch (SecurityException e) {
throw H2O.fail("Exception accessing field: " + current + " in class: " + this.getClass() + ": " + e);
}
for( String key : parms.stringPropertyNames() ) {
try {
Field f = fields.get(key); // No such field error, if parm is junk
if (null == f) {
throw new H2OIllegalArgumentException("Unknown parameter: " + key, "Unknown parameter in fillFromParms: " + key + " for class: " + this.getClass().toString());
}
int mods = f.getModifiers();
if( Modifier.isTransient(mods) || Modifier.isStatic(mods) ) {
// Attempting to set a transient or static; treat same as junk fieldname
throw new H2OIllegalArgumentException(
"Bad parameter for field: " + key + " for class: " + this.getClass().toString(),
"Bad parameter definition for field: " + key + " in fillFromParms for class: " + this.getClass().toString() + " (field was declared static or transient)");
}
// Only support a single annotation which is an API, and is required
API api = (API)f.getAnnotations()[0];
// Must have one of these set to be an input field
if( api.direction() == API.Direction.OUTPUT ) {
throw new H2OIllegalArgumentException(
"Attempting to set output field: " + key + " for class: " + this.getClass().toString(),
"Attempting to set output field: " + key + " in fillFromParms for class: " + this.getClass().toString() + " (field was annotated as API.Direction.OUTPUT)");
}
// Parse value and set the field
setField(this, f, key, parms.getProperty(key), api.required(), thisSchemaClass);
} catch( ArrayIndexOutOfBoundsException aioobe ) {
// Come here if missing annotation
throw H2O.fail("Broken internal schema; missing API annotation for field: " + key);
} catch( IllegalAccessException iae ) {
// Come here if field is final or private
throw H2O.fail("Broken internal schema; field cannot be private nor final: " + key);
}
}
// Here every thing in 'parms' was set into some field - so we have already
// checked for unknown or extra parms.
// Confirm required fields are set
if (checkRequiredFields) {
for (Field f : fields.values()) {
int mods = f.getModifiers();
if (Modifier.isTransient(mods) || Modifier.isStatic(mods))
continue; // Ignore transient & static
try {
API
api =
(API) f.getAnnotations()[0]; // TODO: is there a more specific way we can do this?
if (api.required()) {
if (parms.getProperty(f.getName()) == null) {
IcedHashMap.IcedHashMapStringObject
values =
new IcedHashMap.IcedHashMapStringObject();
values.put("schema", this.getClass().getSimpleName());
values.put("argument", f.getName());
throw new H2OIllegalArgumentException(
"Required field " + f.getName() + " not specified",
"Required field " + f.getName() + " not specified for schema class: " + this
.getClass(),
values);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw H2O.fail("Missing annotation for API field: " + f.getName());
}
}
}
return (S) this;
}
/**
* Safe method to set the field on given schema object
* @param o schema object to modify
* @param f field to modify
* @param key name of field to modify
* @param value string-based representation of value to set
* @param required is field required by API
* @param thisSchemaClass class of schema handling this (can be null)
* @throws IllegalAccessException
*/
public static <T extends Schema> void setField(T o, Field f, String key, String value, boolean required, Class thisSchemaClass) throws IllegalAccessException {
// Primitive parse by field type
Object parse_result = parse(key, value, f.getType(), required, thisSchemaClass);
if (parse_result != null && f.getType().isArray() && parse_result.getClass().isArray() && (f.getType().getComponentType() != parse_result.getClass().getComponentType())) {
// We have to conform an array of primitives. There's got to be a better way. . .
if (parse_result.getClass().getComponentType() == int.class && f.getType().getComponentType() == Integer.class) {
int[] from = (int[])parse_result;
Integer[] copy = new Integer[from.length];
for (int i = 0; i < from.length; i++)
copy[i] = from[i];
f.set(o, copy);
} else if (parse_result.getClass().getComponentType() == Integer.class && f.getType().getComponentType() == int.class) {
Integer[] from = (Integer[])parse_result;
int[] copy = new int[from.length];
for (int i = 0; i < from.length; i++)
copy[i] = from[i];
f.set(o, copy);
} else if (parse_result.getClass().getComponentType() == Double.class && f.getType().getComponentType() == double.class) {
Double[] from = (Double[])parse_result;
double[] copy = new double[from.length];
for (int i = 0; i < from.length; i++)
copy[i] = from[i];
f.set(o, copy);
} else if (parse_result.getClass().getComponentType() == Float.class && f.getType().getComponentType() == float.class) {
Float[] from = (Float[])parse_result;
float[] copy = new float[from.length];
for (int i = 0; i < from.length; i++)
copy[i] = from[i];
f.set(o, copy);
} else {
throw H2O.fail("Don't know how to cast an array of: " + parse_result.getClass().getComponentType() + " to an array of: " + f.getType().getComponentType());
}
} else {
f.set(o, parse_result);
}
}
static <E> Object parsePrimitve(String s, Class fclz) {
if (fclz.equals(String.class)) return s; // Strings already the right primitive type
if (fclz.equals(int.class)) return parseInteger(s, int.class);
if (fclz.equals(long.class)) return parseInteger(s, long.class);
if (fclz.equals(short.class)) return parseInteger(s, short.class);
if (fclz.equals(boolean.class)) {
if (s.equals("0")) return Boolean.FALSE;
if (s.equals("1")) return Boolean.TRUE;
return Boolean.valueOf(s);
}
if (fclz.equals(byte.class)) return parseInteger(s, byte.class);
if (fclz.equals(double.class)) return Double.valueOf(s);
if (fclz.equals(float.class)) return Float.valueOf(s);
//FIXME: if (fclz.equals(char.class)) return Character.valueOf(s);
throw H2O.fail("Unknown primitive type to parse: " + fclz.getSimpleName());
}
// URL parameter parse
static <E> Object parse(String field_name, String s, Class fclz, boolean required, Class schemaClass) {
if (fclz.isPrimitive() || String.class.equals(fclz)) {
try {
return parsePrimitve(s, fclz);
} catch (NumberFormatException ne) {
String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": cannot convert \"" + s + "\" to type " + fclz.getSimpleName();
throw new H2OIllegalArgumentException(msg);
}
}
// An array?
if (fclz.isArray()) {
// Get component type
Class<E> afclz = (Class<E>) fclz.getComponentType();
// Result
E[] a = null;
// Handle simple case with null-array
if (s.equals("null") || s.length() == 0) return null;
// Splitted values
String[] splits; // "".split(",") => {""} so handle the empty case explicitly
if (s.startsWith("[") && s.endsWith("]") ) { // It looks like an array
read(s, 0, '[', fclz);
read(s, s.length() - 1, ']', fclz);
String inside = s.substring(1, s.length() - 1).trim();
if (inside.length() == 0)
splits = new String[]{};
else
splits = splitArgs(inside);
} else { // Lets try to parse single value as an array!
// See PUBDEV-1955
splits = new String[] { s.trim() };
}
// Can't cast an int[] to an Object[]. Sigh.
if (afclz == int.class) { // TODO: other primitive types. . .
a = (E[]) Array.newInstance(Integer.class, splits.length);
} else if (afclz == double.class) {
a = (E[]) Array.newInstance(Double.class, splits.length);
} else if (afclz == float.class) {
a = (E[]) Array.newInstance(Float.class, splits.length);
} else {
// Fails with primitive classes; need the wrapper class. Thanks, Java.
a = (E[]) Array.newInstance(afclz, splits.length);
}
for (int i = 0; i < splits.length; i++) {
if (String.class == afclz || KeyV3.class.isAssignableFrom(afclz)) {
// strip quotes off string values inside array
String stripped = splits[i].trim();
if ("null".equals(stripped)) {
a[i] = null;
} else if (!stripped.startsWith("\"") || !stripped.endsWith("\"")) {
String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": string and key arrays' values must be double quoted, but the client sent: " + stripped;
IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject();
values.put("function", fclz.getSimpleName() + ".fillFromParms()");
values.put("argument", field_name);
values.put("value", stripped);
throw new H2OIllegalArgumentException(msg, msg, values);
}
stripped = stripped.substring(1, stripped.length() - 1);
a[i] = (E) parse(field_name, stripped, afclz, required, schemaClass);
} else {
a[i] = (E) parse(field_name, splits[i].trim(), afclz, required, schemaClass);
}
}
return a;
}
if (fclz.equals(Key.class))
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
else if (!required && (s == null || s.length() == 0)) return null;
else
return Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s); // If the key name is in an array we need to trim surrounding quotes.
if (KeyV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
if (!required && (s == null || s.length() == 0)) return null;
return KeyV3.make(fclz, Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s)); // If the key name is in an array we need to trim surrounding quotes.
}
if (Enum.class.isAssignableFrom(fclz))
return Enum.valueOf(fclz, s); // TODO: try/catch needed!
// TODO: these can be refactored into a single case using the facilities in Schema:
if (FrameV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s);
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (!v.isFrame()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Frame", v.get().getClass());
return new FrameV3((Frame) v.get()); // TODO: version!
}
}
if (JobV3.class.isAssignableFrom(fclz)) {
if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(s);
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (!v.isJob()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Job", v.get().getClass());
return new JobV3().fillFromImpl((Job) v.get()); // TODO: version!
}
}
// TODO: for now handle the case where we're only passing the name through; later we need to handle the case
// where the frame name is also specified.
if (FrameV3.ColSpecifierV3.class.isAssignableFrom(fclz)) {
return new FrameV3.ColSpecifierV3(s);
}
if (ModelSchema.class.isAssignableFrom(fclz))
throw H2O.fail("Can't yet take ModelSchema as input.");
/*
if( (s==null || s.length()==0) && required ) throw new IllegalArgumentException("Missing key");
else if (!required && (s == null || s.length() == 0)) return null;
else {
Value v = DKV.get(s);
if (null == v) return null; // not required
if (! v.isModel()) throw new IllegalArgumentException("Model argument points to a non-model object.");
return v.get();
}
*/
throw H2O.fail("Unimplemented schema fill from " + fclz.getSimpleName());
} // parse()
/**
* Helper functions for parse()
**/
/**
* Parses a string into an integer data type specified by parameter return_type. Accepts any format that
* is accepted by java's BigDecimal class.
* - Throws a NumberFormatException if the evaluated string is not an integer or if the value is too large to
* be stored into return_type without overflow.
* - Throws an IllegalAgumentException if return_type is not an integer data type.
**/
static private <T> T parseInteger(String s, Class<T> return_type) {
try {
java.math.BigDecimal num = new java.math.BigDecimal(s);
T result = (T) num.getClass().getDeclaredMethod(return_type.getSimpleName() + "ValueExact", new Class[0]).invoke(num);
return result;
} catch (InvocationTargetException ite) {
throw new NumberFormatException("The expression's numeric value is out of the range of type " + return_type.getSimpleName());
} catch (NoSuchMethodException nsme) {
throw new IllegalArgumentException(return_type.getSimpleName() + " is not an integer data type");
} catch (IllegalAccessException iae) {
throw H2O.fail("Cannot parse expression as " + return_type.getSimpleName() + " (Illegal Access)");
}
}
static private int read( String s, int x, char c, Class fclz ) {
if( peek(s,x,c) ) return x+1;
throw new IllegalArgumentException("Expected '"+c+"' while reading a "+fclz.getSimpleName()+", but found "+s);
}
static private boolean peek( String s, int x, char c ) { return x < s.length() && s.charAt(x) == c; }
// Splits on commas, but ignores commas in double quotes. Required
// since using a regex blow the stack on long column counts
// TODO: detect and complain about malformed JSON
private static String[] splitArgs(String argStr) {
StringBuffer sb = new StringBuffer (argStr);
StringBuffer arg = new StringBuffer ();
List<String> splitArgList = new ArrayList<String> ();
boolean inDoubleQuotes = false;
boolean inSquareBrackets = false; // for arrays of arrays
for (int i=0; i < sb.length(); i++) {
if (sb.charAt(i) == '"' && !inDoubleQuotes && !inSquareBrackets) {
inDoubleQuotes = true;
arg.append(sb.charAt(i));
} else if (sb.charAt(i) == '"' && inDoubleQuotes && !inSquareBrackets) {
inDoubleQuotes = false;
arg.append(sb.charAt(i));
} else if (sb.charAt(i) == ',' && !inDoubleQuotes && !inSquareBrackets) {
splitArgList.add(arg.toString());
// clear the field for next word
arg.setLength(0);
} else if (sb.charAt(i) == '[') {
inSquareBrackets = true;
arg.append(sb.charAt(i));
} else if (sb.charAt(i) == ']') {
inSquareBrackets = false;
arg.append(sb.charAt(i));
} else {
arg.append(sb.charAt(i));
}
}
if (arg.length() > 0)
splitArgList.add(arg.toString());
return splitArgList.toArray(new String[splitArgList.size()]);
}
private static boolean schemas_registered = false;
/**
* Find all schemas using reflection and register them.
*/
synchronized static public void registerAllSchemasIfNecessary() {
if (schemas_registered) return;
// if (!Paxos._cloudLocked) return; // TODO: It's never getting locked. . . :-(
long before = System.currentTimeMillis();
// Microhack to effect Schema.register(Schema.class), which is
// normally not allowed because it has no version:
new Schema();
String[] packages = new String[] { "water", "hex", /* Disallow schemas whose parent is in another package because it takes ~4s to do the getSubTypesOf call: "" */};
// For some reason when we're run under Hadoop Reflections is failing to find some of the classes unless we're extremely explicit here:
Class<? extends Schema> clzs[] = new Class[] { Schema.class, ModelBuilderSchema.class, ModelSchema.class, ModelOutputSchema.class, ModelParametersSchema.class };
for (String pkg : packages) {
Reflections reflections = new Reflections(pkg);
for (Class<? extends Schema> clz : clzs) {
// NOTE: Reflections sees ModelOutputSchema but not ModelSchema. Another bug to work around:
Log.debug("Registering: " + clz.toString() + " in package: " + pkg);
if (!Modifier.isAbstract(clz.getModifiers()))
Schema.register(clz);
// Register the subclasses:
Log.debug("Registering subclasses of: " + clz.toString() + " in package: " + pkg);
for (Class<? extends Schema> schema_class : reflections.getSubTypesOf(clz))
if (!Modifier.isAbstract(schema_class.getModifiers()))
Schema.register(schema_class);
}
}
schemas_registered = true;
Log.info("Registered: " + Schema.schemas().size() + " schemas in: " + (System.currentTimeMillis() - before) + "mS");
}
/**
* Return an immutable Map of all the schemas: schema_name -> schema Class.
*/
protected static Map<String, Class<? extends Schema>> schemas() {
return Collections.unmodifiableMap(new HashMap<>(schemas));
}
/**
* For a given version and Iced class return the appropriate Schema class, if any.f
* @see #schemaClass(int, java.lang.String)
*/
protected static Class<? extends Schema> schemaClass(int version, Class<? extends Iced> impl_class) {
return schemaClass(version, impl_class.getSimpleName());
}
/**
* For a given version and type (Iced class simpleName) return the appropriate Schema
* class, if any.
* <p>
* If a higher version is asked for than is available (e.g., if the highest version of
* Frame is FrameV2 and the client asks for the schema for (Frame, 17) then FrameV2 will
* be returned. This compatibility lookup is cached.
*/
private static Class<? extends Schema> schemaClass(int version, String type) {
if (version < 1) return null;
Class<? extends Schema> clz = iced_to_schema.get(new Pair(type, version));
if (null != clz) return clz; // found!
clz = schemaClass(version - 1, type);
if (null != clz) iced_to_schema.put(new Pair(type, version), clz); // found a lower-numbered schema: cache
return clz;
}
/**
* For a given version and Iced object return an appropriate Schema instance, if any.
* @see #schema(int, java.lang.String)
*/
public static Schema schema(int version, Iced impl) {
return schema(version, impl.getClass().getSimpleName());
}
/**
* For a given version and Iced class return an appropriate Schema instance, if any.
* @throws H2OIllegalArgumentException if Class.newInstance() throws
* @see #schema(int, java.lang.String)
*/
public static Schema schema(int version, Class<? extends Iced> impl_class) {
return schema(version, impl_class.getSimpleName());
}
// FIXME: can be parameterized by type: public static <T extends Schema> T newInstance(Class<T> clz)
public static <T extends Schema> T newInstance(Class<T> clz) {
T s = null;
try {
s = clz.newInstance();
}
catch (Exception e) {
throw new H2OIllegalArgumentException("Failed to instantiate schema of class: " + clz.getCanonicalName() + ", cause: " + e);
}
return s;
}
/**
* For a given version and type (Iced class simpleName) return an appropriate new Schema
* object, if any.
* <p>
* If a higher version is asked for than is available (e.g., if the highest version of
* Frame is FrameV2 and the client asks for the schema for (Frame, 17) then an instance
* of FrameV2 will be returned. This compatibility lookup is cached.
* @throws H2ONotFoundArgumentException if an appropriate schema is not found
*/
private static Schema schema(int version, String type) {
Class<? extends Schema> clz = schemaClass(version, type);
if (null == clz)
clz = schemaClass(Schema.getExperimentalVersion(), type);
if (null == clz)
throw new H2ONotFoundArgumentException("Failed to find schema for version: " + version + " and type: " + type,
"Failed to find schema for version: " + version + " and type: " + type);
return Schema.newInstance(clz);
}
/**
* For a given schema_name (e.g., "FrameV2") return an appropriate new schema object (e.g., a water.api.Framev2).
* @throws H2ONotFoundArgumentException if an appropriate schema is not found
*/
protected static Schema newInstance(String schema_name) {
Class<? extends Schema> clz = schemas.get(schema_name);
if (null == clz) throw new H2ONotFoundArgumentException("Failed to find schema for schema_name: " + schema_name,
"Failed to find schema for schema_name: " + schema_name);
return Schema.newInstance(clz);
}
/**
* Generate Markdown documentation for this Schema possibly including only the input or output fields.
* @throws H2ONotFoundArgumentException if reflection on a field fails
*/
public StringBuffer markdown(StringBuffer appendToMe, boolean include_input_fields, boolean include_output_fields) {
return markdown(new SchemaMetadata(this), appendToMe, include_input_fields, include_output_fields);
}
/**
* Append Markdown documentation for another Schema, given we already have the metadata constructed.
* @throws H2ONotFoundArgumentException if reflection on a field fails
*/
public StringBuffer markdown(SchemaMetadata meta, StringBuffer appendToMe) {
return markdown(meta, appendToMe, true, true);
}
/**
* Generate Markdown documentation for this Schema, given we already have the metadata constructed.
* @throws H2ONotFoundArgumentException if reflection on a field fails
*/
public StringBuffer markdown(SchemaMetadata meta , StringBuffer appendToMe, boolean include_input_fields, boolean include_output_fields) {
MarkdownBuilder builder = new MarkdownBuilder();
builder.comment("Preview with http://jbt.github.io/markdown-editor");
builder.heading1("schema ", this.getClass().getSimpleName());
builder.hline();
// builder.paragraph(metadata.summary);
// TODO: refactor with Route.markdown():
// fields
boolean first; // don't print the table at all if there are no rows
try {
if (include_input_fields) {
first = true;
builder.heading2("input fields");
for (SchemaMetadata.FieldMetadata field_meta : meta.fields) {
if (field_meta.direction == API.Direction.INPUT || field_meta.direction == API.Direction.INOUT) {
if (first) {
builder.tableHeader("name", "required?", "level", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with");
first = false;
}
builder.tableRow(
field_meta.name,
String.valueOf(field_meta.required),
field_meta.level.name(),
field_meta.type,
String.valueOf(field_meta.is_schema),
field_meta.is_schema ? field_meta.schema_name : "", (null == field_meta.value ? "(null)" : field_meta.value.toString()), // Something better for toString()?
field_meta.help,
(field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)),
(field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)),
(field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with))
);
}
}
if (first)
builder.paragraph("(none)");
}
if (include_output_fields) {
first = true;
builder.heading2("output fields");
for (SchemaMetadata.FieldMetadata field_meta : meta.fields) {
if (field_meta.direction == API.Direction.OUTPUT || field_meta.direction == API.Direction.INOUT) {
if (first) {
builder.tableHeader("name", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with");
first = false;
}
builder.tableRow(
field_meta.name,
field_meta.type,
String.valueOf(field_meta.is_schema),
field_meta.is_schema ? field_meta.schema_name : "",
(null == field_meta.value ? "(null)" : field_meta.value.toString()), // something better than toString()?
field_meta.help,
(field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)),
(field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)),
(field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with)));
}
}
if (first)
builder.paragraph("(none)");
}
// TODO: render examples and other stuff, if it's passed in
}
catch (Exception e) {
IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject();
values.put("schema", this);
// TODO: This isn't quite the right exception type:
throw new H2OIllegalArgumentException("Caught exception using reflection on schema: " + this,
"Caught exception using reflection on schema: " + this + ": " + e,
values);
}
if (null != appendToMe)
appendToMe.append(builder.stringBuffer());
return builder.stringBuffer();
} // markdown()
}
| madmax983/h2o-3 | h2o-core/src/main/java/water/api/Schema.java | Java | apache-2.0 | 52,870 |
package eu.uqasar.model.measure;
/*
* #%L
* U-QASAR
* %%
* Copyright (C) 2012 - 2015 U-QASAR Consortium
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.wicket.model.IModel;
import eu.uqasar.util.resources.IResourceKeyProvider;
import eu.uqasar.util.resources.ResourceBundleLocator;
public enum MetricSource implements IResourceKeyProvider {
TestingFramework("test"),
IssueTracker("issue"),
StaticAnalysis("static"),
ContinuousIntegration("ci"),
CubeAnalysis("cube"),
VersionControl("vcs"),
Manual("manual"),
;
private final String labelKey;
MetricSource(final String labelKey) {
this.labelKey = labelKey;
}
public String toString() {
return getLabelModel().getObject();
}
public IModel<String> getLabelModel() {
return ResourceBundleLocator.getLabelModel(this.getClass(), this);
}
@Override
public String getKey() {
return "label.source." + this.labelKey;
}
public static List<MetricSource> getAllMetricSources(){
List<MetricSource> list = new ArrayList<>();
Collections.addAll(list, MetricSource.values());
return list;
}
}
| U-QASAR/u-qasar.platform | src/main/java/eu/uqasar/model/measure/MetricSource.java | Java | apache-2.0 | 1,796 |
package com.feiyu.storm.streamingdatacollection.spout;
/**
* from https://github.com/apache/incubator-storm/blob/master/examples/storm-starter/src/jvm/storm/starter/spout/RandomSentenceSpout.java
* modified by feiyu
*/
import java.util.Map;
import java.util.Random;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;
@SuppressWarnings("serial")
public class ForTestFakeSpout extends BaseRichSpout {
private SpoutOutputCollector _collector;
private Random _rand;
@SuppressWarnings("rawtypes")
@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
_collector = collector;
_rand = new Random();
}
@Override
public void nextTuple() {
Utils.sleep(5000);
String[] tweets = new String[]{
"I rated X-Men: Days of Future Past 8/10 #IMDb http://www.imdb.com/title/tt1877832",
"I rated Game of Thrones 10/10 #IMDb http://www.imdb.com/title/tt0944947",
"I rated Snowpiercer 7/10 #IMDb really enjoyed this. Beautifully shot & choreographed. Great performance from Swinton http://www.imdb.com/title/tt1706620",
"Back on form. That ending = awesome! - I rated X-Men: Days of Future Past 7/10 #IMDb http://www.imdb.com/title/tt1877832",
"A great movie especially for those trying to learn German ~> I rated Run Lola Run 8/10 #IMDb http://www.imdb.com/title/tt0130827",
"I rated Breaking Bad 8/10 #IMDb :: I would say 7 but last season made it worth it... Matter of taste @mmelgarejoc http://www.imdb.com/title/tt0903747",
"I rated White House Down 7/10 #IMDb bunch of explosions and one liners, fun for all http://www.imdb.com/title/tt2334879"
};
String tweet = tweets[_rand.nextInt(tweets.length)];
_collector.emit(new Values(tweet));
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("tweet"));
}
}
| faustineinsun/WiseCrowdRec | deprecated-wisecrowdrec-springmvc/WiseCrowdRec/src/main/java/com/feiyu/storm/streamingdatacollection/spout/ForTestFakeSpout.java | Java | apache-2.0 | 2,356 |
/*
* Copyright 2016 Axibase Corporation 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
*
* https://www.axibase.com/atsd/axibase-apache-2.0.pdf
*
* 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.axibase.tsd.model.meta;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.Map;
@Data
/* Use chained setters that return this instead of void */
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class EntityAndTags {
@JsonProperty("entity")
private String entityName;
private Long lastInsertTime;
@JsonProperty
private Map<String, String> tags;
}
| axibase/atsd-api-java | src/main/java/com/axibase/tsd/model/meta/EntityAndTags.java | Java | apache-2.0 | 1,151 |
package br.com.ceducarneiro.analisadorsintatico;
public class LexException extends Exception {
private char badCh;
private int line, column;
public LexException(int line, int column, char ch) {
badCh = ch;
this.line = line;
this.column = column;
}
@Override
public String toString() {
return String.format("Caractere inesperado: \"%s\" na linha %d coluna %d", badCh != 0 ? badCh : "EOF", line, column);
}
}
| edu1910/AnalisadorSintatico | src/br/com/ceducarneiro/analisadorsintatico/LexException.java | Java | apache-2.0 | 473 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudtasks.v2.model;
/**
* Encapsulates settings provided to GetIamPolicy.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Tasks API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GetPolicyOptions extends com.google.api.client.json.GenericJson {
/**
* Optional. The maximum policy version that will be used to format the policy. Valid values are
* 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with
* any conditional role bindings must specify version 3. Policies with no conditional role
* bindings may specify any valid value or leave the field unset. The policy in the response might
* use the policy version that you specified, or it might use a lower policy version. For example,
* if you specify version 3, but the policy has no conditional role bindings, the response uses
* version 1. To learn which resources support conditions in their IAM policies, see the [IAM
* documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer requestedPolicyVersion;
/**
* Optional. The maximum policy version that will be used to format the policy. Valid values are
* 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with
* any conditional role bindings must specify version 3. Policies with no conditional role
* bindings may specify any valid value or leave the field unset. The policy in the response might
* use the policy version that you specified, or it might use a lower policy version. For example,
* if you specify version 3, but the policy has no conditional role bindings, the response uses
* version 1. To learn which resources support conditions in their IAM policies, see the [IAM
* documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* @return value or {@code null} for none
*/
public java.lang.Integer getRequestedPolicyVersion() {
return requestedPolicyVersion;
}
/**
* Optional. The maximum policy version that will be used to format the policy. Valid values are
* 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with
* any conditional role bindings must specify version 3. Policies with no conditional role
* bindings may specify any valid value or leave the field unset. The policy in the response might
* use the policy version that you specified, or it might use a lower policy version. For example,
* if you specify version 3, but the policy has no conditional role bindings, the response uses
* version 1. To learn which resources support conditions in their IAM policies, see the [IAM
* documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
* @param requestedPolicyVersion requestedPolicyVersion or {@code null} for none
*/
public GetPolicyOptions setRequestedPolicyVersion(java.lang.Integer requestedPolicyVersion) {
this.requestedPolicyVersion = requestedPolicyVersion;
return this;
}
@Override
public GetPolicyOptions set(String fieldName, Object value) {
return (GetPolicyOptions) super.set(fieldName, value);
}
@Override
public GetPolicyOptions clone() {
return (GetPolicyOptions) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-cloudtasks/v2/1.31.0/com/google/api/services/cloudtasks/v2/model/GetPolicyOptions.java | Java | apache-2.0 | 4,445 |
/*
* Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.client.impl.spi.impl.discovery;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientAutoDetectionDiscoveryTest extends HazelcastTestSupport {
@After
public void tearDown() {
Hazelcast.shutdownAll();
}
@Test
public void defaultDiscovery() {
Hazelcast.newHazelcastInstance();
Hazelcast.newHazelcastInstance();
HazelcastInstance client = HazelcastClient.newHazelcastClient();
assertClusterSizeEventually(2, client);
}
@Test
public void autoDetectionDisabled() {
Config config = new Config();
config.getNetworkConfig().getJoin().getAutoDetectionConfig().setEnabled(false);
Hazelcast.newHazelcastInstance(config);
Hazelcast.newHazelcastInstance(config);
ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().getAutoDetectionConfig().setEnabled(false);
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
// uses 127.0.0.1 and finds only one standalone member
assertClusterSizeEventually(1, client);
}
@Test
public void autoDetectionNotUsedWhenOtherDiscoveryEnabled() {
Config config = new Config();
config.getNetworkConfig().setPort(5710);
config.getNetworkConfig().getJoin().getAutoDetectionConfig().setEnabled(false);
Hazelcast.newHazelcastInstance(config);
ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().addAddress("127.0.0.1:5710");
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
assertClusterSizeEventually(1, client);
}
}
| mdogan/hazelcast | hazelcast/src/test/java/com/hazelcast/client/impl/spi/impl/discovery/ClientAutoDetectionDiscoveryTest.java | Java | apache-2.0 | 2,849 |
package me.banxi.androiddemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity{
public void onCreate(Bundle bundle){
super.onCreate(bundle);
TextView textView = new TextView(this);
textView.setText("Hello,World");
setContentView(textView);
}
}
| banxi1988/android-demo | src/main/java/me/banxi/androiddemo/MainActivity.java | Java | apache-2.0 | 366 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.server;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServers;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class ExpiryRunnerTest extends ActiveMQTestBase {
private ActiveMQServer server;
private ClientSession clientSession;
private final SimpleString qName = new SimpleString("ExpiryRunnerTestQ");
private final SimpleString qName2 = new SimpleString("ExpiryRunnerTestQ2");
private SimpleString expiryQueue;
private SimpleString expiryAddress;
private ServerLocator locator;
@Test
public void testBasicExpire() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
int numMessages = 100;
long expiration = System.currentTimeMillis();
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer.send(m);
}
Thread.sleep(1600);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
}
@Test
public void testExpireFromMultipleQueues() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
clientSession.createQueue(qName2, qName2, null, false);
AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress);
server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings);
ClientProducer producer2 = clientSession.createProducer(qName2);
int numMessages = 100;
long expiration = System.currentTimeMillis();
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer.send(m);
m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer2.send(m);
}
Thread.sleep(1600);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
}
@Test
public void testExpireHalf() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
int numMessages = 100;
long expiration = System.currentTimeMillis();
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
if (i % 2 == 0) {
m.setExpiration(expiration);
}
producer.send(m);
}
Thread.sleep(1600);
Assert.assertEquals(numMessages / 2, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
}
@Test
public void testExpireConsumeHalf() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
int numMessages = 100;
long expiration = System.currentTimeMillis() + 1000;
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer.send(m);
}
ClientConsumer consumer = clientSession.createConsumer(qName);
clientSession.start();
for (int i = 0; i < numMessages / 2; i++) {
ClientMessage cm = consumer.receive(500);
Assert.assertNotNull("message not received " + i, cm);
cm.acknowledge();
Assert.assertEquals("m" + i, cm.getBodyBuffer().readString());
}
consumer.close();
Thread.sleep(2100);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
}
@Test
public void testExpireToExpiryQueue() throws Exception {
AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress);
server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings);
clientSession.deleteQueue(qName);
clientSession.createQueue(qName, qName, null, false);
clientSession.createQueue(qName, qName2, null, false);
ClientProducer producer = clientSession.createProducer(qName);
int numMessages = 100;
long expiration = System.currentTimeMillis();
for (int i = 0; i < numMessages; i++) {
ClientMessage m = createTextMessage(clientSession, "m" + i);
m.setExpiration(expiration);
producer.send(m);
}
Thread.sleep(1600);
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount());
Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount());
ClientConsumer consumer = clientSession.createConsumer(expiryQueue);
clientSession.start();
for (int i = 0; i < numMessages; i++) {
ClientMessage cm = consumer.receive(500);
Assert.assertNotNull(cm);
// assertEquals("m" + i, cm.getBody().getString());
}
for (int i = 0; i < numMessages; i++) {
ClientMessage cm = consumer.receive(500);
Assert.assertNotNull(cm);
// assertEquals("m" + i, cm.getBody().getString());
}
consumer.close();
}
@Test
public void testExpireWhilstConsumingMessagesStillInOrder() throws Exception {
ClientProducer producer = clientSession.createProducer(qName);
ClientConsumer consumer = clientSession.createConsumer(qName);
CountDownLatch latch = new CountDownLatch(1);
DummyMessageHandler dummyMessageHandler = new DummyMessageHandler(consumer, latch);
clientSession.start();
Thread thr = new Thread(dummyMessageHandler);
thr.start();
long expiration = System.currentTimeMillis() + 1000;
int numMessages = 0;
long sendMessagesUntil = System.currentTimeMillis() + 2000;
do {
ClientMessage m = createTextMessage(clientSession, "m" + numMessages++);
m.setExpiration(expiration);
producer.send(m);
Thread.sleep(100);
} while (System.currentTimeMillis() < sendMessagesUntil);
Assert.assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
consumer.close();
consumer = clientSession.createConsumer(expiryQueue);
do {
ClientMessage cm = consumer.receive(2000);
if (cm == null) {
break;
}
String text = cm.getBodyBuffer().readString();
cm.acknowledge();
Assert.assertFalse(dummyMessageHandler.payloads.contains(text));
dummyMessageHandler.payloads.add(text);
} while (true);
for (int i = 0; i < numMessages; i++) {
if (dummyMessageHandler.payloads.isEmpty()) {
break;
}
Assert.assertTrue("m" + i, dummyMessageHandler.payloads.remove("m" + i));
}
consumer.close();
thr.join();
}
//
// public static void main(final String[] args) throws Exception
// {
// for (int i = 0; i < 1000; i++)
// {
// TestSuite suite = new TestSuite();
// ExpiryRunnerTest expiryRunnerTest = new ExpiryRunnerTest();
// expiryRunnerTest.setName("testExpireWhilstConsuming");
// suite.addTest(expiryRunnerTest);
//
// TestResult result = TestRunner.run(suite);
// if (result.errorCount() > 0 || result.failureCount() > 0)
// {
// System.exit(1);
// }
// }
// }
@Override
@Before
public void setUp() throws Exception {
super.setUp();
ConfigurationImpl configuration = (ConfigurationImpl) createDefaultInVMConfig().setMessageExpiryScanPeriod(1000);
server = addServer(ActiveMQServers.newActiveMQServer(configuration, false));
// start the server
server.start();
// then we create a client as normal
locator = createInVMNonHALocator().setBlockOnAcknowledge(true);
ClientSessionFactory sessionFactory = createSessionFactory(locator);
clientSession = sessionFactory.createSession(false, true, true);
clientSession.createQueue(qName, qName, null, false);
expiryAddress = new SimpleString("EA");
expiryQueue = new SimpleString("expiryQ");
AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress);
server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings);
server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings);
clientSession.createQueue(expiryAddress, expiryQueue, null, false);
}
private static class DummyMessageHandler implements Runnable {
List<String> payloads = new ArrayList<>();
private final ClientConsumer consumer;
private final CountDownLatch latch;
private DummyMessageHandler(final ClientConsumer consumer, final CountDownLatch latch) {
this.consumer = consumer;
this.latch = latch;
}
@Override
public void run() {
while (true) {
try {
ClientMessage message = consumer.receive(5000);
if (message == null) {
break;
}
message.acknowledge();
payloads.add(message.getBodyBuffer().readString());
Thread.sleep(110);
}
catch (Exception e) {
e.printStackTrace();
}
}
latch.countDown();
}
}
}
| lburgazzoli/apache-activemq-artemis | tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ExpiryRunnerTest.java | Java | apache-2.0 | 11,691 |
package org.plista.kornakapi.core.training.preferencechanges;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class DelegatingPreferenceChangeListenerForLabel implements PreferenceChangeListenerForLabel {
private final Map<String,List<PreferenceChangeListener>> delegates = Maps.newLinkedHashMap();
public void addDelegate(PreferenceChangeListener listener, String label) {
if(delegates.containsKey(label)){
delegates.get(label).add(listener);
}else{
List<PreferenceChangeListener> delegatesPerLabel = Lists.newArrayList();
delegatesPerLabel.add(listener);
delegates.put(label, delegatesPerLabel);
}
}
@Override
public void notifyOfPreferenceChange(String label) {
for (PreferenceChangeListener listener : delegates.get(label)) {
listener.notifyOfPreferenceChange();
}
}
}
| plista/kornakapi | src/main/java/org/plista/kornakapi/core/training/preferencechanges/DelegatingPreferenceChangeListenerForLabel.java | Java | apache-2.0 | 935 |
/**
* 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 tools.descartes.teastore.persistence.rest;
import java.util.ArrayList;
import java.util.List;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.QueryParam;
import tools.descartes.teastore.persistence.domain.OrderItemRepository;
import tools.descartes.teastore.persistence.repository.DataGenerator;
import tools.descartes.teastore.registryclient.util.AbstractCRUDEndpoint;
import tools.descartes.teastore.entities.OrderItem;
/**
* Persistence endpoint for for CRUD operations on orders.
* @author Joakim von Kistowski
*
*/
@Path("orderitems")
public class OrderItemEndpoint extends AbstractCRUDEndpoint<OrderItem> {
/**
* {@inheritDoc}
*/
@Override
protected long createEntity(final OrderItem orderItem) {
if (DataGenerator.GENERATOR.isMaintenanceMode()) {
return -1L;
}
return OrderItemRepository.REPOSITORY.createEntity(orderItem);
}
/**
* {@inheritDoc}
*/
@Override
protected OrderItem findEntityById(final long id) {
OrderItem item = OrderItemRepository.REPOSITORY.getEntity(id);
if (item == null) {
return null;
}
return new OrderItem(item);
}
/**
* {@inheritDoc}
*/
@Override
protected List<OrderItem> listAllEntities(final int startIndex, final int maxResultCount) {
List<OrderItem> orderItems = new ArrayList<OrderItem>();
for (OrderItem oi : OrderItemRepository.REPOSITORY.getAllEntities(startIndex, maxResultCount)) {
orderItems.add(new OrderItem(oi));
}
return orderItems;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean updateEntity(long id, OrderItem orderItem) {
return OrderItemRepository.REPOSITORY.updateEntity(id, orderItem);
}
/**
* {@inheritDoc}
*/
@Override
protected boolean deleteEntity(long id) {
if (DataGenerator.GENERATOR.isMaintenanceMode()) {
return false;
}
return OrderItemRepository.REPOSITORY.removeEntity(id);
}
/**
* Returns all order items with the given product Id (all order items for that product).
* @param productId The id of the product.
* @param startPosition The index (NOT ID) of the first order item with the product to return.
* @param maxResult The max number of order items to return.
* @return list of order items with the product.
*/
@GET
@Path("product/{product:[0-9][0-9]*}")
public List<OrderItem> listAllForProduct(@PathParam("product") final Long productId,
@QueryParam("start") final Integer startPosition,
@QueryParam("max") final Integer maxResult) {
if (productId == null) {
return listAll(startPosition, maxResult);
}
List<OrderItem> orderItems = new ArrayList<OrderItem>();
for (OrderItem oi : OrderItemRepository.REPOSITORY.getAllEntitiesWithProduct(productId,
parseIntQueryParam(startPosition), parseIntQueryParam(maxResult))) {
orderItems.add(new OrderItem(oi));
}
return orderItems;
}
/**
* Returns all order items with the given order Id (all order items for that order).
* @param orderId The id of the product.
* @param startPosition The index (NOT ID) of the first order item with the product to return.
* @param maxResult The max number of order items to return.
* @return list of order items with the product.
*/
@GET
@Path("order/{order:[0-9][0-9]*}")
public List<OrderItem> listAllForOrder(@PathParam("order") final Long orderId,
@QueryParam("start") final Integer startPosition,
@QueryParam("max") final Integer maxResult) {
if (orderId == null) {
return listAll(startPosition, maxResult);
}
List<OrderItem> orderItems = new ArrayList<OrderItem>();
for (OrderItem oi : OrderItemRepository.REPOSITORY.getAllEntitiesWithOrder(orderId,
parseIntQueryParam(startPosition), parseIntQueryParam(maxResult))) {
orderItems.add(new OrderItem(oi));
}
return orderItems;
}
}
| DescartesResearch/Pet-Supply-Store | services/tools.descartes.teastore.persistence/src/main/java/tools/descartes/teastore/persistence/rest/OrderItemEndpoint.java | Java | apache-2.0 | 4,492 |
package apple.mlcompute;
import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.foundation.protocol.NSCopying;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;
/**
* MLCRMSPropOptimizer
* <p>
* The MLCRMSPropOptimizer specifies the RMSProp optimizer.
*/
@Generated
@Library("MLCompute")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class MLCRMSPropOptimizer extends MLCOptimizer implements NSCopying {
static {
NatJ.register();
}
@Generated
protected MLCRMSPropOptimizer(Pointer peer) {
super(peer);
}
@Generated
@Selector("accessInstanceVariablesDirectly")
public static native boolean accessInstanceVariablesDirectly();
@Generated
@Owned
@Selector("alloc")
public static native MLCRMSPropOptimizer alloc();
@Owned
@Generated
@Selector("allocWithZone:")
public static native MLCRMSPropOptimizer allocWithZone(VoidPtr zone);
/**
* [@property] alpha
* <p>
* The smoothing constant.
* <p>
* The default is 0.99.
*/
@Generated
@Selector("alpha")
public native float alpha();
@Generated
@Selector("automaticallyNotifiesObserversForKey:")
public static native boolean automaticallyNotifiesObserversForKey(String key);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:")
public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
@Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
@Mapped(ObjCObjectMapper.class) Object anArgument);
@Generated
@Selector("classFallbacksForKeyedArchiver")
public static native NSArray<String> classFallbacksForKeyedArchiver();
@Generated
@Selector("classForKeyedUnarchiver")
public static native Class classForKeyedUnarchiver();
@Generated
@Owned
@Selector("copyWithZone:")
@MappedReturn(ObjCObjectMapper.class)
public native Object copyWithZone(VoidPtr zone);
@Generated
@Selector("debugDescription")
public static native String debugDescription_static();
@Generated
@Selector("description")
public static native String description_static();
/**
* [@property] epsilon
* <p>
* A term added to improve numerical stability.
* <p>
* The default is 1e-8.
*/
@Generated
@Selector("epsilon")
public native float epsilon();
@Generated
@Selector("hash")
@NUInt
public static native long hash_static();
@Generated
@Selector("init")
public native MLCRMSPropOptimizer init();
@Generated
@Selector("instanceMethodForSelector:")
@FunctionPtr(name = "call_instanceMethodForSelector_ret")
public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);
@Generated
@Selector("instanceMethodSignatureForSelector:")
public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);
@Generated
@Selector("instancesRespondToSelector:")
public static native boolean instancesRespondToSelector(SEL aSelector);
/**
* [@property] isCentered
* <p>
* If True, compute the centered RMSProp, the gradient is normalized by an estimation of its variance.
* <p>
* The default is false.
*/
@Generated
@Selector("isCentered")
public native boolean isCentered();
@Generated
@Selector("isSubclassOfClass:")
public static native boolean isSubclassOfClass(Class aClass);
@Generated
@Selector("keyPathsForValuesAffectingValueForKey:")
public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);
/**
* [@property] momentumScale
* <p>
* The momentum factor. A hyper-parameter.
* <p>
* The default is 0.0.
*/
@Generated
@Selector("momentumScale")
public native float momentumScale();
@Generated
@Owned
@Selector("new")
public static native MLCRMSPropOptimizer new_objc();
/**
* Create a MLCRMSPropOptimizer object with defaults
*
* @return A new MLCRMSPropOptimizer object.
*/
@Generated
@Selector("optimizerWithDescriptor:")
public static native MLCRMSPropOptimizer optimizerWithDescriptor(MLCOptimizerDescriptor optimizerDescriptor);
/**
* Create a MLCRMSPropOptimizer object
*
* @param optimizerDescriptor The optimizer descriptor object
* @param momentumScale The momentum scale
* @param alpha The smoothing constant value
* @param epsilon The epsilon value to use to improve numerical stability
* @param isCentered A boolean to specify whether to compute the centered RMSProp or not
* @return A new MLCRMSPropOptimizer object.
*/
@Generated
@Selector("optimizerWithDescriptor:momentumScale:alpha:epsilon:isCentered:")
public static native MLCRMSPropOptimizer optimizerWithDescriptorMomentumScaleAlphaEpsilonIsCentered(
MLCOptimizerDescriptor optimizerDescriptor, float momentumScale, float alpha, float epsilon,
boolean isCentered);
@Generated
@Selector("resolveClassMethod:")
public static native boolean resolveClassMethod(SEL sel);
@Generated
@Selector("resolveInstanceMethod:")
public static native boolean resolveInstanceMethod(SEL sel);
@Generated
@Selector("setVersion:")
public static native void setVersion_static(@NInt long aVersion);
@Generated
@Selector("superclass")
public static native Class superclass_static();
@Generated
@Selector("version")
@NInt
public static native long version_static();
}
| multi-os-engine/moe-core | moe.apple/moe.platform.ios/src/main/java/apple/mlcompute/MLCRMSPropOptimizer.java | Java | apache-2.0 | 6,672 |
package com.jflyfox.dudu.module.system.dao;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.jflyfox.dudu.component.model.Query;
import com.jflyfox.dudu.module.system.model.SysMenu;
import com.jflyfox.util.StrUtils;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.jdbc.SQL;
import java.util.List;
/**
* 菜单 数据层
*
* @author flyfox [email protected] on 2017-06-20.
*/
public interface MenuMapper extends BaseMapper<SysMenu> {
@SelectProvider(type = SqlBuilder.class, method = "selectMenuPage")
List<SysMenu> selectMenuPage(Query query);
class SqlBuilder {
public String selectMenuPage(Query query) {
String sqlColumns = "t.id,t.parentid,t.name,t.urlkey,t.url,t.status,t.type,t.sort,t.level,t.enable,t.update_time as updateTime,t.update_id as updateId,t.create_time as createTime,t.create_id as createId";
return new SQL() {{
SELECT(sqlColumns +
" ,p.name as parentName,uu.username as updateName,uc.username as createName");
FROM(" sys_menu t ");
LEFT_OUTER_JOIN(" sys_user uu on t.update_id = uu.id ");
LEFT_OUTER_JOIN(" sys_user uc on t.create_id = uc.id ");
LEFT_OUTER_JOIN(" sys_menu p on t.parentid = p.id ");
if (StrUtils.isNotEmpty(query.getStr("name"))) {
WHERE(" t.name like concat('%',#{name},'%')");
}
if (StrUtils.isNotEmpty(query.getOrderBy())) {
ORDER_BY(query.getOrderBy());
} else {
ORDER_BY(" t.id desc");
}
}}.toString();
}
}
}
| jflyfox/dudu | dudu-admin/src/main/java/com/jflyfox/dudu/module/system/dao/MenuMapper.java | Java | apache-2.0 | 1,715 |
/**
*
* Copyright 2003-2007 Jive Software.
*
* 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.jivesoftware.smack.chat;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.StanzaCollector;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jxmpp.jid.EntityJid;
/**
* A chat is a series of messages sent between two users. Each chat has a unique
* thread ID, which is used to track which messages are part of a particular
* conversation. Some messages are sent without a thread ID, and some clients
* don't send thread IDs at all. Therefore, if a message without a thread ID
* arrives it is routed to the most recently created Chat with the message
* sender.
*
* @author Matt Tucker
* @deprecated use <code>org.jivesoftware.smack.chat2.Chat</code> from <code>smack-extensions</code> instead.
*/
@Deprecated
public class Chat {
private final ChatManager chatManager;
private final String threadID;
private final EntityJid participant;
private final Set<ChatMessageListener> listeners = new CopyOnWriteArraySet<>();
/**
* Creates a new chat with the specified user and thread ID.
*
* @param chatManager the chatManager the chat will use.
* @param participant the user to chat with.
* @param threadID the thread ID to use.
*/
Chat(ChatManager chatManager, EntityJid participant, String threadID) {
if (StringUtils.isEmpty(threadID)) {
throw new IllegalArgumentException("Thread ID must not be null");
}
this.chatManager = chatManager;
this.participant = participant;
this.threadID = threadID;
}
/**
* Returns the thread id associated with this chat, which corresponds to the
* <tt>thread</tt> field of XMPP messages. This method may return <tt>null</tt>
* if there is no thread ID is associated with this Chat.
*
* @return the thread ID of this chat.
*/
public String getThreadID() {
return threadID;
}
/**
* Returns the name of the user the chat is with.
*
* @return the name of the user the chat is occuring with.
*/
public EntityJid getParticipant() {
return participant;
}
/**
* Sends the specified text as a message to the other chat participant.
* This is a convenience method for:
*
* <pre>
* Message message = chat.createMessage();
* message.setBody(messageText);
* chat.sendMessage(message);
* </pre>
*
* @param text the text to send.
* @throws NotConnectedException
* @throws InterruptedException
*/
public void sendMessage(String text) throws NotConnectedException, InterruptedException {
Message message = new Message();
message.setBody(text);
sendMessage(message);
}
/**
* Sends a message to the other chat participant. The thread ID, recipient,
* and message type of the message will automatically set to those of this chat.
*
* @param message the message to send.
* @throws NotConnectedException
* @throws InterruptedException
*/
public void sendMessage(Message message) throws NotConnectedException, InterruptedException {
// Force the recipient, message type, and thread ID since the user elected
// to send the message through this chat object.
message.setTo(participant);
message.setType(Message.Type.chat);
message.setThread(threadID);
chatManager.sendMessage(this, message);
}
/**
* Adds a stanza(/packet) listener that will be notified of any new messages in the
* chat.
*
* @param listener a stanza(/packet) listener.
*/
public void addMessageListener(ChatMessageListener listener) {
if (listener == null) {
return;
}
// TODO these references should be weak.
listeners.add(listener);
}
public void removeMessageListener(ChatMessageListener listener) {
listeners.remove(listener);
}
/**
* Closes the Chat and removes all references to it from the {@link ChatManager}. The chat will
* be unusable when this method returns, so it's recommend to drop all references to the
* instance right after calling {@link #close()}.
*/
public void close() {
chatManager.closeChat(this);
listeners.clear();
}
/**
* Returns an unmodifiable set of all of the listeners registered with this chat.
*
* @return an unmodifiable set of all of the listeners registered with this chat.
*/
public Set<ChatMessageListener> getListeners() {
return Collections.unmodifiableSet(listeners);
}
/**
* Creates a {@link org.jivesoftware.smack.StanzaCollector} which will accumulate the Messages
* for this chat. Always cancel StanzaCollectors when finished with them as they will accumulate
* messages indefinitely.
*
* @return the StanzaCollector which returns Messages for this chat.
*/
public StanzaCollector createCollector() {
return chatManager.createStanzaCollector(this);
}
/**
* Delivers a message directly to this chat, which will add the message
* to the collector and deliver it to all listeners registered with the
* Chat. This is used by the XMPPConnection class to deliver messages
* without a thread ID.
*
* @param message the message.
*/
void deliver(Message message) {
// Because the collector and listeners are expecting a thread ID with
// a specific value, set the thread ID on the message even though it
// probably never had one.
message.setThread(threadID);
for (ChatMessageListener listener : listeners) {
listener.processMessage(this, message);
}
}
@Override
public String toString() {
return "Chat [(participant=" + participant + "), (thread=" + threadID + ")]";
}
@Override
public int hashCode() {
int hash = 1;
hash = hash * 31 + threadID.hashCode();
hash = hash * 31 + participant.hashCode();
return hash;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Chat
&& threadID.equals(((Chat) obj).getThreadID())
&& participant.equals(((Chat) obj).getParticipant());
}
}
| vanitasvitae/smack-omemo | smack-im/src/main/java/org/jivesoftware/smack/chat/Chat.java | Java | apache-2.0 | 7,127 |
package edu.kit.tm.pseprak2.alushare.view;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import java.io.IOException;
/**
* Represent the AudioRecorder of the ChatActivity.
* Enables recording sound and playing the music before sending.
*
* Created by Arthur Anselm on 17.08.15.
*/
public class AudioRecorder {
private String mFileName = null;
private String TAG = "AudioRecorder";
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private ChatController controller;
private boolean busy;
//private SeekBar mSeekbar;
//private Handler mHandler;
/**
* The constructor of this class.
* @param controller the controller for this audioRecorder object
*/
public AudioRecorder(ChatController controller){
if(controller == null){
throw new NullPointerException();
}
this.controller = controller;
//this.mSeekbar = seekBar;
//this.mHandler = new Handler();
this.mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
this.mFileName += "/audiorecord_alushare.m4a";
this.busy = false;
}
/**
* Invokes the method startRecording() (and sets busy to true) if start is true else
* stopRecording().
* @param start boolean to start or stop recording
*/
public void onRecord(boolean start) {
if (start) {
busy = true;
startRecording();
} else {
stopRecording();
}
}
/**
* Invokes startPlaying() if start is true else stopPlaying().
* @param start boolean to start or stop playing
*/
public void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
/**
* Creates a new mediaPlayer and sets it up. After that starts playing the audoFile stored in
* the filesPath mFileName
*/
private void startPlaying() {
if(mFileName == null){
throw new NullPointerException("Recorded file is null.");
}
setUpMediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(TAG, "prepare() failed");
}
}
/**
* Creates a new mediaPlayer and sets the completion listener.
*/
private void setUpMediaPlayer(){
mPlayer = new MediaPlayer();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.e(TAG, " : Playing of Sound completed");
controller.setPlayButtonVisible(true);
}
});
/*
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(final MediaPlayer mp) {
mSeekbar.setMax(mp.getDuration());
new Thread(new Runnable() {
@Override
public void run() {
while (mp != null && mp.getCurrentPosition() < mp.getDuration()) {
mSeekbar.setProgress(mp.getCurrentPosition());
Message msg = new Message();
int millis = mp.getCurrentPosition();
msg.obj = millis / 1000;
mHandler.sendMessage(msg);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});*/
}
/**
* Stops playing the mediaPlayer with the method release() and releases the references to the
* mediaPlayer if the mediaPlayer isn't null.
*/
private void stopPlaying() {
if(mPlayer != null) {
mPlayer.release();
mPlayer = null;
} else {
Log.e(TAG, "MediaPlayer is null. stopPlaying() can't be executed.");
}
}
/**
* Creates a new mediaRecorder and set it up.
* Start recording and saving the audio data into the file stored at fileName.
*/
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mRecorder.setAudioChannels(1);
mRecorder.setAudioSamplingRate(44100);
mRecorder.setAudioEncodingBitRate(96000);
mRecorder.setOutputFile(mFileName);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(TAG, "prepare() failed");
return;
}
mRecorder.start();
}
/**
* Stops recording, invokes release of the mediaRecorder and releases the references to the
* mediaRecorder if the mediaRecorder isn't null.
*/
private void stopRecording() {
if(mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
} else {
Log.e(TAG, "MediaRecorder is null. stopRecording() can't be executed.");
}
}
/**
*Return the filePath of the recorded audio file
* @return this.mFileName
*/
public String getFilePath(){
return mFileName;
}
/**
* Sets the busyness of this audioRecorder
* @param busy true if the audioRecorder is active else false
*/
public void setBusy(boolean busy){
this.busy = busy;
}
/**
* Checks if this audioRecorder is active oder not. Returns busy.
* @return busy
*/
public boolean isBusy(){
return busy;
}
}
| weichweich/AluShare | app/src/main/java/edu/kit/tm/pseprak2/alushare/view/AudioRecorder.java | Java | apache-2.0 | 6,151 |
package com.zts.service.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = DataSourceProperties.DS, ignoreUnknownFields = false)
public class DataSourceProperties {
//对应配置文件里的配置键
public final static String DS="mysql";
private String driverClassName ="com.mysql.jdbc.Driver";
private String url;
private String username;
private String password;
private int maxActive = 100;
private int maxIdle = 8;
private int minIdle = 8;
private int initialSize = 10;
private String validationQuery;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
private boolean testOnBorrow = false;
private boolean testOnReturn = false;
} | tushengtuzhang/zts | cloud-simple-service/src/main/java/com/zts/service/config/DataSourceProperties.java | Java | apache-2.0 | 2,197 |
package com.github.approval.sesame;
/*
* #%L
* approval-sesame
* %%
* Copyright (C) 2014 Nikolavp
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.github.approval.Reporter;
import com.github.approval.reporters.ExecutableDifferenceReporter;
import com.github.approval.reporters.Reporters;
import com.github.approval.reporters.SwingInteractiveReporter;
import java.io.File;
/**
* <p>
* A reporter that can be used to verify dot files. It will compile the file to an image and open it through
* {@link com.github.approval.reporters.Reporters#fileLauncher()}.
* </p>
* <p>
* Note that this reporter cannot be used for anything else and will give you an error beceause it will
* try to compile the verification file with the "dot" command.
* </p>
*/
public final class GraphReporter extends ExecutableDifferenceReporter {
/**
* Get an instance of the reporter.
* @return a graph reporter
*/
public static Reporter getInstance() {
return SwingInteractiveReporter.wrap(new GraphReporter());
}
/**
* Main constructor for the executable reporter.
*/
private GraphReporter() {
super("dot -T png -O ", "dot -T png -O ", "dot");
}
private static File addPng(File file) {
return new File(file.getAbsoluteFile().getAbsolutePath() + ".png");
}
@Override
public void approveNew(byte[] value, File approvalDestination, File fileForVerification) {
super.approveNew(value, approvalDestination, fileForVerification);
Reporters.fileLauncherWithoutInteraction().approveNew(value, addPng(approvalDestination), addPng(fileForVerification));
}
@Override
protected String[] buildApproveNewCommand(File approvalDestination, File fileForVerification) {
return new String[]{getApprovalCommand(), approvalDestination.getAbsolutePath()};
}
@Override
protected String[] buildNotTheSameCommand(File fileForVerification, File fileForApproval) {
return new String[]{getDiffCommand(), fileForApproval.getAbsolutePath()};
}
@Override
public void notTheSame(byte[] oldValue, File fileForVerification, byte[] newValue, File fileForApproval) {
super.notTheSame(oldValue, fileForVerification, newValue, fileForApproval);
Reporters.fileLauncherWithoutInteraction().notTheSame(oldValue, addPng(fileForVerification), newValue, addPng(fileForApproval));
}
}
| nikolavp/approval | approval-sesame/src/main/java/com/github/approval/sesame/GraphReporter.java | Java | apache-2.0 | 2,951 |
package AbsSytree;
import java.util.ArrayList;
public class SynExprSeq extends AbsSynNode {
public ArrayList<AbsSynNode> exprs;
public SynExprSeq(AbsSynNode e) {
this.exprs = new ArrayList<AbsSynNode>();
this.exprs.add(e);
}
public SynExprSeq append(AbsSynNode e) {
this.exprs.add(e);
return this;
}
@Override
public Object visit(SynNodeVisitor visitor) {
return visitor.visit(this);
}
@Override
public void dumpNode(int indent) {
for (int i = 0; i < this.exprs.size(); ++i) {
this.exprs.get(i).dumpNode(indent);
this.dumpFormat(indent, ";");
}
}
@Override
public void clearAttr() {
this.attr = null;
for (int i = 0; i < this.exprs.size(); ++i)
this.exprs.get(i).clearAttr();
}
}
| mingyuan-xia/TigerCC | src/AbsSytree/SynExprSeq.java | Java | apache-2.0 | 767 |
/**
* Copyright 2017 Matthieu Jimenez. All rights reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package paw.graph.customTypes.bitset;
import greycat.base.BaseCustomType;
import greycat.struct.EStructArray;
import greycat.utility.HashHelper;
import org.roaringbitmap.IntIterator;
import java.util.List;
public abstract class CTBitset extends BaseCustomType{
public static final String BITS = "bits";
protected static final int BITS_H = HashHelper.hash(BITS);
public CTBitset(EStructArray p_backend) {
super(p_backend);
}
public abstract void save();
public abstract void clear();
public abstract boolean add(int index);
public abstract boolean addAll(List<Integer> indexs);
public abstract void clear(int index);
public abstract int size();
public abstract int cardinality();
public abstract boolean get(int index);
public abstract int nextSetBit(int startIndex);
public abstract IntIterator iterator();
}
| greycat-incubator/Paw | src/main/java/paw/graph/customTypes/bitset/CTBitset.java | Java | apache-2.0 | 1,522 |
/**
* Copyright Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.windowsazure.core.pipeline;
import com.sun.jersey.core.util.Base64;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/*
* JAXB adapter for a Base64 encoded string element
*/
public class Base64StringAdapter extends XmlAdapter<String, String> {
@Override
public String marshal(String arg0) throws Exception {
return new String(Base64.encode(arg0), "UTF-8");
}
@Override
public String unmarshal(String arg0) throws Exception {
return Base64.base64Decode(arg0);
}
}
| southworkscom/azure-sdk-for-java | core/azure-core/src/main/java/com/microsoft/windowsazure/core/pipeline/Base64StringAdapter.java | Java | apache-2.0 | 1,133 |
/**
* Copyright 2016 William Van Woensel
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*
*
* @author wvw
*
*/
package wvw.utils.rule.builder;
public abstract class RuleBuilder {
protected String id;
protected StringBuffer templateClause = new StringBuffer();
protected StringBuffer conditionClause = new StringBuffer();
public RuleBuilder() {
}
public RuleBuilder(String id) {
this.id = id;
}
public void appendTemplate(String template) {
templateClause.append("\t").append(template);
}
public void appendCondition(String condition) {
conditionClause.append("\t").append(condition);
}
public String getId() {
return id;
}
public abstract String toString();
}
| darth-willy/mobibench | MobiBenchWebService/src/main/java/wvw/utils/rule/builder/RuleBuilder.java | Java | apache-2.0 | 1,192 |
/*
* Copyright 2013, Unitils.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitils.core.reflect;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Tim Ducheyne
*/
public class TypeWrapperIsAssignableParameterizedTypeTest {
/* Tested object */
private TypeWrapper typeWrapper;
private ParameterizedType type1;
private ParameterizedType type2;
private ParameterizedType type3;
private ParameterizedType type4;
private ParameterizedType type5;
private ParameterizedType type6;
private ParameterizedType type7;
private ParameterizedType type8;
@Before
public void initialize() throws Exception {
typeWrapper = new TypeWrapper(null);
type1 = (ParameterizedType) MyClass.class.getDeclaredField("field1").getGenericType();
type2 = (ParameterizedType) MyClass.class.getDeclaredField("field2").getGenericType();
type3 = (ParameterizedType) MyClass.class.getDeclaredField("field3").getGenericType();
type4 = (ParameterizedType) MyClass.class.getDeclaredField("field4").getGenericType();
type5 = (ParameterizedType) MyClass.class.getDeclaredField("field5").getGenericType();
type6 = (ParameterizedType) MyClass.class.getDeclaredField("field6").getGenericType();
type7 = (ParameterizedType) MyClass.class.getDeclaredField("field7").getGenericType();
type8 = (ParameterizedType) MyClass.class.getDeclaredField("field8").getGenericType();
}
@Test
public void equal() {
boolean result = typeWrapper.isAssignableParameterizedType(type1, type2);
assertTrue(result);
}
@Test
public void assignableParameter() {
boolean result = typeWrapper.isAssignableParameterizedType(type6, type7);
assertTrue(result);
}
@Test
public void nestedAssignableParameters() {
boolean result = typeWrapper.isAssignableParameterizedType(type3, type4);
assertTrue(result);
}
@Test
public void falseWhenDifferentNrOfTypeParameters() {
boolean result = typeWrapper.isAssignableParameterizedType(type2, type7);
assertFalse(result);
}
@Test
public void falseWhenNotEqualNonWildCardType() {
boolean result = typeWrapper.isAssignableParameterizedType(type7, type8);
assertFalse(result);
}
@Test
public void falseWhenNotAssignableToWildCard() {
boolean result = typeWrapper.isAssignableParameterizedType(type6, type8);
assertFalse(result);
}
@Test
public void falseWhenNotAssignableToNestedWildCard() {
boolean result = typeWrapper.isAssignableParameterizedType(type3, type5);
assertFalse(result);
}
private static class MyClass {
private Map<Type1, Type1> field1;
private Map<Type1, Type1> field2;
private Map<? extends List<? extends Type1>, ? extends List<?>> field3;
private Map<List<Type1>, List<Type2>> field4;
private Map<List<String>, List<String>> field5;
private List<? extends Type1> field6;
private List<Type2> field7;
private List<String> field8;
}
private static class Type1 {
}
private static class Type2 extends Type1 {
}
}
| Silvermedia/unitils | unitils-test/src/test/java/org/unitils/core/reflect/TypeWrapperIsAssignableParameterizedTypeTest.java | Java | apache-2.0 | 4,075 |
/*
* Copyright (c) 2010-2014. Axon Framework
*
* 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.axonframework.common.lock;
/**
* Interface to the lock factory. A lock factory produces locks on resources that are shared between threads.
*
* @author Allard Buijze
* @since 0.3
*/
public interface LockFactory {
/**
* Obtain a lock for a resource identified by given {@code identifier}. Depending on the strategy, this
* method may return immediately or block until a lock is held.
*
* @param identifier the identifier of the resource to obtain a lock for.
* @return a handle to release the lock.
*/
Lock obtainLock(String identifier);
}
| soulrebel/AxonFramework | core/src/main/java/org/axonframework/common/lock/LockFactory.java | Java | apache-2.0 | 1,205 |
package site;
public class Autocomplete {
private final String label;
private final String value;
public Autocomplete(String label, String value) {
this.label = label;
this.value = value;
}
public final String getLabel() {
return this.label;
}
public final String getValue() {
return this.value;
}
} | CaroleneBertoldi/CountryDetails | country/src/main/java/site/Autocomplete.java | Java | apache-2.0 | 337 |
/*
* 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.cluster.routing;
import com.carrotsearch.hppc.ObjectIntHashMap;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.apache.lucene.util.CollectionUtil;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
/**
* {@link RoutingNodes} represents a copy the routing information contained in
* the {@link ClusterState cluster state}.
*/
public class RoutingNodes implements Iterable<RoutingNode> {
private final MetaData metaData;
private final ClusterBlocks blocks;
private final RoutingTable routingTable;
private final Map<String, RoutingNode> nodesToShards = new HashMap<>();
private final UnassignedShards unassignedShards = new UnassignedShards(this);
private final Map<ShardId, List<ShardRouting>> assignedShards = new HashMap<>();
private final ImmutableOpenMap<String, ClusterState.Custom> customs;
private final boolean readOnly;
private int inactivePrimaryCount = 0;
private int inactiveShardCount = 0;
private int relocatingShards = 0;
private final Map<String, ObjectIntHashMap<String>> nodesPerAttributeNames = new HashMap<>();
private final Map<String, Recoveries> recoveryiesPerNode = new HashMap<>();
public RoutingNodes(ClusterState clusterState) {
this(clusterState, true);
}
public RoutingNodes(ClusterState clusterState, boolean readOnly) {
this.readOnly = readOnly;
this.metaData = clusterState.metaData();
this.blocks = clusterState.blocks();
this.routingTable = clusterState.routingTable();
this.customs = clusterState.customs();
Map<String, List<ShardRouting>> nodesToShards = new HashMap<>();
// fill in the nodeToShards with the "live" nodes
for (ObjectCursor<DiscoveryNode> cursor : clusterState.nodes().dataNodes().values()) {
nodesToShards.put(cursor.value.id(), new ArrayList<>());
}
// fill in the inverse of node -> shards allocated
// also fill replicaSet information
for (ObjectCursor<IndexRoutingTable> indexRoutingTable : routingTable.indicesRouting().values()) {
for (IndexShardRoutingTable indexShard : indexRoutingTable.value) {
assert indexShard.primary != null;
for (ShardRouting shard : indexShard) {
// to get all the shards belonging to an index, including the replicas,
// we define a replica set and keep track of it. A replica set is identified
// by the ShardId, as this is common for primary and replicas.
// A replica Set might have one (and not more) replicas with the state of RELOCATING.
if (shard.assignedToNode()) {
List<ShardRouting> entries = nodesToShards.computeIfAbsent(shard.currentNodeId(), k -> new ArrayList<>());
final ShardRouting sr = getRouting(shard, readOnly);
entries.add(sr);
assignedShardsAdd(sr);
if (shard.relocating()) {
relocatingShards++;
entries = nodesToShards.computeIfAbsent(shard.relocatingNodeId(), k -> new ArrayList<>());
// add the counterpart shard with relocatingNodeId reflecting the source from which
// it's relocating from.
ShardRouting targetShardRouting = shard.buildTargetRelocatingShard();
addInitialRecovery(targetShardRouting);
if (readOnly) {
targetShardRouting.freeze();
}
entries.add(targetShardRouting);
assignedShardsAdd(targetShardRouting);
} else if (shard.active() == false) { // shards that are initializing without being relocated
if (shard.primary()) {
inactivePrimaryCount++;
}
inactiveShardCount++;
addInitialRecovery(shard);
}
} else {
final ShardRouting sr = getRouting(shard, readOnly);
assignedShardsAdd(sr);
unassignedShards.add(sr);
}
}
}
}
for (Map.Entry<String, List<ShardRouting>> entry : nodesToShards.entrySet()) {
String nodeId = entry.getKey();
this.nodesToShards.put(nodeId, new RoutingNode(nodeId, clusterState.nodes().get(nodeId), entry.getValue()));
}
}
private void addRecovery(ShardRouting routing) {
addRecovery(routing, true, false);
}
private void removeRecovery(ShardRouting routing) {
addRecovery(routing, false, false);
}
public void addInitialRecovery(ShardRouting routing) {
addRecovery(routing,true, true);
}
private void addRecovery(final ShardRouting routing, final boolean increment, final boolean initializing) {
final int howMany = increment ? 1 : -1;
assert routing.initializing() : "routing must be initializing: " + routing;
Recoveries.getOrAdd(recoveryiesPerNode, routing.currentNodeId()).addIncoming(howMany);
final String sourceNodeId;
if (routing.relocatingNodeId() != null) { // this is a relocation-target
sourceNodeId = routing.relocatingNodeId();
if (routing.primary() && increment == false) { // primary is done relocating
int numRecoveringReplicas = 0;
for (ShardRouting assigned : assignedShards(routing)) {
if (assigned.primary() == false && assigned.initializing() && assigned.relocatingNodeId() == null) {
numRecoveringReplicas++;
}
}
// we transfer the recoveries to the relocated primary
recoveryiesPerNode.get(sourceNodeId).addOutgoing(-numRecoveringReplicas);
recoveryiesPerNode.get(routing.currentNodeId()).addOutgoing(numRecoveringReplicas);
}
} else if (routing.primary() == false) { // primary without relocationID is initial recovery
ShardRouting primary = findPrimary(routing);
if (primary == null && initializing) {
primary = routingTable.index(routing.index().getName()).shard(routing.shardId().id()).primary;
} else if (primary == null) {
throw new IllegalStateException("replica is initializing but primary is unassigned");
}
sourceNodeId = primary.currentNodeId();
} else {
sourceNodeId = null;
}
if (sourceNodeId != null) {
Recoveries.getOrAdd(recoveryiesPerNode, sourceNodeId).addOutgoing(howMany);
}
}
public int getIncomingRecoveries(String nodeId) {
return recoveryiesPerNode.getOrDefault(nodeId, Recoveries.EMPTY).getIncoming();
}
public int getOutgoingRecoveries(String nodeId) {
return recoveryiesPerNode.getOrDefault(nodeId, Recoveries.EMPTY).getOutgoing();
}
private ShardRouting findPrimary(ShardRouting routing) {
List<ShardRouting> shardRoutings = assignedShards.get(routing.shardId());
ShardRouting primary = null;
if (shardRoutings != null) {
for (ShardRouting shardRouting : shardRoutings) {
if (shardRouting.primary()) {
if (shardRouting.active()) {
return shardRouting;
} else if (primary == null) {
primary = shardRouting;
} else if (primary.relocatingNodeId() != null) {
primary = shardRouting;
}
}
}
}
return primary;
}
private static ShardRouting getRouting(ShardRouting src, boolean readOnly) {
if (readOnly) {
src.freeze(); // we just freeze and reuse this instance if we are read only
} else {
src = new ShardRouting(src);
}
return src;
}
@Override
public Iterator<RoutingNode> iterator() {
return Collections.unmodifiableCollection(nodesToShards.values()).iterator();
}
public RoutingTable routingTable() {
return routingTable;
}
public RoutingTable getRoutingTable() {
return routingTable();
}
public MetaData metaData() {
return this.metaData;
}
public MetaData getMetaData() {
return metaData();
}
public ClusterBlocks blocks() {
return this.blocks;
}
public ClusterBlocks getBlocks() {
return this.blocks;
}
public ImmutableOpenMap<String, ClusterState.Custom> customs() {
return this.customs;
}
public <T extends ClusterState.Custom> T custom(String type) { return (T) customs.get(type); }
public UnassignedShards unassigned() {
return this.unassignedShards;
}
public RoutingNodesIterator nodes() {
return new RoutingNodesIterator(nodesToShards.values().iterator());
}
public RoutingNode node(String nodeId) {
return nodesToShards.get(nodeId);
}
public ObjectIntHashMap<String> nodesPerAttributesCounts(String attributeName) {
ObjectIntHashMap<String> nodesPerAttributesCounts = nodesPerAttributeNames.get(attributeName);
if (nodesPerAttributesCounts != null) {
return nodesPerAttributesCounts;
}
nodesPerAttributesCounts = new ObjectIntHashMap<>();
for (RoutingNode routingNode : this) {
String attrValue = routingNode.node().attributes().get(attributeName);
nodesPerAttributesCounts.addTo(attrValue, 1);
}
nodesPerAttributeNames.put(attributeName, nodesPerAttributesCounts);
return nodesPerAttributesCounts;
}
/**
* Returns <code>true</code> iff this {@link RoutingNodes} instance has any unassigned primaries even if the
* primaries are marked as temporarily ignored.
*/
public boolean hasUnassignedPrimaries() {
return unassignedShards.getNumPrimaries() + unassignedShards.getNumIgnoredPrimaries() > 0;
}
/**
* Returns <code>true</code> iff this {@link RoutingNodes} instance has any unassigned shards even if the
* shards are marked as temporarily ignored.
* @see UnassignedShards#isEmpty()
* @see UnassignedShards#isIgnoredEmpty()
*/
public boolean hasUnassignedShards() {
return unassignedShards.isEmpty() == false || unassignedShards.isIgnoredEmpty() == false;
}
public boolean hasInactivePrimaries() {
return inactivePrimaryCount > 0;
}
public boolean hasInactiveShards() {
return inactiveShardCount > 0;
}
public int getRelocatingShardCount() {
return relocatingShards;
}
/**
* Returns the active primary shard for the given ShardRouting or <code>null</code> if
* no primary is found or the primary is not active.
*/
public ShardRouting activePrimary(ShardRouting shard) {
for (ShardRouting shardRouting : assignedShards(shard.shardId())) {
if (shardRouting.primary() && shardRouting.active()) {
return shardRouting;
}
}
return null;
}
/**
* Returns one active replica shard for the given ShardRouting shard ID or <code>null</code> if
* no active replica is found.
*/
public ShardRouting activeReplica(ShardRouting shard) {
for (ShardRouting shardRouting : assignedShards(shard.shardId())) {
if (!shardRouting.primary() && shardRouting.active()) {
return shardRouting;
}
}
return null;
}
/**
* Returns all shards that are not in the state UNASSIGNED with the same shard
* ID as the given shard.
*/
public Iterable<ShardRouting> assignedShards(ShardRouting shard) {
return assignedShards(shard.shardId());
}
/**
* Returns <code>true</code> iff all replicas are active for the given shard routing. Otherwise <code>false</code>
*/
public boolean allReplicasActive(ShardRouting shardRouting) {
final List<ShardRouting> shards = assignedShards(shardRouting.shardId());
if (shards.isEmpty() || shards.size() < this.routingTable.index(shardRouting.index().getName()).shard(shardRouting.id()).size()) {
return false; // if we are empty nothing is active if we have less than total at least one is unassigned
}
for (ShardRouting shard : shards) {
if (!shard.active()) {
return false;
}
}
return true;
}
public List<ShardRouting> shards(Predicate<ShardRouting> predicate) {
List<ShardRouting> shards = new ArrayList<>();
for (RoutingNode routingNode : this) {
for (ShardRouting shardRouting : routingNode) {
if (predicate.test(shardRouting)) {
shards.add(shardRouting);
}
}
}
return shards;
}
public List<ShardRouting> shardsWithState(ShardRoutingState... state) {
// TODO these are used on tests only - move into utils class
List<ShardRouting> shards = new ArrayList<>();
for (RoutingNode routingNode : this) {
shards.addAll(routingNode.shardsWithState(state));
}
for (ShardRoutingState s : state) {
if (s == ShardRoutingState.UNASSIGNED) {
unassigned().forEach(shards::add);
break;
}
}
return shards;
}
public List<ShardRouting> shardsWithState(String index, ShardRoutingState... state) {
// TODO these are used on tests only - move into utils class
List<ShardRouting> shards = new ArrayList<>();
for (RoutingNode routingNode : this) {
shards.addAll(routingNode.shardsWithState(index, state));
}
for (ShardRoutingState s : state) {
if (s == ShardRoutingState.UNASSIGNED) {
for (ShardRouting unassignedShard : unassignedShards) {
if (unassignedShard.index().equals(index)) {
shards.add(unassignedShard);
}
}
break;
}
}
return shards;
}
public String prettyPrint() {
StringBuilder sb = new StringBuilder("routing_nodes:\n");
for (RoutingNode routingNode : this) {
sb.append(routingNode.prettyPrint());
}
sb.append("---- unassigned\n");
for (ShardRouting shardEntry : unassignedShards) {
sb.append("--------").append(shardEntry.shortSummary()).append('\n');
}
return sb.toString();
}
/**
* Moves a shard from unassigned to initialize state
*
* @param existingAllocationId allocation id to use. If null, a fresh allocation id is generated.
*/
public void initialize(ShardRouting shard, String nodeId, @Nullable String existingAllocationId, long expectedSize) {
ensureMutable();
assert shard.unassigned() : shard;
shard.initialize(nodeId, existingAllocationId, expectedSize);
node(nodeId).add(shard);
inactiveShardCount++;
if (shard.primary()) {
inactivePrimaryCount++;
}
addRecovery(shard);
assignedShardsAdd(shard);
}
/**
* Relocate a shard to another node, adding the target initializing
* shard as well as assigning it. And returning the target initializing
* shard.
*/
public ShardRouting relocate(ShardRouting shard, String nodeId, long expectedShardSize) {
ensureMutable();
relocatingShards++;
shard.relocate(nodeId, expectedShardSize);
ShardRouting target = shard.buildTargetRelocatingShard();
node(target.currentNodeId()).add(target);
assignedShardsAdd(target);
addRecovery(target);
return target;
}
/**
* Mark a shard as started and adjusts internal statistics.
*/
public void started(ShardRouting shard) {
ensureMutable();
assert !shard.active() : "expected an initializing shard " + shard;
if (shard.relocatingNodeId() == null) {
// if this is not a target shard for relocation, we need to update statistics
inactiveShardCount--;
if (shard.primary()) {
inactivePrimaryCount--;
}
}
removeRecovery(shard);
shard.moveToStarted();
}
/**
* Cancels a relocation of a shard that shard must relocating.
*/
public void cancelRelocation(ShardRouting shard) {
ensureMutable();
relocatingShards--;
shard.cancelRelocation();
}
/**
* swaps the status of a shard, making replicas primary and vice versa.
*
* @param shards the shard to have its primary status swapped.
*/
public void swapPrimaryFlag(ShardRouting... shards) {
ensureMutable();
for (ShardRouting shard : shards) {
if (shard.primary()) {
shard.moveFromPrimary();
if (shard.unassigned()) {
unassignedShards.primaries--;
}
} else {
shard.moveToPrimary();
if (shard.unassigned()) {
unassignedShards.primaries++;
}
}
}
}
private static final List<ShardRouting> EMPTY = Collections.emptyList();
private List<ShardRouting> assignedShards(ShardId shardId) {
final List<ShardRouting> replicaSet = assignedShards.get(shardId);
return replicaSet == null ? EMPTY : Collections.unmodifiableList(replicaSet);
}
/**
* Cancels the give shard from the Routing nodes internal statistics and cancels
* the relocation if the shard is relocating.
*/
private void remove(ShardRouting shard) {
ensureMutable();
if (!shard.active() && shard.relocatingNodeId() == null) {
inactiveShardCount--;
assert inactiveShardCount >= 0;
if (shard.primary()) {
inactivePrimaryCount--;
}
} else if (shard.relocating()) {
cancelRelocation(shard);
}
assignedShardsRemove(shard);
if (shard.initializing()) {
removeRecovery(shard);
}
}
private void assignedShardsAdd(ShardRouting shard) {
if (shard.unassigned()) {
// no unassigned
return;
}
List<ShardRouting> shards = assignedShards.computeIfAbsent(shard.shardId(), k -> new ArrayList<>());
assert assertInstanceNotInList(shard, shards);
shards.add(shard);
}
private boolean assertInstanceNotInList(ShardRouting shard, List<ShardRouting> shards) {
for (ShardRouting s : shards) {
assert s != shard;
}
return true;
}
private void assignedShardsRemove(ShardRouting shard) {
ensureMutable();
final List<ShardRouting> replicaSet = assignedShards.get(shard.shardId());
if (replicaSet != null) {
final Iterator<ShardRouting> iterator = replicaSet.iterator();
while(iterator.hasNext()) {
// yes we check identity here
if (shard == iterator.next()) {
iterator.remove();
return;
}
}
assert false : "Illegal state";
}
}
public boolean isKnown(DiscoveryNode node) {
return nodesToShards.containsKey(node.getId());
}
public void addNode(DiscoveryNode node) {
ensureMutable();
RoutingNode routingNode = new RoutingNode(node.id(), node);
nodesToShards.put(routingNode.nodeId(), routingNode);
}
public RoutingNodeIterator routingNodeIter(String nodeId) {
final RoutingNode routingNode = nodesToShards.get(nodeId);
if (routingNode == null) {
return null;
}
return new RoutingNodeIterator(routingNode);
}
public RoutingNode[] toArray() {
return nodesToShards.values().toArray(new RoutingNode[nodesToShards.size()]);
}
public void reinitShadowPrimary(ShardRouting candidate) {
ensureMutable();
if (candidate.relocating()) {
cancelRelocation(candidate);
}
candidate.reinitializeShard();
inactivePrimaryCount++;
inactiveShardCount++;
}
/**
* Returns the number of routing nodes
*/
public int size() {
return nodesToShards.size();
}
public static final class UnassignedShards implements Iterable<ShardRouting> {
private final RoutingNodes nodes;
private final List<ShardRouting> unassigned;
private final List<ShardRouting> ignored;
private int primaries = 0;
private int ignoredPrimaries = 0;
public UnassignedShards(RoutingNodes nodes) {
this.nodes = nodes;
unassigned = new ArrayList<>();
ignored = new ArrayList<>();
}
public void add(ShardRouting shardRouting) {
if(shardRouting.primary()) {
primaries++;
}
unassigned.add(shardRouting);
}
public void sort(Comparator<ShardRouting> comparator) {
CollectionUtil.timSort(unassigned, comparator);
}
/**
* Returns the size of the non-ignored unassigned shards
*/
public int size() { return unassigned.size(); }
/**
* Returns the size of the temporarily marked as ignored unassigned shards
*/
public int ignoredSize() { return ignored.size(); }
/**
* Returns the number of non-ignored unassigned primaries
*/
public int getNumPrimaries() {
return primaries;
}
/**
* Returns the number of temporarily marked as ignored unassigned primaries
*/
public int getNumIgnoredPrimaries() { return ignoredPrimaries; }
@Override
public UnassignedIterator iterator() {
return new UnassignedIterator();
}
/**
* The list of ignored unassigned shards (read only). The ignored unassigned shards
* are not part of the formal unassigned list, but are kept around and used to build
* back the list of unassigned shards as part of the routing table.
*/
public List<ShardRouting> ignored() {
return Collections.unmodifiableList(ignored);
}
/**
* Marks a shard as temporarily ignored and adds it to the ignore unassigned list.
* Should be used with caution, typically,
* the correct usage is to removeAndIgnore from the iterator.
* @see #ignored()
* @see UnassignedIterator#removeAndIgnore()
* @see #isIgnoredEmpty()
*/
public void ignoreShard(ShardRouting shard) {
if (shard.primary()) {
ignoredPrimaries++;
}
ignored.add(shard);
}
public class UnassignedIterator implements Iterator<ShardRouting> {
private final Iterator<ShardRouting> iterator;
private ShardRouting current;
public UnassignedIterator() {
this.iterator = unassigned.iterator();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public ShardRouting next() {
return current = iterator.next();
}
/**
* Initializes the current unassigned shard and moves it from the unassigned list.
*
* @param existingAllocationId allocation id to use. If null, a fresh allocation id is generated.
*/
public void initialize(String nodeId, @Nullable String existingAllocationId, long expectedShardSize) {
innerRemove();
nodes.initialize(new ShardRouting(current), nodeId, existingAllocationId, expectedShardSize);
}
/**
* Removes and ignores the unassigned shard (will be ignored for this run, but
* will be added back to unassigned once the metadata is constructed again).
* Typically this is used when an allocation decision prevents a shard from being allocated such
* that subsequent consumers of this API won't try to allocate this shard again.
*/
public void removeAndIgnore() {
innerRemove();
ignoreShard(current);
}
/**
* Unsupported operation, just there for the interface. Use {@link #removeAndIgnore()} or
* {@link #initialize(String, String, long)}.
*/
@Override
public void remove() {
throw new UnsupportedOperationException("remove is not supported in unassigned iterator, use removeAndIgnore or initialize");
}
private void innerRemove() {
nodes.ensureMutable();
iterator.remove();
if (current.primary()) {
primaries--;
}
}
}
/**
* Returns <code>true</code> iff this collection contains one or more non-ignored unassigned shards.
*/
public boolean isEmpty() {
return unassigned.isEmpty();
}
/**
* Returns <code>true</code> iff any unassigned shards are marked as temporarily ignored.
* @see UnassignedShards#ignoreShard(ShardRouting)
* @see UnassignedIterator#removeAndIgnore()
*/
public boolean isIgnoredEmpty() {
return ignored.isEmpty();
}
public void shuffle() {
Randomness.shuffle(unassigned);
}
/**
* Drains all unassigned shards and returns it.
* This method will not drain ignored shards.
*/
public ShardRouting[] drain() {
ShardRouting[] mutableShardRoutings = unassigned.toArray(new ShardRouting[unassigned.size()]);
unassigned.clear();
primaries = 0;
return mutableShardRoutings;
}
}
/**
* Calculates RoutingNodes statistics by iterating over all {@link ShardRouting}s
* in the cluster to ensure the book-keeping is correct.
* For performance reasons, this should only be called from asserts
*
* @return this method always returns <code>true</code> or throws an assertion error. If assertion are not enabled
* this method does nothing.
*/
public static boolean assertShardStats(RoutingNodes routingNodes) {
boolean run = false;
assert (run = true); // only run if assertions are enabled!
if (!run) {
return true;
}
int unassignedPrimaryCount = 0;
int unassignedIgnoredPrimaryCount = 0;
int inactivePrimaryCount = 0;
int inactiveShardCount = 0;
int relocating = 0;
Map<Index, Integer> indicesAndShards = new HashMap<>();
for (RoutingNode node : routingNodes) {
for (ShardRouting shard : node) {
if (!shard.active() && shard.relocatingNodeId() == null) {
if (!shard.relocating()) {
inactiveShardCount++;
if (shard.primary()) {
inactivePrimaryCount++;
}
}
}
if (shard.relocating()) {
relocating++;
}
Integer i = indicesAndShards.get(shard.index());
if (i == null) {
i = shard.id();
}
indicesAndShards.put(shard.index(), Math.max(i, shard.id()));
}
}
// Assert that the active shard routing are identical.
Set<Map.Entry<Index, Integer>> entries = indicesAndShards.entrySet();
final List<ShardRouting> shards = new ArrayList<>();
for (Map.Entry<Index, Integer> e : entries) {
Index index = e.getKey();
for (int i = 0; i < e.getValue(); i++) {
for (RoutingNode routingNode : routingNodes) {
for (ShardRouting shardRouting : routingNode) {
if (shardRouting.index().equals(index) && shardRouting.id() == i) {
shards.add(shardRouting);
}
}
}
List<ShardRouting> mutableShardRoutings = routingNodes.assignedShards(new ShardId(index, i));
assert mutableShardRoutings.size() == shards.size();
for (ShardRouting r : mutableShardRoutings) {
assert shards.contains(r);
shards.remove(r);
}
assert shards.isEmpty();
}
}
for (ShardRouting shard : routingNodes.unassigned()) {
if (shard.primary()) {
unassignedPrimaryCount++;
}
}
for (ShardRouting shard : routingNodes.unassigned().ignored()) {
if (shard.primary()) {
unassignedIgnoredPrimaryCount++;
}
}
for (Map.Entry<String, Recoveries> recoveries : routingNodes.recoveryiesPerNode.entrySet()) {
String node = recoveries.getKey();
final Recoveries value = recoveries.getValue();
int incoming = 0;
int outgoing = 0;
RoutingNode routingNode = routingNodes.nodesToShards.get(node);
if (routingNode != null) { // node might have dropped out of the cluster
for (ShardRouting routing : routingNode) {
if (routing.initializing()) {
incoming++;
} else if (routing.relocating()) {
outgoing++;
}
if (routing.primary() && (routing.initializing() && routing.relocatingNodeId() != null) == false) { // we don't count the initialization end of the primary relocation
List<ShardRouting> shardRoutings = routingNodes.assignedShards.get(routing.shardId());
for (ShardRouting assigned : shardRoutings) {
if (assigned.primary() == false && assigned.initializing() && assigned.relocatingNodeId() == null) {
outgoing++;
}
}
}
}
}
assert incoming == value.incoming : incoming + " != " + value.incoming;
assert outgoing == value.outgoing : outgoing + " != " + value.outgoing + " node: " + routingNode;
}
assert unassignedPrimaryCount == routingNodes.unassignedShards.getNumPrimaries() :
"Unassigned primaries is [" + unassignedPrimaryCount + "] but RoutingNodes returned unassigned primaries [" + routingNodes.unassigned().getNumPrimaries() + "]";
assert unassignedIgnoredPrimaryCount == routingNodes.unassignedShards.getNumIgnoredPrimaries() :
"Unassigned ignored primaries is [" + unassignedIgnoredPrimaryCount + "] but RoutingNodes returned unassigned ignored primaries [" + routingNodes.unassigned().getNumIgnoredPrimaries() + "]";
assert inactivePrimaryCount == routingNodes.inactivePrimaryCount :
"Inactive Primary count [" + inactivePrimaryCount + "] but RoutingNodes returned inactive primaries [" + routingNodes.inactivePrimaryCount + "]";
assert inactiveShardCount == routingNodes.inactiveShardCount :
"Inactive Shard count [" + inactiveShardCount + "] but RoutingNodes returned inactive shards [" + routingNodes.inactiveShardCount + "]";
assert routingNodes.getRelocatingShardCount() == relocating : "Relocating shards mismatch [" + routingNodes.getRelocatingShardCount() + "] but expected [" + relocating + "]";
return true;
}
public class RoutingNodesIterator implements Iterator<RoutingNode>, Iterable<ShardRouting> {
private RoutingNode current;
private final Iterator<RoutingNode> delegate;
public RoutingNodesIterator(Iterator<RoutingNode> iterator) {
delegate = iterator;
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public RoutingNode next() {
return current = delegate.next();
}
public RoutingNodeIterator nodeShards() {
return new RoutingNodeIterator(current);
}
@Override
public void remove() {
delegate.remove();
}
@Override
public Iterator<ShardRouting> iterator() {
return nodeShards();
}
}
public final class RoutingNodeIterator implements Iterator<ShardRouting>, Iterable<ShardRouting> {
private final RoutingNode iterable;
private ShardRouting shard;
private final Iterator<ShardRouting> delegate;
private boolean removed = false;
public RoutingNodeIterator(RoutingNode iterable) {
this.delegate = iterable.mutableIterator();
this.iterable = iterable;
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public ShardRouting next() {
removed = false;
return shard = delegate.next();
}
@Override
public void remove() {
ensureMutable();
delegate.remove();
RoutingNodes.this.remove(shard);
removed = true;
}
/** returns true if {@link #remove()} or {@link #moveToUnassigned(UnassignedInfo)} were called on the current shard */
public boolean isRemoved() {
return removed;
}
@Override
public Iterator<ShardRouting> iterator() {
return iterable.iterator();
}
public void moveToUnassigned(UnassignedInfo unassignedInfo) {
ensureMutable();
if (isRemoved() == false) {
remove();
}
ShardRouting unassigned = new ShardRouting(shard); // protective copy of the mutable shard
unassigned.moveToUnassigned(unassignedInfo);
unassigned().add(unassigned);
}
public ShardRouting current() {
return shard;
}
}
private void ensureMutable() {
if (readOnly) {
throw new IllegalStateException("can't modify RoutingNodes - readonly");
}
}
private static final class Recoveries {
private static final Recoveries EMPTY = new Recoveries();
private int incoming = 0;
private int outgoing = 0;
int getTotal() {
return incoming + outgoing;
}
void addOutgoing(int howMany) {
assert outgoing + howMany >= 0 : outgoing + howMany+ " must be >= 0";
outgoing += howMany;
}
void addIncoming(int howMany) {
assert incoming + howMany >= 0 : incoming + howMany+ " must be >= 0";
incoming += howMany;
}
int getOutgoing() {
return outgoing;
}
int getIncoming() {
return incoming;
}
public static Recoveries getOrAdd(Map<String, Recoveries> map, String key) {
Recoveries recoveries = map.get(key);
if (recoveries == null) {
recoveries = new Recoveries();
map.put(key, recoveries);
}
return recoveries;
}
}
}
| mapr/elasticsearch | core/src/main/java/org/elasticsearch/cluster/routing/RoutingNodes.java | Java | apache-2.0 | 37,917 |
/*
* Copyright 2017 Yahoo Holdings, 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.yahoo.athenz.zms;
import java.util.List;
import com.yahoo.athenz.zms.store.ObjectStoreConnection;
import com.yahoo.athenz.zms.utils.ZMSUtils;
import com.yahoo.rdl.Timestamp;
class QuotaChecker {
private final Quota defaultQuota;
private boolean quotaCheckEnabled;
public QuotaChecker() {
// first check if the quota check is enabled or not
quotaCheckEnabled = Boolean.parseBoolean(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_CHECK, "true"));
// retrieve default quota values
int roleQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ROLE, "1000"));
int roleMemberQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ROLE_MEMBER, "100"));
int policyQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_POLICY, "1000"));
int assertionQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ASSERTION, "100"));
int serviceQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_SERVICE, "250"));
int serviceHostQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_SERVICE_HOST, "10"));
int publicKeyQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_PUBLIC_KEY, "100"));
int entityQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ENTITY, "100"));
int subDomainQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_SUBDOMAIN, "100"));
defaultQuota = new Quota().setName("server-default")
.setAssertion(assertionQuota).setEntity(entityQuota)
.setPolicy(policyQuota).setPublicKey(publicKeyQuota)
.setRole(roleQuota).setRoleMember(roleMemberQuota)
.setService(serviceQuota).setServiceHost(serviceHostQuota)
.setSubdomain(subDomainQuota).setModified(Timestamp.fromCurrentTime());
}
public Quota getDomainQuota(ObjectStoreConnection con, String domainName) {
Quota quota = con.getQuota(domainName);
return (quota == null) ? defaultQuota : quota;
}
void setQuotaCheckEnabled(boolean quotaCheckEnabled) {
this.quotaCheckEnabled = quotaCheckEnabled;
}
int getListSize(List<?> list) {
return (list == null) ? 0 : list.size();
}
void checkSubdomainQuota(ObjectStoreConnection con, String domainName, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// for sub-domains we need to run the quota check against
// the top level domain so let's get that first. If we are
// creating a top level domain then there is no need for
// quota check
int idx = domainName.indexOf('.');
if (idx == -1) {
return;
}
final String topLevelDomain = domainName.substring(0, idx);
// now get the quota for the top level domain
final Quota quota = getDomainQuota(con, topLevelDomain);
// get the list of sub-domains for our given top level domain
final String domainPrefix = topLevelDomain + ".";
int objectCount = con.listDomains(domainPrefix, 0).size() + 1;
if (quota.getSubdomain() < objectCount) {
throw ZMSUtils.quotaLimitError("subdomain quota exceeded - limit: "
+ quota.getSubdomain() + " actual: " + objectCount, caller);
}
}
void checkRoleQuota(ObjectStoreConnection con, String domainName, Role role, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// if our role is null then there is no quota check
if (role == null) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// first we're going to verify the elements that do not
// require any further data from the object store
int objectCount = getListSize(role.getRoleMembers());
if (quota.getRoleMember() < objectCount) {
throw ZMSUtils.quotaLimitError("role member quota exceeded - limit: "
+ quota.getRoleMember() + " actual: " + objectCount, caller);
}
// now we're going to check if we'll be allowed
// to create this role in the domain
objectCount = con.countRoles(domainName) + 1;
if (quota.getRole() < objectCount) {
throw ZMSUtils.quotaLimitError("role quota exceeded - limit: "
+ quota.getRole() + " actual: " + objectCount, caller);
}
}
void checkRoleMembershipQuota(ObjectStoreConnection con, String domainName,
String roleName, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// now check to make sure we can add 1 more member
// to this role without exceeding the quota
int objectCount = con.countRoleMembers(domainName, roleName) + 1;
if (quota.getRoleMember() < objectCount) {
throw ZMSUtils.quotaLimitError("role member quota exceeded - limit: "
+ quota.getRoleMember() + " actual: " + objectCount, caller);
}
}
void checkPolicyQuota(ObjectStoreConnection con, String domainName, Policy policy, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// if our policy is null then there is no quota check
if (policy == null) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// first we're going to verify the elements that do not
// require any further data from the object store
int objectCount = getListSize(policy.getAssertions());
if (quota.getAssertion() < objectCount) {
throw ZMSUtils.quotaLimitError("policy assertion quota exceeded - limit: "
+ quota.getAssertion() + " actual: " + objectCount, caller);
}
// now we're going to check if we'll be allowed
// to create this policy in the domain
objectCount = con.countPolicies(domainName) + 1;
if (quota.getPolicy() < objectCount) {
throw ZMSUtils.quotaLimitError("policy quota exceeded - limit: "
+ quota.getPolicy() + " actual: " + objectCount, caller);
}
}
void checkPolicyAssertionQuota(ObjectStoreConnection con, String domainName,
String policyName, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// now check to make sure we can add 1 more assertion
// to this policy without exceeding the quota
int objectCount = con.countAssertions(domainName, policyName) + 1;
if (quota.getAssertion() < objectCount) {
throw ZMSUtils.quotaLimitError("policy assertion quota exceeded - limit: "
+ quota.getAssertion() + " actual: " + objectCount, caller);
}
}
void checkServiceIdentityQuota(ObjectStoreConnection con, String domainName,
ServiceIdentity service, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// if our service is null then there is no quota check
if (service == null) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// first we're going to verify the elements that do not
// require any further data from the object store
int objectCount = getListSize(service.getHosts());
if (quota.getServiceHost() < objectCount) {
throw ZMSUtils.quotaLimitError("service host quota exceeded - limit: "
+ quota.getServiceHost() + " actual: " + objectCount, caller);
}
objectCount = getListSize(service.getPublicKeys());
if (quota.getPublicKey() < objectCount) {
throw ZMSUtils.quotaLimitError("service public key quota exceeded - limit: "
+ quota.getPublicKey() + " actual: " + objectCount, caller);
}
// now we're going to check if we'll be allowed
// to create this service in the domain
objectCount = con.countServiceIdentities(domainName) + 1;
if (quota.getService() < objectCount) {
throw ZMSUtils.quotaLimitError("service quota exceeded - limit: "
+ quota.getService() + " actual: " + objectCount, caller);
}
}
void checkServiceIdentityPublicKeyQuota(ObjectStoreConnection con, String domainName,
String serviceName, String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// now check to make sure we can add 1 more public key
// to this policy without exceeding the quota
int objectCount = con.countPublicKeys(domainName, serviceName) + 1;
if (quota.getPublicKey() < objectCount) {
throw ZMSUtils.quotaLimitError("service public key quota exceeded - limit: "
+ quota.getPublicKey() + " actual: " + objectCount, caller);
}
}
void checkEntityQuota(ObjectStoreConnection con, String domainName, Entity entity,
String caller) {
// if quota check is disabled we have nothing to do
if (!quotaCheckEnabled) {
return;
}
// if our entity is null then there is no quota check
if (entity == null) {
return;
}
// first retrieve the domain quota
final Quota quota = getDomainQuota(con, domainName);
// we're going to check if we'll be allowed
// to create this entity in the domain
int objectCount = con.countEntities(domainName) + 1;
if (quota.getEntity() < objectCount) {
throw ZMSUtils.quotaLimitError("entity quota exceeded - limit: "
+ quota.getEntity() + " actual: " + objectCount, caller);
}
}
}
| gurleen-gks/athenz | servers/zms/src/main/java/com/yahoo/athenz/zms/QuotaChecker.java | Java | apache-2.0 | 12,013 |
/* 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 java.nio;
import libcore.io.SizeOf;
/**
* This class wraps a byte buffer to be a char buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by
* the adapter. It must NOT be accessed outside the adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter.
* The adapter extends Buffer, thus has its own position and limit.</li>
* </ul>
* </p>
*
*/
final class ByteBufferAsCharBuffer extends CharBuffer {
private final ByteBuffer byteBuffer;
static CharBuffer asCharBuffer(ByteBuffer byteBuffer) {
ByteBuffer slice = byteBuffer.slice();
slice.order(byteBuffer.order());
return new ByteBufferAsCharBuffer(slice);
}
private ByteBufferAsCharBuffer(ByteBuffer byteBuffer) {
super(byteBuffer.capacity() / SizeOf.CHAR);
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress;
}
@Override
public CharBuffer asReadOnlyBuffer() {
ByteBufferAsCharBuffer buf = new ByteBufferAsCharBuffer(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
buf.byteBuffer.order = byteBuffer.order;
return buf;
}
@Override
public CharBuffer compact() {
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
byteBuffer.limit(limit * SizeOf.CHAR);
byteBuffer.position(position * SizeOf.CHAR);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
@Override
public CharBuffer duplicate() {
ByteBuffer bb = byteBuffer.duplicate().order(byteBuffer.order());
ByteBufferAsCharBuffer buf = new ByteBufferAsCharBuffer(bb);
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public char get() {
if (position == limit) {
throw new BufferUnderflowException();
}
return byteBuffer.getChar(position++ * SizeOf.CHAR);
}
@Override
public char get(int index) {
checkIndex(index);
return byteBuffer.getChar(index * SizeOf.CHAR);
}
@Override
public CharBuffer get(char[] dst, int dstOffset, int charCount) {
byteBuffer.limit(limit * SizeOf.CHAR);
byteBuffer.position(position * SizeOf.CHAR);
if (byteBuffer instanceof DirectByteBuffer) {
((DirectByteBuffer) byteBuffer).get(dst, dstOffset, charCount);
} else {
((ByteArrayBuffer) byteBuffer).get(dst, dstOffset, charCount);
}
this.position += charCount;
return this;
}
@Override
public boolean isDirect() {
return byteBuffer.isDirect();
}
@Override
public boolean isReadOnly() {
return byteBuffer.isReadOnly();
}
@Override
public ByteOrder order() {
return byteBuffer.order();
}
@Override char[] protectedArray() {
throw new UnsupportedOperationException();
}
@Override int protectedArrayOffset() {
throw new UnsupportedOperationException();
}
@Override boolean protectedHasArray() {
return false;
}
@Override
public CharBuffer put(char c) {
if (position == limit) {
throw new BufferOverflowException();
}
byteBuffer.putChar(position++ * SizeOf.CHAR, c);
return this;
}
@Override
public CharBuffer put(int index, char c) {
checkIndex(index);
byteBuffer.putChar(index * SizeOf.CHAR, c);
return this;
}
@Override
public CharBuffer put(char[] src, int srcOffset, int charCount) {
byteBuffer.limit(limit * SizeOf.CHAR);
byteBuffer.position(position * SizeOf.CHAR);
if (byteBuffer instanceof DirectByteBuffer) {
((DirectByteBuffer) byteBuffer).put(src, srcOffset, charCount);
} else {
((ByteArrayBuffer) byteBuffer).put(src, srcOffset, charCount);
}
this.position += charCount;
return this;
}
@Override
public CharBuffer slice() {
byteBuffer.limit(limit * SizeOf.CHAR);
byteBuffer.position(position * SizeOf.CHAR);
ByteBuffer bb = byteBuffer.slice().order(byteBuffer.order());
CharBuffer result = new ByteBufferAsCharBuffer(bb);
byteBuffer.clear();
return result;
}
@Override public CharBuffer subSequence(int start, int end) {
checkStartEndRemaining(start, end);
CharBuffer result = duplicate();
result.limit(position + end);
result.position(position + start);
return result;
}
}
| indashnet/InDashNet.Open.UN2000 | android/libcore/luni/src/main/java/java/nio/ByteBufferAsCharBuffer.java | Java | apache-2.0 | 5,714 |
/*
* Copyright © 2014 - 2018 Leipzig University (Database Research Group)
*
* 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.gradoop.examples.io;
import org.apache.flink.api.common.ProgramDescription;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.gradoop.examples.AbstractRunner;
import org.gradoop.flink.io.impl.deprecated.json.JSONDataSink;
import org.gradoop.flink.io.impl.deprecated.json.JSONDataSource;
import org.gradoop.flink.model.impl.epgm.GraphCollection;
import org.gradoop.flink.model.impl.epgm.LogicalGraph;
import org.gradoop.flink.model.impl.operators.combination.ReduceCombination;
import org.gradoop.flink.model.impl.operators.grouping.Grouping;
import org.gradoop.flink.util.GradoopFlinkConfig;
import static java.util.Collections.singletonList;
/**
* Example program that reads a graph from an EPGM-specific JSON representation
* into a {@link GraphCollection}, does some computation and stores the
* resulting {@link LogicalGraph} as JSON.
*
* In the JSON representation, an EPGM graph collection (or Logical Graph) is
* stored in three (or two) separate files. Each line in those files contains
* a valid JSON-document describing a single entity:
*
* Example graphHead (data attached to logical graphs):
*
* {
* "id":"graph-uuid-1",
* "data":{"interest":"Graphs","vertexCount":4},
* "meta":{"label":"Community"}
* }
*
* Example vertex JSON document:
*
* {
* "id":"vertex-uuid-1",
* "data":{"gender":"m","city":"Dresden","name":"Dave","age":40},
* "meta":{"label":"Person","graphs":["graph-uuid-1"]}
* }
*
* Example edge JSON document:
*
* {
* "id":"edge-uuid-1",
* "source":"14505ae1-5003-4458-b86b-d137daff6525",
* "target":"ed8386ee-338a-4177-82c4-6c1080df0411",
* "data":{},
* "meta":{"label":"friendOf","graphs":["graph-uuid-1"]}
* }
*
* An example graph collection can be found under src/main/resources/data.json.
* For further information, have a look at the {@link org.gradoop.flink.io.impl.deprecated.json}
* package.
*/
public class JSONExample extends AbstractRunner implements ProgramDescription {
/**
* Reads an EPGM graph collection from a directory that contains the separate
* files. Files can be stored in local file system or HDFS.
*
* args[0]: path to input graph
* args[1]: path to output graph
*
* @param args program arguments
*/
public static void main(String[] args) throws Exception {
if (args.length != 2) {
throw new IllegalArgumentException(
"provide graph/vertex/edge paths and output directory");
}
final String inputPath = args[0];
final String outputPath = args[1];
// init Flink execution environment
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
// create default Gradoop config
GradoopFlinkConfig config = GradoopFlinkConfig.createConfig(env);
// create DataSource
JSONDataSource dataSource = new JSONDataSource(inputPath, config);
// read graph collection from DataSource
GraphCollection graphCollection = dataSource.getGraphCollection();
// do some analytics
LogicalGraph schema = graphCollection
.reduce(new ReduceCombination())
.groupBy(singletonList(Grouping.LABEL_SYMBOL), singletonList(Grouping.LABEL_SYMBOL));
// write resulting graph to DataSink
schema.writeTo(new JSONDataSink(outputPath, config));
// execute program
env.execute();
}
@Override
public String getDescription() {
return "EPGM JSON IO Example";
}
}
| niklasteichmann/gradoop | gradoop-examples/src/main/java/org/gradoop/examples/io/JSONExample.java | Java | apache-2.0 | 4,053 |
package com.altas.preferencevobjectfile.model;
import java.io.Serializable;
/**
* @author Altas
* @email [email protected]
* @date 2014年9月27日
*/
public class UserInfo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8558071977129572083L;
public int id;
public String token;
public String userName;
public String headImg;
public String phoneNum;
public double balance;
public int integral;
public UserInfo(){}
public UserInfo(int i,String t,String un,String hi,String pn,double b,int point){
id=i;
token=t;
userName = un;
headImg = hi;
phoneNum = pn;
balance = b;
integral = point;
}
}
| mdreza/PreferenceVObjectFile | PreferenceVObjectFile/src/com/altas/preferencevobjectfile/model/UserInfo.java | Java | apache-2.0 | 663 |
/* Copyright 2017 Braden Farmer
*
* 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.farmerbb.secondscreen.service;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.inputmethodservice.InputMethodService;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.text.InputType;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import com.farmerbb.secondscreen.R;
import com.farmerbb.secondscreen.receiver.KeyboardChangeReceiver;
import com.farmerbb.secondscreen.util.U;
import java.util.Random;
public class DisableKeyboardService extends InputMethodService {
Integer notificationId;
@Override
public boolean onShowInputRequested(int flags, boolean configChange) {
return false;
}
@Override
public void onStartInput(EditorInfo attribute, boolean restarting) {
boolean isEditingText = attribute.inputType != InputType.TYPE_NULL;
boolean hasHardwareKeyboard = getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS;
if(notificationId == null && isEditingText && !hasHardwareKeyboard) {
Intent keyboardChangeIntent = new Intent(this, KeyboardChangeReceiver.class);
PendingIntent keyboardChangePendingIntent = PendingIntent.getBroadcast(this, 0, keyboardChangeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
.setContentIntent(keyboardChangePendingIntent)
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setContentTitle(getString(R.string.disabling_soft_keyboard))
.setContentText(getString(R.string.tap_to_change_keyboards))
.setOngoing(true)
.setShowWhen(false);
// Respect setting to hide notification
SharedPreferences prefMain = U.getPrefMain(this);
if(prefMain.getBoolean("hide_notification", false))
notification.setPriority(Notification.PRIORITY_MIN);
notificationId = new Random().nextInt();
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(notificationId, notification.build());
boolean autoShowInputMethodPicker = false;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
switch(devicePolicyManager.getStorageEncryptionStatus()) {
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
break;
default:
autoShowInputMethodPicker = true;
break;
}
}
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if(keyguardManager.inKeyguardRestrictedInputMode() && autoShowInputMethodPicker) {
InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
manager.showInputMethodPicker();
}
} else if(notificationId != null && !isEditingText) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
notificationId = null;
}
}
@Override
public void onDestroy() {
if(notificationId != null) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
notificationId = null;
}
super.onDestroy();
}
}
| farmerbb/SecondScreen | app/src/main/java/com/farmerbb/secondscreen/service/DisableKeyboardService.java | Java | apache-2.0 | 4,734 |
/**
* Copyright (c) 2005-2012 https://github.com/zhuruiboqq
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.sishuok.es.common.entity.search.filter;
import com.sishuok.es.common.entity.search.SearchOperator;
import com.sishuok.es.common.entity.search.exception.InvlidSearchOperatorException;
import com.sishuok.es.common.entity.search.exception.SearchException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import java.util.List;
/**
* <p>查询过滤条件</p>
* <p>User: Zhang Kaitao
* <p>Date: 13-1-15 上午7:12
* <p>Version: 1.0
*/
public final class Condition implements SearchFilter {
//查询参数分隔符
public static final String separator = "_";
private String key;
private String searchProperty;
private SearchOperator operator;
private Object value;
/**
* 根据查询key和值生成Condition
*
* @param key 如 name_like
* @param value
* @return
*/
static Condition newCondition(final String key, final Object value) throws SearchException {
Assert.notNull(key, "Condition key must not null");
String[] searchs = StringUtils.split(key, separator);
if (searchs.length == 0) {
throw new SearchException("Condition key format must be : property or property_op");
}
String searchProperty = searchs[0];
SearchOperator operator = null;
if (searchs.length == 1) {
operator = SearchOperator.custom;
} else {
try {
operator = SearchOperator.valueOf(searchs[1]);
} catch (IllegalArgumentException e) {
throw new InvlidSearchOperatorException(searchProperty, searchs[1]);
}
}
boolean allowBlankValue = SearchOperator.isAllowBlankValue(operator);
boolean isValueBlank = (value == null);
isValueBlank = isValueBlank || (value instanceof String && StringUtils.isBlank((String) value));
isValueBlank = isValueBlank || (value instanceof List && ((List) value).size() == 0);
//过滤掉空值,即不参与查询
if (!allowBlankValue && isValueBlank) {
return null;
}
Condition searchFilter = newCondition(searchProperty, operator, value);
return searchFilter;
}
/**
* 根据查询属性、操作符和值生成Condition
*
* @param searchProperty
* @param operator
* @param value
* @return
*/
static Condition newCondition(final String searchProperty, final SearchOperator operator, final Object value) {
return new Condition(searchProperty, operator, value);
}
/**
* @param searchProperty 属性名
* @param operator 操作
* @param value 值
*/
private Condition(final String searchProperty, final SearchOperator operator, final Object value) {
this.searchProperty = searchProperty;
this.operator = operator;
this.value = value;
this.key = this.searchProperty + separator + this.operator;
}
public String getKey() {
return key;
}
public String getSearchProperty() {
return searchProperty;
}
/**
* 获取 操作符
*
* @return
*/
public SearchOperator getOperator() throws InvlidSearchOperatorException {
return operator;
}
/**
* 获取自定义查询使用的操作符
* 1、首先获取前台传的
* 2、返回空
*
* @return
*/
public String getOperatorStr() {
if (operator != null) {
return operator.getSymbol();
}
return "";
}
public Object getValue() {
return value;
}
public void setValue(final Object value) {
this.value = value;
}
public void setOperator(final SearchOperator operator) {
this.operator = operator;
}
public void setSearchProperty(final String searchProperty) {
this.searchProperty = searchProperty;
}
/**
* 得到实体属性名
*
* @return
*/
public String getEntityProperty() {
return searchProperty;
}
/**
* 是否是一元过滤 如is null is not null
*
* @return
*/
public boolean isUnaryFilter() {
String operatorStr = getOperator().getSymbol();
return StringUtils.isNotEmpty(operatorStr) && operatorStr.startsWith("is");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Condition that = (Condition) o;
if (key != null ? !key.equals(that.key) : that.key != null) return false;
return true;
}
@Override
public int hashCode() {
return key != null ? key.hashCode() : 0;
}
@Override
public String toString() {
return "Condition{" +
"searchProperty='" + searchProperty + '\'' +
", operator=" + operator +
", value=" + value +
'}';
}
}
| zhuruiboqq/romantic-factor_baseOnES | common/src/main/java/com/sishuok/es/common/entity/search/filter/Condition.java | Java | apache-2.0 | 5,176 |
package com.hzh.corejava.proxy;
public class SpeakerExample {
public static void main(String[] args) {
AiSpeaker speaker = (AiSpeaker) AuthenticationProxy.newInstance(new XiaoaiAiSpeeker());
speaker.greeting();
}
}
| huangzehai/core-java | src/main/java/com/hzh/corejava/proxy/SpeakerExample.java | Java | apache-2.0 | 240 |
package io.skysail.server.queryfilter.nodes.test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import io.skysail.domain.Entity;
import io.skysail.server.domain.jvm.FieldFacet;
import io.skysail.server.domain.jvm.facets.NumberFacet;
import io.skysail.server.domain.jvm.facets.YearFacet;
import io.skysail.server.filter.ExprNode;
import io.skysail.server.filter.FilterVisitor;
import io.skysail.server.filter.Operation;
import io.skysail.server.filter.PreparedStatement;
import io.skysail.server.filter.SqlFilterVisitor;
import io.skysail.server.queryfilter.nodes.LessNode;
import lombok.Data;
public class LessNodeTest {
@Data
public class SomeEntity implements Entity {
private String id, A, B;
}
@Test
public void defaultConstructor_creates_node_with_AND_operation_and_zero_children() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.getOperation(),is(Operation.LESS));
assertThat(lessNode.isLeaf(),is(true));
}
@Test
public void listConstructor_creates_node_with_AND_operation_and_assigns_the_children_parameter() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.getOperation(),is(Operation.LESS));
}
@Test
public void lessNode_with_one_children_gets_rendered() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.asLdapString(),is("(A<0)"));
}
@Test
public void nodes_toString_method_provides_representation() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.toString(),is("(A<0)"));
}
@Test
public void reduce_removes_the_matching_child() {
LessNode lessNode = new LessNode("A", 0);
Map<String, String> config = new HashMap<>();
config.put("BORDERS", "1");
assertThat(lessNode.reduce("(A<0)", new NumberFacet("A",config), null).asLdapString(),is(""));
}
@Test
public void reduce_does_not_remove_non_matching_child() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.reduce("b",null, null).asLdapString(),is("(A<0)"));
}
@Test
public void creates_a_simple_preparedStatement() {
LessNode lessNode = new LessNode("A", 0);
Map<String, FieldFacet> facets = new HashMap<>();
PreparedStatement createPreparedStatement = (PreparedStatement) lessNode.accept(new SqlFilterVisitor(facets));
assertThat(createPreparedStatement.getParams().get("A"),is("0"));
assertThat(createPreparedStatement.getSql(), is("A<:A"));
}
@Test
public void creates_a_preparedStatement_with_year_facet() {
LessNode lessNode = new LessNode("A", 0);
Map<String, FieldFacet> facets = new HashMap<>();
Map<String, String> config = new HashMap<>();
facets.put("A", new YearFacet("A", config));
PreparedStatement createPreparedStatement = (PreparedStatement) lessNode.accept(new SqlFilterVisitor(facets));
assertThat(createPreparedStatement.getParams().get("A"),is("0"));
assertThat(createPreparedStatement.getSql(), is("A.format('YYYY')<:A"));
}
// @Test
// public void evaluateEntity() {
// LessNode lessNode = new LessNode("A", 0);
// Map<String, FieldFacet> facets = new HashMap<>();
// Map<String, String> config = new HashMap<>();
// facets.put("A", new YearFacet("A", config));
//
// SomeEntity someEntity = new SomeEntity();
// someEntity.setA(0);
// someEntity.setB("b");
//
// EntityEvaluationFilterVisitor entityEvaluationVisitor = new EntityEvaluationFilterVisitor(someEntity, facets);
// boolean evaluateEntity = lessNode.evaluateEntity(entityEvaluationVisitor);
//
// assertThat(evaluateEntity,is(false));
// }
@Test
@Ignore
public void getSelected() {
LessNode lessNode = new LessNode("A", 0);
FieldFacet facet = new YearFacet("id", Collections.emptyMap());
Iterator<String> iterator = lessNode.getSelected(facet,Collections.emptyMap()).iterator();
assertThat(iterator.next(),is("0"));
}
@Test
public void getKeys() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.getKeys().size(),is(1));
Iterator<String> iterator = lessNode.getKeys().iterator();
assertThat(iterator.next(),is("A"));
}
@Test
public void accept() {
LessNode lessNode = new LessNode("A", 0);
assertThat(lessNode.accept(new FilterVisitor() {
@Override
public String visit(ExprNode node) {
return ".";
}
}),is("."));
}
}
| evandor/skysail | skysail.server.queryfilter/test/io/skysail/server/queryfilter/nodes/test/LessNodeTest.java | Java | apache-2.0 | 4,873 |
import ch.usi.overseer.OverAgent;
import ch.usi.overseer.OverHpc;
/**
* Overseer.OverAgent sample application.
* This example shows a basic usage of the OverAgent java agent to keep track of all the threads created
* by the JVM. Threads include garbage collectors, finalizers, etc. In order to use OverAgent, make sure to
* append this option to your command-line:
*
* -agentpath:/usr/local/lib/liboverAgent.so
*
* @author Achille Peternier (C) 2011 USI
*/
public class java_agent
{
static public void main(String argv[])
{
// Credits:
System.out.println("Overseer Java Agent test, A. Peternier (C) USI 2011\n");
// Check that -agentpath is working:
if (OverAgent.isRunning())
System.out.println(" OverAgent is running");
else
{
System.out.println(" OverAgent is not running (check your JVM settings)");
return;
}
// Get some info:
System.out.println(" Threads running: " + OverAgent.getNumberOfThreads());
System.out.println();
OverAgent.initEventCallback(new OverAgent.Callback()
{
// Callback invoked at thread creation:
public int onThreadCreation(int pid, String name)
{
System.out.println("[new] " + name + " (" + pid + ")");
return 0;
}
// Callback invoked at thread termination:
public int onThreadTermination(int pid, String name)
{
System.out.println("[delete] " + name + " (" + pid + ")");
return 0;
}});
OverHpc oHpc = OverHpc.getInstance();
int pid = oHpc.getThreadId();
OverAgent.updateStats();
// Waste some time:
double r = 0.0;
for (int d=0; d<10; d++)
{
if (true)
{
for (long c=0; c<100000000; c++)
{
r += r * Math.sqrt(r) * Math.pow(r, 40.0);
}
}
else
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
OverAgent.updateStats();
System.out.println(" Thread " + pid + " abs: " + OverAgent.getThreadCpuUsage(pid) + "%, rel: " + OverAgent.getThreadCpuUsageRelative(pid) + "%");
}
// Done:
System.out.println("Application terminated");
}
}
| IvanMamontov/overseer | examples/java_agent.java | Java | apache-2.0 | 2,131 |
package mat.model;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* The Class SecurityRole.
*/
public class SecurityRole implements IsSerializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The Constant ADMIN_ROLE. */
public static final String ADMIN_ROLE = "Administrator";
/** The Constant USER_ROLE. */
public static final String USER_ROLE = "User";
/** The Constant SUPER_USER_ROLE. */
public static final String SUPER_USER_ROLE = "Super user";
/** The Constant ADMIN_ROLE_ID. */
public static final String ADMIN_ROLE_ID = "1";
/** The Constant USER_ROLE_ID. */
public static final String USER_ROLE_ID = "2";
/** The Constant SUPER_USER_ROLE_ID. */
public static final String SUPER_USER_ROLE_ID = "3";
/** The id. */
private String id;
/** The description. */
private String description;
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Sets the id.
*
* @param id
* the new id
*/
public void setId(String id) {
this.id = id;
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets the description.
*
* @param description
* the new description
*/
public void setDescription(String description) {
this.description = description;
}
}
| JaLandry/MeasureAuthoringTool_LatestSprint | mat/src/mat/model/SecurityRole.java | Java | apache-2.0 | 1,430 |
package com.gaojun.appmarket.ui.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.gaojun.appmarket.R;
/**
* Created by Administrator on 2016/6/29.
*/
public class RationLayout extends FrameLayout {
private float ratio;
public RationLayout(Context context) {
super(context);
initView();
}
public RationLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RationLayout);
int n = array.length();
for (int i = 0; i < n; i++) {
switch (i){
case R.styleable.RationLayout_ratio:
ratio = array.getFloat(R.styleable.RationLayout_ratio,-1);
break;
}
}
array.recycle();
}
public RationLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY &&
ratio>0){
int imageWidth = width - getPaddingLeft() - getPaddingRight();
int imageHeight = (int) (imageWidth/ratio);
height = imageHeight + getPaddingTop() + getPaddingBottom();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void initView() {
}
}
| GaoJunLoveHL/AppMaker | market/src/main/java/com/gaojun/appmarket/ui/view/RationLayout.java | Java | apache-2.0 | 1,962 |
/*
* 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.lightsail.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes a block storage disk mapping.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DiskMap" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DiskMap implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*/
private String originalDiskPath;
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*/
private String newDiskName;
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*
* @param originalDiskPath
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
*/
public void setOriginalDiskPath(String originalDiskPath) {
this.originalDiskPath = originalDiskPath;
}
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*
* @return The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
*/
public String getOriginalDiskPath() {
return this.originalDiskPath;
}
/**
* <p>
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* </p>
*
* @param originalDiskPath
* The original disk path exposed to the instance (for example, <code>/dev/sdh</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DiskMap withOriginalDiskPath(String originalDiskPath) {
setOriginalDiskPath(originalDiskPath);
return this;
}
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*
* @param newDiskName
* The new disk name (e.g., <code>my-new-disk</code>).
*/
public void setNewDiskName(String newDiskName) {
this.newDiskName = newDiskName;
}
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*
* @return The new disk name (e.g., <code>my-new-disk</code>).
*/
public String getNewDiskName() {
return this.newDiskName;
}
/**
* <p>
* The new disk name (e.g., <code>my-new-disk</code>).
* </p>
*
* @param newDiskName
* The new disk name (e.g., <code>my-new-disk</code>).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DiskMap withNewDiskName(String newDiskName) {
setNewDiskName(newDiskName);
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 (getOriginalDiskPath() != null)
sb.append("OriginalDiskPath: ").append(getOriginalDiskPath()).append(",");
if (getNewDiskName() != null)
sb.append("NewDiskName: ").append(getNewDiskName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DiskMap == false)
return false;
DiskMap other = (DiskMap) obj;
if (other.getOriginalDiskPath() == null ^ this.getOriginalDiskPath() == null)
return false;
if (other.getOriginalDiskPath() != null && other.getOriginalDiskPath().equals(this.getOriginalDiskPath()) == false)
return false;
if (other.getNewDiskName() == null ^ this.getNewDiskName() == null)
return false;
if (other.getNewDiskName() != null && other.getNewDiskName().equals(this.getNewDiskName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getOriginalDiskPath() == null) ? 0 : getOriginalDiskPath().hashCode());
hashCode = prime * hashCode + ((getNewDiskName() == null) ? 0 : getNewDiskName().hashCode());
return hashCode;
}
@Override
public DiskMap clone() {
try {
return (DiskMap) 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.lightsail.model.transform.DiskMapMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| aws/aws-sdk-java | aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/DiskMap.java | Java | apache-2.0 | 6,034 |
/*
* Copyright 2011-2014 Zhaotian Wang <[email protected]>
*
* 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 flex.android.magiccube;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Vector;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import flex.android.magiccube.R;
import flex.android.magiccube.bluetooth.MessageSender;
import flex.android.magiccube.interfaces.OnStateListener;
import flex.android.magiccube.interfaces.OnStepListener;
import flex.android.magiccube.solver.MagicCubeSolver;
import flex.android.magiccube.solver.SolverFactory;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.opengl.Matrix;
public class MagicCubeRender implements GLSurfaceView.Renderer {
protected Context context;
private int width;
private int height;
//eye-coordinate
private float eyex;
private float eyey;
protected float eyez;
private float angle = 65.f;
protected float ratio = 0.6f;
protected float zfar = 25.5f;
private float bgdist = 25.f;
//background texture
private int[] BgTextureID = new int[1];
private Bitmap[] bitmap = new Bitmap[1];
private FloatBuffer bgtexBuffer; // Texture Coords Buffer for background
private FloatBuffer bgvertexBuffer; // Vertex Buffer for background
protected final int nStep = 9;//nstep for one rotate
protected int volume;
private boolean solved = false; //indicate if the cube has been solved
//background position
//...
//rotation variable
public float rx, ry;
protected Vector<Command> commands;
private Vector<Command> commandsBack; //backward command
private Vector<Command> commandsForward; //forward command
private Vector<Command> commandsAuto; //forward command
protected int[] command;
protected boolean HasCommand;
protected int CommandLoop;
private String CmdStrBefore = "";
private String CmdStrAfter = "";
public static final boolean ROTATE = true;
public static final boolean MOVE = false;
//matrix
public float[] pro_matrix = new float[16];
public int [] view_matrix = new int[4];
public float[] mod_matrix = new float[16];
//minimal valid move distance
private float MinMovedist;
//the cubes!
protected Magiccube magiccube;
private boolean DrawCube;
private boolean Finished = false;
private boolean Resetting = false;
protected OnStateListener stateListener = null;
private MessageSender messageSender = null;
private OnStepListener stepListener = null;
public MagicCubeRender(Context context, int w, int h) {
this.context = context;
this.width = w;
this.height = h;
this.eyex = 0.f;
this.eyey = 0.f;
this.eyez = 20.f;
this.rx = 22.f;
this.ry = -34.f;
this.HasCommand = false;
this.commands = new Vector<Command>(1,1);
this.commandsBack = new Vector<Command>(100, 10);
this.commandsForward = new Vector<Command>(100, 10);
this.commandsAuto = new Vector<Command>(40,5);
//this.Command = new int[3];
magiccube = new Magiccube();
DrawCube = true;
solved = false;
volume = MagiccubePreference.GetPreference(MagiccubePreference.MoveVolume, context);
//SetCommands("L- R2 F- D+ L+ U2 L2 D2 R+ D2 L+ F- D+ L2 D2 R2 B+ L+ U2 R2 U2 F2 R+ D2 U+");
//SetCommands("F- U+ F- D- L- D- F- U- L2 D-");
// SetCommands("U+");
// mediaPlayer = MediaPlayer.create(context, R.raw.move2);
}
public void SetDrawCube(boolean DrawCube)
{
this.DrawCube = DrawCube;
}
private void LoadBgTexture(GL10 gl)
{
//Load texture bitmap
bitmap[0] = BitmapFactory.decodeStream(
context.getResources().openRawResource(R.drawable.mainbg2));
gl.glGenTextures(1, BgTextureID, 0); // Generate texture-ID array for 6 IDs
//Set texture uv
float[] texCoords = {
0.0f, 1.0f, // A. left-bottom
1.0f, 1.0f, // B. right-bottom
0.0f, 0.0f, // C. left-top
1.0f, 0.0f // D. right-top
};
ByteBuffer tbb = ByteBuffer.allocateDirect(texCoords.length * 4 );
tbb.order(ByteOrder.nativeOrder());
bgtexBuffer = tbb.asFloatBuffer();
bgtexBuffer.put(texCoords);
bgtexBuffer.position(0); // Rewind
// Generate OpenGL texture images
gl.glBindTexture(GL10.GL_TEXTURE_2D, BgTextureID[0]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
// Build Texture from loaded bitmap for the currently-bind texture ID
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap[0], 0);
bitmap[0].recycle();
}
protected void DrawBg(GL10 gl)
{
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, bgvertexBuffer);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, bgtexBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D); // Enable texture (NEW)
gl.glPushMatrix();
gl.glBindTexture(GL10.GL_TEXTURE_2D, this.BgTextureID[0]);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
gl.glPopMatrix();
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
@Override
public void onDrawFrame(GL10 gl) {
// Clear color and depth buffers using clear-value set earlier
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
// You OpenGL|ES rendering code here
gl.glLoadIdentity();
GLU.gluLookAt(gl, eyex, eyey, eyez, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f);
Matrix.setIdentityM(mod_matrix, 0);
Matrix.setLookAtM(mod_matrix, 0, eyex, eyey, eyez, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f);
DrawScene(gl);
}
private void SetBackgroundPosition()
{
float halfheight = (float)Math.tan(angle/2.0/180.0*Math.PI)*bgdist*1.f;
float halfwidth = halfheight/this.height*this.width;
float[] vertices = {
-halfwidth, -halfheight, eyez-bgdist, // 0. left-bottom-front
halfwidth, -halfheight, eyez-bgdist, // 1. right-bottom-front
-halfwidth, halfheight,eyez-bgdist, // 2. left-top-front
halfwidth, halfheight, eyez-bgdist, // 3. right-top-front
};
ByteBuffer vbb = ByteBuffer.allocateDirect(12 * 4);
vbb.order(ByteOrder.nativeOrder());
bgvertexBuffer = vbb.asFloatBuffer();
bgvertexBuffer.put(vertices); // Populate
bgvertexBuffer.position(0); // Rewind
}
@Override
public void onSurfaceChanged(GL10 gl, int w, int h) {
//reset the width and the height;
//Log.e("screen", w+" "+h);
if (h == 0) h = 1; // To prevent divide by zero
this.width = w;
this.height = h;
float aspect = (float)w / h;
// Set the viewport (display area) to cover the entire window
gl.glViewport(0, 0, w, h);
this.view_matrix[0] = 0;
this.view_matrix[1] = 0;
this.view_matrix[2] = w;
this.view_matrix[3] = h;
// Setup perspective projection, with aspect ratio matches viewport
gl.glMatrixMode(GL10.GL_PROJECTION); // Select projection matrix
gl.glLoadIdentity(); // Reset projection matrix
// Use perspective projection
angle = 60;
//calculate the angle to adjust the screen resolution
//float idealwidth = Cube.CubeSize*3.f/(Math.abs(this.eyez-Cube.CubeSize*1.5f))*zfar/ratio;
float idealwidth = Cube.CubeSize*3.f/(Math.abs(this.eyez-Cube.CubeSize*1.5f))*zfar/ratio;
float idealheight = idealwidth/(float)w*(float)h;
angle = (float)(Math.atan2(idealheight/2.f, Math.abs(zfar))*2.f*180.f/Math.PI);
SetBackgroundPosition();
GLU.gluPerspective(gl, angle, aspect, 0.1f, zfar);
MinMovedist = w*ratio/3.f*0.15f;
float r = (float)w/(float)h;
float size = (float)(0.1*Math.tan(angle/2.0/180.0*Math.PI));
Matrix.setIdentityM(pro_matrix, 0);
Matrix.frustumM(pro_matrix, 0, -size*r, size*r, -size , size, 0.1f, zfar);
gl.glMatrixMode(GL10.GL_MODELVIEW); // Select model-view matrix
gl.glLoadIdentity(); // Reset
/* // You OpenGL|ES display re-sizing code here
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
//float []lightparam = {0.6f, 0.2f, 0.2f, 0.6f, 0.2f, 0.2f, 0, 0, 10};
float []lightparam = {1f, 1f, 1f, 3f, 1f, 1f, 0, 0, 5};
gl.glEnable(GL10.GL_LIGHTING);
// ���û�����
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, lightparam, 0);
// ���������
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightparam, 3);
// ���þ��淴��
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_SPECULAR, lightparam, 3);
// ���ù�Դλ��
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightparam, 6);
// ������Դ
gl.glEnable(GL10.GL_LIGHT0);
*/
// �������
//gl.glEnable(GL10.GL_BLEND);
if( this.stateListener != null )
{
stateListener.OnStateChanged(OnStateListener.LOADED);
}
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set color's clear-value to black
gl.glClearDepthf(1.0f); // Set depth's clear-value to farthest
gl.glEnable(GL10.GL_DEPTH_TEST); // Enables depth-buffer for hidden surface removal
gl.glDepthFunc(GL10.GL_LEQUAL); // The type of depth testing to do
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); // nice perspective view
gl.glShadeModel(GL10.GL_SMOOTH); // Enable smooth shading of color
gl.glDisable(GL10.GL_DITHER); // Disable dithering for better performance
// You OpenGL|ES initialization code here
//Initial the cubes
magiccube.LoadTexture(gl, context);
//this.MessUp(50);
LoadBgTexture(gl);
}
public void SetMessageSender(MessageSender messageSender)
{
this.messageSender = messageSender;
}
protected void DrawScene(GL10 gl)
{
this.DrawBg(gl);
if( !DrawCube)
{
return;
}
if(Resetting)
{
//Resetting = false;
//reset();
}
if(HasCommand)
{
Command command = commands.firstElement();
if( CommandLoop == 0 && messageSender != null)
{
messageSender.SendMessage(command.toString());
}
int nsteps = command.N*this.nStep; //rotate nsteps
if(CommandLoop%nStep == 0 && CommandLoop != nsteps)
{
MusicPlayThread musicPlayThread = new MusicPlayThread(context, R.raw.move2, volume);
musicPlayThread.start();
}
if(command.Type == Command.ROTATE_ROW)
{
magiccube.RotateRow(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1);
}
else if(command.Type == Command.ROTATE_COL)
{
magiccube.RotateCol(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1);
}
else
{
magiccube.RotateFace(command.RowID, command.Direction, 90.f/nStep,CommandLoop%nStep==nStep-1);
}
CommandLoop++;
if(CommandLoop==nsteps)
{
CommandLoop = 0;
if(commands.size() > 1)
{
//Log.e("full", "full"+commands.size());
}
this.CmdStrAfter += command.toString() + " ";
commands.removeElementAt(0);
//Log.e("e", commands.size()+"");
if( commands.size() <= 0)
{
HasCommand = false;
}
if( stepListener != null)
{
stepListener.AddStep();
}
//this.ReportFaces();
//Log.e("state", this.GetState());
if(Finished && !this.IsComplete())
{
Finished = false;
if(this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE);
}
}
}
if(this.stateListener != null && this.IsComplete())
{
if( !Finished )
{
Finished = true;
stateListener.OnStateChanged(OnStateListener.FINISH);
stateListener.OnStateNotify(OnStateListener.CANNOTAUTOSOLVE);
}
}
}
DrawCubes(gl);
}
protected void DrawCubes(GL10 gl)
{
gl.glPushMatrix();
gl.glRotatef(rx, 1, 0, 0); //rotate
gl.glRotatef(ry, 0, 1, 0);
// Log.e("rxry", rx + " " + ry);
if(this.HasCommand)
{
magiccube.Draw(gl);
}
else
{
magiccube.DrawSimple(gl);
}
gl.glPopMatrix();
}
public void SetOnStateListener(OnStateListener stateListener)
{
this.stateListener = stateListener;
}
public void SetOnStepListnener(OnStepListener stepListener)
{
this.stepListener = stepListener;
}
public boolean GetPos(float[] point, int[] Pos)
{
//deal with the touch-point is out of the cube
if( true)
{
//return false;
}
if( rx > 0 && rx < 90.f)
{
}
return ROTATE;
}
public String SetCommand(Command command)
{
HasCommand = true;
this.commands.add(command);
this.commandsForward.clear();
this.commandsBack.add(command.Reverse());
if(this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
return command.CmdToCmdStr();
}
public void SetForwardCommand(String CmdStr)
{
//Log.e("cmdstr", CmdStr);
this.commandsForward = Reverse(Command.CmdStrsToCmd(CmdStr));
}
public String SetCommand(int ColOrRowOrFace, int ID, int Direction)
{
solved = false;
return SetCommand(new Command(ColOrRowOrFace, ID, Direction));
}
public boolean IsSolved()
{
return solved;
}
public String MoveBack()
{
if( this.commandsBack.size() <= 0)
{
return null;
}
Command command = commandsBack.lastElement();
HasCommand = true;
this.commands.add(command);
this.commandsBack.remove(this.commandsBack.size()-1);
if(this.commandsBack.size() <= 0 && stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK);
}
if( solved)
{
this.commandsAuto.add(command.Reverse());
}
else
{
this.commandsForward.add(command.Reverse());
if(stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANMOVEFORWARD);
}
}
return command.CmdToCmdStr();
}
public String MoveForward()
{
if( this.commandsForward.size() <= 0)
{
return null;
}
Command command = commandsForward.lastElement();
HasCommand = true;
this.commands.add(command);
this.commandsBack.add(command.Reverse());
this.commandsForward.remove(commandsForward.size()-1);
if( this.commandsForward.size() <= 0 && stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
}
return command.CmdToCmdStr();
}
public int MoveForward2()
{
if( this.commandsForward.size() <= 0)
{
return 0;
}
int n = commandsForward.size();
HasCommand = true;
this.commands.addAll(Reverse(commandsForward));
for( int i=commandsForward.size()-1; i>=0; i--)
{
this.commandsBack.add(commandsForward.get(i).Reverse());
}
this.commandsForward.clear();
if( this.commandsForward.size() <= 0 && stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
}
return n;
}
public int IsInCubeArea(float []Win)
{
int[] HitedFaceIndice = new int[6];
int HitNumber = 0;
for(int i=0; i<6; i++)
{
if(IsInQuad3D(magiccube.faces[i], Win))
{
HitedFaceIndice[HitNumber] = i;
HitNumber++;
}
}
if( HitNumber <=0)
{
return -1;
}
else
{
if( HitNumber == 1)
{
return HitedFaceIndice[0];
}
else //if more than one hitted, then choose the max z-value face as the hitted one
{
float maxzvalue = -1000.f;
int maxzindex = -1;
for( int i = 0; i< HitNumber; i++)
{
float thisz = this.GetCenterZ(magiccube.faces[HitedFaceIndice[i]]);
if( thisz > maxzvalue)
{
maxzvalue = thisz;
maxzindex = HitedFaceIndice[i];
}
}
return maxzindex;
}
}
}
private float GetLength2D(float []P1, float []P2)
{
float dx = P1[0]-P2[0];
float dy = P1[1]-P2[1];
return (float)Math.sqrt(dx*dx + dy*dy);
}
private boolean IsInQuad3D(Face f, float []Win)
{
return IsInQuad3D(f.P1, f.P2, f.P3, f.P4, Win);
}
private boolean IsInQuad3D(float []Point1, float []Point2, float []Point3, float Point4[], float []Win)
{
float[] Win1 = new float[2];
float[] Win2 = new float[2];
float[] Win3 = new float[2];
float[] Win4 = new float[2];
Project(Point1, Win1);
Project(Point2, Win2);
Project(Point3, Win3);
Project(Point4, Win4);
/* Log.e("P1", Win1[0] + " " + Win1[1]);
Log.e("P2", Win2[0] + " " + Win2[1]);
Log.e("P3", Win3[0] + " " + Win3[1]);
Log.e("P4", Win4[0] + " " + Win4[1]);*/
float []WinXY = new float[2];
WinXY[0] = Win[0];
WinXY[1] = this.view_matrix[3] - Win[1];
//Log.e("WinXY", WinXY[0] + " " + WinXY[1]);
return IsInQuad2D(Win1, Win2, Win3, Win4, WinXY);
}
private boolean IsInQuad2D(float []Point1, float []Point2, float []Point3, float Point4[], float []Win)
{
float angle = 0.f;
final float ZERO = 0.0001f;
angle += GetAngle(Win, Point1, Point2);
//Log.e("angle" , angle + " ");
angle += GetAngle(Win, Point2, Point3);
//Log.e("angle" , angle + " ");
angle += GetAngle(Win, Point3, Point4);
//Log.e("angle" , angle + " ");
angle += GetAngle(Win, Point4, Point1);
//Log.e("angle" , angle + " ");
if( Math.abs(angle-Math.PI*2.f) <= ZERO )
{
return true;
}
return false;
}
public String CalcCommand(float [] From, float [] To, int faceindex)
{
float [] from = new float[2];
float [] to = new float[2];
float angle, angleVertical, angleHorizon;
from[0] = From[0];
from[1] = this.view_matrix[3] - From[1];
to[0] = To[0];
to[1] = this.view_matrix[3] - To[1];
angle = GetAngle(from, to);//(float)Math.atan((to[1]-from[1])/(to[0]-from[0]))/(float)Math.PI*180.f;
//calc horizon angle
float ObjFrom[] = new float[3];
float ObjTo[] = new float[3];
float WinFrom[] = new float[2];
float WinTo[] = new float[2];
for(int i=0; i<3; i++)
{
ObjFrom[i] = (magiccube.faces[faceindex].P1[i] + magiccube.faces[faceindex].P4[i])/2.f;
ObjTo[i] = (magiccube.faces[faceindex].P2[i] + magiccube.faces[faceindex].P3[i])/2.f;
}
//Log.e("obj", ObjFrom[0]+" "+ObjFrom[1]+" "+ObjFrom[2]);
this.Project(ObjFrom, WinFrom);
this.Project(ObjTo, WinTo);
angleHorizon = GetAngle(WinFrom, WinTo);//(float)Math.atan((WinTo[1]-WinFrom[1])/(WinTo[0]-WinFrom[0]))/(float)Math.PI*180.f;
//calc vertical angle
for(int i=0; i<3; i++)
{
ObjFrom[i] = (magiccube.faces[faceindex].P1[i] + magiccube.faces[faceindex].P2[i])/2.f;
ObjTo[i] = (magiccube.faces[faceindex].P3[i] + magiccube.faces[faceindex].P4[i])/2.f;
}
this.Project(ObjFrom, WinFrom);
this.Project(ObjTo, WinTo);
angleVertical = GetAngle(WinFrom, WinTo);//(float)Math.atan((WinTo[1]-WinFrom[1])/(WinTo[0]-WinFrom[0]))/(float)Math.PI*180.f;
//Log.e("angle", angle +" " + angleHorizon + " " + angleVertical);
float dangle = DeltaAngle(angleHorizon, angleVertical);
float threshold = Math.min(dangle/2.f, 90.f-dangle/2.f)*0.75f; //this...........
if( DeltaAngle(angle, angleHorizon) < threshold || DeltaAngle(angle, (angleHorizon+180.f)%360.f) < threshold) //the direction
{
if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(0), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(1), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if( faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetHorizonSubFace(2), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if( faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_ROW, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleHorizon) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
}
}
}
else if( DeltaAngle(angle, angleVertical) < threshold || DeltaAngle(angle, (angleVertical+180.f)%360.f) < threshold)
{
if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(0), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(1), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 1, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 1, Cube.ClockWise);
}
}
}
else if(this.IsInQuad3D(magiccube.faces[faceindex].GetVerticalSubFace(2), From))
{
if( faceindex == Face.FRONT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.BACK)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 0, Cube.CounterClockWise);
}
}
else if(faceindex == Face.LEFT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 0, Cube.ClockWise);
}
}
else if(faceindex == Face.RIGHT)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.ClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_FACE, 2, Cube.CounterClockWise);
}
}
else if(faceindex == Face.TOP)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
}
else if(faceindex == Face.BOTTOM)
{
if(DeltaAngle(angle, angleVertical) < threshold)
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.CounterClockWise);
}
else
{
return this.SetCommand(Command.ROTATE_COL, 2, Cube.ClockWise);
}
}
}
}
return null;
}
private float GetAngle(float[] From, float[] To)
{
float angle = (float)Math.atan((To[1]-From[1])/(To[0]-From[0]))/(float)Math.PI*180.f;
float dy = To[1]-From[1];
float dx = To[0]-From[0];
if( dy >= 0.f && dx > 0.f)
{
angle = (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
else if( dx == 0.f)
{
if( dy > 0.f)
{
angle = 90.f;
}
else
{
angle = 270.f;
}
}
else if( dy >= 0.f && dx < 0.f)
{
angle = 180.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
else if( dy < 0.f && dx < 0.f)
{
angle = 180.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
else if(dy <0.f && dx > 0.f)
{
angle = 360.f + (float)Math.atan(dy/dx)/(float)Math.PI*180.f;
}
return angle;
}
private float DeltaAngle(float angle1, float angle2)
{
float a1 = Math.max(angle1, angle2);
float a2 = Math.min(angle1, angle2);
float delta = a1 - a2;
if( delta >= 180.f )
{
delta = 360.f - delta;
}
return delta;
}
private float GetCenterZ(Face f)
{
float zvalue = 0.f;
float [] matrix1 = new float[16];
float [] matrix2 = new float[16];
float [] matrix = new float[16];
Matrix.setIdentityM(matrix1, 0);
Matrix.setIdentityM(matrix2, 0);
Matrix.setIdentityM(matrix, 0);
Matrix.rotateM(matrix1, 0, rx, 1, 0, 0);
Matrix.rotateM(matrix2, 0, ry, 0, 1, 0);
Matrix.multiplyMM(matrix, 0, matrix1, 0, matrix2, 0);
float xyz[] = new float[3];
xyz[0] = f.P1[0];
xyz[1] = f.P1[1];
xyz[2] = f.P1[2];
Transform(matrix, xyz);
zvalue += xyz[2];
xyz[0] = f.P2[0];
xyz[1] = f.P2[1];
xyz[2] = f.P2[2];
Transform(matrix, xyz);
zvalue += xyz[2];
xyz[0] = f.P3[0];
xyz[1] = f.P3[1];
xyz[2] = f.P3[2];
Transform(matrix, xyz);
zvalue += xyz[2];
xyz[0] = f.P4[0];
xyz[1] = f.P4[1];
xyz[2] = f.P4[2];
Transform(matrix, xyz);
zvalue += xyz[2];
return zvalue/4.f;
}
private float GetAngle(float []Point0, float []Point1, float[]Point2)
{
float cos_value = (Point2[0]-Point0[0])*(Point1[0]-Point0[0]) + (Point1[1]-Point0[1])*(Point2[1]-Point0[1]);
cos_value /= Math.sqrt((Point2[0]-Point0[0])*(Point2[0]-Point0[0]) + (Point2[1]-Point0[1])*(Point2[1]-Point0[1]))
* Math.sqrt((Point1[0]-Point0[0])*(Point1[0]-Point0[0]) + (Point1[1]-Point0[1])*(Point1[1]-Point0[1]));
return (float)Math.acos(cos_value);
}
private void Project(float[] ObjXYZ, float [] WinXY)
{
float [] matrix1 = new float[16];
float [] matrix2 = new float[16];
float [] matrix = new float[16];
Matrix.setIdentityM(matrix1, 0);
Matrix.setIdentityM(matrix2, 0);
Matrix.setIdentityM(matrix, 0);
Matrix.rotateM(matrix1, 0, rx, 1, 0, 0);
Matrix.rotateM(matrix2, 0, ry, 0, 1, 0);
Matrix.multiplyMM(matrix, 0, matrix1, 0, matrix2, 0);
float xyz[] = new float[3];
xyz[0] = ObjXYZ[0];
xyz[1] = ObjXYZ[1];
xyz[2] = ObjXYZ[2];
Transform(matrix, xyz);
//Log.e("xyz", xyz[0] + " " + xyz[1] + " " + xyz[2]);
float []Win = new float[3];
GLU.gluProject(xyz[0], xyz[1], xyz[2], mod_matrix, 0, pro_matrix, 0, view_matrix, 0, Win, 0);
WinXY[0] = Win[0];
WinXY[1] = Win[1];
}
private void Transform(float[]matrix, float[]Point)
{
float w = 1.f;
float x, y, z, ww;
x = matrix[0]*Point[0] + matrix[4]*Point[1] + matrix[8]*Point[2] + matrix[12]*w;
y = matrix[1]*Point[0] + matrix[5]*Point[1] + matrix[9]*Point[2] + matrix[13]*w;
z = matrix[2]*Point[0] + matrix[6]*Point[1] + matrix[10]*Point[2] + matrix[14]*w;
ww = matrix[3]*Point[0] + matrix[7]*Point[1] + matrix[11]*Point[2] + matrix[15]*w;
Point[0] = x/ww;
Point[1] = y/ww;
Point[2] = z/ww;
}
public boolean IsComplete()
{
boolean r = true;
for( int i=0; i<6; i++)
{
r = r&&magiccube.faces[i].IsSameColor();
}
return magiccube.IsComplete();
}
public String MessUp(int nStep)
{
this.solved = false;
this.Finished = false;
if( this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE);
}
return magiccube.MessUp(nStep);
}
public void MessUp(String cmdstr)
{
this.solved = false;
magiccube.MessUp(cmdstr);
this.Finished = false;
if( this.stateListener != null)
{
stateListener.OnStateNotify(OnStateListener.CANAUTOSOLVE);
}
}
public boolean IsMoveValid(float[]From, float []To)
{
return this.GetLength2D(From, To) > this.MinMovedist;
}
public void SetCommands(String cmdStr)
{
this.commands = Command.CmdStrsToCmd(cmdStr);
this.HasCommand = true;
}
public String SetCommand(String cmdStr)
{
return SetCommand(Command.CmdStrToCmd(cmdStr));
}
public void AutoSolve(String SolverName)
{
if( !solved)
{
MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName);
if(solver == null)
{
return;
}
//Log.e("state", this.GetState());
String SolveCmd = solver.AutoSolve(magiccube.GetState());
//Log.e("solve", SolveCmd);
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK);
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
}
this.commandsAuto = Reverse(Command.CmdStrsToCmd(SolveCmd));
this.solved = true;
}
else if(commandsAuto.size() > 0)
{
Command command = commandsAuto.lastElement();
HasCommand = true;
this.commands.add(command);
this.commandsBack.add(command.Reverse());
this.commandsAuto.remove(commandsAuto.size()-1);
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANMOVEBACK);
}
}
}
public void AutoSolve2(String SolverName)
{
if( !solved)
{
MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName);
if(solver == null)
{
return;
}
//Log.e("state", this.GetState());
String SolveCmd = solver.AutoSolve(magiccube.GetState());
//Log.e("solve", SolveCmd);
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
this.commands = Command.CmdStrsToCmd(SolveCmd);
for( int i=0; i<commands.size(); i++)
{
commandsBack.add(commands.get(i).Reverse());
}
this.HasCommand = true;
this.solved = true;
}
else
{
commands.addAll(Reverse(commandsAuto));
for( int i=commandsAuto.size()-1; i>=0; i--)
{
commandsBack.add(commandsAuto.get(i).Reverse());
}
commandsAuto.clear();
HasCommand = true;
}
}
public void AutoSolve3(String SolverName)
{
if( !solved)
{
MagicCubeSolver solver = SolverFactory.CreateSolver(SolverName);
if(solver == null)
{
return;
}
//Log.e("state", this.GetState());
String SolveCmd = solver.AutoSolve(magiccube.GetState());
//Log.e("solve", SolveCmd);
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
this.commands = Command.CmdStrsToCmd(SolveCmd);
commands.remove(commands.size()-1);
commands.remove(commands.size()-1);
for( int i=0; i<commands.size(); i++)
{
commandsBack.add(commands.get(i).Reverse());
}
this.HasCommand = true;
this.solved = true;
}
else
{
commands.addAll(Reverse(commandsAuto));
for( int i=commandsAuto.size()-1; i>=0; i--)
{
commandsBack.add(commandsAuto.get(i).Reverse());
}
commandsAuto.clear();
HasCommand = true;
}
}
private Vector<Command> Reverse(Vector<Command> v)
{
Vector<Command> v2 = new Vector<Command>(v.size());
for(int i=v.size()-1; i>=0; i--)
{
v2.add(v.elementAt(i));
}
return v2;
}
public void Reset()
{
Resetting = true;
reset();
}
private void reset()
{
this.rx = 22.f;
this.ry = -34.f;
this.HasCommand = false;
Finished = false;
this.CommandLoop = 0;
this.commands.clear();
this.commandsBack.clear();
this.commandsForward.clear();
this.CmdStrAfter = "";
this.CmdStrBefore = "";
magiccube.Reset();
if( this.stateListener != null)
{
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEBACK);
this.stateListener.OnStateNotify(OnStateListener.CANNOTMOVEFORWARD);
this.stateListener.OnStateNotify(OnStateListener.CANNOTAUTOSOLVE);
}
}
public String GetCmdStrBefore()
{
return this.CmdStrBefore;
}
public void SetCmdStrBefore(String CmdStrBefore)
{
this.CmdStrBefore = CmdStrBefore;
}
public void SetCmdStrAfter(String CmdStrAfter)
{
this.CmdStrAfter = CmdStrAfter;
}
public String GetCmdStrAfter()
{
return this.CmdStrAfter;
}
public void setVolume(int volume) {
this.volume = volume;
}
}
| flexwang/HappyRubik | src/flex/android/magiccube/MagicCubeRender.java | Java | apache-2.0 | 40,437 |
package sagex.phoenix.remote.services;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.script.Invocable;
import javax.script.ScriptException;
import sagex.phoenix.util.PhoenixScriptEngine;
public class JSMethodInvocationHandler implements InvocationHandler {
private PhoenixScriptEngine eng;
private Map<String, String> methodMap = new HashMap<String, String>();
public JSMethodInvocationHandler(PhoenixScriptEngine eng, String interfaceMethod, String jsMethod) {
this.eng = eng;
methodMap.put(interfaceMethod, jsMethod);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class == method.getDeclaringClass()) {
String name = method.getName();
if ("equals".equals(name)) {
return proxy == args[0];
} else if ("hashCode".equals(name)) {
return System.identityHashCode(proxy);
} else if ("toString".equals(name)) {
return proxy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(proxy))
+ ", with InvocationHandler " + this;
} else {
throw new IllegalStateException(String.valueOf(method));
}
}
String jsMethod = methodMap.get(method.getName());
if (jsMethod == null) {
throw new NoSuchMethodException("No Javascript Method for " + method.getName());
}
Invocable inv = (Invocable) eng.getEngine();
try {
return inv.invokeFunction(jsMethod, args);
} catch (NoSuchMethodException e) {
throw new NoSuchMethodException("The Java Method: " + method.getName() + " maps to a Javascript Method " + jsMethod
+ " that does not exist.");
} catch (ScriptException e) {
throw e;
}
}
}
| stuckless/sagetv-phoenix-core | src/main/java/sagex/phoenix/remote/services/JSMethodInvocationHandler.java | Java | apache-2.0 | 1,998 |
package io.izenecloud.larser.framework;
import io.izenecloud.conf.Configuration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.StringOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LaserArgument {
private static final Logger LOG = LoggerFactory
.getLogger(LaserArgument.class);
public static final Set<String> VALID_ARGUMENTS = new HashSet<String>(
Arrays.asList("-configure"));
@Option(name = "-configure", required = true, handler = StringOptionHandler.class)
private String configure;
public String getConfigure() {
return configure;
}
public static void parseArgs(String[] args) throws CmdLineException,
IOException {
ArrayList<String> argsList = new ArrayList<String>(Arrays.asList(args));
for (int i = 0; i < args.length; i++) {
if (i % 2 == 0 && !LaserArgument.VALID_ARGUMENTS.contains(args[i])) {
argsList.remove(args[i]);
argsList.remove(args[i + 1]);
}
}
final LaserArgument laserArgument = new LaserArgument();
new CmdLineParser(laserArgument).parseArgument(argsList
.toArray(new String[argsList.size()]));
Configuration conf = Configuration.getInstance();
LOG.info("Load configure, {}", laserArgument.getConfigure());
Path path = new Path(laserArgument.getConfigure());
FileSystem fs = FileSystem
.get(new org.apache.hadoop.conf.Configuration());
conf.load(path, fs);
}
}
| izenecloud/laser | src/main/java/io/izenecloud/larser/framework/LaserArgument.java | Java | apache-2.0 | 1,698 |
package com.nagopy.android.disablemanager2;
import android.os.Build;
import com.android.uiautomator.core.UiSelector;
@SuppressWarnings("unused")
public class UiSelectorBuilder {
private UiSelector uiSelector;
public UiSelector build() {
return uiSelector;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder() {
uiSelector = new UiSelector();
}
/**
* @since API Level 16
*/
public UiSelectorBuilder text(String text) {
uiSelector = uiSelector.text(text);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder textMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.textMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder textStartsWith(String text) {
uiSelector = uiSelector.textStartsWith(text);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder textContains(String text) {
uiSelector = uiSelector.textContains(text);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder className(String className) {
uiSelector = uiSelector.className(className);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder classNameMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.classNameMatches(regex);
}
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder className(Class<?> type) {
uiSelector = uiSelector.className(type.getName());
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder description(String desc) {
uiSelector = uiSelector.description(desc);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder descriptionMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.descriptionMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder descriptionStartsWith(String desc) {
uiSelector = uiSelector.descriptionStartsWith(desc);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder descriptionContains(String desc) {
uiSelector = uiSelector.descriptionContains(desc);
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder resourceId(String id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.resourceId(id);
}
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder resourceIdMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.resourceIdMatches(regex);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder index(final int index) {
uiSelector = uiSelector.index(index);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder instance(final int instance) {
uiSelector = uiSelector.instance(instance);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder enabled(boolean val) {
uiSelector = uiSelector.enabled(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder focused(boolean val) {
uiSelector = uiSelector.focused(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder focusable(boolean val) {
uiSelector = uiSelector.focusable(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder scrollable(boolean val) {
uiSelector = uiSelector.scrollable(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder selected(boolean val) {
uiSelector = uiSelector.selected(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder checked(boolean val) {
uiSelector = uiSelector.checked(val);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder clickable(boolean val) {
uiSelector = uiSelector.clickable(val);
return this;
}
/**
* @since API Level 18
*/
public UiSelectorBuilder checkable(boolean val) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
uiSelector = uiSelector.checkable(val);
}
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder longClickable(boolean val) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.longClickable(val);
}
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder childSelector(UiSelector selector) {
uiSelector = uiSelector.childSelector(selector);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder fromParent(UiSelector selector) {
uiSelector = uiSelector.fromParent(selector);
return this;
}
/**
* @since API Level 16
*/
public UiSelectorBuilder packageName(String name) {
uiSelector = uiSelector.packageName(name);
return this;
}
/**
* @since API Level 17
*/
public UiSelectorBuilder packageNameMatches(String regex) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
uiSelector = uiSelector.packageNameMatches(regex);
}
return this;
}
}
| 75py/DisableManager | uiautomator/src/main/java/com/nagopy/android/disablemanager2/UiSelectorBuilder.java | Java | apache-2.0 | 6,177 |
package com.salesmanager.shop.model.entity;
import java.io.Serializable;
public abstract class ReadableList implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int totalPages;//totalPages
private int number;//number of record in current page
private long recordsTotal;//total number of records in db
private int recordsFiltered;
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalCount) {
this.totalPages = totalCount;
}
public long getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(long recordsTotal) {
this.recordsTotal = recordsTotal;
}
public int getRecordsFiltered() {
return recordsFiltered;
}
public void setRecordsFiltered(int recordsFiltered) {
this.recordsFiltered = recordsFiltered;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
} | shopizer-ecommerce/shopizer | sm-shop-model/src/main/java/com/salesmanager/shop/model/entity/ReadableList.java | Java | apache-2.0 | 950 |
/*
* @(#)file SASLOutputStream.java
* @(#)author Sun Microsystems, Inc.
* @(#)version 1.10
* @(#)lastedit 07/03/08
* @(#)build @BUILD_TAG_PLACEHOLDER@
*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
*
* The contents of this file are subject to the terms of either the GNU General
* Public License Version 2 only ("GPL") or the Common Development and
* Distribution License("CDDL")(collectively, the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy of the
* License at http://opendmk.dev.java.net/legal_notices/licenses.txt or in the
* LEGAL_NOTICES folder that accompanied this code. See the License for the
* specific language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file found at
* http://opendmk.dev.java.net/legal_notices/licenses.txt
* or in the LEGAL_NOTICES folder that accompanied this code.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.
*
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
*
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding
*
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license."
*
* If you don't indicate a single choice of license, a recipient has the option
* to distribute your version of this file under either the CDDL or the GPL
* Version 2, or to extend the choice of license to its licensees as provided
* above. However, if you add GPL Version 2 code and therefore, elected the
* GPL Version 2 license, then the option applies only if the new code is made
* subject to such option by the copyright holder.
*
*/
package com.sun.jmx.remote.opt.security;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslServer;
import java.io.IOException;
import java.io.OutputStream;
import com.sun.jmx.remote.opt.util.ClassLogger;
public class SASLOutputStream extends OutputStream {
private int rawSendSize = 65536;
private byte[] lenBuf = new byte[4]; // buffer for storing length
private OutputStream out; // underlying output stream
private SaslClient sc;
private SaslServer ss;
public SASLOutputStream(SaslClient sc, OutputStream out)
throws IOException {
super();
this.out = out;
this.sc = sc;
this.ss = null;
String str = (String) sc.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
if (str != null) {
try {
rawSendSize = Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IOException(Sasl.RAW_SEND_SIZE +
" property must be numeric string: " + str);
}
}
}
public SASLOutputStream(SaslServer ss, OutputStream out)
throws IOException {
super();
this.out = out;
this.ss = ss;
this.sc = null;
String str = (String) ss.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
if (str != null) {
try {
rawSendSize = Integer.parseInt(str);
} catch (NumberFormatException e) {
throw new IOException(Sasl.RAW_SEND_SIZE +
" property must be numeric string: " + str);
}
}
}
public void write(int b) throws IOException {
byte[] buffer = new byte[1];
buffer[0] = (byte)b;
write(buffer, 0, 1);
}
public void write(byte[] buffer, int offset, int total) throws IOException {
int count;
byte[] wrappedToken, saslBuffer;
// "Packetize" buffer to be within rawSendSize
if (logger.traceOn()) {
logger.trace("write", "Total size: " + total);
}
for (int i = 0; i < total; i += rawSendSize) {
// Calculate length of current "packet"
count = (total - i) < rawSendSize ? (total - i) : rawSendSize;
// Generate wrapped token
if (sc != null)
wrappedToken = sc.wrap(buffer, offset+i, count);
else
wrappedToken = ss.wrap(buffer, offset+i, count);
// Write out length
intToNetworkByteOrder(wrappedToken.length, lenBuf, 0, 4);
if (logger.traceOn()) {
logger.trace("write", "sending size: " + wrappedToken.length);
}
out.write(lenBuf, 0, 4);
// Write out wrapped token
out.write(wrappedToken, 0, wrappedToken.length);
}
}
public void close() throws IOException {
if (sc != null)
sc.dispose();
else
ss.dispose();
out.close();
}
/**
* Encodes an integer into 4 bytes in network byte order in the buffer
* supplied.
*/
private void intToNetworkByteOrder(int num, byte[] buf,
int start, int count) {
if (count > 4) {
throw new IllegalArgumentException("Cannot handle more " +
"than 4 bytes");
}
for (int i = count-1; i >= 0; i--) {
buf[start+i] = (byte)(num & 0xff);
num >>>= 8;
}
}
private static final ClassLogger logger =
new ClassLogger("javax.management.remote.misc", "SASLOutputStream");
}
| nickman/heliosutils | src/main/java/com/sun/jmx/remote/opt/security/SASLOutputStream.java | Java | apache-2.0 | 5,384 |
/*******************************************************************************
* Copyright © 2012-2015 eBay Software Foundation
* This program is dual licensed under the MIT and Apache 2.0 licenses.
* Please see LICENSE for more information.
*******************************************************************************/
package com.ebay.pulsar.analytics.metricstore.druid.query.sql;
/**
*
* @author mingmwang
*
*/
public class HllConstants {
public static final String HLLPREFIX = "hllhaving_";
}
| pulsarIO/pulsar-reporting-api | pulsarquery-druid/src/main/java/com/ebay/pulsar/analytics/metricstore/druid/query/sql/HllConstants.java | Java | apache-2.0 | 514 |
/**************************************************************************
* Mask.java is part of Touch4j 4.0. Copyright 2012 Emitrom LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
**************************************************************************/
package com.emitrom.touch4j.client.ui;
import com.emitrom.touch4j.client.core.Component;
import com.emitrom.touch4j.client.core.config.Attribute;
import com.emitrom.touch4j.client.core.config.Event;
import com.emitrom.touch4j.client.core.config.XType;
import com.emitrom.touch4j.client.core.handlers.CallbackRegistration;
import com.emitrom.touch4j.client.core.handlers.mask.MaskTapHandler;
import com.google.gwt.core.client.JavaScriptObject;
/**
* A simple class used to mask any Container. This should rarely be used
* directly, instead look at the Container.mask configuration.
*
* @see <a href=http://docs.sencha.com/touch/2-0/#!/api/Ext.Mask>Ext.Mask</a>
*/
public class Mask extends Component {
@Override
protected native void init()/*-{
var c = new $wnd.Ext.Mask();
[email protected]::configPrototype = c.initialConfig;
}-*/;
@Override
public String getXType() {
return XType.MASK.getValue();
}
@Override
protected native JavaScriptObject create(JavaScriptObject config) /*-{
return new $wnd.Ext.Mask(config);
}-*/;
public Mask() {
}
protected Mask(JavaScriptObject jso) {
super(jso);
}
/**
* True to make this mask transparent.
*
* Defaults to: false
*
* @param value
*/
public void setTransparent(String value) {
setAttribute(Attribute.TRANSPARENT.getValue(), value, true);
}
/**
* A tap event fired when a user taps on this mask
*
* @param handler
*/
public CallbackRegistration addTapHandler(MaskTapHandler handler) {
return this.addWidgetListener(Event.TAP.getValue(), handler.getJsoPeer());
}
}
| paulvi/touch4j | src/com/emitrom/touch4j/client/ui/Mask.java | Java | apache-2.0 | 2,495 |
/*
* Copyright 2017-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.util.trace.uploader.launcher;
import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.log.Logger;
import com.facebook.buck.util.env.BuckClasspath;
import com.facebook.buck.util.trace.uploader.types.CompressionType;
import com.google.common.base.Strings;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
/** Utility to upload chrome trace in background. */
public class UploaderLauncher {
private static final Logger LOG = Logger.get(UploaderLauncher.class);
/** Upload chrome trace in background process which runs even after current process dies. */
public static void uploadInBackground(
BuildId buildId,
Path traceFilePath,
String traceFileKind,
URI traceUploadUri,
Path logFile,
CompressionType compressionType) {
LOG.debug("Uploading build trace in the background. Upload will log to %s", logFile);
String buckClasspath = BuckClasspath.getBuckClasspathFromEnvVarOrNull();
if (Strings.isNullOrEmpty(buckClasspath)) {
LOG.error(
BuckClasspath.ENV_VAR_NAME + " env var is not set. Will not upload the trace file.");
return;
}
try {
String[] args = {
"java",
"-cp",
buckClasspath,
"com.facebook.buck.util.trace.uploader.Main",
"--buildId",
buildId.toString(),
"--traceFilePath",
traceFilePath.toString(),
"--traceFileKind",
traceFileKind,
"--baseUrl",
traceUploadUri.toString(),
"--log",
logFile.toString(),
"--compressionType",
compressionType.name(),
};
Runtime.getRuntime().exec(args);
} catch (IOException e) {
LOG.error(e, e.getMessage());
}
}
}
| LegNeato/buck | src/com/facebook/buck/util/trace/uploader/launcher/UploaderLauncher.java | Java | apache-2.0 | 2,379 |
/*
* Copyright 2013, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.builder;
import org.jf.dexlib2.*;
import org.jf.dexlib2.builder.instruction.*;
import org.jf.dexlib2.iface.instruction.*;
import java.util.*;
import javax.annotation.*;
public abstract class BuilderSwitchPayload extends BuilderInstruction implements SwitchPayload {
@Nullable
MethodLocation referrer;
protected BuilderSwitchPayload(@Nonnull Opcode opcode) {
super(opcode);
}
@Nonnull
public MethodLocation getReferrer() {
if (referrer == null) {
throw new IllegalStateException("The referrer has not been set yet");
}
return referrer;
}
@Nonnull
@Override
public abstract List<? extends BuilderSwitchElement> getSwitchElements();
}
| nao20010128nao/show-java | app/src/main/java/org/jf/dexlib2/builder/BuilderSwitchPayload.java | Java | apache-2.0 | 2,310 |
package nodeAST.relational;
import java.util.Map;
import nodeAST.BinaryExpr;
import nodeAST.Expression;
import nodeAST.Ident;
import nodeAST.literals.Literal;
import types.BoolType;
import types.Type;
import visitor.ASTVisitor;
import visitor.IdentifiersTypeMatcher;
public class NEq extends BinaryExpr {
public NEq(Expression leftHandOperand, Expression rightHandOperand) {
super(leftHandOperand,rightHandOperand);
}
@Override
public void accept(ASTVisitor visitor) {
visitor.visit(this, this.leftHandOperand, this.rightHandOperand);
}
@Override
public String toString() {
return this.leftHandOperand.toString() + "!=" + this.rightHandOperand.toString();
}
@Override
public Type getType(IdentifiersTypeMatcher typeMatcher) {
return new BoolType();
}
@Override
public boolean areOperandsTypeValid(IdentifiersTypeMatcher typeMatcher) {
Type t1=this.leftHandOperand.getType(typeMatcher);
Type t2=this.rightHandOperand.getType(typeMatcher);
return t1.isCompatibleWith(t2) &&
(t1.isArithmetic() || t1.isBoolean() || t1.isRelational() || t1.isString() );
}
@Override
public Literal compute(Map<Ident, Expression> identifiers) {
return this.leftHandOperand.compute(identifiers).neq(
this.rightHandOperand.compute(identifiers)
);
}
}
| software-engineering-amsterdam/poly-ql | GeorgePachitariu/ANTLR-First/src/nodeAST/relational/NEq.java | Java | apache-2.0 | 1,336 |
package edu.ptu.javatest._60_dsa;
import org.junit.Test;
import java.util.TreeMap;
import static edu.ptu.javatest._20_ooad._50_dynamic._00_ReflectionTest.getRefFieldBool;
import static edu.ptu.javatest._20_ooad._50_dynamic._00_ReflectionTest.getRefFieldObj;
public class _35_TreeMapTest {
@Test
public void testPrintTreeMap() {
TreeMap hashMapTest = new TreeMap<>();
for (int i = 0; i < 6; i++) {
hashMapTest.put(new TMHashObj(1,i*2 ), i*2 );
}
Object table = getRefFieldObj(hashMapTest, hashMapTest.getClass(), "root");
printTreeMapNode(table);
hashMapTest.put(new TMHashObj(1,9), 9);
printTreeMapNode(table);
System.out.println();
}
public static int getTreeDepth(Object rootNode) {
if (rootNode == null || !rootNode.getClass().toString().equals("class java.util.TreeMap$Entry"))
return 0;
return rootNode == null ? 0 : (1 + Math.max(getTreeDepth(getRefFieldObj(rootNode, rootNode.getClass(), "left")), getTreeDepth(getRefFieldObj(rootNode, rootNode.getClass(), "right"))));
}
public static void printTreeMapNode(Object rootNode) {//转化为堆
if (rootNode == null || !rootNode.getClass().toString().equals("class java.util.TreeMap$Entry"))
return;
int treeDepth = getTreeDepth(rootNode);
Object[] objects = new Object[(int) (Math.pow(2, treeDepth) - 1)];
objects[0] = rootNode;
// objects[0]=rootNode;
// objects[1]=getRefFieldObj(objects,objects.getClass(),"left");
// objects[2]=getRefFieldObj(objects,objects.getClass(),"right");
//
// objects[3]=getRefFieldObj(objects[1],objects[1].getClass(),"left");
// objects[4]=getRefFieldObj(objects[1],objects[1].getClass(),"right");
// objects[5]=getRefFieldObj(objects[2],objects[3].getClass(),"left");
// objects[6]=getRefFieldObj(objects[2],objects[4].getClass(),"right");
for (int i = 1; i < objects.length; i++) {//数组打印
int index = (i - 1) / 2;//parent
if (objects[index] != null) {
if (i % 2 == 1)
objects[i] = getRefFieldObj(objects[index], objects[index].getClass(), "left");
else
objects[i] = getRefFieldObj(objects[index], objects[index].getClass(), "right");
}
}
StringBuilder sb = new StringBuilder();
StringBuilder outSb = new StringBuilder();
String space = " ";
for (int i = 0; i < treeDepth + 1; i++) {
sb.append(space);
}
int nextlineIndex = 0;
for (int i = 0; i < objects.length; i++) {//new line: 0,1 ,3,7
//print space
//print value
if (nextlineIndex == i) {
outSb.append("\n\n");
if (sb.length() >= space.length()) {
sb.delete(0, space.length());
}
nextlineIndex = i * 2 + 1;
}
outSb.append(sb.toString());
if (objects[i] != null) {
Object value = getRefFieldObj(objects[i], objects[i].getClass(), "value");
boolean red = !getRefFieldBool(objects[i], objects[i].getClass(), "color");// BLACK = true;
String result = "" + value + "(" + (red ? "r" : "b") + ")";
outSb.append(result);
} else {
outSb.append("nil");
}
}
System.out.println(outSb.toString());
}
public static class TMHashObj implements Comparable{
int hash;
int value;
TMHashObj(int hash, int value) {
this.hash = hash;
this.value = value;
}
@Override
public int hashCode() {
return hash;
}
@Override
public int compareTo(Object o) {
if (o instanceof TMHashObj){
return this.value-((TMHashObj) o).value;
}
return value-o.hashCode();
}
}
}
| rickgit/Test | JavaTest/src/main/java/edu/ptu/javatest/_60_dsa/_35_TreeMapTest.java | Java | apache-2.0 | 4,084 |
package com.cisco.axl.api._8;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LPhoneSecurityProfile complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="LPhoneSecurityProfile">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element name="phoneType" type="{http://www.cisco.com/AXL/API/8.0}XModel" minOccurs="0"/>
* <element name="protocol" type="{http://www.cisco.com/AXL/API/8.0}XDeviceProtocol" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="deviceSecurityMode" type="{http://www.cisco.com/AXL/API/8.0}XDeviceSecurityMode" minOccurs="0"/>
* <element name="authenticationMode" type="{http://www.cisco.com/AXL/API/8.0}XAuthenticationMode" minOccurs="0"/>
* <element name="keySize" type="{http://www.cisco.com/AXL/API/8.0}XKeySize" minOccurs="0"/>
* <element name="tftpEncryptedConfig" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="nonceValidityTime" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <element name="transportType" type="{http://www.cisco.com/AXL/API/8.0}XTransport" minOccurs="0"/>
* <element name="sipPhonePort" type="{http://www.cisco.com/AXL/API/8.0}XInteger" minOccurs="0"/>
* <element name="enableDigestAuthentication" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* <element name="excludeDigestCredentials" type="{http://www.cisco.com/AXL/API/8.0}boolean" minOccurs="0"/>
* </sequence>
* <attribute name="uuid" type="{http://www.cisco.com/AXL/API/8.0}XUUID" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LPhoneSecurityProfile", propOrder = {
"phoneType",
"protocol",
"name",
"description",
"deviceSecurityMode",
"authenticationMode",
"keySize",
"tftpEncryptedConfig",
"nonceValidityTime",
"transportType",
"sipPhonePort",
"enableDigestAuthentication",
"excludeDigestCredentials"
})
public class LPhoneSecurityProfile {
protected String phoneType;
protected String protocol;
protected String name;
protected String description;
protected String deviceSecurityMode;
protected String authenticationMode;
protected String keySize;
protected String tftpEncryptedConfig;
protected String nonceValidityTime;
protected String transportType;
protected String sipPhonePort;
protected String enableDigestAuthentication;
protected String excludeDigestCredentials;
@XmlAttribute
protected String uuid;
/**
* Gets the value of the phoneType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPhoneType() {
return phoneType;
}
/**
* Sets the value of the phoneType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPhoneType(String value) {
this.phoneType = value;
}
/**
* Gets the value of the protocol property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProtocol() {
return protocol;
}
/**
* Sets the value of the protocol property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProtocol(String value) {
this.protocol = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the 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 deviceSecurityMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDeviceSecurityMode() {
return deviceSecurityMode;
}
/**
* Sets the value of the deviceSecurityMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDeviceSecurityMode(String value) {
this.deviceSecurityMode = value;
}
/**
* Gets the value of the authenticationMode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuthenticationMode() {
return authenticationMode;
}
/**
* Sets the value of the authenticationMode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuthenticationMode(String value) {
this.authenticationMode = value;
}
/**
* Gets the value of the keySize property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKeySize() {
return keySize;
}
/**
* Sets the value of the keySize property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKeySize(String value) {
this.keySize = value;
}
/**
* Gets the value of the tftpEncryptedConfig property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTftpEncryptedConfig() {
return tftpEncryptedConfig;
}
/**
* Sets the value of the tftpEncryptedConfig property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTftpEncryptedConfig(String value) {
this.tftpEncryptedConfig = value;
}
/**
* Gets the value of the nonceValidityTime property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNonceValidityTime() {
return nonceValidityTime;
}
/**
* Sets the value of the nonceValidityTime property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNonceValidityTime(String value) {
this.nonceValidityTime = value;
}
/**
* Gets the value of the transportType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportType() {
return transportType;
}
/**
* Sets the value of the transportType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportType(String value) {
this.transportType = value;
}
/**
* Gets the value of the sipPhonePort property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSipPhonePort() {
return sipPhonePort;
}
/**
* Sets the value of the sipPhonePort property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSipPhonePort(String value) {
this.sipPhonePort = value;
}
/**
* Gets the value of the enableDigestAuthentication property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEnableDigestAuthentication() {
return enableDigestAuthentication;
}
/**
* Sets the value of the enableDigestAuthentication property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEnableDigestAuthentication(String value) {
this.enableDigestAuthentication = value;
}
/**
* Gets the value of the excludeDigestCredentials property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getExcludeDigestCredentials() {
return excludeDigestCredentials;
}
/**
* Sets the value of the excludeDigestCredentials property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExcludeDigestCredentials(String value) {
this.excludeDigestCredentials = value;
}
/**
* Gets the value of the uuid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUuid() {
return uuid;
}
/**
* Sets the value of the uuid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUuid(String value) {
this.uuid = value;
}
}
| ox-it/cucm-http-api | src/main/java/com/cisco/axl/api/_8/LPhoneSecurityProfile.java | Java | apache-2.0 | 10,171 |
package pokemon.vue;
import pokemon.launcher.PokemonCore;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.*;
public class MyActor extends Actor {
public Texture s=new Texture(Gdx.files.internal("crosshair.png"));
SpriteBatch b=new SpriteBatch();
float x,y;
public MyActor (float x, float y) {
this.x=x;
this.y=y;
System.out.print(PokemonCore.m.getCities().get(0).getX());
this.setBounds(x+PokemonCore.m.getCities().get(0).getX(),y+PokemonCore.m.getCities().get(0).getY(),s.getWidth(),s.getHeight());
/* RepeatAction action = new RepeatAction();
action.setCount(RepeatAction.FOREVER);
action.setAction(Actions.fadeOut(2f));*/
this.addAction(Actions.repeat(RepeatAction.FOREVER,Actions.sequence(Actions.fadeOut(1f),Actions.fadeIn(1f))));
//posx=this.getX();
//posy=this.getY();
//this.addAction(action);
//this.addAction(Actions.sequence(Actions.alpha(0),Actions.fadeIn(2f)));
System.out.println("Actor constructed");
b.getProjectionMatrix().setToOrtho2D(0, 0,640,360);
}
@Override
public void draw (Batch batch, float parentAlpha) {
b.begin();
Color color = getColor();
b.setColor(color.r, color.g, color.b, color.a * parentAlpha);
b.draw(s,this.getX()-15,this.getY()-15,30,30);
b.setColor(color);
b.end();
//System.out.println("Called");
//batch.draw(t,this.getX(),this.getY(),t.getWidth(),t.getHeight());
//batch.draw(s,this.getX()+Minimap.BourgPalette.getX(),this.getY()+Minimap.BourgPalette.getY(),30,30);
}
public void setPosition(float x, float y){
this.setX(x+this.x);
this.setY(y+this.y);
}
}
| yongaro/Pokemon | Pokemon-core/src/main/java/pokemon/vue/MyActor.java | Java | apache-2.0 | 2,197 |
package org.tiltedwindmills.fantasy.mfl.services;
import org.tiltedwindmills.fantasy.mfl.model.LoginResponse;
/**
* Interface defining operations required for logging into an MFL league.
*/
public interface LoginService {
/**
* Login.
*
* @param leagueId the league id
* @param serverId the server id
* @param year the year
* @param franchiseId the franchise id
* @param password the password
* @return the login response
*/
LoginResponse login(int leagueId, int serverId, int year, String franchiseId, String password);
}
| tiltedwindmills/mfl-api | src/main/java/org/tiltedwindmills/fantasy/mfl/services/LoginService.java | Java | apache-2.0 | 571 |
package org.ns.vk.cachegrabber.ui;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import org.ns.func.Callback;
import org.ns.ioc.IoC;
import org.ns.vk.cachegrabber.api.Application;
import org.ns.vk.cachegrabber.api.vk.Audio;
import org.ns.vk.cachegrabber.api.vk.VKApi;
/**
*
* @author stupak
*/
public class TestAction extends AbstractAction {
public TestAction() {
super("Test action");
}
@Override
public void actionPerformed(ActionEvent e) {
VKApi vkApi = IoC.get(Application.class).getVKApi();
String ownerId = "32659923";
String audioId = "259636837";
vkApi.getById(ownerId, audioId, new Callback<Audio>() {
@Override
public void call(Audio audio) {
Logger.getLogger(TestAction.class.getName()).log(Level.INFO, "loaded audio: {0}", audio);
}
});
}
}
| nikolaas/vk-cache-grabber | src/main/java/org/ns/vk/cachegrabber/ui/TestAction.java | Java | apache-2.0 | 994 |
package com.mapswithme.maps.maplayer.traffic;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
@MainThread
public enum TrafficManager
{
INSTANCE;
private final static String TAG = TrafficManager.class.getSimpleName();
@NonNull
private final Logger mLogger = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.TRAFFIC);
@NonNull
private final TrafficState.StateChangeListener mStateChangeListener = new TrafficStateListener();
@NonNull
private TrafficState mState = TrafficState.DISABLED;
@NonNull
private final List<TrafficCallback> mCallbacks = new ArrayList<>();
private boolean mInitialized = false;
public void initialize()
{
mLogger.d(TAG, "Initialization of traffic manager and setting the listener for traffic state changes");
TrafficState.nativeSetListener(mStateChangeListener);
mInitialized = true;
}
public void toggle()
{
checkInitialization();
if (isEnabled())
disable();
else
enable();
}
private void enable()
{
mLogger.d(TAG, "Enable traffic");
TrafficState.nativeEnable();
}
private void disable()
{
checkInitialization();
mLogger.d(TAG, "Disable traffic");
TrafficState.nativeDisable();
}
public boolean isEnabled()
{
checkInitialization();
return TrafficState.nativeIsEnabled();
}
public void attach(@NonNull TrafficCallback callback)
{
checkInitialization();
if (mCallbacks.contains(callback))
{
throw new IllegalStateException("A callback '" + callback
+ "' is already attached. Check that the 'detachAll' method was called.");
}
mLogger.d(TAG, "Attach callback '" + callback + "'");
mCallbacks.add(callback);
postPendingState();
}
private void postPendingState()
{
mStateChangeListener.onTrafficStateChanged(mState.ordinal());
}
public void detachAll()
{
checkInitialization();
if (mCallbacks.isEmpty())
{
mLogger.w(TAG, "There are no attached callbacks. Invoke the 'detachAll' method " +
"only when it's really needed!", new Throwable());
return;
}
for (TrafficCallback callback : mCallbacks)
mLogger.d(TAG, "Detach callback '" + callback + "'");
mCallbacks.clear();
}
private void checkInitialization()
{
if (!mInitialized)
throw new AssertionError("Traffic manager is not initialized!");
}
public void setEnabled(boolean enabled)
{
checkInitialization();
if (isEnabled() == enabled)
return;
if (enabled)
enable();
else
disable();
}
private class TrafficStateListener implements TrafficState.StateChangeListener
{
@Override
@MainThread
public void onTrafficStateChanged(int index)
{
TrafficState newTrafficState = TrafficState.values()[index];
mLogger.d(TAG, "onTrafficStateChanged current state = " + mState
+ " new value = " + newTrafficState);
if (mState == newTrafficState)
return;
mState = newTrafficState;
mState.activate(mCallbacks);
}
}
public interface TrafficCallback
{
void onEnabled();
void onDisabled();
void onWaitingData();
void onOutdated();
void onNetworkError();
void onNoData();
void onExpiredData();
void onExpiredApp();
}
}
| rokuz/omim | android/src/com/mapswithme/maps/maplayer/traffic/TrafficManager.java | Java | apache-2.0 | 3,514 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.