text
stringlengths 7
1.01M
|
|---|
/**
* Copyright 2013 52°North Initiative for Geospatial Open Source Software GmbH
*
* 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.n52.oss.sir;
/**
* @author Daniel Nüst
*
*/
public class SMLConstants {
public static final String NAMESPACE = "http://www.opengis.net/sensorML/1.0.1";
public static final String NAMESPACE_PREFIX = "sml";
/**
* Constant for the schema repository of SML
*/
public static final String SCHEMA_LOCATION = NAMESPACE + " http://schemas.opengis.net/sensorML/1.0.1/sensorML.xsd";
public static final String SML_VERSION = "1.0.1";
}
|
package data;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import util.DateUtils;
public class WorkEntry implements Parcelable, Selectable, Comparable<WorkEntry>, Copyable, Restorable{
public static final String PARCELABLE_OBJECT_IDENTIFIER = "work_entry_object_parcel";
public static final String PARCELABLE_ARRAYLIST_IDENTIFIER = "work_entry_list_parcel";
public static final int INVALID_INTEGER = Integer.MAX_VALUE;
public static final long INVALID_LONG = Long.MAX_VALUE;
// Metadata
private long _id = INVALID_LONG;
public long creation_time = INVALID_LONG;
public long last_update = INVALID_LONG; // This gets updated on db operation
private long reference_time = INVALID_LONG;
// Work type related
private String title = null;
private String text = null;
public int type = WorkEntryType.AUTOMATIC;
// Work time related
private List<WorkBlock> work_blocks = new ArrayList<>();
// Helper for recycler views
public boolean isSelected = false;
// Changed
public boolean hasChanged = false;
// Init with default values. Set values later.
public WorkEntry() {
this.creation_time = System.currentTimeMillis();
this.last_update = System.currentTimeMillis();
}
/**
*
* @param referenceTime - Day the work entry is related to
* @param title - The title of the entry
* @param text - The description of the entry
* @param type - The type of the entry found in @link: WorkEntryType
*/
public WorkEntry(final long referenceTime, @Nullable final String title, @Nullable final String text, @WorkEntryType.EntryType final int type){
this(System.currentTimeMillis(), System.currentTimeMillis(), System.currentTimeMillis(), referenceTime, title, text, type);
}
/**
* Constructor used by database created objects
*/
public WorkEntry(long itemId, long creationTime, long lastUpdateTime, long referenceTime, @Nullable String title, @Nullable String text, @WorkEntryType.EntryType int type) {
setId(itemId);
this.creation_time = creationTime;
this.last_update = lastUpdateTime;
this.reference_time = referenceTime;
this.type = type;
setTitle(title);
setText(text);
setChanged(false);
}
public List<WorkBlock> getWorkBlocks(){
return work_blocks;
}
public void addWorkBlock(WorkBlock block){
// Set correct reference id, just to make sure
block.setReferenceId(getId());
work_blocks.add(block);
}
public void addAllWorkBlocks(List<WorkBlock> blocks){
work_blocks.addAll(blocks);
}
public boolean removeWorkBlock(WorkBlock block){
return work_blocks.remove(block);
}
public void removeAllWorkBlocks(){
work_blocks = new ArrayList<>();
}
public int[] getTotalWorkBlockDuration(){
return DateUtils.getDurationInHoursAndMinutes(getTotalWorkBlockDurationInMillies());
}
public long getTotalWorkBlockDurationInMinutes(){
return TimeUnit.MILLISECONDS.toMinutes(getTotalWorkBlockDurationInMillies());
}
public long getTotalWorkBlockDurationInMillies(){
long duration = 0;
for(WorkBlock block : work_blocks){
duration += (block.getWorkEnd() - block.getWorkStart());
}
return duration;
}
public long getDate(){
return reference_time;
}
public void setDate(long timestamp) {
if(timestamp != reference_time){
setChanged(true);
} else {
// No change...
return;
}
// Get difference
long timestampDifference = reference_time - timestamp;
// Set new timestamp
reference_time = timestamp;
// Set all timestamp of the blocks accordingly
for(final WorkBlock block : getWorkBlocks()){
block.setWorkStart(block.getWorkStart() + timestampDifference);
}
}
public @NonNull String getTitle() {
return title == null ? "" : title;
}
public void setTitle(@NonNull String title) {
if(!getTitle().equals(title)){
setChanged(true);
}
this.title = title;
}
public @NonNull String getText() {
return text == null ? "" : text;
}
public void setText(@Nullable String text) {
if(!getText().equals(this.text)){
setChanged(true);
}
this.text = text == null ? "" : text;
}
public void setId(long id){
// Set new reference id for all blocks
for(WorkBlock block : getWorkBlocks()){
block.setReferenceId(id);
}
this._id = id;
}
public long getId(){
return _id;
}
/*
Validation
*/
public boolean hasValidDate(){
return reference_time != INVALID_LONG;
}
public void setChanged(boolean hasChanged){
this.hasChanged = hasChanged;
}
public boolean hasChanged(){
if(!hasChanged){
// Check if any of the entries block has been changed
// If so, the entry itself has changed
for(WorkBlock block : getWorkBlocks()){
if(block.hasChanged()){
setChanged(true);
}
}
}
return hasChanged;
}
/*
Restorable
*/
@Override
public void restore(Object object) {
if(!(object instanceof WorkEntry)){
throw new IllegalArgumentException("Object must me instance of WorkEntry");
}
this._id = ((WorkEntry) object)._id;
this.creation_time = ((WorkEntry) object).creation_time;
this.last_update = ((WorkEntry) object).last_update;
this.reference_time = ((WorkEntry) object).reference_time;
this.title = ((WorkEntry) object).title;
this.text = ((WorkEntry) object).text;
this.removeAllWorkBlocks();
this.addAllWorkBlocks(((WorkEntry) object).getWorkBlocks());
}
/*
Copyable
*/
public Object copy(){
WorkEntry workEntry = new WorkEntry(this._id, this.creation_time, this.last_update, this.reference_time, this.title, this.text, this.type);
for(WorkBlock block : this.getWorkBlocks()){
workEntry.addWorkBlock((WorkBlock) block.copy());
}
return workEntry;
}
/*
Selectable
*/
@Override
public void setSelected(boolean selected) {
isSelected = selected;
}
@Override
public boolean getSelected() {
return isSelected;
}
/*
Parcelable
*/
public WorkEntry(Parcel parcel){
this._id = parcel.readLong();
this.creation_time = parcel.readLong();
this.last_update = parcel.readLong();
this.reference_time = parcel.readLong();
this.title = parcel.readString();
this.text = parcel.readString();
this.type = parcel.readInt();
WorkBlock[] tempArray = new WorkBlock[parcel.readInt()];
tempArray = parcel.createTypedArray(WorkBlock.CREATOR);
//parcel.readTypedArray(tempArray, WorkBlock.CREATOR);
work_blocks = new ArrayList<>(Arrays.asList(tempArray));
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(_id);
parcel.writeLong(creation_time);
parcel.writeLong(last_update);
parcel.writeLong(reference_time);
parcel.writeString(title);
parcel.writeString(text);
parcel.writeInt(type);
WorkBlock[] blocks = new WorkBlock[work_blocks.size()];
int i = 0;
for(WorkBlock block : work_blocks){
blocks[i++] = block;
}
parcel.writeInt(blocks.length);
parcel.writeTypedArray(blocks, flags);
}
public static final Parcelable.Creator<WorkEntry> CREATOR =
new Parcelable.Creator<WorkEntry>() {
@Override
public WorkEntry createFromParcel(Parcel source) {
return new WorkEntry(source);
}
@Override
public WorkEntry[] newArray(int size) {
return new WorkEntry[size];
}
};
/*
Comparable
*/
@Override
public int compareTo(@NonNull WorkEntry another) {
/**
* Sort in desc order to have the newest one on top
*/
if (this.reference_time < another.reference_time) {
return 1;
}else if(this.reference_time == another.reference_time) {
return 0;
}
return -1;
}
}
|
package ij.plugin;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.awt.image.*;
import java.io.*;
import java.lang.reflect.*;
import ij.*;
import ij.process.*;
import ij.gui.*;
import ij.plugin.frame.Editor;
/** Copies and pastes images to the clipboard. Java 1.4 or later is
required to copy to or paste from the system clipboard. */
public class Clipboard implements PlugIn, Transferable {
static java.awt.datatransfer.Clipboard clipboard;
public void run(String arg) {
if (IJ.altKeyDown()) {
if (arg.equals("copy"))
arg = "scopy";
else if (arg.equals("paste"))
arg = "spaste";
}
if (arg.equals("copy"))
copy(false);
else if (arg.equals("paste"))
paste();
else if (arg.equals("cut"))
copy(true);
else if (arg.equals("scopy"))
copyToSystem();
else if (arg.equals("showsys"))
showSystemClipboard();
else if (arg.equals("show"))
showInternalClipboard();
}
void copy(boolean cut) {
ImagePlus imp = WindowManager.getCurrentImage();
if (imp!=null)
imp.copy(cut);
else
IJ.noImage();
}
void paste() {
if (ImagePlus.getClipboard()==null) {
if (IJ.isJava14())
showSystemClipboard();
else
IJ.noImage();
} else {
ImagePlus imp = WindowManager.getCurrentImage();
if (imp!=null)
imp.paste();
else
showInternalClipboard ();
}
}
boolean setup() {
if (!IJ.isJava14()) {
IJ.error("Clipboard", "Java 1.4 or later required");
return false;
}
if (clipboard==null)
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
return true;
}
void copyToSystem() {
if (!setup()) return;
try {
clipboard.setContents(this, null);
} catch (Throwable t) {}
}
void showSystemClipboard() {
if (!setup()) return;
IJ.showStatus("Opening system clipboard...");
try {
Transferable transferable = clipboard.getContents(null);
boolean imageSupported = transferable.isDataFlavorSupported(DataFlavor.imageFlavor);
boolean textSupported = transferable.isDataFlavorSupported(DataFlavor.stringFlavor);
if (!imageSupported && IJ.isMacOSX() && displayMacImage(transferable))
return;
if (imageSupported) {
Image img = (Image)transferable.getTransferData(DataFlavor.imageFlavor);
if (img==null) {
IJ.error("Unable to convert image on system clipboard");
IJ.showStatus("");
return;
}
int width = img.getWidth(null);
int height = img.getHeight(null);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
WindowManager.checkForDuplicateName = true;
new ImagePlus("Clipboard", bi).show();
} else if (textSupported) {
String text = (String)transferable.getTransferData(DataFlavor.stringFlavor);
Editor ed = new Editor();
ed.setSize(600, 300);
ed.create("Clipboard", text);
IJ.showStatus("");
} else
IJ.error("Unable to find an image on the system clipboard");
} catch (Throwable t) {
IJ.showStatus(""+t);
}
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (!isDataFlavorSupported(flavor))
throw new UnsupportedFlavorException(flavor);
ImagePlus imp = WindowManager.getCurrentImage();
if ( imp != null) {
ImageProcessor ip = imp.getProcessor();
ip = ip.crop();
int w = ip.getWidth();
int h = ip.getHeight();
IJ.showStatus(w+"x"+h+ " image copied to system clipboard");
Image img = IJ.getInstance().createImage(w, h);
Graphics g = img.getGraphics();
g.drawImage(ip.createImage(), 0, 0, null);
g.dispose();
return img;
} else {
//IJ.noImage();
return null;
}
}
void showInternalClipboard() {
ImagePlus clipboard = ImagePlus.getClipboard();
if (clipboard!=null) {
ImageProcessor ip = clipboard.getProcessor();
ImagePlus imp2 = new ImagePlus("Clipboard", ip.duplicate());
Roi roi = clipboard.getRoi();
imp2.killRoi();
if (roi!=null && roi.isArea() && roi.getType()!=Roi.RECTANGLE) {
roi = (Roi)roi.clone();
roi.setLocation(0, 0);
imp2.setRoi(roi);
WindowManager.setTempCurrentImage(imp2);
IJ.run("Clear Outside");
imp2.killRoi();
}
WindowManager.checkForDuplicateName = true;
imp2.show();
} else
IJ.error("The internal clipboard is empty.");
}
boolean displayMacImage(Transferable t) {
Image img = getMacImage(t);
if (img!=null) {
WindowManager.checkForDuplicateName = true;
new ImagePlus("Clipboard", img).show();
}
return img!=null;
}
// Mac OS X's data transfer handling is horribly broken. We sometimes
// need to use the "image/x-pict" MIME type and then Quicktime
// for Java in order to get the image data.
Image getMacImage(Transferable t) {
if (!isQTJavaInstalled())
return null;
Image img = null;
DataFlavor[] d = t.getTransferDataFlavors();
if (d==null || d.length==0)
return null;
try {
Object is = t.getTransferData(d[0]);
if (is==null || !(is instanceof InputStream))
return null;
img = getImageFromPictStream((InputStream)is);
} catch (Exception e) {}
return img;
}
// Converts a PICT to an AWT image using QuickTime for Java.
// This code was contributed by Gord Peters.
Image getImageFromPictStream(InputStream is) {
try {
ByteArrayOutputStream baos= new ByteArrayOutputStream();
// We need to strip the header from the data because a PICT file
// has a 512 byte header and then the data, but in our case we only
// need the data. --GP
byte[] header= new byte[512];
byte[] buf= new byte[4096];
int retval= 0, size= 0;
baos.write(header, 0, 512);
while ( (retval= is.read(buf, 0, 4096)) > 0)
baos.write(buf, 0, retval);
baos.close();
size = baos.size();
//IJ.log("size: "+size); IJ.wait(2000);
if (size<=0)
return null;
byte[] imgBytes= baos.toByteArray();
// Again with the uglyness. Here we need to use the Quicktime
// for Java code in order to create an Image object from
// the PICT data we received on the clipboard. However, in
// order to get this to compile on other platforms, we use
// the Java reflection API.
//
// For reference, here is the equivalent code without
// reflection:
//
//
// if (QTSession.isInitialized() == false) {
// QTSession.open();
// }
// QTHandle handle= new QTHandle(imgBytes);
// GraphicsImporter gi=
// new GraphicsImporter(QTUtils.toOSType("PICT"));
// gi.setDataHandle(handle);
// QDRect qdRect= gi.getNaturalBounds();
// GraphicsImporterDrawer gid= new GraphicsImporterDrawer(gi);
// QTImageProducer qip= new QTImageProducer(gid,
// new Dimension(qdRect.getWidth(),
// qdRect.getHeight()));
// return(Toolkit.getDefaultToolkit().createImage(qip));
//
// --GP
//IJ.log("quicktime.QTSession");
Class c = Class.forName("quicktime.QTSession");
Method m = c.getMethod("isInitialized", null);
Boolean b= (Boolean)m.invoke(null, null);
if (b.booleanValue() == false) {
m= c.getMethod("open", null);
m.invoke(null, null);
}
c= Class.forName("quicktime.util.QTHandle");
Constructor con = c.getConstructor(new Class[] {imgBytes.getClass() });
Object handle= con.newInstance(new Object[] { imgBytes });
String s= new String("PICT");
c = Class.forName("quicktime.util.QTUtils");
m = c.getMethod("toOSType", new Class[] { s.getClass() });
Integer type= (Integer)m.invoke(null, new Object[] { s });
c = Class.forName("quicktime.std.image.GraphicsImporter");
con = c.getConstructor(new Class[] { type.TYPE });
Object importer= con.newInstance(new Object[] { type });
m = c.getMethod("setDataHandle",
new Class[] { Class.forName("quicktime.util." + "QTHandleRef") });
m.invoke(importer, new Object[] { handle });
m = c.getMethod("getNaturalBounds", null);
Object rect= m.invoke(importer, null);
c = Class.forName("quicktime.app.view.GraphicsImporterDrawer");
con = c.getConstructor(new Class[] { importer.getClass() });
Object iDrawer = con.newInstance(new Object[] { importer });
m = rect.getClass().getMethod("getWidth", null);
Integer width= (Integer)m.invoke(rect, null);
m = rect.getClass().getMethod("getHeight", null);
Integer height= (Integer)m.invoke(rect, null);
Dimension d= new Dimension(width.intValue(), height.intValue());
c = Class.forName("quicktime.app.view.QTImageProducer");
con = c.getConstructor(new Class[] { iDrawer.getClass(), d.getClass() });
Object producer= con.newInstance(new Object[] { iDrawer, d });
if (producer instanceof ImageProducer)
return(Toolkit.getDefaultToolkit().createImage((ImageProducer)producer));
} catch (Exception e) {IJ.showStatus("QuickTime for java error");}
return null;
}
// Retuns true if QuickTime for Java is installed.
// This code was contributed by Gord Peters.
boolean isQTJavaInstalled() {
boolean isInstalled = false;
try {
Class c= Class.forName("quicktime.QTSession");
isInstalled = true;
} catch (Exception e) {}
return isInstalled;
}
}
|
/*
* Copyright 2019 dc-square GmbH
*
* 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.hivemq.persistence;
import com.google.inject.Inject;
import com.hivemq.extension.sdk.api.annotations.NotNull;
import com.hivemq.common.shutdown.ShutdownHooks;
import javax.annotation.PostConstruct;
/**
* @author Lukas Brandl
*/
public class PersistenceShutdownHookInstaller {
private final @NotNull ShutdownHooks shutdownHooks;
private final @NotNull PersistenceShutdownHook persistenceShutdownHook;
private final @NotNull PersistenceStartup persistenceStartup;
@Inject
public PersistenceShutdownHookInstaller(
final @NotNull ShutdownHooks shutdownHooks, final @NotNull PersistenceShutdownHook persistenceShutdownHook,
final @NotNull PersistenceStartup persistenceStartup) {
this.shutdownHooks = shutdownHooks;
this.persistenceShutdownHook = persistenceShutdownHook;
this.persistenceStartup = persistenceStartup;
}
@PostConstruct
public void postConstruct() {
shutdownHooks.remove(persistenceStartup);
shutdownHooks.add(persistenceShutdownHook);
}
}
|
/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
*/
package co.zhenxi.tools.service.mapper;
import co.zhenxi.common.mapper.CoreMapper;
import co.zhenxi.tools.domain.EmailConfig;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
* @author hupeng
* @date 2020-05-13
*/
@Repository
@Mapper
public interface EmailConfigMapper extends CoreMapper<EmailConfig> {
}
|
/*
* Copyright 2010 Harald Wellmann
*
* 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.ops4j.pax.exam.sample4.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Author {
@Id
@GeneratedValue
@Column(name = "author_id")
private int id;
private String firstName;
private String lastName;
@OneToMany(mappedBy = "author")
private Set<Book> books = new HashSet<Book>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
// CHECKSTYLE:OFF : generated code
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Author other = (Author) obj;
if (id != other.id)
return false;
return true;
}
// CHECKSTYLE:ON
}
|
package io.apptik.rhub;
import com.jakewharton.rxrelay.*;
import io.apptik.roxy.Roxy;
import io.apptik.roxy.RxJava1Proxies;
import rx.Observable;
import rx.subjects.*;
public enum RxJava1ProxyType implements RHub.ProxyType<Roxy<Observable>> {
/**
* Proxy based on {@link BehaviorSubject}
*/
BehaviorSubjectProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.behaviorSubjectProxy();
}
},
/**
* Proxy based on {@link PublishSubject}
*/
PublishSubjectProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.publishSubjectProxy();
}
},
/**
* Proxy based on {@link ReplaySubject}
*/
ReplaySubjectProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.replaySubjectProxy();
}
},
/**
* Proxy based on {@link BehaviorRelay}
*/
BehaviorRelayProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.behaviorRelayProxy();
}
},
/**
* Proxy based on {@link PublishRelay}
*/
PublishRelayProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.publishRelayProxy();
}
},
/**
* Proxy based on {@link ReplayRelay}
*/
ReplayRelayProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.replayRelayProxy();
}
},
/**
* Synchronized Proxy based on {@link BehaviorSubject}
*/
SerializedBehaviorSubjectProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.serializedBehaviorSubjectProxy();
}
},
/**
* Synchronized Proxy based on {@link PublishSubject}
*/
SerializedPublishSubjectProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.serializedPublishSubjectProxy();
}
},
/**
* Synchronized Proxy based on {@link ReplaySubject}
*/
SerializedReplaySubjectProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.serializedReplaySubjectProxy();
}
},
/**
* Synchronized Proxy based on {@link BehaviorRelay}
*/
SerializedBehaviorRelayProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.serializedBehaviorRelayProxy();
}
},
/**
* Synchronized Proxy based on {@link PublishRelay}
*/
SerializedPublishRelayProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.serializedPublishRelayProxy();
}
},
/**
* Synchronized Proxy based on {@link ReplayRelay}
*/
SerializedReplayRelayProxy {
@Override
public Roxy<Observable> getRoxy() {
return RxJava1Proxies.serializedReplayRelayProxy();
}
}
}
|
/*
* 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.common.xcontent.json;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.FastStringReader;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentGenerator;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Set;
/**
* A JSON based content implementation using Jackson.
*/
public class JsonXContent implements XContent {
public static XContentBuilder contentBuilder() throws IOException {
return XContentBuilder.builder(jsonXContent);
}
private static final JsonFactory jsonFactory;
public static final JsonXContent jsonXContent;
static {
jsonFactory = new JsonFactory();
jsonFactory.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
jsonFactory.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
jsonFactory.configure(JsonFactory.Feature.FAIL_ON_SYMBOL_HASH_OVERFLOW, false); // this trips on many mappings now...
// Do not automatically close unclosed objects/arrays in com.fasterxml.jackson.core.json.UTF8JsonGenerator#close() method
jsonFactory.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, false);
jsonXContent = new JsonXContent();
}
private JsonXContent() {
}
@Override
public XContentType type() {
return XContentType.JSON;
}
@Override
public byte streamSeparator() {
return '\n';
}
@Override
public XContentGenerator createGenerator(OutputStream os, Set<String> includes, Set<String> excludes) throws IOException {
return new JsonXContentGenerator(jsonFactory.createGenerator(os, JsonEncoding.UTF8), os, includes, excludes);
}
@Override
public XContentParser createParser(String content) throws IOException {
return new JsonXContentParser(jsonFactory.createParser(new FastStringReader(content)));
}
@Override
public XContentParser createParser(InputStream is) throws IOException {
return new JsonXContentParser(jsonFactory.createParser(is));
}
@Override
public XContentParser createParser(byte[] data) throws IOException {
return new JsonXContentParser(jsonFactory.createParser(data));
}
@Override
public XContentParser createParser(byte[] data, int offset, int length) throws IOException {
return new JsonXContentParser(jsonFactory.createParser(data, offset, length));
}
@Override
public XContentParser createParser(BytesReference bytes) throws IOException {
return createParser(bytes.streamInput());
}
@Override
public XContentParser createParser(Reader reader) throws IOException {
return new JsonXContentParser(jsonFactory.createParser(reader));
}
}
|
package com.xinshang.modular.biz.dao;
import com.xinshang.modular.biz.model.SpecsAttribute;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* 规格属性名 Mapper 接口
* </p>
*
* @author zhangjiajia
* @since 2019-11-25
*/
public interface SpecsAttributeMapper extends BaseMapper<SpecsAttribute> {
}
|
package com.backbase.game;
import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
import java.util.Map;
@Getter
@Setter
public class Kalah {
private Integer gameNumber;
private Map<Integer, Integer> status;
public Kalah() {
Map<Integer, Integer> status = new HashMap<>();
for (int i = 1; i <= 14; i++) {
status.put(i, 6);
}
status.put(7, 0);
status.put(14, 0);
setStatus(status);
}
public Kalah playMove(Integer pit) throws IllegalKalahMoveException, FinishedGameException {
validateMoveInsideBoundaries(pit);
validateMoveNotInHouse(pit);
validateMoveInFinishedGame();
sow(pit);
return this;
}
public boolean isGameFinished() {
return noSeedsOnPlayerOneSide() || noSeedsOnPlayerTwoSide();
}
private void validateMoveInsideBoundaries(Integer pit) throws IllegalKalahMoveException {
if(pit < 1 || pit > 14) {
throw new IllegalKalahMoveException();
}
}
private void validateMoveNotInHouse(Integer pit) throws IllegalKalahMoveException {
if (Integer.valueOf(7).equals(pit) || Integer.valueOf(14).equals(pit)) {
throw new IllegalKalahMoveException();
}
}
private void validateMoveInFinishedGame() throws FinishedGameException {
if(isGameFinished()) {
throw new FinishedGameException();
}
}
private void sow(Integer pit) {
if(getStatus().get(pit) != 0) {
Integer houseToSkip = getHouseToSkipFromOtherPlayer(pit);
Integer seedsOnFinalPit;
do {
pit = sowSeedsFromPit(pit, houseToSkip);
seedsOnFinalPit = getStatus().get(pit);
} while (seedsOnFinalPit != 1 && pit != 7 && pit != 14);
stealPitWhenLastPitIsOwned(pit, houseToSkip);
}
}
private Integer sowSeedsFromPit(Integer pit, Integer houseToSkip) {
Map<Integer, Integer> status = getStatus();
Integer seedsToMove = getSeedsOnPit(pit);
clearPit(pit);
while (seedsToMove != 0) {
pit = seedNextPit(pit, houseToSkip);
seedsToMove--;
}
setStatus(status);
return pit;
}
private Integer getHouseToSkipFromOtherPlayer(Integer pit) {
if (pit > 7) {
return 7;
}
return 14;
}
private Integer getSeedsOnPit(Integer pit) {
return getStatus().get(pit);
}
private void clearPit(Integer pit) {
getStatus().put(pit, 0);
}
private Integer seedNextPit(Integer pit, Integer houseToSkip) {
Map<Integer, Integer> status = getStatus();
pit = getNextNotHousePit(pit, houseToSkip);
status.put(pit, status.get(pit) + 1);
setStatus(status);
return pit;
}
private Integer getNextNotHousePit(Integer pit, Integer houseToSkip) {
pit = getNextPit(pit);
if (pit == houseToSkip) {
pit = getNextPit(pit);
}
return pit;
}
public Integer getNextPit(Integer pit) {
pit++;
if (pit == 15) {
pit = 1;
}
return pit;
}
private void stealPitWhenLastPitIsOwned(Integer pit, Integer houseToSkip) {
if (isLastPitOwned(pit, houseToSkip)) {
stealFromOppositePit(pit, houseToSkip);
}
}
private boolean isLastPitOwned(Integer pit, Integer houseToSkip) {
if (houseToSkip == 14) {
return pit < 7;
}
return pit > 7 && pit < 14;
}
private void stealFromOppositePit(Integer pit, Integer houseToSkip) {
Integer oppositePit = getOppositePit(pit, houseToSkip);
Integer seedsOnOppositePit = getSeedsOnPit(oppositePit);
Integer ownHouse = getOwnHouse(houseToSkip);
clearPit(pit);
clearPit(oppositePit);
Map<Integer, Integer> status = getStatus();
status.put(ownHouse, status.get(ownHouse) + seedsOnOppositePit + 1);
setStatus(status);
}
private Integer getOppositePit(Integer pit, Integer houseToSkip) {
if (houseToSkip == 7) {
return pit - 7;
}
return pit + 7;
}
private Integer getOwnHouse(Integer houseToSkip) {
if (houseToSkip == 7) {
return 14;
}
return 7;
}
private boolean noSeedsOnPlayerOneSide() {
return noSeedsOnPlayerSide(1, 7);
}
private boolean noSeedsOnPlayerTwoSide() {
return noSeedsOnPlayerSide(8, 14);
}
private boolean noSeedsOnPlayerSide(int start, int end) {
Integer seedsOnPlayerSide = 0;
for (int i = start; i <= end; i++) {
seedsOnPlayerSide += getStatus().get(i);
}
return seedsOnPlayerSide == 0;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.portfolio.savings.domain.interest;
import java.math.BigDecimal;
import java.math.MathContext;
import org.apache.fineract.infrastructure.core.domain.LocalDateInterval;
import org.apache.fineract.organisation.monetary.domain.Money;
import org.apache.fineract.organisation.monetary.domain.MoneyHelper;
import org.joda.time.LocalDate;
public class EndOfDayBalance {
private final LocalDate date;
private final Money openingBalance;
private final Money endOfDayBalance;
private final int numberOfDays;
public static EndOfDayBalance from(final LocalDate date, final Money openingBalance, final Money endOfDayBalance,
final int numberOfDays) {
return new EndOfDayBalance(date, openingBalance, endOfDayBalance, numberOfDays);
}
public EndOfDayBalance(final LocalDate date, final Money openingBalance, final Money endOfDayBalance, final int numberOfDays) {
this.date = date;
this.openingBalance = openingBalance;
this.endOfDayBalance = endOfDayBalance;
this.numberOfDays = numberOfDays;
}
public LocalDate date() {
return this.date;
}
public Money closingBalance() {
return this.endOfDayBalance;
}
public BigDecimal cumulativeBalance(final BigDecimal interestToCompound) {
final BigDecimal daysAsBigDecimal = BigDecimal.valueOf(this.numberOfDays);
final BigDecimal realBalanceForInterestCalculation = this.endOfDayBalance.getAmount().add(interestToCompound);
return realBalanceForInterestCalculation.multiply(daysAsBigDecimal, MathContext.DECIMAL64).setScale(9,
MoneyHelper.getRoundingMode());
}
public BigDecimal calculateInterestOnBalance(final BigDecimal interestToCompound, final BigDecimal interestRateAsFraction,
final long daysInYear, final BigDecimal minBalanceForInterestCalculation,
final BigDecimal overdraftInterestRateAsFraction, final BigDecimal minOverdraftForInterestCalculation) {
BigDecimal interest = BigDecimal.ZERO.setScale(9, MoneyHelper.getRoundingMode());
final BigDecimal realBalanceForInterestCalculation = this.endOfDayBalance.getAmount().add(interestToCompound);
if(realBalanceForInterestCalculation.compareTo(BigDecimal.ZERO) >= 0){
if (realBalanceForInterestCalculation.compareTo(minBalanceForInterestCalculation) >= 0) {
final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64);
final BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64);
final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(this.numberOfDays), MathContext.DECIMAL64);
interest = realBalanceForInterestCalculation.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9,
MoneyHelper.getRoundingMode());
}
} else {
if (realBalanceForInterestCalculation.compareTo(minOverdraftForInterestCalculation.negate()) < 0) {
final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64);
final BigDecimal dailyInterestRate = overdraftInterestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64);
final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(this.numberOfDays), MathContext.DECIMAL64);
interest = realBalanceForInterestCalculation.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9,
MoneyHelper.getRoundingMode());
}
}
return interest;
}
/**
* Future Value (FV) = PV x (1+r)^n
*
* Interest = FV - PV PV = Principal or the Account Balance r = rate per
* compounding period (so for daily, r = nominalInterestRateAsFraction x
* 1/365 n = number of periods rate is compounded
*/
public BigDecimal calculateInterestOnBalanceAndInterest(final BigDecimal interestToCompound, final BigDecimal interestRateAsFraction,
final long daysInYear, final BigDecimal minBalanceForInterestCalculation, final BigDecimal overdraftInterestRateAsFraction,
final BigDecimal minOverdraftForInterestCalculation) {
final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64);
final BigDecimal presentValue = this.endOfDayBalance.getAmount().add(interestToCompound);
BigDecimal futureValue = presentValue.setScale(9, MoneyHelper.getRoundingMode());
if(presentValue.compareTo(BigDecimal.ZERO) >= 0){
if (presentValue.compareTo(minBalanceForInterestCalculation) >= 0) {
final BigDecimal r = interestRateAsFraction.multiply(multiplicand);
final BigDecimal interestRateForCompoundingPeriodPlusOne = BigDecimal.ONE.add(r);
final double interestRateForCompoundingPeriodPowered = Math.pow(interestRateForCompoundingPeriodPlusOne.doubleValue(),
Integer.valueOf(this.numberOfDays).doubleValue());
futureValue = presentValue.multiply(BigDecimal.valueOf(interestRateForCompoundingPeriodPowered), MathContext.DECIMAL64)
.setScale(9, MoneyHelper.getRoundingMode());
}
}else{
if (presentValue.compareTo(minOverdraftForInterestCalculation.negate()) < 0) {
final BigDecimal r = overdraftInterestRateAsFraction.multiply(multiplicand);
final BigDecimal interestRateForCompoundingPeriodPlusOne = BigDecimal.ONE.add(r);
final double interestRateForCompoundingPeriodPowered = Math.pow(interestRateForCompoundingPeriodPlusOne.doubleValue(),
Integer.valueOf(this.numberOfDays).doubleValue());
futureValue = presentValue.multiply(BigDecimal.valueOf(interestRateForCompoundingPeriodPowered), MathContext.DECIMAL64)
.setScale(9, MoneyHelper.getRoundingMode());
}
}
return futureValue.subtract(presentValue);
}
/**
* @param compoundingPeriodInterval
* @param upToInterestCalculationDate
* : For calculating maturity details in advance
* upToInterestCalculationDate will be maturity date else it will
* be DateUtils.getLocalDateOfTenant().
* @return
*/
public EndOfDayBalance upTo(final LocalDateInterval compoundingPeriodInterval, final LocalDate upToInterestCalculationDate) {
Money startingBalance = this.openingBalance;
LocalDate balanceStartDate = this.date;
LocalDate oldBalanceEndDate = this.date.plusDays(this.numberOfDays - 1);
int daysOfBalance = this.numberOfDays;
if (this.date.isBefore(compoundingPeriodInterval.startDate())) {
balanceStartDate = compoundingPeriodInterval.startDate();
startingBalance = this.endOfDayBalance;
final LocalDateInterval balancePeriodInterval = LocalDateInterval.create(balanceStartDate, oldBalanceEndDate);
daysOfBalance = balancePeriodInterval.daysInPeriodInclusiveOfEndDate();
}
LocalDate balanceEndDate = balanceStartDate.plusDays(daysOfBalance - 1);
if (balanceEndDate.isAfter(compoundingPeriodInterval.endDate())) {
balanceEndDate = compoundingPeriodInterval.endDate();
final LocalDateInterval balancePeriodInterval = LocalDateInterval.create(balanceStartDate, balanceEndDate);
daysOfBalance = balancePeriodInterval.daysInPeriodInclusiveOfEndDate();
}
if (balanceEndDate.isAfter(upToInterestCalculationDate)) {
balanceEndDate = upToInterestCalculationDate;
final LocalDateInterval balancePeriodInterval = LocalDateInterval.create(balanceStartDate, balanceEndDate);
daysOfBalance = balancePeriodInterval.daysInPeriodInclusiveOfEndDate();
}
return new EndOfDayBalance(balanceStartDate, startingBalance, this.endOfDayBalance, daysOfBalance);
}
public boolean contains(final LocalDateInterval compoundingPeriodInterval) {
final LocalDate balanceUpToDate = this.date.plusDays(this.numberOfDays - 1);
final LocalDateInterval balanceInterval = LocalDateInterval.create(this.date, balanceUpToDate);
return balanceInterval.containsPortionOf(compoundingPeriodInterval);
}
public Integer getNumberOfDays() {
return Integer.valueOf(this.numberOfDays);
}
}
|
/*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.config;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class ArtifactPropertyConfigTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File workspace;
@Before
public void setUp() throws Exception {
this.workspace = temporaryFolder.newFolder("workspace");
}
@Test
public void shouldAddErrorToErrorCollection() throws IOException {
String multipleMatchXPATH = "//artifact/@src";
ArtifactPropertyConfig generator = new ArtifactPropertyConfig("test_property", createSrcFile().getName(), multipleMatchXPATH);
generator.addError("src", "Source invalid");
assertThat(generator.errors().on("src"), is("Source invalid"));
}
@Test
public void shouldValidateThatNameIsMandatory() {
ArtifactPropertyConfig generator = new ArtifactPropertyConfig(null, "props.xml", "//some_xpath");
generator.validateTree(null);
assertThat(generator.errors().on(ArtifactPropertyConfig.NAME), containsString("Invalid property name 'null'."));
}
private File createSrcFile() throws IOException {
String content = "<buildplans>\n"
+ " <buildplan name=\"test\">\n"
+ " <artifacts>\n"
+ " <artifact src=\"target\\connectfour.jar\" dest=\"dist\\jars\" />\n"
+ " <artifact src=\"target\\test-results\" dest=\"testoutput\" type=\"junit\" />\n"
+ " <artifact src=\"build.xml\" />\n"
+ " </artifacts>\n"
+ " <tasks>\n"
+ " <ant workingdir=\"dev\" target=\"all\" />\n"
+ " </tasks>\n"
+ " </buildplan>\n"
+ " </buildplans>";
File file = new File(workspace, "xmlfile");
FileUtils.writeStringToFile(file, content, "UTF-8");
return file;
}
}
|
/**
* 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.cxf.cdi;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.enterprise.inject.spi.AnnotatedConstructor;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Inject;
import javax.ws.rs.core.Context;
import static java.util.stream.Collectors.toSet;
final class DelegateContextAnnotatedType<X> implements AnnotatedType<X> {
private static final Inject INJECT = new InjectLiteral();
private static final ContextResolved CONTEXT_RESOLVED = ContextResolved.LITERAL;
private final AnnotatedType<X> original;
private final Set<AnnotatedField<? super X>> replacedFields;
DelegateContextAnnotatedType(AnnotatedType<X> original) {
this.original = original;
this.replacedFields = replaceFields(original);
}
private Set<AnnotatedField<? super X>> replaceFields(AnnotatedType<? super X> delegate) {
return delegate.getFields().stream().map(this::wrap).collect(toSet());
}
Set<Type> getContextFieldTypes() {
return replacedFields.stream()
.filter(f -> f.isAnnotationPresent(Context.class) || f.isAnnotationPresent(ContextResolved.class))
.map(f -> f.getJavaMember().getAnnotatedType().getType())
.collect(toSet());
}
@Override
public Class<X> getJavaClass() {
return original.getJavaClass();
}
@Override
public Set<AnnotatedConstructor<X>> getConstructors() {
return original.getConstructors();
}
@Override
public Set<AnnotatedMethod<? super X>> getMethods() {
return original.getMethods();
}
@Override
public Set<AnnotatedField<? super X>> getFields() {
return replacedFields;
}
@Override
public Type getBaseType() {
return original.getBaseType();
}
@Override
public Set<Type> getTypeClosure() {
return original.getTypeClosure();
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
return original.getAnnotation(annotationType);
}
@Override
public Set<Annotation> getAnnotations() {
return original.getAnnotations();
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
return original.isAnnotationPresent(annotationType);
}
private AnnotatedField<? super X> wrap(AnnotatedField<? super X> af) {
if (af.isAnnotationPresent(Context.class)) {
return new DelegateAnnotatedField<>(af);
} else {
return af;
}
}
private final class DelegateAnnotatedField<Y> implements AnnotatedField<Y> {
private final AnnotatedField<Y> original;
private final Set<Annotation> annotationSet;
private DelegateAnnotatedField(AnnotatedField<Y> delegate) {
this.original = delegate;
this.annotationSet = processAnnotations(delegate.getAnnotations());
}
private Set<Annotation> processAnnotations(Set<Annotation> annotations) {
Set<Annotation> resultAnnotations = new LinkedHashSet<>();
for (Annotation a : annotations) {
if (a instanceof Context) {
resultAnnotations.add(INJECT);
resultAnnotations.add(CONTEXT_RESOLVED);
}
resultAnnotations.add(a);
}
return Collections.unmodifiableSet(resultAnnotations);
}
@Override
public Field getJavaMember() {
return original.getJavaMember();
}
@Override
public boolean isStatic() {
return original.isStatic();
}
@Override
public AnnotatedType<Y> getDeclaringType() {
return original.getDeclaringType();
}
@Override
public Type getBaseType() {
return original.getBaseType();
}
@Override
public Set<Type> getTypeClosure() {
return original.getTypeClosure();
}
@Override
@SuppressWarnings("unchecked")
public <T extends Annotation> T getAnnotation(Class<T> annotationType) {
for (Annotation a : annotationSet) {
if (annotationType == a.annotationType()) {
return (T)a;
}
}
return null;
}
@Override
public Set<Annotation> getAnnotations() {
return annotationSet;
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
return getAnnotation(annotationType) != null;
}
}
private static final class InjectLiteral extends AnnotationLiteral<Inject> implements Inject {
private static final long serialVersionUID = 1L;
}
}
|
/*
* Copyright 2014 Orient Technologies.
*
* 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.orientechnologies.lucene.manager;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import com.orientechnologies.lucene.collections.OFullTextCompositeKey;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.command.traverse.OTraverse;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.codecs.TermStats;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.Version;
import com.orientechnologies.lucene.OLuceneIndexType;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.index.OCompositeKey;
import com.orientechnologies.orient.core.index.OIndexCursor;
import com.orientechnologies.orient.core.index.OIndexException;
import com.orientechnologies.orient.core.index.OIndexKeyCursor;
import com.orientechnologies.orient.core.record.impl.ODocument;
public class OLuceneFullTextIndexManager extends OLuceneIndexManagerAbstract {
public OLuceneFullTextIndexManager() {
}
@Override
public IndexWriter createIndexWriter(Directory directory, ODocument metadata) throws IOException {
Analyzer analyzer = getAnalyzer(metadata);
Version version = getVersion(metadata);
IndexWriterConfig iwc = new IndexWriterConfig(version, analyzer);
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
return new IndexWriter(directory, iwc);
}
@Override
public IndexWriter openIndexWriter(Directory directory, ODocument metadata) throws IOException {
Analyzer analyzer = getAnalyzer(metadata);
Version version = getVersion(metadata);
IndexWriterConfig iwc = new IndexWriterConfig(version, analyzer);
iwc.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
return new IndexWriter(directory, iwc);
}
@Override
public void init() {
}
@Override
public void deleteWithoutLoad(String indexName) {
}
@Override
public boolean contains(Object key) {
return false;
}
@Override
public boolean remove(Object key) {
return false;
}
@Override
public ORID getIdentity() {
return null;
}
@Override
public Object get(Object key) {
Query q = null;
try {
q = OLuceneIndexType.createFullQuery(index, (OCompositeKey) key, mgrWriter.getIndexWriter().getAnalyzer(),
getVersion(metadata));
OCommandContext context = null;
if (key instanceof OFullTextCompositeKey) {
context = ((OFullTextCompositeKey) key).getContext();
}
return getResults(q, context);
} catch (ParseException e) {
throw new OIndexException("Error parsing lucene query ", e);
}
}
@Override
public void put(Object key, Object value) {
Set<OIdentifiable> container = (Set<OIdentifiable>) value;
for (OIdentifiable oIdentifiable : container) {
Document doc = new Document();
doc.add(OLuceneIndexType.createField(RID, oIdentifiable, oIdentifiable.getIdentity().toString(), Field.Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS));
int i = 0;
for (String f : index.getFields()) {
Object val = null;
if (key instanceof OCompositeKey) {
val = ((OCompositeKey) key).getKeys().get(i);
i++;
} else {
val = key;
}
if (val != null)
doc.add(OLuceneIndexType.createField(f, oIdentifiable, val, Field.Store.NO, Field.Index.ANALYZED));
}
addDocument(doc);
}
}
private Set<OIdentifiable> getResults(Query query, OCommandContext context) {
Set<OIdentifiable> results = new LinkedHashSet<OIdentifiable>();
try {
IndexSearcher searcher = getSearcher();
Map<String, Float> scores = new HashMap<String, Float>();
TopDocs docs = searcher.search(query, Integer.MAX_VALUE);
ScoreDoc[] hits = docs.scoreDocs;
for (ScoreDoc score : hits) {
Document ret = searcher.doc(score.doc);
String rId = ret.get(RID);
results.add(new ORecordId(rId));
scores.put(rId, score.score);
}
if (context != null) {
context.setVariable("$luceneScore", scores);
}
} catch (IOException e) {
throw new OIndexException("Error reading from Lucene index", e);
}
return results;
}
@Override
public Object getFirstKey() {
return null;
}
@Override
public Object getLastKey() {
return null;
}
@Override
public OIndexCursor iterateEntriesBetween(Object rangeFrom, boolean fromInclusive, Object rangeTo, boolean toInclusive,
boolean ascSortOrder, ValuesTransformer transformer) {
return null;
}
@Override
public OIndexCursor iterateEntriesMajor(Object fromKey, boolean isInclusive, boolean ascSortOrder, ValuesTransformer transformer) {
return null;
}
@Override
public OIndexCursor iterateEntriesMinor(Object toKey, boolean isInclusive, boolean ascSortOrder, ValuesTransformer transformer) {
return null;
}
@Override
public OIndexCursor cursor(ValuesTransformer valuesTransformer) {
return null;
}
@Override
public OIndexKeyCursor keyCursor() {
return new OIndexKeyCursor() {
@Override
public Object next(int prefetchSize) {
return null;
}
};
}
@Override
public boolean hasRangeQuerySupport() {
return false;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.functions.api.examples;
import org.apache.pulsar.functions.api.Context;
import org.apache.pulsar.functions.api.Function;
/**
* This Function simulates a pulsar function encountering failing on a particular message.
*/
public class ConsistentlyFailingFunction implements Function<String, String> {
@Override
public String process(String input, Context context) {
if (input.equals("FAIL")) {
throw new RuntimeException("Failed");
} else {
return "SUCCESS";
}
}
}
|
package lsieun.cert.x509;
import lsieun.cert.asn1.ASN1Converter;
import lsieun.cert.asn1.ASN1Struct;
import lsieun.utils.DateUtils;
import java.util.Date;
import java.util.List;
public class ValidityPeriod {
public final Date notBefore;
public final Date notAfter;
public ValidityPeriod(Date notBefore, Date notAfter) {
this.notBefore = notBefore;
this.notAfter = notAfter;
}
@Override
public String toString() {
return "ValidityPeriod {" +
"notBefore='" + DateUtils.format(notBefore) + "'" +
", notAfter='" + DateUtils.format(notAfter) + "'" +
'}';
}
public static ValidityPeriod parse(ASN1Struct struct) {
List<ASN1Struct> children = struct.children;
ASN1Struct asn1_not_before = children.get(0);
ASN1Struct asn1_not_after = children.get(1);
Date notBefore = ASN1Converter.toDate(asn1_not_before);
Date notAfter = ASN1Converter.toDate(asn1_not_after);
return new ValidityPeriod(notBefore, notAfter);
}
}
|
/*
* Copyright 2019. 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 ms.dew.devops.kernel.plugin.appkind.frontend.node_non_natvie;
import ms.dew.devops.kernel.config.FinalProjectConfig;
import ms.dew.devops.kernel.flow.BasicFlow;
import ms.dew.devops.kernel.flow.NoNeedProcessFLow;
import ms.dew.devops.kernel.flow.log.DefaultLogFlow;
import ms.dew.devops.kernel.flow.refresh.DefaultRefreshFlow;
import ms.dew.devops.kernel.flow.release.KubeReleaseFlow;
import ms.dew.devops.kernel.flow.rollback.DefaultRollbackFlow;
import ms.dew.devops.kernel.flow.scale.DefaultScaleFlow;
import ms.dew.devops.kernel.flow.unrelease.DefaultUnReleaseFlow;
import ms.dew.devops.kernel.plugin.appkind.AppKindPlugin;
import java.util.HashMap;
import java.util.Map;
/**
* Node frontend app kind plugin.
*
* @author gudaoxuri
*/
public class FrontendNonNativeNodeAppKindPlugin implements AppKindPlugin {
@Override
public String getName() {
return "Non-Native Node Frontend";
}
@Override
public void customConfig(FinalProjectConfig projectConfig) {
if (projectConfig.getApp().getPort() == null) {
projectConfig.getApp().setPort(80);
}
projectConfig.getApp().setHealthCheckEnabled(false);
projectConfig.getApp().setTraceLogEnabled(false);
projectConfig.getApp().setMetricsEnabled(false);
projectConfig.getApp().setTraceLogSpans(false);
// 前端工程由于在编译时混入了环境信息,所以不允许重用版本,每次部署都要重新编译
projectConfig.setDisableReuseVersion(true);
}
@Override
public BasicFlow prepareFlow() {
return new FrontendNonNativeNodePrepareFlow();
}
@Override
public BasicFlow buildFlow() {
return new FrontendNonNativeNodeBuildFlow();
}
@Override
public BasicFlow releaseFlow() {
return new KubeReleaseFlow();
}
@Override
public BasicFlow unReleaseFlow() {
return new DefaultUnReleaseFlow();
}
@Override
public BasicFlow rollbackFlow(boolean history, String version) {
return new DefaultRollbackFlow(history, version);
}
@Override
public BasicFlow scaleFlow(int replicas, boolean autoScale, int minReplicas, int maxReplicas, int cpuAvg) {
return new DefaultScaleFlow(replicas, autoScale, minReplicas, maxReplicas, cpuAvg);
}
@Override
public BasicFlow refreshFlow() {
return new DefaultRefreshFlow();
}
@Override
public BasicFlow logFlow(String podName, boolean follow) {
return new DefaultLogFlow(podName, follow);
}
@Override
public BasicFlow debugFlow(String podName, int forwardPort) {
return new NoNeedProcessFLow();
}
@Override
public Map<String, String> getEnv(FinalProjectConfig projectConfig) {
return new HashMap<>();
}
}
|
package org.neo4j.cypherdsl.codegen.sdn6.models.labels.nodeswithdifferentlabelannotations;
import java.util.List;
import javax.annotation.Generated;
import org.neo4j.cypherdsl.core.MapExpression;
import org.neo4j.cypherdsl.core.NodeBase;
import org.neo4j.cypherdsl.core.NodeLabel;
import org.neo4j.cypherdsl.core.Properties;
import org.neo4j.cypherdsl.core.SymbolicName;
@Generated(
value = "org.neo4j.cypherdsl.codegen.core.NodeImplBuilder",
date = "2019-09-21T21:21:00+01:00",
comments = "This class is generated by the Neo4j Cypher-DSL. All changes to it will be lost after regeneration."
)
public final class MultipleLabels1_ extends NodeBase<MultipleLabels1_> {
public static final MultipleLabels1_ MULTIPLE_LABELS_1 = new MultipleLabels1_();
public MultipleLabels1_() {
super("Label1", "Label2");
}
private MultipleLabels1_(SymbolicName symbolicName, List<NodeLabel> labels,
Properties properties) {
super(symbolicName, labels, properties);
}
@Override
public MultipleLabels1_ named(SymbolicName newSymbolicName) {
return new MultipleLabels1_(newSymbolicName, getLabels(), getProperties());
}
@Override
public MultipleLabels1_ withProperties(MapExpression newProperties) {
return new MultipleLabels1_(getSymbolicName().orElse(null), getLabels(), Properties.create(newProperties));
}
}
|
/**
* Based on initial work of HidDeviceProfile.java from WearMouse, which comes with the
* following copyright notice, licensed under the Apache License, Version 2.0
*
* Copyright 2018, Google LLC All Rights Reserved.
*
* Modified to model the HID representation of a security key virtual connection
* based on the CTAP2 HID interrupt driven protocol available at:
* https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#usb
*/
package de.wiosense.wiokey.bluetooth;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHidDevice;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.ParcelUuid;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.core.util.Preconditions;
/** Wrapper for BluetoothHidDevice profile that manages paired HID Host devices. */
public class HidDeviceProfile {
private static final String TAG = "HidDeviceProfile";
private static final ParcelUuid HOGP_UUID =
ParcelUuid.fromString("00001812-0000-1000-8000-00805f9b34fb");
private static final ParcelUuid HID_UUID =
ParcelUuid.fromString("00001124-0000-1000-8000-00805f9b34fb");
/** Used to call back when a profile proxy connection state has changed. */
public interface ServiceStateListener {
/**
* Callback to receive the new profile proxy object.
*
* @param proxy Profile proxy object or {@code null} if the service was disconnected.
*/
@MainThread
void onServiceStateChanged(BluetoothProfile proxy);
}
private final BluetoothAdapter bluetoothAdapter;
@Nullable private ServiceStateListener serviceStateListener;
@Nullable private BluetoothHidDevice service;
@SuppressLint("RestrictedApi")
HidDeviceProfile() {
this.bluetoothAdapter = Preconditions.checkNotNull(BluetoothAdapter.getDefaultAdapter());
}
/**
* Check if a device supports HID Host profile.
*
* @param device Device to check.
* @return {@code true} if the HID Host profile is supported, {@code false} otherwise.
*/
public boolean isProfileSupported(BluetoothDevice device) {
// If a device reports itself as a HID Device, then it isn't a HID Host.
ParcelUuid[] uuidArray = device.getUuids();
if (uuidArray != null) {
for (ParcelUuid uuid : uuidArray) {
if (HID_UUID.equals(uuid) || HOGP_UUID.equals(uuid)) {
return false;
}
}
}
return true;
}
/**
* Initiate the connection to the profile proxy service.
*
* @param context Context that is required to establish the service connection.
* @param listener Callback that will receive the profile proxy object.
*/
@SuppressLint("RestrictedApi")
@MainThread
void registerServiceListener(Context context, ServiceStateListener listener) {
context = Preconditions.checkNotNull(context).getApplicationContext();
serviceStateListener = Preconditions.checkNotNull(listener);
bluetoothAdapter.getProfileProxy(
context, new ServiceListener(), BluetoothProfile.HID_DEVICE);
}
/** Close the profile service connection. */
@MainThread
void unregisterServiceListener() {
if (service != null) {
try {
bluetoothAdapter.closeProfileProxy(BluetoothProfile.HID_DEVICE, service);
} catch (Throwable t) {
Log.w(TAG, "Error cleaning up proxy", t);
}
service = null;
}
serviceStateListener = null;
}
/**
* Examine the device for current connection status.
*
* @param device Remote Bluetooth device to examine.
* @return A Bluetooth profile connection state.
*/
@SuppressLint("RestrictedApi")
public int getConnectionState(BluetoothDevice device) {
if (service == null || device == null) {
return BluetoothProfile.STATE_DISCONNECTED;
}
return service.getConnectionState(Preconditions.checkNotNull(device));
}
/**
* Initiate the connection to the remote HID Host device.
*
* @param device Device to connect to.
*/
@MainThread
void connect(BluetoothDevice device) {
if (service != null && isProfileSupported(device)) {
service.connect(device);
}
}
/**
* Close the connection with the remote HID Host device.
*
* @param device Device to disconnect from.
*/
@MainThread
public void disconnect(BluetoothDevice device) {
if (service != null && isProfileSupported(device)) {
service.disconnect(device);
}
}
/**
* Get all devices that are in the "Connected" state.
*
* @return Connected devices list.
*/
@MainThread
List<BluetoothDevice> getConnectedDevices() {
if (service == null) {
return new ArrayList<>();
}
return service.getConnectedDevices();
}
/**
* Get all devices that match one of the specified connection states.
*
* @param states List of states we are interested in.
* @return List of devices that match one of the states.
*/
@MainThread
List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
if (service == null) {
return new ArrayList<>();
}
return service.getDevicesMatchingConnectionStates(states);
}
private final class ServiceListener implements BluetoothProfile.ServiceListener {
@Override
@MainThread
public void onServiceConnected(int profile, BluetoothProfile proxy) {
service = (BluetoothHidDevice) proxy;
if (serviceStateListener != null) {
Log.d(TAG, "Actioning service state listener");
serviceStateListener.onServiceStateChanged(service);
} else {
bluetoothAdapter.closeProfileProxy(BluetoothProfile.HID_DEVICE, proxy);
}
}
@Override
@MainThread
public void onServiceDisconnected(int profile) {
service = null;
if (serviceStateListener != null) {
serviceStateListener.onServiceStateChanged(null);
}
}
}
}
|
/**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.redisson.jcache;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.redisson.client.codec.Codec;
import org.redisson.client.handler.State;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;
import io.netty.buffer.ByteBuf;
import io.netty.util.internal.PlatformDependent;
/**
*
* @author Nikita Koksharov
*
*/
public class JCacheEventCodec implements Codec {
private final Codec codec;
private final boolean sync;
private final Decoder<Object> decoder = new Decoder<Object>() {
@Override
public Object decode(ByteBuf buf, State state) throws IOException {
List<Object> result = new ArrayList<Object>();
int keyLen;
if (PlatformDependent.isWindows()) {
keyLen = buf.readIntLE();
} else {
keyLen = (int) buf.readLongLE();
}
ByteBuf keyBuf = buf.readSlice(keyLen);
Object key = codec.getMapKeyDecoder().decode(keyBuf, state);
result.add(key);
int valueLen;
if (PlatformDependent.isWindows()) {
valueLen = buf.readIntLE();
} else {
valueLen = (int) buf.readLongLE();
}
ByteBuf valueBuf = buf.readSlice(valueLen);
Object value = codec.getMapValueDecoder().decode(valueBuf, state);
result.add(value);
if (sync) {
double syncId = buf.readDoubleLE();
result.add(syncId);
}
return result;
}
};
public JCacheEventCodec(Codec codec, boolean sync) {
super();
this.codec = codec;
this.sync = sync;
}
@Override
public Decoder<Object> getMapValueDecoder() {
throw new UnsupportedOperationException();
}
@Override
public Encoder getMapValueEncoder() {
throw new UnsupportedOperationException();
}
@Override
public Decoder<Object> getMapKeyDecoder() {
throw new UnsupportedOperationException();
}
@Override
public Encoder getMapKeyEncoder() {
throw new UnsupportedOperationException();
}
@Override
public Decoder<Object> getValueDecoder() {
return decoder;
}
@Override
public Encoder getValueEncoder() {
throw new UnsupportedOperationException();
}
@Override
public ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
}
|
/*******************************************************************************
* Copyright SemanticBits, Northwestern University and Akaza Research
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caaers/LICENSE.txt for details.
******************************************************************************/
package gov.nih.nci.cabig.caaers.dao.index;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import gov.nih.nci.cabig.caaers.domain.index.OrganizationIndex;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.transaction.annotation.Transactional;
public class OrganizationIndexDao extends AbstractIndexDao {
@Override
public String entityIdColumnName() {
return "organization_id";
}
@Override
public String indexTableName() {
return "organization_index";
}
@Override
public String sequenceName() {
return "seq_organization_index_id";
}
@Override
public String entityTableName() {
return "organizations";
}
@Override
public String getIdColumnFromEntity() {
return "id";
}
}
|
package xyz.jecy.gateway.config;
import java.net.URI;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
//import xyz.jecy.gateway.error.ErrorCode;
import xyz.jecy.util.response.Response;
/**
* @Author dkw[dongkewei@xinzhili.cn]
* @data 2020/1/10 3:43 下午
*/
@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {
@Value("permit.all")
private List<String> permitAll;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
if (needCheck(request)) {
String accessToken = getToken(request);
if(StringUtils.isEmpty(accessToken)){
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}
return chain.filter(exchange);
}
// ServerHttpResponse response = exchange.getResponse(); //设置header
// HttpHeaders httpHeaders = response.getHeaders();
// httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
// httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"); //设置body
// String bodyPackage = "{\"status\":\"110\",\"message\":\"未登录或登录超时\"}";
// DataBuffer bodyDataBuffer = response.bufferFactory().wrap(bodyPackage.getBytes()); //返回
// return response.writeWith(Mono.just(bodyDataBuffer));
private boolean needCheck(ServerHttpRequest request) {
URI uri = request.getURI();
String requestUri = uri.getPath();
return !permitAll.contains(requestUri);
}
private String getToken(ServerHttpRequest request) {
List<String> headers = request.getHeaders().get("Authorization");
if (!CollectionUtils.isEmpty(headers)) {
String value = headers.get(0);
String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
// Add this here for the auth details later. Would be better to change the signature of this method.
int commaIndex = authHeaderValue.indexOf(',');
if (commaIndex > 0) {
authHeaderValue = authHeaderValue.substring(0, commaIndex);
}
return authHeaderValue;
}
return "";
}
@Override
public int getOrder() {
return 0;
}
}
|
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package org.apache.cloudstack.direct.download;
import static com.cloud.storage.Storage.ImageFormat;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
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.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.agent.directdownload.DirectDownloadAnswer;
import org.apache.cloudstack.agent.directdownload.DirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.DirectDownloadCommand.DownloadProtocol;
import org.apache.cloudstack.agent.directdownload.HttpDirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.HttpsDirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.MetalinkDirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.NfsDirectDownloadCommand;
import org.apache.cloudstack.agent.directdownload.RevokeDirectDownloadCertificateCommand;
import org.apache.cloudstack.agent.directdownload.SetupDirectDownloadCertificateCommand;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.managed.context.ManagedContextRunnable;
import org.apache.cloudstack.poll.BackgroundPollManager;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.event.ActionEventUtils;
import com.cloud.event.EventTypes;
import com.cloud.event.EventVO;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.VMTemplateStoragePoolVO;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplatePoolDao;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.security.CertificateHelper;
import sun.security.x509.X509CertImpl;
public class DirectDownloadManagerImpl extends ManagerBase implements DirectDownloadManager {
private static final Logger s_logger = Logger.getLogger(DirectDownloadManagerImpl.class);
protected static final String httpHeaderDetailKey = "HTTP_HEADER";
protected static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
protected static final String END_CERT = "-----END CERTIFICATE-----";
protected final static String LINE_SEPARATOR = "\n";
@Inject
private VMTemplateDao vmTemplateDao;
@Inject
private PrimaryDataStoreDao primaryDataStoreDao;
@Inject
private HostDao hostDao;
@Inject
private AgentManager agentManager;
@Inject
private VMTemplatePoolDao vmTemplatePoolDao;
@Inject
private DataStoreManager dataStoreManager;
@Inject
private DirectDownloadCertificateDao directDownloadCertificateDao;
@Inject
private DirectDownloadCertificateHostMapDao directDownloadCertificateHostMapDao;
@Inject
private BackgroundPollManager backgroundPollManager;
@Inject
private DataCenterDao dataCenterDao;
@Inject
private ConfigurationDao configDao;
protected ScheduledExecutorService executorService;
@Override
public List<Class<?>> getCommands() {
final List<Class<?>> cmdList = new ArrayList<Class<?>>();
return cmdList;
}
/**
* Return protocol to use from provided URL
* @param url
* @return
*/
public static DownloadProtocol getProtocolFromUrl(String url) {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
throw new CloudRuntimeException("URI is incorrect: " + url);
}
if ((uri != null) && (uri.getScheme() != null)) {
if (uri.getPath().endsWith(".metalink")) {
return DownloadProtocol.METALINK;
} else if (uri.getScheme().equalsIgnoreCase("http")) {
return DownloadProtocol.HTTP;
} else if (uri.getScheme().equalsIgnoreCase("https")) {
return DownloadProtocol.HTTPS;
} else if (uri.getScheme().equalsIgnoreCase("nfs")) {
return DownloadProtocol.NFS;
} else {
throw new CloudRuntimeException("Scheme is not supported " + url);
}
} else {
throw new CloudRuntimeException("URI is incorrect: " + url);
}
}
/**
* Return HTTP headers from template details
* @param templateDetails
* @return
*/
protected Map<String, String> getHeadersFromDetails(Map<String, String> templateDetails) {
if (MapUtils.isEmpty(templateDetails)) {
return new HashMap<>();
}
Map<String, String> headers = new HashMap<>();
for (String key : templateDetails.keySet()) {
if (key.startsWith(httpHeaderDetailKey)) {
String header = key.split(":")[1];
String value = templateDetails.get(key);
headers.put(header, value);
}
}
return headers;
}
/**
* Get running host IDs within the same hypervisor, cluster and datacenter than hostId. ID hostId is not included on the returned list
*/
protected List<Long> getRunningHostIdsInTheSameCluster(Long clusterId, long dataCenterId, HypervisorType hypervisorType, long hostId) {
List<Long> list = hostDao.listByDataCenterIdAndHypervisorType(dataCenterId, hypervisorType)
.stream()
.filter(x -> x.getHypervisorType().equals(hypervisorType) && x.getStatus().equals(Status.Up) &&
x.getType().equals(Host.Type.Routing) && x.getClusterId().equals(clusterId) &&
x.getId() != hostId)
.map(x -> x.getId())
.collect(Collectors.toList());
Collections.shuffle(list);
return list;
}
/**
* Create host IDs array having hostId as the first element
*/
protected Long[] createHostIdsList(List<Long> hostIds, long hostId) {
if (CollectionUtils.isEmpty(hostIds)) {
return Arrays.asList(hostId).toArray(new Long[1]);
}
Long[] ids = new Long[hostIds.size() + 1];
ids[0] = hostId;
int i = 1;
for (Long id : hostIds) {
ids[i] = id;
i++;
}
return ids;
}
/**
* Get hosts to retry download having hostId as the first element
*/
protected Long[] getHostsToRetryOn(Long clusterId, long dataCenterId, HypervisorType hypervisorType, long hostId) {
List<Long> hostIds = getRunningHostIdsInTheSameCluster(clusterId, dataCenterId, hypervisorType, hostId);
return createHostIdsList(hostIds, hostId);
}
@Override
public void downloadTemplate(long templateId, long poolId, long hostId) {
VMTemplateVO template = vmTemplateDao.findById(templateId);
StoragePoolVO pool = primaryDataStoreDao.findById(poolId);
HostVO host = hostDao.findById(hostId);
if (pool == null) {
throw new CloudRuntimeException("Storage pool " + poolId + " could not be found");
}
if (template == null) {
throw new CloudRuntimeException("Template " + templateId + " could not be found");
}
if (host == null) {
throw new CloudRuntimeException("Host " + hostId + " could not be found");
}
if (!template.isDirectDownload()) {
throw new CloudRuntimeException("Template " + templateId + " is not marked for direct download");
}
Map<String, String> details = template.getDetails();
String url = template.getUrl();
String checksum = template.getChecksum();
Map<String, String> headers = getHeadersFromDetails(details);
DataStore store = dataStoreManager.getDataStore(poolId, DataStoreRole.Primary);
if (store == null) {
throw new CloudRuntimeException("Data store " + poolId + " could not be found");
}
PrimaryDataStore primaryDataStore = (PrimaryDataStore) store;
PrimaryDataStoreTO to = (PrimaryDataStoreTO) primaryDataStore.getTO();
DownloadProtocol protocol = getProtocolFromUrl(url);
DirectDownloadCommand cmd = getDirectDownloadCommandFromProtocol(protocol, url, templateId, to, checksum, headers);
Answer answer = sendDirectDownloadCommand(cmd, template, poolId, host);
VMTemplateStoragePoolVO sPoolRef = vmTemplatePoolDao.findByPoolTemplate(poolId, templateId);
if (sPoolRef == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Not found (templateId:" + templateId + " poolId: " + poolId + ") in template_spool_ref, persisting it");
}
DirectDownloadAnswer ans = (DirectDownloadAnswer) answer;
sPoolRef = new VMTemplateStoragePoolVO(poolId, templateId);
sPoolRef.setDownloadPercent(100);
sPoolRef.setDownloadState(VMTemplateStorageResourceAssoc.Status.DOWNLOADED);
sPoolRef.setState(ObjectInDataStoreStateMachine.State.Ready);
sPoolRef.setTemplateSize(ans.getTemplateSize());
sPoolRef.setLocalDownloadPath(ans.getInstallPath());
sPoolRef.setInstallPath(ans.getInstallPath());
vmTemplatePoolDao.persist(sPoolRef);
}
}
/**
* Send direct download command for downloading template with ID templateId on storage pool with ID poolId.<br/>
* At first, cmd is sent to host, in case of failure it will retry on other hosts before failing
* @param cmd direct download command
* @param template template
* @param poolId pool id
* @param host first host to which send the command
* @return download answer from any host which could handle cmd
*/
private Answer sendDirectDownloadCommand(DirectDownloadCommand cmd, VMTemplateVO template, long poolId, HostVO host) {
boolean downloaded = false;
int retry = 3;
Long[] hostsToRetry = getHostsToRetryOn(host.getClusterId(), host.getDataCenterId(), host.getHypervisorType(), host.getId());
int hostIndex = 0;
Answer answer = null;
Long hostToSendDownloadCmd = hostsToRetry[hostIndex];
boolean continueRetrying = true;
while (!downloaded && retry > 0 && continueRetrying) {
s_logger.debug("Sending Direct download command to host " + hostToSendDownloadCmd);
answer = agentManager.easySend(hostToSendDownloadCmd, cmd);
if (answer != null) {
DirectDownloadAnswer ans = (DirectDownloadAnswer)answer;
downloaded = answer.getResult();
continueRetrying = ans.isRetryOnOtherHosts();
}
hostToSendDownloadCmd = hostsToRetry[(hostIndex + 1) % hostsToRetry.length];
retry --;
}
if (!downloaded) {
logUsageEvent(template, poolId);
throw new CloudRuntimeException("Template " + template.getId() + " could not be downloaded on pool " + poolId + ", failing after trying on several hosts");
}
return answer;
}
/**
* Log and persist event for direct download failure
*/
private void logUsageEvent(VMTemplateVO template, long poolId) {
String event = EventTypes.EVENT_TEMPLATE_DIRECT_DOWNLOAD_FAILURE;
if (template.getFormat() == ImageFormat.ISO) {
event = EventTypes.EVENT_ISO_DIRECT_DOWNLOAD_FAILURE;
}
String description = "Direct Download for template Id: " + template.getId() + " on pool Id: " + poolId + " failed";
s_logger.error(description);
ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), template.getAccountId(), EventVO.LEVEL_INFO, event, description, 0);
}
/**
* Return DirectDownloadCommand according to the protocol
*/
private DirectDownloadCommand getDirectDownloadCommandFromProtocol(DownloadProtocol protocol, String url, Long templateId, PrimaryDataStoreTO destPool,
String checksum, Map<String, String> httpHeaders) {
int connectTimeout = DirectDownloadConnectTimeout.value();
int soTimeout = DirectDownloadSocketTimeout.value();
int connectionRequestTimeout = DirectDownloadConnectionRequestTimeout.value();
if (protocol.equals(DownloadProtocol.HTTP)) {
return new HttpDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders, connectTimeout, soTimeout);
} else if (protocol.equals(DownloadProtocol.HTTPS)) {
return new HttpsDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders, connectTimeout, soTimeout, connectionRequestTimeout);
} else if (protocol.equals(DownloadProtocol.NFS)) {
return new NfsDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders);
} else if (protocol.equals(DownloadProtocol.METALINK)) {
return new MetalinkDirectDownloadCommand(url, templateId, destPool, checksum, httpHeaders, connectTimeout, soTimeout);
} else {
return null;
}
}
/**
* Return the list of running hosts to which upload certificates for Direct Download
*/
private List<HostVO> getRunningHostsToUploadCertificate(Long zoneId, HypervisorType hypervisorType) {
return hostDao.listAllHostsUpByZoneAndHypervisor(zoneId, hypervisorType);
}
/**
* Return pretified PEM certificate
*/
protected String getPretifiedCertificate(String certificateCer) {
String cert = certificateCer.replaceAll("(.{64})", "$1\n");
if (!cert.startsWith(BEGIN_CERT) && !cert.endsWith(END_CERT)) {
cert = BEGIN_CERT + LINE_SEPARATOR + cert + LINE_SEPARATOR + END_CERT;
}
return cert;
}
/**
* Generate and return certificate from the string
* @throws CloudRuntimeException if the certificate is not well formed
*/
private Certificate getCertificateFromString(String certificatePem) {
try {
return CertificateHelper.buildCertificate(certificatePem);
} catch (CertificateException e) {
e.printStackTrace();
throw new CloudRuntimeException("Cannot parse the certificate provided, please provide a PEM certificate. Error: " + e.getMessage());
}
}
/**
* Perform sanity of string parsed certificate
*/
protected void certificateSanity(String certificatePem) {
Certificate certificate = getCertificateFromString(certificatePem);
if (certificate instanceof X509CertImpl) {
X509CertImpl x509Cert = (X509CertImpl) certificate;
try {
x509Cert.checkValidity();
} catch (CertificateExpiredException | CertificateNotYetValidException e) {
String msg = "Certificate is invalid. Please provide a valid certificate. Error: " + e.getMessage();
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
if (x509Cert.getSubjectDN() != null) {
s_logger.debug("Valid certificate for domain name: " + x509Cert.getSubjectDN().getName());
}
}
}
@Override
public boolean uploadCertificateToHosts(String certificateCer, String alias, String hypervisor, Long zoneId, Long hostId) {
if (alias != null && (alias.equalsIgnoreCase("cloud") || alias.startsWith("cloudca"))) {
throw new CloudRuntimeException("Please provide a different alias name for the certificate");
}
List<HostVO> hosts;
DirectDownloadCertificateVO certificateVO;
HypervisorType hypervisorType = HypervisorType.getType(hypervisor);
if (hostId == null) {
hosts = getRunningHostsToUploadCertificate(zoneId, hypervisorType);
String certificatePem = getPretifiedCertificate(certificateCer);
certificateSanity(certificatePem);
certificateVO = directDownloadCertificateDao.findByAlias(alias, hypervisorType, zoneId);
if (certificateVO != null) {
throw new CloudRuntimeException("Certificate alias " + alias + " has been already created");
}
certificateVO = new DirectDownloadCertificateVO(alias, certificatePem, hypervisorType, zoneId);
directDownloadCertificateDao.persist(certificateVO);
} else {
HostVO host = hostDao.findById(hostId);
hosts = Collections.singletonList(host);
certificateVO = directDownloadCertificateDao.findByAlias(alias, hypervisorType, zoneId);
if (certificateVO == null) {
s_logger.info("Certificate must be uploaded on zone " + zoneId);
return false;
}
}
s_logger.info("Attempting to upload certificate: " + alias + " to " + hosts.size() + " hosts on zone " + zoneId);
int hostCount = 0;
if (CollectionUtils.isNotEmpty(hosts)) {
for (HostVO host : hosts) {
if (!uploadCertificate(certificateVO.getId(), host.getId())) {
String msg = "Could not upload certificate " + alias + " on host: " + host.getName() + " (" + host.getUuid() + ")";
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
hostCount++;
}
}
s_logger.info("Certificate was successfully uploaded to " + hostCount + " hosts");
return true;
}
/**
* Upload and import certificate to hostId on keystore
*/
public boolean uploadCertificate(long certificateId, long hostId) {
DirectDownloadCertificateVO certificateVO = directDownloadCertificateDao.findById(certificateId);
if (certificateVO == null) {
throw new CloudRuntimeException("Could not find certificate with id " + certificateId + " to upload to host: " + hostId);
}
String certificate = certificateVO.getCertificate();
String alias = certificateVO.getAlias();
s_logger.debug("Uploading certificate: " + certificateVO.getAlias() + " to host " + hostId);
SetupDirectDownloadCertificateCommand cmd = new SetupDirectDownloadCertificateCommand(certificate, alias);
Answer answer = agentManager.easySend(hostId, cmd);
if (answer == null || !answer.getResult()) {
String msg = "Certificate " + alias + " could not be added to host " + hostId;
if (answer != null) {
msg += " due to: " + answer.getDetails();
}
s_logger.error(msg);
return false;
}
s_logger.info("Certificate " + alias + " successfully uploaded to host: " + hostId);
DirectDownloadCertificateHostMapVO map = directDownloadCertificateHostMapDao.findByCertificateAndHost(certificateId, hostId);
if (map != null) {
map.setRevoked(false);
directDownloadCertificateHostMapDao.update(map.getId(), map);
} else {
DirectDownloadCertificateHostMapVO mapVO = new DirectDownloadCertificateHostMapVO(certificateId, hostId);
directDownloadCertificateHostMapDao.persist(mapVO);
}
return true;
}
@Override
public boolean revokeCertificateAlias(String certificateAlias, String hypervisor, Long zoneId, Long hostId) {
HypervisorType hypervisorType = HypervisorType.getType(hypervisor);
DirectDownloadCertificateVO certificateVO = directDownloadCertificateDao.findByAlias(certificateAlias, hypervisorType, zoneId);
if (certificateVO == null) {
throw new CloudRuntimeException("Certificate alias " + certificateAlias + " does not exist");
}
List<DirectDownloadCertificateHostMapVO> maps = null;
if (hostId == null) {
maps = directDownloadCertificateHostMapDao.listByCertificateId(certificateVO.getId());
} else {
DirectDownloadCertificateHostMapVO hostMap = directDownloadCertificateHostMapDao.findByCertificateAndHost(certificateVO.getId(), hostId);
if (hostMap == null) {
s_logger.info("Certificate " + certificateAlias + " cannot be revoked from host " + hostId + " as it is not available on the host");
return false;
}
maps = Collections.singletonList(hostMap);
}
s_logger.info("Attempting to revoke certificate alias: " + certificateAlias + " from " + maps.size() + " hosts");
if (CollectionUtils.isNotEmpty(maps)) {
for (DirectDownloadCertificateHostMapVO map : maps) {
Long mappingHostId = map.getHostId();
if (!revokeCertificateAliasFromHost(certificateAlias, mappingHostId)) {
String msg = "Could not revoke certificate from host: " + mappingHostId;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
s_logger.info("Certificate " + certificateAlias + " revoked from host " + mappingHostId);
map.setRevoked(true);
directDownloadCertificateHostMapDao.update(map.getId(), map);
}
}
return true;
}
protected boolean revokeCertificateAliasFromHost(String alias, Long hostId) {
RevokeDirectDownloadCertificateCommand cmd = new RevokeDirectDownloadCertificateCommand(alias);
try {
Answer answer = agentManager.send(hostId, cmd);
return answer != null && answer.getResult();
} catch (AgentUnavailableException | OperationTimedoutException e) {
s_logger.error("Error revoking certificate " + alias + " from host " + hostId, e);
}
return false;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
executorService = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("DirectDownloadCertificateMonitor"));
return true;
}
@Override
public boolean stop() {
executorService.shutdownNow();
return true;
}
@Override
public boolean start() {
if (DirectDownloadCertificateUploadInterval.value() > 0L) {
executorService.scheduleWithFixedDelay(
new DirectDownloadCertificateUploadBackgroundTask(this, hostDao, dataCenterDao,
directDownloadCertificateDao, directDownloadCertificateHostMapDao),
60L, DirectDownloadCertificateUploadInterval.value(), TimeUnit.HOURS);
}
return true;
}
@Override
public String getConfigComponentName() {
return DirectDownloadManager.class.getSimpleName();
}
@Override
public ConfigKey<?>[] getConfigKeys() {
return new ConfigKey<?>[]{
DirectDownloadCertificateUploadInterval,
DirectDownloadConnectTimeout,
DirectDownloadSocketTimeout,
DirectDownloadConnectionRequestTimeout
};
}
public static final class DirectDownloadCertificateUploadBackgroundTask extends ManagedContextRunnable {
private DirectDownloadManager directDownloadManager;
private HostDao hostDao;
private DirectDownloadCertificateDao directDownloadCertificateDao;
private DirectDownloadCertificateHostMapDao directDownloadCertificateHostMapDao;
private DataCenterDao dataCenterDao;
public DirectDownloadCertificateUploadBackgroundTask(
final DirectDownloadManager manager,
final HostDao hostDao,
final DataCenterDao dataCenterDao,
final DirectDownloadCertificateDao directDownloadCertificateDao,
final DirectDownloadCertificateHostMapDao directDownloadCertificateHostMapDao) {
this.directDownloadManager = manager;
this.hostDao = hostDao;
this.dataCenterDao = dataCenterDao;
this.directDownloadCertificateDao = directDownloadCertificateDao;
this.directDownloadCertificateHostMapDao = directDownloadCertificateHostMapDao;
}
@Override
protected void runInContext() {
try {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Direct Download Manager background task is running...");
}
final DateTime now = DateTime.now(DateTimeZone.UTC);
List<DataCenterVO> enabledZones = dataCenterDao.listEnabledZones();
for (DataCenterVO zone : enabledZones) {
List<DirectDownloadCertificateVO> zoneCertificates = directDownloadCertificateDao.listByZone(zone.getId());
if (CollectionUtils.isNotEmpty(zoneCertificates)) {
for (DirectDownloadCertificateVO certificateVO : zoneCertificates) {
List<HostVO> hostsToUpload = hostDao.listAllHostsUpByZoneAndHypervisor(certificateVO.getZoneId(), certificateVO.getHypervisorType());
if (CollectionUtils.isNotEmpty(hostsToUpload)) {
for (HostVO hostVO : hostsToUpload) {
DirectDownloadCertificateHostMapVO mapping = directDownloadCertificateHostMapDao.findByCertificateAndHost(certificateVO.getId(), hostVO.getId());
if (mapping == null) {
s_logger.debug("Certificate " + certificateVO.getId() +
" (" + certificateVO.getAlias() + ") was not uploaded to host: " + hostVO.getId() +
" uploading it");
boolean result = directDownloadManager.uploadCertificate(certificateVO.getId(), hostVO.getId());
s_logger.debug("Certificate " + certificateVO.getAlias() + " " +
(result ? "uploaded" : "could not be uploaded") +
" to host " + hostVO.getId());
}
}
}
}
}
}
} catch (final Throwable t) {
s_logger.error("Error trying to run Direct Download background task", t);
}
}
}
}
|
package com.shltr.darrieng.shltr_android;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.shltr.darrieng.shltr_android.Pojo.UserPojo;
import com.squareup.picasso.Picasso;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Adapter for list of nearby users.
*/
public class NearbyPersonAdapter extends RecyclerView.Adapter<NearbyPersonAdapter.ViewHolder> {
Context context;
List<UserPojo> userList;
static class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.profile_pic)
ImageView profilePic;
@BindView(R.id.user_name)
TextView userNameView;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
/**
* Constructor
*
* @param context Android context.
* @param userList List of users and their info.
*/
public NearbyPersonAdapter(Context context, List<UserPojo> userList) {
this.context = context;
this.userList = userList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(
parent.getContext()).inflate(R.layout.profile_row, parent, false);
return new ViewHolder(itemLayoutView);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Picasso.with(context).load("http://hack.symerit.com/images/users/" +
userList.get(position).getPicture()).resize(200, 200).into(holder.profilePic);
holder.userNameView.setText(userList.get(position).getName());
}
@Override
public int getItemCount() {
return userList.size();
}
/**
* Add user to the list of users.
*
* @param newUser New user to add.
*/
public void addUser(UserPojo newUser) {
for (UserPojo pojo : userList) {
if (pojo.getPicture().equals(newUser.getPicture())) {
return;
}
}
userList.add(newUser);
notifyItemChanged(userList.size() - 1);
}
}
|
package org.bc.asn1.esf;
import org.bc.asn1.ASN1EncodableVector;
import org.bc.asn1.ASN1Object;
import org.bc.asn1.ASN1ObjectIdentifier;
import org.bc.asn1.ASN1Primitive;
import org.bc.asn1.ASN1Sequence;
import org.bc.asn1.DERSequence;
public class CommitmentTypeIndication extends ASN1Object {
private ASN1ObjectIdentifier commitmentTypeId;
private ASN1Sequence commitmentTypeQualifier;
private CommitmentTypeIndication(ASN1Sequence var1) {
this.commitmentTypeId = (ASN1ObjectIdentifier)var1.getObjectAt(0);
if (var1.size() > 1) {
this.commitmentTypeQualifier = (ASN1Sequence)var1.getObjectAt(1);
}
}
public CommitmentTypeIndication(ASN1ObjectIdentifier var1) {
this.commitmentTypeId = var1;
}
public CommitmentTypeIndication(ASN1ObjectIdentifier var1, ASN1Sequence var2) {
this.commitmentTypeId = var1;
this.commitmentTypeQualifier = var2;
}
public static CommitmentTypeIndication getInstance(Object var0) {
return var0 != null && !(var0 instanceof CommitmentTypeIndication) ? new CommitmentTypeIndication(ASN1Sequence.getInstance(var0)) : (CommitmentTypeIndication)var0;
}
public ASN1ObjectIdentifier getCommitmentTypeId() {
return this.commitmentTypeId;
}
public ASN1Sequence getCommitmentTypeQualifier() {
return this.commitmentTypeQualifier;
}
public ASN1Primitive toASN1Primitive() {
ASN1EncodableVector var1 = new ASN1EncodableVector();
var1.add(this.commitmentTypeId);
if (this.commitmentTypeQualifier != null) {
var1.add(this.commitmentTypeQualifier);
}
return new DERSequence(var1);
}
}
|
package zserio.emit.java;
import zserio.ast.ZserioType;
import zserio.emit.common.ZserioEmitException;
/**
* The exception which can be thrown by Java emitter.
*/
public class ZserioEmitJavaException extends ZserioEmitException
{
/**
* Constructor.
*
* @param message Exception message.
*/
public ZserioEmitJavaException(String message)
{
super(message);
}
/**
* Constructs a new ZserioEmitJavaException indicating that the emit-operation is not supported in case
* of the specified type.
*
* @param type Type which is not supported.
*/
public ZserioEmitJavaException(ZserioType type)
{
super(type);
}
private static final long serialVersionUID = 1L;
}
|
package br.com.resultatec.sagflix.api.v1.model.input;
import javax.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ComentarioVideoInput {
@NotBlank
private String comentario;
}
|
package com.platform.utils.excel;
import com.platform.utils.RRException;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Excel文件导入的基本功能类
* 可导入EXCEL2003 和 EXCEL2007格式。
*
* @author taylor
* @email 516195940@qq.com
* @date 2017年10月28日 13:11:27
*/
public class ExcelImport {
/**
* excel2003扩展名
*/
public static final String EXCEL03_EXTENSION = ".xls";
/**
* excel2007扩展名
*/
public static final String EXCEL07_EXTENSION = ".xlsx";
private ExcelImport() {
}
/**
* 解析EXCEL数据为 List<String[]>
*
* @param excelFile 要解析的上传EXCEL文件
* @return List<String[]) 行(列)
*/
public static List<String[]> getExcelData07(MultipartFile excelFile) {
List<String[]> resultList = null;
if (null == excelFile || excelFile.isEmpty()) {
throw new RRException("文件内容为空!");
}
Excel2007Reader excel07 = new Excel2007Reader();
try {
excel07.process(excelFile.getInputStream(), false);
} catch (Exception e) {
throw new RRException("excel解析失败!");
}
resultList = excel07.getSheetData(0);
return resultList;
}
/**
* 解析EXCEL数据为 List<String[]>
*
* @param excelFile 要解析的上传EXCEL文件
* @return List<String[]) 行(列)
*/
public static List<String[]> getExcelData03(MultipartFile excelFile) {
List<String[]> resultList = null;
if (null == excelFile || excelFile.isEmpty()) {
throw new RRException("文件内容为空!");
}
Excel2003Reader excel03 = new Excel2003Reader();// 实例化excel处理对象
try {
excel03.process(excelFile.getInputStream());
} catch (IOException e) {
throw new RRException("excel解析失败!");
}
resultList = excel03.getSheetData(0);
return resultList;
}
/**
* 通过解析MultipartFile对象获取excel内容,并且将其拼装为List<String[]>对象返回
*
* @param excelFile
* @return
* @throws Exception
*/
public static List<String[]> getExcelData(MultipartFile excelFile)
throws RRException {
List<String[]> resultList = null;
if (!excelFile.isEmpty()) {// 上传的文件不能为空
String excelFileName = excelFile.getOriginalFilename();// 文件名(带后缀)
if (excelFileName.toLowerCase().endsWith(EXCEL03_EXTENSION)) {// 如果文件是以.xls为后缀
Excel2003Reader excel03 = new Excel2003Reader();// 实例化excel处理对象
try {
excel03.process(excelFile.getInputStream());
} catch (IOException e) {
throw new RRException("excel解析失败!");
}
resultList = excel03.getSheetData(0);
} else if (excelFileName.toLowerCase().endsWith(EXCEL07_EXTENSION)) {// 如果文件是以.xlsx为后缀
Excel2007Reader excel07 = new Excel2007Reader();
try {
excel07.process(excelFile.getInputStream(), false);
} catch (Exception e) {
throw new RRException("excel解析失败!");
}
resultList = excel07.getSheetData(0);
}
}
return resultList;
}
/**
* 通过解析MultipartFile对象获取excel内容,并且将其拼装为Map<Integer, List<String[]>>对象返回
*
* @param excelFile
* @return
* @throws Exception
*/
public static Map<Integer, List<String[]>> getExcelDataAll(MultipartFile excelFile)
throws RRException {
Map<Integer, List<String[]>> result = null;
if (!excelFile.isEmpty()) {// 上传的文件不能为空
String excelFileName = excelFile.getOriginalFilename();// 文件名(带后缀)
if (excelFileName.toLowerCase().endsWith(EXCEL03_EXTENSION)) {// 如果文件是以.xls为后缀
Excel2003Reader excel03 = new Excel2003Reader();// 实例化excel处理对象
try {
excel03.process(excelFile.getInputStream());
} catch (IOException e) {
throw new RRException("excel解析失败!");
}
result = excel03.getSheetData();
} else if (excelFileName.toLowerCase().endsWith(EXCEL07_EXTENSION)) {// 如果文件是以.xlsx为后缀
Excel2007Reader excel07 = new Excel2007Reader();
try {
excel07.process(excelFile.getInputStream(), true);
} catch (Exception e) {
throw new RRException("excel解析失败!");
}
result = excel07.getSheetData();
}
}
return result;
}
}
|
/*------------------------------------------------------------------------------
Copyright (c) CovertJaguar, 2011-2020
This work (the API) is licensed under the "MIT" License,
see LICENSE.md for details.
-----------------------------------------------------------------------------*/
package mods.railcraft.api.carts;
import net.minecraft.item.EnumDyeColor;
/**
*
* @author CovertJaguar <http://www.railcraft.info/>
*/
public interface IPaintedCart {
EnumDyeColor getPrimaryDyeColor();
EnumDyeColor getSecondaryDyeColor();
}
|
package util;
import androidx.recyclerview.widget.RecyclerView;
public interface OnStartDragListener {
void onStartDrag(RecyclerView.ViewHolder viewHolder);
}
|
package com.mydomain.accounting.dao;
import java.util.List;
import com.mydomain.accounting.dao.mapper.TagMapper;
import com.mydomain.accounting.model.persistence.TagPersistenceModel;
import org.springframework.stereotype.Repository;
@Repository
public class TagDaoIpl implements TagDao {
private final TagMapper tagMapper;
public TagDaoIpl(TagMapper tagMapper) {
this.tagMapper = tagMapper;
}
@Override
public void createTag(TagPersistenceModel tag) {
tagMapper.createTag(tag);
}
@Override
public TagPersistenceModel getTagByTagId(Long id) {
return tagMapper.getTagByTagId(id);
}
@Override
public TagPersistenceModel getTagByTagDescription(String description) {
return tagMapper.getTagByTagDescription(description);
}
@Override
public void updateTag(TagPersistenceModel tag) {
tagMapper.updateTag(tag);
}
@Override
public List<TagPersistenceModel> getTagListByTagIdList(List<Long> tagIdList) {
return tagMapper.getTagListByTagIdList(tagIdList);
}
@Override
public List<TagPersistenceModel> getTagListByUserId(Long userId, int pageNum, int pageSize) {
return tagMapper.getTagListByUserId(userId, pageNum, pageSize);
}
}
|
package lol.maki.socks.order;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import static java.math.BigDecimal.ZERO;
public class Order {
private final String id;
private final Customer customer;
private final Address address;
private final Card card;
private final List<Item> items;
private final Shipment shipment;
private final OffsetDateTime date;
private final OrderStatus status;
public Order(String id, Customer customer, Address address, Card card, List<Item> items, Shipment shipment, OffsetDateTime date, OrderStatus status) {
this.id = id;
this.customer = customer;
this.address = address;
this.card = card;
this.items = items;
this.shipment = shipment;
this.date = date;
this.status = status;
}
public String id() {
return id;
}
public Customer customer() {
return customer;
}
public Address address() {
return address;
}
public Card card() {
return card;
}
public List<Item> items() {
return items;
}
public Shipment shipment() {
return shipment;
}
public OffsetDateTime date() {
return date;
}
public OrderStatus status() {
return status;
}
public Order addItem(Item item) {
this.items.add(item);
return this;
}
public Order withShipment(Shipment shipment) {
return new Order(this.id, this.customer, this.address, this.card, this.items, shipment, this.date, this.status);
}
public static String newOrderId(Supplier<UUID> idGenerator) {
return idGenerator.get().toString().substring(0, 8);
}
public final BigDecimal total() {
return this.items()
.stream()
.map(Item::subTotal)
.reduce(ZERO, BigDecimal::add);
}
public final int itemCount() {
return this.items()
.stream()
.mapToInt(Item::quantity)
.sum();
}
}
|
package org.jenkinsci.plugins.p4.scm;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.mixin.ChangeRequestSCMHead;
public class P4GraphRequestSCMHead extends P4SCMHead implements ChangeRequestSCMHead {
private static final long serialVersionUID = 1L;
private final SCMHead target;
private final String repo;
private final String branch;
P4GraphRequestSCMHead(String name, String repo, String branch, P4Path path, SCMHead target) {
super(name, path);
this.target = target;
this.repo = repo;
this.branch = branch;
}
@Override
public String getId() {
return getName();
}
public String getRepo() {
return repo;
}
public String getBranch() {
return branch;
}
/**
* Branch to which this change would be merged or applied if it were accepted.
*
* @return a “target” or “base” branch
*/
@Override
public SCMHead getTarget() {
return target;
}
}
|
package com.example.batch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
/**
* Created by icttb0 on 06/02/2017.
*/
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {
private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class);
public JobCompletionNotificationListener() {
}
@Override
public void afterJob(JobExecution jobExecution) {
if(jobExecution.getStatus() == BatchStatus.COMPLETED) {
log.info("================================================================");
log.info("Completato Job " + jobExecution.getJobConfigurationName());
log.info("================================================================");
}
}
}
|
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.bluecolored.bluemap.common.web;
import com.flowpowered.math.vector.Vector2i;
import com.flowpowered.math.vector.Vector3f;
import de.bluecolored.bluemap.core.config.MapConfig;
import de.bluecolored.bluemap.core.map.BmMap;
import de.bluecolored.bluemap.core.util.FileUtils;
import de.bluecolored.bluemap.core.util.MathUtils;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.gson.GsonConfigurationLoader;
import org.spongepowered.configurate.loader.ConfigurationLoader;
import org.spongepowered.configurate.serialize.SerializationException;
import java.io.File;
import java.io.IOException;
public class MapSettings {
private final ConfigurationLoader<? extends ConfigurationNode> configLoader;
private ConfigurationNode rootNode;
public MapSettings(File settingsFile) throws IOException {
FileUtils.createFile(settingsFile);
configLoader = GsonConfigurationLoader.builder()
.file(settingsFile)
.build();
load();
}
public void load() throws IOException {
rootNode = configLoader.load();
}
public void save() throws IOException {
configLoader.save(rootNode);
}
public void set(Object value, Object... path) throws SerializationException {
rootNode.node(path).set(value);
}
public Object get(Object... path) {
return rootNode.node(path).raw();
}
public String getString(Object... path) {
return rootNode.node(path).getString();
}
public int getInt(Object... path) {
return rootNode.node(path).getInt();
}
public long getLong(Object... path) {
return rootNode.node(path).getLong();
}
public float getFloat(Object... path) {
return rootNode.node(path).getFloat();
}
public double getDouble(Object... path) {
return rootNode.node(path).getDouble();
}
public String getMapId() {
return getString("world");
}
public void setFrom(BmMap map) throws SerializationException {
Vector2i hiresTileSize = map.getHiresModelManager().getTileGrid().getGridSize();
Vector2i gridOrigin = map.getHiresModelManager().getTileGrid().getOffset();
Vector2i lowresTileSize = map.getLowresModelManager().getTileSize();
Vector2i lowresPointsPerHiresTile = map.getLowresModelManager().getPointsPerHiresTile();
set(hiresTileSize.getX(), "hires", "tileSize", "x");
set(hiresTileSize.getY(), "hires", "tileSize", "z");
set(1, "hires", "scale", "x");
set(1, "hires", "scale", "z");
set(gridOrigin.getX(), "hires", "translate", "x");
set(gridOrigin.getY(), "hires", "translate", "z");
Vector2i pointSize = hiresTileSize.div(lowresPointsPerHiresTile);
Vector2i tileSize = pointSize.mul(lowresTileSize);
set(tileSize.getX(), "lowres", "tileSize", "x");
set(tileSize.getY(), "lowres", "tileSize", "z");
set(pointSize.getX(),"lowres", "scale", "x");
set(pointSize.getY(),"lowres", "scale", "z");
set(pointSize.getX() / 2, "lowres", "translate", "x");
set(pointSize.getY() / 2, "lowres", "translate", "z");
set(map.getWorld().getSpawnPoint().getX(), "startPos", "x");
set(map.getWorld().getSpawnPoint().getZ(), "startPos", "z");
set(map.getWorld().getUUID().toString(), "world");
}
public void setFrom(MapConfig mapConfig) throws SerializationException {
Vector2i startPos = mapConfig.getStartPos();
if (startPos != null) {
set(startPos.getX(), "startPos", "x");
set(startPos.getY(), "startPos", "z");
}
Vector3f skyColor = MathUtils.color3FromInt(mapConfig.getSkyColor());
set(skyColor.getX(), "skyColor", "r");
set(skyColor.getY(), "skyColor", "g");
set(skyColor.getZ(), "skyColor", "b");
set(mapConfig.getAmbientLight(), "ambientLight");
setName(mapConfig.getName(), mapConfig.getId());
}
public void setOrdinal(int ordinal) throws SerializationException {
set(ordinal, "ordinal");
}
public int getOrdinal(String mapId) {
return getInt("ordinal");
}
public void setName(String name, String mapId) throws SerializationException {
set(name, "name");
}
public String getName(String mapId) {
return getString("name");
}
}
|
// Targeted by JavaCPP version 1.5.7-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.ale;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.ale.global.ale.*;
@Opaque @Properties(inherit = org.bytedeco.ale.presets.ale.class)
public class Deserializer extends Pointer {
/** Empty constructor. Calls {@code super((Pointer)null)}. */
public Deserializer() { super((Pointer)null); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public Deserializer(Pointer p) { super(p); }
}
|
package frc.robot;
import edu.wpi.first.math.kinematics.DifferentialDriveKinematics;
/**
* The Constants class provides a convenient place for teams to hold robot-wide numerical or boolean
* constants. This class should not be used for any other purpose. All constants should be declared
* globally (i.e. public static). Do not put anything functional in this class.
*
* <p>It is advised to statically import this class (or one of its inner classes) wherever the
* constants are needed, to reduce verbosity.
*/
public final class Constants {
public static class AutoConstants{
public static final int numOfCalls = 50;
public static final double speed = -0.5;
public static final double sideSpeed = 0;
public static final double rotationSpeed = 0;
public static final double kRamseteZeta = 0;
public static final double kRamseteB = 0;
public static int calls = 0;
}
public static class DriveTrainConstants{
public static final int rightFrontFalconID = 1;
public static final int rightBackFalconID = 4;
public static final int leftFrontFalconID = 2;
public static final int leftBackFalconID = 3;
//Logitech Controller - Ryan
// public static final int forward_axis = 1;
// public static final int side_axis = 0;
// public static final int rotation_axis = 4;
public static final int forward_axis = 1;
public static final int side_axis = 0;
public static final int rotation_axis = 4;
}
public static class ClimbingConstants{
public static final int climbMotor = 12;
public static final int armRotationMotor = 14;
public static final int armElevationMotorLeft = 15;
public static final int armElevationMotorRight = 16;
public static final double armRotationSensitivity = .25;
public static final double staticArmRotationSensitivity = .75;
public static final double armHeightSensitivity = .75;
public static final double climbSensitivity = 1;
public static final double climbReleaseSensitivity = .75;
public static final int rotateAxis = 0;
public static final int climbAxis = 1;
}
public static class OI_Constants{
public static final int m_joystickID = 0;//Logitech Controller
public static final int c_joystickID = 1;//Flight Joystick Climb
public static final int i_joystickID = 2;//Flight Joystick Intake
public static final int armClimbButton = 1;
public static final int climbButton = 2;
public static final int prepClimbButton = 4;
public static final int rotateClimberButton = 2;
// public static final int rotateStaticHookButton = 6;
public static final int runIntakeButton = 1;
public static final int rotateIntakeHeadButton = 2;
}
public static class IntakeConstants{
public static final int intakeMotorID = 7;
public static final int intakeHeadMotorID = 6;
public static final int intakeRotationMotorID = 10;
public static final int maxRevolutions = 48;
public static int location = 0;
public static final double armSens = 0.25;
public static final int intakeArmRotateAxis = 1;
public static final int intakeHeadRotateAxis = 0;
}
public static class DriveConstants{
public static final double ksVolts = 0;
public static final double kvVoltSecondsPerMeter = 0;
public static final double kaVoltSecondsSquaredPerMeter = 0;
public static final double kPDriveVel = 0;
public static final DifferentialDriveKinematics kDriveKinematics =
new DifferentialDriveKinematics(.503);
}
/**Does NOT work */
// public static class AccelCurve{
// public static final int x = 0;
// public static final double sensitive = 0;
// public static final double exponent = 3;
// public static final double startPoint = 50;
// public static final double m = Math.pow(startPoint, (1/exponent))/startPoint;
// public static final double sub_amount = m*startPoint;
// public static final double add_amount = startPoint;
// example of curve, this is actually implemented in the subsystem/command
// public static final double accelCurve = (Math.pow((m*x-sub_amount), exponent)+add_amount);
// }
}
/**
* Motor Name ID
*
* Front Right Drivetrain motor: 1
* Front Left Drivetrain motor: 3
* Back Right Drivetrain motor: 2
* Back Left Drivetrain motor: 4
*
* Altiude Climb Motor: ???
* Climb Tower Height Motor: 14 & 20
*
* Intake Motor: 6
* Intake Leg Motor: 9
* Intake Head Motor: 10
*
*/
/**
* Button Mapping
* Button Use / Name Button ID
* TBD 0
* TBD 1
* TBD 2
* TBD 3
* TBD 4
* TBD 5
* TBD 6
* TBD 7
* TBD 8
* TBD 9
* TBD 10
* TBD 11
* TBD 12
*
*
* Joystick Axis Uses
* Logitech
* Drive Forward 1 - Left Joystick - Y
* Drive Sideways 2 - Left Joystick - X
* Rotate 3 - Right Joystick - X
* TBD 4 - Right Joystick - Y
* TBD 5 - DPad - X
* TBD 6 - DPad - Y
*
* Flight Controller
* TBD 1 - X Axis
* TBD 2 - Y Axis
* TBD 3 - Twist
* TBD 4 - Power Slider
* TBD 5 - Hat - X
* TBD 6 - Hat - Y
*
*/
|
package com.conveyal.datatools.editor.models.transit;
public enum AttributeAvailabilityType {
UNKNOWN,
AVAILABLE,
UNAVAILABLE
}
|
package com.github.informramiz.popularmovies;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.github.informramiz.popularmovies.model.Movie;
import com.github.informramiz.popularmovies.utils.NetworkUtils;
import com.squareup.picasso.Picasso;
import java.net.URISyntaxException;
import java.net.URL;
public class MovieDetailActivity extends AppCompatActivity {
public static final String EXTRA_MOVIE = "movie";
private ImageView mPosterImageView;
private TextView mOverviewTextView;
private TextView mAverageVoteTextView;
private TextView mReleaseDateTextView;
private Movie mMovie;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
Intent intentThatStartThisActivity = getIntent();
if (intentThatStartThisActivity.hasExtra(EXTRA_MOVIE)) {
mMovie = intentThatStartThisActivity.getParcelableExtra(EXTRA_MOVIE);
} else {
Toast.makeText(this, R.string.error_msg_invalid_movie_data, Toast.LENGTH_SHORT).show();
finish();
return;
}
mPosterImageView = findViewById(R.id.iv_movie_poster);
mOverviewTextView = findViewById(R.id.tv_overview);
mAverageVoteTextView = findViewById(R.id.tv_vote_average);
mReleaseDateTextView = findViewById(R.id.tv_release_date);
loadMovieDataIntoViews();
}
private void loadMovieDataIntoViews() {
//set title of movie as screen title
setTitle(mMovie.getTitle());
//load movie poster image using Picasso
URL posterImageURL = NetworkUtils.buildImageUrl(mMovie.getPosterPath());
try {
Uri posterImageUri = Uri.parse(posterImageURL.toURI().toString());
Picasso.get().load(posterImageUri).into(mPosterImageView);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//set synopsis (overview)
mOverviewTextView.setText(mMovie.getOverview());
//set user rating (voteAverage)
mAverageVoteTextView.setText(String.valueOf(mMovie.getVoteAverage()));
//set release date
mReleaseDateTextView.setText(mMovie.getReleaseDate());
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|plan
operator|.
name|ptf
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|plan
operator|.
name|Explain
import|;
end_import
begin_class
specifier|public
specifier|abstract
class|class
name|WindowExpressionDef
extends|extends
name|PTFExpressionDef
block|{
specifier|private
name|String
name|alias
decl_stmt|;
annotation|@
name|Explain
argument_list|(
name|displayName
operator|=
literal|"alias"
argument_list|)
specifier|public
name|String
name|getAlias
parameter_list|()
block|{
return|return
name|alias
return|;
block|}
specifier|public
name|void
name|setAlias
parameter_list|(
name|String
name|alias
parameter_list|)
block|{
name|this
operator|.
name|alias
operator|=
name|alias
expr_stmt|;
block|}
block|}
end_class
end_unit
|
/**
* 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 greycatTest.internal.utility;
import greycat.utility.L3Map;
import org.junit.Assert;
import org.junit.Test;
public class L3MapTest {
@Test
public void test() {
L3Map map = new L3Map(false);
map.put(1, 1, 1, -1);
Assert.assertTrue(map.contains(1, 1, 1));
Assert.assertEquals(1, map.size());
for (int i = 0; i < 100; i++) {
map.put(i, i ^ 2, i ^ 3, -1);
}
Assert.assertEquals(101, map.size());
map.put(1, 1, 1, -1);
Assert.assertEquals(101, map.size());
for (int i = 0; i < 100; i++) {
Assert.assertTrue(map.contains(i, i ^ 2, i ^ 3));
}
Assert.assertTrue(!map.contains(100,100,100));
}
}
|
package net.ros.common.ore;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.ros.common.block.BlockVeinOre;
import net.ros.common.init.ROSItems;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Ores
{
public static final List<Mineral> MINERALS;
public static final Mineral IRON;
public static final Mineral GOLD;
public static final Mineral REDSTONE;
public static final Mineral ZINC;
public static final Mineral COPPER;
public static final Mineral TIN;
public static final Mineral NICKEL;
public static final Mineral LEAD;
public static final List<Ore> ORES;
public static final Ore SPHALERITE;
public static final Ore CHALCOPYRITE;
public static final Ore MALACHITE;
public static final Ore TETRAHEDRITE;
public static final Ore CASSITERITE;
public static final Ore TEALLITE;
public static final Ore PENTLANDITE;
public static final Ore GARNIERITE;
public static final Ore LATERITE;
public static final Ore GOLD_ORE;
public static final Ore REDSTONE_ORE;
static
{
MINERALS = new ArrayList<>();
IRON = new Mineral("iron", EnumRarity.COMMON);
GOLD = new Mineral("gold", EnumRarity.UNCOMMON);
REDSTONE = new Mineral("redstone", EnumRarity.COMMON);
ZINC = new Mineral("zinc", EnumRarity.COMMON);
COPPER = new Mineral("copper", EnumRarity.COMMON);
TIN = new Mineral("tin", EnumRarity.COMMON);
NICKEL = new Mineral("nickel", EnumRarity.COMMON);
LEAD = new Mineral("lead", EnumRarity.COMMON);
MINERALS.addAll(Arrays.asList(IRON, GOLD, REDSTONE, ZINC, COPPER, TIN, NICKEL, LEAD));
ORES = new ArrayList<>();
SPHALERITE = Ore.builder().name("sphalerite")
.toolLevel(1).hardness(2.0F).resistance(5.0F)
.slag(Slag.FERROUS)
.mineral(ZINC, 0.6f).mineral(IRON, 0.3f).build();
CHALCOPYRITE = Ore.builder().name("chalcopyrite")
.toolLevel(1).hardness(2.0F).resistance(5.0F)
.slag(Slag.COPPER)
.mineral(COPPER, 0.45f).mineral(IRON, 0.3f).build();
MALACHITE = Ore.builder().name("malachite")
.toolLevel(1).hardness(2.0F).resistance(5.0F)
.slag(Slag.COPPER)
.mineral(COPPER, 0.3f).build();
TETRAHEDRITE = Ore.builder().name("tetrahedrite")
.toolLevel(1).hardness(2.0F).resistance(5.0F)
.slag(Slag.COPPER)
.mineral(COPPER, 0.7f).mineral(IRON, 0.1f).build();
CASSITERITE = Ore.builder().name("cassiterite")
.toolLevel(1).hardness(2.0F).resistance(5.0F)
.slag(Slag.TIN)
.mineral(TIN, 0.8f).build();
TEALLITE = Ore.builder().name("teallite")
.toolLevel(1).hardness(2.0F).resistance(5.0F)
.slag(Slag.TIN)
.mineral(TIN, 0.4f).mineral(LEAD, 0.3f).build();
PENTLANDITE = Ore.builder().name("pentlandite")
.toolLevel(1).hardness(2.0F).resistance(5.0F)
.slag(Slag.FERROUS)
.mineral(IRON, 0.4f).mineral(NICKEL, 0.4f).build();
GARNIERITE = Ore.builder().name("garnierite")
.toolLevel(1).hardness(2.0F).resistance(5.0F)
.slag(Slag.FERROUS)
.mineral(IRON, 0.07f).mineral(NICKEL, 0.75f).build();
LATERITE = Ore.builder().name("laterite")
.toolLevel(1).hardness(2.0F).resistance(5.0F)
.slag(Slag.FERROUS)
.mineral(IRON, 0.2f).mineral(NICKEL, 0.7f).build();
GOLD_ORE = Ore.builder().name("gold")
.toolLevel(2).hardness(3.0F).resistance(5.0F)
.slag(Slag.SHINY)
.mineral(GOLD, 1f).build();
REDSTONE_ORE = Ore.builder().name("redstone")
.toolLevel(2).hardness(2.0F).resistance(5.0F)
.slag(Slag.SPARKLING)
.mineral(REDSTONE, 1f).build();
ORES.addAll(Arrays.asList(SPHALERITE, CHALCOPYRITE, MALACHITE, TETRAHEDRITE, TEALLITE, CASSITERITE,
PENTLANDITE, GARNIERITE, LATERITE, GOLD_ORE, REDSTONE_ORE));
}
public static Optional<Mineral> getMineralFromName(String name)
{
return MINERALS.stream().filter(mineral -> mineral.getName().equalsIgnoreCase(name) ||
mineral.getName().equalsIgnoreCase(name.substring(4))).findAny();
}
public static Optional<Ore> getOreFromState(IBlockState state)
{
if (state.getBlock() instanceof BlockVeinOre)
return getOreFromName(state.getValue(((BlockVeinOre) state.getBlock()).getVARIANTS()));
return Optional.empty();
}
public static Optional<Ore> getOreFromName(String name)
{
return ORES.stream().filter(ore -> ore.getName().equals(name)).findAny();
}
public static ItemStack getRawMineral(Mineral mineral, MineralDensity density)
{
ItemStack rawOre = new ItemStack(ROSItems.RAW_ORE);
rawOre.setItemDamage((MINERALS.indexOf(mineral) * MineralDensity.VALUES.length) + density.ordinal());
return rawOre;
}
public static Fluid toSludge(Ore ore)
{
return FluidRegistry.getFluid("sludge" + ore.getName());
}
public static Optional<Ore> fromSludge(Fluid fluid)
{
return ORES.stream().filter(ore -> fluid.getName().equalsIgnoreCase("sludge" + ore.getName())).findFirst();
}
public static boolean isSludge(Fluid fluid)
{
return ORES.stream().anyMatch(ore -> fluid.getName().equalsIgnoreCase("sludge" + ore.getName()));
}
}
|
package io.github.learnjpahibernate.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import io.github.learnjpahibernate.model.LateInvoice;
@Repository
public interface LateInvoiceRepository extends JpaRepository<LateInvoice, Long> {
}
|
package org.robolectric.shadows;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.robolectric.Shadows.shadowOf;
import android.app.Application;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.R;
import org.robolectric.Shadows;
import org.robolectric.shadow.api.Shadow;
@RunWith(AndroidJUnit4.class)
public class ShadowBitmapDrawableTest {
private final Resources resources =
((Application) ApplicationProvider.getApplicationContext()).getResources();
@Test
public void constructors_shouldSetBitmap() throws Exception {
Bitmap bitmap = Shadow.newInstanceOf(Bitmap.class);
BitmapDrawable drawable = new BitmapDrawable(bitmap);
assertThat(drawable.getBitmap()).isEqualTo(bitmap);
drawable = new BitmapDrawable(resources, bitmap);
assertThat(drawable.getBitmap()).isEqualTo(bitmap);
}
@Test
public void getBitmap_shouldReturnBitmapUsedToDraw() throws Exception {
BitmapDrawable drawable = (BitmapDrawable) resources.getDrawable(R.drawable.an_image);
assertThat(shadowOf(drawable.getBitmap()).getDescription()).isEqualTo("Bitmap for"
+ " resource:org.robolectric:drawable/an_image");
}
@Test
public void mutate_createsDeepCopy() throws Exception {
BitmapDrawable original = (BitmapDrawable) resources.getDrawable(R.drawable.an_image);
Drawable mutated = original.mutate();
assertThat(original).isNotSameInstanceAs(mutated);
assertThat(mutated instanceof BitmapDrawable).isTrue();
assertThat(mutated.getIntrinsicHeight()).isEqualTo(original.getIntrinsicHeight());
assertThat(mutated.getIntrinsicWidth()).isEqualTo(original.getIntrinsicWidth());
assertThat(mutated.getBounds()).isEqualTo(original.getBounds());
}
@Test
public void draw_shouldCopyDescriptionToCanvas() throws Exception {
BitmapDrawable drawable = (BitmapDrawable) resources.getDrawable(R.drawable.an_image);
Canvas canvas = new Canvas();
drawable.draw(canvas);
assertThat(shadowOf(canvas).getDescription()).isEqualTo("Bitmap for"
+ " resource:org.robolectric:drawable/an_image");
}
@Test
public void shouldInheritSourceStringFromDrawableDotCreateFromStream() throws Exception {
InputStream emptyInputStream = new ByteArrayInputStream("".getBytes(UTF_8));
BitmapDrawable drawable = (BitmapDrawable) Drawable.createFromStream(emptyInputStream, "source"
+ " string"
+ " value");
assertThat(shadowOf(drawable).getSource()).isEqualTo("source string value");
}
@Test
public void withColorFilterSet_draw_shouldCopyDescriptionToCanvas() throws Exception {
BitmapDrawable drawable = (BitmapDrawable) resources.getDrawable(R.drawable.an_image);
drawable.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix()));
Canvas canvas = new Canvas();
drawable.draw(canvas);
assertThat(shadowOf(canvas).getDescription()).isEqualTo("Bitmap for"
+ " resource:org.robolectric:drawable/an_image"
+ " with"
+ " ColorMatrixColorFilter<1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0>");
}
@Test
public void shouldStillHaveShadow() throws Exception {
Drawable drawable = resources.getDrawable(R.drawable.an_image);
assertThat(Shadows.shadowOf(drawable).getCreatedFromResId()).isEqualTo(R.drawable.an_image);
}
@Test
public void shouldSetTileModeXY() throws Exception {
BitmapDrawable drawable = (BitmapDrawable) resources.getDrawable(R.drawable.an_image);
drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.MIRROR);
assertThat(drawable.getTileModeX()).isEqualTo(Shader.TileMode.REPEAT);
assertThat(drawable.getTileModeY()).isEqualTo(Shader.TileMode.MIRROR);
}
@Test
public void constructor_shouldSetTheIntrinsicWidthAndHeightToTheWidthAndHeightOfTheBitmap() throws Exception {
Bitmap bitmap = Bitmap.createBitmap(5, 10, Bitmap.Config.ARGB_8888);
BitmapDrawable drawable =
new BitmapDrawable(ApplicationProvider.getApplicationContext().getResources(), bitmap);
assertThat(drawable.getIntrinsicWidth()).isEqualTo(5);
assertThat(drawable.getIntrinsicHeight()).isEqualTo(10);
}
@Test
public void constructor_shouldAcceptNullBitmap() throws Exception {
assertThat(
new BitmapDrawable(
ApplicationProvider.getApplicationContext().getResources(), (Bitmap) null))
.isNotNull();
}
}
|
/*
* Copyright (C) 2015 Noorq, 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 model;
import com.noorq.casser.mapping.annotation.ClusteringColumn;
import com.noorq.casser.mapping.annotation.Index;
import com.noorq.casser.mapping.annotation.PartitionKey;
import com.noorq.casser.mapping.annotation.Table;
@Table
public interface Subscription {
@PartitionKey
String applicationId();
@ClusteringColumn
String email();
@Index
boolean active();
}
|
package org.eclipse.rcp.intro.dialogs.standard.handler;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;
public class OpenDialog extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
Shell shell = HandlerUtil.getActiveWorkbenchWindow(event).getShell();
FileDialog fileDialog = new FileDialog(shell);
fileDialog.setText("Select File");
fileDialog.setFilterExtensions(new String[] { "*.txt" });
fileDialog.setFilterNames(new String[] { "Textfiles(*.txt)" });
String selected = fileDialog.open();
System.out.println(selected);
DirectoryDialog dirDialog = new DirectoryDialog(shell);
dirDialog.setText("Select your home directory");
String selectedDir = dirDialog.open();
System.out.println(selectedDir);
FontDialog fontDialog = new FontDialog(shell);
fontDialog.setText("Select your favorite font");
FontData selectedFont = fontDialog.open();
System.out.println(selectedFont);
ColorDialog colorDialog = new ColorDialog(shell);
colorDialog.setText("Select your favorite color");
RGB selectedColor = colorDialog.open();
System.out.println(selectedColor);
MessageDialog.openConfirm(shell, "Confirm", "Please confirm");
MessageDialog.openError(shell, "Error", "Error occured");
MessageDialog.openInformation(shell, "Info", "Info for you");
MessageDialog.openQuestion(shell, "Question", "Really, really?");
MessageDialog.openWarning(shell, "Warning", "I warn you");
return null;
}
}
|
/*
* Copyright 2008-2009 the original 赵永春(zyc@hasor.net).
*
* 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.dev.toos.constcode.ui.handler.vartree;
import org.dev.toos.constcode.model.bridge.AbstractBridge;
import org.dev.toos.constcode.ui.handler.AbstractAdapter;
import org.dev.toos.constcode.ui.view.ConstCodeViewPage;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
/**
*
* @version : 2013-2-3
* @author 赵永春 (zyc@byshell.org)
*/
public class VarTreeEditAdapter extends AbstractAdapter implements SelectionListener {
public VarTreeEditAdapter(ConstCodeViewPage pageObject) {
super(pageObject);
}
@Override
public void widgetSelected(SelectionEvent e) {
TreeViewer treeViewer = this.getViewPage().getVarTreeViewer();
TreeSelection selection = (TreeSelection) treeViewer.getSelection();
if (selection.isEmpty() == true)
return;
AbstractBridge bridge = (AbstractBridge) selection.getFirstElement();
if (bridge.readOnly() == true)
return;
bridge.doEdit();
treeViewer.editElement(bridge, 0);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
}
|
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.config.manager.testingservices.threadpool;
public interface TestingThreadPoolConfigMXBean {
public int getThreadCount();
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package watermaze_ver_3_0;
import java.util.Arrays;
import javax.swing.JOptionPane;
/**
*
* @author Balaji
*/
class TraceData extends Object{
double[] xData = null;
double[] yData = null;
int CurrPos = 0;
int DataLength = 0;
int ActLength =0;
//boolean Y_Only = false;
public TraceData( int length){
if (length > 0){
DataLength = length;
xData = new double[DataLength];
yData = new double[DataLength];
}
}
public TraceData( double[] x, double[] y){
if( x != null && y != null){
xData = (double[])x.clone();
yData = (double[])y.clone();
DataLength = Math.min(xData.length,yData.length);
}
}
public boolean addData(double x, double y){
if (CurrPos >= DataLength){
JOptionPane.showMessageDialog(null,"OOPS! I am full you can not add anymore to me");
return false;
}
xData[CurrPos] = x;
yData[CurrPos] = y;
CurrPos++;
ActLength = CurrPos > ActLength ? CurrPos : ActLength;
return true;
}
public boolean addXData(double x, int pos){
if( pos >= xData.length)
return false;
xData[pos] = x;
return true;
}
public boolean addData(double x){
return addData(x, CurrPos);
}
public boolean addYData(double y, int pos){
if(pos >= yData.length)
return false;
yData[pos] = y;
return true;
}
public double getX(int pos){
if(pos < DataLength)
return xData[pos];
return xData[DataLength];
}
public double getY(int pos){
if(pos < DataLength) return yData[pos];
return yData[DataLength];
}
public double[] getXY(int pos){
double[] XY = new double[2];
if (pos < DataLength){
XY[1] = xData[pos];
XY[2] = yData[pos];
}
else{
XY[1] = xData[DataLength];
XY[2] = yData[DataLength];
}
return XY;
}
public boolean setPosition(int pos){
if(pos < DataLength){
CurrPos = pos;
return true;
}
return false;
}
public int getPosition(){
return CurrPos;
}
public int getDataLength(){
return DataLength;
}
public double[] getX(){
return (double [])xData.clone();
}
public double[] getY(){
return (double [])yData.clone();
}
public double[] getX(boolean trimmed){
return Arrays.copyOf(xData, ActLength);
}
public double[] getY(boolean trimmed){
return Arrays.copyOf(yData, ActLength);
}
public boolean setLength(int length){
if (DataLength != 0)
return false;
if (length > 0){
DataLength = length;
xData = new double[DataLength];
yData = new double[DataLength];
CurrPos = ActLength = 0;
return true;
}
return false;
}
public void OverrideLength(int length){
if (length == 0){
xData = null;
yData = null;
return;
}
DataLength = length;
xData = new double[DataLength];
yData = new double[DataLength];
CurrPos = ActLength = 0;
return;
}
}
|
//Convert infix into postfix
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG{
public static void main(String[] args)throws java.lang.Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-->0){
String str = br.readLine().trim();
convert(str);
}
}
static int prec(char c){
switch(c){
case '^':
return 3;
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
}
return -1;
}
static void convert(String str){
int n = str.length();
String result = "";
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i<n; i++){
char c = str.charAt(i);
if(Character.isLetterOrDigit(c)){
result += c;
}
else if( c == '(' ){
stack.push(c);
}
else if(c == ')'){
while( !stack.isEmpty() && stack.peek() != '('){
result += stack.pop();
}
if(!stack.isEmpty())
stack.pop();
}
else {
while(!stack.isEmpty() && prec(c) <= prec(stack.peek())) {
result += stack.pop();
}
stack.push(c);
}
}
while(!stack.isEmpty()){
result += stack.pop();
}
System.out.println(result);
}
}
|
package com.example.bakingapp.adapters;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.bakingapp.R;
import com.example.bakingapp.activities.RecipeActivity;
import com.example.bakingapp.fragments.DetailFragment;
import com.example.bakingapp.models.Steps;
import java.util.ArrayList;
import androidx.recyclerview.widget.RecyclerView;
public class ShortDescAdapter extends RecyclerView.Adapter<ShortDescAdapter.ViewHolder> {
private static final String TAG = ShortDescAdapter.class.getSimpleName();
private final ArrayList<String> shortDescriptionList;
private final ArrayList<Steps> stepList;
private DetailFragment detailFragment;
private Context context;
public ShortDescAdapter(ArrayList<String> shortDescriptionList, ArrayList<Steps> stepList) {
this.shortDescriptionList = shortDescriptionList;
this.stepList = stepList;
}
@Override
public ShortDescAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
context = viewGroup.getContext();
int layoutIdForListItem = R.layout.short_description_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layoutIdForListItem, viewGroup, false);
return new ShortDescAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(ShortDescAdapter.ViewHolder holder, int position) {
holder.shortDescriptionTextView.setText(shortDescriptionList.get(position));
if (!RecipeActivity.isTablet(context))
holder.shortDescriptionTextView.setOnClickListener(v ->
{
detailFragment = new DetailFragment();
Bundle bundle = new Bundle();
bundle.putInt("clickedPosition", position);
detailFragment.setArguments(bundle);
((RecipeActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.testframe, detailFragment).commit();
((RecipeActivity) context).findViewById(R.id.recipe_card).setVisibility(View.GONE);
});
else {
holder.shortDescriptionTextView.setOnClickListener(v ->
{
detailFragment = new DetailFragment();
Bundle bundle = new Bundle();
bundle.putInt("clickedPosition", position);
detailFragment.setArguments(bundle);
((RecipeActivity) context).getSupportFragmentManager().beginTransaction().replace(R.id.tabFrameLayout600, detailFragment).commit();
});
}
}
@Override
public int getItemCount() {
if (shortDescriptionList == null)
return 0;
return shortDescriptionList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView shortDescriptionTextView;
public ViewHolder(View itemView) {
super(itemView);
shortDescriptionTextView = itemView.findViewById(R.id.mShortDescription);
}
}
}
|
package com.tensquare.base.controller;
import com.tensquare.base.entity.Label;
import com.tensquare.base.service.ILabelService;
import com.tensquare.common.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* @Author HanLei
* @Date 2020-03-12
*/
@Slf4j
@CrossOrigin
@RestController
public class LabelController {
@Resource
private ILabelService labelService;
/**
* 增加标签
*/
@PostMapping("/label")
public Result addLabel(@RequestBody Label label) {
return labelService.addLabel(label);
}
/**
* 标签全部列表
*/
@GetMapping("/label")
public Result getLabelList() {
return labelService.getLabelList();
}
/**
* 推荐标签列表
*/
@GetMapping("/label/toplist")
public Result getLabelTopList() {
return labelService.getLabelTopList();
}
/**
* 有效标签列表
*/
@GetMapping("/label/list")
public Result getNormalLabelList() {
return labelService.getNormalLabelList();
}
/**
* 根据ID查询
*/
@GetMapping("/label/{labelId}")
public Result getLabelById(@PathVariable String labelId) {
return labelService.getLabelById(labelId);
}
/**
* 修改标签
*/
@PutMapping("/label/{labelId}")
public Result editLabel(@PathVariable String labelId, @RequestBody Label label) {
return labelService.editLabel(labelId, label);
}
/**
* 根据ID删除
*/
@DeleteMapping("/label/{labelId}")
public Result deleteLabel(@PathVariable String labelId) {
return labelService.deleteLabel(labelId);
}
/**
* 标签分页
*/
@PostMapping("/label/search/{pageNo}/{pageSize}")
public Result getLabelListWithPage(@RequestBody Label label, @PathVariable Integer pageNo, @PathVariable Integer pageSize) {
return labelService.getLabelListWithPage(label, pageNo, pageSize);
}
/**
* 查询标签列表
*/
@PostMapping("/label/search")
public Result getLabelByParam(@RequestBody Label label) {
return labelService.getLabelByParam(label);
}
}
|
/*
* Copyright 2002-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 org.springframework.web.servlet.view;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.lang.Nullable;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.View;
/**
* A {@link org.springframework.web.servlet.ViewResolver} implementation that uses
* bean definitions in a {@link ResourceBundle}, specified by the bundle basename.
*
* <p>The bundle is typically defined in a properties file, located in the classpath.
* The default bundle basename is "views".
*
* <p>This {@code ViewResolver} supports localized view definitions, using the
* default support of {@link java.util.PropertyResourceBundle}. For example, the
* basename "views" will be resolved as class path resources "views_de_AT.properties",
* "views_de.properties", "views.properties" - for a given Locale "de_AT".
*
* <p>Note: This {@code ViewResolver} implements the {@link Ordered} interface
* in order to allow for flexible participation in {@code ViewResolver} chaining.
* For example, some special views could be defined via this {@code ViewResolver}
* (giving it 0 as "order" value), while all remaining views could be resolved by
* a {@link UrlBasedViewResolver}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see java.util.ResourceBundle#getBundle
* @see java.util.PropertyResourceBundle
* @see UrlBasedViewResolver
*/
public class ResourceBundleViewResolver extends AbstractCachingViewResolver
implements Ordered, InitializingBean, DisposableBean {
/** The default basename if no other basename is supplied. */
public static final String DEFAULT_BASENAME = "views";
private String[] basenames = new String[] {DEFAULT_BASENAME};
private ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader();
@Nullable
private String defaultParentView;
@Nullable
private Locale[] localesToInitialize;
/* Locale -> BeanFactory */
private final Map<Locale, BeanFactory> localeCache = new HashMap<>();
/* List of ResourceBundle -> BeanFactory */
private final Map<List<ResourceBundle>, ConfigurableApplicationContext> bundleCache = new HashMap<>();
private int order = Ordered.LOWEST_PRECEDENCE; // default: same as non-Ordered
/**
* Set a single basename, following {@link java.util.ResourceBundle} conventions.
* The default is "views".
* <p>{@code ResourceBundle} supports different suffixes. For example,
* a base name of "views" might map to {@code ResourceBundle} files
* "views", "views_en_au" and "views_de".
* <p>Note that ResourceBundle names are effectively classpath locations: As a
* consequence, the JDK's standard ResourceBundle treats dots as package separators.
* This means that "test.theme" is effectively equivalent to "test/theme",
* just like it is for programmatic {@code java.util.ResourceBundle} usage.
* @see #setBasenames
* @see java.util.ResourceBundle#getBundle(String)
*/
public void setBasename(String basename) {
setBasenames(basename);
}
/**
* Set an array of basenames, each following {@link java.util.ResourceBundle}
* conventions. The default is a single basename "views".
* <p>{@code ResourceBundle} supports different suffixes. For example,
* a base name of "views" might map to {@code ResourceBundle} files
* "views", "views_en_au" and "views_de".
* <p>The associated resource bundles will be checked sequentially
* when resolving a message code. Note that message definitions in a
* <i>previous</i> resource bundle will override ones in a later bundle,
* due to the sequential lookup.
* <p>Note that ResourceBundle names are effectively classpath locations: As a
* consequence, the JDK's standard ResourceBundle treats dots as package separators.
* This means that "test.theme" is effectively equivalent to "test/theme",
* just like it is for programmatic {@code java.util.ResourceBundle} usage.
* @see #setBasename
* @see java.util.ResourceBundle#getBundle(String)
*/
public void setBasenames(String... basenames) {
this.basenames = basenames;
}
/**
* Set the {@link ClassLoader} to load resource bundles with.
* Default is the thread context {@code ClassLoader}.
*/
public void setBundleClassLoader(ClassLoader classLoader) {
this.bundleClassLoader = classLoader;
}
/**
* Return the {@link ClassLoader} to load resource bundles with.
* <p>Default is the specified bundle {@code ClassLoader},
* usually the thread context {@code ClassLoader}.
*/
protected ClassLoader getBundleClassLoader() {
return this.bundleClassLoader;
}
/**
* Set the default parent for views defined in the {@code ResourceBundle}.
* <p>This avoids repeated "yyy1.(parent)=xxx", "yyy2.(parent)=xxx" definitions
* in the bundle, especially if all defined views share the same parent.
* <p>The parent will typically define the view class and common attributes.
* Concrete views might simply consist of an URL definition then:
* a la "yyy1.url=/my.jsp", "yyy2.url=/your.jsp".
* <p>View definitions that define their own parent or carry their own
* class can still override this. Strictly speaking, the rule that a
* default parent setting does not apply to a bean definition that
* carries a class is there for backwards compatibility reasons.
* It still matches the typical use case.
*/
public void setDefaultParentView(String defaultParentView) {
this.defaultParentView = defaultParentView;
}
/**
* Specify Locales to initialize eagerly, rather than lazily when actually accessed.
* <p>Allows for pre-initialization of common Locales, eagerly checking
* the view configuration for those Locales.
*/
public void setLocalesToInitialize(Locale... localesToInitialize) {
this.localesToInitialize = localesToInitialize;
}
/**
* Specify the order value for this ViewResolver bean.
* <p>The default value is {@code Ordered.LOWEST_PRECEDENCE}, meaning non-ordered.
* @see org.springframework.core.Ordered#getOrder()
*/
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
/**
* Eagerly initialize Locales if necessary.
* @see #setLocalesToInitialize
*/
@Override
public void afterPropertiesSet() throws BeansException {
if (this.localesToInitialize != null) {
for (Locale locale : this.localesToInitialize) {
initFactory(locale);
}
}
}
@Override
protected View loadView(String viewName, Locale locale) throws Exception {
BeanFactory factory = initFactory(locale);
try {
return factory.getBean(viewName, View.class);
}
catch (NoSuchBeanDefinitionException ex) {
// Allow for ViewResolver chaining...
return null;
}
}
/**
* Initialize the View {@link BeanFactory} from the {@code ResourceBundle},
* for the given {@link Locale locale}.
* <p>Synchronized because of access by parallel threads.
* @param locale the target {@code Locale}
* @return the View factory for the given Locale
* @throws BeansException in case of initialization errors
*/
protected synchronized BeanFactory initFactory(Locale locale) throws BeansException {
// Try to find cached factory for Locale:
// Have we already encountered that Locale before?
if (isCache()) {
BeanFactory cachedFactory = this.localeCache.get(locale);
if (cachedFactory != null) {
return cachedFactory;
}
}
// Build list of ResourceBundle references for Locale.
List<ResourceBundle> bundles = new LinkedList<>();
for (String basename : this.basenames) {
ResourceBundle bundle = getBundle(basename, locale);
bundles.add(bundle);
}
// Try to find cached factory for ResourceBundle list:
// even if Locale was different, same bundles might have been found.
if (isCache()) {
BeanFactory cachedFactory = this.bundleCache.get(bundles);
if (cachedFactory != null) {
this.localeCache.put(locale, cachedFactory);
return cachedFactory;
}
}
// Create child ApplicationContext for views.
GenericWebApplicationContext factory = new GenericWebApplicationContext();
factory.setParent(getApplicationContext());
factory.setServletContext(getServletContext());
// Load bean definitions from resource bundle.
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(factory);
reader.setDefaultParentBean(this.defaultParentView);
for (ResourceBundle bundle : bundles) {
reader.registerBeanDefinitions(bundle);
}
factory.refresh();
// Cache factory for both Locale and ResourceBundle list.
if (isCache()) {
this.localeCache.put(locale, factory);
this.bundleCache.put(bundles, factory);
}
return factory;
}
/**
* Obtain the resource bundle for the given basename and {@link Locale}.
* @param basename the basename to look for
* @param locale the {@code Locale} to look for
* @return the corresponding {@code ResourceBundle}
* @throws MissingResourceException if no matching bundle could be found
* @see java.util.ResourceBundle#getBundle(String, java.util.Locale, ClassLoader)
*/
protected ResourceBundle getBundle(String basename, Locale locale) throws MissingResourceException {
return ResourceBundle.getBundle(basename, locale, getBundleClassLoader());
}
/**
* Close the bundle View factories on context shutdown.
*/
@Override
public void destroy() throws BeansException {
for (ConfigurableApplicationContext factory : this.bundleCache.values()) {
factory.close();
}
this.localeCache.clear();
this.bundleCache.clear();
}
}
|
/*
* Copyright (c) 2006 Hyperic, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hyperic.sigar;
import java.util.HashMap;
import java.io.IOException;
import java.io.File;
/**
* Helper class to build a map of mounted file systems.
*/
public class FileSystemMap extends HashMap {
/**
* FileSystemMap is read-only, this method is unsupported.
* @see #init
*/
public Object put(Object key, Object value) {
throw new UnsupportedOperationException();
}
/**
* Populate the map. FileSystem.getDirName is used as the map key.
*/
public void init(FileSystem[] fslist) {
super.clear();
for (int i=0; i<fslist.length; i++) {
super.put(fslist[i].getDirName(), fslist[i]);
}
}
public FileSystem getFileSystem(String name) {
return (FileSystem)get(name);
}
public boolean isMounted(String name) {
return (get(name) != null);
}
/**
* Find the file system the given file or directory is within.
* @return FileSystem or null if file or directory name does not exist.
*/
public FileSystem getMountPoint(String name) {
FileSystem fs = getFileSystem(name);
if (fs != null) {
return fs;
}
File dir = new File(name);
if (!dir.exists()) {
return null;
}
try {
dir = dir.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException(e.getMessage());
}
if (!dir.isDirectory()) {
dir = dir.getParentFile();
}
do {
fs = getFileSystem(dir.toString());
if (fs != null) {
return fs;
}
dir = dir.getParentFile();
} while (dir != null);
return null;
}
}
|
package com.andrewkats.katsprint.data;
public enum Paper
{
// Add additional paper sizes here.
// Use PRICE_INVALID to set as unavaliable.
A4(Price.A4_BLACK_SINGLE, Price.A4_BLACK_DOUBLE, Price.A4_COLOR_SINGLE, Price.A4_COLOR_DOUBLE),
NONE(Price.PRICE_INVALID, Price.PRICE_INVALID, Price.PRICE_INVALID, Price.PRICE_INVALID);
// The default paper size to prompt if no size is found.
public final static Paper DEFAULT_SIZE = A4;
// Add additional print types here.
// NOTE: We are using "COLOR" to increase readability.
public final String NAME;
public final Type BLACK;
public final Type COLOR;
private Paper(int blackSingle, int blackDouble, int colorSingle, int colorDouble)
{
NAME = name();
this.BLACK = new Type(NAME + " BLACK", blackSingle, blackDouble);
this.COLOR = new Type(NAME + " COLOR", colorSingle, colorDouble);
}
public final class Type
{
public final String NAME;
public final Side SINGLE;
public final Side DOUBLE;
private Type(String NAME, int priceSingle, int priceDouble)
{
this.NAME = NAME;
this.SINGLE = new Side(NAME + " SINGLE", priceSingle);
this.DOUBLE = new Side(NAME + " DOUBLE", priceDouble);
}
public final class Side
{
public final String NAME;
public final int PRICE;
private Side(String NAME, int tPrice)
{
if(tPrice <= 0) tPrice = Price.PRICE_INVALID;
this.NAME = NAME;
this.PRICE = tPrice;
}
}
}
}
|
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.identitymodel.tokens;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import system.identitymodel.tokens.SecurityTokenValidationException;
/**
* The base .NET class managing System.IdentityModel.Tokens.AudienceUriValidationFailedException, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089. Extends {@link NetException}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.IdentityModel.Tokens.AudienceUriValidationFailedException" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.IdentityModel.Tokens.AudienceUriValidationFailedException</a>
*/
public class AudienceUriValidationFailedException extends SecurityTokenValidationException {
/**
* Fully assembly qualified name: System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
*/
public static final String assemblyFullName = "System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
/**
* Assembly name: System.IdentityModel
*/
public static final String assemblyShortName = "System.IdentityModel";
/**
* Qualified class name: System.IdentityModel.Tokens.AudienceUriValidationFailedException
*/
public static final String className = "System.IdentityModel.Tokens.AudienceUriValidationFailedException";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
JCNativeException jcNativeException = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException jce) {
JCOReflector.writeLog(jce);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public AudienceUriValidationFailedException() {
super();
}
public AudienceUriValidationFailedException(Object instance) {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else if (instance instanceof JCNativeException) {
jcNativeException = (JCNativeException) instance;
classInstance = jcNativeException.getCLRException();
}
}
public AudienceUriValidationFailedException(String message) {
super(message);
}
public AudienceUriValidationFailedException(NetException cause) {
super(cause);
}
public AudienceUriValidationFailedException(String message, NetException cause) {
super(message, cause);
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link AudienceUriValidationFailedException}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link AudienceUriValidationFailedException} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static AudienceUriValidationFailedException cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new AudienceUriValidationFailedException(from.getJCOInstance());
}
// Constructors section
// Methods section
// Properties section
}
|
/*
* Protocoder
* A prototyping platform for Android devices
*
* Victor Diaz Barrales victormdb@gmail.com
*
* Copyright (C) 2014 Victor Diaz
* Copyright (C) 2013 Motorola Mobility LLC
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.protocoderrunner.apprunner.api.other;
import android.app.Activity;
import android.content.Context;
import org.protocoderrunner.apidoc.annotation.APIMethod;
import org.protocoderrunner.apidoc.annotation.APIParam;
import org.protocoderrunner.apprunner.PInterface;
import org.protocoderrunner.apprunner.ProtocoderScript;
import org.protocoderrunner.utils.FFT;
public class SignalUtils extends PInterface {
FFT fft;
double im[];
public SignalUtils(Context a, int n) {
super(a);
fft = new FFT(n);
im = new double[n];
for(int i = 0; i < n; i++){
im[i] = 0;
}
}
public LowPass lowpass() {
return null;
}
@ProtocoderScript
@APIMethod(description = "", example = "")
@APIParam(params = { "function()" })
public double[] fft(double[] re) {
fft.fft(re, im.clone());
return re;
}
class LowPass {
int n;
float[] vals;
float sum = 0.0f;
public LowPass(int n) {
this.n = n;
vals = new float[n];
}
public float smooth(float newVal) {
for (int i = 0; i < vals.length; i++) {
sum = +vals[i];
// shift to the left
if (i < vals.length - 1) {
vals[i] = vals[i + 1];
} else {
vals[i] = newVal;
}
}
return sum / n;
}
}
}
|
/*
* Licensed to ElasticSearch and Shay Banon 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.common.xcontent.support;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.unit.TimeValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
*/
public class XContentMapValues {
/**
* Extracts raw values (string, int, and so on) based on the path provided returning all of them
* as a single list.
*/
public static List<Object> extractRawValues(String path, Map<String, Object> map) {
List<Object> values = Lists.newArrayList();
String[] pathElements = Strings.splitStringToArray(path, '.');
if (pathElements.length == 0) {
return values;
}
extractRawValues(values, map, pathElements, 0);
return values;
}
@SuppressWarnings({"unchecked"})
private static void extractRawValues(List values, Map<String, Object> part, String[] pathElements, int index) {
if (index == pathElements.length) {
return;
}
String currentPath = pathElements[index];
Object currentValue = part.get(currentPath);
if (currentValue == null) {
return;
}
if (currentValue instanceof Map) {
extractRawValues(values, (Map<String, Object>) currentValue, pathElements, index + 1);
} else if (currentValue instanceof List) {
extractRawValues(values, (List) currentValue, pathElements, index + 1);
} else {
values.add(currentValue);
}
}
@SuppressWarnings({"unchecked"})
private static void extractRawValues(List values, List<Object> part, String[] pathElements, int index) {
for (Object value : part) {
if (value == null) {
continue;
}
if (value instanceof Map) {
extractRawValues(values, (Map<String, Object>) value, pathElements, index);
} else if (value instanceof List) {
extractRawValues(values, (List) value, pathElements, index);
} else {
values.add(value);
}
}
}
public static Object extractValue(String path, Map<String, Object> map) {
String[] pathElements = Strings.splitStringToArray(path, '.');
if (pathElements.length == 0) {
return null;
}
return extractValue(pathElements, 0, map);
}
@SuppressWarnings({"unchecked"})
private static Object extractValue(String[] pathElements, int index, Object currentValue) {
if (index == pathElements.length) {
return currentValue;
}
if (currentValue == null) {
return null;
}
if (currentValue instanceof Map) {
Map map = (Map) currentValue;
return extractValue(pathElements, index + 1, map.get(pathElements[index]));
}
if (currentValue instanceof List) {
List valueList = (List) currentValue;
List newList = new ArrayList(valueList.size());
for (Object o : valueList) {
Object listValue = extractValue(pathElements, index, o);
if (listValue != null) {
newList.add(listValue);
}
}
return newList;
}
return null;
}
public static Map<String, Object> filter(Map<String, Object> map, String[] includes, String[] excludes) {
Map<String, Object> result = Maps.newHashMap();
filter(map, result, includes, excludes, new StringBuilder());
return result;
}
private static void filter(Map<String, Object> map, Map<String, Object> into, String[] includes, String[] excludes, StringBuilder sb) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
int mark = sb.length();
if (sb.length() > 0) {
sb.append('.');
}
sb.append(key);
String path = sb.toString();
boolean excluded = false;
for (String exclude : excludes) {
if (Regex.simpleMatch(exclude, path)) {
excluded = true;
break;
}
}
if (excluded) {
sb.setLength(mark);
continue;
}
if (includes.length > 0) {
boolean atLeastOnOneIncludeMatched = false;
for (String include : includes) {
// check for prefix as well, something like: obj1.arr1.*
// note, this does not work well with middle matches, like obj1.*.obj3
if (include.startsWith(path) || Regex.simpleMatch(include, path)) {
atLeastOnOneIncludeMatched = true;
break;
}
}
if (!atLeastOnOneIncludeMatched) {
sb.setLength(mark);
continue;
}
}
if (entry.getValue() instanceof Map) {
Map<String, Object> innerInto = Maps.newHashMap();
filter((Map<String, Object>) entry.getValue(), innerInto, includes, excludes, sb);
if (!innerInto.isEmpty()) {
into.put(entry.getKey(), innerInto);
}
} else if (entry.getValue() instanceof List) {
List<Object> list = (List<Object>) entry.getValue();
List<Object> innerInto = new ArrayList<Object>(list.size());
filter(list, innerInto, includes, excludes, sb);
into.put(entry.getKey(), innerInto);
} else {
into.put(entry.getKey(), entry.getValue());
}
sb.setLength(mark);
}
}
private static void filter(List<Object> from, List<Object> to, String[] includes, String[] excludes, StringBuilder sb) {
for (Object o : from) {
if (o instanceof Map) {
Map<String, Object> innerInto = Maps.newHashMap();
filter((Map<String, Object>) o, innerInto, includes, excludes, sb);
if (!innerInto.isEmpty()) {
to.add(innerInto);
}
} else if (o instanceof List) {
List<Object> innerInto = new ArrayList<Object>();
filter((List<Object>) o, innerInto, includes, excludes, sb);
} else {
to.add(o);
}
}
}
public static boolean isObject(Object node) {
return node instanceof Map;
}
public static boolean isArray(Object node) {
return node instanceof List;
}
public static String nodeStringValue(Object node, String defaultValue) {
if (node == null) {
return defaultValue;
}
return node.toString();
}
public static float nodeFloatValue(Object node, float defaultValue) {
if (node == null) {
return defaultValue;
}
return nodeFloatValue(node);
}
public static float nodeFloatValue(Object node) {
if (node instanceof Number) {
return ((Number) node).floatValue();
}
return Float.parseFloat(node.toString());
}
public static double nodeDoubleValue(Object node, double defaultValue) {
if (node == null) {
return defaultValue;
}
return nodeDoubleValue(node);
}
public static double nodeDoubleValue(Object node) {
if (node instanceof Number) {
return ((Number) node).doubleValue();
}
return Double.parseDouble(node.toString());
}
public static int nodeIntegerValue(Object node) {
if (node instanceof Number) {
return ((Number) node).intValue();
}
return Integer.parseInt(node.toString());
}
public static int nodeIntegerValue(Object node, int defaultValue) {
if (node == null) {
return defaultValue;
}
if (node instanceof Number) {
return ((Number) node).intValue();
}
return Integer.parseInt(node.toString());
}
public static short nodeShortValue(Object node, short defaultValue) {
if (node == null) {
return defaultValue;
}
return nodeShortValue(node);
}
public static short nodeShortValue(Object node) {
if (node instanceof Number) {
return ((Number) node).shortValue();
}
return Short.parseShort(node.toString());
}
public static byte nodeByteValue(Object node, byte defaultValue) {
if (node == null) {
return defaultValue;
}
return nodeByteValue(node);
}
public static byte nodeByteValue(Object node) {
if (node instanceof Number) {
return ((Number) node).byteValue();
}
return Byte.parseByte(node.toString());
}
public static long nodeLongValue(Object node, long defaultValue) {
if (node == null) {
return defaultValue;
}
return nodeLongValue(node);
}
public static long nodeLongValue(Object node) {
if (node instanceof Number) {
return ((Number) node).longValue();
}
return Long.parseLong(node.toString());
}
public static boolean nodeBooleanValue(Object node, boolean defaultValue) {
if (node == null) {
return defaultValue;
}
return nodeBooleanValue(node);
}
public static boolean nodeBooleanValue(Object node) {
if (node instanceof Boolean) {
return (Boolean) node;
}
if (node instanceof Number) {
return ((Number) node).intValue() != 0;
}
String value = node.toString();
return !(value.equals("false") || value.equals("0") || value.equals("off"));
}
public static TimeValue nodeTimeValue(Object node, TimeValue defaultValue) {
if (node == null) {
return defaultValue;
}
return nodeTimeValue(node);
}
public static TimeValue nodeTimeValue(Object node) {
if (node instanceof Number) {
return TimeValue.timeValueMillis(((Number) node).longValue());
}
return TimeValue.parseTimeValue(node.toString(), null);
}
}
|
package com.soulin.mvpdouban.data.model;
import com.google.auto.value.AutoValue;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.Gson;
@AutoValue
public abstract class Avatars{
@SerializedName("small")
public abstract String small();
@SerializedName("large")
public abstract String large();
@SerializedName("medium")
public abstract String medium();
public static TypeAdapter<Avatars> typeAdapter(Gson gson) {
return new AutoValue_Avatars.GsonTypeAdapter(gson);
}
public static Builder builder() {
return new AutoValue_Avatars.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder small(String small);
public abstract Builder large(String large);
public abstract Builder medium(String medium);
public abstract Avatars build();
}
}
|
/*
* Copyright 2001-2005 Stephen Colebourne
*
* 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.joda.time;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.base.BasePeriod;
/**
* This class is a Junit unit test for MutableDuration.
*
* @author Stephen Colebourne
*/
public class TestMutablePeriod_Basics extends TestCase {
// Test in 2002/03 as time zones are more well known
// (before the late 90's they were all over the place)
private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris");
private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London");
long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 +
365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365;
long y2003days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 +
365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
366 + 365 + 365;
// 2002-06-09
private long TEST_TIME_NOW =
(y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;
// 2002-04-05
private long TEST_TIME1 =
(y2002days + 31L + 28L + 31L + 5L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 12L * DateTimeConstants.MILLIS_PER_HOUR
+ 24L * DateTimeConstants.MILLIS_PER_MINUTE;
// 2003-05-06
private long TEST_TIME2 =
(y2003days + 31L + 28L + 31L + 30L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 14L * DateTimeConstants.MILLIS_PER_HOUR
+ 28L * DateTimeConstants.MILLIS_PER_MINUTE;
private DateTimeZone originalDateTimeZone = null;
private TimeZone originalTimeZone = null;
private Locale originalLocale = null;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestMutablePeriod_Basics.class);
}
public TestMutablePeriod_Basics(String name) {
super(name);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
originalDateTimeZone = DateTimeZone.getDefault();
originalTimeZone = TimeZone.getDefault();
originalLocale = Locale.getDefault();
DateTimeZone.setDefault(LONDON);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Locale.setDefault(Locale.UK);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
//-----------------------------------------------------------------------
public void testTest() {
assertEquals("2002-06-09T00:00:00.000Z", new Instant(TEST_TIME_NOW).toString());
assertEquals("2002-04-05T12:24:00.000Z", new Instant(TEST_TIME1).toString());
assertEquals("2003-05-06T14:28:00.000Z", new Instant(TEST_TIME2).toString());
}
//-----------------------------------------------------------------------
public void testGetPeriodType() {
MutablePeriod test = new MutablePeriod();
assertEquals(PeriodType.standard(), test.getPeriodType());
}
public void testGetMethods() {
MutablePeriod test = new MutablePeriod();
assertEquals(0, test.getYears());
assertEquals(0, test.getMonths());
assertEquals(0, test.getDays());
assertEquals(0, test.getWeeks());
assertEquals(0, test.getDays());
assertEquals(0, test.getHours());
assertEquals(0, test.getMinutes());
assertEquals(0, test.getSeconds());
assertEquals(0, test.getMillis());
}
public void testEqualsHashCode() {
MutablePeriod test1 = new MutablePeriod(123L);
MutablePeriod test2 = new MutablePeriod(123L);
assertEquals(true, test1.equals(test2));
assertEquals(true, test2.equals(test1));
assertEquals(true, test1.equals(test1));
assertEquals(true, test2.equals(test2));
assertEquals(true, test1.hashCode() == test2.hashCode());
assertEquals(true, test1.hashCode() == test1.hashCode());
assertEquals(true, test2.hashCode() == test2.hashCode());
MutablePeriod test3 = new MutablePeriod(321L);
assertEquals(false, test1.equals(test3));
assertEquals(false, test2.equals(test3));
assertEquals(false, test3.equals(test1));
assertEquals(false, test3.equals(test2));
assertEquals(false, test1.hashCode() == test3.hashCode());
assertEquals(false, test2.hashCode() == test3.hashCode());
assertEquals(false, test1.equals("Hello"));
assertEquals(true, test1.equals(new MockMutablePeriod(123L)));
assertEquals(false, test1.equals(new Period(123L, PeriodType.dayTime())));
}
class MockMutablePeriod extends BasePeriod {
public MockMutablePeriod(long value) {
super(value, null, null);
}
}
//-----------------------------------------------------------------------
public void testSerialization() throws Exception {
MutablePeriod test = new MutablePeriod(123L);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(test);
byte[] bytes = baos.toByteArray();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
MutablePeriod result = (MutablePeriod) ois.readObject();
ois.close();
assertEquals(test, result);
}
// //-----------------------------------------------------------------------
// public void testAddTo1() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance().years().add(expected, 1);
// expected = ISOChronology.getInstance().months().add(expected, 2);
// expected = ISOChronology.getInstance().weeks().add(expected, 3);
// expected = ISOChronology.getInstance().days().add(expected, 4);
// expected = ISOChronology.getInstance().hours().add(expected, 5);
// expected = ISOChronology.getInstance().minutes().add(expected, 6);
// expected = ISOChronology.getInstance().seconds().add(expected, 7);
// expected = ISOChronology.getInstance().millis().add(expected, 8);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8);
// long added = test.addTo(TEST_TIME_NOW, 1);
// assertEquals(expected, added);
// }
//
// public void testAddTo2() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance().years().add(expected, -2);
// expected = ISOChronology.getInstance().months().add(expected, -4);
// expected = ISOChronology.getInstance().weeks().add(expected, -6);
// expected = ISOChronology.getInstance().days().add(expected, -8);
// expected = ISOChronology.getInstance().hours().add(expected, -10);
// expected = ISOChronology.getInstance().minutes().add(expected, -12);
// expected = ISOChronology.getInstance().seconds().add(expected, -14);
// expected = ISOChronology.getInstance().millis().add(expected, -16);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8);
// long added = test.addTo(TEST_TIME_NOW, -2);
// assertEquals(expected, added);
// }
//
// public void testAddTo3() {
// long expected = TEST_TIME_NOW;
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8);
// long added = test.addTo(TEST_TIME_NOW, 0);
// assertEquals(expected, added);
// }
//
// public void testAddTo4() {
// long expected = TEST_TIME_NOW + 100L;
// MutablePeriod test = new MutablePeriod(100L);
// long added = test.addTo(TEST_TIME_NOW, 1);
// assertEquals(expected, added);
// }
//
// //-----------------------------------------------------------------------
// public void testAddToWithChronology1() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance().years().add(expected, 1);
// expected = ISOChronology.getInstance().months().add(expected, 2);
// expected = ISOChronology.getInstance().weeks().add(expected, 3);
// expected = ISOChronology.getInstance().days().add(expected, 4);
// expected = ISOChronology.getInstance().hours().add(expected, 5);
// expected = ISOChronology.getInstance().minutes().add(expected, 6);
// expected = ISOChronology.getInstance().seconds().add(expected, 7);
// expected = ISOChronology.getInstance().millis().add(expected, 8);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8);
// long added = test.addTo(TEST_TIME_NOW, 1, ISOChronology.getInstance());
// assertEquals(expected, added);
// }
//
// public void testAddToWithChronology2() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstanceUTC().years().add(expected, -2);
// expected = ISOChronology.getInstanceUTC().months().add(expected, -4);
// expected = ISOChronology.getInstanceUTC().weeks().add(expected, -6);
// expected = ISOChronology.getInstanceUTC().days().add(expected, -8);
// expected = ISOChronology.getInstanceUTC().hours().add(expected, -10);
// expected = ISOChronology.getInstanceUTC().minutes().add(expected, -12);
// expected = ISOChronology.getInstanceUTC().seconds().add(expected, -14);
// expected = ISOChronology.getInstanceUTC().millis().add(expected, -16);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard());
// long added = test.addTo(TEST_TIME_NOW, -2, ISOChronology.getInstanceUTC()); // chrono specified so use it
// assertEquals(expected, added);
// }
//
// public void testAddToWithChronology3() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance().years().add(expected, -2);
// expected = ISOChronology.getInstance().months().add(expected, -4);
// expected = ISOChronology.getInstance().weeks().add(expected, -6);
// expected = ISOChronology.getInstance().days().add(expected, -8);
// expected = ISOChronology.getInstance().hours().add(expected, -10);
// expected = ISOChronology.getInstance().minutes().add(expected, -12);
// expected = ISOChronology.getInstance().seconds().add(expected, -14);
// expected = ISOChronology.getInstance().millis().add(expected, -16);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard());
// long added = test.addTo(TEST_TIME_NOW, -2, null); // no chrono so use default
// assertEquals(expected, added);
// }
//
// //-----------------------------------------------------------------------
// public void testAddToRI1() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance().years().add(expected, 1);
// expected = ISOChronology.getInstance().months().add(expected, 2);
// expected = ISOChronology.getInstance().weeks().add(expected, 3);
// expected = ISOChronology.getInstance().days().add(expected, 4);
// expected = ISOChronology.getInstance().hours().add(expected, 5);
// expected = ISOChronology.getInstance().minutes().add(expected, 6);
// expected = ISOChronology.getInstance().seconds().add(expected, 7);
// expected = ISOChronology.getInstance().millis().add(expected, 8);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8);
// DateTime added = test.addTo(new Instant(), 1); // Instant has no time zone, use default
// assertEquals(expected, added.getMillis());
// assertEquals(ISOChronology.getInstance(), added.getChronology());
// }
//
// public void testAddToRI2() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance().years().add(expected, -2);
// expected = ISOChronology.getInstance().months().add(expected, -4);
// expected = ISOChronology.getInstance().weeks().add(expected, -6);
// expected = ISOChronology.getInstance().days().add(expected, -8);
// expected = ISOChronology.getInstance().hours().add(expected, -10);
// expected = ISOChronology.getInstance().minutes().add(expected, -12);
// expected = ISOChronology.getInstance().seconds().add(expected, -14);
// expected = ISOChronology.getInstance().millis().add(expected, -16);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard());
// DateTime added = test.addTo(new Instant(), -2); // Instant has no time zone, use default
// assertEquals(expected, added.getMillis());
// assertEquals(ISOChronology.getInstance(), added.getChronology());
// }
//
// public void testAddToRI3() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstanceUTC().years().add(expected, -2);
// expected = ISOChronology.getInstanceUTC().months().add(expected, -4);
// expected = ISOChronology.getInstanceUTC().weeks().add(expected, -6);
// expected = ISOChronology.getInstanceUTC().days().add(expected, -8);
// expected = ISOChronology.getInstanceUTC().hours().add(expected, -10);
// expected = ISOChronology.getInstanceUTC().minutes().add(expected, -12);
// expected = ISOChronology.getInstanceUTC().seconds().add(expected, -14);
// expected = ISOChronology.getInstanceUTC().millis().add(expected, -16);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard());
// DateTime added = test.addTo(new DateTime(ISOChronology.getInstanceUTC()), -2); // DateTime has UTC time zone
// assertEquals(expected, added.getMillis());
// assertEquals(ISOChronology.getInstanceUTC(), added.getChronology());
// }
//
// public void testAddToRI4() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance(PARIS).years().add(expected, -2);
// expected = ISOChronology.getInstance(PARIS).months().add(expected, -4);
// expected = ISOChronology.getInstance(PARIS).weeks().add(expected, -6);
// expected = ISOChronology.getInstance(PARIS).days().add(expected, -8);
// expected = ISOChronology.getInstance(PARIS).hours().add(expected, -10);
// expected = ISOChronology.getInstance(PARIS).minutes().add(expected, -12);
// expected = ISOChronology.getInstance(PARIS).seconds().add(expected, -14);
// expected = ISOChronology.getInstance(PARIS).millis().add(expected, -16);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard());
// DateTime added = test.addTo(new DateTime(PARIS), -2); // DateTime has PARIS time zone
// assertEquals(expected, added.getMillis());
// assertEquals(ISOChronology.getInstance(PARIS), added.getChronology());
// }
//
// public void testAddToRI5() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance().years().add(expected, -2);
// expected = ISOChronology.getInstance().months().add(expected, -4);
// expected = ISOChronology.getInstance().weeks().add(expected, -6);
// expected = ISOChronology.getInstance().days().add(expected, -8);
// expected = ISOChronology.getInstance().hours().add(expected, -10);
// expected = ISOChronology.getInstance().minutes().add(expected, -12);
// expected = ISOChronology.getInstance().seconds().add(expected, -14);
// expected = ISOChronology.getInstance().millis().add(expected, -16);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard());
// DateTime added = test.addTo(null, -2); // null has no time zone, use default
// assertEquals(expected, added.getMillis());
// assertEquals(ISOChronology.getInstance(), added.getChronology());
// }
//
// //-----------------------------------------------------------------------
// public void testAddIntoRWI1() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance().years().add(expected, 1);
// expected = ISOChronology.getInstance().months().add(expected, 2);
// expected = ISOChronology.getInstance().weeks().add(expected, 3);
// expected = ISOChronology.getInstance().days().add(expected, 4);
// expected = ISOChronology.getInstance().hours().add(expected, 5);
// expected = ISOChronology.getInstance().minutes().add(expected, 6);
// expected = ISOChronology.getInstance().seconds().add(expected, 7);
// expected = ISOChronology.getInstance().millis().add(expected, 8);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8);
// MutableDateTime mdt = new MutableDateTime();
// test.addInto(mdt, 1);
// assertEquals(expected, mdt.getMillis());
// }
//
// public void testAddIntoRWI2() {
// long expected = TEST_TIME_NOW;
// expected = ISOChronology.getInstance().years().add(expected, -2);
// expected = ISOChronology.getInstance().months().add(expected, -4);
// expected = ISOChronology.getInstance().weeks().add(expected, -6);
// expected = ISOChronology.getInstance().days().add(expected, -8);
// expected = ISOChronology.getInstance().hours().add(expected, -10);
// expected = ISOChronology.getInstance().minutes().add(expected, -12);
// expected = ISOChronology.getInstance().seconds().add(expected, -14);
// expected = ISOChronology.getInstance().millis().add(expected, -16);
//
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.standard());
// MutableDateTime mdt = new MutableDateTime();
// test.addInto(mdt, -2); // MutableDateTime has a chronology, use it
// assertEquals(expected, mdt.getMillis());
// }
//
// public void testAddIntoRWI3() {
// MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8);
// try {
// test.addInto(null, 1);
// fail();
// } catch (IllegalArgumentException ex) {}
// }
//-----------------------------------------------------------------------
public void testToString() {
MutablePeriod test = new MutablePeriod(1, 2, 3, 4, 5, 6, 7, 8);
assertEquals("P1Y2M3W4DT5H6M7.008S", test.toString());
test = new MutablePeriod(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("PT0S", test.toString());
test = new MutablePeriod(12345L);
assertEquals("PT12.345S", test.toString());
}
//-----------------------------------------------------------------------
public void testToPeriod() {
MutablePeriod test = new MutablePeriod(123L);
Period result = test.toPeriod();
assertEquals(test, result);
}
public void testToMutablePeriod() {
MutablePeriod test = new MutablePeriod(123L);
MutablePeriod result = test.toMutablePeriod();
assertEquals(test, result);
}
//-----------------------------------------------------------------------
// public void testToDurationMillisFrom() {
// MutablePeriod test = new MutablePeriod(123L);
// assertEquals(123L, test.toDurationMillisFrom(0L, null));
// }
public void testToDurationFrom() {
MutablePeriod test = new MutablePeriod(123L);
assertEquals(new Duration(123L), test.toDurationFrom(new Instant(0L)));
}
//-----------------------------------------------------------------------
public void testCopy() {
MutablePeriod test = new MutablePeriod(123L);
MutablePeriod copy = test.copy();
assertEquals(test.getPeriodType(), copy.getPeriodType());
assertEquals(test, copy);
}
//-----------------------------------------------------------------------
public void testClone() {
MutablePeriod test = new MutablePeriod(123L);
MutablePeriod copy = (MutablePeriod) test.clone();
assertEquals(test.getPeriodType(), copy.getPeriodType());
assertEquals(test, copy);
}
}
|
package no.unit.nva.search.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.JsonNode;
import nva.commons.core.JacocoGenerated;
import nva.commons.core.paths.UriWrapper;
import java.net.URI;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static no.unit.nva.search.IndexedDocumentsJsonPointers.SOURCE_JSON_POINTER;
import static no.unit.nva.search.constants.ApplicationConstants.objectMapperWithEmpty;
import static nva.commons.core.attempt.Try.attempt;
@JsonPropertyOrder({"@context", "id", "took","email", "total", "hits" })
public class SearchResourcesResponse {
public static final String TOTAL_JSON_POINTER = "/hits/total/value";
public static final String TOOK_JSON_POINTER = "/took";
public static final String HITS_JSON_POINTER = "/hits/hits";
public static final URI DEFAULT_SEARCH_CONTEXT = URI.create("https://api.nva.unit.no/resources/search");
public static final String QUERY_PARAMETER = "query";
@JsonProperty("@context")
private final URI context;
private final URI id;
private final int took;
private final int total;
private final List<JsonNode> hits;
/**
* Creates a SearchResourcesResponse with given properties.
*/
@JacocoGenerated
@JsonCreator
public SearchResourcesResponse(@JsonProperty("@context") URI context,
@JsonProperty("id") URI id,
@JsonProperty("took") int took,
@JsonProperty("total") int total,
@JsonProperty("hits") List<JsonNode> hits) {
this.context = context;
this.id = id;
this.took = took;
this.total = total;
this.hits = hits;
}
protected SearchResourcesResponse(Builder builder) {
this.context = builder.context;
this.id = builder.id;
this.took = builder.took;
this.total = builder.total;
this.hits = builder.hits;
}
@JacocoGenerated
public URI getContext() {
return context;
}
@JacocoGenerated
public URI getId() {
return id;
}
@JacocoGenerated
public int getTook() {
return took;
}
@JacocoGenerated
public int getTotal() {
return total;
}
@JacocoGenerated
public List<JsonNode> getHits() {
return hits;
}
@JacocoGenerated
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SearchResourcesResponse that = (SearchResourcesResponse) o;
return took == that.took
&& total == that.total
&& Objects.equals(context, that.context)
&& Objects.equals(id, that.id)
&& Objects.equals(hits, that.hits);
}
@JacocoGenerated
@Override
public int hashCode() {
return Objects.hash(context, id, took, total, hits);
}
public static final class Builder {
private URI context;
private URI id;
private int took;
private int total;
private List<JsonNode> hits;
public Builder withContext(URI context) {
this.context = context;
return this;
}
public Builder withId(URI id) {
this.id = id;
return this;
}
public Builder withTook(int took) {
this.took = took;
return this;
}
public Builder withTotal(int total) {
this.total = total;
return this;
}
public Builder withHits(List<JsonNode> hits) {
this.hits = hits;
return this;
}
public SearchResourcesResponse build() {
return new SearchResourcesResponse(this);
}
}
public static SearchResourcesResponse toSearchResourcesResponse(
URI requestUri, String searchTerm, String body) {
JsonNode values = attempt(() -> objectMapperWithEmpty.readTree(body)).orElseThrow();
List<JsonNode> sourceList = extractSourceList(values);
int total = intFromNode(values, TOTAL_JSON_POINTER);
int took = intFromNode(values, TOOK_JSON_POINTER);
URI searchResultId = createIdWithQuery(requestUri, searchTerm);
return new SearchResourcesResponse.Builder()
.withContext(DEFAULT_SEARCH_CONTEXT)
.withId(searchResultId)
.withTook(took)
.withTotal(total)
.withHits(sourceList)
.build();
}
private static URI createIdWithQuery(URI requestUri, String searchTerm) {
return new UriWrapper(requestUri).addQueryParameter(QUERY_PARAMETER, searchTerm).getUri();
}
private static List<JsonNode> extractSourceList(JsonNode record) {
return toStream(record.at(HITS_JSON_POINTER))
.map(SearchResourcesResponse::extractSourceStripped)
.collect(Collectors.toList());
}
private static JsonNode extractSourceStripped(JsonNode record) {
return record.at(SOURCE_JSON_POINTER);
}
private static Stream<JsonNode> toStream(JsonNode node) {
return StreamSupport.stream(node.spliterator(), false);
}
private static int intFromNode(JsonNode jsonNode, String jsonPointer) {
JsonNode json = jsonNode.at(jsonPointer);
return isPopulated(json) ? json.asInt() : 0;
}
private static boolean isPopulated(JsonNode json) {
return !json.isNull() && !json.asText().isBlank();
}
}
|
import java.awt.*;
/**
* Uno
*
* WildColourSelectorOverlay class:
* Defines the overlay for choosing colours for wild and +4 cards.
*
* @author Peter Mitchell
* @version 2021.1
*/
public class WildColourSelectorOverlay extends WndInterface implements TurnDecisionOverlayInterface {
/**
* Tracking of the area hovered with the current grid position and region number.
*/
private int hoveredRegion, hoverX, hoverY;
/**
* Reference to the TurnAction that triggered the display of this overlay.
*/
private TurnActionFactory.TurnDecisionAction controllingTurnAction;
/**
* Initialises the overlay using the specified region.
*
* @param position Position to place the overlay.
* @param width Width of the overlay.
* @param height Height of the overlay.
*/
public WildColourSelectorOverlay(Position position, int width, int height) {
super(new Rectangle(position, width, height));
setEnabled(false);
}
/**
* Does nothing.
*
* @param deltaTime Time since last update.
*/
@Override
public void update(int deltaTime) {
}
/**
* Draws a selection interface to choose a colour.
*
* @param g Reference to the Graphics object for rendering.
*/
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(bounds.position.x-20, bounds.position.y-40, bounds.width+40, bounds.height+60);
// Red, blue, green, yellow segments for any wild card in the middle.
for(int i = 0; i < 4; i++) {
g.setColor(Card.getColourByID(i));
if(i == hoveredRegion) {
int offsetX = (hoverX == 0) ? -1 : 1;
int offsetY = (hoverY == 0) ? -1 : 1;
g.fillArc(bounds.position.x+offsetX*10, bounds.position.y+offsetY*10,
bounds.width, bounds.height, 270 + 90 * i, 90);
} else {
g.fillArc(bounds.position.x, bounds.position.y, bounds.width, bounds.height,
270 + 90 * i, 90);
}
}
g.setColor(Color.WHITE);
g.drawRect(bounds.position.x-20, bounds.position.y-40, bounds.width+40, bounds.height+60);
g.setFont(new Font("Arial", Font.BOLD, 20));
String message = "Choose Colour";
int strWidth = g.getFontMetrics().stringWidth(message);
g.drawString(message, bounds.position.x+bounds.width/2-strWidth/2, bounds.position.y-5);
}
/**
* Updates the currently hovered region in the colour wheel.
*
* @param mousePosition Position of the mouse during this movement.
*/
@Override
public void handleMouseMove(Position mousePosition) {
hoveredRegion = -1;
if(bounds.isPositionInside(mousePosition)) {
hoverX = (mousePosition.x - bounds.position.x) / (bounds.width/2);
hoverY = (mousePosition.y - bounds.position.y) / (bounds.height/2);
if(hoverX == 0 && hoverY == 0) hoveredRegion = 2;
else if(hoverX == 1 && hoverY == 0) hoveredRegion = 1;
else if(hoverX == 1 && hoverY == 1) hoveredRegion = 0;
else if(hoverX == 0 && hoverY == 1) hoveredRegion = 3;
}
}
/**
* Checks if the region clicked is valid for a colour selection and
* applies the colour as an action if appropriate.
*
* @param mousePosition Position of the mouse cursor during the press.
* @param isLeft If true, the mouse button is left, otherwise is right.
*/
@Override
public void handleMousePress(Position mousePosition, boolean isLeft) {
handleMouseMove(mousePosition);
if(hoveredRegion != -1) {
controllingTurnAction.injectProperty("colourID", hoveredRegion);
controllingTurnAction.injectFlagProperty(1);
setEnabled(false);
}
}
/**
* Shows the overlay.
*
* @param currentAction The action used to trigger this interface.
*/
@Override
public void showOverlay(TurnActionFactory.TurnDecisionAction currentAction) {
this.controllingTurnAction = currentAction;
setEnabled(true);
}
}
|
import org.checkerframework.common.value.qual.IntRange;
public class RefinementGTE {
void test_forward(int a, int j, int s) {
/** forwards greater than or equals */
// :: error: (assignment)
@IntRange(from = -1) int aa = a;
if (a >= -1) {
@IntRange(from = -1) int b = a;
} else {
// :: error: (assignment)
@IntRange(from = -1) int c = a;
}
if (j >= 0) {
@IntRange(from = 0) int k = j;
// :: error: (assignment)
@IntRange(from = 1) int k1 = j;
@IntRange(from = -1) int k2 = j;
} else {
// :: error: (assignment)
@IntRange(from = 0) int l = j;
}
}
void test_backwards(int a, int j, int s) {
/** backwards greater than or equal */
// :: error: (assignment)
@IntRange(from = 0) int aa = a;
if (-1 >= a) {
// :: error: (assignment)
@IntRange(from = 0) int b = a;
} else {
@IntRange(from = 0) int c = a;
}
if (0 >= j) {
// :: error: (assignment)
@IntRange(from = 1) int k = j;
} else {
@IntRange(from = 1) int l = j;
@IntRange(from = -1) int l1 = j;
@IntRange(from = 0) int l2 = j;
}
if (1 >= s) {
// :: error: (assignment)
@IntRange(from = 1) int t = s;
} else {
@IntRange(from = 1) int u = s;
}
}
}
|
package net.i2p.util;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
/**
* A simple in-JVM ServerSocket using Piped Streams.
* We use port numbers just like regular sockets.
* Can only be connected by InternalSocket.
*
* Warning - this uses Piped Streams, which don't like multiple writers from threads
* that may vanish. If you do use multipe writers,
* you may get intermittent 'write end dead' or 'pipe broken' IOExceptions on the reader side.
* See http://techtavern.wordpress.com/2008/07/16/whats-this-ioexception-write-end-dead/
* @since 0.7.9
*/
public class InternalServerSocket extends ServerSocket {
private static final ConcurrentHashMap<Integer, InternalServerSocket> _sockets = new ConcurrentHashMap<Integer, InternalServerSocket>(4);
private final BlockingQueue<InternalSocket> _acceptQueue;
private final Integer _port;
private volatile boolean _running;
//private static Log _log = I2PAppContext.getGlobalContext().logManager().getLog(InternalServerSocket.class);
/**
* @param port > 0
*/
public InternalServerSocket(int port) throws IOException {
if (port <= 0)
throw new IOException("Bad port: " + port);
_port = Integer.valueOf(port);
InternalServerSocket previous = _sockets.putIfAbsent(_port, this);
if (previous != null)
throw new IOException("Internal port in use: " + port);
_running = true;
_acceptQueue = new LinkedBlockingQueue<InternalSocket>();
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("Registered " + _port);
}
@Override
public void close() {
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("Closing " + _port);
_running = false;
_sockets.remove(_port);
_acceptQueue.clear();
try {
// use null streams as a poison
_acceptQueue.put(new InternalSocket(null, null));
} catch (InterruptedException ie) {}
}
@Override
public Socket accept() throws IOException {
InternalSocket serverSock = null;
while (_running) {
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("Accepting " + _port);
try {
serverSock = _acceptQueue.take();
} catch (InterruptedException ie) {
continue;
}
if (serverSock.getInputStream() == null) // poison
throw new IOException("closed");
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("Accepted " + _port);
break;
}
return serverSock;
}
@Override
public String toString() {
return ("Internal server socket on port " + _port);
}
/**
* This is how the client connects.
*
* @param port > 0
*/
static void internalConnect(int port, InternalSocket clientSock) throws IOException {
InternalServerSocket iss = _sockets.get(Integer.valueOf(port));
if (iss == null)
throw new IOException("No server for port: " + port);
PipedInputStream cis = BigPipedInputStream.getInstance();
PipedInputStream sis = BigPipedInputStream.getInstance();
PipedOutputStream cos = new PipedOutputStream(sis);
PipedOutputStream sos = new PipedOutputStream(cis);
clientSock.setInputStream(cis);
clientSock.setOutputStream(cos);
iss.queueConnection(new InternalSocket(sis, sos));
}
private void queueConnection(InternalSocket sock) throws IOException {
if (!_running)
throw new IOException("Server closed for port: " + _port);
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("Queueing " + _port);
try {
_acceptQueue.put(sock);
} catch (InterruptedException ie) {}
}
@Override
public int getLocalPort() {
return _port.intValue();
}
// ignored stuff
/** warning - unsupported */
@Override
public void setSoTimeout(int timeout) {}
@Override
public int getSoTimeout () {
return 0;
}
// everything below here unsupported
/** @deprecated unsupported */
@Override
public void bind(SocketAddress endpoint) {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public void bind(SocketAddress endpoint, int backlog) {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public ServerSocketChannel getChannel() {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public InetAddress getInetAddress() {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public SocketAddress getLocalSocketAddress() {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public int getReceiveBufferSize() {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public boolean getReuseAddress() {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public boolean isBound() {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public boolean isClosed() {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public void setReceiveBufferSize(int size) {
throw new IllegalArgumentException("unsupported");
}
/** @deprecated unsupported */
@Override
public void setReuseAddress(boolean on) {
throw new IllegalArgumentException("unsupported");
}
}
|
package com.lucodeveloper.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* @author lucodeveloper
*/
@Entity
@Table(name="persona")
public class Persona {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int codigo;
@Column(name="nombres")
private String nombres;
@Column(name="apellidos")
private String apellidos;
@Column(name="sexo")
private String sexo;
@Temporal(TemporalType.DATE)
@Column(name="fechaNacimiento")
private Date fechaNacimiento;
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getNombres() {
return nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + this.codigo;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Persona other = (Persona) obj;
if (this.codigo != other.codigo) {
return false;
}
return true;
}
@Override
public String toString() {
return "Persona{" + "codigo=" + codigo + '}';
}
}
|
package com.nx.logger.diskLog;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import com.nx.logger.androidBase.LogInterface;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Abstract class that takes care of background threading the printToFile log operation on Android.
* implementing classes are free to directly perform I/O operations there.
*/
public class DiskLogImplement implements LogInterface {
private final Handler handler;
public DiskLogImplement(Handler handler) {
this.handler = handler;
}
@Override
public void log(int level, String tag, String message) {
// do nothing on the calling thread, simply pass the tag/msg to the background thread
handler.sendMessage(handler.obtainMessage(level, message));
}
static class WriteHandler extends Handler {
private final String folder;
private final int maxFileSize;
WriteHandler(Looper looper, String folder, int maxFileSize) {
super(looper);
this.folder = folder;
this.maxFileSize = maxFileSize;
}
@SuppressWarnings("checkstyle:emptyblock")
@Override
public void handleMessage(Message msg) {
String content = (String) msg.obj;
FileWriter fileWriter = null;
File logFile = getLogFile(folder, "logs");
if (logFile.exists()) {
Log.i("nx:", "logFile.exists() writeLog : " + content);
} else {
Log.i("nx:", "logFile.not exists() ");
}
try {
fileWriter = new FileWriter(logFile, true);
writeLog(fileWriter, content);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
if (fileWriter != null) {
try {
fileWriter.flush();
fileWriter.close();
} catch (IOException e1) {
e.printStackTrace();
/* fail silently */
}
}
}
}
/**
* This is always called on a single background thread.
* Implementing classes must ONLY write to the fileWriter and nothing more.
* The abstract class takes care of everything else including close the stream and catching IOException
*
* @param fileWriter an instance of FileWriter already initialised to the correct printToFile
*/
private void writeLog(FileWriter fileWriter, String content) throws IOException {
fileWriter.append(content);
}
private File getLogFile(String folderName, String fileName) {
File folder = new File(folderName);
if (!folder.exists()) {
//TODO: What if folder is not created, what happens then?
folder.mkdirs();
}
int newFileCount = 0;
File newFile;
File existingFile = null;
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm", Locale.UK);
String datetime = dateFormat.format(date);
newFile = new File(folder, String.format("%s_%s_%s.log", fileName, datetime, newFileCount));
// newFile = new File(folder, String.format("%s_%s.log", fileName, newFileCount));
while (newFile.exists()) {
existingFile = newFile;
newFileCount++;
newFile = new File(folder, String.format("%s_%s.log", fileName, newFileCount));
}
if (existingFile != null) {
if (existingFile.length() >= maxFileSize) {
return newFile;
}
return existingFile;
}
return newFile;
}
}
}
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.basicoperations;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.lib.utils.FieldMasks;
import com.google.ads.googleads.v10.enums.CampaignStatusEnum.CampaignStatus;
import com.google.ads.googleads.v10.errors.GoogleAdsError;
import com.google.ads.googleads.v10.errors.GoogleAdsException;
import com.google.ads.googleads.v10.resources.Campaign;
import com.google.ads.googleads.v10.services.CampaignOperation;
import com.google.ads.googleads.v10.services.CampaignServiceClient;
import com.google.ads.googleads.v10.services.MutateCampaignResult;
import com.google.ads.googleads.v10.services.MutateCampaignsResponse;
import com.google.ads.googleads.v10.utils.ResourceNames;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
/** Updates a campaign by setting the status to PAUSED. To get campaigns, run GetCampaigns.java. */
public class UpdateCampaign {
private static class UpdateCampaignParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
@Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
private Long campaignId;
}
public static void main(String[] args) {
UpdateCampaignParams params = new UpdateCampaignParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new UpdateCampaign().runExample(googleAdsClient, params.customerId, params.campaignId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param campaignId the ID of the campaign to update.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(GoogleAdsClient googleAdsClient, Long customerId, Long campaignId) {
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
// Creates a Campaign object with the proper resource name and any other changes.
Campaign campaign =
Campaign.newBuilder()
.setResourceName(ResourceNames.campaign(customerId, campaignId))
.setStatus(CampaignStatus.PAUSED)
.build();
// Constructs an operation that will update the campaign, using the FieldMasks utility to
// derive the update mask. This mask tells the Google Ads API which attributes of the
// campaign you want to change.
CampaignOperation operation =
CampaignOperation.newBuilder()
.setUpdate(campaign)
.setUpdateMask(FieldMasks.allSetFieldsOf(campaign))
.build();
// Sends the operation in a mutate request.
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
customerId.toString(), Collections.singletonList(operation));
// Prints the resource name of each updated object.
for (MutateCampaignResult mutateCampaignResult : response.getResultsList()) {
System.out.printf(
"Updated campaign with resourceName: %s.%n", mutateCampaignResult.getResourceName());
}
}
}
}
|
/*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package fredboat.command.util;
import fredboat.command.music.control.*;
import fredboat.command.music.info.ExportCommand;
import fredboat.command.music.info.GensokyoRadioCommand;
import fredboat.command.music.info.ListCommand;
import fredboat.command.music.info.NowplayingCommand;
import fredboat.command.music.seeking.ForwardCommand;
import fredboat.command.music.seeking.RestartCommand;
import fredboat.command.music.seeking.RewindCommand;
import fredboat.command.music.seeking.SeekCommand;
import fredboat.commandmeta.CommandRegistry;
import fredboat.commandmeta.abs.Command;
import fredboat.commandmeta.abs.CommandContext;
import fredboat.commandmeta.abs.IMusicCommand;
import fredboat.commandmeta.abs.IUtilCommand;
import fredboat.messaging.internal.Context;
import fredboat.util.Emojis;
import fredboat.util.TextUtils;
import net.dv8tion.jda.core.Permission;
import java.util.*;
import javax.annotation.Nonnull;
public class MusicHelpCommand extends Command implements IUtilCommand {
public MusicHelpCommand(String name, String... aliases) {
super(name, aliases);
}
@Override
public void onInvoke(@Nonnull CommandContext context) {
getFormattedCommandHelp(context);
}
//TODO this does a lot of i18n calls, music comms are static tho (except for the language), so they should be cached per language
private static List<String> getMusicComms(Context context) {
//aggregate all commands and the aliases they may be called with
Map<Class<? extends Command>, List<String>> commandToAliases = new HashMap<>();
Set<String> commandsAndAliases = CommandRegistry.getRegisteredCommandsAndAliases();
for (String commandOrAlias : commandsAndAliases) {
Command command = CommandRegistry.getCommand(commandOrAlias).command;
List<String> aliases = commandToAliases.get(command.getClass());
if (aliases == null) {
aliases = new ArrayList<>();
}
aliases.add(commandOrAlias);
commandToAliases.put(command.getClass(), aliases);
}
//sum up existing music commands & sort them in a presentable way
List<Command> sortedComms = new ArrayList<>();
for (List<String> as : commandToAliases.values()) {
Command c = CommandRegistry.getCommand(as.get(0)).command;
if (c instanceof IMusicCommand) {
sortedComms.add(c);
}
}
sortedComms.sort(new MusicCommandsComparator());
//create help strings for each music command and its main alias
List<String> musicComms = new ArrayList<>();
for (Command command : sortedComms) {
String mainAlias = commandToAliases.get(command.getClass()).get(0);
mainAlias = CommandRegistry.getCommand(mainAlias).name;
String formattedHelp = HelpCommand.getFormattedCommandHelp(context, command, mainAlias);
musicComms.add(formattedHelp);
}
return musicComms;
}
private static void getFormattedCommandHelp(CommandContext context) {
final List<String> musicComms = getMusicComms(context);
// Start building string:
String out = "< " + context.i18n("helpMusicCommandsHeader") + " >\n";
for (String s : musicComms) {
if (out.length() + s.length() >= 1990) {
sendCommandsHelpInDM(context, out);
out = "";
}
out += s + "\n";
}
sendCommandsHelpInDM(context, out);
}
private static void sendCommandsHelpInDM(CommandContext context, String dmMsg) {
context.replyPrivate(TextUtils.asCodeBlock(dmMsg, "md"),
success -> context.replyWithName(context.i18n("helpSent")),
failure -> {
if (context.hasPermissions(Permission.MESSAGE_WRITE)) {
context.replyWithName(Emojis.EXCLAMATION + context.i18n("helpDmFailed"));
}
}
);
}
@Nonnull
@Override
public String help(@Nonnull Context context) {
return "{0}{1}\n#" + context.i18n("helpMusicHelpCommand");
}
/**
* Sort the commands in a sensible way to display them to the user
*/
static class MusicCommandsComparator implements Comparator<Command> {
@Override
public int compare(Command o1, Command o2) {
return getCommandRank(o1) - getCommandRank(o2);
}
/**
* a container of smelly code
* http://stackoverflow.com/a/2790215
*/
private static int getCommandRank(Command c) {
int result;
if (c instanceof PlayCommand) {
result = 10050;
} else if (c instanceof ListCommand) {
result = 10100;
} else if (c instanceof NowplayingCommand) {
result = 10150;
} else if (c instanceof SkipCommand) {
result = 10200;
} else if (c instanceof StopCommand) {
result = 10250;
} else if (c instanceof PauseCommand) {
result = 10300;
} else if (c instanceof UnpauseCommand) {
result = 10350;
} else if (c instanceof JoinCommand) {
result = 10400;
} else if (c instanceof LeaveCommand) {
result = 10450;
} else if (c instanceof RepeatCommand) {
result = 10500;
} else if (c instanceof ShuffleCommand) {
result = 10550;
} else if (c instanceof ReshuffleCommand) {
result = 10560;
} else if (c instanceof ForwardCommand) {
result = 10600;
} else if (c instanceof RewindCommand) {
result = 10650;
} else if (c instanceof SeekCommand) {
result = 10700;
} else if (c instanceof RestartCommand) {
result = 10750;
} else if (c instanceof ExportCommand) {
result = 10800;
} else if (c instanceof PlaySplitCommand) {
result = 10850;
} else if (c instanceof SelectCommand) {
result = 10900;
} else if (c instanceof GensokyoRadioCommand) {
result = 10950;
} else if (c instanceof VolumeCommand) {
result = 10970;
} else {
//everything else
//newly added commands will land here, just add them to the giant if construct above to assign them a fixed place
result = 10999;
}
return result;
}
}
}
|
package com.gm.dscustomer.dto.in;
public class OrderProductInDTO {
private Integer productId;
private Integer quantity;
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
}
|
package org.hl7.fhir.convertors.conv40_50;
import org.hl7.fhir.convertors.VersionConvertor_40_50;
import org.hl7.fhir.exceptions.FHIRException;
/*
Copyright (c) 2011+, HL7, 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 HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Sun, Feb 24, 2019 11:37+1100 for FHIR v4.0.0
public class Patient40_50 extends VersionConvertor_40_50 {
public static org.hl7.fhir.r5.model.Patient convertPatient(org.hl7.fhir.r4.model.Patient src) throws FHIRException {
if (src == null)
return null;
org.hl7.fhir.r5.model.Patient tgt = new org.hl7.fhir.r5.model.Patient();
copyDomainResource(src, tgt);
for (org.hl7.fhir.r4.model.Identifier t : src.getIdentifier()) tgt.addIdentifier(convertIdentifier(t));
if (src.hasActive())
tgt.setActiveElement(convertBoolean(src.getActiveElement()));
for (org.hl7.fhir.r4.model.HumanName t : src.getName()) tgt.addName(convertHumanName(t));
for (org.hl7.fhir.r4.model.ContactPoint t : src.getTelecom()) tgt.addTelecom(convertContactPoint(t));
if (src.hasGender())
tgt.setGenderElement(Enumerations40_50.convertAdministrativeGender(src.getGenderElement()));
if (src.hasBirthDate())
tgt.setBirthDateElement(convertDate(src.getBirthDateElement()));
if (src.hasDeceased())
tgt.setDeceased(convertType(src.getDeceased()));
for (org.hl7.fhir.r4.model.Address t : src.getAddress()) tgt.addAddress(convertAddress(t));
if (src.hasMaritalStatus())
tgt.setMaritalStatus(convertCodeableConcept(src.getMaritalStatus()));
if (src.hasMultipleBirth())
tgt.setMultipleBirth(convertType(src.getMultipleBirth()));
for (org.hl7.fhir.r4.model.Attachment t : src.getPhoto()) tgt.addPhoto(convertAttachment(t));
for (org.hl7.fhir.r4.model.Patient.ContactComponent t : src.getContact()) tgt.addContact(convertContactComponent(t));
for (org.hl7.fhir.r4.model.Patient.PatientCommunicationComponent t : src.getCommunication()) tgt.addCommunication(convertPatientCommunicationComponent(t));
for (org.hl7.fhir.r4.model.Reference t : src.getGeneralPractitioner()) tgt.addGeneralPractitioner(convertReference(t));
if (src.hasManagingOrganization())
tgt.setManagingOrganization(convertReference(src.getManagingOrganization()));
for (org.hl7.fhir.r4.model.Patient.PatientLinkComponent t : src.getLink()) tgt.addLink(convertPatientLinkComponent(t));
return tgt;
}
public static org.hl7.fhir.r4.model.Patient convertPatient(org.hl7.fhir.r5.model.Patient src) throws FHIRException {
if (src == null)
return null;
org.hl7.fhir.r4.model.Patient tgt = new org.hl7.fhir.r4.model.Patient();
copyDomainResource(src, tgt);
for (org.hl7.fhir.r5.model.Identifier t : src.getIdentifier()) tgt.addIdentifier(convertIdentifier(t));
if (src.hasActive())
tgt.setActiveElement(convertBoolean(src.getActiveElement()));
for (org.hl7.fhir.r5.model.HumanName t : src.getName()) tgt.addName(convertHumanName(t));
for (org.hl7.fhir.r5.model.ContactPoint t : src.getTelecom()) tgt.addTelecom(convertContactPoint(t));
if (src.hasGender())
tgt.setGenderElement(Enumerations40_50.convertAdministrativeGender(src.getGenderElement()));
if (src.hasBirthDate())
tgt.setBirthDateElement(convertDate(src.getBirthDateElement()));
if (src.hasDeceased())
tgt.setDeceased(convertType(src.getDeceased()));
for (org.hl7.fhir.r5.model.Address t : src.getAddress()) tgt.addAddress(convertAddress(t));
if (src.hasMaritalStatus())
tgt.setMaritalStatus(convertCodeableConcept(src.getMaritalStatus()));
if (src.hasMultipleBirth())
tgt.setMultipleBirth(convertType(src.getMultipleBirth()));
for (org.hl7.fhir.r5.model.Attachment t : src.getPhoto()) tgt.addPhoto(convertAttachment(t));
for (org.hl7.fhir.r5.model.Patient.ContactComponent t : src.getContact()) tgt.addContact(convertContactComponent(t));
for (org.hl7.fhir.r5.model.Patient.PatientCommunicationComponent t : src.getCommunication()) tgt.addCommunication(convertPatientCommunicationComponent(t));
for (org.hl7.fhir.r5.model.Reference t : src.getGeneralPractitioner()) tgt.addGeneralPractitioner(convertReference(t));
if (src.hasManagingOrganization())
tgt.setManagingOrganization(convertReference(src.getManagingOrganization()));
for (org.hl7.fhir.r5.model.Patient.PatientLinkComponent t : src.getLink()) tgt.addLink(convertPatientLinkComponent(t));
return tgt;
}
public static org.hl7.fhir.r5.model.Patient.ContactComponent convertContactComponent(org.hl7.fhir.r4.model.Patient.ContactComponent src) throws FHIRException {
if (src == null)
return null;
org.hl7.fhir.r5.model.Patient.ContactComponent tgt = new org.hl7.fhir.r5.model.Patient.ContactComponent();
copyElement(src, tgt);
for (org.hl7.fhir.r4.model.CodeableConcept t : src.getRelationship()) tgt.addRelationship(convertCodeableConcept(t));
if (src.hasName())
tgt.setName(convertHumanName(src.getName()));
for (org.hl7.fhir.r4.model.ContactPoint t : src.getTelecom()) tgt.addTelecom(convertContactPoint(t));
if (src.hasAddress())
tgt.setAddress(convertAddress(src.getAddress()));
if (src.hasGender())
tgt.setGenderElement(Enumerations40_50.convertAdministrativeGender(src.getGenderElement()));
if (src.hasOrganization())
tgt.setOrganization(convertReference(src.getOrganization()));
if (src.hasPeriod())
tgt.setPeriod(convertPeriod(src.getPeriod()));
return tgt;
}
public static org.hl7.fhir.r4.model.Patient.ContactComponent convertContactComponent(org.hl7.fhir.r5.model.Patient.ContactComponent src) throws FHIRException {
if (src == null)
return null;
org.hl7.fhir.r4.model.Patient.ContactComponent tgt = new org.hl7.fhir.r4.model.Patient.ContactComponent();
copyElement(src, tgt);
for (org.hl7.fhir.r5.model.CodeableConcept t : src.getRelationship()) tgt.addRelationship(convertCodeableConcept(t));
if (src.hasName())
tgt.setName(convertHumanName(src.getName()));
for (org.hl7.fhir.r5.model.ContactPoint t : src.getTelecom()) tgt.addTelecom(convertContactPoint(t));
if (src.hasAddress())
tgt.setAddress(convertAddress(src.getAddress()));
if (src.hasGender())
tgt.setGenderElement(Enumerations40_50.convertAdministrativeGender(src.getGenderElement()));
if (src.hasOrganization())
tgt.setOrganization(convertReference(src.getOrganization()));
if (src.hasPeriod())
tgt.setPeriod(convertPeriod(src.getPeriod()));
return tgt;
}
public static org.hl7.fhir.r5.model.Patient.PatientCommunicationComponent convertPatientCommunicationComponent(org.hl7.fhir.r4.model.Patient.PatientCommunicationComponent src) throws FHIRException {
if (src == null)
return null;
org.hl7.fhir.r5.model.Patient.PatientCommunicationComponent tgt = new org.hl7.fhir.r5.model.Patient.PatientCommunicationComponent();
copyElement(src, tgt);
if (src.hasLanguage())
tgt.setLanguage(convertCodeableConcept(src.getLanguage()));
if (src.hasPreferred())
tgt.setPreferredElement(convertBoolean(src.getPreferredElement()));
return tgt;
}
public static org.hl7.fhir.r4.model.Patient.PatientCommunicationComponent convertPatientCommunicationComponent(org.hl7.fhir.r5.model.Patient.PatientCommunicationComponent src) throws FHIRException {
if (src == null)
return null;
org.hl7.fhir.r4.model.Patient.PatientCommunicationComponent tgt = new org.hl7.fhir.r4.model.Patient.PatientCommunicationComponent();
copyElement(src, tgt);
if (src.hasLanguage())
tgt.setLanguage(convertCodeableConcept(src.getLanguage()));
if (src.hasPreferred())
tgt.setPreferredElement(convertBoolean(src.getPreferredElement()));
return tgt;
}
public static org.hl7.fhir.r5.model.Patient.PatientLinkComponent convertPatientLinkComponent(org.hl7.fhir.r4.model.Patient.PatientLinkComponent src) throws FHIRException {
if (src == null)
return null;
org.hl7.fhir.r5.model.Patient.PatientLinkComponent tgt = new org.hl7.fhir.r5.model.Patient.PatientLinkComponent();
copyElement(src, tgt);
if (src.hasOther())
tgt.setOther(convertReference(src.getOther()));
if (src.hasType())
tgt.setTypeElement(convertLinkType(src.getTypeElement()));
return tgt;
}
public static org.hl7.fhir.r4.model.Patient.PatientLinkComponent convertPatientLinkComponent(org.hl7.fhir.r5.model.Patient.PatientLinkComponent src) throws FHIRException {
if (src == null)
return null;
org.hl7.fhir.r4.model.Patient.PatientLinkComponent tgt = new org.hl7.fhir.r4.model.Patient.PatientLinkComponent();
copyElement(src, tgt);
if (src.hasOther())
tgt.setOther(convertReference(src.getOther()));
if (src.hasType())
tgt.setTypeElement(convertLinkType(src.getTypeElement()));
return tgt;
}
static public org.hl7.fhir.r5.model.Enumeration<org.hl7.fhir.r5.model.Patient.LinkType> convertLinkType(org.hl7.fhir.r4.model.Enumeration<org.hl7.fhir.r4.model.Patient.LinkType> src) throws FHIRException {
if (src == null || src.isEmpty())
return null;
org.hl7.fhir.r5.model.Enumeration<org.hl7.fhir.r5.model.Patient.LinkType> tgt = new org.hl7.fhir.r5.model.Enumeration<>(new org.hl7.fhir.r5.model.Patient.LinkTypeEnumFactory());
VersionConvertor_40_50.copyElement(src, tgt);
switch(src.getValue()) {
case REPLACEDBY:
tgt.setValue(org.hl7.fhir.r5.model.Patient.LinkType.REPLACEDBY);
break;
case REPLACES:
tgt.setValue(org.hl7.fhir.r5.model.Patient.LinkType.REPLACES);
break;
case REFER:
tgt.setValue(org.hl7.fhir.r5.model.Patient.LinkType.REFER);
break;
case SEEALSO:
tgt.setValue(org.hl7.fhir.r5.model.Patient.LinkType.SEEALSO);
break;
default:
tgt.setValue(org.hl7.fhir.r5.model.Patient.LinkType.NULL);
break;
}
return tgt;
}
static public org.hl7.fhir.r4.model.Enumeration<org.hl7.fhir.r4.model.Patient.LinkType> convertLinkType(org.hl7.fhir.r5.model.Enumeration<org.hl7.fhir.r5.model.Patient.LinkType> src) throws FHIRException {
if (src == null || src.isEmpty())
return null;
org.hl7.fhir.r4.model.Enumeration<org.hl7.fhir.r4.model.Patient.LinkType> tgt = new org.hl7.fhir.r4.model.Enumeration<>(new org.hl7.fhir.r4.model.Patient.LinkTypeEnumFactory());
VersionConvertor_40_50.copyElement(src, tgt);
switch(src.getValue()) {
case REPLACEDBY:
tgt.setValue(org.hl7.fhir.r4.model.Patient.LinkType.REPLACEDBY);
break;
case REPLACES:
tgt.setValue(org.hl7.fhir.r4.model.Patient.LinkType.REPLACES);
break;
case REFER:
tgt.setValue(org.hl7.fhir.r4.model.Patient.LinkType.REFER);
break;
case SEEALSO:
tgt.setValue(org.hl7.fhir.r4.model.Patient.LinkType.SEEALSO);
break;
default:
tgt.setValue(org.hl7.fhir.r4.model.Patient.LinkType.NULL);
break;
}
return tgt;
}
}
|
package onethreeseven.spm.data;
import onethreeseven.collections.IntArray;
import onethreeseven.spm.model.CoveredSequentialPattern;
import onethreeseven.spm.model.SequentialPattern;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* For parsing output from SPMF sequential patterns.
* Can also parseSequences SPMF sequence files.
* @see <a href="http://www.philippe-fournier-viger.com/spmf/index.php?link=developers.php">SPMF</a>
* for details on the file format.
* @author Luke Bermingham
*/
public class SPMFParser {
private interface PatternProcessor{
void parseLine(String line);
}
private final String delimiter;
public SPMFParser(){
this(" ");
}
public SPMFParser(String delimiter){
this.delimiter = delimiter;
}
public int[][] parseSequences(File file){
try {
return parseSequences(new BufferedReader(new FileReader(file)));
} catch (FileNotFoundException e) {
System.err.println("Could not find spmf output file to parseSequences: " + e.getMessage());
}
return new int[][]{};
}
public int[][] parseSequences(BufferedReader br){
final ArrayList<int[]> sequences = new ArrayList<>();
parseImpl(br, line -> {
//parseSequences
int[] seq = parseSequence(line, SPMFParser.this.delimiter);
sequences.add(seq);
});
int[][] out = new int[sequences.size()][];
out = sequences.toArray(out);
return out;
}
public List<SequentialPattern> parsePatterns(File file){
ArrayList<SequentialPattern> patterns = new ArrayList<>();
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
parseImpl(br, line -> {
SequentialPattern pattern =
parsePattern(line, SPMFParser.this.delimiter);
patterns.add(pattern);
});
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return patterns;
}
private void parseImpl(BufferedReader br, PatternProcessor processor){
String line;
boolean keepReading = true;
while(keepReading){
try {
line = br.readLine();
if(line != null && !line.isEmpty()){
processor.parseLine(line);
}
keepReading = line != null;
} catch (IOException e) {
System.err.println("Could not read spmf file: " + e.getMessage());
}
}
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static int[] parseSequence(String line, String delimiter){
line = line.trim();
String[] lineParts = line.split(delimiter);
IntArray arr = new IntArray(lineParts.length, false);
for (String part : lineParts) {
part = part.trim();
if(part.equals("-1") || part.equals("-2") || part.isEmpty()){continue;}
if(part.startsWith("#")){break;}
arr.add(Integer.parseInt(part));
}
return arr.getArray();
}
static int extractValuePreceededByString(String line, String preceedingString){
//case: has support like #SUP:
int supIdx = line.indexOf(preceedingString);
int extractedValue = -1;
if(supIdx != -1){
int startIdx = supIdx + preceedingString.length();
int endIdx = startIdx;
int lastIdx = line.length();
for (; endIdx < lastIdx; endIdx++) {
char c = line.charAt(endIdx);
//if we hit a non-whitespace non-digit character, stop
if(!Character.isWhitespace(c) && !Character.isDigit(c)){
break;
}
}
String candidateSupStr = line.substring(startIdx, endIdx).trim();
if(candidateSupStr.isEmpty()){
return extractedValue;
}
try{
extractedValue = Integer.parseInt(candidateSupStr);
}catch (NumberFormatException e){
e.printStackTrace();
}
}
return extractedValue;
}
static SequentialPattern parsePattern(String line, String delimiter){
line = line.trim();
//spmf sequences always end in -2
String[] lineParts = line.split("#")[0].split(delimiter);
IntArray arr = new IntArray(lineParts.length, false);
int sup = extractValuePreceededByString(line, "#SUP:");
int cover = extractValuePreceededByString(line, "#COVER:");
for (String part : lineParts) {
part = part.trim();
if(!part.equals("-1") && !part.equals("-2") && !part.isEmpty()){
arr.add(Integer.parseInt(part));
}
}
if(cover == -1){
return new SequentialPattern(arr.getArray(), sup);
}else{
return new CoveredSequentialPattern(arr.getArray(), sup, cover);
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.transforms;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Nullable;
import org.apache.beam.sdk.transforms.display.DisplayData;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TypeDescriptor;
/**
* {@code PTransform}s for mapping a simple function over the elements of a {@link PCollection}.
*/
public class MapElements<InputT, OutputT>
extends PTransform<PCollection<? extends InputT>, PCollection<OutputT>> {
/**
* Temporarily stores the argument of {@link #into(TypeDescriptor)} until combined with the
* argument of {@link #via(SerializableFunction)} into the fully-specified {@link #fn}. Stays null
* if constructed using {@link #via(SimpleFunction)} directly.
*/
@Nullable private final transient TypeDescriptor<OutputT> outputType;
/**
* Non-null on a fully specified transform - is null only when constructed using {@link
* #into(TypeDescriptor)}, until the fn is specified using {@link #via(SerializableFunction)}.
*/
@Nullable private final SimpleFunction<InputT, OutputT> fn;
private final DisplayData.ItemSpec<?> fnClassDisplayData;
private MapElements(
@Nullable SimpleFunction<InputT, OutputT> fn,
@Nullable TypeDescriptor<OutputT> outputType,
@Nullable Class<?> fnClass) {
this.fn = fn;
this.outputType = outputType;
this.fnClassDisplayData = DisplayData.item("mapFn", fnClass).withLabel("Map Function");
}
/**
* For a {@code SimpleFunction<InputT, OutputT>} {@code fn}, returns a {@code PTransform} that
* takes an input {@code PCollection<InputT>} and returns a {@code PCollection<OutputT>}
* containing {@code fn.apply(v)} for every element {@code v} in the input.
*
* <p>This overload is intended primarily for use in Java 7. In Java 8, the overload
* {@link #via(SerializableFunction)} supports use of lambda for greater concision.
*
* <p>Example of use in Java 7:
* <pre>{@code
* PCollection<String> words = ...;
* PCollection<Integer> wordsPerLine = words.apply(MapElements.via(
* new SimpleFunction<String, Integer>() {
* public Integer apply(String word) {
* return word.length();
* }
* }));
* }</pre>
*/
public static <InputT, OutputT> MapElements<InputT, OutputT> via(
final SimpleFunction<InputT, OutputT> fn) {
return new MapElements<>(fn, null, fn.getClass());
}
/**
* Returns a new {@link MapElements} transform with the given type descriptor for the output
* type, but the mapping function yet to be specified using {@link #via(SerializableFunction)}.
*/
public static <OutputT> MapElements<?, OutputT>
into(final TypeDescriptor<OutputT> outputType) {
return new MapElements<>(null, outputType, null);
}
/**
* For a {@code SerializableFunction<InputT, OutputT>} {@code fn} and output type descriptor,
* returns a {@code PTransform} that takes an input {@code PCollection<InputT>} and returns a
* {@code PCollection<OutputT>} containing {@code fn.apply(v)} for every element {@code v} in the
* input.
*
* <p>Example of use in Java 8:
*
* <pre>{@code
* PCollection<Integer> wordLengths = words.apply(
* MapElements.into(TypeDescriptors.integers())
* .via((String word) -> word.length()));
* }</pre>
*
* <p>In Java 7, the overload {@link #via(SimpleFunction)} is more concise as the output type
* descriptor need not be provided.
*/
public <NewInputT> MapElements<NewInputT, OutputT> via(
SerializableFunction<NewInputT, OutputT> fn) {
return new MapElements<>(
SimpleFunction.fromSerializableFunctionWithOutputType(fn, outputType),
null,
fn.getClass());
}
@Override
public PCollection<OutputT> expand(PCollection<? extends InputT> input) {
checkNotNull(fn, "Must specify a function on MapElements using .via()");
return input.apply(
"Map",
ParDo.of(
new DoFn<InputT, OutputT>() {
@ProcessElement
public void processElement(ProcessContext c) {
c.output(fn.apply(c.element()));
}
@Override
public void populateDisplayData(DisplayData.Builder builder) {
builder.delegate(MapElements.this);
}
@Override
public TypeDescriptor<InputT> getInputTypeDescriptor() {
return fn.getInputTypeDescriptor();
}
@Override
public TypeDescriptor<OutputT> getOutputTypeDescriptor() {
return fn.getOutputTypeDescriptor();
}
}));
}
@Override
public void populateDisplayData(DisplayData.Builder builder) {
super.populateDisplayData(builder);
builder
.include("mapFn", fn)
.add(fnClassDisplayData);
}
}
|
package io.hawt.dockerui;
import org.apache.http.*;
import org.apache.http.client.methods.AbortableHttpRequest;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.HeaderGroup;
import org.apache.http.util.EntityUtils;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.BitSet;
import java.util.Enumeration;
import java.util.Formatter;
import io.hawt.util.Strings;
/**
* Original implementation at https://github.com/mitre/HTTP-Proxy-Servlet, released under ASL 2.0.
*/
/**
* An HTTP reverse proxy/gateway servlet. It is designed to be extended for customization
* if desired. Most of the work is handled by
* <a href="http://hc.apache.org/httpcomponents-client-ga/">Apache HttpClient</a>.
* <p>
* There are alternatives to a servlet based proxy such as Apache mod_proxy if that is available to you. However
* this servlet is easily customizable by Java, secure-able by your web application's security (e.g. spring-security),
* portable across servlet engines, and is embeddable into another web application.
* </p>
* <p>
* Inspiration: http://httpd.apache.org/docs/2.0/mod/mod_proxy.html
* </p>
*
* @author David Smiley dsmiley@mitre.org
*/
public class ProxyServlet extends HttpServlet {
/* INIT PARAMETER NAME CONSTANTS */
/**
* A boolean parameter name to enable logging of input and target URLs to the servlet log.
*/
public static final String P_LOG = "log";
/**
* A boolean parameter name to enable forwarding of the client IP
*/
public static final String P_FORWARDEDFOR = "forwardip";
/**
* The parameter name for the target (destination) URI to proxy to.
*/
private static final String P_TARGET_URI = "targetUri";
/* MISC */
protected boolean doLog = false;
protected boolean doForwardIP = true;
/**
* User agents shouldn't send the url fragment but what if it does?
*/
protected boolean doSendUrlFragment = true;
protected CloseableHttpClient proxyClient;
private static final String STRING_HOST_HEADER_NAME = "Host";
public static final String DEFAULT_HOST_AND_PORT = "http://localhost:4243";
public static final String DEFAULT_SOCKET_PATH = "/var/run/docker.sock";
private ServletContext servletContext;
private String hostAndPort = DEFAULT_HOST_AND_PORT;
@Override
public String getServletInfo() {
return "A proxy servlet by David Smiley, dsmiley@mitre.org";
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
String doForwardIPString = servletConfig.getInitParameter(P_FORWARDEDFOR);
if (doForwardIPString != null) {
this.doForwardIP = Boolean.parseBoolean(doForwardIPString);
}
String doLogStr = servletConfig.getInitParameter(P_LOG);
if (doLogStr != null) {
this.doLog = Boolean.parseBoolean(doLogStr);
}
proxyClient = HttpClients.createSystem();
this.servletContext = servletConfig.getServletContext();
/*
if (LOG.isDebugEnabled()) {
LOG.debug("Registered OpenShiftProtocolSocketFactory Protocol for http: " + Protocol.getProtocol("http").getSocketFactory());
}
*/
boolean useSocket = false;
String dockerHost = System.getenv("DOCKER_HOST");
if (Strings.isBlank(dockerHost)) {
dockerHost = DEFAULT_HOST_AND_PORT;
}
hostAndPort = dockerHost;
if (hostAndPort.startsWith("tcp:")) {
hostAndPort = "http:" + hostAndPort.substring(4);
}
String socketPath = DEFAULT_SOCKET_PATH;
if (useSocket) {
servletContext.log("Using docker socket : " + socketPath);
/*
UnixSocketFactory socketFactory = new UnixSocketFactory(socketPath);
Protocol http = new Protocol("http", socketFactory, 80);
Protocol.registerProtocol("http", http);
*/
} else {
servletContext.log("Using docker URL: " + hostAndPort);
}
}
@Override
public void destroy() {
try {
proxyClient.close();
} catch (IOException e) {
log("While destroying servlet, shutting down httpclient: " + e, e);
}
super.destroy();
}
@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
throws ServletException, IOException {
// Make the Request
//note: we won't transfer the protocol version because I'm not sure it would truly be compatible
String method = servletRequest.getMethod();
String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
URI targetUriObj = null;
try {
targetUriObj = new URI(proxyRequestUri);
} catch (URISyntaxException e) {
throw new ServletException(e);
}
HttpRequest proxyRequest;
//spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null ||
servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
// Add the input entity (streamed)
// note: we don't bother ensuring we close the servletInputStream since the container handles it
eProxyRequest.setEntity(new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
proxyRequest = eProxyRequest;
} else
proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
copyRequestHeaders(servletRequest, proxyRequest, targetUriObj);
setXForwardedForHeader(servletRequest, proxyRequest);
HttpResponse proxyResponse = null;
try {
// Execute the request
if (doLog) {
log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri());
}
proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest);
// Process the response
int statusCode = proxyResponse.getStatusLine().getStatusCode();
if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode, targetUriObj)) {
//the response is already "committed" now without any body to send
//TODO copy response headers?
return;
}
// Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
// reason along too.
//noinspection deprecation
servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());
copyResponseHeaders(proxyResponse, servletResponse);
// Send the content to the client
copyResponseEntity(proxyResponse, servletResponse);
} catch (Exception e) {
//abort request, according to best practice with HttpClient
if (proxyRequest instanceof AbortableHttpRequest) {
AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
abortableHttpRequest.abort();
}
if (e instanceof RuntimeException)
throw (RuntimeException) e;
if (e instanceof ServletException)
throw (ServletException) e;
//noinspection ConstantConditions
if (e instanceof IOException)
throw (IOException) e;
throw new RuntimeException(e);
} finally {
// make sure the entire entity was consumed, so the connection is released
if (proxyResponse != null)
EntityUtils.consumeQuietly(proxyResponse.getEntity());
//Note: Don't need to close servlet outputStream:
// http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
}
}
protected boolean doResponseRedirectOrNotModifiedLogic(
HttpServletRequest servletRequest, HttpServletResponse servletResponse,
HttpResponse proxyResponse, int statusCode, URI targetUriObj)
throws ServletException, IOException {
// Check if the proxy response is a redirect
// The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
&& statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
if (locationHeader == null) {
throw new ServletException("Received status code: " + statusCode
+ " but no " + HttpHeaders.LOCATION + " header was found in the response");
}
// Modify the redirect to go to this proxy servlet rather that the proxied host
String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue(), targetUriObj.toString());
servletResponse.sendRedirect(locStr);
return true;
}
// 304 needs special handling. See:
// http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
// We get a 304 whenever passed an 'If-Modified-Since'
// header and the data on disk has not changed; server
// responds w/ a 304 saying I'm not going to send the
// body because the file has not changed.
if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return true;
}
return false;
}
protected void closeQuietly(Closeable closeable) {
try {
closeable.close();
} catch (IOException e) {
log(e.getMessage(), e);
}
}
/**
* These are the "hop-by-hop" headers that should not be copied.
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
* I use an HttpClient HeaderGroup class instead of Set<String> because this
* approach does case insensitive lookup faster.
*/
protected static final HeaderGroup hopByHopHeaders;
static {
hopByHopHeaders = new HeaderGroup();
String[] headers = new String[]{
"Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization",
"TE", "Trailers", "Transfer-Encoding", "Upgrade"};
for (String header : headers) {
hopByHopHeaders.addHeader(new BasicHeader(header, null));
}
}
/**
* Copy request headers from the servlet client to the proxy request.
*/
protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest, URI targetUriObj) {
// Get an Enumeration of all of the header names sent by the client
Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames();
while (enumerationOfHeaderNames.hasMoreElements()) {
String headerName = (String) enumerationOfHeaderNames.nextElement();
//Instead the content-length is effectively set via InputStreamEntity
if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH))
continue;
if (hopByHopHeaders.containsHeader(headerName))
continue;
Enumeration headers = servletRequest.getHeaders(headerName);
while (headers.hasMoreElements()) {//sometimes more than one value
String headerValue = (String) headers.nextElement();
// In case the proxy host is running multiple virtual servers,
// rewrite the Host header to ensure that we get content from
// the correct virtual server
if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) {
HttpHost host = URIUtils.extractHost(targetUriObj);
headerValue = host.getHostName();
if (host.getPort() != -1)
headerValue += ":" + host.getPort();
}
proxyRequest.addHeader(headerName, headerValue);
}
}
}
private void setXForwardedForHeader(HttpServletRequest servletRequest,
HttpRequest proxyRequest) {
String headerName = "X-Forwarded-For";
if (doForwardIP) {
String newHeader = servletRequest.getRemoteAddr();
String existingHeader = servletRequest.getHeader(headerName);
if (existingHeader != null) {
newHeader = existingHeader + ", " + newHeader;
}
proxyRequest.setHeader(headerName, newHeader);
}
}
/**
* Copy proxied response headers back to the servlet client.
*/
protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletResponse servletResponse) {
for (Header header : proxyResponse.getAllHeaders()) {
if (hopByHopHeaders.containsHeader(header.getName()))
continue;
servletResponse.addHeader(header.getName(), header.getValue());
}
}
/**
* Copy response body data (the entity) from the proxy to the servlet client.
*/
protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletResponse servletResponse) throws IOException {
HttpEntity entity = proxyResponse.getEntity();
if (entity != null) {
OutputStream servletOutputStream = servletResponse.getOutputStream();
entity.writeTo(servletOutputStream);
}
}
/**
* Reads the request URI from {@code servletRequest} and rewrites it. It's used to make the new request.
*/
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
ProxyDetails details = new ProxyDetails(hostAndPort, servletRequest, servletContext);
return details.getStringProxyURL();
}
/**
* For a redirect response from the target server, this translates {@code theUrl} to redirect to
* and translates it to one the original client can use.
*/
protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, String theUrl, String targetUri) {
//TODO document example paths
if (theUrl.startsWith(targetUri)) {
String curUrl = servletRequest.getRequestURL().toString();//no query
String pathInfo = servletRequest.getPathInfo();
if (pathInfo != null) {
assert curUrl.endsWith(pathInfo);
curUrl = curUrl.substring(0, curUrl.length() - pathInfo.length());//take pathInfo off
}
theUrl = curUrl + theUrl.substring(targetUri.length());
}
return theUrl;
}
/**
* Encodes characters in the query or fragment part of the URI.
* <p/>
* <p>Unfortunately, an incoming URI sometimes has characters disallowed by the spec. HttpClient
* insists that the outgoing proxied request has a valid URI because it uses Java's {@link URI}.
* To be more forgiving, we must escape the problematic characters. See the URI class for the
* spec.
*
* @param in example: name=value&foo=bar#fragment
*/
protected static CharSequence encodeUriQuery(CharSequence in) {
//Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things.
StringBuilder outBuf = null;
Formatter formatter = null;
for (int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
boolean escape = true;
if (c < 128) {
if (asciiQueryChars.get((int) c)) {
escape = false;
}
} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii
escape = false;
}
if (!escape) {
if (outBuf != null)
outBuf.append(c);
} else {
//escape
if (outBuf == null) {
outBuf = new StringBuilder(in.length() + 5 * 3);
outBuf.append(in, 0, i);
formatter = new Formatter(outBuf);
}
//leading %, 0 padded, width 2, capital hex
formatter.format("%%%02X", (int) c);//TODO
}
}
return outBuf != null ? outBuf : in;
}
protected static final BitSet asciiQueryChars;
static {
char[] c_unreserved = "_-!.~'()*".toCharArray();//plus alphanum
char[] c_punct = ",;:$&+=".toCharArray();
char[] c_reserved = "?/[]@".toCharArray();//plus punct
asciiQueryChars = new BitSet(128);
for (char c = 'a'; c <= 'z'; c++) asciiQueryChars.set((int) c);
for (char c = 'A'; c <= 'Z'; c++) asciiQueryChars.set((int) c);
for (char c = '0'; c <= '9'; c++) asciiQueryChars.set((int) c);
for (char c : c_unreserved) asciiQueryChars.set((int) c);
for (char c : c_punct) asciiQueryChars.set((int) c);
for (char c : c_reserved) asciiQueryChars.set((int) c);
asciiQueryChars.set((int) '%');//leave existing percent escapes in place
}
}
|
package club.zhcs.thunder.task;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.nutz.aop.interceptor.async.Async;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.integration.quartz.annotation.Scheduled;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.ContinueLoop;
import org.nutz.lang.Each;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.weixin.bean.WxTemplateData;
import org.nutz.weixin.spi.WxApi2;
import org.nutz.weixin.spi.WxResp;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import club.zhcs.thunder.bean.acl.User;
import club.zhcs.thunder.bean.apm.APMAlarm;
import club.zhcs.thunder.bean.apm.APMAlarm.Type;
import club.zhcs.thunder.biz.acl.UserService;
import club.zhcs.thunder.biz.eamil.EmailService;
import club.zhcs.titans.gather.CPUGather;
import club.zhcs.titans.gather.DISKGather;
import club.zhcs.titans.gather.MemoryGather;
import club.zhcs.titans.gather.NetInterfaceGather;
import club.zhcs.titans.utils.common.Ips;
import club.zhcs.titans.utils.common.Numbers;
import com.google.common.collect.Lists;
/**
* @author Kerbores(kerbores@gmail.com)
*
* @project app
*
* @file APMTask.java
*
* @description 告警检测业务
*
* @time 2016年3月15日 上午11:54:46
*
*/
@IocBean(name = "apmTask", fields = "dao", create = "init")
@Scheduled(cron = "*/10 * * * * ? ")
public class APMTask implements Job {
private static Log LOG = Logs.getLog(APMTask.class);
private Dao dao;
@Inject
PropertiesProxy config;
@Inject("wxApi")
WxApi2 api;
@Inject
UserService userService;
@Inject
EmailService emailService;
List<User> listeners = Lists.newArrayList();
public void init() {
String listener = config.get("alarm.listener");
Lang.each(listener.split(","), new Each<String>() {
@Override
public void invoke(int index, String lis, int length) throws ExitLoop, ContinueLoop, LoopException {
listeners.add(userService.fetch(Cnd.where("name", "=", lis)));
}
});
}
/**
*
*/
public APMTask() {
}
public APMTask(Dao dao) {
this.dao = dao;
}
public Dao getDao() {
return dao;
}
public void setDao(Dao dao) {
this.dao = dao;
}
public String hostIp = Ips.hostIp();
/*
* (non-Javadoc)
*
* @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
*/
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
try {
Sigar sigar = new Sigar();
MemoryGather memory = MemoryGather.gather(sigar);
// 内存
double jvmUsage, ramUsage, swapUsage;
if ((jvmUsage = memory.getJvm().getUsedPercent()) > config.getInt("jvm.alarm.percent")) {
alarm(Type.MEM, "内存警告", "JVM", jvmUsage, config.getInt("jvm.alarm.percent"));
}
if ((ramUsage = memory.getMem().getUsedPercent()) > config.getInt("ram.alarm.percent")) {
alarm(Type.MEM, "内存警告", "RAM", ramUsage, config.getInt("ram.alarm.percent"));
}
if (memory.getSwap().getTotal() != 0) {
if ((swapUsage = memory.getSwap().getUsed() * 100 / memory.getSwap().getTotal()) > config.getInt("swap.alarm.percent")) {
alarm(Type.MEM, "内存警告", "SWAP", swapUsage, config.getInt("swap.alarm.percent"));
}
}
CPUGather cpu = CPUGather.gather(sigar);
// CPU
double cpuUsage;
if ((cpuUsage = 100 - (cpu.getTimer().getIdle() * 100 / cpu.getTimer().getTotal())) > config.getInt("cpu.alarm.percent")) {
alarm(Type.MEM, "CPU警告", "CPU", cpuUsage, config.getInt("cpu.alarm.percent"));
}
// 磁盘
List<DISKGather> disks = DISKGather.gather(sigar);
for (DISKGather disk : disks) {
if (disk.getStat() != null && disk.getStat().getUsePercent() * 100 > config.getInt("disk.alarm.percent")) {
alarm(Type.DISK, "磁盘警告", "DISK", disk.getStat().getUsePercent(), config.getInt("disk.alarm.percent"));
}
}
// 网络流量
double niUsage, noUsage;
NetInterfaceGather ni = NetInterfaceGather.gather(sigar);
if ((niUsage = ni.getRxbps() * 100 / ni.getStat().getSpeed()) > config.getInt("network.alarm.percent")) {
alarm(Type.NETWORK, "流量警告", "NETWORK", niUsage, config.getInt("network.alarm.percent"));
}
if ((noUsage = ni.getTxbps() * 100 / ni.getStat().getSpeed()) > config.getInt("network.alarm.percent")) {
alarm(Type.NETWORK, "流量警告", "NETWORK", noUsage, config.getInt("network.alarm.percent"));
}
} catch (SigarException e) {
LOG.error(e);
}
}
/**
*
* @param type
* @param title
* @param device
* @param usage
* @param alarmPoint
*/
@Async
private void alarm(Type type, String title, String device, double usage, int alarmPoint) {
final APMAlarm alarm = new APMAlarm();
alarm.setType(type);
alarm.setIp(hostIp);
alarm.setMsg(String.format("%s:当前 %s 使用率 %f,高于预警值 %d", title, device, usage, alarmPoint));
alarm.setTitle(title);
alarm.setDevice(device);
alarm.setUsage(usage);
alarm.setAlarm(alarmPoint);
String alarmTypes = config.get(device.toLowerCase() + ".alarm.types");
Lang.each(alarmTypes.split(","), new Each<String>() {
@Override
public void invoke(int index, String type, int length) throws ExitLoop, ContinueLoop, LoopException {
if (Strings.equals(type, "EMAIL")) {// 发送邮件
sendALarmByEmail(alarm);
}
if (Strings.equals(type, "SMS")) {// 发送短信
}
if (Strings.equals(type, "WECHAT")) {// 发送微信消息
sendAlarmByWechat(alarm);
}
}
});
if (dao == null) {
LOG.debug(alarm);
} else {
dao.insert(alarm);
}
}
@Async
private void sendALarmByEmail(final APMAlarm alarm) {
Lang.each(listeners, new Each<User>() {
@Override
public void invoke(int index, User user, int length) throws ExitLoop, ContinueLoop, LoopException {
if (user == null) {
return;
}
emailService.sendAlarm(alarm, user.getEmail());
}
});
}
/**
* @param alarm
* @param alarm
*/
@Async
protected void sendAlarmByWechat(APMAlarm alarm) {
final Map<String, WxTemplateData> data = new HashMap<String, WxTemplateData>();
data.put("type", new WxTemplateData(alarm.getTitle()));
data.put("ip", new WxTemplateData(alarm.getIp()));
data.put("key", new WxTemplateData(alarm.getDevice()));
data.put("usage", new WxTemplateData(Numbers.keepPrecision(alarm.getUsage() + "", 2)));
data.put("alarm", new WxTemplateData(alarm.getAlarm() + ""));
Lang.each(listeners, new Each<User>() {
@Override
public void invoke(int index, User user, int length) throws ExitLoop, ContinueLoop, LoopException {
if (user == null) {
return;
}
WxResp resp = api.template_send(user.getOpenid(), "MnNkTihmclGa4OAFelkMwAwxUiKu41hsn2l9fHxLRdA", null, data);
LOG.debug(resp);
}
});
}
}
|
package com.joymain.jecs.util;
import java.beans.PropertyDescriptor;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.joymain.jecs.model.BaseObject;
import com.joymain.jecs.model.LabelValue;
import org.springframework.aop.support.AopUtils;
/**
* Utility class to convert one object to another.
*
* <p>
* <a href="ConvertUtil.java.html"><i>View Source</i></a>
* </p>
*
* @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
*/
public final class ConvertUtil {
//~ Static fields/initializers =============================================
private static Log log = LogFactory.getLog(ConvertUtil.class);
//~ Methods ================================================================
/**
* Method to convert a ResourceBundle to a Map object.
* @param rb a given resource bundle
* @return Map a populated map
*/
public static Map convertBundleToMap(ResourceBundle rb) {
Map map = new HashMap();
for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
String key = (String) keys.nextElement();
map.put(key, rb.getString(key));
}
return map;
}
public static Map convertListToMap(List list) {
Map map = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
LabelValue option = (LabelValue) it.next();
map.put(option.getLabel(), option.getValue());
}
return map;
}
/**
* Method to convert a ResourceBundle to a Properties object.
* @param rb a given resource bundle
* @return Properties a populated properties object
*/
public static Properties convertBundleToProperties(ResourceBundle rb) {
Properties props = new Properties();
for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
String key = (String) keys.nextElement();
props.put(key, rb.getString(key));
}
return props;
}
/**
* Convenience method used by tests to populate an object from a
* ResourceBundle
* @param obj an initialized object
* @param rb a resource bundle
* @return a populated object
*/
public static Object populateObject(Object obj, ResourceBundle rb) {
try {
Map map = convertBundleToMap(rb);
BeanUtils.copyProperties(obj, map);
} catch (Exception e) {
e.printStackTrace();
log.error("Exception occured populating object: " + e.getMessage());
}
return obj;
}
/**
* This method inspects a POJO or Form and figures out its pojo/form
* equivalent.
*
* @param o the object to inspect
* @return the Class of the persistable object
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static Object getOpposingObject(Object o) throws ClassNotFoundException,
InstantiationException,
IllegalAccessException {
String name = o.getClass().getName();
if (o instanceof BaseObject) {
if (log.isDebugEnabled()) {
log.debug("getting form equivalent of pojo...");
}
name = StringUtils.replace(name, ".model.", ".webapp.form.");
if (AopUtils.isCglibProxy(o)) {
name = name.substring(0, name.indexOf("$$"));
}
name += "Form";
} else {
if (log.isDebugEnabled()) {
log.debug("getting pojo equivalent of form...");
}
name = StringUtils.replace(name, ".webapp.form.", ".model.");
name = name.substring(0, name.lastIndexOf("Form"));
}
Class obj = Class.forName(name);
if (log.isDebugEnabled()) {
log.debug("returning className: " + obj.getName());
}
return obj.newInstance();
}
/**
* Convenience method to convert a form to a POJO and back again
*
* @param o the object to tranfer properties from
* @return converted object
*/
public static Object convert(Object o) throws Exception {
if (o == null) {
return null;
}
Object target = getOpposingObject(o);
BeanUtils.copyProperties(target, o);
return target;
}
/**
* Convenience method to convert Lists (in a Form) from POJOs to Forms.
* Also checks for and formats dates.
*
* @param o
* @return Object with converted lists
* @throws Exception
*/
public static Object convertLists(Object o) throws Exception {
if (o == null) {
return null;
}
Object target = null;
PropertyDescriptor[] origDescriptors =
PropertyUtils.getPropertyDescriptors(o);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
if (origDescriptors[i].getPropertyType().equals(List.class)) {
List list = (List) PropertyUtils.getProperty(o, name);
for (int j=0; j < list.size(); j++) {
Object origin = list.get(j);
target = convert(origin);
list.set(j, target);
}
PropertyUtils.setProperty(o, name, list);
}
}
return o;
}
}
|
/*
* Copyright (C) 2019 Everwin (www.everwin.fr)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package fr.everwin.open.api.model.companies;
import javax.ws.rs.core.Link;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.List;
import fr.everwin.open.api.model.core.BasicList;
/**
* @author d.storti
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "customerlist")
public class CustomerList extends BasicList<Company> {
private final static String METHOD="query";
@XmlElement(name = "company")
@XmlElementWrapper(name = "companies")
private List<Company> items;
@XmlElement(name = "selflink")
protected String href;
@XmlElement(name = "link")
@XmlElementWrapper(name = "links")
@XmlJavaTypeAdapter(Link.JaxbAdapter.class)
protected List<Link> links;
/**
*
*/
public CustomerList() {
// TODO Auto-generated constructor stub
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
@Override
public List<Link> getLinks() {
return links;
}
public void setLinks(List<Link> links) {
this.links = links;
}
@Override
public List<Company> getItems() {
return items;
}
@Override
public void setItems(List<Company> items) {
this.items = items;
}
}
|
package com.github.lunatrius.schematica.network.message;
import com.github.lunatrius.schematica.api.ISchematic;
import com.github.lunatrius.schematica.handler.DownloadHandler;
import com.github.lunatrius.schematica.world.storage.Schematic;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf;
import net.minecraft.item.ItemStack;
public class MessageDownloadBegin implements IMessage, IMessageHandler<MessageDownloadBegin, IMessage> {
public ItemStack icon;
public int width;
public int height;
public int length;
public MessageDownloadBegin() {
}
public MessageDownloadBegin(ISchematic schematic) {
this.icon = schematic.getIcon();
this.width = schematic.getWidth();
this.height = schematic.getHeight();
this.length = schematic.getLength();
}
@Override
public void fromBytes(ByteBuf buf) {
this.icon = ByteBufUtils.readItemStack(buf);
this.width = buf.readShort();
this.height = buf.readShort();
this.length = buf.readShort();
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeItemStack(buf, this.icon);
buf.writeShort(this.width);
buf.writeShort(this.height);
buf.writeShort(this.length);
}
@Override
public IMessage onMessage(MessageDownloadBegin message, MessageContext ctx) {
DownloadHandler.INSTANCE.schematic = new Schematic(message.icon, message.width, message.height, message.length);
return new MessageDownloadBeginAck();
}
}
|
package org.jvnet.ogc.gml.v_3_2_1.jts.gml2jts;
import org.locationtech.jts.geom.GeometryFactory;
public class GML321ToJTSConstants {
private GML321ToJTSConstants() {
}
public static final String[] DEFAULT_SRID_FORMAT_PATTERNS = {
"EPSG:{0,number,integer}",
"urn:ogc:def:crs:EPSG::{0,number,#}",
"urn:ogc:def:crs:EPSG:{1}:{0,number,#}",
"urn:x-ogc:def:crs:EPSG::{0,number,#}",
"urn:x-ogc:def:crs:EPSG:{1}:{0,number,#}",
"http://www.opengis.net/gml/srs/epsg.xml#{0,number,#}" };
public static final GeometryFactory DEFAULT_GEOMETRY_FACTORY = new GeometryFactory();
public static final GML321ToJTSSRIDConverterInterface DEFAULT_SRID_CONVERTER = new GML321ToJTSSRIDConverter(
DEFAULT_SRID_FORMAT_PATTERNS);
}
|
package com.ypx.imagepicker.data;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import com.ypx.imagepicker.bean.ImageSet;
import com.ypx.imagepicker.bean.MimeType;
import com.ypx.imagepicker.bean.selectconfig.BaseSelectConfig;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Set;
import static com.ypx.imagepicker.data.MediaStoreConstants.COLUMN_BUCKET_DISPLAY_NAME;
import static com.ypx.imagepicker.data.MediaStoreConstants.COLUMN_BUCKET_ID;
import static com.ypx.imagepicker.data.MediaStoreConstants.COLUMN_COUNT;
import static com.ypx.imagepicker.data.MediaStoreConstants.COLUMN_URI;
/**
* Description: 媒体文件夹数据
* <p>
* Author: peixing.yang
* Date: 2019/4/11
*/
public class MediaSetsDataSource implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int LOADER_ID = 1;
private WeakReference<FragmentActivity> mContext;
private LoaderManager mLoaderManager;
private MediaSetProvider mediaSetProvider;
private boolean isLoadVideo;
private boolean isLoadImage;
private Set<MimeType> mimeTypeSet = MimeType.ofAll();
public MediaSetsDataSource setMimeTypeSet(BaseSelectConfig config) {
isLoadImage = config.isShowImage();
isLoadVideo = config.isShowVideo();
mimeTypeSet = config.getMimeTypes();
return this;
}
public MediaSetsDataSource setMimeTypeSet(Set<MimeType> mimeTypeSet) {
this.mimeTypeSet = mimeTypeSet;
for (MimeType mimeType : mimeTypeSet) {
if (MimeType.ofVideo().contains(mimeType)) {
isLoadVideo = true;
}
if (MimeType.ofImage().contains(mimeType)) {
isLoadImage = true;
}
}
return this;
}
public void loadMediaSets(MediaSetProvider mediaSetProvider) {
this.mediaSetProvider = mediaSetProvider;
mLoaderManager.initLoader(LOADER_ID, null, this);
}
public static MediaSetsDataSource create(FragmentActivity activity) {
return new MediaSetsDataSource(activity);
}
private MediaSetsDataSource(FragmentActivity activity) {
mContext = new WeakReference<>(activity);
mLoaderManager = LoaderManager.getInstance(mContext.get());
}
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Context context = mContext.get();
return MediaSetsLoader.create(context, mimeTypeSet, isLoadVideo, isLoadImage);
}
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) {
FragmentActivity context = mContext.get();
if (context == null) {
return;
}
ArrayList<ImageSet> imageSetList = new ArrayList<>();
if (!context.isDestroyed() && cursor.moveToFirst() && !cursor.isClosed()) {
do {
ImageSet imageSet = new ImageSet();
imageSet.id = getString(cursor, COLUMN_BUCKET_ID);
imageSet.name = getString(cursor, COLUMN_BUCKET_DISPLAY_NAME);
imageSet.coverPath = getString(cursor, COLUMN_URI);
imageSet.count = getInt(cursor, COLUMN_COUNT);
imageSetList.add(imageSet);
} while (!context.isDestroyed() && cursor.moveToNext() && !cursor.isClosed());
}
if (mediaSetProvider != null) {
mediaSetProvider.providerMediaSets(imageSetList);
}
if (mLoaderManager != null) {
mLoaderManager.destroyLoader(LOADER_ID);
}
}
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
}
public interface MediaSetProvider {
void providerMediaSets(ArrayList<ImageSet> imageSets);
}
private long getLong(Cursor data, String text) {
int index = hasColumn(data, text);
if (index != -1) {
return data.getLong(index);
} else {
return 0;
}
}
private int getInt(Cursor data, String text) {
int index = hasColumn(data, text);
if (index != -1) {
return data.getInt(index);
} else {
return 0;
}
}
private String getString(Cursor data, String text) {
int index = hasColumn(data, text);
if (index != -1) {
return data.getString(index);
} else {
return "";
}
}
private int hasColumn(Cursor data, String id) {
return data.getColumnIndex(id);
}
}
|
// ============================================================================
//
// Copyright (C) 2006-2017 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.components.salesforce.connection.oauth;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.talend.components.common.oauth.Oauth2ImplicitClient;
import org.talend.components.common.oauth.properties.Oauth2ImplicitFlowProperties;
import org.talend.daikon.i18n.GlobalI18N;
import org.talend.daikon.i18n.I18nMessages;
/**
* This use the Oauth2 implicit flow that need a user interaction.
* This connection get and store a refresh token after user manual consent and store it in a local file to reuse it for future
* authentication
*/
public class SalesforceImplicitConnection {
private final Logger LOGGER = LoggerFactory.getLogger(SalesforceImplicitConnection.class.getName());
private static final I18nMessages messages = GlobalI18N.getI18nMessageProvider()
.getI18nMessages(SalesforceImplicitConnection.class);
private static final String REFRESHTOKEN_KEY = "refreshtoken"; //$NON-NLS-1$
private String url;
private Oauth2ImplicitFlowProperties implicitFlowProp;
public SalesforceImplicitConnection(Oauth2ImplicitFlowProperties oauthProperties, String url) {
this.implicitFlowProp = oauthProperties;
this.url = url;
}
/**
* Try to get a token using the stored refresh token. if no refresh token. we try to get it and stored in a local file
*/
public SalesforceOAuthAccessTokenResponse getToken() {
SalesforceOAuthAccessTokenResponse token = null;
// 1. if tokenFile exist, try refresh token
String tokenFilePath = implicitFlowProp.tokenFile.getStringValue();
if (tokenFilePath != null) {
token = tryTokenRefresh(tokenFilePath, implicitFlowProp.clientId.getStringValue(),
implicitFlowProp.clientSecret.getStringValue());
}
// 2. try to auth if session_id can't be retrieved
if (token == null) {
token = doAuthenticate(implicitFlowProp.clientId.getStringValue(), implicitFlowProp.clientSecret.getStringValue(),
implicitFlowProp.callbackHost.getStringValue(), implicitFlowProp.callbackPort.getValue());
}
// 3.if refresh token & tokenFile exist, store
if (token != null && token.getRefreshToken() != null && tokenFilePath != null) {
storeToken(token, tokenFilePath);
}
return token;
}
/**
* Try a token refresh from the file passed in the parameter.
*
* @param tokenFilePath : path to the file that contain the REFRESH TOKEN
* @param clientSecret
* @param clientId
* @return a valid token if refresh is done correctly, <code>null<code> otherwise
*/
private SalesforceOAuthAccessTokenResponse tryTokenRefresh(String tokenFilePath, String clientId, String clientSecret) {
File tokenFile = new File(tokenFilePath);
if (tokenFile.exists()) {
try (FileInputStream inputStream = new FileInputStream(tokenFilePath)) {
Properties prop = new Properties();
prop.load(inputStream);
String storedRefreshToken = (String) prop.get(REFRESHTOKEN_KEY);
if (storedRefreshToken != null) {
Oauth2ImplicitClient oauthClient = new Oauth2ImplicitClient.RefreshTokenBuilder(new URL(url + "/token"),
clientId, clientSecret).setRefreshToken(storedRefreshToken).build();
return oauthClient.getToken(SalesforceOAuthAccessTokenResponse.class);
}
} catch (FileNotFoundException e) {// ignored exception
LOGGER.warn(messages.getMessage("warn.notFoundRefreshToken"), e);
} catch (IOException e) {// ignored exception
LOGGER.warn(messages.getMessage("warn.cantRefreshToken"), e);
}
}
return null;
}
/**
* Get the authentication token from salesforce
*
* @param callBackPort
* @param callBackHost
* @param clientSecret
* @param clientId
*
* @return a valid token
* @throws RuntimeException if authentication failed, or the returned token is <code>null</code>
*/
private SalesforceOAuthAccessTokenResponse doAuthenticate(String clientId, String clientSecret, String callbackHost,
Integer callbackPort) {
try {
Oauth2ImplicitClient oauthClient = new Oauth2ImplicitClient.AuthorizationCodeBuilder(new URL(url + "/token"), //$NON-NLS-1$
clientId, clientSecret).setAuthorizationLocation(new URL(url + "/authorize")) //$NON-NLS-1$
.setCallbackURL(new URL("https://" + callbackHost + ":" + callbackPort)).setResponseType("code")
.build();
SalesforceOAuthAccessTokenResponse token = oauthClient.getToken(SalesforceOAuthAccessTokenResponse.class);
if (token == null) {
throw new RuntimeException(messages.getMessage("err.nullToken"));
}
return token;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
/**
* Store the token to a file
*
* @param token : valid token that contain the refresh token
* @param tokenFilePath : path to the file where the refresh token will be stored
*
* @throws RuntimeException if the refresh token can't be stored
*/
private void storeToken(SalesforceOAuthAccessTokenResponse token, String tokenFilePath) {
File tokenFile = new File(tokenFilePath);
if (!tokenFile.exists()) {
try {
tokenFile.getParentFile().mkdirs();
tokenFile.createNewFile();
} catch (IOException e) {
throw new RuntimeException(messages.getMessage("err.tokenFileCreationFailed"), e);
}
}
try (FileOutputStream outputStream = new FileOutputStream(tokenFile)) {
Properties prop = new Properties();
prop.setProperty(REFRESHTOKEN_KEY, token.getRefreshToken());
prop.store(outputStream, null);
} catch (IOException e) {
throw new RuntimeException(messages.getMessage("err.unexpectedTokenFileCreationError"), e);
}
}
}
|
package concurrency;//: concurrency/HorseRace.java
// Using CyclicBarriers.
import java.util.concurrent.*;
import java.util.*;
import static net.mindview.util.Print.*;
class Horse implements Runnable {
private static int counter = 0;
private final int id = counter++;
private int strides = 0;
private static Random rand = new Random(47);
private static CyclicBarrier barrier;
public Horse(CyclicBarrier b) { barrier = b; }
public synchronized int getStrides() { return strides; }
public void run() {
try {
while(!Thread.interrupted()) {
synchronized(this) {
strides += rand.nextInt(3); // Produces 0, 1 or 2
}
barrier.await();
}
} catch(InterruptedException e) {
// A legitimate way to exit
} catch(BrokenBarrierException e) {
// This one we want to know about
throw new RuntimeException(e);
}
}
public String toString() { return "Horse " + id + " "; }
public String tracks() {
StringBuilder s = new StringBuilder();
for(int i = 0; i < getStrides(); i++)
s.append("*");
s.append(id);
return s.toString();
}
}
public class HorseRace {
static final int FINISH_LINE = 75;
private List<Horse> horses = new ArrayList<Horse>();
private ExecutorService exec =
Executors.newCachedThreadPool();
private CyclicBarrier barrier;
public HorseRace(int nHorses, final int pause) {
barrier = new CyclicBarrier(nHorses, new Runnable() {
public void run() {
StringBuilder s = new StringBuilder();
for(int i = 0; i < FINISH_LINE; i++)
s.append("="); // The fence on the racetrack
print(s);
for(Horse horse : horses)
print(horse.tracks());
for(Horse horse : horses)
if(horse.getStrides() >= FINISH_LINE) {
print(horse + "won!");
exec.shutdownNow();
return;
}
try {
TimeUnit.MILLISECONDS.sleep(pause);
} catch(InterruptedException e) {
print("barrier-action sleep interrupted");
}
}
});
for(int i = 0; i < nHorses; i++) {
Horse horse = new Horse(barrier);
horses.add(horse);
exec.execute(horse);
}
}
public static void main(String[] args) {
int nHorses = 7;
int pause = 200;
if(args.length > 0) { // Optional argument
int n = new Integer(args[0]);
nHorses = n > 0 ? n : nHorses;
}
if(args.length > 1) { // Optional argument
int p = new Integer(args[1]);
pause = p > -1 ? p : pause;
}
new HorseRace(nHorses, pause);
}
} /* (Execute to see output) *///:~
|
package sg.atom.corex.spatial;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import com.google.common.base.Predicate;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.SceneGraphVisitor;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* SceneGraphHelper provide various functions in the scenegraph and spatial
* related in corporated with Spatials. SceneGraphHelper consider a scenegraph
* is just like a repository of data or "a big fat tree model" for slurping and
* searching around.
*
* <p>
* <b>Features</b>
*
* <ul> <li>It provide various ways to do query (scan) in the scenegraph: by
* spanning type (no condition), By name, by path, by type, by hash, by a path
* query, a graph query.</li>
*
* <li>It provide high performance way : index/ compress/ partition that
* scenegraph.</li>
*
* <li>It provide custom functions/ obversation/ hook/ data in any spatial. So,
* monitors and events are possible!</li>
*
* <li>It provide specific Lock/ transactional/ authority aware functions over
* any spatial. </li>
*
* </ul>
* <p>
* SceneGraphUtils.wrap(Node rootNode) builds a SpatialInfos MVCC concurrent
* tree upon the rootNode. Any operation over the holded SpatialInfo of the
* associated Node will result as concurrent operations (delay, defered, lazy,
* parallel ...) and the dataflow is monitored in the dataflow framework.
*
* <p>
* SceneGraphUtils.$(Node rootNode) provide fluent (JQuery like) upon the tree.
*
* <p>
* CHANGE V.1.0: Changed SceneGraphHelper to SceneGraphUtils to get name
* convention persist.
*
* @author atomix
*/
public class SceneGraphUtils {
private static Control controlResult = null;
private static Object dataResult = null;
private static Spatial result = null;
private static List<Control> controlResults = new ArrayList<Control>();
private static List<Spatial> spatialResults = new ArrayList<Spatial>();
private static List<Object> dataResults = new ArrayList<Object>();
// Finding things ------------------------------------------------------------
public static Spatial findSpatialByPath(String path, Node searchNode) {
String name[] = path.split("/");
Node currentNode = searchNode;
Spatial result;
int i = 0;
for (String currentName : name) {
i++;
result = currentNode.getChild(currentName);
if (result == null) {
// this current node don't have a child has the current name!
return null;
} else {
if (i == name.length) {
return result;
} else {
if (result instanceof Node) {
currentNode = (Node) result;
} else {
// Path inside a Geometry , WRONG!
return null;
}
}
}
}
return null;
}
public static Spatial findSpatialByControlTravelUp(Spatial sp, Class<? extends Control> aClass) {
if (sp.getControl(aClass) == null) {
if (sp.getParent() != null) {
return findSpatialByControlTravelUp(sp.getParent(), aClass);
} else {
return null;
}
} else {
return sp;
}
}
public static <T extends Control> T findControlTravelUp(Spatial sp, Class<T> aClass) {
if (sp.getControl(aClass) == null) {
if (sp.getParent() != null) {
return findControlTravelUp(sp.getParent(), aClass);
} else {
return null;
}
} else {
return sp.getControl(aClass);
}
}
public static <T extends Control> T findControl(Spatial sp, final Class<T> aClass, boolean travelUp) {
controlResult = null;
sp.breadthFirstTraversal(new SceneGraphVisitor() {
@Override
public void visit(Spatial spatial) {
if (spatial.getControl(aClass) != null) {
controlResult = spatial.getControl(aClass);
}
}
});
return (T) controlResult;
}
public static List<Geometry> findGeometries(Node node, List<Geometry> geoms) {
for (Iterator<Spatial> it = node.getChildren().iterator(); it.hasNext();) {
Spatial spatial = it.next();
if (spatial instanceof Geometry) {
geoms.add((Geometry) spatial);
} else if (spatial instanceof Node) {
findGeometries((Node) spatial, geoms);
}
}
return geoms;
}
public static Spatial findSpatialByName(final String name, Node parent, final boolean useReg) {
parent.breadthFirstTraversal(new SceneGraphVisitor() {
public void visit(Spatial spatial) {
if (useReg) {
if (spatial.getName().matches(name)) {
result = spatial;
return;
}
} else {
if (spatial.getName().equals(name)) {
result = spatial;
return;
}
}
}
});
return result;
}
public static Geometry findGeoByName(String name, Node parent) {
for (Spatial sp : parent.getChildren()) {
if (sp instanceof Geometry) {
if (sp.getName().equals(name)) {
return (Geometry) sp;
}
}
}
for (Spatial sp : parent.getChildren()) {
if (sp instanceof Node) {
Geometry result = findGeoByName(name, (Node) sp);
if (result != null) {
return (Geometry) result;
}
}
}
return null;
}
public static Geometry findFirstGeo(Spatial sp) {
if (sp instanceof Geometry) {
return (Geometry) sp;
} else {
for (Spatial child : ((Node) sp).getChildren()) {
if (!(child instanceof Geometry)) {
continue; // could be an attachment node, ignore.
}
Geometry geom = (Geometry) child;
return geom;
}
}
return null;
}
public static <T extends Control> T findFirstControl(Spatial sp, final Class<T> aClass) {
controlResult = null;
sp.breadthFirstTraversal(new SceneGraphVisitor() {
@Override
public void visit(Spatial spatial) {
if (spatial.getControl(aClass) != null) {
controlResult = spatial.getControl(aClass);
}
}
});
return (T) controlResult;
}
public static <T extends Spatial> T findFirstBy(Class<T> clazz, Predicate<Spatial>... predicate) {
return null;
}
public static <T extends Spatial> List<T> findBy(Class<T> clazz, Predicate<Spatial>... predicate) {
return null;
}
public static Spatial findFirstBy(Predicate<Spatial>... predicate) {
return null;
}
public static List<Spatial> findBy(Predicate<Spatial>... predicate) {
return null;
}
public static <T extends Spatial> List<T> findByPath(Class<T> clazz, String path) {
return null;
}
public static <T extends Spatial> List<T> findByXPath(Class<T> clazz, String path) {
return null;
}
public static <T extends Spatial> List<T> findByGPath(Class<T> clazz, String path) {
return null;
}
//Structure ----------------------------------------------------------------
//Relational & Graph query --------------------------------------------------------------
//Functional-------------------------------------------------------------
//Positional ---------------------------------------------------------------
//Data & Compress-----------------------------------------------------------
}
|
package com.example.empty;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.empty", appContext.getPackageName());
}
}
|
/*****************************************************************
* 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.cayenne.event;
import org.apache.cayenne.util.Util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
public class EventSubjectTest {
@Test
public void testIllegalArguments() {
try {
EventSubject.getSubject(null, "Subject");
fail();
} catch (IllegalArgumentException ex) {
// OK
}
try {
EventSubject.getSubject(Object.class, null);
fail();
} catch (IllegalArgumentException ex) {
// OK
}
try {
EventSubject.getSubject(Object.class, "");
fail();
} catch (IllegalArgumentException ex) {
// OK
}
}
@Test
public void testEqualityOfClonedSubjects() throws Exception {
EventSubject s1 = EventSubject.getSubject(EventSubjectTest.class, "MySubject");
EventSubject s2 = (EventSubject) Util.cloneViaSerialization(s1);
assertNotSame(s1, s2);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
}
@Test
public void testIdenticalSubject() {
EventSubject s1 = EventSubject.getSubject(EventSubjectTest.class, "MySubject");
EventSubject s2 = EventSubject.getSubject(EventSubjectTest.class, "MySubject");
assertSame(s1, s2);
}
@Test
public void testEqualityOfIdenticalSubjects() {
EventSubject s1 = EventSubject.getSubject(EventSubjectTest.class, "MySubject");
EventSubject s2 = EventSubject.getSubject(EventSubjectTest.class, "MySubject");
assertEquals(s1, s2);
}
@Test
public void testEqualityOfSubjectsByDifferentOwner() {
EventSubject s1 = EventSubject.getSubject(EventSubject.class, "MySubject");
EventSubject s2 = EventSubject.getSubject(EventSubjectTest.class, "MySubject");
assertFalse(s1.equals(s2));
}
@Test
public void testEqualityOfSubjectsByDifferentTopic() {
EventSubject s1 = EventSubject.getSubject(EventSubjectTest.class, "Subject1");
EventSubject s2 = EventSubject.getSubject(EventSubjectTest.class, "Subject2");
assertFalse(s1.equals(s2));
}
@Test
public void testSubjectEqualsNull() {
EventSubject s1 = EventSubject.getSubject(EventSubjectTest.class, "MySubject");
assertFalse(s1.equals(null));
}
// TODO: (Andrus) This test can not be run reliably and in fact consistently
// fails in some environments, since forcing GC at a certain time is not
// guaranteed.
/*
* public void testSubjectGC() { EventSubject s =
* EventSubject.getSubject(EventSubjectTst.class, "GCSubject"); long hash1 =
* s.hashCode(); // try to make the subject go away s = null; System.gc();
* System.gc(); s = EventSubject.getSubject(EventSubjectTst.class,
* "GCSubject"); long hash2 = s.hashCode(); Assert.assertTrue(hash1 !=
* hash2); }
*/
}
|
package org.adorsys.adcore.jpa;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class SearchResult<T>
{
/*
* The number of entities matching this search.
*/
private Long count;
/*
* The result list.
*/
private List<T> resultList;
/*
* The original search input object. For stateless clients.
*/
private SearchInput<T> searchInput;
public SearchResult()
{
super();
}
public SearchResult(Long count, List<T> resultList,
SearchInput<T> searchInput)
{
super();
this.count = count;
this.resultList = resultList;
this.searchInput = searchInput;
}
public Long getCount()
{
return count;
}
public List<T> getResultList()
{
return resultList;
}
public SearchInput<T> getSearchInput()
{
return searchInput;
}
public void setCount(Long count)
{
this.count = count;
}
public void setResultList(List<T> resultList)
{
this.resultList = resultList;
}
public void setSearchInput(SearchInput<T> searchInput)
{
this.searchInput = searchInput;
}
}
|
package org.cyclops.integratedtunnels.core.part;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.network.PacketBuffer;
import org.cyclops.cyclopscore.helper.ValueNotifierHelpers;
import org.cyclops.integrateddynamics.api.part.IPartContainer;
import org.cyclops.integrateddynamics.api.part.IPartType;
import org.cyclops.integrateddynamics.api.part.PartTarget;
import org.cyclops.integrateddynamics.core.helper.PartHelpers;
import org.cyclops.integrateddynamics.core.inventory.container.ContainerPartSettings;
import org.cyclops.integratedtunnels.RegistryEntries;
import java.util.Optional;
/**
* @author rubensworks
*/
public class ContainerInterfaceSettings extends ContainerPartSettings {
private final int lastChannelInterfaceValueId;
public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, PacketBuffer packetBuffer) {
this(id, playerInventory, new Inventory(0), PartHelpers.readPartTarget(packetBuffer), Optional.empty(), PartHelpers.readPart(packetBuffer));
}
public ContainerInterfaceSettings(int id, PlayerInventory playerInventory, IInventory inventory,
PartTarget target, Optional<IPartContainer> partContainer, IPartType partType) {
super(RegistryEntries.CONTAINER_INTERFACE_SETTINGS, id, playerInventory, inventory, target, partContainer, partType);
lastChannelInterfaceValueId = getNextValueId();
}
@Override
protected int getPlayerInventoryOffsetY() {
return 134;
}
@Override
protected void initializeValues() {
super.initializeValues();
ValueNotifierHelpers.setValue(this, lastChannelInterfaceValueId, ((PartTypeInterfacePositionedAddon.State) getPartState()).getChannelInterface());
}
public int getLastChannelInterfaceValueId() {
return lastChannelInterfaceValueId;
}
public int getLastChannelInterfaceValue() {
return ValueNotifierHelpers.getValueInt(this, lastChannelInterfaceValueId);
}
@Override
protected void updatePartSettings() {
super.updatePartSettings();
((PartTypeInterfacePositionedAddon.State) getPartState()).setChannelInterface(getLastChannelInterfaceValue());
}
}
|
package com.github.ingogriebsch.sample.spring.jdbc.postgresql.lob.handling;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class ContentDispositionUtilsTest {
@Test(expected = NullPointerException.class)
public void attachement_should_throw_exception_if_input_is_null() {
ContentDispositionUtils.attachment(null);
}
@Test
public void attachement_should_return_string_containing_filename() {
String filename = "test.txt";
assertThat(ContentDispositionUtils.attachment(filename)).contains(filename);
}
@Test(expected = NullPointerException.class)
public void inline_should_throw_exception_if_input_is_null() {
ContentDispositionUtils.inline(null);
}
@Test
public void inline_should_return_string_containing_filename() {
String filename = "test.txt";
assertThat(ContentDispositionUtils.inline(filename)).contains(filename);
}
}
|
package experiment;
import java.util.ArrayList;
public class Grupo extends Element {
private String observacao;
//private ArrayList<ArquivoInterpretacao> arquivosInterpretacaoGrupo = new ArrayList<>();
//private ArrayList<Interpretacao> interpretacoes = new ArrayList<>();
public Grupo() {
super("grupo");
}
public String getObservacao() {
return observacao;
}
public void setObservacao(String observacao) {
this.observacao = observacao;
}
/*
public ArrayList<ArquivoInterpretacao> getArquivosInterpretacaoGrupo() {
return arquivosInterpretacaoGrupo;
}
public void setArquivosInterpretacaoGrupo(ArrayList<ArquivoInterpretacao> arquivosInterpretacaoGrupo) {
this.arquivosInterpretacaoGrupo = arquivosInterpretacaoGrupo;
}
public ArrayList<Interpretacao> getInterpretacoes() {
return interpretacoes;
}
public void setInterpretacoes(ArrayList<Interpretacao> interpretacoes) {
this.interpretacoes = interpretacoes;
}
*/
}
|
/*
* Copyright 2018 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.web.view;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.navercorp.pinpoint.common.server.bo.stat.DataSourceBo;
import com.navercorp.pinpoint.loader.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.web.mapper.stat.sampling.sampler.DataSourceSampler;
import com.navercorp.pinpoint.web.test.util.DataSourceTestUtils;
import com.navercorp.pinpoint.web.util.TimeWindow;
import com.navercorp.pinpoint.common.server.util.time.Range;
import com.navercorp.pinpoint.web.vo.stat.SampledDataSource;
import com.navercorp.pinpoint.web.vo.stat.chart.agent.DataSourceChart;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
/**
* @author Taejin Koo
*/
@RunWith(MockitoJUnitRunner.class)
public class DataSourceChartSerializerTest {
private static final int MIN_VALUE_OF_MAX_CONNECTION_SIZE = 20;
private static final int CREATE_TEST_OBJECT_MAX_SIZE = 10;
private final DataSourceSampler sampler = new DataSourceSampler();
private final ObjectMapper mapper = new ObjectMapper();
@Mock
private ServiceTypeRegistryService serviceTypeRegistryService;
@Before
public void setUp() throws Exception {
when(serviceTypeRegistryService.findServiceType(any(Short.class))).thenReturn(ServiceType.UNKNOWN);
}
@Test
public void serializeTest() throws Exception {
long currentTimeMillis = System.currentTimeMillis();
TimeWindow timeWindow = new TimeWindow(Range.between(currentTimeMillis - 300000, currentTimeMillis));
List<SampledDataSource> sampledDataSourceList = createSampledDataSourceList(timeWindow);
DataSourceChart dataSourceChartGroup = new DataSourceChart(timeWindow, sampledDataSourceList, serviceTypeRegistryService);
String jsonValue = mapper.writeValueAsString(dataSourceChartGroup);
Map<?, ?> map = mapper.readValue(jsonValue, Map.class);
Assert.assertTrue(map.containsKey("id"));
Assert.assertTrue(map.containsKey("jdbcUrl"));
Assert.assertTrue(map.containsKey("databaseName"));
Assert.assertTrue(map.containsKey("serviceType"));
Assert.assertTrue(map.containsKey("charts"));
}
private List<SampledDataSource> createSampledDataSourceList(TimeWindow timeWindow) {
List<SampledDataSource> sampledDataSourceList = new ArrayList<>();
int maxConnectionSize = RandomUtils.nextInt(MIN_VALUE_OF_MAX_CONNECTION_SIZE, MIN_VALUE_OF_MAX_CONNECTION_SIZE * 2);
long from = timeWindow.getWindowRange().getFrom();
long to = timeWindow.getWindowRange().getTo();
for (long i = from; i < to; i += timeWindow.getWindowSlotSize()) {
sampledDataSourceList.add(createSampledDataSource(i, maxConnectionSize));
}
return sampledDataSourceList;
}
private SampledDataSource createSampledDataSource(long timestamp, int maxConnectionSize) {
int testObjectSize = RandomUtils.nextInt(1, CREATE_TEST_OBJECT_MAX_SIZE);
List<DataSourceBo> dataSourceBoList = DataSourceTestUtils.createDataSourceBoList(1, testObjectSize, maxConnectionSize);
return sampler.sampleDataPoints(0, timestamp, dataSourceBoList, null);
}
}
|
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.control.security;
import ${package}.model.domain.SessionUser;
public interface SessionInspector {
SessionUser getUser();
String getToken();
}
|
package com.atguigu.gmall.oms.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.gmall.oms.entity.OrderReturnApplyEntity;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.QueryCondition;
/**
* 订单退货申请
*
* @author lixianfeng
* @email lxf@atguigu.com
* @date 2020-02-08 18:35:08
*/
public interface OrderReturnApplyService extends IService<OrderReturnApplyEntity> {
PageVo queryPage(QueryCondition params);
}
|
package com.example.tetianapriadko.people.dialog_fragments;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
public class DlgFragDeleteTeachList extends DlgFragAbstractOkCancel{
@Override
protected String getOKText() {
return "Yes, delete it";
}
@Override
protected String getCancelText() {
return "Cancel";
}
@Override
protected void performOK(DialogInterface dialog, int id) {
if (getTargetFragment() != null) {
Intent intent = new Intent();
intent.putExtra("positionTeacher", getArguments().getInt("positionTeacher"));
getTargetFragment().onActivityResult(getTargetRequestCode(),
Activity.RESULT_OK,
intent);
dismiss();
} else {
dismiss();
}
}
@Override
protected void performCancel(DialogInterface dialog, int id) {
if (getTargetFragment() != null) {
getTargetFragment().onActivityResult(getTargetRequestCode(),
Activity.RESULT_CANCELED,
null);
dismiss();
} else {
dismiss();
}
}
@Override
protected View getTitleView() {
return null;
}
@Override
protected String getTitle() {
return "Delete Teacher?";
}
@Override
protected View getRootView() {
return null;
}
}
|
package posters.loadtest.util;
import java.util.UUID;
import org.apache.commons.lang3.RandomStringUtils;
import com.xceptance.xlt.api.data.GeneralDataProvider;
/**
* Provides a customer account.
*/
public class Account
{
/**
* the email address
*/
private String email;
/**
* the first name
*/
private String firstName;
/**
* the last name
*/
private String lastName;
/**
* the password
*/
private String password;
/**
* Create generic generated account.
*/
public Account()
{
final GeneralDataProvider provider = GeneralDataProvider.getInstance();
firstName = provider.getFirstName(false);
lastName = provider.getLastName(false);
email = RandomStringUtils.randomAlphanumeric(2) + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 12) + "@varmail.de";
password = RandomStringUtils.randomAlphanumeric(10);
}
public String getEmail()
{
return email;
}
public void setEmail(final String email)
{
this.email = email;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(final String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(final String lastName)
{
this.lastName = lastName;
}
public String getPassword()
{
return password;
}
public void setPassword(final String password)
{
this.password = password;
}
}
|
package net.ibizsys.pswf.core;
/**
* 流程版本模型
* @author lionlau
*
*/
public interface IWFVersionModel
{
/**
* 初始化
* @param iWFModel
* @throws Exception
*/
void init(IWFModel iWFModel) throws Exception;
/**
* 获取标识
* @return
*/
String getId();
/**
* 获取名称
* @return
*/
String getName();
/**
* 获取流程版本
* @return
*/
int getWFVersion();
/**
* 获取工作流模型对象
* @return
*/
IWFModel getWFModel();
/**
* 获取流程处理集合
* @return
*/
java.util.Iterator<IWFProcessModel> getWFProcessModels();
/**
* 获取流程连接集合
* @return
*/
java.util.Iterator<IWFLinkModel> getWFLinkModels();
/**
* 获取流程处理模型对象
* @return
*/
IWFProcessModel getWFProcessModel(String strWFProcessModelName,boolean bTryMode)throws Exception;
/**
* 获取流程步骤值对应的处理模型对象
* @param strWFStepValue
* @param bTryMode 尝试模式
* @return
* @throws Exception
*/
IWFProcessModel getWFProcessModelByWFStepValue(String strWFStepValue,boolean bTryMode)throws Exception;
/**
* 获取开始的流程处理
* @return
*/
IWFProcessModel getStartWFProcessModel();
/**
* 获取当前流程版本是否有并行子流程处理模型
* @return
*/
boolean hasWFParallelSubWFProcessModel();
/**
* 获取流程模式
* @return
*/
String getWFMode();
}
|
package class1;
import java.util.HashMap;
public class Problem_08_TopKTimes2 {
public static class Node {
public String str;
public int times;
public Node(String s, int t) {
str = s;
times = t;
}
}
public static class TopKRecord {
private Node[] heap;
private int index;
private HashMap<String, Node> strNodeMap;
private HashMap<Node, Integer> nodeIndexMap;
public TopKRecord(int size) {
heap = new Node[size];
index = 0;
strNodeMap = new HashMap<String, Node>();
nodeIndexMap = new HashMap<Node, Integer>();
}
public void add(String str) {
Node curNode = null;
int preIndex = -1;
if (!strNodeMap.containsKey(str)) {
curNode = new Node(str, 1);
strNodeMap.put(str, curNode);
nodeIndexMap.put(curNode, -1);
} else {
curNode = strNodeMap.get(str);
curNode.times++;
preIndex = nodeIndexMap.get(curNode);
}
if (preIndex == -1) {
if (index == heap.length) {
if (heap[0].times < curNode.times) {
nodeIndexMap.put(heap[0], -1);
nodeIndexMap.put(curNode, 0);
heap[0] = curNode;
heapify(0, index);
}
} else {
nodeIndexMap.put(curNode, index);
heap[index] = curNode;
heapInsert(index++);
}
} else {
heapify(preIndex, index);
}
}
public void printTopK() {
System.out.println("TOP: ");
for (int i = 0; i != heap.length; i++) {
if (heap[i] == null) {
break;
}
System.out.print("Str: " + heap[i].str);
System.out.println(" Times: " + heap[i].times);
}
}
private void heapInsert(int index) {
while (index != 0) {
int parent = (index - 1) / 2;
if (heap[index].times < heap[parent].times) {
swap(parent, index);
index = parent;
} else {
break;
}
}
}
private void heapify(int index, int heapSize) {
int l = index * 2 + 1;
int r = index * 2 + 2;
int smallest = index;
while (l < heapSize) {
if (heap[l].times < heap[index].times) {
smallest = l;
}
if (r < heapSize && heap[r].times < heap[smallest].times) {
smallest = r;
}
if (smallest != index) {
swap(smallest, index);
} else {
break;
}
index = smallest;
l = index * 2 + 1;
r = index * 2 + 2;
}
}
private void swap(int index1, int index2) {
nodeIndexMap.put(heap[index1], index2);
nodeIndexMap.put(heap[index2], index1);
Node tmp = heap[index1];
heap[index1] = heap[index2];
heap[index2] = tmp;
}
}
public static String[] generateRandomArray(int len, int max) {
String[] res = new String[len];
for (int i = 0; i != len; i++) {
res[i] = String.valueOf((int) (Math.random() * (max + 1)));
}
return res;
}
public static void printArray(String[] arr) {
for (int i = 0; i != arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
TopKRecord record = new TopKRecord(2);
record.add("zuo");
record.printTopK();
record.add("cheng");
record.add("cheng");
record.printTopK();
record.add("Yun");
record.add("Yun");
record.printTopK();
}
}
|
/*
* Copyright 2013-2018 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.guardduty.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* Information about the activity described in a finding.
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/Action" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class Action implements Serializable, Cloneable, StructuredPojo {
/** GuardDuty Finding activity type. */
private String actionType;
/** Information about the AWS_API_CALL action described in this finding. */
private AwsApiCallAction awsApiCallAction;
/** Information about the DNS_REQUEST action described in this finding. */
private DnsRequestAction dnsRequestAction;
/** Information about the NETWORK_CONNECTION action described in this finding. */
private NetworkConnectionAction networkConnectionAction;
/** Information about the PORT_PROBE action described in this finding. */
private PortProbeAction portProbeAction;
/**
* GuardDuty Finding activity type.
*
* @param actionType
* GuardDuty Finding activity type.
*/
public void setActionType(String actionType) {
this.actionType = actionType;
}
/**
* GuardDuty Finding activity type.
*
* @return GuardDuty Finding activity type.
*/
public String getActionType() {
return this.actionType;
}
/**
* GuardDuty Finding activity type.
*
* @param actionType
* GuardDuty Finding activity type.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Action withActionType(String actionType) {
setActionType(actionType);
return this;
}
/**
* Information about the AWS_API_CALL action described in this finding.
*
* @param awsApiCallAction
* Information about the AWS_API_CALL action described in this finding.
*/
public void setAwsApiCallAction(AwsApiCallAction awsApiCallAction) {
this.awsApiCallAction = awsApiCallAction;
}
/**
* Information about the AWS_API_CALL action described in this finding.
*
* @return Information about the AWS_API_CALL action described in this finding.
*/
public AwsApiCallAction getAwsApiCallAction() {
return this.awsApiCallAction;
}
/**
* Information about the AWS_API_CALL action described in this finding.
*
* @param awsApiCallAction
* Information about the AWS_API_CALL action described in this finding.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Action withAwsApiCallAction(AwsApiCallAction awsApiCallAction) {
setAwsApiCallAction(awsApiCallAction);
return this;
}
/**
* Information about the DNS_REQUEST action described in this finding.
*
* @param dnsRequestAction
* Information about the DNS_REQUEST action described in this finding.
*/
public void setDnsRequestAction(DnsRequestAction dnsRequestAction) {
this.dnsRequestAction = dnsRequestAction;
}
/**
* Information about the DNS_REQUEST action described in this finding.
*
* @return Information about the DNS_REQUEST action described in this finding.
*/
public DnsRequestAction getDnsRequestAction() {
return this.dnsRequestAction;
}
/**
* Information about the DNS_REQUEST action described in this finding.
*
* @param dnsRequestAction
* Information about the DNS_REQUEST action described in this finding.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Action withDnsRequestAction(DnsRequestAction dnsRequestAction) {
setDnsRequestAction(dnsRequestAction);
return this;
}
/**
* Information about the NETWORK_CONNECTION action described in this finding.
*
* @param networkConnectionAction
* Information about the NETWORK_CONNECTION action described in this finding.
*/
public void setNetworkConnectionAction(NetworkConnectionAction networkConnectionAction) {
this.networkConnectionAction = networkConnectionAction;
}
/**
* Information about the NETWORK_CONNECTION action described in this finding.
*
* @return Information about the NETWORK_CONNECTION action described in this finding.
*/
public NetworkConnectionAction getNetworkConnectionAction() {
return this.networkConnectionAction;
}
/**
* Information about the NETWORK_CONNECTION action described in this finding.
*
* @param networkConnectionAction
* Information about the NETWORK_CONNECTION action described in this finding.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Action withNetworkConnectionAction(NetworkConnectionAction networkConnectionAction) {
setNetworkConnectionAction(networkConnectionAction);
return this;
}
/**
* Information about the PORT_PROBE action described in this finding.
*
* @param portProbeAction
* Information about the PORT_PROBE action described in this finding.
*/
public void setPortProbeAction(PortProbeAction portProbeAction) {
this.portProbeAction = portProbeAction;
}
/**
* Information about the PORT_PROBE action described in this finding.
*
* @return Information about the PORT_PROBE action described in this finding.
*/
public PortProbeAction getPortProbeAction() {
return this.portProbeAction;
}
/**
* Information about the PORT_PROBE action described in this finding.
*
* @param portProbeAction
* Information about the PORT_PROBE action described in this finding.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Action withPortProbeAction(PortProbeAction portProbeAction) {
setPortProbeAction(portProbeAction);
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 (getActionType() != null)
sb.append("ActionType: ").append(getActionType()).append(",");
if (getAwsApiCallAction() != null)
sb.append("AwsApiCallAction: ").append(getAwsApiCallAction()).append(",");
if (getDnsRequestAction() != null)
sb.append("DnsRequestAction: ").append(getDnsRequestAction()).append(",");
if (getNetworkConnectionAction() != null)
sb.append("NetworkConnectionAction: ").append(getNetworkConnectionAction()).append(",");
if (getPortProbeAction() != null)
sb.append("PortProbeAction: ").append(getPortProbeAction());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof Action == false)
return false;
Action other = (Action) obj;
if (other.getActionType() == null ^ this.getActionType() == null)
return false;
if (other.getActionType() != null && other.getActionType().equals(this.getActionType()) == false)
return false;
if (other.getAwsApiCallAction() == null ^ this.getAwsApiCallAction() == null)
return false;
if (other.getAwsApiCallAction() != null && other.getAwsApiCallAction().equals(this.getAwsApiCallAction()) == false)
return false;
if (other.getDnsRequestAction() == null ^ this.getDnsRequestAction() == null)
return false;
if (other.getDnsRequestAction() != null && other.getDnsRequestAction().equals(this.getDnsRequestAction()) == false)
return false;
if (other.getNetworkConnectionAction() == null ^ this.getNetworkConnectionAction() == null)
return false;
if (other.getNetworkConnectionAction() != null && other.getNetworkConnectionAction().equals(this.getNetworkConnectionAction()) == false)
return false;
if (other.getPortProbeAction() == null ^ this.getPortProbeAction() == null)
return false;
if (other.getPortProbeAction() != null && other.getPortProbeAction().equals(this.getPortProbeAction()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getActionType() == null) ? 0 : getActionType().hashCode());
hashCode = prime * hashCode + ((getAwsApiCallAction() == null) ? 0 : getAwsApiCallAction().hashCode());
hashCode = prime * hashCode + ((getDnsRequestAction() == null) ? 0 : getDnsRequestAction().hashCode());
hashCode = prime * hashCode + ((getNetworkConnectionAction() == null) ? 0 : getNetworkConnectionAction().hashCode());
hashCode = prime * hashCode + ((getPortProbeAction() == null) ? 0 : getPortProbeAction().hashCode());
return hashCode;
}
@Override
public Action clone() {
try {
return (Action) 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.guardduty.model.transform.ActionMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
package md53d543179a8e0b35fe087ec2065efd0d5;
public class SwitchRenderer
extends md53d543179a8e0b35fe087ec2065efd0d5.ViewRenderer_2
implements
mono.android.IGCUserPeer,
android.widget.CompoundButton.OnCheckedChangeListener
{
static final String __md_methods;
static {
__md_methods =
"n_onCheckedChanged:(Landroid/widget/CompoundButton;Z)V:GetOnCheckedChanged_Landroid_widget_CompoundButton_ZHandler:Android.Widget.CompoundButton/IOnCheckedChangeListenerInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" +
"";
mono.android.Runtime.register ("Xamarin.Forms.Platform.Android.SwitchRenderer, Xamarin.Forms.Platform.Android, Version=1.3.5.0, Culture=neutral, PublicKeyToken=null", SwitchRenderer.class, __md_methods);
}
public SwitchRenderer (android.content.Context p0, android.util.AttributeSet p1, int p2) throws java.lang.Throwable
{
super (p0, p1, p2);
if (getClass () == SwitchRenderer.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.SwitchRenderer, Xamarin.Forms.Platform.Android, Version=1.3.5.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:System.Int32, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", this, new java.lang.Object[] { p0, p1, p2 });
}
public SwitchRenderer (android.content.Context p0, android.util.AttributeSet p1) throws java.lang.Throwable
{
super (p0, p1);
if (getClass () == SwitchRenderer.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.SwitchRenderer, Xamarin.Forms.Platform.Android, Version=1.3.5.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065:Android.Util.IAttributeSet, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0, p1 });
}
public SwitchRenderer (android.content.Context p0) throws java.lang.Throwable
{
super (p0);
if (getClass () == SwitchRenderer.class)
mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.SwitchRenderer, Xamarin.Forms.Platform.Android, Version=1.3.5.0, Culture=neutral, PublicKeyToken=null", "Android.Content.Context, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065", this, new java.lang.Object[] { p0 });
}
public void onCheckedChanged (android.widget.CompoundButton p0, boolean p1)
{
n_onCheckedChanged (p0, p1);
}
private native void n_onCheckedChanged (android.widget.CompoundButton p0, boolean p1);
java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
|
package org.mousephenotype.cda.ri.services;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
/**
* Base test class to aggregate the spring test annotations.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@ContextConfiguration(classes = {org.mousephenotype.cda.ri.services.BaseTestConfig.class})
public abstract class BaseTest {
@Autowired
protected ApplicationContext context;
@Autowired
protected DataSource riDataSource;
@Before
public void setup() throws Exception {
Resource r = context.getResource("classpath:sql/h2/schema.sql");
ScriptUtils.executeSqlScript(riDataSource.getConnection(), r);
r = context.getResource("classpath:sql/h2/base-test-data.sql");
ScriptUtils.executeSqlScript(riDataSource.getConnection(), r);
}
}
|
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.validator;
import java.util.ArrayList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.errorhandling.StreamInterface;
import org.pentaho.di.trans.steps.validator.Validation;
import org.pentaho.di.trans.steps.validator.ValidatorMeta;
import org.pentaho.di.ui.core.dialog.EnterStringDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.warning.SimpleWarningMessage;
import org.pentaho.di.ui.core.widget.warning.SupportsWarningInterface;
import org.pentaho.di.ui.core.widget.warning.TextVarWarning;
import org.pentaho.di.ui.core.widget.warning.WarningInterface;
import org.pentaho.di.ui.core.widget.warning.WarningMessageInterface;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class ValidatorDialog extends BaseStepDialog implements StepDialogInterface
{
private static Class<?> PKG = ValidatorMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private ValidatorMeta input;
private List wValidationsList;
private RowMetaInterface inputFields;
private Button wValidateAll;
private Validation selectedField;
private Label wlDescription;
private Text wDescription;
private Label wlFieldName;
private CCombo wFieldName;
private Label wlNullAllowed;
private Button wNullAllowed;
private Label wlOnlyNullAllowed;
private Button wOnlyNullAllowed;
private Label wlOnlyNumeric;
private Button wOnlyNumeric;
private java.util.List<Validation> selectionList;
private Label wlMaxLength;
private TextVarWarning wMaxLength;
private Label wlMinLength;
private TextVarWarning wMinLength;
private Group wgData;
private Group wgType;
private Label wlDataTypeVerified;
private Button wDataTypeVerified;
private Label wlDataType;
private Combo wDataType;
private Label wlConversionMask;
private TextVarWarning wConversionMask;
private Label wlDecimalSymbol;
private TextVarWarning wDecimalSymbol;
private Label wlGroupingSymbol;
private TextVarWarning wGroupingSymbol;
private Label wlMaxValue;
private TextVarWarning wMaxValue;
private Label wlMinValue;
private TextVarWarning wMinValue;
private Label wlAllowedValues;
private List wAllowedValues;
private Label wlSourceValues;
private Button wSourceValues;
private Label wlSourceStep;
private Combo wSourceStep;
private Label wlSourceField;
private Combo wSourceField;
private Button wbAddAllowed;
private Button wbRemoveAllowed;
private Button wClear;
private Button wNew;
private Label wlStartStringExpected;
private TextVarWarning wStartStringExpected;
private Label wlEndStringExpected;
private TextVarWarning wEndStringExpected;
private Label wlStartStringDisallowed;
private TextVarWarning wStartStringDisallowed;
private Label wlEndStringDisallowed;
private TextVarWarning wEndStringDisallowed;
private Label wlRegExpExpected;
private TextVarWarning wRegExpExpected;
private Label wlRegExpDisallowed;
private TextVarWarning wRegExpDisallowed;
private Label wlErrorCode;
private TextVarWarning wErrorCode;
private Label wlErrorDescription;
private TextVarWarning wErrorDescription;
private Button wConcatErrors;
private TextVarWarning wConcatSeparator;
public ValidatorDialog(Shell parent, Object in, TransMeta tr, String sname)
{
super(parent, (BaseStepMeta)in, tr, sname);
input=(ValidatorMeta)in;
// Just to make sure everything is nicely in sync...
//
java.util.List<StreamInterface> infoStreams = input.getStepIOMeta().getInfoStreams();
for (int i=0;i<infoStreams.size();i++) {
input.getValidations().get(i).setSourcingStepName(infoStreams.get(i).getStepname());
}
selectedField = null;
selectionList = new ArrayList<Validation>();
// Copy the data from the input into the map...
//
for (Validation field : input.getValidations()) {
selectionList.add(field.clone());
}
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
props.setLook(shell);
setShellImage(shell, input);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "ValidatorDialog.Shell.Title")); //$NON-NLS-1$
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
Rectangle imageBounds = GUIResource.getInstance().getImageInfoHop().getBounds();
// Stepname line
//
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "ValidatorDialog.Stepname.Label")); //$NON-NLS-1$
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right= new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
// Some buttons
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); //$NON-NLS-1$
wNew=new Button(shell, SWT.PUSH);
wNew.setText(BaseMessages.getString(PKG, "ValidatorDialog.NewButton.Label")); //$NON-NLS-1$
wClear=new Button(shell, SWT.PUSH);
wClear.setText(BaseMessages.getString(PKG, "ValidatorDialog.ClearButton.Label")); //$NON-NLS-1$
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); //$NON-NLS-1$
setButtonPositions(new Button[] { wOK, wNew, wClear, wCancel }, margin, null);
// List of fields to the left...
//
Label wlFieldList = new Label(shell, SWT.LEFT);
wlFieldList.setText(BaseMessages.getString(PKG, "ValidatorDialog.FieldList.Label")); //$NON-NLS-1$
props.setLook(wlFieldList);
FormData fdlFieldList = new FormData();
fdlFieldList.left = new FormAttachment(0, 0);
fdlFieldList.right= new FormAttachment(middle, -margin);
fdlFieldList.top = new FormAttachment(wStepname, margin);
wlFieldList.setLayoutData(fdlFieldList);
wValidationsList=new List(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
props.setLook(wValidationsList);
wValidationsList.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
showSelectedValidatorField(wValidationsList.getSelection()[0]);
}
});
FormData fdFieldList = new FormData();
fdFieldList.left = new FormAttachment(0, 0);
fdFieldList.top = new FormAttachment(wlFieldList, margin);
fdFieldList.right = new FormAttachment(middle, -margin);
fdFieldList.bottom = new FormAttachment(wOK, -margin*2);
wValidationsList.setLayoutData(fdFieldList);
// General: an option to allow ALL the options to be checked.
//
wValidateAll=new Button(shell, SWT.CHECK);
wValidateAll.setText(BaseMessages.getString(PKG, "ValidatorDialog.ValidateAll.Label")); //$NON-NLS-1$
props.setLook(wValidateAll);
FormData fdValidateAll = new FormData();
fdValidateAll.left = new FormAttachment(middle, 0);
fdValidateAll.right= new FormAttachment(100, 0);
fdValidateAll.top = new FormAttachment(wStepname, margin);
wValidateAll.setLayoutData(fdValidateAll);
wValidateAll.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { setFlags(); } });
// General: When validating all options, still output a single row, errors concatenated
//
wConcatErrors=new Button(shell, SWT.CHECK);
wConcatErrors.setText(BaseMessages.getString(PKG, "ValidatorDialog.ConcatErrors.Label")); //$NON-NLS-1$
props.setLook(wConcatErrors);
FormData fdConcatErrors = new FormData();
fdConcatErrors.left = new FormAttachment(middle, 0);
fdConcatErrors.top = new FormAttachment(wValidateAll, margin);
wConcatErrors.setLayoutData(fdConcatErrors);
wConcatErrors.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { setFlags(); } });
// The separator
//
wConcatSeparator=new TextVarWarning(transMeta, shell, SWT.LEFT | SWT.SINGLE | SWT.BORDER);
props.setLook(wConcatSeparator);
FormData fdConcatSeparator = new FormData();
fdConcatSeparator.left = new FormAttachment(wConcatErrors, margin);
fdConcatSeparator.right= new FormAttachment(100, 0);
fdConcatSeparator.top = new FormAttachment(wValidateAll, margin);
wConcatSeparator.setLayoutData(fdConcatSeparator);
// Create a scrolled composite on the right side...
//
ScrolledComposite wSComp = new ScrolledComposite(shell, SWT.H_SCROLL | SWT.V_SCROLL);
props.setLook(wSComp);
wSComp.setLayout(new FillLayout());
FormData fdComp = new FormData();
fdComp.left = new FormAttachment(middle, 0);
fdComp.top = new FormAttachment(wConcatSeparator, 2*margin);
fdComp.right = new FormAttachment(100, 0);
fdComp.bottom = new FormAttachment(wOK, -margin*2);
wSComp.setLayoutData(fdComp);
Composite wComp = new Composite(wSComp, SWT.BORDER);
props.setLook(wComp);
FormLayout compLayout = new FormLayout();
compLayout.marginWidth = 3;
compLayout.marginHeight = 3;
wComp.setLayout(compLayout);
int extra = imageBounds.width;
// Description (list key)
//
wlDescription=new Label(wComp, SWT.RIGHT);
wlDescription.setText(BaseMessages.getString(PKG, "ValidatorDialog.Description.Label")); //$NON-NLS-1$
props.setLook(wlDescription);
FormData fdlDescription = new FormData();
fdlDescription.left = new FormAttachment(0, 0);
fdlDescription.right= new FormAttachment(middle, -margin);
fdlDescription.top = new FormAttachment(0, 0);
wlDescription.setLayoutData(fdlDescription);
wDescription=new Text(wComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDescription);
FormData fdDescription = new FormData();
fdDescription.left = new FormAttachment(middle, margin+extra);
fdDescription.right= new FormAttachment(100, 0);
fdDescription.top = new FormAttachment(0, 0);
wDescription.setLayoutData(fdDescription);
wDescription.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent event) {
// See if there is a selected Validation
//
if (wValidationsList!=null && wValidationsList.getItemCount()>0 && wValidationsList.getSelection().length==1) {
int index = wValidationsList.getSelectionIndex();
String description = wValidationsList.getItem(index);
Validation validation = Validation.findValidation(selectionList, description);
String newDescription = wDescription.getText();
validation.setName(newDescription);
wValidationsList.setItem(index, newDescription);
wValidationsList.select(index);
}
}
});
// The name of the field to validate
//
wlFieldName=new Label(wComp, SWT.RIGHT);
wlFieldName.setText(BaseMessages.getString(PKG, "ValidatorDialog.FieldName.Label")); //$NON-NLS-1$
props.setLook(wlFieldName);
FormData fdlFieldName = new FormData();
fdlFieldName.left = new FormAttachment(0, 0);
fdlFieldName.right= new FormAttachment(middle, -margin);
fdlFieldName.top = new FormAttachment(wDescription, margin);
wlFieldName.setLayoutData(fdlFieldName);
wFieldName=new CCombo(wComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wFieldName);
FormData fdFieldName = new FormData();
fdFieldName.left = new FormAttachment(middle, margin+extra);
fdFieldName.right= new FormAttachment(100, 0);
fdFieldName.top = new FormAttachment(wDescription, margin);
wFieldName.setLayoutData(fdFieldName);
// TODO: grab field list in thread in the background...
//
try {
inputFields = transMeta.getPrevStepFields(stepMeta);
wFieldName.setItems(inputFields.getFieldNames());
} catch (KettleStepException ex) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "ValidatorDialog.Exception.CantGetFieldsFromPreviousSteps.Title"), BaseMessages.getString(PKG, "ValidatorDialog.Exception.CantGetFieldsFromPreviousSteps.Message"), ex);
}
// ErrorCode
//
wlErrorCode=new Label(wComp, SWT.RIGHT);
wlErrorCode.setText(BaseMessages.getString(PKG, "ValidatorDialog.ErrorCode.Label")); //$NON-NLS-1$
props.setLook(wlErrorCode);
FormData fdlErrorCode = new FormData();
fdlErrorCode.left = new FormAttachment(0, 0);
fdlErrorCode.right= new FormAttachment(middle, -margin);
fdlErrorCode.top = new FormAttachment(wFieldName, margin);
wlErrorCode.setLayoutData(fdlErrorCode);
wErrorCode=new TextVarWarning(transMeta, wComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wErrorCode);
FormData fdErrorCode = new FormData();
fdErrorCode.left = new FormAttachment(middle, margin);
fdErrorCode.right= new FormAttachment(100, 0);
fdErrorCode.top = new FormAttachment(wFieldName, margin);
wErrorCode.setLayoutData(fdErrorCode);
addSpacesWarning(wErrorCode);
// ErrorDescription
//
wlErrorDescription=new Label(wComp, SWT.RIGHT);
wlErrorDescription.setText(BaseMessages.getString(PKG, "ValidatorDialog.ErrorDescription.Label")); //$NON-NLS-1$
props.setLook(wlErrorDescription);
FormData fdlErrorDescription = new FormData();
fdlErrorDescription.left = new FormAttachment(0, 0);
fdlErrorDescription.right= new FormAttachment(middle, -margin);
fdlErrorDescription.top = new FormAttachment(wErrorCode, margin);
wlErrorDescription.setLayoutData(fdlErrorDescription);
wErrorDescription=new TextVarWarning(transMeta, wComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wErrorDescription);
FormData fdErrorDescription = new FormData();
fdErrorDescription.left = new FormAttachment(middle, margin);
fdErrorDescription.right= new FormAttachment(100, 0);
fdErrorDescription.top = new FormAttachment(wErrorCode, margin);
wErrorDescription.setLayoutData(fdErrorDescription);
addSpacesWarning(wErrorDescription);
// Data type validations & constants masks...
//
wgType = new Group(wComp, SWT.NONE);
props.setLook(wgType);
wgType.setText(BaseMessages.getString(PKG, "ValidatorDialog.TypeGroup.Label"));
FormLayout typeGroupLayout = new FormLayout();
typeGroupLayout.marginHeight = Const.FORM_MARGIN;
typeGroupLayout.marginWidth = Const.FORM_MARGIN;
wgType.setLayout(typeGroupLayout);
FormData fdType = new FormData();
fdType.left = new FormAttachment(0, 0);
fdType.right= new FormAttachment(100, 0);
fdType.top = new FormAttachment(wErrorDescription, margin*2);
wgType.setLayoutData(fdType);
// Check for data type correctness?
//
wlDataTypeVerified=new Label(wgType, SWT.RIGHT);
wlDataTypeVerified.setText(BaseMessages.getString(PKG, "ValidatorDialog.DataTypeVerified.Label")); //$NON-NLS-1$
props.setLook(wlDataTypeVerified);
FormData fdldataTypeVerified = new FormData();
fdldataTypeVerified.left = new FormAttachment(0, 0);
fdldataTypeVerified.right= new FormAttachment(middle, -margin);
fdldataTypeVerified.top = new FormAttachment(0, 0);
wlDataTypeVerified.setLayoutData(fdldataTypeVerified);
wDataTypeVerified=new Button(wgType, SWT.CHECK);
props.setLook(wDataTypeVerified);
FormData fddataTypeVerified = new FormData();
fddataTypeVerified.left = new FormAttachment(middle, margin+extra);
fddataTypeVerified.right= new FormAttachment(100, 0);
fddataTypeVerified.top = new FormAttachment(0, 0);
wDataTypeVerified.setLayoutData(fddataTypeVerified);
// Data type
//
wlDataType=new Label(wgType, SWT.RIGHT);
wlDataType.setText(BaseMessages.getString(PKG, "ValidatorDialog.DataType.Label")); //$NON-NLS-1$
props.setLook(wlDataType);
FormData fdlDataType = new FormData();
fdlDataType.left = new FormAttachment(0, 0);
fdlDataType.right= new FormAttachment(middle, -margin);
fdlDataType.top = new FormAttachment(wDataTypeVerified, margin);
wlDataType.setLayoutData(fdlDataType);
wDataType=new Combo(wgType, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wDataType.setItems(ValueMeta.getTypes());
props.setLook(wDataType);
FormData fdDataType = new FormData();
fdDataType.left = new FormAttachment(middle, margin+extra);
fdDataType.right= new FormAttachment(100, 0);
fdDataType.top = new FormAttachment(wDataTypeVerified, margin);
wDataType.setLayoutData(fdDataType);
// Conversion mask
//
wlConversionMask=new Label(wgType, SWT.RIGHT);
wlConversionMask.setText(BaseMessages.getString(PKG, "ValidatorDialog.ConversionMask.Label")); //$NON-NLS-1$
props.setLook(wlConversionMask);
FormData fdlConversionMask = new FormData();
fdlConversionMask.left = new FormAttachment(0, 0);
fdlConversionMask.right= new FormAttachment(middle, -margin);
fdlConversionMask.top = new FormAttachment(wDataType, margin);
wlConversionMask.setLayoutData(fdlConversionMask);
wConversionMask=new TextVarWarning(transMeta, wgType, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wConversionMask);
FormData fdConversionMask = new FormData();
fdConversionMask.left = new FormAttachment(middle, margin);
fdConversionMask.right= new FormAttachment(100, 0);
fdConversionMask.top = new FormAttachment(wDataType, margin);
wConversionMask.setLayoutData(fdConversionMask);
addSpacesWarning(wConversionMask);
// Decimal Symbol
//
wlDecimalSymbol=new Label(wgType, SWT.RIGHT);
wlDecimalSymbol.setText(BaseMessages.getString(PKG, "ValidatorDialog.DecimalSymbol.Label")); //$NON-NLS-1$
props.setLook(wlDecimalSymbol);
FormData fdlDecimalSymbol = new FormData();
fdlDecimalSymbol.left = new FormAttachment(0, 0);
fdlDecimalSymbol.right= new FormAttachment(middle, -margin);
fdlDecimalSymbol.top = new FormAttachment(wConversionMask, margin);
wlDecimalSymbol.setLayoutData(fdlDecimalSymbol);
wDecimalSymbol=new TextVarWarning(transMeta, wgType, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDecimalSymbol);
FormData fdDecimalSymbol = new FormData();
fdDecimalSymbol.left = new FormAttachment(middle, margin);
fdDecimalSymbol.right= new FormAttachment(100, 0);
fdDecimalSymbol.top = new FormAttachment(wConversionMask, margin);
wDecimalSymbol.setLayoutData(fdDecimalSymbol);
addSpacesWarning(wDecimalSymbol);
// Grouping Symbol
//
wlGroupingSymbol=new Label(wgType, SWT.RIGHT);
wlGroupingSymbol.setText(BaseMessages.getString(PKG, "ValidatorDialog.GroupingSymbol.Label")); //$NON-NLS-1$
props.setLook(wlGroupingSymbol);
FormData fdlGroupingSymbol = new FormData();
fdlGroupingSymbol.left = new FormAttachment(0, 0);
fdlGroupingSymbol.right= new FormAttachment(middle, -margin);
fdlGroupingSymbol.top = new FormAttachment(wDecimalSymbol, margin);
wlGroupingSymbol.setLayoutData(fdlGroupingSymbol);
wGroupingSymbol=new TextVarWarning(transMeta, wgType, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wGroupingSymbol);
FormData fdGroupingSymbol = new FormData();
fdGroupingSymbol.left = new FormAttachment(middle, margin);
fdGroupingSymbol.right= new FormAttachment(100, 0);
fdGroupingSymbol.top = new FormAttachment(wDecimalSymbol, margin);
wGroupingSymbol.setLayoutData(fdGroupingSymbol);
addSpacesWarning(wGroupingSymbol);
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// The data group...
//
//
wgData = new Group(wComp, SWT.NONE);
props.setLook(wgData);
wgData.setText(BaseMessages.getString(PKG, "ValidatorDialog.DataGroup.Label"));
FormLayout dataGroupLayout = new FormLayout();
dataGroupLayout.marginHeight = Const.FORM_MARGIN;
dataGroupLayout.marginWidth = Const.FORM_MARGIN;
wgData.setLayout(dataGroupLayout);
FormData fdData = new FormData();
fdData.left = new FormAttachment(0, 0);
fdData.right= new FormAttachment(100, 0);
fdData.top = new FormAttachment(wgType, margin);
wgData.setLayoutData(fdData);
// Check for null?
//
wlNullAllowed=new Label(wgData, SWT.RIGHT);
wlNullAllowed.setText(BaseMessages.getString(PKG, "ValidatorDialog.NullAllowed.Label")); //$NON-NLS-1$
props.setLook(wlNullAllowed);
FormData fdlNullAllowed = new FormData();
fdlNullAllowed.left = new FormAttachment(0, 0);
fdlNullAllowed.right= new FormAttachment(middle, -margin);
fdlNullAllowed.top = new FormAttachment(0, 0);
wlNullAllowed.setLayoutData(fdlNullAllowed);
wNullAllowed=new Button(wgData, SWT.CHECK);
props.setLook(wNullAllowed);
FormData fdNullAllowed = new FormData();
fdNullAllowed.left = new FormAttachment(middle, margin+extra);
fdNullAllowed.right= new FormAttachment(100, 0);
fdNullAllowed.top = new FormAttachment(0, 0);
wNullAllowed.setLayoutData(fdNullAllowed);
// Only null allowed?
//
wlOnlyNullAllowed=new Label(wgData, SWT.RIGHT);
wlOnlyNullAllowed.setText(BaseMessages.getString(PKG, "ValidatorDialog.OnlyNullAllowed.Label")); //$NON-NLS-1$
props.setLook(wlOnlyNullAllowed);
FormData fdlOnlyNullAllowed = new FormData();
fdlOnlyNullAllowed.left = new FormAttachment(0, 0);
fdlOnlyNullAllowed.right= new FormAttachment(middle, -margin);
fdlOnlyNullAllowed.top = new FormAttachment(wNullAllowed, margin);
wlOnlyNullAllowed.setLayoutData(fdlOnlyNullAllowed);
wOnlyNullAllowed=new Button(wgData, SWT.CHECK);
props.setLook(wOnlyNullAllowed);
FormData fdOnlyNullAllowed = new FormData();
fdOnlyNullAllowed.left = new FormAttachment(middle, margin+extra);
fdOnlyNullAllowed.right= new FormAttachment(100, 0);
fdOnlyNullAllowed.top = new FormAttachment(wNullAllowed, margin);
wOnlyNullAllowed.setLayoutData(fdOnlyNullAllowed);
// Only numeric allowed?
//
wlOnlyNumeric=new Label(wgData, SWT.RIGHT);
wlOnlyNumeric.setText(BaseMessages.getString(PKG, "ValidatorDialog.OnlyNumeric.Label")); //$NON-NLS-1$
props.setLook(wlOnlyNumeric);
FormData fdlOnlyNumeric = new FormData();
fdlOnlyNumeric.left = new FormAttachment(0, 0);
fdlOnlyNumeric.right= new FormAttachment(middle, -margin);
fdlOnlyNumeric.top = new FormAttachment(wOnlyNullAllowed, margin);
wlOnlyNumeric.setLayoutData(fdlOnlyNumeric);
wOnlyNumeric=new Button(wgData, SWT.CHECK);
props.setLook(wOnlyNumeric);
FormData fdOnlyNumeric = new FormData();
fdOnlyNumeric.left = new FormAttachment(middle, margin+extra);
fdOnlyNumeric.right= new FormAttachment(100, 0);
fdOnlyNumeric.top = new FormAttachment(wOnlyNullAllowed, margin);
wOnlyNumeric.setLayoutData(fdOnlyNumeric);
// Maximum length
//
wlMaxLength=new Label(wgData, SWT.RIGHT);
wlMaxLength.setText(BaseMessages.getString(PKG, "ValidatorDialog.MaxLength.Label")); //$NON-NLS-1$
props.setLook(wlMaxLength);
FormData fdlMaxLength = new FormData();
fdlMaxLength.left = new FormAttachment(0, 0);
fdlMaxLength.right= new FormAttachment(middle, -margin);
fdlMaxLength.top = new FormAttachment(wOnlyNumeric, margin);
wlMaxLength.setLayoutData(fdlMaxLength);
wMaxLength=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxLength);
FormData fdMaxLength = new FormData();
fdMaxLength.left = new FormAttachment(middle, margin);
fdMaxLength.right= new FormAttachment(100, 0);
fdMaxLength.top = new FormAttachment(wOnlyNumeric, margin);
wMaxLength.setLayoutData(fdMaxLength);
addSpacesWarning(wMaxLength);
// Minimum length
//
wlMinLength=new Label(wgData, SWT.RIGHT);
wlMinLength.setText(BaseMessages.getString(PKG, "ValidatorDialog.MinLength.Label")); //$NON-NLS-1$
props.setLook(wlMinLength);
FormData fdlMinLength = new FormData();
fdlMinLength.left = new FormAttachment(0, 0);
fdlMinLength.right= new FormAttachment(middle, -margin);
fdlMinLength.top = new FormAttachment(wMaxLength, margin);
wlMinLength.setLayoutData(fdlMinLength);
wMinLength=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMinLength);
FormData fdMinLength = new FormData();
fdMinLength.left = new FormAttachment(middle, margin);
fdMinLength.right= new FormAttachment(100, 0);
fdMinLength.top = new FormAttachment(wMaxLength, margin);
wMinLength.setLayoutData(fdMinLength);
addSpacesWarning(wMinLength);
// Maximum value
//
wlMaxValue=new Label(wgData, SWT.RIGHT);
wlMaxValue.setText(BaseMessages.getString(PKG, "ValidatorDialog.MaxValue.Label")); //$NON-NLS-1$
props.setLook(wlMaxValue);
FormData fdlMaxValue = new FormData();
fdlMaxValue.left = new FormAttachment(0, 0);
fdlMaxValue.right= new FormAttachment(middle, -margin);
fdlMaxValue.top = new FormAttachment(wMinLength, margin);
wlMaxValue.setLayoutData(fdlMaxValue);
wMaxValue=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMaxValue);
FormData fdMaxValue = new FormData();
fdMaxValue.left = new FormAttachment(middle, margin);
fdMaxValue.right= new FormAttachment(100, 0);
fdMaxValue.top = new FormAttachment(wMinLength, margin);
wMaxValue.setLayoutData(fdMaxValue);
addSpacesWarning(wMaxValue);
// Minimum value
//
wlMinValue=new Label(wgData, SWT.RIGHT);
wlMinValue.setText(BaseMessages.getString(PKG, "ValidatorDialog.MinValue.Label")); //$NON-NLS-1$
props.setLook(wlMinValue);
FormData fdlMinValue = new FormData();
fdlMinValue.left = new FormAttachment(0, 0);
fdlMinValue.right= new FormAttachment(middle, -margin);
fdlMinValue.top = new FormAttachment(wMaxValue, margin);
wlMinValue.setLayoutData(fdlMinValue);
wMinValue=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMinValue);
FormData fdMinValue = new FormData();
fdMinValue.left = new FormAttachment(middle, margin);
fdMinValue.right= new FormAttachment(100, 0);
fdMinValue.top = new FormAttachment(wMaxValue, margin);
wMinValue.setLayoutData(fdMinValue);
addSpacesWarning(wMinValue);
// Expected start string
//
wlStartStringExpected=new Label(wgData, SWT.RIGHT);
wlStartStringExpected.setText(BaseMessages.getString(PKG, "ValidatorDialog.StartStringExpected.Label")); //$NON-NLS-1$
props.setLook(wlStartStringExpected);
FormData fdlStartStringExpected = new FormData();
fdlStartStringExpected.left = new FormAttachment(0, 0);
fdlStartStringExpected.right= new FormAttachment(middle, -margin);
fdlStartStringExpected.top = new FormAttachment(wMinValue, margin);
wlStartStringExpected.setLayoutData(fdlStartStringExpected);
wStartStringExpected=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wStartStringExpected);
FormData fdStartStringExpected = new FormData();
fdStartStringExpected.left = new FormAttachment(middle, margin);
fdStartStringExpected.right= new FormAttachment(100, 0);
fdStartStringExpected.top = new FormAttachment(wMinValue, margin);
wStartStringExpected.setLayoutData(fdStartStringExpected);
addSpacesWarning(wStartStringExpected);
// Expected End string
//
wlEndStringExpected=new Label(wgData, SWT.RIGHT);
wlEndStringExpected.setText(BaseMessages.getString(PKG, "ValidatorDialog.EndStringExpected.Label")); //$NON-NLS-1$
props.setLook(wlEndStringExpected);
FormData fdlEndStringExpected = new FormData();
fdlEndStringExpected.left = new FormAttachment(0, 0);
fdlEndStringExpected.right= new FormAttachment(middle, -margin);
fdlEndStringExpected.top = new FormAttachment(wStartStringExpected, margin);
wlEndStringExpected.setLayoutData(fdlEndStringExpected);
wEndStringExpected=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wEndStringExpected);
FormData fdEndStringExpected = new FormData();
fdEndStringExpected.left = new FormAttachment(middle, margin);
fdEndStringExpected.right= new FormAttachment(100, 0);
fdEndStringExpected.top = new FormAttachment(wStartStringExpected, margin);
wEndStringExpected.setLayoutData(fdEndStringExpected);
addSpacesWarning(wEndStringExpected);
// Disallowed start string
//
wlStartStringDisallowed=new Label(wgData, SWT.RIGHT);
wlStartStringDisallowed.setText(BaseMessages.getString(PKG, "ValidatorDialog.StartStringDisallowed.Label")); //$NON-NLS-1$
props.setLook(wlStartStringDisallowed);
FormData fdlStartStringDisallowed = new FormData();
fdlStartStringDisallowed.left = new FormAttachment(0, 0);
fdlStartStringDisallowed.right= new FormAttachment(middle, -margin);
fdlStartStringDisallowed.top = new FormAttachment(wEndStringExpected, margin);
wlStartStringDisallowed.setLayoutData(fdlStartStringDisallowed);
wStartStringDisallowed=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wStartStringDisallowed);
FormData fdStartStringDisallowed = new FormData();
fdStartStringDisallowed.left = new FormAttachment(middle, margin);
fdStartStringDisallowed.right= new FormAttachment(100, 0);
fdStartStringDisallowed.top = new FormAttachment(wEndStringExpected, margin);
wStartStringDisallowed.setLayoutData(fdStartStringDisallowed);
addSpacesWarning(wStartStringDisallowed);
// Disallowed End string
//
wlEndStringDisallowed=new Label(wgData, SWT.RIGHT);
wlEndStringDisallowed.setText(BaseMessages.getString(PKG, "ValidatorDialog.EndStringDisallowed.Label")); //$NON-NLS-1$
props.setLook(wlEndStringDisallowed);
FormData fdlEndStringDisallowed = new FormData();
fdlEndStringDisallowed.left = new FormAttachment(0, 0);
fdlEndStringDisallowed.right= new FormAttachment(middle, -margin);
fdlEndStringDisallowed.top = new FormAttachment(wStartStringDisallowed, margin);
wlEndStringDisallowed.setLayoutData(fdlEndStringDisallowed);
wEndStringDisallowed=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wEndStringDisallowed);
FormData fdEndStringDisallowed = new FormData();
fdEndStringDisallowed.left = new FormAttachment(middle, margin);
fdEndStringDisallowed.right= new FormAttachment(100, 0);
fdEndStringDisallowed.top = new FormAttachment(wStartStringDisallowed, margin);
wEndStringDisallowed.setLayoutData(fdEndStringDisallowed);
addSpacesWarning(wEndStringDisallowed);
// Expected regular expression
//
wlRegExpExpected=new Label(wgData, SWT.RIGHT);
wlRegExpExpected.setText(BaseMessages.getString(PKG, "ValidatorDialog.RegExpExpected.Label")); //$NON-NLS-1$
props.setLook(wlRegExpExpected);
FormData fdlRegExpExpected = new FormData();
fdlRegExpExpected.left = new FormAttachment(0, 0);
fdlRegExpExpected.right= new FormAttachment(middle, -margin);
fdlRegExpExpected.top = new FormAttachment(wEndStringDisallowed, margin);
wlRegExpExpected.setLayoutData(fdlRegExpExpected);
wRegExpExpected=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wRegExpExpected);
FormData fdRegExpExpected = new FormData();
fdRegExpExpected.left = new FormAttachment(middle, margin);
fdRegExpExpected.right= new FormAttachment(100, 0);
fdRegExpExpected.top = new FormAttachment(wEndStringDisallowed, margin);
wRegExpExpected.setLayoutData(fdRegExpExpected);
addSpacesWarning(wRegExpExpected);
// Disallowed regular expression
//
wlRegExpDisallowed=new Label(wgData, SWT.RIGHT);
wlRegExpDisallowed.setText(BaseMessages.getString(PKG, "ValidatorDialog.RegExpDisallowed.Label")); //$NON-NLS-1$
props.setLook(wlRegExpDisallowed);
FormData fdlRegExpDisallowed = new FormData();
fdlRegExpDisallowed.left = new FormAttachment(0, 0);
fdlRegExpDisallowed.right= new FormAttachment(middle, -margin);
fdlRegExpDisallowed.top = new FormAttachment(wRegExpExpected, margin);
wlRegExpDisallowed.setLayoutData(fdlRegExpDisallowed);
wRegExpDisallowed=new TextVarWarning(transMeta, wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wRegExpDisallowed);
FormData fdRegExpDisallowed = new FormData();
fdRegExpDisallowed.left = new FormAttachment(middle, margin);
fdRegExpDisallowed.right= new FormAttachment(100, 0);
fdRegExpDisallowed.top = new FormAttachment(wRegExpExpected, margin);
wRegExpDisallowed.setLayoutData(fdRegExpDisallowed);
addSpacesWarning(wRegExpDisallowed);
// Allowed values: a list box.
//
// Add an entry
//
wbAddAllowed = new Button(wgData, SWT.PUSH);
wbAddAllowed.setText(BaseMessages.getString(PKG, "ValidatorDialog.ButtonAddAllowed.Label")); //$NON-NLS-1$
FormData fdbAddAllowed = new FormData();
fdbAddAllowed.right = new FormAttachment(100, 0);
fdbAddAllowed.top = new FormAttachment(wRegExpDisallowed, margin);
wbAddAllowed.setLayoutData(fdbAddAllowed);
wbAddAllowed.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addAllowedValue(); } });
// Remove an entry
//
wbRemoveAllowed = new Button(wgData, SWT.PUSH);
wbRemoveAllowed.setText(BaseMessages.getString(PKG, "ValidatorDialog.ButtonRemoveAllowed.Label")); //$NON-NLS-1$
FormData fdbRemoveAllowed = new FormData();
fdbRemoveAllowed.right = new FormAttachment(100, 0);
fdbRemoveAllowed.top = new FormAttachment(wbAddAllowed, margin);
wbRemoveAllowed.setLayoutData(fdbRemoveAllowed);
wbRemoveAllowed.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { removeAllowedValue(); } });
wlAllowedValues=new Label(wgData, SWT.RIGHT);
wlAllowedValues.setText(BaseMessages.getString(PKG, "ValidatorDialog.AllowedValues.Label")); //$NON-NLS-1$
props.setLook(wlAllowedValues);
FormData fdlAllowedValues = new FormData();
fdlAllowedValues.left = new FormAttachment(0, 0);
fdlAllowedValues.right= new FormAttachment(middle, -margin);
fdlAllowedValues.top = new FormAttachment(wRegExpDisallowed, margin);
wlAllowedValues.setLayoutData(fdlAllowedValues);
wAllowedValues=new List(wgData, SWT.MULTI | SWT.LEFT | SWT.BORDER);
props.setLook(wAllowedValues);
FormData fdAllowedValues = new FormData();
fdAllowedValues.left = new FormAttachment(middle, margin+extra);
fdAllowedValues.right = new FormAttachment(wbRemoveAllowed, -20);
fdAllowedValues.top = new FormAttachment(wRegExpDisallowed, margin);
fdAllowedValues.bottom = new FormAttachment(wRegExpDisallowed, 150);
wAllowedValues.setLayoutData(fdAllowedValues);
// Source allowed values from another step?
//
wlSourceValues=new Label(wgData, SWT.RIGHT);
wlSourceValues.setText(BaseMessages.getString(PKG, "ValidatorDialog.SourceValues.Label")); //$NON-NLS-1$
props.setLook(wlSourceValues);
FormData fdlSourceValues = new FormData();
fdlSourceValues.left = new FormAttachment(0, 0);
fdlSourceValues.right= new FormAttachment(middle, -margin);
fdlSourceValues.top = new FormAttachment(wAllowedValues, margin);
wlSourceValues.setLayoutData(fdlSourceValues);
wSourceValues=new Button(wgData, SWT.CHECK);
props.setLook(wSourceValues);
FormData fdSourceValues = new FormData();
fdSourceValues.left = new FormAttachment(middle, margin+extra);
fdSourceValues.right= new FormAttachment(100, 0);
fdSourceValues.top = new FormAttachment(wAllowedValues, margin);
wSourceValues.setLayoutData(fdSourceValues);
wSourceValues.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
enableFields();
}
});
// Source allowed values : source step
//
wlSourceStep=new Label(wgData, SWT.RIGHT);
wlSourceStep.setText(BaseMessages.getString(PKG, "ValidatorDialog.SourceStep.Label")); //$NON-NLS-1$
props.setLook(wlSourceStep);
FormData fdlSourceStep = new FormData();
fdlSourceStep.left = new FormAttachment(0, margin);
fdlSourceStep.right= new FormAttachment(middle, -margin);
fdlSourceStep.top = new FormAttachment(wSourceValues, margin);
wlSourceStep.setLayoutData(fdlSourceStep);
wSourceStep=new Combo(wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSourceStep);
FormData fdSourceStep = new FormData();
fdSourceStep.left = new FormAttachment(middle, margin+extra);
fdSourceStep.right= new FormAttachment(100, 0);
fdSourceStep.top = new FormAttachment(wSourceValues, margin);
wSourceStep.setLayoutData(fdSourceStep);
wSourceStep.addFocusListener(new FocusAdapter() { public void focusGained(org.eclipse.swt.events.FocusEvent e) { getSteps(); } } );
wSourceStep.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { getSteps(); } } );
// Source allowed values : source field
//
wlSourceField=new Label(wgData, SWT.RIGHT);
wlSourceField.setText(BaseMessages.getString(PKG, "ValidatorDialog.SourceField.Label")); //$NON-NLS-1$
props.setLook(wlSourceField);
FormData fdlSourceField = new FormData();
fdlSourceField.left = new FormAttachment(0, margin);
fdlSourceField.right= new FormAttachment(middle, -margin);
fdlSourceField.top = new FormAttachment(wSourceStep, margin);
wlSourceField.setLayoutData(fdlSourceField);
wSourceField=new Combo(wgData, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSourceField);
FormData fdSourceField = new FormData();
fdSourceField.left = new FormAttachment(middle, margin+extra);
fdSourceField.right= new FormAttachment(100, 0);
fdSourceField.top = new FormAttachment(wSourceStep, margin);
wSourceField.setLayoutData(fdSourceField);
wSourceField.addFocusListener(new FocusAdapter() { public void focusGained(org.eclipse.swt.events.FocusEvent e) { getFields(); } } );
wSourceField.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { getFields(); } } );
wComp.layout();
wComp.pack();
Rectangle bounds = wComp.getBounds();
wSComp.setContent(wComp);
wSComp.setExpandHorizontal(true);
wSComp.setExpandVertical(true);
wSComp.setMinWidth(bounds.width);
wSComp.setMinHeight(bounds.height);
// Add listeners
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
wCancel.addListener(SWT.Selection, lsCancel);
wOK.addListener (SWT.Selection, lsOK );
wClear.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// Clear the validation rules for a certain field...
//
int index = wValidationsList.getSelectionIndex();
if (index>=0) {
selectionList.remove(index);
selectedField=null;
wValidationsList.remove(index);
enableFields();
}
}
});
wNew.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// Create a new validation rule page ...
//
EnterStringDialog enterStringDialog = new EnterStringDialog(shell, "", BaseMessages.getString(PKG, "ValidatorDialog.EnterValidationRuleName.Title"), BaseMessages.getString(PKG, "ValidatorDialog.EnterValidationRuleName.Message"));
String description = enterStringDialog.open();
if (description!=null) {
if (Validation.findValidation(selectionList, description)!=null) {
MessageBox messageBox = new MessageBox(shell, SWT.ICON_ERROR);
messageBox.setText(BaseMessages.getString(PKG, "ValidatorDialog.ValidationRuleNameAlreadyExists.Title"));
messageBox.setMessage(BaseMessages.getString(PKG, "ValidatorDialog.ValidationRuleNameAlreadyExists.Message"));
messageBox.open();
return;
}
saveChanges();
Validation validation = new Validation();
validation.setName(description);
selectionList.add(validation);
selectedField = validation;
refreshValidationsList();
wValidationsList.select(selectionList.size()-1);
getValidatorFieldData(validation);
}
}
});
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
wConversionMask.addSelectionListener(lsDef);
wGroupingSymbol.addSelectionListener(lsDef);
wDecimalSymbol.addSelectionListener(lsDef);
wMaxLength.addSelectionListener(lsDef);
wMinLength.addSelectionListener(lsDef);
wMaxValue.addSelectionListener(lsDef);
wMinValue.addSelectionListener(lsDef);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
// Set the shell size, based upon previous time...
setSize();
getData();
input.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
protected void setFlags() {
wConcatErrors.setEnabled(wValidateAll.getSelection());
wConcatSeparator.setEnabled(wConcatErrors.getSelection());
}
private void addSpacesWarning(SupportsWarningInterface warningText) {
warningText.addWarningInterface(new WarningInterface() { public WarningMessageInterface getWarningSituation(String text, Control widget, Object subject) {
return new SimpleWarningMessage( spacesValidation(text), BaseMessages.getString(PKG, "System.Warning.OnlySpaces")); }});
warningText.addWarningInterface(new WarningInterface() { public WarningMessageInterface getWarningSituation(String text, Control widget, Object subject) {
return new SimpleWarningMessage( text!=null && text.endsWith(" "), BaseMessages.getString(PKG, "System.Warning.TrailingSpaces")); }});
}
public boolean spacesValidation(String text) {
return Const.onlySpaces(text) && !Const.isEmpty(text);
}
/**
* Remove the selected entries from the allowed entries
*/
protected void removeAllowedValue() {
String[] selection = wAllowedValues.getSelection();
for (String string : selection) {
wAllowedValues.remove(string);
}
}
/**
* Add one entry to the list of allowed values...
*/
protected void addAllowedValue() {
EnterStringDialog dialog = new EnterStringDialog(shell, "", BaseMessages.getString(PKG, "ValidatorDialog.Dialog.AddAllowedValue.Title"), BaseMessages.getString(PKG, "ValidatorDialog.Dialog.AddAllowedValue.Message"), true, transMeta);
String value = dialog.open();
if (!Const.isEmpty(value)) {
wAllowedValues.add(value);
}
}
private void getValidatorFieldData(Validation field) {
wDescription.setText(Const.NVL(field.getName(), ""));
wFieldName.setText(Const.NVL(field.getFieldName(), ""));
wErrorCode.setText(Const.NVL(field.getErrorCode(), ""));
wErrorDescription.setText(Const.NVL(field.getErrorDescription(), ""));
wDataTypeVerified.setSelection(field.isDataTypeVerified());
wDataType.setText(ValueMeta.getTypeDesc(field.getDataType()));
wConversionMask.setText(Const.NVL(field.getConversionMask(), ""));
wDecimalSymbol.setText(Const.NVL(field.getDecimalSymbol(), ""));
wGroupingSymbol.setText(Const.NVL(field.getGroupingSymbol(), ""));
wNullAllowed.setSelection(field.isNullAllowed());
wOnlyNullAllowed.setSelection(field.isOnlyNullAllowed());
wOnlyNumeric.setSelection(field.isOnlyNumericAllowed());
wMaxLength.setText(Const.NVL(field.getMaximumLength(), ""));
wMinLength.setText(Const.NVL(field.getMinimumLength(), ""));
wMaxValue.setText(Const.NVL(field.getMaximumValue(), ""));
wMinValue.setText(Const.NVL(field.getMinimumValue(), ""));
wStartStringExpected.setText(Const.NVL(field.getStartString(), ""));
wEndStringExpected.setText(Const.NVL(field.getEndString(), ""));
wStartStringDisallowed.setText(Const.NVL(field.getStartStringNotAllowed(), ""));
wEndStringDisallowed.setText(Const.NVL(field.getEndStringNotAllowed(), ""));
wRegExpExpected.setText(Const.NVL(field.getRegularExpression(), ""));
wRegExpDisallowed.setText(Const.NVL(field.getRegularExpressionNotAllowed(), ""));
wAllowedValues.removeAll();
if (field.getAllowedValues()!=null) {
for (String allowedValue : field.getAllowedValues()) {
wAllowedValues.add(Const.NVL(allowedValue, ""));
}
}
wSourceValues.setSelection(field.isSourcingValues());
wSourceStep.setText( Const.NVL(field.getSourcingStepName(), "") );
wSourceField.setText(Const.NVL(field.getSourcingField(), ""));
}
private void enableFields() {
boolean visible = selectedField!=null;
wgType.setVisible(visible);
wgData.setVisible(visible);
wlFieldName.setVisible(visible);
wFieldName.setVisible(visible);
wlDescription.setVisible(visible);
wDescription.setVisible(visible);
wlErrorCode.setVisible(visible);
wErrorCode.setVisible(visible);
wlErrorDescription.setVisible(visible);
wErrorDescription.setVisible(visible);
wlSourceStep.setEnabled(wSourceValues.getSelection());
wSourceStep.setEnabled(wSourceValues.getSelection());
wlSourceField.setEnabled(wSourceValues.getSelection());
wSourceField.setEnabled(wSourceValues.getSelection());
wlAllowedValues.setEnabled(!wSourceValues.getSelection());
wAllowedValues.setEnabled(!wSourceValues.getSelection());
wbAddAllowed.setEnabled(!wSourceValues.getSelection());
wbRemoveAllowed.setEnabled(!wSourceValues.getSelection());
}
private void showSelectedValidatorField(String selection) {
// Someone hit a field...
//
saveChanges();
Validation field = Validation.findValidation(selectionList, selection);
if (field==null) {
field = new Validation(selection);
ValueMetaInterface valueMeta = inputFields.searchValueMeta(selection);
if (valueMeta!=null) {
// Set the default data type
//
field.setDataType(valueMeta.getType());
}
}
selectedField = field;
getValidatorFieldData(selectedField);
enableFields();
}
private void saveChanges() {
if (selectedField!=null) {
// First grab the info from the dialog...
//
selectedField.setFieldName(wFieldName.getText());
selectedField.setErrorCode(wErrorCode.getText());
selectedField.setErrorDescription(wErrorDescription.getText());
selectedField.setDataTypeVerified(wDataTypeVerified.getSelection());
selectedField.setDataType(ValueMeta.getType(wDataType.getText()));
selectedField.setConversionMask(wConversionMask.getText());
selectedField.setDecimalSymbol(wDecimalSymbol.getText());
selectedField.setGroupingSymbol(wGroupingSymbol.getText());
selectedField.setNullAllowed(wNullAllowed.getSelection());
selectedField.setOnlyNullAllowed(wOnlyNullAllowed.getSelection());
selectedField.setOnlyNumericAllowed(wOnlyNumeric.getSelection());
selectedField.setMaximumLength(wMaxLength.getText());
selectedField.setMinimumLength(wMinLength.getText());
selectedField.setMaximumValue(wMaxValue.getText());
selectedField.setMinimumValue(wMinValue.getText());
selectedField.setStartString(wStartStringExpected.getText());
selectedField.setEndString(wEndStringExpected.getText());
selectedField.setStartStringNotAllowed(wStartStringDisallowed.getText());
selectedField.setEndStringNotAllowed(wEndStringDisallowed.getText());
selectedField.setRegularExpression(wRegExpExpected.getText());
selectedField.setRegularExpressionNotAllowed(wRegExpDisallowed.getText());
selectedField.setAllowedValues(wAllowedValues.getItems());
selectedField.setSourcingValues(wSourceValues.getSelection());
selectedField.setSourcingField(wSourceField.getText());
selectedField.setSourcingStep(transMeta.findStep(wSourceStep.getText()));
// Save the old info in the map
//
// selectionList.add(selectedField);
}
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
// Populate the list of validations...
//
refreshValidationsList();
enableFields();
wValidateAll.setSelection(input.isValidatingAll());
wConcatErrors.setSelection(input.isConcatenatingErrors());
wConcatSeparator.setText(Const.NVL(input.getConcatenationSeparator(), ""));
// Select the first available field...
//
if (input.getValidations().size()>0) {
Validation validatorField = input.getValidations().get(0);
String description = validatorField.getName();
int index = wValidationsList.indexOf(description);
if (index>=0) {
wValidationsList.select(index);
showSelectedValidatorField(description);
}
}
setFlags();
wStepname.selectAll();
}
private void refreshValidationsList() {
wValidationsList.removeAll();
for (Validation validation : selectionList) {
wValidationsList.add(validation.getName());
}
}
private void cancel()
{
stepname=null;
input.setChanged(changed);
dispose();
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
stepname = wStepname.getText(); // return value
saveChanges();
input.setChanged();
input.setValidatingAll(wValidateAll.getSelection());
input.setConcatenatingErrors(wConcatErrors.getSelection());
input.setConcatenationSeparator(wConcatSeparator.getText());
input.setValidations(selectionList);
dispose();
}
private void getSteps() {
Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(busy);
String fieldStep = wSourceStep.getText();
wSourceStep.removeAll();
wSourceStep.setItems(transMeta.getPrevStepNames(stepMeta));
wSourceStep.setText(fieldStep);
shell.setCursor(null);
busy.dispose();
}
private void getFields() {
Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
shell.setCursor(busy);
try {
String sourceStepName = wSourceStep.getText();
if (!Const.isEmpty(sourceStepName)) {
String fieldName = wSourceField.getText();
RowMetaInterface r = transMeta.getStepFields(sourceStepName);
if (r != null) {
wSourceField.setItems(r.getFieldNames());
}
wSourceField.setText(fieldName);
}
shell.setCursor(null);
busy.dispose();
} catch (KettleException ke) {
shell.setCursor(null);
busy.dispose();
new ErrorDialog(shell, BaseMessages.getString(PKG, "ValidatorDialog.FailedToGetFields.DialogTitle"), BaseMessages.getString(PKG, "ValidatorDialog.FailedToGetFields.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
|
package com.training.onetomany.entity;
import javax.persistence.*;
@Entity
@Table(name = "Flights")
public class Flight {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="flightID")
private int flightId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="origin")
private Airport origin;
@Column(name="FlightNum")
private String flightNum;
@Column(name="Distance")
private int distance;
@Column(name="Dest")
private String dest;
@Column(name="AirTime")
private int airTime;
public int getFlightId() { return flightId; }
public String getFlightNum() { return flightNum; }
public int getDistance() {
return distance;
}
public void setFlightId(int flightId) {
this.flightId = flightId;
}
public void setFlightNum(String flightNum) {
this.flightNum = flightNum;
}
public String getDest() {return dest;}
public void setDest(String dest){ this.dest = dest;}
public int getAirTime() {return airTime;}
public void setAirTime(int airTime){ this.airTime = airTime;}
public void setDistance(int distance) { this.distance = distance; }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.